In PyROOT, how can one plot the invariant mass of Z using 4-vector component variables in a tree?

Let’s say I have a ROOT file containing a tree of variables that have been selected for the purposes of creating a Z invariant mass plot (i.e. leptons of opposite sign charge etc.). The variables in the tree are el_pt, el_eta, el_phi, el_e and so on (for the electron case).

For each event, one could create a TLorentzVector for each electron, add them and then get the invariant mass using the M2 function of the resultant TLorentzVector. These invariant mass values could be appended to a list and then plotted in a histogram.

In PyROOT, this approach could be slow and memory intensive. So, is there a more efficient way to do something like this? It appears appealing to use the machinery behind the tree “project” functionality (, but it is not obvious to me how something like an invariant mass calculation could be specified for it. Do you have any suggestions for this or another approach?


one of the advantages of using pyROOT is the possibility to easily loop over trees.
You can start from this example, cooked starting from the information of your post:

def calcInvMass(px1,py1,pz1,e1,px2,py2,pz2,e2):
myFile = ROOT.TFile("myFileName.root")
myTree = myFile.myTreeName
for event in myTree:
    invMass = calcInvMas(event.el1_px, event.el1_py, event.el1_pz, event.el1_e,
                                    event.el2_px, event.el2_py, event.el2_pz, event.el2_e)

As for the performance, I would not be worried as the time will be almost entirely spent in IO operations which are performed by routines in the ROOT libraries which are written in C++ and compiled.