import numpy as np
from matplotlib import pyplot as plt
from scipy.io import wavfile

Fs = 120e6         # Частота дискретизации
A0 = 65535         # Амплитуда сигнала
tp = 100e-6        # Длина импульса
Tp = 1000e-6 + tp  # Длина между импульсами
Np = 1             # Количество импульсов

Tr = Np*Tp

N_fft = 2**22
N=int(Tr*Fs)
nT=np.arange(N)/Fs

def signal(t):
	s = np.zeros_like(t)
	mask = (0 <= t) & (t <= tp)
	s[mask] = A0
	
	return s

def signal_pulse(t):
	s = np.zeros_like(t)
	for i in range(Np):
		s += signal(t-i*Tp)
	
	return s
	
	
def spectr(s, Fs, N_fft):
	S = np.fft.fft(s, n=N_fft)
	S_fft = S/Fs 
	S_Power = S**2/(N*Fs)
	
	S_fft = np.abs(S_fft)
	S_Power = np.abs(S_Power)
	f_fft = np.fft.fftfreq(N_fft, d=1/Fs)
	S_fft = np.fft.fftshift(S_fft)
	S_Power = np.fft.fftshift(S_Power)
	f_fft = np.fft.fftshift(f_fft)
	return (S_fft, S_Power, f_fft)


S_sum = signal_pulse(nT)
S, Power, f = spectr(S_sum, Fs, N_fft)

S = 20*np.log(S)
Power = 10*np.log(Power)

S_sum_real = S_sum.real
S_sum_imag = S_sum.imag

S_complex = np.zeros(int(len(S_sum)*2))
S_complex [::2] = S_sum_real
S_complex [1::2] = S_sum_imag
S_complex = S_complex.astype('int16')

with open ('pulse.pcm', 'wb') as File:
	File.write(S_complex)

plt.figure(1,figsize=(12, 8))
plt.subplot(3,1,1)
plt.plot(nT,S_sum)
plt.xlabel('nT, с')
plt.ylabel('S, В')
plt.grid()

plt.subplot(3,1,2)
plt.plot(f,S)
plt.xlabel('f, Гц')
plt.ylabel('$S_{dB}$, дБ')
plt.grid()

plt.subplot(3,1,3)
plt.plot(f,Power)
plt.xlabel('f, Гц')
plt.ylabel('$S_{dB}^{2}$, дБ')
plt.grid()
plt.tight_layout()

plt.show()

