Creating a TTree with Branches in Using Root through Python

812 Views Asked by At

I am trying to create a tree with branches in root through python. I have a .root file and I am trying to create branches that are the variables (or data pts) of my .root file. Here is my attempt:

f = ROOT.TFile('event.root', 'read') #opening the file and creating a file object f
T = ROOT.TTree("T", "simple tree")



#ntuple = ROOT.TNtuple("ntuple","Demo ntuple","px:py:pz:m")
T.Scan("px:py:pz:m")

This just gives me:

Error in TTreeFormula::Compile: Bad numerical expression : “px”
Error in TTreeFormula::Compile: Bad numerical expression : “py”
Error in TTreeFormula::Compile: Bad numerical expression : “pz”
Error in TTreeFormula::Compile: Bad numerical expression : “m”

Row * px * py * pz * m *

which I understand why since I did not define my variables. So I am looking through an example, https://www.niser.ac.in/sercehep2017/notes/RootTutorial_TTree.pdf, (slide 3) and I attempt to define my variable that should be contained in my .root file as:

f = ROOT.TFile('event.root', 'read') #opening the file and creating a file object f
T = ROOT.TTree("T", "simple tree")

px_as_floats = float(px)
py_as_float = float(py)
pz_as_float = float(pz)
m_as_float = float(m)
T.Branch("px",&px,"px/F")
T.Branch("py",&py,"py/F")
T.Branch("pz,&pz,"pz/F")
T.Branch("m",&m,"m/F")

But, I end up with this error:

Traceback (most recent call last):
File “”, line 1, in
File “/mnt/c/1/writeroot.py”, line 17
T.Branch(“px”,&px,“px/F”)
              ^
SyntaxError: invalid syntax

Is there a way to write this in python? Writing:

T.ROOT.Branch(“px”,&px,“px/F”)

did not work either.

 Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/mnt/c/1/writeroot.py", line 17
  T.ROOT.Branch("pt1",&pt1,"pt/F")
                    ^
 SyntaxError: invalid syntax

How can I fix the syntax. Ultimately I am trying to load the dictionary used from the .root file to my tree and then do some calculations on the items in the dictionary. In other words, how do you extract the dictionary from the .root file?

When I type:

When I type gFile->ls(), I get

TFile** rdata.root TFile* rdata.root KEY: TH1F mass;1 masses KEY: TNtuple tnt;1 tnt

1

There are 1 best solutions below

4
On BEST ANSWER

Unless you are trying to make bitwise AND operation, the symobl & is not valid. I assume that you want to send pointer to original variable. We don't do this in python. If that's the case look up on google for local and global variable. Tl;dr in python all mutable types are passed by reference Personally I would have wrote this like:

T.Branch("px",px,"px/F")
T.Branch("py",py,"py/F")
T.Branch("pz", pz,"pz/F")
T.Branch("m",m,"m/F")