如何填充树枝?

时间:2019-03-06 01:28:42

标签: python python-3.x root pyroot

import sys
import ROOT
from progressbar import Bar, Percentage, ProgressBar
from time import time
from tools import duration, check_outfile_path

ECMS = 3.686
p4shw = ROOT.vector('double')()

def main ():     
    args = sys.argv[1:]

    if (len(args) < 2):
        print 'input error'

    infile = args[0]
    outfile = args[1]
    check_outfile_path(outfile)

    fin = ROOT.TFile(infile)
    t = fin.Get('ana')
    t.SetBranchAddress("p4shw", p4shw)
    entries = t.GetEntriesFast()

    fout = ROOT.TFile(outfile, "RECREATE")
    t_out = ROOT.TTree("ana","ana")
    rec_mass_gam1 = ROOT.vector('double')()
    rec_mass_gam2 = ROOT.vector('double')()
    t_out.Branch("rec_mass_gam1", rec_mass_gam1, "rec_mass_gam1/D")
    t_out.Branch("rec_mass_gam2", rec_mass_gam2, "rec_mass_gam2/D")

    pbar = ProgressBar(widgets=[Percentage(), Bar()], maxval=entries).start()
    time_start = time()
    print("checking error 2")
    cms_p4 = ROOT.TLorentzVector(0.011*ECMS, 0, 0, ECMS)
    print 'entries=', entries
    print("checking error 3")
    for k in range(entries):

        pbar.update(k+1)

        #t.GetEntry(k)
        print("indentent error checking")
        #exit()
        p4shw_gam1 = ROOT.TLorentzVector(t.p4shw[0],t.p4shw[1],t.p4shw[2],t.p4shw[3])
        p4shw_gam2 = ROOT.TLorentzVector(t.p4shw[4],t.p4shw[5],t.p4shw[6],t.p4shw[7])
        print("checking error 4")
        p4_shw_gam1 = cms_p4 - p4shw_gam1
        p4_shw_gam2 = cms_p4 - p4shw_gam2
        rec_mass_gam1 = p4_shw_gam1.M()
        rec_mass_gam2 = p4_shw_gam2.M()
        print("rec_mass_gam1", rec_mass_gam1)
        #exit()
        t_out.Fill()
        print("checking error 5")
    t_out.Write()
    fout.Close()
    pbar.finish()
    dur = duration(time()-time_start)
    sys.stdout.write(' \nDone in %s. \n' % dur)
    print("checking error 6")

if __name__ =='__main__':
    main()

1 个答案:

答案 0 :(得分:0)

当我将您的代码与this example进行比较时,您使用的是ROOT.vector而不是array。当我执行此更改时,分支将按预期填充

#!/bin/python

import ROOT
from array import array


# doesn't work
def test1():
    t_out = ROOT.TTree("ana", "ana")
    rec_mass_gam1 = ROOT.vector('double')()
    t_out.Branch("rec_mass_gam1", rec_mass_gam1, "rec_mass_gam1/D")
    rec_mass_gam1 = 1337.
    t_out.Fill()
    t_out.Draw("rec_mass_gam1")


# works
def test2():
    t_out = ROOT.TTree("ana", "ana")
    rec_mass_gam1 = array('f', [0.])
    t_out.Branch("rec_mass_gam1", rec_mass_gam1, "rec_mass_gam1/F")
    rec_mass_gam1[0] = 1337.
    t_out.Fill()
    t_out.Draw("rec_mass_gam1")

运行test1时,我看到树和分支被填充了,只是没有得到我想要的值。在第二个示例中,将填充所需的值。

现在仔细看看发生了什么,脚本中肯定有错误:

python不会将rec_mass_gam1 = p4_shw_gam1.M()视为“将向量变量rec_mass_gam1的值设置为退出M()方法的数字,而是创建一个新的float-名称为rec_mass_gam1的变量和原始矢量变量(分支使用)保持不变。

我不得不承认我不知道是否还有一种方法可以用vector来填充分支。