#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Feb 26 16:45:19 2018 @author: neutron """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 12 12:42:47 2017 @author: god """ import u6 import numpy as np #import time import traceback from datetime import datetime from pathlib import Path import os #import time import sys from matplotlib import pyplot as plt N=0.1 freq=1000 p=freq direct='debug/debug0103' prefix='deleteme' #N=int(input('how long to scan (min) ? \n')) #freq = 1000 #number of channels chlist=[0,2,4,6,8,10,12] chlist=[0] NC=len(chlist) CO=[128]*NC tt=60 #samples per packet per channel: ppc=20//NC #SamplesPerPacket spp=NC*ppc MAX_REQUESTS=int(N*tt*freq*NC/spp) setvoltage='CH0 to 3.4V,CH2&4 to 2.6V' #avg over and save every pth of a second # #rename if files exist already---------------------------------------------------------------------------------------------- # print(direct+'/'+prefix+'_data_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt') datafile = Path(direct+'/'+prefix+'_data_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt') # rawdata = Path(direct+'/'+prefix+'_rawdata_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt') # vppfile = Path(direct+'/'+prefix+'_vpp_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt') # sigfile = Path(direct+'/'+prefix+'_sig_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt') if datafile.is_file(): os.rename(direct+'/'+prefix+'_data_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt',direct+'/'+prefix+'_data_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt'+'.old') print('\n'+'***moved existing '+direct+'/'+prefix+'_data_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt'+' to '+direct+'/'+prefix+'_data_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt'+'.old***'+'\n') # if sigfile.is_file(): # os.rename(direct+'/'+prefix+'_sig_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt',direct+'/'+prefix+'_sig_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt'+'.old') # print('\n'+'***moved existing '+direct+'/'+prefix+'_sig_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt'+' to '+direct+'/'+prefix+'_sig_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt'+'.old***'+'\n') # if vppfile.is_file(): # os.rename(direct+'/'+prefix+'_vpp_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt',direct+'/'+prefix+'_vpp_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt'+'.old') # print('\n'+'***moved existing '+direct+'/'+prefix+'_vpp_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt'+' to '+direct+'/'+prefix+'_vpp_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt'+'.old***'+'\n') # if rawdata.is_file(): # os.rename(direct+'/'+prefix+'_rawdata_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt',direct+'/'+prefix+'_rawdata_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt'+'.old') # print('\n'+'***moved existing '+direct+'/'+prefix+'_rawdata_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt'+' to '+direct+'/'+prefix+'_rawdata_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt'+'.old***'+'\n') # # ---------------------------------------------------------------------------------------------- d = u6.U6() d.configU6() d.getCalibrationData() d.streamConfig(NumChannels=NC, ResolutionIndex=0, SamplesPerPacket=spp, ChannelNumbers=chlist, ChannelOptions=CO, ScanFrequency=freq) # To prevent the program from crashing when encountering an exception, we use a try statement try: d.streamStart() # processedDataList=[[0],[0],[0]] rawDataStr ="" start = datetime.now() # print the scan start time print("Started stream at " +str(datetime.now())+ '\n') missed = 0 # initialize counters dataCount = 0 packetCount = 0 # rawdata=open(direct+'/'+prefix+'_rawdata_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt', "a+") #t0=time.time() for r in d.streamData(convert=False): if r is not None: #packetStartTime = datetime.now() #miniRuntime = (packetStartTime - start).seconds + float((packetStartTime - start).microseconds) / 1000000 # Our stop condition if dataCount >= MAX_REQUESTS: break if r['errors'] != 0: print "Error: %s ; " % r['errors'], datetime.now() if r['numPackets'] != d.packetsPerRequest: print("----- UNDERFLOW : %s : " +str(r['numPackets'])+str(datetime.now())) if r['missed'] != 0: missed += r['missed'] print("+++ Missed "+str(r['missed'])) rawDataStr+=r['result'] #t1=time.time() # if len(r['AIN0'])!=ppc: # break #sometimes, we miss a value for a channel, thus implement a safguard by cheking lengths #append a nan value to the shorter vector is the chosen method here # if (len(r['AIN0'])!=len(r['AIN2']) or len(r['AIN2'])!=len(r['AIN4']) or len(r['AIN0'])!=len(r['AIN4'])): # length=np.array([len(r['AIN0']),len(r['AIN2']),len(r['AIN4'])]) # index=np.where(length==length.min())[0][0] # r['AIN'+str(index*2)].append(np.nan) #rawAIN=[r['AIN0'],r['AIN2'],r['AIN4'] #print(len(r["AIN0"])) #print(r['AIN0']) dataCount += 1 sys.stdout.write("\r" +'DAQ Currently @ '+str(100*dataCount//MAX_REQUESTS)+'%') sys.stdout.flush() #print("dataCount= ",dataCount) packetCount += r['numPackets'] # processedDataList[0].extend(r["AIN0"]) # processedDataList[1].extend(r["AIN4"]) # processedDataList[2].extend(r["AIN8"]) else: # Got no data back from our read. # This only happens if your stream isn't faster than the # the USB read timeout, ~1 sec. print "No data, timeout", datetime.now() #write rawdata every 100 datapts: # if dataCount % 100==0: # print('saving') # for l in range(len(processedDataList[0])): # rawdata.write("%f %f %f\n"%(processedDataList[0][l],processedDataList[1][l],processedDataList[2][l])) # #rawdata.write("%s\n" %' '.join(map(str,[r['AIN0'][l],r['AIN2'][l],r['AIN4'][l]]))) except: print("exception!!") print "".join(i for i in traceback.format_exc()) # rawdata.close() finally: # rawdata.close() d.streamStop() print('\n ####### DATACOUNT '+str(dataCount)+' #######') #save last time, to account for potentially yet unsaved data #rawdata.close() processedDataList = d.processStreamData(rawDataStr) #remove the first line in the list cuz its just zeros: # for x in processedDataList: # del x[0] #write data properly if it comes to this:---------------------------------------------------------------------------------------------------------------------------------- # vppfile=open(direct+'/'+prefix+'_vpp_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt', "a+") # sigfile=open(direct+'/'+prefix+'_sig_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt', "a+") plt.figure() for j in range(NC): plt.plot(np.linspace(1,len(processedDataList['AIN0']),len(processedDataList['AIN0'])),processedDataList['AIN'+str(chlist[j])],'o',label='AIN'+str(chlist[j])) # plt.plot(np.linspace(1,len(processedDataList['AIN0']),len(processedDataList['AIN0'])),processedDataList['AIN2']) # plt.plot(np.linspace(1,len(processedDataList['AIN0']),len(processedDataList['AIN0'])),processedDataList['AIN4']) plt.title(str(NC)+'CH stream meas @'+str(freq)+'Hz '+setvoltage) plt.legend() plt.figure() height=freq/p width=len(processedDataList['AIN0'])//height #actual channels: xx=np.asarray(processedDataList['AIN0']).reshape(height,width) # yy=np.asarray(processedDataList['AIN2']).reshape(height,width) # zz=np.asarray(processedDataList['AIN4']).reshape(height,width) #useless shortcircuited channels: # x0=np.asarray(processedDataList[1]).reshape(height,width) # y0=np.asarray(processedDataList[3]).reshape(height,width) # z0=np.asarray(processedDataList[5]).reshape(height,width) #sample along p by taking the mean value: datax=np.mean(xx,axis=1) # datay=np.mean(yy,axis=1) # dataz=np.mean(zz,axis=1) # datax0=np.mean(x0,axis=0) # datay0=np.mean(y0,axis=0) # dataz0=np.mean(z0,axis=0) # vppx=np.max(datax)-np.min(datax) # vppy=np.max(datay)-np.min(datay) # vppz=np.max(dataz)-np.min(dataz) # sigx=np.std(datax) # sigy=np.std(datay) # sigz=np.std(dataz) # #write the files # vppfile.write("%f %f %f\n"%(vppx,vppy,vppz)) # sigfile.write("%f %f %f\n"%(sigx,sigy,sigz)) datafile=open(direct+'/'+prefix+'_data_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt', "a+") # #loop necessary to write array instead of just vector for l in range(len(processedDataList['AIN0'])): #this formatting is necessary to avoid brackets in the file datafile.write("%f\n"%(processedDataList['AIN0'][l])) # datafile.write("%f %f %f\n"%(processedDataList['AIN0'][l],processedDataList['AIN2'][l],processedDataList['AIN4'][l])) datafile.close() # # vppfile.close() # sigfile.close() #END write data properly if it comes to this:------------------------------------------------------------- stop = datetime.now() print '\n' , "Stream stopped at", datetime.now(), '\n' d.close() sampleTotal = packetCount * d.streamSamplesPerPacket scanTotal = sampleTotal / 1 # sampleTotal / NumChannels print "%s requests with %s packets per request with %s samples per packet = %s samples total." % ( dataCount, (float(packetCount) / dataCount), d.streamSamplesPerPacket, sampleTotal) print "%s samples were lost due to errors." % missed print "%f percent of total samples were lost" % (float(missed) * 100 / sampleTotal) sampleTotal -= missed print "Adjusted number of samples = %s" % sampleTotal print '\n' runTime = (stop - start).seconds + float((stop - start).microseconds) / 1000000 print "The experiment took %s seconds." % runTime print "Scan Rate : %s scans / %s seconds = %s Hz" % (scanTotal, runTime, float(scanTotal) / runTime) print "Sample Rate : %s samples / %s seconds = %s Hz" % (sampleTotal, runTime, float(sampleTotal) / runTime) # print "The average voltage was %s volts over the scan period" % (averageVoltage) #print(processedDataList) d.close() # if return_avg: # return np.mean(datax),np.mean(datay),np.mean(dataz) # def close(): # d = u6.U6() # d.configU6() # d.getCalibrationData() # d.close() data=np.loadtxt(direct+'/'+prefix+'_data_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt') vpp=np.max(data,axis=0)-np.min(data,axis=0) sigma=np.std(data,axis=0) mean=np.mean(data,axis=0) print(vpp) plt.figure() plt.plot(np.linspace(1,len(data),len(data)),data,'o',label='file') plt.title(str(NC)+'CH stream meas from file @'+str(freq)+'Hz '+setvoltage) plt.legend() #plt.figure() #for k in range(np.shape(data[0,:])[0]): # plt.plot(np.linspace(1,len(data[:,0]),len(data[:,0])),data[:,k],'o',label='file column'+str(k)) #plt.title(str(NC)+'CH stream meas from file @'+str(freq)+'Hz '+setvoltage) #plt.legend() #rawdata=np.loadtxt(direct+'/'+prefix+'_data_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt') #vpp=np.max(rawdata,axis=0)-np.min(rawdata,axis=0) #sigma=np.std(rawdata,axis=0) #mean=np.mean(rawdata,axis=0) #print(vpp) # #for k in range(np.shape(rawdata[0,:])[0]): # plt.plot(np.linspace(1,len(rawdata[:,0]),len(rawdata[:,0])),rawdata[:,k],label='file column'+str(k)) #plt.title(str(NC)+'CH stream meas from file @'+str(freq)+'Hz '+setvoltage) #plt.legend() # # #plt.plot(np.linspace(1,len(rawdata[:,1]),len(rawdata[:,1])),rawdata[:,1]) # plt.plot(np.linspace(1,len(rawdata[:,2]),len(rawdata[:,2])),rawdata[:,2]) # plt.plot(np.linspace(1,len(rawdata[:,4]),len(rawdata[:,4])),rawdata[:,4]) # plt.plot(np.linspace(1,len(rawdata[:,6]),len(rawdata[:,6])),rawdata[:,6]) # plt.figure() # plt.plot(np.linspace(1,len(rawdata[:,1]),len(rawdata[:,1])),rawdata[:,1]) # plt.plot(np.linspace(1,len(rawdata[:,3]),len(rawdata[:,3])),rawdata[:,3]) # plt.plot(np.linspace(1,len(rawdata[:,5]),len(rawdata[:,5])),rawdata[:,5])