Ejemplo n.º 1
0
 def plot_phase(self, finalfreq): #MOVER
     # plot different spectrum types:
     plt.phase_spectrum(self.output_signal, Fs=self.fs, color='C1')
     plt.xlabel('f(Hz)')
     plt.ylabel('rad')
     plt.xlim(0, finalfreq)
     plt.show()
Ejemplo n.º 2
0
def plot_snd(fn):
    print "load file:", fn
    raw = load_sound_files(fn)
    s = np.array(raw)

    N = 5
    i = 1

    figsize = (5, 7)
    plt.figure(figsize=figsize)

    plt.subplot(N, 1, i)
    plt.title(fn)
    #plt.plot(t, s)

    librosa.display.waveplot(s, sr=22050)
    #plt.plot(s)

    i = i + 1
    plt.subplot(N, 1, i)

    #sp = librosa.core.spectrum(s,Fs=Fs)
    #plt.plot(sp)
    plt.ylabel("magnitude_spectrum")
    plt.magnitude_spectrum(s, Fs=Fs)

    #plt.subplot(4, 1, 3)
    #plt.magnitude_spectrum(s, Fs=Fs, scale='dB')

    i = i + 1
    plt.subplot(N, 1, i)
    plt.title("STFT-amp")
    #plt.angle_spectrum(s, Fs=Fs)
    a, amax, amin = get_amp(s)
    print "STFT-amp shape:", a.shape
    ave = np.average(a, axis=1)
    print "min:", amin, "max:", amax, "ave of amp:", ave
    plt.plot(a)
    #plt.plot(ave)
    fingerprints = a.reshape(1, 2048)[0]  #.astype(np.float32)
    print "fingerprint:", fingerprints.shape, len(
        fingerprints), fingerprints[:10]

    i = i + 1
    plt.subplot(N, 1, i)
    plt.title("MFCC")
    mfccs = librosa.feature.mfcc(y=s, sr=Fs, n_mfcc=24)
    print "MFCC:", mfccs.shape, len(mfccs)
    plt.plot(mfccs)

    i = i + 1
    plt.subplot(N, 1, i)
    plt.title("phase_spectrum")
    plt.phase_spectrum(s, Fs=Fs)

    plt.tight_layout()
    plt.show()

    png = "%s.png" % (fn.split("/")[-1].split(".")[0])
    plt.savefig(png)
def rectangularPulse(A, tStart, tEnd, t0, t1):
    y = []
    time = np.arange(t0, t1, 1 / 100)
    for x in time:
        if x > tStart and x < tEnd:
            y.append(A)
        else:
            y.append(0)

    #time domain
    plt.figure()
    plt.plot(time, y)
    plt.xlabel('time')
    plt.ylabel('amplitude')

    #magnitude plot
    Y = np.fft.fft(y)
    plt.figure()
    plt.xlabel('index')
    plt.ylabel('magnitude')
    plt.plot(abs(Y))

    #phase spectrum
    plt.figure()
    plt.xlabel('Frequency')
    plt.ylabel('Phase (Radians)')
    plt.phase_spectrum(y)
Ejemplo n.º 4
0
def plot_transfer_function(in_data, out_data, fs):  # plot_magn_and phase?
    L = len(out_data)
    in_pad = pad_input_to_output_length(in_data, out_data)
    in_fft = fft(in_pad) / L
    out_fft = fft(out_data) / L
    # t = np.linspace(0, L, L) / fs
    tf = out_fft / in_fft
    fn = fs / 2  # ?
    fv = np.linspace(0, 1, np.floor(L / 2) + 1) * fn

    fig, ax = plt.subplots()
    #ax.semilogy(fv, np.abs(tf[:len(fv)])*2)
    #plt.plot(fv, 20*np.log10(np.abs(tf[:len(fv)])))
    #ax.semilogy(fv, 20*np.log10(np.abs(tf[:len(fv)])))
    ax.grid()
    #plt.plot(t, in_pad, t, out_data)
    #plt.plot(fv, np.imag(tf[:len(fv)]))
    #plt.yscale("symlog")
    #plt.plot(np.angle(tf))

    spectrum, freqs, line = plt.phase_spectrum(out_data, fs)
    #spectrum, freqs, line = plt.magnitude_spectrum(tf, fs)
    #pxx, freqs = plt.psd(tf, NFFT=None, Fs=fs)  # in_data, out_data
    #spectrum, freqs, line = plt.angle_spectrum(tf, fs)

    plt.plot(freqs, spectrum)
    plt.show()
Ejemplo n.º 5
0
    def plot_Phase(self, sensor: str):
        """
        Plots Phase Function of a single sensor.

        :param sensor: The value of the column name from the loaded files where the desired information is. [SENSOR NAME]
        :param sampling_freq: The signal sampling frequency.

        :return Return Instance so that it can be linearly written in code.
        """

        plt.phase_spectrum(x=self.data_read[sensor], Fs=self.sampling_rate)

        # Setup Plot Parameters.
        plt.title('Phase Function of  ' + sensor)
        plt.show()

        return self  # Return Instance so that it can be linearly written in code.
Ejemplo n.º 6
0
def plotWavAnalysisDeep():
    """
    Read .WAV files, then plot a full analysis of the signal as in:
    https://matplotlib.org/gallery/lines_bars_and_markers/spectrum_demo.html#sphx-glr-gallery-lines-bars-and-markers-spectrum-demo-py

    Plot 1:
    """
    # Cut to the last ~30 seconds of the song since it had the most interesting
    # spectrogram.
    rate, data = wavfile.read('./Give_Love_A_Try.wav')
    f, t, Sxx = signal.spectrogram(data,rate)

    myfft = sf.sfft2(f)
    Interval = t[t.size-1] - t[0]
    Fs = len(myfft)                     # no. of samples
    s = np.abs(myfft)[:len(myfft)//2]   # Real signal symmetry only requires half the samples


    # plot time signal:
    plt.subplot(3,2,1)
    plt.title("Signal")
    plt.plot(s , color='C0')
    plt.xlabel("Time")
    plt.ylabel("Amplitude")

    # plot different spectrum types:
    plt.subplot(3,2,3)
    plt.title("Magnitude Spectrum")
    plt.magnitude_spectrum(s, Fs=Fs, color='C1')


    plt.subplot(3,2,4)
    plt.title("Logarithmic Magnitude Spectrum")
    plt.magnitude_spectrum(s, Fs=Fs, scale='dB', color='C1')


    plt.subplot(3,2,5)
    plt.title("Phase Spectrum")
    plt.phase_spectrum(s, Fs=Fs, color='C2')


    plt.subplot(3,2,6)
    plt.title("Anlge Spectrum")
    plt.angle_spectrum(s, Fs=Fs, color='C2')
    plt.tight_layout()
    plt.show()
Ejemplo n.º 7
0
def plotStep():
    A=1
    t0=0
    t=np.linspace(-5,5,100)
    fs=100
    
    x=myStep(A,t0,t)
    plt.figure()
    plt.plot(x)
    plt.xlabel('Time')
    plt.ylabel('Amplitude')
    
    plt.figure()
    plt.phase_spectrum(x,fs)
    
    plt.figure()
    plt.magnitude_spectrum(x,fs)
Ejemplo n.º 8
0
 def generate_spectres(path, signal, Fs, stypeName):
     spectrum = np.fft.fft(signal)  # Transformada de Fourier
     #freqs = np.fft.fftfreq(len(signal), 1/Fs)  # Frequências do Sinal
     freqs = np.fft.fftfreq(len(spectrum))
     magnitude = np.abs(spectrum)  # Amplitude do Sinal
     #phase = np.angle(spectrum)  # Fase do Sinal
     plt.subplot(2, 1, 1)
     #plt.magnitude_spectrum(signal,Fs=0.01,  color='C1')
     plt.plot(freqs, magnitude)
     plt.title('Espectros do Sinal')
     plt.ylabel("Magnitude")
     plt.xlabel('Frequência (Hz)')
     plt.subplot(2, 1, 2)
     plt.phase_spectrum(signal, Fs=Fs, color='C2')
     #plt.plot(freqs, phase)
     plt.xlabel('Frequência (Hz)')
     plt.ylabel("Fase")
     plt.tight_layout()
     plt.savefig(path + "Amplitude_Fase_" + stypeName)
     plt.show()
Ejemplo n.º 9
0
def simulate_over_R_G():
    # SET R TO AT LEAST 10 ** 4 FOR AN EFFECT ON THE SIMULATION!
    print_band_gap_frequencies(C0, L0, C, L, CELL_LEN)
    gammas = []
    for i in range(-10, 3):
        r = R * (10**i)
        g = r
        abcd_simulator = ABCDSimulator(r, L0, g, C0, L, C, CELL_LEN, CELLS_NUM,
                                       START_FREQ, END_FREQ, V_end, I_end)
        abcd_simulator.run()
        abcd_simulator.plot_s_params()
        gammas.append(abcd_simulator.gamma_arr)

    plt.figure(1)
    title = f'Gamma vs frequency over different R,G'
    plt.suptitle(title, fontSize=FONT_SIZE)
    for i in range(-10, 3):
        r = R * (10**i)
        plt.phase_spectrum(gammas[10 + i], label=f'R=G={r}')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Gamma (Db)')
    plt.legend(loc='best')
    plt.show()
Ejemplo n.º 10
0
# Load the data and calculate the time of each sample
samplerate, data = wavfile.read('bark of the pine tree.wav')
times = np.arange(len(data)) / float(samplerate)

# You can tweak the figsize (width, height) in inches
plt.figure(figsize=(width, height))
plt.title('wav file in time domain')

#plt.fill_between(times, data[:,0], data, color='b')
plt.xlim(times[0], times[-1])
plt.xlabel('time (s)')
plt.ylabel('amplitude')
plt.plot(times, data)
plt.savefig('plot.jpeg', dpi=80)
plt.show()

# Plot the signal read from wav file
plt.figure(figsize=(width, height))  #first arg - length. second - height.
plt.title('Spectrogram of a wav file')
plt.specgram(data, Fs=samplerate)  #left channel only
plt.xlabel('Time')
plt.ylabel('Frequency')
plt.show()

#spectre = np.fft.fft(data)
#freq = np.fft.fftfreq(data.size, 1/samplerate)

plt.figure(figsize=(width, height))  #first arg - length. second - height.
plt.title('phase of a wav file')
plt.phase_spectrum(data, Fs=samplerate)
Ejemplo n.º 11
0
def phase_spectrum(*args, **kwargs):
    r"""starkplot wrapper for phase_spectrum"""
    return _pyplot.phase_spectrum(*args, **kwargs)
Ejemplo n.º 12
0
def plotInFrequency(y, fs):
    N = len(y)
    Y = np.fft.fft(y)
    Y = abs(Y)
    N = int(np.ceil(N / 2))
    Y = Y[:N]
    f = np.arange(0, fs / 2, fs / 2 / N)
    plt.plot(f, Y)
    plt.grid()
    plt.title('Magnitude Spectrum(first version)')
    plt.xlabel('Frequency')
    plt.ylabel('Magnitude')
    plt.figure()


x = np.array([1, -2, 0, 1])
X = np.fft.fft(x)
y = myCosine(2, 5, 0, 1, 2, 100)  #A=2,f=5,ph0=0,t0=1,t1=2,fs=100
plotInTime(y, 100)
plotInFrequency(y, 100)
plt.title('Magnitude Spectrum(second version)')
plt.magnitude_spectrum(y, 100)
plt.grid()
plt.figure()
plt.title('Phase Spectrum')
plt.phase_spectrum(y, 100)
plt.grid()

#We have 2 versions for the magnitude,the first one is computted manually
#,and the second one is provided by the matplot library
Ejemplo n.º 13
0
cnse = cnse[:len(t)]
s = 0.1 * np.sin(2 * np.pi * t) + cnse

plt.subplot(3, 2, 1)
plt.plot(t, s)

plt.subplot(3, 2, 3)
plt.magnitude_spectrum(s, Fs=Fs)

plt.subplot(3, 2, 4)
plt.magnitude_spectrum(s, Fs=Fs, scale='dB')

plt.subplot(3, 2, 5)
plt.angle_spectrum(s, Fs=Fs)

plt.subplot(3, 2, 6)
plt.phase_spectrum(s, Fs=Fs)

plt.show()

print("Test04-----------Start------------------")

x = np.array([0, 1, 2, 3, 4])
y = np.array([-1, 0.2, 0.9, 2.1, 1.2])
A = np.vstack([x, np.ones(len(x))]).T
m, c = np.linalg.lstsq(A, y)[0]
plt.plot(x, y, 'o', label='Original data', markersize=10)
plt.plot(x, m * x + c, 'r', label='Fitted line')
plt.legend()
plt.show()
Ejemplo n.º 14
0
plt.figure(figsize=(12, 4))
plt.plot(n, s)
plt.title('Sinal Modulado')
plt.xlabel('Tempo(s)')
plt.ylabel('Amplitude')
plt.grid()
plt.show()

#   Graficos de espectros
plt.subplot(2, 1, 1)
plt.magnitude_spectrum(s, Fs=Fs, color='C1')
plt.title('Espectros do Sinal Modulado')
plt.ylabel("Magnitude")
plt.xlabel('Frequência (Hz)')
plt.subplot(2, 1, 2)
plt.phase_spectrum(s, Fs=Fs, color='C2')
plt.xlabel('Frequência (Hz)')
plt.ylabel("Fase")
plt.tight_layout()
plt.show()

# Demodulação do sinal
fa = 10
h = s * np.cos(2 * np.pi * fa * n)
plt.figure(figsize=(12, 4))
plt.plot(n, h)
plt.title('Sinal Demodulado')
plt.xlabel('Tempo(s)')
plt.ylabel('Amplitude')
plt.grid()
plt.show()
Ejemplo n.º 15
0
import matplotlib.pyplot as plt
import numpy as np

Fs = 100
T = 1 / Fs
N = 50
n = np.arange(0, N)
w = .1 * np.pi
x_n = np.cos(w * n)

X_w = np.fft.fft(x_n / len(x_n))
X_w = X_w[range(int(len(x_n)))]

tp = len(x_n)
val = np.arange(int(tp / 2))
tim_per = tp / Fs
fre = val / tim_per

plt.subplot(311)
plt.plot(x_n)
plt.subplot(312)
plt.magnitude_spectrum(x_n)
plt.subplot(313)
plt.phase_spectrum(x_n)
plt.show()
    plt.title("STFT: %s" % dictionary[key])
    plt.xlabel("Frequency [Hz]")
    plt.ylabel("Amplitude [g]")
    plt.grid("True", which='both')
    plt.semilogx(np.arange(len(data_fft)) / 2 / fs, data_fft / fs)

    plt.tight_layout()
    plt.savefig("./data/%s.png" % key[4:], format='png')

    plt.figure(figsize=(10, 10))
    plt.subplot(2, 1, 1)
    plt.title("Widmo Amplitudowo-częstotliwościowe: {}".format(
        dictionary[key]))
    plt.ylabel("Amplituda")
    plt.xlabel("Częstotliwość [Hz]")
    spectrum = Spectrum(stft)
    frequencyArray = np.linspace(0, fs / 2, len(spectrum))
    plt.grid(True, which='both')
    plt.semilogx(frequencyArray, spectrum)

    plt.subplot(2, 1, 2)
    plt.title("Widmo fazowo-czętotliwościowe: {}".format(dictionary[key]))
    plt.phase_spectrum(stft, Fs=fs)
    plt.grid(True, which='both')
    plt.tight_layout(pad=1.1)
    plt.savefig('./a/zad4{}.png'.format(dictionary[key]), format='png')

    peaks = sg.find_peaks(spectrum, threshold=0.05 * np.max(spectrum))
    print("in: \"{}\" peaks where found at: {}".format(
        dictionary[key], [str(i) + "Hz" for i in peaks[0]]))
Ejemplo n.º 17
0
#Make Equal length Spectrums
pad_to1 = highestPowerof2(len(sig1))
pad_to2 = highestPowerof2(len(sig2))

pad_to = min(pad_to1,pad_to2)

if fs1 != fs2:
    print('Unable to Calculate. (Sampling Freqs are different)')
    sys.exit(0)

#Signal 1   
sig1 = sig1/max(sig1)
spectrum1, freqs1, line1 = plot.magnitude_spectrum(sig1, Fs = fs1, scale = 'dB', pad_to = pad_to)
spectrum_db1 = 20*np.log10(spectrum1)

phase1,freqs_phase1,line_phase1 = plot.phase_spectrum(sig1, Fs = fs1, pad_to = pad_to)

#Signal 2
sig2 = sig2/max(sig2)
spectrum2, freqs2, line2 = plot.magnitude_spectrum(sig2, Fs = fs2, scale = 'dB', pad_to = pad_to)
spectrum_db2 = 20*np.log10(spectrum2)

phase2,freqs_phase2,line_phase2 = plot.phase_spectrum(sig2, Fs = fs2, pad_to = pad_to)


#1st Spectrum Plot
plot.subplot(221)
y_max1 = max(spectrum_db1)+5
y_min1 = max(min(spectrum_db1)-5,-100)
plot.ylim([y_min1,y_max1])
plot.title(args.i1.split('/')[-1] + ' Spectrum')
print("====== ZAD 4 ======")

plt.figure(figsize=(10,10))
plt.subplot(2, 1, 1)
plt.title("Widmo Amplitudowo-częstotliwościowe")
plt.ylabel("Amplituda")
plt.xlabel("Częstotliwość [Hz]")
spectrum = Spectrum(signalOutput)
frequencyArray = np.linspace(0, fs/2, len(spectrum))
plt.grid(True, which='both')
plt.plot(frequencyArray, spectrum)

plt.subplot(2, 1, 2)
plt.title("Widmo fazowo-czętotliwościowe")
plt.phase_spectrum(signalOutput, Fs=fs)
plt.grid(True, which='both')
plt.tight_layout(pad=1.1)
plt.savefig('./lab2data/zad4.png', format='png')

plt.figure()
plt.title("Widmo Uśredniane amplitudowo")
plt.xlabel("częstotliwość [Hz]")
plt.ylabel("Magnitude")
[frequencies, Pxx] = sg.welch(signalOutput, fs=fs, window=
                              'hamming')
plt.plot(frequencies, Pxx)
plt.savefig('./lab2data/zad4Averaged.png', format='png')


Ejemplo n.º 19
0
import numpy as np

np.random.seed(0)

dt = 0.01
Fs = 1 / dt
t = np.arange(0, 10, dt)
nse = np.random.randn(len(t))
r = np.exp(-t / 0.05)

cnse = np.convolve(nse, r) * dt
cnse = cnse[:len(t)]
s = 0.1 * np.sin(2 * np.pi * t) + cnse

plt.subplot(3, 2, 1)
plt.plot(t, s)

plt.subplot(3, 2, 3)
plt.magnitude_spectrum(s, Fs=Fs)

plt.subplot(3, 2, 4)
plt.magnitude_spectrum(s, Fs=Fs, scale='dB')

plt.subplot(3, 2, 5)
plt.angle_spectrum(s, Fs=Fs)

plt.subplot(3, 2, 6)
plt.phase_spectrum(s, Fs=Fs)

plt.show()
stim_downsamp = signal.decimate(stim, int(samp_freq / 5000))
rEMG_downsamp = signal.decimate(rEMG, int(samp_freq / 5000))
lEMG_downsamp = signal.decimate(lEMG, int(samp_freq / 5000))

plt.subplot(2, 1, 1)
plt.plot(stim)
plt.subplot(2, 1, 2)
plt.plot(stim_downsamp)

plt.subplot(2, 3, 1)
plt.plot(rEMG[0:500])
plt.subplot(2, 3, 2)
plt.magnitude_spectrum(rEMG, 25000)
plt.xlim([0, 2500])
plt.subplot(2, 3, 3)
plt.phase_spectrum(rEMG, 25000)
plt.xlim([0, 2500])
plt.subplot(2, 3, 4)
plt.plot(rEMG_downsamp[0:100])
plt.subplot(2, 3, 5)
plt.magnitude_spectrum(rEMG_downsamp, 5000)
plt.subplot(2, 3, 6)
plt.phase_spectrum(rEMG_downsamp, 5000)

# the above plots look good. downsampling seems to work

# desired_freq = 2000
# secs = len(stim)/samp_freq # Number of seconds in signal X
# samps = int(round(secs*desired_freq))     # Number of samples to downsample
# resample_stim = signal.resample(stim, samps)