#!/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 def daq_measure(N,freq,p,direct,prefix): #N=int(input('how long to scan (min) ? \n')) #freq = 1000 #number of channels NC=3 #tt=int(input('how long to scan (sec) ? \n')) #tt is in seconds bc Hz is in sec-1 tt=60 #t=tt*NC #SamplesPerPacket spp=NC MAX_REQUESTS=int(N*tt*freq) #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=1, SamplesPerPacket=spp, ChannelNumbers=[0,2,4], ChannelOptions=[128,128,128], ScanFrequency=freq) # To prevent the program from crashing when encountering an exception, we use a try statement try: d.streamStart() rawDataStr ="" rawAIN=[[]]*4 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=True): if r is not None: #print("YAY;RESULTS") #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() #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']] dataCount += 1 sys.stdout.write("\r" +'\n Currently @ '+str(100*dataCount//MAX_REQUESTS)+'%') sys.stdout.flush() #print("dataCount= ",dataCount) packetCount += r['numPackets'] for l in range(len(rawAIN[0])): rawdata.write("%s\n" %' '.join(map(str,[round(rawAIN[0][l],6),round(rawAIN[1][l],6),round(rawAIN[2][l],6),round(t1-t0,3)]))) 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() except: print("exception!!") print "".join(i for i in traceback.format_exc()) rawdata.close() finally: d.streamStop() #save last time, to account for potentially yet unsaved data rawdata.close() processedDataList = d.processStreamData(rawDataStr) #write data properly if it comes to this:---------------------------------------------------------------------------------------------------------------------------------- datafile=open(direct+'/'+prefix+'_data_'+str(N)+'min_'+str(freq)+'Hz_@'+str(p)+'Hz.txt', "a+") 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+") xx=np.asarray(processedDataList['AIN0']).reshape(freq/p,int(N*tt*p)) yy=np.asarray(processedDataList['AIN2']).reshape(freq/p,int(N*tt*p)) zz=np.asarray(processedDataList['AIN4']).reshape(freq/p,int(N*tt*p)) #plus one in order not to overwrite last take datax=np.mean(xx,axis=0) datay=np.mean(yy,axis=0) dataz=np.mean(zz,axis=0) vppx=np.max(xx)-np.min(xx) vppy=np.max(yy)-np.min(yy) vppz=np.max(zz)-np.min(zz) sigx=np.std(xx,axis=0) sigy=np.std(yy,axis=0) sigz=np.std(zz,axis=0) #write the files vppfile.write("%s\n" %' '.join(map(str, [round(vppx,6),round(vppy,6),round(vppz,6)]))) #loop necessary to write array instead of just vector for l in range(len(datax)): #this formatting is necessary to avoid brackets in the file datafile.write("%s\n" %' '.join(map(str, [round(datax[l],6),round(datay[l],6),round(dataz[l],6)]))) sigfile.write("%s\n" %' '.join(map(str, [round(sigx[l],6),round(sigy[l],6),round(sigz[l],6)]))) 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() def close(): d = u6.U6() d.configU6() d.getCalibrationData() d.close()