def loadFPGA(parser): time.sleep(0.5) session = startIcebootSession(parser) print ('loading FPGA firmware...') flashLS = session.flashLS() firmwarefilename = flashLS[len(flashLS)-1]['Name'] # latest uploaded file try : session.flashConfigureCycloneFPGA(firmwarefilename) except : print(f'Error during the loading firmware {firmwarename}. Exit.') session.close() sys.exit(0) else : print(f'Configuration of the FPGA firmware {firmwarefilename} was successfully completed. ') session.close() time.sleep(1.0)
def main(parser): session = startIcebootSession(parser) flashLS = session.flashLS() if len(flashLS) == 0: print( 'Valid firmware images not found. \n' + 'Please upload the correct image file into the flash memory before running the script. ' ) sys.exit(0) firmwarefilename = flashLS[len(flashLS) - 1]['Name'] # latest uploaded file print(f'Found valid firmware {firmwarefilename} in the flash memory.\n' + 'Try to configure... ') try: session.flashConfigureCycloneFPGA(firmwarefilename) except: print(f'Error during the loading firmware {firmwarefilename}. Exit.') session.close() sys.exit(0) else: time.sleep(0.1) FpgaVersion = session.fpgaVersion() SoftwareVersion = session.softwareVersion() SoftwareId = session.softwareId() FpgaId = session.fpgaChipID() FlashId = session.flashID() print( f'FPGA: {FpgaId} with Firmware ver.{hex(FpgaVersion)}, Flash ID: {FlashId}, ' + f'Software ver.{hex(SoftwareVersion)} with ID {SoftwareId}. ') session.close() return FpgaVersion, SoftwareVersion, flashLS, SoftwareId, FpgaId, FlashId
def main(parser,path=".",comment=""): (options, args) = parser.parse_args() loadFPGA(parser) session = startIcebootSession(parser) filename = f'{path}/OnboardSensors{comment}{options.comment}.hdf5' axels = [] magns = [] press = [] temps = [] absaxels = [] absmagns = [] session.enableCalibrationPower() session.setCalibrationSlavePowerMask(1) session.setCameraEnableMask(0xFF) time.sleep(1) session.setCalibrationSlavePowerMask(2) session.enableCalibrationTrigger(1000) session.setFlasherMask(0xFFFF) session.setFlasherBias(0xFFFF) for i in range(int(options.iter)): axeldata = session.readAccelerometerXYZ() absaxel = np.sqrt(np.sum(np.square(axeldata))) magndata = session.readMagnetometerXYZ() absmagn = np.sqrt(np.sum(np.square(magndata))) pressure = session.readPressure() temperature = readSloAdcChannel(session,7) axels.append(axeldata) magns.append(magndata) press.append(pressure) temps.append(temperature) absaxels.append(absaxel) absmagns.append(absmagn) with tables.open_file(filename,'a') as open_file: try: table = open_file.get_node('/sensor') except: class Sensor(tables.IsDescription): time = tables.Int32Col() AxelX = tables.Float32Col() AxelY = tables.Float32Col() AxelZ = tables.Float32Col() AbsAxel = tables.Float32Col() MagnX = tables.Float32Col() MagnY = tables.Float32Col() MagnZ = tables.Float32Col() AbsMagn = tables.Float32Col() Press = tables.Float32Col() temp = tables.Float32Col() table = open_file.create_table('/','sensor',Sensor) table = open_file.get_node('/sensor') sensor = table.row sensor['time'] = time.time() sensor['AxelX'] = axeldata[0] sensor['AxelY'] = axeldata[1] sensor['AxelZ'] = axeldata[2] sensor['AbsAxel'] = absaxel sensor['MagnX'] = magndata[0] sensor['MagnY'] = magndata[1] sensor['MagnZ'] = magndata[2] sensor['AbsMagn'] = absmagn sensor['Press'] = pressure sensor['temp'] = temperature sensor.append() table.flush() meanaxel = np.append(np.mean(axels,axis=0), np.mean(absaxels)) meanmagn = np.append(np.mean(magns,axis=0), np.mean(absmagns)) meanpres = np.mean(press) meantemp = np.mean(temps) erraxel = np.append(np.std(axels,axis=0), np.std(absaxels)) errmagn = np.append(np.std(magns,axis=0), np.std(absmagns)) errpres = np.std(press) errtemp = np.std(temps) with tables.open_file(filename,'a') as open_file: try: table = open_file.get_node('/summary') except: class Summary(tables.IsDescription): MeanAxel = tables.Float32Col(shape=np.asarray(meanaxel).shape) MeanMagn = tables.Float32Col(shape=np.asarray(meanmagn).shape) MeanPres = tables.Float32Col() MeanTemp = tables.Float32Col() ErrAxel = tables.Float32Col(shape=np.asarray(erraxel).shape) ErrMagn = tables.Float32Col(shape=np.asarray(errmagn).shape) ErrPres = tables.Float32Col() ErrTemp = tables.Float32Col() table = open_file.create_table('/','summary',Summary) table = open_file.get_node('/summary') summary = table.row summary['MeanAxel'] = meanaxel summary['MeanMagn'] = meanmagn summary['MeanPres'] = meanpres summary['MeanTemp'] = meantemp summary['ErrAxel'] = erraxel summary['ErrMagn'] = errmagn summary['ErrPres'] = errpres summary['ErrTemp'] = errtemp summary.append() table.flush() print(f'MeanAxel: {meanaxel} m/s2, ErrAxel: {erraxel}') print(f'MeanMagn: {meanmagn} T, ErrMagn: {errmagn}') print(f'MeanPres: {meanpres:.6g} hPa , ErrPres: {errpres}') print(f'MeanTemp: {meantemp:.6g} degC, ErrTemp: {errtemp}') session.disableCalibrationPower() return [meanaxel, erraxel], [meanmagn, errmagn], [meanpres, errpres], [meantemp, errtemp]
def main(): plotSetting(plt) matplotlib.rcParams['axes.xmargin'] = 0 plt.rcParams['figure.figsize'] = [6.0, 4.5] plt.rcParams['figure.subplot.right'] = 0.9 parser = getParser() scope.AddParser(parser) (options, args) = parser.parse_args() nevents = int(options.nevents) snum = options.mbsnum if len(snum.split('/')) > 1: print('Do not use "/" in the MB serial number. Exit.') sys.exit(0) date = datetime.date.today() index = 1 prepath = f'results/QHist/{snum}/{date}/Run' path = prepath + str(index) while os.path.isdir(path): index = index + 1 path = prepath + str(index) print(f'=== File path is: {path}. ===') os.system(f'mkdir -p {path}') baseline = [0, 0] if options.filename is None: print('Requires option: --filename.') print('Quit.') sys.exit(0) datapath = f'{path}/raw' os.system(f'mkdir -p {datapath}') hdfout_pre = f'{datapath}/{options.filename}' hdfout = f'{hdfout_pre}.hdf5' baselineset = 30450 baseline = [8176, 8185] if options.measure_baselines: baseline[0] = getThreshold(parser, 0, baselineset, 0, path) baseline[1] = getThreshold(parser, 1, baselineset, 0, path) if options.preset_baseline0 is not None: baseline[0] = options.preset_baseline0 if options.preset_baseline1 is not None: baseline[1] = options.preset_baseline1 print(f'Measured baseline: {int(baseline[0])}, {int(baseline[1])}') # constants threshold_above_baseline = [9, 9] #72.59/10 # 0.1 p.e. hv = [1650, 1750] if options.hv0 is not None: hv[0] = options.hv0 if options.hv1 is not None: hv[1] = options.hv1 # ROOT ofile = TFile(f'{hdfout_pre}.root', "RECREATE") h = [ROOTHistInit(0), ROOTHistInit(1)] for channel in range(2): session = startIcebootSession(parser) session.flashConfigureFPGA("degg_fw_v0x10e.rbf.gz") session.enableHV(channel) session.setDEggHV(channel, hv[channel]) time.sleep(2) HVobs = [ session.readSloADC_HVS_Voltage(0), session.readSloADC_HVS_Voltage(1) ] print( f'Observed HV Supply Voltages for channel {channel}: {HVobs[channel]} V.' ) session.setDAC('A', baselineset) time.sleep(1) session.setDAC('B', baselineset) time.sleep(1) session.setDEggConstReadout(0, 1, 128) session.setDEggConstReadout(1, 1, 128) #session.startDEggDualChannelTrigStream( # baseline[0]+threshold_above_baseline, # baseline[1]+threshold_above_baseline) starttime = time.time() session.startDEggThreshTrigStream( channel, baseline[channel] + threshold_above_baseline[channel]) block = session.DEggReadChargeBlock(10, 15, 14 * nevents, timeout=300) difftime = time.time() - starttime session.disableHV(channel) session.close() index = 0 divpar = 100000 charges = [] #charges = [(rec.charge *1e12) for rec in block[channel] if not rec.flags] for rec in tqdm(block[channel]): if rec.flags: continue if index % divpar == 0: hdfout = f'{hdfout_pre}_{int(index/divpar)}.hdf5' with tables.open_file(hdfout, 'a') as open_file: try: table = open_file.get_node('/data') except: class Qdata(tables.IsDescription): event_id = tables.Int32Col() timestamp = tables.Int64Col() chargestamp = tables.Int64Col() channel = tables.Int32Col() hv = tables.Int32Col() threshold = tables.Int32Col() table = open_file.create_table('/', 'data', Qdata) table = open_file.get_node('/data') event = table.row event['event_id'] = index event['timestamp'] = rec.timeStamp event['chargestamp'] = rec.charge * 1e12 event['hv'] = HVobs[channel] event['channel'] = channel event['threshold'] = baseline[ channel] + threshold_above_baseline[channel] index += 1 charges.append(rec.charge * 1e12) h[channel].Fill(rec.charge * 1e12) plt.figure().patch.set_facecolor('w') plt.hist(charges, bins=880, range=(-1, 10), label=f'Channel {channel}', histtype="step", color="blue") plt.xlabel('Charge [pC]', ha='right', x=1.0) plt.ylabel('Entries', ha='right', y=1.0) plt.xlim(-1, 5) plt.legend( title= f'HV: {HVobs[channel]:.2f} V \nThresh: {int(baseline[channel])}+{int(threshold_above_baseline[channel])} LSB \n#Events: {len(charges)} \nDuration: {difftime:.2f} sec' ) print(len(charges)) plt.savefig(f'{path}/figure{channel}.pdf') h[channel].Write()
def main(parser, path='.'): (options, args) = parser.parse_args() hvbnums = (options.hvbnums).split(',') session = startIcebootSession(parser) session.setDEggHV(0, 0) session.setDEggHV(1, 0) time.sleep(1) HVsettings = np.arange(0, 1500, 20) datapath = f'{path}/raw' for channel in range(2): hvvobs0, hvcobs0, hvverr0, hvcerr0 = getLists(session, HVsettings, channel, hvbnums, datapath) plotSetting(plt) plt.rcParams['figure.figsize'] = [8.0, 7.0] plt.rcParams['figure.subplot.right'] = 0.9 #fig, ax1 = plt.subplots() fig = plt.figure() spec = gridspec.GridSpec(ncols=1, nrows=2, height_ratios=[3, 1], hspace=0.05) ax1 = fig.add_subplot(spec[0]) axr = fig.add_subplot(spec[1]) ## top plot #ax1.set_xlabel('Set Value [V]', ha='right', x=1.0) ax1.set_ylabel('Observed Voltage $V_\mathrm{obs}$ [V]', ha='right', y=1.0) ax1.errorbar(HVsettings, hvvobs0, hvverr0, fmt='o-', color='black', label=f'Ch{channel} voltage') ax1.set_ylim(0, 2000) ax1.tick_params(labelbottom=False) ax2 = ax1.twinx() ax2.set_ylabel('Observed Current $I_\mathrm{obs}$ [$\mu$A]', ha='right', y=1.0, color='red') ax2.errorbar(HVsettings, hvcobs0, hvcerr0, fmt='o-', color='red', label=f'Ch{channel} current') ax2.set_ylim(0, 40) ax2.spines['right'].set_color('red') ax2.tick_params(which='both', axis='y', colors='red') handler1, label1 = ax1.get_legend_handles_labels() handler2, label2 = ax2.get_legend_handles_labels() ax1.legend(handler1 + handler2, label1 + label2) ## bottom plot axr.set_xlabel('Set Voltage $V_\mathrm{set}$ [V]', ha='right', x=1.0) axr.set_ylabel( r'$\dfrac{V_\mathrm{obs}-V_\mathrm{set}}{V_\mathrm{set}}$ [%]', ha='right', y=1.0) HVsettingNonZero = HVsettings HVsettingNonZero[0] = 1 print(HVsettingNonZero) diffhv = (np.array(hvvobs0) - HVsettings) / HVsettingNonZero * 100 axr.errorbar(HVsettings, diffhv, hvverr0, fmt='o-', color='black') axr.set_ylim(-7, 7) if options.b: fig.canvas.draw() fig.canvas.flush_events() plt.savefig(f'{datapath}/hv{hvbnums[channel]}_{channel}.pdf') session.setDEggHV(0, 0) session.setDEggHV(1, 0) session.disableHV(0) session.disableHV(1) return [ f'hv{hvbnums[0]}_0.pdf', 'Comparison between set and observed HV values for channel 0.', f'hv{hvbnums[1]}_1.pdf', 'Comparison between set and observed HV values for channel 1.' ]
def main(parser): (options, args) = parser.parse_args() session = startIcebootSession(parser) ''' Readout the slow ADC values: ch 0: +1V1 Current Monitor (mA) ch 1: +1V35 Current Monitor (mA) ch 2: +1V8 Current Monitor (mA) ch 3: +2V5 Current Monitor (mA) ch 4: +3V3 Current Monitor (mA) ch 5: +1V8_A Voltage Monitor (V) ch 6: Light Sensor output (mV) ch 7: Temperature Sensor (degC) ch 8: HV 0 Voltage Monitor (V) ch 9: HV 0 Current Monitor (muA) ch10: HV 1 Voltage Monitor (V) ch11: HV 1 Current Monitor (muA) ch12: +1V1 Voltage Monitor (V) ch13: +1V35 Voltage Monitor (V) ch14: +2V5 Voltage Monitor (V) ch15: +3V3 Voltage Monitor (V) ''' citems = [ '+1V1 Current', '+1V35 Current', '+1V8 Current', '+2V5 Current', '+3V3 Current', '+1V8\_A Voltage', 'Light Sensor', 'Temperature', 'HV ch0 Voltage', 'HV ch0 Current', 'HV ch1 Voltage', 'HV ch1 Current', '+1V1 Voltage', '+1V35 Voltage', '+2V5 Voltage', '+3V3 Voltage', 'Pressure' ] units = [ '~mA', '~mA', '~mA', '~mA', '~mA', '~V', '~mV', '${}^{\circ}$C', '~V', '~$\mu$A', '~V', '~$\mu$A', '~V', '~V', '~V', '~V', '~hPa' ] #targetMax = [500,500,500,500,500,1.9,5000,60,2000,100,2000,100,1.2,1.45,2.6,3.4,2000] #targetMin = [ 0, 0, 0, 0, 0,1.7, 0,10, 0, 0, 0, 0,1.0,1.25,2.4,3.2, 500] targetMax = [ 1000, 500, 500, 500, 500, 1.9, 5000, 35, int(options.hvv) + 5, 200, int(options.hvv) + 5, 200, 1.2, 1.45, 2.6, 3.4, 1200 ] targetMin = [ 10, 10, 10, 10, 10, 1.7, 0, 5, int(options.hvv) - 5, 0, int(options.hvv) - 5, 0, 1.0, 1.25, 2.4, 3.2, 900 ] if options.degg: targetMax[16] = 850 targetMin[16] = 300 outputs = [] outbool = [] session.setDEggHV(0, int(options.hvv)) session.setDEggHV(1, int(options.hvv)) session.enableHV(0) session.enableHV(1) time.sleep(5) for ch in range(17): output = 0 if ch == 16: try: output = session.readPressure() except IOError: output = -1 else: output = readSloAdcChannel(session, ch) outputs.append(output) value = 0 if isinstance(output, float): if targetMin[ch] <= float(output) <= targetMax[ch]: value = 1 print( f'{targetMin[ch]} <= {float(output)} <= {targetMax[ch]} : {value}' ) else: print(f'{targetMin[ch]} <= {output} <= {targetMax[ch]} : {value}') outbool.append(value) print(f'output value: {outbool}') session.disableHV(0) session.disableHV(1) return targetMin, targetMax, outputs, outbool, citems, units
def main(parser, inchannel=-1, dacvalue=-1, path='.', feplsr=0, threshold=0, testRun=0): (options, args) = parser.parse_args() print('Start the session.') isLoaded = 0 while not isLoaded: try: session = startIcebootSession(parser) except: print("Loading failed. Try again...") else: isLoaded = 1 trial = 0 while session.fpgaVersion() == 65535: session.close() print('Session closed.') loadFPGA(parser) trial = trial + 1 print(f'Re-start the session. Trial {trial}...') session = startIcebootSession(parser) nevents = int(options.nevents) if testRun > 0: nevents = testRun channel = 0 if inchannel > -1: channel = inchannel else: channel = int(options.channel) setchannel = 'A' if channel == 1: setchannel = 'B' if (len(options.dacSettings) == 0) and (dacvalue > -1): session.setDAC(setchannel, dacvalue) time.sleep(0.1) setdacvalue = 0 if len(options.dacSettings) > 0: for setting in options.dacSettings: setdacvalue = setting[1] else: setdacvalue = dacvalue # Number of samples must be divisible by 4 nSamples = (int(options.samples) / 4) * 4 if (nSamples < 16): print("Number of samples must be at least 16") sys.exit(1) session.setDEggConstReadout(channel, 2, int(nSamples)) plt.ion() plt.show() fig = plt.figure() ax = fig.add_subplot(111) plt.xlabel("Waveform Bin", ha='right', x=1.0) plt.ylabel("ADC Count", ha='right', y=1.0) line = None HVobs = 0 if int(options.hvv) > 0: if int(nSamples) > 128: session.setDEggConstReadout(channel, 4, int(nSamples)) session.enableHV(channel) session.setDEggHV(channel, int(options.hvv)) time.sleep(1) HVobs = session.readSloADC_HVS_Voltage(channel) print(f'Observed HV Supply Voltage for channel {channel}: {HVobs} V.') if feplsr > 0: session.setDAC(setchannel, 30000) if int(nSamples) > 128: session.setDEggConstReadout(channel, 4, int(nSamples)) session.setDAC('D', feplsr) time.sleep(0.1) session.enableFEPulser(channel, 4) mode = beginWFstream(session, options, channel, testRun, threshold, feplsr) # define signal handler to end the stream on CTRL-C def signal_handler(*args): print('\nEnding waveform stream...') session.endStream() session.disableFEPulser(channel) print('Done') sys.exit(1) signal.signal(signal.SIGINT, signal_handler) odir = f'{path}/raw' if dacvalue > -1: filename = f'{odir}/dacscan_ch{channel}_{dacvalue}.hdf5' elif feplsr > 0: filename = f'{odir}/plscalib_ch{channel}_{feplsr}.hdf5' elif options.filename is None: raise ValueError('Please supply a filename to save the data to!') else: if not os.path.isdir(odir): os.system(f'mkdir -p {odir}') filename = f'{odir}/{options.filename}' # Prepare hdf5 file if not os.path.isfile(filename): class Config(tables.IsDescription): threshold = tables.Int32Col() mainboard = tables.StringCol(10) triggermode = tables.StringCol(10) flashid = tables.StringCol(len(session.flashID())) fpgaVersion = tables.Int32Col() MCUVersion = tables.Int32Col() baselinedac = tables.Int32Col() with tables.open_file(filename, 'w') as open_file: table = open_file.create_table('/', 'config', Config) table = open_file.get_node('/config') config = table.row config['mainboard'] = str(options.mbsnum) config['flashid'] = str(session.flashID()) config['fpgaVersion'] = session.fpgaVersion() config['MCUVersion'] = session.softwareVersion() config['triggermode'] = mode config['baselinedac'] = setdacvalue config.append() table.flush() else: print("File already exists! Try again. Exit.") return i = 0 index = 0 while (True): print('\rEvent: %d' % i, end='') try: readout = parseTestWaveform(session.readWFMFromStream()) except IOError: print('Timeout! Ending waveform stream and exiting') session.endStream() index = index + 1 mode = beginWFstream(session, options, channel, testRun, threshold, feplsr) continue # Check for timeout if readout is None: continue if options.bsub: applyPatternSubtraction(readout) wf = readout["waveform"] # Fix for 0x6a firmware if len(wf) != nSamples: continue xdata = [x for x in range(len(wf))] timestamp = readout["timestamp"] pc_time = time.time() tot = readout["thresholdFlags"] # Write to hdf5 file with tables.open_file(filename, 'a') as open_file: try: table = open_file.get_node('/data') except: class Event(tables.IsDescription): event_id = tables.Int32Col() time = tables.Float32Col(shape=np.asarray(xdata).shape) waveform = tables.Float32Col(shape=np.asarray(wf).shape) timestamp = tables.Int64Col() pc_time = tables.Float32Col() thresholdFlags = tables.Int32Col( shape=np.asarray(xdata).shape) temperature = tables.Float32Col() hv = tables.Float32Col() channel = tables.Int32Col() i_1V1 = tables.Float32Col() i_1V35 = tables.Float32Col() i_1V8 = tables.Float32Col() i_2V5 = tables.Float32Col() i_3V3 = tables.Float32Col() v_1V1 = tables.Float32Col() v_1V35 = tables.Float32Col() v_1V8 = tables.Float32Col() v_2V5 = tables.Float32Col() v_3V3 = tables.Float32Col() table = open_file.create_table('/', 'data', Event) table = open_file.get_node('/data') event = table.row event['event_id'] = i event['time'] = np.asarray(xdata, dtype=np.float32) event['waveform'] = np.asarray(wf, dtype=np.float32) event['timestamp'] = timestamp event['pc_time'] = pc_time event['thresholdFlags'] = tot event['temperature'] = readSloAdcChannel(session, 7) event['channel'] = channel event['hv'] = session.readSloADC_HVS_Voltage(channel) event['i_1V1'] = readSloAdcChannel(session, 0) event['i_1V35'] = readSloAdcChannel(session, 1) event['i_1V8'] = readSloAdcChannel(session, 2) event['i_2V5'] = readSloAdcChannel(session, 3) event['i_3V3'] = readSloAdcChannel(session, 4) event['v_1V1'] = readSloAdcChannel(session, 12) event['v_1V35'] = readSloAdcChannel(session, 13) event['v_1V8'] = readSloAdcChannel(session, 5) event['v_2V5'] = readSloAdcChannel(session, 14) event['v_3V3'] = readSloAdcChannel(session, 15) event.append() table.flush() i += 1 if not line: line, = ax.plot(xdata, wf, 'r-') else: line.set_ydata(wf) if (options.adcMin is None or options.adcRange is None): wfrange = (max(wf) - min(wf)) plt.axis( [0, len(wf), max(wf) - wfrange * 1.2, min(wf) + wfrange * 1.2]) else: plt.axis([ 0, len(wf), int(options.adcMin), int(options.adcMin) + int(options.adcRange) ]) if options.b: fig.canvas.draw() fig.canvas.flush_events() #plt.pause(0.001) time.sleep(0.001) if i >= nevents: print("\nReached end of run - exiting...") session.endStream() session.disableFEPulser(channel) #session.disableHV(channel) #session.setDEggHV(channel,0) session.close() print('Session closed.') print('Done') time.sleep(1.0) break signal.signal(signal.SIGINT, signal.SIG_IGN) plt.close() time.sleep(0.5) return