예제 #1
0
def plot_x_and_psd_with_estimated_omega(x, sample_step=1, dt=1.0):
    y = x[::sample_step]
    F = freq(x, sample_step, dt)
    T = 1.0 / F

    pylab.clf()

    # plot PSD
    pylab.subplot(211)
    pylab.psd(y, Fs=1.0 / sample_step / dt)
    ylim = pylab.ylim()
    pylab.vlines(F, *ylim)
    pylab.ylim(ylim)

    # plot time series
    pylab.subplot(223)
    pylab.plot(x)

    # plot time series (three cycles)
    n = int(T / dt) * 3
    m = n // sample_step
    pylab.subplot(224)
    pylab.plot(x[:n])
    pylab.plot(numpy.arange(0, n, sample_step)[:m], y[:m], 'o')

    pylab.suptitle('F = %s' % F)
예제 #2
0
def RMSfromPSD(data, samplerate, graph=True):

    y, x = pylab.psd(data, NFFT=nfft, Fs=samplerate)
    t = np.linspace(0, len(data) * samplerate, num=len(data))
    # Calculate the RMS

    # The energy returned by PSD depends on FFT size
    freqbandwidth = x[1]
    y = y * freqbandwidth

    # The energy returned by PSD depends on Samplerate
    y = y / float(samplerate)

    # Summing the power in freq domain to get RMS
    rms = scipy.sqrt(y.sum())
    if graph == True:
        pylab.subplot(311)
        pylab.plot(t, data)
        pylab.subplot(312)
        pylab.plot(MovingAverage(data, 100))
        pylab.subplot(313)
        pylab.psd(data, nfft, samplerate)
        pylab.show()

    return rms
예제 #3
0
def main():
    sdr = LimeSDR()

    sdr.enable_channel(False, 0, True)
    sdr.set_LO_frequency(False, 0, 434e6)

    sdr.set_antenna(False, 0, 2)

    sdr.set_sample_rate(10e6, 4)
    a, b, c = sdr.get_LPF_BW_range(False)

    sdr.set_LPF_BW(False, 0, 10e6)
    sdr.set_normalized_gain(False, 0, 0.7)

    sdr.calibrate(False, 0, 10e6, 0)
    stream = sdr.setup_stream(0, 1024 * 1024, 0.5, False, 2)
    sdr.start_stream(stream)

    start_time = datetime.datetime.now()
    current_time = datetime.datetime.now()
    while ((current_time - start_time).seconds < 2):
        iq = sdr.receive_stream_iq(stream, 1024, 1000)
        mpl.figure()
        mpl.psd(iq, NFFT=1024, Fc=434, Fs=10)
        mpl.show()
        print('  signal mean:', sum(iq) / len(iq))
        current_time = datetime.datetime.now()

    sdr.close()
예제 #4
0
파일: analysis.py 프로젝트: adrianq/netpyne
def plotLFPSpectrum():
    colorspsd=array([[0.42,0.67,0.84],[0.42,0.83,0.59],[0.90,0.76,0.00],[0.90,0.32,0.00],[0.34,0.67,0.67],[0.42,0.82,0.83],[0.90,0.59,0.00],[0.33,0.67,0.47],[1.00,0.85,0.00],[0.71,0.82,0.41],[0.57,0.67,0.33],[1.00,0.38,0.60],[0.5,0.2,0.0],[0.0,0.2,0.5]]) 

    lfpv=[[] for c in range(len(f.lfppops))]    
    # Get last modified .mat file if no input and plot
    for c in range(len(f.lfppops)):
        lfpv[c] = f.lfps[:,c]    
    lfptot = sum(lfpv)
        
    # plot pops separately
    plotPops = 0
    if plotPops:    
        figure() # Open a new figure
        for p in range(len(f.lfppops)):
            psd(lfpv[p],Fs=200, linewidth= 2,color=colorspsd[p])
            xlabel('Frequency (Hz)')
            ylabel('Power')
            h=axes()
            h.set_yticklabels([])
        legend(['L2/3','L5A', 'L5B', 'L6'])

    # plot overall psd
    figure() # Open a new figure
    psd(lfptot,Fs=200, linewidth= 2)
    xlabel('Frequency (Hz)')
    ylabel('Power')
    h=axes()
    h.set_yticklabels([])

    show()
예제 #5
0
def main():
    sdr = RtlSdr()

    print 'Configuring SDR...'
    sdr.rs = 2.4e6
    sdr.fc = 100e6
    sdr.gain = 10
    print '  sample rate: %0.6f MHz' % (sdr.rs/1e6)
    print '  center frequency %0.6f MHz' % (sdr.fc/1e6)
    print '  gain: %d dB' % sdr.gain

    print 'Reading samples...'
    samples = sdr.read_samples(256*1024)
    print '  signal mean:', sum(samples)/len(samples)

    print 'Testing callback...'
    sdr.read_samples_async(test_callback, 256*1024)

    try:
        import pylab as mpl

        print 'Testing spectrum plotting...'
        mpl.figure()
        mpl.psd(samples, NFFT=1024, Fc=sdr.fc/1e6, Fs=sdr.rs/1e6)

        mpl.show()
    except:
        # matplotlib not installed/working
        pass

    print 'Done\n'
    sdr.close()
예제 #6
0
def analyze_data(data):
    """ analyzes characteristics of the (input) data
    """
    example = 4
    pylab.figure()
    pylab.subplot(2, 1, 1)
    pylab.plot(data[:, example])
    pylab.subplot(2, 1, 2)
    pylab.psd(data[:, example])

    example = 3
    pylab.figure()
    pylab.subplot(2, 1, 1)
    pylab.plot(data[:, example])
    pylab.subplot(2, 1, 2)
    pylab.psd(data[:, example])

    # nicht wirklich aussagekraeftig:
    #    pylab.figure()
    #    pylab.subplot(2,1,1)
    #    pylab.plot(data.flatten())
    #    pylab.subplot(2,1,2)
    #    pylab.psd(data.flatten())

    pylab.show()
    exit(0)
예제 #7
0
def test_waveletfilter(plot=False):
    # make test signal
    Fs = 44100
    freqs = [100,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000]
    t = np.arange(Fs,dtype=np.float64) / float(Fs) # 1 second
    x = np.zeros(len(t))
    for f in freqs:
        x += np.sin(t * f * 2. * np.pi)
    x /= len(freqs)
    # print t,x
    
    filtered = pywaveclus.dsp.wavelet.filt(x, minlevel=3, maxlevel=6)
    assert len(filtered) == len(x),\
        "len(filtered)[%i] != len(x)[%i]" % (len(filtered), len(x))
    
    # TODO: test effectiveness of cutoffs
    
    if plot:
        import pylab as pl
        pl.subplot(221)
        pl.plot(t,x)
        pl.subplot(222)
        pl.psd(x,Fs=Fs)
        pl.subplot(223)
        pl.plot(t,filtered)
        pl.subplot(224)
        pl.psd(filtered,Fs=Fs)
        
        pl.show()
예제 #8
0
def test_waveletfilter(plot=False):
    # make test signal
    Fs = 44100
    freqs = [100, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]
    t = np.arange(Fs, dtype=np.float64) / float(Fs)  # 1 second
    x = np.zeros(len(t))
    for f in freqs:
        x += np.sin(t * f * 2. * np.pi)
    x /= len(freqs)
    # print t,x

    filtered = pywaveclus.dsp.wavelet.filt(x, minlevel=3, maxlevel=6)
    assert len(filtered) == len(x),\
        "len(filtered)[%i] != len(x)[%i]" % (len(filtered), len(x))

    # TODO: test effectiveness of cutoffs

    if plot:
        import pylab as pl
        pl.subplot(221)
        pl.plot(t, x)
        pl.subplot(222)
        pl.psd(x, Fs=Fs)
        pl.subplot(223)
        pl.plot(t, filtered)
        pl.subplot(224)
        pl.psd(filtered, Fs=Fs)

        pl.show()
예제 #9
0
def main():
    sdr = RtlSdr()

    print 'Configuring SDR...'
    sdr.rs = 2.4e6
    sdr.fc = 100e6
    sdr.gain = 10
    print '  sample rate: %0.6f MHz' % (sdr.rs / 1e6)
    print '  center frequency %0.6f MHz' % (sdr.fc / 1e6)
    print '  gain: %d dB' % sdr.gain

    print 'Reading samples...'
    samples = sdr.read_samples(256 * 1024)
    print '  signal mean:', sum(samples) / len(samples)

    print 'Testing callback...'
    sdr.read_samples_async(test_callback, 256 * 1024)

    try:
        import pylab as mpl

        print 'Testing spectrum plotting...'
        mpl.figure()
        mpl.psd(samples, NFFT=1024, Fc=sdr.fc / 1e6, Fs=sdr.rs / 1e6)

        mpl.show()
    except:
        # matplotlib not installed/working
        pass

    print 'Done\n'
    sdr.close()
예제 #10
0
def plot_x_and_psd_with_estimated_omega(x, sample_step=1, dt=1.0):
    y = x[::sample_step]
    F = freq(x, sample_step, dt)
    T = 1.0 / F

    pylab.clf()

    # plot PSD
    pylab.subplot(211)
    pylab.psd(y, Fs=1.0 / sample_step / dt)
    ylim = pylab.ylim()
    pylab.vlines(F, *ylim)
    pylab.ylim(ylim)

    # plot time series
    pylab.subplot(223)
    pylab.plot(x)

    # plot time series (three cycles)
    n = int(T / dt) * 3
    m = n // sample_step
    pylab.subplot(224)
    pylab.plot(x[:n])
    pylab.plot(numpy.arange(0, n, sample_step)[:m], y[:m], 'o')

    pylab.suptitle('F = %s' % F)
예제 #11
0
def main():
	ntone = 64
	buflen = 65536

	v = np.zeros(buflen,dtype=np.complex)
	phase = 2*pi*np.random.uniform(size=ntone)

	for i in range(ntone):
		j = i * buflen/ntone
		u = np.exp(1.j*phase[i])
		v[j] = u

	ts = np.fft.ifft(v)
	re,im = ts.real,ts.imag

	maxval = np.max(np.abs([re,im]))
	re *= 0.2*32767./maxval
	im *= 0.2*32767./maxval

	re = np.round(re).astype(dtype=np.int16)
	im = np.round(im).astype(dtype=np.int16)

	ts = re + 1.0j*im

	d = np.vstack((re,im)).T
	print d.shape

	np.savetxt('rf_in.dat',d,fmt='%d',header='%d'%buflen)

	pl.psd(ts)
	pl.show()
예제 #12
0
	def PlotPsd(self):
		"""
		compute and plot the matplotlib psd

		"""

		py.psd(self.data,512,self.length)
		py.show()
예제 #13
0
    def PlotPsd(self):
        """
		compute and plot the matplotlib psd

		"""

        py.psd(self.data, 512, self.length)
        py.show()
예제 #14
0
def main():

	print ' '

	# Space Frequency
	f1 = -50000 #Hz
	# Mark Freq
	f2 = 50000 #Hz
	# Sample Rate
	sampleRate = 2.4e6#Hz
	# Baud Rate
	baud=1200.0 #sps
	# Number of Samples
	numSamples = 256*256

	packet=[1,0,1,1,0]

	samples=[]
	timeVector=[]
	bitNum=0
	timePassed=0

	for i in range(numSamples):

		timePassed=timePassed+1/sampleRate

		if (timePassed>(1/baud)):
			timePassed=0
			print(packet[bitNum])
			bitNum=bitNum+1
			if (bitNum==len(packet)):
				bitNum=0

		if(packet[bitNum]==0):
			samples.append(numpy.power(numpy.e,1j*2*numpy.pi*f1*i/sampleRate))
		
		if(packet[bitNum]==1):
			samples.append(numpy.power(numpy.e,1j*2*numpy.pi*f2*i/sampleRate))


	pylab.figure()
	pylab.psd(samples, NFFT=1024, Fc=1, Fs=sampleRate/(1e6))
	pylab.show()

	pylab.figure()
	pylab.plot(samples)
	pylab.show()

	print 'Creating IQ.csv...' + '\n'
	f=open('IQ_gen.csv','w')

	f.write('Sample Rate,' + str(sampleRate)+ '\nCenter Freq,'+str((f2+f1)/2)+ '\nGain,'+str(20)+ '\nSamples Per Sweep,'+str(numSamples)+'\nNumber of Sweeps,'+str(numSamples)+str('\n\n'))
	f.write('Time Elapsed, Sample\n')

	print 'Writing CSV data...' + '\n'

	for j in range(numSamples):
		f.write(str(j/sampleRate)+','+str(samples[j])+ '\n')
def test_psd():

    from numpy import linspace,sin
    from pylab import psd,show
    x = linspace(0,100,10000)
    y = sin(x*100)/100.

    psd(y,NFFT=256,scale_by_freq=True)
    show()
예제 #16
0
def plot_sample0(samp):
    N = min(len(samp), 256)
    fs = 48000
    pl.subplot(211)
    pl.grid()
    pl.plot(samp)
    pl.subplot(212)
    pl.grid()
    #pl.ylim((-50, 50))
    pl.psd(samp, N, window=pl.blackman(N), Fs=fs)
예제 #17
0
    def plot_psd(self,fc,samp_scale=256):
        if self.sdr.center_freq != fc:
            self.sdr.center_freq = fc

        samples = self.sdr.read_samples(samp_scale*1024)

        # use matplotlib to estimate and plot the PSD
        psd(samples, NFFT=1024, Fs=self.sdr.sample_rate/1e6, \
            Fc=self.sdr.center_freq/1e6)
        xlabel('Frequency (MHz)')
        ylabel('Relative power (dB)')

        show()
예제 #18
0
파일: IQ_Record.py 프로젝트: rlagoy/comms
def main():
	sdr = RtlSdr()
	print ' '

	# Bandwidth/Sample Rate
	sdr.rs = 2e6
	# Center Freq
	sdr.fc = 907.941e6
	# Gain
	sdr.gain = 20
	numSamplesPerSweep = 256*256*8
	numSweeps = 7

	samples=[0]*numSweeps*numSamplesPerSweep
	timeVector=[]

	print 'Capturing data for ' + str(numSweeps) + ' sweeps...' + '\n'
	for i in range(numSweeps):
		samples[i*numSamplesPerSweep:(i+1)*numSamplesPerSweep-1]=(sdr.read_samples(numSamplesPerSweep))
		timeVector.append(time.clock())
		# print samples

	print 'Creating IQ.csv...' + '\n'
	f=open('IQ.csv','w')

	print 'Writing CSV data...' + '\n'

	f.write('Sample Rate,' + str(sdr.rs)+ '\nCenter Freq,'+str(sdr.fc)+ '\nGain,'+str(sdr.gain)+ '\nSamples Per Sweep,'+str(numSamplesPerSweep)+'\nNumber of Sweeps,'+str(numSweeps)+str('\n\n'))
	f.write('Time Elapsed, Sample\n')


	for i in range(numSweeps):
		for j in range(numSamplesPerSweep-1):
			f.write(str(timeVector[i]-timeVector[0]+j/sdr.rs)+','+str(samples[i*numSamplesPerSweep+j])+ '\n')
		f.write(str(timeVector[i]-timeVector[0]+j/sdr.rs)+','+str(samples[(i+1)*numSamplesPerSweep-1]) + '\n')

	f.close

	print 'CSV file created; program terminating...' + '\n'

	pylab.figure()
	pylab.psd(samples, NFFT=1024, Fc=sdr.fc/(1e6), Fs=sdr.rs/(1e6))
	pylab.show()

	pylab.figure()
	pylab.plot(samples)
	pylab.show()



	sdr.close()
예제 #19
0
def numsyls(path1):
    fils1 = [x for x in os.listdir(path1) if x[-4:] == '.wav']

    fils1 = fils1[:120]

    filename1 = path1.split('/')[-2]

    datano = 15000  # maximum number of syllables to be analyzed

    # get syllables from all of the songs in folder
    syls1 = []
    objss1 = []
    for file in fils1:
        song = impwav(path1 + file)
        if len(song[0]) < 1: break
        syls, objs, frq = (getsyls(song))
        objss1.append(objs)
        syls1.append([frq] + syls)

    # convert syllables so PSDs
    segedpsds1 = []
    for x in syls1[:datano]:
        fs = x[0]
        nfft = int(round(2 ** 14 / 32000.0 * fs))
        segstart = int(round(600 / (fs / float(nfft))))
        segend = int(round(16000 / (fs / float(nfft))))
        psds = [psd(norm(y), NFFT=nfft, Fs=fs) for y in x[1:]]
        spsds = [norm(n[0][segstart:segend]) for n in psds]
        for n in spsds: segedpsds1.append(n)
        if len(segedpsds1) > datano: break

    segedpsds, sylno_bic = EMofgmmcluster(segedpsds1)

    print(filename1 + '\t' + str(sylno_bic))
예제 #20
0
파일: PreProcessI.py 프로젝트: qAp/LisaMapp
    def psd(self,xstr,nfft=256,noverlap=0,coarsable=False):
        """Return the PSD(power spectral density) of the time-series

        Positional parameter:
        xstr -- string naming the observable, either 'A'or 'E'

        Keyword parameters:
        nfft -- length of the fast fourier transform (fft) (default 256)
        noverlap -- number of data points overlapping between segments (default 0)
        coarsable -- return the PSD as a Coarsable object (default False)
        
        OUTPUT:
        f -- frequencies 
        P -- PSD 

        Note:
        The PSD is calculated using pl.psd() with an additional factor of dt in the normalisation.
        This gives the correct dimension.

        """
        x = getattr(self,xstr)
        fs = 1. / x.Cadence1
        P , f = pl.psd( x.data , nfft , fs , noverlap=noverlap , scale_by_freq=False )
        P = P / fs
        if coarsable:
            scale = {'Offset1' : f[0] ,
                     'Cadence1': f[1] - f[0] }
            f = ASI.Coarsable( f , **scale )
            P = ASI.Coarsable( P , **scale )
        return f , P
예제 #21
0
    def psd(self, xstr, nfft=256, noverlap=0, coarsable=False):
        """Return the PSD(power spectral density) of the time-series

        Positional parameter:
        xstr -- string naming the observable, either 'A'or 'E'

        Keyword parameters:
        nfft -- length of the fast fourier transform (fft) (default 256)
        noverlap -- number of data points overlapping between segments (default 0)
        coarsable -- return the PSD as a Coarsable object (default False)
        
        OUTPUT:
        f -- frequencies 
        P -- PSD 

        Note:
        The PSD is calculated using pl.psd() with an additional factor of dt in the normalisation.
        This gives the correct dimension.

        """
        x = getattr(self, xstr)
        fs = 1. / x.Cadence1
        P, f = pl.psd(x.data, nfft, fs, noverlap=noverlap, scale_by_freq=False)
        P = P / fs
        if coarsable:
            scale = {'Offset1': f[0], 'Cadence1': f[1] - f[0]}
            f = ASI.Coarsable(f, **scale)
            P = ASI.Coarsable(P, **scale)
        return f, P
예제 #22
0
def main():

    f = open('TRAJEC.xyz','r')
    t = []
    dr = []
    lines = f.readlines()
    f.close()

    dr = []
    out = open('f_bond.dat','w')

    for i in range(len(lines)/4):
        natom = int(lines.pop(0))
        out.write(str(int(lines.pop(0)))+'    ')
        typat1,x1,y1,z1 = lines.pop(0).split()
        typat2,x2,y2,z2 = lines.pop(0).split()

        r = ( (float(x1)-float(x2))**2 + (float(y1)-float(y2))**2 + (float(z1)-float(z2))**2 )**0.5
        out.write(str(abs(r))+'\n')
        dr.append(abs(r))

        for i in range(natom-2): lines.pop(0)

    out.close()

    pxx, f = pylab.psd(dr,NFFT=32768)
    pylab.savefig('psd.png')

    out2 = open('psd.dat','w')
    for i in range(len(pxx)):
        out2.write(str(pxx[i])+'    '+str(f[i])+'\n')

    out2.close()
예제 #23
0
파일: eta.py 프로젝트: xaratustrah/iq_apps
def do_it(filename):
    dic1, _ = read_tiq(filename, 1, 1024, 1)
    center1 = dic1['center']
    fs1 = dic1['fs']
    nframes_tot = dic1['nframes_tot']

    naf = nacnt = np.array([])

    for i in range(1, nframes_tot, 100):
        dic1, _ = read_tiq(filename, 1, 1024, i)
        x1 = dic1['data']
        Pxx1, freqs1 = psd(x1, NFFT=1024, Fs=fs1, noverlap=512)
        naf = np.append(naf, freqs1[Pxx1.argmax()])
        nacnt = np.append(nacnt, i)

    naf = naf + center1
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(nacnt, naf, 'r.')
    ax.annotate('ISO at: {} [MHz]'.format(naf.max() / 1.0e6), xy=(nacnt[naf.argmax()], naf.max()), xycoords='data',
                xytext=(0.5, 0.5), textcoords='figure fraction',
                arrowprops=dict(width=1, headwidth=5, edgecolor='blue', facecolor='blue', shrink=0.05))
    plt.ylabel('Frequency [Hz]')
    plt.xlabel('Frame Number')
    plt.title('File: ' + filename.split('/')[3])
    plt.grid(True)
    fig.savefig(os.path.splitext(filename)[0] + '.pdf')
    plt.show()
예제 #24
0
    def importData(self, filename):
        self.filename = filename
        ifile = open(filename, "r")
        reader = csv.reader(ifile)
        for row in reader:
            if len(row) > 1:
                if row[1].lstrip() == "XXX":
                    break
                
        #self.data_array = fromiter((int(row[1].lstrip(), 16) for row in reader), int)
        self.raw_data = [[int(num.lstrip(),16) for num in row if num != ' '] for row in reader]

        self.adc_int_values = [row[1] for row in self.raw_data]
        
        self.adc_raw_values = [row[2:] for row in self.raw_data]
        self.adc_raw_values = reshape(array(self.adc_raw_values), array(self.adc_raw_values).size, order='F').reshape(12,-1)
        
        for i in arange(12):
            for j in arange(len(self.adc_raw_values[0])):
                self.adc_raw_values[i][j] = self.adc_raw_values[i][j] + 2*i


        for i in range(len(self.adc_int_values)):
            if self.adc_int_values[i] >= 2048:
                self.adc_int_values[i] = self.adc_int_values[i] - 4096

        self.data_psd = psd(self.adc_int_values, 2048, 50000000, label=self.filename)
예제 #25
0
    def plot_x_and_psd_with_estimated_omega(self, x, sample_step=1, dt=1.0):
        y = x[::sample_step]
        F = self.freq(x, sample_step, dt)

        pylab.clf()

        # plot PSD
        pylab.subplot(211)
        pylab.psd(y, Fs=1.0 / sample_step / dt)
        ylim = pylab.ylim()
        pylab.vlines(F, *ylim)
        pylab.ylim(ylim)

        # plot time series
        pylab.subplot(223)
        pylab.plot(x)
예제 #26
0
파일: eta.py 프로젝트: xaratustrah/iq_apps
def do_it(filename):
    dic1, _ = read_tiq(filename, 1, 1024, 1)
    center1 = dic1['center']
    fs1 = dic1['fs']
    nframes_tot = dic1['nframes_tot']

    naf = nacnt = np.array([])

    for i in range(1, nframes_tot, 100):
        dic1, _ = read_tiq(filename, 1, 1024, i)
        x1 = dic1['data']
        Pxx1, freqs1 = psd(x1, NFFT=1024, Fs=fs1, noverlap=512)
        naf = np.append(naf, freqs1[Pxx1.argmax()])
        nacnt = np.append(nacnt, i)

    naf = naf + center1
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(nacnt, naf, 'r.')
    ax.annotate('ISO at: {} [MHz]'.format(naf.max() / 1.0e6),
                xy=(nacnt[naf.argmax()], naf.max()),
                xycoords='data',
                xytext=(0.5, 0.5),
                textcoords='figure fraction',
                arrowprops=dict(width=1,
                                headwidth=5,
                                edgecolor='blue',
                                facecolor='blue',
                                shrink=0.05))
    plt.ylabel('Frequency [Hz]')
    plt.xlabel('Frame Number')
    plt.title('File: ' + filename.split('/')[3])
    plt.grid(True)
    fig.savefig(os.path.splitext(filename)[0] + '.pdf')
    plt.show()
예제 #27
0
def main():
    sdr = RtlSdr()
    print('Configuring SDR...')
    sdr.DEFAULT_ASYNC_BUF_NUMBER = 16
    sdr.rs = 2.5e6   ## sampling rate
    sdr.fc = 100e6   ## center frequency
    sdr.gain = 10

    print('  sample rate: %0.6f MHz' % (sdr.rs/1e6))
    print('  center frequency %0.6f MHz' % (sdr.fc/1e6))
    print('  gain: %d dB' % sdr.gain)

    print('Reading samples...')
    samples = sdr.read_samples(256*1024)
    print('  signal mean:', sum(samples)/len(samples))

    filter = signal.firwin(5, 2* array([99.5,100.5])/sdr.rs,pass_zero=False)



    mpl.figure()
    for i in range(100):
        print('Testing spectrum plotting...')
        mpl.clf()
        signal2 = convolve(sdr.read_samples(256*1024),filter)
        psd = mpl.psd(signal2, NFFT=1024, Fc=sdr.fc/1e6, Fs=sdr.rs/1e6)

        mpl.pause(0.001)
        #mpl.plot(sdr.read_samples(256*1024))
        mpl.show(block=False)

    print('Done\n')
    sdr.close()
예제 #28
0
def WelchPeriodogram(data, NFFT=None,  sampling=1., **kargs):
    r"""Simple periodogram wrapper of numpy.psd function.

    :param A: the input data
    :param int NFFT: total length of the final data sets (padded 
        with zero if needed; default is 4096)
    :param str window:

    :Technical documentation:

    When we calculate the periodogram of a set of data we get an estimation
    of the spectral density. In fact as we use a Fourier transform and a
    truncated segments the spectrum is the convolution of the data with a
    rectangular window which Fourier transform is

    .. math::

        W(s)= \frac{1}{N^2} \left[ \frac{\sin(\pi s)}{\sin(\pi s/N)} \right]^2

    Thus oscillations and sidelobes appears around the main frequency. One aim of t he tapering is to reduced this effects. We multiply data by a window whose  sidelobes are much smaller than the main lobe. Classical window is hanning window.  But other windows are available. However we must take into account this energy and divide the spectrum by energy of taper used. Thus periodogram becomes :

    .. math::

        D_k \equiv \sum_{j=0}^{N-1}c_jw_j \; e^{2\pi ijk/N}  \qquad k=0,...,N-1

    .. math::

        P(0)=P(f_0)=\frac{1}{2\pi W_{ss}}\arrowvert{D_0}\arrowvert^2

    .. math::

        P(f_k)=\frac{1}{2\pi W_{ss}} \left[\arrowvert{D_k}\arrowvert^2+\arrowvert{D_{N-k}}\arrowvert^2\right]        \qquad k=0,1,...,     \left( \frac{1}{2}-1 \right)

    .. math::

        P(f_c)=P(f_{N/2})= \frac{1}{2\pi W_{ss}} \arrowvert{D_{N/2}}\arrowvert^2

    with

    .. math::

        {W_{ss}} \equiv N\sum_{j=0}^{N-1}w_j^2


    .. plot::
        :width: 80%
        :include-source:

        from spectrum import WelchPeriodogram, marple_data
        psd = WelchPeriodogram(marple_data, 256)

    """
    from pylab import psd
    spectrum = Spectrum(data, sampling=1.)

    P = psd(data, NFFT, Fs=sampling, **kargs)
    spectrum.psd = P[0]
    #spectrum.__Spectrum_sides = 'twosided'

    return P, spectrum
def test_NFFT(s):
    from numpy import arange,power
    from pylab import psd,show
    import matplotlib.pyplot as plt 
    import seaborn as sns
    sns.__version__

    NFFTs = power(2,arange(6,10))

    for NFFT in NFFTs[::-1]:
        psd(s,NFFT,scale_by_freq=True,Fs=10000)

    plt.xlim(200,5000)
    plt.ylim(-45,-35)
    plt.semilogx()
    show()
예제 #30
0
def plot_frame(n=-1):
    j=225 # z=10
    k=28 # x=1
    vis = netCDF4.Dataset('vis.nc')
    #values
    
    U = vis.variables['U'][n,0,:,:] 
    UHTS = vis.variables['U'][:,0,j,:]
    UVTS = vis.variables['U'][:,0,:j,k]
    #grid stuff
    x = vis.variables['x'][:]
    yf = vis.variables['yf'][:]
    t = vis.variables['t'][:]
    vis.close

    interpolation = 'nearest'
    aspect = 'auto'

    dt = np.mean(np.diff(t))
    plt.subplot(311)
    #plt.plot(k,y,'k-',linewidth=2)
    #plt.plot(x,j,'k-',linewidth=2)
    plt.axhline(y=yf[j])
    plt.axvline(x=x[k])
    #plot horizontal velocity
    plt.ylim(ymin=-7,ymax = 0)
    plt.imshow(U, origin='lower', aspect=aspect,
    interpolation=interpolation,
    vmin = -UMAX, vmax = UMAX, 
    extent=[x[0], x[-1], yf[0], yf[-1]])

    plt.colorbar()
    plt.title('U, frame %d' % n)
    plt.xlabel('x')
    plt.ylabel('z')

    #compute power spectral density x
    plt.subplot(312)
    plt.ylim(ymin=-230,ymax=10)
    plt.xlim(xmin=0,xmax=10)
    plt.psd(UHTS[n,:], NFFT=len(UHTS[n,:]), Fs=(2*np.pi)/(dt))        

    #compute power spectral density z
    plt.subplot(313)
    plt.ylim(ymin=-80,ymax=0)
    #plt.xlim(xmin=0,xmax=10)
    plt.psd(UVTS[n,:], NFFT=len(UVTS[n,:]), Fs=(2*np.pi)/(dt))        
예제 #31
0
파일: viewIQData.py 프로젝트: rlagoy/comms
def main():

	print ' '

	# Space Frequency
	f1 = -0.1e6 #Hz
	# Mark Freq
	f2 = 0.1e6 #Hz
	# Sample Rate
	sampleRate = 3e6#Hz
	# Baud Rate
	baud=2.0 #sps
	# Number of Samples
	numSamples = 3000000

	packet=[1,0]

	samples=[]
	timeVector=[]
	bitNum=0
	timePassed=0

	for i in range(numSamples):

		timePassed=timePassed+1/sampleRate

		if (timePassed>(1/baud)):
			timePassed=0
			print(packet[bitNum])
			bitNum=bitNum+1
			if (bitNum==len(packet)):
				bitNum=0

		if(packet[bitNum]==0):
			samples.append(numpy.power(numpy.e,1j*2*numpy.pi*f1*i/sampleRate))
		
		if(packet[bitNum]==1):
			samples.append(numpy.power(numpy.e,1j*2*numpy.pi*f2*i/sampleRate))


	pylab.figure()
	pylab.psd(samples, NFFT=1024, Fc=0, Fs=sampleRate/(1e6))
	pylab.show()

	sampleArray=numpy.array(samples)

	sampleArray.tofile('txData.bin')
def collectSignal(freq, freq_file_path, mag_file_path):
    # Define function for writing signal data into file
    def write_data(data_points, magnitudeData, frequencyData, mag_file,
                   freq_file):
        i = 0
        mag_file.write('[')
        freq_file.write('[')
        while i < data_points - 1:
            mag_file.write("%s, " % magnitudeData[i])
            freq_file.write("%s, " % frequencyData[i])
            i += 1
        mag_file.write('%s]\n' % magnitudeData[i])
        freq_file.write('%s]\n' % frequencyData[i])

    sdr = RtlSdr()

    # Configure SDR
    sdr.sample_rate = 2.4e6  # Hz
    sdr.center_freq = freq  # Hz
    sdr.freq_correction = 60  # PPM
    sdr.gain = 4  # 'auto'

    # Initialize
    data_points = 1024
    samples = sdr.read_samples(256 * data_points)
    mag_file_path = mag_file_path + "magdata.txt"
    freq_file_path = freq_file_path + "freqdata.txt"

    ### *** IMPORTANT *** (for later, when optimizing)
    ### I'm not sure if we should leave this outside of the function
    ### and move it to the end of the main code, after the flight path
    ### ends. Idk the impact of leaving the SDR open/on for an extended
    ### period of time. If we move sdr.close() outside, we have to
    ### remember to also move the above code outside as well.
    ### Leaving this line within this function should be fine for now.
    sdr.close()

    # PSD plot data
    psddata = psd(samples,
                  NFFT=data_points,
                  Fs=sdr.sample_rate / 1e6,
                  Fc=sdr.center_freq / 1e6)

    # Extracting pertinent information from the PSD plot calculation
    magnitudeData = psddata[0]
    frequencyData = psddata[1]

    # Check for .txt file and write data
    # Magnitude has not been converted to dB yet. To convert, 10*log(magnitude). This comment is for Ron.
    if Path(mag_file_path).is_file() and Path(freq_file_path).is_file():
        with open(mag_file_path, 'a') as mag_file, open(freq_file_path,
                                                        'a') as freq_file:
            write_data(data_points, magnitudeData, frequencyData, mag_file,
                       freq_file)
    else:
        with open(mag_file_path, 'w') as mag_file, open(freq_file_path,
                                                        'w') as freq_file:
            write_data(data_points, magnitudeData, frequencyData, mag_file,
                       freq_file)
예제 #33
0
def get_psd(wav, fs, nfft=PSD_NFFT, plot=False):
	"""
	Given a wav, returns a tuple of the power spectral density using Welch's method and associated frequencies.
	"""

	(pxx, fxx) = pylab.psd(wav, nfft, fs)

	if plot:
		pylab.show()

	return (pxx, fxx)
예제 #34
0
 def display_power_density(self,widget):
     print 'trying'
     from pylab import psd,show,figure,ion,title
     nfft = int(self.builder.get_object('entry1').get_text())
     srate = float(self.builder.get_object('entry2').get_text())
     chind = self.chlabels.index(self.chan_sel);print 'chind',chind
     data = self.data[:,chind]
     figure()
     pow,freq=psd(data, NFFT=nfft, Fs=srate);ion();
     title('Spectral Power of Channel: '+self.chan_sel)
     show()
예제 #35
0
파일: utilities.py 프로젝트: mjibson/junk
def get_psd(wav, fs, nfft=PSD_NFFT, plot=False):
    """
	Given a wav, returns a tuple of the power spectral density using Welch's method and associated frequencies.
	"""

    (pxx, fxx) = pylab.psd(wav, nfft, fs)

    if plot:
        pylab.show()

    return (pxx, fxx)
예제 #36
0
파일: detrend.py 프로젝트: wilseypa/eis
def testDataRead():
    channels = [0,1,2,3,4,5,6,7]

    import pylab
    for i in range(50):
        print i
        data = readFile(datfile,start=1*i,stop=1*(i+1))
        for c in channels:
            pylab.subplot(4,2,c+1)
            px,freq = pylab.psd(data[c])
    pylab.show()
예제 #37
0
def shifted_horizontal_psd(n=-1):
    j1 = 225
    j2 = 175
    j3 = 125
    
    vis = netCDF4.Dataset('vis.nc')

    U1 = vis.variables['U'][:,0,j1,:]
    U2 = vis.variables['U'][:,0,j2,:]
    U3 = vis.variables['U'][:,0,j3,:]
    x = vis.variables['x'][:]
    yf = vis.variables['yf'][:]
    t = vis.variables['t'][:]
    vis.close

    dt = np.mean(np.diff(t))
    plt.subplot(311)
    plt.ylim(ymin=-230,ymax=10)
    plt.xlim(xmin=0,xmax=10)    
    plt.psd(U1[n,:], NFFT = len(U1[n,:]), Fs=(2*np.pi)/(dt))
    
    plt.subplot(312)
    plt.ylim(ymin=-230,ymax=10)
    plt.xlim(xmin=0,xmax=10)    
    plt.psd(U2[n,:], NFFT = len(U2[n,:]), Fs=(2*np.pi)/(dt))
    
    plt.subplot(313)
    plt.ylim(ymin=-230,ymax=10)
    plt.xlim(xmin=0,xmax=10)    
    plt.psd(U3[n,:], NFFT = len(U3[n,:]), Fs=(2*np.pi)/(dt))
예제 #38
0
def test_callback(samples, rtlsdr_obj):
    #print(samples)
    mpl.clf()
    #dataset.extend(samples)
    x = samples
    yb1 = signal.convolve(x, filterB1)
    #mpl.psd(yb1, NFFT=1024, Fc=0, Fs=48e3)
    yn1 = downsample(yb1, 10)
    #mpl.psd(yn1, NFFT=1024, Fc=0, Fs=sdr.rs/10)
    zdis = discrim(yn1)
    #mpl.psd(zdis, NFFT=1024, Fc=0, Fs=sdr.rs/10)

    zb2 = signal.convolve(zdis, filterB2)
    zn2 = downsample(zb2, 5)
    mpl.psd(x)
    mpl.psd(zn2, NFFT=1024, Fc=0, Fs=48e3)
    mpl.plot(zdis)
    mpl.pause(0.0001)
    mpl.show(block=False)
    zn2 /= npmax(abs(zn2),axis=0)
    # complex2wav("teste.wav",48e3,zn2)
    play(zn2, fs=48e3)
예제 #39
0
파일: detrend.py 프로젝트: wilseypa/eis
def testReadAndDetrendAndBP(detrend_length=10,s_freq=100000):
    import copy,pylab
    channels = [0,1,2,3,4,5,6,7]
    data = readFile(datfile,start=0,stop=1,sfreq = s_freq)
    #detrendData = copy.deepcopy(data)
    
    bipolar = generateBipolar(data)
    pylab.plot(bipolar)
    detrend(data,detrend_Kernel_Length = detrend_length,sampling_Frequency = s_freq)
    
    bipolar = generateBipolar(data)
    pylab.psd(bipolar[0])
    pylab.psd(bipolar[1])
    pylab.psd(bipolar[2])
    pylab.psd(bipolar[3])
    pylab.show()
예제 #40
0
파일: rtldev.py 프로젝트: overcyber/RTLion
 def get_fft_data(self, scan=False):
     try:
         [Y, F] = plt.psd(self.read_samples(), NFFT=1024, Fs=int(self.sample_rate)/1e6, \
                 Fc=int(self.center_freq)/1e6, color='k')    
         if scan: max_freqs = self.find_peaks(plt, Y, F, n=self.sensivity)
         plt.xlabel('Frequency (MHz)')
         plt.ylabel('Relative power (dB)')
         plt.savefig(self.static_dir + '/img/fft.png', bbox_inches='tight', pad_inches = 0)
         plt.clf()
         encoded = base64.b64encode(open(self.static_dir + '/img/fft.png', "rb"). \
                 read()).decode("utf-8")
         return encoded if not scan else [encoded, max_freqs]
     except Exception as e:
         self.logcl.log("Failed to get graph data.\n" + str(e), 'error')
예제 #41
0
파일: test.py 프로젝트: Wolfrax/pyrtlsdr
def test(sdr=None):
    if sdr is None:
        if is_travisci():
            sdr_cls = DummyRtlSdr
        else:
            sdr_cls = RtlSdr
    sdr = build_test_sdr(sdr_cls)

    print('Configuring SDR...')
    sdr.rs = 2.4e6
    sdr.fc = 100e6
    sdr.gain = 10
    print('  sample rate: %0.6f MHz' % (sdr.rs/1e6))
    print('  center frequency %0.6f MHz' % (sdr.fc/1e6))
    print('  gain: %d dB' % sdr.gain)

    print('Reading samples...')
    samples = sdr.read_samples(256*1024)
    print('  signal mean:', sum(samples)/len(samples))

    print('Testing callback...')
    async_read_test(sdr, 256*1024)

    try:
        import pylab as mpl

        print('Testing spectrum plotting...')
        mpl.figure()
        mpl.psd(samples, NFFT=1024, Fc=sdr.fc/1e6, Fs=sdr.rs/1e6)

        mpl.show()
    except:
        # matplotlib not installed/working
        pass

    print('Done\n')
    sdr.close()
예제 #42
0
def test(sdr=None):
    if sdr is None:
        if is_travisci():
            sdr_cls = DummyRtlSdr
        else:
            sdr_cls = RtlSdr
    sdr = build_test_sdr(sdr_cls)

    print('Configuring SDR...')
    sdr.rs = 2.4e6
    sdr.fc = 100e6
    sdr.gain = 10
    print('  sample rate: %0.6f MHz' % (sdr.rs / 1e6))
    print('  center frequency %0.6f MHz' % (sdr.fc / 1e6))
    print('  gain: %d dB' % sdr.gain)

    print('Reading samples...')
    samples = sdr.read_samples(256 * 1024)
    print('  signal mean:', sum(samples) / len(samples))

    print('Testing callback...')
    async_read_test(sdr, 256 * 1024)

    try:
        import pylab as mpl

        print('Testing spectrum plotting...')
        mpl.figure()
        mpl.psd(samples, NFFT=1024, Fc=sdr.fc / 1e6, Fs=sdr.rs / 1e6)

        mpl.show()
    except:
        # matplotlib not installed/working
        pass

    print('Done\n')
    sdr.close()
예제 #43
0
def transform_target_data_old(audiofile,analyze=0):
    """ Calculates the target data (in MIDI pitch classes) out of the REF.txt files.
    (for the old datasets of Ellis and MIREX)
    """
    target_file = DATA_PATH + audiofile[:-4] + "REF.txt"
    data = read_array(target_file)
    
    # remove time axes and convert to midi
    data = data[:,1]
    midi_data = audiotools.freq_to_midi(data)
    midi_data = np.round(midi_data)
    
    if analyze:
        pylab.plot(midi_data)
    
    # get the unique element (nr. of different notes) of the piece
    unique = list(set(midi_data))
    target = np.zeros((len(midi_data), len(unique)))
    for n in range( len(midi_data) ):
        ind = unique.index( midi_data[n] )
        target[n,ind] = 1
    
    if analyze:
        print "classes:",len(unique)
        pylab.figure()
        pylab.psd(target.flatten())
        pylab.show()
        exit(0)
    
    savefile = OUTPUT_DIR + audiofile[:-4] + "_STFT.dat"
    data = shelve.open(savefile)
    lenge = data["features"].shape[0]
    data["targets"] = target[:lenge]
    data["target_midi"] = midi_data[:lenge]
    data["pitch_classes"] = unique
    data.close()
예제 #44
0
파일: FFT_Test.py 프로젝트: rlagoy/comms
def main():

	print ' '

	# Space Frequency
	f1 = 2e4 #Hz
	# Sample Rate
	sampleRate = 2e6#Hz

	# Number of Samples
	numSamples = 256

	packet=[0]

	samples=[]
	timeVector=[]
	bitNum=0
	timePassed=0

	for i in range(numSamples):

		samples.append(numpy.power(numpy.e,1j*2*numpy.pi*f1*i/sampleRate))
		

	pylab.figure()
	pylab.psd(samples, NFFT=256, Fc=1, Fs=sampleRate/(1e6))
	pylab.show()


	pylab.figure()
	pylab.plot(samples)
	pylab.show()

	pylab.figure()
	pylab.plot(numpy.fft.fft(samples,8))
	pylab.show()
예제 #45
0
def plotpsd():
    colorspsd = array([[0.42, 0.67, 0.84], [0.42, 0.83, 0.59],
                       [0.90, 0.76, 0.00], [0.90, 0.32, 0.00],
                       [0.34, 0.67, 0.67], [0.42, 0.82, 0.83],
                       [0.90, 0.59, 0.00], [0.33, 0.67, 0.47],
                       [1.00, 0.85, 0.00], [0.71, 0.82, 0.41],
                       [0.57, 0.67, 0.33], [1.00, 0.38, 0.60], [0.5, 0.2, 0.0],
                       [0.0, 0.2, 0.5]])

    lfpv = [[] for c in range(len(s.lfppops))]
    # Get last modified .mat file if no input and plot
    for c in range(len(s.lfppops)):
        lfpv[c] = s.lfps[:, c]
    lfptot = sum(lfpv)

    # plot pops separately
    plotPops = 0
    if plotPops:
        figure()  # Open a new figure
        for p in range(len(s.lfppops)):
            psd(lfpv[p], Fs=200, linewidth=2, color=colorspsd[p])
            xlabel('Frequency (Hz)')
            ylabel('Power')
            h = axes()
            h.set_yticklabels([])
        legend(['L2/3', 'L5A', 'L5B', 'L6'])

    # plot overall psd
    figure()  # Open a new figure
    psd(lfptot, Fs=200, linewidth=2)
    xlabel('Frequency (Hz)')
    ylabel('Power')
    h = axes()
    h.set_yticklabels([])

    show()
예제 #46
0
    def plot_fft(self, reals, imags, timea, sample_rate, fc, NFFT, myfile):
        M = len(reals) / NFFT

        for i in range(0, int(M)):
            iq_samples = np.array([
                (re + 1j * co) for re, co in zip(reals, imags)
            ])[i * NFFT:(i + 1) * NFFT]
            x = pylab.psd(iq_samples,
                          NFFT=NFFT,
                          Fs=sample_rate / 1e6,
                          Fc=fc,
                          window=mlab.window_hanning)
            totalpower = self.totalpower(x[0])
            #print i, totalpower
            myfile.write("%s\n" % totalpower)
            myfile.flush()
            pylab.close()
예제 #47
0
def EMofgmmcluster(array_of_syls):
    """takes an array of segmented sylables, fits a series of
    gaussian mixture models with an increasing number of mixtures, 
    and identifies the best number of mixtures to describe the data
    by BIC. If data is limiting, we don't recommend using cross validation 
    for BIC.  If you have sufficient data 3 fold cross validated BIC values
    compare well with un-cross validated values and human assesment of syllable
    number.  If data are limiting, cross validated values underestimate
    the number of syllables relative to human assessment or non-cross
    validated BIC values.
    """
    nfft = 2 ** 14
    fs = 32000
    segstart = int(600 / (fs / nfft))
    segend = int(16000 / (fs / nfft))

    welchpsds = [psd(x, NFFT=nfft, Fs=fs) for x in array_of_syls]
    segedpsds1 = [norm(x[0][segstart:segend]) for x in welchpsds]

    models = range(2, 22)

    # select the first 50 syllables of the reference song as the basis set
    basis_set = segedpsds1[:50]
    # select a random set of 50 syllablse as the basis set
    # basis_set=[segedpsds1[rnd.randint(0,len(segedpsds1))] for x in range(50)]
    d = sc.spatial.distance.cdist(segedpsds1, basis_set, 'sqeuclidean')
    s = 1 - d / np.max(d) * 1000
    bic = []
    # xv=3
    for x in models:
        bics = []
        # this commented section implements cross validation for the BIC values
        '''ss=chunks(s,len(s)/xv)
        for y in range(len(ss)):
        testset=ss[y]
        trainset=[]
        [trainset.extend(ss[n]) for n in [z for z in range(len(ss)) if z!=y]]
        gmm = mixture.GMM(n_components=x, n_iter=100000,n_init=5, covariance_type='full')
        gmm.fit(np.array(s))
        bics.append(gmm.bic(np.array(s)))
        bic.append(np.mean(bics))'''
        gmm = GMM(n_components=x, max_iter=100000, n_init=5, covariance_type='full')
        gmm.fit(np.array(s))
        bic.append(gmm.bic(np.array(s)))
    return segedpsds1, bic.index(min(bic)) + 2
예제 #48
0
    def display_power_density(self,widget):
        #self.create_draw_frame(widget)
        #return
        print 'trying'
        from pylab import psd,show,figure,ion,title
        nfft = int(self.builder.get_object('entry1').get_text())
        srate = float(self.builder.get_object('entry2').get_text())
        chind = self.chlabels.index(self.chan_sel);print 'chind',chind
        data = self.data[:,chind]
        print 'NFFT',nfft,'SRATE',srate



        #figure()
        f = figure(figsize=(20,10), dpi=45)
        #title('Spectral Power of Channel: '+self.chan_sel)
        a = f.add_subplot(111)
        pow,freq=psd(data, NFFT=nfft, Fs=srate)
        f.show()
예제 #49
0
파일: analysis.py 프로젝트: jettify/OpenINS
def psd(data, dt=0.005, NFFT=512, plot=1):
    """
    Compute power spectrum destinity for input time array.

    This function just wraper for pylab.psd implementation

    Paramters:
    ----------
    data: array
        input time series
    dt: float
        Sample time (1/fs). It is used to calculate the Fourier frequencies,
        freqs, in cycles per time unit. The default value is 0.005
    NFFT: The number of data points used in each block for the FFT.
        Must be even; a power 2 is most efficient. The default value is 256.

    Returns:
    -------
    Pxx: array
        power spectral destinity
    freqs: array
        coresponding frequencies

    References:
    ----------
    [1] http://matplotlib.sourceforge.net/api/pyplot_api.htmld
    [2] IEEE Std 647-1995, IEEE Standard Specification Format Guide and Test
        Procedure for Single-Axis. Laser Gyros
    """

    (Pxx, freqs) = pylab.psd(data, NFFT, dt)

    ## Total number of samples
    N = np.shape(data)[0]
    time = np.arange(0,(N))

    pylab.subplot(211)
    pylab.plot(time,data)
    pylab.subplot(212)

    if plot == 1:
        pylab.show()
    return Pxx, freqs
예제 #50
0
파일: detrend.py 프로젝트: wilseypa/eis
def testDataVariance():

    class varState:
       n = 0.0                
       mean = 0.0
       M2 = 0.0
       var = 0.0
    def online_variance(x,S):
       S.n = S.n + 1.0
       delta = x - S.mean
       S.mean = S.mean + delta/S.n
       if S.n > 1:
           S.M2 = S.M2 + delta*(x - S.mean)
       S.var = S.M2/(S.n)
       return S


    channels = [0,1,2,3,4,5,6,7]
    varChannels = [[varState() for j in range(129)] for i in channels]



    import pylab
    pylab.figure()
    for i in range(50):
        print i
        data = readFile(datfile,start=1*i,stop=1*(i+1))
        for c in channels:
            pylab.subplot(4,2,c+1)
            px,freq = pylab.psd(data[c])
            varChannels[c] = [online_variance(px[i],varChannels[c][i] ) for i in range(129)]
            #fftX = pylab.fft(data[c])
            #filter(lambda x: (x>100 and x<10000),fftX)
            #print min(fftX),max(fftX)
            #pylab.semilogx(fftX)

    pylab.show()
    pylab.figure()
    for v in varChannels:
        print sum([v[c].var for i in range(129)])/129.0
        pylab.plot([v[c].var for i in range(129)])
    pylab.show()
예제 #51
0
 def plot_fft(self, reals, imags, time, sample_rate, fc, nfft, tfile):
     m = len(reals) / nfft
     dfs = []
     for i in range(0, int(m)):
         iqs = np.array([(re + 1j * co) for re, co in zip(reals, imags)
                         ])[i * nfft:(i + 1) * nfft]
         x = pylab.psd(iqs,
                       NFFT=nfft,
                       Fs=sample_rate / 1e6,
                       Fc=fc,
                       window=mlab.window_hanning)
         total_power = self.total_power(x[0])
         y = list(10 * np.log10(x[0]))
         dfs.append(y)
         self.total_i += 1
         #print(myfile, self.total_i, total_power)
         tfile.write("%s\t" % (self.total_i))
         tfile.write("%s\n" % total_power)
         tfile.flush()
         pylab.close()
예제 #52
0
def harmonic_spectrum(a, Fs = 32000):

    n_harmonics = 2

    spectrum, faxis = psd(a, Fs=Fs, NFFT=500)    
    f_idxs = np.arange(0,len(spectrum),1)
    f_idxs = f_idxs.astype(int)
    max_freq = np.floor(float(faxis[-1])/n_harmonics)
    max_idx = f_idxs[faxis>max_freq][0]-1
    f1_idxs = np.arange(0, max_idx, 1)
    f1_idxs = f1_idxs.astype(int)
    f1 = faxis[f1_idxs]

    f2_idxs = [ f_idxs[faxis >= 2*faxis[idx]][0]  for idx in f1_idxs]
    f2 = faxis[f2_idxs]
    fig = plt.figure()
    ax = fig.add_subplot(2,1,1)
    plt.plot(f1, spectrum[f1_idxs])
    plt.plot(f1, spectrum[f2_idxs])
    plt.show()
예제 #53
0
    def plot_fft(self, reals, imags, timea, sample_rate, fc, NFFT, myfile):
        M = len(reals) / NFFT

        # Open a file
        text_file = open(myfile + "_energyfft.txt", "w")

        for i in range(0, int(M)):
            iq_samples = np.array([
                (re + 1j * co) for re, co in zip(reals, imags)
            ])[i * NFFT:(i + 1) * NFFT]
            x = pylab.psd(iq_samples,
                          NFFT=NFFT,
                          Fs=sample_rate / 1e6,
                          Fc=fc,
                          window=mlab.window_hanning)
            totalpower = self.totalpower(x[0])
            print myfile, i, totalpower
            text_file.write("%s\n" % totalpower)
            text_file.flush()
            #pylab.show()
            pylab.close()

        text_file.close()
    y1r = n1r + hr ; y2r = n2r + hr

    """ Straight cross-correlation """
    Ometer = np.mean( y1 * y2 )
    Ometer_ana , var_Ometer_ana = Omega , ( var_n1 + Omega )*( var_n2 + Omega ) / N + Omega**2/N

    """ Cross-correlation with filtering """
    Y1 = stime * np.fft.fft( y1 ) ; Y2 = stime * np.fft.fft( y2 ) ; df_c12 = 1. / ( N*stime )
    if N % 2 == 0 :
        c12 = 2 * np.conj( Y1[ : N/2+1 ] ) * Y2[ : N/2+1 ] / (N*stime) ; f_c12 = df_c12 * np.arange( N/2+1 )
    else :
        c12 = 2 * np.conj( Y1[ : (N+1)/2 ] ) * Y2[ : (N+1)/2 ] / (N*stime) ; f_c12 = df_c12 * np.arange( (N+1)/2 )
    Qc12 = AS.Coarsable( c12 , Offset1=f_c12[0] , Cadence1=df_c12 )
    Qf_c12 = AS.Coarsable( f_c12 , Offset1=f_c12[0] , Cadence1=df_c12 )

    p11l , f_p11l = pl.psd( y1l , nfft , fs , noverlap=noverlap )
    p11r , f_p11r = pl.psd( y1r , nfft , fs , noverlap=noverlap )
    p11 = ( p11l + p11r ) / 2 ; f_p11 = np.copy( f_p11l ) ; df_p11 = f_p11[1] - f_p11[0]
    Qp11 = AS.Coarsable( p11 , Offset1=f_p11[0] , Cadence1=df_p11 )
    Qf_p11 = AS.Coarsable( f_p11 , Offset1=f_p11[0] , Cadence1=df_p11 )
    p22l , f_p22l = pl.psd( y2l , nfft , fs , noverlap=noverlap )
    p22r , f_p22r = pl.psd( y2r , nfft , fs , noverlap=noverlap )
    p22 = ( p22l + p22r ) / 2 ; f_p22 = np.copy( f_p22l ) ; df_p22 = f_p22[1] - f_p22[0]
    Qp22 = AS.Coarsable( p22 , Offset1=f_p22[0] , Cadence1=df_p22 )

    Qff = AS.coarsefrequency( Qf_c12 , Qf_p11 ) ; Nf = Qff.data.shape[0]

    Qcc12 = Qc12.coarsegrain( Offset1=Qff.Offset1 , Cadence1=Qff.Cadence1 , N1=Qff.data.shape[0] )
    Qpp11 = Qp11.coarsegrain( Offset1=Qff.Offset1 , Cadence1=Qff.Cadence1 , N1=Qff.data.shape[0] )
    Qpp22 = Qp22.coarsegrain( Offset1=Qff.Offset1 , Cadence1=Qff.Cadence1 , N1=Qff.data.shape[0] )
    
    n1 , n2 , n3 = tsdict['s1'].data , tsdict['s2'].data , tsdict['s3'].data

    stime = t[1] - t[0] ; inittime = t[0] ; N = t.shape[0]
    fs = 1. / stime

    power_max = 3
    Nsegs = 10**np.arange( power_max + 1 )
    P12s = [] ; P12s_legend = [] ; C12s = [] ; C12s_legend = []
    P13s = [] ; P13s_legend = [] ; C13s = [] ; C13s_legend = []
    P23s = [] ; P23s_legend = [] ; C23s = [] ; C23s_legend = []
    for i , Nseg in enumerate( Nsegs ) :
        print "Taking %d averages to esimate spectral densities ... " % ( 2*Nseg )
        nfft = int( np.round( N / Nseg ) )
        noverlap = nfft / 2

        P11 , f = pl.psd( n1 , nfft , fs , noverlap = noverlap )
        P22 , f = pl.psd( n2 , nfft , fs , noverlap = noverlap )
        P33 , f = pl.psd( n3 , nfft , fs , noverlap = noverlap )

        P12 , f = pl.csd( n1 , n2 , nfft , fs , noverlap = noverlap )
        P23 , f = pl.csd( n2 , n3 , nfft , fs , noverlap = noverlap )
        P13 , f = pl.csd( n1 , n3 , nfft , fs , noverlap = noverlap )

        C12 = np.abs( P12 )**2 / ( P11*P22 )
        C23 = np.abs( P23 )**2 / ( P22*P33 )
        C13 = np.abs( P13 )**2 / ( P11*P33 )
        for k in range( C12.shape[0] ) :
            if C12[k] < 0 :
                print 'C12[%d] < 0' % k
        P12s += [ f , np.abs( P12 ) ] ; C12s += [ f , C12 ] ; C12s_legend += [ '%d' % Nseg ]
        P23s += [ f , np.abs( P23 ) ] ; C23s += [ f , C23 ] ; C23s_legend += [ '%d' % Nseg ]
Count = 2000
Rate = 10000

Options = UL.CONVERTDATA
ADData = Numeric.zeros((Count,), Numeric.Int16)

ActualRate = UL.cbAInScan(BoardNum, LowChan, HighChan, Count,
                   	 Rate, Gain, ADData, Options)
time = Numeric.arange( ADData.shape[0] )*1.0/ActualRate

# convert to Volts
data_in_volts = [ UL.cbToEngUnits(BoardNum, Gain, y) for y in ADData]
data_in_volts = Numeric.array(data_in_volts) # convert to Numeric array

pxx, freqs = pylab.psd( data_in_volts, Fs=ActualRate )
decibels = 10*Numeric.log10(pxx)
pylab.subplot(2,1,1)
pylab.plot(time[100:200],data_in_volts[100:200],'o-') # plot a few samples
pylab.xlabel('time (sec)')
pylab.ylabel('Volts')
pylab.subplot(2,1,2)
pylab.plot(freqs, decibels, 'o-')
pylab.xlabel('frequency')
pylab.ylabel('Power (decibels)')
pylab.savefig('example4.png',dpi=72)
pylab.show()

# <markdowncell>

# For this example, I've turned up the frequency on the function generator