首页 > 编程语言 >波达方向估计(DOA)-Python代码实现

波达方向估计(DOA)-Python代码实现

时间:2024-01-18 17:55:22浏览次数:37  
标签:plot ax1 Python DOA set np theta 波达 squeeze

https://mp.weixin.qq.com/s/fMGc8ziglySGKr1fY8Jvkw

模拟一个由三根全向天线组成的阵列,然后使用数组来模拟到达阵列的信号。相邻天线之间距离为1/2波长(也称为“半波长间隔”)。将模拟发射机的信号以一定角度theta到达该阵列。另外在这个接收到的信号中添加噪声。

import numpy as np
import matplotlib.pyplot as plt

sample_rate = 1e6
N = 10000  # number of samples to simulate

# Create a tone to act as the transmitted signal
t = np.arange(N) / sample_rate
f_tone = 0.02e6
tx = np.exp(2j * np.pi * f_tone * t)

# Simulate three omnidirectional antennas in a line with 1/2 wavelength between adjancent ones, receiving a signal that arrives at an angle

d = 0.5
Nr = 3
theta_degrees = 20  # direction of arrival
theta = theta_degrees / 180 * np.pi  # convert to radians
a = np.exp(-2j * np.pi * d * np.arange(Nr) * np.sin(theta))
print(a)

# we have to do a matrix multiplication of a and tx, so first lets convert both to matrix' instead of numpy arrays which dont let us do 1d matrix math
a = np.asmatrix(a)
tx = np.asmatrix(tx)

# so how do we use this? simple:

r = a.T @ tx  # matrix multiply. dont get too caught up by the transpose a, the important thing is we're multiplying the array factor by the tx signal
print(r.shape)  # r is now going to be a 2D array, 1d is time and 1d is spatial

# Plot the real part of the first 200 samples of all three elements

fig, (ax1) = plt.subplots(1, 1, figsize=(7, 3))
ax1.plot(np.asarray(r[0, :]).squeeze().real[
         0:200])  # the asarray and squeeze are just annoyances we have to do because we came from a matrix
ax1.plot(np.asarray(r[1, :]).squeeze().real[0:200])
ax1.plot(np.asarray(r[2, :]).squeeze().real[0:200])
ax1.set_ylabel("Samples")
ax1.set_xlabel("Time")
ax1.grid()
ax1.legend(['0', '1', '2'], loc=1)
plt.show()

# note the phase shifts, they are also there on the imaginary portions of the samples

# So far this has been simulating the recieving of a signal from a certain angle of arrival
# in your typical DOA problem you are given samples and have to estimate the angle of arrival(s)
# there are also problems where you have multiple receives signals from different directions and one is the SOI while another might be a jammer or interferer you have to null out

# One thing we didnt both doing- lets add noise to this recieved signal.
# AWGN with a phase shift applied is still AWGN so we can add it after or before the array factor is applied, doesnt really matter, we'll do it after
# we need to make sure each element gets an independent noise signal added

n = np.random.randn(Nr, N) + 1j * np.random.randn(Nr, N)
r = r + 0.1 * n

fig, (ax1) = plt.subplots(1, 1, figsize=(7, 3))
ax1.plot(np.asarray(r[0, :]).squeeze().real[
         0:200])  # the asarray and squeeze are just annoyances we have to do because we came from a matrix
ax1.plot(np.asarray(r[1, :]).squeeze().real[0:200])
ax1.plot(np.asarray(r[2, :]).squeeze().real[0:200])
ax1.set_ylabel("Samples")
ax1.set_xlabel("Time")
ax1.grid()
ax1.legend(['0', '1', '2'], loc=1)
plt.show()

# conventional beamforming

theta_scan = np.linspace(-1 * np.pi, np.pi, 1000)  # 100 different thetas between -180 and +180 degrees
results = []
for theta_i in theta_scan:
    # print(theta_i)
    w = np.asmatrix(np.exp(-2j * np.pi * d * np.arange(Nr) * np.sin(theta_i)))  # look familiar?
    r_weighted = np.conj(w) @ r  # apply our weights corresponding to the direction theta_i
    r_weighted = np.asarray(r_weighted).squeeze()  # get it back to a normal 1d numpy array
    results.append(np.mean(np.abs(r_weighted) ** 2))  # energy detector

print(theta_scan[np.argmax(results)] * 180 / np.pi)  # 19.99999999999998

fig, (ax1) = plt.subplots(1, 1, figsize=(7, 3))
ax1.plot(theta_scan * 180 / np.pi, results)  # lets plot angle in degrees
ax1.plot([20], [np.max(results)], 'r.')
ax1.text(-5, np.max(results) + 0.7, '20 degrees')
ax1.set_xlabel("Theta [Degrees]")
ax1.set_ylabel("DOA Metric")
ax1.grid()
plt.show()

fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
ax.plot(theta_scan, results)  # MAKE SURE TO USE RADIAN FOR POLAR
ax.set_theta_zero_location('N')  # make 0 degrees point up
ax.set_theta_direction(-1)  # increase clockwise
ax.set_rgrids([0, 2, 4, 6, 8])
ax.set_rlabel_position(22.5)  # Move grid labels away from other labels
plt.show()

标签:plot,ax1,Python,DOA,set,np,theta,波达,squeeze
From: https://www.cnblogs.com/smalldong/p/17973092

相关文章

  • 猜字谜python文心一言
    猜字谜是一种经典的智力游戏,通过猜测谜底中的字母来逐步揭示谜底。在Python中,我们可以使用一些简单的方法来实现猜字谜游戏,并提供一些提示和反馈,使游戏更加有趣。首先,让我们来看看猜字谜游戏的基本流程。游戏开始时,我们会先设定一个谜底,这个谜底可以是任意长度的单词或短语。然后,......
  • python之数据类型
    字符串详解                                          1.centerdefcenter(self,*args,**kwargs):#realsignatureunknown"""Returnacenteredstringoflengthwi......
  • Python_python读写图片以及对应的库比较
    图片读写通过numpy来做数据计算的沟通JPEG是一种有损格式, 图像PNG,是一种无损格式cv2.imdecode()作用是将图像数据从存储格式中解析出来并转化为OpenCV中的图像格式 imdecode得到的影像波段顺序是RGBnp.fromfile将文本或二进制文件中数据构造成数组 cv2.imencod......
  • WhisperService 多GPU python
    如何实现“WhisperService多GPUPython”作为一名经验丰富的开发者,你将教会一位刚入行的小白如何实现“WhisperService多GPUPython”。下面是整个实现过程的步骤:步骤说明步骤一导入必要的库并设置GPU步骤二加载数据步骤三构建模型步骤四配置训练参数......
  • python数据结构中实现队列的几种方法
    1.list实现enqueueappend()dequeuepop(0)或enqueueinsert(0,item)dequeuepop()MAX_SIZE=100classMyQueue1(object):"""模拟队列"""def__init__(self):self.items=[]self.size=0defis_empty(s......
  • Python使用__dict__查看对象内部属性的名称和值
    1、定义一个类classMyObj:def__init__(self,name,age):self.name=nameself.age=agedefmyFunc(self):passmo=MyObj('Boby',24)print(mo)print(mo.__dict__)#结果<__main__.MyObjobjectat0x000000815C36451......
  • python编程中break pass continue这三个有什么区别?
    在Python编程中,break、pass和continue是三种不同的控制流语句,它们各自有不同的用途和行为:(以下内容由百度文心一言生成)   break:       break语句用于终止循环的执行。当程序执行到break语句时,会立即跳出当前循环,不再执行循环内的剩余代码,而是继续执行循环之后的代......
  • python llama_index
    PythonLlamaIndexIntroductionPythonisapopularprogramminglanguageknownforitssimplicityandreadability.Ithasavastecosystemoflibrariesandframeworksthatmakeitsuitableforawiderangeofapplications,fromwebdevelopmenttodataana......
  • python 安装 llama_index
    Python安装llama_index简介在进行数据分析和机器学习的过程中,我们经常需要对数据进行索引和检索。其中,llama_index是一个强大的Python库,用于快速构建和管理索引。它提供了各种功能,包括全文搜索、近似搜索、范围搜索等。本文将向您介绍如何安装和使用llama_index。安装要安装l......
  • python迭代器和生成器
    迭代器:定义:迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。迭代器有两个基本的方法:iter()和next()。字符串,列表或元组对象都可用于创建迭代器:ex:#!/usr/bin/python3list=[1,2,3,4]it=iter(list)#创建迭代器对......