When creating a TGraph using PyROOT and numpy arrays I noticed something unexpected. Using the following:
g = ROOT.TGraph(3, np.array([1,2,3]), np.array([4.5,5.4,6.3]))
and later saving the graph to a file, the y
values shown are correct, but the x
values are all set to zero. Using instead
g = ROOT.TGraph(3, np.array([1.,2.,3.]), np.array([4.5,5.4,6.3]))
or
g = ROOT.TGraph(3, np.array([1,2,3], dtype='d'), np.array([4.5,5.4,6.3]))
the graph is displayed as expected.
I would expect the values to be cast to double, or that I should at least receive an error specifying that I am calling the following constructor:
TGraph (Int_t n, const Int_t *x, const Double_t *y)
which does not exist.
Interestingly, if I instead run the following:
g = ROOT.TGraph(3, np.array([1,2,3], dtype='i'), np.array([4.5,5.4,6.3]))
I get the error messages I would expect:
TypeError: none of the 11 overloaded methods succeeded. Full details:
TGraph::TGraph() =>
takes at most 0 arguments (3 given)
TGraph::TGraph(int n) =>
takes at most 1 arguments (3 given)
TGraph::TGraph(const TGraph& gr) =>
takes at most 1 arguments (3 given)
TGraph::TGraph(const TVectorT<float>& vx, const TVectorT<float>& vy) =>
takes at most 2 arguments (3 given)
TGraph::TGraph(const TVectorT<double>& vx, const TVectorT<double>& vy) =>
takes at most 2 arguments (3 given)
TGraph::TGraph(const TH1* h) =>
takes at most 1 arguments (3 given)
TGraph::TGraph(const TF1* f, const char* option = "") =>
takes at most 2 arguments (3 given)
TGraph::TGraph(const char* filename, const char* format = "%lg %lg", const char* option = "") =>
could not convert argument 1 (expected string or Unicode object, int found)
TGraph::TGraph(int n, const int* x, const int* y) =>
could not convert argument 3 ('numpy.ndarray' object has no attribute 'typecode' and given element size (8) do not match needed (4))
TGraph::TGraph(int n, const float* x, const float* y) =>
could not convert argument 3 ('numpy.ndarray' object has no attribute 'typecode' and given element size (8) do not match needed (4))
TGraph::TGraph(int n, const double* x, const double* y) =>
could not convert argument 2 ('numpy.ndarray' object has no attribute 'typecode' and given element size (4) do not match needed (8))
Please note that numpy
's default type is np.int64
and the option dtype='i'
uses np.int32
. Therefore, something wrong happens when PyRoot looks at the former type.
This other post seems related: TGraphErrors taking numpy arrays as arguments.