def test4(): '''Test the measure_multiple function in sp.C, which trys to locate the signal by seaching the maximum and use the period info to find others. It's used used only for calibration.''' s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5) # data1 = s1.generate_adcDataBuf() # ((ctypes.c_float * self.nSamples) * self.nAdcCh)() data1 = (s1.ANALYSIS_WAVEFORM_BASE_TYPE * (s1.nSamples * s1.nAdcCh))() sp = SignalProcessor() sp.fltParam.clear() for x in [30, 50, 200, -1]: sp.fltParam.push_back(x) # sp.IO_adcData = data1 # sp.allocAdcData() sp.CF_chan_en.clear() sp.IO_mAvg.clear() for i in range(20): sp.CF_chan_en.push_back(1) sp.IO_mAvg.push_back(0.) inRoot = 'data/fpgaLin/Feb28t3_data_0.root' fout1 = TFile(inRoot, 'read') tree1 = fout1.Get('tree1') tree1.SetBranchAddress('adc', data1) N = 2000 # 2500 Hz for ievt in range(1): tree1.GetEntry(ievt) sp.measure_multiple(data1, N) # print sp.IO_mAvg.size() print ievt, [sp.IO_mAvg[i] for i in range(20)]
def readSignal4b(argX, runPattern='.*_data_(\d+).root'): '''For Mar08 data processing, take the decay time from configuration file''' args = argX.split(';') inRoot = args[0] oTag = args[1] print "Starting", inRoot, oTag ### pulse test dV = -1 dvPattern = '.*_(\d+)mV_f\d+.root' m = re.match(dvPattern, inRoot) if m: try: dV = int(m.group(1)) except ValueError: print "Failed to get the dV in file:", iRoot ### data check run = -1 if runPattern is not None: m = re.match(runPattern, inRoot) if m: try: run = int(m.group(1)) except ValueError: print "Run number not exatracted for file", iRoot return else: if dV < 0: print "Run number not exatracted for file", iRoot return sp1 = SignalProcessor() # apply_config(sp1, 'Hydrogen') apply_config(sp1, 'Hydrogen/c3') fin1 = TFile(inRoot, 'read') tree1 = fin1.Get('tree1') tree2 = 0 outRoot = os.path.dirname(inRoot) + '/' + oTag + os.path.basename(inRoot) tf = sp1.processFile(tree1, tree2, outRoot, run) tf.Close()
def test5(): '''Test the measure_multipleX function in sp.C, which trys to locate the signal by seaching the maximum and use the period info to find others. It's used used only for calibration.''' s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5) data1 = (s1.ANALYSIS_WAVEFORM_BASE_TYPE * (s1.nSamples * s1.nAdcCh))() sp = SignalProcessor() sp.fltParam.clear() P = 1. / 0.006 / 2500 / 1024 * 5000000 for x in [30, 50, 200, P]: sp.fltParam.push_back(x) sp.CF_chan_en.clear() sp.IO_mAvg.clear() for i in range(20): sp.CF_chan_en.push_back(1) sp.IO_mAvg.push_back(0.) # inRoot = 'data/fpgaLin/Feb28t3_data_0.root' inRoot = 'data/fpgaLin/Mar05T1a_data_0.root' fout1 = TFile(inRoot, 'read') tree1 = fout1.Get('tree1') tree1.SetBranchAddress('adc', data1) N = 2000 # 2500 Hz Vs = array('f', [0] * (20 * 8)) # for i in range(20*8) for ievt in range(3): tree1.GetEntry(ievt) sp.measure_multipleX(data1, N, Vs) for i in range(20): print i, ':', for j in range(8): # print i*8+j, print Vs[i * 8 + j], print
def __init__(self, cd): threading.Thread.__init__(self) self.cd = cd self.tx_qs = None self.rx_qs = None self.on = True self.mask = [0] * cd.nCh self.nSig = 3 ### this copy of sensorVcodes is used to save the best value find so far self.sensorVcodes = [[v for v in cd.sensorVcodes[i]] for i in range(cd.nCh)] # self.bestConfigFile = 'current_best_config.json' self.bestConfigFile = 'C3_tt6_config.json' self.retBest = [0.] * cd.nAdcCh ### for data taking self.sc = None ### plotting self.axs = None self.plot_x = None self.pltCnt = 0 self.pltN = 20 self.sp = SignalProcessor() apply_config(self.sp, 'Helium') self.NVAL = 8 s1 = self.cd.sigproc self.data1 = (s1.ANALYSIS_WAVEFORM_BASE_TYPE * (s1.nSamples * s1.nAdcCh))() self.ret1 = array.array('f', [0] * s1.nAdcCh) self.par1 = array.array('f', [0] * (self.cd.nCh * len(self.cd.inputVs))) self.t_values = array.array('f', [0] * (s1.nAdcCh * self.NVAL)) self.keepAllData = False self.saveT0 = -1 self.T = array.array('i', [0]) self.Tag = array.array('i', [0])
def test1(): s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5) # data1 = s1.generate_adcDataBuf() # data2 = s1.generate_sdmDataBuf() # data1 = ((s1.ANALYSIS_WAVEFORM_BASE_TYPE * s1.nSamples) * s1.nAdcCh)() data1 = (s1.ANALYSIS_WAVEFORM_BASE_TYPE * (s1.nSamples * s1.nAdcCh))() # data1 = ((s1.ANALYSIS_WAVEFORM_BASE_TYPE * s1.nSamples) * s1.nAdcCh)() # print len(data1[0]) print type(data1) # print type(byref(data1[0])) print type(pointer(data1)) data1 = array('f', [0] * (16384 * 20)) inRoot = 'data/fpgaLin/Feb09b_data_581.root' fout1 = TFile(inRoot, 'read') tree1 = fout1.Get('tree1') tree1.SetBranchAddress('adc', data1) i = 37 tree1.GetEntry(i) # print data1[3] sp1 = SignalProcessor() sp1.nAdcCh = 20 # sp1.sRanges.clear() # sp1.sRanges.push_back((0,3000)) # sp1.sRanges.push_back((3000,8000)) # sp1.sRanges.push_back((8000,15000)) # sp1.measure_pulse(byref(data1)) # sp1.measure_pulse(pointer(data1)) # sp1.measure_pulse(data1) print sp1.nMeasParam f = 1000 a = 16384 * 0.2 * f * 0.000001 print 16384 * 0.2 * f * 0.000001 n1 = int(1 / (0.2 * f * 0.000001)) print n1 sp1.sRanges.clear() ip = 0 while ip + n1 < sp1.nSamples: iq = ip + n1 # if iq > sp1.nSamples: iq = sp1.nSamples # a = (ip, iq) sp1.sRanges.push_back((ip, iq)) ip = iq # sp1.measure_pulse(data1) for i in range(sp1.nAdcCh): # print i, sp1.measParam[sp1.nMeasParam*i], sp1.measParam[sp1.nMeasParam*i+1], sp1.measParam[sp1.nMeasParam*i+2], sp1.measParam[sp1.nMeasParam*i+3] print i, for j in range(sp1.nMeasParam): print sp1.measParam[sp1.nMeasParam * i + j], print sp1.test2()
def test3a(): '''To test the event reconstruction''' data1 = array('f', [0] * (16384 * 20)) inRoot = 'data/fpgaLin/Feb27a_data_40.root' fout1 = TFile(inRoot, 'read') tree1 = fout1.Get('tree1') tree1.SetBranchAddress('adc', data1) i = 81 tree1.GetEntry(i) ### here comes the constructor sp1 = SignalProcessor() sp1.nAdcCh = 20 sp1.IO_adcData = data1 sp1.fltParam.clear() for x in [30, 100, 300, -1]: sp1.fltParam.push_back(x) thre = [0.001] * sp1.nAdcCh thre[19] = 0.02 sp1.ch_thre.clear() for x in thre: sp1.ch_thre.push_back(x) sp1.reco() Unit = 0.2 h3 = TH3F('h3', 'h3;x [cm];y [cm];t [ps]', 9, -1.8, 1.8, 9, -1.8, 1.8, 100, -1. * Unit * sp1.CF_uSize, Unit * sp1.CF_dSize) # for e in sp1.IO_evts: for e in sp1.get_events(): print e.trigID, len(e.sigs) h3.Reset() showEvent(e, h3, h2) h3.Draw('BOX2Z') waitRootCmdX() # for j in range(sp1.nAdcCh): print j, e.sigs[j].im # d = [e.sigs[j].Q for j in range(sp1.nAdcCh)] # print d # showA(d) e1 = sp1.IO_evts[0] print dir(e1) print dir(e1.sigs[0]) print '****', e1.sigs[0].im showEvents(sp1.IO_evts)
def check_calib(): sp1 = SignalProcessor() sp1.nSamples = 16384 sp1.nAdcCh = 20 ### setup the calibration file fin1 = TFile('fout_calib.root') sp1.corr_spine.clear() sp1.corr_TF1.clear() sp1.corr_spine.reserve(sp1.nAdcCh) sp1.corr_TF1.reserve(sp1.nAdcCh) for i in range(sp1.nAdcCh - 1): sp1.corr_spine.push_back(fin1.Get('gr_calib_ch' + str(i))) sp1.corr_TF1.push_back(sp1.corr_spine[i].GetFunction('pol1')) ## run a test for x in sp1.corr_spine[5].GetX(): t = 1 print sp1.correction(1, x) * t, sp1.correction( 1, x, 1) * t, '|', sp1.correction(5, x) * t, sp1.correction( 5, x, 1) * t
def overlayFilters(inRoot): sp1 = SignalProcessor() sp1.nSamples = 16384 sp1.nAdcCh = 20 sp1.fltParam.clear() sp1.x_thre = 0.1 # sp3a for x in [30, 15, 50, 2500]: sp1.fltParam.push_back(x) # for x in [50, 5, 15, 2500]: sp1.fltParam.push_back(x) # sp3b # for x in [50, 500, 700, 2500]: sp1.fltParam.push_back(x) run = int(inRoot.rstrip('.root').split('_')[-1]) data1 = array('f', [0] * (sp1.nSamples * sp1.nAdcCh)) dataT = array('i', [0]) fin1 = TFile(inRoot, 'read') tree1 = fin1.Get('tree1') tree1.SetBranchAddress('adc', data1) tree1.SetBranchAddress('T', dataT) oTag = 'flt_' fout1 = TFile( os.path.dirname(inRoot) + '/' + oTag + os.path.basename(inRoot), 'recreate') tup1 = TNtuple('flt', "filter analysis tuple", 'run:evt:ch:ip:V') NPOINTS = 200 ch = 19 NEVT = tree1.GetEntries() for ievt in range(NEVT): tree1.GetEntry(ievt) sp1.measure_pulse2(data1, ch) for ip in range(NPOINTS): tup1.Fill(run, ievt, ch, ip, sp1.scrAry[ip]) tup1.Write() fout1.Close()
def readSignal(inRoot, outText, freq=1000): sp1 = SignalProcessor() sp1.nSamples = 16384 sp1.nAdcCh = 20 sp1.fltParam.clear() for x in [50, 150, 200, -1.]: sp1.fltParam.push_back(x) n1 = int(1 / (0.2 * freq * 0.000001)) sp1.sRanges.clear() ip = 0 dn = 2500 % n1 ## 2500 is the expected position of the signal # while ip+dn < sp1.nSamples: # sp1.sRanges.push_back((ip, min(ip+n1, sp1.nSamples))) # ip += n1 sp1.sRanges.push_back((0, 400)) # while ip+n1<sp1.nSamples: # sp1.sRanges.push_back((ip, ip+n1)) # ip += n1 data1 = array('f', [0] * (sp1.nSamples * sp1.nAdcCh)) # inRoot = 'data/fpgaLin/Jan21b_C2_100mV_f1000.root' fout1 = TFile(inRoot, 'read') tree1 = fout1.Get('tree1') tree1.SetBranchAddress('adc', data1) with open(outText, 'w') as fout: fout.write(':'.join( ['sID/I', 'ch/I', 'B/F', 'dB/F', 'im/I', 'idx/I', 'A/F'])) for ievt in range(tree1.GetEntries()): tree1.GetEntry(ievt) sp1.measure_pulse(data1) for i in range(sp1.nAdcCh): itmp = sp1.nMeasParam * i for j in range(sp1.nMeasParam / 2 - 1): fout.write('\n' + ' '.join([ str(ievt), str(i), str(sp1.measParam[itmp]), str(sp1.measParam[itmp + 1]), str(j), str(int(sp1.measParam[itmp + 2 * j + 2])), str(sp1.measParam[itmp + 2 * j + 3]) ]))
def check1b(argX, chs=None, nEvt=None, runPattern='.*_data_(\d+).root', step2=False): '''Use various filters to extract the results''' args = argX.split(';') inRoot = args[0] oTag = args[1] outRoot = os.path.dirname(inRoot) + '/' + oTag + os.path.basename(inRoot) # outRoot = inRoot.rstrip('.root')+oTag+'.root' print "Starting", inRoot, '->', outRoot if os.path.exists(outRoot): print "has:", inRoot, outRoot return run = -1 if runPattern is not None: m = re.match(runPattern, inRoot) if m: run = int(m.group(1)) else: print "Run number not exatracted for file", iRoot sp1 = SignalProcessor() sp1.nSamples = 16384 sp1.nAdcCh = 20 testPulseOnly = False ### look for signal peak in the expected regions only if testPulseOnly: freq = 1000 n1 = int(1 / (0.2 * freq * 0.000001)) sp1.sRanges.clear() ip = 0 dn = 2500 % n1 ## 2500 is the expected position of the signal while ip + dn < sp1.nSamples: sp1.sRanges.push_back((ip, min(ip + n1, sp1.nSamples))) ip += n1 ### for storing data data1 = array('f', [0] * (sp1.nSamples * sp1.nAdcCh)) dataT = array('i', [0]) fin1 = TFile(inRoot, 'read') tree1 = fin1.Get('tree1') tree1.SetBranchAddress('adc', data1) tree1.SetBranchAddress('T', dataT) if nEvt is None: nEvt = tree1.GetEntries() if chs is None: chs = range(sp1.nAdcCh) ch = chs[0] if len(chs) == 1 else -1 fout1 = TFile(outRoot, 'recreate') # tup1 = TNtuple('tup1',"filter analysis tuple",'evt:fR:fW:ich:b:bE:im:idx:A') tup1 = TNtuple('tup1', "filter analysis tuple", 'run:evt:fR:fW:ch:B:dB:iA:imean:imax:A:w0:w1:w2:T') chs = [19] rRange = range(10, 200, 20) wRange = range(50, 300, 20) ### start processing INTV = 1000 if nEvt > 10000 else max(nEvt / 10, 1) for ievt in range(nEvt): tree1.GetEntry(ievt) if ievt % INTV == 0: print ievt, ' events processed' for R in rRange: for W in wRange: sp1.fltParam.clear() for x in [500, R, W, 2500.]: sp1.fltParam.push_back(x) sp1.measure_pulse2(data1, ch) for ich in chs: ss = sp1.signals[ich] iA = 0 for ii in ss: tup1.Fill(run, ievt, R, W, ich, 0, 0, iA, ii.im, ii.idx, ii.Q, ii.w0, ii.w1, ii.w2, dataT[0] - 788947200) iA += 1 tup1.Write() ### save the ENC results tup2 = TNtuple('tup2', "filter analysis tuple enc", 'ich:fR:fW:m:mE:sigma:sigmaE:fq:fStatus') for R in rRange: for W in wRange: for ich in chs: gDirectory.Delete('h1*') tup1.Draw( 'A>>h1', 'int(fW)=={0:d}&&int(fR)=={1:d}&&ch=={2:d}'.format( W, R, ich), 'goff') h1 = gDirectory.Get('h1') r = h1.Fit('gaus', 'S0') fun1 = h1.GetFunction('gaus') tup2.Fill(ich, R, W, fun1.GetParameter(1), fun1.GetParError(1), fun1.GetParameter(2), fun1.GetParError(2), r.Prob(), r.Status()) tup2.Write() fout1.Close()
def readSignal2(inRoot, oTag=None, freq=1000, runPattern='.*_data_(\d+).root'): if oTag is None: oTag = readSignal2.oTag print "Starting", inRoot, oTag # return run = -1 if runPattern is not None: m = re.match(runPattern, inRoot) if m: run = int(m.group(1)) print run sp1 = SignalProcessor() sp1.nSamples = 16384 sp1.nAdcCh = 20 sp1.fltParam.clear() for x in [50, 150, 250, 2500]: sp1.fltParam.push_back(x) # for x in [50, 150, 200, -1.]: sp1.fltParam.push_back(x) # for x in [50, 150, 200, 2500]: sp1.fltParam.push_back(x) # for x in [50, 15, 50, 2500]: sp1.fltParam.push_back(x) # for x in [500, 450, 800, 2500]: sp1.fltParam.push_back(x) n1 = int(1 / (0.2 * freq * 0.000001)) sp1.sRanges.clear() ip = 0 dn = 2500 % n1 ## 2500 is the expected position of the signal # while ip+dn < sp1.nSamples: # sp1.sRanges.push_back((ip, min(ip+n1, sp1.nSamples))) # ip += n1 # sp1.sRanges.push_back((0, 400)) sp1.sRanges.push_back((0, 3000)) data1 = array('f', [0] * (sp1.nSamples * sp1.nAdcCh)) dataT = array('i', [0]) fin1 = TFile(inRoot, 'read') tree1 = fin1.Get('tree1') tree1.SetBranchAddress('adc', data1) tree1.SetBranchAddress('T', dataT) fout1 = TFile( os.path.dirname(inRoot) + '/' + oTag + os.path.basename(inRoot), 'recreate') tup1 = TNtuple('tup1', "filter analysis tuple", 'run:sID:ch:B:dB:im:idx:A:T') for ievt in range(tree1.GetEntries()): tree1.GetEntry(ievt) sp1.measure_pulse(data1) for i in range(sp1.nAdcCh): itmp = sp1.nMeasParam * i for j in range(sp1.nMeasParam / 2 - 1): tup1.Fill(run, ievt, i, sp1.measParam[itmp], sp1.measParam[itmp + 1], j, sp1.measParam[itmp + 2 * j + 2], sp1.measParam[itmp + 2 * j + 3], dataT[0] - 788947200) tup1.Write() fout1.Close()
def test3(): '''To test the event reconstruction''' gStyle.SetOptStat(0) gROOT.ProcessLine('.L Pal.C') gStyle.SetPalette(55) gStyle.SetPadRightMargin(0.15) # from ROOT import Pal2 # Pal2() data1 = array('f', [0] * (16384 * 20)) # inRoot = 'data/fpgaLin/Feb27a_data_40.root' inRoot = 'data/fpgaLin/Mar08D1a/Mar08D1a_data_70.root' fout1 = TFile(inRoot, 'read') tree1 = fout1.Get('tree1') tree1.SetBranchAddress('adc', data1) ### here comes the constructor sp1 = SignalProcessor() # sp1.nAdcCh=20 sp1.IO_adcData = data1 apply_config(sp1, 'Hydrogen') # sp1.fltParam.clear() # for x in [30, 100, 300, -1]: sp1.fltParam.push_back(x) # thre = [0.001]*sp1.nAdcCh # thre[19] = 0.02 # # sp1.ch_thre.clear() # for x in thre: sp1.ch_thre.push_back(x) Unit = 0.2 h3 = TH3F('h3', 'h3;x [cm];y [cm];t [ps]', 9, -1.8, 1.8, 9, -1.8, 1.8, 100, -1. * Unit * sp1.CF_uSize, Unit * sp1.CF_dSize) h2 = TH2F('h2', 'h2;t [ps];Channel;Q', (sp1.CF_uSize + sp1.CF_dSize), -1. * Unit * sp1.CF_uSize, Unit * sp1.CF_dSize, 20, 0, 20) cx = TCanvas('cx', 'cx', 1500, 700) cx.Divide(2, 1) for i in range(tree1.GetEntries()): tree1.GetEntry(i) sp1.reco() for ich in range(sp1.nAdcCh): for s in sp1.signals[ich]: print ich, ':', s.idx, s.im, s.Q, s.w0, s.w1, s.w2 for e in sp1.IO_evts: print e.trigID, len(e.sigs) h3.Reset() h2.Reset() showEvent(e, h3, h2) cx.cd(1) h3.Draw('BOX2') cx.cd(2) t = h2.GetBinContent(h2.GetMaximumBin()) * 1.06 h2.GetZaxis().SetRangeUser(-0.05 * t, t * 0.95) h2.Draw('colz') # h2.Draw('axis same') cx.cd(0) waitRootCmdX()
def readSignal3(argX, runPattern='.*_data_(\d+).root'): args = argX.split(';') inRoot = args[0] oTag = args[1] print "Starting", inRoot, oTag ### pulse test dV = -1 dvPattern = '.*_(\d+)mV_f\d+.root' m = re.match(dvPattern, inRoot) if m: try: dV = int(m.group(1)) except ValueError: print "Failed to get the dV in file:", iRoot ### data check run = -1 if runPattern is not None: m = re.match(runPattern, inRoot) if m: try: run = int(m.group(1)) except ValueError: print "Run number not exatracted for file", iRoot return else: if dV < 0: print "Run number not exatracted for file", iRoot return sp1 = SignalProcessor() sp1.nSamples = 16384 sp1.nAdcCh = 20 sp1.fltParam.clear() # for i in range(sp1.nAdcCh): sp1.ch_thre[i] = 0.002 # sp1.ch_thre[19] = 0.05 thre = [0.002] * sp1.nAdcCh thre[2] = 0.0008 thre[4] = 0.001 thre[6] = 0.001 thre[7] = 0.001 thre[10] = 0.001 thre[11] = 0.0007 thre[14] = 0.0007 thre[17] = 0.001 thre[19] = 0.05 sp1.ch_thre.clear() for x in thre: sp1.ch_thre.push_back(x) # sp3a # for x in [30, 15, 50, 2500]: sp1.fltParam.push_back(x) # flt = [50, 50, 250, 2500] # flt = [50, 50, 150, -1] flt = [50, 100, 500, -1] # dp01a # flt = [30, 250, 350, 2500] # flt = [50, 10, 150, 2500] # flt = [50, 500, 600, 2500] # flt = [50, 5, 100, 2500] for x in flt: sp1.fltParam.push_back(x) # sp3b # for x in [50, 500, 700, 2500]: sp1.fltParam.push_back(x) data1 = array('f', [0] * (sp1.nSamples * sp1.nAdcCh)) dataT = array('i', [0]) fin1 = TFile(inRoot, 'read') tree1 = fin1.Get('tree1') tree1.SetBranchAddress('adc', data1) tree1.SetBranchAddress('T', dataT) fout1 = TFile( os.path.dirname(inRoot) + '/' + oTag + os.path.basename(inRoot), 'recreate') tup1 = TNtuple('tup1', "filter analysis tuple", 'run:evt:ch:B:dB:iA:imean:imax:A:w0:w1:w2:T:dV') a = TObjString("filter:" + str(flt)) a.Write('Info') ### for background subtraction be1 = bkgEstimator() # chs = [19] chs = None for ievt in range(tree1.GetEntries()): tree1.GetEntry(ievt) # apply_wiener_filter(data1, ich=19) # be1.correct(data1, 19) sp1.measure_pulse2(data1) for ich in range(sp1.nAdcCh): if chs and (ich not in chs): continue # print "processing channle", ich ss = sp1.signals[ich] itmp = sp1.nMeasParam * ich iA = 0 for ii in ss: tup1.Fill(run, ievt, ich, sp1.measParam[itmp], sp1.measParam[itmp + 1], iA, ii.im, ii.idx, ii.Q, ii.w0, ii.w1, ii.w2, dataT[0] - 788947200, dV) iA += 1 tup1.Write() fout1.Close()
def readSignal4c(argX, runPattern='.*_data_(\d+).root'): '''Based on readSignal4b; for single channel. And IO is from readSignal3''' args = argX.split(';') inRoot = args[0] oTag = args[1] print "Starting", inRoot, oTag ### pulse test dV = -1 dvPattern = '.*_(\d+)mV_f\d+.root' m = re.match(dvPattern, inRoot) if m: try: dV = int(m.group(1)) except ValueError: print "Failed to get the dV in file:", iRoot ### data check run = -1 if runPattern is not None: m = re.match(runPattern, inRoot) if m: try: run = int(m.group(1)) except ValueError: print "Run number not exatracted for file", iRoot return else: if dV < 0: print "Run number not exatracted for file", iRoot return sp1 = SignalProcessor() apply_config(sp1, 'Hydrogen') ### IO configuration data1 = array('f', [0] * (sp1.nSamples * sp1.nAdcCh)) dataT = array('i', [0]) fin1 = TFile(inRoot, 'read') tree1 = fin1.Get('tree1') tree1.SetBranchAddress('adc', data1) tree1.SetBranchAddress('T', dataT) fout1 = TFile( os.path.dirname(inRoot) + '/' + oTag + os.path.basename(inRoot), 'recreate') tup1 = TNtuple('tup1', "filter analysis tuple", 'run:evt:ch:B:dB:iA:imean:imax:A:w0:w1:w2:T:dV') a = TObjString("filter:" + str(sp1.fltParam)) a.Write('Info') chs = [0] chx = chs[0] if (chs and len(chs) == 1) else -1 for ievt in range(tree1.GetEntries()): tree1.GetEntry(ievt) sp1.measure_pulse2(data1, chx) for ich in range(sp1.nAdcCh): if chs and (ich not in chs): continue ss = sp1.signals[ich] itmp = sp1.nMeasParam * ich iA = 0 for ii in ss: tup1.Fill(run, ievt, ich, sp1.measParam[itmp], sp1.measParam[itmp + 1], iA, ii.im, ii.idx, ii.Q, ii.w0, ii.w1, ii.w2, dataT[0] - 788947200, dV) iA += 1 tup1.Write() fout1.Close()
def tune_check(): '''The same configuration as the tune''' be1 = bkgEstimator() # be1.show_data() s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5) data1 = (s1.ANALYSIS_WAVEFORM_BASE_TYPE * (s1.nSamples * s1.nAdcCh))() data1 = array('f', [0] * (16384 * 20)) # pTag = 'Feb09b' pTag = 'Feb25a' tagA = 'data/fpgaLin/' + pTag + '_data_' inRoot = 'data/fpgaLin/' + pTag + '_data_1138.root' if len(sys.argv) > 1: if os.path.exists(sys.argv[1]): inRoot = sys.argv[1] elif os.path.exists(tagA + sys.argv[1] + '.root'): inRoot = tagA + sys.argv[1] + '.root' else: files = sorted([f for f in glob(tagA + '*.root')], key=lambda f: os.path.getmtime(f)) a = -1 try: a = int(sys.argv[1]) except TypeError: pass if time.time() - os.path.getmtime(files[-1]) < 10: print "dropping the latest file, which probably is still being written:", files[ -1] if a != 0: files.pop() else: a = -1 if abs(a) < len(files): inRoot = files[a] else: print "Index {0:d} out of range:{1:d}".format(a, len(files)) return print "Using file:", inRoot fout1 = TFile(inRoot, 'read') tree1 = fout1.Get('tree1') tree1.SetBranchAddress('adc', data1) print "Entries in the tree:", tree1.GetEntries() run = -1 runPattern = '.*_data_(\d+).root' if runPattern is not None: m = re.match(runPattern, inRoot) if m: try: run = int(m.group(1)) except ValueError: print "Run number not exatracted for file", iRoot i = 56 ich = 1 sp1 = SignalProcessor() print "using configuration:", apply_config(sp1, 'Helium') for i in range(sp1.nAdcCh): sp1.CF_chan_en[i] = 1 if i == ich else 0 plt.ion() plt.show() # fig, ax1 = plt.subplots(1, 1, figsize=(28, 10)) fig, ax1 = plt.subplots(1, 1, figsize=(14, 5)) # fig.set_size_inches(11,8) ax1.set_xlabel('time index') ax1.set_ylabel('U [V]', color='b') ax1.tick_params('y', colors='b') ax2 = ax1.twinx() ax2.set_ylabel('U [V]', color='r') ax2.tick_params('y', colors='r') # for ievt in range(tree1.GetEntries()): NMax = tree1.GetEntries() ievt = 0 NVAL = 8 t_values = array('f', [0] * (sp1.nAdcCh * NVAL)) while ievt < NMax: print "Event:", ievt tree1.GetEntry(ievt) va = data1[ich * sp1.nSamples:(ich + 1) * sp1.nSamples] # be1.correct(data1, ich) # apply_wiener_filter(data1, ich) # sp1.measure_pulse2(data1, ich) sp1.measure_multipleX(data1, 2000, t_values) vx = np.array([sp1.scrAry[i] for i in range(sp1.nSamples)]) vo = data1[ich * sp1.nSamples:(ich + 1) * sp1.nSamples] ax1.clear() ax2.clear() ax1.plot(va, label='Raw', color='b') # ax1.plot(vo, label='Wiener', color='g') ax2.plot(vx, label='Filtered', color='r') # ax2.plot([vo[i]-va[i] for i in range(sp1.nSamples)], label='Correction', color='k') ylim1 = ax1.get_ylim() ylim2 = ax2.get_ylim() x1 = min(ylim1[0], ylim2[0] + vo[0]) x2 = max(ylim1[1], ylim2[1] + vo[0]) # print x1,x2 ax1.set_ylim(x1, x2) ax2.set_ylim(x1 - vo[0], x2 - vo[0]) # print sp1.signals[ich].size() x1 = [] y1 = [] iss = 0 for x in t_values[ich * NVAL:(ich + 1) * NVAL]: print x # if len(sp1.signals[ich])>0: # print "idx: iMax iMidian A w0 w1 w2" # print '-'*30 # for s in sp1.signals[ich]: # print iss,':', s.idx, s.im, s.Q, s.w0, s.w1, s.w2 # x1.append(s.im) # y1.append(s.Q) # plt.axvline(x=s.im, linestyle='--', color='black') # iss += 1 plt.text(0.04, 0.1, 'run {0:d} event {1:d}, ch {2:d}'.format(run, ievt, ich), horizontalalignment='center', verticalalignment='center', transform=ax2.transAxes) plt.xlim(auto=False) if x1: ax2.scatter(x1, y1, c="g", marker='o', s=220, label='Analysis') fig.tight_layout() plt.draw() plt.legend() plt.grid(True) plt.pause(0.001) while True: x = raw_input("Next:") if x == 'q': sys.exit() elif len(x) > 0 and x[0] == 's': for name in x.split()[1:]: dirx = os.path.dirname(name) if not os.path.exists(dirx): os.makedirs(dirx) plt.savefig(name) print "saved figure to", name elif len(x) > 2 and x[:2] == 'ch': try: ich = int(x[2:]) for i in range(sp1.nAdcCh): sp1.CF_chan_en[i] = 1 if i == ich else 0 print "Switching to channel:", ich break except ValueError: continue elif len(x) > 0 and x[0] == 'p': ievt -= 1 break else: try: ievt = int(x) except ValueError: ievt += 1 break
def check1(inRoot, chRange=None, nEvt=None, oTag='_tt'): '''Use various filters to extract the results''' if os.path.exists(inRoot.rstrip('.root') + oTag + '.root'): print "has:", inRoot return # print inRoot # return sp1 = SignalProcessor() sp1.nSamples = 16384 sp1.nAdcCh = 20 freq = 1000 n1 = int(1 / (0.2 * freq * 0.000001)) sp1.sRanges.clear() ip = 0 dn = 2500 % n1 ## 2500 is the expected position of the signal while ip + dn < sp1.nSamples: sp1.sRanges.push_back((ip, min(ip + n1, sp1.nSamples))) ip += n1 data1 = array('f', [0] * (sp1.nSamples * sp1.nAdcCh)) fin1 = TFile(inRoot, 'read') tree1 = fin1.Get('tree1') tree1.SetBranchAddress('adc', data1) if nEvt is None: nEvt = tree1.GetEntries() if chRange is None: chRange = range(sp1.nAdcCh) fout1 = TFile(inRoot.rstrip('.root') + oTag + '.root', 'recreate') tup1 = TNtuple('tup1', "filter analysis tuple", 'evt:fR:fW:ich:b:bE:im:idx:A') ### start processing INTV = 1000 if nEvt > 10000 else max(nEvt / 10, 1) for ievt in range(nEvt): tree1.GetEntry(ievt) if ievt % INTV == 0: print ievt, ' events processed' for R in range(50, 300, 50): for W in range(50, 600, 50): sp1.fltParam.clear() for x in [500, R, W, -1.]: sp1.fltParam.push_back(x) sp1.measure_pulse(data1) for ich in chRange: itmp = sp1.nMeasParam * ich for j in range(sp1.nMeasParam / 2 - 1): tup1.Fill(ievt, R, W, ich, sp1.measParam[itmp], sp1.measParam[itmp + 1], j, sp1.measParam[itmp + 2 * j + 2], sp1.measParam[itmp + 2 * j + 3]) tup1.Write() ### save the ENC results tup2 = TNtuple('tup2', "filter analysis tuple enc", 'ich:fR:fW:m:mE:sigma:sigmaE:fq:fStatus') for R in range(50, 300, 50): for W in range(50, 600, 50): for ich in chRange: gDirectory.Delete('h1*') tup1.Draw( 'A>>h1', 'int(fW)=={0:d}&&int(fR)=={1:d}&&ich=={2:d}'.format( W, R, ich), 'goff') h1 = gDirectory.Get('h1') r = h1.Fit('gaus', 'S0') fun1 = h1.GetFunction('gaus') tup2.Fill(ich, R, W, fun1.GetParameter(1), fun1.GetParError(1), fun1.GetParameter(2), fun1.GetParError(2), r.Prob(), r.Status()) tup2.Write() fout1.Close()
def readSignal4a(argX, runPattern='.*_data_(\d+).root'): '''Use non default time window''' args = argX.split(';') inRoot = args[0] oTag = args[1] print "Starting", inRoot, oTag ### pulse test dV = -1 dvPattern = '.*_(\d+)mV_f\d+.root' m = re.match(dvPattern, inRoot) if m: try: dV = int(m.group(1)) except ValueError: print "Failed to get the dV in file:", iRoot ### data check run = -1 if runPattern is not None: m = re.match(runPattern, inRoot) if m: try: run = int(m.group(1)) except ValueError: print "Run number not exatracted for file", iRoot return else: if dV < 0: print "Run number not exatracted for file", iRoot return sp1 = SignalProcessor() sp1.nSamples = 16384 sp1.nAdcCh = 20 sp1.fltParam.clear() # for i in range(sp1.nAdcCh): sp1.ch_thre[i] = 0.002 # sp1.ch_thre[19] = 0.05 thre = [0.002] * sp1.nAdcCh thre[2] = 0.0008 thre[4] = 0.001 thre[6] = 0.001 thre[7] = 0.001 thre[10] = 0.001 thre[11] = 0.0007 thre[14] = 0.0007 thre[17] = 0.001 thre[19] = 0.05 sp1.CF_uSize = 600 sp1.CF_dSize = 1100 sp1.ch_thre.clear() for x in thre: sp1.ch_thre.push_back(x) sp1.CF_chan_en.clear() for i in range(20): sp1.CF_chan_en.push_back(1) flt = [50, 100, 500, -1] # dp01a for x in flt: sp1.fltParam.push_back(x) fin1 = TFile(inRoot, 'read') tree1 = fin1.Get('tree1') tree2 = 0 outRoot = os.path.dirname(inRoot) + '/' + oTag + os.path.basename(inRoot) tf = sp1.processFile(tree1, tree2, outRoot, run) tf.Close()
def check0(): inRoot = sys.argv[1] if len(sys.argv) > 1 else "test.root" ich = int(sys.argv[2]) if len(sys.argv) > 2 else 0 sp1 = SignalProcessor() sp1.nSamples = 16384 sp1.nAdcCh = 20 freq = 1000 n1 = int(1 / (0.2 * freq * 0.000001)) sp1.sRanges.clear() ip = 0 dn = 2500 % n1 ## 2500 is the expected position of the signal while ip + dn < sp1.nSamples: sp1.sRanges.push_back((ip, min(ip + n1, sp1.nSamples))) ip += n1 data1 = array('f', [0] * (sp1.nSamples * sp1.nAdcCh)) fout1 = TFile(inRoot, 'read') tree1 = fout1.Get('tree1') tree1.SetBranchAddress('adc', data1) ### range eRange = None if len(sys.argv) > 3: lx = [] r = sys.argv[3].split(',') for ri in r: si = ri.find('-') if si == -1: lx.append(int(ri)) else: end = tree1.GetEntries() if si == len(ri) - 1 else int(ri[si + 1:]) lx += range(int(ri[:si]), end) eRange = lx else: eRange = range(tree1.GetEntries()) ### plotting plt.ion() plt.show() fig, ax1 = plt.subplots() ax1.set_xlabel('time (s)') # Make the y-axis label, ticks and tick labels match the line color. ax1.set_ylabel('exp', color='b') ax1.tick_params('y', colors='b') ax2 = ax1.twinx() ax2.set_ylabel('sin', color='r') ax2.tick_params('y', colors='r') # fl1 = Filter_ibl(sp1.nSamples) # fl1.setup(2,3e-3) fl1 = Filter_ibb(sp1.nSamples) fl1.setup(4, 2e-3, 5e-3) # for i in range(10): for i in eRange: print i tree1.GetEntry(i) ax1.clear() ax1.plot(data1[sp1.nSamples * ich:sp1.nSamples * (ich + 1)]) ax2.clear() sp1.fltParam.clear() # for x in [500, 150, 200, 2500]: sp1.fltParam.push_back(x) for x in [500, 800, 2000, 2500]: sp1.fltParam.push_back(x) sp1.measure_pulse(data1, ich) ax2.plot([sp1.scrAry[i] for i in range(sp1.nSamples)], 'r.') sp1.fltParam.clear() for x in [500, 15, 50, 2500]: sp1.fltParam.push_back(x) # for x in [500, 150, 200, 2500]: sp1.fltParam.push_back(x) sp1.measure_pulse(data1, ich) # ax2.plot([sp1.scrAry[i] for i in range(sp1.nSamples)], 'g.') vx = np.array([sp1.scrAry[i] for i in range(sp1.nSamples)]) ax2.plot(vx, 'g.') fl1.apply(sp1.scrAry) vf1 = np.array([fl1.outWav[i] for i in range(sp1.nSamples)]) ax2.plot(vf1, 'm.') # peakind = find_peaks_cwt(vx, np.arange(1,100)) # peaks = find_peaks_cwt(vx, np.array([5, 10, 20,30,50,100,200,350]), min_snr=50) # print peaks, vx[peaks] # peaks, properties = signal.find_peaks(vx, prominence=1, width=20) # plt.plot(peaks, vx[peaks], "x") fig.tight_layout() plt.draw() plt.grid(True) plt.pause(0.001) x = raw_input("Press [enter] to continue.") if x == 'q': break
class Train(threading.Thread): def __init__(self, cd): threading.Thread.__init__(self) self.cd = cd self.tx_qs = None self.rx_qs = None self.on = True self.mask = [0] * cd.nCh self.nSig = 3 ### this copy of sensorVcodes is used to save the best value find so far self.sensorVcodes = [[v for v in cd.sensorVcodes[i]] for i in range(cd.nCh)] # self.bestConfigFile = 'current_best_config.json' self.bestConfigFile = 'C3_tt6_config.json' self.retBest = [0.] * cd.nAdcCh ### for data taking self.sc = None ### plotting self.axs = None self.plot_x = None self.pltCnt = 0 self.pltN = 20 self.sp = SignalProcessor() apply_config(self.sp, 'Helium') self.NVAL = 8 s1 = self.cd.sigproc self.data1 = (s1.ANALYSIS_WAVEFORM_BASE_TYPE * (s1.nSamples * s1.nAdcCh))() self.ret1 = array.array('f', [0] * s1.nAdcCh) self.par1 = array.array('f', [0] * (self.cd.nCh * len(self.cd.inputVs))) self.t_values = array.array('f', [0] * (s1.nAdcCh * self.NVAL)) self.keepAllData = False self.saveT0 = -1 self.T = array.array('i', [0]) self.Tag = array.array('i', [0]) def setupOutput(self, outRootName='tt_test.root'): s1 = self.cd.sigproc self.fout1 = TFile(outRootName, 'recreate') self.tree1 = TTree( 'tree1', "tune data for {0:d} channels, {1:d} samples".format( s1.nAdcCh, s1.nSamples)) self.tree1.Branch('tag', self.Tag, 'tag/I') self.tree1.Branch('T', self.T, 'T/i') self.tree1.Branch('adc', self.data1, "adc[{0:d}][{1:d}]/F".format(s1.nAdcCh, s1.nSamples)) self.tree1.Branch('ret', self.ret1, "ret[{0:d}]/F".format(s1.nAdcCh)) self.tree1.Branch( 'par', self.par1, "par[{0:d}][{1:d}]/F".format(self.cd.nCh, len(self.cd.inputVs))) self.tree1.Branch( 'val', self.t_values, "val[{0:d}][{1:d}]/F".format(self.cd.nAdcCh, self.NVAL)) def plot_data(self): # item = self.q.get() if self.axs is None: print("creating the plot......") import matplotlib matplotlib.rcParams['toolbar'] = 'None' plt.ion() fig, self.axs = plt.subplots(self.cd.nAdcCh, 1, sharex=True) # Remove horizontal space between axes plt.tight_layout(pad=0) fig.subplots_adjust(hspace=0) self.plot_x = [self.cd.adcDt * i for i in range(self.cd.nSamples)] for i in range(self.cd.nAdcCh): self.axs[i].cla() # self.axs[i].plot(self.cd.adcData[i]) # self.axs[i].step(array.array('f', self.cd.adcData[i]), where='post') # self.axs[i].plot(self.plot_x, array.array('f', self.cd.adcData[i])) self.axs[i].plot( self.plot_x, self.data1[i * self.cd.nSamples:(i + 1) * self.cd.nSamples]) plt.draw() # self.q.task_done() def test_update_sensor(self, inputVs=None): print('/' * 40) if inputVs is None: inputVs = [[1.379, 1.546, 1.626, 1.169, 1.357, 2.458], [1.379, 1.546, 1.626, 1.169, 1., 2.]] #### update sensor configurations ss = set() for i, p in enumerate(inputVs): if p is None: continue self.cd.set_sensor(i, p) ss.add(self.sc.tms1mmX19chainSensors[ self.sc.tms1mmX19sensorInChain[i]][0]) ### apply the configurations print(ss) for isr in ss: self.sc.update_sensor(isr) print('\\' * 40) def take_data2(self, NEVT=100): '''return an array of FOM''' s1 = self.cd.sigproc for ievt in range(NEVT): self.T[0] = int(time.time()) self.cd.dataSocket.sendall(self.cd.cmd.send_pulse(1 << 2)) buf = self.cd.cmd.acquire_from_datafifo(self.cd.dataSocket, self.cd.nWords, self.cd.sampleBuf) s1.demux_fifodata(buf, self.data1, self.cd.sdmData) ### measure self.sp.measure_multipleX(self.data1, 2000, self.t_values) ### save self.tree1.Fill() def take_data(self): '''return an array of FOM''' s1 = self.cd.sigproc NV = 8 NEVT = 100 Values = [[0.] * (NV * NEVT) for i in range(self.cd.nAdcCh)] for ievt in range(NEVT): self.cd.dataSocket.sendall(self.cd.cmd.send_pulse(1 << 2)) buf = self.cd.cmd.acquire_from_datafifo(self.cd.dataSocket, self.cd.nWords, self.cd.sampleBuf) s1.demux_fifodata(buf, self.data1, self.cd.sdmData) self.sp.measure_multipleX(self.data1, 2000, self.t_values) # if ievt == 0: # print("EVT",ievt) # # print([self.t_values[i] for i in range(NV*self.cd.nAdcCh)]) # print([self.t_values[6*NV+i] for i in range(NV)]) for ich in range(self.cd.nAdcCh): for ipeak in range(NV): Values[ich][ievt * NV + ipeak] = self.t_values[ich * NV + ipeak] for i in range(s1.nAdcCh): # self.ret1[i] = np.std(Values[i])/np.mean(Values[i]) self.ret1[i] = -np.mean(Values[i]) / np.std(Values[i]) # if i==6: # # print(i,'->', Values[i][20*8:21*8]) # print(i,'->', Values[i][0*8:1*8]) # print(i, np.std(Values[i]), np.mean(Values[i]), self.ret1[i]) self.T[0] = int(time.time()) # print(self.ret1[3],self.ret1[0]) # for i in range(self.cd.nAdcCh): print(i,self.ret1[i]) self.tree1.Fill() if self.T[0] - self.saveT0 > 200: self.tree1.AutoSave('SaveSelf') self.saveT0 = self.T[0] def run(self): nPar = len(self.cd.inputVs) ### save the initial values for i in range(self.cd.nCh): for kk in range(nPar): self.par1[i * nPar + kk] = self.cd.tms1mmReg.dac_code2volt( self.sensorVcodes[i][kk]) while self.on: cnt = 0 # cnt1 = 0 ss = set() for i, q in enumerate(self.rx_qs): if q is None: continue cnt += 1 # x = q.get() # self.pars[i] = x if not q.empty(): # cnt1 += 1 x = q.get() self.mask[i] = 1 # print('--- {0:d} get'.format(i)+' ['+','.join([str(a) for a in x])+']') # self.pars[i] = x # print(i,x) self.cd.set_sensor(i, x) for kk in range(nPar): self.par1[i * nPar + kk] = x[kk] ss.add(self.sc.tms1mmX19chainSensors[ self.sc.tms1mmX19sensorInChain[i]][0]) if cnt == 0: self.on = False if len(ss) == 0: continue # if cnt1 == 0: continue #### update sensor configurations # ss = set() # for i,p in enumerate(self.pars): # if self.mask[i] == 1: # self.cd.set_sensor(i,p) # ss.append(self.sc.tms1mmX19chainSensors[self.sc.tms1mmX19sensorInChain[i]][0]) ### apply the configurations for isr in ss: self.sc.update_sensor(isr, quiet=1) ### take data self.pltCnt += 1 t = None if self.pltCnt % self.pltN == 0: self.plot_data() # t = threading.Thread(target=self.plot_data) # t.daemon = True # t.start() # self.q.put('run') time.sleep(30) if t is not None: t.join() self.take_data() ret = self.ret1 ### return needUpdate = False for i, t in enumerate(self.tx_qs): if self.mask[i] == 1: t.put(ret[i]) self.mask[i] = 0 ### save the values if it's the best so far if ret[i] < self.retBest[i]: print("find better parameters for channel", i) print('old:', self.sensorVcodes[i], self.retBest[i]) self.retBest[i] = ret[i] self.sensorVcodes[i] = [ a for a in self.cd.sensorVcodes[i] ] print('new:', self.sensorVcodes[i], self.retBest[i]) needUpdate = True # print("--- {0:d} {1:g}".format(i, self.meas[i])) if needUpdate: self.sc.write_config_fileX(self.bestConfigFile, self.sensorVcodes) print('Stopping the train.....') plt.close('all') self.tree1.Write() self.fout1.Close()
def main(): inRoot = sys.argv[1] if len(sys.argv) > 1 else "test.root" ich = int(sys.argv[2]) if len(sys.argv) > 2 else 0 sp1 = SignalProcessor() sp1.nSamples = 16384 sp1.nAdcCh = 20 sp1.fltParam.clear() for x in [50, 150, 200, -1.]: sp1.fltParam.push_back(x) freq = 1000 n1 = int(1 / (0.2 * freq * 0.000001)) sp1.sRanges.clear() ip = 0 dn = 2500 % n1 ## 2500 is the expected position of the signal while ip + dn < sp1.nSamples: sp1.sRanges.push_back((ip, min(ip + n1, sp1.nSamples))) ip += n1 data1 = array('f', [0] * (sp1.nSamples * sp1.nAdcCh)) fout1 = TFile(inRoot, 'read') tree1 = fout1.Get('tree1') tree1.SetBranchAddress('adc', data1) ### range eRange = None if len(sys.argv) > 3: lx = [] r = sys.argv[3].split(',') for ri in r: si = ri.find('-') if si == -1: lx.append(int(ri)) else: end = tree1.GetEntries() if si == len(ri) - 1 else int(ri[si + 1:]) lx += range(int(ri[:si]), end) eRange = lx else: eRange = range(tree1.GetEntries()) ### plotting plt.ion() plt.show() fig, ax1 = plt.subplots() ax1.set_xlabel('time (s)') # Make the y-axis label, ticks and tick labels match the line color. ax1.set_ylabel('exp', color='b') ax1.tick_params('y', colors='b') ax2 = ax1.twinx() ax2.set_ylabel('sin', color='r') ax2.tick_params('y', colors='r') # for i in range(10): for i in eRange: print i tree1.GetEntry(i) sp1.measure_pulse(data1, ich) ax1.clear() ax1.plot(data1[sp1.nSamples * ich:sp1.nSamples * (ich + 1)]) ax2.clear() ax2.plot([sp1.scrAry[i] for i in range(sp1.nSamples)], 'r.') fig.tight_layout() plt.draw() plt.pause(0.001) x = raw_input("Press [enter] to continue.") if x == 'q': break
def display_test(inRoot='data/fpgaLin/Feb27a_data_40.root', ievt=0): '''To test the event reconstruction''' gStyle.SetOptStat(0) gROOT.ProcessLine('.L Pal.C') gStyle.SetPalette(55) gStyle.SetPadRightMargin(0.15) # from ROOT import Pal2 # Pal2() data1 = array('f', [0] * (16384 * 20)) fout1 = TFile(inRoot, 'read') tree1 = fout1.Get('tree1') tree1.SetBranchAddress('adc', data1) ### here comes the constructor sp1 = SignalProcessor() sp1.nAdcCh = 20 sp1.IO_adcData = data1 sp1.CF_chan_en.clear() for i in range(20): sp1.CF_chan_en.push_back(1) sp1.fltParam.clear() for x in [30, 100, 300, -1]: sp1.fltParam.push_back(x) thre = [0.001] * sp1.nAdcCh thre[19] = 0.02 sp1.ch_thre.clear() for x in thre: sp1.ch_thre.push_back(x) Unit = 0.2 h3 = TH3F('h3', 'h3;x [cm];y [cm];t [ps]', 9, -1.8, 1.8, 9, -1.8, 1.8, 100, -1. * Unit * sp1.CF_uSize, Unit * sp1.CF_dSize) h2 = TH2F('h2', 'h2;t [ps];Channel;Q', (sp1.CF_uSize + sp1.CF_dSize), -1. * Unit * sp1.CF_uSize, Unit * sp1.CF_dSize, 20, 0, 20) cx = TCanvas('cx', 'cx', 1500, 700) cx.Divide(2, 1) # for i in range(tree1.GetEntries()): while ievt >= 0: tree1.GetEntry(ievt) sp1.reco() for e in sp1.IO_evts: print e.trigID, len(e.sigs) h3.Reset() h2.Reset() showEvent(e, h3, h2) cx.cd(1) # h3.Draw('BOX2') # h3.Draw() # h3.SetMarkerStyle(20) # h3.SetMarkerSize(1) h3.Draw('COLZ') cx.cd(2) t = h2.GetBinContent(h2.GetMaximumBin()) * 1.06 h2.GetZaxis().SetRangeUser(-0.05 * t, t * 0.95) h2.Draw('colz') # h2.Draw('axis same') cx.cd(0) # gPad.Update() # a = raw_input("x:") waitRootCmdX(cx) ievt += 1
def test2a(): # be1 = bkgEstimator() # be1.show_data() s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5) data1 = (s1.ANALYSIS_WAVEFORM_BASE_TYPE * (s1.nSamples * s1.nAdcCh))() data1 = array('f', [0] * (16384 * 20)) # pTag = 'Feb09b' pTag = 'Feb25a' tagA = 'data/fpgaLin/' + pTag + '_data_' inRoot = 'data/fpgaLin/' + pTag + '_data_1138.root' if len(sys.argv) > 1: # import os if os.path.exists(sys.argv[1]): inRoot = sys.argv[1] elif os.path.exists(tagA + sys.argv[1] + '.root'): inRoot = tagA + sys.argv[1] + '.root' else: files = sorted([f for f in glob(tagA + '*.root')], key=lambda f: os.path.getmtime(f)) a = -1 try: a = int(sys.argv[1]) except TypeError: pass if time.time() - os.path.getmtime(files[-1]) < 10: print "dropping the latest file, which probably is still being written:", files[ -1] if a != 0: files.pop() else: a = -1 if abs(a) < len(files): inRoot = files[a] else: print "Index {0:d} out of range:{1:d}".format(a, len(files)) return print "Using file:", inRoot fout1 = TFile(inRoot, 'read') tree1 = fout1.Get('tree1') tree1.SetBranchAddress('adc', data1) print "Entries in the tree:", tree1.GetEntries() run = -1 runPattern = '.*_data_(\d+).root' if runPattern is not None: m = re.match(runPattern, inRoot) if m: try: run = int(m.group(1)) except ValueError: print "Run number not exatracted for file", iRoot i = 56 ich = 1 sp1 = SignalProcessor() sp1.fltParam.clear() # P is the constant using 0.2 ps as unit wit # 0.006 is the constant using 1/2500/1024 as unit 1/0.006 T = 1/0.006 * 1/2500/1024 s = 1/0.006 *1/2500/1024* 5000000 pts # for x in [500, 500, 700, 2500]: sp1.fltParam.push_back(x) # for x in [500, 5, 15, 2500]: sp1.fltParam.push_back(x) # for x in [500, 50, 150, 2500]: sp1.fltParam.push_back(x) # for x in [30, 15, 50, 2500]: sp1.fltParam.push_back(x) # for x in [30, 50, 250, 2500]: sp1.fltParam.push_back(x) P = 1. / 0.006 / 2500 / 1024 * 5000000 for x in [30, 50, 200, P]: sp1.fltParam.push_back(x) # for x in [50, 100, 500, -1]: sp1.fltParam.push_back(x) # for x in [30, 5, 100, 2500]: sp1.fltParam.push_back(x) # for x in [30, 250, 350, 2500]: sp1.fltParam.push_back(x) # sp1.x_thre = 0.002 # for i in range(20): sp1.ch_thre[i] = 0.002 # sp1.ch_thre[19] = 0.05 thre = [0.002] * sp1.nAdcCh thre[19] = 0.05 sp1.ch_thre.clear() for x in thre: sp1.ch_thre.push_back(x) plt.ion() fig, axs = plt.subplots(nrows=20, ncols=1, sharex=True, sharey=False, squeeze=True, figsize=(13, 12.5), dpi=72) plt.subplots_adjust(left=0.1, right=0.98, top=0.98, bottom=0.05, hspace=0, wspace=0) plt.show() # fig, ax1 = plt.subplots(1, 1, figsize=(28, 10)) # fig.set_size_inches(11,8) # ax1.set_xlabel('time index') # ax1.set_ylabel('U [V]', color='b') # ax1.tick_params('y', colors='b') # ax2 = ax1.twinx() # ax2.set_ylabel('U [V]', color='r') # ax2.tick_params('y', colors='r') # for ievt in range(tree1.GetEntries()): NMax = tree1.GetEntries() ievt = 0 while ievt < NMax: print "Event:", ievt tree1.GetEntry(ievt) for ich in range(sp1.nAdcCh): va = data1[ich * sp1.nSamples:(ich + 1) * sp1.nSamples] sp1.measure_pulse2(data1, ich) vx = np.array([sp1.scrAry[i] for i in range(sp1.nSamples)]) vo = data1[ich * sp1.nSamples:(ich + 1) * sp1.nSamples] axs[ich].clear() axs[ich].plot(vo) tx = axs[ich].twinx() tx.clear() tx.plot(vx, color='r') plt.draw() plt.grid(True) plt.pause(0.001) while True: x = raw_input("Next:") if x == 'q': sys.exit() elif len(x) > 0 and x[0] == 's': for name in x.split()[1:]: dirx = os.path.dirname(name) if not os.path.exists(dirx): os.makedirs(dirx) plt.savefig(name) print "saved figure to", name elif len(x) > 2 and x[:2] == 'ch': try: ich = int(x[2:]) print "Switching to channel:", ich break except ValueError: continue else: try: ievt = int(x) except ValueError: ievt += 1 break