Exemplo n.º 1
0
def staff():

    staff = ROOT.staff_t()

    # The input file cern.dat is a copy of the CERN staff data base
    # from 1988

    f = TFile('staff.root', 'RECREATE')
    tree = TTree('T', 'staff data from ascii file')
    tree.Branch('staff', staff,
                'Category/I:Flag:Age:Service:Children:Grade:Step:Hrweek:Cost')
    tree.Branch('Divisions', AddressOf(staff, 'Division'), 'Division/C')
    tree.Branch('Nation', AddressOf(staff, 'Nation'), 'Nation/C')

    # note that the branches Division and Nation cannot be on the first branch
    fname = os.path.expandvars('$ROOTSYS/tutorials/tree/cernstaff.dat')
    for line in open(fname).readlines():
        t = filter(lambda x: x, re.split('\s+', line))
        staff.Category = int(t[0])  # assign as integers
        staff.Flag = int(t[1])
        staff.Age = int(t[2])
        staff.Service = int(t[3])
        staff.Children = int(t[4])
        staff.Grade = int(t[5])
        staff.Step = int(t[6])
        staff.Hrweek = int(t[7])
        staff.Cost = int(t[8])
        staff.Division = t[9]  # assign as strings
        staff.Nation = t[10]

        tree.Fill()

    tree.Print()
    tree.Write()
Exemplo n.º 2
0
    def initLbdata(self):

        #
        # Define LBDATA tree
        gROOT.ProcessLine("struct LbdataStruct {\
            Float_t fB1IntensityBPTX;\
            Float_t fB2IntensityBPTX;\
            Float_t fB1IntensityAllBPTX;\
            Float_t fB2IntensityAllBPTX;\
            Float_t fB1IntensityBCT;\
            Float_t fB2IntensityBCT;\
            Float_t fB1IntensityAllBCT;\
            Float_t fB2IntensityAllBCT;\
            Float_t fB1IntensityAllDCCT;\
            Float_t fB2IntensityAllDCCT;\
        };")
        from ROOT import LbdataStruct
        self.lbdataStruct = LbdataStruct()

        self.tree.Branch(
            'BPTX_LBDATA', AddressOf(self.lbdataStruct, 'fB1IntensityBPTX'),
            'BPTX_B1Intensity/F:BPTX_B2Intensity/F:BPTX_B1IntensityAll/F:BPTX_B2IntensityAll/F'
        )
        self.tree.Branch(
            'BCT_LBDATA', AddressOf(self.lbdataStruct, 'fB1IntensityBCT'),
            'BCT_B1Intensity/F:BCT_B2Intensity/F:BCT_B1IntensityAll/F:BCT_B2IntensityAll/F'
        )
        self.tree.Branch('DCCT_LBDATA',
                         AddressOf(self.lbdataStruct, 'fB1IntensityAllDCCT'),
                         'DCCT_B1IntensityAll/F:DCCT_B2IntensityAll/F')
Exemplo n.º 3
0
    def test05WriteSomeDataObjectBranched(self):
        """Test writing of a complex object across different branches"""

        f = TFile(self.fname, 'RECREATE')
        t = TTree(self.tname, self.ttitle)

        d = SomeDataStruct()

        # note: for p2.2, which has incomplete support of property types,
        # we need to keep a reference alive to the result of the property
        # call, or it will be deleted too soon; for later pythons, it is
        # safe to use d.Floats directly in the Branch() call
        fl = d.Floats
        t.Branch('floats', fl)
        t.Branch('nlabel', AddressOf(d, 'NLabel'), 'NLabel/I')
        t.Branch('label', AddressOf(d, 'Label'), 'Label/C')

        for i in range(self.N):
            for j in range(self.M):
                d.Floats.push_back(i * self.M + j)

            d.NLabel = i
            d.Label = '%d' % i

            t.Fill()

        f.Write()
        f.Close()
Exemplo n.º 4
0
def main(basedir=None):

    #production directory
    if basedir is None:
        basedir = ".."

    #input
    infile = basedir + "/lmon.root"

    #output
    outfile = basedir + "/HCal.csv"

    #lmon input
    inp = TFile.Open(infile)
    tree = inp.Get("DetectorTree")

    #load the tree
    gROOT.ProcessLine("struct EntryD {Double_t v;};")
    ucal_edep_EMC = rt.EntryD()
    ucal_edep_HAC1 = rt.EntryD()
    ucal_edep_HAC2 = rt.EntryD()
    ucal_edep_layers = std.vector(float)()
    tree.SetBranchAddress("ucal_edep_EMC", AddressOf(ucal_edep_EMC, "v"))
    tree.SetBranchAddress("ucal_edep_HAC1", AddressOf(ucal_edep_HAC1, "v"))
    tree.SetBranchAddress("ucal_edep_HAC2", AddressOf(ucal_edep_HAC2, "v"))
    tree.SetBranchAddress("ucal_edep_layers", ucal_edep_layers)

    #output txt csv
    out = open(outfile, "write")

    #file header
    tree.GetEntry(0)
    nlay = ucal_edep_layers.size()

    col = ["ucal_edep_EMC", "ucal_edep_HAC1", "ucal_edep_HAC2"]
    for i in range(nlay):
        col.append("ucal_edep_layer" + str(i))

    strcol = ""
    for i in col:
        strcol += "," + i

    out.write(strcol + "\n")

    #event loop
    for iev in xrange(tree.GetEntriesFast()):

        tree.GetEntry(iev)

        lin = str(iev + 1)
        lin += "," + str(ucal_edep_EMC.v)
        lin += "," + str(ucal_edep_HAC1.v)
        lin += "," + str(ucal_edep_HAC2.v)

        for i in xrange(nlay):
            lin += "," + str(ucal_edep_layers.at(i))

        out.write(lin + "\n")

    out.close()
Exemplo n.º 5
0
    def initFillParams(self):

        #
        # Define FILLPARAMS tree
        gROOT.ProcessLine("struct FillParamsStruct {\
            Int_t fB1Bunches;\
            Int_t fB1BCIDs[3564];\
            Int_t fB2Bunches;\
            Int_t fB2BCIDs[3564];\
            Int_t fLuminousBunches;\
            Int_t fLuminousBCIDs[3564];\
        };")
        from ROOT import FillParamsStruct
        self.fillParamsStruct = FillParamsStruct()

        self.fillParamsStruct.fB1Bunches = 0
        self.fillParamsStruct.fB2Bunches = 0
        self.fillParamsStruct.fLuminousBunches = 0
        # self.fB1BCIDs = array('i', 3564*[0])
        # self.fB2BCIDs = array('i', 3564*[0])
        # self.fLuminousBCIDs = array('i', 3564*[0])

        self.tree.Branch('FILLPARAMSB1',
                         AddressOf(self.fillParamsStruct, 'fB1Bunches'),
                         'B1Bunches/I:B1BCIDs[B1Bunches]/I')
        self.tree.Branch('FILLPARAMSB2',
                         AddressOf(self.fillParamsStruct, 'fB2Bunches'),
                         'B2Bunches/I:B2BCIDs[B2Bunches]/I')
        self.tree.Branch('FILLPARAMS',
                         AddressOf(self.fillParamsStruct, 'fLuminousBunches'),
                         'LuminousBunches/I:LuminousBCIDs[LuminousBunches]/I')

        print('Defined FillParams data type')
def init_tree_from_table(hit_table,
                         meta_table,
                         chunk_size=1,
                         hit_tree_entry=None,
                         meta_tree_entry=None):
    ''' Initializes a ROOT tree from a HDF5 table.
    Takes the HDF5 table column names and types and creates corresponding 
    branches. If a chunk size is specified the branches will have the length of 
    the chunk size and an additional parameter is returned to change the chunk 
    size at a later stage. If a tree_entry is defined (a ROOT c-struct) the new 
    tree has the branches set to the corresponding tree entry address.
    
    Parameters
    ----------
    numpy_type_descriptor: np.dtype
    '''
    if (chunk_size > 1 and hit_tree_entry is not None
            and meta_tree_entry is not None):
        raise NotImplementedError()

    tree = TTree('Table', 'Converted HDF5 table')
    n_entries = None
    if chunk_size > 1:
        n_entries = ctypes.c_int(chunk_size) if chunk_size > 1 else 1
        # needs to be added, otherwise one cannot access chunk_size_tree:
        tree.Branch('n_entries', ctypes.addressof(n_entries), 'n_entries/I')

    # adding branches for hit table:
    for hit_column_name in hit_table.dtype.names:
        print hit_column_name, hit_table.dtype[
            hit_column_name], get_root_type_descriptor(
                hit_table.dtype[hit_column_name])
        tree.Branch(
            hit_column_name, 'NULL' if hit_tree_entry is None else AddressOf(
                hit_tree_entry, hit_column_name),
            hit_column_name + '[n_entries]/' +
            get_root_type_descriptor(hit_table.dtype[hit_column_name])
            if chunk_size > 1 else hit_column_name + '/' +
            get_root_type_descriptor(hit_table.dtype[hit_column_name]))

    # adding branches for meta table (timestamps):
    for meta_column_name in meta_table.dtype.names:

        print meta_column_name, meta_table.dtype[
            meta_column_name], get_root_type_descriptor(
                meta_table.dtype[meta_column_name])

        if meta_column_name == 'timestamp_start' or meta_column_name == 'timestamp_stop':
            tree.Branch(
                meta_column_name,
                'NULL' if meta_tree_entry is None else AddressOf(
                    meta_tree_entry, meta_column_name),
                meta_column_name + '[n_entries]/' +
                get_root_type_descriptor(meta_table.dtype[meta_column_name])
                if chunk_size > 1 else meta_column_name + '/' +
                get_root_type_descriptor(meta_table.dtype[meta_column_name]))

    return tree, n_entries
Exemplo n.º 7
0
def main(basedir=None):

    #production directory
    if basedir is None:
        basedir = ".."

    #input
    infile = basedir + "/lmon.root"

    #output
    outfile = basedir + "/HCal.csv"

    #lmon input
    inp = TFile.Open(infile)
    tree = inp.Get("DetectorTree")



    #load the tree
    gROOT.ProcessLine("struct EntryD {Double_t v;};")
    hcal_edep_EM = rt.EntryD()
    hcal_edep_HAD = rt.EntryD()
    hcal_edep_layers = std.vector(float)()
    tree.SetBranchAddress("hcal_edep_EM", AddressOf(hcal_edep_EM, "v"))
    tree.SetBranchAddress("hcal_edep_HAD", AddressOf(hcal_edep_HAD, "v"))
    tree.SetBranchAddress("hcal_edep_layers", hcal_edep_layers)

    tree.GetEntry(0)
    nlay = hcal_edep_layers.size()

    #output DataFrame
    col = ["hcal_edep_EM", "hcal_edep_HAD"]
    lnam = {}
    for i in range(nlay):
        n = "hcal_edep_layer"+str(i)
        lnam[i] = n
        col.append(n)

    df = DataFrame(columns=col)

    #event loop
    for iev in xrange(tree.GetEntriesFast()):

        tree.GetEntry(iev)

        #print hcal_edep_EM.v, hcal_edep_HAD.v

        df.loc[iev+1, "hcal_edep_EM"] = hcal_edep_EM.v
        df.loc[iev+1, "hcal_edep_HAD"] = hcal_edep_HAD.v

        for i in xrange(nlay):
            #print "i", i, hcal_edep_layers.at(i)

            df.loc[iev+1, lnam[i]] = hcal_edep_layers.at(i)

    #print df

    df.to_csv(outfile)
Exemplo n.º 8
0
def run_convert(basedir, beam):

    print "Converting for:", beam

    infile = basedir + "/lmon_p"+str(beam)+".root"
    outfile = basedir + "/HCal_p"+str(beam)+".h5"

    #lmon input
    inp = TFile.Open(infile)
    tree = inp.Get("DetectorTree")

    #load the tree
    ucal_edep_EMC = rt.EntryD()
    ucal_edep_HAC1 = rt.EntryD()
    ucal_edep_HAC2 = rt.EntryD()
    ucal_edep_layers = std.vector(float)()
    tree.SetBranchAddress("ucal_edep_EMC", AddressOf(ucal_edep_EMC, "v"))
    tree.SetBranchAddress("ucal_edep_HAC1", AddressOf(ucal_edep_HAC1, "v"))
    tree.SetBranchAddress("ucal_edep_HAC2", AddressOf(ucal_edep_HAC2, "v"))
    tree.SetBranchAddress("ucal_edep_layers", ucal_edep_layers)

    tree.GetEntry(0)
    nlay = ucal_edep_layers.size()

    #output DataFrame
    col = ["ucal_edep_EMC", "ucal_edep_HAC1", "ucal_edep_HAC2"]
    for i in range(nlay):
        col.append( "ucal_edep_layer"+str(i) )

    df_inp = []

    #event loop
    for iev in xrange(tree.GetEntriesFast()):

        tree.GetEntry(iev)

        lin = []
        lin.append(ucal_edep_EMC.v)
        lin.append(ucal_edep_HAC1.v)
        lin.append(ucal_edep_HAC2.v)

        for i in xrange(nlay):

            lin.append(ucal_edep_layers.at(i))

        df_inp.append(lin)

    df = DataFrame(df_inp, columns=col)

    print df

    out = HDFStore(outfile)
    out["hcal"] = df
    out.close()

    inp.Close()
Exemplo n.º 9
0
def pion(args, figname):
    datatype = args[0]
    label = args[1]
    test = get_options(args, 'test')
    batch = get_options(args, 'batch')

    if batch:
        cmd = create_batch_cmd()
        bashname = '%s.sh' %figname
        bashfile = create_bashfile_cmd(cmd, bashname, label, test=test)
        logfile = set_logfile('fig', datatype, label, figname)
        jobname = 'figptpion'
        bsub_jobs(logfile, jobname, bashfile, test)
        return

    figfile = set_figfile(figname, label, '.pdf', test=test)
    rootfile = atr.rootfile(datatype, label, test=test)
    obj = atr.root_tree_obj(datatype, label)
    chain = root_chain(rootfile, obj)

    canvas = TCanvas("aCanvas", "Canvas", 600, 600)
    hist = TH1F('pionpt', '#pi p_{T}', 100, 0, 20)
 
    Gen_Pion_P4_ = TClonesArray('TLorentzVector')
    chain.SetBranchAddress('Gen_Pion_P4', AddressOf(Gen_Pion_P4_))

    PionPP4_ = TClonesArray('TLorentzVector')
    chain.SetBranchAddress('PionPP4', AddressOf(PionPP4_))

    ntot = chain.GetEntries()
    if test:
        ntot = 1000

    sys.stdout.write('Processing %s events ...\n' %ntot)
    sys.stdout.flush()
    nfill = 0 
    for i in xrange(ntot):
        chain.LoadTree(i)
        chain.GetEntry(i)

        if 'GEN' in label:
            pionp4 = chain.Gen_Pion_P4[0]
        else:
            if chain.nXcand <= 0:
                continue
            pionp4 = pionp4 = chain.PionPP4[0]
        hist.Fill(pionp4.Pt())
        nfill += 1
        
    sys.stdout.write('Filled %s events. \n' %nfill)
    hist.GetXaxis().SetTitle('p_{T} (GeV/c)')
    hist.Draw()
    canvas.SaveAs(figfile)
    hist.Delete()
        
Exemplo n.º 10
0
def cli():
    
    helpString = "This script takes an input Sim file from Cosima and spits out a Root\
    file which can be used in Alex MGeant analysis scripts.  Takes as\
    input the Simulation File name and the Root File name."

    import argparse

    parser = argparse.ArgumentParser(description=helpString)
    parser.add_argument("SimFile", help="Input Simulation File (from Cosima)")
    parser.add_argument("RootFile", help="Output Root File")

    args = parser.parse_args()
    
    from EventViewer import parse
    from ROOT import TFile, TTree, AddressOf

    sim = parse(args.SimFile)
    print "There are {} events in this file.".format(len(sim.events))

    #for event in sim.events[:10]:
    #    print event.hits

    #Make the tree
    f = TFile(args.RootFile, 'RECREATE')
    t = TTree('h10','Simulations')

    MGS = MGSimulation()

    t.Branch('Runevt', AddressOf(MGS.MGStruct, 'Runevt'), 'Runevt/F')
    t.Branch('Xcor', AddressOf(MGS.MGStruct, 'Xcor'), 'Xcor/F')
    t.Branch('Ycor', AddressOf(MGS.MGStruct, 'Ycor'), 'Ycor/F')
    t.Branch('Zcor', AddressOf(MGS.MGStruct, 'Zcor'), 'Zcor/F')
    t.Branch('Estep', AddressOf(MGS.MGStruct, 'Estep'), 'Estep/F')
    #t.Branch('Det', AddressOf(MGS.MGStruct, 'Det'), 'Det/F')
    
    for event in sim.events:

        hits = zip(event.hits.detector,
                   event.hits.x,
                   event.hits.y,
                   event.hits.z,
                   event.hits.energy)
    
        for hit in hits:
            MGS.MGStruct.Runevt = float(event.id_trigger)
            #MGS.MGStruct.Det = hit[0]
            MGS.MGStruct.Xcor = hit[1]
            MGS.MGStruct.Ycor = hit[2]
            MGS.MGStruct.Zcor = hit[3]
            MGS.MGStruct.Estep = hit[4]
            t.Fill()

    f.Write()
    f.Close()
Exemplo n.º 11
0
    def __init__(self, file, tree, events):

        self.file = file
        self.tree = tree
        self.events = events

        # self.tree.Branch("events", events, 'nEvts/I:nPhotons:Energy')
        self.tree.Branch("nPhotons", AddressOf(self.events, 'nPhotons'),
                         'nPhotons/I')
        self.tree.Branch("isr_e", AddressOf(self.events, 'Energy'),
                         'isr_e[nPhotons]/D')
Exemplo n.º 12
0
    def initLBData(self):

        self.lbDataStruct = self.getLBDataStruct()

        # l = 64 bit unsigned int, L = 64 bit signed int
        self.tree.Branch('LBDATA', self.lbDataStruct,
                         'StartTime/l:EndTime/l:Run/i:LB/i:stable/i')

        self.tree.Branch('BPTXBeam1All',
                         AddressOf(self.lbDataStruct, 'fBPTXBeam1'),
                         'BPTXBeam1All/F')
        self.tree.Branch('BPTXBeam2All',
                         AddressOf(self.lbDataStruct, 'fBPTXBeam2'),
                         'BPTXBeam2All/F')
        self.tree.Branch('BCTBeam1All',
                         AddressOf(self.lbDataStruct, 'fBCTBeam1'),
                         'BCTBeam1All/F')
        self.tree.Branch('BCTBeam2All',
                         AddressOf(self.lbDataStruct, 'fBCTBeam2'),
                         'BCTBeam2All/F')
        self.tree.Branch('DCCTBeam1All',
                         AddressOf(self.lbDataStruct, 'fDCCTBeam1'),
                         'DCCTBeam1All/F')
        self.tree.Branch('DCCTBeam2All',
                         AddressOf(self.lbDataStruct, 'fDCCTBeam2'),
                         'DCCTBeam2All/F')
        self.tree.Branch('DCCT24Beam1All',
                         AddressOf(self.lbDataStruct, 'fDCCT24Beam1'),
                         'DCCT24Beam1All/F')
        self.tree.Branch('DCCT24Beam2All',
                         AddressOf(self.lbDataStruct, 'fDCCT24Beam2'),
                         'DCCT24Beam2All/F')
Exemplo n.º 13
0
    def setBranchAddress(self, tree, varname, holder, pointername=None):
        if not pointername: pointername = varname
        " Set tree branch varname to holder "
        if not tree.GetBranchStatus(varname):
            tree.SetBranchStatus(varname, True)
            # fix the AddressOf in new ROOT versions we need only one argument

            try:
                tree.SetBranchAddress(varname, AddressOf(holder, pointername))
            except:
                tree.SetBranchAddress(varname, AddressOf(holder))
            MSG_DEBUG(self, "Set %s branch address on %s", varname, tree)
        else:
            MSG_DEBUG(self, "Already set %s branch address on %s", varname,
                      tree)
Exemplo n.º 14
0
    def make_root(self, parse):

        #ROOT output

        nam = parse.get("lgen", "nam").strip("\"'") + ".root"
        print "ROOT output name:", nam

        self.out_root = TFile(nam, "recreate")
        #tree variables, all Double_t
        tlist = ["phot_en", "phot_theta", "phot_phi"]
        tlist += ["el_en", "el_theta", "el_phi"]
        #C structure holding the variables
        struct = "struct tree_out { Double_t "
        for i in tlist:
            struct += i + ", "
        struct = struct[:-2] + ";};"
        gROOT.ProcessLine(struct)
        #create the output tree
        self.tree_out = rt.tree_out()  # instance of the C structure
        self.ltree = TTree("ltree", "ltree")
        for i in tlist:
            exec("self.tree_out." + i + "=0")
            self.ltree.Branch(i, AddressOf(self.tree_out, i), i + "/D")

        #particles array
        self.particles_out = TClonesArray("TParticle")
        self.particles_out.SetOwner(True)
        self.ltree.Branch("particles", self.particles_out)

        atexit.register(self.close_root)
Exemplo n.º 15
0
 def load_phase_template(self, path):
     from ROOT import TTree, TFile, gROOT, AddressOf
     gROOT.ProcessLine("""struct fidSettings_t {
         Double_t const_baseline;
         Double_t const_baseline_used;
         Double_t edge_width;
         Double_t edge_ignore;
         Double_t start_amplitude;
         Double_t baseline_freq_thresh;
         Double_t filter_low_freq;
         Double_t filter_high_freq;
         Double_t filter_freq_width;
         Double_t fft_peak_width;
         Double_t centroid_thresh;
         Double_t hyst_thresh;
         Double_t snr_thresh;
         Double_t len_thresh;
         Double_t t0_shift;
         Double_t t0_shift_corr;
         Double_t LengthReduction;
         Double_t LengthReduction1;
         Double_t LengthReduction2;
         Double_t LengthReduction3;
         Double_t SpikeThreshold;
         Double_t FreqTemplate[378];
         Double_t PhaseTemplate[378*4096];
         Int_t    PhaseTemplateN;
         Int_t fit_range_scheme;
         Int_t phase_fit_scheme;
         Int_t SmoothWidth;
         UInt_t TruncateBeginning;
         UInt_t TruncateEnd;
         UInt_t ZeroPadding;
         UInt_t const_baseline_start;
         UInt_t const_baseline_end;
         UInt_t baseline_mode;
         UInt_t baseline_event;
         UInt_t SmoothIteration;
         UInt_t poln;
         UInt_t auto_filter_window;
         UInt_t higher_order_correction;
         UInt_t ha_npar;
         UInt_t NSample;
         UInt_t CompareDistance;
         UInt_t HalfVetoWindow;
         UInt_t FitStart[378];
         UInt_t FitEnd[378];
         UInt_t NZeros[378];
         char filter[64];
         char PhaseTemplateFile[128];
         char TemplatePath[128];
         char FitRangeTemplateFile[128];}""")
     from ROOT import fidSettings_t
     data = fidSettings_t()
     f = TFile(path)
     tree = f.Get("SettingsCollector/settings")
     tree.SetBranchAddress("FixedProbeFid", AddressOf(data,"const_baseline"))
     tree.GetEntry(0)
     self.phase_template = np.array(np.frombuffer(data.PhaseTemplate, dtype='double').reshape([378,4096]))
     self.frequency_template = np.array(np.frombuffer(data.FreqTemplate, dtype='double').reshape(378))
Exemplo n.º 16
0
def create_simple_tree(nevents):
    """Create a simple TTree with a couple of branches."""
    t = TTree('aTTree','A TTree')
    t.Branch('run', AddressOf(pytree, 'run'),'run/I')
    t.Branch('evt', AddressOf(pytree, 'evt'),'evt/I')
    t.Branch('x', AddressOf(pytree, 'x'),'x/F')
    t.Branch('y', AddressOf(pytree, 'y'),'y/F')
    t.Branch('z', AddressOf(pytree, 'z'),'z/F')
    for i in range(nevents):
        pytree.run = 1 if (i<500) else 2
        pytree.evt = i
        pytree.x = gauss(0., 10.)
        pytree.y = gauss(0, 10.)
        pytree.z = gauss(5., 50.)
        t.Fill()
    return t
Exemplo n.º 17
0
    def save_delta_VTHR_root(self):
        """
        Save the information about thr and baseline in a root file
        :return:
        """

        if self.primo_giro:
            gROOT.ProcessLine('struct TreeStruct2 {\
                            int layer_id;\
                            int gemroc_id;\
                            int software_feb_id;\
                            int channel_id;\
                            int baseline_t;\
                            int baseline_e;\
                            int vth1;\
                            int vth2;\
                            int delta_vth1_baseline;\
                            int delta_vth2_baseline;\
                            float thr_t_fC;\
                            float thr_e_fC;\
            };')
            self.primo_giro=False
        rootFile = ROOT.TFile("delta_vth.root", 'recreate')
        tree = ROOT.TTree('tree', '')
        mystruct = ROOT.TreeStruct2()
        for key in ROOT.TreeStruct2.__dict__.keys():
            if '__' not in key:
                formstring = '/F'
                if isinstance(mystruct.__getattribute__(key), int):
                    formstring = '/I'
                tree.Branch(key, AddressOf(mystruct, key), key + formstring)

        for GEMROC in range(0, 11):
            if GEMROC < 4:
                lyr = 1
            elif GEMROC < 11:
                lyr = 2
            else:
                lyr = 3
            for TIGER in range(0, 8):
                for ch in range(0, 64):
                    mystruct.layer_id = int(lyr)
                    mystruct.gemroc_id = (int(GEMROC))
                    mystruct.software_feb_id = int(TIGER)
                    mystruct.channel_id = int(ch)
                    mystruct.baseline_t = int(self.real_baseline_T[GEMROC][TIGER][ch])
                    mystruct.baseline_e = int(self.real_baseline_E[GEMROC][TIGER][ch])
                    mystruct.vth1 = int(self.thr_matrix_T[GEMROC][TIGER][ch])
                    mystruct.vth2 = int(self.thr_matrix_E[GEMROC][TIGER][ch])
                    mystruct.delta_vth1_baseline = int(self.real_baseline_T[GEMROC][TIGER][ch]-self.thr_matrix_T[GEMROC][TIGER][ch])
                    mystruct.delta_vth2_baseline = int(self.real_baseline_E[GEMROC][TIGER][ch]-self.thr_matrix_E[GEMROC][TIGER][ch])
                    mystruct.thr_t_fC = float(self.real_baseline_T[GEMROC][TIGER][ch]-self.thr_matrix_T[GEMROC][TIGER][ch])*0.42
                    mystruct.thr_e_fC = float(self.real_baseline_E[GEMROC][TIGER][ch]-self.thr_matrix_E[GEMROC][TIGER][ch])*0.42
                    tree.Fill()

        rootFile.Write()
        rootFile.Close()
        os.system("root -l convert_VTH.cxx")
        os.system("rm delta_vth.root")
Exemplo n.º 18
0
   def test05WriteSomeDataObjectBranched( self ):
      """Test writing of a complex object across different branches"""

      f = TFile( self.fname, 'RECREATE' )
      t = TTree( self.tname, self.ttitle )

      d = SomeDataStruct()

    # note: for p2.2, which has incomplete support of property types,
    # we need to keep a reference alive to the result of the property
    # call, or it will be deleted too soon; for later pythons, it is
    # safe to use d.Floats directly in the Branch() call
      fl = d.Floats
      t.Branch( 'floats', fl )

      if exp_pyroot:
          # The Branch pythonization expects an integer with the
          # address of the field of the struct
          addressof_nlabel = addressof( d, 'NLabel' )
          addressof_label  = addressof( d, 'Label' )
      else:
          # Old PyROOT has a bug in AddressOf(o, 'field').
          # Instead of returning a buffer whose first position
          # contains the address of the field, it just returns the
          # address of the field (which is what we need here).
          # addressof(o, 'field'), which is what we should really
          # use, is also broken in old PyROOT, so we need to use
          # AddressOf here
          addressof_nlabel = AddressOf( d, 'NLabel' )
          addressof_label  = AddressOf( d, 'Label' )

      t.Branch( 'nlabel', addressof_nlabel, 'NLabel/I' )
      t.Branch( 'label',  addressof_label,  'Label/C' )

      for i in range( self.N ):
         for j in range( self.M ):
            d.Floats.push_back( i*self.M+j )

         d.NLabel = i
         d.Label  = '%d' % i

         t.Fill()

      f.Write()
      f.Close()
Exemplo n.º 19
0
    def test14OpaquePointerPassing(self):
        """Test passing around of opaque pointers"""

        import ROOT

        s = TString("Hello World!")
        co = AsCObject(s)

        if self.exp_pyroot:
            # In new Cppyy, addressof returns an integer/long
            ad = AddressOf(s)
        else:
            ad = AddressOf(s)[0]

        self.assert_(s == BindObject(co, s.__class__))
        self.assert_(s == BindObject(co, "TString"))
        self.assert_(s == BindObject(ad, s.__class__))
        self.assert_(s == BindObject(ad, "TString"))
Exemplo n.º 20
0
 def __setBranchAddress( self, tree, varname, holder ):
   " Set tree branch varname to holder "
   if not tree.GetBranchStatus(varname):
     tree.SetBranchStatus( varname, True )
     from ROOT import AddressOf
     tree.SetBranchAddress( varname, AddressOf(holder, varname) )
     self._debug("Set %s branch address on %s", varname, tree )
   else:
     self._debug("Already set %s branch address on %s", varname, tree)
Exemplo n.º 21
0
 def _bindBranches(self,name,items,datastore):        
     struct = self.myStructs[name]
     if isinstance(datastore,dict):
         tree = self.myTrees[name]
         #print ROOT.selected_z_vars_holder.ell1LVec
         for item in items:                
             #print name, item, getattr(struct,item)
             if ( isinstance(datastore[item],int) or
                  isinstance(datastore[item],bool) ):
                 tree.Branch(item,
                             AddressOf(struct,item),
                            '%s/I'%item)
             elif isinstance(datastore[item],float):
                 tree.Branch(item,
                             AddressOf(struct,item),
                             '%s/F'%item)
             elif isinstance(datastore[item],long):
                 tree.Branch(item,
                             AddressOf(struct,item),
                             '%s/L'%item)
             elif isinstance(datastore[item],ROOT.TObject):
                 tree.Branch(item,
                             datastore[item].Class().GetName(),
                             self.myDicts[name][item])
             else:
                 raise Exception("Type %s not supported"%type(datastore[item]))
     elif isinstance(datastore,TTree):
         
         tree = self.importedTrees[name]
         leaves = tree.GetListOfLeaves()
         size = leaves.GetEntries()
         for i in range(size):                
             leafName = leaves.At(i).GetName()
             #sanitize leafnames... weirdness
             if leafName[-1] == '_':
                 leafName = leafName[0:-1]               
             if ( items is None or
                  leafName in items ):
                 tree.SetBranchAddress(leafName,
                                       AddressOf(struct,leafName))
                 
     else:
         print "Data store type %s is not supported!"%(str(type(datastore)))
         exit(1) 
Exemplo n.º 22
0
def get_bins(tree, bnam, bmatch, prec, ons, delt):

    #load tracks momenta to lists for all and matched tracks

    tree.SetBranchStatus("*", 0)
    tree.SetBranchStatus(bnam[0], 1)
    tree.SetBranchStatus(bnam[1], 1)
    tree.SetBranchStatus(bmatch[0], 1)
    tree.SetBranchStatus(bmatch[1], 1)

    #C++ structure for tree entry
    gROOT.ProcessLine("struct Entry {Double_t p0, p1; Bool_t match0, match1;};")
    entry = rt.Entry()
    tree.SetBranchAddress(bnam[0], AddressOf(entry, "p0"))
    tree.SetBranchAddress(bnam[1], AddressOf(entry, "p1"))
    tree.SetBranchAddress(bmatch[0], AddressOf(entry, "match0"))
    tree.SetBranchAddress(bmatch[1], AddressOf(entry, "match1"))

    #momenta values for all and matched tracks
    valAll = rt.list(double)()
    valSel = rt.list(double)()

    for i in xrange(tree.GetEntriesFast()):
        tree.GetEntry(i)
        valAll.push_back(entry.p0)
        valAll.push_back(entry.p1)
        if entry.match0 == 1: valSel.push_back(entry.p0)
        if entry.match1 == 1: valSel.push_back(entry.p1)

    tree.ResetBranchAddresses()

    #bin edges
    bins = vector(rt.double)()

    t0 = time()

    #runs faster when the algorithm is in plain ROOT
    gROOT.LoadMacro("get_bins.C")
    rt.get_bins(bins, valAll, valSel, prec, ons, delt)

    t1 = time()
    print "Time to calculate the bins (sec):", t1-t0

    return bins
Exemplo n.º 23
0
def mkdir_cd_rootfile(root_file_, folder_path_):
    from ROOT import AddressOf

    try:
        AddressOf(root_file_.GetDirectory(folder_path_))
    except ValueError:
        root_file_.mkdir(folder_path_)

    root_file_.cd(folder_path_)
    return root_file_.GetDirectory(folder_path_)
Exemplo n.º 24
0
    def save_delta_VTHR_root(self):
        """
        Save the information about thr and baseline in a root file
        :return:
        """
        gROOT.ProcessLine('struct TreeStruct2 {\
                        int layer_id;\
                        int gemroc_id;\
                        int software_feb_id;\
                        int channel_id;\
                        int baseline;\
                        int vth1_digit;\
                        int vth2_digit;\
                        float vth1_mV;\
                        float vth2_mV;\
                        };')
        rootFile = ROOT.TFile("thresholds.root", 'recreate')
        tree = ROOT.TTree('tree', '')
        mystruct = ROOT.TreeStruct2()
        for key in ROOT.TreeStruct2.__dict__.keys():
            if '__' not in key:
                formstring = '/F'
                if isinstance(mystruct.__getattribute__(key), int):
                    formstring = '/I'
                tree.Branch(key, AddressOf(mystruct, key), key + formstring)

        for GEMROC in range(0, 4):
            for TIGER in range(0, 8):
                for ch in range(0, 64):
                    mystruct.layer_id = int(1)
                    mystruct.gemroc_id = (int(GEMROC))
                    mystruct.software_feb_id = int(TIGER)
                    mystruct.channel_id = int(ch)
                    mystruct.vth1_digit = int(self.thr_matrix_T[GEMROC][TIGER][ch])
                    mystruct.vth2_digit = int(self.thr_matrix_E[GEMROC][TIGER][ch])
                    mystruct.vth1_mV = float(mystruct.vth1_digit*step+base_value)
                    mystruct.vth2_mV = float(mystruct.vth2_digit*step+base_value)
                    tree.Fill()

        for GEMROC in range(4, 11):
            for TIGER in range(0, 8):
                for ch in range(0, 64):
                    mystruct.layer_id = int(2)
                    mystruct.gemroc_id = (int(GEMROC))
                    mystruct.software_feb_id = int(TIGER)
                    mystruct.channel_id = int(ch)
                    mystruct.baseline = int(self.real_baseline_T[GEMROC][TIGER][ch])
                    mystruct.vth1_digit = int(self.thr_matrix_T[GEMROC][TIGER][ch])
                    mystruct.vth2_digit = int(self.thr_matrix_E[GEMROC][TIGER][ch])
                    mystruct.vth1_mV = float(mystruct.vth1_digit*step+base_value)
                    mystruct.vth2_mV = float(mystruct.vth2_digit*step+base_value)
                    tree.Fill()
        rootFile.Write()
        rootFile.Close()
Exemplo n.º 25
0
 def extract_baseline(self):
     """
     Excrat the baseline values and write them in a pickle (and in a root file)
     :return:
     """
     # Create root file and tree
     map_file = ROOT.TFile.Open("mapping_IHEP_L2_2planari_penta.root")
     mapping_matrix = {1: {}, 2: {}, 3: {}, 0: {}}
     for event in map_file.tree:
         mapping_matrix[event.layer_id][event.HW_FEB_id, event.chip_id] = [
             event.gemroc_id, event.SW_FEB_id
         ]
     gROOT.ProcessLine('struct TreeStruct {\
             int layer_id;\
             int hardware_FEB_id;\
             int chip_id;\
             int channel_id;\
             float baseline;\
             };')
     rootFile = ROOT.TFile("baselines.root", 'recreate')
     tree = ROOT.TTree('tree', '')
     mystruct = ROOT.TreeStruct()
     for key in ROOT.TreeStruct.__dict__.keys():
         if '__' not in key:
             formstring = '/F'
             if isinstance(mystruct.__getattribute__(key), int):
                 formstring = '/I'
             tree.Branch(key, AddressOf(mystruct, key), key + formstring)
     for root, dirs, files in os.walk(self.run_path):
         for scan_file, (layer, HW_FEB, chip, others) in glob2.iglob(
                 root + sep + "L*FEB*_c*_VTH*.dat",
                 with_matches=True,
                 recursive=True):
             importer = dt.Import_Data("./", scan_file, False)
             try:
                 GEMROC_ID, TIGER_ID = mapping_matrix[int(layer)][
                     int(HW_FEB), int(chip)]
                 for ch in range(0, 64):
                     data = importer.labVIEW_data[ch][0]['tot_evts']
                     self.baseline_from_calib_matrix[GEMROC_ID][TIGER_ID][
                         ch] = int((np.argmax(data)))
                     # if GEMROC_ID==6 and TIGER_ID==7:
                     #     input("Ho preso per gemroc {}, tiger {} dal file {}".format(GEMROC_ID,TIGER_ID,scan_file))
                     mystruct.layer_id = int(layer)
                     mystruct.hardware_FEB_id = int(HW_FEB)
                     mystruct.chip_id = int(chip)
                     mystruct.channel_id = int(ch)
                     mystruct.baseline = int((np.argmax(data)))
                     tree.Fill()
             except KeyError:
                 print("{} is spare FEB".format(HW_FEB))
     rootFile.Write()
     rootFile.Close()
Exemplo n.º 26
0
 def book(self):
     structcode = ['struct', 'struct_name', '{']
     for var, type in self.vars.iteritems():
         structcode.append('{type} {var};'.format(type=type, var=var))
     structcode.append('};')
     gROOT.ProcessLine(' '.join(structcode))
     from ROOT import struct_name
     self.s = struct_name()
     for var, type in self.vars.iteritems():
         self.ttree.Branch(var, AddressOf(self.s, var),
                           '/'.join([var, self.shortType(type)]))
     self.reinit()
Exemplo n.º 27
0
 def _preSetsLoop(self):
     """ Just build a tree to keep information of each set of toy """
     self.otree = ROOT.TTree("tree", "")
     self.treeContent = ROOT.MyTreeContent()
     self.otree.Branch("fl", AddressOf(self.treeContent, 'fl'), 'fl/D')
     self.otree.Branch("afb", AddressOf(self.treeContent, 'afb'), 'afb/D')
     self.otree.Branch("fs", AddressOf(self.treeContent, 'fs'), 'fs/D')
     self.otree.Branch("transAs", AddressOf(self.treeContent, 'transAs'), 'as/D')
     self.otree.Branch("nSig", AddressOf(self.treeContent, 'nSig'), 'nSig/D')
     self.otree.Branch("nBkgComb", AddressOf(self.treeContent, 'nBkgComb'), 'nBkgComb/D')
     self.otree.Branch("nll", AddressOf(self.treeContent, 'nll'), 'nll/D')
Exemplo n.º 28
0
    def write_root(self, NUM):
        path = "noise.n"
        gROOT.ProcessLine('struct TreeStruct {\
                int layer_id;\
                int gemroc_id;\
                int tiger_id;\
                float noise_lvl;\
                int channel_id;\
                float variance;\
                };')

        rname = path.replace(".n", ".root")

        rootFile = ROOT.TFile(rname, 'recreate')
        tree = ROOT.TTree('tree', '')
        mystruct = ROOT.TreeStruct()

        for key in ROOT.TreeStruct.__dict__.keys():
            if '__' not in key:
                formstring = '/F'
                if isinstance(mystruct.__getattribute__(key), int):
                    formstring = '/I'
                tree.Branch(key, AddressOf(mystruct, key), key + formstring)
        if type(NUM) == tuple:
            first = NUM[0]
            last = NUM[1] + 1
        else:
            first = NUM
            last = NUM + 1
        for G in range(first, last):
            filename = "GEMROC{}".format(G) + sep + "noise.n"
            with open(filename, 'r') as file:
                linee = file.readlines()

            for linea in linee:
                mystruct.gemroc_id = G
                mystruct.tiger_id = int(linea.split()[2].replace("TIG", ""))
                mystruct.channel_id = int(linea.split()[3].replace("CH", ""))
                mystruct.noise_lvl = float(linea.split()[5])
                mystruct.variance = float(linea.split()[7])
                if G < 4:
                    mystruct.layer_id = 1
                elif G < 11:
                    mystruct.layer_id = 2
                else:
                    mystruct.layer_id = 3

                tree.Fill()

        rootFile.Write()
        rootFile.Close()
Exemplo n.º 29
0
    def test13WriteMisnamedLeaf(self):
        """Test writing of an differently named leaf"""

        f = TFile(self.fname, 'RECREATE')
        t = TTree(self.tname, self.ttitle)
        s = SomeDataStruct()
        t.Branch('cpu_packet_time', AddressOf(s, 'NLabel'), 'time/I')

        for i in range(self.N):
            s.NLabel = i
            t.Fill()

        f.Write()
        f.Close()
Exemplo n.º 30
0
def main(input_folder, output_folder, iCore, nCores):
    mySPP = SPP()
    f = TFile(str(output_folder) + 'MC_FS_SPP.root', 'RECREATE')
    tree = TTree('SPP', 'Just A Tree')
    tree.Branch('ASIC', AddressOf(mySPP, 'fAsicID'), 'AsicID/I')
    tree.Branch('Col', AddressOf(mySPP, 'fCol'), 'Col/I')
    tree.Branch('Row', AddressOf(mySPP, 'fRow'), 'Row/I')
    tree.Branch('Original_BCID', AddressOf(mySPP, 'fOriginal_BCID'),
                'Original_BCID/I')
    tree.Branch('Full_BCID', AddressOf(mySPP, 'fFull_BCID'), 'Full_BCID/I')
    tree.Branch('Hitmap', AddressOf(mySPP, 'fHitmap'), 'Hitmap/C')
    tree.Branch('Hitmap_I', AddressOf(mySPP, 'fHitmap_I'), 'Hitmap_I/I')

    fileList = []
    for iFile in glob.glob(os.path.join(str(input_folder), '*.txt')):
        fileList.append(iFile)
    for thisFile in fileList:
        asicID = int(
            ((thisFile.split('/')[1]).split('.')[0]).split('desync')[1])

        if asicID % nCores == iCore:
            print 'Processing file:', thisFile
            with open(thisFile) as i_file:
                raw_data = i_file.read().split('\n')
            spp_list = split_spp(raw_data)
            spp_sorted = time_sort(spp_list)
            cycle = 0
            prevBCID = -1
            for each_spp in spp_sorted:
                if int(each_spp) != 0:
                    myBCID = gtoi(each_spp[:9])
                    if myBCID < prevBCID:
                        cycle += 1
                        if cycle == 21:
                            break
                    prevBCID = myBCID

                    mySPP.fAsicID = asicID
                    mySPP.fCol = int(each_spp[9:16], 2)  #7 bits: from 0 to 128
                    mySPP.fRow = int(each_spp[16:22], 2)  #6 bits: from 0 to 64
                    mySPP.fOriginal_BCID = myBCID
                    mySPP.fFull_BCID = myBCID + 512 * (cycle % 7)
                    mySPP.fHitmap = str(
                        each_spp[22:])  # note string assignment
                    mySPP.fHitmap_I = int(each_spp[22:],
                                          2)  # note string assignment
                    tree.Fill()

    f.Write()
    f.Close()