# TTree : Drawing sum of arrays

Hello,

Is it possible to draw the sum of elements of an array with TTree->Draw() ?
Suppose we have a branch with a simple array of variable size, does something like this exists :

tree->Draw(“sum(arr)”)

where sum(arr) = arr[0]+arr[1]+…+arr[size(arr)-1].

A possibly connected question : is there a variable a bit like Iteration\$, let say Ntrue\$, which is the number of time the expression in the selection was evaluated as true for one event ?
For exemple :

tree->Draw(“Ntrue\$”,“arr>5”);

Which would fill an histo with one entry by event this entry being the number of element of arr greater than 5.

From my understanding of the Draw() function, I fear it may not be possible…
But is there any way to do such things ?

Thanks for your help !

P.A.

1 Like

Hi,

Indeed this is not directly possible using TTreeFormula.
The closest you can do is to use the Alt\$ function:

``````tree->Draw("arr[0]+Alt\$(arr[1],0)+Alt\$(arr[2],0)");
``````

There is nothing like Ntrue\$.

The correct solution in both case is to use the tree proxy mechanism.
Write a small file sum.C containing:

```double sum() { double res = 0; for(int i=0;i<arr.GetEntries();++i) res+= arr[i]; return res; }```and do

Cheers,
Philippe.

Hello,

Thanks a lot for your answer !

The proxy mechanism is very usefull. But I need to write a file for each variable I want to plot , is this correct ?

Would it be a good idea to suggest implementation of such an Ntrue\$ variable or a sum mechanism (or other simple manipulation like product or other) ?
If yes and if there is an official way to ask for new features I’m willing to do it !

Thanks again,

P-A.

[quote]If yes and if there is an official way to ask for new features I’m willing to do it ! [/quote]You just did
About Ntrue\$ does not really fit in the general flow of TTreeFormula (it would requires to keep a state from a previous implementation) but it could be implemented in term of Sum\$:
tree->Draw(“Sum\$(arr<2)”);
I will think about implementing Sum\$.

Cheers,
Philippe.

```// Sum\$(formula): return the sum of the value of the elements of the formula given // as a parameter. For eaxmple the mean for all the elements n // one entry can be calculated with: // Sum\$(formula)/Length\$(formula)```
is the new TTreeFormual special function. It will be upload in CVS shortly.

Philippe.

Great ! Thanks a lot !
It is very nice to see such reactivity from the ROOT team !

Just one question to understand well how it will work :
What will be the result of something like :

tree->Draw(“arr*Sum\$(arr)”);

??

P-A.

`tree->Draw("arr*Sum\$(arr)"); `This will plot each values of arr multiply by the sum of the values (within an entry).
I.e. it is equivalent to

```for each entry sum = 0; for each element in arr, sum += arr[i] for each element in arr, plot sum*arr[i] ```Cheers,
Philippe.