Catching TH2::Rebin error in pyRoot

Hi, I have pyroot script where I take a 2D histogram and rebin this until the number of effective entries is sufficiently large. i.e. I do something like this:

while int(my_th1d.GetEffectiveEntries() < 10):
  my_th2d.RebinY()
  my_th1d = my_th2d.ProjectionX( "a", iBin, iBin, "ed")

The problem is that I get an error for a particular value of iBin (an integer taking values corresponding to the y-axis bins):

Error in <TH2D::Rebin2D>: Illegal value of nygroup=2

I want to be able to catch this error in pyRoot, maybe using try and except so that I can then change nygroup to a larger value or exit the while loop some other way. Is there a way to do this in pyRoot? How can I keep track of the fact that there is an ROOT error. I have seen the rootpy logger (7. Logging — rootpy 1.0.0.dev0 documentation) module, but I’m not sure how to use this for my needs.

Many thanks,
Ben


Please read tips for efficient and successful posting and posting code

ROOT Version: 6.20/06
Platform: SLC7
Compiler: linuxx8664gcc


Hi @BPH,

In ROOT C++ you can set a custom error handler via ::SetErrorHandler() (declared in TError.h); setting up a custom error handler would allow you to catch those errors and act accordingly. However, I am not sure if this can be used in PyROOT or whether there is another approach. Perhaps, @etejedor can help here.

Cheers,
J.

Thank you jalopezg! I have a hacky workaround where I just check if the number of effective entries stays the same 3 times in a row and then exits the loop if it does. This works, so not the end of the world if a nice solution cannot be found. Woulds still be nice to do this in a non-hacky way though!

Appreciate the help
Ben

Hi @BPH,

Ignore my previous reply ;-). As it seems, the error comes from the my_th2d.RebinY() call, where the default value for the ngroup parameter is 2. In this case, you can check that the number of bins is at least 2 before trying to call RebinY() by using GetNbinsY().

Cheers,
J.

Hi @jalopezg ,

Ah, of course. The rebinning is failing because the number of bins after rebinning is not compatible with the ngroup parameter. Thanks a lot! That’s a good solution :slight_smile:

Cheers,
Ben

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.