Switching code from pyroot to C++

Hello,
I’m having a problem getting missing mass plot for each missing momentum bin using C++.
I do this in python but I get trouble when I switch to C++. Could you please help me to rewrite it in C++.
Here is apart of my code

hx = h2.ProjectionX()
nbins = 10
xlims = [0]
for ib in range(hx.GetNbinsX()):
  if hx.Integral(xlims[-1], ib) > hx.GetEntries()/nbins:
    print(hx.Integral(xlims[-1], ib))

    xlims.append(ib)
xlims.append(hx.GetNbinsX())
print(xlims)
ll = ROOT.TLine()
ll.SetLineColor(2)
lblue = ROOT.TLine()
lblue.SetLineColor(4)
hx.Draw()
for ix0, ix in zip(xlims[:-1], xlims[1:]):
  xx = hx.GetBinCenter(ix)
  hx.GetXaxis().SetRange(ix0, ix)
  xmean = hx.GetMean()
  ll.DrawLine(xx,0,xx,hx.GetMaximum())
  lblue.DrawLine(xmean,0,xmean,hx.GetMaximum()/2)
hx.GetXaxis().SetRange(0,-1)
c1.Print('test.pdf')

for ix0, ix1 in zip(xlims[:-1], xlims[1:]):
  hx.GetXaxis().SetRange(ix0, ix1)
  xmean = hx.GetMean()
  hy = h2.ProjectionY("",ix0,ix1)
  hy.GetXaxis().SetRangeUser(0,2)
  hy.Draw()
  c1.Print('test.pdf')
c1.Print('test.pdf]')

Please read tips for efficient and successful posting and posting code

ROOT Version: 6.16/00
Platform: Not Provided
Compiler: Not Provided


I guess @etejedor can probably help

Hi @lamya86 ,

What is exactly the issue you have when you translate your code to C++?

When I am trying to print this loop:

nbins = 10
xlims = [0]
for ib in range(hx.GetNbinsX()):
  if hx.Integral(xlims[-1], ib) > hx.GetEntries()/nbins:
    print(xlims[-1],ib)
    xlims.append(ib)
xlims.append(hx.GetNbinsX())
print(xlims)

It is give me
(0, 10)
(10, 13)
(13, 16)
(16, 19)
(19, 22)
(22, 25)
(25, 28)
(28, 31)
(31, 34)
(34, 39)
[0, 10, 13, 16, 19, 22, 25, 28, 31, 34, 39, 150]

and when I change nbins these values will be changed. So I am actually trying to divide my histogram into nbins =10 with almost the same statistical data in each nbins

Here is my attempts

int nbin =12;
    int xlim[]={0};
    Double_t integ = 0; 
    int nOfevent=0;
    for (int i = 1; i<=g2->GetNbinsX(); i++) {
        integ += g2->Integral(i,i+1);
        nOfevent =  g2->GetEntries()/nbin;
        
        if (integ > nOfevent){
            std::cout<<"integ  "  <<integ <<"  i "  << i<< std::endl;
            std::cout<<"nOfevent  "  <<nOfevent <<"  i "  << i<< std::endl;
        }

        integ=0;
    }

Hi,
A couple of comments about your C++ code:

  • xlims is a Python list in the Python version, perhaps you can use an std::vector in the C++ one (since you need to append numbers).
  • The for loop in Python goes from 0 to hx.GetNbinsX() -1, whereas the for loop in C++ starts at 1 and ends at g2->GetNbinsX(). You can make it symmetric with the Python version if you use the vector in C++.

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