Pyroot loading a single value out of a vector in a tree

Hello,
I wanted to create a tree with vectors in which I can save different values and the time I get these. To keep it simple i tried this code to create my file with the values.

file = ROOT.TFile.Open(name,“create”)
tree = ROOT.TTree(“tree”, “tree”)
pv1 = ROOT.vector(‘float’)(0)
tree.Branch(“pv1”, pv1)

tree.Fill()
file.Write()
I’m resizing my vectors while running in order to save the new values.

Now I’m trying to load those vectors again in order to print just a single random value but dunno how to do this. I tried :

file = ROOT.TFile(name,“READ”)
tree = file.Get(‘tree’)
pv1 = tree.Branch(“pv1”)
print(pv1[0])

but I’m getting the following error and I’ve the feeling there should be a better way to do this.

TypeError: ‘int’ object is not subscriptable

Would appreciate any kind of help or new input regarding my problem.
Henry

ROOT Version: 6.22.06
Platform: Ubuntu 20.04
Compiler: Not Provided


Maybe pv1 = tree.GetBranch("pv1") instead?

1 Like

This is working but it seems like my Values are not getting saved on my file.
I’m using this code to save them at the moment to try out everything I wanna use later.

 def load():
     file = ROOT.TFile.Open(name, "recreate")
     tree = ROOT.TTree("new","new")
     pv1 = np.empty(1000, "float64")
     pv2 = np.empty(1000,"float64")
     pv3 = np.empty(1000,"float64")
     time = np.empty(1000,"float64")
     tree.Branch("time",time,"time/F")
     tree.Branch("pv1",pv1,"pv1/F")
     tree.Branch("pv2",pv2,"pv2/F")
     tree.Branch("pv3",pv3,"pv3/F")
     return file,pv1,pv2,pv3,time,tree
 
 def save():
     tree.Fill()
     file.Write()
 
 
 while i < n:
     if i == 0:
         file,pv1,pv2,pv3,time, tree = load()
     pv1[i]=1
     pv2[i]=2
     pv3[i] = 3
     time[i] = 0
     i=i+1
     save()

But if I open my file again the values aren’t saved. Would you mind taking a quick look at this code? Maybe you are able to see my fault.

Thank you so far
Henry

I’m sure @etejedor will take a look once back from vacation

Hello,

You need to define your array branches as arrays of doubles, right now they are defined as single floats.

So if you define:

pv1 = np.empty(1000, "float64")

then you need:

tree.Branch("pv1",pv1,"pv1[1000]/D")

You can find examples of how to use the Branch pythonization here (look for the PyROOT box after the C++ docs):

Also, when you read the values back, you can do it with this syntax:

f = ROOT.TFile.Open(name)
t = f.new
for entry in t:
    for elem in entry.pv1:
         print(elem)

Thanks that helped a lot. Would you mind if I ask another question right away?

Thanks for your time so far.
Henry

Sure please ask away!

1 Like