Exemplo n.º 1
0
 def plot_spectrum(self, finalfreq): #MOVER
     # plot different spectrum types:
     plt.magnitude_spectrum(self.output_signal, Fs=self.fs, color='C1')
     plt.xlabel('f(Hz)')
     plt.ylabel('amplitude(A)')
     plt.xlim(0, finalfreq)
     plt.show()
Exemplo n.º 2
0
 def plot_fd(self, x_start, x_end):
     nchannels = self.nchannels
     nframes = self.nframes
     framerate = self.framerate
     if x_start < x_end:
         time_start = self.x_start
         time_end = self.x_end
     else:
         time_start = self.x_end
         time_end = self.x_start
     data_start = int(time_start * framerate)
     data_end = int(time_end * framerate)
     print data_start, data_end
     if data_start < 0 or data_end > nframes:
         print 'exceed'
         return
     else:
         figure()
         for i in range(0, nchannels):
             loc = nchannels * 100 + 10 + i + 1
             subplot(loc)
             if i == 0:
                 fig_title = 'Time range:' + str(
                     round(time_start, 2)) + 's to ' + str(
                         round(time_end, 2)) + 's'
                 title(fig_title)
             wava_data_onechannel = self.wave_data[i][data_start:data_end]
             magnitude_spectrum(wava_data_onechannel,
                                Fs=framerate,
                                sides='default',
                                scale='dB')
         show()
Exemplo n.º 3
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)
Exemplo n.º 4
0
def ddc_test(dut):
    f_s = 25e6
    f_in = 5e6
    f_nco = -4.9e6

    duration = .0001
    t_s = 1 / f_s

    t = np.arange(0, duration, t_s)
    s_in = np.sin(2 * np.pi * f_in * t) * (2**10)

    phase_inc = dut.nco.calc_phase_inc(f_s, f_nco)
    yield dut.nco.i_phase_inc.eq(phase_inc)

    i_results = []
    q_results = []
    mixer_out = []
    nco_out = []

    for s_i in s_in:
        yield dut.i_sample.eq(int(s_i))

        m_i = (yield dut.o_i)
        n_i = (yield dut.nco.o_nco_i)
        mixer_out.append(m_i)
        nco_out.append(n_i)

        if (yield dut.o_valid):
            i_result = (yield dut.o_i)
            q_result = (yield dut.o_q)
            i_results.append(i_result)
            q_results.append(q_result)
        yield

    nco_out = np.array(nco_out)
    mixer_out = np.array(mixer_out)
    synth_mixer = nco_out * s_in
    i_results = np.array(i_results)
    q_results = np.array(q_results)
    s_results = i_results + 1j * q_results
    s_results = s_results - np.mean(s_results)

    plt.subplot(3, 1, 1)
    plt.plot(nco_out)
    plt.plot(mixer_out)
    plt.title('NCO and mixer output')

    plt.subplot(3, 1, 2)
    plt.plot(np.real(s_results))
    plt.plot(np.imag(s_results))
    plt.title('real and imag output of ddc')

    plt.subplot(3, 1, 3)
    plt.magnitude_spectrum(s_results, f_s / 8, scale='dB', alpha=.5)
    plt.title('ddc output spectrum')
    plt.show()
Exemplo n.º 5
0
def get_stereo_amps(chunk_left, chunk_right, delta_freq, rel_vol, hi_sens,
                    hi_sep, samp_rate, color_map):
    """  
    The primary function that takes a chunk of time series data, runs the 
    fft, and returns an array of color values for each note on the scale.
    This function is called for succesive "chunks" of wav file data, 
    corresponding to the time marker indicating the current portion of the
    wav file being played
    
    Parameters                                                                                
    ----------                                                                                
    chunk_left : left channel time series chunk data from WAV
    chunk_right : right channel time series chunk data from WAV
    delta_freq : frequency difference between succesive values in the fft array
    rel_vol : relative volume of given chunk compared to maximum overall 
        for the entire wav file
    hi_sens : higher sensitivity flag, allows quieter components to be brighter
        this is done by taking the square root of the spectrum, making the 
        peaks have more similar amplitudes
    hi_sep : higher separation, allows stronger stereo color visualization
    samp_rate : wav file sampling rate
                                                                                                                                                                                                                    
    Returns                                                                                   
    ------- 
    colors_255 : array of color values corresponding to each of the 88 piano 
        key notes
      
    """

    try:
        Pxxl, freq_array, dummy = plt.magnitude_spectrum(chunk_left, samp_rate)
        plt.close()
        Pxxr, freq_array, dummy = plt.magnitude_spectrum(
            chunk_right, samp_rate)
        plt.close()
    except:
        print("exception in getting the frequency spectrum data")

    amps_l = []
    amps_r = []

    for n in range(1, 89):
        ampll = get_amp(n, Pxxl, delta_freq)
        amplr = get_amp(n, Pxxr, delta_freq)

        if hi_sens:
            amps_l.append(np.sqrt(ampll))
            amps_r.append(np.sqrt(amplr))
        else:
            amps_l.append(ampll)
            amps_r.append(amplr)

    colors_255 = get_colors(amps_l, amps_r, rel_vol, hi_sep, color_map)

    return colors_255
Exemplo n.º 6
0
def plot_specgram(sound_names, raw_sounds):
    i = 1
    fig = plt.figure(figsize=(16, 12))  # , dpi = 900
    for n, f in zip(sound_names, raw_sounds):
        plt.subplot(10, 1, i)
        #specgram(np.array(f), Fs=22050)
        magnitude_spectrum(np.array(f), Fs=100)
        #print "specgram"
        plt.title(n.title())
        i += 1
    plt.suptitle('Figure 2: Spectrogram', x=0.5, y=0.915, fontsize=18)
Exemplo n.º 7
0
def _shortTimeFourierTransform_1(s, w, f0, fs):
    plt.magnitude_spectrum(s[:len(w)], Fs=fs, window=w)
    plt.axvline(x=f0, color='r', linestyle='--')
    plt.text(f0 + 4, 0.9, 'f0')
    plt.axvline(x=2 * f0, color='g', linestyle='--')
    plt.text(2 * f0 + 4, 0.9, '2f0')
    plt.axvline(x=3 * f0, color='y', linestyle='--')
    plt.text(3 * f0 + 4, 0.9, '3f0')
    plt.axvline(x=4 * f0, color='b', linestyle='--')
    plt.text(4 * f0 + 4, 0.9, '4f0')
    plt.show()
Exemplo n.º 8
0
def series(x, y):  
     
    plt.subplot(211)
    plt.plot(x, y)
    plt.xlabel('Time')
    plt.ylabel('Amplitude')
    
    plt.subplot(212)
    plt.magnitude_spectrum(y, Fs = 10)
    plt.xlabel("Frequency [Hz]")
    plt.ylabel("Amplitude")
    plt.show()
Exemplo n.º 9
0
    def PlotFreqSpectrum(self, eeg_data, fs=125.0, channels=16):
        for c in range(channels):
            plt.figure("fourier")
            plt.magnitude_spectrum(eeg_data[:, c], Fs=fs)
            plt.title("Fourier Transform")
            # plt.figure("welch")
            # win = 4*self.fs
            # freqs, psd = signal.welch(eeg_data[:,c], fs=self.fs, nperseg=win)
            # plt.plot(freqs, psd)
            # plt.title("Power Spectral Density")
            # plt.xlabel('Frequency (Hz)')
            # plt.ylabel('Power spectral density (V^2 / Hz)')

        plt.show()
Exemplo n.º 10
0
def analyzePitch(fname, Fs):
    """
    # Arguments
        classifier: A classifier object loaded with `keras.models.load_model`
        or generated with `buildClassifier`
        fname: Name of the audio file to analyze

    # Returns
        None

    # Raises
        Not handled yet
    """
    # Extract the audio data from the wav file
    sample_length = 0.5  #seconds

    signal = loadAudio(fname)

    live_samples = splitAudio(signal, sample_length)

    # Downsamples the samples, most variation occurs at frequencies under 4k
    downsampled_audio = zeros(
        (live_samples.shape[0], int(live_samples.shape[1] / 2)), int16)
    step = 2
    for i in range(len(live_samples)):
        downsampled_audio[i, :] = downSample(live_samples[i, :],
                                             cutoff=Fs / (2 * step),
                                             Fs=Fs,
                                             step=step)
    Fs_down = Fs / step

    bin_width = 500
    n_bins = int((Fs_down / 2) / bin_width)
    avg_freqs = zeros((downsampled_audio.shape[0], n_bins), float16)
    max_freqs = zeros(avg_freqs.shape, float16)
    avg_freqs_zeroed = zeros(avg_freqs.shape, float16)
    max_freqs_zeroed = zeros(avg_freqs.shape, float16)
    max_proportions = zeros(avg_freqs.shape, float16)
    for i in range(len(downsampled_audio)):
        (spectrum, freqs, _) = plt.magnitude_spectrum(downsampled_audio[i, :],
                                                      Fs=Fs_down)
        freqs = freqs / (2 * max(freqs))
        spectrum = spectrum
        for j in range(int(n_bins)):
            #avg_freqs[i, j] = (Fs_down)*np.dot(spectrum[int(j*Fs_down/n_bins):int((j+1)*Fs_down/n_bins)], freqs[int(j*Fs_down/n_bins):int((j+1)*Fs_down/n_bins)])/sum(spectrum[int(j*Fs_down/n_bins):int((j+1)*Fs_down/n_bins)])
            max_freqs[i, j] = max(
                spectrum[int(j * sample_length * Fs_down /
                             (2 * n_bins)):int((j + 1) * sample_length *
                                               Fs_down / (2 * n_bins))])

    for i in range(n_bins):
        avg_freqs_zeroed[:, i] = avg_freqs[:, i] - average(avg_freqs[:, i])
        max_freqs_zeroed[:, i] = max_freqs[:, i] - average(max_freqs[:, i])

    for i in range(live_samples.shape[0]):
        if sum(max_freqs[i, :]) != 0:
            max_proportions[i, :] = max_freqs[i, :] / sum(max_freqs[i, :])

    plt.figure()
    plt.boxplot(max_proportions)
Exemplo n.º 11
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()
def create_lpspectrum(file, order):
    file = str(file)
    audio_path = 'static/wav/audio' + file + '.wav'
    audio, sampling_rate = librosa.load(audio_path)

    lp_result = librosa.lpc(audio, order)
    y_result = scipy.signal.lfilter([0] + -1 * lp_result[1:], [1], audio)

    plt.figure()
    plt.grid()
    plt.magnitude_spectrum(y_result, Fs=sampling_rate, color="blue")
    plt.title('LP Spectrum')
    plt.grid(color='grey', linestyle='--', linewidth=0.5)
    plt.savefig('static/images/lpspectrum-wav' + file + '-order' + str(order) +
                '.png')
    plt.close()
    return plt
Exemplo n.º 13
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)
Exemplo n.º 14
0
def mplot(x, y, z, q, title, Fs=4000):
    plt.figure()
    plt.subplot(2, 1, 1)
    plt.title(title)
    plt.magnitude_spectrum(x, Fs=Fs, color='blue', scale='dB')
    plt.magnitude_spectrum(y, Fs=Fs, color='red', scale='dB')

    plt.subplot(2, 1, 2)
    plt.magnitude_spectrum(z, Fs=Fs, color='blue', scale='dB')
    plt.magnitude_spectrum(q, Fs=Fs, color='red', scale='dB')
Exemplo n.º 15
0
    def makeChart(self, intensities, masses):
        # allIntensities = np.sort([intensity for sample in intensities for intensity in sample])
        plt.figure(figsize=(6.25, 7.25))
        plt.title("Magnitude Spectrum")
        plt.ylabel('Intensities')
        plt.xlabel('M/Z charge')
        for i in range(0, intensities.shape[0]):
            plt.magnitude_spectrum(intensities[i][:], Fs=masses)

        plt.savefig('TESTMASS.png',
                    dpi=300,
                    facecolor='w',
                    edgecolor='w',
                    orientation='portrait',
                    papertype=None,
                    format=None,
                    transparent=False,
                    bbox_inches=None,
                    pad_inches=0.1)
Exemplo n.º 16
0
def plots(samples, freq, data):
    plt.figure()
    spec, freq, line = plt.magnitude_spectrum(data, Fs=freq, scale='dB', color='C2')
    peak, _ = signal.find_peaks(spec, height=10000)
    plt.plot(freq[peak], 20 * np.log10(spec[peak]), 'x')
    print(freq[peak])
    plt.xlim(0, 500)

    plt.figure()
    plt.plot(data[:samples],)
Exemplo n.º 17
0
def plot_imu_scaled_fft(sensor, measurements, attrs):
    """Plot imu scaled fft results."""
    #dt = 0.0769
    #Fs = 1/dt
    Fs = 26.0

    plt.figure("Sensor Scaled - FFT")

    plt.subplot(3, 1, 1)
    plt.magnitude_spectrum(measurements[:, 1] * attrs[0],
                           Fs=Fs,
                           scale='linear')
    plt.ylabel(attrs[2])
    plt.title(sensor)

    plt.subplot(3, 1, 2)
    plt.magnitude_spectrum(measurements[:, 2] * attrs[0],
                           Fs=Fs,
                           scale='linear')
    plt.ylabel(attrs[3])

    plt.subplot(3, 1, 3)
    plt.magnitude_spectrum(measurements[:, 3] * attrs[0],
                           Fs=Fs,
                           scale='linear')
    plt.xlabel('Frequency')
    plt.ylabel(attrs[4])

    plt.show()
Exemplo n.º 18
0
def cic_test_noise(dut):
    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.signal import lfilter

    fs = 25e6
    ts = 1/fs
    d = 8

    fc = 10e6
    t = np.arange(0,.001,ts)
    print(ts)
    s = np.int16(np.random.normal(0,1024,len(t)))

    s_output = []

    for s_i in s:
        yield dut.i_sample.eq(int(s_i))
        if (yield dut.o_valid):
            result = (yield dut.o_result)
            s_output.append(result/512)
        yield

    s_output = np.array(s_output)
    t_output = t[::d]
    s_output_filtered = lfilter([1,-10,1], 1.0, s_output)/8
    plt.subplot(2,1,1)
    plt.plot(t,s)
    plt.plot(t_output, s_output)
    plt.plot(t_output, s_output_filtered)
    plt.subplot(2,1,2)
    plt.magnitude_spectrum(s, fs, scale='dB', alpha=.5)
    plt.magnitude_spectrum(s_output, fs/d, scale='dB', alpha=.5)
    plt.magnitude_spectrum(s_output_filtered, fs/d, scale='dB', alpha=.5)
    plt.show()
Exemplo n.º 19
0
def plot_spectogram(channel):
    """
    Plot a spectocram for sample.
    """
    channel = np.array(channel[0, :])[0]
    # f, t, Sxx = signal.spectrogram(channel, fs=100)
    # print(f, t, Sxx)
    # plt.pcolormesh(t, f, Sxx)
    plt.specgram(channel,
                 Fs=100,
                 scale='dB',
                 NFFT=100,
                 noverlap=5,
                 mode='psd',
                 detrend='mean')
    plt.ylabel('Frequency [Hz]')
    plt.xlabel('Time [s]')
    plt.ylim([0, 100])
    plt.show()
    plt.magnitude_spectrum(channel, Fs=100, scale='dB')
    plt.xlim([0, 30])
    plt.show()
Exemplo n.º 20
0
    def draw_MFCC(self):
        random = np.random.randint(0, len(self.words))
        x_axis = np.linspace(0, 800, len(self.words[0]))

        # plt.figure("Plots of the word "+self.class_names[int(self.labels[random])])
        plt.subplot(311)
        # plt.title("Time domain Representation")
        plt.xlabel("Time (in ms)")
        plt.ylabel("Amplitude")
        plt.plot(x_axis, self.words[random])

        plt.subplot(312)
        # plt.title("Frequency domain Representation")
        plt.xlabel("Frequency (in Hz)")
        plt.ylabel("Power")
        plt.magnitude_spectrum(self.words[random], Fs=self.SR)

        plt.subplot(313)
        mfcc = librosa.feature.mfcc(y=self.words[random],
                                    sr=self.SR,
                                    n_mfcc=40,
                                    cmap="RdYlBu")
        librosa.display.specshow(mfcc, sr=self.SR, x_axis="ms", y_axis="mel")
        plt.show()
    def find_most_periodic_signal(self, pca_array, time_array):
        """
        Find the most periodic signal to use for pulse calculation.
        Uses the highest value of the autocorrelation funciton
        :param pca_array: the array resulting from process_PCA
        :param time_array:
        """
        sample_rate = len(pca_array[0]) / (time_array[-1] - time_array[0])
        best_signal = None
        best_frequency = 0
        best_correlation = 0
        for ind, signal in enumerate(pca_array):
            spectrum, frequencies, _ = plt.magnitude_spectrum(signal,
                                                              Fs=sample_rate)
            max_index = np.argmax(spectrum)
            strongest_frequency = frequencies[max_index]

            # strongest frequency is far too small
            if strongest_frequency < 0.1:
                continue

            T_i = int(sample_rate / strongest_frequency)
            s_i_new = np.roll(signal, T_i)
            correlation = stats.pearsonr(s_i_new, signal)[0]

            if correlation > best_correlation:
                best_frequency = strongest_frequency
                best_correlation = correlation
                best_signal = signal

            #  uncomment the following lines to see the magnitude spectrum of the PCA singal. For debugging.
            # filename = "/home/studienarbeit/Dokumente/" + str(self.published_pulse_value_sequence) + "_step5_periodic_pca_signal_" + str(ind)
            # plt.xlim(0, 10)
            # plt.savefig(filename)
            # plt.close()

        # uncomment the following lines to see the most periodic signal of the PCA. For debugging.
        # filename = "/home/studienarbeit/Dokumente/" + str(self.seq) + "_periodic_pca_signal_"
        # sample_rate = len(pca_array[0]) / (time_array[-1] - time_array[0])
        # stepsize = 1. / sample_rate
        # pca_array = None
        # xs = np.arange(time_array[0], time_array[-1], stepsize)
        # plt.figure(figsize=(6.5, 4))
        # plt.plot(xs, best_signal, label="S")
        # plt.show()
        # print(best_frequency)
        return best_signal, best_frequency
Exemplo n.º 22
0
def plot_imu_scaled_fft(sensor, measurements, attrs):
    """Plot imu scaled fft results."""
    #dt = 0.0769
    #Fs = 1/dt
    Fs = 26.0

    plt.figure("Sensor Scaled - FFT")

    plt.subplot(3, 1, 1)
    plt.magnitude_spectrum(measurements[:, 1]*attrs[0], Fs=Fs, scale='linear')
    plt.ylabel(attrs[2])
    plt.title(sensor)

    plt.subplot(3, 1, 2)
    plt.magnitude_spectrum(measurements[:, 2]*attrs[0], Fs=Fs, scale='linear')
    plt.ylabel(attrs[3])

    plt.subplot(3, 1, 3)
    plt.magnitude_spectrum(measurements[:, 3]*attrs[0], Fs=Fs, scale='linear')
    plt.xlabel('Frequency')
    plt.ylabel(attrs[4])

    plt.show()
Exemplo n.º 23
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()
Exemplo n.º 24
0
T = 1 / fs


f1 = 0.1 * fs
f2 = 0.2 * fs
f3 = 0.4 * fs

plt.grid()

t = numpy.linspace(0, N * T, N)
sig = (0.8 * numpy.sin(2 * numpy.pi * t * f1) +
       1.0 * numpy.sin(2 * numpy.pi * t * f2) +
       0.6 * numpy.sin(2 * numpy.pi * t * f3) +
       numpy.random.randn(N))

plt.magnitude_spectrum(sig, fs)
plt.show()

# sig_f = numpy.fft.fft(sig)
# x_f = numpy.fft.fftfreq(N,T)


filt = signal.firwin(DOWN*10, 1./UP)


w, h = signal.freqz(filt)
plt.plot(0.5*fs*w/numpy.pi, numpy.abs(h), 'b')
plt.show()

downsample = sig.reshape([-1, DOWN]).T
filt_down = filt.reshape([DOWN, -1])
Exemplo n.º 25
0
[fs1, sig1] = util.WavRead(args.i1)
[fs2, sig2] = util.WavRead(args.i2)

#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
wait = 3
while wait > 0:
    print(wait)
    time.sleep(1)
    wait = wait - 1
if wait <= 0:
    print('START')
my_recording = sd.rec(int(rec_duration_s * sps_hz),
                      samplerate=sps_hz,
                      channels=1)
sd.wait()
write('input.wav', sps_hz, my_recording)

# 2. Apply FFT on recording to get highest audible frequency:
fs_rate, signal = read("input.wav")
spectrum, freqs, line = plt.magnitude_spectrum(signal, fs_rate)
max_idx = np.argmax(spectrum)
HighestAudibleFrequency = freqs[max_idx]
print(HighestAudibleFrequency)

# 4. Generate a tone:
tone_duration_s = 3

# To find the fifth of a note, multiply its frequency by 1.5
fifth_freq_hz = int(HighestAudibleFrequency * 1.5)

each_sample_number = np.arange(tone_duration_s * sps_hz)
waveform = np.sin(2 * np.pi * each_sample_number * fifth_freq_hz / sps_hz)
# Tone down the amplitude by a factor of 0.3
waveform_quiet = waveform * 0.3
# Convert to 16 bits (2^16 = 65536, 65536/2 = 32768 (x-axis to peak))
Exemplo n.º 27
0
def create_grafic(create_grafic_file_name, y, h, create_grafic_datafilt, data,
                  fs):
    """
    -> Cria os graficos 
    :param create_grafic_file_name: str
            Nome do arquivo que foi tratado
    :param y: array_like
            Dados filtrados
    :param h: array_like
            Dados filtrados retirado o noth
    :param create_grafic_datafilt: np.array
            Dados filtrados salvos tipo numpy
    :param data: array_like
            dados originais sem tratamento
    :param fs: int
            Valor do SampleRate  
    :return: Sem retorno
    
    Thiago Carvalho @destritux    
    """
    name_path_file = './' + create_grafic_file_name
    os.makedirs(name_path_file)
    name = name_path_file + '/' + create_grafic_file_name + '_filtrado'
    save_file(y, name)

    print(f"\nCriando plot RAW SIGNAL...")
    plt.figure(1)
    plt.clf()
    plt.title("RAW signal ")
    plt.plot(data, color=Plt_color, linewidth=Plt_width)
    plt.ylabel("ΔV(mV)")
    plt.xlabel("time(s)")
    plt.tight_layout()

    grafic_name = str('RAW_SIGNAL')
    name_file = name_path_file + '/' + create_grafic_file_name + '_' + grafic_name

    save_img_tiff(name_path_file, create_grafic_file_name, grafic_name)
    save_file(data, name_file)
    print("RAW SIGNAL concluído!")
    print("-=" * 30)

    print("\nCriando plot FILTERED SIGNAL...")
    plt.figure(2)
    plt.clf()
    plt.title("Filtered signal")
    plt.plot(create_grafic_datafilt, color=Plt_color, linewidth=Plt_width)
    plt.ylabel("ΔV(mV)")
    plt.xlabel("time(s)")
    plt.tight_layout()

    grafic_name = str('FILTERED_SIGNAL')
    name_file = name_path_file + '/' + create_grafic_file_name + '_' + grafic_name

    save_img_tiff(name_path_file, create_grafic_file_name, grafic_name)
    save_file(y, name_file)
    print("FILTERED SIGNAL concluído!")
    print("-=" * 30)

    print("\nCriando plot FFT FILT...")
    plt.figure(3)
    plt.clf()
    plt.title("Fast Fourier Transform FILT")
    plt.magnitude_spectrum(create_grafic_datafilt,
                           Fs=fs,
                           color=Plt_color,
                           linewidth=Plt_width)
    plt.ylabel("F")
    plt.xlabel('frequency (Hz)')
    plt.tight_layout()

    grafic_name = str('FFT_FILT')
    name_file = name_path_file + '/' + create_grafic_file_name + '_' + grafic_name

    save_img_tiff(name_path_file, create_grafic_file_name, grafic_name)
    save_file(y, name_file)

    print("FFT FILT concluído!")
    print("-=" * 30)

    print("\nCriando plot FFT RAW...")
    plt.figure(4)
    plt.clf()
    plt.title("Fast Fourier Transform RAW...")
    plt.magnitude_spectrum(data, Fs=fs, color=Plt_color, linewidth=Plt_width)
    plt.ylabel("F")
    plt.xlabel('frequency (Hz)')
    plt.tight_layout()

    grafic_name = str('FFT_RAW')
    name_file = name_path_file + '/' + create_grafic_file_name + '_' + grafic_name

    save_img_tiff(name_path_file, create_grafic_file_name, grafic_name)
    save_file(y, name_file)
    print("FAST FOURIER TRANSFORM concluído!")
    print("-=" * 30)

    print("\nCriando plot PSD...")
    f_values, psd_values = signal.welch(create_grafic_datafilt, fs)

    plt.figure(5)
    plt.clf()
    plt.title("Power Spectral Density")
    plt.plot(f_values,
             psd_values,
             linestyle='-',
             color=Plt_color,
             linewidth=Plt_width)
    plt.xlabel('frequency (Hz)')
    plt.ylabel('PSD')
    plt.tight_layout()

    grafic_name = str('PSD')
    name_file = name_path_file + '/' + create_grafic_file_name + '_' + grafic_name

    save_img_tiff(name_path_file, create_grafic_file_name, grafic_name)
    save_file(y, name_file)
    print("PSD concluído!")
    print("-=" * 30)

    print("\nCriando plot Histogram...")
    plt.figure(6)
    plt.clf()
    plt.title("Histogram")

    series = pd.Series(create_grafic_datafilt)
    series.hist(bins=44, grid=0)
    plt.tight_layout()
    grafic_name = str('Histogram')
    name_file = name_path_file + '/' + create_grafic_file_name + '_' + grafic_name

    save_img_tiff(name_path_file, create_grafic_file_name, grafic_name)
    #save_file(y, name_file)
    print("Histogram concluído!")
    print("-=" * 30)
    plt.plot()

    print("\nCriando plot Density...")
    plt.figure(7)
    plt.clf()
    plt.title("Density")
    series.plot(kind='kde')
    plt.tight_layout()
    grafic_name = str('Density')
    name_file = name_path_file + '/' + create_grafic_file_name + '_' + grafic_name

    save_img_tiff(name_path_file, create_grafic_file_name, grafic_name)
    print("Density concluído!")
    print("-=" * 30)
    plt.plot()

    print("\nCriando plot Lag Scatter...")
    plt.figure(8)
    plt.clf()
    plt.title("Lag Scatter")

    pd.plotting.lag_plot(series)

    plt.tight_layout()
    grafic_name = str('Lag Scatter')
    name_file = name_path_file + '/' + create_grafic_file_name + '_' + grafic_name

    save_img_tiff(name_path_file, create_grafic_file_name, grafic_name)
    print("Lag Scatter concluído!")
    print("-=" * 30)
    plt.plot()

    print("\nCriando plot Autocorrelation...")
    plt.figure(9)
    plt.clf()
    plt.title("Autocorrelation")

    pd.plotting.autocorrelation_plot(series)

    plt.tight_layout()
    grafic_name = str('Autocorrelation')
    name_file = name_path_file + '/' + create_grafic_file_name + '_' + grafic_name

    save_img_tiff(name_path_file, create_grafic_file_name, grafic_name)
    print("Autocorrelation concluído!")
    print("-=" * 30)
    plt.plot()
    return
Exemplo n.º 28
0
def magnitude_spectrum(*args, **kwargs):
    r"""starkplot wrapper for magnitude_spectrum"""
    return _pyplot.magnitude_spectrum(*args, **kwargs)
Exemplo n.º 29
0
no_dither = [0.0] * length
lfsr_dither = [0.0] * length
random_dither = [0.0] * length

for n in range(length):

    lfsr_config = {"in": 1, "ce": 1}
    no_dither[n] = fractional_n_divider_model_no_dither.update()
    lfsr_dither[n] = fractional_n_divider_model_lfsr_dither.update()
    random_dither[n] = fractional_n_divider_model_random_dither.update()

    if lfsr_dither[n] != lfsr_dither[n - 1]:
        fractional_n_divider_model_lfsr_dither.set_divide_value(
            N + F + lfsr_model.update(lfsr_config) / 2**WIDTH_MODULUS)

    if random_dither[n] != random_dither[n - 1]:
        fractional_n_divider_model_random_dither.set_divide_value(
            N + F + random.randint(0, 1) / 2**WIDTH_MODULUS)

# find the average value
print(np.mean(no_dither))
print(np.mean(lfsr_dither))
print(np.mean(random_dither))

# plot the resulting sprectrum
plt.magnitude_spectrum(no_dither, Fs=10e6, scale='dB')
plt.magnitude_spectrum(lfsr_dither, Fs=10e6, scale='dB')
plt.magnitude_spectrum(random_dither, Fs=10e6, scale='dB')
plt.legend(['no dither', 'lfsr dither', 'random dither'])
plt.xscale('log')
plt.show()
Exemplo n.º 30
0
plt.plot(array[:, 0], array[:, 1])
plt.subplot(412)
plt.plot(array[:, 0], array[:, 2])
plt.subplot(413)
plt.plot(array[:, 0], array[:, 3])
plt.subplot(414)
plt.plot(array[:, 0], array[:, 4])

plt.show()
plt.figure(2)
plt.subplot(411)
plt.plot(array[:, 0], array[j:1:i, 5], array[j:1:i, 0], array[j:1:i, 9])
plt.subplot(412)
plt.plot(array[j:1:i, 0], array[j:1:i, 6], array[j:1:i, 0], array[:, 10])
plt.subplot(413)
plt.plot(array[j:1:i, 0], array[j:1:i, 7], array[j:1:i, 0], array[j:1:i, 11])
plt.subplot(414)
plt.plot(array[j:1:i, 0], array[j:1:i, 8], array[j:1:i, 0], array[j:1:i, 12])
plt.show()

plt.figure(3)
plt.subplot(3, 2, 1)
plt.plot(array[j:1:i, 4])
plt.yscale('linear')
plt.title('Acelerometer Axis value')
plt.subplot(3, 2, 3)
plt.magnitude_spectrum(array[j:1:i, 4], Fs=Fs)
plt.subplot(3, 2, 4)
plt.magnitude_spectrum(array[j:1:i, 4], Fs=Fs, scale='dB')
plt.show()
Exemplo n.º 31
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
def plot_frequency(samples, shifted_samples, sampling_rate):
	plt.magnitude_spectrum(samples, Fs=sampling_rate, label='Original')
	plt.magnitude_spectrum(shifted_samples, Fs=sampling_rate, label='Shifted')
	plt.legend()
	plt.show()
	return
Exemplo n.º 33
0
                                    0)  # Receive a number of samples

    if type == 62:
        Qa, In = format(type, 1, result)
        np.savetxt(
            'C:/Users/senag/Documents/Project_SRON/Output_files/Qa_out.out',
            Qa[:samples])  # Save results in file
        np.savetxt(
            'C:/Users/senag/Documents/Project_SRON/Output_files/In_out.out',
            In[:samples])  # Save results in file
        plt.figure()
        plt.plot(Qa[:samples])
        plt.plot(In[:samples])
        plt.figure()
        plt.magnitude_spectrum(Qa[:samples],
                               Fs=Sample_frequency,
                               color='red',
                               scale='dB')
        plt.magnitude_spectrum(In[:samples],
                               Fs=Sample_frequency,
                               color='blue',
                               scale='dB')
    elif type == 48:
        adc, sin, cos = format(type, 1, result)
        np.savetxt(
            'C:/Users/senag/Documents/Project_SRON/Output_files/adc_out.out',
            adc[:samples])  # Save results in file
        np.savetxt(
            'C:/Users/senag/Documents/Project_SRON/Output_files/sin_out.out',
            sin[:samples])  # Save results in file
        np.savetxt(
            'C:/Users/senag/Documents/Project_SRON/Output_files/cos_out.out',
Exemplo n.º 34
0
import numpy as np

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.tight_layout()

plt.show()