I’m trying to write a function which multiply two TGraphs in python.
Because it is TGraph I am using :
After multiplying the values, I want to insert them into a new TGraph (y is the new vector)
I have two problems:
- the types are not matching none of the TGraph options: <type ‘ROOT.PyDoubleBuffer’>
- How do I put values in TVector in python?
I hope that someone know how to help, or have another solution for multiplying…
The thing returned in PyROOT from doing TGraph::GetX (and other similar methods) is a “buffer”, it’s not the same as an array or vector. To do the multiplying, you can convert it into a numpy.array or a python array.array. These python containers are ok to use to construct your new TGraph.
In : import ROOT
In : import array
# First let's make an "original" TGraph:
In : X1 = array.array('d',[i for i in range(10)])
In : Y1 = array.array('d',[i*i for i in range(10)])
In : g1 = ROOT.TGraph(len(X1),X1,Y1)
In : g1.Draw()
Info in <TCanvas::MakeDefCanvas>: created default TCanvas with name c1
# Now we use the GetX and GetY methods that return a PyDoubleBuffer
In : x1buff = g1.GetX()
In : y1buff = g1.GetY()
In : type(x1buff)
# We have to use SetSize because the PyDoubleBuffer doesn't initially know how long it is.
In : x1buff.SetSize(g1.GetN())
In : y1buff.SetSize(g1.GetN())
# Convert the PyDoubleBuffers into python arrays.
In : X2 = array.array('d',x1buff)
In : Y2 = array.array('d',y1buff)
# Now do whatever your manipulations are on X2 and Y2
In : g2 = ROOT.TGraph(len(X2),X2,Y2)
In : g2.Draw()
Note that my code should also work if you use numpy.arrays instead of built-in python array.arrays. The only lines to change would be #2, 3, 4, and 12 and 13.
I hope that helps!