def test_base_adder_neg(self):
     wave_neg = vector('short')(10,-1000)
     wave_max = vector('short')(10,32767)
     self.rda.AddRawDigits(self.wave1,wave_neg)
     self.assertEqual(wave_neg.size(),10)
     self.assertEqual(wave_neg,wave_max)
     self.assertEqual(self.orig_wave1,self.wave1)
示例#2
0
def draw_pulse():

    #draw a single pulse of photoelectrons using the hits for a given event

    ievt = 7

    cell = "03x03"

    #tree.Print()

    #get the hits from the tree
    hitTime = std.vector(float)()
    hitNphot = std.vector(int)()

    tree.SetBranchAddress("phot_"+cell+"_OpDet_hits_time", hitTime)
    tree.SetBranchAddress("phot_"+cell+"_OpDet_hits_nphot", hitNphot)

    tree.GetEntry(ievt)

    nhits = hitTime.size()

    can = ut.box_canvas()

    gHits = TGraph(nhits)

    for i in xrange(nhits):
        gHits.SetPoint(i, hitTime.at(i), hitNphot.at(i))

    gHits.Draw("A*l")

    ut.invert_col(rt.gPad)
    can.SaveAs("01fig.pdf")
示例#3
0
def main():

    #open the input
    inp = TFile.Open("../../data/lmon.root")
    tree = inp.Get("DetectorTree")

    #get the branches for MC particle
    pdg = std.vector(int)()
    px = std.vector(float)()
    py = std.vector(float)()
    pz = std.vector(float)()
    en = std.vector(float)()

    tree.SetBranchAddress("gen_pdg", pdg)
    tree.SetBranchAddress("gen_px", px)
    tree.SetBranchAddress("gen_py", py)
    tree.SetBranchAddress("gen_pz", pz)
    tree.SetBranchAddress("gen_en", en)

    ievt = 2  # event number to read

    #load the event
    tree.GetEntry(ievt)

    #loop over MC particles, all vectors are of the same size
    for i in xrange(pdg.size()):

        print i, pdg.at(i), px.at(i), py.at(i), pz.at(i), en.at(i)
def load_croppedset_sparse_dualflow_nomc(io,
                                         producer="croppedadc",
                                         threshold=10.0):

    # get crop set
    ev_crops = io.get_data(larcv.kProductImage2D, producer)
    crop_v = ev_crops.Image2DArray()
    ncrops = crop_v.size()
    nsets = ncrops / 3

    print "Number of sets=", nsets, " ncrops=", ncrops

    thresh_v = std.vector('float')(3, threshold)
    cuton_v = std.vector('int')(3, 1)

    # we are making a batch. collect the sparse arrays
    data = {"pixadc": []}
    for iset in xrange(nsets):
        # get instance, convert to numpy array, nfeatures per flow
        sparsedata = larcv.SparseImage(crop_v, iset * 3, iset * 3 + 2,
                                       thresh_v, cuton_v)
        sparse_np = larcv.as_ndarray(sparsedata, larcv.msg.kNORMAL)
        data["pixadc"].append(sparse_np)
        #print "nfeatures: ",nfeatures
    return data
示例#5
0
	def __init__(self,readname=None,writename=None,ttreetype='F',inival=-900.,size='1') :
		self.__readname=readname
		self.__writename=writename
		self.__ttreetype=ttreetype
		self.__inival = inival
		if (self.__ttreetype=='I' or self.__ttreetype=='i') and self.__inival==-900. :
			self.__inival=0
		self.__size = size
		#figure out the array type
		self.__arraytype = get_array_type(ttreetype)
		#figure out the array length
		self.__arraylength = get_array_length(size)
		#Set the array to read into
		if readname!=None :
			if ttreetype!='vi' :
				if self.__arraylength>1 :
					self.__readArray = array(self.__arraytype,self.__arraylength*[self.__inival])
				else :
					self.__readArray = array(self.__arraytype,[self.__inival])
			else :
				self.__readArray = std.vector(std.vector('int'))()
		#Set the array to write into
		if writename!=None :
			#If we're just copying over, use the same array to read and write
			if readname!=None :
				self.__writeArray = self.__readArray
			elif self.__arraylength>1 :
				self.__writeArray = array(self.__arraytype,self.__arraylength*[self.__inival])
			else :
				self.__writeArray = array(self.__arraytype,[self.__inival])
示例#6
0
   def test03NamespaceInTemplates( self ):
      """Templated data members need to retain namespaces of arguments"""

      PR_NS_A = ROOT.PR_NS_A

      p = std.pair( std.vector( PR_NS_A.PR_ST_B ), std.vector( PR_NS_A.PR_NS_D.PR_ST_E ) )()
      self.assert_( "vector<PR_NS_A::PR_ST_B>" in type(p.first).__name__ )
      self.assert_( "vector<PR_NS_A::PR_NS_D::PR_ST_E>" in type(p.second).__name__ )
示例#7
0
   def test03NamespaceInTemplates( self ):
      """Templated data members need to retain namespaces of arguments"""

      PR_NS_A = ROOT.PR_NS_A

      p = std.pair( std.vector( PR_NS_A.PR_ST_B ), std.vector( PR_NS_A.PR_NS_D.PR_ST_E ) )()
      self.assert_( "vector<PR_NS_A::PR_ST_B>" in type(p.first).__name__ )
      self.assert_( "vector<PR_NS_A::PR_NS_D::PR_ST_E>" in type(p.second).__name__ )
 def test_base_adder_list(self):
     waveList = vector(vector('short'))()
     waveList.push_back(self.wave1)
     waveList.push_back(self.wave2)
     self.rda.AddRawDigits(waveList,self.wave3)
     self.assertEqual(self.wave2.size(),10)
     self.assertEqual(self.wave3,self.wave1pwave2)
     self.assertEqual(self.orig_wave1,self.wave1)
     self.assertEqual(self.orig_wave2,self.wave2)
 def test_base_adder_list(self):
     waveList = vector(vector('short'))()
     waveList.push_back(self.wave1)
     waveList.push_back(self.wave2)
     self.rda.AddRawDigits(waveList,self.wave3)
     self.assertEqual(self.wave2.size(),10)
     for x in range(0,10):
         self.assertEqual(self.wave3[x],self.wave1pwave2[x])
         self.assertEqual(self.orig_wave1[x],self.wave1[x])
         self.assertEqual(self.orig_wave2[x],self.wave2[x])
示例#10
0
    def __init__(self, name, tree):

        #hit representation in the tree
        self.pdg = std.vector(int)()
        self.en = std.vector(float)()
        self.hx = std.vector(float)()
        self.hy = std.vector(float)()
        self.hz = std.vector(float)()
        self.prim = std.vector(int)()
        self.conv = std.vector(int)()
        self.edep = std.vector(float)()
        self.nsec = std.vector(int)()

        tree.SetBranchAddress(name + "_HitPdg", self.pdg)
        tree.SetBranchAddress(name + "_HitEn", self.en)
        tree.SetBranchAddress(name + "_HitX", self.hx)
        tree.SetBranchAddress(name + "_HitY", self.hy)
        tree.SetBranchAddress(name + "_HitZ", self.hz)
        tree.SetBranchAddress(name + "_HitPrim", self.prim)
        tree.SetBranchAddress(name + "_HitConv", self.conv)
        tree.SetBranchAddress(name + "_HitEdep", self.edep)
        tree.SetBranchAddress(name + "_HitNsec", self.nsec)

        #interface to the hit
        self.hit = self.Hit()
 def setUp(self):
     self.rda = RawDigitAdder_HardSaturate(False)
     self.wave3 = vector('short')()
     self.wave3 += [0,-1,10,-2,0]
     self.wave1 = vector('short')()
     self.wave1 += [0,1,0,3,9,4,1,2,0,1]
     self.wave2 = vector('short')()
     self.wave2 += [1,1,8,22,15,2,0,0,1,3]
     self.wave1pwave2 = vector('short')()
     self.wave1pwave2 += [1,2,8,25,24,6,1,2,1,4]
     self.orig_wave1=self.wave1
     self.orig_wave2=self.wave2
     self.orig_wave3=self.wave3
示例#12
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()
示例#13
0
    def __init__( self, input_larcv_files, input_ana_files, npairs=20000, use_triplets=True ):

        self.input_larcv_files = input_larcv_files
        self.input_ana_files   = input_ana_files
        
        # load chain
        self.match_v = std.vector("larflow::FlowMatchMap")()
        self.tchain = rt.TChain("flowmatchdata")
        for fin in input_ana_files:
            print "adding ana file: ",fin
            self.tchain.Add( fin )
        self.tchain.SetBranchAddress( "matchmap", rt.AddressOf(self.match_v))
        print "chain has ",self.tchain.GetEntries()," entries"

        self.params = {"has_truth":True,
                       "verbose":False,
                       "npairs":npairs,
                       "matchtree":self.tchain,
                       "match_v":self.match_v}
        
        self.nworkers = 1
        self.feeder = LArCVServer(1,"larmatchfeed",
                                  load_larmatch_data,
                                  self.input_larcv_files,
                                  self.nworkers,
                                  io_tickbackward=False,
                                  func_params=self.params)
示例#14
0
def vec(vv):
    from ROOT import std
    import array
    return array.array('d', vv)
    vvv = std.vector("double")()
    for v in vv:
        vvv.push_back(v)
    return vvv
示例#15
0
def stdVector(*args):
    '''Make a std::vector from a python list'''
    from ROOT import std
    floatType = False
    for i in args:
        floatType |= isinstance(i, float)

    if floatType:
        vec = std.vector(float)()
        for i in args:
            vec.push_back(i)
        return vec
    else:
        vec = std.vector(int)()
        for i in args:
            vec.push_back(i)
        return vec
示例#16
0
    def process_entry(self,entry_num):
        """
        perform all actions -- send, receive, process, store -- for entry.

        we must:
        1) split full image into 3D-correlated crops for larflow
        2) package up into messages
        3) send, then get reply
        """

        # timing
        ttotal = time.time()

        tread = time.time()

        # get the entries
        ok = self._inlarcv.read_entry(entry_num)
        if not ok:
            raise RuntimeError("could not read larcv entry %d"%(entry_num))

        ev_wholeview = self._inlarcv.get_data(larcv.kProductImage2D,
                                              self._adc_producer)
        wholeview_v = ev_wholeview.Image2DArray()

        tread = time.time()-tread

        tsplit = time.time()
        roi_v  = std.vector("larcv::ROI")()
        crop_v = std.vector("larcv::Image2D")()
        self._split_algo.process( wholeview_v, crop_v, roi_v )
        tsplit = time.time()-tsplit
        print("split whole image into {} crops in {} secs".format(crop_v.size(),tsplit))

        flow_v = self.sendreceive_crops(crop_v,
                                        self._inlarcv.event_id().run(),
                                        self._inlarcv.event_id().subrun(),
                                        self._inlarcv.event_id().event())

        self.store_replies(flow_v, crop_v)

        self._outlarcv.set_id( self._inlarcv.event_id().run(),
                               self._inlarcv.event_id().subrun(),
                               self._inlarcv.event_id().event())

        self._outlarcv.save_entry()
        return True
示例#17
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)
 def test_hs_adder_hardsaturate(self):
     hs_wave1pwave2 = vector('short')()
     hs_wave1pwave2 += [1,2,8,20,20,6,1,2,1,4]
     self.rda.SetSaturationPoint(20)
     self.rda.AddRawDigits(self.wave1,self.wave2,self.wave3)
     self.assertEqual(self.wave3.size(),10)
     self.assertEqual(self.wave3,hs_wave1pwave2)
     self.assertEqual(self.orig_wave1,self.wave1)
     self.assertEqual(self.orig_wave2,self.wave2)
示例#19
0
def MGTWFFromNpArray(npArr):
    """ Convert a numpy array back into an MGTWaveform. """
    from ROOT import MGTWaveform, std
    vec = std.vector("double")()
    for adc in npArr:
        vec.push_back(adc)
    mgtwf = MGTWaveform()
    mgtwf.SetData(vec)
    return mgtwf
示例#20
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()
示例#21
0
def main():

    inp = TFile.Open("../lmon.root")
    tree = inp.Get("DetectorTree")

    #tree.Print()

    gen_pdg = std.vector(int)()
    gen_en = std.vector(float)()
    tree.SetBranchAddress("gen_pdg", gen_pdg)
    tree.SetBranchAddress("gen_en", gen_en)

    tree.GetEntry(0)

    ngen = gen_pdg.size()

    for i in range(ngen):

        print i, gen_pdg.at(i), gen_en.at(i)
示例#22
0
   def test2WriteNonTObjectDerived( self ):
      """Test writing of an std::vector<double> into a pickle file"""

      v = std.vector( 'double' )()

      for i in range( Nvec ):
         v.push_back( i*i )

      pickle.dump(  v, self.out1 )
      cPickle.dump( v, self.out2 )
示例#23
0
   def test2WriteNonTObjectDerived( self ):
      """Test writing of an std::vector<double> into a pickle file"""

      v = std.vector( 'double' )()

      for i in range( Nvec ):
         v.push_back( i*i )

      pickle.dump(  v, self.out1 )
      cPickle.dump( v, self.out2 )
示例#24
0
文件: kde.py 项目: tglauch/KDE_Tool
    def eval_point(self, point):
        l = self.args.ndim
        #l = len(point)
        #if not l==self.args.ndim:
        #	print "dim(point) != dim(phasespace) !!"
        #	sys.exit(1)

        v = std.vector(Double)(l)
        for i in range(l):
            v[i] = point[i]
        return self.kde.density(v) * self.kde_norm
def createMorph(obs, nuis_var, norm, up, down):
    pdf_list = RooArgList()
    pdf_list.add(down)
    pdf_list.add(up)
    pdf_list.add(norm)  # nominal pdf

    nref_points = std.vector('double')()
    nref_points.push_back(-1)
    nref_points.push_back(1)

    nnuis_points = std.vector('int')()
    nnuis_points.push_back(2)

    par_list = RooArgList()
    par_list.add(nuis_var)

    morph = ROOT.RooStarMomentMorph("morph", "morph", par_list, obs, pdf_list,
                                    nnuis_points, nref_points,
                                    ROOT.RooStarMomentMorph.Linear)
    return morph
示例#26
0
    def test3TemplateInstantiationWithVectorOfFloat(self):
        """Test template instantiation with a std::vector< float >"""

        gROOT.LoadMacro("Template.C+")
        MyTemplatedClass = ROOT.MyTemplatedClass

        # the following will simply fail if there is a naming problem (e.g. std::,
        # allocator<int>, etc., etc.); note the parsing required ...
        b = MyTemplatedClass(std.vector(float))()

        for i in range(5):
            b.m_b.push_back(i)
            self.assertEqual(round(b.m_b[i], 5), float(i))
示例#27
0
      def fill( self ):
         v = std.vector( 'PR_ValClass*' )()
         n = fillVect( v )

         self.assertEqual( n, len(v) )
         self.assertEqual( v[0].m_val, "aap" )

         m = {}
         for i in range( n ):
            m[i] = v[i]

         self.assertEqual( len(m), len(v) )
         return m
示例#28
0
      def fill( self ):
         v = std.vector( 'PR_ValClass*' )()
         n = fillVect( v )

         self.assertEqual( n, len(v) )
         self.assertEqual( v[0].m_val, "aap" )

         m = {}
         for i in range( n ):
            m[i] = v[i]

         self.assertEqual( len(m), len(v) )
         return m
示例#29
0
def visualize2d_larlite_shower(larlite_shower):

    cm_per_tick = larutil.LArProperties.GetME().DriftVelocity() * 0.5

    shr = larlite_shower
    shrlen = shr.Length()

    # get projections: vertex
    vtx_v = std.vector("double")(3)
    vtx_v[0] = shr.ShowerStart().X()
    vtx_v[1] = shr.ShowerStart().Y()
    vtx_v[2] = shr.ShowerStart().Z()

    # get projections: end
    end_v = std.vector("double")(3)
    end_v[0] = vtx_v[0] + shrlen * shr.Direction().X()
    end_v[1] = vtx_v[1] + shrlen * shr.Direction().Y()
    end_v[2] = vtx_v[2] + shrlen * shr.Direction().Z()

    # wire coordintes
    vtx = [larutil.Geometry.GetME().WireCoordinate(vtx_v, p) for p in range(3)]
    end = [larutil.Geometry.GetME().WireCoordinate(end_v, p) for p in range(3)]

    shower_traces = {}
    for p in range(3):
        shower_trace = {
            "type": "scatter",
            "x": [vtx[p], end[p]],
            "y":
            [3200 + vtx_v[0] / cm_per_tick, 3200 + end_v[0] / cm_per_tick],
            "mode": "lines",
            "line": {
                "color": "rgb(255,155,255)"
            },
        }
        shower_traces[p] = shower_trace

    return shower_traces
示例#30
0
def make_scin_edep(inlist, outfile):

    #input
    tree = TChain("DetectorTree")
    for i in inlist:
        tree.Add(i)

    scin_istrip = std.vector(int)()
    scin_ilay = std.vector(int)()
    scin_edep = std.vector(float)()

    tree.SetBranchAddress("bpc_scin_istrip", scin_istrip)
    tree.SetBranchAddress("bpc_scin_ilay", scin_ilay)
    tree.SetBranchAddress("bpc_scin_edep", scin_edep)

    #output txt csv
    out = open(outfile, "w")
    out.write("bpc_edep\n")

    #event loop
    nev = tree.GetEntries()
    for ievt in range(nev):
        tree.GetEntry(ievt)

        #deposited energy in event
        edep = 0.

        #scintillator loop
        for iscin in range(scin_edep.size()):

            #print(iscin, scin_istrip.at(iscin), scin_ilay.at(iscin), scin_edep.at(iscin))
            edep += scin_edep.at(iscin)

        out.write(str(edep)+"\n")

    out.close()

    print("Done")
示例#31
0
   def test1AssignToReturnByRef( self ):
      """Test assignment to an instance returned by reference"""
      
      RefTester = ROOT.RefTester

      a = std.vector( RefTester )()
      a.push_back( RefTester( 42 ) )

      self.assertEqual( len(a), 1 )
      self.assertEqual( a[0].m_i, 42 )

      a[0] = RefTester( 33 )
      self.assertEqual( len(a), 1 )
      self.assertEqual( a[0].m_i, 33 )
示例#32
0
   def test3TemplateInstantiationWithVectorOfFloat( self ):
      """Test template instantiation with a std::vector< float >"""

      gROOT.LoadMacro( "Template.C+" )
      MyTemplatedClass = ROOT.MyTemplatedClass


    # the following will simply fail if there is a naming problem (e.g. std::,
    # allocator<int>, etc., etc.); note the parsing required ...
      b = MyTemplatedClass( std.vector( float ) )()

      for i in range(5):
         b.m_b.push_back( i )
         self.assertEqual( round( b.m_b[i], 5 ), float(i) )
示例#33
0
   def test1AssignToReturnByRef( self ):
      """Test assignment to an instance returned by reference"""

      RefTester = ROOT.RefTester

      a = std.vector( RefTester )()
      a.push_back( RefTester( 42 ) )

      self.assertEqual( len(a), 1 )
      self.assertEqual( a[0].m_i, 42 )

      a[0] = RefTester( 33 )
      self.assertEqual( len(a), 1 )
      self.assertEqual( a[0].m_i, 33 )
示例#34
0
def main():

    #open the input
    inp = TFile.Open("../../data/lmon.root")
    tree = inp.Get("DetectorTree")

    #get the branches with scintillator signals
    istrip = std.vector(int)()
    ilay = std.vector(int)()
    edep = std.vector(float)()

    tree.SetBranchAddress("lowQ2_scin_istrip", istrip)
    tree.SetBranchAddress("lowQ2_scin_ilay", ilay)
    tree.SetBranchAddress("lowQ2_scin_edep", edep)

    ievt = 2  # event number to read

    #load the event
    tree.GetEntry(ievt)

    #loop over the scintillators, all vectors are of the same size
    for i in xrange(istrip.size()):

        print i, ilay.at(i), istrip.at(i), edep.at(i)
示例#35
0
    def __init__(self, name, tree):

        #hit representation in the tree
        self.pdg = std.vector(int)()
        self.en = std.vector(float)()
        self.hx = std.vector(float)()
        self.hy = std.vector(float)()
        self.hz = std.vector(float)()

        tree.SetBranchAddress(name+"_HitPdg", self.pdg)
        tree.SetBranchAddress(name+"_HitEn", self.en)
        tree.SetBranchAddress(name+"_HitX", self.hx)
        tree.SetBranchAddress(name+"_HitY", self.hy)
        tree.SetBranchAddress(name+"_HitZ", self.hz)

        #interface to the hit
        self.hit = self.Hit(self)

        #counter position for transformation to local coordinates
        self.xpos = 0.
        self.ypos = 0.
        self.zpos = 0.
        self.theta_y = 0.
        self.theta_x = 0.
示例#36
0
   def test01WriteStdVector( self ):
      """Test writing of a single branched TTree with an std::vector<double>"""

      f = TFile( self.fname, 'RECREATE' )
      t = TTree( self.tname, self.ttitle )
      v = std.vector( 'double' )()
      t.Branch( 'mydata', v.__class__.__name__, v )

      for i in range( self.N ):
         for j in range( self.M ):
            v.push_back( i*self.M+j )
         t.Fill()
         v.clear()
      f.Write()
      f.Close()
示例#37
0
    def test01WriteStdVector(self):
        """Test writing of a single branched TTree with an std::vector<double>"""

        f = TFile(self.fname, 'RECREATE')
        t = TTree(self.tname, self.ttitle)
        v = std.vector('double')()
        t.Branch('mydata', v.__class__.__name__, v)

        for i in range(self.N):
            for j in range(self.M):
                v.push_back(i * self.M + j)
            t.Fill()
            v.clear()
        f.Write()
        f.Close()
示例#38
0
 def readFromROOT(self):
     #Check if data have already been read,
     #if not read in branch data
     if self._cache == None:
         branch = self.getObject()
         if self.branchType == Branch.BranchType.VECTORDOUBLE:
             #Use some ROOT's stuff to read vector<double>
             #Note we need to use ROOT.Double to have correct data type in vectors
             from ROOT import std, Double, AddressOf
             #Create a vector to contain doubles
             vect = std.vector(Double)(self.nelements, 0)
             data = AddressOf(vect)
         else:
             #Create an array to store data for each entry
             datatype = self.nelements * Branch.BranchType._typesMap[
                 self.branchType]
             data = datatype()
         #Set address of branch to the array
         branch.SetAddress(data)
         #Loop on events
         self._cache = []
         for entry in xrange(branch.GetEntries()):
             branch.GetEntry(entry)
             #First simple case of simple variable
             if self.nelements == 1 and self.branchType != Branch.BranchType.VECTORDOUBLE:
                 self._cache.append(data[0])
             else:
                 #Check if specific element is needed or all elements
                 if self.element == -1:
                     #Loop on elements of arrays
                     d = []
                     for elem in xrange(self.nelements):
                         if self.branchType == Branch.BranchType.VECTORDOUBLE:
                             d.append(vect.at(elem))
                         else:
                             d.append(data[elem])
                 else:
                     #Get array/vector element self.element
                     if self.branchType == Branch.BranchType.VECTORDOUBLE:
                         d = vect.at(self.element)
                     else:
                         d = data[self.element]
                 self._cache.append(d)
     return self._cache
示例#39
0
    def compute( self, data, **kwargs ) :
        """computes moments of data set (wrapper for C++ computeRooRealMoments)

        Looping over data in python is quite a bit slower than in C++. Hence, we
        adapt the arguments and then defer to the C++ computeRooRealMoments.
        """
        from P2VV.Load import P2VVLibrary
        from ROOT import std, computeRooRealMoments
        momVec = std.vector('RooRealMoment*')()
        for func in self._basisFuncNames : momVec.push_back( self[func]._var )
        computeRooRealMoments( data, momVec, kwargs.pop( 'ResetFirst', False ), kwargs.pop( 'Verbose', True ) )

        for it1, func1 in enumerate(self._basisFuncNames) :
            self._coefficients[func1] = ( self[func1].coefficient(), self[func1].stdDev(), self[func1].significance() )
            if self._covMatrixSize == len(self._basisFuncNames) :
                corrs = { }
                for it2, func2 in enumerate(self._basisFuncNames) :
                    corrs[func2] = self[func2].correlation( it1 - it2 ) if it2 < it1 else self[func1].correlation( it2 - it1)
                self._correlations[func1] = corrs
示例#40
0
 def readFromROOT(self):
     #Check if data have already been read,
     #if not read in branch data
     if self._cache == None:
         branch = self.getObject()
         if self.branchType == Branch.BranchType.VECTORDOUBLE:
             #Use some ROOT's stuff to read vector<double>
             #Note we need to use ROOT.Double to have correct data type in vectors
             from ROOT import std,Double,AddressOf
             #Create a vector to contain doubles
             vect = std.vector(Double)(self.nelements,0)
             data = AddressOf( vect )
         else:
             #Create an array to store data for each entry
             datatype = self.nelements * Branch.BranchType._typesMap[ self.branchType ] 
             data = datatype()
         #Set address of branch to the array
         branch.SetAddress( data )
         #Loop on events
         self._cache = []
         for entry in xrange( branch.GetEntries() ):
             branch.GetEntry( entry )
             #First simple case of simple variable
             if self.nelements == 1 and self.branchType != Branch.BranchType.VECTORDOUBLE:
                 self._cache.append( data[0] )
             else:
                 #Check if specific element is needed or all elements
                 if self.element == -1: 
                     #Loop on elements of arrays
                     d = []
                     for elem in xrange( self.nelements ):
                         if self.branchType == Branch.BranchType.VECTORDOUBLE:
                             d.append( vect.at(elem) )
                         else:
                             d.append( data[elem] )
                 else:
                     #Get array/vector element self.element
                     if self.branchType == Branch.BranchType.VECTORDOUBLE:
                         d = vect.at( self.element )
                     else:
                         d = data[self.element]
                 self._cache.append( d )
     return self._cache
示例#41
0
def treatPropertyValue(value):

    if (type(value) is list) and (type(value[0]) is str):
        return list_to_stdvector('string', value)
    elif (type(value) is list) and (type(value[0]) is int):
        return list_to_stdvector('int', value)
    elif (type(value) is list) and (type(value[0]) is float):
        return list_to_stdvector('float', value)
    elif (type(value) is list) and (type(value[0]) is bool):
        return list_to_stdvector('bool', value)
    # list of list with ints, should be vector<vector<int>>
    elif (type(value) is list) and (type(value[0]) is list) and (type(
            value[0][0]) is int):
        from ROOT.std import vector
        vec = vector("vector<int>")()
        for v in value:
            vec.push_back(list_to_stdvector('int', v))
        return vec
    else:
        return value
示例#42
0
    def eval_point(self, kernel_density, coord):
        """Evaluates PDF value at a given coordinate of normalized
        `KernelDensity` instance.

        Parameters
        ----------
        kernel_density : KernelDensity
            Binned or adaptive `KernelDensity` instance.
        coord : tuple of floats
            Coordinates of a point at which the `kernel_density` is evaluated.

        Returns
        -------
        value : float
            Evaluated PDF value at a given coordinate of normalized
            `kernel_density`.
        """
        l = len(coord)
        v = std.vector(Double)(l)
        for i in range(l):
            v[i] = coord[i]
        return kernel_density.density(v) * self.model.kde_norm
示例#43
0
def ReadFile(fil,tr,variables):
    data = TFile.Open(fil)
    tree = data.Get(tr)
    label = std.vector('int')(1)
    tree.SetBranchAddress('classID', label)
    
    x,y,w=[],[],[]
    for i in range(tree.GetEntries()):
        tree.GetEntry(i)
        x_tmp=[]
        for var in variables:
            x_tmp.append(getattr(tree,var))
        x.append(x_tmp)
        y_tmp=[]
        for j in range(label.size()):
            y_tmp.append(label[j])
        y.append(y_tmp)
        w.append(getattr(tree,'weight'))
    data.Close()
    
    if len(y[0])==1 : y = [e[0] for e in y]
    
    return x,y,w
示例#44
0
def main():
    args = parser()

    xSecFile = yaml.load(
        file(
            "{}/src/ChargedHiggs/Skimming/data/xsec.yaml".format(
                os.environ["CMSSW_BASE"]), "r"))

    xSec = 1.

    for key in xSecFile.keys():
        if key in args.out_name:
            xSec = xSecFile[key]["xsec"]

    isData = True in [
        name in args.out_name for name in ["Electron", "Muon", "MET"]
    ]

    channels = vector("string")()
    [channels.push_back(channel) for channel in args.channel]

    skimmer = NanoSkimmer(args.filename, isData)
    skimmer.EventLoop(channels, xSec)
    skimmer.WriteOutput(args.out_name)
# default configuration of the ElectronIsEMSelectorCutDefs
# This one is used for tight++ menu

import cppyy
try :
    cppyy.loadDictionary('ElectronPhotonSelectorToolsDict')
except :
    pass
  
from ROOT import egammaPID, std

# Next 3 lines are needed due to a difference how pyROOT and pyCintex handle stl vectors
std.vector('float')
std.vector('double')
std.vector('int')


# Import a needed helper
from PATCore.HelperUtils import *

# Define GeV
GeV = 1000.0

def ElectronIsEMTightSelectorConfigDC14(theTool) :
    '''
    These are the cut base isEM definitions: Tight from MC15
    '''
    
    theTool = GetTool(theTool)

    theTool.ConfigFile = "ElectronPhotonSelectorTools/offline/mc15_20150329/ElectronIsEMTightSelectorCutDefs.conf"
示例#46
0
def multiplyP2VVAngleBases( angleBasis, **kwargs ) :
    doReset = kwargs.pop( 'DoReset', True )

    def __dref__(arg) :
        from ROOT import RooAbsArg
        if isinstance( arg, RooAbsArg ) : return arg
        return arg._var

    if 'Functions' in kwargs :
        funcs = kwargs.pop('Functions')
        if 'Coefficients' in kwargs :
            coefs = kwargs.pop('Coefficients')
            assert len(funcs) == len(coefs)\
                   , 'P2VV - ERROR: multiplyP2VVAngleBases(): numbers of functions and coefficients are different'
        else :
            coefs = [ ConstVar( Name = 'one', Value = 1. ) for it in range( len(funcs) ) ]

        from ROOT import RooArgList
        funcList = RooArgList( __dref__(func) for func in funcs )
        coefList = RooArgList( __dref__(coef) for coef in coefs )
        angleBasis.createProdSum( funcList, coefList, doReset )

    elif all( inds in kwargs for inds in ( 'iIndices', 'jIndices', 'lIndices', 'mIndices' ) ) :
        iInds = kwargs.pop('iIndices')
        jInds = kwargs.pop('jIndices')
        lInds = kwargs.pop('lIndices')
        mInds = kwargs.pop('mIndices')
        assert len(iInds) == len(jInds) == len(lInds) == len(mInds)\
               , 'P2VV - ERROR: multiplyP2VVAngleBases(): different numbers i, j, l and m indices specified'

        if 'FixedCoefs' in kwargs :
            fixCoefs = kwargs.pop('FixedCoefs')
            assert len(iInds) == len(fixCoefs)\
                   , 'P2VV - ERROR: multiplyP2VVAngleBases(): numbers of indices and fixed coefficients are different'
        else :
            fixCoefs = [ 1. for it in range( len(iInds) ) ]

        if 'Coefficients' in kwargs :
            coefs = kwargs.pop('Coefficients')
            assert len(iInds) == len(coefs)\
                   , 'P2VV - ERROR: multiplyP2VVAngleBases(): numbers of indices and coefficients are different'
        else :
            coefs = [ ConstVar( Name = 'one', Value = 1. ) for it in range( len(iInds) ) ]

        from ROOT import std
        iIndsVec    = std.vector('Int_t')()
        jIndsVec    = std.vector('Int_t')()
        lIndsVec    = std.vector('Int_t')()
        mIndsVec    = std.vector('Int_t')()
        fixCoefsVec = std.vector('Double_t')()
        for ind  in iInds    : iIndsVec.push_back(ind)
        for ind  in jInds    : jIndsVec.push_back(ind)
        for ind  in lInds    : lIndsVec.push_back(ind)
        for ind  in mInds    : mIndsVec.push_back(ind)
        for coef in fixCoefs : fixCoefsVec.push_back(coef)

        from ROOT import RooArgList
        coefList = RooArgList( __dref__(coef) for coef in coefs )

        angleBasis.createProdSum( iIndsVec, jIndsVec, lIndsVec, mIndsVec, fixCoefsVec, coefList, doReset )

    else :
        raise RuntimeError, 'P2VV - ERROR: multiplyP2VVAngleBases(): either functions or indices should be specified'
示例#47
0
print 'P2VV - INFO: Processing tree (%s initial entries): %s'%(intermediateTree.GetEntries(),protoTreePath)
if addRunPeriodInfo:   
    print 'P2VV - INFO: Adding run period (%s) info to ntuple'%runPeriod
    addIntegerToTree(intermediateTree, int(runPeriod), 'runPeriod' )

if addKaonSignInfo:
    print 'P2VV - INFO: Adding kaon sign (%+i) info to ntuple'%kaonSign
    addIntegerToTree(intermediateTree, int(kaonSign), 'kaonSign' )

if calculateHelAngles: calculateHelicityAngles(intermediateTree)

if addKpiMassCategory: 
    from ROOT import addCategoryToTree, std
    print 'P2VV - INFO: Adding Kpi-mass category with indices "%s" and KK-mass boundaries "%s" to n-tuple' % ( KpiMassInds, KpiMassBinBounds )
    bounds = std.vector('Double_t')()
    inds   = std.vector('Int_t')()
    for bound in KpiMassBinBounds : bounds.push_back(bound)
    for ind in KpiMassInds : inds.push_back(ind)
    addCategoryToTree( intermediateTree, KpiMassBranchName, 'KpiMassCat', bounds, inds )

# copy-rename branches
from ROOT import copyFloatInTree
for oldBranchName, newBranchName in obsDict.iteritems():
    if oldBranchName != newBranchName[0]:
        print 'P2VV - INFO: Copying and renaming branch: %s --> %s'%(oldBranchName,newBranchName[0])
        copyFloatInTree( intermediateTree, oldBranchName, newBranchName[0] )

# close intermediate files
intermediateTree.Write()
intermediateFile.Close()
示例#48
0
    def process(self, event):

        decayMode1 = -1
        decayMode2 = -1

        if self.cfg_ana.l1type == 'tau':
            decayMode1 = event.leg1.decayMode()
        if self.cfg_ana.l2type == 'tau':
            decayMode2 = event.leg2.decayMode()

        # RIC: some PF muons/electron can get the wrong mass assigned.
        # Peg their masses to the PDG values
        if self.cfg_ana.l1type == 'muon':
            mass1 = 0.10566    # PDG mass [GeV]
        elif self.cfg_ana.l1type == 'ele':
            mass1 = 0.51100e-3  # PDG mass [GeV]
        else:
            mass1 = event.leg1.mass()

        if self.cfg_ana.l2type == 'muon':
            mass2 = 0.10566    # PDG mass [GeV]
        elif self.cfg_ana.l2type == 'ele':
            mass2 = 0.51100e-3  # PDG mass [GeV]
        else:
            mass2 = event.leg2.mass()

        leg1 = measuredTauLepton(self.legType[self.cfg_ana.l1type], event.leg1.pt(),
                                 event.leg1.eta(), event.leg1.phi(), mass1, decayMode1)
        leg2 = measuredTauLepton(self.legType[self.cfg_ana.l2type], event.leg2.pt(),
                                 event.leg2.eta(), event.leg2.phi(), mass2, decayMode2)

        measuredLeptons = std.vector('svFitStandalone::MeasuredTauLepton')()

        # RIC: not really needed since SVfit internally sorts the inputs
        if hasattr(self.cfg_ana, 'order') and self.cfg_ana.order == '12':
            measuredLeptons.push_back(leg1)
            measuredLeptons.push_back(leg2)
        else:
            measuredLeptons.push_back(leg2)
            measuredLeptons.push_back(leg1)

        metcov = TMatrixD(2, 2)

        a_metcov = array.array('d', [event.diLepton.mvaMetSig(0, 0), event.diLepton.mvaMetSig(1, 0),
                               event.diLepton.mvaMetSig(0, 1), event.diLepton.mvaMetSig(1, 1)])

        metcov.SetMatrixArray(a_metcov)

        mex = event.diLepton.met().px()
        mey = event.diLepton.met().py()

        svfit = SVfitAlgo(measuredLeptons, mex, mey, metcov, 2*self.cfg_ana.verbose)

        # add an additional logM(tau,tau) term to the nll
        # to suppress tails on M(tau,tau) (default is false)
        # svfit.addLogM(False)

        if self.cfg_ana.integration == 'VEGAS':
            svfit.integrateVEGAS()
        elif self.cfg_ana.integration == 'MarkovChain':
            svfit.integrateMarkovChain()
        else:
            print 'The integration method must be defined in the cfg as "integration".'
            print 'Options: [VEGAS, MarkovChain]'
            raise

        # debug
        if self.cfg_ana.verbose:
            if abs(event.diLepton.svfitMass()-svfit.mass()) > 0.01:
                print 'WARNING: run {RUN}, lumi {LUMI}, event {EVT}'.format(RUN=str(event.run),
                                                                            LUMI=str(event.lumi),
                                                                            EVT=str(event.eventId))
                print 'precomputed svfit mass   ', event.diLepton.svfitMass()
                print 'svfit mass computed here ', svfit.mass()

        # method override
        event.diLepton.svfitMass = svfit.mass
        event.diLepton.svfitMassError = svfit.massUncert

        # add also the pt, eta and phi as computed by SVfit
        if self.cfg_ana.integration == 'MarkovChain':
            event.diLepton.svfitPt = svfit.pt
            event.diLepton.svfitPtError = svfit.ptUncert
            event.diLepton.svfitEta = svfit.eta
            event.diLepton.svfitPhi = svfit.phi
            event.diLepton.svfitMET = svfit.fittedMET
            event.diLepton.svfitTaus = svfit.fittedTauLeptons
示例#49
0
import ROOT
from ROOT import fcc, std
import numpy as np
import networkx as nx


# command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("filename", help="edm file to read")
parser.add_argument("--nevents", help="max events to process (takes length of input root file by default)", type=int, default=-1)
parser.add_argument('--output', type=str, help="name of rootfile to write", default="simVertices.root")
args = parser.parse_args()



primaryStartVertexVector = std.vector(fcc.GenVertexData)()
primaryEndVertexVector = std.vector(fcc.GenVertexData)()
secondaryStartVertexVector = std.vector(fcc.GenVertexData)()
secondaryEndVertexVector = std.vector(fcc.GenVertexData)()
hitProducingStartVertices = std.vector(fcc.GenVertexData)()

print "creating root file and trees ..."
f = ROOT.TFile(args.output, "recreate")
t = ROOT.TTree( 'processedEvents', 'tree with processed fcc data' )
psvb = t.Branch("primaryStartVertices", primaryStartVertexVector)
pevb = t.Branch("primaryEndVertices", primaryEndVertexVector)
ssvb = t.Branch("secondaryStartVertices", secondaryStartVertexVector)
sevb = t.Branch("secondaryEndVertices", secondaryEndVertexVector)
hb = t.Branch("hitProducingStartVertices", hitProducingStartVertices)

def r(point):
示例#50
0
      def __dovtest( self, v ):
         self.assertEqual( v.__class__, std.vector( 'double' ) )
         self.assertEqual( v.size(), Nvec )

         for i in range( Nvec ):
            self.assertEqual( v[i], i*i )
示例#51
0
    def puWeight(self):
        print 'PU scaling'
        puW = numpy.ones(1, dtype=numpy.float32)
        self.ttree.Branch(self.weightName,puW,self.weightName+"/F")

        self.inDATAFile = openTFile(self.inputDATAFileName)
        self.inMCFile   = openTFile(self.inputMCFileName)

        self.puScaleDATAhisto = getHist(self.inDATAFile,self.HistoName)
        self.puScaleMChisto   = getHist(self.inMCFile,self.HistoName)


        data_nBin = self.puScaleDATAhisto.GetNbinsX()
        data_minValue = self.puScaleDATAhisto.GetXaxis().GetXmin()
        data_maxValue = self.puScaleDATAhisto.GetXaxis().GetXmax()
        data_dValue = (data_maxValue - data_minValue) / data_nBin

        mc_nBin = self.puScaleMChisto.GetNbinsX()
        mc_minValue = self.puScaleMChisto.GetXaxis().GetXmin()
        mc_maxValue = self.puScaleMChisto.GetXaxis().GetXmax()
        mc_dValue = (mc_maxValue - mc_minValue) / mc_nBin
  
        ratio = mc_dValue/data_dValue
        nBin = data_nBin
        minValue = data_minValue
        maxValue = data_maxValue
        dValue = data_dValue
 
        print " ratio = "
        print ratio
 
        if (mc_dValue/data_dValue - (int) (mc_dValue/data_dValue)) != 0 :
          print " ERROR:: incompatible intervals!"
          exit(0);
        
 
        puScaleDATA   = std.vector(float)()
        puScaleMCtemp = std.vector(float)()
        puScaleMC     = std.vector(float)()

        ################
        # remove last bin -> peak in DATA distribution
        # nBin = nBin-1
        ################   

        for iBin in range(0, nBin):
            puScaleDATA.push_back(self.puScaleDATAhisto.GetBinContent(iBin+1))
            mcbin = int(floor(iBin / ratio))
            puScaleMCtemp.push_back(self.puScaleMChisto.GetBinContent(mcbin+1))

 
        integralDATA = 0.
        integralMC   = 0.
 
        for iBin in range(0, nBin):
            integralDATA += puScaleDATA.at(iBin)
            integralMC   += puScaleMCtemp.at(iBin)

        print " integralDATA = " + "%.3f" %integralDATA
        print " integralMC   = " + "%.3f" %integralMC
 
        for iBin in range(0, nBin):
            puScaleMC.push_back( puScaleMCtemp.at(iBin) * integralDATA / integralMC) 


 
        nentries = self.nentries
        print 'total number of entries: '+str(nentries)
        i = 0
        for ientry in range(0,nentries):
            i+=1
            self.oldttree.GetEntry(ientry)

            ## print event count
            step = 50000
            if i > 0 and i%step == 0.:
                print str(i)+' events processed.'

##
## ----------------------------------------------------------------
##
            puW[0] = 1.
            
            ibin = -1

## true pu reweighting 
            if self.kindPU == "trpu" : 
               ibin = int(self.oldttree.trpu / dValue)
## in time pu reweighting (observed)
            if self.kindPU == "itpu" : 
               ibin = int(self.oldttree.itpu / dValue)

            if ibin < puScaleDATA.size() :
               if puScaleMC.at(ibin) != 0 :
                  puW[0] = 1. * puScaleDATA.at(ibin) / puScaleMC.at(ibin)
               else :
                  puW[0] = 1.
            else :
               ibin = puScaleDATA.size()-1
               if puScaleMC.at(ibin) != 0 :
                  puW[0] = 1. * puScaleDATA.at(ibin) / puScaleMC.at(ibin)
               else :
                  puW[0] = 1.

#            print puW

            self.ttree.Fill()
示例#52
0
 def setReadCollectionNames(  self, colNames ):
     #wrapper example for an autogenerated method that takes a string vector
     v = std.vector(std.string)()
     for col in colNames:
         v.push_back(col)
     self.reader.setReadCollectionNames( v )
示例#53
0
nTupleIn = nTupleFileIn.Get(nTupleName)
nTupleFileOut = TFile.Open( nTupleFilePathOut, 'RECREATE' )
nTupleOut = nTupleIn.CloneTree()
nTupleFileIn.Close()
del nTupleFileIn

from P2VV.Load import P2VVLibrary
if runPeriod :
    from ROOT import addIntegerToTree
    print 'adding run period "%s" to n-tuple' % runPeriod
    addIntegerToTree( nTupleOut, runPeriod, 'runPeriod' )

if firstData :
    from ROOT import addCategoryToTree, std
    print 'adding "first data" flag to n-tuple for data with run number < %d' % firstData
    bounds = std.vector('Double_t')()
    inds   = std.vector('Int_t')()
    bounds.push_back( float(firstData) )
    inds.push_back(1)
    inds.push_back(0)
    addCategoryToTree( nTupleOut, 'runNumber', 'firstData', bounds, inds )

if prescaleBounds :
    from ROOT import addCategoryToTree, std
    print 'adding prescale category with indices "%s" and run-number boundaries "%s" to n-tuple' % ( prescaleInds, prescaleBounds )
    bounds = std.vector('Double_t')()
    inds   = std.vector('Int_t')()
    for bound in prescaleBounds : bounds.push_back(bound)
    for ind in prescaleInds : inds.push_back(ind)
    addCategoryToTree( nTupleOut, 'runNumber', 'hlt2_prescale', bounds, inds )
示例#54
0
from ROOT import std

#test cluster
id = Id.makeEcalId()
tv =TVector3(0,0,0)
cluster = ClusterCPP(3,tv,12,12345678)

class AliceR(long):
  @staticmethod
  def value():
    return 6

print AliceR.value()

#test vectors
m= std.vector('papas::Cluster')()
m.push_back(cluster)
m.size()
print m[0].energy()


v=std.unordered_map('uint64_t','papas::Cluster')()
v[3] = ClusterCPP(3,tv,12,12345678)
#test vectors

w=std.unordered_map('int','int')()

#try running papas simulation and reconstruction
from ROOT.papas import CMS
from ROOT.papas import PFEventDisplay, ViewPane, GDetector
from ROOT.papas import Simulator
示例#55
0
                                     100, phsp.lowerLimit(1), phsp.upperLimit(1))
poly_hist = TH2F("poly", "Polynomial PDF", 100, phsp.lowerLimit(0), phsp.upperLimit(0), 
                                     100, phsp.lowerLimit(1), phsp.upperLimit(1))
kernel_hist = TH2F("kernel", "Kernel PDF", 100, phsp.lowerLimit(0), phsp.upperLimit(0), 
                                           100, phsp.lowerLimit(1), phsp.upperLimit(1))

true_kpi = TH1F("true_kpi", "M^{2}(K_{S}#pi) slice", 100, phsp.lowerLimit(0), phsp.upperLimit(0) )
poly_kpi = TH1F("poly_kpi", "M^{2}(K_{S}#pi) slice", 100, phsp.lowerLimit(0), phsp.upperLimit(0) )
kernel_kpi = TH1F("kernel_kpi", "M^{2}(K_{S}#pi) slice", 100, phsp.lowerLimit(0), phsp.upperLimit(0) )
true_pipi = TH1F("true_pipi", "M^{2}(#pi#pi) slice", 100, phsp.lowerLimit(1), phsp.upperLimit(1) )
poly_pipi = TH1F("poly_pipi", "M^{2}(#pi#pi) slice", 100, phsp.lowerLimit(1), phsp.upperLimit(1) )
kernel_pipi = TH1F("kernel_pipi", "M^{2}(#pi#pi) slice", 100, phsp.lowerLimit(1), phsp.upperLimit(1) )

# Coordinates in the phase space where we will create the 1D slices.
from ROOT import std, Double
v = std.vector(Double)(2)
v[0] = 1.0;
v[1] = 0.3;

# Fill histogram with the result of kernel density estimation
truepdf.project(true_hist)
true_hist.Write()
poly.project(poly_hist)
poly_hist.Write()
kde.project(kernel_hist)
kernel_hist.Write()

# Fill 1D slice in x projection, at the point y=v[1]
truepdf.slice(v, 0, true_kpi) 
true_kpi.Write() 
poly.slice(v, 0, poly_kpi)
示例#56
0
import sys
import re
import time
import argparse
oldargv = sys.argv[:]
sys.argv = [ '-b-' ]
import ROOT, os
from ROOT import std
ROOT.gROOT.SetBatch(True)
sys.argv = oldargv

ROOT.gSystem.Load("lib/libCFGMan.so")

cfg = ROOT.CfgManager("test/test.cfg")
cfg.ParseConfigString("test2.addedFromString 'new option from string'")
cfg.ParseConfigString("test2.addedFromString+= work like a charm")
cfg.ParseConfigString("test2.add+= 'added from py' great")

cfg.Print()

test_string = cfg.GetOpt("test.stringa")

print(test_string)
print(cfg.GetOpt("test.stringa", 1))

for opt in cfg.GetOpt(std.vector(std.string))("test.newline"):
    print(opt)

sub_cfg = cfg.GetSubCfg("test3.subtest1")
sub_cfg.Print()
示例#57
0
        #legend
        aleg = TLegend(0.6,0.4,0.8,0.6)
        SetOwnership( aleg, 0 )
        aleg.SetMargin(0.12)
        aleg.SetTextSize(0.035)
        aleg.SetFillColor(10)
        aleg.SetBorderSize(0)

        isFirst = 1
        ii = 0

        stacklist[thegraph[ikey].name] = THStack("astack"+thegraph[ikey].name,thegraph[ikey].title)
        astack = stacklist[thegraph[ikey].name]
        xVal_val = TVectorD()
        yVal_val = TVectorD()
        yBin_val = std.vector(int)()
        xErr_val = TVectorD()
        yErr_val = TVectorD()
	zVal_val = TVectorD()
	zErr_val = TVectorD()
        nVal_val = 0
        
        xVal_ref = TVectorD()
        yVal_ref = TVectorD()
        yBin_ref = std.vector(int)()
        xErr_ref = TVectorD()
        yErr_ref = TVectorD()
	zVal_ref = TVectorD()
	zErr_ref = TVectorD()
        nVal_ref = 0
示例#58
0
文件: testTree.py 项目: noamhod/2HDM
#!/usr/bin/python
import ROOT
from ROOT import std, gROOT, gStyle, gPad, TCanvas, TH1, TH1D, TH2D, TLegend, TLine, TFile, TTree, TLorentzVector, TMath, TVirtualPad, TEventList

fXX = TFile("tops.SMIA.tmp.10k.root","READ")
tXX = fXX.Get("SMIA")
pXX = ROOT.vector(TLorentzVector)()
iXX = std.vector(int)()
tXX.SetBranchAddress("p4",pXX);
tXX.SetBranchAddress("id",iXX);

hmSMXgen = TH1D("hmSMXgen", ";Truth #it{m}_{#it{t}#bar{#it{t}}} [GeV];Events",25,350,850)
hmSMXgen.Sumw2()
hmSMXgen.SetLineWidth(2)
hmSMXgen.SetLineColor(ROOT.kAzure+9)
hmSMXgen.SetMarkerColor(ROOT.kAzure+9)
hmSMXgen.SetMarkerStyle(24)

n=1
for event in tXX:
   if(n%1000==0): print "processed |SM+X|^2 generated ", n
   t1=event.p4[2]
   t2=event.p4[3]
   mtt = (t1+t2).M()
   hmSMXgen.Fill(mtt)
   n+=1

cnv = TCanvas("cnv","",600,600)
cnv.Draw()
cnv.cd()
hmSMXgen.Draw()
示例#59
0
   gStyle.SetLineStyleString(2,"[12 12]"); # postscript dashes
   gStyle.SetEndErrorSize(0.);
   # gStyle.SetOptTitle(0);
   gStyle.SetOptStat(0);
   gStyle.SetOptFit(0);
   gStyle.SetPadTickX(1);
   gStyle.SetPadTickY(1);
   gStyle.SetPaintTextFormat("4.1f")


setStyle()

fMG = TFile("tops.MG_SM.500k.root","READ")
tMG = fMG.Get("MG_SM")
pMG = ROOT.vector(TLorentzVector)()
iMG = std.vector(int)()
tMG.SetBranchAddress("p4",pMG);
tMG.SetBranchAddress("id",iMG);

fSM = TFile("tops.SM.500k.root","READ")
tSM = fSM.Get("SM")
pSM = ROOT.vector(TLorentzVector)()
iSM = std.vector(int)()
tSM.SetBranchAddress("p4",pSM);
tSM.SetBranchAddress("id",iSM);

hmMG = TH1D("hmMG", ";Truth #it{m}_{#it{t}#bar{#it{t}}} [GeV];Events",25,350,850)
hmMG.Sumw2()
hmMG.SetLineWidth(2)
hmMG.SetLineColor(ROOT.kBlack)
hmMG.SetMarkerColor(ROOT.kBlack)
示例#60
0
name  = args.n
jobid = args.i
print 'name  : ',name
print 'jobid : ',jobid


# Set up ROOT and RootCore:
import ROOT
ROOT.gROOT.Macro( '$ROOTCOREDIR/scripts/load_packages.C' )
if(not ROOT.xAOD.Init().isSuccess()): print "Failed xAOD.Init()" # Initialize the xAOD infrastructure

from ROOT import std, gROOT, TFile, TTree, TLorentzVector
tfile = "tops.SM.root" 
tfile = TFile(tfile,"RECREATE")
tree = TTree("SM","SM")
pdgid = std.vector(int)()
p4    = ROOT.vector(TLorentzVector)()
RunNumber = array( 'i', [ 0 ] )
EventNumber = array( 'i', [ 0 ] )
tree.Branch("id",pdgid) 
tree.Branch("p4",p4)
tree.Branch("RunNumber",RunNumber,"RunNumber/I")
tree.Branch("EventNumber",EventNumber,"EventNumber/I")


# Set up the input files:
xaodpath = "$HOME/data/MC/ttbar/ntup/"
fullpath = ROOT.gSystem.ExpandPathName(xaodpath)
fileName = fullpath+"/DAOD_TRUTH1.NTUP."+name+"."+jobid+".root"
treeName = "CollectionTree" # default when making transient tree anyway
f = ROOT.TFile.Open(fileName)