def check_enc2(self, inRoot, outText):
        s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5)
        data1 = s1.generate_adcDataBuf()
        data2 = s1.generate_sdmDataBuf()

        fout1 = TFile(inRoot, 'read')
        tree1 = fout1.Get('tree1')
        #         tree1.SetBranchAddress('ch0',data1)
        tree1.SetBranchAddress('adc', data1)
        with open(outText, 'w') as fout:
            fout.write(':'.join(
                ['sID/I', 'ch/I', 'B/F', 'dB/F', 'idx/I', 'A/F']))

            for i in range(tree1.GetEntries()):
                if i % 100 == 0: print(str(i) + ' entries processed')
                tree1.GetEntry(i)
                mxx = s1.measure_pulse(data1, fltParam=[500, 150, 200, -1.])
                for ch in range(s1.nAdcCh):
                    mx = mxx[ch]
                    if isnan(mx[1]): print("xxxx")
                    fout.write('\n' + ' '.join([
                        str(i),
                        str(ch),
                        str(mx[0]),
                        str(mx[1]), '{0:d}'.format(int(mx[2])),
                        str(mx[3])
                    ]))
    def show_sample(self,
                    fnameP='/data/Samples/TMSPlane/Dec26/sample_{0:d}.adc',
                    Ns=10,
                    ich=8):
        from ROOT import TGraph, gPad, TLatex
        s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5)
        data1 = s1.generate_adcDataBuf()
        data2 = s1.generate_sdmDataBuf()

        data3 = ((s1.ANALYSIS_WAVEFORM_BASE_TYPE * s1.nSamples) * Ns)()
        dataList = []
        for i in range(Ns):
            fname = fnameP.format(i)
            s1.read_data([fname, ''], data1, data2)
            x = array.array('f', range(s1.nSamples))
            #             s1.filters_trapezoidal(data1[ich], data3[i], [100,100,200,-1])
            s1.filters_trapezoidal(data1[ich], data3[i],
                                   [100, 100, 100, 0.000722])
            g1 = TGraph(s1.nSamples, x, data3[i])
            #             g1 = TGraph(s1.nSamples, x, data1[ich])

            opt = 'AP' if i == 0 else "PSame"
            g1.Draw(opt + ' PLC PMC')
            dataList.append(g1)

        lt = TLatex()
        lt.DrawLatexNDC(0.2, 0.8, "Chan={0:d}".format(ich))
        gPad.Update()
        waitRootCmdX()
    def check_event(self, rootfile, idxs):
        s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5)
        data1 = s1.generate_adcDataBuf()

        fout1 = TFile(rootfile, 'read')
        tree1 = fout1.Get('tree1')
        tree1.SetBranchAddress('adc', data1)
        for i in idxs:
            tree1.GetEntry(i)
            mx = s1.measure_pulse(data1, fltParam=[500, 150, 200, -1.])
            d = [x[3] for x in mx]
            self.plot_data(d)

            waitRootCmdX()
def get_tgraph(ch,entry,inRoot):
    s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5)
    data1 = s1.generate_adcDataBuf()
    fout1 = TFile(inRoot,'read')
    tree1 = fout1.Get('tree1')
    tree1.SetBranchAddress('adc',data1)
    tree1.GetEntry(entry)

    data3 = (s1.ANALYSIS_WAVEFORM_BASE_TYPE * s1.nSamples)()
    s1.filters_trapezoidal(data1[ch], data3, [100,100,200,10])

    x1 = array('f',range(s1.nSamples))
    g1 = TGraph(s1.nSamples, x1, data3)

    return g1
Example #5
0
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)]
Example #6
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 check_file(self, fname):
        s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5)
        data1 = s1.generate_adcDataBuf()
        data2 = s1.generate_sdmDataBuf()

        s1.read_data([fname, ''], data1, data2)

        mx = s1.measure_pulse(data1, fltParam=[500, 150, 200, -1.])
        d = [x[2] for x in mx]
        self.plot_data(d)
    def take_samples(self, n=10, name="sample_{0:d}"):
        s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5)
        data1 = s1.generate_adcDataBuf()
        data2 = s1.generate_sdmDataBuf()

        # FPGA internal fifo : 512 bit width x 16384 depth
        nWords = (512 // 32) * 16384
        nBytes = nWords * 4
        buf = bytearray(nBytes)

        for i in range(n):
            self.s.sendall(self.cmd.send_pulse(1 << 2))
            time.sleep(0.5)

            name1 = name.format(i)
            ret = self.cmd.acquire_from_datafifo(self.s, nWords, buf)
            s1.demux_fifodata(ret, data1, data2)
            s1.save_data([name1 + '.adc', name1 + '.sdm'], data1, data2)
    def take_samples2(self, n=10, outRootName='test_sample.root', runNumber=0):
        if not self.connected: self.connect()
        nMonitor = 20

        s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5)
        data1 = s1.generate_adcDataBuf()
        data2 = s1.generate_sdmDataBuf()

        T = array.array('i', [0])
        V = array.array('i', [0])
        if self.fileSuffix:
            while os.path.exists(outRootName):
                outRootName += self.fileSuffix
        fout1 = TFile(outRootName, 'recreate')
        tree1 = TTree(
            'tree1', "data: {0:d} channel, {1:d} samples".format(
                s1.nAdcCh, s1.nSamples))
        tree1.Branch('T', T, 'T/i')
        tree1.Branch('V', V, 'V/I')
        tree1.Branch('adc', data1,
                     "adc[{0:d}][{1:d}]/F".format(s1.nAdcCh, s1.nSamples))

        # FPGA internal fifo : 512 bit width x 16384 depth
        nWords = (512 // 32) * 16384
        nBytes = nWords * 4
        buf = bytearray(nBytes)

        status = 0
        try:
            for i in range(n):
                if i % 100 == 0:
                    print(str(i) + ' samples taken.')
                    try:
                        with open(
                                '/home/dlzhang/work/repos/TMSPlane2/Software/Control/src/.pulse_status'
                        ) as f1:
                            V[0] = int(f1.readline().rstrip())
                    except:
                        V[0] = -999
                self.s.sendall(self.cmd.send_pulse(1 << 2))

                T[0] = int(time.time())
                ret = self.cmd.acquire_from_datafifo(self.s, nWords, buf)
                s1.demux_fifodata(ret, data1, data2)
                tree1.Fill()

                if i % nMonitor == 1: tree1.AutoSave("SaveSelf")
        except KeyboardInterrupt:
            status = 1

        fout1.Write()
        return status
def train_wavs(data_folder):
    hmm_models = []
    test_set = []
    for dirname in os.listdir(data_folder):
        # Get the name of the subfolder
        subfolder = os.path.join(data_folder, dirname)
        if not os.path.isdir(subfolder):
            continue
        # Extract the label
        label = subfolder[subfolder.rfind('/') + 1:]
        print('[*] ' + label)
        # Initialize variables
        X = np.array([])
        y_words = []

        # Iterate through the audio files (leaving 1 file for testing in each class)
        files = [x for x in os.listdir(subfolder) if x.endswith('.wav')]
        train_set = files[:-2]
        test_set.append([os.path.join(subfolder, i) for i in files[-2:]])
        for filename in tqdm(train_set):
            # Extract Feature
            print
            filepath = os.path.join(subfolder, filename)
            try:
                mfcc_features = SigProc(filepath).MFCC().T
            except:
                pass
            # Append to the variable X
            if len(X) == 0:
                X = mfcc_features
            else:
                X = np.append(X, mfcc_features, axis=0)

            # Append the label
            y_words.append(label)

        # Train and save HMM model
        hmm_trainer = HMMTrainer()
        hmm_trainer.train(X)
        hmm_models.append((hmm_trainer, label))
        joblib.dump(hmm_trainer, subfolder + "/ModelTrained.pkl")
        hmm_trainer = None
    return test_set
Example #11
0
def text2root(spattern, irange, outname):
    s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5)
    data1 = s1.generate_adcDataBuf()
    data2 = s1.generate_sdmDataBuf()

    fout1 = TFile(outname, 'recreate')
    tree1 = TTree(
        'tree1',
        "data: {0:d} channel, {1:d} samples".format(s1.nAdcCh, s1.nSamples))
    tree1.Branch('ch0', data1,
                 "ch0[{0:d}][{1:d}]/F".format(s1.nAdcCh, s1.nSamples))

    for i in irange:
        s1.read_data([spattern.format(i), 'xxx'], data1, data2)
        tree1.Fill()
    fout1.Write()
Example #12
0
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
Example #13
0
    def check_enc(self, filePattern):
        s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5)
        data1 = s1.generate_adcDataBuf()
        data2 = s1.generate_sdmDataBuf()

        files = glob.glob(filePattern)
        with open('test1bbb.dat', 'w') as fout:
            fout.write(':'.join(
                ['sID/I', 'ch/I', 'B/F', 'dB/F', 'idx/I', 'A/F']))
            for fname in files:
                s1.read_data([fname, ''], data1, data2)
                mxx = s1.measure_pulse(data1, fltParam=[500, 150, 200, -1.])
                for ch in range(s1.nAdcCh):
                    mx = mxx[ch]
                    fout.write('\n' + ' '.join([
                        fname[fname.find('_') + 1:-4],
                        str(ch),
                        str(mx[0]),
                        str(mx[1]), '{0:d}'.format(int(mx[2])),
                        str(mx[3])
                    ]))
Example #14
0
    def show_signal(self):
        s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5)
        data1 = s1.generate_adcDataBuf()
        data2 = s1.generate_sdmDataBuf()

        # FPGA internal fifo : 512 bit width x 16384 depth
        nWords = (512 // 32) * 16384
        nBytes = nWords * 4
        buf = bytearray(nBytes)

        self.s.sendall(self.cmd.send_pulse(1 << 2))
        time.sleep(0.5)

        ret = self.cmd.acquire_from_datafifo(self.s, nWords, buf)
        s1.demux_fifodata(ret, data1, data2)

        mx = s1.measure_pulse(data1, fltParam=[500, 150, 200, -1.])
        for x in mx:
            for i in range(len(x)):
                print x[i]
        d = [x[1] for x in mx]
        self.plot_data(d)
from sigproc import SigProc
import matplotlib.pyplot as plt
import array

if __name__ == "__main__":

    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("-c",
                        "--control-ip-port",
                        type=str,
                        default="192.168.2.3:1024",
                        help="main control system ipaddr and port")
    args = parser.parse_args()

    s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5)
    data1 = s1.generate_adcDataBuf()
    data2 = s1.generate_sdmDataBuf()

    data_source = 0

    if data_source == 0:
        ctrlipport = args.control_ip_port.split(':')
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((ctrlipport[0], int(ctrlipport[1])))
        cmd = Cmd()

        # reset data fifo
        s.sendall(cmd.send_pulse(1 << 2))
        time.sleep(0.5)
Example #16
0
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
Example #17
0
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