import numpy as np import matplotlib pyplot as plt from scipy import f

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import numpy as np
import matplotlib.pyplot as plt
from scipy import fftpack, signal
n_Sample = 500
f_Signal = 50
f_sampling = f_Signal*1000
n_Period = 1
u_RMS = 50
need_to_draw_filtered = True
total_time = 1.0 / (f_Signal * n_Period)
x = np.linspace(0.0, n_Sample*total_time, n_Sample)
y = u_RMS*np.sqrt(2)*np.sin(f_Signal * 2.0*np.pi*x)
y_with_imp_max = np.copy(y)
y_with_sqrt_imp = np.copy(y)
y_with_trig_imp = np.copy(y)
for index, point in enumerate(y):
if point == max(y):
y_with_imp_max[index] = u_RMS*3
y_with_sqrt_imp[index-5:index+5] = u_RMS*3
y_with_trig_imp[index] = u_RMS*3
step = (u_RMS * 3 - y[index-5]) / 5
for index_up in range(0,5):
y_with_trig_imp[index-5+index_up]+=index_up*step
y_with_trig_imp[index+index_up+1]+=(4-index_up)*step
def get_filter_and_fft(y):
sos = signal.butter(2, Wn=2*f_Signal*20/f_sampling, output='sos',btype='low')
filtered = signal.sosfilt(sos, y)
return filtered, fftpack.fft(filtered)
arr_list = [(y_with_imp_max, fftpack.fft(y_with_imp_max),(2,50)),
(y_with_sqrt_imp, fftpack.fft(y_with_sqrt_imp),(2,100)),
(y_with_trig_imp, fftpack.fft(y_with_trig_imp),(2,100)),
]
arr_list_filtered = [(*get_filter_and_fft(res[0]), res[2]) for res in arr_list]
def create_plot(arg):
arr1, arr2, (down, up) = arg
x = [x_*(f_sampling/len(arr2)) for x_ in range(len(arr2)//2)]
plt.subplot(4, 1, 1)
plt.plot(np.linspace(0.0, total_time, n_Sample), arr1)
plt.title('signal'); plt.xlabel('t, c'); plt.ylabel('U, В'); plt.grid()
plt.subplot(4, 1, 2)
plt.plot(x, 2.0 / n_Sample * np.abs(arr2[:n_Sample // 2]))
plt.title('FFT (full)'); plt.xlabel('f, Гц'); plt.ylabel('U, В'); plt.grid()
plt.subplot(4, 1, 3)
plt.plot(x[down:], 2.0 / n_Sample * np.abs(arr2[down:n_Sample // 2]))
plt.title('FFT ({}:f/2)'.format(down)); plt.xlabel('f, Гц'); plt.ylabel('U, В'); plt.grid()
plt.subplot(4, 1, 4)
_, stemLines, _ = plt.stem(x[down:up], 2.0 / n_Sample * np.abs(arr2[down:up]))
plt.title('FFT ({}:{})'.format(down,up)); plt.xlabel('f, Гц'); plt.ylabel('U, В'); plt.grid()
plt.show()
list_to_draw = arr_list_filtered if need_to_draw_filtered else arr_list
for arr_tuple in arr_list_filtered:
create_plot(arr_tuple)