def __init__(self, R, N_f, Rg_f, S_f, \ N_c=0.0, Rg_c=1.5, S_c=0.3,\ Density=1.0, PSD_base = np.e): ''' Inputs: N_f, Rg_f, S_f: fine mode number conentration [#/cm^3], median radius [um] and standard deviation [um] N_c, Rg_c, S_c: coarse mode number conentration [#/cm^3], median radius [um] and standard deviation [um] Density: Density of the aerosol [g / cm^3] PSD_base = base of logarithm for lognormal PSD computation rmin, rmax: min and max radius of aerosol ''' self.R = R self.N_f = N_f self.Rg_f = Rg_f self.S_f = S_f self.N_c = N_c self.Rg_c = Rg_c self.S_c = S_c self.Density = Density self.PSD_base = PSD_base dNdlnrf = PSD.dNdlnr_Lognormal(self.R, np.log(self.Rg_f)/np.log(self.PSD_base), self.S_f, \ N0=self.N_f, normalize=True, base=self.PSD_base) dNdlnrc = PSD.dNdlnr_Lognormal(self.R, np.log(self.Rg_c)/np.log(self.PSD_base), self.S_c, \ N0=self.N_c, normalize=True, base=self.PSD_base) self.dNdlnr = dNdlnrf + dNdlnrc self.dNdr = 1.0/self.R * self.dNdlnr self.dVdlnr = 4.0/3.0*np.pi * (self.R **3) * self.dNdlnr self.dAdlnr = np.pi * (self.R **2) * self.dNdlnr self.dMdlnr = self.dVdlnr * self.Density
def plot_worker(frame): ''' Calculate ch0 and ch1 filtered data. Then calculate feature vectors according to the method selected Raises: KeyError -- Error raised if feat_method set wrong in config dict ''' global ch0_line, ch1_line, ch0_line_gaussed, ch1_line_gaussed, ch0_fft_line, ch1_fft_line, ch0_grad_line global ch0_list, ch1_list global x_list, new_feature global feat0, feat1, filtered_ch0, filtered_ch1 if not paused: ch0_line.set_data(x_list,ch0_list) ch1_line.set_data(x_list,ch1_list) # Gaussian filtering gauss_inp_ch0 = np.array(ch0_list) filtered_ch0 = scipy.ndimage.filters.gaussian_filter1d(gauss_inp_ch0, sigma=config['ch0_gauss_filter_sigma']) gauss_inp_ch1 = np.array(ch1_list) filtered_ch1 = scipy.ndimage.filters.gaussian_filter1d(gauss_inp_ch1, sigma=config['ch1_gauss_filter_sigma']) ch0_line_gaussed.set_data(x_list_np,filtered_ch0) ch1_line_gaussed.set_data(x_list_np,filtered_ch1) # ========================================================================================== # # fft plot # N = np.arange(config['x_window']) # fft0 = np.fft.fft(filtered_ch0) # fft1 = np.fft.fft(filtered_ch1) # freq = np.fft.fftfreq(config['x_window'],d=(config['sample_time_period']/1000))*2000 # ch0_fft_line.set_data(freq, fft0.real) # ch1_fft_line.set_data(freq, fft1.real) # ========================================================================================== if config['feat_method']=='psd': # PSD extract feat0 = PSD.PSD_extractor(ch0_list) feat1 = PSD.PSD_extractor(ch1_list) N = np.arange(config['psd_feature_size']*3) ch0_fft_line.set_data(N, np.array(feat0)) ch1_fft_line.set_data(N, np.array(feat1)) # ========================================================================================== elif config['feat_method']=='dwt': # DWT extract feat0 = DWT.DWT_extractor(ch0_list) feat1 = DWT.DWT_extractor(ch1_list) N = np.arange(len(feat0)) ch0_fft_line.set_data(N, np.array(feat0)) ch1_fft_line.set_data(N, np.array(feat1)) # ========================================================================================== else: raise KeyError("invalid feat method") new_feature = True if config['compute_concentration_energy']: concentration_energy = np.trapz(feat0[20:30],dx=1)#/np.trapz(feat0[8:12],dx=1) print(concentration_energy) time.sleep(config['sample_time_period']/1000) return ch0_line, ch1_line, ch0_line_gaussed, ch1_line_gaussed, ch0_fft_line, ch1_fft_line
def Refresh_PSD(p1): loadpsd = empty_like(loaddata, dtype=float) if issim == 0: loadpsd[1:5] = dsp_core.normalize(loaddata[1], loaddata[2], loaddata[3], loaddata[4]) else: loadpsd = loaddata fs = get_freq() psd1 = PSD.plotpsd(loadpsd[1], fs) print(len(psd1[0])) print(len(psd1[1])) plotrefresh(pl8[0], pl8[1], psd1[0], psd1[1], 1, ylab="PSD(rad^2/Hz)", xlab="frequency (Hz)") psd2 = PSD.plotpsd(loadpsd[2], fs) plotrefresh(pl9[0], pl9[1], psd2[0], psd2[1], 1, ylab="PSD(rad^2/Hz)", xlab="frequency (Hz)") psd3 = PSD.plotpsd(loadpsd[3], fs) plotrefresh(pl10[0], pl10[1], psd3[0], psd3[1], 1, ylab="PSD(rad^2/Hz)", xlab="frequency (Hz)") psd4 = PSD.plotpsd(loadpsd[4], fs) plotrefresh(pl11[0], pl11[1], psd4[0], psd4[1], 1, ylab="PSD(rad^2/Hz)", xlab="frequency (Hz)")
def psd_phi(p1): fs = get_freq() psd13 = PSD.plotpsd(phil, fs) plotrefresh(pl13[0], pl13[1], psd13[0], psd13[1], 1, ylab="PSD(rad^2/Hz)", xlab="frequency (Hz)") sys.stdout.flush()
def phipsd_pressed(p1): psd00 = PSD.plotpsd(f_ph, 1 / float(st_de.get())) f = figure() ax = f.add_subplot(111) ax.plot(psd00[0], psd00[1]) locmaj = matplotlib.ticker.LogLocator(base=10, numticks=12) ax.xaxis.set_major_locator(locmaj) ax.loglog() ax.grid() ax.set_ylabel("Phase PSD (V^2/Hz)") ax.set_xlabel("frequency (Hz)") f.show() sys.stdout.flush() f.show() sys.stdout.flush()
def main(): # Read in the users data file as two columns # timestep, dr (ang) try: fin = sys.argv[1] step = float(sys.argv[2]) f = open(fin, 'r') except IndexError: print '\nusage ' + sys.argv[0] + ' f_bond.dat timestep_in_A.U.\n' sys.exit(0) lines = f.readlines() f.close() x, y = [], [] for line in lines: row = line.split() x.append(float(row[0])) y.append(float(row[1])) # Calculate the PSD and save a figure psd_obj = PSD.psd(x, y) f, psd = psd_obj.getPSD() # Write PSD data to file out = open('PSD.dat', 'w') out.write('#f psd\n') # Neglect the zeroth value for i in range(len(f) / 2 - 1): out.write(str(f[i + 1]) + ' ' + str(psd[i + 1]) + '\n') # Domiqnant frequency psd = list(psd)[1:len(psd) / 2] f = list(f)[1:len(f) / 2] max_f = f[psd.index(max(psd))] # Corresponding period T = 1.0 / max_f # Convert period from number of timesteps to femtoseconds T = T * (step * 2.41880e-02) out.close() print 'The period is ' + str(T) + ' femtoseconds'
def main(): # Read in the users data file as two columns # timestep, dr (ang) try: fin = sys.argv[1] step = float(sys.argv[2]) f = open(fin,'r') except IndexError: print '\nusage '+sys.argv[0]+' f_bond.dat timestep_in_A.U.\n' sys.exit(0) lines = f.readlines() f.close() x, y = [], [] for line in lines: row = line.split() x.append(float(row[0])) y.append(float(row[1])) # Calculate the PSD and save a figure psd_obj = PSD.psd(x,y) f, psd = psd_obj.getPSD() # Write PSD data to file out = open('PSD.dat','w') out.write('#f psd\n') # Neglect the zeroth value for i in range(len(f)/2-1): out.write(str(f[i+1])+' '+str(psd[i+1])+'\n') # Domiqnant frequency psd = list(psd)[1:len(psd)/2] f = list(f)[1:len(f)/2] max_f = f[ psd.index(max(psd)) ] # Corresponding period T = 1.0 / max_f # Convert period from number of timesteps to femtoseconds T = T * (step * 2.41880e-02) out.close() print 'The period is '+str(T)+' femtoseconds'
def get_scat_prop(self, sizep, nr, ni, ang, alb, qe, gf, P11, P12, P33, P34): """ Inputs: Scattering property database sizep: size parameter nr: real part of refractice index ni: imaginary of refractive index G : projected area ang: scattering angle alb: single scattering albedoe qe: exintciton efficiency gf: asymmetry factor P11, P12: phase functions """ G_all = [] qe_all = [] alb_all = [] P11_all = [] P22_all = [] P33_all = [] P44_all = [] P12_all = [] P34_all = [] for iwvl in range(self.Ref_wvl.size): r=sizep*self.Ref_wvl[iwvl]/2.0/np.pi dNdr = np.interp(r, self.R, self.dNdr) nr_index = np.where(nr >=self.Refr_real[iwvl])[0][0] ni_index = np.where(ni >=self.Refr_imag[iwvl])[0][0] qe_sub = np.squeeze( qe[:,nr_index,ni_index]) alb_sub = np.squeeze(alb[:,nr_index,ni_index]) P11_sub = np.squeeze(P11[:,nr_index,ni_index,:]) P12_sub = np.squeeze(P12[:,nr_index,ni_index,:]) P33_sub = np.squeeze(P33[:,nr_index,ni_index,:]) P34_sub = np.squeeze(P34[:,nr_index,ni_index,:]) G_avg, qe_avg, alb_avg, P11_avg, P12_avg, P33_avg, P34_avg = \ PSD.PSD_avg_sphere(r, dNdr, ang*np.pi/180.0,\ qe_sub,alb_sub,P11_sub,P12_sub,P33_sub,P34_sub) G_all = np.append(G_all,G_avg) qe_all = np.append(qe_all,qe_avg) alb_all = np.append(alb_all,alb_avg) P11_all = np.append(P11_all,P11_avg) P22_all = np.append(P22_all,P11_avg) P33_all = np.append(P33_all,P33_avg) P44_all = np.append(P44_all,P33_avg) P12_all = np.append(P12_all,P12_avg) P34_all = np.append(P34_all,P34_avg) P11_all=P11_all.reshape(self.Ref_wvl.size,ang.size) P22_all=P22_all.reshape(self.Ref_wvl.size,ang.size) P33_all=P33_all.reshape(self.Ref_wvl.size,ang.size) P44_all=P44_all.reshape(self.Ref_wvl.size,ang.size) P12_all=P12_all.reshape(self.Ref_wvl.size,ang.size) P34_all=P34_all.reshape(self.Ref_wvl.size,ang.size) self.G = G_all self.ang = ang self.Qe = qe_all self.Alb = alb_all self.P11 = P11_all self.P22 = P22_all self.P33 = P33_all self.P44 = P44_all self.P12 = P12_all self.P34 = P34_all
def main(): # Check for required user input try: fname = sys.argv[1] step = int(sys.argv[2]) except IndexError: print '\nusage: '+sys.argv[0]+' TRAJEC.cbn step_in_au\n' sys.exit(0) # Get the neighbor list from cbn file nn = nearest_neighbor(fname) # Open and read header from cbn file f = open(fname,'r') for i in range(8): if i == 3: alat = float(f.readline().split()[-1])*0.5291772 # Convert to angstroms natom = int(f.readline().split()[-1]) f.readline() lines = f.readlines() f.close() # Calculate all the bond lengths over time dr = [[] for i in range(len(nn))] Nconfigs = len(lines)/len(nn) for j in range(len(lines)/(len(nn))): # Report progress to user if j % 200 == 0 and j != 0: print int(round((float(j)/Nconfigs)*100)), '% ...' for i in range(natom): # Current atom's coords and its partner's typat1,x1,y1,z1,dummy1 = lines[i].split() typat2,x2,y2,z2,dummy2 = lines[nn[i]].split() # Caclulate bond length using the minimum image convention dx = (float(x1) - float(x2)) * 0.5291772 dy = (float(y1) - float(y2)) * 0.5291772 dz = (float(z1) - float(z2)) * 0.5291772 dx -= alat*pbc_round(dx/alat) dy -= alat*pbc_round(dy/alat) dz -= alat*pbc_round(dz/alat) # Calculate bond length in angstroms r = ( dx**2 + dy**2 + dz**2 )**0.5 dr[i].append(abs(r)) for k in range(natom): lines.pop(0) frequencies, periods, bond_lengths = [], [], [] for dr_array in dr: # Calculate the PSD psd_obj = PSD.psd([i for i in range(len(dr_array))],dr_array) f, psd = psd_obj.getPSD() f, psd = list(f), list(psd) # Dominant frequency (in region of interest) max_f = 0 while max_f == 0: max_f = f.pop( psd[1:len(psd)/2].index(max(psd[1:len(psd)/2])) ) # Corresponding period in femtoseconds T = (1.0 / max_f) * (step * 2.4188000000000003e-02) frequencies.append(max_f) periods.append(T) bond_lengths += dr_array """ # Write PSD data to file out = open('PSD.dat','w') out.write('#f psd\n') # Neglect the zeroth value and the second half for i in range(len(f)/2-1): out.write(str(f[i+1])+' '+str(psd[i+1])+'\n') out.close() """ # Histograms of values pylab.figure(num=1,figsize=(5,3),facecolor='w',edgecolor='k') pylab.hist(frequencies, normed=1, label='_nolegend_') pylab.savefig('bond_frequencies_hist.png') pylab.clf() pylab.hist(periods, normed=1, label='_nolegend_') pylab.savefig('bond_periods_hist.png') pylab.clf() pylab.hist(bond_lengths, bins=250, normed=1, label='_nolegend_') pylab.savefig('bond_length_hist.png') pylab.clf()
def kernel_knn_graph(K, k): (N, D) = K.shape D = PSD.to_square_dist(K) idx = KNN.find_knn(D, k, want_self=False) G = create_knn_graph(N, idx, k) return G, idx
def dataProcessingNoExtClock(datafile, photonDataFile, tic): import h5py import numpy as np import matplotlib.pyplot as plt import pylab import time import adc2kev import PSD import generateConesNoExtClock #### Extract data here #### f = h5py.File(datafile, 'r') adcBoardKey = list(f.keys())[0] adcBoardVals = f[adcBoardKey] adcBoardVals = np.array(adcBoardVals) adcChannelKey = list(f.keys())[1] adcChannel = f[adcChannelKey] adcChannel = np.array(adcChannel) groupTimeVals = list(f.keys())[5] timeVals = f[groupTimeVals] timeVals = np.array(timeVals) groupKeyVal = list(f.keys())[4] rawData = f[groupKeyVal] rawDataMat = np.array(rawData, dtype='float') #### Extract photon data here for ADC conversion #### #f1 = h5py.File(photonDataFile, 'r') #adcGammaBoardKey = list(f1.keys())[0] #adcGammaBoardVals = f1[adcGammaBoardKey] #adcGammaBoardVals = np.array(adcGammaBoardVals) #adcGammaChannelKey = list(f1.keys())[1] #adcGammaChannel = f1[adcGammaChannelKey] #adcGammaChannel = np.array(adcGammaChannel) #groupTimeVals = list(f.keys())[5] #timeVals = f[groupTimeVals] #timeVals = np.array(timeVals) #groupKeyValGamma = list(f1.keys())[4] #rawGammaData = f1[groupKeyValGamma] rawGammaDataMat = photonDataFile #np.array(photonDataFile,dtype='float') # detectorVal = [] #### Break up detectors into 1-24 based on adcChannel and adcBoard values #### #### Separate data based on each plane of detectors #### plane1Data = [] plane2Data = [] plane1Times = [] plane2Times = [] plane1Dets = [] plane2Dets = [] plane1PhotonData = [] # t1 = time.time() for i in range(0, len(adcBoardVals)): #10000): # tic = time.time() if adcBoardVals[i] == 5: if adcChannel[i] == 0: #detectorVal = detectorVal + [0] plane1Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane1Times += [timeVals[i]] plane1Dets += [0] #plane1PhotonData += [rawGammaDataMat[i,:]] elif adcChannel[i] == 1: #detectorVal = detectorVal + [1] plane1Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane1Times += [timeVals[i]] plane1Dets += [1] #plane1PhotonData += [rawGammaDataMat[i,:]] elif adcChannel[i] == 2: #detectorVal = detectorVal + [2] plane1Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane1Times += [timeVals[i]] plane1Dets += [2] #plane1PhotonData += [rawGammaDataMat[i,:]] elif adcChannel[i] == 3: #detectorVal = detectorVal + [3] plane1Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane1Times += [timeVals[i]] plane1Dets += [3] #plane1PhotonData += [rawGammaDataMat[i,:]] elif adcChannel[i] == 4: #detectorVal = detectorVal + [4] plane2Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane2Times += [timeVals[i]] plane2Dets += [20] elif adcChannel[i] == 5: #detectorVal = detectorVal + [5] plane2Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane2Times += [timeVals[i]] plane2Dets += [21] elif adcChannel[i] == 6: #detectorVal = detectorVal + [6] plane2Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane2Times += [timeVals[i]] plane2Dets += [22] elif adcChannel[i] == 7: #detectorVal = detectorVal + [7] plane2Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane2Times += [timeVals[i]] plane2Dets += [23] elif adcBoardVals[i] == 7: if adcChannel[i] == 0: #detectorVal = detectorVal + [16] plane2Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane2Times += [timeVals[i]] plane2Dets += [16] elif adcChannel[i] == 1: #detectorVal = detectorVal + [17] plane2Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane2Times += [timeVals[i]] plane2Dets += [17] elif adcChannel[i] == 2: #detectorVal = detectorVal + [18] plane2Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane2Times += [timeVals[i]] plane2Dets += [18] elif adcChannel[i] == 3: #detectorVal = detectorVal + [19] plane2Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane2Times += [timeVals[i]] plane2Dets += [19] elif adcChannel[i] == 4: #detectorVal = detectorVal + [20] plane1Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane1Times += [timeVals[i]] plane1Dets += [4] #plane1PhotonData += [rawGammaDataMat[i,:]] elif adcChannel[i] == 5: #detectorVal = detectorVal + [21] plane1Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane1Times += [timeVals[i]] plane1Dets += [5] #plane1PhotonData += [rawGammaDataMat[i,:]] elif adcChannel[i] == 6: #detectorVal = detectorVal + [22] plane1Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane1Times += [timeVals[i]] plane1Dets += [6] #plane1PhotonData += [rawGammaDataMat[i,:]] elif adcChannel[i] == 7: #detectorVal = detectorVal + [23] plane1Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane1Times += [timeVals[i]] plane1Dets += [7] #plane1PhotonData += [rawGammaDataMat[i,:]] elif adcBoardVals[i] == 6: if adcChannel[i] == 0: #detectorVal = detectorVal + [8] plane1Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane1Times += [timeVals[i]] plane1Dets += [8] #plane1PhotonData += [rawGammaDataMat[i,:]] elif adcChannel[i] == 1: #detectorVal = detectorVal + [9] plane1Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane1Times += [timeVals[i]] plane1Dets += [9] #plane1PhotonData += [rawGammaDataMat[i,:]] elif adcChannel[i] == 2: #detectorVal = detectorVal + [10] plane1Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane1Times += [timeVals[i]] plane1Dets += [10] #plane1PhotonData += [rawGammaDataMat[i,:]] elif adcChannel[i] == 3: #detectorVal = detectorVal + [11] plane1Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane1Times += [timeVals[i]] plane1Dets += [11] #plane1PhotonData += [rawGammaDataMat[i,:]] elif adcChannel[i] == 4: #detectorVal = detectorVal + [12] plane2Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane2Times += [timeVals[i]] plane2Dets += [12] elif adcChannel[i] == 5: #detectorVal = detectorVal + [13] plane2Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane2Times += [timeVals[i]] plane2Dets += [13] elif adcChannel[i] == 6: #detectorVal = detectorVal + [14] plane2Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane2Times += [timeVals[i]] plane2Dets += [14] elif adcChannel[i] == 7: #detectorVal = detectorVal + [15] plane2Data += [rawDataMat[i, :] ] #-np.mean(np.mean(rawDataMat[i,1:20]))] plane2Times += [timeVals[i]] plane2Dets += [15] if i % 100000 == 0: print('k = ', i) toc = time.time() # print('tictoc = ',toc-tic) print('elapsed = ', toc - tic, 's') #### Convert list into numpy array #### #detectorVal = np.array(detectorVal,dtype='float') plane1Data = np.array(plane1Data, dtype='float') plane2Data = np.array(plane2Data, dtype='float') plane1Times = np.array(plane1Times, dtype='float') plane2Times = np.array(plane2Times, dtype='float') plane1Dets = np.array(plane1Dets, dtype='int') plane2Dets = np.array(plane2Dets, dtype='int') rowTest = [i for i in plane1Data[0, :] if i >= 0] rowTest = np.array(rowTest) #plt.plot(plane1Data[0,:]) plt.plot(rowTest) plt.show() #plane1PhotonData = np.array(plane1PhotonData,dtype='float') # print('plane1Data = ',plane1Data) # print('plane1Times = ',plane1Times) # print('plane1Dets = ',plane1Dets) # for i in range(0,len(adcBoardVals)):#10000): # if i%100000 == 0: # print('i = ',i) # # if detectorVal[i] <= 11: # plane1Data = plane1Data + [rawDataMat[i,:]] # plane1Times = plane1Times + [timeVals[i]] # plane1Dets = plane1Dets + [11] # else: # plane2Data = plane2Data + [rawDataMat[i,:]] # plane2Times = plane2Times + [timeVals[i]] # plane2Dets = plane2Dets + [detectorVal[i]] #### Convert list into numpy array #### # plane1Data = np.array(plane1Data,dtype='float') # plane2Data = np.array(plane2Data,dtype='float') # plane1Times = np.array(plane1Times,dtype='float') # plane2Times = np.array(plane2Times,dtype='float') # plane1Dets = np.array(plane1Dets,dtype='int') # plane2Dets = np.array(plane2Dets,dtype='int') print('Creating ADC Conversion') toc = time.time() # print('tictoc = ',toc-tic) print('elapsed = ', toc - tic, 's') slope, intercept = adc2keV(rawGammaDataMat) #### Perform PSD for each plane of data to extract just neutron information #### print('Performing PSD on Plane 1') toc = time.time() # print('tictoc = ',toc-tic) print('elapsed = ', toc - tic, 's') plane1NeutronDets, plane1NeutronTimes, plane1NeutronPulseADC = PSD( plane1Dets, plane1Times, plane1Data, 'Plane 1', slope, intercept, tic) print('Performing PSD on Plane 2') toc = time.time() # print('tictoc = ',toc-tic) print('elapsed = ', toc - tic, 's') plane2NeutronDets, plane2NeutronTimes, plane2NeutronPulseADC = PSD( plane2Dets, plane2Times, plane2Data, 'Plane 2', slope, intercept, tic) # np.savetxt("plane1NeutronDets.csv", plane1NeutronDets, delimiter=",") # np.savetxt("plane2NeutronDets.csv", plane2NeutronDets, delimiter=",") # np.savetxt("plane1NeutronTimes.csv", plane1NeutronTimes, delimiter=",") # np.savetxt("plane2NeutronTimes.csv", plane2NeutronTimes, delimiter=",") # np.savetxt("plane1NeutronPulseADC.csv", plane1NeutronPulseADC, delimiter=",") # np.savetxt("plane2NeutronPulseADC.csv", plane2NeutronPulseADC, delimiter=",") # print('length of plane1NeutronDets: ',len(plane1NeutronDets)) # print('length of plane1NeutronTimes: ',len(plane1NeutronTimes)) # print('length of neutronPulseData1: ',len(neutronPulseData1[:,0])) # print('length of plane2NeutronDets: ',len(plane2NeutronDets)) # print('length of plane2NeutronTimes: ',len(plane2NeutronTimes)) # print('length of neutronPulseData2: ',len(neutronPulseData2[:,0])) #### Generate cones and do energy reconstruction of neutrons #### print('Performing Energy Reconstruction and Cone Generation') #toc = time.time() # print('tictoc = ',toc-tic) print('elapsed = ', toc - tic, 's') neutronEnergy = generateConesNoExtClock( slope, intercept, plane1NeutronDets, plane2NeutronDets, plane1NeutronTimes, plane2NeutronTimes, plane1NeutronPulseADC, plane2NeutronPulseADC, tic) print('elapsed = ', toc - tic, 's') print('Calculating Absorbed Dose') kFactor = calculateAbsorbedDose(neutronEnergy, tic) print('elapsed = ', toc - tic, 's') return
def openConnection(): HOST = "localhost" PORT = 000 #invalid port number for security reasons s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((HOST, PORT)) except socket.error as err: print('Bind failed. Error Code : '.format(err)) s.listen(10) #conn, addr = s.accept() open = True try: while (open): conn, addr = s.accept() #conn.send(bytes("Message1"+"\r\n",'UTF-8')) message = conn.recv(1024) msg = message.decode(encoding='UTF-8') if (msg == "filePaths"): paths = [] while (msg != "done"): message = conn.recv(1024) msg = message.decode(encoding='UTF-8') paths.append(msg) for p in paths: pa = p.replace('/', '\\') classification = PSD.convertAndClassify(pa) conn.send(bytes(classification + "\r", 'UTF-8')) elif (msg != "close"): credentials = msg.split() username = credentials[0] password = hash_sha1(credentials[1]) event = credentials[2] if (event == "login"): # p = collection.find_one({'username': username}) # print(p['password']) # print("\n\n") # print(password) if (collection.count_documents({ 'username': username, 'password': password }) == 1): #if(verifyPass(p['password'], password)): conn.send(bytes("ok" + "\r\n", 'UTF-8')) else: conn.send(bytes("notok" + "\r\n", 'UTF-8')) if (event == "register"): if (collection.count_documents({'username': username}) >= 1): conn.send(bytes("taken" + "\r\n", 'UTF-8')) else: conn.send(bytes("ok" + "\r\n", 'UTF-8')) collection.insert_one({ 'username': username, 'password': password }) # print(message.decode(encoding='UTF-8')) if (message.decode(encoding='UTF-8') == "close"): print("Connection gracefully closed") open = False except ConnectionResetError: s.close() print("Connection terminated") s.close()
T = re.search('_(.*)C.bin', file) print T.group(1) Temperature.append(T.group(1)) print "Files to read: ", DataList print "Temperatures: ", Temperature # NormalizeTimeAlignedWaveforms = np.empty([len(DataList), NoOfWaveforms]) for F, file in enumerate(DataList): print "Reading ", file ## Read in N waveforms from bin file. ## For each waveform with a peak above PeakThreshold, ## do a baseline correction and time alignment of the sample at which ## the signal crosses 'Threshold'. ## Normalise each signal ## Add signals together and divide by NoOfWaveforms to get the average signal. FID, cols, rows = PSD.OpenFile(file) #print cols, rows ## ReadBinary(..) returns a NxM matrix of waveforms. FID = fileID, NoOfWaveforms. AllWaveforms = np.array( PSD.ReadBinaryFile(FID, ReadWaveforms, cols, rows)) # Remove waveforms that show saturation. i.e. Ones in which the maximum value is 100mV AllWaveforms = RemoveSaturation(AllWaveforms, SatLimit) if (RandomSample): # Randomly select NoOfWaveforms from all the waveforms. Selection = random.sample(AllWaveforms, np.shape(AllWaveforms)[0]) if (not RandomSample): ## Or... find the NoOfWaveforms that have the greatest sum (Largest Signals) SumAllWaveforms = PSD.GetFullIntegral(AllWaveforms) ## Get NoOfWaveforms indices of the AllWaveforms N_Max = SumAllWaveforms.argsort()[-NoOfWaveforms:]