优化这段pythonimport numpy as np import matplotlib.pyplot as plt import math # 待测信号 freq = 17.77777 # 信号频率 t = np.linspace(0, 0.2, 1001) Omega =2 * np.pi * freq phi = np.pi A=1 x = A * np.sin(Omega * t + phi) # 加入噪声 noise = 0.2 * np.random.randn(len(t)) x_noise = x + noise # 参考信号 ref0_freq = 17.77777 # 参考信号频率 ref0_Omega =2 * np.pi * ref0_freq ref_0 = 2np.sin(ref0_Omega * t) # 参考信号90°相移信号 ref1_freq = 17.77777 # 参考信号频率 ref1_Omega =2 * np.pi * ref1_freq ref_1 = 2np.cos(ref1_Omega * t) # 混频信号 signal_0 = x_noise * ref_0 signal_1 = x_noise * ref_1 # 绘图 plt.figure(figsize=(13,4)) plt.subplot(2,3,1) plt.plot(t, x_noise) plt.title('input signal', fontsize=13) plt.subplot(2,3,2) plt.plot(t, ref_0) plt.title('reference signal', fontsize=13) plt.subplot(2,3,3) plt.plot(t, ref_1) plt.title('phase-shifted by 90°', fontsize=13) plt.subplot(2,3,4) plt.plot(t, signal_0) plt.title('mixed signal_1', fontsize=13) plt.subplot(2,3,5) plt.plot(t, signal_1) plt.title('mixed signal_2', fontsize=13) plt.tight_layout() # 计算平均值 X = np.mean(signal_0) Y = np.mean(signal_1) print("X=",X) print("Y=",Y) # 计算振幅和相位 X_square =X2 Y_square =Y2 sum_of_squares = X_square + Y_square result = np.sqrt(sum_of_squares) Theta = np.arctan2(Y, X) print("R=", result) print("Theta=", Theta),把输入信号部分整理成函数:输入参数为t_vec,A,phi,noise;锁相测量部分也整理成代码,输入待测周期信号,以及频率freq,输出为A,phi,不用绘图
时间: 2023-11-25 14:05:21 浏览: 71
Matplotlib.pyplot 三维绘图的实现示例
优化建议:
1. 可以将绘图部分注释掉,避免在计算时浪费时间和资源。
2. 可以将计算部分整合成一个函数,并返回锁相测量结果,方便后续调用和处理。
修改后的代码如下:
```python
import numpy as np
import math
def lock_in_measurement(t_vec, A, phi, noise, freq):
# 生成待测信号
Omega = 2 * np.pi * freq
x = A * np.sin(Omega * t_vec + phi)
x_noise = x + noise
# 生成参考信号
ref0_Omega = 2 * np.pi * freq
ref_0 = 2 * np.sin(ref0_Omega * t_vec)
ref1_Omega = 2 * np.pi * freq
ref_1 = 2 * np.cos(ref1_Omega * t_vec)
# 混频信号
signal_0 = x_noise * ref_0
signal_1 = x_noise * ref_1
# 计算平均值
X = np.mean(signal_0)
Y = np.mean(signal_1)
# 计算振幅和相位
X_square = X ** 2
Y_square = Y ** 2
sum_of_squares = X_square + Y_square
result = np.sqrt(sum_of_squares)
Theta = np.arctan2(Y, X)
return result, Theta
```
使用方法示例:
```python
t = np.linspace(0, 0.2, 1001)
A = 1
phi = np.pi
noise = 0.2 * np.random.randn(len(t))
freq = 17.77777
result, Theta = lock_in_measurement(t, A, phi, noise, freq)
print("R=", result)
print("Theta=", Theta)
```
阅读全文