TGraphErrors taking numpy arrays as arguments

I am trying to use python to produce a figure in Root,

My code is attached, The error message that I receive is:

Traceback (most recent call last):
File “test7”, line 21, in
graph_a = TGraphErrors(len(axs),axs,ays,adxs,adys)

with the relevant error being:
TGraphErrors::TGraphErrors(Int_t n, const Double_t* x, const Double_t* y, const Double_t* ex = 0, const Double_t* ey = 0) =>
could not convert argument 2

I don’t understand what is going wrong. I have checked other threads and have made sure that the arrays are in the correct format, but this still doesn’t work.

Many Thanks for all your help

Geoff Herbert

ps. Both files should be renamed to test7 and graph_data.dat respectively
graph_data.txt (9.89 KB)
test7.txt (1.02 KB)

Hi,

the resulting ndarray’s in your code are discontiguous. In order for a numpy array to pass through a pointer that expects a C-style array, it needs to be a C-style array. If there is no way to tell numpy.loadtxt to create properly formed arrays (I couldn’t find any), then you can call axs.flatten(‘C’) etc. on each of them and pass the results of that to the TGraphErrors constructor.

Cheers,
Wim

Ok, so now I’m running the code:

axs, adxs, ays, adys = plot_graph(‘a’)
axs = axs.flatten(‘C’)
asxs = adxs.flatten(‘C’)
ays = ays.flatten(‘C’)
adys = adys.flatten(‘C’)
graph_a = TGraphErrors(len(axs),axs,ays,adxs,adys)

but I’m now receiving the error:
could not convert argument 2 (‘numpy.ndarray’ object has no attribute ‘typecode’)

I have no idea what this means. Any ideas?

Ok, Have managed to get it fixed.

If you want to use numpy.loadtxt() to obtain the data from a file, eg:
sample_array, other_array = numpy.loadtxt(‘sample_file.dat’, usecols=(1, 2), unpack =1)

Then you will need to flatten the arrays that loadtxt gives you:
sample_array = sample_array.flatten(‘C’)
(I dont know why, but it seems to work)

Then, You need to ensure that all of the data is in the correct format:
sample_array = sample_array.astype(‘float’)
(even if you’re fairly certain that it is already in the correct format, this is a worthwhile step.)

Then the arrays can be passed to TGraphErrors or TGraph.

Many Thanks

Hi,

what I meant was: TGraphErrors( len(axs),axs.flatten(‘C’), … etc. ).

Cheers,
Wim