Beispiel #1
0
//________________________________________________________________
void KVCanvas::DynamicZoomTH1(Int_t Sign, Int_t px, Int_t)
{
   // Zoom in or out of histogram with mouse wheel

   if (!fSelected) return;
   TH1* TheHisto = (TH1*) FindHisto();//fSelected;

   Double_t percent = 0.15 - Sign * 0.05;

   Int_t dX = 0;

   px = AbsPixeltoX(px);

   TAxis* ax = TheHisto->GetXaxis();
   Int_t NbinsXtmp = ax->GetNbins();
   Int_t X0tmp = ax->GetFirst();
   Int_t X1tmp = ax->GetLast();
   Int_t step = TMath::Min(TMath::Max(1, (Int_t)(percent * (X1tmp - X0tmp))), NbinsXtmp / 2);
   step *= Sign;
   X0tmp = TMath::Min(TMath::Max(X0tmp + step, 1), X1tmp - step);
   X1tmp = TMath::Max(TMath::Min(X1tmp - step, NbinsXtmp), X0tmp);
   if (X0tmp >= X1tmp) X0tmp = X1tmp - 1;
   if (Sign > 0) dX = (Int_t)(X0tmp + (X1tmp - X0tmp) * 0.5 - ax->FindBin(px));
   if ((X0tmp - dX) < 0) ax->SetRange(0, X1tmp - X0tmp);
   else if ((X1tmp - dX) > ax->GetNbins()) ax->SetRange(ax->GetNbins() - (X1tmp - X0tmp), ax->GetNbins());
   else ax->SetRange(X0tmp - dX, X1tmp - dX);


   Modified();
   Update();
   return;
}
Beispiel #2
0
TH1* linearizeHistogram(TH1* histogram)
{
  if ( !histogram ) return 0;

  TH1* histogram2d = dynamic_cast<TH2*>(histogram);
  if ( !histogram2d ) return histogram;

  TAxis* xAxis = histogram2d->GetXaxis();
  int numBinsX = xAxis->GetNbins();
  TAxis* yAxis = histogram2d->GetYaxis();
  int numBinsY = yAxis->GetNbins();

  std::string histogramName1d = Form("%s_1d", histogram->GetName());
  int numBins1d = numBinsX*numBinsY;
  TH1* histogram1d = new TH1D(histogramName1d.data(),histogramName1d.data(), numBins1d, -0.5, numBins1d - 0.5);
  int iBin1d = 1;
  for ( int iBinX = 1; iBinX <= numBinsX; ++iBinX ) {
    for ( int iBinY = 1; iBinY <= numBinsY; ++iBinY ) {
      double binContent = histogram2d->GetBinContent(iBinX, iBinY);
      double binError = histogram2d->GetBinError(iBinX, iBinY);
      histogram1d->SetBinContent(iBin1d, binContent);
      histogram1d->SetBinError(iBin1d, binError);
      ++iBin1d;
    }
  }

  return histogram1d;
}
Beispiel #3
0
//______________________________________________________________________________
TEveCaloDataVec* MakeVecData(Int_t ncells=0)
{
   // Example how to fill data when bins can be iregular.
   // If ncells = 0 (default) whole histogram is taken,
   // otherwise just ncells cells around the maximum.

   TFile::SetCacheFileDir(".");
   TFile* hf = TFile::Open(histFile, "CACHEREAD");
   TH2F* h1 = (TH2F*)hf->Get("ecalLego");
   TH2F* h2 = (TH2F*)hf->Get("hcalLego");

   TEveCaloDataVec* data = new TEveCaloDataVec(2);
   data->RefSliceInfo(0).Setup("ECAL", 0.3, kRed);
   data->RefSliceInfo(1).Setup("HCAL", 0.1, kBlue);

   TAxis *ax =  h1->GetXaxis();
   TAxis *ay =  h1->GetYaxis();

   Int_t xm = 1, xM = ax->GetNbins();
   Int_t ym = 1, yM = ay->GetNbins();
   if (ncells != 0)
   {
      Int_t cx, cy, cz;
      h1->GetMaximumBin(cx, cy, cz);
      xm = TMath::Max(xm, cx-ncells);
      xM = TMath::Min(xM, cx+ncells);
      ym = TMath::Max(ym, cy-ncells);
      yM = TMath::Min(yM, cy+ncells);
   }

   // Take every second cell and set a random size.
   for(Int_t i=xm; i<=xM; i+=2)
   {
      for(Int_t j=ym; j<=yM; j+=2)
      {
         if ( (i+j) % 3)
         {
            data->AddTower(ax->GetBinLowEdge(i), ax->GetBinUpEdge(i),
                           ay->GetBinLowEdge(j), ay->GetBinUpEdge(j));
            data->FillSlice(0, h1->GetBinContent(i, j));
            data->FillSlice(1, h2->GetBinContent(i, j));
         }
         else
         {
            data->AddTower(ax->GetBinLowEdge(i),
                           2 * ax->GetBinWidth(i) + ax->GetBinLowEdge(i),
                           ay->GetBinLowEdge(j),
                           2 * ay->GetBinWidth(j) + ay->GetBinLowEdge(j));
            data->FillSlice(0, h2->GetBinContent(i, j));
            data->FillSlice(1, h2->GetBinContent(i, j));
         }
      }
   }

   data->SetEtaBins(ax);
   data->SetPhiBins(ay);
   data->DataChanged();
   return data;
}
    static bool CheckAxisCompatibility(const TAxis& a, const TAxis& b)
    {
        static const double delta_max = 0.001;
        static const double rel_delta_max = 0.01;

        if(a.GetNbins() != b.GetNbins()) return false;
        for(Int_t n = 1; n <= a.GetNbins(); ++n) {
            const double c_a = a.GetBinCenter(n);
            const double c_b = b.GetBinCenter(n);
            const double delta = c_a - c_b;
            if( ( c_a && std::abs(delta/c_a) > rel_delta_max ) || ( !c_a && std::abs(delta) > delta_max ) )
                return false;
        }
        return true;
    }
Beispiel #5
0
//______________________________________________________________________________
void drawsparse_draw(THnSparse* h)
{
   // Draw a THnSparse using TParallelCoord, creating a temporary TTree.

   TTree* tree = toTree(h);

   TString whatToDraw;
   TIter iLeaf(tree->GetListOfLeaves());
   const TLeaf* leaf = 0;
   while ((leaf = (const TLeaf*)iLeaf())) {
      if (whatToDraw.Length())
         whatToDraw += ":";
      whatToDraw += leaf->GetName();
   }
   tree->Draw(whatToDraw, "", "para");
   TParallelCoord* parallelCoord = (TParallelCoord*)gPad->GetListOfPrimitives()->FindObject("ParaCoord");

   TIter iVar(parallelCoord->GetVarList());
   TParallelCoordVar* var = 0;
   for (Int_t d = 0;(var = (TParallelCoordVar*) iVar()) && d < h->GetNdimensions(); ++d) {
      TAxis* axis = h->GetAxis(d);
      var->SetHistogramBinning(axis->GetNbins());
      var->SetCurrentLimits(axis->GetXmin(), axis->GetXmax());
      var->SetTitle(axis->GetTitle());
   }
   var->SetTitle("bin content");
}
Beispiel #6
0
 /** comapre axis for equalitiy
  *
  * check whether the cass histogram axis and the root histogram axis are the
  * same. Test for number of bins, low and high ends and the title of the axis.
  *
  * @return true when both axis are the same
  * @param ca the axis of the cass histogram
  * @param ra the axis of the root histogram
  *
  * @author Lutz Foucar
  */
 bool operator== (const cass::Result<float>::axe_t &ca, const TAxis &ra)
 {
   return (static_cast<int>(ca.nBins) == ra.GetNbins() &&
           fabs(ca.low - ra.GetXmin()) <  sqrt(numeric_limits<double>::epsilon()) &&
           fabs(ca.up  - ra.GetXmax())  <  sqrt(numeric_limits<double>::epsilon()) &&
           ca.title == ra.GetTitle());
 }
void BinLog(TH2F *h) 
{

   TAxis *axis = h->GetXaxis(); 
   int bins = axis->GetNbins();

   Axis_t from = axis->GetXmin();
   Axis_t to = axis->GetXmax();
   Axis_t width = (to - from) / bins;
   Axis_t *new_bins = new Axis_t[bins + 1];

   for (int i = 0; i <= bins; i++) {
     new_bins[i] = TMath::Power(10, from + i * width);
   } 
   axis->Set(bins, new_bins); 

   TAxis *axis2 = h->GetYaxis(); 
   int bins2 = axis2->GetNbins();

   Axis_t from2 = axis2->GetXmin();
   Axis_t to2 = axis2->GetXmax();
   Axis_t width2 = (to2 - from2) / bins2;
   Axis_t *new_bins2 = new Axis_t[bins2 + 1];

   for (int i = 0; i <= bins2; i++) {
     new_bins2[i] = TMath::Power(10, from2 + i * width2);
   } 
   axis2->Set(bins2, new_bins2); 

   delete new_bins;
   delete new_bins2;
}
void
getLimits (TH1D *cutFlow, TDirectoryFile *dir)
{
  string histName = cutFlow->GetName ();
  TH1D *lowerLimit = (TH1D *) cutFlow->Clone ((histName + "LowerLimit").c_str ()),
       *upperLimit = (TH1D *) cutFlow->Clone ((histName + "UpperLimit").c_str ());

  TAxis *x = cutFlow->GetXaxis ();
  for (int i = 1; i <= x->GetNbins (); i++)
    {
      double events = cutFlow->GetBinContent (i), eventsLowerLimit, eventsUpperLimit;

      // The calculation of upper and lower limits is taken from the PDG Statistics chapter.  
      // "Poisson or binomal data", section 37.4.2.3 in 2013 version; Eqns. 37.71a, 37.71b.  
      // Here ALPHA is the confidence level, so ALPHA = 0.68 corresponds to a 68% C.L.
      // The PDG uses a different convention:  the C.L is 1 - \alpha.  
      // For example, the 68% CL upper limit on an observation of 0 events is:
      // 0.5 * TMath::ChisquareQuantile (0.68, 2) = 1.139  
      eventsLowerLimit = 0.5 * TMath::ChisquareQuantile (1 - ALPHA, 2 * events);
      eventsUpperLimit = 0.5 * TMath::ChisquareQuantile (ALPHA, 2 * (events + 1));
      lowerLimit->SetBinContent (i, eventsLowerLimit);
      upperLimit->SetBinContent (i, eventsUpperLimit);
    }
  dir->cd ();
  lowerLimit->Write ((histName + "LowerLimit").c_str ());
  upperLimit->Write ((histName + "UpperLimit").c_str ());
}
Beispiel #9
0
TH2F * histo_rebin(TH2F *h, const int nx, const Double_t *xbins, const int ny, const Double_t *ybins){

  // NB: the errors of the rebinned histogram are wrong!

  TH2F * h_new = new TH2F("h_new",h->GetTitle(),nx,xbins,ny,ybins);
  h_new->Sumw2();

  TAxis *xaxis = h->GetXaxis();
  TAxis *yaxis = h->GetYaxis();
  
  for (int jbin=1; jbin<=yaxis->GetNbins(); ++jbin){
    for (int ibin=1; ibin<=xaxis->GetNbins(); ++ibin){
      h_new->Fill(xaxis->GetBinCenter(ibin),yaxis->GetBinCenter(jbin),h->GetBinContent(ibin,jbin));
    }
  }
  
  return (TH2F*) h_new->Clone();
  
}
Beispiel #10
0
void divideByBinWidth(TH1* histogram)
{
  if ( !histogram ) return;
  TAxis* xAxis = histogram->GetXaxis();
  int numBins = xAxis->GetNbins();
  for ( int iBin = 1; iBin <= numBins; ++iBin ) {
    double binContent = histogram->GetBinContent(iBin);
    double binError = histogram->GetBinError(iBin);
    double binWidth = xAxis->GetBinWidth(iBin);
    histogram->SetBinContent(iBin, binContent/binWidth);
    histogram->SetBinError(iBin, binError/binWidth);
  }
}
void dumpHistogram(TH1* histogram)
{
  std::cout << "<dumpHistogram>:" << std::endl;
  std::cout << " histogram: name = " << histogram->GetName() << ", title = " << histogram->GetTitle() << std::endl;
  std::cout << "  fillColor = " << histogram->GetFillColor() << ", fillStyle = " << histogram->GetFillStyle() << ","
	    << " lineColor = " << histogram->GetLineColor() << ", lineStyle = " << histogram->GetLineStyle() << ", lineWidth = " << histogram->GetLineWidth() << "," 
	    << " markerColor = " << histogram->GetMarkerColor() << ", markerStyle = " << histogram->GetMarkerStyle() << ", markerSize = " << histogram->GetMarkerSize() << std::endl;
  TAxis* xAxis = histogram->GetXaxis();
  int numBins = xAxis->GetNbins();
  for ( int iBin = 1; iBin <= numBins; ++iBin ) {
    std::cout << "bin #" << iBin << " (x = " << xAxis->GetBinCenter(iBin) << "): " << histogram->GetBinContent(iBin) << " +/- " << histogram->GetBinError(iBin) << std::endl;
  }
  std::cout << "integral = " << compIntegral(histogram, true, true) << std::endl;
}
TH1* divideHistogramByBinWidth(TH1* histogram)
{
  std::string histogramDensityName = Form("%s_density", histogram->GetName());
  TH1* histogramDensity = (TH1*)histogram->Clone(histogramDensityName.data());
  TAxis* xAxis = histogram->GetXaxis();
  int numBins = xAxis->GetNbins();
  for ( int iBin = 1; iBin <= numBins; ++iBin ) {
    double binContent = histogram->GetBinContent(iBin);
    double binError = histogram->GetBinError(iBin);
    double binWidth = xAxis->GetBinWidth(iBin);
    histogramDensity->SetBinContent(iBin, binContent/binWidth);
    histogramDensity->SetBinError(iBin, binError/binWidth);
  }
  return histogramDensity;
}
Beispiel #13
0
void findFilterEnergyLoss::BinLogY(TH2 *h) {
   TAxis *axis = h->GetYaxis();
   int bins = axis->GetNbins();

   Axis_t from = axis->GetXmin();
   Axis_t to = axis->GetXmax();
   Axis_t width = (to - from) / bins;

   Axis_t *new_bins = new Axis_t[bins+1];

   for (int i=0; i <= bins; i++) {
      new_bins[i] = TMath::Power(10, from + i * width);
   }

   axis->Set(bins, new_bins);
   delete new_bins;
}
Beispiel #14
0
void printStat(const char* fl)
{
  printf("Stat for %s\n",fl);
  TFile* ff = TFile::Open(fl);
  TList* lst = (TList*)ff->Get("clist");
  if (!lst) {printf("no clist\n");return;}
  TH1* hstat = (TH1*)lst->FindObject("stat");
  if (!hstat) {printf("no hstat\n");return;}
  //
  TAxis* ax = hstat->GetXaxis();
  for (int ib=1;ib<ax->GetNbins();ib++) {
    double val = hstat->GetBinContent(ib);
    if (val) printf("%-20s\t%9d\n",ax->GetBinLabel(ib),int(val));
  }
  ff->Close();
  delete ff;
  return;
}
Beispiel #15
0
//________________________________________________________________
void KVCanvas::DynamicZoom(Int_t Sign, Int_t px, Int_t py)
{
   // Zoom in or out of histogram with mouse wheel

   //    Info("DynamicZoom","px=%d py=%d",px,py);

   if (!fSelected) return;
   TH2* TheHisto = (TH2*) FindHisto();//fSelected;

   Double_t percent = 0.15 - Sign * 0.05;

   Int_t dX = 0;
   Int_t dY = 0;

   Double_t ppx = AbsPixeltoX(px);
   Double_t ppy = AbsPixeltoY(py);

   TAxis* ax = TheHisto->GetXaxis();
   Int_t NbinsXtmp = ax->GetNbins();
   Int_t X0tmp = ax->GetFirst();
   Int_t X1tmp = ax->GetLast();
   Int_t step = TMath::Min(TMath::Max(1, (Int_t)(percent * (X1tmp - X0tmp))), NbinsXtmp / 2);
   step *= Sign;
   X0tmp = TMath::Min(TMath::Max(X0tmp + step, 1), X1tmp - step);
   X1tmp = TMath::Max(TMath::Min(X1tmp - step, NbinsXtmp), X0tmp);
   if (X0tmp >= X1tmp) X0tmp = X1tmp - 1;
   if (Sign > 0) dX = (Int_t)(X0tmp + (X1tmp - X0tmp) * 0.5 - ax->FindBin(ppx));
   if ((X0tmp - dX) < 0) ax->SetRange(0, X1tmp - X0tmp);
   else if ((X1tmp - dX) > ax->GetNbins()) ax->SetRange(ax->GetNbins() - (X1tmp - X0tmp), ax->GetNbins());
   else ax->SetRange(X0tmp - dX, X1tmp - dX);

   ax = TheHisto->GetYaxis();
   Int_t NbinsYtmp = ax->GetNbins();
   Int_t Y0tmp = ax->GetFirst();
   Int_t Y1tmp = ax->GetLast();
   step = TMath::Min(TMath::Max(1, (Int_t)(percent * (Y1tmp - Y0tmp))), NbinsYtmp / 2);
   step *= Sign;
   Y0tmp = TMath::Min(TMath::Max(Y0tmp + step, 1), Y1tmp - step);
   Y1tmp = TMath::Max(TMath::Min(Y1tmp - step, NbinsYtmp), Y0tmp);
   if (Y0tmp >= Y1tmp) Y0tmp = Y1tmp - 1;
   if (Sign > 0) dY = (Int_t)(Y0tmp + (Y1tmp - Y0tmp) * 0.5 - ax->FindBin(ppy));
   if ((Y0tmp - dY) < 0) ax->SetRange(0, Y1tmp - Y0tmp);
   else if ((Y1tmp - dY) > ax->GetNbins()) ax->SetRange(ax->GetNbins() - (Y1tmp - Y0tmp), ax->GetNbins());
   else ax->SetRange(Y0tmp - dY, Y1tmp - dY);

   Modified();
   Update();
   return;
}
void th22mama(TH2* m, const char* filename, const char* comment="none")
{
    char tmp[128];
    time_t now = time(0);
    strftime(tmp, sizeof(tmp), "%Y-%m-%d %T", localtime(&now)); // not the 23-Mar-07 16:02:34 format
    
    TAxis *xax = m->GetXaxis(), *yax = m->GetYaxis();
    
    const int nx = std::min(xax->GetNbins(), 2048);
    const int ny = yax->GetNbins();
    std::cout << "matrix is " << nx << 'x' << ny << "; comment='" << comment << "'" << std::endl;
    
    std::ofstream mama(filename);
    mama << "!FILE=Disk \n"
    "!KIND=Matrix \n"
    "!LABORATORY=Oslo Cyclotron Laboratory (OCL) \n"
    "!EXPERIMENT=siri2root \n"
    "!COMMENT=" << comment << "\n"
    "!TIME=" << tmp << "\n"
    "!CALIBRATION EkeV=6";
    const float cal[6] = { xax->GetBinLowEdge(1), xax->GetBinWidth(1), 0,
        yax->GetBinLowEdge(1), yax->GetBinWidth(1), 0 };
    for(int i=0; i<6; ++i) {
        snprintf(tmp, sizeof(tmp), ",%13.6E", cal[i]);
        mama << tmp;
    }
    mama << "\n!PRECISION=16\n";
    snprintf(tmp, sizeof(tmp), "!DIMENSION=2,0:%4d,0:%4d\n", nx-1, ny-1);
    mama << tmp;
    snprintf(tmp, sizeof(tmp), "!CHANNEL=(0:%4d,0:%4d)\n", nx-1, ny-1);
    mama << tmp;
    
    for(int iy=1; iy<=ny; ++iy) {
        for(int ix=1; ix<=nx; ++ix)
            mama << m->GetBinContent(ix, iy) << ' ';
        mama << "\n";
    }
    mama << "!IDEND=" << endl << endl;
    
    mama.close();
}
void BinLogAxis(const TH1 *h)
{
  //
  // Method for the correct logarithmic binning of histograms
  //
  TAxis *axis = const_cast<TAxis*>(h->GetXaxis());
  const Int_t bins = axis->GetNbins();
  
  const Double_t from = axis->GetXmin();
  const Double_t to = axis->GetXmax();
  Double_t *newBins = new Double_t[bins + 1];
  
  newBins[0] = from;
  Double_t factor = pow(to / from, 1. / bins);
  
  for (Int_t i = 1; i <= bins; i++) {
    newBins[i] = factor * newBins[i - 1];
  }
  axis->Set(bins, newBins);
  delete [] newBins;
  
}
 void fillHistograms(double mvaOutput, double pt, double eta, double Nvtx, double evtWeight)
 {    
   histogramPt_denominator_->Fill(pt, evtWeight);
   histogramEta_denominator_->Fill(eta, evtWeight);
   histogramNvtx_denominator_->Fill(Nvtx, evtWeight);
   bool passesCuts = (mvaOutput > mvaCut_);
   //std::cout << "passesCuts = " << passesCuts << std::endl;
   if ( passesCuts ) {
     histogramPt_numerator_->Fill(pt, evtWeight);
     histogramEta_numerator_->Fill(eta, evtWeight);
     histogramNvtx_numerator_->Fill(Nvtx, evtWeight);
   }
   double y = mvaOutput;
   TAxis* yAxis = histogramMVAoutput_vs_Pt_->GetYaxis();
   int binY = yAxis->FindBin(y);
   int numBinsY = yAxis->GetNbins();
   if ( binY <  1       ) binY = 1;
   if ( binY > numBinsY ) binY = numBinsY;
   double yWithinRange = yAxis->GetBinCenter(binY);
   histogramMVAoutput_vs_Pt_->Fill(pt, y, evtWeight);
   histogramPt_->Fill(pt, evtWeight);
 }
Beispiel #19
0
TH1* VariableSizeRebin(TH1* inhisto, unsigned int nbinsx,
		       double *xbins, TString axisname="x",
		       TString newhistoname="newhist")
{
  if ( nbinsx == 0 ) {
    cout << "Error! nbinsx must be non-zero." << endl; return 0; }

  if ( inhisto == 0 ) {
    cout << "Error! Input histogram pointer is null." << endl; return 0; }

  if ( axisname == "y"  &&  !inhisto->InheritsFrom("TH2") ) {
    cout << "No y-axis defined for " << inhisto->GetName() << endl; return 0; }

  if ( newhistoname == "" ) {
    cout << "Error! Output histogram name is null."<< endl; return 0; }

  double *edgeArr = new double[nbinsx+2]; // an extra bin for safety

  TAxis *axis = (axisname=="y" ? inhisto->GetYaxis() : inhisto->GetXaxis());

  unsigned int nbins = 0; // number of bins for the new histogram
  unsigned int j = 0; // dummy bin index (to be used as a pointer)

  for ( unsigned int i=0; i<=axis->GetNbins()+1; ++i ) {

    if ( j > nbinsx ) break;

    double ble = axis->GetBinLowEdge(i);

    if ( xbins[j] > ble ) continue;

    edgeArr[nbins] = ble; j++; nbins++;

    if ( xbins[j-1] < ble ) {
      cout << "Warning! Bin edge at " << xbins[j-1] << " does not align with"
	   << " input histo. Realigning at " << ble << ".\n";
      // check if the upcoming bin edges become obsolete after realigning.
      while ( j<=nbinsx && xbins[j] <= ble ) j++;
    }

  }

  // if we finished the loop normally, ie. not 'break'ing out, it must be
  // that the input histogram xrange is shorter than what the new binning
  // tried to get. So handle that.
  if ( j <= nbinsx ) {
    double xmax = axis->GetBinLowEdge(axis->GetNbins()+1);
    if ( xmax>edgeArr[nbins-1] ) {
      edgeArr[nbins]=xmax;
      cout << "Warning! Input histo reached max value of its x-range. "
	   << "Last bin to be closed at " << edgeArr[nbins] << "." << endl;
      nbins++; }
  }

  // we go out of the loop when index j overshoots. So our nbins is
  // always one more than actual number of bins. Fix that.
  nbins--;

  if ( nbinsx != nbins )
    cout << "Warning! nbinsx set to " << nbins
	 << " instead of " << nbinsx << "." << endl;

  //for ( unsigned int i=0; i<=nbins; i++ )
  //  cout << "For bin " << i+1 << "\tlowedge= " << edgeArr[i] << endl;

  // Now generate the new histogram
  TH1 *newhist = 0;

  if ( !inhisto->InheritsFrom("TH2") )
    newhist = inhisto->Rebin(nbins,newhistoname.Data(),edgeArr);

  else {

    // Copy the perpendicular axis as it is.
    TAxis *axisp = (axisname=="y" ? inhisto->GetXaxis() : inhisto->GetYaxis());
    unsigned int nbinsp = axisp->GetNbins();
    double *edgeArrp = new double[nbinsp+1];
    for ( unsigned int i=1; i<=nbinsp+1; ++i )
      edgeArrp[i] = axisp->GetBinLowEdge(i);

    if ( axisname == "y" ) {

      if ( axisp->IsVariableBinSize() )
	newhist = new TH2D(newhistoname, inhisto->GetTitle(),
			   nbinsp, edgeArrp, nbins, edgeArr);
      else
	newhist = new TH2D(newhistoname, inhisto->GetTitle(),
			   nbinsp, edgeArrp[0], edgeArrp[nbinsp+1],
			   nbins, edgeArr);

      if ( axisp->GetLabels() )
	for ( unsigned int i=1; i<=nbinsp; ++i )
	newhist->GetXaxis()->SetBinLabel(i, axisp->GetBinLabel(i));

    }
    else
      // ToDo: Have not yet implemented the above nice stuff for axisname=="x"
      newhist = new TH2D(newhistoname, inhisto->GetTitle(),
			 nbins, edgeArr, nbinsp, edgeArrp);

    newhist->GetYaxis()->SetTitle(inhisto->GetYaxis()->GetTitle());
    newhist->GetXaxis()->SetTitle(inhisto->GetXaxis()->GetTitle());
    bool sw2 = ( inhisto->GetSumw2N() != 0 );

    // Fill the new histogram from the input histogram
    j=0; // reset the dummy bin index
    for ( unsigned int i=0; i<=axis->GetNbins()+1; ++i ) {

      double ble = axis->GetBinLowEdge(i);
      if ( edgeArr[j] == ble ) j++; 

      for ( unsigned int k=0; k<=nbinsp+1; ++k ) {

	int newbin(0), oldbin(0);
	// Equivalent 1D bin number = binx + (fXaxis.GetNbins()+2)*biny
	if ( axisname == "y" ) {
	  newbin = k+j*(nbinsp+2); oldbin = k+i*(nbinsp+2); }
	else {
	  newbin = j+k*(nbins+2); oldbin = i+k*(axis->GetNbins()+2); }

	newhist->SetBinContent( newbin, newhist->GetBinContent(newbin)
				+ inhisto->GetBinContent(oldbin) );
	if ( sw2 )
	  newhist->SetBinError( newbin,
			        sqrt(pow(newhist->GetBinError(newbin),2) +
				     pow(inhisto->GetBinError(oldbin),2)) );
      }
    }

    newhist->SetEntries(inhisto->GetEntries());

  }

  //newhist->Draw();
  delete [] edgeArr;
  return newhist;
}
Beispiel #20
0
//______________________________________________________________________________
void KVCanvas::HandleInput(EEventType event, Int_t px, Int_t py)
{
   // Handle Input Events.
   //
   //  Handle input events, like button up/down in current canvas.

   if (fFreezed) return;

   TPad*    pad;
   TPad*    prevSelPad = (TPad*) fSelectedPad;
   TObject* prevSelObj = fSelected;

   fPadSave = (TPad*)gPad;
   cd();        // make sure this canvas is the current canvas

   fEvent  = event;
   fEventX = px;
   fEventY = py;

   Int_t sign = 0;
   Bool_t sendOrder = true;

   if (fHasDisabledClasses && fSelected) {
      if (fDisabledClasses.Contains(fSelected->ClassName())) sendOrder = false;
   }

   if (fHasDisabledObject && fSelected) {
      if (fDisabledObjects.Contains(fSelected)) sendOrder = false;
   }

   switch (event) {

      case kMouseMotion:
         // highlight object tracked over
         pad = Pick(px, py, prevSelObj);
         if (!pad) return;

         EnterLeave(prevSelPad, prevSelObj);

         gPad = pad;   // don't use cd() we will use the current
         // canvas via the GetCanvas member and not via
         // gPad->GetCanvas

         if (sendOrder) fSelected->ExecuteEvent(event, px, py);

         RunAutoExec();

         if (fAgeOfEmpire && (fSelected->InheritsFrom("TH2"))) {
            TH2* TheHisto = (TH2*) FindHisto();//fSelected;

            Double_t size = 0.4 - 0.35 * fVenerMode;

            Int_t dX = 0;
            Int_t dY = 0;

            Double_t ppx = AbsPixeltoX(px);
            Double_t ppy = AbsPixeltoY(py);

            TAxis* ax = TheHisto->GetXaxis();
            Int_t X0 = ax->GetFirst();
            Int_t X1 = ax->GetLast();
            Int_t NbinsX = ax->GetNbins();
            px = ax->FindBin(ppx);

            Double_t ddX   = (X1 + X0) * 0.5 - px;
            Double_t distX = TMath::Abs(ddX) / (X1 - X0);
            if (distX >= 0.5) return;

            TAxis* ay = TheHisto->GetYaxis();
            Int_t Y0 = ay->GetFirst();
            Int_t Y1 = ay->GetLast();
            Int_t NbinsY = ay->GetNbins();
            py = ay->FindBin(ppy);

            Double_t ddY   = (Y1 + Y0) * 0.5 - py;
            Double_t distY = TMath::Abs(ddY) / (Y1 - Y0);
            if (distY >= 0.5) return;

            if ((distX <= size) && (distY <= size)) return;
            dX = TMath::Nint(ddX * (0.05 + 0.05 * fVenerMode));
            dY = TMath::Nint(ddY * (0.05 + 0.05 * fVenerMode));

            if (TMath::Abs(dX) < 1) dX = TMath::Sign(1., ddX);
            if (TMath::Abs(dY) < 1) dY = TMath::Sign(1., ddY);


            Bool_t up = false;
            if ((X0 - dX > 0) && (X1 - dX < NbinsX)) {
               ax->SetRange(X0 - dX, X1 - dX);
               up = true;
            }
            if ((Y0 - dY > 0) && (Y1 - dY < NbinsY)) {
               ay->SetRange(Y0 - dY, Y1 - dY);
               up = true;
            }
            if (up) {
               Modified();
               Update();
            }
         }

         break;

      case kMouseEnter:
         // mouse enters canvas
         if (!fDoubleBuffer) FeedbackMode(kTRUE);
         break;

      case kMouseLeave:
         // mouse leaves canvas
         {
            // force popdown of tooltips
            TObject* sobj = fSelected;
            TPad*    spad = fSelectedPad;
            fSelected     = 0;
            fSelectedPad  = 0;
            EnterLeave(prevSelPad, prevSelObj);
            fSelected     = sobj;
            fSelectedPad  = spad;
            if (!fDoubleBuffer) FeedbackMode(kFALSE);
         }
         break;

      case kButton1Double:
      // triggered on the second button down within 350ms and within
      // 3x3 pixels of the first button down, button up finishes action

      case kButton1Down:
         // find pad in which input occured
         pad = Pick(px, py, prevSelObj);
         if (!pad) return;

         gPad = pad;   // don't use cd() because we won't draw in pad
         // we will only use its coordinate system

         if (fSelected) {
            FeedbackMode(kTRUE);   // to draw in rubberband mode
            fSelected->ExecuteEvent(event, px, py);

            RunAutoExec();

            if (fSelected->InheritsFrom("TH2")) {
               oldx = GetEventX();
               oldy = GetEventY();
               xmin = AbsPixeltoX(oldx);
               ymin = AbsPixeltoY(oldy);
               gVirtualX->DrawBox(XtoAbsPixel(xmin), YtoAbsPixel(ymin), oldx, oldy, TVirtualX::kHollow);
            }

         }

         break;

      case kButton1Motion:
         if (fSelected) {
            if (fSelected->InheritsFrom("TH2")) {
               gVirtualX->DrawBox(XtoAbsPixel(xmin), YtoAbsPixel(ymin), oldx, oldy, TVirtualX::kHollow);
               oldx = GetEventX();
               oldy = GetEventY();
               gVirtualX->DrawBox(XtoAbsPixel(xmin), YtoAbsPixel(ymin), oldx, oldy, TVirtualX::kHollow);
               moved = true;
            }
         }
      case kButton1ShiftMotion: //8 == kButton1Motion + shift modifier
         if (fSelected) {
            gPad = fSelectedPad;

            if (sendOrder) fSelected->ExecuteEvent(event, px, py);
            gVirtualX->Update();

            if (!fSelected->InheritsFrom(TAxis::Class())) {
               Bool_t resize = kFALSE;
               if (fSelected->InheritsFrom(TBox::Class()))
                  resize = ((TBox*)fSelected)->IsBeingResized();
               if (fSelected->InheritsFrom(TVirtualPad::Class()))
                  resize = ((TVirtualPad*)fSelected)->IsBeingResized();

               if ((!resize && TestBit(kMoveOpaque)) || (resize && TestBit(kResizeOpaque))) {
                  gPad = fPadSave;
                  Update();
                  FeedbackMode(kTRUE);
               }
            }

            RunAutoExec();
         }

         break;

      case kButton1Up:

         if (fSelected) {
            gPad = fSelectedPad;

            if (sendOrder) fSelected->ExecuteEvent(event, px, py);

            RunAutoExec();

            if (fPadSave)
               gPad = fPadSave;
            else {
               gPad     = this;
               fPadSave = this;
            }
            if (fSelected->InheritsFrom("TH2") && moved && !fSelected->InheritsFrom("TH3")) {
               xmax = AbsPixeltoX(GetEventX());
               ymax = AbsPixeltoY(GetEventY());
               Double_t toto = 0;
               if (xmax < xmin) {
                  toto = xmax;
                  xmax = xmin;
                  xmin = toto;
               }
               if (ymax < ymin) {
                  toto = ymax;
                  ymax = ymin;
                  ymin = toto;
               }
               ZoomSelected((TH2*)FindHisto());
//                ZoomSelected((TH2*)fSelected);
               moved = false;
            }
            Update();    // before calling update make sure gPad is reset
         }
         break;

      //*-*----------------------------------------------------------------------

      case kButton2Down:
         // find pad in which input occured
         pad = Pick(px, py, prevSelObj);
         if (!pad) return;

         gPad = pad;   // don't use cd() because we won't draw in pad
         // we will only use its coordinate system

         FeedbackMode(kTRUE);

         if (!fSelected->InheritsFrom("TH1")) fSelected->Pop();             // pop object to foreground
         pad->cd();                                 // and make its pad the current pad

         if (fSelected->InheritsFrom("TH2") && !fSelected->InheritsFrom("TH3")) {
            // implement pan & scan
            X0 = px;
            Y0 = py;  // u clikd here
            theXaxis = ((TH2*)FindHisto())->GetXaxis();
            theYaxis = ((TH2*)FindHisto())->GetYaxis();
            NXbins = theXaxis->GetNbins();  // maximum bin number in X
            NYbins = theYaxis->GetNbins();  // maximum bin number in Y
            Xf1 = Xfirst0 = theXaxis->GetFirst(); // initial displayed bin range in X
            Xl1 = Xlast0 = theXaxis->GetLast();
            Yf1 = Yfirst0 = theYaxis->GetFirst(); // initial displayed bin range in Y
            Yl1 = Ylast0 = theYaxis->GetLast();
            // size of axes in pixels
            Int_t pixelWidthX = gPad->XtoAbsPixel(gPad->GetUxmax()) - gPad->XtoAbsPixel(gPad->GetUxmin());
            Int_t pixelWidthY = gPad->YtoAbsPixel(gPad->GetUymax()) - gPad->YtoAbsPixel(gPad->GetUymin());
            // sizes of bins in pixels
            NdisXbins = Xlast0 - Xfirst0 + 1;
            NdisYbins = Ylast0 - Yfirst0 + 1;
            XbinPixel = pixelWidthX / (1.0 * NdisXbins);
            YbinPixel = pixelWidthY / (1.0 * NdisYbins);
         }




         if (gDebug)
            printf("Current Pad: %s / %s\n", pad->GetName(), pad->GetTitle());

         // loop over all canvases to make sure that only one pad is highlighted
         {
            TIter next(gROOT->GetListOfCanvases());
            TCanvas* tc;
            while ((tc = (TCanvas*)next()))
               tc->Update();
         }

         /*if (pad->GetGLDevice() != -1 && fSelected)
          fSelected->ExecuteEvent(event, px, py);*/

         break;   // don't want fPadSave->cd() to be executed at the end

      case kButton2Motion:
         //was empty!
         if (fSelected && fSelected->InheritsFrom("TH2") && !fSelected->InheritsFrom("TH3")) {
            // implement pan & scan
            Int_t dX = px - X0; // how far have i moved ?
            Int_t dY = py - Y0;
            Int_t dXbins = dX / XbinPixel;
            Int_t dYbins = dY / YbinPixel;
            Bool_t changed = kFALSE;
            Int_t newXfirst = Xfirst0 - dXbins;
            Int_t newXlast;
            if (newXfirst < 1) {
               newXfirst = 1;
               newXlast = NdisXbins;
            } else {
               newXlast = Xlast0 - dXbins;
               if (newXlast > NXbins) {
                  newXlast = NXbins;
                  newXfirst = newXlast - NdisXbins + 1;
               }
            }
            if (newXfirst != Xf1) {
               Xf1 = newXfirst;
               Xl1 = newXlast;
               theXaxis->SetRange(Xf1, Xl1);
               changed = kTRUE;
            }
            Int_t newYfirst = Yfirst0 - dYbins;
            Int_t newYlast;
            if (newYfirst < 1) {
               newYfirst = 1;
               newYlast = NdisYbins;
            } else {
               newYlast = Ylast0 - dYbins;
               if (newYlast > NYbins) {
                  newYlast = NYbins;
                  newYfirst = newYlast - NdisYbins + 1;
               }
            }
            if (newYfirst != Yf1) {
               Yf1 = newYfirst;
               Yl1 = newYlast;
               theYaxis->SetRange(Yf1, Yl1);
               changed = kTRUE;
            }
            if (changed) {
               Modified();
               Update();
            }
         }


      case kButton2Up:
         if (fSelected) {
            gPad = fSelectedPad;

            if (sendOrder) fSelected->ExecuteEvent(event, px, py);
            RunAutoExec();
         }
         break;

      case kButton2Double:
         break;

      //*-*----------------------------------------------------------------------

      case kButton3Down:
         // popup context menu
         pad = Pick(px, py, prevSelObj);
         if (!pad) return;

         if (!fDoubleBuffer) FeedbackMode(kFALSE);

         if (fContextMenu && !fSelected->TestBit(kNoContextMenu) && !pad->TestBit(kNoContextMenu) && !TestBit(kNoContextMenu)) {
            if (sendOrder) fContextMenu->Popup(px, py, fSelected, this, pad);
            else fSelected->ExecuteEvent(event, px, py);
         }

         break;

      case kButton3Motion:
         break;

      case kButton3Up:
         if (!fDoubleBuffer) FeedbackMode(kTRUE);
         break;

      case kButton3Double:
         break;

      case kKeyDown:
         //       Info("HandleInput","Key down: %d %d",px,py);
         break;

      case kKeyUp:
         //       Info("HandleInput","Key up: %d %d",px,py);
         break;

      case kKeyPress:
         if (!fSelectedPad || !fSelected) return;
         gPad = fSelectedPad;   // don't use cd() because we won't draw in pad
         // we will only use its coordinate system
         fSelected->ExecuteEvent(event, px, py);

         HandleKey(px, py);
         RunAutoExec();

         break;
      case kButton1Shift:
         // Try to select
         pad = Pick(px, py, prevSelObj);

         if (!pad) return;

         EnterLeave(prevSelPad, prevSelObj);

         gPad = pad;   // don't use cd() we will use the current
         // canvas via the GetCanvas member and not via
         // gPad->GetCanvas
         fSelected->ExecuteEvent(event, px, py);
         RunAutoExec();

         break;
      case kWheelUp:
      case kWheelDown:
         pad = Pick(px, py, prevSelObj);
         if (!pad) return;

         sign = (event == kWheelUp ? 1 : -1);

         gPad = pad;
         if (fSelected->InheritsFrom("TAxis")) fSelected->ExecuteEvent(event, px, py);
         else if (fSelected->InheritsFrom("TH2")) DynamicZoom(sign, px, py);

         RunAutoExec();

         break;
      default:
         break;
   }

   if (fPadSave && event != kButton2Down)
      fPadSave->cd();

   if (event != kMouseLeave) { // signal was already emitted for this event
      ProcessedEvent(event, px, py, fSelected);  // emit signal
      DrawEventStatus(event, px, py, fSelected);
   }
}
Beispiel #21
0
void RebinProfile(){

	f = new TFile("../../../rootfiles/MC/EPOS_PbPb_Ntrk_0.root");

	TH2D* h2;
	h2 = (TH2D*)f->Get("demo/scatterHist_effcorr");



	TCanvas* C = new TCanvas("fitscatterplot","EPOS Hydjet Scatterplot",1800,1200);

	C->Divide(3,2);
	C->cd(1);

	double newbins[8] = {-0.3,-0.075,-0.045,-0.015,0.015,0.045,0.075,0.3};
	//double newbins[6] = {-0.3,-0.045,-0.015,0.015,0.045,0.3};
	TH2D* hnew = new TH2D("rebin","rebin",7,newbins,1000,-0.3,0.3); 

	TAxis *xaxis = h2->GetXaxis();
	TAxis *yaxis = h2->GetYaxis();
	for (int k=1; k<=yaxis->GetNbins();k++) {
		for (int l=1; l<=xaxis->GetNbins();l++) {
			hnew->Fill(xaxis->GetBinCenter(l),yaxis->GetBinCenter(k),h2->GetBinContent(l,k));
		}
	}

	TProfile *prof = hnew->ProfileX();

	TF1* fit1 = new TF1("Linear fitting case 1", "[0]+x*[1]", -0.2, 0.2);
	fit1->SetLineColor(kBlue);
	fit1->SetLineStyle(1);
	fit1->SetLineWidth(3);
	prof->Fit(fit1,"RN0");

	TLatex* text2 = makeLatex(Form("slope : %.3f #pm %.3f",fit1->GetParameter(1),fit1->GetParError(1)),0.55,0.25) ;
	prof->Draw();

	text2->Draw("same");
	fit1->Draw("same");


	


/*
	for (Int_t i=0;i<2;i++) {
		for (Int_t j=0;j<3;j++) {


			h = (TH2D*)f->Get("demo/scatterHist_noeffcorr");
			h -> new TH2D(" ");


			corrTable[oc]->SetBinContent(eta+1, pt+1, c);

			

			double c1 = testload.getWeight(ptbins[pt], etabins[eta], ocbin[oc], "eff");
			double c2 = testload.getWeight(ptbins[pt], etabins[eta], ocbin[oc], "fak");
			double c = c1/(1-c2);

			if( oc == 0 && eta == 15 && pt == 20 ) cout << "1: " << c << endl;
			if( oc == 4 && eta == 15 && pt == 20 ) cout << "4: " << c << endl;
				//cout << "corr factor: " << c << endl; 
			corrTable[oc]->SetBinContent(eta+1, pt+1, c);


			c = c1/(1-c2);
			c2 = c3/(1-c1);
			c4 = c2/(1-c3);
			c5 = c6/(1-c7);

*/
		}
TGraphAsymmErrors* getEfficiency(const TH1* histogram_numerator, const TH1* histogram_denominator)
{
  Int_t error = 0;
  if ( !(histogram_numerator->GetNbinsX()           == histogram_denominator->GetNbinsX())           ) error = 1;
  if ( !(histogram_numerator->GetXaxis()->GetXmin() == histogram_denominator->GetXaxis()->GetXmin()) ) error = 1;
  if ( !(histogram_numerator->GetXaxis()->GetXmax() == histogram_denominator->GetXaxis()->GetXmax()) ) error = 1;
  
  if ( error ){
    std::cerr << "Error in <getEfficiency>: Dimensionality of histograms does not match !!" << std::endl;
    return 0;
  }
  
  TAxis* xAxis = histogram_numerator->GetXaxis();

  Int_t nBins = xAxis->GetNbins();
  TArrayF x(nBins);
  TArrayF dxUp(nBins);
  TArrayF dxDown(nBins);
  TArrayF y(nBins);
  TArrayF dyUp(nBins);
  TArrayF dyDown(nBins);

  for ( Int_t ibin = 1; ibin <= nBins; ibin++ ){
    Int_t nObs = TMath::Nint(histogram_denominator->GetBinContent(ibin));
    Int_t rObs = TMath::Nint(histogram_numerator->GetBinContent(ibin));

    Float_t xCenter = histogram_denominator->GetBinCenter(ibin);
    Float_t xWidth  = histogram_denominator->GetBinWidth(ibin);

    x[ibin - 1]      = xCenter;
    dxUp[ibin - 1]   = 0.5*xWidth;
    dxDown[ibin - 1] = 0.5*xWidth;
    
    if ( nObs > 0 ){
      Float_t rMin = 0.;
      Float_t rMax = 0.;
      
      getBinomialBounds(nObs, rObs, rMin, rMax);

      y[ibin - 1]      = rObs/((Float_t)nObs);
      dyUp[ibin - 1]   = (rMax - rObs)/((Float_t)nObs);
      dyDown[ibin - 1] = (rObs - rMin)/((Float_t)nObs);
    } else{
      y[ibin - 1]      = 0.;
      dyUp[ibin - 1]   = 0.;
      dyDown[ibin - 1] = 0.;
    }
  }
  
  TString name  = TString(histogram_numerator->GetName()).Append("Graph");
  TString title = histogram_numerator->GetTitle();

  TGraphAsymmErrors* graph = 
    new TGraphAsymmErrors(nBins, x.GetArray(), y.GetArray(), 
			  dxDown.GetArray(), dxUp.GetArray(), dyDown.GetArray(), dyUp.GetArray());

  graph->SetName(name);
  graph->SetTitle(title);

  return graph;
}
//void pi0_mfitpeak(char *FileName, char *HistName, Int_t etapi0flag) 
void pi0_mfitpeak(TH1F *mh1, Int_t etapi0flag, float xmin, float xmax, int npol,float res[],int posFlag, const char *dirName, const char *histName, float text_x, float text_y, const char *texName) 
  
{
  TGaxis::SetMaxDigits(3);


  // TVirtualFitter::SetDefaultFitter("Minuit");
  


  // This script attempts to fit any pi0 peak so that the freaking fit function would converge
  // currently background is fitted to a pol4 function and the peak by a gaussian;
  // results are not very nice
  // usage  .x pi0_mfitpeak.C++ ("pi0calib.root","minv_spb")
  // or eg.  .x pi0_mfitpeak.C ("../pi0anal/pi0ana_punorm.root","minv_spb",0)

  gROOT->Reset();
  //  gStyle->SetOptFit();
  //  gStyle->SetOptFit(0);
  //  gStyle->SetOptStat(0);
  //  gStyle->SetOptTitle(0);
Bool_t NOTE=1;
  if(NOTE) gStyle->SetCanvasBorderMode(0);

  gStyle->SetPadTopMargin(0.08);
  gStyle->SetPadBottomMargin(0.12);
  gStyle->SetPadLeftMargin(0.15);
  gStyle->SetPadRightMargin(0.08);

  mh1->GetXaxis()->SetRangeUser(xmin,xmax);
  
  Int_t highx=500;
  TCanvas *c2 = new TCanvas("c2","",200,10,highx,500);


    // cout<<FileName<<" "<<HistName<<endl;

  //     TFile f(FileName);
  //   TH1F *mh1 = (TH1F*) f.Get(HistName);
      mh1->SetMarkerStyle(20);
      mh1->SetMarkerSize(1.);
      mh1->SetStats(0); // 1/0 to set the stat box

   mh1->GetXaxis()->SetTitle("Invariant Mass of Photon Pairs (GeV/c^{2})");


   float binwidth = mh1->GetBinWidth(1);
   
   char *ytitle = new char[100];

   sprintf(ytitle,"Photon Pairs / %4.3f GeV/c^{2}",binwidth);
   

   mh1->GetYaxis()->SetTitle(ytitle);


   mh1->GetXaxis()->SetTitleSize(0.055);
   mh1->GetYaxis()->SetTitleSize(0.055);
   mh1->GetXaxis()->SetLabelSize(0.045);
   mh1->GetYaxis()->SetLabelSize(0.045);
   mh1->GetXaxis()->SetTitleOffset(0.90);
   mh1->GetXaxis()->CenterTitle();
   mh1->GetYaxis()->SetTitleOffset(1.32);
   

   // First work with the histogram and find the peak and fit ranges
   TAxis *xaxis = mh1->GetXaxis();
   Float_t binsiz= xaxis->GetBinCenter(3) - xaxis->GetBinCenter(2);
   Int_t nbins = xaxis->GetNbins(); 
   Float_t nevtperbin0[10000];
   Float_t errorbin0[10000];
   Float_t nevttot;
   Float_t maxbin=0; Int_t nmaxbin=0, nminbord=0, nmaxbord=nbins;
   
   for (Int_t nn=1; nn <= nbins; nn++)
     {
       nevtperbin0[nn] = mh1->GetBinContent(nn); 
       if(nevtperbin0[nn] > maxbin) { maxbin=nevtperbin0[nn]; nmaxbin=nn; }
       errorbin0[nn] = mh1->GetBinError(nn); 
       nevttot+=nevtperbin0[nn];
       if(nevtperbin0[nn] > 0 && nminbord == 0) nminbord=nn; 
       if(nevtperbin0[nn] == 0 && (nn > nminbord +10) && nmaxbord==0 && nminbord > 0) nmaxbord=nn; 
     }
   cout<<"Minbordl "<<nminbord<<" with events: "<<nevtperbin0[nminbord]<<endl;
   cout<<"Maxbordl "<<nmaxbord<<" with events: "<<nevtperbin0[nmaxbord]<<endl;
   nminbord+=0;
   nmaxbord-=0;
   Int_t nmin0=nminbord;
   while(nevtperbin0[nminbord] < nevtperbin0[nmaxbin]*0.025) nminbord++;
   while(nevtperbin0[nmaxbord] < nevtperbin0[nmaxbin]*0.025) nmaxbord--;
   // the above was just to get the info and low/high bins

   // Set the fit range ! This is for total fit !	 
   Float_t fitl=xmin;
     float fith=xmax;
   //     Float_t fitl=0.07, fith=0.2;// this works better for pileup
   //         Float_t fitl=0.08, fith=0.18;// this works even better for pileup
     //  if(etapi0flag == 1)
     // {
     //  fitl=0.35; fith=0.75;
     //}
     

     //   if(fitl < xaxis->GetBinCenter(nmin0)) fitl = xaxis->GetBinCenter(nmin0);
   //if(fith > xaxis->GetBinCenter(nmaxbord)) fith = xaxis->GetBinCenter(nmaxbord);
 
   


   cout<<" fit range "<<fitl<<" -- "<<fith<<endl;

   cout <<"Bin size "<<binsiz<<endl;
   cout<<"Total events "<<nevttot<<endl;
   cout<<"MaxBin "<<nmaxbin<<" with events: "<<nevtperbin0[nmaxbin]<<endl;
   cout<<"Minbord "<<nminbord<<" with events: "<<nevtperbin0[nminbord]<<endl;
   cout<<"Maxbord "<<nmaxbord<<" with events: "<<nevtperbin0[nmaxbord]<<endl;
      mh1->DrawCopy("sep");

      Float_t lowgauss=0.135-4.*0.010;
      Float_t highgauss=0.135+4.*0.010;
      if(etapi0flag == 1)
	{
	  lowgauss=0.55-5.*0.025;
              highgauss=0.55+5.*0.025;
	}
      Int_t nlowgauss=Int_t((lowgauss-xaxis->GetBinCenter(1))/Float_t(binsiz)+0.5);
      Int_t nhighgauss=Int_t((highgauss-xaxis->GetBinCenter(1))/Float_t(binsiz)+0.5);
      cout <<xaxis->GetBinCenter(nlowgauss)<<" "<<xaxis->GetBinCenter(nhighgauss)<<endl;
   // now make the "background" histogram and fit it with p4
      Float_t lowvalgauss=nevtperbin0[nlowgauss];
      Float_t increm=(nevtperbin0[nhighgauss]-nevtperbin0[nlowgauss])/Float_t(nhighgauss-nlowgauss);
      TH1F *hbkg = (TH1F*)mh1->Clone();
      hbkg->SetName("bkg_clone");
      for (Int_t nn=nlowgauss; nn<=nhighgauss; nn++)
	{
	  hbkg->SetBinContent(nn,Float_t(lowvalgauss+(nn-nlowgauss)*increm));
	  hbkg->SetBinError(nn,sqrt(lowvalgauss+(nn-nlowgauss)*increm));
	}
      hbkg->DrawCopy("samesep");
      //      break;
      // Now define the "gaussian" histogram
      TH1F *hgauss = (TH1F*)mh1->Clone();
      hgauss->SetName("gauss_clone");
      hgauss->Sumw2();
      hgauss->Add(mh1,hbkg,1,-1); // if errors are independent Add needs to be used !
       for (Int_t nn=1; nn <= nbins; nn++)
	 {
	   if(hgauss->GetBinContent(nn) < 0.) hgauss->SetBinContent(nn,0.001*nevtperbin0[nmaxbin]);
	   hgauss->SetBinError(nn,sqrt(hgauss->GetBinContent(nn)));
	 }

   // Declare function with wich to fit
       TF1 *g1 = new TF1("g1","gaus",lowgauss,highgauss);
   hgauss->Fit(g1,"R0");
   hgauss->DrawCopy("sep");
   g1->Draw("same");
   //  break;

   char *polff = new char[20];

   sprintf(polff,"pol%d",npol);
   
   TF1 *p4bkg; 
   if(etapi0flag != 1)
     p4bkg   = new TF1("pm2",polff, xaxis->GetBinCenter(nminbord),xaxis->GetBinCenter(nmaxbord));
   else
     p4bkg   = new TF1("pm2",polff, 0.35,0.75);
   
   

   hbkg->Fit(p4bkg,"R0");
   hbkg->DrawCopy("sep");
   p4bkg->SetLineStyle(kDashed);
   p4bkg->Draw("same");
   // break;
   
   
   Double_t par[20],parf[20],errparf[20];
   g1->GetParameters(&par[0]);
   p4bkg->GetParameters(&par[3]);

   char *totff = new char[20];
   
   sprintf(totff,"gaus(0)+pol%d(3)",npol);
   
   
   TF1 *total = new TF1("total",totff,fitl,fith);
   TF1 *p4bkgfin   = new TF1("pm2",polff,fitl,fith);
   total->SetParameters(par);

   if(etapi0flag==0){
     total->SetParLimits(1,0.10,0.15);
     total->SetParLimits(2,0.135*0.06,0.135*0.3);
     
   }else{
     total->SetParLimits(1,0.35,0.65);
   }
   
   
   //  total->FixParameter(1,1.21340e-01); 
   // total->FixParameter(2,2.69780e-02);
   
   
   

   

   mh1->Fit(total,"R0");
   
   cout<<" yield.. "<< total->GetParameter(0) <<"+/- " << total->GetParError(0)<<endl;
   

     total->GetParameters(parf);


     for( Int_t nn=0; nn < 3+npol+1; nn++) errparf[nn]=total->GetParError(nn);
     g1->SetParameters(&parf[0]);
     p4bkgfin->SetParameters(&parf[3]);
     cout <<" Piz Mass = "<<parf[1]*1000.<<" +- "<<errparf[1]*1000.<<
       " Sigma ="<<parf[2]*1000.<<" +- "<<errparf[2]*1000.<<endl;
      cout << " Sigma Rel. = "<< parf[2]/parf[1]<<" +- "
	   << errparf[2]/parf[1] <<endl;

    Float_t int_min=parf[1]-3.*parf[2];
    Float_t int_max=parf[1]+3.*parf[2];
    Float_t sig_peak=g1->Integral(int_min,int_max)/binsiz;
    Float_t bkgd_peak=p4bkgfin->Integral(int_min,int_max)/binsiz;
    cout<<" In +-3. sigma window: Signal="<<sig_peak<<" Bkgd="<<bkgd_peak<<endl;
    Float_t SB=sig_peak/bkgd_peak; Float_t SBerr=SB*(sqrt(1./sig_peak+1./bkgd_peak));
    cout<<" Signal/Bkgd "<<SB<<" +- "<<SBerr<<endl;   

    int_min=parf[1]-2.*parf[2];
    int_max=parf[1]+2.*parf[2];
    sig_peak=g1->Integral(int_min,int_max)/binsiz;
    bkgd_peak=p4bkgfin->Integral(int_min,int_max)/binsiz;
    cout<<" In +-2.sigma window: Signal="<<sig_peak<<" Bkgd="<<bkgd_peak<<endl;
    SB=sig_peak/bkgd_peak; SBerr=SB*(sqrt(1./sig_peak+1./bkgd_peak));
    cout<<" Signal/Bkgd "<<SB<<" +- "<<SBerr<<endl;   
 			

    float S = sig_peak; 
    float B = bkgd_peak; 
    
    int_min=parf[1]-20.*parf[2];
    int_max=parf[1]+20.*parf[2];
    float S_all = g1->Integral(int_min,int_max)/binsiz;
    
    

    float test_sall =  parf[0] * parf[2] * sqrt(acos(-1)) / binsiz; 
    
    cout<<"signal all: "<< S_all << " "<< test_sall <<endl; 
    
    float Serr_all = errparf[0]/ parf[0] * S_all; 
    


    res[0] = S_all; 
    res[1] = Serr_all; 

    res[2] = parf[1]; 
    res[3] = errparf[1];
    
    res[4] = parf[2]; 
    res[5] = errparf[2];

    res[6] = SB; 
    res[7] = SBerr; 
    


    total->SetLineWidth(3);
    
   total->SetLineColor(kBlue);

   p4bkgfin->SetLineWidth(3);
   
   p4bkgfin->SetLineColor(kRed);
   mh1->DrawCopy("sep");

   //   total->SetRange(0.07,0.185);
   //    p4bkgfin->SetRange(0.07,0.185);
   total->Draw("same");
   p4bkgfin->SetLineStyle(kDashed);
   p4bkgfin->Draw("same");   

   TLatex l;
   
   //   l.SetTextSize(0.06);
   l.SetTextSize(0.05);
   
   
   l.SetTextColor(1);
   l.SetNDC();
   
  
   float sigma = parf[2]/ parf[1]*100; 
   float sigmaerr = errparf[2]/ parf[1]*100; 
   char *sigma_name = new char[50]; 
   if(sigmaerr>0.005)
     sprintf(sigma_name,"#sigma = %3.2f #pm %3.2f %% ",sigma,sigmaerr);
   else sprintf(sigma_name,"#sigma = %3.2f %% ",sigma);
   
   if(posFlag==1){
     l.DrawLatex(0.54,0.75,sigma_name);
   }else if( posFlag==2){
     l.DrawLatex(0.54,0.3,sigma_name);

   }
      
      //  sprintf(sigma_name,"S/B = %3.2f #pm %3.2f ",SB,SBerr);
      //
      sprintf(sigma_name,"S = %2.1f #pm %2.1f",S_all,Serr_all);
	      //
      
      // l.DrawLatex(0.5,0.5,sigma_name);
      
      sprintf(sigma_name,"M = %3.1f #pm %3.1f MeV",parf[1]*1000.,errparf[1]*1000);
      if(posFlag==1){
      l.DrawLatex(0.54,0.82,sigma_name);
      }else if( posFlag==2){
	l.DrawLatex(0.54,0.37,sigma_name);

      }
      ///l.DrawLatex(0.169,470.,"d)");


      c2->Modified();
   c2->Update();
   //   c2->SaveAs("nice_pi0.gif");

   
   
   if( text_x >0 && text_y >0){
    TLatex *   tex = new TLatex(text_x, text_y, texName);
    tex->SetNDC();
    tex->SetTextSize(0.06);
    tex->SetLineWidth(2);
    tex->Draw();
  }
  

   char *filename = new char[1000];

   
   sprintf(filename,"%s/%s.gif",dirName,histName);
   c2->Print(filename);
   sprintf(filename,"%s/%s.C",dirName,histName);
   c2->Print(filename);
   
   // .x pi0_mfitpeak.C ("pi0ana_508030.root","minv_spb",0)
   // .x pi0_mfitpeak.C ("pi0ana_npu.root","minv_bkg",0)  
   // .x pi0_mfitpeak.C ("pi0ana_punormv2.root","minv_spb",0)
}
Beispiel #24
0
//------------------------------------------------------------------------------
//
// drawXS
//
//------------------------------------------------------------------------------
void drawXS(UInt_t theCharge = WInclusive)
{
  gStyle->SetEndErrorSize(5);


  // 7 TeV inclusive
  //----------------------------------------------------------------------------
  xs_value[WInclusive][EEE] = 23.00;
  xs_value[WInclusive][EEM] = 19.67;
  xs_value[WInclusive][MME] = 19.81;
  xs_value[WInclusive][MMM] = 21.02;
  xs_value[WInclusive][all] = 20.76;
  
  xs_stat[WInclusive][EEE] = 3.10;
  xs_stat[WInclusive][EEM] = 2.73;
  xs_stat[WInclusive][MME] = 2.60;
  xs_stat[WInclusive][MMM] = 2.30;
  xs_stat[WInclusive][all] = 1.32;
  
  xs_syst[WInclusive][EEE] = 1.39;
  xs_syst[WInclusive][EEM] = 1.50;
  xs_syst[WInclusive][MME] = 1.55;
  xs_syst[WInclusive][MMM] = 1.47;
  xs_syst[WInclusive][all] = 1.13;
  
  xs_lumi[WInclusive][EEE] = 0.51;
  xs_lumi[WInclusive][EEM] = 0.43;
  xs_lumi[WInclusive][MME] = 0.44;
  xs_lumi[WInclusive][MMM] = 0.46;
  xs_lumi[WInclusive][all] = 0.46;
  
  
  // 7 TeV W+
  //----------------------------------------------------------------------------
  xs_value[WPlus][EEE] = 13.39;
  xs_value[WPlus][EEM] = 13.18;
  xs_value[WPlus][MME] = 14.14;
  xs_value[WPlus][MMM] = 11.43;
  xs_value[WPlus][all] = 12.73;
  
  xs_stat[WPlus][EEE] = 2.39;
  xs_stat[WPlus][EEM] = 2.24;
  xs_stat[WPlus][MME] = 2.19;
  xs_stat[WPlus][MMM] = 1.71;
  xs_stat[WPlus][all] = 1.04;
  
  xs_syst[WPlus][EEE] = 0.75;
  xs_syst[WPlus][EEM] = 0.64;
  xs_syst[WPlus][MME] = 0.74;
  xs_syst[WPlus][MMM] = 0.53;
  xs_syst[WPlus][all] = 0.59;
  
  xs_lumi[WPlus][EEE] = 0.29;
  xs_lumi[WPlus][EEM] = 0.29;
  xs_lumi[WPlus][MME] = 0.31;
  xs_lumi[WPlus][MMM] = 0.25;
  xs_lumi[WPlus][all] = 0.28;
  
  
  // 7 TeV W-
  //----------------------------------------------------------------------------
  xs_value[WMinus][EEE] = 9.49;
  xs_value[WMinus][EEM] = 6.51;
  xs_value[WMinus][MME] = 5.73;
  xs_value[WMinus][MMM] = 9.48;
  xs_value[WMinus][all] = 7.46;
  
  xs_stat[WMinus][EEE] = 1.95;
  xs_stat[WMinus][EEM] = 1.58;
  xs_stat[WMinus][MME] = 1.40;
  xs_stat[WMinus][MMM] = 1.52;
  xs_stat[WMinus][all] = 0.79;
  
  xs_syst[WMinus][EEE] = 0.60;
  xs_syst[WMinus][EEM] = 0.37;
  xs_syst[WMinus][MME] = 0.37;
  xs_syst[WMinus][MMM] = 0.50;
  xs_syst[WMinus][all] = 0.40;
  
  xs_lumi[WMinus][EEE] = 0.21;
  xs_lumi[WMinus][EEM] = 0.14;
  xs_lumi[WMinus][MME] = 0.13;
  xs_lumi[WMinus][MMM] = 0.21;
  xs_lumi[WMinus][all] = 0.16;


  // Do the work
  //----------------------------------------------------------------------------
  TGraphErrors* gStat = new TGraphErrors(nChannel);
  TGraphErrors* gSyst = new TGraphErrors(nChannel);
  TGraphErrors* gLumi = new TGraphErrors(nChannel);

  for (UInt_t i=0; i<nChannel; i++)
    {
      Double_t errorSquared = (xs_stat[theCharge][i] * xs_stat[theCharge][i]);

      gStat->SetPointError(i, sqrt(errorSquared) / xs_nlo[theCharge], 0.0);
      
      errorSquared += (xs_syst[theCharge][i] * xs_syst[theCharge][i]);

      gSyst->SetPointError(i, sqrt(errorSquared) / xs_nlo[theCharge], 0.0);

      errorSquared += (xs_lumi[theCharge][i] * xs_lumi[theCharge][i]);

      gLumi->SetPointError(i, sqrt(errorSquared) / xs_nlo[theCharge], 0.0);

      gStat->SetPoint(i, xs_value[theCharge][i] / xs_nlo[theCharge], nChannel-i-1);
      gSyst->SetPoint(i, xs_value[theCharge][i] / xs_nlo[theCharge], nChannel-i-1);
      gLumi->SetPoint(i, xs_value[theCharge][i] / xs_nlo[theCharge], nChannel-i-1);
    }


  // Cosmetics
  //----------------------------------------------------------------------------
  gStat->SetLineWidth  (2);
  gStat->SetMarkerSize (1.3);
  gStat->SetMarkerStyle(kFullCircle);

  gSyst->SetLineColor  (kRed);
  gSyst->SetLineWidth  (2);
  gSyst->SetMarkerSize (1.3);
  gSyst->SetMarkerStyle(kFullCircle);

  gLumi->SetLineColor  (kBlue);
  gLumi->SetLineWidth  (2);
  gLumi->SetMarkerSize (1.3);
  gLumi->SetMarkerStyle(kFullCircle);


  // Draw
  //----------------------------------------------------------------------------
  TString suffix = "7TeV_" + sCharge[theCharge];

  TCanvas* canvas = new TCanvas("ratioNLO_" + suffix, "ratioNLO_" + suffix);

  canvas->SetLeftMargin(canvas->GetRightMargin());

  Double_t xmin    =  0.0;
  Double_t xmax    =  2.0;
  Double_t ylegend =  1.2;
  Double_t ymin    = -0.6;
  Double_t ymax    = nChannel + ymin + ylegend;
  
  TH2F* h2 = new TH2F("h2_" + suffix, "", 100, xmin, xmax, 100, ymin, ymax);

  h2->Draw();
  
  
  // NLO WZ cross-section
  //----------------------------------------------------------------------------
  TBox* nlo = new TBox(1. - xs_nlo_left [theCharge] / xs_nlo[theCharge], ymin,
		       1. + xs_nlo_right[theCharge] / xs_nlo[theCharge], ymax - ylegend);

  nlo->SetLineColor(0);
  nlo->SetFillColor(kGray);
  nlo->SetFillStyle(1001);

  nlo->Draw("e2,same");

  TLine* line = new TLine(1., ymin, 1., ymax - ylegend);

  line->SetLineColor(kGray+1);
  line->SetLineWidth(2);

  line->Draw("same");


  // Cross sections
  //----------------------------------------------------------------------------
  gLumi->Draw("p,same");
  gSyst->Draw("p,same");
  gStat->Draw("p,same");


  // Labels
  //----------------------------------------------------------------------------
  for (UInt_t i=0; i<nChannel; i++) {

    Double_t x = gStat->GetX()[i];
    Double_t y = gStat->GetY()[i];

    Double_t gStatError = gStat->GetErrorX(i);
    Double_t gSystError = gSyst->GetErrorX(i);
    Double_t gLumiError = gLumi->GetErrorX(i);

    DrawTLatex(42, xmin+0.06, y+0.15, 0.035, 12,
	       Form("%s %.2f #pm %.2f",
		    lChannel[i].Data(), x, gLumiError), 0);

    gLumiError = sqrt(gLumiError*gLumiError - gSystError*gSystError);
    gSystError = sqrt(gSystError*gSystError - gStatError*gStatError);

    DrawTLatex(42, xmin+0.06, y-0.15, 0.025, 12,
	       Form("%.2f #pm %.2f #pm %.2f #pm %.2f",
		    x, gStatError, gSystError, gLumiError), 0);
  }

  DrawTLatex(42, 0.050, 0.975, _bigLabelSize, 13, "CMS Preliminary");

  DrawTLatex(42, 0.940, 0.983, _bigLabelSize, 33, 
	     Form("#sqrt{s} = 7 TeV, L = %.1f fb^{-1}", luminosity/1e3));

  TString swz = "";

  if      (theCharge == WPlus)  swz = "W^{+}Z";
  else if (theCharge == WMinus) swz = "W^{-}Z";
  else                          swz = "W^{#pm}Z";
  
  h2->GetXaxis()->CenterTitle();
  h2->GetXaxis()->SetTitleOffset(1.4);
  h2->GetXaxis()->SetTitle(Form("#sigma_{%s}^{exp} / #sigma_{%s}^{theory}",
				   swz.Data(),
				   swz.Data()));

  h2->GetYaxis()->SetTitle("");


  // Remove y-axis labels
  //----------------------------------------------------------------------------
  TAxis* yaxis = h2->GetYaxis();
  
  for (Int_t j=1; j<yaxis->GetNbins(); j++) yaxis->SetBinLabel(j, "");


  // Additional legend
  //----------------------------------------------------------------------------
  DrawLegend(0.645, 0.840, gStat, " stat.",  "lp");
  DrawLegend(0.645, 0.795, nlo,   " theory", "f");
  DrawLegend(0.800, 0.840, gSyst, " syst.",  "l");
  DrawLegend(0.800, 0.795, gLumi, " lumi.",  "l");


  // Save
  //----------------------------------------------------------------------------
  canvas->Update();
  canvas->GetFrame()->DrawClone();
  canvas->RedrawAxis();

  canvas->SaveAs(Form("pdf/ratioNLO_%s.pdf", suffix.Data()));
  canvas->SaveAs(Form("png/ratioNLO_%s.png", suffix.Data()));
}
Beispiel #25
0
int fitHisto(int siteNum,string dataVer)
{

//===>initialize variable
	bool anaLiHe=true;//He8/Li9 bg
    int ADNumOfSite[3]={0};
    int daqHistNum=5;
    if( dataVer.find("13")!=-1 || dataVer.find("14")!=-1 || dataVer.find("15")!=-1 || dataVer.find("16")!=-1)
    {
        ADNumOfSite[0]=2;
        ADNumOfSite[1]=2;
        ADNumOfSite[2]=4;
        daqHistNum=5;
    } else
    {
        if( dataVer.find("11")!=-1 || dataVer.find("12")!=-1 )
        {
            ADNumOfSite[0]=2;
            ADNumOfSite[1]=1;
            ADNumOfSite[2]=3;
            daqHistNum=4;
        }
    }
	string site;
	if( siteNum==1 )
	{
		site="EH1";
	} else if(siteNum==2)
	{
		site="EH2";
	}else if (siteNum==3)
	{
		site="EH3";
	}else
	{
		site="EH1";
	}

//===>initialize histograms
	//livetime
	string runnum;
	TH1F* h[daqHistNum];//the fifth is for daqtime
	Double_t totalTime[5]={0.};

	//Li9 He8
	double n98total=0.;
	//double in98total=0.;
    double ifitn98total=0.;
    double n98Rate=0.;
    double in98Rate=0.;
    double tlivetime=0.;
	TH1F* showermuonNum[6]; 
	TH1F* time2lastshowermuon[6];
	TH1F* hh[6];

//===>get histograms from .root file for analyse
	string filename;
    filename=site;
    filename+="mergedHist_";
    filename+=dataVer;
    filename+=".root";
    TFile* f=new TFile(filename.c_str());

		//livetime
		for( int i=0 ; i<daqHistNum ; i++ )
		{

			stringstream hname;
			if( i==daqHistNum-1 )
			{
				hname<<"LiveTime/DaqTime";
			} else
			{
				hname<<"LiveTime/AD";
				hname<<i+1;
				hname<<"LiveTime";	
			}
			h[i] = (TH1F*)f->Get(hname.str().c_str());
			if( !(h[i]) )
			{
				cout<<"Can not get Hist : "<<hname.str()<<" from "<<site<<"/"<<runnum<<" ."<<endl;
				//return true;
                continue;
			}
		}

		//Li9 He8
        if(anaLiHe)
		{
            for( int i=0 ; i<6 ; i++ )
            {
                TString hnameLi;
                hnameLi="lidj/showermuonNum";
                hnameLi+=i+1;
                showermuonNum[i]=(TH1F*)f->Get(hnameLi);
                hnameLi="lidj/time2lastshowermuon";
                hnameLi+=i+1;
                hnameLi+="4Li";
                time2lastshowermuon[i]=(TH1F*)f->Get(hnameLi);
            }
		}
	
//===>analyse 
	TAxis *xaxis = h[0]->GetXaxis();
	int binNum = xaxis->GetNbins();
    int BinBound=h[0]->FindBin(1346428800);//2012.9.1 0:0:0
	//livetime
    if( BinBound!=0 )
    {
        if( site=="EH2" )
        {
            for(int j=1  ; j<=BinBound ; j++ )
            {
                h[1]->SetBinContent(j,0);
            }
        }
        if( site=="EH3" )
        {
            for(int j=1  ; j<=BinBound ; j++ )
            {
                h[3]->SetBinContent(j,0);
            }
        }
    }
    double totalTimeSpecical=0.;
    for( int j=BinBound ; j<=binNum ; j++ )
    {
        totalTimeSpecical+=h[4]->GetBinContent(j);
    }

    for( int i=0 ; i<5 ; i++ )
    {
        totalTime[i]=0.;
        for( int j=1 ; j<=binNum ; j++ )
        {
            totalTime[i]+=h[i]->GetBinContent(j);
        }

    }
    double totalDaqtime=0.;
    if( site=="EH2" )
    {
        totalDaqtime=totalTime[4]+totalTimeSpecical;
    }else if( site=="EH3" )
    {
        totalDaqtime=totalTime[4]*3+totalTimeSpecical;
    } else
    {
        totalDaqtime=totalTime[4]*2;
    }

	//Li He
    std::cout<<"begin to analyse Li "<<endl;
	if(anaLiHe)
	{
        int hnum=time2lastshowermuon[0]->FindBin(100);
        //std::cout<<"0.001  : "<<time2lastshowermuon[0]->FindBin(0.001)<<endl;
        //std::cout<<"100  : "<<time2lastshowermuon[0]->FindBin(100)<<endl;
        //std::cout<<"hnum  : "<<hnum<<endl;
        for( int k=0 ; k<6 ; k++ )
        {
            TString hhname="slice";
            hhname+=k+1;
            hh[k]=new TH1F(hhname,"hh",hnum-2,0.001,100);
                for( int i=1 ; i<hnum-2 ; i++ )
                {
                    hh[k]->SetBinContent(i,time2lastshowermuon[k]->GetBinContent(i+1));
                }
                hh[k]->SetOption("E1");
        }
        double showerTh[7] = {0.02, 0.5, 1.5, 2.5, 3.5, 4.5, 5.0};
        TH1F* LiResult[5];
        LiResult[0]= new TH1F("LiResult", "All", 6, showerTh);
        LiResult[1]= new TH1F("LiResult", "AD1", 6, showerTh);
        LiResult[2]= new TH1F("LiResult", "AD2", 6, showerTh);
        LiResult[3]= new TH1F("LiResult", "AD3", 6, showerTh);
        LiResult[4]= new TH1F("LiResult", "AD4", 6, showerTh);
		double NumMuon[6]={0.};
		double RateMuon[6]={0.};
		double NumIbd[6]={0.};
        
		RooRealVar x("x","x",0.001,40., "s");
		RooRealVar tauLi9("tauLi9", "tauLi9", -0.257, "s");
		RooRealVar tauHe8("tauHe8", "tauHe8", -0.172, "s");
		RooRealVar rateMu("rateMu","rate of showermuon",-0.1,-10., 0.,"Hz");
		RooRealVar Li9Frac("Li9Frac","Li9's Frac", 0.0);//R
		RooRealVar N98("N98","total number of Li9 and He8",500.,0.,1.e5);
		//RooRealVar N98("N98","total number of Li9 and He8",3e2, 1e1, 2.e5);
		RooFormulaVar lambdaLi9("lambdaLi9","lambdaLi9","1/@0 + @1",RooArgList(tauLi9, rateMu));
		RooFormulaVar lambdaHe8("lambdaHe8","lambdaHe8","1/@0 + @1",RooArgList(tauHe8, rateMu));
		RooFormulaVar coeLi9("coeLi9","coeLi9","@0 * @1 ",RooArgList(N98,Li9Frac));
		RooFormulaVar coeHe8("coeHe8","coeHe8","@0 * ( 1 - @1 )",RooArgList(N98,Li9Frac));
		RooRealVar NIbd("NIbd","number of background",3e2, 1e1, 2.e6);
		RooExponential expLi9("expLi9", "Li9 distribution", x, lambdaLi9);
		RooExponential expHe8("expHe8", "He8 distribution", x, lambdaHe8);
        double Ibdrate[3]={0.0076,0.0067,0.00082};
        RooRealVar rateIbd("rateIbd","rateIbd",-Ibdrate[siteNum-1],-10,0.,"Hz");
        RooFormulaVar lambdaIbd("lambdaIbd","lambdaIbd","@0 + @1",RooArgList(rateIbd, rateMu));
		RooExponential expIbd("expIbd","Ibd distribution",x,rateMu);
		//RooExponential expIbd("expIbd","Ibd distribution",x,lambdaIbd);
		
		RooFitResult* fitres;
		RooAddPdf* sum;
		RooDataHist* data;
        RooPlot* mesframe[6];
		double n98[41]={0.};
		double in98[41]={0.};
		double nIbd[41]={0.};
		double inIbd[41]={0.};
		double minNLL[41]={0.};
        double rateMuValue[41]={0.};
        double rateMuErr[41]={0.};
		//double minNl[6]={0.};
		int minindex[6]={0};
		double n98fit[6]={0.};
		double in98fit[6]={0.};
        double rateMufit[6]={0.};
		double binwidth=0.;
        TH1F* lh[5][6];
        TString lname[5]={"","AD1","AD2","AD3","AD4"};
        int lcolor[5]={4,3,2,6,5};
        bool draw6slice=false;
        TCanvas* c;
        TString xTitle[6]={"slice 1 : 0.02~0.5GeV","slice 2 : 0.5~1.5GeV","slice 3 : 1.5~2.5GeV","slice 4 : 2.5~3.5GeV","slice 5 : 3.5~4.5GeV","slice 6 : >4.5GeV"};
        if( draw6slice )
        {
	        c = new TCanvas("c","c",2000,800) ; 
	        c->Divide(3,2);
	        gStyle->SetEndErrorSize(5.0);
	        gStyle->SetMarkerSize(0.1);
	        //gStyle->SetHistLineWidth(1);
	        if( 0 )
	        {
	            // it's strange ,if you can't draw following six figs in the big 3*2 pad,you can fist use these code,run once,don't exit the ROOT,then you can draw six figs!!!
			    data = new RooDataHist("data", "data", x, time2lastshowermuon[0]);
				sum  = new RooAddPdf("sum","sum",RooArgList(expLi9, expHe8, expIbd),RooArgList(coeLi9, coeHe8, NIbd));
		        RooPlot* mesframe = x.frame() ;
		        data->plotOn(mesframe) ;
		        c->cd(1);
		        mesframe->Draw();
	            return true;
	        }
        }
        for( int ihist=0 ; ihist<1 ; ihist++ )
        {
			double minNl[6]={0.};
			for( int j=0 ; j<6 ; j++ )
			{
	            std::cout<<"now is  "<< j+1<<endl;
	            NumIbd[j]=hh[j]->Integral(1,hh[j]->FindBin(40));
	            hh[j]->Rebin(100);
				data = new RooDataHist("data", "data", x, hh[j]);
				sum  = new RooAddPdf("sum","sum",RooArgList(expLi9, expHe8, expIbd),RooArgList(coeLi9, coeHe8, NIbd));
				for( int i=0 ; i<41 ; i++ )
				{
					Li9Frac.setVal(i*0.025);
					fitres = sum->fitTo((*data),Save(),PrintLevel(-1),Extended(kTRUE));
	                //fitres->Print();
					n98[i]=N98.getVal(0);
					in98[i]=N98.getError();
	                nIbd[i]=NIbd.getVal(0);
	                inIbd[i]=NIbd.getError();
	                rateMuValue[i]=rateMu.getVal(0);
	                rateMuErr[i]=rateMu.getError();
					minNLL[i] = fitres->minNll();
					if( minNLL[i]<minNl[j] )
					{
						minNl[j]=minNLL[i];
						minindex[j]=i;
					}
				}
				n98fit[j]=n98[minindex[j]];
				in98fit[j]=in98[minindex[j]];
	            rateMufit[j]=rateMuValue[minindex[j]];
	            if( draw6slice )
	            {
		            //for drawing fit figure
					Li9Frac.setVal(minindex[j]*0.025);
					fitres = sum->fitTo((*data),Save(),PrintLevel(-1),Extended(kTRUE));
		            //fitres->Print();
		            mesframe[j] = x.frame() ;
		            data->plotOn(mesframe[j]) ;
		            sum->plotOn(mesframe[j]);
		            sum->plotOn(mesframe[j],Components(expIbd),LineStyle(kDashed),LineColor(kGreen)) ;
		            sum->plotOn(mesframe[j],Components(RooArgSet(expLi9,expHe8)),LineStyle(kDashed),LineColor(kRed)) ;
		            xTitle[j]+="        time since last muon (s)";
		            mesframe[j]->GetXaxis()->SetTitle(xTitle[j]);
		            mesframe[j]->GetYaxis()->SetTitle("Entries");
		            c->cd(j+1);
		            mesframe[j]->Draw();
		            //gPad->SetLogy();
	            }
			}
	        
			n98total=(n98fit[0]+n98fit[1]+n98fit[2]+(n98fit[3]+n98fit[4]+n98fit[5])*exp(-1/0.257))/0.678;
			ifitn98total=sqrt(in98fit[0]*in98fit[0]+in98fit[1]*in98fit[1]+in98fit[2]*in98fit[2]+((in98fit[3]+in98fit[4]+in98fit[5])*exp(-1/0.257)*(in98fit[3]+in98fit[4]+in98fit[5])*exp(-1/0.257)))/0.678;
	        if( ihist==0 )
	        {
	            for( int i=0 ; i<ADNumOfSite[siteNum-1] ; i++ )
	            {
	                tlivetime+=totalTime[i];
	            }
	        }else
	        {
	            tlivetime=totalTime[ihist-1];
	        }
	        n98Rate=n98total/(tlivetime/(24*3600));
	        in98Rate=sqrt((ifitn98total/(tlivetime/(24*3600)))*(ifitn98total/(tlivetime/(24*3600)))+(n98total/(tlivetime/(24*3600))/2)*(n98total/(tlivetime/(24*3600))/2));
	        for( int j=0 ; j<6 ; j++ )
	        {
	            LiResult[ihist]->SetBinContent(j+1,n98fit[j]);
	            LiResult[ihist]->SetBinError(j+1,in98fit[j]);
			    for( int jbin=0 ; jbin<binNum ; jbin++ )
	            {
	                NumMuon[j]+=showermuonNum[j]->GetBinContent(jbin);
	            }
				RateMuon[j]=NumMuon[j]/totalDaqtime;
	            //std::cout<<"RateMuon[j]  : "<<RateMuon[j]<<endl;
	            //std::cout<<"RateMuon0[j]  : "<<RateMuon0[j]<<endl;
	            std::cout<<"  R "<<minindex[j]*0.025<<"   n98["<<minindex[j]<<"] "<<n98fit[j]<<"   in98["<<minindex[j]<<"] "<< in98fit[j]<<"   fitRateMu["<<minindex[j]<<"] "<<rateMufit[j]<<"  realRateMu "<<RateMuon[j]<<"   NumTol "<<NumIbd[j]<<endl;
	        }
	        std::cout<<"n98Num   : "<<n98total<<" +- "<<ifitn98total<<" Rate  : "<<n98Rate<<" +- "<< in98Rate<<endl;
        }
        
            /*
        //TCanvas* c4 = new TCanvas("c4", "c4", 600, 400);
        //gStyle->SetEndErrorSize(0.0);
        LiResult[0]->SetMarkerStyle(20);
		LiResult[0]->SetMarkerColor(lcolor[0]);
		LiResult[0]->SetLineColor(lcolor[0]);
		LiResult[0]->SetMarkerSize(1.0);
		LiResult[0]->SetMinimum(0);
		LiResult[0]->SetMaximum(LiResult[0]->GetMaximum()*1.5);
		LiResult[0]->GetXaxis()->SetTitle("Muon visible energy (GeV)");
		LiResult[0]->GetYaxis()->SetTitle("Fitted ^{9}Li events");
		LiResult[0]->SetTitle("");
        LiResult[0]->SetStats(kFALSE);
		LiResult[0]->Draw("EP");
        TLegend *legend=new TLegend(.6,.65,.79,.89);
        TString legendLabel=dataVer+" "+site+" "+"All";
        legend->AddEntry(LiResult[0],legendLabel,"lp");

        for( int ihist=1 ; ihist<ADNumOfSite[siteNum-1]+1; ihist++ )
        {
            LiResult[ihist]->SetMarkerStyle(20);
		    LiResult[ihist]->SetMarkerColor(lcolor[ihist]);
		    LiResult[ihist]->SetLineColor(lcolor[ihist]);
		    LiResult[ihist]->SetMarkerSize(1.0);
            LiResult[ihist]->SetStats(kFALSE);
		    LiResult[ihist]->Draw("EPsame");
            legend->AddEntry(LiResult[ihist],lname[ihist],"lp");
        }
        legend->SetFillColor(0);
        legend->Draw();
        */
	}	
	
    //f->Close();
//===>print result
	std::cout<<""<<endl;
	std::cout<<site <<"'s infomation : "<<endl;
	std::cout<<""<<endl;
	for( int i=0 ; i<ADNumOfSite[siteNum-1] ; i++ )
	{
		std::cout<<"Total AD"<<i+1<<"LiveTime                         : "<<totalTime[i]/(24*3600)<<endl;
	}
	std::cout<<"Total DaqTime : "<<totalTime[daqHistNum-1]/(24*3600)<<" day" <<endl;
	std::cout<<""<<endl;

	if(anaLiHe)
	{
	    std::cout<<" "<<endl;
        /*
	    std::cout<<"Li9/He8 "<<endl;
	    std::cout<<"n98total  : "<<n98total <<" +- "<<in98total <<" Rate:"<<n98total/totalTime[0]*24*3600 <<" +- "<<in98total/totalTime[0]*24*3600 <<endl;
	    std::cout<<"n98total0(without rpc)  : "<<n98total0 <<" +- "<<in98total0 <<" Rate:"<<n98total0/totalTime0[0]*24*3600 <<" +- "<<in98total0/totalTime0[0]*24*3600 <<endl;
        */
	}

//===>write into .root file
	string rootname=site;
	rootname+="FitResult_"+dataVer+".root";
	TFile* file = new TFile(rootname.c_str(),"RECREATE");
    file->cd();
    for( int i=0 ; i<daqHistNum ; i++ )
    {
        h[i]->Write();
    }
    
    if( anaLiHe )
    {
		//for( int i=0 ; i<ADNumOfSite[siteNum-1] ; i++ )
		for( int i=0 ; i<6 ; i++ )
		{
			hh[i]->Write();
		}
    }
	file->Close();
	f->Close();
	return 0;
}
Double_t effSigma(TH1 *hist )
{

  TAxis *xaxis = hist->GetXaxis();
  Int_t nb = xaxis->GetNbins();
  if(nb < 10) {
    cout << "effsigma: Not a valid histo. nbins = " << nb << endl;
    return 0.;
  }
  
  Double_t bwid = xaxis->GetBinWidth(1);
  if(bwid == 0) {
    cout << "effsigma: Not a valid histo. bwid = " << bwid << endl;
    return 0.;
  }
  Double_t xmin = xaxis->GetXmin();
  Double_t ave = hist->GetMean();
  Double_t rms = hist->GetRMS();

  Double_t total=0.;
  for(Int_t i=0; i<nb+2; i++) {
    total+=hist->GetBinContent(i);
  }
  if(total < 100.) {
    cout << "effsigma: Too few entries " << total << endl;
    return 0.;
  }
  Int_t ierr=0;
  Int_t ismin=999;
  
  Double_t rlim=0.683*total;
  Int_t nrms=rms/(bwid);    // Set scan size to +/- rms
  if(nrms > nb/10) nrms=nb/10; // Could be tuned...

  Double_t widmin=9999999.;
  for(Int_t iscan=-nrms;iscan<nrms+1;iscan++) { // Scan window centre
    Int_t ibm=(ave-xmin)/bwid+1+iscan;
    Double_t x=(ibm-0.5)*bwid+xmin;
    Double_t xj=x;
    Double_t xk=x;
    Int_t jbm=ibm;
    Int_t kbm=ibm;
    Double_t bin=hist->GetBinContent(ibm);
    total=bin;
    for(Int_t j=1;j<nb;j++){
      if(jbm < nb) {
        jbm++;
        xj+=bwid;
        bin=hist->GetBinContent(jbm);
        total+=bin;
        if(total > rlim) break;
      }
      else ierr=1;
      if(kbm > 0) {
        kbm--;
        xk-=bwid;
        bin=hist->GetBinContent(kbm);
        total+=bin;
        if(total > rlim) break;
      }
      else ierr=1;
    }
    Double_t dxf=(total-rlim)*bwid/bin;
    Double_t wid=(xj-xk+bwid-dxf)*0.5;
    if(wid < widmin) {
      widmin=wid;
      ismin=iscan;
    }   
  }
  if(ismin == nrms || ismin == -nrms) ierr=3;
  if(ierr != 0) cout << "effsigma: Error of type " << ierr << endl;
  
  return widmin;
  
}
//from Andrius
//******************************************//
// author: Chris Seez
//
// This function evaluates the effective
// sigma of a histogram.
//
//******************************************//
Double_t StudySel::calc_effSigma(TH1 * hist)
{
  using std::cout;
  using std::endl;
  TAxis *xaxis = hist->GetXaxis();
  Int_t nb = xaxis->GetNbins();
  if(nb < 10) {
    cout << "effsigma: Not a valid histo. nbins = " << nb << endl;
    return 0.;
  }
  Double_t bwid = hist->GetBinWidth(1);
  if(bwid == 0) {
    cout << "effsigma: Not a valid histo. bwid = " << bwid << endl;
    return 0.;
  }
  //Double_t xmax = xaxis->GetXmax(); // not used
  Double_t xmin = xaxis->GetXmin();
  Double_t ave = hist->GetMean();
  Double_t rms = hist->GetRMS();
  Double_t total=0.;
  for(Int_t i=0; i<nb+2; i++) {
    total+=hist->GetBinContent(i);
  }
  if(total < 10.) {
    cout << "effsigma: Too few entries " << total << endl;
    return 0.;
  }
  Int_t ierr=0;
  Int_t ismin=999;
  Double_t rlim=0.683*total;
  Int_t nrms= Int_t(2.0*rms/(bwid)); // Set scan size to +/- rms
  //if(nrms > nb/10) nrms=nb/10; // Could be tuned...
  Double_t widmin=9999999.;
  for(Int_t iscan=-nrms;iscan<nrms+1;iscan++) { // Scan window centre
    Int_t ibm=Int_t((ave-xmin)/bwid+1+iscan);
    Double_t x=(ibm-0.5)*bwid+xmin;
    Double_t xj=x;
    Double_t xk=x;
    Int_t jbm=ibm;
    Int_t kbm=ibm;
    // ibm -- curent bin value
    // x, xj, xk -- value of the x-axis
    // jbm, kbm -- bin values
    Double_t bin=hist->GetBinContent(ibm);
    total=bin;
    for(Int_t j=1;j<nb;j++){
      if(jbm < nb) {
	jbm++;
	xj+=bwid;
	bin=hist->GetBinContent(jbm);
	total+=bin;
	if(total > rlim) break;
      }
      else ierr=1;
      if(kbm > 0) {
	kbm--;
	xk-=bwid;
	bin=hist->GetBinContent(kbm);
	total+=bin;
	if(total > rlim) break;
      }
      else ierr=1;
    }
    Double_t dxf=(total-rlim)*bwid/bin;
    Double_t wid=(xj-xk+bwid-dxf)*0.5;
    if(wid < widmin) {
      widmin=wid;
      ismin=iscan;
    }
  }
  if(ismin == nrms || ismin == -nrms) {
    cout << endl << endl << "CRAP!!!" << endl;
    cout << ismin << '\t' << nrms << endl;
    ierr=3;
  }
  if(ierr != 0 && ierr != 1) cout << "effsigma: Error of type " << ierr <<endl;
  return widmin;
}
Beispiel #28
0
TCanvas* plotting36GS( bool logScale=false ) 
{

  std::cout << "plotting mu + standalone " << std::endl;
  TGaxis::SetMaxDigits(3);

  // channels, ordered as in the legend
  vector<TString> channels;  
  vector<TString> hnames; 
  vector<TString> type;

  map<TString,int> fillColor_;
  map<TString,int> lineColor_;
  int lineWidth1(2);
  int lineWidth2(1);

  bool salamanderStyle=true;
  if( salamanderStyle )
    {
      fillColor_["Signal"] = kOrange-2;
      lineColor_["Signal"] = kOrange+3;
      
      fillColor_["EWK"] = kOrange+7;
      lineColor_["EWK"] = kOrange+3;
      
      fillColor_["QCD"] = kViolet-5;
      lineColor_["QCD"] = kViolet+3;
      
      fillColor_["ttbar"] = kRed+2;
      lineColor_["ttbar"] = kRed+4;
      
      fillColor_["gamma+jet"] = kMagenta+4;
      lineColor_["gamma+jet"] = kViolet+3;
    }
  else
    {
      lineWidth1 = 2;
      lineWidth2 = 2;

      fillColor_["Signal"] = kPink+6;
      lineColor_["Signal"] = kMagenta+3;
      
      fillColor_["EWK"] = kAzure+8;
      lineColor_["EWK"] = kAzure+4;
      
      fillColor_["QCD"] = kYellow-7;
      lineColor_["QCD"] = kYellow+4;
      
      fillColor_["ttbar"] = kGreen;
      lineColor_["ttbar"] = kGreen+2;
      
      fillColor_["gamma+jet"] = kOrange;
      lineColor_["gamma+jet"] = kOrange+2;
    }

  // root file, where the data is
  TString fname("root/");

  // histogram limits, in linear and logarithmic
  int nbin_(100);
  float xmin_(0.), xmax_(0.); 
  float ymin_(0.), ymax_(0.); 
  float yminl_(0.), ymaxl_(0.); 

  // titles and axis, marker size
  TString xtitle;
  TString ytitle;
  int ndivx(510);
  int ndivy(510);
  float markerSize(0.);
  float titleOffset(1.);

  float r0_ = 1.;
  float dr_ = 0.3;
  if( use_chi )
    {
      r0_ = 0.;
      dr_ = 7.5;
      //dr_ = 3.0;
    }

  // canvas name
  TString cname("");
  TString ctitle;

  // legend position and scale;
  float xl_  = 0.;
  float yl_  = 0.; 	   
  float scalel_ = 0.0;

  {
    if( logScale )
      //      fname += "Zmumu_40-200_36pb";
      fname += "Zmusta_36pb";
    else
      fname += "Zmusta_36pb";

    if( logScale )
      {
	lineWidth1 = 1;
	lineWidth2 = 1;
      }
    
    channels.push_back("Zmumu"); 
    hnames.push_back("   Z #rightarrow #mu^{+}#mu^{-}"); 
    type.push_back("Signal"); 
    
    bool revert(false);
    if( logScale )
      {
 	if( revert )
 	  {
 	    channels.push_back("EWK");          
 	    hnames.push_back("   EWK");                
	    type.push_back("EWK"); 
	    
 	    channels.push_back("tt");              
 	    hnames.push_back("   t#bar{t}");         
	    type.push_back("ttbar"); 

	     	    channels.push_back("QCD");              
	     	    hnames.push_back("   QCD");              
	    	    type.push_back("QCD"); 
 	  }
 	else
 	  {
 	    channels.push_back("EWK");          
 	    hnames.push_back("   EWK");                
	    type.push_back("EWK"); 
	    
 	    channels.push_back("tt");              
 	    hnames.push_back("   t#bar{t}");         
	    type.push_back("ttbar"); 
	    
	    channels.push_back("QCD");              
	     	    hnames.push_back("   QCD");              
	    	    type.push_back("QCD"); 	  
	      
 	  }
       }
    
    if( !logScale )
      {
	// lin scale
	xmin_ = 60;
	xmax_ = 120;
	ymin_ = 0.01;
	ymax_ = 2100;

  }
    else
      {	
	// log scale
	xmin_ = 40;
	xmax_ = 200;
	yminl_ = 0.08;
	ymaxl_ = 3000;

      }

    xtitle = "M(#mu^{+}#mu^{-})    [GeV]";
    ytitle = "number of events /";    


    ndivx = 504;
    if( logScale )
      {
	ytitle += "5 GeV";
	ndivy = 510;
      }
    else
      {
	ytitle += " GeV";
	ndivy = 506;
      }
    
    if( logScale )
      {
	markerSize = 0.48;
      }
    else
      {	
	markerSize = 0.75;
      }
    
    cname += "Zmusta";
    ctitle = "Z to mu sta analysis";
    
    if( logScale )
      {
	xl_ = 0.60;
	yl_ = 0.50;
	scalel_ = 0.065;
      }
    else
      {
	xl_ = 0.22;
	yl_ = 0.50;
	scalel_ = 0.072;
      }
  }

  if( logScale ) cname += "MuSta_log";
  else           cname += "MuStaNotInThePAPER_lin";

  //Open the root file containing histograms and graphs
  fname += ".root";
  TFile* f_ = TFile::Open(fname,"READ");

  TCanvas* c_ = new TCanvas(cname,ctitle,300,300,479,510);
  c_->SetLeftMargin(  87./479 );
  c_->SetRightMargin( 42./479 );
  c_->SetTopMargin(  30./510 );
  c_->SetBottomMargin( 80./510 ); 
  c_->SetFillColor(0);
  c_->SetTickx(1);
  c_->SetTicky(1);
  c_->SetFrameFillStyle(0);
  c_->SetFrameLineWidth(2);
  c_->SetFrameBorderMode(0);
  Double_t scale = 4;
  Double_t wbin = 42*scale;
  Double_t left  = 8*scale;
  Double_t right = 5*scale;
  Double_t h1 = 135*scale;
  Double_t h2 = 45*scale;
  Double_t top1 = 15*scale;
  Double_t bot1 = 3*scale;
  Double_t top2 = 3*scale;
  //  Double_t bot1 = 0*scale;
  //  Double_t top2 = 0*scale;
  Double_t bot2 = 80*scale;
  Double_t W = left + wbin + right;
  Double_t H = h1 + h2;
  Double_t s[2] = {1, h1/h2 };

  TPad* pad[2];
  pad[0] = new TPad( "top", "top", 
		     0, h2/H, 1, 1,
		     kWhite,0,0);
  pad[0]->SetLeftMargin(  left/W );
  pad[0]->SetRightMargin( right/W );
  pad[0]->SetTopMargin(  top1/H );
  pad[0]->SetBottomMargin( bot1/H );

  pad[1] = new TPad( "bottom", "bottom", 
		     0, 0, 1, h2/H,
		     kWhite,0,0);
  pad[1]->SetLeftMargin(  left/W );
  pad[1]->SetRightMargin( right/W );
  pad[1]->SetTopMargin(  top2/H );
  pad[1]->SetBottomMargin( bot2/H );
  pad[1]->SetGridy();

  for( int ii=0; ii<2; ii++ )
    {
      pad[ii]->SetFillColor(0);
      pad[ii]->SetTickx(1);
      pad[ii]->SetTicky(1);
      pad[ii]->SetFrameFillStyle(0);
      pad[ii]->SetFrameLineWidth(2);
      pad[ii]->SetFrameBorderMode(0);
      pad[ii]->SetFrameFillStyle(0);
      pad[ii]->SetFrameLineWidth(2);
      pad[ii]->SetFrameBorderMode(0);
    }

  // a dummy histogram with the correct x axis
  // Warning: setTDRstyle() must be called before
  TH1F* h_= new TH1F( "bidon", "bidon", nbin_, xmin_, xmax_ );
  TAxis* ax_ = h_->GetXaxis();
  TAxis* ay_ = h_->GetYaxis();

  ax_->SetTitle(xtitle);
  ax_->CenterTitle();
  ax_->SetTitleOffset(1.0);
  ax_->SetNdivisions(ndivx);

  ay_->SetTitle(ytitle);
  ay_->CenterTitle();
  ay_->SetNdivisions(ndivy);
  ay_->SetTitleOffset(titleOffset);
  ay_->SetLabelOffset(0.015);

  // fetch histograms and dress them
  vector<TH1F*> histos;

  size_t nChan=channels.size();   
  for( size_t ii=0;ii<nChan;ii++)
    {
      TH1F* tmp = (TH1F*)f_->Get(channels[ii]);      
      tmp->SetFillColor( fillColor_[type[ii]] );
      tmp->SetLineColor( lineColor_[type[ii]] );
      tmp->SetLineWidth( lineWidth2 );
      histos.push_back(tmp);
    }

  //
  // stack histograms
  //
  TH1* h_stack = (TH1*) histos[nChan-1]->Clone();
  h_stack -> Reset();

  TString stackName_ = TString("Mll");
  vector<TH1*> listOfStackedHists;
  for( size_t ii=0; ii<nChan; ii++ )
    {
      TH1* hh_ = (TH1*) histos[nChan-ii-1]->Clone();

      stackName_ += "_";
      stackName_ += hh_->GetName();	  	  

      TAxis* xaxis = h_stack->GetXaxis();
      for( int iBin=1; iBin<=xaxis->GetNbins(); iBin++ )
	{
	  hh_ -> AddBinContent( iBin, h_stack->GetBinContent( iBin ) );
	}        

      hh_->SetName( stackName_ );
      delete h_stack;
      h_stack = hh_;
      listOfStackedHists.push_back( (TH1*)hh_->Clone() );
    }
  delete h_stack;
  
  TH1* totalHisto = listOfStackedHists[nChan-1];

  // colors the stacked histogram
  totalHisto->SetLineColor( lineColor_["Signal"] );
  totalHisto->SetLineWidth( lineWidth1 );
  
  // The data points are presented as a TGraph 
  // - error bars indicate the Poisson confidence interval at 68%
  // - bins with zero entry are removed
  TH1* hdata = (TH1*) f_->Get("hdata");
  // hdata->Sumw2();
  //hdata->Rebin(2);
  RooHist* roohist;
  TGraphAsymmErrors* dataGraph;

  roohist = new RooHist((*hdata));

  int Nn0=0;
  vector<double> vY;
  vector<double> vX;
  vector<double > veY;
  vector<double > veX;
  vector<double> tmp(0,2);

  for(int ip=0;ip<roohist->GetN();ip++) 
    {
      double Y,X;
      roohist->GetPoint(ip,X,Y);
      
      if(Y!=0) 
	{
	  Nn0++;
	  
	  vY.push_back(Y);
	  vX.push_back(X);
	  veX.push_back( roohist->GetErrorXlow(ip) );
	  veX.push_back( roohist->GetErrorXhigh(ip) );
	  veY.push_back( roohist->GetErrorYlow(ip) );
	  veY.push_back( roohist->GetErrorYhigh(ip) );
	}
    }
  dataGraph=new TGraphAsymmErrors(Nn0);
  for(int ip=0;ip<Nn0;ip++) 
    {
      dataGraph->SetPoint(ip,vX[ip],vY[ip]);      
      dataGraph->SetPointError(ip,veX[ip*2],veX[ip*2+1],veY[ip*2],veY[ip*2+1]);
    }
  dataGraph->SetName("data");

  dataGraph->SetMarkerStyle(kFullCircle);
  dataGraph->SetMarkerColor(kBlack);
  dataGraph->SetMarkerSize(markerSize);

  TGraph* dummyGraph = (TGraph*) dataGraph->Clone("dummyGraph");
  dummyGraph->SetLineColor(0);
  dummyGraph->SetMarkerSize(1.5*markerSize);

  // Remove the horizontal bars (at Michael's request)
  double x_(0), y_(0);
  for( int ii=0; ii<dataGraph->GetN(); ii++ )
    {
      dataGraph->SetPointEXlow(ii,0);
      dataGraph->SetPointEXhigh(ii,0);
      dataGraph->GetPoint(ii,x_,y_ );
      if( y_==0 )
	{
	  dataGraph->RemovePoint( ii );
	  ii--;
	}	  
    }

  // get the ratio data/fit
  TGraphAsymmErrors* ratioGraph = (TGraphAsymmErrors*) dataGraph->Clone("ratio");
  TH1* hfit = totalHisto;
  for( int ii=0; ii<dataGraph->GetN(); ii++ )
    {
      dataGraph->GetPoint(ii,x_,y_ );
      ratioGraph->SetPointEYlow(ii,0);
      ratioGraph->SetPointEYhigh(ii,0);
      ratioGraph->SetPoint(ii,x_,0 );
      double eyl_ = dataGraph->GetErrorYlow(ii);
      double eyh_ = dataGraph->GetErrorYhigh(ii);
      int jj = hfit->FindBin(x_);
      float fit_ = hfit->GetBinContent( jj );
      if( fit_>0 )
	{
	  if( use_chi )
	    {
	      ratioGraph->SetPointEYlow(ii,eyl_/sqrt(fit_));
	      ratioGraph->SetPointEYhigh(ii,eyh_/sqrt(fit_));
	      ratioGraph->SetPoint(ii,x_,(y_-fit_)/sqrt(fit_) );
	    }
	  else
	    {
	      ratioGraph->SetPointEYlow(ii,eyl_/fit_);
	      ratioGraph->SetPointEYhigh(ii,eyh_/fit_);
	      ratioGraph->SetPoint(ii,x_,y_/fit_ );
	    }
	}
      //      cout << ii << " ratio=" << ratioGraph->GetY()[ii] 
      //       	   << "+" << ratioGraph->GetEYhigh()[ii] 
      //	   << "-" << ratioGraph->GetEYlow()[ii] << endl;
    }

  TH1* hratio_ = (TH1*) h_->Clone("hratio");
  ax_->SetLabelOffset(99);
  ax_->SetTitleOffset(99);

  //
  // now plotting
  //  
  c_->Draw();
  c_->cd();

  TPad* p_ = pad[0];
  p_->Draw();
  p_->cd();

  if( logScale )
    {
      p_->SetLogy(true);
    }
  else
    {
      p_->SetLogy(false);
    }

  if( !logScale )
    {
      h_->GetYaxis()->SetRangeUser(ymin_+0.001*(ymax_-ymin_),ymax_);
    }
  else
    {
      h_->GetYaxis()->SetRangeUser(yminl_,ymaxl_);
    }

  h_->Draw();

  float dxl_ = scalel_*3.5;
  float dyl_ = scalel_*1.8;
  if( logScale )
    {
      dxl_ = scalel_*4;
      dyl_ = scalel_*3.4;
    }
  TLegend* legend=new TLegend(xl_,yl_,xl_+dxl_,yl_+dyl_);
  legend->SetLineColor(0);
  legend->SetFillColor(0);
  legend->SetTextFont(42);
  legend->SetTextSize(0.048);
  
  legend->AddEntry(dummyGraph,"   data","pl");      
  if( logScale )
    {
      legend->AddEntry(dummyGraph,"       ","0");
    }
  for(size_t ii=0;ii<nChan;ii++) 
    {
      legend->AddEntry(histos[ii],hnames[ii],"f");
    }
  legend->Draw("same");

  totalHisto->Draw("same");

  for( size_t ii=0; ii<nChan; ii++ )
    {
      //  listOfStackedHists[nChan-ii-1]->Sumw2();   
      listOfStackedHists[nChan-ii-1]->Rebin(1.);
      listOfStackedHists[nChan-ii-1]->Scale(1.);
      listOfStackedHists[nChan-ii-1]->Draw("Same");
    }

  // draw the data points
  dataGraph->Draw("PE");

  // redraw axis
  p_->RedrawAxis();

  //lumi pad, cms prelim pad etc..
  {
    int txtFont = 42;  // bold is 62
    float txtSize1 = 0.055;
    float txtX1 = 0.91;
    float txtY1 = 0.935;

    float txtSize2 = 0.05;
    float txtX2 = 0.85;
    float txtY2 = 0.83;
    
    // TEST FOR THE NAME ZMT, ZMMNONISO, ZMS
    float txtSize3 = 0.055;
    float txtX3 = 0.3;
    float txtY3 = 0.935;

    TLatex latex;
    latex.SetNDC();
    latex.SetTextFont(txtFont);
    
    latex.SetTextSize(txtSize1);    
    latex.SetTextAlign(31); // align right
    latex.DrawLatex(txtX1,txtY1,"CMS");

    latex.SetTextAlign(31); // align right
    latex.SetTextSize(txtSize2);
    latex.DrawLatex(txtX2,txtY2,"36 pb^{-1}  at  #sqrt{s} = 7 TeV");

    latex.SetTextAlign(21); // align left???
    latex.SetTextSize(txtSize3);
    latex.DrawLatex(txtX3,txtY3,"global plus standalone muon");
  }

  c_->cd();
  
  p_ = pad[1];

  p_->Draw();

  p_->cd();

  TAxis* xratio_ = hratio_->GetXaxis();
  TAxis* yratio_ = hratio_->GetYaxis();

  yratio_->SetRangeUser(r0_-0.9999*dr_,r0_+0.9999*dr_);
  yratio_->SetLabelSize( s[1]*yratio_->GetLabelSize() );
  yratio_->SetTitleSize( s[1]*yratio_->GetTitleSize() );
  yratio_->SetLabelOffset( yratio_->GetLabelOffset() );
  yratio_->SetTitleOffset( yratio_->GetTitleOffset()/s[1] );
  if( use_chi )
    {
      yratio_->SetTitle("#chi");
      yratio_->SetNdivisions(4);
    }
  else
    {
      yratio_->SetTitle("data/fit");
      yratio_->SetNdivisions(3);
    }

  xratio_->SetLabelSize( s[1]*xratio_->GetLabelSize() );
  xratio_->SetTitleSize( s[1]*xratio_->GetTitleSize() );
  xratio_->SetTitleOffset( 1.0 );
  xratio_->CenterTitle();
  xratio_->SetLabelOffset( xratio_->GetLabelOffset()*s[1] );
  xratio_->SetTickLength( xratio_->GetTickLength()*s[1] );

  hratio_->Draw();
  ratioGraph->SetMarkerSize( ratioGraph->GetMarkerSize()*1. );
  ratioGraph->SetLineColor( kBlack );

  ratioGraph->SetMarkerColor( kGray+2 );
  ratioGraph->SetMarkerStyle( kFullCircle );
  ratioGraph->DrawClone("PE");
  ratioGraph->SetMarkerColor( kBlack );
  ratioGraph->SetMarkerStyle( kOpenCircle );
  ratioGraph->DrawClone("PE");

  p_->RedrawAxis();

  c_->cd();

  return c_;
}
TauAnalysisSelector::TauAnalysisSelector(const std::string& puWeight, bool isEmbedded,
                                         const std::string& embeddingWTauMuFile, const std::string& embeddingWTauMuPath,
                                         const std::string& mcTauMultiplicity, const std::string& mcTauMode,
                                         const std::string& embeddingNormalizationMode,
                                         TH1 *embeddingMuonWeights):
  BaseSelector(),
  //fMuons("Emb"),
  fGenTaus(isEmbedded ? "gentausOriginal" : "gentaus", true),
  fGenTausEmbedded("gentausEmbedded", true),
  fPuWeightName(puWeight),
  fIsEmbedded(isEmbedded),
  fEmbeddingWTauMuWeights(0),
  fMCTauMultiplicity(parseMCTauMultiplicity(mcTauMultiplicity)),
  fMCTauMode(parseMCTauMode(mcTauMode)),
  fEmbeddingNormalizationMode(parseEmbeddingNormalizationMode(embeddingNormalizationMode)),
  fEmbeddingMuonWeights(embeddingMuonWeights),
  cAll(fEventCounter.addCounter("All events")),
  //cElectronVeto(fEventCounter.addCounter("Electron veto")),
  cGeneratorWeight(fEventCounter.addCounter("Vis. pt weight")),
  cTauBRWeight(fEventCounter.addCounter("Tau BR weighting")),
  cGenTauFound(fEventCounter.addCounter("Gen tau found")),
  cTauMCSelection(fEventCounter.addCounter("Tau MC requirement")),
  cOnlyWMu(fEventCounter.addCounter("Only W->mu")),
  cWTauMuWeight(fEventCounter.addCounter("W->tau->mu weighting")),
  cTriggerEffWeight(fEventCounter.addCounter("Muon trigger eff weighting")),
  cIdEffWeight(fEventCounter.addCounter("Muon ID eff weighting")),
  cMuonWeight(fEventCounter.addCounter("Muon corr weighting (from argument)")),
  cJetSelection(fEventCounter.addCounter("Jet selection")),
  cPrimaryVertex(fEventCounter.addCounter("Primary vertex")),
  cAllTauCandidates(fEventCounter.addCounter(">= 1 tau candidate")),
  cPrePtCut(fEventCounter.addCounter("Pre Pt cut")),
  cDecayModeFinding(fEventCounter.addCounter("Decay mode finding")),
  cEtaCut(fEventCounter.addCounter("Eta cut")),
  cPtCut(fEventCounter.addCounter("Pt cut")),
  cLeadingTrackPtCut(fEventCounter.addCounter("Leading track pt")),
  cEcalCracks(fEventCounter.addCounter("ECAL fiducial: cracks")),
  cEcalGap(fEventCounter.addCounter("ECAL fiducial: gap")),
  cAgainstElectron(fEventCounter.addCounter("Against electron")),
  cAgainstMuon(fEventCounter.addCounter("Against muon")),
  cIsolation(fEventCounter.addCounter("Isolation")),
  cOneProng(fEventCounter.addCounter("One prong")),
  cRtau(fEventCounter.addCounter("Rtau")),
  cMuTrigger(fEventCounter.addCounter("Mu trigger"))
{
  if(isEmbedded && !embeddingWTauMuFile.empty()) {
    TFile *file = TFile::Open(embeddingWTauMuFile.c_str());
    TEfficiency *eff = dynamic_cast<TEfficiency *>(file->Get(embeddingWTauMuPath.c_str()));
    TAxis *xaxis = eff->GetPassedHistogram()->GetXaxis();
    fEmbeddingWTauMuWeights = new TH1F("weights", "weights", xaxis->GetNbins(), xaxis->GetBinLowEdge(xaxis->GetFirst()), xaxis->GetBinUpEdge(xaxis->GetLast()));
    fEmbeddingWTauMuWeights->SetDirectory(0);
    for(int bin=1; bin <= xaxis->GetNbins(); ++bin) {
      fEmbeddingWTauMuWeights->SetBinContent(bin, eff->GetEfficiency(bin));
      std::cout << "Bin " << bin << " low edge " << fEmbeddingWTauMuWeights->GetXaxis()->GetBinLowEdge(bin) << " value " << fEmbeddingWTauMuWeights->GetBinContent(bin) << std::endl;
    }
    fEmbeddingWTauMuWeights->SetBinContent(xaxis->GetNbins()+1, fEmbeddingWTauMuWeights->GetBinContent(xaxis->GetNbins()));
    file->Close();
  }

  if(isEmbedded) {
    fMuons.setIdEfficiencyName("efficiency_Run2011AB");
    fMuons.setTriggerEfficiencyName("efficiency_trigger");
  }
}