Reading strings from ROOT tree

Hi. I am trying to get into PyROOT and there’s one problem I cannot solve right now.

I was looking through many examples how-to access ROOT files with Python, here’s what I got:

create a struct:

ROOT.gROOT.ProcessLine(
"struct complete_t {\
   UInt_t          track_id;\
   string        a_string;\
}" )

then access the tree:

struct_complete = ROOT.complete_t()
tree.SetBranchAddress("track_id",ROOT.AddressOf(struct_complete,"track_id"))
tree.SetBranchAddress("a_string",ROOT.AddressOf(struct_complete,"a_string"))

This works very well for track_id, but not for a_string. I also tried TString , TObjString , none of it apparently worked.

But:

tree.a_string

works fine in my loop over all events, but I dislike that workaround and I guess it is even slower?
Is there a way to integrate strings into my struct?

Thanks in advance.

Hi,

suppose to have a tree called “myTree” in a ROOT file “myFile” with a branch “myString” of type std::string and other branches (b1, b2, …, bn)
What one would do to access it in a pythonic way is:

t = myFile.myTree
for entry in t:
    print entry.myString
    print entry.b1
    # ...
    print entry.bN

Cheers,
Danilo

Are all different types; only actual type will work. Check with tree.Print(): it may be char*. Using ‘tree.a_string’ is dog in python (fine in pypy-c); SetBranchAddress() is faster.

-Dom

Thanks for your replies.

This works of course but is rather slow.

Before I started to create my struct I tried tree.Print() of course, but I guess it is a “normal” string, at least
I am using a std::string in my C++ code.

*............................................................................* *Br 9 :a_string : string * *Entries : 60035686 : Total Size= 1961393511 bytes File Size = 138507063 * *Baskets : 841 : Basket Size= 5264384 bytes Compression= 14.16 * *............................................................................*

tree.a_string = ROOT.std.string() tree.SetBranchAddress('a_string', tree.a_string) for i in xrange(tree.GetEntries()): tree.GetEntry(i) print tree.a_string
-Dom

[quote=“Dominique”]tree.a_string = ROOT.std.string() tree.SetBranchAddress('a_string', tree.a_string) for i in xrange(tree.GetEntries()): tree.GetEntry(i) print tree.a_string
-Dom[/quote]

Thanks this does increase the reading speed by roughly 25%.
Can this be incorporated into my struct?

No, can’t grab objet:[code]>>> toto = ROOT.complete_t()

print type(toto.a_string)
<type ‘str’>[/code]
Can workaround, but need keep alive:toto = ROOT.complete_t() toto._cppstr = ROOT.BindObject(ROOT.AddressOf(toto, "a_string"), ROOT.std.string) tree.SetBranchAddress('a_string', toto._cppstr) for i in xrange(tree.GetEntries()): tree.GetEntry(i) print toto.a_string
Aside, can then also use directly for bit more speedup:... toto._cppstr = ROOT.BindObject(ROOT.AddressOf(toto, "a_string"), ROOT.std.string) rapid_cppstr = toto._cppstr ... # loop etc print rapid_cppstr
-Dom