def plotLFP (): print('Plotting LFP power spectral density...') 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(sim.lfppops))] # Get last modified .mat file if no input and plot for c in range(len(sim.lfppops)): lfpv[c] = sim.lfps[:,c] lfptot = sum(lfpv) # plot pops separately plotPops = 0 if plotPops: figure() # Open a new figure for p in range(len(sim.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()
def plot_data_psds(data,rate): plt.figure() plt.psd(data[3],NFFT=256,Fs=rate) #plt.psd(data[1],NFFT=256,Fs=rate) #plt.psd(data[2],NFFT=256,Fs=rate) #plt.psd(data[3],NFFT=256,Fs=rate) #plt.psd(data[4],NFFT=256,Fs=rate) #plt.psd(data[5],NFFT=256,Fs=rate) plt.xlim(0,65) plt.title('Subject 1 - Channel 4 - Good Sleep') plt.show()
def convert_syl_to_psd(syls, max_num_psds): """convert syllable segments to power spectral density Parameters ---------- syls : list of ndarray, syllable segments extracted from .wav files max_num_psds : int maximum number of psds to calculate Returns ------- segedpsds """ segedpsds = [] for x in syls[:max_num_psds]: 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: segedpsds.append(n) return segedpsds
def __init__(self,patient_file,logger=lg.logger(0)): self.log = logger self.sr,self.Vt = wav.read(patient_file) self.log.info('patient loaded') self.nfft=2**int(math.log(len(self.Vt),2))+1 self.Pxx,self.freqs=pylab.psd(x=self.Vt,Fs=self.sr,NFFT=self.nfft,window=pylab.window_none, noverlap=1) self.log.info('patient initialized')
def plot_example_psds(example,rate): """ This function creates a figure with 4 lines to show the overall psd for the four sleep examples. (Recall row 0 is REM, rows 1-3 are NREM stages 1, 2 and 3/4) """ plt.figure() ##YOUR CODE HERE # 256 and 512 are both reasonable values for the FFT for examples in examples: plt.psd(example, NFFT=512, Fs=rate) plt.xlim(0, 30) plt.show() return None # No return type, all side-effects
def plot_example_psds(example,rate): """ This function creates a figure with 4 lines to show the overall psd for the four sleep examples. (Recall row 0 is REM, rows 1-3 are NREM stages 1, 2 and 3/4) """ plt.figure() for idx in range(len(example)): plt.subplot(2,2,idx+1) x = np.linspace(0, len(example[idx])/rate,len(example[idx]) ) plt.plot(x,example[idx]) plt.title('Phase'+str(idx)) plt.figure() for idx in range(len(example)): Pxx, freqs = plt.psd(example[idx], NFFT=512, Fs=rate) plt.xlim((0,70)) plt.legend(('REM','NREM stage 1','NREEM stage 2','NREEM stage 3/4'), loc='upper right',prop={'size':8}) plt.figure() for idx in range(len(example)): Pxx, freqs = m.psd(example[idx], NFFT=512, Fs=rate) index30=np.nonzero(freqs==30)[0][0] pxx = 10*np.log10(Pxx[0:index30+1]) normalized_pxx = pxx/sum(abs(pxx)) plt.plot(freqs[0:index30+1], normalized_pxx) plt.legend(('REM','NREM stage 1','NREEM stage 2','NREEM stage 3/4'), loc='upper right',prop={'size':8}) ##YOUR CODE HERE return
def recalcBartlet(self, current): curentPSD, freqs = pylab.psd(x=current, Fs=self.sr, NFFT=self.nfft, window=pylab.window_none, noverlap=1) self.bartlet = np.divide(np.divide(self.Pxx, np.sum(self.Pxx)), np.divide(curentPSD, np.sum(curentPSD)))
def classify_epoch(epoch,rate): """ This function returns a sleep stage classification (integers: 1 for NREM stage 1, 2 for NREM stage 2, and 3 for NREM stage 3/4) given an epoch of EEG and a sampling rate. """ ###YOUR CODE HERE # Find the frequency content in the ranges - [2-7]Hz, and 10-15Hz and use the range [5-10]Hz as reference # If the # 1. find the mag spectrum - psd print "---------" Pxx,freq = plt.psd(epoch/np.sum(epoch),NFFT=512,Fs=rate); Pxx = Pxx/np.sum(Pxx) psd_lf = np.max(10*np.log10(Pxx[2:7])) - np.min(10*np.log10(Pxx[2:7])); psd_ref = np.max(10*np.log10(Pxx[7:10])) - np.min(10*np.log10(Pxx[7:10])) psd_hf = np.max(10*np.log10(Pxx[12:14])) - np.min(10*np.log10(Pxx[12:14])) # Avg psd in low feq rang print "Avg 2-7Hz = " + str(psd_lf) print "Avg 7-10Hz = " + str(psd_ref) print "Avg 10-13Hz = " + str(psd_hf) alpha_pow_ratio = np.sum(Pxx[8:12]) /np.sum(Pxx[1:40]) lf_pow_ratio = np.sum(Pxx[2:5]) /np.sum(Pxx[1:40]) hf_pow_ratio = np.sum(Pxx[12:15]) /np.sum(Pxx[1:40]) ref_pow_ratio = np.sum(Pxx[18:25]) /np.sum(Pxx[1:40]) print "Low freq power = " + str(lf_pow_ratio * 100) print "High freq power = " + str(hf_pow_ratio * 100) print "Ref freq power = " + str(ref_pow_ratio * 100) print "Alpha freq power = " + str(alpha_pow_ratio * 100) # plt.figure(); # plt.hist(Pxx[1:40]) # ,cumulative=True,histtype='step' pkh_hf1 = find_peak(Pxx[7:15]) pkh_hf2 = find_peak(Pxx[0:5]) pkh_ref = find_peak(Pxx[4:10]) stage = 0 if pkh_hf1 != 0: if (hf_pow_ratio > ref_pow_ratio) and (lf_pow_ratio * 100 < 50.0) and (lf_pow_ratio * 100 > 25.0): print "NREM 2 detected" # There are 2 peaks one at 12 Hz and another at 15 Hz and the peak is reasonably high (2x the valley) stage = 2 # NREM stages 3 and 4, also known as SWS, is dominated by delta wave (0 - 4 Hz) activity. if (stage == 0) and (lf_pow_ratio * 100 > 40.0): stage = 3 print "NREM 3/4 detected" elif(stage == 0): print "NREM 1 detected" stage = 1 #if(stage != ans): # print "Wrong result, expected " + str(ans) + " Got " + str(stage) #return stage return stage
def fpp(self,rate,C): self.log.info('C = ' + str(C) + '; rate = ' + str(rate) ) Vt,t = FPP.FPP(log=lg.logger(0), N=10000, dt=1./24000, distributionParameter=[C,rate], plotAll=False,efield=False) Pxi,freqs = pylab.psd(x=Vt,Fs=self.sr,NFFT=self.nfft,window=pylab.window_none, noverlap=1) self.log.info('L2 = ' + str(np.sqrt((np.square(np.subtract(self.Pxx[370:3300],10000*Pxi[370:3300])).sum())))) #pylab.show() #pylab.loglog(10000*Pxi[37:3300]) #pylab.loglog(self.Pxx[37:3300]) #pylab.show() #pylab.plot(self.freqs) #pylab.show() return np.subtract(self.Pxx[37:3300],10000*Pxi[37:3300])
def __init__(self, patient_file, logger=lg.logger(0)): self.log = logger self.sr, self.Vt = wav.read(patient_file) self.log.info('patient loaded') self.nfft = 2**int(math.log(len(self.Vt), 2)) + 1 self.Pxx, self.freqs = pylab.psd(x=self.Vt, Fs=self.sr, NFFT=self.nfft, window=pylab.window_none, noverlap=1) self.bartlet = self.Pxx self.log.info('patient initialized')
def fpp(self, rate, C): self.log.info('C = ' + str(C) + '; rate = ' + str(rate)) Vt, t = FPP.FPP(log=lg.logger(0), N=10000, dt=1. / 24000, distributionParameter=[C, rate], plotAll=False, efield=False) Pxi, freqs = pylab.psd(x=Vt, Fs=self.sr, NFFT=self.nfft, window=pylab.window_none, noverlap=1) self.log.info('L2 = ' + str( np.sqrt((np.square( np.subtract(self.Pxx[370:3300], 10000 * Pxi[370:3300])).sum())))) #pylab.show() #pylab.loglog(10000*Pxi[37:3300]) #pylab.loglog(self.Pxx[37:3300]) #pylab.show() #pylab.plot(self.freqs) #pylab.show() return np.subtract(self.Pxx[37:3300], 10000 * Pxi[37:3300])
if __name__ == '__main__': # xxxxxxxxxx Input generation (not part of OFDM) xxxxxxxxxxxxxxxxxxxxxx num_bits = 2500 # generating 1's and 0's ip_bits = np.random.random_integers(0, 1, num_bits) # Number of modulated symbols num_mod_symbols = num_bits * 1 # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # xxxxxxxxxxxxxxx BPSK modulation xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # bit0 --> -1 # bit1 --> +1 ip_mod = 2 * ip_bits - 1 ofdm_obj = OFDM(64, 16, 52) ofdm_symbols = ofdm_obj.modulate(ip_mod) # Code to plot the power spectral density fsMHz = 20e6 Pxx, W = pylab.psd(ofdm_symbols, NFFT=ofdm_obj.fft_size, Fs=fsMHz) # [Pxx,W] = pwelch(st,[],[],4096,20); plt.plot( W, # 10 * np.log10(np.fft.fftshift(Pxx)) 10 * np.log10(Pxx) ) plt.xlabel('frequency, MHz') plt.ylabel('power spectral density') plt.title('Transmit spectrum OFDM (based on 802.11a)') plt.show()
def FPP(log=Logger.logger(0), N = 10000, dt = 1./24000, distributionParameter = [30], plotAll = True, efield = False): #check if rate file or rate is present if len(distributionParameter) == 1: try: data = np.loadtxt(distributionParameter[0],delimiter = ' ') log.info("Rate data loaded") BGsim = True STNdata = [] tick = [] for n in data: STNdata.append(n[1]) tick.append(n[0]) Ratetime = pylab.cumsum(tick) BGdt = tick[1] timeSteps = int(Ratetime[-1]/dt) except: float(distributionParameter[0]) Ratetime = 1. timeSteps = int(Ratetime/dt) BGsim = False else: Ratetime = 1. BGsim = False timeSteps = int(Ratetime/dt) maxrate = 1./0.009 times = [] for n in range(timeSteps): times.append(dt*n) # check for current file, if none present use impules try: It = np.loadtxt('C:\\Users\\Kristian\\Dropbox\\phd\\Data\\apcurrent24k.dat',delimiter = ',') #/home/uqkweegi/Documents/Data/apcurrent24k.dat',delimiter = ',') except: log.error('no current file present') It = np.array(1) log.info('Current loaded') It = np.multiply(np.true_divide(It,It.min()),250e-9) #normalize currentLength = len(It) #calculate extracellular effects epsilon = 8.85e-12 #Permitivity of free space rho = 10.**5 * 10.**6 #density of neurons in STN m^-3 r = np.power(np.multiply(3./4*N/(np.pi*rho),np.array([random.uniform(0,1) for _ in range(N)])),1./3) #create a power law distribution of neuron radii r.sort() if efield: rijk = [[random.uniform(0,1)-0.5 for _ in range(N)],[random.uniform(0,1)-0.5 for _ in range(N)],[random.uniform(0,1)-0.5 for _ in range(N)]] #create vector direction of field #if plotAll: # vi = pylab.plot(rijk[0]) # vj = pylab.plot(rijk[1]) # vk = pylab.plot(rijk[2]) # pylab.show() R3 = 0.96e3 C3 = 2.22e-6 C2 = 9.38e-9 C3 = 1.56e-6 C2 = 9.38e-9 R4 = 100.e6 R2N = np.multiply(1./(4*np.pi*epsilon),r) R1 = 2100.; t_impulse = np.array([dt*n for n in range(100)]) log.info('initialization complete') Vt = pylab.zeros(len(times)) Vi = Vt Vj = Vt Vk = Vt # start simulation #-------------------------------------------------------------------------------# for neuron in range(N): R2 = R2N[neuron] ppwave = pylab.zeros(len(times)) if BGsim: absoluteTimes = np.random.exponential(1./(maxrate*STNdata[0]),1) else: if len(distributionParameter) == 1: absoluteTimes = np.random.exponential(1./(distributionParameter[0]),1) else: absoluteTimes = [random.weibullvariate(distributionParameter[0],distributionParameter[1])] while absoluteTimes[-1] < times[-1]-currentLength*dt: wave_start = int(absoluteTimes[-1]/dt) wave_end = wave_start+currentLength if wave_end > len(times): break ppwave[wave_start:wave_end] = np.add(ppwave[wave_start:wave_end],It) if BGsim: isi = np.random.exponential(1./(maxrate*STNdata[int(absoluteTimes[-1]/BGdt)]),1) else: if len(distributionParameter) == 1: isi = np.random.exponential(1./(distributionParameter[0]),1) else: isi = random.weibullvariate(distributionParameter[0],distributionParameter[1]) absoluteTimes = np.append(absoluteTimes,[absoluteTimes[-1]+isi]) # calculate neuron contribution #------------------------------------------------------------------------------# extracellular_impulse_response = np.multiply(np.multiply(np.exp(np.multiply(t_impulse,-20*17*((C2*R1*R2 + C2*R1*R3 + C2*R1*R4 - C3*R1*R3 + C3*R2*R3 + C3*R3*R4))/(2*C2*C3*R1*R3*(R2 + R4)))),(np.add(np.cosh(np.multiply(t_impulse,(C2**2*R1**2*R2**2 + 2*C2**2*R1**2*R2*R3 + 2*C2**2*R1**2*R2*R4 + C2**2*R1**2*R3**2 + 2*C2**2*R1**2*R3*R4 + C2**2*R1**2*R4**2 + 2*C2*C3*R1**2*R2*R3 - 2*C2*C3*R1**2*R3**2 + 2*C2*C3*R1**2*R3*R4 - 2*C2*C3*R1*R2**2*R3 - 2*C2*C3*R1*R2*R3**2 - 4*C2*C3*R1*R2*R3*R4 - 2*C2*C3*R1*R3**2*R4 - 2*C2*C3*R1*R3*R4**2 + C3**2*R1**2*R3**2 - 2*C3**2*R1*R2*R3**2 - 2*C3**2*R1*R3**2*R4 + C3**2*R2**2*R3**2 + 2*C3**2*R2*R3**2*R4 + C3**2*R3**2*R4**2)**(1/2)/(2*C2*C3*R1*R3*(R2 + R4)))),np.divide(np.sinh(np.multiply(t_impulse,(C2**2*R1**2*R2**2 + 2*C2**2*R1**2*R2*R3 + 2*C2**2*R1**2*R2*R4 + C2**2*R1**2*R3**2 + 2*C2**2*R1**2*R3*R4 + C2**2*R1**2*R4**2 + 2*C2*C3*R1**2*R2*R3 - 2*C2*C3*R1**2*R3**2 + 2*C2*C3*R1**2*R3*R4 - 2*C2*C3*R1*R2**2*R3 - 2*C2*C3*R1*R2*R3**2 - 4*C2*C3*R1*R2*R3*R4 - 2*C2*C3*R1*R3**2*R4 - 2*C2*C3*R1*R3*R4**2 + C3**2*R1**2*R3**2 - 2*C3**2*R1*R2*R3**2 - 2*C3**2*R1*R3**2*R4 + C3**2*R2**2*R3**2 + 2*C3**2*R2*R3**2*R4 + C3**2*R3**2*R4**2)**(1/2)/(2*C2*C3*R1*R3*(R2 + R4))))*(C2*R1*R2 - C2*R1*R3 + C2*R1*R4 + C3*R1*R3 - C3*R2*R3 - C3*R3*R4),(C2**2*R1**2*R2**2 + 2*C2**2*R1**2*R2*R3 + 2*C2**2*R1**2*R2*R4 + C2**2*R1**2*R3**2 + 2*C2**2*R1**2*R3*R4 + C2**2*R1**2*R4**2 + 2*C2*C3*R1**2*R2*R3 - 2*C2*C3*R1**2*R3**2 + 2*C2*C3*R1**2*R3*R4 - 2*C2*C3*R1*R2**2*R3 - 2*C2*C3*R1*R2*R3**2 - 4*C2*C3*R1*R2*R3*R4 - 2*C2*C3*R1*R3**2*R4 - 2*C2*C3*R1*R3*R4**2 + C3**2*R1**2*R3**2 - 2*C3**2*R1*R2*R3**2 - 2*C3**2*R1*R3**2*R4 + C3**2*R2**2*R3**2 + 2*C3**2*R2*R3**2*R4 + C3**2*R3**2*R4**2)**(1/2))))),-R4/(C2*(R2 + R4))); electrode_ppwave = np.convolve(ppwave,extracellular_impulse_response,'same'); if efield: #add fields amp = 1/np.sqrt((np.square(rijk[0][neuron])+np.square(rijk[1][neuron])+np.square(rijk[2][neuron]))) rijk[0][neuron] = rijk[0][neuron]*amp rijk[1][neuron] = rijk[1][neuron]*amp rijk[2][neuron] = rijk[2][neuron]*amp Vi = np.add(Vi,np.multiply(electrode_ppwave,rijk[0][neuron])) Vj = np.add(Vj,np.multiply(electrode_ppwave,rijk[1][neuron])) Vk = np.add(Vk,np.multiply(electrode_ppwave,rijk[2][neuron])) else: #add scalar Vt = np.add(Vt,electrode_ppwave) if np.mod(neuron,1000) == 999: log.info(str(neuron+1)+" neurons calculated") #------------------------------------------------------------------------------# # end simulation log.info('neuron contribution to MER complete') #remove bias if efield: Vt = np.sqrt(np.add(np.square(Vi),np.square(Vj),np.square(Vk))) Vt = np.subtract(Vt,np.mean(Vt)) #apply hardware filters flow = 5500*2. fhigh = 500. b,a = signal.butter(18,flow*dt,'low') Vt = signal.lfilter(b, a, Vt) b,a = signal.butter(1,fhigh*dt,'high') Vt = signal.lfilter(b, a, Vt) #produce plots if plotAll: volts = pylab.plot(times,Vt) if BGsim: stnrate = pylab.plot(Ratetime,np.multiply(STNdata,200)) pylab.show() nfft=2**int(math.log(len(Vt),2))+1 sr = 1/dt Pxi,freqs=pylab.psd(x=Vt,Fs=sr,NFFT=nfft/10,window=pylab.window_none, noverlap=100) pylab.show() return freqs, Pxi psd = pylab.loglog(freqs, Pxi) pylab.show() return Vt, times
Fid=open('C:\Users\uqkweegi\Documents\Data\DAfit\patients.txt') patients=Fid.read() Fid.close() PRList=E1R.split('\n') PLList=E1L.split('\n') PatientList=patients.split('\\') #Determine how many patients PatientNumbers=[] for item in PatientList: if len(item) > 7: if item[0:7]=='Patient': PatientNumbers.append(item[7:-3]) sr,Vt=wav.read(PLList[0]) nfft=2**int(math.log(len(Vt),2))+1 Pxx,freqs=pylab.psd(x=Vt,Fs=sr,NFFT=nfft/10,window=pylab.window_none, noverlap=100) #find mean PSD and write to XML file # #Add in NFFT,Fs,Window,nooverlap to XML file fid=open('C:\Users\uqkweegi\Documents\Data\DAfit\patientspsd.xml','w') fid.write("<PATIENTDATA>\n") for PNitem in PatientNumbers: Pxx-=Pxx; fid.write("\t<PATIENT>\n") fid.write("\t\t<ID>"+str(PNitem)+"</ID>\n") fid.write("\t\t<SIDE>\n\t\t\t<ID>Left</ID>\n") count=1 for item in PLList: if item[56:56+len(PNitem)] == PNitem: sr,Vt=wav.read(item)
def recalcBartlet(self,current): curentPSD,freqs = pylab.psd(x=current,Fs=self.sr,NFFT=self.nfft,window=pylab.window_none, noverlap=1) self.bartlet = np.divide(np.divide(self.Pxx,np.sum(self.Pxx)),np.divide(curentPSD,np.sum(curentPSD)))
Fid.close() PRList = E1R.split('\n') PLList = E1L.split('\n') PatientList = patients.split('\\') #Determine how many patients PatientNumbers = [] for item in PatientList: if len(item) > 7: if item[0:7] == 'Patient': PatientNumbers.append(item[7:-3]) sr, Vt = wav.read(PLList[0]) nfft = 2**int(math.log(len(Vt), 2)) + 1 Pxx, freqs = pylab.psd(x=Vt, Fs=sr, NFFT=nfft / 10, window=pylab.window_none, noverlap=100) #find mean PSD and write to XML file # #Add in NFFT,Fs,Window,nooverlap to XML file fid = open('C:\Users\uqkweegi\Documents\Data\DAfit\patientspsd.xml', 'w') fid.write("<PATIENTDATA>\n") for PNitem in PatientNumbers: Pxx -= Pxx fid.write("\t<PATIENT>\n") fid.write("\t\t<ID>" + str(PNitem) + "</ID>\n") fid.write("\t\t<SIDE>\n\t\t\t<ID>Left</ID>\n") count = 1 for item in PLList:
if __name__ == '__main__': # xxxxxxxxxx Input generation (not part of OFDM) xxxxxxxxxxxxxxxxxxxxxx num_bits = 2500 # generating 1's and 0's ip_bits = np.random.random_integers(0, 1, num_bits) # Number of modulated symbols num_mod_symbols = num_bits * 1 # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # xxxxxxxxxxxxxxx BPSK modulation xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # bit0 --> -1 # bit1 --> +1 ip_mod = 2 * ip_bits - 1 ofdm_obj = OFDM(64, 16, 52) ofdm_symbols = ofdm_obj.modulate(ip_mod) # Code to plot the power spectral density fsMHz = 20e6 Pxx, W = pylab.psd(ofdm_symbols, NFFT=ofdm_obj.fft_size, Fs=fsMHz) # [Pxx,W] = pwelch(st,[],[],4096,20); plt.plot( W, # 10 * np.log10(np.fft.fftshift(Pxx)) 10 * np.log10(Pxx)) plt.xlabel('frequency, MHz') plt.ylabel('power spectral density') plt.title('Transmit spectrum OFDM (based on 802.11a)') plt.show()