Добавил:
EcuaDora
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:Лабы / lab1
.py
variant = 17
test_signal_duration = 100
dt = 0.001
test_sig_ampl = 1 + variant * 0.1
test_sig_freq = 1 + variant * 3.5
non_lin_param_1 = 0.5 + variant * 0.1
lin_param_k = 0.5 + variant * 0.3
lin_param_T = 0.1 + variant * 0.2
print("Вариант номер {}".format(variant))
print("Период дискретизации сигнала: {:.2} с".format(dt))
print("Амплитуда тестового сигнала:{:.2}".format(test_sig_ampl))
print("Частота тестового сигнала: {:.2}Гц".format(test_sig_freq))
print("Длительность тестового сигнала: {}с".format(test_signal_duration))
print("Параметр нелинейностей 1:{:.2}".format(non_lin_param_1))
print("Коэффициент усиления линейного звена:{:.2}".format(lin_param_k))
print("Постоянная времени линейного звена:{:.2}".format(lin_param_T))
# Cформируем вектор времени
'''
При работе в программных средах необходимо предварительно сформировать вектор времени.
В Python для формирования принято использовать команду numpy.arange(start, stop step)
или numpy.linspace(T_0, T_k, N_t) соответственно.
В сообществе Python имеется соглашение по импорту библиотеки numpy
следующим образом: import numpy as np, что означает импорт библиотеки
с заменой имени на np (что значительно сокращает длину строки кода).
Создадим вектор времени от 0 до 100 секунд с частотой дискретизации 0.001
'''
import numpy as np
t = np.arange(0, test_signal_duration, dt)
import matplotlib.pyplot as plt
from scipy import signal
print("Размерность массива: {}".format(t.shape))
print("Содержимое массива: {}".format(t))
'''
Строим пробные сигналы (сейчас конкретнее о синусе).
Для формирования синусоиды в Python используется функция sin(Phase) библиотеки NumPy.
Функций, вычисляющая синус, в NumPy, как и в большинстве других библиотек
на вход принимает угол в радианах, поэтому для корректного вычисления необходимо
преобразовать время в радианы с учетом частоты (в герцах):
'''
plt.figure ('1. Пробные сигналы')
#Построим пробный сигнал (синусоиду)
sig_sin = test_sig_ampl * np.sin(test_sig_freq * t * 2 * np.pi)
##print("Размерность сигнала: {}".format(sig_sin.shape))
##print("Содержимое массива сигнала: {}".format(sig_sin))
plt.subplot(3,1,1)
plt.plot(t[0:100], sig_sin[0:100])
plt.title('Синусоидальный сигнал')
plt.grid()
plt.ylim(-3, 3)
#Построим пробный сигнал (меандр)
sig_meandr = test_sig_ampl * signal.square(test_sig_freq * t * 2 * np.pi)
##print("Размерность сигнала: {}".format(sig_meandr.shape))
##print("Содержимое массива сигнала: {}".format(sig_meandr))
plt.subplot(3,1,2)
plt.plot(t[0:100], sig_meandr[0:100])
plt.title('Меандр')
plt.grid()
plt.ylim(-3, 3)
#Построим пробный сигнал (пила)
sig_sawtooth = test_sig_ampl * signal.sawtooth(test_sig_freq * t * 2 * np.pi)
##print("Размерность сигнала: {}".format(sig_sawtooth.shape))
##print("Содержимое массива сигнала: {}".format(sig_sawtooth))
plt.subplot(3,1,3)
plt.plot(t[0:100], sig_sawtooth[0:100])
plt.title('Пилообразный сигнал')
plt.grid()
plt.ylim(-3, 3)
plt.subplots_adjust(wspace=0, hspace=0.5)
plt.show()
#################################################################################################
'''
Построим спектры сигналов
Для построения спектра дискретных сигналов берется модуль от дискретного
(быстрого) преобразования Фурье сигнала.
В Python для этого используется функция np.fft.fft() и np.abs()
для вычисления спектра и получения амплитуды, соответственно.
'''
#Получение вектора частот для типовых сигналов
freqs_sin = np.fft.fftfreq(sig_sin.shape[0], dt)
freqs_meandr = np.fft.fftfreq(sig_meandr.shape[0], dt)
freqs_sawtooth = np.fft.fftfreq(sig_sawtooth.shape[0], dt)
##синус
sig_sin_spec = np.abs(np.fft.fft(sig_sin)) #получение амплитуды спектра
print("Размерность массива спектра (синус): {}".format(sig_sin_spec.shape))
print("Содержимое массива спектра (синус): {}".format(sig_sin_spec))
##меандр
sig_meandr_spec = np.abs(np.fft.fft(sig_meandr)) #получение амплитуды спектра
print("Размерность массива спектра (меандр): {}".format(sig_meandr_spec.shape))
print("Содержимое массива спектра (меандр): {}".format(sig_meandr_spec))
##пила
sig_sawtooth_spec = np.abs(np.fft.fft(sig_sawtooth)) #получение амплитуды спектра
print("Размерность массива спектра (пила): {}".format(sig_sawtooth_spec.shape))
print("Содержимое массива спектра (пила): {}".format(sig_sawtooth_spec))
#Построение спектров сигналов
plt.figure ('2. Построение спектров сигналов')
##Синус
plt.subplot(3, 1, 1)
plt.plot(freqs_sin, sig_sin_spec)
plt.title('Спектр синусоидального сигнала')
plt.grid()
plt.xlim(-100, 100)
##Меандр
plt.subplot(3, 1, 2)
plt.plot(freqs_meandr, sig_meandr_spec)
plt.title('Спектр меандра')
plt.grid()
plt.xlim(-1000, 1000)
##Пила
plt.subplot(3, 1, 3)
plt.plot(freqs_sawtooth, sig_sawtooth_spec)
plt.title('Спектр пилообразного сигнала')
plt.grid()
plt.xlabel('Частота, Гц')
plt.xlim(-1000, 1000)
plt.subplots_adjust(wspace=0, hspace=0.5)
plt.show()
#################################################################################################
# 3. Типовые нелинейные звенья
plt.figure ('3. Отклик типового нелинейного звена на пробный сигнал')
## Идеальное реле
sig_sin_after_relay = np.sign(sig_sin)
sig_meandr_after_relay = np.sign(sig_meandr)
sig_sawtooth_after_relay = np.sign(sig_sawtooth)
###синус
plt.subplot(1,3,1)
plt.plot(t, sig_sin, t, sig_sin_after_relay)
plt.grid()
plt.xlabel('Время, с')
plt.ylabel('Амплитуда')
plt.ylim(-3, 3)
plt.xlim(0, 0.1)
#меандр
plt.subplot(1,3,2)
plt.plot(t, sig_meandr, t, sig_meandr_after_relay)
plt.grid()
plt.xlabel('Время, с')
plt.ylim(-3, 3)
plt.xlim(0, 0.1)
#пила
plt.subplot(1,3,3)
plt.plot(t, sig_sawtooth, t, sig_sawtooth_after_relay)
plt.grid()
plt.xlabel('Время, с')
plt.ylim(-3, 3)
plt.xlim(0, 0.1)
plt.show()
############################### Отклик Мертвая зона ###############################
def dead_zone_scalar(x, width=0.5):
if np.abs(x) < width:
return 0
elif x > 0:
return x - width
else:
return x + width
dead_zone = np.vectorize(dead_zone_scalar, otypes=[np.float], excluded=['width'])
sig_sin_after_dead_zone = dead_zone(sig_sin, non_lin_param_1)
sig_meandr_after_dead_zone = dead_zone(sig_meandr, non_lin_param_1)
sig_sawtooth_after_dead_zone = dead_zone(sig_sawtooth, non_lin_param_1)
## синус
plt.subplot(1,3,1)
plt.plot(t, sig_sin, t, sig_sin_after_dead_zone)
plt.grid()
plt.xlabel('Время, с')
plt.ylabel('Амплитуда')
plt.ylim(-3, 3)
plt.xlim(0, 0.1)
##меандр
plt.subplot(1,3,2)
plt.plot(t, sig_meandr, t, sig_meandr_after_dead_zone)
plt.grid()
plt.xlabel('Время, с')
plt.ylim(-3, 3)
plt.xlim(0, 0.1)
##Пила
plt.subplot(1,3,3)
plt.plot(t, sig_sawtooth, t, sig_sawtooth_after_dead_zone)
plt.grid()
plt.xlabel('Время, с')
plt.ylim(-3, 3)
plt.xlim(0, 0.1)
plt.show()
############################### Отклик усилитель с насыщением ###############################
def saturation_scalar(x, hight=0.5):
if np.abs(x) < hight:
return x
elif x > 0:
return hight
else:
return -hight
saturation = np.vectorize(saturation_scalar, otypes=[np.float])
sig_sin_after_saturation = saturation(sig_sin, non_lin_param_1)
sig_meandr_after_saturation = saturation(sig_meandr, non_lin_param_1)
sig_sawtooth_after_saturation = saturation(sig_sawtooth, non_lin_param_1)
##синус
plt.subplot(1,3,1)
plt.plot(t, sig_sin, t, sig_sin_after_saturation)
plt.grid()
plt.xlabel('Время, с')
plt.ylabel('Амплитуда')
plt.ylim(-3, 3)
plt.xlim(0, 0.1)
##меандр
plt.subplot(1,3,2)
plt.plot(t, sig_meandr, t, sig_meandr_after_saturation)
plt.grid()
plt.xlabel('Время, с')
plt.ylim(-3, 3)
plt.xlim(0, 0.1)
##Пила
plt.subplot(1,3,3)
plt.plot(t, sig_sawtooth, t, sig_sawtooth_after_saturation)
plt.grid()
plt.xlabel('Время, с')
plt.ylim(-3, 3)
plt.xlim(0, 0.1)
plt.show()
#################################################################################################
# 4. Построить спектр преобразованного сигнала
# 4.1. Реле
plt.figure ('4.1. Спектр преобразованного сигнала (реле)')
sig_sin_after_relay_spec = np.abs(np.fft.fft(sig_sin_after_relay)) # спектр отклика реле на синус
sig_meandr_after_relay_spec = np.abs(np.fft.fft(sig_meandr_after_relay)) # спектр отклика реле на меандр
sig_sawtooth_after_relay_spec = np.abs(np.fft.fft(sig_sawtooth_after_relay)) # спектр отклика реле на пилообразный сигнал
###синус
plt.subplot(1,3,1)
plt.plot(freqs_sin, sig_sin_spec, freqs_sin, sig_sin_after_relay_spec);
plt.grid()
plt.xlabel('Частота, Гц')
plt.xlim(-1000, 1000)
###меандр
plt.subplot(1,3,2)
plt.plot(freqs_meandr, sig_meandr_spec, freqs_meandr, sig_meandr_after_relay_spec)
plt.grid()
plt.xlabel('Частота, Гц')
plt.xlim(-1000, 1000)
###пила
plt.subplot(1,3,3)
plt.plot(freqs_sawtooth, sig_sawtooth_spec, freqs_sawtooth, sig_sawtooth_after_relay_spec)
plt.grid()
plt.xlabel('Частота, Гц')
plt.xlim(-1000, 1000)
plt.show()
# 4.2. Мертвая зона
plt.figure ('4.2. Спектр преобразованного сигнала (мертвая зона)')
sig_sin_after_dead_zone_spec = np.abs(np.fft.fft(sig_sin_after_dead_zone)) # спектр отклика мертвой зоны на синус
sig_meandr_after_dead_zone_spec = np.abs(np.fft.fft(sig_meandr_after_dead_zone)) # спектр отклика мертвой зоны на меандр
sig_sawtooth_after_dead_zone_spec = np.abs(np.fft.fft(sig_sawtooth_after_dead_zone)) # спектр отклика мертвой зоны на пилообразный сигнал
###синус
plt.subplot(1,3,1)
plt.plot(freqs_sin, sig_sin_spec, freqs_sin, sig_sin_after_dead_zone_spec)
plt.grid()
plt.xlabel('Частота, Гц')
plt.xlim(-1000, 1000)
###меандр
plt.subplot(1,3,2)
plt.plot(freqs_meandr, sig_meandr_spec, freqs_meandr, sig_meandr_after_dead_zone_spec)
plt.grid()
plt.xlabel('Частота, Гц')
plt.xlim(-1000, 1000)
###пила
plt.subplot(1,3,3)
plt.plot(freqs_sawtooth, sig_sawtooth_spec, freqs_sawtooth, sig_sawtooth_after_dead_zone_spec)
plt.grid()
plt.xlabel('Частота, Гц')
plt.xlim(-1000, 1000)
plt.show()
# 4.3. Усилитель с насыщением
plt.figure ('4.3. Спектр преобразованного сигнала (усилитель с насыщением)')
sig_sin_after_saturation_spec = np.abs(np.fft.fft(sig_sin_after_saturation)) # спектр отклика мертвой зоны на синус
sig_meandr_after_saturation_spec = np.abs(np.fft.fft(sig_meandr_after_saturation)) # спектр отклика мертвой зоны на меандр
sig_sawtooth_after_saturation_spec = np.abs(np.fft.fft(sig_sawtooth_after_saturation)) # спектр отклика мертвой зоны на пилообразный сигнал
###синус
plt.subplot(1,3,1)
plt.plot(freqs_sin, sig_sin_spec, freqs_sin, sig_sin_after_saturation_spec)
plt.grid()
plt.xlabel('Частота, Гц')
plt.xlim(-1000, 1000)
###меандр
plt.subplot(1,3,2)
plt.plot(freqs_meandr, sig_meandr_spec, freqs_meandr, sig_meandr_after_saturation_spec)
plt.grid()
plt.xlabel('Частота, Гц')
plt.xlim(-1000, 1000)
###пила
plt.subplot(1,3,3)
plt.plot(freqs_sawtooth, sig_sawtooth_spec, freqs_sawtooth, sig_sawtooth_after_saturation_spec)
plt.grid()
plt.xlabel('Частота, Гц')
plt.xlim(-1000, 1000)
plt.show()
#################################################################################################
# 5. Построить СХ нелинейного звена
# Реле
plt.figure ('5.1. СХ идеального реле при разных пробных сигналах')
plt.subplot(1,3,1)
plt.plot(sig_sin, sig_sin_after_relay)
plt.title('синусоидальный сигнал')
plt.grid()
plt.ylim(-1.5, 1.5)
plt.xlim(-2, 2)
plt.subplot(1,3,2)
plt.plot(sig_meandr, sig_meandr_after_relay)
plt.title('меандр')
plt.grid()
plt.ylim(-1.5, 1.5)
plt.xlim(-2, 2)
plt.subplot(1,3,3)
plt.plot(sig_sawtooth, sig_sawtooth_after_relay)
plt.title('пилообразный сигнал')
plt.grid()
plt.ylim(-1.5, 1.5)
plt.xlim(-2, 2)
plt.subplots_adjust(wspace=0.5, hspace=0)
plt.show()
# Мертвая зона
plt.figure ('5.2. СХ мертвой зоны при разных пробных сигналах')
plt.subplot(1,3,1)
plt.plot(sig_sin, sig_sin_after_dead_zone)
plt.title('синусоидальный сигнал')
plt.grid()
plt.ylim(-1.5, 1.5)
plt.xlim(-2, 2)
plt.subplot(1,3,2)
plt.plot(sig_meandr, sig_meandr_after_dead_zone)
plt.title('меандр')
plt.grid()
plt.ylim(-1.5, 1.5)
plt.xlim(-2, 2)
plt.subplot(1,3,3)
plt.plot(sig_sawtooth, sig_sawtooth_after_dead_zone)
plt.title('пилообразный сигнал')
plt.grid()
plt.ylim(-1.5, 1.5)
plt.xlim(-2, 2)
plt.subplots_adjust(wspace=0.5, hspace=0)
plt.show()
# Усилитель с насыщением
plt.figure ('5.3. СХ усилителя с насыщением при разных пробных сигналах')
plt.subplot(1,3,1)
plt.plot(sig_sin, sig_sin_after_saturation)
plt.title('синусоидальный сигнал')
plt.grid()
plt.ylim(-1.5, 1.5)
plt.xlim(-2, 2)
plt.subplot(1,3,2)
plt.plot(sig_meandr, sig_meandr_after_saturation)
plt.title('меандр')
plt.grid()
plt.ylim(-1.5, 1.5)
plt.xlim(-2, 2)
plt.subplot(1,3,3)
plt.plot(sig_sawtooth, sig_sawtooth_after_saturation)
plt.title('пилообразный сигнал')
plt.grid()
plt.ylim(-1.5, 1.5)
plt.xlim(-2, 2)
plt.subplots_adjust(wspace=0.5, hspace=0)
plt.show()