# Using a predefined TH2D in RDataframe to compute new quantiy

**URL:** <https://root-forum.cern.ch/t/using-a-predefined-th2d-in-rdataframe-to-compute-new-quantiy/50881>\
**Category:** Newbie\
**Tags:** rdataframe\
**Created:** [July 20, 2022, 4:07pm UTC](https://root-forum.cern.ch/t/using-a-predefined-th2d-in-rdataframe-to-compute-new-quantiy/50881 "2022-07-20T16:07:21Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![tancredi](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/tancredi/32/20395_2.png) [@tancredi](https://root-forum.cern.ch/u/tancredi)\
**Post date:** [July 20, 2022, 4:07pm UTC](https://root-forum.cern.ch/t/using-a-predefined-th2d-in-rdataframe-to-compute-new-quantiy/50881/1 "2022-07-20T16:07:21Z")

</div>

Hello,

I have a probability as a function of two variable x,y. Typically stored in a 2d-histogram.  
How can I make this available in RDataFrame ?

e.g for each track in the detector (RVec) I would like to get the probability as function of x,y.

I would know how to implement this in a C++ function that I call from RDataFrame, e.g.

RVec Probability( RVec x, RVec y) (

static TH2D\* hprob=0;  
static bool firstevent=false;  
if (firstevent) {  
read histogram hprob from a file

firstevent=false  
}  
int ibin=hprob-\>FindBin(x,y);  
return hprob-\>GetBinContent(ibin);

)  
and the in RDataFrame  
d.Define(“prob”,“Probability(x,y)”)  
Is this multi-tread safe ? Is there a more clever way to implement this ?

---

<div class="post-metadata">

**Author:** ![RENATO\_QUAGLIANI](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/renato_quagliani/32/19496_2.png) [@RENATO\_QUAGLIANI](https://root-forum.cern.ch/u/RENATO_QUAGLIANI)\
**Post date:** [July 20, 2022, 9:27pm UTC](https://root-forum.cern.ch/t/using-a-predefined-th2d-in-rdataframe-to-compute-new-quantiy/50881/2 "2022-07-20T21:27:35Z")

</div>

> [@DataFrame define column with "input" histogram](https://root-forum.cern.ch/t/dataframe-define-column-with-input-histogram/34143):
>
> Dear experts I gave a first trial to “fill” a weight bracnh reading a histogram and a couple of variables on my ntuple… The code i came up and make it run/work is something like this : TH1D \* \_histo = new TH1D( "dummy","dummy", 100,0.,100); auto GetHistogramVal = [&\_histo](double \_variable){ double \_val = std::numeric\_limits\<float\>::min(); int \_bin = \_histo-\>FindBin(\_variable); if (\_histo-\>IsBinUnderflow(\_bin) || \_histo-\>IsBinOverflow(\_bin)) { if (\_variable \<…

Maybe this can be helpful  
There are shorter and clever tricks than the one posted here, for example you can simply make a struct implementing a member being your 2D histo to read and one operator() implementation, or even better maybe and simple to use lambda capturing the histogram as argument

```auto
 auto reweight=[& inputHist]( double X, double y){
....
};
node = node.Define( "w", reweight,{ "col1","col2"})

```

( Personally I prefer to declare a functor class to do this since then I can compile and make dictionary for it and use in pyROOT for other cases I need it)

. The only thing to be careful is that you use only const methods on the TH2D object in the operator() implementation.  
(E.g FindFixBin, GetBinContent, check out the doxygen if the methods you use are marked `const` for your Root version.

---

<div class="post-metadata">

**Author:** ![eguiraud](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/eguiraud/32/32217_2.png) [@eguiraud](https://root-forum.cern.ch/u/eguiraud)\
**Post date:** [July 21, 2022, 7:16am UTC](https://root-forum.cern.ch/t/using-a-predefined-th2d-in-rdataframe-to-compute-new-quantiy/50881/3 "2022-07-21T07:16:58Z")

</div>

Hi @tancredi ,

I would also suggest to create a little helper struct, that’s probably the cleanest:

```auto
struct ProbEvaluator {
   TH2D *hprob = nullptr;
   ProbEvaluator(TH2D *h) : hprob(h) {}

   // as Renato mentions, this should be thread-safe as long as we limit
   // ourselves to using const methods of TH2D (i.e. we don't modify the TH2D) 
   float operator()(float x, float y) {
       int ibin=hprob->FindBin(x,y);
      return hprob->GetBinContent(ibin);
   }
};

```

and then

```auto
ProbEvaluator p(yourHisto);
df.Define("prob", p, ["x", "y"]);

```

It would be great if @moneta could confirm that `TH2::FindBin` and `TH2::GetBinContent` are indeed thread-safe (but I would otherwise assume they are since they should be read-only operations).

Cheers,  
Enrico

---

<div class="post-metadata">

**Author:** ![RENATO\_QUAGLIANI](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/renato_quagliani/32/19496_2.png) [@RENATO\_QUAGLIANI](https://root-forum.cern.ch/u/RENATO_QUAGLIANI)\
**Post date:** [July 21, 2022, 8:10am UTC](https://root-forum.cern.ch/t/using-a-predefined-th2d-in-rdataframe-to-compute-new-quantiy/50881/4 "2022-07-21T08:10:35Z")

</div>

To be clearer, and thread safe, what i usually do is

```auto
struct ProbEvaluator {
   const TH2D hprob;
   ProbEvaluator(TH2D *h) : hprob(*h) {}
   ProbEvaluator(ProbEvaluator &other) : hprob(other.hprob) {}

   // as Renato mentions, this should be thread-safe as long as we limit
   // ourselves to using const methods of TH2D (i.e. we don't modify the TH2D) 
   float operator()(float x, float y) {
       int ibin=hprob.FindBin(x,y);
      return hprob.GetBinContent(ibin);
   }
};

```

The compiler should complaint using non `const` methods with this in principle (enforcing thread safety protections), that’s why i think `FindFixBin` should be used (or at least i usually do)

In the latest ROOT version also the `Interpolate` is marked `const` and `GetBinContent` probably always has been so. But yes, a confirmation would be useful

---

<div class="post-metadata">

**Author:** ![tancredi](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/tancredi/32/20395_2.png) [@tancredi](https://root-forum.cern.ch/u/tancredi)\
**Post date:** [July 21, 2022, 11:46am UTC](https://root-forum.cern.ch/t/using-a-predefined-th2d-in-rdataframe-to-compute-new-quantiy/50881/5 "2022-07-21T11:46:20Z")

</div>

Hello,  
thank you very much for the replies. How would I do this in python ?  
I guess I can compile the C++ code like usual, but how to implement this part

```auto
ProbEvaluator p(yourHisto);
df.Define("prob", p);

```

in python ?  
Regards,  
Tancredi

---

<div class="post-metadata">

**Author:** ![eguiraud](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/eguiraud/32/32217_2.png) [@eguiraud](https://root-forum.cern.ch/u/eguiraud)\
**Post date:** [July 21, 2022, 1:30pm UTC](https://root-forum.cern.ch/t/using-a-predefined-th2d-in-rdataframe-to-compute-new-quantiy/50881/6 "2022-07-21T13:30:59Z")

</div>

It should be just:

```auto
p = ROOT.ProbEvaluator(yourHisto)
df.Define("prob", p)

```

after you declare that C++ struct to ROOT, e.g. with `ROOT.gInterpreter.Declare('#include "ProbEvaluator.hxx"')`

Cheers,  
Enrico

---

<div class="post-metadata">

**Author:** ![moneta](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/moneta/32/19423_2.png) [@moneta](https://root-forum.cern.ch/u/moneta)\
**Post date:** [July 21, 2022, 2:13pm UTC](https://root-forum.cern.ch/t/using-a-predefined-th2d-in-rdataframe-to-compute-new-quantiy/50881/7 "2022-07-21T14:13:54Z")

</div>

Hi,

`TH1::GetBinContent` should be thread safe, if you are not using an histogram with the buffer (automatic binning)… Also it is true better using `FindFixBin` because `FindBin` can extend the axis for values outside the range, if the axis can be extended.

Lorenzo

---

<div class="post-metadata">

**Author:** ![tancredi](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/tancredi/32/20395_2.png) [@tancredi](https://root-forum.cern.ch/u/tancredi)\
**Post date:** [July 26, 2022, 7:57am UTC](https://root-forum.cern.ch/t/using-a-predefined-th2d-in-rdataframe-to-compute-new-quantiy/50881/8 "2022-07-26T07:57:20Z")

</div>

Dear @eguiraud  
I tried your solution but I get stuck declaring it in the RDataFrame.  
I attach a root file and my macro.

[prob.py](https://root-forum.cern.ch/uploads/short-url/14FwRwhe81Pgyzfua65o97dZp8g.py) (891 Bytes)  
[pion\_probablitity.root](https://root-forum.cern.ch/uploads/short-url/k4AgB0z8dTofMQMFBQfnfXIubP4.root) (7.1 KB)

```auto
#!/usr/bin/env python
#
import ROOT
import os,sys
#include c++ in python
ROOT.gInterpreter.Declare(
""" 
struct ProbEvaluator {
   const TH2D hprob;
   ProbEvaluator(TH2D *h) : hprob(*h) {}
   
   float operator()(float x, float y) {
       int ibin=hprob.FindFixBin(x,y);
      return hprob.GetBinContent(ibin);
   }
};
""")

#
if __name__ == " __main__":
 
 path = "root://eospublic.cern.ch//eos/opendata/atlas/OutreachDatasets/2020-01-22/"
 filename=path+'GamGam/Data/data_A.GamGam.root'
 print ('filename= ',filename)
 d = ROOT.RDataFrame("mini", filename) 
 #
 file = ROOT.TFile.Open('pion_probablitity.root','READ')
 h = file.Get("hcorrected")
 #h.Print("all")
 # this does not work 
 prob = ROOT.ProbEvaluator(h) 
 d = d.Define('prob', prob)

```

Can you help ?  
Tancredi

---

<div class="post-metadata">

**Author:** ![eguiraud](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/eguiraud/32/32217_2.png) [@eguiraud](https://root-forum.cern.ch/u/eguiraud)\
**Post date:** [August 1, 2022, 6:43pm UTC](https://root-forum.cern.ch/t/using-a-predefined-th2d-in-rdataframe-to-compute-new-quantiy/50881/9 "2022-08-01T18:43:02Z")

</div>

Hi @tancredi ,

sorry for the late reply, I was off last week.

The error message is doing its best to tell you what’s wrong, in particular:

```bash
runtime_error: 2 column names are required but none were provided and the default list has size 0

```

means that you should call `Define('prob', prob, ['column1', 'column2'])` instead of just `Define('prob', prob)`. In other words you have to tell RDataFrame what columns to apply your `ProbEvaluator` to.

Cheers,  
Enrico

---

<div class="post-metadata">

**Author:** ![tancredi](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/tancredi/32/20395_2.png) [@tancredi](https://root-forum.cern.ch/u/tancredi)\
**Post date:** [August 5, 2022, 5:41am UTC](https://root-forum.cern.ch/t/using-a-predefined-th2d-in-rdataframe-to-compute-new-quantiy/50881/10 "2022-08-05T05:41:11Z")

</div>

Thank you. This works !  
Tancredi
