// get FWHHM
vector<double> getFWHM(RooRealVar *mass, RooAbsPdf *pdf, RooDataSet *data, double wmin=110., double wmax=130., double step=0.0004) {
 
  cout << "Computing FWHM...." << endl;
  double nbins = (wmax-wmin)/step;
  TH1F *h = new TH1F("h","h",int(floor(nbins+0.5)),wmin,wmax);
  if (data){
    pdf->fillHistogram(h,RooArgList(*mass),data->sumEntries());
  }
  else {
    pdf->fillHistogram(h,RooArgList(*mass));
  }
  
  double hm = h->GetMaximum()*0.5;
  double low = h->GetBinCenter(h->FindFirstBinAbove(hm));
  double high = h->GetBinCenter(h->FindLastBinAbove(hm));

  cout << "FWHM: [" << low << "-" << high << "] Max = " << hm << endl;
  vector<double> result;
  result.push_back(low);
  result.push_back(high);
  result.push_back(hm);
  result.push_back(h->GetBinWidth(1));
  
  delete h;
  return result;
}
Example #2
0
TH1F * DrawOverflow(TH1F *h)
{
      // This function paint the histogram h with an extra bin for overflows
   UInt_t nx    = h->GetNbinsX()+1;
   Double_t *xbins= new Double_t[nx+1];
   for (UInt_t i=0;i<nx;i++)
     xbins[i]=h->GetBinLowEdge(i+1);
   xbins[nx]=xbins[nx-1]+h->GetBinWidth(nx);
   char *tempName= new char[strlen(h->GetName())+10];
   sprintf(tempName,"%swtOverFlow",h->GetName());
   // Book a temporary histogram having ab extra bin for overflows
   TH1F *htmp = new TH1F(tempName, h->GetTitle(), nx, xbins);
   // Reset the axis labels
   htmp->SetXTitle(h->GetXaxis()->GetTitle());
   htmp->SetYTitle(h->GetYaxis()->GetTitle());
   // Fill the new hitogram including the extra bin for overflows
   for (UInt_t i=1; i<=nx; i++)
     htmp->Fill(htmp->GetBinCenter(i), h->GetBinContent(i));
   // Fill the underflows
   htmp->Fill(h->GetBinLowEdge(1)-1, h->GetBinContent(0));
   // Restore the number of entries
   htmp->SetEntries(h->GetEntries());
   // FillStyle and color
   htmp->SetFillStyle(h->GetFillStyle());
   htmp->SetFillColor(h->GetFillColor());
   return htmp;
}
Example #3
0
void Difference(TH1* iH0,TH1 *iH1) {
  std::string lName = std::string(iH0->GetName());
  //TH1F *lHDiff  = new TH1F((lName+"Diff").c_str(),(lName+"Diff").c_str(),50,0,300); lHDiff->Sumw2();
  TH1F *lHDiff  = new TH1F((lName+"Diff").c_str(),(lName+"Diff").c_str(),iH0->GetNbinsX(),iH0->GetXaxis()->GetXmin(),iH0->GetXaxis()->GetXmax()); lHDiff->Sumw2();
  lHDiff->SetFillColor(kViolet); lHDiff->SetFillStyle(1001); lHDiff->SetLineWidth(1);
  TH1F *lXHDiff1 = new TH1F((lName+"XDiff1").c_str(),(lName+"XDiff1").c_str(),iH0->GetNbinsX(),iH0->GetXaxis()->GetXmin(),iH0->GetXaxis()->GetXmax());
  int i1 = 0;
  lXHDiff1->SetLineStyle(2); lXHDiff1->SetLineWidth(2); lXHDiff1->SetLineColor(kRed);

  lHDiff->GetYaxis()->SetRangeUser(0,2);
  lHDiff->GetYaxis()->SetTitleOffset(0.6);
  lHDiff->GetYaxis()->SetTitleSize(0.08);
  lHDiff->GetYaxis()->SetLabelSize(0.08);
  lHDiff->GetYaxis()->CenterTitle();
  lHDiff->GetXaxis()->SetTitleOffset(1.2);
  lHDiff->GetXaxis()->SetTitleSize(0.10);
  lHDiff->GetXaxis()->SetLabelSize(0.08);
  lHDiff->GetXaxis()->SetTitle("#slash{E}_{T} [GeV]");
  //lHDiff->GetXaxis()->CenterTitle();
  //lHDiff->GetYaxis()->SetTitle(YLabel);

  for(int i0 = 0; i0 < lHDiff->GetNbinsX()+1; i0++) {
    double lXCenter = lHDiff->GetBinCenter(i0);
    double lXVal     = iH0   ->GetBinContent(i0);
    lXHDiff1->SetBinContent(i0, 1.0);
    while(iH1->GetBinCenter(i1) < lXCenter) {i1++;}
    if(iH1->GetBinContent(i0) > 0) lHDiff->SetBinContent(i0,(lXVal-iH1->GetBinContent(i0))/(iH1->GetBinContent(i0)));
    if(iH1->GetBinContent(i0) > 0) lHDiff->SetBinError  (i0,iH0->GetBinError(i0)/(iH1->GetBinContent(i0)));
  }
  lHDiff->SetMarkerStyle(kFullCircle); lHDiff->SetLineColor(kBlack); lHDiff->SetMarkerColor(kBlack);
  lHDiff->Draw("E1");
  lXHDiff1->Draw("hist sames");
}
Example #4
0
TH1* AddOverflow(TH1* h) {

  ++overflowCounter;

  TString  name = h->GetName();
  Int_t    nx   = h->GetNbinsX()+1;
  Double_t bw   = h->GetBinWidth(nx);
  Double_t x1   = h->GetBinLowEdge(1);
  Double_t x2   = h->GetBinLowEdge(nx) + bw;
  
  // Book a new histogram having an extra bin for overflows
  TH1F* htmp = new TH1F(Form(name + "_overflow_%d", overflowCounter), "", nx, x1, x2);

  // Fill the new histogram including the extra bin for overflows
  for (Int_t i=1; i<=nx; i++) {
    htmp->Fill(htmp->GetBinCenter(i), h->GetBinContent(i));
    htmp->SetBinError(i, h->GetBinError(i));
  }

  // Fill the underflow
  htmp->Fill(x1-1, h->GetBinContent(0));

  // Restore the number of entries
  htmp->SetEntries(h->GetEntries());

  // Cosmetics
  htmp->SetLineColor(h->GetLineColor());
  htmp->SetLineWidth(h->GetLineWidth());
  htmp->GetXaxis()->SetTitleOffset(1.5);

  return htmp;
}
void PaintOverflow(TH1 *h)
{
  // This function paint the histogram h with an extra bin for overflows
  
  char* name  = h->GetName();
  char* title = h->GetTitle();
  Int_t nx    = h->GetNbinsX()+1;
  Double_t x1 = h->GetBinLowEdge(1);
  Double_t bw = h->GetBinWidth(nx);
  Double_t x2 = h->GetBinLowEdge(nx)+bw;
  
  // Book a temporary histogram having ab extra bin for overflows
  TH1F *htmp = new TH1F(name, title, nx, x1, x2);
  
  // Fill the new hitogram including the extra bin for overflows
  for (Int_t i=1; i<=nx; i++) {
    htmp->Fill(htmp->GetBinCenter(i), h->GetBinContent(i));
  }
  
  // Fill the underflows
  htmp->Fill(x1-1, h->GetBinContent(0));
  
  // Restore the number of entries
  htmp->SetEntries(h->GetEntries());
  
  // Draw the temporary histogram
  htmp->Draw();
  /*
  TText *t = new TText(x2-bw/2,h->GetBinContent(nx),"Overflow");
  t->SetTextAngle(90);
  t->SetTextAlign(12);
  t->SetTextSize(0.03);;
  t->Draw();
  */
}
//Difference plotting
void drawDifference(TH1* iH0,TH1 *iH1,TH1 *iHH=0,TH1 *iHL=0,TH1 *iHH1=0,TH1 *iHL1=0) {
  std::string lName = std::string(iH0->GetName());
  TH1F *lHDiff   = (TH1F*) iH0->Clone("Diff");
  TH1F *lHDiffH  = (TH1F*) iH0->Clone("DiffH");
  TH1F *lHDiffL  = (TH1F*) iH0->Clone("DiffL"); 
  TH1F *lHDiffH1 = (TH1F*) iH0->Clone("DiffH1");
  TH1F *lHDiffL1 = (TH1F*) iH0->Clone("DiffL1"); 
  lHDiff  ->SetFillColor(kViolet); lHDiff->SetFillStyle(1001); lHDiff->SetLineWidth(1);
  lHDiffL ->SetLineWidth(1); lHDiffL ->SetLineColor(iHL ->GetLineColor());
  lHDiffH ->SetLineWidth(1); lHDiffH ->SetLineColor(iHH ->GetLineColor());
  lHDiffL1->SetLineWidth(1); lHDiffL1->SetLineColor(iHL1->GetLineColor());
  lHDiffH1->SetLineWidth(1); lHDiffH1->SetLineColor(iHH1->GetLineColor());
  TH1F *lXHDiff1 = new TH1F((lName+"XDiff1").c_str(),(lName+"XDiff1").c_str(),iH0->GetNbinsX(),iH0->GetXaxis()->GetXmin(),iH0->GetXaxis()->GetXmax());
  TH1F *lXHDiff2 = new TH1F((lName+"XDiff2").c_str(),(lName+"XDiff2").c_str(),iH0->GetNbinsX(),iH0->GetXaxis()->GetXmin(),iH0->GetXaxis()->GetXmax());
  int i1 = 0;
  lXHDiff1->SetLineWidth(2); lXHDiff1->SetLineColor(kRed);
  lXHDiff2->SetLineWidth(2); lXHDiff2->SetLineColor(kRed);

  lXHDiff1->GetYaxis()->SetTitle("Ratio");
  lXHDiff1->GetYaxis()->SetRangeUser(0.2,1.8);
  lXHDiff1->GetYaxis()->SetTitleOffset(0.4);
  lXHDiff1->GetYaxis()->SetTitleSize(0.2);
  lXHDiff1->GetYaxis()->SetLabelSize(0.11);
  for(int i0 = 0; i0 < lHDiff->GetNbinsX()+1; i0++) {
    double lXCenter = lHDiff->GetBinCenter(i0);
    double lXVal     = iH0   ->GetBinContent(i0);
    double lXValH    = iHH   ->GetBinContent(i0);
    double lXValL    = iHL   ->GetBinContent(i0);
    double lXValH1   = iHH1  ->GetBinContent(i0);
    double lXValL1   = iHL1  ->GetBinContent(i0);
    lXHDiff1->SetBinContent(i0, 1.0);
    lXHDiff2->SetBinContent(i0, 1.0);
    while(iH1->GetBinCenter(i1) < lXCenter) {i1++;}
    if(iH1->GetBinContent(i0) > 0) lHDiff->SetBinContent(i0,lXVal      /(iH1->GetBinContent(i0)));
    if(iH1->GetBinContent(i0) > 0) lHDiff->SetBinError  (i0,sqrt(lXVal)/(iH1->GetBinContent(i0)));
    if(iH1->GetBinContent(i0) > 0) lHDiffL->SetBinContent(i0,lXValL/(iH1->GetBinContent(i0)));
    if(iH1->GetBinContent(i0) > 0) lHDiffH->SetBinContent(i0,lXValH/(iH1->GetBinContent(i0)));
    if(iH1->GetBinContent(i0) > 0) lHDiffL1->SetBinContent(i0,lXValL1/(iH1->GetBinContent(i0)));
    if(iH1->GetBinContent(i0) > 0) lHDiffH1->SetBinContent(i0,lXValH1/(iH1->GetBinContent(i0)));
   //if(iH1->GetBinContent(i0) > 0)  cout << "unc" << lXVal << " -- " << sqrt(lXVal)/(iH1->GetBinContent(i0)) << endl;
  }
  lHDiff->SetMarkerStyle(kFullCircle);
  //lHDiff->Draw("EP");
  
  lXHDiff1->SetStats(0);
  lXHDiff2->SetStats(0);
  lHDiff->SetStats(0);
  lHDiffH->SetStats(0);
  lHDiffL->SetStats(0);
  lHDiffH1->SetStats(0);
  lHDiffL1->SetStats(0);

  lXHDiff1->Draw("hist");
  lXHDiff2->Draw("hist sames");
  lHDiff->Draw("EP sames");
  lHDiffH ->Draw("hist sames");
  lHDiffL ->Draw("hist sames");
  lHDiffH1->Draw("hist sames");
  lHDiffL1->Draw("hist sames");
}
void FitterCBForSignificance(){



  //  TFile* _shapes = new TFile("/afs/cern.ch/user/m/mgouzevi/scratch0/CMGTools/CMSSW_4_2_8/src/StatTools/BayesianDijetFit/Results/Resonance_Shapes_gg_TuneD6T_Emine2013.root");

  TFile* _shapes = new TFile("/afs/cern.ch/user/m/mgouzevi/scratch0/CMGTools/CMSSW_4_2_8/src/StatTools/BayesianDijetFit/Results/Resonance_Shapes_qg_TuneD6T_Emine2013.root");



  //  TFile* _shapes = new TFile("/afs/cern.ch/user/m/mgouzevi/scratch0/CMGTools/CMSSW_4_2_8/src/StatTools/BayesianDijetFit/Results/Resonance_Shapes_Qstar_2012_D6T_ak5_fat30_save.root");
  //  TFile* _shapes = new TFile("/afs/cern.ch/user/m/mgouzevi/scratch0/CMGTools/CMSSW_4_2_8/src/StatTools/BayesianDijetFit/Results/Resonance_Shapes_RSGraviton_2012_D6T_ak5_GGtoGG_fat30_save.root");
  //TFile* _shapes = new TFile("/afs/cern.ch/user/m/mgouzevi/scratch0/CMGTools/CMSSW_4_2_8/src/StatTools/BayesianDijetFit/Results/Resonance_Shapes_RSGraviton_2012_D6T_ak5_QQtoQQ_fat30_save.root");

  //TFile* _shapes = new TFile("/afs/cern.ch/user/m/mgouzevi/scratch0/CMGTools/CMSSW_4_2_8/src/StatTools/BayesianDijetFit/Results/Resonance_Shapes_Qstar_ak5_fat30.root");
  for (int i = 1; i < 2; i++){
	   TH1F* shape = (TH1F*) _shapes->Get(Form("h_qg_%d;1", 1000+i*100));
	   TH1F* shape_largeBinning = new TH1F("shape_large_binning", "", NBINS, BOUNDARIES);

	   for (int j = 1; j < shape->GetNbinsX()+1; j++){
	     double binCenter = shape->GetBinCenter(j);
	     double weight = shape->GetBinContent(j);
	     double binWidth = shape->GetBinWidth(j);
	     shape_largeBinning->Fill(binCenter, weight);
	     //	     cout << "j = " << j << " binWidth = " << binWidth << " weight = " << weight << endl;
	     shape->SetBinContent(j, weight/binWidth);
	   }

	   for (int j = 1; j < shape_largeBinning->GetNbinsX()+1; j++){
	     double weight = shape_largeBinning->GetBinContent(j);
	     double binWidth = shape_largeBinning->GetBinWidth(j);
	     shape_largeBinning->SetBinContent(j, weight/binWidth*1000000);
	   }

	   shape->Draw();

	   shape_largeBinning->SetLineColor(kRed);
	   shape_largeBinning->Draw("SAME");

	   //   
	   FitHistWithCBShape(shape_largeBinning, 1000.+i*100);		
	}

	  cout << "mass\tsMean\tsSigma\tsAlphaHigh\tsAlphaLow\tsNHigh\tsNLow\tsFrac"<<endl;

	for (int i = 0; i < 40; i++){
	
	  cout << Masses[i] << "\t" << Means[i] << "\t" << Sigmas[i] << "\t"
	       << alphaHights[i] << "\t\t" << alphaLows[i] << "\t"
	       << nHighs[i] << "\t\t" << nLows[i] << "\t" << fracs[i] << endl;

	}
}
Example #8
0
bool isgood(TH1F h, float sigma){
  if(sigma == -1) return true;
  bool Flag = true;
  int imaxbin = h.GetMaximumBin();
  float bincenter = h.GetBinCenter(imaxbin);
  for(int ibin=0;ibin<h.GetNbinsX();ibin++){
      if((h.GetBinCenter(ibin)<(bincenter-sigma)) || (h.GetBinCenter(ibin)>(bincenter+sigma))){
          if(h.GetBinContent(ibin)!=0){
              Flag = false;
              break;
          }
      }
  }

  if(Flag){
  h.SetBinContent(imaxbin,0);
  imaxbin = h.GetMaximumBin();
  bincenter = h.GetBinCenter(imaxbin);
  for(int ibin=0;ibin<h.GetNbinsX();ibin++){
      if((h.GetBinCenter(ibin)<(bincenter-sigma)) || (h.GetBinCenter(ibin)>(bincenter+sigma))){
          if(h.GetBinContent(ibin)!=0){
              Flag = false;
              break;
          }
      }
  }
  }
  return Flag;
}
Example #9
0
/**
 * Saving Histogram Data
 */
void ExportHistogram(TFile* f,const char* histKey,const char* outputfile){
  // Root Setup
  TH1F* h = (TH1F*) f->Get(histKey);

  // File Setup
  ofstream out;
  out.open(outputfile);
  out<<"Bin,Value,Error"<<endl;
  for (int i = 1; i < h->GetNbinsX()-1; i++){
    out<<h->GetBinCenter(i)<<","<<h->GetBinContent(i)<<","<<h->GetBinError(i)<<endl;
  }
  out.close();
}
Example #10
0
void drawPileup(const std::string& fileName)
{
  TFile* f = TFile::Open(((fileName)+".root").c_str(),"READ");
  TH1F* h = (TH1F*)( f->Get("pileup") );
  
  TCanvas* c = new TCanvas("c","pileup");
  c -> cd();
  c -> SetGridx();
  c -> SetGridy();
  
  h -> GetXaxis() -> SetTitle("n_{PU}");
  h -> GetXaxis() -> SetLabelSize(0.04);
  h -> GetYaxis() -> SetLabelSize(0.04);
  h -> GetYaxis() -> SetTitle("event fraction");
  h -> Scale(1./h->Integral());
  h -> SetMarkerStyle(20);
  h -> Draw("P");
  
  c -> Update();
  
  for(int bin = 1; bin <= h->GetNbinsX(); ++bin)
  {
    if( int(h->GetBinCenter(bin)) < 10 )
      std::cout << "distrPU_DATA[" << int(h->GetBinCenter(bin)) <<"]  = ";
    else
      std::cout << "distrPU_DATA[" << int(h->GetBinCenter(bin)) <<"] = ";
    std::cout << std::fixed << std::setprecision(9) << std::setw(11) << h -> GetBinContent(bin);
    std::cout << ";" << std::endl;
  }
  
  
  
  TFile* o = new TFile(((fileName)+"_plot.root").c_str(),"RECREATE");
  o -> cd();
  
  h -> Write();
  
  o -> Close();
}
Example #11
0
// Called within makePlot when making the pu plot
// Basically adds in the +/- 5% systematic error bars
TGraphAsymmErrors makePUPlot( THStack stack, TString anaType, const float lumi ) {

  // Got the stack, now sum the =/- 5% histograms and make two new stacks
  // Make dummy legend etc.
  THStack p5Stack("Background MC p5","");
  THStack m5Stack("Background MC m5","");
  TLegend *legend= new TLegend(0.1,0.1,0.1,0.1);

  addBackgroundHistos( anaType, "nRecoPV_p5", p5Stack, legend, lumi );
  addBackgroundHistos( anaType, "nRecoPV_m5", m5Stack, legend, lumi );

  // Get last histogram in stacks i.e. sum of all backgrounds
  TH1F * hist = new TH1F( *(TH1F*)(stack.GetStack()->Last()) );
  TH1F * p5Hist = new TH1F( *(TH1F*)p5Stack.GetStack()->Last() );
  TH1F * m5Hist = new TH1F( *(TH1F*)m5Stack.GetStack()->Last() );

  // Create structures to make TGraphAssymErrors
  Int_t n=p5Hist->GetNbinsX();
  Double_t x[n]; // x values
  Double_t y[n]; // y values
  Double_t exl[n]; // low x error
  Double_t eyl[n]; // low y error
  Double_t exh[n]; // high x error
  Double_t eyh[n]; // high y error

  // Loop over histos and get values
  for ( int bin=1; bin < n+1; bin++ ) {
    x[bin-1]=hist->GetBinCenter( bin );
    y[bin-1]=hist->GetBinContent( bin );
    exl[bin-1]=hist->GetBinWidth( bin )/2;
    eyl[bin-1]=p5Hist->GetBinContent( bin )-y[bin-1];
    exh[bin-1]=hist->GetBinWidth( bin )/2;
    eyh[bin-1]=y[bin-1]-m5Hist->GetBinContent( bin );
  }


  // Make TGraphAssymErrors
  TGraphAsymmErrors gr(n,x,y,exl,exh,eyl,eyh);

  return gr;
}
Example #12
0
//----------------------------------------//
// Get profile from all events mixed
//----------------------------------------//
TProfile* getMixProfile(TFile* file, int nbins,
			float xmin, float xmax,
			int color, int marker)
{

  // Histograms all have same base name
  string base = "h_evt";
  
  // String stream easy for manipulation
  stringstream ss;
  
  // Create Profile
  TProfile* p = new TProfile("mixed","",nbins,xmin,xmax);
  p->SetMarkerSize(0.75);
  p->SetMarkerStyle(marker);
  p->SetMarkerColor(color);
  p->SetLineColor(color);

  // Now loop over events and get result
  TH1F* h = NULL;
  for(int i=0; i<m_nEvent; ++i){
    ss.str("");
    ss << base << i;
    h = (TH1F*) file->Get(ss.str().c_str());

    // Loop over bin content
    for(int bin=1; bin<=h->GetNbinsX(); ++bin){
      float content = h->GetBinContent(bin);
      float center  = h->GetBinCenter(bin);
      p->Fill(center, content);
    }
    
    h = NULL;

  }// end loop events

  return p;

}
Example #13
0
void Plot::FitSignal(int mode, int fitMode) {

	const int nPar = 6;
	TRandom ran;

	if(mode==0) {
		gStyle->SetOptLogy(1);
	} else {
		gStyle->SetOptLogy(0);
	}
	gStyle->SetOptStat(0);
	gStyle->SetOptTitle(0);
	const float limitBinSize = 2.0; // **** bin size here
	TCanvas* c = NewCanvas();
	c->Divide(1,2);

	gROOT->cd();
	TH1F* cc = new TH1F("CCSignal","CC Signal",500,0.0,1000.0);
	TH1F* ccBg = new TH1F("CCBgFit","CC Bg Fit",500,0.0,1000.0);
	TH1F* ccBgErr = new TH1F("CCBgErr","CC Bg Err",500,0.0,1000.0);
	TH1F* ccBgP = new TH1F("CCBgPlus","CC Bg Plus",500,0.0,1000.0);
	TH1F* ccBgM = new TH1F("CCBgMinus","CC Bg Minus",500,0.0,1000.0);
	TH1F* cp = new TH1F("CPSignal","CP Signal",500,0.0,1000.0);
	TH1F* cpBg = new TH1F("CPBgFit","CP Bg Fit",500,0.0,1000.0);
	TH1F* cpBgErr = new TH1F("CPBgErr","CP Bg Err",500,0.0,1000.0);
	TH1F* cpBgP = new TH1F("CPBgPlus","CP Bg Plus",500,0.0,1000.0);
	TH1F* cpBgM = new TH1F("CPBgMinus","CP Bg Minus",500,0.0,1000.0);
	TMatrixD matrix(nPar,nPar);

	fd->cd();

	TH1F* hInt,*hBgInt;
	char fitname[100];
	for(int ind=0; ind<2; ind++) {
		if(debug) printf("starting ind %i\n",ind);
		c->cd(ind+1);
		gStyle->SetOptLogy(1);
		printf("Starting %i ######################################\n",ind);

		TH1F* h;
		//char cind[20];
		//char handle[100];
		//sprintf(handle,"side_1exp_%02i_%02i_%02i",ind,mode,fitMode);
		TF1* fits[4];
		//TF1* dpx[4];
		if(debug) printf("looking for h %i\n",int(fd));
		if(ind==0) {
			h = (TH1F*)fd->FindObjectAny("pair_mass_2GeV1");
		} else if(ind==1) {
			h = (TH1F*)fd->FindObjectAny("pair_mass_2GeV3");
		}
		if(debug) printf("new h %i\n",int(h));

		if(debug) printf("new fit\n");
		sprintf(fitname,"hfit_%1i",ind);
		fits[ind] = new TF1(fitname,"([0]*pow((x-30.0),[1])+[3]*pow((x-30.0),0.2))*([2]*exp(-[2]*(x-30.0))+[4]*[5]*exp(-[5]*(x-30.0)))",30.0,500.0);
		//fits[ind] = new TF1(fitname,"([0]*((1-[3])*pow((x-30.0),[1])+[3]*pow((x-30.0),0.2)))*(exp(-[2]*(x-30.0))+[4]*exp(-[5]*(x-30.0)))",30.0,500.0);
		fits[ind]->SetParameter(0,0.0004);
		fits[ind]->SetParameter(1,2);
		fits[ind]->SetParameter(2,0.02);
		fits[ind]->SetParameter(3,0.005);
		//fits[ind]->SetParameter(3,0.5);
		fits[ind]->SetParameter(4,1.005);
		fits[ind]->SetParameter(5,0.05);

		float llim = 30.0;
		h->Fit(fits[ind],"LN","",llim,1000.0);

		double par[20],parMin[20],fval,fvalMin;
		for(int i=0; i<nPar; i++) parMin[i] = fits[ind]->GetParameter(i);

		gMinuit->Eval(nPar,0,fvalMin,parMin,0);
		//printf("got back %10.5f\n",fvalMin);

		// save the fit results in a histogram, for limit program
		for(int ibin=16; ibin<250; ibin++) {
			float xx = h->GetBinCenter(ibin);
			float yy = fits[ind]->Eval(xx);
			if(ind==0) {
				cc->SetBinContent(ibin,h->GetBinContent(ibin));
				ccBg->SetBinContent(ibin,yy);
				ccBgErr->SetBinContent(ibin,0.0);
				ccBgP->SetBinContent(ibin,0.0);
				ccBgM->SetBinContent(ibin,99999.0);
			} else {
				cp->SetBinContent(ibin,h->GetBinContent(ibin));
				cpBg->SetBinContent(ibin,yy);
				cpBgErr->SetBinContent(ibin,0.0);
				cpBgP->SetBinContent(ibin,0.0);
				cpBgM->SetBinContent(ibin,99999.0);
			}
		}

		//vary the parameters to find an error envelope
		double par2[20],fval2=1e10;
		int pslim = (ind==0?25000:150000);
		for(int ips=0; ips<pslim; ips++) {
			if(ips%10000==0) printf("Processing %d\n",ips);
			for(int i=0; i<nPar; i++) {
				par[i] = parMin[i];
			}
			for(int i=0; i<nPar; i++) {
				//int i = (ips%2==0?0:3);
				par[i] = parMin[i]+(2.0*(ran.Uniform()-0.5))*fits[ind]->GetParError(i);
			}
			fval = 0.0;
			gMinuit->Eval(nPar,0,fval,par,0);
			if((fval-fvalMin)<1.0) {
				printf("Found nearby min %10.5f\n",fval-fvalMin);
				float eOld,eNew;
				for(int ibin=16; ibin<250; ibin++) {
					float xx = h->GetBinCenter(ibin);
					for(int i=0; i<nPar; i++) fits[ind]->SetParameter(i,par[i]);
					float yy = fits[ind]->Eval(xx);
					for(int i=0; i<nPar; i++) fits[ind]->SetParameter(i,parMin[i]);
					float yyMin = fits[ind]->Eval(xx);
					TH1F *hBgErr,*hBgP,*hBgM;
					if(ind==0) {
						hBgErr = ccBgErr; hBgP = ccBgP; hBgM = ccBgM;
					} else {
						hBgErr = cpBgErr; hBgP = cpBgP; hBgM = cpBgM;
					}

					eOld = hBgErr->GetBinContent(ibin);
					eNew = yy - yyMin;
					if(eOld>fabs(eNew)) hBgErr->SetBinContent(ibin,fabs(eNew));
					eOld = hBgP->GetBinContent(ibin);
					if(yy>eOld)  hBgP->SetBinContent(ibin,yy);
					eOld = hBgM->GetBinContent(ibin);
					if(yy<eOld)  hBgM->SetBinContent(ibin,yy);
				}

			} // end if near maximum

			/*
				if(fval<fval2) {
				for(int i=0; i<nPar; i++) par2[i] = par[i];
				fval2 = fval;
				}
				*/
		}

		/*
			printf("forcing new fit..\n");
			for(int i=0; i<nPar; i++) {
			printf("old,new = %10.5f %10.5f\n",parMin[i],par2[i]);
			fits[ind]->SetParameter(i,par2[i]);
			}
			*/

		// restore original fit
		fval = 0.0;
		gMinuit->Eval(nPar,0,fval,parMin,0);
		for(int i=0; i<nPar; i++) fits[ind]->SetParameter(i,parMin[i]);



		//extract fit error matrix
		gMinuit->mnemat(matrix.GetMatrixArray(),nPar);
		matrix.Print();

		for(int i=0; i<nPar; i++) {
			for(int j=0; j<nPar; j++) {
				printf("%10.5f",matrix(i,j)/sqrt(matrix(i,i)*matrix(j,j)));
			}
			printf("\n");
		}
		//matrix.Draw("text");

		float hm = h->GetMaximum();
		if(mode==0) {
			//TAxis* ax = h->GetXaxis();
			//ax->SetRangeUser(24.1,199.9);
			h->SetMaximum(1.2*hm);
			//h->SetMinimum(0.0);
		} else if(mode==1) {
			TAxis* ax = h->GetXaxis();
			ax->SetRangeUser(20.0,500.0);
			h->SetMaximum(1.15*hm);
			h->SetMinimum(0.0);
		}


		h->Draw();
		fits[ind]->SetLineColor(1);
		fits[ind]->SetLineWidth(2.0);
		fits[ind]->Draw("SAME");
		// find chi2's and KS's
		//AnaChiKs(h,fits[ind]);



		TAxis* ax,*ay;
		ax = h->GetXaxis(); 
		ay = h->GetYaxis();
		ax->SetTitle("m(#gamma#gamma) (GeV/c^{2})"); 
		ay->SetTitle("Entries/2 GeV/c^{2}");
		ax->CenterTitle(); ay->CenterTitle();
		ax->SetTitleOffset(0.9);
		ay->SetTitleOffset(1.0);
		ax->SetTitleSize(0.08);
		ay->SetTitleSize(0.07);
		ax->SetLabelSize(0.07);
		ay->SetLabelSize(0.07);

		gPad->SetLeftMargin(0.16);
		gPad->SetBottomMargin(0.16);

		TText* text;
		text = new TLatex(0.5,0.8,"Diphoton Data");
		text->SetNDC(true);
		text->SetTextSize(0.06);
		text->Draw();
		if(ind==0)      text = new TLatex(0.5,0.72,"Central-Central");
		else if(ind==1) text = new TLatex(0.5,0.72,"Central-Plug");
		text->SetNDC(true);
		text->SetTextSize(0.06);
		text->Draw();
		if(ind==0) {
			text = new TLatex(0.15,0.92,"W/Z H#rightarrow X(#gamma#gamma)");
			text->SetNDC(true);
			text->SetTextSize(0.08);
			text->Draw();

			text = new TLatex(0.5,0.92,"CDF Run II Preliminary, 2.0 fb^{-1}");
			text->SetNDC(true);
			text->SetTextSize(0.06);
			text->Draw();
		}    

		/*
			if(debug) printf("start loop\n");
			int ibin;
			for(ibin=16; ibin<=250; ibin++) {
			if(debug) printf("start bin            %i\n",ibin);
			float xx = (ibin-0.5)*2.0; // *** bin width here
			if(debug) printf("-1 test ibin %i\n",ibin);
			float yy = fits[ind]->Eval(xx);
		//printf("%f  yy= %f \n",xx,yy);
		// the derivative of this yield wrt parameters
		if(debug) printf("0 test ibin %i\n",ibin);
		double y0 = yy;
		if(debug) printf("1 test ibin %i\n",ibin);
		TMatrixD vv(nPar,1);
		float dirSize = 0.5;
		for(int i=0; i<nPar; i++){
		int ipar = i;
		double par = fits[ind]->GetParameter(ipar);
		double spar = fits[ind]->GetParError(ipar);
		double parp = par + dirSize*spar;
		fits[ind]->SetParameter(ipar,parp);
		double yp = fits[ind]->Eval(xx);
		vv(i,0) = limitBinSize*(yp-y0)/(dirSize*spar);
		fits[ind]->SetParameter(ipar,par);
		//printf("%f %f %f\n",yp,y0,spar);
		}
		//vv.Print();
		if(debug) printf("start matrix %i\n",ibin);
		TMatrixD tempM(matrix, TMatrixDBase::kMult, vv);
		//matrix.Print();
		TMatrixD tempN(vv, TMatrixDBase::kTransposeMult, tempM);
		//tempN.Print();
		float bgSig = 0.0;
		if(tempN(0,0)>0.0) bgSig = sqrt(tempN(0,0));
		// ****** hack temp  **********
		bgSig = 0.3*y0;


		// file hists to be saved
		if(debug) printf("start fill %i\n",ibin);
		if(ind==0) {
		//printf("filling cc %i %f\n",ibin,h->GetBinContent(ibin));
		cc->SetBinContent(ibin,h->GetBinContent(ibin));
		//printf("getting cc %i %f\n",ibin,cc->GetBinContent(ibin));
		ccBg->SetBinContent(ibin,yy);
		ccBgErr->SetBinContent(ibin,bgSig);
		ccBgP->SetBinContent(ibin,yy+bgSig);
		ccBgM->SetBinContent(ibin,TMath::Max(yy-bgSig,float(0.0)));
		//if(ibin==27) {
		//printf("bg %f %f \n",yy,bgSig);
		//}
		} else {
		cp->SetBinContent(ibin,h->GetBinContent(ibin));
		cpBg->SetBinContent(ibin,yy);
		cpBgErr->SetBinContent(ibin,bgSig);
		cpBgP->SetBinContent(ibin,yy+bgSig);
		cpBgM->SetBinContent(ibin,TMath::Max(yy-bgSig,float(0.0)));
		}
		if(debug) printf("end fill %i\n",ibin);
		}
		*/

	}

	printf("cc plus  BG=%f\n",ccBgP->GetSum());
	printf("cc minus BG=%f\n",ccBgM->GetSum());
	printf("cp plus  BG=%f\n",cpBgP->GetSum());
	printf("cp minus BG=%f\n",cpBgM->GetSum());

	char fn[100];
	if(mode==0) {
		sprintf(fn,"FitSignal_%d",fitMode);
		savePlot(c,fn);
	} else if(mode==1) {
		sprintf(fn,"FitSignalLin_%d",fitMode);
		savePlot(c,fn);
	}

	//if(mode!=0) return;

	// plot of fit results
	gStyle->SetOptLogy(0);
	c = NewCanvas();
	c->Divide(1,2);

	c->cd(1);
	cc->Draw();
	ccBg->Draw("SAME");
	c->cd(2);
	ccBgErr->SetMinimum(0.0); ccBgErr->SetMaximum(4.0); 
	ccBgErr->Draw();
	ccBgP->SetLineStyle(2); ccBgP->Draw("SAME");
	ccBgM->SetLineStyle(2); ccBgM->Draw("SAME");

	savePlot(c,"FitSignalResultsCC");

	c = NewCanvas();
	c->Divide(1,2);

	c->cd(1);
	cp->Draw();
	cpBg->Draw("SAME");
	c->cd(2);
	cpBgErr->SetMinimum(0.0); cpBgErr->SetMaximum(4.0); 
	cpBgErr->Draw();
	cpBgP->SetLineStyle(2); cpBgP->Draw("SAME");
	cpBgM->SetLineStyle(2); cpBgM->Draw("SAME");

	savePlot(c,"FitSignalResultsCP");

	char title[100];
	if(name) {
		sprintf(title,"TPeaksHiggs_FitSignalHist_%s.root",name);
		TFile* ff = new TFile(title,"RECREATE");
		gROOT->GetList()->Write();
		ff->Close();
	}

}
Example #14
0
void aliceReferror()
{
  cout<<endl;
  cout<<endl;
  gStyle->SetOptFit(0);

  //Fill ALice(7TeV,|y|<0.5) and CMS(2.76TeV,|y|<1) FONLL values
  cout<<"---- Fill ALice(7TeV,|y|<0.5) and CMS(2.76TeV,|y|<1) FONLL values"<<endl;

  TString infnameAlice="fonllInput/fo_Dzero_pp_7_y0p5_curve.dat";
  TString infnameAnly="fonllInput/fo_Dzero_pp_2p76_y1_curve.dat";
  ifstream getdataAlice(infnameAlice.Data());
  ifstream getdataAnly(infnameAnly.Data());

  TH1F* hptAlice = new TH1F("hptAlice","",fo_BIN_NUM,HMIN,HMAX);          TH1F* hptAnly = new TH1F("hptAnly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hminallAlice = new TH1F("hminallAlice","",fo_BIN_NUM,HMIN,HMAX);  //TH1F* hminallAnly = new TH1F("hminallAnly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hmaxallAlice = new TH1F("hmaxallAlice","",fo_BIN_NUM,HMIN,HMAX);  //TH1F* hmaxallAnly = new TH1F("hmaxllAnly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hpt11Alice = new TH1F("hpt11Alice","",fo_BIN_NUM,HMIN,HMAX);      TH1F* hpt11Anly = new TH1F("hpt11Anly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hpt55Alice = new TH1F("hpt55Alice","",fo_BIN_NUM,HMIN,HMAX);      TH1F* hpt55Anly = new TH1F("hpt55Anly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hpt22Alice = new TH1F("hpt22Alice","",fo_BIN_NUM,HMIN,HMAX);      TH1F* hpt22Anly = new TH1F("hpt22Anly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hpt21Alice = new TH1F("hpt21Alice","",fo_BIN_NUM,HMIN,HMAX);      TH1F* hpt21Anly = new TH1F("hpt21Anly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hpt12Alice = new TH1F("hpt12Alice","",fo_BIN_NUM,HMIN,HMAX);      TH1F* hpt12Anly = new TH1F("hpt12Anly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hpt15Alice = new TH1F("hpt15Alice","",fo_BIN_NUM,HMIN,HMAX);      TH1F* hpt15Anly = new TH1F("hpt15Anly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hpt51Alice = new TH1F("hpt51Alice","",fo_BIN_NUM,HMIN,HMAX);      TH1F* hpt51Anly = new TH1F("hpt51Anly","",fo_BIN_NUM,HMIN,HMAX);

  Double_t a11_Alice[fo_BIN_NUM],a55_Alice[fo_BIN_NUM],a22_Alice[fo_BIN_NUM],a21_Alice[fo_BIN_NUM],a12_Alice[fo_BIN_NUM],a15_Alice[fo_BIN_NUM],a51_Alice[fo_BIN_NUM];
  Double_t a11_Anly[fo_BIN_NUM],a55_Anly[fo_BIN_NUM],a22_Anly[fo_BIN_NUM],a21_Anly[fo_BIN_NUM],a12_Anly[fo_BIN_NUM],a15_Anly[fo_BIN_NUM],a51_Anly[fo_BIN_NUM];
  Double_t min_all_Alice[fo_BIN_NUM],max_all_Alice[fo_BIN_NUM],min_sc_Alice[fo_BIN_NUM],max_sc_Alice[fo_BIN_NUM],min_mass_Alice[fo_BIN_NUM],max_mass_Alice[fo_BIN_NUM],min_pdf_Alice[fo_BIN_NUM],max_pdf_Alice[fo_BIN_NUM];
  Double_t min_all_Anly[fo_BIN_NUM],max_all_Anly[fo_BIN_NUM],min_sc_Anly[fo_BIN_NUM],max_sc_Anly[fo_BIN_NUM],min_mass_Anly[fo_BIN_NUM],max_mass_Anly[fo_BIN_NUM],min_pdf_Anly[fo_BIN_NUM],max_pdf_Anly[fo_BIN_NUM];
  Int_t i,j;
  Double_t tem=0.;
  Double_t pdfrac=0.557*1.e-6;
  for(i=0;i<fo_BIN_NUM;i++)
    {
      getdataAlice>>tem;
      getdataAlice>>a11_Alice[i];
      getdataAlice>>min_all_Alice[i];
      getdataAlice>>max_all_Alice[i];
      getdataAlice>>min_sc_Alice[i];
      getdataAlice>>max_sc_Alice[i];
      getdataAlice>>min_mass_Alice[i];
      getdataAlice>>max_mass_Alice[i];
      getdataAlice>>min_pdf_Alice[i];
      getdataAlice>>max_pdf_Alice[i];
      getdataAlice>>a55_Alice[i];
      getdataAlice>>a22_Alice[i];
      getdataAlice>>a21_Alice[i];
      getdataAlice>>a12_Alice[i];
      getdataAlice>>a15_Alice[i];
      getdataAlice>>a51_Alice[i];
    }
  for(i=0;i<fo_BIN_NUM;i++)
    {
      getdataAnly>>tem;
      getdataAnly>>a11_Anly[i];
      getdataAnly>>min_all_Anly[i];
      getdataAnly>>max_all_Anly[i];
      getdataAnly>>min_sc_Anly[i];
      getdataAnly>>max_sc_Anly[i];
      getdataAnly>>min_mass_Anly[i];
      getdataAnly>>max_mass_Anly[i];
      getdataAnly>>min_pdf_Anly[i];
      getdataAnly>>max_pdf_Anly[i];
      getdataAnly>>a55_Anly[i];
      getdataAnly>>a22_Anly[i];
      getdataAnly>>a21_Anly[i];
      getdataAnly>>a12_Anly[i];
      getdataAnly>>a15_Anly[i];
      getdataAnly>>a51_Anly[i];
    }
  for(i=0;i<fo_BIN_NUM;i++)
    {
      hptAlice->SetBinContent(i+1,a11_Alice[i]*pdfrac);
      hminallAlice->SetBinContent(i+1,min_all_Alice[i]*pdfrac);
      hmaxallAlice->SetBinContent(i+1,max_all_Alice[i]*pdfrac);
      hpt11Alice->SetBinContent(i+1,a11_Alice[i]*pdfrac);
      hpt55Alice->SetBinContent(i+1,a55_Alice[i]*pdfrac);
      hpt22Alice->SetBinContent(i+1,a22_Alice[i]*pdfrac);
      hpt21Alice->SetBinContent(i+1,a21_Alice[i]*pdfrac);
      hpt12Alice->SetBinContent(i+1,a12_Alice[i]*pdfrac);
      hpt15Alice->SetBinContent(i+1,a15_Alice[i]*pdfrac);
      hpt51Alice->SetBinContent(i+1,a51_Alice[i]*pdfrac);
      hptAnly->SetBinContent(i+1,a11_Anly[i]*pdfrac);
      hpt11Anly->SetBinContent(i+1,a11_Anly[i]*pdfrac);
      hpt55Anly->SetBinContent(i+1,a55_Anly[i]*pdfrac);
      hpt22Anly->SetBinContent(i+1,a22_Anly[i]*pdfrac);
      hpt21Anly->SetBinContent(i+1,a21_Anly[i]*pdfrac);
      hpt12Anly->SetBinContent(i+1,a12_Anly[i]*pdfrac);
      hpt15Anly->SetBinContent(i+1,a15_Anly[i]*pdfrac);
      hpt51Anly->SetBinContent(i+1,a51_Anly[i]*pdfrac);
    }

  //Calculate data weighted ptbin centers
  cout<<"---- Calculate data weighted ptbin centers"<<endl;
  Double_t da_bincenter[da_BIN_NUM];
  Double_t summul=0,sum=0;
  for(i=0;i<da_BIN_NUM;i++)
    {
      summul=0;
      sum=0;
      for(j=da_ptbin[i]*4;j<da_ptbin[i+1]*4;j++)
	{
	  summul+=hptAlice->GetBinContent(j+1)*hptAlice->GetBinCenter(j+1);
	  sum+=hptAlice->GetBinContent(j+1);
	}
      da_bincenter[i] = summul/sum;
    }
  
  //Back up
  TH1F* hptAliceRef=(TH1F*)hptAlice->Clone();
  hptAliceRef->SetName("hptAliceRef");
  TH1F* hptAnlyRef=(TH1F*)hptAnly->Clone();
  hptAnlyRef->SetName("hptAnlyRef");

  Double_t apt[da_BIN_NUM],aptl[da_BIN_NUM],aptlsyst[da_BIN_NUM],aptlscaling[da_BIN_NUM];
  TH1F* hptAlice_rebinalice = (TH1F*)hptAliceRef->Rebin(da_BIN_NUM,"hptAlice_rebinalice",da_ptbin);
  for(i=0;i<da_BIN_NUM;i++)
    {
      apt[i] = hptAlice_rebinalice->GetBinCenter(i+1);
      aptl[i] = hptAlice_rebinalice->GetBinWidth(i+1)/2.;
      aptlsyst[i] = 1./6.;
      aptlscaling[i] = 1./4.;
    }
  
  //Test ALICE results
  if(testAliceData)
    {
      cout<<"---- Test Alice data points"<<endl;
      Double_t asigma[da_BIN_NUM],aerrorl[da_BIN_NUM],aerrorh[da_BIN_NUM],aminall[da_BIN_NUM],amaxall[da_BIN_NUM];
      TH1F* hminallAlice_rebinalice = (TH1F*)hminallAlice->Rebin(da_BIN_NUM,"hminallAlice_rebinalice",da_ptbin);
      TH1F* hmaxallAlice_rebinalice = (TH1F*)hmaxallAlice->Rebin(da_BIN_NUM,"hmaxallAlice_rebinalice",da_ptbin);
      for(i=0;i<da_BIN_NUM;i++)
	{
	  hptAlice_rebinalice->SetBinContent(i+1,hptAlice_rebinalice->GetBinContent(i+1)/(hptAlice_rebinalice->GetBinWidth(i+1)*4));
	  asigma[i]=hptAlice_rebinalice->GetBinContent(i+1);
	  hminallAlice_rebinalice->SetBinContent(i+1,hminallAlice_rebinalice->GetBinContent(i+1)/(hminallAlice_rebinalice->GetBinWidth(i+1)*4));
	  aminall[i]=hminallAlice_rebinalice->GetBinContent(i+1);
	  hmaxallAlice_rebinalice->SetBinContent(i+1,hmaxallAlice_rebinalice->GetBinContent(i+1)/(hmaxallAlice_rebinalice->GetBinWidth(i+1)*4));
	  amaxall[i]=hmaxallAlice_rebinalice->GetBinContent(i+1);
	  aerrorl[i] = asigma[i]-aminall[i];
	  aerrorh[i] = amaxall[i]-asigma[i];
	}
      TCanvas* cReproduceAlice = new TCanvas("cReproduceAlice","",600,600);
      cReproduceAlice->SetLogy();
      TH2F* hempty_cReproduceAlice = new TH2F("hempty_cReproduceAlice","",10,0,25.,10.,0.006,1.e+3);
      hempty_cReproduceAlice->SetStats(0);
      hempty_cReproduceAlice->GetXaxis()->SetTitle("p_{t} (GeV/c)");
      hempty_cReproduceAlice->GetYaxis()->SetTitle("d#sigma(D^{0})/dp_{T}(pb GeV-1c)");
      hempty_cReproduceAlice->GetXaxis()->SetTitleOffset(1.);
      hempty_cReproduceAlice->GetYaxis()->SetTitleOffset(.9);
      hempty_cReproduceAlice->GetXaxis()->SetTitleSize(0.045);
      hempty_cReproduceAlice->GetYaxis()->SetTitleSize(0.045);
      hempty_cReproduceAlice->GetXaxis()->SetTitleFont(42);
      hempty_cReproduceAlice->GetYaxis()->SetTitleFont(42);
      hempty_cReproduceAlice->GetXaxis()->SetLabelFont(42);
      hempty_cReproduceAlice->GetYaxis()->SetLabelFont(42);
      hempty_cReproduceAlice->GetXaxis()->SetLabelSize(0.04);
      hempty_cReproduceAlice->GetYaxis()->SetLabelSize(0.04);  
      hempty_cReproduceAlice->Draw();
      TGraphAsymmErrors* gAliceFONLL = new TGraphAsymmErrors(da_BIN_NUM, apt, asigma, aptl, aptl, aerrorl, aerrorh);
      gAliceFONLL->SetFillColor(kRed);
      gAliceFONLL->SetFillStyle(3002);
      gAliceFONLL->SetLineWidth(2.);
      gAliceFONLL->SetLineColor(kRed);
      gAliceFONLL->Draw("5same");
      TGraphAsymmErrors* gAliceSyst = new TGraphAsymmErrors(da_BIN_NUM, apt, da_cs, aptlsyst, aptlsyst, da_syst_dw, da_syst_up);
      gAliceSyst->SetFillColor(0);
      gAliceSyst->SetFillStyle(0);
      gAliceSyst->SetLineWidth(2.);
      gAliceSyst->SetLineColor(kBlack);
      gAliceSyst->Draw("5same");
      TGraphAsymmErrors* gAliceStat = new TGraphAsymmErrors(da_BIN_NUM, apt, da_cs, aptl, aptl, da_stat, da_stat);
      gAliceStat->SetMarkerStyle(21);
      gAliceStat->SetMarkerColor(kBlack);
      gAliceStat->SetLineWidth(2);
      gAliceStat->SetLineColor(kBlack);
      gAliceStat->Draw("psame");
      cReproduceAlice->SaveAs(Form("plots/%s/reproduceAlice.pdf",rapi.Data()));
    }

  cout<<"---- Rebin into data ptbins"<<endl;
  TH1F* hpt11Alice_rebin = (TH1F*)hpt11Alice->Rebin(da_BIN_NUM,"hpt11Alice_rebin",da_ptbin);
  TH1F* hpt55Alice_rebin = (TH1F*)hpt55Alice->Rebin(da_BIN_NUM,"hpt55Alice_rebin",da_ptbin);
  TH1F* hpt22Alice_rebin = (TH1F*)hpt22Alice->Rebin(da_BIN_NUM,"hpt22Alice_rebin",da_ptbin);
  TH1F* hpt21Alice_rebin = (TH1F*)hpt21Alice->Rebin(da_BIN_NUM,"hpt21Alice_rebin",da_ptbin);
  TH1F* hpt12Alice_rebin = (TH1F*)hpt12Alice->Rebin(da_BIN_NUM,"hpt12Alice_rebin",da_ptbin);
  TH1F* hpt15Alice_rebin = (TH1F*)hpt15Alice->Rebin(da_BIN_NUM,"hpt15Alice_rebin",da_ptbin);
  TH1F* hpt51Alice_rebin = (TH1F*)hpt51Alice->Rebin(da_BIN_NUM,"hpt51Alice_rebin",da_ptbin);
  TH1F* hpt11Anly_rebin = (TH1F*)hpt11Anly->Rebin(da_BIN_NUM,"hpt11Anly_rebin",da_ptbin);
  TH1F* hpt55Anly_rebin = (TH1F*)hpt55Anly->Rebin(da_BIN_NUM,"hpt55Anly_rebin",da_ptbin);
  TH1F* hpt22Anly_rebin = (TH1F*)hpt22Anly->Rebin(da_BIN_NUM,"hpt22Anly_rebin",da_ptbin);
  TH1F* hpt21Anly_rebin = (TH1F*)hpt21Anly->Rebin(da_BIN_NUM,"hpt21Anly_rebin",da_ptbin);
  TH1F* hpt12Anly_rebin = (TH1F*)hpt12Anly->Rebin(da_BIN_NUM,"hpt12Anly_rebin",da_ptbin);
  TH1F* hpt15Anly_rebin = (TH1F*)hpt15Anly->Rebin(da_BIN_NUM,"hpt15Anly_rebin",da_ptbin);
  TH1F* hpt51Anly_rebin = (TH1F*)hpt51Anly->Rebin(da_BIN_NUM,"hpt51Anly_rebin",da_ptbin);

  //Calculate ratios and errors with different sets of scaling
  cout<<"---- Calculate ratios and errors with different sets of scaling"<<endl;
  TH1F* hratio11_rebin = (TH1F*)hpt11Anly_rebin->Clone();  hratio11_rebin->SetName("hratio11_rebin");  hratio11_rebin->Divide(hpt11Alice_rebin);  Double_t aratio11[da_BIN_NUM];
  TH1F* hratio55_rebin = (TH1F*)hpt55Anly_rebin->Clone();  hratio55_rebin->SetName("hratio55_rebin");  hratio55_rebin->Divide(hpt55Alice_rebin);  Double_t aratio55[da_BIN_NUM];
  TH1F* hratio22_rebin = (TH1F*)hpt22Anly_rebin->Clone();  hratio22_rebin->SetName("hratio22_rebin");  hratio22_rebin->Divide(hpt22Alice_rebin);  Double_t aratio22[da_BIN_NUM];
  TH1F* hratio21_rebin = (TH1F*)hpt21Anly_rebin->Clone();  hratio21_rebin->SetName("hratio21_rebin");  hratio21_rebin->Divide(hpt21Alice_rebin);  Double_t aratio21[da_BIN_NUM];
  TH1F* hratio12_rebin = (TH1F*)hpt12Anly_rebin->Clone();  hratio12_rebin->SetName("hratio12_rebin");  hratio12_rebin->Divide(hpt12Alice_rebin);  Double_t aratio12[da_BIN_NUM];
  TH1F* hratio15_rebin = (TH1F*)hpt15Anly_rebin->Clone();  hratio15_rebin->SetName("hratio15_rebin");  hratio15_rebin->Divide(hpt15Alice_rebin);  Double_t aratio15[da_BIN_NUM];
  TH1F* hratio51_rebin = (TH1F*)hpt51Anly_rebin->Clone();  hratio51_rebin->SetName("hratio51_rebin");  hratio51_rebin->Divide(hpt51Alice_rebin);  Double_t aratio51[da_BIN_NUM];
  Double_t aratioErrup[da_BIN_NUM], aratioErrdw[da_BIN_NUM];

  for(i=0;i<da_BIN_NUM;i++)
    {
      Double_t sortup=-1,sortdw=10000;
      aratio11[i] = hratio11_rebin->GetBinContent(i+1);  if(aratio11[i]>sortup){sortup=aratio11[i];}  if(aratio11[i]<sortdw){sortdw=aratio11[i];}
      aratio55[i] = hratio55_rebin->GetBinContent(i+1);  if(aratio55[i]>sortup){sortup=aratio55[i];}  if(aratio55[i]<sortdw){sortdw=aratio55[i];}
      aratio22[i] = hratio22_rebin->GetBinContent(i+1);  if(aratio22[i]>sortup){sortup=aratio22[i];}  if(aratio22[i]<sortdw){sortdw=aratio22[i];}
      aratio21[i] = hratio21_rebin->GetBinContent(i+1);  if(aratio21[i]>sortup){sortup=aratio21[i];}  if(aratio21[i]<sortdw){sortdw=aratio21[i];}
      aratio12[i] = hratio12_rebin->GetBinContent(i+1);  if(aratio12[i]>sortup){sortup=aratio12[i];}  if(aratio12[i]<sortdw){sortdw=aratio12[i];}
      aratio15[i] = hratio15_rebin->GetBinContent(i+1);  if(aratio15[i]>sortup){sortup=aratio15[i];}  if(aratio15[i]<sortdw){sortdw=aratio15[i];}
      aratio51[i] = hratio51_rebin->GetBinContent(i+1);  if(aratio51[i]>sortup){sortup=aratio51[i];}  if(aratio51[i]<sortdw){sortdw=aratio51[i];}
      aratioErrup[i] = sortup-aratio11[i];
      aratioErrdw[i] = aratio11[i]-sortdw;
    }
  TGraph* gratio11 = new TGraph(da_BIN_NUM,da_ptctr,aratio11);
  TGraph* gratio55 = new TGraph(da_BIN_NUM,da_ptctr,aratio55);
  TGraph* gratio22 = new TGraph(da_BIN_NUM,da_ptctr,aratio22);
  TGraph* gratio21 = new TGraph(da_BIN_NUM,da_ptctr,aratio21);
  TGraph* gratio12 = new TGraph(da_BIN_NUM,da_ptctr,aratio12);
  TGraph* gratio15 = new TGraph(da_BIN_NUM,da_ptctr,aratio15);
  TGraph* gratio51 = new TGraph(da_BIN_NUM,da_ptctr,aratio51);

  cout<<"  -- Plot FONLL ratio center values"<<endl;
  TCanvas* ccenterRatio = new TCanvas("ccenterRatio","",700,500);
  TH2F* hempty_ccenterRatio = new TH2F("hempty_ccenterRatio","",10,0,17.,10.,0.2,2.2);
  hempty_ccenterRatio->SetStats(0);
  hempty_ccenterRatio->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hempty_ccenterRatio->GetYaxis()->SetTitle("#sigma(2.76TeV,|y|<1)/#sigma(7TeV.|y|<0.5)");
  hempty_ccenterRatio->GetXaxis()->SetTitleOffset(1.);
  hempty_ccenterRatio->GetYaxis()->SetTitleOffset(.9);
  hempty_ccenterRatio->GetXaxis()->SetTitleSize(0.045);
  hempty_ccenterRatio->GetYaxis()->SetTitleSize(0.045);
  hempty_ccenterRatio->GetXaxis()->SetTitleFont(42);
  hempty_ccenterRatio->GetYaxis()->SetTitleFont(42);
  hempty_ccenterRatio->GetXaxis()->SetLabelFont(42);
  hempty_ccenterRatio->GetYaxis()->SetLabelFont(42);
  hempty_ccenterRatio->GetXaxis()->SetLabelSize(0.04);
  hempty_ccenterRatio->GetYaxis()->SetLabelSize(0.04);
  hempty_ccenterRatio->Draw();
  gratio11->SetLineColor(1);   gratio11->SetLineWidth(2);  gratio11->Draw("lsame");
  ccenterRatio->SaveAs(Form("plots/%s/cratioCenter.pdf",rapi.Data()));

  cout<<"  -- Plot FONLL ratios with different sets of scaling"<<endl;  
  TCanvas* ccompareRatio = new TCanvas("ccompareRatio","",700,500);
  TH2F* hempty_ccompareRatio = new TH2F("hempty_ccompareRatio","",10,0,17.,10.,0.2,2.2);
  hempty_ccompareRatio->SetStats(0);
  hempty_ccompareRatio->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hempty_ccompareRatio->GetYaxis()->SetTitle("#sigma(2.76TeV,|y|<1)/#sigma(7TeV.|y|<0.5)");
  hempty_ccompareRatio->GetXaxis()->SetTitleOffset(1.);
  hempty_ccompareRatio->GetYaxis()->SetTitleOffset(.9);
  hempty_ccompareRatio->GetXaxis()->SetTitleSize(0.045);
  hempty_ccompareRatio->GetYaxis()->SetTitleSize(0.045);
  hempty_ccompareRatio->GetXaxis()->SetTitleFont(42);
  hempty_ccompareRatio->GetYaxis()->SetTitleFont(42);
  hempty_ccompareRatio->GetXaxis()->SetLabelFont(42);
  hempty_ccompareRatio->GetYaxis()->SetLabelFont(42);
  hempty_ccompareRatio->GetXaxis()->SetLabelSize(0.04);
  hempty_ccompareRatio->GetYaxis()->SetLabelSize(0.04);
  hempty_ccompareRatio->Draw();
  TGraphAsymmErrors* gratioGlobal = new TGraphAsymmErrors(da_BIN_NUM, apt, aratio11, aptl, aptl, aratioErrdw, aratioErrup);
  gratioGlobal->SetFillStyle(1001);
  gratioGlobal->SetFillColor(kYellow-9);
  gratioGlobal->Draw("2same");
  gratio11->SetLineColor(1);   gratio11->SetLineWidth(2);  gratio11->Draw("lsame");
  gratio55->SetLineColor(3);   gratio55->SetLineWidth(2);  gratio55->Draw("lsame");
  gratio22->SetLineColor(9);   gratio22->SetLineWidth(2);  gratio22->Draw("lsame");
  gratio21->SetLineColor(47);  gratio21->SetLineWidth(2);  gratio21->Draw("lsame");
  gratio12->SetLineColor(6);   gratio12->SetLineWidth(2);  gratio12->Draw("lsame");
  gratio15->SetLineColor(7);   gratio15->SetLineWidth(2);  gratio15->Draw("lsame");
  gratio51->SetLineColor(43);  gratio51->SetLineWidth(2);  gratio51->Draw("lsame");
  TLegend* legratioScaling = new TLegend(0.60,0.50,0.80,0.89);
  legratioScaling->SetFillColor(0);
  legratioScaling->SetBorderSize(0);
  legratioScaling->AddEntry((TObject*)0,"#mu_{F}/#mu_{0}  #mu_{R}/#mu_{0}","");
  legratioScaling->AddEntry(gratio11,"  1       1","l");
  legratioScaling->AddEntry(gratio55," 0.5     0.5","l");
  legratioScaling->AddEntry(gratio22,"  2       2","l");
  legratioScaling->AddEntry(gratio21,"  2       1","l");
  legratioScaling->AddEntry(gratio12,"  1       2","l");
  legratioScaling->AddEntry(gratio15,"  1      0.5","l");
  legratioScaling->AddEntry(gratio51," 0.5      1","l");
  legratioScaling->Draw("same");
  ccompareRatio->SaveAs(Form("plots/%s/cratioGlobal.pdf",rapi.Data()));

  //Plot global relative FONLL ratio errors
  cout<<"  -- Plot global relative FONLL ratio errors"<<endl;
  Double_t aratioRela[da_BIN_NUM],aratioErrdwRela[da_BIN_NUM],aratioErrupRela[da_BIN_NUM];
  for(i=0;i<da_BIN_NUM;i++)
    {
      aratioRela[i] = 0;
      aratioErrdwRela[i] = aratioErrdw[i]/aratio11[i];
      aratioErrupRela[i] = aratioErrup[i]/aratio11[i];
    }
  TCanvas* cratioRela = new TCanvas("cratioRela","",700,500);
  cratioRela->SetGrid();
  TH2F* hempty_cratioRela = new TH2F("hempty_cratioRela","",10,1,16.,10.,-1,1);
  hempty_cratioRela->SetStats(0);
  hempty_cratioRela->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hempty_cratioRela->GetYaxis()->SetTitle("#sigma(2.76TeV,|y|<1.)/#sigma(7TeV,|y|<0.5) Relative unc.");
  hempty_cratioRela->GetXaxis()->SetTitleOffset(1.);
  hempty_cratioRela->GetYaxis()->SetTitleOffset(.9);
  hempty_cratioRela->GetXaxis()->SetTitleSize(0.045);
  hempty_cratioRela->GetYaxis()->SetTitleSize(0.045);
  hempty_cratioRela->GetXaxis()->SetTitleFont(42);
  hempty_cratioRela->GetYaxis()->SetTitleFont(42);
  hempty_cratioRela->GetXaxis()->SetLabelFont(42);
  hempty_cratioRela->GetYaxis()->SetLabelFont(42);
  hempty_cratioRela->GetXaxis()->SetLabelSize(0.04);
  hempty_cratioRela->GetYaxis()->SetLabelSize(0.04);
  hempty_cratioRela->Draw();
  TGraphAsymmErrors* gratioRela = new TGraphAsymmErrors(da_BIN_NUM, apt, aratioRela, aptl, aptl, aratioErrdwRela, aratioErrupRela);
  gratioRela->SetFillStyle(3001);
  gratioRela->SetFillColor(8);
  gratioRela->Draw("2same");
  cratioRela->SaveAs(Form("plots/%s/cratioRela.pdf",rapi.Data()));

  //Scale ALICE data points and propagate uncertainties
  cout<<"---- Scale ALice data center values and propagate uncertainties"<<endl;
  Double_t acrosssec[da_BIN_NUM],aminErr[da_BIN_NUM],amaxErr[da_BIN_NUM],aminErrrel[da_BIN_NUM],amaxErrrel[da_BIN_NUM],aminErrsyst[da_BIN_NUM],amaxErrsyst[da_BIN_NUM],aminErrstat[da_BIN_NUM],amaxErrstat[da_BIN_NUM],aminErrscaling[da_BIN_NUM],amaxErrscaling[da_BIN_NUM];
  for(i=0;i<da_BIN_NUM;i++)
    {
      acrosssec[i] = da_cs[i]*aratio11[i];
      aminErr[i] = acrosssec[i]*TMath::Sqrt((da_syst_dw[i]*da_syst_dw[i]+da_stat[i]*da_stat[i])/(da_cs[i]*da_cs[i])
					  + aratioErrdwRela[i]*aratioErrdwRela[i]);
      aminErrrel[i] = aminErr[i]/acrosssec[i];
      amaxErr[i] = acrosssec[i]*TMath::Sqrt((da_syst_up[i]*da_syst_up[i]+da_stat[i]*da_stat[i])/(da_cs[i]*da_cs[i])
					  + aratioErrupRela[i]*aratioErrupRela[i]);
      amaxErrrel[i] = amaxErr[i]/acrosssec[i];
      aminErrsyst[i] = acrosssec[i]*(da_syst_dw[i]/da_cs[i]);
      amaxErrsyst[i] = acrosssec[i]*(da_syst_up[i]/da_cs[i]);
      aminErrstat[i] = acrosssec[i]*(da_stat[i]/da_cs[i]);
      amaxErrstat[i] = acrosssec[i]*(da_stat[i]/da_cs[i]);
      aminErrscaling[i] = acrosssec[i]*aratioErrdwRela[i];
      amaxErrscaling[i] = acrosssec[i]*aratioErrupRela[i];
    }
  cout<<"---- Plot scaled data with different components of uncertainties"<<endl;
  TCanvas* cErrors = new TCanvas("cErrors","",500,500);
  cErrors->SetLogy();
  TH2F* hempty_cErrors = new TH2F("hempty_cErrors","",10,0,17.,10.,1.e-2,1.e+3);
  hempty_cErrors->SetStats(0);
  hempty_cErrors->GetXaxis()->SetTitle("p_{t} (GeV/c)");
  hempty_cErrors->GetYaxis()->SetTitle("d#sigma(D^{0})/dp_{T}(#mub GeV-1c)");
  hempty_cErrors->GetXaxis()->SetTitleOffset(1.);
  hempty_cErrors->GetYaxis()->SetTitleOffset(.9);
  hempty_cErrors->GetXaxis()->SetTitleSize(0.045);
  hempty_cErrors->GetYaxis()->SetTitleSize(0.045);
  hempty_cErrors->GetXaxis()->SetTitleFont(42);
  hempty_cErrors->GetYaxis()->SetTitleFont(42);
  hempty_cErrors->GetXaxis()->SetLabelFont(42);
  hempty_cErrors->GetYaxis()->SetLabelFont(42);
  hempty_cErrors->GetXaxis()->SetLabelSize(0.04);
  hempty_cErrors->GetYaxis()->SetLabelSize(0.04);
  hempty_cErrors->Draw();
  for(i=0;i<da_BIN_NUM;i++)
   {
     aptlscaling[i] = 1./3.;
   }
  TGraphAsymmErrors* gErrScaling = new TGraphAsymmErrors(da_BIN_NUM, da_ptctr, acrosssec, aptlscaling, aptlscaling, aminErrscaling, amaxErrscaling); gErrScaling->SetName("gErrScaling");
  gErrScaling->SetLineWidth(0);
  gErrScaling->SetFillStyle(1001);
  gErrScaling->SetFillColor(kMagenta-7);
  gErrScaling->Draw("2same");
  TGraphAsymmErrors* gErrTotal = new TGraphAsymmErrors(da_BIN_NUM, da_ptctr, acrosssec, aptl, aptl, aminErr, amaxErr);
  gErrTotal->SetFillStyle(0);
  gErrTotal->SetLineColor(kMagenta+2);
  gErrTotal->SetLineWidth(2);
  gErrTotal->Draw("5same");
  TGraphAsymmErrors* gErrSyst = new TGraphAsymmErrors(da_BIN_NUM, da_ptctr, acrosssec, aptlsyst, aptlsyst, aminErrsyst, amaxErrsyst);
  gErrSyst->SetFillStyle(0);
  gErrSyst->SetLineColor(kAzure-2);
  gErrSyst->SetLineWidth(2.);
  gErrSyst->Draw("5same");
  TGraphAsymmErrors* gErrStat = new TGraphAsymmErrors(da_BIN_NUM, da_ptctr, acrosssec, aptl, aptl, aminErrstat, amaxErrstat);
  gErrStat->SetMarkerSize(0);
  gErrStat->SetLineColor(kAzure-2);
  gErrStat->SetLineWidth(2.);
  gErrStat->Draw("psame");
  TGraph* gErr = new TGraph(da_BIN_NUM, da_ptctr, acrosssec);
  gErr->SetMarkerStyle(20);
  gErr->SetMarkerSize(1.);
  gErr->SetMarkerColor(kMagenta+2);
  gErr->Draw("psame");
  TLegend* legErrors = new TLegend(0.60,0.70,0.90,0.90);
  legErrors->SetFillColor(0);
  legErrors->SetBorderSize(0);
  legErrors->AddEntry(gErrTotal,"Total unc.","f");
  legErrors->AddEntry(gErrSyst,"Data syst. unc.","f");
  legErrors->AddEntry(gErrStat,"Data stat. unc.","lep");
  legErrors->AddEntry(gErrScaling,"FONLL scaling unc.","f");
  legErrors->Draw("same");
  cErrors->SaveAs(Form("plots/%s/cErrors.pdf",rapi.Data()));

  //Print out scaled data points center values and total uncert.
  cout<<"---- Print out scaled data points center values and total uncert."<<endl;
  Int_t q=0;
  cout<<endl;
  cout<<"  -- Scaled reference before rebin"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"pT bins[]";
  cout<<" = {";
  for(q=0;q<da_BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      TString sptbin = Form("(%.1f,%.1f)",da_ptbin[q],da_ptbin[q+1]);
      cout<<setiosflags(std::ios::left)<<setw(12)<<sptbin;
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Center value[]";
  cout<<" = {";
  for(q=0;q<da_BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      cout<<setiosflags(std::ios::left)<<setw(12)<<acrosssec[q];
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Up errors[]";
  cout<<" = {";
  for(q=0;q<da_BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      cout<<setiosflags(std::ios::left)<<setw(12)<<amaxErr[q];
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Relative Up errors[]";
  cout<<" = {";
  for(q=0;q<da_BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      TString percsign = "%";
      TString sperc = Form("%.2f%s",amaxErrrel[q]*100.,percsign.Data());
      cout<<setiosflags(std::ios::left)<<setw(12)<<sperc;
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Dw errors[]";
  cout<<" = {";
  for(q=0;q<da_BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      cout<<setiosflags(std::ios::left)<<setw(12)<<aminErr[q];
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Relative Dw errors[]";
  cout<<" = {";
  for(q=0;q<da_BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      TString percsign = "%";
      TString sperc = Form("%.2f%s",aminErrrel[q]*100.,percsign.Data());
      cout<<setiosflags(std::ios::left)<<setw(12)<<sperc;
    }
  cout<<"};"<<endl;
  cout<<endl;

  //Plot and fit scaled data points
  cout<<"---- Plot and fit scaled data"<<endl;
  cout<<"  -- Plot scaled data with total uncertainty"<<endl;
  Double_t iexl[da_BIN_NUM],iexr[da_BIN_NUM];
  for(i=0;i<da_BIN_NUM;i++)
    {
      iexl[i] = da_bincenter[i]-da_ptbin[i];
      iexr[i] = da_ptbin[i+1]-da_bincenter[i];
    }
  TGraphAsymmErrors* gcrosssec_rescaled = new TGraphAsymmErrors(da_BIN_NUM, da_bincenter, acrosssec, iexl, iexr, aminErr, amaxErr);
  gcrosssec_rescaled->SetMarkerStyle(20);
  gcrosssec_rescaled->SetMarkerSize(0.7);
  gcrosssec_rescaled->SetMarkerColor(kBlack);
  gcrosssec_rescaled->SetLineWidth(2);
  gcrosssec_rescaled->SetLineColor(kBlack);
  TCanvas* crescaled =  new TCanvas("crescaled","",400,400);
  crescaled->SetLogy();
  TH2F* hempty_crescaled=new TH2F("hempty_crescaled","",10,0,20.,10.,1.e-2,1.e+3);
  hempty_crescaled->SetStats(0);
  hempty_crescaled->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hempty_crescaled->GetYaxis()->SetTitle("Scaled d#sigma(D^{0})/dp_{T}(#mub GeV-1c)");
  hempty_crescaled->GetXaxis()->SetTitleOffset(1.);
  hempty_crescaled->GetYaxis()->SetTitleOffset(.9);
  hempty_crescaled->GetXaxis()->SetTitleSize(0.045);
  hempty_crescaled->GetYaxis()->SetTitleSize(0.045);
  hempty_crescaled->GetXaxis()->SetTitleFont(42);
  hempty_crescaled->GetYaxis()->SetTitleFont(42);
  hempty_crescaled->GetXaxis()->SetLabelFont(42);
  hempty_crescaled->GetYaxis()->SetLabelFont(42);
  hempty_crescaled->GetXaxis()->SetLabelSize(0.04);
  hempty_crescaled->GetYaxis()->SetLabelSize(0.04);
  hempty_crescaled->Draw();
  gcrosssec_rescaled->Draw("psame");
  TLegend* legcrosssec_rescaled = new TLegend(0.60,0.80,0.90,0.90);
  legcrosssec_rescaled->SetFillColor(0);
  legcrosssec_rescaled->SetBorderSize(0);
  legcrosssec_rescaled->AddEntry(gcrosssec_rescaled,"Total unc.","lep");
  legcrosssec_rescaled->Draw("same");

  //Fit scaled data points
  cout<<"  -- Fit scaled data"<<endl;
  TF1* fdata = new TF1("fdata","pow(10,[0]*exp([1]*x)+[2])",da_ptbin[0],da_ptbin[da_BIN_NUM]);
  //fdata->SetParameter(1,-0.055);
  fdata->SetParLimits(1,-0.100,-0.055);
  fdata->SetParLimits(0,5.,8.);
  fdata->SetParLimits(2,-4.,-2.);

  //TF1* fdata = new TF1("fdata","pow(10,[0]*exp([1]*x)+[2])",da_ptbin[0],da_ptbin[da_BIN_NUM]);
  //fdata->SetParLimits(1,-0.070,-0.055);
  //fdata->SetParLimits(0,5.,7.);
  //fdata->SetParLimits(2,-4.,-3.);

  //TF1* fdata = new TF1("fdata"," exp([1]+[2]*x+[3]*x*x+[4]*x*x*x)",da_ptbin[0],da_ptbin[da_BIN_NUM]);
  //fdata->SetParameter(1,6.91);
  //fdata->SetParameter(2,-0.72);
  //fdata->SetParLimits(3,-0.01,0.008);
  //fdata->SetParLimits(4,0.0008,0.0012);
  gcrosssec_rescaled->Fit("fdata","q","",da_ptbin[1],da_ptbin[da_BIN_NUM]);
  cout<<fdata->GetParameter(0)<<"  "<<fdata->GetParameter(1)<<"  "<<fdata->GetParameter(2)<<"  "<<fdata->GetParameter(3)<<endl;
  crescaled->SaveAs(Form("plots/%s/rescaled.pdf",rapi.Data()));

  //Rebin into 2.76TeV PbPb ptbins
  cout<<"---- Rebin into 2.76TeV PbPb ptbins"<<endl;
  TH1F* hfitref = new TH1F("hfitref","",BIN_NUM,ptbin);
  TH1F* hfitreffitDoublecheck = new TH1F("hfitreffitDoublecheck","",da_BIN_NUM,da_ptbin);
  Double_t integ;
  Double_t afinalsc[BIN_NUM],afinapt[BIN_NUM],afinaptl[BIN_NUM];
  Double_t afinalupWeighted[BIN_NUM],afinaldwWeighted[BIN_NUM],afinaluprelWeighted[BIN_NUM],afinaldwrelWeighted[BIN_NUM];
  Double_t afinalupUnWeighted[BIN_NUM],afinaldwUnWeighted[BIN_NUM],afinaluprelUnWeighted[BIN_NUM],afinaldwrelUnWeighted[BIN_NUM];
  Double_t afitDoublecheck[da_BIN_NUM];

  //Calculate error rebin fraction
  cout<<"  -- Calculate error rebin fraction"<<endl;
  Double_t afracWeighted[BIN_NUM][COB_NUM],afracUnWeighted[BIN_NUM][COB_NUM];
  for(i=0;i<BIN_NUM;i++)
    {
      for(j=0;j<COB_NUM;j++)
	{
	  afracWeighted[i][j]=0;
	  afracUnWeighted[i][j]=0;
	}
    }
  for(i=0;i<BIN_NUM;i++)
    {
      for(j=0;j<COB_NUM;j++)
	{
	  if(ind[i][j]>-1)
	    {
	      afracWeighted[i][j] = fdata->Integral(lowridge[i][j],highridge[i][j]) / fdata->Integral(ptbin[i],ptbin[i+1]);
	      afracUnWeighted[i][j] = (highridge[i][j]-lowridge[i][j]) / (ptbin[i+1]-ptbin[i]);
	    }
	}
    }
  cout<<"  -- Rebin center value by fitting function"<<endl;
  cout<<"  -- Rebin uncertainties by statistic weight"<<endl;
  for(i=0;i<da_BIN_NUM;i++)
    {
      integ = fdata->Integral(da_ptbin[i],da_ptbin[i+1])/hfitreffitDoublecheck->GetBinWidth(i+1);
      afitDoublecheck[i] = integ/acrosssec[i];
    }
  TGraph* gfitDoublecheck = new TGraph(da_BIN_NUM,da_ptctr,afitDoublecheck);  
  TCanvas* cfitDoublecheck = new TCanvas("cfitDoublecheck","",500,500);
  TH2F* hempty_cfitDoublecheck = new TH2F("hempty_cfitDoublecheck","",10,0,17.,10.,0.2,2.2);
  hempty_cfitDoublecheck->SetStats(0);
  hempty_cfitDoublecheck->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hempty_cfitDoublecheck->GetYaxis()->SetTitle("#sigma(scaled data)/#sigma(rebin by fit)");
  hempty_cfitDoublecheck->GetXaxis()->SetTitleOffset(1.);
  hempty_cfitDoublecheck->GetYaxis()->SetTitleOffset(.9);
  hempty_cfitDoublecheck->GetXaxis()->SetTitleSize(0.045);
  hempty_cfitDoublecheck->GetYaxis()->SetTitleSize(0.045);
  hempty_cfitDoublecheck->GetXaxis()->SetTitleFont(42);
  hempty_cfitDoublecheck->GetYaxis()->SetTitleFont(42);
  hempty_cfitDoublecheck->GetXaxis()->SetLabelFont(42);
  hempty_cfitDoublecheck->GetYaxis()->SetLabelFont(42);
  hempty_cfitDoublecheck->GetXaxis()->SetLabelSize(0.04);
  hempty_cfitDoublecheck->GetYaxis()->SetLabelSize(0.04);
  hempty_cfitDoublecheck->Draw();
  gfitDoublecheck->SetMarkerStyle(2);   gfitDoublecheck->SetMarkerSize(2);  gfitDoublecheck->Draw("psame");
  cfitDoublecheck->SaveAs(Form("plots/%s/cfitDoublecheck.pdf",rapi.Data()));


  for(i=0;i<BIN_NUM;i++)
    {
      integ = fdata->Integral(ptbin[i],ptbin[i+1])/hfitref->GetBinWidth(i+1);
      afinalsc[i] = integ;
      hfitref->SetBinContent(i+1,integ);
      afinalupWeighted[i]=0;  afinalupUnWeighted[i]=0;
      afinaldwWeighted[i]=0;  afinaldwUnWeighted[i]=0;
      for(j=0;j<COB_NUM;j++)
	{
	  if(ind[i][j]<0) continue;
	  afinaldwrelWeighted[i]+=aminErrrel[ind[i][j]]*afracWeighted[i][j];
	  afinaldwWeighted[i] = afinaldwrelWeighted[i]*afinalsc[i];
	  afinaluprelWeighted[i]+=amaxErrrel[ind[i][j]]*afracWeighted[i][j];
	  afinalupWeighted[i] = afinaluprelWeighted[i]*afinalsc[i];
	  afinaldwrelUnWeighted[i]+=aminErrrel[ind[i][j]]*afracUnWeighted[i][j];
	  afinaldwUnWeighted[i] = afinaldwrelUnWeighted[i]*afinalsc[i];
	  afinaluprelUnWeighted[i]+=amaxErrrel[ind[i][j]]*afracUnWeighted[i][j];
	  afinalupUnWeighted[i] = afinaluprelUnWeighted[i]*afinalsc[i];
	}
      afinapt[i] = hfitref->GetBinCenter(i+1);
      afinaptl[i] = hfitref->GetBinWidth(i+1)/2.;
    }



  //Print out 2.76TeV data-driven pp reference values
  cout<<"---- Print out 2.76TeV data-driven pp reference results"<<endl;
  cout<<endl;
  //weighted
  cout<<"  -- Final reference after rebin"<<endl;
  if(displayAreaUnweighted) cout<<"  -- Area Weighted"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"pT bins[]";
  cout<<" = {";
  for(q=0;q<BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      TString sptbin = Form("(%.1f,%.1f)",ptbin[q],ptbin[q+1]);
      cout<<setiosflags(std::ios::left)<<setw(12)<<sptbin;
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Center value[]";
  cout<<" = {";
  for(q=0;q<BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      cout<<setiosflags(std::ios::left)<<setw(12)<<afinalsc[q];
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Up errors[]";
  cout<<" = {";
  for(q=0;q<BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      cout<<setiosflags(std::ios::left)<<setw(12)<<afinalupWeighted[q];
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Relative Up errors[]";
  cout<<" = {";
  for(q=0;q<BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      TString percsign = "%";
      TString sperc = Form("%.2f%s",afinaluprelWeighted[q]*100,percsign.Data());
      cout<<setiosflags(std::ios::left)<<setw(12)<<sperc;
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Dw errors[]";
  cout<<" = {";
  for(q=0;q<BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      cout<<setiosflags(std::ios::left)<<setw(12)<<afinaldwWeighted[q];
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Relative Dw errors[]";
  cout<<" = {";
  for(q=0;q<BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      TString percsign = "%";
      TString sperc = Form("%.2f%s",afinaldwrelWeighted[q]*100,percsign.Data());
      cout<<setiosflags(std::ios::left)<<setw(12)<<sperc;
    }
  cout<<"};"<<endl;
  //unweighted
  if(displayAreaUnweighted)
    {
      cout<<"  -- Area UnWeighted"<<endl;
      cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"pT bins[]";
      cout<<" = {";
      for(q=0;q<BIN_NUM;q++)
	{
	  if(q!=0) cout<<", ";
	  TString sptbin = Form("(%.1f,%.1f)",ptbin[q],ptbin[q+1]);
	  cout<<setiosflags(std::ios::left)<<setw(12)<<sptbin;
	}
      cout<<"};"<<endl;
      cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Center value[]";
      cout<<" = {";
      for(q=0;q<BIN_NUM;q++)
	{
	  if(q!=0) cout<<", ";
	  cout<<setiosflags(std::ios::left)<<setw(12)<<afinalsc[q];
	}
      cout<<"};"<<endl;
      cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Up errors[]";
      cout<<" = {";
      for(q=0;q<BIN_NUM;q++)
	{
	  if(q!=0) cout<<", ";
	  cout<<setiosflags(std::ios::left)<<setw(12)<<afinalupUnWeighted[q];
	}
      cout<<"};"<<endl;
      cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Relative Up errors[]";
      cout<<" = {";
      for(q=0;q<BIN_NUM;q++)
	{
	  if(q!=0) cout<<", ";
	  TString percsign = "%";
	  TString sperc = Form("%.2f%s",afinaluprelUnWeighted[q]*100,percsign.Data());
	  cout<<setiosflags(std::ios::left)<<setw(12)<<sperc;
	}
      cout<<"};"<<endl;
      cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Dw errors[]";
      cout<<" = {";
      for(q=0;q<BIN_NUM;q++)
	{
	  if(q!=0) cout<<", ";
	  cout<<setiosflags(std::ios::left)<<setw(12)<<afinaldwUnWeighted[q];
	}
      cout<<"};"<<endl;
      cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Relative Dw errors[]";
      cout<<" = {";
      for(q=0;q<BIN_NUM;q++)
	{
	  if(q!=0) cout<<", ";
	  TString percsign = "%";
	  TString sperc = Form("%.2f%s",afinaldwrelUnWeighted[q]*100,percsign.Data());
	  cout<<setiosflags(std::ios::left)<<setw(12)<<sperc;
	}
      cout<<"};"<<endl;
    }
  cout<<endl;
  
  //Plot 2.76TeV data-driven pp reference
  cout<<"---- Plot rebinned 2.76TeV data-driven pp reference"<<endl;
  TGraphAsymmErrors* gfinalref = new TGraphAsymmErrors(BIN_NUM, afinapt, afinalsc, afinaptl, afinaptl, afinaldwWeighted, afinalupWeighted);
  gfinalref->SetMarkerStyle(20);
  gfinalref->SetMarkerSize(0.7);
  gfinalref->SetMarkerColor(kBlack);
  gfinalref->SetLineWidth(2);
  gfinalref->SetLineColor(kBlack);
  TCanvas* cfinalref = new TCanvas("cfinalref","",400,400);
  cfinalref->SetLogy();
  TH2F* hempty_cfinalref = new TH2F("hempty_cfinalref","",10,0,20.,10.,1.e-2,1.e+3);
  hempty_cfinalref->SetStats(0);
  hempty_cfinalref->GetXaxis()->SetTitle("p_{t} (GeV/c)");
  hempty_cfinalref->GetYaxis()->SetTitle("Fitted d#sigma(D^{0})/dp_{T}(#mub/(GeV/c))");
  hempty_cfinalref->GetXaxis()->SetTitleOffset(1.);
  hempty_cfinalref->GetYaxis()->SetTitleOffset(.9);
  hempty_cfinalref->GetXaxis()->SetTitleSize(0.045);
  hempty_cfinalref->GetYaxis()->SetTitleSize(0.045);
  hempty_cfinalref->GetXaxis()->SetTitleFont(42);
  hempty_cfinalref->GetYaxis()->SetTitleFont(42);
  hempty_cfinalref->GetXaxis()->SetLabelFont(42);
  hempty_cfinalref->GetYaxis()->SetLabelFont(42);
  hempty_cfinalref->GetXaxis()->SetLabelSize(0.04);
  hempty_cfinalref->GetYaxis()->SetLabelSize(0.04);  
  hempty_cfinalref->Draw();
  gfinalref->Draw("psame");
  cfinalref->SaveAs(Form("plots/%s/finalref.pdf",rapi.Data()));
  
  //Plot ratio of data-driven pp reference and pure FONLL
  cout<<"---- Plot ratio of data-driven pp reference and FONLL"<<endl;
  TH1F* hptAnlyRef_rebin = (TH1F*)hptAnlyRef->Rebin(BIN_NUM,"hptAnlyRef_rebin",ptbin);
  for(i=0;i<BIN_NUM;i++)
    {
      hptAnlyRef_rebin->SetBinContent(i+1,hptAnlyRef_rebin->GetBinContent(i+1)/(hptAnlyRef_rebin->GetBinWidth(i+1)*4));      
    }
  Double_t aratiosc[BIN_NUM],aratioup[BIN_NUM],aratiodw[BIN_NUM];
  for(i=0;i<BIN_NUM;i++)
    {
      aratiosc[i] = afinalsc[i]/hptAnlyRef_rebin->GetBinContent(i+1);
      aratioup[i] = afinalupWeighted[i]/hptAnlyRef_rebin->GetBinContent(i+1);
      aratiodw[i] = afinaldwWeighted[i]/hptAnlyRef_rebin->GetBinContent(i+1);
    }
  TGraphAsymmErrors* gratioref = new TGraphAsymmErrors(BIN_NUM, afinapt, aratiosc, afinaptl, afinaptl, aratiodw, aratioup);
  gratioref->SetMarkerStyle(20);
  gratioref->SetMarkerSize(0.7);
  gratioref->SetMarkerColor(kBlack);
  gratioref->SetLineWidth(2);
  gratioref->SetLineColor(kBlack);
  TCanvas* cratioref = new TCanvas("cratioref","",400,400);
  TH2F* hempty_cratioref = new TH2F("hempty_cratioref","",10,0,18.,10.,0.,3.5);
  hempty_cratioref->SetStats(0);
  hempty_cratioref->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hempty_cratioref->GetYaxis()->SetTitle("data/FONLL");
  hempty_cratioref->GetXaxis()->SetTitleOffset(1.);
  hempty_cratioref->GetYaxis()->SetTitleOffset(.9);
  hempty_cratioref->GetXaxis()->SetTitleSize(0.045);
  hempty_cratioref->GetYaxis()->SetTitleSize(0.045);
  hempty_cratioref->GetXaxis()->SetTitleFont(42);
  hempty_cratioref->GetYaxis()->SetTitleFont(42);
  hempty_cratioref->GetXaxis()->SetLabelFont(42);
  hempty_cratioref->GetYaxis()->SetLabelFont(42);
  hempty_cratioref->GetXaxis()->SetLabelSize(0.04);
  hempty_cratioref->GetYaxis()->SetLabelSize(0.04);  
  hempty_cratioref->Draw();
  gratioref->Draw("psame");
  cratioref->SaveAs(Form("plots/%s/ratioref.pdf",rapi.Data()));

  cout<<endl;

}
void OneSidedFrequentistUpperLimitWithBands(const char* infile = "",
                                            const char* workspaceName = "combined",
                                            const char* modelConfigName = "ModelConfig",
                                            const char* dataName = "obsData") {



   double confidenceLevel=0.95;
   int nPointsToScan = 20;
   int nToyMC = 200;

   // -------------------------------------------------------
   // First part is just to access a user-defined file
   // or create the standard example file if it doesn't exist
   const char* filename = "";
   if (!strcmp(infile,"")) {
      filename = "results/example_combined_GaussExample_model.root";
      bool fileExist = !gSystem->AccessPathName(filename); // note opposite return code
      // if file does not exists generate with histfactory
      if (!fileExist) {
#ifdef _WIN32
         cout << "HistFactory file cannot be generated on Windows - exit" << endl;
         return;
#endif
         // Normally this would be run on the command line
         cout <<"will run standard hist2workspace example"<<endl;
         gROOT->ProcessLine(".! prepareHistFactory .");
         gROOT->ProcessLine(".! hist2workspace config/example.xml");
         cout <<"\n\n---------------------"<<endl;
         cout <<"Done creating example input"<<endl;
         cout <<"---------------------\n\n"<<endl;
      }

   }
   else
      filename = infile;

   // Try to open the file
   TFile *file = TFile::Open(filename);

   // if input file was specified byt not found, quit
   if(!file ){
      cout <<"StandardRooStatsDemoMacro: Input file " << filename << " is not found" << endl;
      return;
   }


   // -------------------------------------------------------
   // Now get the data and workspace

   // get the workspace out of the file
   RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
   if(!w){
      cout <<"workspace not found" << endl;
      return;
   }

   // get the modelConfig out of the file
   ModelConfig* mc = (ModelConfig*) w->obj(modelConfigName);

   // get the modelConfig out of the file
   RooAbsData* data = w->data(dataName);

   // make sure ingredients are found
   if(!data || !mc){
      w->Print();
      cout << "data or ModelConfig was not found" <<endl;
      return;
   }

   // -------------------------------------------------------
   // Now get the POI for convenience
   // you may want to adjust the range of your POI

   RooRealVar* firstPOI = (RooRealVar*) mc->GetParametersOfInterest()->first();
   /*  firstPOI->setMin(0);*/
   /*  firstPOI->setMax(10);*/

   // --------------------------------------------
   // Create and use the FeldmanCousins tool
   // to find and plot the 95% confidence interval
   // on the parameter of interest as specified
   // in the model config
   // REMEMBER, we will change the test statistic
   // so this is NOT a Feldman-Cousins interval
   FeldmanCousins fc(*data,*mc);
   fc.SetConfidenceLevel(confidenceLevel);
   /*  fc.AdditionalNToysFactor(0.25); // degrade/improve sampling that defines confidence belt*/
   /*  fc.UseAdaptiveSampling(true); // speed it up a bit, don't use for expected limits*/
   fc.SetNBins(nPointsToScan); // set how many points per parameter of interest to scan
   fc.CreateConfBelt(true); // save the information in the belt for plotting

   // -------------------------------------------------------
   // Feldman-Cousins is a unified limit by definition
   // but the tool takes care of a few things for us like which values
   // of the nuisance parameters should be used to generate toys.
   // so let's just change the test statistic and realize this is
   // no longer "Feldman-Cousins" but is a fully frequentist Neyman-Construction.
   /*  ProfileLikelihoodTestStatModified onesided(*mc->GetPdf());*/
   /*  fc.GetTestStatSampler()->SetTestStatistic(&onesided);*/
   /* ((ToyMCSampler*) fc.GetTestStatSampler())->SetGenerateBinned(true); */
   ToyMCSampler*  toymcsampler = (ToyMCSampler*) fc.GetTestStatSampler();
   ProfileLikelihoodTestStat* testStat = dynamic_cast<ProfileLikelihoodTestStat*>(toymcsampler->GetTestStatistic());
   testStat->SetOneSided(true);

   // Since this tool needs to throw toy MC the PDF needs to be
   // extended or the tool needs to know how many entries in a dataset
   // per pseudo experiment.
   // In the 'number counting form' where the entries in the dataset
   // are counts, and not values of discriminating variables, the
   // datasets typically only have one entry and the PDF is not
   // extended.
   if(!mc->GetPdf()->canBeExtended()){
      if(data->numEntries()==1)
         fc.FluctuateNumDataEntries(false);
      else
         cout <<"Not sure what to do about this model" <<endl;
   }

   // We can use PROOF to speed things along in parallel
   // However, the test statistic has to be installed on the workers
   // so either turn off PROOF or include the modified test statistic
   // in your `$ROOTSYS/roofit/roostats/inc` directory,
   // add the additional line to the LinkDef.h file,
   // and recompile root.
   if (useProof) {
      ProofConfig pc(*w, nworkers, "", false);
      toymcsampler->SetProofConfig(&pc); // enable proof
   }

   if(mc->GetGlobalObservables()){
      cout << "will use global observables for unconditional ensemble"<<endl;
      mc->GetGlobalObservables()->Print();
      toymcsampler->SetGlobalObservables(*mc->GetGlobalObservables());
   }


   // Now get the interval
   PointSetInterval* interval = fc.GetInterval();
   ConfidenceBelt* belt = fc.GetConfidenceBelt();

   // print out the interval on the first Parameter of Interest
   cout << "\n95% interval on " <<firstPOI->GetName()<<" is : ["<<
      interval->LowerLimit(*firstPOI) << ", "<<
      interval->UpperLimit(*firstPOI) <<"] "<<endl;

   // get observed UL and value of test statistic evaluated there
   RooArgSet tmpPOI(*firstPOI);
   double observedUL = interval->UpperLimit(*firstPOI);
   firstPOI->setVal(observedUL);
   double obsTSatObsUL = fc.GetTestStatSampler()->EvaluateTestStatistic(*data,tmpPOI);


   // Ask the calculator which points were scanned
   RooDataSet* parameterScan = (RooDataSet*) fc.GetPointsToScan();
   RooArgSet* tmpPoint;

   // make a histogram of parameter vs. threshold
   TH1F* histOfThresholds = new TH1F("histOfThresholds","",
                                       parameterScan->numEntries(),
                                       firstPOI->getMin(),
                                       firstPOI->getMax());
   histOfThresholds->GetXaxis()->SetTitle(firstPOI->GetName());
   histOfThresholds->GetYaxis()->SetTitle("Threshold");

   // loop through the points that were tested and ask confidence belt
   // what the upper/lower thresholds were.
   // For FeldmanCousins, the lower cut off is always 0
   for(Int_t i=0; i<parameterScan->numEntries(); ++i){
      tmpPoint = (RooArgSet*) parameterScan->get(i)->clone("temp");
      //cout <<"get threshold"<<endl;
      double arMax = belt->GetAcceptanceRegionMax(*tmpPoint);
      double poiVal = tmpPoint->getRealValue(firstPOI->GetName()) ;
      histOfThresholds->Fill(poiVal,arMax);
   }
   TCanvas* c1 = new TCanvas();
   c1->Divide(2);
   c1->cd(1);
   histOfThresholds->SetMinimum(0);
   histOfThresholds->Draw();
   c1->cd(2);

   // -------------------------------------------------------
   // Now we generate the expected bands and power-constraint

   // First: find parameter point for mu=0, with conditional MLEs for nuisance parameters
   RooAbsReal* nll = mc->GetPdf()->createNLL(*data);
   RooAbsReal* profile = nll->createProfile(*mc->GetParametersOfInterest());
   firstPOI->setVal(0.);
   profile->getVal(); // this will do fit and set nuisance parameters to profiled values
   RooArgSet* poiAndNuisance = new RooArgSet();
   if(mc->GetNuisanceParameters())
      poiAndNuisance->add(*mc->GetNuisanceParameters());
   poiAndNuisance->add(*mc->GetParametersOfInterest());
   w->saveSnapshot("paramsToGenerateData",*poiAndNuisance);
   RooArgSet* paramsToGenerateData = (RooArgSet*) poiAndNuisance->snapshot();
   cout << "\nWill use these parameter points to generate pseudo data for bkg only" << endl;
   paramsToGenerateData->Print("v");


   RooArgSet unconditionalObs;
   unconditionalObs.add(*mc->GetObservables());
   unconditionalObs.add(*mc->GetGlobalObservables()); // comment this out for the original conditional ensemble

   double CLb=0;
   double CLbinclusive=0;

   // Now we generate background only and find distribution of upper limits
   TH1F* histOfUL = new TH1F("histOfUL","",100,0,firstPOI->getMax());
   histOfUL->GetXaxis()->SetTitle("Upper Limit (background only)");
   histOfUL->GetYaxis()->SetTitle("Entries");
   for(int imc=0; imc<nToyMC; ++imc){

      // set parameters back to values for generating pseudo data
      //    cout << "\n get current nuis, set vals, print again" << endl;
      w->loadSnapshot("paramsToGenerateData");
      //    poiAndNuisance->Print("v");

      RooDataSet* toyData = 0;
      // now generate a toy dataset
      if(!mc->GetPdf()->canBeExtended()){
         if(data->numEntries()==1)
            toyData = mc->GetPdf()->generate(*mc->GetObservables(),1);
         else
            cout <<"Not sure what to do about this model" <<endl;
      } else{
         //      cout << "generating extended dataset"<<endl;
         toyData = mc->GetPdf()->generate(*mc->GetObservables(),Extended());
      }

      // generate global observables
      // need to be careful for simpdf
      //    RooDataSet* globalData = mc->GetPdf()->generate(*mc->GetGlobalObservables(),1);

      RooSimultaneous* simPdf = dynamic_cast<RooSimultaneous*>(mc->GetPdf());
      if(!simPdf){
         RooDataSet *one = mc->GetPdf()->generate(*mc->GetGlobalObservables(), 1);
         const RooArgSet *values = one->get();
         RooArgSet *allVars = mc->GetPdf()->getVariables();
         *allVars = *values;
         delete allVars;
         delete values;
         delete one;
      } else {

         //try fix for sim pdf
         TIterator* iter = simPdf->indexCat().typeIterator() ;
         RooCatType* tt = NULL;
         while((tt=(RooCatType*) iter->Next())) {

            // Get pdf associated with state from simpdf
            RooAbsPdf* pdftmp = simPdf->getPdf(tt->GetName()) ;

            // Generate only global variables defined by the pdf associated with this state
            RooArgSet* globtmp = pdftmp->getObservables(*mc->GetGlobalObservables()) ;
            RooDataSet* tmp = pdftmp->generate(*globtmp,1) ;

            // Transfer values to output placeholder
            *globtmp = *tmp->get(0) ;

            // Cleanup
            delete globtmp ;
            delete tmp ;
         }
      }

      //    globalData->Print("v");
      //    unconditionalObs = *globalData->get();
      //    mc->GetGlobalObservables()->Print("v");
      //    delete globalData;
      //    cout << "toy data = " << endl;
      //    toyData->get()->Print("v");

      // get test stat at observed UL in observed data
      firstPOI->setVal(observedUL);
      double toyTSatObsUL = fc.GetTestStatSampler()->EvaluateTestStatistic(*toyData,tmpPOI);
      //    toyData->get()->Print("v");
      //    cout <<"obsTSatObsUL " <<obsTSatObsUL << "toyTS " << toyTSatObsUL << endl;
      if(obsTSatObsUL < toyTSatObsUL) // not sure about <= part yet
         CLb+= (1.)/nToyMC;
      if(obsTSatObsUL <= toyTSatObsUL) // not sure about <= part yet
         CLbinclusive+= (1.)/nToyMC;


      // loop over points in belt to find upper limit for this toy data
      double thisUL = 0;
      for(Int_t i=0; i<parameterScan->numEntries(); ++i){
         tmpPoint = (RooArgSet*) parameterScan->get(i)->clone("temp");
         double arMax = belt->GetAcceptanceRegionMax(*tmpPoint);
         firstPOI->setVal( tmpPoint->getRealValue(firstPOI->GetName()) );
         //   double thisTS = profile->getVal();
         double thisTS = fc.GetTestStatSampler()->EvaluateTestStatistic(*toyData,tmpPOI);

         //   cout << "poi = " << firstPOI->getVal()
         // << " max is " << arMax << " this profile = " << thisTS << endl;
         //      cout << "thisTS = " << thisTS<<endl;
         if(thisTS<=arMax){
            thisUL = firstPOI->getVal();
         } else{
            break;
         }
      }



      /*
      // loop over points in belt to find upper limit for this toy data
      double thisUL = 0;
      for(Int_t i=0; i<histOfThresholds->GetNbinsX(); ++i){
         tmpPoint = (RooArgSet*) parameterScan->get(i)->clone("temp");
         cout <<"----------------  "<<i<<endl;
         tmpPoint->Print("v");
         cout << "from hist " << histOfThresholds->GetBinCenter(i+1) <<endl;
         double arMax = histOfThresholds->GetBinContent(i+1);
         // cout << " threhold from Hist = aMax " << arMax<<endl;
         // double arMax2 = belt->GetAcceptanceRegionMax(*tmpPoint);
         // cout << "from scan arMax2 = "<< arMax2 << endl; // not the same due to TH1F not TH1D
         // cout << "scan - hist" << arMax2-arMax << endl;
         firstPOI->setVal( histOfThresholds->GetBinCenter(i+1));
         //   double thisTS = profile->getVal();
         double thisTS = fc.GetTestStatSampler()->EvaluateTestStatistic(*toyData,tmpPOI);

         //   cout << "poi = " << firstPOI->getVal()
         // << " max is " << arMax << " this profile = " << thisTS << endl;
         //      cout << "thisTS = " << thisTS<<endl;

         // NOTE: need to add a small epsilon term for single precision vs. double precision
         if(thisTS<=arMax + 1e-7){
            thisUL = firstPOI->getVal();
         } else{
            break;
         }
      }
      */

      histOfUL->Fill(thisUL);

      // for few events, data is often the same, and UL is often the same
      //    cout << "thisUL = " << thisUL<<endl;

      delete toyData;
   }
   histOfUL->Draw();
   c1->SaveAs("one-sided_upper_limit_output.pdf");

   // if you want to see a plot of the sampling distribution for a particular scan point:
   /*
   SamplingDistPlot sampPlot;
   int indexInScan = 0;
   tmpPoint = (RooArgSet*) parameterScan->get(indexInScan)->clone("temp");
   firstPOI->setVal( tmpPoint->getRealValue(firstPOI->GetName()) );
   toymcsampler->SetParametersForTestStat(tmpPOI);
   SamplingDistribution* samp = toymcsampler->GetSamplingDistribution(*tmpPoint);
   sampPlot.AddSamplingDistribution(samp);
   sampPlot.Draw();
      */

   // Now find bands and power constraint
   Double_t* bins = histOfUL->GetIntegral();
   TH1F* cumulative = (TH1F*) histOfUL->Clone("cumulative");
   cumulative->SetContent(bins);
   double band2sigDown, band1sigDown, bandMedian, band1sigUp,band2sigUp;
   for(int i=1; i<=cumulative->GetNbinsX(); ++i){
      if(bins[i]<RooStats::SignificanceToPValue(2))
         band2sigDown=cumulative->GetBinCenter(i);
      if(bins[i]<RooStats::SignificanceToPValue(1))
         band1sigDown=cumulative->GetBinCenter(i);
      if(bins[i]<0.5)
         bandMedian=cumulative->GetBinCenter(i);
      if(bins[i]<RooStats::SignificanceToPValue(-1))
         band1sigUp=cumulative->GetBinCenter(i);
      if(bins[i]<RooStats::SignificanceToPValue(-2))
         band2sigUp=cumulative->GetBinCenter(i);
   }
   cout << "-2 sigma  band " << band2sigDown << endl;
   cout << "-1 sigma  band " << band1sigDown << " [Power Constraint)]" << endl;
   cout << "median of band " << bandMedian << endl;
   cout << "+1 sigma  band " << band1sigUp << endl;
   cout << "+2 sigma  band " << band2sigUp << endl;

   // print out the interval on the first Parameter of Interest
   cout << "\nobserved 95% upper-limit "<< interval->UpperLimit(*firstPOI) <<endl;
   cout << "CLb strict [P(toy>obs|0)] for observed 95% upper-limit "<< CLb <<endl;
   cout << "CLb inclusive [P(toy>=obs|0)] for observed 95% upper-limit "<< CLbinclusive <<endl;

   delete profile;
   delete nll;

}
Example #16
0
// iSyst =  0 : Cent
//         +1 :
//         -1 : 
void initIntWght(std::string wFile , int iType , int iSyst, float Hmass = 350, float cprime = 1.0) { // c'=1.0 --> SM

   if ( iType == 0 ) { //---- ggH 
     TFile* f = new TFile(wFile.c_str() , "READ");
     gROOT->cd();
     if (hInt_ggH) hInt_ggH->Delete();
     hInt_ggH = new TH1F("h_MWW_rel_NNLO_cen","h_MWW_rel_NNLO_cen",2000,0.,4000.);
     TH1F* hCen = (TH1F*) f->Get("h_MWW_rel_NNLO_cen");
     TH1F* hUp  = (TH1F*) f->Get("h_MWW_rel_NNLO_mul");
     TH1F* hDo  = (TH1F*) f->Get("h_MWW_rel_NNLO_add");
     // low/high Mass -> no value
     float firstM    = 9999.;
     float lastM     = -1.  ;
     float firstVal  = -1;
     float lastVal   = -1;
     bool  foundFirst=false;
     bool  foundLast =false;
     for ( int iBin = 1 ; iBin <= hCen->GetNbinsX() ; ++iBin ) {
       float m  = hCen->GetBinCenter(iBin);
       float v  = hCen->GetBinContent(iBin);
       if (v != 0 && ! foundFirst && m < Hmass ) {
         firstVal   = v ;
         firstM     = m ;
         foundFirst = true;
       }
       if ( m > Hmass && v==0) foundLast = true;
       if (!foundLast) {
         lastVal   = v ;
         lastM     = m ;
       }
     }
     // Create Histograms 
     for ( int iBin = 1 ; iBin <= hInt_ggH->GetNbinsX() ; ++iBin ) {
       float m = hInt_ggH->GetBinCenter(iBin);
       if ( m >= hCen->GetXaxis()->GetXmin() && m <= hCen->GetXaxis()->GetXmax() ) {
         int jBin = hCen->FindBin(m);
         if (iSyst ==  0) hInt_ggH->SetBinContent(iBin,hCen->GetBinContent(jBin));
         if (iSyst ==  1) hInt_ggH->SetBinContent(iBin,hUp->GetBinContent(jBin));
         if (iSyst == -1) hInt_ggH->SetBinContent(iBin,hDo->GetBinContent(jBin));
       } 
       if ( m < firstM || m < hCen->GetXaxis()->GetXmin() ) {
         if (iSyst ==  0) hInt_ggH->SetBinContent(iBin,firstVal);
         if (iSyst ==  1) hInt_ggH->SetBinContent(iBin,firstVal*2);
         if (iSyst == -1) hInt_ggH->SetBinContent(iBin,0.        );
       }
       if ( m > lastM  || m > hCen->GetXaxis()->GetXmax() ) {
         if (iSyst ==  0) hInt_ggH->SetBinContent(iBin,lastVal);
         if (iSyst ==  1) hInt_ggH->SetBinContent(iBin,0.     );
         if (iSyst == -1) hInt_ggH->SetBinContent(iBin,lastVal*2);
       }

     } 
     //hInt_ggH->Draw();
     //hUp->Draw("same");
     wInt_ggH = new TSpline3(hInt_ggH) ;
     wInt_ggH->SetLineColor(kRed); 
     wInt_ggH->Draw("same");
     //gPad->WaitPrimitive();
     f->Close();
   }
   else if ( iType ==1 ) { //---- qqH

    TString *readfile = new TString ("data/InterferenceVBF/file_for_interpolation.root"); //file with the values of the all parameters
    TFile* SI = new TFile(readfile->Data());
    Double_t fill_param[16]; // 9 + 7 = 16

    for (int i=0; i<9; i++) {
     TString *name = new TString (parameters_normal[i]);
     name->Append("_SI.txt");
     variables_SI[i] = (TGraph2D*)SI->Get(name->Data());
    }
    for (int i=0; i<7; i++) {
     TString *name = new TString (parameters_normal[i]);
     name->Append("_S.txt");
     variables_S[i] = (TGraph2D*)SI->Get(name->Data());
    }

    crystal_Icorr_qqH = new TF1("crystal_Icorr_qqH",CrystalBallLowHighPlusExpDividedByCrystalBallLowHigh,0,3000,16);

    for (int iVar = 0; iVar<9; iVar++) {
     crystal_Icorr_qqH->SetParameter(iVar, variables_SI[iVar]->Interpolate(Hmass, cprime));
    }
    for (int iVar = 0; iVar<7; iVar++) {
     crystal_Icorr_qqH->SetParameter(iVar+9, variables_S[iVar]->Interpolate(Hmass, cprime));
    }

   }

}
Example #17
0
void t1pfmetPhiwithCorr(double pt1min, double pt2min, double METmin, double DPHImin){
gStyle->SetPadTickY(1);
gStyle->SetPadTickX(1);

int  i = 0;
  TLegend* leg = new TLegend(0.35,0.65,0.87,0.87);
  leg->SetNColumns(2);
  leg->SetBorderSize(0);
  leg->SetFillStyle(0);

  TCanvas *canvas = new TCanvas("c1n","",500,600);
  TPad *mainPad = new TPad("mainPad","",0,0.3,1,1);
  TPad *smallPad = new TPad("smallPad","",0,0.05,1,0.3);
  mainPad->SetBottomMargin(0.015);


  smallPad->SetTopMargin(0.05);
  smallPad->SetBottomMargin(0.25);

  canvas->cd();

  mainPad->Draw();
  mainPad->cd();







 
  //  gPad->SetLogy();
  TCut mggmax = "mgg<180";
  TCut mggmin = "mgg>100";
  TCut pt1Cut = Form("pt1/mgg>%lf",pt1min);
  TCut pt2Cut = Form("pt2/mgg>%lf",pt2min);
  //  TCut METCut = Form("t1pfmetCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0)>%lf",METmin);
  TCut METCut = "";
 TCut DPHICut =  Form("Delta(pt1,eta1,phi1,pt2,eta2,phi2,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>%lf",DPHImin);
  TCut eveto1 = "eleveto1 == 1";
  TCut eveto2 = "eleveto2 == 1";
  TCut eveto = eveto1 && eveto2;
  TCut genmatch = "((genmatch1==1 && genmatch2==0)||(genmatch1==0 && genmatch2==1)||(genmatch1==0 && genmatch2==0))";  
  TCut metF = "((metF_GV==1) && (metF_HBHENoise==1) && (metF_HBHENoiseIso==1) && (metF_CSC==1) && (metF_eeBadSC==1))";  
  TCut NegWeight = "weight>0.";

  /* 
     TFile *M1 =  TFile::Open("./50ns_betaV3/NewWeightDMHtoGG_M1.root","READ");  
     TFile *M10 =  TFile::Open("./50ns_betaV3/NewWeightDMHtoGG_M10.root","READ");
     TFile *M100 =  TFile::Open("./50ns_betaV3/NewWeightDMHtoGG_M100.root","READ");  
     TFile *M1000 =  TFile::Open("./50ns_betaV3/NewWeightDMHtoGG_M1000.root","READ");
  */

  TFile *data = TFile::Open("./25ns_2246inv_v3/DoubleEG.root","READ");
  
  TFile *sig1 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP600.root","READ");
  TFile *sig2 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP800.root","READ");
  TFile *sig3 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1000.root","READ");
  TFile *sig4 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1200.root","READ");
  TFile *sig5 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1400.root","READ");  
  TFile *sig6 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1700.root","READ");
  TFile *sig7 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP2500.root","READ");
  /*
    TFile *bkg1 =  TFile::Open("./50ns_betaV3/DiPhoton.root","READ");  
    TFile *bkg2 =  TFile::Open("./50ns_betaV3/DYJetsToLL.root","READ");  
    TFile *bkg3 =  TFile::Open("./50ns_betaV3/GJets.root","READ");  
    TFile *bkg4 =  TFile::Open("./50ns_betaV3/GluGluHToGG.root","READ");  
    TFile *bkg5 =  TFile::Open("./50ns_betaV3/QCD.root","READ");  
    TFile *bkg6 =  TFile::Open("./50ns_betaV3/VH.root","READ");  
  */

  TFile *bkg1 =  TFile::Open("./25ns_2246inv_v3/DiPhoton.root","READ");  
  TFile *bkg2 =  TFile::Open("./25ns_2246inv_v3/DYJetsToLL.root","READ");  
  TFile *bkg3 =  TFile::Open("./25ns_2246inv_v3/GJets.root","READ");  
  TFile *bkg4 =  TFile::Open("./25ns_2246inv_v3/GluGluHToGG.root","READ");  
  TFile *bkg5 =  TFile::Open("./25ns_2246inv_v3/QCD.root","READ");  
  TFile *bkg6 =  TFile::Open("./25ns_2246inv_v3/VH.root","READ");  
  TFile *bkg7 =  TFile::Open("./25ns_2246inv_v3/ttHJetToGG.root","READ");
  TFile *bkg8 =  TFile::Open("./25ns_2246inv_v3/VBFHToGG.root","READ");
  TFile *bkg9 =  TFile::Open("./25ns_2246inv_v3/TGJets.root","READ");
  TFile *bkg10 =  TFile::Open("./25ns_2246inv_v3/TTGJets.root","READ");
  TFile *bkg11 =  TFile::Open("./25ns_2246inv_v3/WGToLNuG.root","READ");
  TFile *bkg12 =  TFile::Open("./25ns_2246inv_v3/ZGTo2LG.root","READ");
  /*
    TTree *tree_M1 = (TTree*) M1->Get("DiPhotonTree");
    TTree *tree_M10 = (TTree*) M10->Get("DiPhotonTree");
    TTree *tree_M100 = (TTree*) M100->Get("DiPhotonTree");
    TTree *tree_M1000 = (TTree*) M1000->Get("DiPhotonTree");
  */

  TTree *tree_data = (TTree*) data->Get("DiPhotonTree");
  
  TTree *tree_sig1 = (TTree*) sig1->Get("DiPhotonTree");
  TTree *tree_sig2 = (TTree*) sig2->Get("DiPhotonTree");
  TTree *tree_sig3 = (TTree*) sig3->Get("DiPhotonTree");
  TTree *tree_sig4 = (TTree*) sig4->Get("DiPhotonTree");
  TTree *tree_sig5 = (TTree*) sig5->Get("DiPhotonTree");
  TTree *tree_sig6 = (TTree*) sig6->Get("DiPhotonTree");
  TTree *tree_sig7 = (TTree*) sig7->Get("DiPhotonTree");
 
  
  
  TTree *tree_bkg1 = (TTree*) bkg1->Get("DiPhotonTree");
  TTree *tree_bkg2 = (TTree*) bkg2->Get("DiPhotonTree");
  TTree *tree_bkg3 = (TTree*) bkg3->Get("DiPhotonTree");
  TTree *tree_bkg4 = (TTree*) bkg4->Get("DiPhotonTree");
  TTree *tree_bkg5 = (TTree*) bkg5->Get("DiPhotonTree");
  TTree *tree_bkg6 = (TTree*) bkg6->Get("DiPhotonTree");
  TTree *tree_bkg7 = (TTree*) bkg7->Get("DiPhotonTree");
  TTree *tree_bkg8 = (TTree*) bkg8->Get("DiPhotonTree");
  TTree *tree_bkg9 = (TTree*) bkg9->Get("DiPhotonTree");
  TTree *tree_bkg10 = (TTree*) bkg10->Get("DiPhotonTree");
  TTree *tree_bkg11 = (TTree*) bkg11->Get("DiPhotonTree");
  TTree *tree_bkg12 = (TTree*) bkg12->Get("DiPhotonTree");
  
  
  /* 
     tree_M1->Draw("(t1pfmet)>>h1(30,100,200)","weight*10"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto && Cut_Jets));
     TH1F *h1 =(TH1F*)gPad->GetPrimitive("h1");
     tree_M10->Draw("(t1pfmet)>>h2(30,100,200)","weight*10"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto && Cut_Jets));
     TH1F *h2 =(TH1F*)gPad->GetPrimitive("h2");
     tree_M100->Draw("(t1pfmet)>>h3(30,100,200)","weight*10"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto && Cut_Jets));
     TH1F *h3 =(TH1F*)gPad->GetPrimitive("h3");
     tree_M1000->Draw("(t1pfmet)>>h4(30,100,200)","weight*10"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto && Cut_Jets));
     TH1F *h4 =(TH1F*)gPad->GetPrimitive("h4");  
  */
  
  tree_data->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,1))>>hdata(10,-4,4)","(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && eveto && METCut  && metF&& DPHICut ));
  TH1F *hdata =(TH1F*)gPad->GetPrimitive("hdata");

  tree_sig1->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h1(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h1 =(TH1F*)gPad->GetPrimitive("h1");
  tree_sig2->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h2(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h2 =(TH1F*)gPad->GetPrimitive("h2");
  tree_sig3->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h3(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h3 =(TH1F*)gPad->GetPrimitive("h3");
  tree_sig4->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h4(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h4 =(TH1F*)gPad->GetPrimitive("h4");
  tree_sig5->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h5(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h5 =(TH1F*)gPad->GetPrimitive("h5");
  tree_sig6->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h6(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h6 =(TH1F*)gPad->GetPrimitive("h6");
  tree_sig7->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h7(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h7 =(TH1F*)gPad->GetPrimitive("h7");

  





  tree_bkg1->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg1(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg1 =(TH1F*)gPad->GetPrimitive("hbkg1");
  tree_bkg2->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg2(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg2 =(TH1F*)gPad->GetPrimitive("hbkg2");
  tree_bkg3->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg3(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && genmatch && DPHICut));
  TH1F *hbkg3 =(TH1F*)gPad->GetPrimitive("hbkg3");
     
tree_bkg4->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg4(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut)); 
  TH1F *hbkg4 =(TH1F*)gPad->GetPrimitive("hbkg4");
  tree_bkg5->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg5(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && genmatch && DPHICut));
  TH1F *hbkg5 =(TH1F*)gPad->GetPrimitive("hbkg5");
  tree_bkg6->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg6(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg6 =(TH1F*)gPad->GetPrimitive("hbkg6");  
  tree_bkg7->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg7(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg7 =(TH1F*)gPad->GetPrimitive("hbkg7");  
  tree_bkg8->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg8(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg8 =(TH1F*)gPad->GetPrimitive("hbkg8");  
  tree_bkg9->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg9(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut)); 
  TH1F *hbkg9 =(TH1F*)gPad->GetPrimitive("hbkg9");  
  tree_bkg10->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg10(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg10 =(TH1F*)gPad->GetPrimitive("hbkg10");  
 tree_bkg11->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg11(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg11 =(TH1F*)gPad->GetPrimitive("hbkg11");  
 tree_bkg12->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg12(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg12 =(TH1F*)gPad->GetPrimitive("hbkg12");  



 

  hdata->SetMarkerColor(kBlack);
  hdata->SetLineColor(kBlack);
  hdata->SetMarkerStyle(20);
  
  h1->SetLineColor(kRed+3);
  h2->SetLineColor(kRed+1);
  h3->SetLineColor(kRed);
  h4->SetLineColor(kPink+2);
  h5->SetLineColor(kPink+4);
 h6->SetLineColor(kPink+7);
 h7->SetLineColor(kMagenta+2);
 h1->SetLineWidth(2);
 h2->SetLineWidth(2);
 h3->SetLineWidth(2);
 h4->SetLineWidth(2);
 h5->SetLineWidth(2);
 h6->SetLineWidth(2);
 h7->SetLineWidth(2);


  
  
  THStack *hs=new THStack("hs","");
  hbkg7->SetFillColor(kGreen+2);
  hbkg6->SetFillColor(kGreen);
  hbkg8->SetFillColor(kYellow);
  hbkg4->SetFillColor(kOrange);
  hbkg9->SetFillColor(kOrange+7);
  hbkg10->SetFillColor(kOrange+4);
  hbkg11->SetFillColor(kCyan);
  hbkg12->SetFillColor(kCyan+1);
  hbkg5->SetFillColor(kBlue+2);
  hbkg2->SetFillColor(kBlue);  
  hbkg3->SetFillColor(kMagenta-2);
  hbkg1->SetFillColor(kViolet);

  hbkg1->SetLineColor(kBlack);
  hbkg2->SetLineColor(kBlack);
  hbkg3->SetLineColor(kBlack);
  hbkg4->SetLineColor(kBlack);
  hbkg5->SetLineColor(kBlack);
  hbkg6->SetLineColor(kBlack);
  hbkg7->SetLineColor(kBlack);
  hbkg8->SetLineColor(kBlack);
  hbkg9->SetLineColor(kBlack);
  hbkg10->SetLineColor(kBlack);
  hbkg11->SetLineColor(kBlack);
  hbkg12->SetLineColor(kBlack);

  hs->Add(hbkg7);
  hs->Add(hbkg6);
  hs->Add(hbkg8);
  hs->Add(hbkg4);
  hs->Add(hbkg9);
  hs->Add(hbkg10);
  hs->Add(hbkg11);
  hs->Add(hbkg12);
  hs->Add(hbkg2);
  hs->Add(hbkg5);
  hs->Add(hbkg3);
  hs->Add(hbkg1);
  
  TH1F *hsum = (TH1F*)hbkg1->Clone("hsum"); 
  hsum->Add(hbkg2);
  hsum->Add(hbkg3);
  hsum->Add(hbkg4);
  hsum->Add(hbkg5);
  hsum->Add(hbkg6);
  hsum->Add(hbkg7);
  hsum->Add(hbkg8);
  hsum->Add(hbkg9);
  hsum->Add(hbkg10);
  hsum->Add(hbkg11);
  hsum->Add(hbkg12);
  


  canvas->SetLeftMargin(0.12);

  // hs->SetMinimum(0.01);
  hs->SetMaximum(5700);

  hs->SetTitle("");
  hs->Draw("HIST"); 
  hsum->SetMarkerStyle(1);
  hsum->SetFillColor(kGray+3);
  hsum->SetFillStyle(3002);
  hsum->Draw("same e2");
  //  h2->Draw("same hist");
  // h3->Draw("same hist"); 
  // h4->Draw("same hist");
  // h1->Draw("same hist");
  //h5->Draw("same hist"); //only for 25ns samples
  //h7->Draw("same hist"); //only for 25ns samples
  // h6->Draw("same hist"); //only for 25ns samples
  hdata->Draw("same E1");
  

  hs->GetXaxis()->SetLabelOffset(999);
  hs->GetYaxis()->SetTitleOffset(1.5);
  hs->GetYaxis()->SetTitle("Events/0.8");  
  //int  iPos = 11;
//  CMS_lumi(canvas,true,iPos,false);
  gPad->Modified();


  leg->AddEntry(hdata,"Data","elp");
  /*leg->AddEntry(h1,"m_{#chi} = 1 GeV","l");
  leg->AddEntry(h2,"m_{#chi} = 10 GeV","l");
  leg->AddEntry(h3,"m_{#chi} = 100 GeV","l");      
  leg->AddEntry(h4,"m_{#chi} = 1000 GeV","l");*/
  //  leg->AddEntry(h1,"m_{Z'} = 600 GeV","l");
  leg->AddEntry(hbkg1,"#gamma #gamma","f");
  // leg->AddEntry(h2,"m_{Z'} = 800 GeV","l");
  leg->AddEntry(hbkg2,"Drell Yann","f");
  // leg->AddEntry(h3,"m_{Z'} = 1000 GeV","l");
  leg->AddEntry(hbkg3,"#gamma + Jets","f");
  // leg->AddEntry(h4,"m_{Z'} = 1200 GeV","l");
  leg->AddEntry(hbkg5,"QCD","f");
  // leg->AddEntry(h5,"m_{Z'} = 1400 GeV","l"); //only for 25ns samples                                                              
  leg->AddEntry(hbkg4,"ggH","f");
  //leg->AddEntry(h6,"m_{Z'} = 1700 GeV","l"); //only for 25ns samples                                                              
  leg->AddEntry(hbkg6,"VH","f");
  // leg->AddEntry(h7,"m_{Z'} = 2500 GeV","l"); //only for 25ns samples                                                              
  leg->AddEntry(hbkg7,"ttH","f");
  leg->AddEntry(hbkg8,"VBF H","f");
  leg->AddEntry(hbkg9,"t + #gamma + Jets","f");
  leg->AddEntry(hbkg10,"tt + #gamma +Jets","f");
  leg->AddEntry(hbkg11,"#gamma+W","f");
  leg->AddEntry(hbkg12,"#gamma+Z","f");
 leg->AddEntry(hsum,"Bkg uncertainty","f");
  leg->Draw("same");




  
  gStyle->SetOptStat(0);  
 

  canvas->cd();
  smallPad->Draw();
  smallPad->cd();

  TGraphErrors *gr = new TGraphErrors(0);
  double integralData=hdata->Integral();
  double integralBKG=hsum->Integral();
  double error, ratio;
  for(int w=1; w<20; w++){
    if((hdata->GetBinContent(w)!=0) && (hsum->GetBinContent(w)!=0)){

      gr->SetPoint(w, hdata->GetBinCenter(w),(hdata->GetBinContent(w))/(hsum->GetBinContent(w)));
      ratio= (hdata->GetBinContent(w))/(hsum->GetBinContent(w));
      error= (hdata->GetBinContent(w)*sqrt(hsum->GetBinContent(w))/(hsum->GetBinContent(w)*hsum->GetBinContent(w)) + sqrt(hdata->GetBinContent(w))/hsum->GetBinContent(w));
      std::cout<<"VALUE: "<<ratio<<" ERROR: "<<error<<std::endl;
      gr->SetPointError(w, hdata->GetBinWidth(w)/2,error);
    }else{
      gr->SetPoint(w, hdata->GetBinCenter(w),10);
    }
  }



  gStyle->SetPadTickY(1);
  gStyle->SetPadTickX(1);
  gr->GetHistogram()->SetMaximum(2);
  gr->GetHistogram()->SetMinimum(0.1);

  gStyle->SetTextSize(14);
  gROOT->ForceStyle();

  gr->GetXaxis()->SetLabelFont(43);
  gr->GetXaxis()->SetLabelSize(15);
  gr->GetYaxis()->SetLabelFont(43);
  gr->GetYaxis()->SetLabelSize(15);

  gr->GetXaxis()->SetLimits(-4,4);


  gPad->SetGrid();
  gStyle->SetStripDecimals(kTRUE);
  gr->SetMarkerStyle(20);
  gr->SetMarkerSize(0.7);


  gr->Draw("AZP");
  gr->GetXaxis()->SetTitle("#phi_{MET}^{corr}");
  gr->GetXaxis()->SetTitleSize(0.1);
  gr->GetYaxis()->SetTitleSize(0.1);
  gr->GetYaxis()->SetNdivisions(505);

  gr->GetXaxis()->SetTitleOffset(1);
  gr->GetYaxis()->SetTitle("Data/MC");
  gr->GetYaxis()->SetTitleOffset(0.4);
  gr->SetTitle("");
  smallPad->Update();
  TF1* line = new TF1("line","1",-4,4);
  line->SetLineColor(kRed);
  line->SetLineWidth(2);
  line->Draw("L same");
  gr->Draw("ZP SAME");


  canvas->SaveAs(Form("./25ns_2246inv_v3/plots/kinematics/metphicorr_MET%.0lf.pdf",METmin)); 
  canvas->SaveAs(Form("./25ns_2246inv_v3/plots/kinematics/metphicorr_MET%.0lf.png",METmin)); 
    
}
void MakePileupReweight(int option = 0) {


  TFile *pileupTargetFile = 0;
  if (option == 0) pileupTargetFile = new TFile("/afs/cern.ch/work/c/cpena/public/CMSSW_7_6_3/src/RazorAnalyzer/data/MyDataPileupHistogram.root", "READ");
  else if (option == 1) pileupTargetFile = new TFile("/afs/cern.ch/work/c/cpena/public/CMSSW_7_6_3/src/RazorAnalyzer/data/MyDataPileupHistogramUp.root", "READ");
  else if (option == 2) pileupTargetFile = new TFile("/afs/cern.ch/work/c/cpena/public/CMSSW_7_6_3/src/RazorAnalyzer/data/MyDataPileupHistogramDown.root", "READ");
  else {
    return;
  }
  TH1F *pileupTargetHist = (TH1F*)pileupTargetFile->Get("pileup");
  assert(pileupTargetHist);
  std::cout << "pileupTargetHist " << pileupTargetHist->Integral() << std::endl;

  TFile *pileupSourceFile = new TFile("/afs/cern.ch/work/c/cpena/public/CMSSW_7_6_3/src/RazorAnalyzer/data/DoubleEG_Run2015_CMSSW_7_6_March15.root", "READ");
  //TH1F *pileupSourceHist = (TH1F*)pileupSourceFile->Get("PileupSourceHist");
  TH1F *pileupSourceHist = (TH1F*)pileupSourceFile->Get("pileup"); 
  assert(pileupSourceHist);
  std::cout << "pileupSourceFile " << pileupSourceHist->Integral() << std::endl;
  std::cout << "FILES RETRIEVED" << std::endl;
  //*******************************************************************************************
  //Make NVtx Reweighting Function
  //*******************************************************************************************
  TH1F *PileupTargetNormalized = NormalizeHist( pileupTargetHist );
  TH1F *PileupSourceNormalized = NormalizeHist( pileupSourceHist );
  std::cout << "HISTOS NORMALIZED" << std::endl;
  TH1F *PileupReweight = new TH1F ("PileupReweight",";NPU;Weight",50,0,50);

  for (int i=0; i<PileupReweight->GetXaxis()->GetNbins()+2; i++) {

    double data = 0;
    double bkg = 0;
    if (PileupSourceNormalized->GetBinContent(i) > 0) {
      PileupReweight->SetBinContent(i,PileupTargetNormalized->GetBinContent(i)/PileupSourceNormalized->GetBinContent(i));
    } else if (PileupTargetNormalized->GetBinContent(i) == 0){
      PileupReweight->SetBinContent(i,0.0);
    } else {
      if (i == 1) {
	PileupReweight->SetBinContent(i,1);
      } else {
	PileupReweight->SetBinContent(i,PileupReweight->GetBinContent(i-1));
      }
    }

    cout << "Bin " << i << " : " << PileupReweight->GetXaxis()->GetBinCenter(i) << " : " << PileupReweight->GetBinCenter(i) << " : " << PileupTargetNormalized->GetBinContent(i) << " / " << PileupSourceNormalized->GetBinContent(i) << " = " << PileupReweight->GetBinContent(i) << "\n";
  }

  
  double k = 0;
  for (int i=0; i<PileupSourceNormalized->GetXaxis()->GetNbins()+2; i++) {
    double weight = PileupReweight->GetBinContent(PileupReweight->GetXaxis()->FindFixBin(i-1));
    cout << i << " : " << i-1 << " : " << weight << " : " << PileupSourceNormalized->GetBinContent(i) << " -> " << PileupSourceNormalized->GetBinContent(i)*weight << "\n";
    k += PileupSourceNormalized->GetBinContent(i)*weight;    
  }
  cout << "int = " << k << "\n";

  TFile *file = TFile::Open("PileupReweight2015.root", "UPDATE");
  file->cd();
  if (option == 0) file->WriteTObject(PileupReweight, "PileupReweight", "WriteDelete");
  else if (option == 1) file->WriteTObject(PileupReweight, "PileupReweightSysUp", "WriteDelete");
  else if (option == 2) file->WriteTObject(PileupReweight, "PileupReweightSysDown", "WriteDelete");
  file->Close();
  delete file;

}
Example #19
0
int main(int argc, char **argv)
{
	TString xvar = "TMath::Power(J_psi_1S_MM/1000,2)";
	TString xvarname = "q2";
	TString type = "All";
	TCut extCut = "";
	
	string drawopt = "";
	TString outFileName = "";
	bool rel = false, doSys = false, percent = false, jpsi = false, pythia6 = false;
	
	int xnbins = 12;
	double def_xbins[] = {0.1, 2.0, 4.0, 6.0, 8.0, 9.1, 10.1, 11.0, 12.5, 15.0, 16.0, 18.0, 20.0};
	//double def_xbins[] = {1.1, 6.0, 15.0, 20.0};
	double * xbins = &def_xbins[0];
	
	if(argc > 1)
	{
		for(int a = 1; a < argc; a++)
		{
			string arg = argv[a];
			string str = arg.substr(2,arg.length()-2);
			
			if(arg.find("-t") != string::npos) type = (TString)str;
			if(arg == "-r") rel = true;
			if(arg.find("-b") != string::npos ) xbins = decodeBinning(str,&xnbins);
			if(arg.find("-c") != string::npos ) xbins = decodeBinning(str,&xnbins,"custom");
			if(arg.find("-C") != string::npos ) extCut = (TCut)((TString)str);
			if(arg == "-highq2Cut") extCut = (TCut)"( TMath::Power(J_psi_1S_MM/1000,2) > 15. && TMath::Power(J_psi_1S_MM/1000,2) < 20. )";
			if(arg == "-Pythia6") pythia6 = true;
			if(arg.find("-X") != string::npos) { xvar = str; xvarname = xvar; }
			if(arg.find("-D") != string::npos) drawopt = str;
			if(arg.find("-sys") != string::npos) doSys = true;
			if(arg.find("-percent") != string::npos) percent = true;
			if(arg.find("-o") != string::npos) outFileName = str;
			if(arg.find("-jpsi") != string::npos) jpsi = true;
		}
	}
	
	if(jpsi) { if(xvarname=="q2") xbins = decodeBinning("[1,0,25]",&xnbins); rel = false; doSys = false; }

	// Set trees of cancdidates previously created

	TString mctype = "MC_Pythia8_NBweighted";
	if(pythia6) mctype = "MC_Pythia6_NBweighted"; 
	TString weight = "MCnorm*(lifeTimeW > 0)*(physRate_pol0_noDecay > 0)";
	cout << "Using: " << mctype << endl;
	cout << "Plotting: " << xvar << endl;
	cout << "Binning: [";
	for(int i = 0; i < xnbins; i++) cout << xbins[i] << ",";
	cout << xbins[xnbins] << "]" << endl;	

	TString namefileMCgeom = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/Lb2Lmumu_geom"+mctype+".root";
	TString namefileMC = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/Lb2Lmumu_"+mctype+".root";
	TString namefileMCjpsi = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/Lb2JpsiL_"+mctype+".root";
	TString namefileMCjpsiGeom = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/Lb2JpsiL_geom"+mctype+".root";
	TString namefileDataJpsi = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/Lb2Lmumu_CL_NBweighted.root";

	TString nameGeomTree = "MCtree";
	if(xvar=="cosThetaB") nameGeomTree = "MCtreeDecay";
	TFile * MCfile = TFile::Open(namefileMCgeom);
	TTree * treeMCgeom = (TTree *)MCfile->Get(nameGeomTree);
	MCfile = TFile::Open(namefileMC);
	TTree * treeMC = (TTree *)MCfile->Get("tree");
	TTree * treeMCGen = (TTree *)MCfile->Get("MCtreeDecay");
	TTree * treeMCAllGen = (TTree *)MCfile->Get("MCtree");
	MCfile = TFile::Open("/afs/cern.ch/work/p/pluca/weighted/Lmumu/trainingSamples.root");
	TTree * treeMCmva = (TTree *)MCfile->Get("sigTestSample");

	TTree * treeMCjpsi = NULL, * treeMCjpsi_Gen = NULL, * treeMCjpsi_AllGen = NULL, * treeMCjpsi_geom = NULL;
	if(rel || jpsi)
	{
		
		MCfile = TFile::Open(namefileMCjpsi);
		if(jpsi) {
		treeMC = (TTree *)MCfile->Get("tree");
		treeMCmva = (TTree *)MCfile->Get("tree");
		treeMCGen = (TTree *)MCfile->Get("MCtreeDecay");
		treeMCAllGen = (TTree *)MCfile->Get("MCtree");	}
		else {
		treeMCjpsi = (TTree *)MCfile->Get("tree");
		treeMCjpsi_Gen = (TTree *)MCfile->Get("MCtreeDecay");
		treeMCjpsi_AllGen = (TTree *)MCfile->Get("MCtree");	}
		
		MCfile = TFile::Open(namefileMCjpsiGeom);		
		if(jpsi) treeMCgeom = (TTree *)MCfile->Get(nameGeomTree);
		else treeMCjpsi_geom = (TTree *)MCfile->Get(nameGeomTree);

	
/*	
		MCfile = TFile::Open(namefileMC);
		treeMCjpsi = (TTree *)MCfile->Get("tree");
		treeMCjpsi_Gen = (TTree *)MCfile->Get("MCtreeDecay");
		treeMCjpsi_AllGen = (TTree *)MCfile->Get("MCtree");	
		
		MCfile = TFile::Open(namefileMCgeom);		
		treeMCjpsi_geom = (TTree *)MCfile->Get(nameGeomTree);
*/

	}
	
	TCut geomCut = CutsDef::geomCut;
	TCut baseCut = extCut + CutsDef::baseCutMuMu;
	if(jpsi) baseCut = extCut + CutsDef::baseCutJpsi;
	TCut baseJpsiCut = extCut + CutsDef::baseCutJpsi;
	TCut binCut = "TMath::Power(J_psi_1S_MM/1000,2) > 9.1 && TMath::Power(J_psi_1S_MM/1000,2) < 10.1";
	if(type == "DD") { baseCut += CutsDef::DDcut; baseJpsiCut += CutsDef::DDcut; }
	else if(type == "LL") { baseCut += CutsDef::LLcut; baseJpsiCut += CutsDef::LLcut; }
	cout << "Analysisng " << type << " events" << endl;

	//TCut simpleEffCut = geomCut + (TCut)"TMath::Sqrt(TMath::Power(pplus_TRUEP_X,2) + TMath::Power(pplus_TRUEP_Y,2) + TMath::Power(pplus_TRUEP_Z,2)) > 6000 && TMath::Sqrt(TMath::Power(piminus_TRUEP_X,2) + TMath::Power(piminus_TRUEP_Y,2) + TMath::Power(piminus_TRUEP_Z,2)) > 2000 && TMath::Sqrt(TMath::Power(muminus_TRUEP_X,2) + TMath::Power(muminus_TRUEP_Y,2) + TMath::Power(muminus_TRUEP_Z,2)) > 3000 && TMath::Sqrt(TMath::Power(muplus_TRUEP_X,2) + TMath::Power(muplus_TRUEP_Y,2) + TMath::Power(muplus_TRUEP_Z,2)) > 3000 && pplus_TRUEPT > 400 && muplus_TRUEPT > 100 && muminus_TRUEPT > 100";


	TString myName = "Lbeff";
	if(rel) myName = "Lbreleff";
	if(doSys) myName += "AndSys";
	if(jpsi) myName += "_Jpsi"; 
	myName += ("vs"+xvarname+"_"+type+".root");
	if(outFileName!="") myName = outFileName;
	TFile * histFile = new TFile(myName,"recreate");

	/**      Calc efficiencies and systematics        */

	vector <TString> effnames;
	effnames.push_back("geom");
	effnames.push_back("det");
	effnames.push_back("reco");
	effnames.push_back("mva");
	effnames.push_back("trig");

	vector <TH1F * >  hdefault;
	vector <TH1F * >  lfsys_plus, lfsys_minus;
	vector <TH1F * >  decaysys, DDsys;
	vector <TH1F * >  polsys_minus, polsys_plus;
	vector <TH1F * >  poljpsi1, poljpsi2, poljpsi3, poljpsi4, poljpsi5, poljpsi6, poljpsi7, poljpsi8;
	
	cout << "Analysing GEO sys" << endl;
	getAllEffSys("GEO", xvar, xnbins, xbins, weight,
			treeMCgeom, geomCut+extCut, treeMCgeom, extCut,
			treeMCjpsi_geom, geomCut+extCut+binCut, treeMCjpsi_geom, extCut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "-f0.5", jpsi);

	cout << "Analysing DET sys" << endl;
	if(xvar=="cosThetaB")
		getAllEffSys("DET", xvar, xnbins, xbins, weight,
			treeMCGen, extCut, treeMCgeom, geomCut+extCut,
			treeMCjpsi_Gen, extCut+binCut, treeMCjpsi_AllGen, geomCut+extCut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "", jpsi );	
	else
		getAllEffSys("DET", xvar, xnbins, xbins, weight,
			treeMCGen, extCut, treeMCAllGen, extCut,
			treeMCjpsi_Gen, extCut+binCut, treeMCjpsi_AllGen, extCut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "", jpsi );
	
	cout << "Analysing RECO sys" << endl;
	getAllEffSys("RECO", xvar, xnbins, xbins, weight,
			treeMC, baseCut, treeMCGen, extCut,
			treeMCjpsi, baseJpsiCut+binCut, treeMCjpsi_Gen, extCut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "", jpsi );
	
	cout << "Analysing MVA sys" << endl;
	getAllEffSys("MVA", xvar, xnbins, xbins, weight,
			treeMCmva, baseCut+CutsDef::MVAcut, treeMCmva, baseCut,
			treeMCjpsi, baseJpsiCut+CutsDef::MVAcut+binCut, treeMCjpsi, baseJpsiCut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "", jpsi );

	cout << "Analysing TRIG sys" << endl;
	getAllEffSys("TRIG", xvar, xnbins, xbins, weight,
			treeMC, baseCut+CutsDef::MVAcut+CutsDef::TrigPassed, treeMC, baseCut+CutsDef::MVAcut,
			treeMCjpsi, baseJpsiCut+CutsDef::MVAcut+CutsDef::TrigPassed+binCut, treeMCjpsi, baseJpsiCut+CutsDef::MVAcut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "", jpsi );
	
	TH1F * toteff_lowSel = NULL;
	if(rel || jpsi)
	{
		TString polweight = "physRate_polp006";
		if(jpsi) polweight = "physRate_pol0";
		TH1F * mva_lowSel = getEff("UPPER", xvar, xnbins, xbins,
			treeMCmva, baseCut+CutsDef::MVAcut, treeMCmva, baseCut,
			weight+"*lifeTimeW*pt_weight*"+polweight,
			treeMCjpsi, baseJpsiCut+CutsDef::MVAcut_lowSel+binCut, treeMCjpsi, baseJpsiCut+binCut,
			weight+"*lifeTimeW*physRate_pol0*pt_weight" );
		mva_lowSel->Write("hmvaeff_lowSel");
		TH1F * uppereff_lowSel = (TH1F *)hdefault[2]->Clone("huppereff_lowSel");
		uppereff_lowSel->Multiply(hdefault[3]);
		uppereff_lowSel->Multiply(mva_lowSel);
		toteff_lowSel = (TH1F *)hdefault[0]->Clone("htoteff_lowSel");
		toteff_lowSel->Multiply(hdefault[1]);
		toteff_lowSel->Multiply(uppereff_lowSel);
		uppereff_lowSel->Write("huppereff_lowSel");
		toteff_lowSel->Write("htoteff_lowSel");
	}

	//Simply model
	//TH1F * simpleeff = getEff("SIMPLY", xvar, xnbins, xbins,
	//		treeMCgeom, simpleEffCut, treeMCgeom, "", weight);


			
	TCanvas * c = new TCanvas();
	gStyle->SetOptStat(0);
	gStyle->SetOptFit();
	TH1F * uppereff = (TH1F *)hdefault[2]->Clone("huppereff");
	uppereff->Multiply(hdefault[3]);
	uppereff->Multiply(hdefault[4]);

	TH1F * toteff = (TH1F *)hdefault[0]->Clone("htoteff");
	if(xvar=="cosThetaB") hdefault[1]->Scale(1./hdefault[1]->Integral());
	toteff->Multiply(hdefault[1]);
	toteff->Multiply(uppereff);
	toteff->SetTitle("Total eff");
	//toteff->Fit("pol2");
	c->Print("effvs"+xvarname+"_"+type+"_tot.pdf");
	toteff->Write("htoteff");
	//uppereff->Fit("pol2");
	c->Print("effvs"+xvarname+"_"+type+"_upper.pdf");
	uppereff->Write("huppereff");
	TH1F * tot_nodet_eff = (TH1F *)hdefault[0]->Clone("htot_nodet_eff");
	tot_nodet_eff->Multiply(uppereff);
	tot_nodet_eff->Write("htot_nodet_eff");
	//simpleeff->Write("simplified_eff");
	
	for(unsigned i = 0; i < effnames.size(); i++)
	{
		//hdefault[i]->Fit("pol2");
		if(!jpsi)
		for(int b = 0; b < hdefault[i]->GetNbinsX(); b++)
		{
			hdefault[i]->SetBinContent(hdefault[i]->GetXaxis()->FindBin(8.5),0);
			hdefault[i]->SetBinError(hdefault[i]->GetXaxis()->FindBin(8.5),0);
			hdefault[i]->SetBinContent(hdefault[i]->GetXaxis()->FindBin(10.5),0);
			hdefault[i]->SetBinError(hdefault[i]->GetXaxis()->FindBin(10.5),0);
		}
		if(rel) hdefault[i]->SetMinimum(0.5);
		if(rel) hdefault[i]->SetMaximum(1.5);
		hdefault[i]->Draw();
		c->Print("effvs"+xvarname+"_"+type+"_"+effnames[i]+".pdf");
		hdefault[i]->Write("h"+effnames[i]+"eff");
	}

	gStyle->SetOptFit(0);



	/** Printing out efficiencies and systematics **/

	vector <TString> sysnames;
	sysnames.push_back("Lifetime");
	sysnames.push_back("Decay Model");
	sysnames.push_back("Polarization");
	if(type=="DD") sysnames.push_back("DD vtx");
	
	/** Print efficiencies */ 

	cout << "\n\n" << xvarname << " bin " << " \t\t\t& ";
	for(unsigned s = 0; s < effnames.size(); s++) cout << effnames[s] << " \t\t\t\t& ";
	cout << "Upper \t\t\t\t& Total  \\\\" << endl;

	TGraphErrors * grtoteff = new TGraphErrors();
	TGraphErrors * grtoteff_lowSel = new TGraphErrors();
	for(int j = 1; j <= toteff->GetNbinsX(); j++)
	{
		if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
		if(xbins[j]==9.1 || xbins[j-1]==10.1) continue;
		cout << fixed << setprecision(1) << "eff " << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(5) << " \t & ";

		for(unsigned i = 0; i < hdefault.size(); i++)	
			cout << "$" << hdefault[i]->GetBinContent(j) << " \\pm " << hdefault[i]->GetBinError(j) << "$ \t & ";

		cout << "$" << uppereff->GetBinContent(j) << " \\pm " << uppereff->GetBinError(j) << "$ \t & ";
		cout << "$" << toteff->GetBinContent(j) << " \\pm " << toteff->GetBinError(j) << "$ \\\\ " << endl;

		grtoteff->SetPoint(j,toteff->GetBinCenter(j),toteff->GetBinContent(j));
		grtoteff->SetPointError(j,toteff->GetBinWidth(j)/2.,toteff->GetBinError(j));
		if(toteff_lowSel) grtoteff_lowSel->SetPoint(j,toteff_lowSel->GetBinCenter(j),toteff_lowSel->GetBinContent(j));
		if(toteff_lowSel) grtoteff_lowSel->SetPointError(j,toteff_lowSel->GetBinWidth(j)/2.,toteff_lowSel->GetBinError(j));
	}

	grtoteff->Write("toteff");
	if(toteff_lowSel) grtoteff_lowSel->Write("toteff_lowSel");
	if(!doSys) { delete MCfile; delete histFile; return 0; }


	/** Print sys separate in efficiency */
	
	vector < TH1F * > tmp;
	vector < vector < TH1F * > > sys_eff(4,tmp);
	vector < TH1F * > tot_sys_eff;

	cout << endl << endl << endl;
	if(!percent) cout << "\n\n" << xvarname << " bin\t\t& Value \t & Stats";
	else cout << "\n\n" << xvarname << " bin ";
	for(unsigned s = 0; s < sysnames.size(); s++) cout << "\t& " << sysnames[s];
	cout << " \\\\" << endl;

	for(int j = 1; j <= toteff->GetNbinsX(); j++)
	{
		if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
		if(xbins[j]==9.1 || xbins[j-1]==10.1) continue;
		cout << "-----------------------------------------------------------------------------------------" << endl;
		cout << fixed << setprecision(1) << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(3) << endl;
		cout << "-----------------------------------------------------------------------------------------" << endl;
		if(!percent) cout << fixed << setprecision(5);

		for(unsigned i = 0; i < effnames.size(); i++)
		{
			if(j==1)
			{
				sys_eff[0].push_back((TH1F*)toteff->Clone("sys_lf_"+effnames[i]));
				sys_eff[1].push_back((TH1F*)toteff->Clone("sys_decay_"+effnames[i]));
				sys_eff[2].push_back((TH1F*)toteff->Clone("sys_pol_"+effnames[i]));
				sys_eff[3].push_back((TH1F*)toteff->Clone("sys_DD_"+effnames[i]));
				tot_sys_eff.push_back((TH1F*)toteff->Clone("tot_sys_eff"));
				sys_eff[0][i]->Reset();
				sys_eff[1][i]->Reset();
				sys_eff[2][i]->Reset();
				sys_eff[3][i]->Reset();
				tot_sys_eff[i]->Reset();
			}

			double lf_sys = createSys(j,hdefault[i], lfsys_minus[i], lfsys_plus[i]);
			double decay_sys = createSys(j,hdefault[i], decaysys[i], decaysys[i]);
			double DD_sys = 0;
			double pol_sys = createSys(j, hdefault[i], polsys_minus[i], polsys_plus[i]);
			pol_sys = createSys(j, hdefault[i], poljpsi1[i], poljpsi2[i], pol_sys);
			pol_sys = createSys(j, hdefault[i], poljpsi3[i], poljpsi4[i], pol_sys);
			pol_sys = createSys(j, hdefault[i], poljpsi5[i], poljpsi6[i], pol_sys);
			pol_sys = createSys(j, hdefault[i], poljpsi7[i], poljpsi8[i], pol_sys);
			double cureff = hdefault[i]->GetBinContent(j);
			double curerr = hdefault[i]->GetBinError(j);
			double tot_eff_sys = TMath::Sqrt( TMath::Power(lf_sys,2) + TMath::Power(pol_sys,2) + TMath::Power(decay_sys,2) );
			
			if(type=="DD")
			{
				DD_sys = createSys(j, hdefault[i], DDsys[i], DDsys[i]);
				tot_eff_sys = TMath::Sqrt( TMath::Power(tot_eff_sys,2) + TMath::Power(DD_sys,2) );
				sys_eff[3][i]->SetBinContent(j,DD_sys);
			}

			cout << effnames[i] << " \t  & ";
			if(percent)
			{
				cout << lf_sys*100 << "\\% \t & " << decay_sys*100 << "\\% \t & " << pol_sys*100 << "\\% \t";
				if(type=="DD") cout << " & " << DD_sys*100 << " \t ";	
			}	
			else
			{
				cout << cureff << " \t & " << curerr << " \t & ";
				cout << lf_sys*cureff << " \t & " << decay_sys*cureff << " \t & " << pol_sys*cureff << " \t";
				if(type=="DD") cout << " & " << DD_sys*cureff << " \t";	
			}	
			cout << " \\\\ " << endl;
			sys_eff[0][i]->SetBinContent(j,lf_sys);
			sys_eff[1][i]->SetBinContent(j,decay_sys);
			sys_eff[2][i]->SetBinContent(j,pol_sys);
			tot_sys_eff[i]->SetBinContent(j,tot_eff_sys);
		}
	}


		/** Print total sys */

	vector< TH1F * > sys;
	TH1F * tot_sys = getErrHist(toteff);

	for(unsigned s = 0; s < sysnames.size(); s++)
	{
		TH1F * tmp_sys = NULL;
		
		for(unsigned i = 0; i < effnames.size(); i++)
			tmp_sys = sqSum(tmp_sys,sys_eff[s][i]); 
		
		sys.push_back( tmp_sys );
		tmp_sys->Write("sys_"+sysnames[s]);
		tot_sys = sqSum(tot_sys,tmp_sys);
	}
	tot_sys->Write("sys_tot");

	cout << endl << endl << endl;	
	if(!percent) cout << "\n\n" << xvarname << " bin\t\t& Value \t & Stats";
	else cout << "\n\n" << xvarname << " bin ";
	for(unsigned s = 0; s < sysnames.size(); s++) cout << " \t & " << sysnames[s];
	cout << " \t & Total \\\\" << endl;
	
	for(unsigned i = 0; i < effnames.size(); i++)
	{
		TGraphErrors * grtot_eff = new TGraphErrors();
		cout << endl << effnames[i] << endl;

		for(int j = 1; j <= toteff->GetNbinsX(); j++)
		{
			if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
			cout << fixed << setprecision(1) << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(3) << "  \t & ";
		
			double cureff = hdefault[i]->GetBinContent(j);
			if(!percent) cout << fixed << setprecision(5) << cureff << " \t & " << hdefault[i]->GetBinError(j) << "   \t & ";
		
			for(unsigned s = 0; s < sysnames.size(); s++)
				if(percent) cout << sys_eff[s][i]->GetBinContent(j)*100 << "\\% \t & ";
				else cout << sys_eff[s][i]->GetBinContent(j)*cureff << " \t & ";
			
			if(percent) cout << tot_sys_eff[i]->GetBinContent(j)*100 << "\\%";
			else cout << tot_sys_eff[i]->GetBinContent(j)*cureff;
			cout << " \\\\ " << endl;

			grtot_eff->SetPoint(j,tot_sys_eff[i]->GetBinCenter(j),tot_sys_eff[i]->GetBinContent(j));
			grtot_eff->SetPointError(j,tot_sys_eff[i]->GetBinWidth(j)/2.,0.);
		}

		grtot_eff->Write(effnames[i]+"sys");
	}

	cout << endl << endl;	
	if(!percent) cout << "\n\n" << xvarname << " bin\t\t& Value \t\t & Stats";
	else cout << "\n\n" << xvarname << " bin ";
	for(unsigned s = 0; s < sysnames.size(); s++) cout << " \t\t & " << sysnames[s];
	cout << " \\\\" << endl;

	TGraphErrors * grtot = new TGraphErrors();
	for(int j = 1; j <= toteff->GetNbinsX(); j++)
	{
		if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
		cout << fixed << setprecision(1) << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(3);
		double cureff = toteff->GetBinContent(j);
		if(!percent) cout << fixed << setprecision(5) << cureff << " \t\t & " << toteff->GetBinError(j);
		
		for(unsigned s = 0; s < sysnames.size(); s++)
			if(percent) cout << "  \t\t\t & " << sys[s]->GetBinContent(j)*100 << "\\% ";
			else cout << " \t\t\t & " << sys[s]->GetBinContent(j)*cureff;
			
		cout << " \\\\ " << endl;

		grtot->SetPoint(j,tot_sys->GetBinCenter(j),tot_sys->GetBinContent(j));
		grtot->SetPointError(j,tot_sys->GetBinWidth(j)/2.,0.);
	}
	
	grtot->Write("totsys");

/*
	cout << "\n\n" << xvarname << " bin\t\t& Value \\\\" << endl;
	for(int j = 1; j <= toteff->GetNbinsX(); j++)
	{
		if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
		cout << fixed << setprecision(1) << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(5) << " \t & ";
		cout << "$" << toteff->GetBinContent(j) << " \\pm " << tot_sys->GetBinContent(j)*toteff->GetBinContent(j) << "$ \\\\ " << endl;
	}
*/
	delete MCfile;
	delete histFile;
	return 0;
}
Example #20
0
void SPEFit(char * fLEDname, char * fPEDname, int run, int LED_amp, double cutmax = 250.0)
{

  //set plotting styles
  gStyle->SetCanvasColor(0);
  gStyle->SetPadColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);

    //set file names
    stringstream out_fname;
    stringstream out_fname1;
    out_fname<<"SPEconstants_Run_"<<run<<".txt";
    out_fname1<<"SPEspec_Run_"<<run<<".txt";

    ofstream  constants_file(out_fname.str().c_str(),ios_base::trunc); 
    //ofstream  constants_file1(out_fname1.str().c_str(),ios_base::trunc); 
    constants_file<<"Run "<<run<<endl;
    constants_file<<"type SPE"<<endl;
    constants_file<<"LED_amplitude "<<LED_amp<<endl<<endl;

    constants_file<<endl<<"LED_amplitude Depth Phi Eta Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;

    out_fname.str("");
    out_fname<<"SPEdistributions_Run_"<<run<<".txt";

    out_fname.str("");
    out_fname<<"SPEextra_Run_"<<run<<".txt";
    //ofstream  extra_file(out_fname.str().c_str(),ios_base::trunc); 


    double scale = 1.0;
    scale = 2.6; //Need to scale up HF charge
    double fC2electrons = 6240.; //convert fC to #electrons

    char spename[128], pedname[128], spehistname[128];
 
    TFile *tfLED = new TFile(fLEDname);
    TFile *tfPED = new TFile(fPEDname);
    


    //const int NnewBins = 106;
    //double binsX[NnewBins] = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};

    const int NnewBins = 80;
    double binsX[NnewBins] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,114,117,120,123,126,129,132,135,138,141,144,147,150,153,156,159,162,165,168,171,174,177,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};	  
    TH1F* hspe = new TH1F("hspe","hspe",NnewBins-1,binsX);


    int NDepth = 2; //number of depths
    int MinDepth = 1;
    int MaxDepth = 2;
    int MinEta = 29; 
    int MaxEta = 41;
    int MinPhi = 41;
    int MaxPhi = 53;
   
 
    TCanvas *Carray[NDepth+1][MaxPhi+1];
    bool drawflag[NDepth+1][MaxPhi+1];  
    TH1F *LED[NDepth+1][MaxEta+1][MaxPhi+1];
    TH1F *PED[NDepth+1][MaxEta+1][MaxPhi+1];

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){

	bool nonNull = false;

	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  LED[iDepth][iEta][iPhi]=(TH1F *)tfLED->Get(spename);
	  if(LED[iDepth][iEta][iPhi]) nonNull = true;
      
	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  PED[iDepth][iEta][iPhi]=(TH1F *)tfPED->Get(spename);
	}

	drawflag[iDepth][iPhi] = false;
	char canvname[16];
	sprintf(canvname, "c_%d_%d", iDepth,iPhi);
	if(nonNull){ //only create canvas if distributions exist
	  Carray[iDepth][iPhi] = new TCanvas(canvname,canvname,1200,700);
	  Carray[iDepth][iPhi]->Divide(5,3);
	}

      }
    }



    int HV=0;

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){
	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  //cout<<iDepth<<" "<<iPhi<<" "<<iEta<<endl;

	  if(!LED[iDepth][iEta][iPhi]) continue;

	  sprintf(spehistname,"led %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hspe_temp = (TH1F *)LED[iDepth][iEta][iPhi]->Clone(spehistname);
	  sprintf(spehistname,"ped %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hped = (TH1F *)PED[iDepth][iEta][iPhi]->Clone(spehistname);
	  hspe->Reset();
	  sprintf (spehistname, "SumLED_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  hspe->SetTitle(spehistname);

	  //combine bins of original SPE histogram
	  for(int ib=1; ib<=hspe_temp->GetNbinsX(); ib++) {
	    double bin_center = hspe_temp->GetBinCenter(ib);
	    if(bin_center>hspe->GetXaxis()->GetXmax()) continue;
	    int newbin = hspe->FindBin(bin_center);
	    double new_content = hspe->GetBinContent(newbin) + hspe_temp->GetBinContent(ib);
	    double new_error = sqrt(pow(hspe->GetBinError(newbin),2)+pow(hspe_temp->GetBinError(ib),2));
	    hspe->SetBinContent(newbin,new_content);
	    hspe->SetBinError(newbin,new_error);
	  }
	  TH1F* hspe_unscaled = (TH1F*)hspe->Clone("hspe_unscaled");
	  //renormalize bins of new SPE histogram
	  for(int ib=1; ib<=hspe->GetNbinsX(); ib++) {
	    double new_content = hspe->GetBinContent(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    double new_error = hspe->GetBinError(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    hspe->SetBinContent(ib,new_content);
	    hspe->SetBinError(ib,new_error);
	  }
	  
	  if(hspe_temp->Integral()==0) continue;
	  else drawflag[iDepth][iPhi] = true;	  

	  Nev = hspe_temp->Integral()*hspe_temp->GetXaxis()->GetBinWidth(1); 
	  TF1 *fped = new TF1("fped","gaus",0, 80);
	  hped->Fit(fped,"NQR");
	  double pploc = fped->GetParameter(1), ppwidth = fped->GetParameter(2);
	  hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + ppwidth);  
	  
	  //estimate SPE peak location
	  int max_SPE_bin, maxbin, Nbins;
	  double max_SPE_height=0, minheight, max_SPE_location;
	  bool minflag = false;
	  maxbin=hspe->FindBin(fped->GetParameter(1)); //location of pedestal peak
	  minheight=hspe->GetBinContent(maxbin); //initialize minheight
	  Nbins = hspe->GetNbinsX();
	  for(int j=maxbin+1; j<Nbins-1; j++) { //start from pedestal peak and loop through bins
	    if(hspe->GetBinContent(j) > minheight && !minflag) minflag=true; //only look for SPE peak when minflag=true
	    if(hspe->GetBinContent(j) < minheight )  minheight = hspe->GetBinContent(j);
	    if(minflag && hspe->GetBinContent(j) > max_SPE_height){
	      max_SPE_bin = j;
	      max_SPE_location = hspe->GetBinCenter(max_SPE_bin);
	      max_SPE_height = hspe->GetBinContent(j);
	    }
	  } //start from pedestal peak and loop through bins
	  //find minimum bin between pedestal and SPE peaks
	  hspe->GetXaxis()->SetRange(maxbin,max_SPE_bin);
	  int minbin = hspe->GetMinimumBin(); 
	  double minbin_location = hspe->GetBinCenter(minbin);
	  hspe->GetXaxis()->SetRange(1,Nbins);	    
	  
	  TF1 *fit = new TF1("fit", FitFun, 0, 500, 5);
	    
	  double mu = - log(fped->Integral(0,100)/Nev);
	  if(mu<0) mu=0.01;
	  double gain_est = max_SPE_location-1.0*fped->GetParameter(1);
	  if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, 20, 1, gain_est, gain_est*0.5);
	  else fit->SetParameters(mu, 20, 1, 2.1*fped->GetParameter(2), 10); //case of no clear minimum; start looking for SPE peak at 2sigma away from pedestal peak
	  fit->SetParLimits(0, 0, 10);
	  fit->FixParameter(1, fped->GetParameter(1));
	  fit->FixParameter(2, fped->GetParameter(2));
	  fit->SetParLimits(3, fped->GetParameter(2)*2, 350);
	  fit->SetParLimits(4, fped->GetParameter(2)*1.01, 250);
	  

	  double maxfitrange = 500.;    
	  double minfitrange = 0.;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);
	  maxfitrange = fped->GetParameter(1)+4*fit->GetParameter(3)+fit->GetParameter(4);
	  if(500<maxfitrange) maxfitrange = 500;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);

	  //calculate NDOF of fit excluding bins with 0 entries
	  int myNDOF=-3; //three free parameters
	  for(int j=hspe->FindBin(minfitrange); j<=hspe->FindBin(maxfitrange); j++) { //loop through fitted spe bins
	    if(hspe->GetBinContent(j)) myNDOF++;
	  } //loop through fitted spe bins


	  //calculate means and integrals of the fit and data
	  double fint, fint_error, hint, favg, havg;
	  int temp_lowbin, temp_highbin;
	  temp_lowbin = hspe->FindBin(minfitrange);
	  temp_highbin = hspe->FindBin(maxfitrange);
	  hspe_unscaled->GetXaxis()->SetRangeUser(minfitrange, maxfitrange);
	  havg = hspe_unscaled->GetMean();
	  hint = hspe->Integral(temp_lowbin,temp_highbin,"width");
	  double min_frange = hspe->GetBinLowEdge(temp_lowbin);
	  favg = fit->Mean(min_frange, maxfitrange);
	  fint = fit->Integral(min_frange, maxfitrange);
	  //fint_error = fit->IntegralError(min_frange, maxfitrange);
	  
	  double PE5int = 0; //integral of events with >=5 PE
	  double PE5loc =  fped->GetParameter(1)+ 5*fit->GetParameter(3);
	  if(PE5loc>500) PE5int = 0;
	  else {
	    int PE5bin =  hspe_temp->FindBin(PE5loc);
	    temp_highbin = hspe_temp->FindBin(maxfitrange)-1;
	    PE5int =  hspe_temp->Integral(PE5bin,temp_highbin,"width");
	  }
	  int PE5flag = 0;
	  if(PE5int/hint>0.05) PE5flag = 1; //set flag if more than 5% of events in the fit correspond to >=5PE
	//=========================================    
	  //for(int i1=1;i1<hspe->GetNbinsX();i1++){
	    //constants_file1<<HV<<"\t"<<iDepth<<"\t"<<iEta<<"\t"<<iPhi<<"\t"<<2.6*hspe->GetBinCenter(i1)<<"\t"<<hspe->GetBinContent(i1)<<"\t"<<fit->Eval(hspe->GetBinCenter(i1))<<"\n";
          //}
        //=========================================    

	  //printf("%d\n",myNDOF);
	  //output calibrations constants
	  //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;
	  constants_file<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	    

	  /*
	  if(iDepth==2 && iPhi==53 && iEta==36){
	    cout<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<gain_est<<" "<<fit->GetParameter(3)<<endl;
	    cout<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	  }
	  */

	  Carray[iDepth][iPhi]->cd(iEta-MinEta+1);
	  gPad->SetBorderMode(0);
	  gPad->SetBorderSize(0);
	  gPad->SetRightMargin(0.01);
	  gPad->SetBottomMargin(0.1);
	  gPad->SetLogy(true);
	  hspe->GetXaxis()->SetRangeUser(0, 200 /*300*//*508*/);
	  hspe->SetLineColor(kBlue);
	  hspe->DrawClone("hist");
	  fit->SetLineWidth(2);
	  fit->Draw("same");

	}
    
	if(drawflag[iDepth][iPhi]) { //draw plots of fit if data for the HV is present
	  stringstream plot_name;
	  plot_name<<"Plots/SPEFits_Run_"<<run<<"_Depth"<<iDepth<<"_Phi"<<iPhi<<".pdf";
	  Carray[iDepth][iPhi]->SaveAs(plot_name.str().c_str());
	  plot_name.str( std::string() );
	}

      }
    }

    constants_file.close();
    //constants_file1.close();
}
void hand_beam_asymmetry_vs_nu(){

	bool includeVetos;
// 	If includeVetos = false, then only good bars will be displayed. If 
//	includeVetos = true, then veto bars will be shown along with the good bars.
//	includeVetos = true;
	includeVetos = false;

	bool includeAntivetos;
// 	If includeAntivetos = false, then only good bars will be displayed. If 
//	includeAntivetos = true, then antiveto bars will be shown along with the good bars.
//	includeAntivetos = true;
	includeAntivetos = false;

	bool antivetosAsVetos;
//	If antivetosAsVetos = false, then the antivetos will not be included in the veto cut
//	If antivetosAsVetos = true, then the antivetos will be included in the veto cut
//	Discusses elsewhere, antivetos are the bars immediately following a goodBar
	antivetosAsVetos = false;
//	antivetosAsVetos = true;

	bool drawCuts = true;
//	bool drawCuts = false;

// 	The SinglePlane and SingleBar booleans skip the loop that goes over
// 	ever bar into just a single plane and/or a single bar.
	bool SinglePlane;
	bool SingleBar;
	int singleplane;
	int singlebar;
//	SinglePlane = true;
	SinglePlane = false;
	singleplane = 2;
//	SingleBar = true;
	SingleBar = false;
	singlebar = 10;
/*
	int HeRunNumber = 22441;
	int endHeRunNumber = 22441;
	TString Q2 = "1.0";
	double q2min = 0.75;
	double q2max = 1.2;
	double numin = 0.3;
	double numax = 0.7;
	int Positionbins = 30;
	double Positionmin = -30;
	double Positionmax = 30;
	int TDCbins = 100;
	double TDCmin = 700;
	double TDCmax = 800;
	int ADCbins = 700;
	double ADCmin = -100;
	double ADCmax = 11100;
	double goodTDCleftcutmin = 752;
	double goodTDCleftcutmax = 775;
	double goodTDCrightcutmin = 752;
	double goodTDCrightcutmax = 775;
	double vetoTDCcutmin = 750;
	double vetoTDCcutmax = 785;
*/
/*
// ********* Vertical, Q2=1.0 *******************
	int HeRunNumber = 20596;
	int endHeRunNumber = 20683;
	TString Q2 = "1.0";
	double q2min = 0.75;
	double q2max = 1.2;
	double numin = 0.3;
	double numax = 0.7;
	int Positionbins = 30;
	double Positionmin = -30;
	double Positionmax = 30;
	int TDCbins = 200;
	double TDCmin = 1300;
	double TDCmax = 1700;
	int ADCbins = 700;
	double ADCmin = -100;
	double ADCmax = 11100;
	double goodTDCleftcutmin = 1385;
	double goodTDCleftcutmax = 1415;
	double goodTDCrightcutmin = 1385;
	double goodTDCrightcutmax = 1415;
	double vetoTDCcutmin = 1385;
	double vetoTDCcutmax = 1415;
*/
/*
// ********* Vertical, Q2=0.5 *******************
	int HeRunNumber = 20890;
	int endHeRunNumber = 20890;
	TString Q2 = "0.5";
	double q2min = 0.3;
	double q2max = 0.6;
	double numin = 0.1;
	double numax = 0.35;
	int Positionbins = 30;
	double Positionmin = -30;
	double Positionmax = 30;
	int TDCbins = 75;
	double TDCmin = 1300;
	double TDCmax = 1500;
	int ADCbins = 700;
	double ADCmin = -100;
	double ADCmax = 11100;
	double goodTDCleftcutmin = 1385;
	double goodTDCleftcutmax = 1415;
	double goodTDCrightcutmin = 1385;
	double goodTDCrightcutmax = 1415;
	double vetoTDCcutmin = 1385;
	double vetoTDCcutmax = 1415;
*/

/*
// ********* Vertical, Q2=0.42 *******************
	int HeRunNumber = 21383;
	int endHeRunNumber = 21387;
	TString Q2 = "0.42";
	double q2min = 0.33;
	double q2max = 0.51;
	double numin = 0.17;
	double numax = 0.3;
	int Positionbins = 30;
	double Positionmin = -30;
	double Positionmax = 30;
	int TDCbins = 50;
	double TDCmin = 700;
	double TDCmax = 800;
	int ADCbins = 700;
	double ADCmin = -100;
	double ADCmax = 11100;
	double goodTDCleftcutmin = 730;
	double goodTDCleftcutmax = 770;
	double goodTDCrightcutmin = 740;
	double goodTDCrightcutmax = 780;
	double vetoTDCcutmin = 730;
	double vetoTDCcutmax = 770;
*/
/*
	int HeRunNumber = 21714;
	int endHeRunNumber = 22248;
	TString Q2 = "0.52";
	double q2min = 0.33;
	double q2max = 0.62;
	double numin = 0.17;
	double numax = 0.35;
	int Positionbins = 30;
	double Positionmin = -30;
	double Positionmax = 30;
	int TDCbins = 50;
	double TDCmin = 700;
	double TDCmax = 800;
	int ADCbins = 700;
	double ADCmin = -100;
	double ADCmax = 11100;
	double goodTDCleftcutmin = 730;
	double goodTDCleftcutmax = 770;
	double goodTDCrightcutmin = 740;
	double goodTDCrightcutmax = 780;
	double vetoTDCcutmin = 730;
	double vetoTDCcutmax = 770;
*/

// ********* Transverse, Q2=1.0 *******************
	int HeRunNumber = 22450;
	int endHeRunNumber = 22450;
//	int endHeRunNumber = 22489;
	TString Q2 = "1.0";
	double q2min = 0.75;
	double q2max = 1.2;
	double numin = 0.3;
	double numax = 0.7;
	int Positionbins = 30;
	double Positionmin = -30;
	double Positionmax = 30;
	int TDCbins = 100;
	double TDCmin = 650;
	double TDCmax = 850;
/*
	int TDCbins = 600;
	double TDCmin = 0;
	double TDCmax = 1600;
*/
	int ADCbins = 700;
	double ADCmin = -100;
	double ADCmax = 11100;

/*	double goodTDCleftcutmin = 745;
	double goodTDCleftcutmax = 775;
	double goodTDCrightcutmin = 750;
	double goodTDCrightcutmax = 780;
*/
//	double goodTDCleftcutmin = 645;
//	double goodTDCleftcutmax = 875;
//	double goodTDCrightcutmin = 650;
//	double goodTDCrightcutmax = 880;

	double goodTDCleftcutmin = 1;
	double goodTDCleftcutmax = 1600;
	double goodTDCrightcutmin = 1;
	double goodTDCrightcutmax = 1600;



	double vetoTDCcutmin = 745;
	double vetoTDCcutmax = 780;



//	const int nuBins = 50;
	const int nuBins = 10;
	double nuMin = 0.35;
	double nuMax = 0.65;

	double xmin = 0.6;
	double xmax = 3.0;

	int bins = 50;

	TString outputPlotsHere = "/home/ellie/physics/e05-102/images/plots_for_hand/hand_beam_asymmetry_vs_nu/";

	TString outputRootString = outputPlotsHere;
	outputRootString += "hand_beam_asym_vs_nu_for_runs_";
	outputRootString += HeRunNumber;
	outputRootString += "-";
	outputRootString += endHeRunNumber;
	outputRootString += ".root";
//	TFile *outputRoot = new TFile(outputRootString,"RECREATE");
	TFile outputRoot(outputRootString,"RECREATE");

	outputRoot.Close();

	TString asymOutFileName = outputPlotsHere;
	asymOutFileName += "target_asymmetry_for_runs_";
	asymOutFileName += HeRunNumber;
	asymOutFileName += "-";
	asymOutFileName += endHeRunNumber;
	if (includeVetos) asymOutFileName += "-with-vetos";
	asymOutFileName += ".txt";
	ofstream asymOutFile;
	asymOutFile.open(asymOutFileName);

	// Although declared here, the goodTDCcut is actually made down below where  it can be included
	// in the loop so that it is easy to have it change for each good bar when done one at a time.
	// However, the left and right min and max TDC values are defined here
	TCut goodTDCcut = "";

	TChain* chainHe = new TChain("T");
	TString filenameHe;

	for (int thisHeRunNumber=HeRunNumber; thisHeRunNumber<(endHeRunNumber+1); thisHeRunNumber++)
	{
		// Skipping Vertical Non-Production Runs
		if(thisHeRunNumber==20591){thisHeRunNumber=20596;}
		if(thisHeRunNumber==20731){thisHeRunNumber=20738;}
		if(thisHeRunNumber==20732){thisHeRunNumber=20738;}
		if(thisHeRunNumber==20733){thisHeRunNumber=20738;}
		if(thisHeRunNumber==20734){thisHeRunNumber=20738;}
		if(thisHeRunNumber==20736){thisHeRunNumber=20738;}
		if(thisHeRunNumber==20737){thisHeRunNumber=20738;}
		if(thisHeRunNumber==20762){thisHeRunNumber=20789;}
		if(thisHeRunNumber==20763){thisHeRunNumber=20789;}
		if(thisHeRunNumber==20764){thisHeRunNumber=20789;}
		if(thisHeRunNumber==20791){thisHeRunNumber=20814;}
		if(thisHeRunNumber==20792){thisHeRunNumber=20814;}

		// Skipping Longitudinal Non-Production Runs
		if(thisHeRunNumber==22380){thisHeRunNumber=22393;}
		if(thisHeRunNumber==22389){thisHeRunNumber=22393;}
		if(thisHeRunNumber==22425){thisHeRunNumber=22436;}
		if(thisHeRunNumber==22426){thisHeRunNumber=22436;}

		// Skipping Transverse Non-Production Runs
		if(thisHeRunNumber==22461){thisHeRunNumber=22465;}


		for (int t=0; t<1000; t++)
		{
			filenameHe = "/home/ellie/physics/e05-102/ellana/ROOTfiles/e05102_R_";
			filenameHe += thisHeRunNumber;
			if (t != 0)
			{
				filenameHe += "_";
				filenameHe += t;
			}
			filenameHe += ".root";
			ifstream ifileHe(filenameHe);
			if (ifileHe)
			{
				cout << "Adding file to chainHe: " << filenameHe << endl;
				chainHe->Add(filenameHe);
			}
			else
			{
				cout << "File " << filenameHe << " does not exist. Ending here." << endl;
				t=999999999;
			}
			TFile fileHe(filenameHe);
		}
	}

	gStyle->SetPalette(1);

	TCut cut = ""; TCut kinematics = ""; TCut eventtype = ""; TCut dp = ""; TCut target = "";
	TCut tracks = ""; TCut thph = ""; TCut xbj = ""; TCut pssh = ""; TCut cerenkov = "";
	TCut q2nu = ""; TCut basic = ""; TCut cuts = "";

	TString imageCutsTitle = outputPlotsHere;
	imageCutsTitle += "HAND_plots_Run_Num_";
	imageCutsTitle += HeRunNumber;
	imageCutsTitle += "-";
	imageCutsTitle += endHeRunNumber;
	imageCutsTitle += "_basic_cuts";
	if (includeVetos) imageCutsTitle += "_with_vetos";
	if (includeAntivetos) {imageCutsTitle += "_with_antivetos";}
	if (antivetosAsVetos && includeAntivetos) {imageCutsTitle += "_as_vetos";}
	imageCutsTitle += ".png";

	hand_basic_cuts(cut, kinematics, eventtype, dp, target, tracks, thph, xbj, pssh, cerenkov, q2nu, basic, cuts, imageCutsTitle, HeRunNumber, endHeRunNumber, chainHe, numin, numax, q2min, q2max, bins, xmin, xmax, drawCuts, Q2, outputRootString);

	TFile *outputRoot1 = new TFile(outputRootString,"UPDATE");

	TString cutstring = TString(cuts);
	cout << "Cuts: " << cutstring << endl;
// **********************************************************************************************
	gStyle->SetOptFit(1111);
        TString veto1plane = "";
        TString veto1bar = "";
        TString veto2plane = "";
        TString veto2bar = "";
        TString veto3plane = "";
        TString veto3bar = "";
        TString veto4plane = "";
        TString veto4bar = "";
        TString veto5plane = "";
        TString veto5bar = "";
        TString veto6plane = "";
        TString veto6bar = "";
        TString antiveto1plane = "";
        TString antiveto1bar = "";
        TString antiveto2plane = "";
        TString antiveto2bar = "";
        TString antiveto3plane = "";
        TString antiveto3bar = "";
        TString allVetos = "";
        TString allAntivetos = "";
        TString vetoTDCslSt = "";
        TString vetoTDCsrSt = "";
        TCut vetoTDCsl = "";
        TCut vetoTDCsr = "";
        TCut vetoTDCs = "";
        TString antivetosTDCslSt = "";
        TString antivetosTDCsrSt = "";
	int maxbars = 0;
	int vetoplane = 0;
	int padBins = 0;
	double padMin = 0;
	double padMax = 0;

// **********************************************************************************************
// This bit of code should set the charge and livetime scaling factors
        double HeChargeScale; double Helivetime;
        double HeChargeScaleUp; double HelivetimeUp;
        double HeChargeScaleDown; double HelivetimeDown;
        double BeamChargeScaleUp; double BeamlivetimeUp;
        double BeamChargeScaleDown; double BeamlivetimeDown;
        hand_scaling_factors(HeRunNumber, endHeRunNumber, HeChargeScale, Helivetime, HeChargeScaleUp, HelivetimeUp, HeChargeScaleDown, HelivetimeDown, BeamChargeScaleUp, BeamlivetimeUp, BeamChargeScaleDown, BeamlivetimeDown);
	HeChargeScale = 0.00001 * int(HeChargeScale * 100000.0 + 0.5);
	HeChargeScaleUp = 0.00001 * int(HeChargeScaleUp * 100000.0 + 0.5);
	HeChargeScaleDown = 0.00001 * int(HeChargeScaleDown * 100000.0 + 0.5);
	BeamChargeScaleUp = 0.00001 * int(BeamChargeScaleUp * 100000.0 + 0.5);
	BeamChargeScaleDown = 0.00001 * int(BeamChargeScaleDown * 100000.0 + 0.5);
	Helivetime = 0.0001 * int(Helivetime * 10000.0 + 0.5);
	HelivetimeUp = 0.0001 * int(HelivetimeUp * 10000.0 + 0.5);
	HelivetimeDown = 0.0001 * int(HelivetimeDown * 10000.0 + 0.5);
	BeamlivetimeUp = 0.0001 * int(BeamlivetimeUp * 10000.0 + 0.5);
	BeamlivetimeDown = 0.0001 * int(BeamlivetimeDown * 10000.0 + 0.5);
	cout << "HeChargeScale: " << HeChargeScale << "C, Helivetime: " << Helivetime << endl;
	cout << "HeChargeScaleUp: " << HeChargeScaleUp << "C, HelivetimeUp: " << HelivetimeUp << endl;
	cout << "HeChargeScaleDown: " << HeChargeScaleDown << "C, HelivetimeDown: " << HelivetimeDown << endl;
	cout << "BeamChargeScaleUp: " << BeamChargeScaleUp << "C, BeamlivetimeUp: " << BeamlivetimeUp << endl;
	cout << "BeamChargeScaleDown: " << BeamChargeScaleDown << "C, BeamlivetimeDown: " << BeamlivetimeDown << endl;

// **********************************************************************************************

// The section below plots the HAND data
// **********************************************************************************************
//	int whichplane = 0;
	int whichplane = 1;
	int endplane = 5;
	if (SinglePlane) {whichplane = singleplane; endplane = singleplane+1;}
	int whichbar=0;
//	int whichbar=11;
	TString titleTotalSpinUpx = "Total Helicity Up vs. xBj";
	if (includeVetos) {titleTotalSpinUpx += " with vetos";}
	else {titleTotalSpinUpx += " without vetos";}
	titleTotalSpinUpx += " with goodTDC cuts";
	cout << "Drawing " << titleTotalSpinUpx << "..." << endl;
	TString plotTotalSpinUpx = "HANDTotalSpinUpx";
	TH1F *HANDTotalSpinUpx = new TH1F(plotTotalSpinUpx,titleTotalSpinUpx,nuBins,nuMin,nuMax);
	TString titleTotalSpinDownx = "Total Spin Down vs. xBj";
	if (includeVetos) {titleTotalSpinDownx += " with vetos";}
	else {titleTotalSpinDownx += " without vetos";}
	titleTotalSpinDownx += " with goodTDC cuts";
	cout << "Drawing " << titleTotalSpinDownx << "..." << endl;
	TString plotTotalSpinDownx = "HANDTotalSpinDownx";
	TH1F *HANDTotalSpinDownx = new TH1F(plotTotalSpinDownx,titleTotalSpinDownx,nuBins,nuMin,nuMax);

	for (int nplane=whichplane; nplane<endplane; nplane++)
	{
		if (nplane==0) maxbars=32;
		if (nplane==1) maxbars=30;
		if (nplane==2) maxbars=24;
		if (nplane==3) maxbars=22;
		if (nplane==4) maxbars=12;
		if (SingleBar) {whichbar = singlebar; maxbars = singlebar + 1;}
		for (int thisbar=whichbar; thisbar<maxbars; thisbar++)
		{

			TString goodPlane = nplane;
			TString goodPMT = thisbar;
			hand_define_vetos(includeVetos, includeAntivetos, antivetosAsVetos, nplane, thisbar, veto1plane, veto2plane, veto3plane, veto4plane, veto5plane, veto6plane, veto1bar, veto2bar, veto3bar, veto4bar, veto5bar, veto6bar, antiveto1plane, antiveto2plane, antiveto3plane, antiveto1bar, antiveto2bar, antiveto3bar, allVetos, allAntivetos, vetoTDCslSt, vetoTDCsrSt, vetoTDCsl, vetoTDCsr, vetoTDCs, vetoTDCcutmin, vetoTDCcutmax, antivetosTDCslSt, antivetosTDCsrSt);
			
			TString goodBar = "nd.p";
			goodBar += nplane;
			goodBar += ".";
			goodBar += thisbar;
			goodBar += " ";
			cout << "Good Bar: " << goodBar << endl;

			TString goodTDCl = "NA.nd.p";
			goodTDCl += nplane;
			if (nplane == 0) goodTDCl = "NA.veto";
			goodTDCl += ".lt_c[";
			goodTDCl += thisbar;
			goodTDCl += "]";
			TString goodTDCr = "NA.nd.p";
			goodTDCr += nplane;
			if (nplane == 0) goodTDCr = "NA.veto";
			goodTDCr += ".rt_c[";
			goodTDCr += thisbar;
			goodTDCr += "]";
			TString goodTDCs = goodTDCl;
			goodTDCs += ":";
			goodTDCs += goodTDCr;
		
                        TString goodADCl = "NA.nd.p";
                        goodADCl += nplane;
                        if (nplane == 0) goodADCl = "NA.veto";
                        goodADCl += ".la_c[";
                        goodADCl += thisbar;
                        goodADCl += "]";
                        TString goodADCr = "NA.nd.p";
                        goodADCr += nplane;
                        if (nplane == 0) goodADCr = "NA.veto";
                        goodADCr += ".ra_c[";
                        goodADCr += thisbar;
                        goodADCr += "]";
                        TString goodADCs = goodADCl;
                        goodADCs += ":";
                        goodADCs += goodADCr;
	
			TString canvasName = "handp";
			canvasName += nplane;
			canvasName += "b";
			canvasName += thisbar;
			TString canvasTitle = "HAND - Plane ";
			canvasTitle += nplane;
			canvasTitle += ", Bar ";
			canvasTitle += thisbar;
			TCanvas *handCanvas = new TCanvas(canvasName,canvasTitle,1400,770); //x,y
			handpad01 =  new TPad("handpad01","handpad01",0.0000,0.0000,0.1000,1.0000,0,0,0);
			handpad02 =  new TPad("handpad02","handpad02",0.1000,0.6666,0.5500,1.0000,0,0,0);
			handpad03 =  new TPad("handpad03","handpad03",0.5500,0.6666,1.0000,1.0000,0,0,0);
			handpad04 =  new TPad("handpad04","handpad04",0.1000,0.3333,0.5500,0.6666,0,0,0);
			handpad05 =  new TPad("handpad05","handpad05",0.5500,0.3333,1.0000,0.6666,0,0,0);
			handpad06 =  new TPad("handpad06","handpad06",0.1000,0.0000,0.5500,0.3333,0,0,0);
			handpad07 =  new TPad("handpad07","handpad07",0.5500,0.0000,1.0000,0.3333,0,0,0);
			handpad01->Draw(); handpad02->Draw(); handpad03->Draw(); handpad04->Draw(); handpad05->Draw();
			handpad06->Draw(); handpad07->Draw();

			// This section will run hand_draw.h which will draw the HAND in handpad01.
			handpad01->cd();
			hand_draw(HeRunNumber, endHeRunNumber, antivetosAsVetos, allVetos, goodBar, allAntivetos);
			handpad01->Update();

			TString goodTDCleftcutString = "(NA.nd.p";
			goodTDCleftcutString += nplane;
			if (nplane == 0) {goodTDCleftcutString = "(NA.veto";}
			goodTDCleftcutString += ".lt_c[";
			goodTDCleftcutString += thisbar;
			goodTDCleftcutString += "]>";
			goodTDCleftcutString += goodTDCleftcutmin;
			if (nplane > 0)
			{
				goodTDCleftcutString += " && NA.nd.p";
				goodTDCleftcutString += nplane;
			}
			if (nplane == 0) {goodTDCleftcutString += " && NA.veto";}
			goodTDCleftcutString += ".lt_c[";
			goodTDCleftcutString += thisbar;
			goodTDCleftcutString += "]<";
			goodTDCleftcutString += goodTDCleftcutmax;
			goodTDCleftcutString += ")";
			cout << "goodTDCleftcutString = " << goodTDCleftcutString << endl;
			TCut goodTDCleftcut = goodTDCleftcutString;
	
			TString goodTDCrightcutString = "(NA.nd.p";
			goodTDCrightcutString += nplane;
			if (nplane == 0) {goodTDCrightcutString = "(NA.veto";}
			goodTDCrightcutString += ".rt_c[";
			goodTDCrightcutString += thisbar;
			goodTDCrightcutString += "]>";
			goodTDCrightcutString += goodTDCrightcutmin;
			if (nplane > 0)
			{
				goodTDCrightcutString += " && NA.nd.p";
				goodTDCrightcutString += nplane;
			}
			if (nplane == 0) {goodTDCrightcutString += " && NA.veto";}
			goodTDCrightcutString += ".rt_c[";
			goodTDCrightcutString += thisbar;
			goodTDCrightcutString += "]<";
			goodTDCrightcutString += goodTDCrightcutmax;
			goodTDCrightcutString += ")";
			cout << "goodTDCrightcutString = " << goodTDCrightcutString << endl;
			TCut goodTDCrightcut = goodTDCrightcutString;
		
			TString firstTrackString = "NA.n.plane==";
			firstTrackString += (nplane - 1);
			firstTrackString += " && NA.n.pad==";
			firstTrackString += thisbar;
			TCut firstTrack = firstTrackString;

	
			goodTDCcut = (goodTDCleftcut || goodTDCrightcut);

//			cout << "Cuts: " << cutstring << endl;
			TString vetoCutString = TString(vetoTDCs);
//			cout << "Veto Cuts: " << vetoCutString << endl; 

			handpad02->cd();
			TString titleHANDleft = "Left TDC for Plane #";
			titleHANDleft += nplane;
			titleHANDleft += ", PMT # ";
			titleHANDleft += thisbar;
			if (includeVetos) {titleHANDleft += " with vetos";}
			else {titleHANDleft += " without vetos";}
			cout << "Drawing " << titleHANDleft << "..." << endl;
			TString plotHANDleft = "HANDleft_p";
			plotHANDleft += nplane;
			plotHANDleft += "_b";
			plotHANDleft += thisbar;
			TString plotHANDleftcut = plotHANDleft;
			plotHANDleftcut += "_cut";
//			cout << "plotHANDleft: " << plotHANDleft << ", plotHANDleftcut: " << plotHANDleftcut << endl;
			cout << "goodTDCl: " << goodTDCl << endl;
			TH1F *HANDleft = new TH1F(plotHANDleft,titleHANDleft,TDCbins,TDCmin,TDCmax);
			HANDleft->SetMinimum(0);
			TH1F *HANDleftcut = new TH1F(plotHANDleftcut,titleHANDleft,TDCbins,TDCmin,TDCmax);
			HANDleftcut->SetMinimum(0);
			TString HANDleftTDC = goodTDCl;
			HANDleftTDC += ">>";
			HANDleftTDC += plotHANDleft;
			TString HANDleftTDCcut = goodTDCl;
			HANDleftTDCcut += ">>";
			HANDleftTDCcut += plotHANDleftcut;
			chainHe->Draw(HANDleftTDC, cuts && vetoTDCs && firstTrack,"");
//			chainHe->Draw(HANDleftTDC, vetoTDCs,"");
//			HANDleft->Scale(1/(HeChargeScale*Helivetime));
			HANDleft->Write();
			HANDleft->Draw();
			if (!includeVetos) {chainHe->Draw(HANDleftTDCcut, cuts && goodTDCleftcut&& firstTrack,"same");}
			if (includeVetos) {chainHe->Draw(HANDleftTDCcut, cuts && vetoTDCs && goodTDCleftcut && firstTrack,"same");}
			HANDleftcut->SetFillColor(kViolet);
//			HANDleftcut->Scale(1/(HeChargeScale*Helivetime));
			HANDleftcut->Write();
			HANDleftcut->Draw("same");
			// ********************************************************************************
			// This section below gathers and prints some statistics on the plot
			double numHANDleftcutEvents = 0;
			for (int i=0; i<TDCbins; i++){ numHANDleftcutEvents = numHANDleftcutEvents + HANDleftcut->GetBinContent(i);}
			TString HANDleftFactorsString = "Total Charge for Runs: ";
			HANDleftFactorsString += HeChargeScale;
			HANDleftFactorsString += " C";
			TString HANDleftFactorsString1 = "Total Livetime for Runs: ";
			HANDleftFactorsString1 += Helivetime;
			TString HANDleftFactorsString2 = "# of Cut (Purple) Events: ";
			HANDleftFactorsString2 += numHANDleftcutEvents;
			HANDleftFactors = new TPaveText(0.11,0.69,0.4,0.89,"NDC");
			TText *t1 = HANDleftFactors->AddText(HANDleftFactorsString);
			TText *t2 = HANDleftFactors->AddText(HANDleftFactorsString1);
			TText *t2 = HANDleftFactors->AddText(HANDleftFactorsString2);
			HANDleftFactors->Write();
			HANDleftFactors->Draw("same");
			// ********************************************************************************
			handpad02->Update();

			handpad03->cd();
			TString titleHANDright = "Right TDC for Plane #";
			titleHANDright += nplane;
			titleHANDright += ", PMT # ";
			titleHANDright += thisbar;
			if (includeVetos) {titleHANDright += " with vetos";}
			else {titleHANDright += " without vetos";}
			TString plotHANDright = "HANDright_p";
			plotHANDright += nplane;
			plotHANDright += "_b";
			plotHANDright += thisbar;
			TString plotHANDrightcut = plotHANDright;
			plotHANDrightcut += "_cut";
			cout << "Drawing " << titleHANDright << "..." << endl;
			TH1F *HANDright = new TH1F(plotHANDright,titleHANDright,TDCbins,TDCmin,TDCmax);
			HANDright->SetMinimum(0);
			TH1F *HANDrightcut = new TH1F(plotHANDrightcut,titleHANDright,TDCbins,TDCmin,TDCmax);
			HANDrightcut->SetMinimum(0);
			TString HANDrightTDC = goodTDCr;
			HANDrightTDC += ">>";
			HANDrightTDC += plotHANDright;
			TString HANDrightTDCcut = goodTDCr;
			HANDrightTDCcut += ">>";
			HANDrightTDCcut += plotHANDrightcut;
			chainHe->Draw(HANDrightTDC, cuts && vetoTDCs && firstTrack,"");
//			HANDright->Scale(1/(HeChargeScale*Helivetime));
			HANDright->Write();
			HANDright->Draw();
			if (!includeVetos) {chainHe->Draw(HANDrightTDCcut, cuts && firstTrack && goodTDCrightcut,"same");}
			if (includeVetos) {chainHe->Draw(HANDrightTDCcut, cuts && vetoTDCs && goodTDCrightcut && firstTrack,"same");}
			HANDrightcut->SetFillColor(kViolet);
//			HANDrightcut->Scale(1/(HeChargeScale*Helivetime));
			HANDrightcut->Write();
			HANDrightcut->Draw("same");
			// ********************************************************************************
			// This section below gathers and prints some statistics on the plot
			double numHANDrightcutEvents = 0;
			for (int j=0; j<TDCbins; j++){ numHANDrightcutEvents = numHANDrightcutEvents + HANDrightcut->GetBinContent(j);}
			TString HANDrightFactorsString = "Total Charge for Runs: ";
			HANDrightFactorsString += HeChargeScale;
			HANDrightFactorsString += " C";
			TString HANDrightFactorsString1 = "Total Livetime for Runs: ";
			HANDrightFactorsString1 += Helivetime;
			TString HANDrightFactorsString2 = "# of Cut (Purple) Events: ";
			HANDrightFactorsString2 += numHANDrightcutEvents;
			HANDrightFactors = new TPaveText(0.11,0.69,0.4,0.89,"NDC");
			TText *t1 = HANDrightFactors->AddText(HANDrightFactorsString);
			TText *t2 = HANDrightFactors->AddText(HANDrightFactorsString1);
			TText *t2 = HANDrightFactors->AddText(HANDrightFactorsString2);
			HANDrightFactors->Write();
			// ********************************************************************************
			handpad03->Update();

			handpad04->cd();
			cout << "Drawing Helicity Up vs. xBj..." << endl;
			TString titleSpinUpx = "Helicity Up vs. xBj for Plane #";
			titleSpinUpx += nplane;
			titleSpinUpx += ", PMT # ";
			titleSpinUpx += thisbar;
			if (includeVetos) {titleSpinUpx += " with vetos";}
			else {titleSpinUpx += " without vetos";}
			TString titleSpinUpxcut = titleSpinUpx;
			titleSpinUpxcut += " with goodTDC cuts";
			cout << "Drawing " << titleSpinUpx << "..." << endl;
			TString plotSpinUpx = "HANDSpinUpx_p";
			plotSpinUpx += nplane;
			plotSpinUpx += "_b";
			plotSpinUpx += thisbar;
			TH1F *HANDSpinUpx = new TH1F(plotSpinUpx,titleSpinUpxcut,nuBins,nuMin,nuMax);
			TString HANDSpinUpxString = "PriKineR.nu";
			HANDSpinUpxString += ">>";
			HANDSpinUpxString += plotSpinUpx;
			if (includeVetos) {chainHe->Draw(HANDSpinUpxString, cuts && vetoTDCs && goodTDCcut && firstTrack && "((g0hel.R.helicity==1 && g.runnum<22467) || (g0hel.R.helicity==-1 && g.runnum>22468))","");}
			if (!includeVetos) {chainHe->Draw(HANDSpinUpxString, cuts && firstTrack && goodTDCcut && "((g0hel.R.helicity==1 && g.runnum<22467) || (g0hel.R.helicity==-1 && g.runnum>22468))","");}
			HANDSpinUpx->SetMinimum(0);
			HANDSpinUpx->Write();
			HANDSpinUpx->Draw();
			handpad04->Update();

			handpad05->cd();
			cout << "Drawing Helicity Down vs. xBj..." << endl;
			TString titleSpinDownx = "Helicity Down vs. xBj for Plane #";
			titleSpinDownx += nplane;
			titleSpinDownx += ", PMT # ";
			titleSpinDownx += thisbar;
			if (includeVetos) {titleSpinDownx += " with vetos";}
			else {titleSpinDownx += " without vetos";}
			TString titleSpinDownxcut = titleSpinDownx;
			titleSpinDownxcut += " with goodTDC cuts";
			cout << "Drawing " << titleSpinDownx << "..." << endl;
			TString plotSpinDownx = "HANDSpinDownx_p";
			plotSpinDownx += nplane;
			plotSpinDownx += "_b";
			plotSpinDownx += thisbar;
			TH1F *HANDSpinDownx = new TH1F(plotSpinDownx,titleSpinDownxcut,nuBins,nuMin,nuMax);
			TString HANDSpinDownxString = "PriKineR.nu";
			HANDSpinDownxString += ">>";
			HANDSpinDownxString += plotSpinDownx;
			if (includeVetos) {chainHe->Draw(HANDSpinDownxString, cuts && vetoTDCs && goodTDCcut && firstTrack && "((g0hel.R.helicity==-1 && g.runnum<22467) || (g0hel.R.helicity==1 && g.runnum>22468))","");}
			if (!includeVetos) {chainHe->Draw(HANDSpinDownxString, cuts && firstTrack && goodTDCcut && "((g0hel.R.helicity==-1 && g.runnum<22467) || (g0hel.R.helicity==1 && g.runnum>22468))","");}
			HANDSpinDownx->SetMinimum(0);
			HANDSpinDownx->Write();
			HANDSpinDownx->Draw();
			handpad05->Update();

			handpad06->cd();
			cout << "Drawing Total Helicity Up vs. xBj..." << endl;
//			TString titleTotalSpinUpx = "Total Spin Up vs. xBj";
//			if (includeVetos) {titleTotalSpinUpx += " with vetos";}
//			else {titleTotalSpinUpx += " without vetos";}
//			titleTotalSpinUpx += " with goodTDC cuts";
//			cout << "Drawing " << titleTotalSpinUpx << "..." << endl;
//			TString plotTotalSpinUpx = "HANDTotalSpinUpx";
//			TH1F *HANDTotalSpinUpx = new TH1F(plotTotalSpinUpx,titleTotalSpinUpx,nuBins,nuMin,nuMax);
			HANDTotalSpinUpx->Add(HANDSpinUpx);
			HANDTotalSpinUpx->SetMinimum(0);
			HANDTotalSpinUpx->Write();
			HANDTotalSpinUpx->Draw();
			handpad06->Update();

			handpad07->cd();
			cout << "Drawing Total Helicity Down vs. xBj..." << endl;
//			TString titleTotalSpinDownx = "Total Spin Down vs. xBj";
//			if (includeVetos) {titleTotalSpinDownx += " with vetos";}
//			else {titleTotalSpinDownx += " without vetos";}
//			titleTotalSpinDownx += " with goodTDC cuts";
//			cout << "Drawing " << titleTotalSpinDownx << "..." << endl;
//			TString plotTotalSpinDownx = "HANDTotalSpinDownx";
//			TH1F *HANDTotalSpinDownx = new TH1F(plotTotalSpinDownx,titleTotalSpinDownx,nuBins,nuMin,nuMax);
			HANDTotalSpinDownx->Add(HANDSpinDownx);
			HANDTotalSpinDownx->SetMinimum(0);
			HANDTotalSpinDownx->Write();
			HANDTotalSpinDownx->Draw();
			handpad07->Update();




			TString imageTitle = outputPlotsHere;
			imageTitle += "TDC_plots_for_beam_asym_Run_Num_";
			imageTitle += HeRunNumber;
			imageTitle += "-";
			imageTitle += endHeRunNumber;
			imageTitle += "_p";
			imageTitle += nplane;
			imageTitle += "_b";
			if (thisbar < 10) {imageTitle += "0";}
			imageTitle += thisbar;
			if (includeVetos) {imageTitle += "_with_vetos";}
			if (includeAntivetos) {imageTitle += "_with_antivetos";}
			if (antivetosAsVetos && includeAntivetos) {imageTitle += "_as_vetos";}
			imageTitle+= ".png";
			handCanvas->Print(imageTitle);

			TString imageAntivetosTitle = outputPlotsHere;
			imageAntivetosTitle += "antivetos_for_beam_asym_for_Run_Num_";
			imageAntivetosTitle += HeRunNumber;
			imageAntivetosTitle += "-";
			imageAntivetosTitle += endHeRunNumber;
			imageAntivetosTitle += "_p";
			imageAntivetosTitle += nplane;
			imageAntivetosTitle += "_b";
			imageAntivetosTitle += thisbar;
			if (includeVetos) {imageAntivetosTitle += "_with_vetos";}
			if (includeAntivetos) {imageAntivetosTitle += "_with_antivetos";}
			if (antivetosAsVetos && includeAntivetos) {imageAntivetosTitle += "_as_vetos";}
			imageAntivetosTitle += ".png";

			if (includeAntivetos) {hand_draw_antivetos(antiveto1plane, antiveto1bar, antiveto2plane, antiveto2bar, antiveto3plane, antiveto3bar, HeRunNumber, endHeRunNumber, chainHe, TDCbins, TDCmin, TDCmax, cuts, goodTDCcut, vetoTDCs, imageAntivetosTitle, nplane, thisbar, includeVetos, includeAntivetos, antivetosAsVetos, veto1plane, veto1bar, veto2plane, veto2bar, veto3plane, veto3bar, veto4plane, veto4bar, veto5plane, veto5bar, veto6plane, veto6bar, allVetos, allAntivetos);}

// *********************************************************************************************************
// The section below will plot the bars used for vetos for the previous canvas. It will consist of two
// canvases, one without the veto cuts made and one with to show the different.
			TString imageVetosWithoutVetosTitle = outputPlotsHere;
			imageVetosWithoutVetosTitle += "vetos_without_veto_cut_for_beam_asym_for_Run_Num_";
			imageVetosWithoutVetosTitle += HeRunNumber;
			imageVetosWithoutVetosTitle += "-";
			imageVetosWithoutVetosTitle += endHeRunNumber;
			imageVetosWithoutVetosTitle += "_p";
			imageVetosWithoutVetosTitle += nplane;
			imageVetosWithoutVetosTitle += "_b";
			imageVetosWithoutVetosTitle += thisbar;
			if (includeVetos) {imageVetosWithoutVetosTitle += "_with_vetos";}
			if (includeAntivetos) {imageVetosWithoutVetosTitle += "_with_antivetos";}
			if (antivetosAsVetos && includeAntivetos) {imageVetosWithoutVetosTitle += "_as_vetos";}
			imageVetosWithoutVetosTitle+= ".png";

			TString imageVetosWithVetosTitle = outputPlotsHere;
			imageVetosWithVetosTitle += "vetos_with_veto_cut_for_beam_asym_Run_Num_";
			imageVetosWithVetosTitle += HeRunNumber;
			imageVetosWithVetosTitle += "-";
			imageVetosWithVetosTitle += endHeRunNumber;
			imageVetosWithVetosTitle += "_p";
			imageVetosWithVetosTitle += nplane;
			imageVetosWithVetosTitle += "_b";
			imageVetosWithVetosTitle += thisbar;
			if (includeVetos) {imageVetosWithVetosTitle += "_with_vetos";}
			if (includeAntivetos) {imageVetosWithVetosTitle += "_with_antivetos";}
			if (antivetosAsVetos && includeAntivetos) {imageVetosWithVetosTitle += "_as_vetos";}
			imageVetosWithVetosTitle+= ".png";

//			if (includeVetos) {hand_draw_vetos(veto1plane, veto2plane, veto3plane, veto4plane, veto5plane, veto6plane,veto1bar, veto2bar, veto3bar, veto4bar, veto5bar, veto6bar, imageVetosWithoutVetosTitle, imageVetosWithVetosTitle, HeRunNumber, endHeRunNumber, chainHe, nplane, thisbar, TDCbins, TDCmin, TDCmax, cuts, vetoTDCs, antivetosAsVetos, allVetos, allAntivetos);}

//		if ((nplane==1) && (thisbar==15)) { nplane = 2; thisbar = 7;}
//		if ((nplane==2) && (thisbar==12)) { nplane = 3; thisbar = 6;}
//		if ((nplane==3) && (thisbar==11)) { nplane = 4; thisbar = 3;}
//		if ((nplane==4) && (thisbar==7))  { nplane = 4; thisbar = 99;}


		}
	}

	TString canvasTotalSpinTest = "TotalSpinTest";
	TString canvasTitleTotalSpinTest = "HAND - Total Spin (Not Scaled)";
	TCanvas *totalSpinTestCanvas = new TCanvas(canvasTotalSpinTest,canvasTitleTotalSpinTest,1400,770); //x,y
	totalspintestpad01 =  new TPad("totalspintestpad01","totalspintestpad01",0.0000,0.5000,0.5000,1.0000,0,0,0);
	totalspintestpad02 =  new TPad("totalspintestpad02","totalspintestpad02",0.5000,0.5000,1.0000,1.0000,0,0,0);
	totalspintestpad03 =  new TPad("totalspintestpad03","totalspintestpad03",0.0000,0.0000,1.0000,0.5000,0,0,0);
	totalspintestpad01->Draw(); totalspintestpad02->Draw(); totalspintestpad03->Draw();

	totalspintestpad01->cd();
	HANDTotalSpinUpx->SetTitle("Total Spin Up (Not Scaled)");
	HANDTotalSpinUpx->Write();
	HANDTotalSpinUpx->Draw();
	totalspintestpad01->Update();

	totalspintestpad02->cd();
	HANDTotalSpinDownx->SetTitle("Total Spin Down (Not Scaled)");
	HANDTotalSpinDownx->Write();
	HANDTotalSpinDownx->Draw();
	totalspintestpad02->Update();

	totalspintestpad03->cd();
        TF1 *fitasymtest = new TF1("fitasymtest","[0]",nuMin,nuMax);
	HANDAsymTest = HANDTotalSpinUpx->GetAsymmetry(HANDTotalSpinDownx);
	TString AsymTestTitle = "Target Asymmerty with Neutron Cuts vs. xBj for runs ";
	AsymTestTitle += HeRunNumber;
	AsymTestTitle += "-";
	AsymTestTitle += endHeRunNumber;
	HANDAsymTest->SetTitle(AsymTestTitle);
	HANDAsymTest->Write();
	HANDAsymTest->Draw();
        fitasymtest->SetLineColor(kBlue);
        HANDAsymTest->Fit("fitasymtest","R");
	totalspintestpad03->Update();


	TString asymTitle = "Target Asymmetry for Runs ";
	asymTitle += HeRunNumber;
	asymTitle += "-";
	asymTitle += endHeRunNumber;
	TCanvas *asymCanvas = new TCanvas("asymCanvas",asymTitle,1400,770); //x,y
	asymCanvas->cd();
	asymCanvas->SetGrid();
	Double_t x[nuBins], y[nuBins], errorx[nuBins], errory[nuBins];
	double minError;
	double maxError;
	double posStuff;
	double negStuff;
	double UpEvents;
	double DownEvents;
	asymOutFile << "Runs " << HeRunNumber << "-" << endHeRunNumber << endl;
	cout << "Runs " << HeRunNumber << "-" << endHeRunNumber << endl;
	asymOutFile << "xBj	Asymmetry	Stat. Error	# BeamPos Events	BeamPos Charge	PosBeam LT	# Neg Events	BeamNeg Charge	NegBeam LT" << endl;
	cout << "xBj	Asymmetry	Stat. Error	# BeamPos Events	BeamPos Charge	PosBeam LT	# Neg Events	BeamNeg Charge	NegBeam LT" << endl;
	for (int i=0; i<nuBins; i++)
	{	
		UpEvents = HANDTotalSpinUpx->GetBinContent(i);
		DownEvents = HANDTotalSpinDownx->GetBinContent(i);
		x[i] = HANDTotalSpinUpx->GetBinCenter(i);
		if (x[i] != (HANDTotalSpinDownx->GetBinCenter(i))) { cout << endl << endl << "!!!!!!!!!!!!!!!!!!!!!!!!!! STOP! THERE'S A PROBLEM!!!!!!!!!!!!!!!!!!!!!!" << endl << endl << endl;}
		posStuff = UpEvents/(BeamChargeScaleUp * BeamlivetimeUp + 1e-15);
		negStuff = DownEvents/(BeamChargeScaleDown * BeamlivetimeDown + 1e-15);
		y[i] = ((posStuff - negStuff)/(posStuff + negStuff + 1e-15));
		errory[i] = 2*(DownEvents*sqrt(UpEvents) + UpEvents*sqrt(DownEvents))/((BeamChargeScaleUp*BeamlivetimeUp)*(BeamChargeScaleDown*BeamlivetimeDown)*pow((UpEvents/(BeamChargeScaleUp*BeamlivetimeUp)) + (DownEvents/(BeamChargeScaleDown*BeamlivetimeDown)),2) + 1e-15);
		if ((UpEvents == 0) || (DownEvents == 0)) { errory[i] = 1;}
		if ((UpEvents == 0) || (DownEvents == 0)) { y[i] = NULL;}
		if (i==0)
		{
			minError = y[i] - 2*errory[i];
			maxError = y[i] + 2*errory[i];
		}
		if ((y[i] - 2*errory[i]) < minError) { minError = y[i] - 2*errory[i];}
		if ((y[i] + 2*errory[i]) > maxError) { maxError = y[i] + 2*errory[i];}
		errorx[i] = ((nuMax - nuMin)/nuBins)/2;
		asymOutFile << x[i] << "	" << y[i] << "	" << errory[i] << "	" << UpEvents << "	" << BeamChargeScaleUp << "	" << BeamlivetimeUp << "	" << DownEvents << "	" << BeamChargeScaleDown << "	" << BeamlivetimeDown << endl;
		cout << x[i] << "	" << y[i] << "	" << errory[i] << "	" << UpEvents << "	" << BeamChargeScaleUp << "	" << BeamlivetimeUp << "	" << DownEvents << "	" << BeamChargeScaleDown << "	" << BeamlivetimeDown << endl;
	}
	asymGraph = new TGraphErrors(nuBins, x, y, errorx, errory);
	asymGraph->SetMarkerStyle(21);
	asymGraph->SetMarkerColor(4);
	asymGraph->SetTitle(asymTitle);
	asymTestHist = new TH2F("asymTestHist",asymTitle,nuBins,nuMin,nuMax,100,minError,maxError);
	asymTestHist->SetStats(kFALSE);
	asymTestHist->Write();
	asymTestHist->Draw();
	cout << "Fit min = " << nuMin << "; Fit max = " << nuMax << endl;
	TF1 *fitAsymGraph = new TF1("fitAsymGraph", "[0]", nuMin, nuMax);
	asymGraph->Draw("P");
	fitAsymGraph->SetLineColor(kBlue);
	asymGraph->Fit("fitAsymGraph","R");
	asymGraph->Write();
	asymCanvas->Update();

	TString TotalAsymOutTitle = outputPlotsHere;
	TotalAsymOutTitle += "target_asymmetry_good_for_Run_Num_";
	TotalAsymOutTitle += HeRunNumber;
	TotalAsymOutTitle += "-";
	TotalAsymOutTitle += endHeRunNumber;
	if (includeVetos) {TotalAsymOutTitle += "_with_vetos";}
	if (includeAntivetos) {TotalAsymOutTitle += "_with_antivetos";}
	if (antivetosAsVetos && includeAntivetos) {TotalAsymOutTitle += "_as_vetos";}
	TotalAsymOutTitle += ".png";
	asymCanvas->Print(TotalAsymOutTitle);



	TString canvasTotalSpin = "TotalSpin";
	TString canvasTitleTotalSpin = "HAND - Total Spin";
	TCanvas *totalSpinCanvas = new TCanvas(canvasTotalSpin,canvasTitleTotalSpin,1400,770); //x,y
	totalspinpad01 =  new TPad("totalspinpad01","totalspinpad01",0.0000,0.5000,0.5000,1.0000,0,0,0);
	totalspinpad02 =  new TPad("totalspinpad02","totalspinpad02",0.5000,0.5000,1.0000,1.0000,0,0,0);
	totalspinpad03 =  new TPad("totalspinpad03","totalspinpad03",0.0000,0.0000,1.0000,0.5000,0,0,0);
	totalspinpad01->Draw(); totalspinpad02->Draw(); totalspinpad03->Draw();

	totalspinpad01->cd();
	cout << "HeChargeScaleUp: " << HeChargeScaleUp << "   HelivetimeUp: " << HelivetimeUp << endl;
	HANDTotalSpinUpx->Scale(1/(BeamChargeScaleUp * BeamlivetimeUp));
	HANDTotalSpinUpx->SetTitle("Total Spin Up (Scaled by Charge, LT)");
	HANDTotalSpinUpx->Write();
	HANDTotalSpinUpx->Draw();
	// ********************************************************************************
	// This section below gathers and prints some statistics on the plot
	TString HANDUpFactorsString = "Total Positive Charge for Runs: ";
	HANDUpFactorsString += BeamChargeScaleUp;
	HANDUpFactorsString += " C";
	TString HANDUpFactorsString1 = "Total Positive Livetime for Runs: ";
	HANDUpFactorsString1 += BeamlivetimeUp;
	HANDUpFactors = new TPaveText(0.11,0.69,0.4,0.89,"NDC");
	TText *t1 = HANDUpFactors->AddText(HANDUpFactorsString);
	TText *t2 = HANDUpFactors->AddText(HANDUpFactorsString1);
	HANDUpFactors->Write();
	HANDUpFactors->Draw("same");
	// ********************************************************************************
	totalspinpad01->Update();

	totalspinpad02->cd();
	cout << "HeChargeScaleDown: " << HeChargeScaleDown << "   HelivetimeDown: " << HelivetimeDown << endl;
	HANDTotalSpinDownx->Scale(1/(BeamChargeScaleDown * BeamlivetimeDown));
	HANDTotalSpinDownx->SetTitle("Total Spin Down (Scaled by Charge, LT)");
	HANDTotalSpinDownx->Write();
	HANDTotalSpinDownx->Draw();
	// ********************************************************************************
	// This section below gathers and prints some statistics on the plot
	TString HANDDownFactorsString = "Total Negative Charge for Runs: ";
	HANDDownFactorsString += BeamChargeScaleDown;
	HANDDownFactorsString += " C";
	TString HANDDownFactorsString1 = "Total Negative Livetime for Runs: ";
	HANDDownFactorsString1 += BeamlivetimeDown;
	HANDDownFactors = new TPaveText(0.11,0.69,0.4,0.89,"NDC");
	TText *t1 = HANDDownFactors->AddText(HANDDownFactorsString);
	TText *t2 = HANDDownFactors->AddText(HANDDownFactorsString1);
	HANDDownFactors->Write();
	HANDDownFactors->Draw("same");
	// ********************************************************************************
	totalspinpad02->Update();

	totalspinpad03->cd();
        TF1 *fitasym = new TF1("fitasym","[0]",nuMin,nuMax);
	HANDAsym = HANDTotalSpinUpx->GetAsymmetry(HANDTotalSpinDownx);
	TString AsymTitle = "Target Asymmerty (Scaled by Charge, LT) with Neutron Cuts vs. xBj for runs ";
	AsymTitle += HeRunNumber;
	AsymTitle += "-";
	AsymTitle += endHeRunNumber;
	HANDAsym->SetTitle(AsymTitle);
	HANDAsym->Write();
	HANDAsym->Draw();
        fitasym->SetLineColor(kBlue);
        HANDAsym->Fit("fitasym","R");
	totalspinpad03->Update();

	TString TotalSpinOutTitle = outputPlotsHere;
	TotalSpinOutTitle += "target_asymmetry_for_Run_Num_";
	TotalSpinOutTitle += HeRunNumber;
	TotalSpinOutTitle += "-";
	TotalSpinOutTitle += endHeRunNumber;
	if (includeVetos) {TotalSpinOutTitle += "_with_vetos";}
	if (includeAntivetos) {TotalSpinOutTitle += "_with_antivetos";}
	if (antivetosAsVetos && includeAntivetos) {TotalSpinOutTitle += "_as_vetos";}
	TotalSpinOutTitle += ".png";
	totalSpinCanvas->Print(TotalSpinOutTitle);


	asymOutFile.close();

	outputRoot1->Close();

	cout << "All done!" << endl;



}
Example #22
0
void toyMC(int nsteps = 1e6) {
    
    Float_t LA = 9.2;
    Float_t LB = 10.3;
    
    Float_t SF = 492./LB;
    Float_t eSF = TMath::Sqrt(23.*23.+19.7*19.7)/LB;
//     Float_t OF = 358./LA;
//     Float_t eOF = 27./LA;
    Float_t OF = 358./LB;
    Float_t eOF = 31./LB;
    
    Float_t SigB = 188.+238-414;
    
    
    TH1F* hSig = new TH1F("hSig ; SF-R_{SF/OF}#timesOF ; ","Signal component",600,-100.,500.);
    
    hSig->SetLineColor(kRed+2);
    
    TRandom3* ran = new TRandom3();
    
    for ( int i=0; i<nsteps; ++i ) {
        
        Float_t nBSF = ran->Gaus(SF*LB,eSF*LB);
        Float_t nBOF = ran->Gaus(OF*LB,eOF*LB);
        Float_t rsfof = ran->Gaus(1.0,0.05);
        
        hSig->Fill(nBSF-nBOF*rsfof);
        
    }
    
    
    TCanvas* mycan = new TCanvas("mycan","",100,10,900,600);
    mycan->SetLogy();
    TH1F* hSigNorm = hSig->DrawNormalized("");
    hSigNorm->SetMinimum(1e-5);
    hSigNorm->Draw();
    
    // Find 95% CL range
    float integral = 0;
    int binStart = -1;
    while ( integral <= 0.025 ) {
        ++binStart;
        integral += hSigNorm->GetBinContent(binStart);
    }
    std::cout << integral << " up to " << hSigNorm->GetBinCenter(binStart) << std::endl;
    integral = 0;
    int binEnd = hSigNorm->GetNbinsX()+2;
    while ( integral <= 0.025 ) {
        --binEnd;
        integral += hSigNorm->GetBinContent(binEnd);
    }
    std::cout << integral << " up to " << hSigNorm->GetBinCenter(binEnd) << std::endl;
    
    // Draw 95% CL
    TBox* range95 = new TBox(hSigNorm->GetBinCenter(binStart),hSigNorm->GetMinimum(),hSigNorm->GetBinCenter(binEnd),1.2*hSigNorm->GetMaximum());
    range95->SetFillColor(kBlue-9);
    range95->SetFillStyle(1000);
    range95->SetLineColor(range95->GetFillColor());
    range95->Draw();
    
    hSigNorm->SetTitle("hSigNorm; \"S\" #equiv SF - R_{SF/OF}#timesOF ; pdf");
    hSigNorm->Draw("same");
    
    std::cout << "Integrating from 0 to " << SigB << ": " << std::endl;
    std::cout << hSigNorm->Integral(0,hSigNorm->FindBin(SigB)) <<std::endl;
    
    TLegend* legend = new TLegend(0.6,0.7,0.95,0.9,"","brNDC");
    legend->SetBorderSize(0);
    legend->AddEntry(hSigNorm,"Expected \"S\" for block B","l");
    legend->AddEntry(range95,"95% region","f");
    legend->Draw();

    mycan->RedrawAxis();
    mycan->SaveAs("toyMCexp.pdf");

    TArrow* a = new TArrow(SigB,hSigNorm->GetMaximum(),SigB,hSigNorm->GetMinimum()*1.1,0.02);
    a->SetLineColor(kBlue+2);
    a->Draw();


    TLegend* legend2 = new TLegend(0.6,0.6,0.95,0.7,"","brNDC");
    legend2->SetBorderSize(0);
    legend2->AddEntry(a,"Observed (p-value 0.6%)","l");
    legend2->Draw();
    

    mycan->SaveAs("toyMC.pdf");
    
}
void OneSidedFrequentistUpperLimitWithBands_intermediate(const char* infile = "",
					    const char* workspaceName = "combined",
					    const char* modelConfigName = "ModelConfig",
					    const char* dataName = "obsData"){


  double confidenceLevel=0.95;
  // degrade/improve number of pseudo-experiments used to define the confidence belt.  
  // value of 1 corresponds to default number of toys in the tail, which is 50/(1-confidenceLevel)
  double additionalToysFac = 1.;  
  int nPointsToScan = 30; // number of steps in the parameter of interest 
  int nToyMC = 100; // number of toys used to define the expected limit and band

  TStopwatch t;
  t.Start();
  /////////////////////////////////////////////////////////////
  // First part is just to access a user-defined file 
  // or create the standard example file if it doesn't exist
  ////////////////////////////////////////////////////////////
  const char* filename = "";
  if (!strcmp(infile,""))
    filename = "results/example_combined_GaussExample_model.root";
  else
    filename = infile;
  // Check if example input file exists
  TFile *file = TFile::Open(filename);

  // if input file was specified byt not found, quit
  if(!file && strcmp(infile,"")){
    cout <<"file not found" << endl;
    return;
  } 

  // if default file not found, try to create it
  if(!file ){
    // Normally this would be run on the command line
    cout <<"will run standard hist2workspace example"<<endl;
    gROOT->ProcessLine(".! prepareHistFactory .");
    gROOT->ProcessLine(".! hist2workspace config/example.xml");
    cout <<"\n\n---------------------"<<endl;
    cout <<"Done creating example input"<<endl;
    cout <<"---------------------\n\n"<<endl;
  }

  // now try to access the file again
  file = TFile::Open(filename);
  if(!file){
    // if it is still not there, then we can't continue
    cout << "Not able to run hist2workspace to create example input" <<endl;
    return;
  }

  
  /////////////////////////////////////////////////////////////
  // Now get the data and workspace
  ////////////////////////////////////////////////////////////

  // get the workspace out of the file
  RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
  if(!w){
    cout <<"workspace not found" << endl;
    return;
  }

  // get the modelConfig out of the file
  ModelConfig* mc = (ModelConfig*) w->obj(modelConfigName);

  // get the modelConfig out of the file
  RooAbsData* data = w->data(dataName);

  // make sure ingredients are found
  if(!data || !mc){
    w->Print();
    cout << "data or ModelConfig was not found" <<endl;
    return;
  }

  cout << "Found data and ModelConfig:" <<endl;
  mc->Print();

  /////////////////////////////////////////////////////////////
  // Now get the POI for convenience
  // you may want to adjust the range of your POI
  ////////////////////////////////////////////////////////////
  RooRealVar* firstPOI = (RooRealVar*) mc->GetParametersOfInterest()->first();
  //  firstPOI->setMin(0);
  //  firstPOI->setMax(10);

  /////////////////////////////////////////////
  // create and use the FeldmanCousins tool
  // to find and plot the 95% confidence interval
  // on the parameter of interest as specified
  // in the model config
  // REMEMBER, we will change the test statistic
  // so this is NOT a Feldman-Cousins interval
  FeldmanCousins fc(*data,*mc);
  fc.SetConfidenceLevel(confidenceLevel); 
  fc.AdditionalNToysFactor(additionalToysFac); // improve sampling that defines confidence belt
  //  fc.UseAdaptiveSampling(true); // speed it up a bit, but don't use for expectd limits
  fc.SetNBins(nPointsToScan); // set how many points per parameter of interest to scan
  fc.CreateConfBelt(true); // save the information in the belt for plotting

  /////////////////////////////////////////////
  // Feldman-Cousins is a unified limit by definition
  // but the tool takes care of a few things for us like which values
  // of the nuisance parameters should be used to generate toys.
  // so let's just change the test statistic and realize this is 
  // no longer "Feldman-Cousins" but is a fully frequentist Neyman-Construction.
  //  ProfileLikelihoodTestStatModified onesided(*mc->GetPdf());
  //  fc.GetTestStatSampler()->SetTestStatistic(&onesided);
  // ((ToyMCSampler*) fc.GetTestStatSampler())->SetGenerateBinned(true);
  ToyMCSampler*  toymcsampler = (ToyMCSampler*) fc.GetTestStatSampler(); 
  ProfileLikelihoodTestStat* testStat = dynamic_cast<ProfileLikelihoodTestStat*>(toymcsampler->GetTestStatistic());
  testStat->SetOneSided(true);


  // test speedups:
  testStat->SetReuseNLL(true);
  //  toymcsampler->setUseMultiGen(true); // not fully validated

  // Since this tool needs to throw toy MC the PDF needs to be
  // extended or the tool needs to know how many entries in a dataset
  // per pseudo experiment.  
  // In the 'number counting form' where the entries in the dataset
  // are counts, and not values of discriminating variables, the
  // datasets typically only have one entry and the PDF is not
  // extended.  
  if(!mc->GetPdf()->canBeExtended()){
    if(data->numEntries()==1)     
      fc.FluctuateNumDataEntries(false);
    else
      cout <<"Not sure what to do about this model" <<endl;
  }

  // We can use PROOF to speed things along in parallel
  ProofConfig pc(*w, 4, "",false); 
  if(mc->GetGlobalObservables()){
    cout << "will use global observables for unconditional ensemble"<<endl;
    mc->GetGlobalObservables()->Print();
    toymcsampler->SetGlobalObservables(*mc->GetGlobalObservables());
  }
  toymcsampler->SetProofConfig(&pc);	// enable proof


  // Now get the interval
  PointSetInterval* interval = fc.GetInterval();
  ConfidenceBelt* belt = fc.GetConfidenceBelt();
 
  // print out the iterval on the first Parameter of Interest
  cout << "\n95% interval on " <<firstPOI->GetName()<<" is : ["<<
    interval->LowerLimit(*firstPOI) << ", "<<
    interval->UpperLimit(*firstPOI) <<"] "<<endl;

  // get observed UL and value of test statistic evaluated there
  RooArgSet tmpPOI(*firstPOI);
  double observedUL = interval->UpperLimit(*firstPOI);
  firstPOI->setVal(observedUL);
  double obsTSatObsUL = fc.GetTestStatSampler()->EvaluateTestStatistic(*data,tmpPOI);


  // Ask the calculator which points were scanned
  RooDataSet* parameterScan = (RooDataSet*) fc.GetPointsToScan();
  RooArgSet* tmpPoint;

  // make a histogram of parameter vs. threshold
  TH1F* histOfThresholds = new TH1F("histOfThresholds","",
				    parameterScan->numEntries(),
				    firstPOI->getMin(),
				    firstPOI->getMax());
  histOfThresholds->GetXaxis()->SetTitle(firstPOI->GetName());
  histOfThresholds->GetYaxis()->SetTitle("Threshold");

  // loop through the points that were tested and ask confidence belt
  // what the upper/lower thresholds were.
  // For FeldmanCousins, the lower cut off is always 0
  for(Int_t i=0; i<parameterScan->numEntries(); ++i){
    tmpPoint = (RooArgSet*) parameterScan->get(i)->clone("temp");
    double arMax = belt->GetAcceptanceRegionMax(*tmpPoint);
    double poiVal = tmpPoint->getRealValue(firstPOI->GetName()) ;
    histOfThresholds->Fill(poiVal,arMax);
  }
  TCanvas* c1 = new TCanvas();
  c1->Divide(2);
  c1->cd(1);
  histOfThresholds->SetMinimum(0);
  histOfThresholds->Draw();
  c1->cd(2);

  /////////////////////////////////////////////////////////////
  // Now we generate the expected bands and power-constriant
  ////////////////////////////////////////////////////////////

  // First: find parameter point for mu=0, with conditional MLEs for nuisance parameters
  RooAbsReal* nll = mc->GetPdf()->createNLL(*data);
  RooAbsReal* profile = nll->createProfile(*mc->GetParametersOfInterest());
  firstPOI->setVal(0.);
  profile->getVal(); // this will do fit and set nuisance parameters to profiled values
  RooArgSet* poiAndNuisance = new RooArgSet();
  if(mc->GetNuisanceParameters())
    poiAndNuisance->add(*mc->GetNuisanceParameters());
  poiAndNuisance->add(*mc->GetParametersOfInterest());
  w->saveSnapshot("paramsToGenerateData",*poiAndNuisance);
  RooArgSet* paramsToGenerateData = (RooArgSet*) poiAndNuisance->snapshot();
  cout << "\nWill use these parameter points to generate pseudo data for bkg only" << endl;
  paramsToGenerateData->Print("v");


  double CLb=0;
  double CLbinclusive=0;

  // Now we generate background only and find distribution of upper limits
  TH1F* histOfUL = new TH1F("histOfUL","",100,0,firstPOI->getMax());
  histOfUL->GetXaxis()->SetTitle("Upper Limit (background only)");
  histOfUL->GetYaxis()->SetTitle("Entries");
  for(int imc=0; imc<nToyMC; ++imc){

    // set parameters back to values for generating pseudo data
    w->loadSnapshot("paramsToGenerateData");

    // in 5.30 there is a nicer way to generate toy data  & randomize global obs
    RooAbsData* toyData = toymcsampler->GenerateToyData(*paramsToGenerateData);

    // get test stat at observed UL in observed data
    firstPOI->setVal(observedUL);
    double toyTSatObsUL = fc.GetTestStatSampler()->EvaluateTestStatistic(*toyData,tmpPOI);
    //    toyData->get()->Print("v");
    //    cout <<"obsTSatObsUL " <<obsTSatObsUL << "toyTS " << toyTSatObsUL << endl;
    if(obsTSatObsUL < toyTSatObsUL) // (should be checked)
      CLb+= (1.)/nToyMC;
    if(obsTSatObsUL <= toyTSatObsUL) // (should be checked)
      CLbinclusive+= (1.)/nToyMC;


    // loop over points in belt to find upper limit for this toy data
    double thisUL = 0;
    for(Int_t i=0; i<parameterScan->numEntries(); ++i){
      tmpPoint = (RooArgSet*) parameterScan->get(i)->clone("temp");
      double arMax = belt->GetAcceptanceRegionMax(*tmpPoint);
      firstPOI->setVal( tmpPoint->getRealValue(firstPOI->GetName()) );
      double thisTS = fc.GetTestStatSampler()->EvaluateTestStatistic(*toyData,tmpPOI);

      if(thisTS<=arMax){
	thisUL = firstPOI->getVal();
      } else{
	break;
      }
    }
    

    histOfUL->Fill(thisUL);

    
    delete toyData;
  }
  histOfUL->Draw();
  c1->SaveAs("one-sided_upper_limit_output.pdf");

  // if you want to see a plot of the sampling distribution for a particular scan point:

  // Now find bands and power constraint
  Double_t* bins = histOfUL->GetIntegral();
  TH1F* cumulative = (TH1F*) histOfUL->Clone("cumulative");
  cumulative->SetContent(bins);
  double band2sigDown=0, band1sigDown=0, bandMedian=0, band1sigUp=0,band2sigUp=0;
  for(int i=1; i<=cumulative->GetNbinsX(); ++i){
    if(bins[i]<RooStats::SignificanceToPValue(2))
      band2sigDown=cumulative->GetBinCenter(i);
    if(bins[i]<RooStats::SignificanceToPValue(1))
      band1sigDown=cumulative->GetBinCenter(i);
    if(bins[i]<0.5)
      bandMedian=cumulative->GetBinCenter(i);
    if(bins[i]<RooStats::SignificanceToPValue(-1))
      band1sigUp=cumulative->GetBinCenter(i);
    if(bins[i]<RooStats::SignificanceToPValue(-2))
      band2sigUp=cumulative->GetBinCenter(i);
  }

  t.Stop();
  t.Print();

  cout << "-2 sigma  band " << band2sigDown << endl;
  cout << "-1 sigma  band " << band1sigDown  << endl;
  cout << "median of band " << bandMedian << " [Power Constriant)]" << endl;
  cout << "+1 sigma  band " << band1sigUp << endl;
  cout << "+2 sigma  band " << band2sigUp << endl;

  // print out the iterval on the first Parameter of Interest
  cout << "\nobserved 95% upper-limit "<< interval->UpperLimit(*firstPOI) <<endl;
  cout << "CLb strict [P(toy>obs|0)] for observed 95% upper-limit "<< CLb <<endl;
  cout << "CLb inclusive [P(toy>=obs|0)] for observed 95% upper-limit "<< CLbinclusive <<endl;

  delete profile;
  delete nll;

}
Example #24
0
void FitDijetMass_Data() {

  
  TFile *inf  = new TFile("MassResults_ak7calo.root");
  TH1F *hCorMassDen     = (TH1F*) inf->Get("DiJetMass");
  hCorMassDen->SetXTitle("Corrected Dijet Mass (GeV)");
  hCorMassDen->SetYTitle("Events/GeV");
  hCorMassDen->GetYaxis()->SetTitleOffset(1.5);
  hCorMassDen->SetMarkerStyle(20);
  hCorMassDen->GetXaxis()->SetRangeUser(120.,900.);



  gROOT->ProcessLine(".L tdrstyle.C");
  setTDRStyle();
  tdrStyle->SetErrorX(0.5);
  tdrStyle->SetPadRightMargin(0.08);
  tdrStyle->SetLegendBorderSize(0);
  gStyle->SetOptFit(1111);
  tdrStyle->SetOptStat(0); 

  
  TCanvas* c2 = new TCanvas("c2","DijetMass", 500, 500);
  /////// perform 4 parameters fit
  TF1 *func = new TF1("func", "[0]*((1-x/7000.+[3]*(x/7000)^2)^[1])/(x^[2])", 
  100., 1000.);
  func->SetParameter(0, 1.0e+08);
  func->SetParameter(1, -1.23);
  func->SetParameter(2, 4.13);
  func->SetParameter(3, 1.0);

  func->SetLineColor(4);
  func->SetLineWidth(3);

  TVirtualFitter::SetMaxIterations( 10000 );
  TVirtualFitter *fitter;
  TMatrixDSym* cov_matrix;

  int fitStatus = hCorMassDen->Fit("func","LLI","",130.0, 800.0); // QCD fit
 
  TH1F *hFitUncertainty = hCorMassDen->Clone("hFitUncertainty");
  hFitUncertainty->SetLineColor(5);
  hFitUncertainty->SetFillColor(5);
  hFitUncertainty->SetMarkerColor(5);

  if (fitStatus == 0) {
    fitter = TVirtualFitter::GetFitter();
    double* m_elements = fitter->GetCovarianceMatrix();
    cov_matrix = new TMatrixDSym( func->GetNumberFreeParameters(),m_elements);
    cov_matrix->Print();
    double x, y, e;

    for(int i=0;i<hFitUncertainty->GetNbinsX();i++)
      {
	x = hFitUncertainty->GetBinCenter(i+1);
	y = func->Eval(x);
	e = QCDFitUncertainty( func, *cov_matrix, x);
	hFitUncertainty->SetBinContent(i+1,y);
	hFitUncertainty->SetBinError(i+1,e);
      }
  }

  hCorMassDen->Draw("ep");
  gPad->Update();
  TPaveStats *st = (TPaveStats*)hCorMassDen->FindObject("stats");
  st->SetName("stats1");
  st->SetX1NDC(0.3); //new x start position
  st->SetX2NDC(0.6); //new x end position
  st->SetTextColor(4);
  hCorMassDen->GetListOfFunctions()->Add(st);



  /////// perform 2 parameters fit
  TF1 *func2 = new TF1("func2", "[0]*(1-x/7000.)/(x^[1])", 100., 1000.);
  func2->SetParameter(0, 10000.);
  func2->SetParameter(1, 5.0);
  func2->SetLineWidth(3);

  fitStatus = hCorMassDen->Fit("func2","LLI","",130.0, 800.0); // QCD fit

  TH1F *hFitUncertainty2 = hCorMassDen->Clone("hFitUncertainty2");
  hFitUncertainty2->SetLineColor(kGray);
  hFitUncertainty2->SetFillColor(kGray);
  hFitUncertainty2->SetMarkerColor(kGray);

  if (fitStatus == 0) {
    fitter = TVirtualFitter::GetFitter();
    double* m_elements = fitter->GetCovarianceMatrix();
    cov_matrix = new TMatrixDSym( func2->GetNumberFreeParameters(),m_elements);
    cov_matrix->Print();
    double x, y, e;

    for(int i=0;i<hFitUncertainty2->GetNbinsX();i++)
      {
	x = hFitUncertainty2->GetBinCenter(i+1);
	y = func2->Eval(x);
	e = QCDFitUncertainty( func2, *cov_matrix, x);
	hFitUncertainty2->SetBinContent(i+1,y);
	hFitUncertainty2->SetBinError(i+1,e);
      }
  }

  hFitUncertainty->Draw("E3 same");
  hCorMassDen->Draw("ep sames");
  hFitUncertainty2->Draw("E3 same");
  hCorMassDen->Draw("ep sames");
  func2->Draw("same");
  c2->SetLogy(1);



/*
  

  TH1F *hCorMass     = hCorMassDen->Clone("hCorMass");


  for(int i=0; i<hCorMass->GetNbinsX(); i++){
    hCorMass->SetBinContent(i+1, hCorMassDen->GetBinContent(i+1) * hCorMassDen->GetBinWidth(i+1));
    hCorMass->SetBinError(i+1, hCorMassDen->GetBinError(i+1) * hCorMassDen->GetBinWidth(i+1));
  } 




  // Our observable is the invariant mass
  RooRealVar invMass("invMass", "Corrected dijet mass", 
		     100., 1000.0, "GeV");
  RooDataHist data( "data", "", invMass, hCorMass);

   //////////////////////////////////////////////




   // make QCD model
  RooRealVar p0("p0", "# events", 600.0, 0.0, 10000000000.);
  RooRealVar p1("p1","p1", 3.975, -10., 10.) ;  
  RooRealVar p2("p2","p2", 5.302, 4., 8.) ; 
  RooRealVar p3("p3","p3", -1.51, -100., 100.) ; 



//    // define QCD line shape
  RooGenericPdf qcdModel("qcdModel", "pow([email protected]/[email protected]*(@0/7000.)*(@0/7000.),@1)*pow(@0/7000.,[email protected])",
			 RooArgList(invMass,p1,p2,p3)); 

   // full model
   RooAddPdf model("model","qcd",RooArgList(qcdModel), RooArgList(p0)); 



   //plot sig candidates, full model, and individual componenets 

   //   __ _ _    
   //  / _(_) |_  
   // | |_| | __| 
   // |  _| | |_  
   // |_| |_|\__| 


 // Important: fit integrating f(x) over ranges defined by X errors, rather
  // than taking point at center of bin

   RooFitResult* fit = model.fitTo(data, Minos(kFALSE), Extended(kTRUE),
				   SumW2Error(kFALSE),Save(kTRUE), Range(130.,800.),
				   Integrate(kTRUE) );

   // to perform chi^2 minimization fit instead
   //    RooFitResult* fit = model.chi2FitTo(data, Extended(kTRUE), 
   // 				       Save(),Range(50.,526.),Integrate(kTRUE) );

   fit->Print();


   //plot data 
   TCanvas* cdataNull = new TCanvas("cdataNull","fit to dijet mass",500,500);
   RooPlot* frame1 = invMass.frame() ; 
   data.plotOn(frame1, DataError(RooAbsData::SumW2) ) ; 
   model.plotOn(frame1, LineColor(kBlue)) ; 
   model.plotOn(frame1, VisualizeError(*fit, 1),FillColor(kYellow)) ;   
   data.plotOn(frame1, DataError(RooAbsData::SumW2) ) ; 
   model.plotOn(frame1, LineColor(kBlue)) ; 
   model.paramOn(frame1, Layout(0.4, 0.85, 0.92)); 
   TPaveText* dataPave = (TPaveText*) frame1->findObject("model_paramBox");
   dataPave->SetY1(0.77);
   gPad->SetLogy();
   frame1->GetYaxis()->SetNoExponent();
   frame1->GetYaxis()->SetRangeUser(5E-2,5E+4);
   frame1->GetYaxis()->SetTitle("Events / bin");
   frame1->GetYaxis()->SetTitleOffset(1.35);
   frame1->SetTitle("fit to data with QCD lineshape");
   frame1->Draw() ;


    
    // S h o w   r e s i d u a l   a n d   p u l l   d i s t s
    // -------------------------------------------------------
    
   //// Construct a histogram with the residuals of the data w.r.t. the curve
   RooHist* hresid = frame1->residHist() ;
   // Create a new frame to draw the residual distribution and add the distribution to the frame
   RooPlot* frame2 = invMass.frame(Title("Residual Distribution")) ;
   frame2->addPlotable(hresid,"P") ;


    
   ///// Construct a histogram with the pulls of the data w.r.t the curve
   RooHist* hpull = frame1->pullHist() ;   
   //// Create a new frame to draw the pull distribution and add the distribution to the frame
   RooPlot* frame3 = invMass.frame(Title("Pull Distribution")) ;
   frame3->addPlotable(hpull,"P") ;


   TCanvas* cResidual = new TCanvas("cResidual","Residual Distribution",1000,500);
   cResidual->Divide(2) ;
   cResidual->cd(1) ; gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.6) ; frame2->Draw() ;
   cResidual->cd(2) ; gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.6) ; frame3->Draw() ;
  
*/
}
Example #25
0
void printBfraction(char *tagger="discr_ssvHighEff", Double_t workingPoint=2, char *taggerName="ssvHighEff", int doCent=2, int do3bin=1) {

  gROOT->ForceStyle(1);

  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);


  gStyle->SetTextFont(42);
  gStyle->SetLabelFont(42,"XYZ");
  gStyle->SetTitleFont(42,"XYZ");

  // hack
  if(doCent)gStyle->SetErrorX(0);
  gStyle->SetLabelSize(0.05,"xy");
  gStyle->SetTitleSize(0.05,"xy");
  gStyle->SetTitleOffset(1.5,"xy");
  gStyle->SetPadLeftMargin(0.15);
  gStyle->SetPadBottomMargin(0.12);
  gStyle->SetNdivisions(408,"y");


  TFile *fin1, *fin2;
  if(doCent){
    if(doCent==1){
      fin1 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL1_centDep_80_100.root");
      fin2 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL0_centDep_80_100.root");
    }
    if(doCent==2){
      fin1 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL1_centDep_100_120.root");
      fin2 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL0_centDep_100_120.root");
    }
    // broken
    //fin1 = new TFile("output/bFractionMerged_ssvHighEffat2.0FixCL1_centDep_80_100.root");
    //fin2 = new TFile("output/bFractionMerged_ssvHighEffat2.0FixCL0_centDep_80_100.root");
  }
  else{
    // try to smear by 2 sigma
    //fin1 = new TFile("output/bFractionMerged_Smear2Sigma_SSVHEat2.0FixCL1_bin_0_40_eta_0_2.root");
    //fin2 = new TFile("output/bFractionMerged_Smear2Sigma_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root");
    // with reg tracks in reco jets
    //fin1 = new TFile("output/bFractionMerged_regPFJets_SSVHEat2.0FixCL1_bin_0_40_eta_0_2.root");
    //fin2 = new TFile("output/bFractionMerged_regPFJets_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root");
    if(do3bin){
      fin1 = new TFile("output/bFractionMerged_3bins_SSVHEat2.0FixCL1_bin_0_40_eta_0_2.root");
      fin2 = new TFile("output/bFractionMerged_3bins_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root");
    }
    else{
      fin1 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL1_bin_0_40_eta_0_2.root");
      fin2 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root");
      // old naming convention
    //fin1 = new TFile("output/bFractionMerged_ssvHighEffat2.0FixCL1_bin_0_40_eta_0_2.root");
    //fin2 = new TFile("output/bFractionMerged_ssvHighEffat2.0FixCL0_bin_0_40_eta_0_2.root");

    }
  }

  TH1F *hBFractionMC = (TH1F*) fin1->Get("hBFractionMC");

  TH1F *hBFractionData = (TH1F*) fin1->Get("hBFractionData");
  TH1F *hBFractionDataLTJP = (TH1F*) fin1->Get("hBFractionDataLTJP");
  TH1F *hBFractionJPdirect = (TH1F*) fin1->Get("hBFractionJPdirect");

  TH1F *hBFractionDataFixC = (TH1F*) fin2->Get("hBFractionData");
  TH1F *hBFractionDataLTJPFixC = (TH1F*) fin2->Get("hBFractionDataLTJP");
  TH1F *hBFractionJPdirectFixC = (TH1F*) fin2->Get("hBFractionJPdirect");

  


  /*  --- correction due to Jet Energy Scale (calcul) ---
  correct(hBFractionMC);
  correct(hBFractionData);
  correct(hBFractionDataMoreC);
  correct(hBFractionDataLessC);
  correct(hBFractionDataLTJP);
  correct(hBFractionDataLTJPMoreC);
  correct(hBFractionDataLTJPLessC);
  correct(hBFractionJPdirect);
  correct(hBFractionJPdirectMoreC);
  correct(hBFractionJPdirectLessC);
  //*/

  //*  --- correction due to Jet Energy Scale (by hand) ---
  if(doCent){
    correctByCent(hBFractionMC,doCent);
    correctByCent(hBFractionData,doCent);
    correctByCent(hBFractionDataFixC,doCent);
    correctByCent(hBFractionDataLTJP,doCent);
    correctByCent(hBFractionDataLTJPFixC,doCent);
    correctByCent(hBFractionJPdirect,doCent);
    correctByCent(hBFractionJPdirectFixC,doCent);
  }
  else{
    //*
    correct2(hBFractionMC,do3bin);
    correct2(hBFractionData,do3bin);
    correct2(hBFractionDataFixC,do3bin);
    correct2(hBFractionDataLTJP,do3bin);
    correct2(hBFractionDataLTJPFixC,do3bin);
    correct2(hBFractionJPdirect,do3bin);
    correct2(hBFractionJPdirectFixC,do3bin);
    //*/
  }
  //*/

  //  --- plots with variation of charm ---


  TCanvas *cBFraction1 = new TCanvas("cBFraction1","b-jet fraction",600,600);
  hBFractionMC->SetLineColor(2);
  hBFractionMC->SetLineWidth(2);
  hBFractionMC->SetMarkerColor(2);
  //hBFractionMC->SetMarkerStyle(4);
  if(!doCent)hBFractionMC->SetAxisRange(80,200,"X");
  hBFractionMC->SetAxisRange(0,0.06,"Y");
  hBFractionMC->SetTitleOffset(1,"X");  
  hBFractionMC->GetYaxis()->SetTitle("b-jet fraction");;
  //hBFractionMC->Draw("e1"); 
  
  //hBFractionMC->GetYaxis()->SetNdivisions(505);
  
  TH1F *hBFractionMC_dummy= (TH1F*)hBFractionMC->Clone("hBFractionMC_dummy");
  hBFractionMC_dummy->SetLineWidth(0);
  hBFractionMC_dummy->SetLineColor(0);
  hBFractionMC_dummy->SetMarkerSize(0);
  hBFractionMC_dummy->Draw(); 
  //  hBFractionMC->Draw("hist"); 

  hBFractionData->SetMarkerStyle(8);
  hBFractionData->Draw("e1,same");  
  hBFractionDataLTJP->SetLineColor(kGreen-2); 
  hBFractionDataLTJP->SetMarkerColor(kGreen-2); 
  hBFractionDataLTJP->SetMarkerStyle(8); 
  hBFractionDataLTJP->Draw("e1,same");
  hBFractionJPdirect->SetMarkerStyle(8); 
  hBFractionJPdirect->SetMarkerColor(kBlue);
  hBFractionJPdirect->SetLineColor(kBlue);
  hBFractionJPdirect->Draw("e1,same");

  
  hBFractionDataFixC->SetLineStyle(2);
  //hBFractionDataFixC->Draw("e1same");   
  hBFractionDataLTJPFixC->SetLineColor(kGreen-2);
  hBFractionDataLTJPFixC->SetMarkerColor(kGreen-2);
  hBFractionDataLTJPFixC->SetMarkerStyle(4);
  hBFractionDataLTJPFixC->SetLineStyle(2);
  hBFractionDataLTJPFixC->Draw("e1same");
  hBFractionJPdirectFixC->SetLineStyle(2);
  //hBFractionJPdirectFixC->Draw("e1same");

  
  TLegend *legFrac1 = new TLegend(0.15,0.65,0.87,0.95);

  legFrac1->SetBorderSize(0);
  legFrac1->SetFillStyle(0);
  legFrac1->SetHeader("PbPb, #sqrt{s_{NN}} = 2.76 TeV");
  legFrac1->AddEntry(hBFractionDataLTJP,Form("SSVHE, LT method",taggerName,workingPoint),"pl");
  legFrac1->AddEntry(hBFractionDataLTJPFixC,Form("SSVHE, LT method, Floating Charm Norm.",taggerName,workingPoint),"pl");
  legFrac1->AddEntry(hBFractionData,Form("SSVHE, MC eff.",taggerName,workingPoint),"pl");
  legFrac1->AddEntry(hBFractionJPdirect,"Jet Probability","pl");
  //legFrac1->AddEntry(hBFractionMC,"MC Input (reconstructed)","l");

  legFrac1->Draw();




  //  --- plots of LT method with syst. uncertainty ---

  TCanvas *cBFraction2 = new TCanvas("cBFraction2","b-jet fraction",600,600);

  TH1F *hBFractionMC2 = hBFractionMC->Clone("hBFractionMC2");
  if(!doCent)hBFractionMC2->GetXaxis()->SetRangeUser(80,200);
  hBFractionMC2->SetMarkerSize(0);
  hBFractionMC2->SetMaximum(0.06);
  hBFractionMC2->SetMinimum(0.0);
  hBFractionMC2->Draw("hist");


  TGraphAsymmErrors *gBFractionMC2 = new TGraphAsymmErrors(hBFractionMC);
  if(!doCent){
    setMeanPt(gBFractionMC2,hBFractionMC,0,do3bin);
    gBFractionMC2->GetXaxis()->SetRangeUser(80,200);
  }



  TLatex *prel;
  if(doCent)prel= new TLatex(10,0.0615,"CMS preliminary");
  else prel= new TLatex(85,0.0615,"CMS preliminary");
  prel->Draw();

  TLatex *roots = new TLatex(147,0.0615,"#sqrt{s_{NN}} = 2.76 TeV");
  roots->Draw();

  if(!doCent){
    TLatex *csel = new TLatex(90,0.05,"Centrality 0-100%");
    csel->Draw();
  }
  TLatex *ptlabel;
  if(doCent==1) ptlabel= new TLatex(20,0.005,"80 < Jet p_{T} < 100 GeV/c");
  if(doCent==2) ptlabel= new TLatex(20,0.005,"100 < Jet p_{T} < 120 GeV/c");
  if(doCent)ptlabel->Draw();

  // to be precise we should evaluate mcStatErr for 3 bins seperately
  float mcStatErr[4] = {0.03,0.06,0.07,0.15};

  
  //TGraphAsymmErrors *gSyst = new TGraphAsymmErrors(3);
  TGraphErrors *gSyst;
  if(do3bin) gSyst= new TGraphErrors(3);
  else gSyst= new TGraphErrors(4);
  Double_t errCLratio, errMethod, totalSystErr;

  for(Int_t i=1;i<=hBFractionDataLTJP->GetNbinsX();i++) {
    gSyst->SetPoint(i-1,hBFractionDataLTJP->GetBinCenter(i),hBFractionDataLTJP->GetBinContent(i));
    cout<<" central value "<<hBFractionDataLTJP->GetBinContent(i)<<endl;
    errCLratio = abs(hBFractionDataLTJP->GetBinContent(i)-hBFractionDataLTJPFixC->GetBinContent(i));
    errMethod = max(abs(hBFractionDataLTJP->GetBinContent(i)-hBFractionData->GetBinContent(i)),abs(hBFractionDataLTJP->GetBinContent(i)-hBFractionJPdirect->GetBinContent(i)));
    double errJES = 0.14*hBFractionDataLTJP->GetBinContent(i);
    
    totalSystErr = norm(errCLratio,errMethod,errJES);
    gSyst->SetPointError(i-1,hBFractionDataLTJP->GetBinWidth(i)/2,totalSystErr);
    cout<<" sys error "<<totalSystErr<<endl;
    // add in MC template uncertainties
    float origStatErr = hBFractionDataLTJP->GetBinError(i);
    int statBin=i-1;
    if(doCent==1) statBin=0;
    if(doCent==2) statBin=1;
    float extraStatErr = mcStatErr[statBin]*hBFractionDataLTJP->GetBinContent(i);
    float totalStatErr = sqrt(origStatErr*origStatErr + extraStatErr*extraStatErr);
    hBFractionDataLTJP->SetBinError(i,totalStatErr);
    cout<<" total error "<<sqrt(totalSystErr*totalSystErr+totalStatErr*totalStatErr)<<endl;

  }

  gSyst->SetFillColor(5);
  gSyst->Draw("2");


  gBFractionMC2->Draw("Z,p,same");
  hBFractionMC2->Draw("hist,same");


  TGraphAsymmErrors *gBFractionDataLTJP2 = new TGraphAsymmErrors(hBFractionDataLTJP);
  if(!doCent)setMeanPt(gBFractionDataLTJP2,hBFractionDataLTJP,1,do3bin);
  gBFractionDataLTJP2->SetLineColor(1);
  gBFractionDataLTJP2->SetMarkerColor(1);
  gBFractionDataLTJP2->SetMarkerSize(1.5);
  gBFractionDataLTJP2->Draw("p,e1,same");


  TLegend *legFrac2 = new TLegend(0.2,0.15,0.8,0.34);
  if(doCent){
    legFrac2->SetX1(0.365);
    legFrac2->SetY1(0.657);
    legFrac2->SetX2(0.965);
    legFrac2->SetY2(0.848);
  }

  legFrac2->SetHeader("#int L dt = 150 #mub^{-1}");
  legFrac2->SetBorderSize(0);
  legFrac2->SetFillStyle(0);
  legFrac2->AddEntry(gBFractionDataLTJP2,"PbPb data","p");
  legFrac2->AddEntry(gBFractionMC2,"PYTHIA+HYDJET 1.8","lp");
  legFrac2->AddEntry(gSyst,"Exp. uncertainty","f");
  legFrac2->Draw();

 
  cBFraction2->RedrawAxis();

}
void drawDifference(TH1* iH0,TH1 *iH1,TH1* iH2, TGraphErrors* iH3, int chnl,TGraphErrors* iH4,TGraphAsymmErrors* iH5,TH1* StatErrBand,TGraphErrors* iH6){
  std::string lName = std::string(iH0->GetName());
  TH1F *lHDiff  = new TH1F((lName+"Diff").c_str(),(lName+"Diff").c_str(),nBins-1,WptLogBins);// lHDiff->Sumw2();
  TH1F *lXHDiff1 = new TH1F((lName+"XDiff1").c_str(),(lName+"XDiff1").c_str(),iH0->GetNbinsX(),iH0->GetXaxis()->GetXmin(),iH0->GetXaxis()->GetXmax());
  int i1 = 0;
  lXHDiff1->SetLineWidth(2); lXHDiff1->SetLineColor(kBlack); //lXHDiff1->SetLineStyle(2);
  
  StatErrBand->SetMarkerStyle(kFullCircle); StatErrBand->SetMarkerColor(kBlack);StatErrBand->SetMarkerSize(0.6);
  StatErrBand->SetLineWidth(2); StatErrBand->SetLineColor(kBlack);

  //lHDiff->GetYaxis()->SetRangeUser(0.2,1.8);
  lHDiff->GetYaxis()->SetRangeUser(0.6,1.5);
  if (chnl == 2)
    lHDiff->GetYaxis()->SetRangeUser(0.4,1.4);
  if (chnl == 3)
    lHDiff->GetYaxis()->SetRangeUser(0.3,1.3);
  lHDiff->GetYaxis()->SetTitleOffset(0.4);
  lHDiff->GetYaxis()->SetTitleSize(0.12);
  lHDiff->GetYaxis()->SetLabelSize(0.12);
  lHDiff->GetYaxis()->CenterTitle();
  lHDiff->GetXaxis()->SetTitleOffset(1.);
  lHDiff->GetXaxis()->SetTitleSize(0.12);
  lHDiff->GetXaxis()->SetLabelSize(0);
  if(chnl==3)
    lHDiff->GetXaxis()->SetLabelSize(0.12);
  lHDiff->GetYaxis()->SetNdivisions(405);
  if (chnl == 3)
    lHDiff->GetXaxis()->SetTitle(" W p_{T} ");
  lHDiff->GetYaxis()->SetTitle("Theory/Data");
  //lHDiff->GetYaxis()->SetTitle("Data/ResBos");
  gStyle->SetOptStat(0);
  
  for(int i0 = 0; i0 < lHDiff->GetNbinsX()+1; i0++) {
    double lXCenter = lHDiff->GetBinCenter(i0);
    double lXVal     = iH0   ->GetBinContent(i0);
    lXHDiff1->SetBinContent(i0, 1.0);
    while(iH1->GetBinCenter(i1) < lXCenter) {i1++;}
    if(iH1->GetBinContent(i0) > 0) lHDiff->SetBinContent(i0,lXVal/(iH1->GetBinContent(i0)));
    //if(iH1->GetBinContent(i0) > 0) lHDiff->SetBinError(i0,iH0->GetBinError(i0)/(iH1->GetBinContent(i0)));
    if(iH1->GetBinContent(i0) > 0) lHDiff->SetBinError(i0,0.00001);
  }
  
  TGraphErrors* ErrBand = new TGraphErrors(iH2);
  ErrBand->SetFillColor(kBlack);
  ErrBand->SetFillStyle(3354);
  ErrBand->SetLineWidth(1);
  
  if (chnl == 1)
  {
    lHDiff->SetMarkerStyle(kOpenCircle);
    lHDiff->SetMarkerColor(kBlue);
    lHDiff->SetLineColor(kBlue);
  }
  if (chnl == 2)
  {
    lHDiff->SetMarkerStyle(kOpenTriangleUp);
    lHDiff->SetMarkerColor(kRed);
    lHDiff->SetLineColor(kRed);
  }
  if (chnl == 3)
  {
    lHDiff->SetMarkerStyle(kOpenSquare);
    lHDiff->SetMarkerColor(kGreen+3);
    lHDiff->SetLineColor(kGreen+3);
  }
  
  lHDiff->SetMarkerSize(0.8);
  
  //lHDiff->SetLineColor(kBlack); lHDiff->SetMarkerColor(kBlack);
  
  lHDiff->SetTitle("");
  lHDiff->Draw("E");
  if (chnl == 1)
    iH5->Draw("2same");
  if (chnl == 2 || chnl == 3)
    iH4->Draw("2same");
  if (chnl == 2 || chnl == 3)
    iH3->Draw("2same");
  if (chnl == 3)
    iH6->Draw("2");
  lXHDiff1->Draw("histsame");
  ErrBand->Draw("2same");
  lHDiff->Draw("Esame");
  StatErrBand->Draw("E1same");
}
void add_hand_targ_asymmetry_vs_nu(){

	TString targ;
	TString kine;
	TString veto;
	bool check = false;

	cout << "Which target do you want to look at? (v=vertical 3He, l=longitudinal 3He, t=transverse 3He, c=All Carbon, h=All Hydrogen, n=All Nitrogen, vc=Vertish Carbon, ltc=Longtransish Carbon, vh=Vertish Hydrogen, lth=Longtransish Hydrogen, ltn=Longtransish Nitrogen)" << endl;
	cin >> targ;
	if ((targ == "v") || (targ == "l") || (targ == "t") || (targ == "c") || (targ == "vc") || (targ == "ltc") || (targ == "h") || (targ == "vh") || (targ == "lth") || (targ == "n") || (targ == "ltn")) { check = true;}
	if (!check) {cout << "Not a valid entry. Exiting..." << endl; return 0;} 
	check = false;
	cout << "What Q2 do you want to look at? (1.0, 0.5, 0.42, 0.1)" << endl;
	cin >> kine;
	if ((kine == "1.0") || (kine == "0.5") || (kine == "0.42") || (kine == "0.1")) { check = true;}
	if (!check) {cout << "Not a valid entry. Exiting..." << endl; return 0;}
	check = false;
	cout << "Do you want data with vetos or without vetos? (w, wo)" << endl;
	cin >> veto;
	if ((veto == "w") || (veto == "wo")) { check = true;}
	if (!check) { cout << "Not a valid entry. Exiting..." << endl; return 0;}
	cout << "Did I make it here?" << endl;

	bool drawCuts = true;
//	bool drawCuts = false;

	bool includeVetos;
	if (veto == "w") {includeVetos = true;}
	if (veto == "wo") {includeVetos = false;}

	int HeRunNumber;
	int endHeRunNumber;
	if (kine == "1.0")
	{
//		if (targ == "v") {HeRunNumber = 20596; endHeRunNumber = 20789;}
		if (targ == "v") {HeRunNumber = 20596; endHeRunNumber = 20760;}
//		if (targ == "v") {HeRunNumber = 20751; endHeRunNumber = 20760;}
//		if (targ == "v") {HeRunNumber = 20751; endHeRunNumber = 20760;}
		if (targ == "l") {HeRunNumber = 22393; endHeRunNumber = 22438;}
		if (targ == "t") {HeRunNumber = 22447; endHeRunNumber = 22489;}
		if (targ == "vc") {HeRunNumber = 20591; endHeRunNumber = 20734;}
		if (targ == "ltc") {HeRunNumber = 22380; endHeRunNumber = 22461;}
		if (targ == "vh") {HeRunNumber = 20791; endHeRunNumber = 20792;}
		if (targ == "lth") {HeRunNumber = 22441; endHeRunNumber = 22441;}
		if (targ == "ltn") {HeRunNumber = 22442; endHeRunNumber = 22442;}
		double nuMax = 0.65;
		double nuMin = 0.35;
	}
	if (kine == "0.5")
	{
		if (targ == "v") {HeRunNumber = 20890; endHeRunNumber = 21005;}
		double nuMax = 0.125;
		double nuMin = 0.425;
	}
	if (kine == "0.1")
	{
//		if (targ == "v") {HeRunNumber = 20487; endHeRunNumber = 20540;}
//		if (targ == "v") {HeRunNumber = 20487; endHeRunNumber = 20532;}
		if (targ == "v") {HeRunNumber = 20487; endHeRunNumber = 20511;}
//		if (targ == "v") {HeRunNumber = 20533; endHeRunNumber = 20538;}
		double nuMin = 0;
		double nuMax = 0.13;
	}
	
	TString outputPlotsHere = "/home/ellie/physics/e05-102/images/plots_for_hand/hand_beam_asymmetry_vs_nu/";

	const int nuBins = 10;

	TChain* chainHe = new TChain("T");
	TString filenameHe;
	TString outFileName;

	filenameHe = "/home/ellie/physics/e05-102/analysis-scripts/devel/neutron_hunt/results/targ_ssa/";
	if (veto == "w") {filenameHe += "with_vetos/";}			
	if (veto == "wo") {filenameHe += "without_vetos/";}			
	if (targ == "v") {filenameHe += "vert_3he_";}
	if (targ == "l") {filenameHe += "long_3he_";}
	if (targ == "t") {filenameHe += "trans_3he_";}
	if (targ == "c") {filenameHe += "carbon_";}
	if (targ == "vc") {filenameHe += "v_carbon_";}
	if (targ == "ltc") {filenameHe += "lt_carbon_";}
	if (targ == "h") {filenameHe += "hydrogen_";}
	if (targ == "vh") {filenameHe += "v_hydrogen_";}
	if (targ == "lth") {filenameHe += "lt_hydrogen_";}
	if (targ == "n") {filenameHe += "nitrogen_";}
	if (targ == "ltn") {filenameHe += "lt_nitrogen_";}
	if (kine == "1.0") {filenameHe += "q2_1";}
	if (kine == "0.5") {filenameHe += "q2_05";}
	if (kine == "0.1") {filenameHe += "q2_01";}
	if (kine == "0.42") {filenameHe += "q2_042";}
	outFileName = filenameHe;
	filenameHe += ".root";

	TString asymOutFileName = outFileName;
	asymOutFileName += "_ssa_target_asymmetry_runs_";
	asymOutFileName += HeRunNumber;
	asymOutFileName += "-";
	asymOutFileName += endHeRunNumber;
	asymOutFileName += ".txt";
	ofstream asymOutFile;
	asymOutFile.open(asymOutFileName);

	ifstream ifileHe(filenameHe);
	if (ifileHe)
	{
		cout << "Adding file to chainHe: " << filenameHe << endl;
		chainHe->Add(filenameHe);
	}
	else
	{
		cout << "File " << filenameHe << " does not exist. Exiting..." << endl;
		return 0;
//		If this loop is causing you problems, read the IMPORTANT note above
	}

	TFile fileHe(filenameHe);

	gStyle->SetPalette(1);

	hand_basic_cuts(HeRunNumber, endHeRunNumber, drawCuts, kine, filenameHe, targ);
// **********************************************************************************************
	gStyle->SetOptFit(1111);
	TString veto1plane = "";
	TString veto1bar = "";
	TString veto2plane = "";
	TString veto2bar = "";
	TString veto3plane = "";
	TString veto3bar = "";
	TString veto4plane = "";
	TString veto4bar = "";
	TString veto5plane = "";
	TString veto5bar = "";
	TString veto6plane = "";
	TString veto6bar = "";
	TString antiveto1plane = ""; 
	TString antiveto1bar = "";
	TString antiveto2plane = "";
	TString antiveto2bar = "";
	TString antiveto3plane = "";
	TString antiveto3bar = "";
	TString allVetos = "";
	TString allAntivetos = "";
	TString vetoTDCslSt = "";
	TString vetoTDCsrSt = "";
	TCut vetoTDCsl = "";
	TCut vetoTDCsr = "";
	TCut vetoTDCs = "";
	TString antivetosTDCslSt = ""; 
	TString antivetosTDCsrSt = "";
	int maxbars = 0;
	int vetoplane = 0;
	int padBins = 0;
	double padMin = 0;
	double padMax = 0;

// **********************************************************************************************
// This bit of code should set the charge and livetime scaling factors
	double HeChargeScale; double Helivetime;
	double HeChargeScaleUp; double HelivetimeUp;
	double HeChargeScaleDown; double HelivetimeDown;
	double BeamChargeScaleUp; double BeamlivetimeUp;
	double BeamChargeScaleDown; double BeamlivetimeDown;
	hand_scaling_factors(HeRunNumber, endHeRunNumber, HeChargeScale, Helivetime, HeChargeScaleUp, HelivetimeUp, HeChargeScaleDown, HelivetimeDown, BeamChargeScaleUp, BeamlivetimeUp, BeamChargeScaleDown, BeamlivetimeDown, kine, targ);
	HeChargeScale = 0.00001 * int(HeChargeScale * 100000.0 + 0.5);
	HeChargeScaleUp = 0.00001 * int(HeChargeScaleUp * 100000.0 + 0.5);
	HeChargeScaleDown = 0.00001 * int(HeChargeScaleDown * 100000.0 + 0.5);
	BeamChargeScaleUp = 0.00001 * int(BeamChargeScaleUp * 100000.0 + 0.5);
	BeamChargeScaleDown = 0.00001 * int(BeamChargeScaleDown * 100000.0 + 0.5);
	Helivetime = 0.0001 * int(Helivetime * 10000.0 + 0.5);
	HelivetimeUp = 0.0001 * int(HelivetimeUp * 10000.0 + 0.5);
	HelivetimeDown = 0.0001 * int(HelivetimeDown * 10000.0 + 0.5);
	BeamlivetimeUp = 0.0001 * int(BeamlivetimeUp * 10000.0 + 0.5);
	BeamlivetimeDown = 0.0001 * int(BeamlivetimeDown * 10000.0 + 0.5);
	cout << "HeChargeScale: " << HeChargeScale << "C, Helivetime: " << Helivetime << endl;
	cout << "HeChargeScaleUp: " << HeChargeScaleUp << "C, HelivetimeUp: " << HelivetimeUp << endl;
	cout << "HeChargeScaleDown: " << HeChargeScaleDown << "C, HelivetimeDown: " << HelivetimeDown << endl;
	cout << "BeamChargeScaleUp: " << BeamChargeScaleUp << "C, BeamlivetimeUp: " << BeamlivetimeUp << endl;
	cout << "BeamChargeScaleDown: " << BeamChargeScaleDown << "C, BeamlivetimeDown: " << BeamlivetimeDown << endl;

// **********************************************************************************************

// The section below plots the HAND data
// **********************************************************************************************
//	int whichplane = 0;
	int whichplane = 1;
	int endplane = 5;
	int whichbar=0;
//	int whichbar=11;
	TString titleTotalSpinUpx = "Total Target Spin Up vs. Omega";
	if (includeVetos) {titleTotalSpinUpx += " with vetos";}
	else {titleTotalSpinUpx += " without vetos";}
	titleTotalSpinUpx += " with goodTDC cuts";
	cout << "Drawing " << titleTotalSpinUpx << "..." << endl;
	TString plotTotalSpinUpx = "newHANDTotalSpinUpx";
	TH1F *newHANDTotalSpinUpx = new TH1F(plotTotalSpinUpx,titleTotalSpinUpx,nuBins,nuMin,nuMax);
	TString titleTotalSpinDownx = "Total Spin Down vs. Omega";
	if (includeVetos) {titleTotalSpinDownx += " with vetos";}
	else {titleTotalSpinDownx += " without vetos";}
	titleTotalSpinDownx += " with goodTDC cuts";
	cout << "Drawing " << titleTotalSpinDownx << "..." << endl;
	TString plotTotalSpinDownx = "newHANDTotalSpinDownx";
	TH1F *newHANDTotalSpinDownx = new TH1F(plotTotalSpinDownx,titleTotalSpinDownx,nuBins,nuMin,nuMax);

	for (int nplane=whichplane; nplane<endplane; nplane++)
	{
		if (nplane==0) maxbars=32;
		if (nplane==1) maxbars=30;
		if (nplane==2) maxbars=24;
		if (nplane==3) maxbars=22;
		if (nplane==4) maxbars=12;
		for (int thisbar=whichbar; thisbar<maxbars; thisbar++)
		{

			TString goodPlane = nplane;
			TString goodPMT = thisbar;
//			hand_define_vetos(includeVetos, includeAntivetos, antivetosAsVetos, nplane, thisbar, veto1plane, veto2plane, veto3plane, veto4plane, veto5plane, veto6plane, veto1bar, veto2bar, veto3bar, veto4bar, veto5bar, veto6bar, antiveto1plane, antiveto2plane, antiveto3plane, antiveto1bar, antiveto2bar, antiveto3bar, allVetos, allAntivetos, vetoTDCslSt, vetoTDCsrSt, vetoTDCsl, vetoTDCsr, vetoTDCs, vetoTDCcutmin, vetoTDCcutmax, antivetosTDCslSt, antivetosTDCsrSt);
			hand_define_vetos(includeVetos, false, false, nplane, thisbar, veto1plane, veto2plane, veto3plane, veto4plane, veto5plane, veto6plane, veto1bar, veto2bar, veto3bar, veto4bar, veto5bar, veto6bar, antiveto1plane, antiveto2plane, antiveto3plane, antiveto1bar, antiveto2bar, antiveto3bar, allVetos, allAntivetos, vetoTDCslSt, vetoTDCsrSt, vetoTDCsl, vetoTDCsr, vetoTDCs, 745, 755, antivetosTDCslSt, antivetosTDCsrSt);
			
			TString goodBar = "nd.p";
			goodBar += nplane;
			goodBar += ".";
			goodBar += thisbar;
			goodBar += " ";
			cout << "Good Bar: " << goodBar << endl;

			TString canvasName = "handp";
			canvasName += nplane;
			canvasName += "b";
			canvasName += thisbar;
			TString canvasTitle = "HAND - Plane ";
			canvasTitle += nplane;
			canvasTitle += ", Bar ";
			canvasTitle += thisbar;
			TCanvas *handCanvas = new TCanvas(canvasName,canvasTitle,1400,730); //x,y
			handpad01 =  new TPad("handpad01","handpad01",0.0000,0.0000,0.1000,1.0000,0,0,0);
			handpad02 =  new TPad("handpad02","handpad02",0.1000,0.6666,0.5500,1.0000,0,0,0);
			handpad03 =  new TPad("handpad03","handpad03",0.5500,0.6666,1.0000,1.0000,0,0,0);
			handpad04 =  new TPad("handpad04","handpad04",0.1000,0.3333,0.5500,0.6666,0,0,0);
			handpad05 =  new TPad("handpad05","handpad05",0.5500,0.3333,1.0000,0.6666,0,0,0);
			handpad06 =  new TPad("handpad06","handpad06",0.1000,0.0000,0.5500,0.3333,0,0,0);
			handpad07 =  new TPad("handpad07","handpad07",0.5500,0.0000,1.0000,0.3333,0,0,0);
			handpad01->Draw(); handpad02->Draw(); handpad03->Draw(); handpad04->Draw(); handpad05->Draw();
			handpad06->Draw(); handpad07->Draw();

			// This section will run hand_draw.h which will draw the HAND in handpad01.
			handpad01->cd();
//			hand_draw(HeRunNumber, endHeRunNumber, antivetosAsVetos, allVetos, goodBar, allAntivetos);
			hand_draw(HeRunNumber, endHeRunNumber, false, allVetos, goodBar, allAntivetos);
			handpad01->Update();

			handpad02->cd();
			TString titleHANDleft = "Left TDC for Plane #";
			titleHANDleft += nplane;
			titleHANDleft += ", PMT # ";
			titleHANDleft += thisbar;
			if (includeVetos) {titleHANDleft += " with vetos";}
			else {titleHANDleft += " without vetos";}
			cout << "Drawing " << titleHANDleft << "..." << endl;
			TString plotHANDleft = "HANDleft_p";
			plotHANDleft += nplane;
			plotHANDleft += "_b";
			plotHANDleft += thisbar;
			TString plotHANDleftcut = plotHANDleft;
			plotHANDleftcut += "_cut";
			TH1F *HANDleft = (TH1F*)fileHe.Get(plotHANDleft);
			HANDleft->SetMinimum(0);
			HANDleft->Draw();
//			HANDleftcut->Scale(1/(HeChargeScale*Helivetime));
			TH1F *HANDleftcut = (TH1F*)fileHe.Get(plotHANDleftcut);
			HANDleftcut->SetMinimum(0);
			HANDleftcut->Draw("same");
			// ********************************************************************************
			// This section below gathers and prints some statistics on the plot
			double numHANDleftcutEvents = 0;
			for (int i=0; i<(HANDleft->GetSize()); i++){ numHANDleftcutEvents = numHANDleftcutEvents + HANDleftcut->GetBinContent(i);}
			TString HANDleftFactorsString = "Total Charge for Runs: ";
			HANDleftFactorsString += HeChargeScale;
			HANDleftFactorsString += " C";
			TString HANDleftFactorsString1 = "Total Livetime for Runs: ";
			HANDleftFactorsString1 += Helivetime;
			TString HANDleftFactorsString2 = "# of Cut (Purple) Events: ";
			HANDleftFactorsString2 += numHANDleftcutEvents;
/*			HANDleftFactors = new TPaveText(0.11,0.69,0.4,0.89,"NDC");
			TText *t1 = HANDleftFactors->AddText(HANDleftFactorsString);
			TText *t2 = HANDleftFactors->AddText(HANDleftFactorsString1);
			TText *t2 = HANDleftFactors->AddText(HANDleftFactorsString2);
			HANDleftFactors->Draw("same");
*/			// ********************************************************************************
			handpad02->Update();

			handpad03->cd();
			TString titleHANDright = "Right TDC for Plane #";
			titleHANDright += nplane;
			titleHANDright += ", PMT # ";
			titleHANDright += thisbar;
			if (includeVetos) {titleHANDright += " with vetos";}
			else {titleHANDright += " without vetos";}
			TString plotHANDright = "HANDright_p";
			plotHANDright += nplane;
			plotHANDright += "_b";
			plotHANDright += thisbar;
			TString plotHANDrightcut = plotHANDright;
			plotHANDrightcut += "_cut";
			cout << "Drawing " << titleHANDright << "..." << endl;
			TH1F *HANDright = (TH1F*)fileHe.Get(plotHANDright);
			HANDright->SetMinimum(0);
			TH1F *HANDrightcut = (TH1F*)fileHe.Get(plotHANDrightcut);
			HANDrightcut->SetMinimum(0);
//			HANDright->Scale(1/(HeChargeScale*Helivetime));
			HANDright->Draw();
			HANDrightcut->SetFillColor(kViolet);
//			HANDrightcut->Scale(1/(HeChargeScale*Helivetime));
			HANDrightcut->Draw("same");
			// ********************************************************************************
			// This section below gathers and prints some statistics on the plot
			double numHANDrightcutEvents = 0;
			for (int i=0; i<(HANDright->GetSize()); i++){ numHANDrightcutEvents = numHANDrightcutEvents + HANDrightcut->GetBinContent(i);}
			TString HANDrightFactorsString = "Total Charge for Runs: ";
			HANDrightFactorsString += HeChargeScale;
			HANDrightFactorsString += " C";
			TString HANDrightFactorsString1 = "Total Livetime for Runs: ";
			HANDrightFactorsString1 += Helivetime;
			TString HANDrightFactorsString2 = "# of Cut (Purple) Events: ";
			HANDrightFactorsString2 += numHANDrightcutEvents;
/*			HANDrightFactors = new TPaveText(0.11,0.69,0.4,0.89,"NDC");
			TText *t1 = HANDrightFactors->AddText(HANDrightFactorsString);
			TText *t2 = HANDrightFactors->AddText(HANDrightFactorsString1);
			TText *t2 = HANDrightFactors->AddText(HANDrightFactorsString2);
			HANDrightFactors->Draw("same");
*/			// ********************************************************************************
			handpad03->Update();

			handpad04->cd();
			cout << "Drawing Helicity Up vs. xBj..." << endl;
			TString titleSpinUpx = "Helicity Up vs. xBj for Plane #";
			titleSpinUpx += nplane;
			titleSpinUpx += ", PMT # ";
			titleSpinUpx += thisbar;
			if (includeVetos) {titleSpinUpx += " with vetos";}
			else {titleSpinUpx += " without vetos";}
			TString titleSpinUpxcut = titleSpinUpx;
			titleSpinUpxcut += " with goodTDC cuts";
			cout << "Drawing " << titleSpinUpx << "..." << endl;
			TString plotSpinUpx = "HANDSpinUpx_p";
			plotSpinUpx += nplane;
			plotSpinUpx += "_b";
			plotSpinUpx += thisbar;
			TH1F *HANDSpinUpx = (TH1F*)fileHe.Get(plotSpinUpx);
			HANDSpinUpx->SetMinimum(0);
			HANDSpinUpx->Draw();
			handpad04->Update();

			handpad05->cd();
			cout << "Drawing Helicity Down vs. xBj..." << endl;
			TString titleSpinDownx = "Helicity Down vs. xBj for Plane #";
			titleSpinDownx += nplane;
			titleSpinDownx += ", PMT # ";
			titleSpinDownx += thisbar;
			if (includeVetos) {titleSpinDownx += " with vetos";}
			else {titleSpinDownx += " without vetos";}
			TString titleSpinDownxcut = titleSpinDownx;
			titleSpinDownxcut += " with goodTDC cuts";
			cout << "Drawing " << titleSpinDownx << "..." << endl;
			TString plotSpinDownx = "HANDSpinDownx_p";
			plotSpinDownx += nplane;
			plotSpinDownx += "_b";
			plotSpinDownx += thisbar;
			TH1F *HANDSpinDownx = (TH1F*)fileHe.Get(plotSpinDownx);
			HANDSpinDownx->SetMinimum(0);
			HANDSpinDownx->Draw();
			handpad05->Update();

			handpad06->cd();
			cout << "Drawing Total Helicity Up vs. xBj..." << endl;
//			TString titleTotalSpinUpx = "Total Spin Up vs. xBj";
//			if (includeVetos) {titleTotalSpinUpx += " with vetos";}
//			else {titleTotalSpinUpx += " without vetos";}
//			titleTotalSpinUpx += " with goodTDC cuts";
//			cout << "Drawing " << titleTotalSpinUpx << "..." << endl;
//			TString plotTotalSpinUpx = "HANDTotalSpinUpx";
//			TH1F *HANDTotalSpinUpx = new TH1F(plotTotalSpinUpx,titleTotalSpinUpx,nuBins,nuMin,nuMax);
			newHANDTotalSpinUpx->Add(HANDSpinUpx);
			newHANDTotalSpinUpx->SetMinimum(0);
			newHANDTotalSpinUpx->Draw();
			handpad06->Update();

			handpad07->cd();
			cout << "Drawing Total Helicity Down vs. xBj..." << endl;
//			TString titleTotalSpinDownx = "Total Spin Down vs. xBj";
//			if (includeVetos) {titleTotalSpinDownx += " with vetos";}
//			else {titleTotalSpinDownx += " without vetos";}
//			titleTotalSpinDownx += " with goodTDC cuts";
//			cout << "Drawing " << titleTotalSpinDownx << "..." << endl;
//			TString plotTotalSpinDownx = "HANDTotalSpinDownx";
//			TH1F *HANDTotalSpinDownx = new TH1F(plotTotalSpinDownx,titleTotalSpinDownx,nuBins,nuMin,nuMax);
			newHANDTotalSpinDownx->Add(HANDSpinDownx);
			newHANDTotalSpinDownx->SetMinimum(0);
			newHANDTotalSpinDownx->Draw();
			handpad07->Update();




//			if (includeAntivetos) {hand_draw_antivetos(antiveto1plane, antiveto1bar, antiveto2plane, antiveto2bar, antiveto3plane, antiveto3bar, HeRunNumber, endHeRunNumber, chainHe, TDCbins, TDCmin, TDCmax, cuts, goodTDCcut, vetoTDCs, imageAntivetosTitle, nplane, thisbar, includeVetos, includeAntivetos, antivetosAsVetos, veto1plane, veto1bar, veto2plane, veto2bar, veto3plane, veto3bar, veto4plane, veto4bar, veto5plane, veto5bar, veto6plane, veto6bar, allVetos, allAntivetos);}

// *********************************************************************************************************
// The section below will plot the bars used for vetos for the previous canvas. It will consist of two
// canvases, one without the veto cuts made and one with to show the different.
//			if (includeVetos) {hand_draw_vetos(veto1plane, veto2plane, veto3plane, veto4plane, veto5plane, veto6plane,veto1bar, veto2bar, veto3bar, veto4bar, veto5bar, veto6bar, imageVetosWithoutVetosTitle, imageVetosWithVetosTitle, HeRunNumber, endHeRunNumber, chainHe, nplane, thisbar, TDCbins, TDCmin, TDCmax, cuts, vetoTDCs, antivetosAsVetos, allVetos, allAntivetos);}

//		if ((nplane==1) && (thisbar==15)) { nplane = 2; thisbar = 7;}
//		if ((nplane==2) && (thisbar==12)) { nplane = 3; thisbar = 6;}
//		if ((nplane==3) && (thisbar==11)) { nplane = 4; thisbar = 3;}
//		if ((nplane==4) && (thisbar==7))  { nplane = 4; thisbar = 99;}


		}
	}

	TString canvasTotalSpinTest = "TotalSpinTest";
	TString canvasTitleTotalSpinTest = "HAND - Total Spin (Not Scaled)";
	TCanvas *totalSpinTestCanvas = new TCanvas(canvasTotalSpinTest,canvasTitleTotalSpinTest,1400,730); //x,y
	totalspintestpad01 =  new TPad("totalspintestpad01","totalspintestpad01",0.0000,0.5000,0.5000,1.0000,0,0,0);
	totalspintestpad02 =  new TPad("totalspintestpad02","totalspintestpad02",0.5000,0.5000,1.0000,1.0000,0,0,0);
	totalspintestpad03 =  new TPad("totalspintestpad03","totalspintestpad03",0.0000,0.0000,1.0000,0.5000,0,0,0);
	totalspintestpad01->Draw(); totalspintestpad02->Draw(); totalspintestpad03->Draw();

	totalspintestpad01->cd();
	newHANDTotalSpinUpx->SetTitle("Total Spin Up (Not Scaled)");
	newHANDTotalSpinUpx->Draw();
	totalspintestpad01->Update();

	totalspintestpad02->cd();
	newHANDTotalSpinDownx->SetTitle("Total Spin Down (Not Scaled)");
	newHANDTotalSpinDownx->Draw();
	totalspintestpad02->Update();

	totalspintestpad03->cd();
        TF1 *fitasymtest = new TF1("fitasymtest","[0]",nuMin,nuMax);
	HANDAsymTest = newHANDTotalSpinUpx->GetAsymmetry(newHANDTotalSpinDownx);
	TString AsymTestTitle = "Target Asymmerty with Neutron Cuts vs. xBj for runs ";
	AsymTestTitle += HeRunNumber;
	AsymTestTitle += "-";
	AsymTestTitle += endHeRunNumber;
	HANDAsymTest->SetTitle(AsymTestTitle);
	HANDAsymTest->Draw();
        fitasymtest->SetLineColor(kBlue);
        HANDAsymTest->Fit("fitasymtest","R");
	totalspintestpad03->Update();


	TString asymTitle = "Target Asymmetry for Runs ";
	asymTitle += HeRunNumber;
	asymTitle += "-";
	asymTitle += endHeRunNumber;
	TCanvas *asymCanvas = new TCanvas("asymCanvas",asymTitle,1400,730); //x,y
	asymCanvas->cd();
	asymCanvas->SetGrid();
	Double_t x[nuBins], y[nuBins], errorx[nuBins], errory[nuBins];
	double minError;
	double maxError;
	double posStuff;
	double negStuff;
	double UpEvents;
	double DownEvents;
	if ((targ == "v") || (targ == "l") || (targ == "t") || (targ == "c") || (targ == "h")) { check = true;}
	if (targ == "v") {asymOutFile << "Dataset:	Vertical 3He, Q2=" << kine << endl; cout << "Dataset:	Vertical 3He, Q2=" << kine << endl;}
	if (targ == "l") {asymOutFile << "Dataset:	Longitudinal 3He, Q2=" << kine << endl; cout << "Dataset:	Longitudinal 3He, Q2=" << kine << endl;}
	if (targ == "t") {asymOutFile << "Dataset:	Transverse 3He, Q2=" << kine << endl; cout << "Dataset:	Transverse 3He, Q2=" << kine << endl;}
	if (targ == "c") {asymOutFile << "Dataset:	Carbon, Q2=" << kine << endl; cout << "Dataset:	Carbon, Q2=" << kine << endl;}
	if (targ == "h") {asymOutFile << "Dataset:	Hydrogen, Q2=" << kine << endl; cout << "Dataset:	Hydrogen, Q2=" << kine << endl;}
	asymOutFile << "Runs:	" << HeRunNumber << "-" << endHeRunNumber << endl;
	cout << "Runs:	" << HeRunNumber << "-" << endHeRunNumber << endl;
	asymOutFile << "Omega	Asymmetry	Stat. Error	# HePos Events	HePos Charge	PosHe LT	# Neg Events	HeNeg Charge	NegHe LT" << endl;
	cout << "xBj	Asymmetry	Stat. Error	# HePos Events	HePos Charge	PosHe LT	# Neg Events	HeNeg Charge	NegHe LT" << endl;
	for (int i=0; i<nuBins; i++)
	{	
		UpEvents = newHANDTotalSpinUpx->GetBinContent(i);
		DownEvents = newHANDTotalSpinDownx->GetBinContent(i);
		x[i] = newHANDTotalSpinUpx->GetBinCenter(i);
		if (x[i] != (newHANDTotalSpinDownx->GetBinCenter(i))) { cout << endl << endl << "!!!!!!!!!!!!!!!!!!!!!!!!!! STOP! THERE'S A PROBLEM!!!!!!!!!!!!!!!!!!!!!!" << endl << endl << endl;}
		posStuff = UpEvents/(HeChargeScaleUp * HelivetimeUp + 1e-15);
		negStuff = DownEvents/(HeChargeScaleDown * HelivetimeDown + 1e-15);
		y[i] = ((posStuff - negStuff)/(posStuff + negStuff + 1e-15));
		errory[i] = 2*(DownEvents*sqrt(UpEvents) + UpEvents*sqrt(DownEvents))/((HeChargeScaleUp*HelivetimeUp)*(HeChargeScaleDown*HelivetimeDown)*pow((UpEvents/(HeChargeScaleUp*HelivetimeUp + 1e-25)) + (DownEvents/(HeChargeScaleDown*HelivetimeDown + 1e-25)),2) + 1e-15);
		if ((UpEvents == 0) || (DownEvents == 0)) { errory[i] = 1;}
		if ((UpEvents == 0) || (DownEvents == 0)) { y[i] = NULL;}
		if (i==0)
		{
			minError = y[i] - 2*errory[i];
			maxError = y[i] + 2*errory[i];
		}
		if ((y[i] - 2*errory[i]) < minError) { minError = y[i] - 2*errory[i];}
		if ((y[i] + 2*errory[i]) > maxError) { maxError = y[i] + 2*errory[i];}
		errorx[i] = ((nuMax - nuMin)/nuBins)/2;
		asymOutFile << x[i] << "	" << y[i] << "	" << errory[i] << "	" << UpEvents << "	" << HeChargeScaleUp << "	" << HelivetimeUp << "	" << DownEvents << "	" << HeChargeScaleDown << "	" << HelivetimeDown << endl;
		cout << x[i] << "	" << y[i] << "	" << errory[i] << "	" << UpEvents << "	" << HeChargeScaleUp << "	" << HelivetimeUp << "	" << DownEvents << "	" << HeChargeScaleDown << "	" << HelivetimeDown << endl;
	}
	asymGraph = new TGraphErrors(nuBins, x, y, errorx, errory);
	asymGraph->SetMarkerStyle(21);
	asymGraph->SetMarkerColor(4);
	asymGraph->SetTitle(asymTitle);
	asymTestHist = new TH2F("asymTestHist",asymTitle,nuBins,nuMin,nuMax,100,minError,maxError);
	asymTestHist->SetStats(kFALSE);
	asymTestHist->Draw();
	cout << "Fit min = " << nuMin << "; Fit max = " << nuMax << endl;
	TF1 *fitAsymGraph = new TF1("fitAsymGraph", "[0]", nuMin, nuMax);
	asymGraph->Draw("P");
	fitAsymGraph->SetLineColor(kBlue);
	asymGraph->Fit("fitAsymGraph","R");
	asymCanvas->Update();
/*
	TString TotalAsymOutTitle = outputPlotsHere;
	TotalAsymOutTitle += "target_asymmetry_good_for_Run_Num_";
	TotalAsymOutTitle += HeRunNumber;
	TotalAsymOutTitle += "-";
	TotalAsymOutTitle += endHeRunNumber;
	if (includeVetos) {TotalAsymOutTitle += "_with_vetos";}
	if (includeAntivetos) {TotalAsymOutTitle += "_with_antivetos";}
	if (antivetosAsVetos && includeAntivetos) {TotalAsymOutTitle += "_as_vetos";}
	TotalAsymOutTitle += ".png";
	asymCanvas->Print(TotalAsymOutTitle);
*/


	TString canvasTotalSpin = "TotalSpin";
	TString canvasTitleTotalSpin = "HAND - Total Spin";
	TCanvas *totalSpinCanvas = new TCanvas(canvasTotalSpin,canvasTitleTotalSpin,1400,730); //x,y
	totalspinpad01 =  new TPad("totalspinpad01","totalspinpad01",0.0000,0.5000,0.5000,1.0000,0,0,0);
	totalspinpad02 =  new TPad("totalspinpad02","totalspinpad02",0.5000,0.5000,1.0000,1.0000,0,0,0);
	totalspinpad03 =  new TPad("totalspinpad03","totalspinpad03",0.0000,0.0000,1.0000,0.5000,0,0,0);
	totalspinpad01->Draw(); totalspinpad02->Draw(); totalspinpad03->Draw();

	totalspinpad01->cd();
	cout << "HeChargeScaleUp: " << HeChargeScaleUp << "   HelivetimeUp: " << HelivetimeUp << endl;
	newHANDTotalSpinUpx->Scale(1/(HeChargeScaleUp * HelivetimeUp + 1e-25));
	newHANDTotalSpinUpx->SetTitle("Total Spin Up (Scaled by Charge, LT)");
	newHANDTotalSpinUpx->Draw();
	// ********************************************************************************
	// This section below gathers and prints some statistics on the plot
	TString HANDUpFactorsString = "Total Positive Charge for Runs: ";
	HANDUpFactorsString += HeChargeScaleUp;
	HANDUpFactorsString += " C";
	TString HANDUpFactorsString1 = "Total Positive Livetime for Runs: ";
	HANDUpFactorsString1 += HelivetimeUp;
	HANDUpFactors = new TPaveText(0.11,0.69,0.4,0.89,"NDC");
	TText *t1 = HANDUpFactors->AddText(HANDUpFactorsString);
	TText *t2 = HANDUpFactors->AddText(HANDUpFactorsString1);
	HANDUpFactors->Draw("same");
	// ********************************************************************************
	totalspinpad01->Update();

	totalspinpad02->cd();
	cout << "HeChargeScaleDown: " << HeChargeScaleDown << "   HelivetimeDown: " << HelivetimeDown << endl;
	newHANDTotalSpinDownx->Scale(1/(HeChargeScaleDown * HelivetimeDown + 1e-25));
	newHANDTotalSpinDownx->SetTitle("Total Spin Down (Scaled by Charge, LT)");
	newHANDTotalSpinDownx->Draw();
	// ********************************************************************************
	// This section below gathers and prints some statistics on the plot
	TString HANDDownFactorsString = "Total Negative Charge for Runs: ";
	HANDDownFactorsString += HeChargeScaleDown;
	HANDDownFactorsString += " C";
	TString HANDDownFactorsString1 = "Total Negative Livetime for Runs: ";
	HANDDownFactorsString1 += HelivetimeDown;
	HANDDownFactors = new TPaveText(0.11,0.69,0.4,0.89,"NDC");
	TText *t1 = HANDDownFactors->AddText(HANDDownFactorsString);
	TText *t2 = HANDDownFactors->AddText(HANDDownFactorsString1);
	HANDDownFactors->Draw("same");
	// ********************************************************************************
	totalspinpad02->Update();

	totalspinpad03->cd();
        TF1 *fitasym = new TF1("fitasym","[0]",nuMin,nuMax);
	HANDAsym = newHANDTotalSpinUpx->GetAsymmetry(newHANDTotalSpinDownx);
	TString AsymTitle = "Target Asymmerty with Neutron Cuts vs. xBj for runs ";
	AsymTitle += HeRunNumber;
	AsymTitle += "-";
	AsymTitle += endHeRunNumber;
	HANDAsym->SetTitle(AsymTitle);
	HANDAsym->Draw();
        fitasym->SetLineColor(kBlue);
        HANDAsym->Fit("fitasym","R");
	totalspinpad03->Update();
/*
	TString TotalSpinOutTitle = outputPlotsHere;
	TotalSpinOutTitle += "target_asymmetry_for_Run_Num_";
	TotalSpinOutTitle += HeRunNumber;
	TotalSpinOutTitle += "-";
	TotalSpinOutTitle += endHeRunNumber;
	if (includeVetos) {TotalSpinOutTitle += "_with_vetos";}
	TotalSpinOutTitle += ".png";
	totalSpinCanvas->Print(TotalSpinOutTitle);
*/

	asymOutFile.close();

//	TString exitst;
//	cout << "Are you ready to finish?" << endl;
//	cin >> exitst;

	cout << "All done!" << endl;

}
Example #28
0
void Unfold2(int algo= 3,bool useSpectraFromFile=0, bool useMatrixFromFile=0, int doToy = 0, int isMC = 0,char *spectraFileName = (char*)"pbpb_spectra_akPu3PF.root",double recoJetPtCut = 60.,double trackMaxPtCut = 0, int nBayesianIter = 4, int doBjets=1, int doTrigEffCorr=1) // algo 2 =akpu2 ; 3 =akpu3 ; 4 =akpu4 ;1 = icpu5
{
  
  gStyle->SetErrorX(0.);
  gStyle->SetPaintTextFormat("3.2f");
  gStyle->SetOptLogz(1);
  gStyle->SetPadRightMargin(0.13);	
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);


  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();
  
  // input files
  char *fileNamePP_mc = NULL;
  char *fileNamePbPb_mc = NULL;
  char *fileNamePP_data = NULL;
  char *fileNamePbPb_data = NULL;
  

  // pp file needs replacing
  if(doBjets)fileNamePP_data = (char*)"~/Work/bTagging/outputTowardsFinal/NewFormatV5_bFractionMCTemplate_pppp1_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root";
  //else fileNamePP_data = (char*)"../spectra/rawIncSpectra_MB_fixedBinSize_v4.root";
  else fileNamePP_data = (char*)"../spectra/rawIncSpectra_MB_varBinSize_v4.root";
  //if(doBjets)fileNamePbPb_data = (char*)"~/Work/bTagging/outputTowardsFinal/AltBinningV6_bFractionMCTemplate_ppPbPb1_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root";
  if(doBjets)fileNamePbPb_data = (char*)"~/Work/bTagging/outputTowardsFinal/bFractionMCTemplate_ppPbPb1_SSVHEat2.0FixCL0_bin_0_40_eta_0_2_binomErrors_jet55_wideBin_v2.root";
  //else fileNamePbPb_data = (char*)"../spectra/rawIncSpectra_MB_fixedBinSize_v4.root";
  else fileNamePbPb_data = (char*)"../spectra/rawIncSpectra_MB_varBinSize_v4.root";
  if(doBjets) fileNamePP_mc = (char*)"~/Work/bTagging/histos/ppMC_ppReco_ak3PF_BjetTrig_noIPupperCut.root";
  else fileNamePP_mc = (char*)"~/Work/bTagging/histos/ppMC_ppReco_ak3PF_QCDjetTrig_noIPupperCut.root";
  if(doBjets)fileNamePbPb_mc = (char*) "~/Work/bTagging/histos/PbPbBMC_pt30by3_ipHICalibCentWeight_noTrig.root";
  else fileNamePbPb_mc = (char*) "~/Work/bTagging/histos/PbPbQCDMC_pt30by3_ipHICalibCentWeight_noTrig.root";


  // grab ntuples
  TFile *infPbPb_mc = new TFile(fileNamePbPb_mc);
  TFile *infPP_mc = new TFile(fileNamePP_mc);
  

  string bJetString = "Inc";
  if(doBjets) bJetString = "bJets";

  // Output file
  TFile *pbpb_Unfo;
  if (isMC) pbpb_Unfo = new TFile(Form("pbpb_Unfo_%s_MC_v2.root",algoName[algo]),"RECREATE");
  else pbpb_Unfo  = new TFile(Form("pbpb_Unfo_%s_jtpt%.0f_%s_v4.root",algoName[algo],recoJetPtCut,bJetString.c_str()),"RECREATE");

  // Histograms used by RooUnfold
  UnfoldingHistos *uhist[nbins_cent+1];
		
  // Initialize Histograms   
	
  for (int i=0;i<=nbins_cent;i++) uhist[i] = new UnfoldingHistos(i);
	
  // Initialize reweighting functions
  /*
  TCut dataSelection;
  TCut dataSelectionPP;
  TCut TriggerSelectionPP;
  TCut TriggerSelectionPbPb80;

  if(doBjets)dataSelection = "weight*(abs(refparton_flavorForB)==5&&abs(jteta)<2)";
  else dataSelection = "weight*(abs(jteta)<2)";
  */

  if (isMC) cout<<"This is a MC closure test"<<endl;
  else cout<< "This is a data analysis"<<endl;    		     
	     	
  // Setup jet data branches, basically the jet tree branches are assigned to this object when we loop over the events
	
  JetDataPbPb *dataPbPb   = new JetDataPbPb(fileNamePbPb_mc,(char*)"nt"); // PbPb data	
  JetDataPP *dataPP = new JetDataPP(fileNamePP_mc,(char*)"nt");	// pp data
	
  TFile *fSpectra(0);		
  if (useSpectraFromFile||useMatrixFromFile){
    fSpectra = new TFile(spectraFileName,"read");
  }
  
  // Come back to the output file dir
  pbpb_Unfo->cd();

  cout <<"MC..."<<endl;	
  
  TH1F *hCent = new TH1F("hCent","",nbins_cent,boundaries_cent);
 

  // if you change the binning you have to change these, too
  // inclusive trig eff
  /*
    float trigEffInc[6]={0.777265,
			 0.95765,
			 0.998357,
			 0.999941,
			 1.,
			 1.};
  */

    // b-jet trig eff
    /*
    float trigEffbJet[6]={0.660276,
		      0.908997,
		      0.980793,
		      0.998767,
		      0.999442,
		      1.};
    */



 
		
  // Fill PbPb MC   
  if (!useMatrixFromFile) {
    for (Long64_t jentry2=0; jentry2<dataPbPb->tJet->GetEntries();jentry2++) {
      dataPbPb->tJet->GetEntry(jentry2);
      
      // change when we switch to centrality binning
      int cBin = 0;
            
      if ( dataPbPb->refpt  < 0. ) continue;
      if ( dataPbPb->jteta  > 2. || dataPbPb->jteta < -2. ) continue;
      if ( dataPbPb->refpt<0) dataPbPb->refpt=0;
      if (doBjets && fabs(dataPbPb->refparton_flavorForB)!=5) continue;
      //if (doBjets&& dataPbPb->discr_ssvHighEff<2) continue;
      if (doBjets && dataPbPb->jtptB < recoJetPtCut) continue;
      if (!doBjets && dataPbPb->jtptA < recoJetPtCut) continue;
      //if (!doTrigEffCorr && dataPbPb->isTrig <1) continue;
      if ( dataPbPb->isTrig <1) continue;
      
      //if(!doBjets)if(dataPbPb->refpt < 50 && dataPbPb->jtptA>120) continue;
      //if(doBjets)if(dataPbPb->refpt < 50 && dataPbPb->jtptB>120) continue;

      float weight = dataPbPb->weight;

      if(doTrigEffCorr){
	for(int iBin = 0; iBin<nbins_rec; iBin++){
	  float myJtPt = 0.;
	  if(doBjets) myJtPt = dataPbPb->jtptB;
	  else myJtPt = dataPbPb->jtptA;
	  if(myJtPt > boundaries_rec[iBin] && myJtPt < boundaries_rec[iBin+1]){
	    if(doBjets) weight/= trigEffbJet[iBin];
	    else weight/= trigEffInc[iBin];
	  }							  
	}
      }
      if (!isMC||jentry2 % 2 == 1) {
	if(doBjets)uhist[cBin]-> hMatrix->Fill(dataPbPb->refpt,dataPbPb->jtptB,weight);
	else uhist[cBin]-> hMatrix->Fill(dataPbPb->refpt,dataPbPb->jtptA,weight);
      }	  
      if (jentry2 % 2 == 0) {
	uhist[cBin]-> hGen->Fill(dataPbPb->refpt,weight);   
	if(doBjets)uhist[cBin]-> hMeas->Fill(dataPbPb->jtptB,weight);  	 
	else uhist[cBin]-> hMeas->Fill(dataPbPb->jtptA,weight);  	 
	//uhist[cBin]-> hMeasJECSys->Fill(dataPbPb->jtpt*(1.+0.02/nbins_cent*(nbins_cent-i)),weight); 
	// FIXME!!!!!!  i is supposed to be a loop over centrality !!!!
	if(doBjets)uhist[cBin]-> hMeasJECSys->Fill(dataPbPb->jtptB*(1.+0.02/nbins_cent*(nbins_cent-0)),weight); 
	else uhist[cBin]-> hMeasJECSys->Fill(dataPbPb->jtptA*(1.+0.02/nbins_cent*(nbins_cent-0)),weight); 
      }
    }

    //pp will just fill the last index of the centrality array

    // fill pp MC
    for (Long64_t jentry2=0; jentry2<dataPP->tJet->GetEntries();jentry2++) {
      dataPP->tJet->GetEntry(jentry2);
      
      if ( dataPP->refpt<0) continue;
      if ( dataPP->jteta  > 2. || dataPP->jteta < -2. ) continue;
      if ( dataPP->refpt<0) dataPP->refpt=0;
      if ( doBjets && fabs(dataPP->refparton_flavorForB)!=5) continue;
      //if ( doBjets && dataPP->discr_ssvHighEff<2) continue;
      if ( dataPP->jtpt < recoJetPtCut) continue;
      
      if (!isMC||jentry2 % 2 == 1) {
	uhist[nbins_cent]-> hMatrix->Fill(dataPP->refpt,dataPP->jtpt,dataPP->weight);
      }	  
      if (jentry2 % 2 == 0) {
	uhist[nbins_cent]-> hGen->Fill(dataPP->refpt,dataPP->weight);   
	uhist[nbins_cent]-> hMeas->Fill(dataPP->jtpt,dataPP->weight); 
      }           
    }
  }
  /*
  for (int i=0;i<=nbins_cent;i++){
    for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
	float binContent = uhist[i]->hGen->GetBinContent(x);
	float binError = uhist[i]->hGen->GetBinError(x);
	float binWidth =  uhist[i]->hGen->GetXaxis()->GetBinWidth(x);
	uhist[i]->hGen->SetBinContent(x,binContent/binWidth);
	uhist[i]->hGen->SetBinError(x,binError/binWidth);
    }
  }

<<<<<<< HEAD
  for (int i=0;i<=nbins_cent;i++){
    for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
	float binContent = uhist[i]->hMeas->GetBinContent(x);
	float binError = uhist[i]->hMeas->GetBinError(x);
	float binWidth =  uhist[i]->hMeas->GetXaxis()->GetBinWidth(x);
	uhist[i]->hMeas->SetBinContent(x,binContent/binWidth);
	uhist[i]->hMeas->SetBinError(x,binError/binWidth);
    }
  }

  for (int i=0;i<=nbins_cent;i++){
    for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
      for (int y=1;y<=uhist[i]->hMatrix->GetNbinsY();y++) {
	float binContent = uhist[i]->hMatrix->GetBinContent(x,y);
	float binError = uhist[i]->hMatrix->GetBinError(x,y);
	float binWidth2 =  uhist[i]->hMatrix->GetXaxis()->GetBinWidth(x)*uhist[i]->hMatrix->GetYaxis()->GetBinWidth(y);
	uhist[i]->hMatrix->SetBinContent(x,y,binContent/binWidth2);
	uhist[i]->hMatrix->SetBinError(x,y,binError/binWidth2);
      }      
    }
  }	
  */


  if (isMC==0) {
    // Use measured histogram from Matt & Kurt's file
	   
    // PbPb file:

    TFile *infMatt = new TFile(fileNamePbPb_data);
    TH1F *hMattPbPb = NULL;
    TH1F *hTagEffPbPb = NULL;

    if(doBjets){
      hMattPbPb = (TH1F*) infMatt->Get("hRawBData");
      hTagEffPbPb = (TH1F*) infMatt->Get("hBEfficiencyMC");
    }
    else hMattPbPb = (TH1F*) infMatt->Get("hPbPb");
    //divideBinWidth(hMattPbPb);
           
    // Need to match the binning carefully, please double check whenever you change the binning
    for (int i=1;i<=hMattPbPb->GetNbinsX();i++)
      {
     	float binContent = hMattPbPb->GetBinContent(i);  
	float binError = hMattPbPb->GetBinError(i); 

	if(doBjets){
	  float tagEff =hTagEffPbPb->GetBinContent(i);
	  float tagEffErr =     hTagEffPbPb->GetBinError(i);   
	  
	  if(tagEff>0){
	    // careful of the order here!
	    binError=binContent/tagEff *sqrt(tagEffErr*tagEffErr/tagEff/tagEff + binError*binError/binContent/binContent);
	    binContent /= tagEff;
	  }
	  else cout<<" TAGEFF = 0"<<endl;	  
	}

	float binCenter = hMattPbPb->GetBinCenter(i);  
	if(binCenter - hMattPbPb->GetBinWidth(i)/2.  < recoJetPtCut) continue;
	
	int ibin=0;
	
	for(ibin=1;ibin<=uhist[0]->hMeas->GetNbinsX();ibin++){
	  float testLowEdge = uhist[0]->hMeas->GetBinLowEdge(ibin);
	  float testBinWidth = uhist[0]->hMeas->GetBinWidth(ibin);
	  if(binCenter>testLowEdge && binCenter < testLowEdge+testBinWidth) break;
	}
	
	
	if(doTrigEffCorr){
	  float trigEff = 0;
	  if(doBjets) trigEff = trigEffbJet[ibin-1];
	  else  trigEff = trigEffInc[ibin-1];

	  cout<<" binCenter = "<<binCenter<<" trigEff "<<trigEff<<endl;

	  if(trigEff>0){
	    // careful of the order here!
	    binContent /= trigEff;
	    binError /= trigEff;
	  }
	  else cout<<" TRIGEFF = 0"<<endl;	  
	}


     
	uhist[0]->hMeas->SetBinContent(ibin,binContent);  
	uhist[0]->hMeas->SetBinError(ibin,binError);  

      }

    // pp file:
    TFile *infMattPP = new TFile(fileNamePP_data);
    TH1F *hMattPP = NULL;
    TH1F *hTagEffPP = NULL;
    if(doBjets){
      hMattPP = (TH1F*) infMattPP->Get("hRawBData");
      hTagEffPP = (TH1F*) infMattPP->Get("hBEfficiencyMC");
    }
    else hMattPP = (TH1F*) infMattPP->Get("hpp");
    //divideBinWidth(hMattPP);	   
    for (int i=1;i<=hMattPP->GetNbinsX();i++)
      {
      	float binContent = hMattPP->GetBinContent(i);  
	float binError = hMattPP->GetBinError(i);  
	
	if(doBjets){
	  float tagEff =hTagEffPP->GetBinContent(i);
	  float tagEffErr =     hTagEffPP->GetBinError(i);   
	  if(tagEff>0){
	    // careful of the order here!
	    binError=binContent/tagEff *sqrt(tagEffErr*tagEffErr/tagEff/tagEff + binError*binError/binContent/binContent);
	    binContent /= tagEff;
	  }
	  else cout<<" TAGEFF = 0"<<endl;	  
	}
	
     	float binCenter = hMattPP->GetBinCenter(i);  
	if(binCenter - hMattPP->GetBinWidth(i)/2.  < recoJetPtCut) continue;

	int ibin=0;

	for(ibin=1;ibin<=uhist[nbins_cent]->hMeas->GetNbinsX();ibin++){
	  float testLowEdge = uhist[nbins_cent]->hMeas->GetBinLowEdge(ibin);
	  float testBinWidth = uhist[nbins_cent]->hMeas->GetBinWidth(ibin);
	  if(binCenter>testLowEdge && binCenter < testLowEdge+testBinWidth) break;
	}
	uhist[nbins_cent]->hMeas->SetBinContent(ibin,binContent);  
	uhist[nbins_cent]->hMeas->SetBinError(ibin,binError);  

    
	/*
	cout<<" i "<<i<<endl;
	int newBin = i+uhist[nbins_cent]->hMeas->FindBin(61)-1;

	cout<<" newBin "<<newBin<<endl;
	cout<<"hMattPP->GetBinCenter(i) "<<hMattPP->GetBinCenter(i)<<endl;
	cout<<"uhist[nbins_cent]->hMeas->GetBinCenter(newBin) "<<uhist[nbins_cent]->hMeas->GetBinCenter(newBin)<<endl;
	*/
      }

  }



   //=========================================Response Matrix========================================================= 

  cout <<"Response Matrix..."<<endl;
	
  TCanvas * cMatrix = new TCanvas("cMatrix","Matrix",800,400);
  cMatrix->Divide(2,1);

  for (int i=0;i<=nbins_cent;i++){
    cMatrix->cd(i+1);
    if (!useMatrixFromFile) {
      TF1 *f = new TF1("f","[0]*pow(x+[2],[1])");
      f->SetParameters(1e10,-8.8,40);
      for (int y=1;y<=uhist[i]->hMatrix->GetNbinsY();y++) {
	double sum=0;
	for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
	  if (uhist[i]->hMatrix->GetBinContent(x,y)<=1*uhist[i]->hMatrix->GetBinError(x,y)) {
	    uhist[i]->hMatrix->SetBinContent(x,y,0);
	    uhist[i]->hMatrix->SetBinError(x,y,0);
	  }
	  sum+=uhist[i]->hMatrix->GetBinContent(x,y);
	}
				
	for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {	   
	  double ratio = 1;
	  uhist[i]->hMatrix->SetBinContent(x,y,uhist[i]->hMatrix->GetBinContent(x,y)*ratio);
	  uhist[i]->hMatrix->SetBinError(x,y,uhist[i]->hMatrix->GetBinError(x,y)*ratio);
	}
      }
    }
    uhist[i]->hResponse = (TH2F*)uhist[i]->hMatrix->Clone(Form("hResponse_cent%d",i));

    for (int y=1;y<=uhist[i]->hResponse->GetNbinsY();y++) {
      double sum=0;
      for (int x=1;x<=uhist[i]->hResponse->GetNbinsX();x++) {
	if (uhist[i]->hResponse->GetBinContent(x,y)<=0*uhist[i]->hResponse->GetBinError(x,y)) {
	  uhist[i]->hResponse->SetBinContent(x,y,0);
	  uhist[i]->hResponse->SetBinError(x,y,0);
	}
	sum+=uhist[i]->hResponse->GetBinContent(x,y);
      }
			
      for (int x=1;x<=uhist[i]->hResponse->GetNbinsX();x++) {  	
	if (sum==0) continue;
	double ratio = uhist[i]->hMeas->GetBinContent(y)/sum;
	if (uhist[i]->hMeas->GetBinContent(y)==0) ratio = 1e-100/sum;
      }
    }
		
    TH1F *hProj = (TH1F*)uhist[i]->hResponse->ProjectionY(Form("hProj_cent%d",i));
    
    for (int y=1;y<=uhist[i]->hResponse->GetNbinsY();y++) {
      for (int x=1;x<=uhist[i]->hResponse->GetNbinsX();x++) {  	
	double sum=hProj->GetBinContent(y);
	cout <<y<<" "<<x<<" "<<sum<<endl;
	if (sum==0) continue;
	double ratio = uhist[i]->hMeas->GetBinContent(y)/sum;
	if (uhist[i]->hMeas->GetBinContent(y)==0) ratio = 1e-100/sum;
        uhist[i]->hResponse->SetBinContent(x,y,uhist[i]->hResponse->GetBinContent(x,y)*ratio);
	uhist[i]->hResponse->SetBinError(x,y,uhist[i]->hResponse->GetBinError(x,y)*ratio);
      }
    }

    uhist[i]->hResponseNorm = (TH2F*)uhist[i]->hMatrix->Clone(Form("hResponseNorm_cent%d",i));
    for (int x=1;x<=uhist[i]->hResponseNorm->GetNbinsX();x++) {
      double sum=0;
      for (int y=1;y<=uhist[i]->hResponseNorm->GetNbinsY();y++) {
	if (uhist[i]->hResponseNorm->GetBinContent(x,y)<=0*uhist[i]->hResponseNorm->GetBinError(x,y)) {
	  uhist[i]->hResponseNorm->SetBinContent(x,y,0);
	  uhist[i]->hResponseNorm->SetBinError(x,y,0);
	}
	sum+=uhist[i]->hResponseNorm->GetBinContent(x,y);
      }
			
      for (int y=1;y<=uhist[i]->hResponseNorm->GetNbinsY();y++) {  	
	if (sum==0) continue;
	double ratio = 1./sum;
	uhist[i]->hResponseNorm->SetBinContent(x,y,uhist[i]->hResponseNorm->GetBinContent(x,y)*ratio);
	uhist[i]->hResponseNorm->SetBinError(x,y,uhist[i]->hResponseNorm->GetBinError(x,y)*ratio);
      }
    }
		
    uhist[i]->hResponse->Draw("colz");
		
    if (!useMatrixFromFile) uhist[i]->hMatrixFit = uhist[i]->hMatrix;
    uhist[i]->hMatrixFit->SetName(Form("hMatrixFit_cent%d",i));
  }

  pbpb_Unfo->cd();
	
  cout << "==================================== UNFOLD ===================================" << endl;
	
  //char chmet[100]; 
	
  // ======================= Reconstructed pp and PbPb spectra =========================================================
  TCanvas * cPbPb = new TCanvas("cPbPb","Comparison",1200,600);
  cPbPb->Divide(2,1); 
  cPbPb->cd(1);
	
  TH1F *hRecoBW[nbins_cent+1], *hRecoBinByBinBW[nbins_cent+1], *hMeasBW[nbins_cent+1], *hGenBW[nbins_cent+1];


  TCanvas * cPbPbMeas = new TCanvas("cPbPbMeas","Measurement",1200,600);
  cPbPbMeas->Divide(2,1); 
  cPbPbMeas->cd(1);
	

  for (int i=0;i<=nbins_cent;i++) {
    cPbPb->cd(i+1)->SetLogy();   
    // Do Bin-by-bin
    TH1F *hBinByBinCorRaw = (TH1F*)uhist[i]->hResponse->ProjectionY(); 
    TH1F *hMCGen           = (TH1F*)uhist[i]->hResponse->ProjectionX(); // gen
    hBinByBinCorRaw->Divide(hMCGen);
    TF1 *f = new TF1("f","[0]+[1]*x");
    hBinByBinCorRaw->Fit("f","LL ","",90,300);
    TH1F* hBinByBinCor = (TH1F*)hBinByBinCorRaw->Clone();//functionHist(f,hBinByBinCorRaw,Form("hBinByBinCor_cent%d",i));
    uhist[i]->hRecoBinByBin = (TH1F*) uhist[i]->hMeas->Clone(Form("hRecoBinByBin_cent%d",i));
    uhist[i]->hRecoBinByBin->Divide(hBinByBinCor);
		
    // Do unfolding
    //if (isMC) uhist[i]->hMeas = (TH1F*)uhist[i]->hMatrix->ProjectionY()->Clone(Form("hMeas_cent%d",i));
    prior myPrior(uhist[i]->hMatrixFit,uhist[i]->hMeas,0);
    myPrior.unfold(uhist[i]->hMeas,1);
    TH1F *hPrior;//=(TH1F*) functionHist(fPow,uhist[i]->hMeas,Form("hPrior_cent%d",i));
//    hPrior = (TH1F*)uhist[i]->hGen->Clone("hPrior");
//    hPrior = (TH1F*)uhist[i]->hMeas->Clone(Form("hPrior_cent%d",i));
    hPrior=(TH1F*)hMCGen->Clone("hPrior");
    removeZero(hPrior);
    TH1F *hReweighted = (TH1F*)(TH1F*)uhist[i]->hResponse->ProjectionY(Form("hReweighted_cent%d",i));
		
    bayesianUnfold myUnfoldingJECSys(uhist[i]->hMatrixFit,hPrior,0);
    myUnfoldingJECSys.unfold(uhist[i]->hMeasJECSys,nBayesianIter);
    bayesianUnfold myUnfoldingSmearSys(uhist[i]->hMatrixFit,hPrior,0);
    myUnfoldingSmearSys.unfold(uhist[i]->hMeasSmearSys,nBayesianIter);
    bayesianUnfold myUnfolding(uhist[i]->hMatrixFit,myPrior.hPrior,0);
    myUnfolding.unfold(uhist[i]->hMeas,nBayesianIter);
    cout <<"Unfolding bin "<<i<<endl;

    delete hBinByBinCorRaw;
    delete hMCGen;

    // Iteration Systematics
    for (int j=2;j<=7;j++)
      {

	bayesianUnfold myUnfoldingSys(uhist[i]->hMatrixFit,hPrior,0);
	myUnfoldingSys.unfold(uhist[i]->hMeas,j);
	uhist[i]->hRecoIterSys[j]  = (TH1F*) myUnfoldingSys.hPrior->Clone(Form("hRecoRAA_IterSys%d_cent%d",j,i));
      }
    
    
    uhist[i]->hReco         = (TH1F*) uhist[i]->hRecoIterSys[nBayesianIter]->Clone(Form("Unfolded_cent%i",i));
    uhist[i]->hRecoJECSys   = (TH1F*) myUnfoldingJECSys.hPrior->Clone(Form("UnfoldedJeCSys_cent%i",i));
    uhist[i]->hRecoSmearSys   = (TH1F*) myUnfoldingSmearSys.hPrior->Clone(Form("UnfoldedSmearSys_cent%i",i));
    uhist[i]->hRecoBinByBin->SetName(Form("UnfoldedBinByBin_cent%i",i));
    
    if (doToy) {
      TCanvas *cToy = new TCanvas("cToy","toy",600,600);
      cToy->cd();
      int nExp=1000;
      TH1F *hTmp[nbins_truth+1];
      TH1F *hTmp2[nbins_truth+1];
      for (int j=1;j<=nbins_truth;j++) {
	hTmp[j] = new TH1F(Form("hTmp%d",j),"",200,0,10.+uhist[i]->hReco->GetBinContent(j)*2);
	hTmp2[j] = new TH1F(Form("hTmp2%d",j),"",200,0,10.+uhist[i]->hRecoBinByBin->GetBinContent(j)*2);
      }
      for (int exp =0; exp<nExp; exp++) {
	TH1F *hToy = (TH1F*)uhist[i]->hMeas->Clone();   
	TH2F *hMatrixToy = (TH2F*)uhist[i]->hMatrixFit->Clone();
	hToy->SetName("hToy");
	if (exp%100==0) cout <<"Pseudo-experiment "<<exp<<endl;
	for (int j=1;j<=hToy->GetNbinsX();j++) {
	  double value = gRandom->Poisson(uhist[i]->hMeas->GetBinContent(j));
	  hToy->SetBinContent(j,value);
	}
				
	for (int j=1;j<=hMatrixToy->GetNbinsX();j++) {
	  for (int k=1;k<=hMatrixToy->GetNbinsY();k++) {
	    double value = gRandom->Gaus(uhist[i]->hMatrixFit->GetBinContent(j,k),uhist[i]->hMatrixFit->GetBinError(j,k));
	    hMatrixToy->SetBinContent(j,k,value);
	  }
	}

	prior myPriorToy(hMatrixToy,hToy,0.0);
	myPriorToy.unfold(hToy,1);
	bayesianUnfold myUnfoldingToy(hMatrixToy,myPriorToy.hPrior,0.0);
	myUnfoldingToy.unfold(hToy,nBayesianIter);
	TH1F *hRecoTmp = (TH1F*) myUnfoldingToy.hPrior->Clone();
				
	for (int j=1;j<=hRecoTmp->GetNbinsX();j++) {
	  hTmp[j]->Fill(hRecoTmp->GetBinContent(j));
	}
	delete hToy;
	delete hRecoTmp;
	delete hMatrixToy;
      }
      TF1 *fGaus = new TF1("fGaus","[0]*TMath::Gaus(x,[1],[2])");
      for (int j=1;j<=nbins_truth;j++)
	{

	  f->SetParameters(hTmp[j]->GetMaximum(),hTmp[j]->GetMean(),hTmp[j]->GetRMS());
				
	  if (hTmp[j]->GetMean()>0) {
	    hTmp[j]->Fit(fGaus,"LL Q ");
	    hTmp[j]->Fit(fGaus,"LL Q ");
	    uhist[i]->hReco->SetBinError(j,f->GetParameter(2));
	  }	       
	  f->SetParameters(hTmp2[j]->GetMaximum(),hTmp2[j]->GetMean(),hTmp2[j]->GetRMS());
	  if (hTmp2[j]->GetMean()>0) {
	    hTmp2[j]->Fit(fGaus,"LL Q ");
	    hTmp2[j]->Fit(fGaus,"LL Q ");
	    uhist[i]->hRecoBinByBin->SetBinError(j,f->GetParameter(2));
	  }	       
	  delete hTmp[j];
	  delete hTmp2[j];
	}
      cPbPb->cd(i+1);
    }

    uhist[i]->hMeas->SetMarkerStyle(20);
    uhist[i]->hMeas->SetMarkerColor(2);
    uhist[i]->hReco->SetMarkerStyle(25);
    uhist[i]->hReco->SetName(Form("hReco_cent%d",i));
    
    uhist[i]->hReco->SetXTitle("p_{T} (GeV/c)");    
    uhist[i]->hReco->SetYTitle("Counts");    
    uhist[i]->hReco->GetXaxis()->SetNdivisions(505);
    //uhist[i]->hReco->Draw("");    
    uhist[i]->hReco->SetAxisRange(0,250,"X");
    uhist[i]->hReco->Draw("");   
     
    uhist[i]->hGen->SetLineWidth(2);
    uhist[i]->hGen->SetLineColor(2);
    //if(isMC)uhist[i]->hGen->Draw("hist same");
    //uhist[i]->hReco->Draw("same");    
    uhist[i]->hRecoBinByBin->SetMarkerStyle(28);
    uhist[i]->hRecoBinByBin->Draw("same");    

    uhist[i]->hReco->SetAxisRange(recoJetPtCut,300);
    TH1F *hReproduced = (TH1F*)myUnfolding.hReproduced->Clone(Form("hReproduced_cent%d",i));
    hReproduced->SetMarkerColor(4);
    hReproduced->SetMarkerStyle(24);
    //uhist[i]->hMeas->Draw("same");    

    hRecoBW[i] = (TH1F*)uhist[i]->hReco->Clone(Form("hReco%d",i));
    hRecoBinByBinBW[i] = (TH1F*)uhist[i]->hRecoBinByBin->Clone(Form("hRecoBinByBin%d",i));
    hMeasBW[i] = (TH1F*)uhist[i]->hMeas->Clone(Form("hMeas%d",i));
    if(isMC)hGenBW[i] = (TH1F*)uhist[i]->hGen->Clone(Form("hGen%d",i));

    divideBinWidth(hRecoBW[i]);    
    if(isMC)divideBinWidth(hGenBW[i]);    
    divideBinWidth(hRecoBinByBinBW[i]);    
    divideBinWidth(hMeasBW[i]);    

    hRecoBW[i]->Draw();
    if(isMC)hGenBW[i]->Draw("hist,same");
    hRecoBinByBinBW[i]->Draw("same");
    hMeasBW[i]->Draw("same");
    

    uhist[i]->hReco->SetTitle("Baysian Unfolded");
    uhist[i]->hRecoBinByBin->SetTitle("Bin-by-bin Unfolded");

    TLegend *leg = new TLegend(0.45,0.65,0.85,0.95);
    leg->SetBorderSize(0);
    leg->SetFillStyle(0);
    leg->AddEntry(uhist[i]->hMeas,"Measured","pl");
    leg->AddEntry(uhist[i]->hReco,"Bayesian unfolded","pl");
    leg->AddEntry(uhist[i]->hRecoBinByBin,"Bin-by-bin unfolded","pl");
    if(isMC)leg->AddEntry(uhist[i]->hGen,"Generator level truth","l");
    leg->Draw();

    cPbPbMeas->cd(i+1)->SetLogy();   
    uhist[i]->hMeas->SetAxisRange(0,240,"X");
    uhist[i]->hMeas->Draw();
    hReproduced->Draw("same");

    TLegend *leg2 = new TLegend(0.5,0.5,0.85,0.9);
    leg2->SetBorderSize(0);
    leg2->SetFillStyle(0);
    leg2->AddEntry(uhist[i]->hMeas,"Measured","pl");
    leg2->AddEntry(hReproduced,"Reproduced","pl");

    leg2->Draw();
  }	     
  
 
  pbpb_Unfo->Write();

  SysData systematics;
  TLine *line = new TLine(60,1,250,1);

  // Iteration systematics
  TCanvas *cIterSys = new TCanvas("cIterSys","cIterSys",1200,600);
  cIterSys->Divide(2,1);
  cIterSys->cd(2);
  TH1F *hRecoIterSysPP[100];
  TH1F *hRebinPP_tmp         = rebin(uhist[nbins_cent]->hReco, (char*)"hRebinPP_tmp");
  TLegend *legBayesianIterPP = myLegend(0.4,0.7,0.9,0.9);
  legBayesianIterPP->AddEntry("","PP","");
         
  for (int j=2;j<7;j++) {
    hRecoIterSysPP[j] = rebin(uhist[nbins_cent]->hRecoIterSys[j],Form("hRecoIterSysPP_IterSys%d",j));
    hRecoIterSysPP[j]->SetLineColor(colorCode[j-2]);
    hRecoIterSysPP[j]->SetMarkerColor(colorCode[j-2]);
    hRecoIterSysPP[j]->Divide(hRebinPP_tmp);
    if (j==2){
      makeHistTitle(hRecoIterSysPP[j],(char*)"",(char*)"Jet p_{T} (GeV/c)",(char*)"Ratio (Unfolded / Nominal)");
      hRecoIterSysPP[j]->SetTitleOffset(1.4,"Y");
      hRecoIterSysPP[j]->SetTitleOffset(1.2,"X");
      hRecoIterSysPP[j]->SetAxisRange(0.5,1.5,"Y");
      hRecoIterSysPP[j]->Draw(); 
    } else {
      hRecoIterSysPP[j]->Draw("same");
    }
         
    checkMaximumSys(systematics.hSysIter[nbins_cent],hRecoIterSysPP[j],0,1.1);
    legBayesianIterPP->AddEntry(hRecoIterSysPP[j],Form("Iteration %d",j),"pl");     
  }

  legBayesianIterPP->Draw();
  line->Draw();
  drawEnvelope(systematics.hSysIter[nbins_cent],(char*)"hist same");


  cIterSys->cd(1);
  TH1F *hRecoIterSysPbPb[100];
  TH1F *hRebinPbPb_tmp         = rebin(uhist[0]->hReco, (char*)"hRebinPbPb_tmp");
  TLegend *legBayesianIterPbPb = myLegend(0.4,0.7,0.9,0.9);
  legBayesianIterPbPb->AddEntry("","PbPb","");
  for (int j=2;j<7;j++) {
    hRecoIterSysPbPb[j] = rebin(uhist[0]->hRecoIterSys[j],Form("hRecoIterSysPbPb_IterSys%d",j));
    hRecoIterSysPbPb[j]->SetLineColor(colorCode[j-2]);
    hRecoIterSysPbPb[j]->SetMarkerColor(colorCode[j-2]);
    hRecoIterSysPbPb[j]->Divide(hRebinPbPb_tmp);
    if (j==2){
      makeHistTitle(hRecoIterSysPbPb[j],(char*)"",(char*)"Jet p_{T} (GeV/c)",(char*)"Ratio (Unfolded / Nominal)");
      hRecoIterSysPbPb[j]->SetTitleOffset(1.4,"Y");
      hRecoIterSysPbPb[j]->SetTitleOffset(1.2,"X");
      hRecoIterSysPbPb[j]->SetAxisRange(0.5,1.5,"Y");
      hRecoIterSysPbPb[j]->Draw(); 
    } else {
      hRecoIterSysPbPb[j]->Draw("same");
    }
         
    checkMaximumSys(systematics.hSysIter[0],hRecoIterSysPbPb[j],0,1.1);
    legBayesianIterPbPb->AddEntry(hRecoIterSysPbPb[j],Form("Iteration %d",j),"pl");     
  }
  legBayesianIterPbPb->Draw();
  line->Draw();
  drawEnvelope(systematics.hSysIter[0],(char*)"hist same");
}
//___________________________________________________________________________
Double_t* Ifit(int shift, Double_t& dataResult, Double_t& dataErr, std::string dataFile, 
	       TH1D* hsig, TH1D* hbkg, TH1D* hEGdata, Double_t* FitPar,
	       int ptbin=30, char EBEE[10]="EB", int fit_data=2)
{
  
  printf(" *** calling Ifit for %s , ptbin %d *** \n\n", EBEE,ptbin);

  cout << "The number of bins are: " << endl;
  cout << "hdata nbins = " << hEGdata->GetNbinsX() << endl;
  cout << "hsig nbins = " << hsig->GetNbinsX() << endl;
  cout << "hbkg nbins = " << hbkg->GetNbinsX() << endl;
  

  TCanvas *c1 = new TCanvas("HF1", "Histos1", 0, 0, 600, 600);
  gStyle->SetOptFit(0);

  if(fit_data != 3) dataColl.clear();
  sigColl.clear();
  bkgColl.clear();

  totalColl.clear();
  ctauColl.clear();
  Para.clear();
  Para_err.clear();

  info.clear();
  info_err.clear();

  float ptmax=0.;  
  if(ptbin== 21) ptmax= 23;
  if(ptbin== 23) ptmax= 26;
  if(ptbin== 26) ptmax= 30;
  if(ptbin== 30) ptmax= 35;
  if(ptbin== 35) ptmax= 40;
  if(ptbin== 40) ptmax= 45;
  if(ptbin== 45) ptmax= 50;
  if(ptbin== 50) ptmax= 60;
  if(ptbin== 60) ptmax= 85;
  if(ptbin== 85) ptmax= 120;
  if(ptbin== 120) ptmax= 300;
  if(ptbin== 300) ptmax= 500;



  Double_t* fitted = new Double_t[6];
  fitted[0] = 0.;    fitted[1] = 0.;    fitted[2] = 0.;    fitted[3] = 0.;
  fitted[4] = 0.;    fitted[5] = 0.;

  char hname[30];


  hsig->SetLineColor(1);
  hbkg->SetLineColor(1);
  hsig->SetNdivisions(505,"XY");
  hbkg->SetNdivisions(505,"XY");
  hsig->SetTitle("");
  hbkg->SetTitle("");
  hsig->SetXTitle("combined ISO (GeV)");
  hbkg->SetXTitle("combined ISO (GeV)");

  TH1F *hsum = (TH1F*)hsig->Clone();  
  hsum->Add(hbkg,1);
  float ntemplate = 1.;
  if (hsum->Integral()>1.) ntemplate = hsum->Integral();
  float sigfrac = hsig->Integral()/ntemplate*0.8;

  TH1F *hsum_norm = (TH1F*)hsum->Clone();  
  hsum_norm->Scale(1./hsum->Integral());

  TH1F *hdata = new TH1F();
  int ndata=0;
  if ( fit_data==1 ) {
    hdata = (TH1F*)hEGdata->Clone();
    ndata = (int)hdata->Integral();    
    for(int ibin=1; ibin<=hdata->GetNbinsX(); ibin++){
      for(int ipoint=0; ipoint<hdata->GetBinContent(ibin); ipoint++) {
	dataColl.push_back(hdata->GetBinCenter(ibin));
      }
    }
    ndata = dataColl.size();
  }else if (fit_data==2 ){
      hdata = (TH1F*)hEGdata->Clone();
    hdata -> Reset();
    dataColl.clear();
    FILE *infile =  fopen(dataFile.data(),"r");  
    float xdata, xdata1, xdata2; // combined isolation, pt, eta

    int flag = 1;
    while (flag!=-1){
      flag =fscanf(infile,"%f %f %f",&xdata, &xdata1, &xdata2);
      if( xdata1 >= ptbin && xdata1 < ptmax && xdata<20.) {
	if((strcmp(EBEE,"EB")==0 && TMath::Abs(xdata2)<1.45) ||
	   (strcmp(EBEE,"EE")==0 && TMath::Abs(xdata2)<2.5 && TMath::Abs(xdata2)>1.7) ) {
 	  dataColl.push_back(xdata);
	  hdata->Fill(xdata);
 	}
      } 
    }// keep reading files as long as text exists
    ndata = dataColl.size();

    printf("test print data 2 %2.3f \n", dataColl[2]);    
//     cout << "ndata in dataColl = " << ndata << endl;
    if ( ndata == 0 ) {
      printf(" no data to fit \n");
      return fitted;
    }
  }

  if(ndata==0) {
    printf(" ---  no events in the fit \n");
    return fitted;
  }
    
  //test fit the template and get PDFs
  TCanvas *c10 = new TCanvas("c10","c10",1000,500);
  c10->Divide(2,1);
  c10->cd(1);

  double par[20] = {hsig->GetMaximum(), 1., 0.6, 0.3,
		    hbkg->GetMaximum(), -.45, -0.05, 0.03, 1., 1., 1., 1.};

  if(strcmp(EBEE,"EE")==0) { par[2]=-0.1, par[3]=0.2; par[6]=-0.15; par[7]=0.02; };
  int fit_status;

  TF1 *f1 = new TF1("f1", exp_conv, -1., 20., 11);
  TF1 *fmcsigfit = new TF1("fmcsigfit", exp_conv, -1., 20., 11);
  fmcsigfit->SetLineColor(4);
  fmcsigfit->SetLineWidth(2);

  f1->SetNpx(10000);
  f1->SetParameters(par);
  f1->SetLineWidth(2);
  c10->cd(1);
  fit_status = hsig->Fit(f1,"","",-1., 5.);

  hsig->Draw();
  f1->Draw("same");
  if ( fit_status > 0 ) {
     printf("fit signal template failed. QUIT \n");
     return fitted;
  }
  if(para_index>0 && para_index<4){
    double tmppar = f1->GetParameter(para_index);
    f1->SetParameter(para_index, tmppar+para_sigma*f1->GetParError(para_index));
  }

  TF1 *fmcsig = (TF1*)f1->Clone();
  TF1 *fmcsigcorr = (TF1*)f1->Clone();
  fmcsig->SetNpx(10000);
  fmcsigcorr->SetNpx(10000);
  fmcsigfit->SetNpx(10000);
  
  TCanvas *c101 = new TCanvas("c101","c101",1000,500);
  c101->Divide(2,1);
  c101->cd(1);

  fmcsig->SetLineColor(1);
//   fmcsig->Draw();
//   f1->Draw("same");
  TH1F *htmp1 = (TH1F*)fmcsig->GetHistogram();
//   TH1F *htmp2 = (TH1F*)fmcsigcorr->GetHistogram();
  
  TH2F *htmp2 = new TH2F("htmp2","",210, -1., 20., 100, 0., htmp1->GetMaximum()*1.25);

  htmp2->SetNdivisions(505,"XY");
  htmp2->SetXTitle("Iso");
  htmp2->SetYTitle("A.U.");
  htmp2->SetLineColor(1);

//   htmp2->Draw();
//   htmp1->Draw("same");
//   htmp2->Add(htmp1,-1);
//   htmp2->Divide(htmp1);
  htmp2->GetXaxis()->SetRangeUser(-1., 10.);
  htmp2->SetMinimum(-1.);
  //htmp2->SetMaximum(1.5);
  htmp2->Draw();
  fmcsig->Draw("same");
//   fmcsigcorr->Draw("same");
  
  TLegend *tleg1 = new TLegend(0.5, 0.7, 0.93, 0.92);
  tleg1->SetHeader("");
  tleg1->SetFillColor(0);
  tleg1->SetShadowColor(0);
  tleg1->SetBorderSize(0);
  tleg1->AddEntry(fmcsig,"Zee data","l");
  //tleg1->AddEntry(fmcsigcorr,"corrected shape","l");
  tleg1->AddEntry(fmcsigfit,"shape from data","l");
  tleg1->Draw();

  //return fitted;
       
  SigPDFnorm = f1->Integral(-1.,20.);
  printf("status %d, sig area %3.3f \n", fit_status,f1->Integral(-1., 20.));


  f1->SetParameter(2,f1->GetParameter(2)+0.2);
  f1->SetParameter(3,f1->GetParameter(3)+0.1);

  Para.push_back(f1->GetParameter(0));
  Para.push_back(f1->GetParameter(1));
  Para.push_back(f1->GetParameter(2));
  Para.push_back(f1->GetParameter(3));

  Para_err.push_back(f1->GetParError(0));
  Para_err.push_back(f1->GetParError(1));
  Para_err.push_back(f1->GetParError(2));
  Para_err.push_back(f1->GetParError(3));

  c10->cd(2);
  TF1 *fbkgfit = new TF1("fbkgfit", expinv_power, -1., 20., 11);  

  TF1 *f3 = new TF1("f3", expinv_power, -1., 20., 11);
  fbkgfit->SetNpx(10000);  
  fbkgfit->SetLineColor(4);
  fbkgfit->SetLineWidth(2);

  f3->SetNpx(10000);
  f3->SetLineWidth(2);
  f3->SetParameters(f1->GetParameters());
    
  f3->SetParLimits(5,-5.,0.);
  f3->SetParLimits(6,-0.5,0.);
  f3->SetParLimits(7,0.001,0.2);
  f3->SetParLimits(8,0.5,5.);
  if ( strcmp(EBEE,"EB")==0 ){  
//     f3->FixParameter(8,1.);
//     f3->FixParameter(6,-0.1);
    f3->SetParLimits(8,1.,1.5);
  }

  float bkg_bend_power = 1.;
  if ( ptbin==21 ) bkg_bend_power = 4.5;
  if ( ptbin==23 ) bkg_bend_power = 4.;
  if ( ptbin==26 ) bkg_bend_power = 3.5;
  if ( ptbin==30 ) bkg_bend_power = 2.6;
  if ( ptbin==35 ) bkg_bend_power = 2.2;
  if ( ptbin==40 ) bkg_bend_power = 2.;
  if ( ptbin==45 ) bkg_bend_power = 2.;
  if ( ptbin==50 ) bkg_bend_power = 1.8;
  if ( ptbin==60 ) bkg_bend_power = 1.5;
  if ( ptbin==85 ) bkg_bend_power = 1.;
  if ( ptbin==120 ) bkg_bend_power = 1.;


  if ( strcmp(EBEE,"EE")==0 ){  
    f3->SetParameter(8,bkg_bend_power);
    f3->SetParLimits(8,bkg_bend_power-1., bkg_bend_power+1.);
  }

  f3->FixParameter(0,f3->GetParameter(0));
  f3->FixParameter(1,f3->GetParameter(1));
  f3->FixParameter(2,f3->GetParameter(2));
  f3->FixParameter(3,f3->GetParameter(3));

  hbkg->SetMaximum(hbkg->GetMaximum()*3.);
  fit_status = hbkg->Fit(f3,"b","",-1., 20.);
  hbkg->Draw();
  if ( fit_status > 0 ) {
    printf("fit background template failed. QUIT \n");    
    return fitted;
  }else {
    f3->Draw("same");
  }

  TF1 *fmcbkg = (TF1*)f3->Clone();
  fmcbkg->SetLineColor(1);
  c101->cd(2);

  htmp1 = (TH1F*)fmcbkg->GetHistogram();
  htmp2 = new TH2F("htmp2","",210, -1., 20., 100, 0., htmp1->GetMaximum()*1.25);

  htmp2->SetNdivisions(505,"XY");
  htmp2->SetXTitle("Iso");
  htmp2->SetYTitle("A.U.");
  htmp2->SetLineColor(1);

  htmp2->GetXaxis()->SetRangeUser(-1., 20.);
  htmp2->SetMinimum(-1.);
  htmp2->SetMaximum(1.5);
  htmp2->Draw();
  fmcbkg->Draw("same");

  TLegend *tleg2 = new TLegend(0.25, 0.2, 0.6, 0.42);
  tleg2->SetHeader("");
  tleg2->SetFillColor(0);
  tleg2->SetShadowColor(0);
  tleg2->SetBorderSize(0);
  if ( strcmp(EBEE,"EB")==0 ){  
    tleg2->AddEntry(fmcbkg,"MC shape","l");
  }else {
    tleg2->AddEntry(fmcbkg,"Data SB shape","l");
  }
  tleg2->AddEntry(fbkgfit,"shape from data","l");
  tleg2->Draw();
  
  if(para_index>4){
    double tmppar = f3->GetParameter(para_index);
    f3->SetParameter(para_index, tmppar+para_sigma*f3->GetParError(para_index));
  }

//   f3->SetParameter(5,-0.5);
//   f3->SetParameter(6,-0.05);
//   f3->SetParameter(7,0.02);
//   f3->SetParameter(8,1.);

  Para.push_back(f3->GetParameter(4));
  Para.push_back(f3->GetParameter(5));
  Para.push_back(f3->GetParameter(6));
  Para.push_back(f3->GetParameter(7)); 
  Para.push_back(f3->GetParameter(8)); 

  Para_err.push_back(f3->GetParError(4));
  Para_err.push_back(f3->GetParError(5));
  Para_err.push_back(f3->GetParError(6));
  Para_err.push_back(f3->GetParError(7));
  Para_err.push_back(f3->GetParError(8));

  BkgPDFnorm = f3->Integral(-1., 20.);
  printf("status %d, bkg area %3.3f \n", fit_status,f3->Integral(-1., 20.)/hdata->GetBinWidth(2));

  //test PDFs
  TCanvas *c11 = new TCanvas("c11","c11",1000,500);
  c11->Divide(2,1);
  c11->cd(1);
  TF1 *f11 = new TF1("f11",exp_conv_norm, -1., 20., 11);
  f11->SetNpx(10000);
  f11->SetParameters(f3->GetParameters());
  f11->Draw();
  printf(" SIG PDF area %2.3f \n", f11->Integral(-1., 20.));

  c11->cd(2);
  TF1 *f12 = new TF1("f12",expinv_power_norm, -1., 20., 11);
  f12->SetNpx(10000);
  f12->SetParameters(f3->GetParameters());
  f12->Draw();
  printf(" BKG PDF area %2.3f \n", f12->Integral(-1., 20.));

  //c1->cd();

  printf(" --------- before the fit ------------- \n");
  printf("Nsig %2.3f, Nbg %2.3f, Ntemplate %3.3f \n", hsig->Integral(), hbkg->Integral(), ntemplate);
  printf("Purity %2.3f, init size %4.3f,  fit sample size %4d\n", hsig->Integral()/hsum->Integral(), hsum->Integral(), ndata);
  printf(" -------------------------------------- \n");



  printf( " -----  Got %d, %d, %d events for fit ----- \n ", dataColl.size(),
	  sigColl.size(), bkgColl.size() );  

  //--------------------------------------------------
  //init parameters for fit
  Double_t vstart[11] = {1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.};
  vstart[0] = sigfrac*ndata;
  vstart[1] = (1-sigfrac)*ndata;
  for (int ii=0; ii<9; ii++) {    
    vstart[ii+2] = Para[ii]; //8 shape parameters
  }
  TMinuit *gMinuit = new TMinuit(NPAR);  
  gMinuit->Command("SET STR 1");
  gMinuit->SetFCN(fcn);
  Double_t arglist[11];
  Int_t ierflg = 0;
  
  arglist[0] = 1;
  gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
  arglist[0] = 1;
  gMinuit->mnexcm("SET PRINT", arglist ,1,ierflg);

  Double_t step[] = { 1.,1.,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,};

  for ( int ii=0; ii<9; ii++){
    printf(" para %d, %.5f, err %.5f \n", ii, Para[ii], Para_err[ii]);
  }

  float sigma = 3.;
  gMinuit->mnparm(0,  "Signal yield"  , vstart[0],  step[0], 0., ndata*2.  , ierflg);
  gMinuit->mnparm(1,  "background yield"  , vstart[1],  step[1], 0., ndata*2. , ierflg);

//   gMinuit->mnparm(2,  "constant"     , Para[0],  0.00,  Para[0], Para[0] , ierflg);
//   gMinuit->mnparm(3,  "exp tail"     , Para[1],  0.01,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg);
//   gMinuit->mnparm(4,  "exg mean"     , Para[2],  0.01,  Para[2]-sigma*Para_err[2], Para[2]+sigma*Para_err[2], ierflg);
//   gMinuit->mnparm(5,  "exg width"    , Para[3],  0.01,  Para[3]-sigma*Para_err[3], Para[3]+sigma*Para_err[3], ierflg);
//   gMinuit->mnparm(6,  "constant"     , Para[4],  0.00,  Para[4]                  , Para[4]                  , ierflg);
//   gMinuit->mnparm(7,  "bg exp turnon", Para[5],  0.01,  Para[5]-sigma*Para_err[5], Para[5]+sigma*Para_err[5], ierflg);
//   gMinuit->mnparm(8,  "bg x offset  ", Para[6],  0.01,  Para[6]-sigma*Para_err[6], Para[6]+sigma*Para_err[6], ierflg);
//   gMinuit->mnparm(9,  "bg bend slope", Para[7],  0.01,  0.001                    , 0.1                      , ierflg);
// //   gMinuit->mnparm(10, "bg bend power", Para[8],  0.01,  Para[8]-sigma*Para_err[8], Para[8]+sigma*Para_err[8], ierflg);
//   gMinuit->mnparm(10, "bg bend power", Para[8],  0.01,  0.5                       , 5.                       , ierflg);

//   gMinuit->mnparm(2,  "constant"     , Para[0], TMath::Abs(Para[0]*0.0) ,  Para[0], Para[0], ierflg);
//   gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.01) ,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg); 
// //   gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.1) ,  0.8    , 1.3    , ierflg);
//   gMinuit->mnparm(4,  "exg mean"     , Para[2], TMath::Abs(Para[2]*0.1) ,  0.5    , 1.0    , ierflg);
//   gMinuit->mnparm(5,  "exg width"    , Para[3], TMath::Abs(Para[3]*0.1) ,  0.25   , 0.5    , ierflg);
//   gMinuit->mnparm(6,  "constant"     , Para[4], TMath::Abs(Para[4]*0.0) ,  Para[4], Para[4], ierflg);
//   gMinuit->mnparm(7,  "bg exp turnon", Para[5], TMath::Abs(Para[5]*0.1) ,  -0.7   , -0.3   , ierflg);
//   gMinuit->mnparm(8,  "bg x offset  ", Para[6], TMath::Abs(Para[6]*0.0) ,  -0.15  , -0.05  , ierflg);
//   gMinuit->mnparm(9,  "bg bend slope", Para[7], TMath::Abs(Para[7]*0.1) ,  0.01   , 0.05   , ierflg);
//   gMinuit->mnparm(10, "bg bend power", Para[8], TMath::Abs(Para[8]*0.1) ,  0.5    , 1.5    , ierflg);

  gMinuit->mnparm(2,  "constant"     , Para[0],  0.00,  Para[0], Para[0] , ierflg);
  gMinuit->mnparm(3,  "exp tail"     , Para[1],  0.00,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg);
  gMinuit->mnparm(4,  "exg mean"     , Para[2],  0.00,  Para[2]-sigma*Para_err[2], Para[2]+sigma*Para_err[2], ierflg);
  gMinuit->mnparm(5,  "exg width"    , Para[3],  0.00,  Para[3]-sigma*Para_err[3], Para[3]+sigma*Para_err[3], ierflg);
  gMinuit->mnparm(6,  "constant"     , Para[4],  0.00,  Para[4]                  , Para[4]                  , ierflg);
  gMinuit->mnparm(7,  "bg exp turnon", Para[5],  0.00,  Para[5]-sigma*Para_err[5], Para[5]+sigma*Para_err[5], ierflg);
  gMinuit->mnparm(8,  "bg x offset  ", Para[6],  0.00,  Para[6]-sigma*Para_err[6], Para[6]+sigma*Para_err[6], ierflg);
  gMinuit->mnparm(9,  "bg bend slope", Para[7],  0.00,  0.001                    , 0.1                      , ierflg);
  gMinuit->mnparm(10, "bg bend power", Para[8],  0.00,  Para[8]-sigma*Para_err[8], Para[8]+sigma*Para_err[8], ierflg);
  
  printf(" --------------------------------------------------------- \n");
  printf(" Now ready for minimization step \n --------------------------------------------------------- \n");
  
  arglist[0] = 500; // number of iteration
  gMinuit->mnexcm("MIGRAD", arglist,1,ierflg);
  //can do scan
//   arglist[0] = 0;
//   gMinuit->mnexcm("SCAN", arglist,1,ierflg);

  printf (" -------------------------------------------- \n");
  printf("Finished.  ierr = %d \n", ierflg);

  double para[NPAR+1],errpara[NPAR+1];

  double tmp_errpara[NPAR+1];

  for(int j=0; j<=NPAR-1;j++) { tmp_errpara[j]=0.1; }
  for(int j=2; j<=NPAR-1;j++) { 
    if(Para_err[j-2]!=0.) tmp_errpara[j]=TMath::Abs(Para_err[j-2]); 
  }
  
  int ni=6;       if ( strcmp(EBEE,"EE")==0 ) { ni=6; }//if(ptbin==21) ni=0;}
  
  if ( ierflg == 0 ) {
    for(int i=0; i<ni; i++) {
      float istep[10] = {0.,0.,0.,0.,0.,0.,0.};
      if (i<(ni-1)) {
	istep[i] = 0.001;
      }else {
	for (int j=0; j<ni-1; j++) {istep[j] = 0.001;}
      }

      for(int j=0; j<=NPAR-1;j++) {
	gMinuit->GetParameter(j, para[j], errpara[j]);
	if (errpara[j] != 0. ) {
	  tmp_errpara[j] = TMath::Abs(errpara[j]);
	}
      }

      if ( strcmp(EBEE,"EB")==0 ) {

	sigma = 10.;

 	if ( i==(ni-1) ) { sigma=5.;istep[1]=istep[4]=0.; }
	if ( ptbin==21 && i==1 ){ sigma=3.; }
 	if ( ptbin==21 && i==(ni-1) ){ sigma=20.; }
	if ( ptbin==23 && i==0 ){ para[7]=-0.5; }
	if ( ptbin==23 && i==1 ){ istep[1]=0.; istep[3]=0.01; }
 	if ( ptbin==23 && i==3 ){ istep[1]=0.01; istep[3]=0.0; }
	if ( ptbin==23 && i==(ni-1) ){ sigma=20.; }
 	if ( ptbin==26 && i==1 ){ sigma=5.; }	
	if ( ptbin==26 && i==(ni-1) ){ sigma=20.; }
	if ( ptbin==30 && i==(ni-1) ){ sigma=3.; }
 	if ( ptbin==35 && i==(ni-1) ) { sigma=10.; }
 	if ( ptbin==40 && i==(ni-1) ) { sigma=5.; istep[4]=0.01; }
 	if ( ptbin==45 && i==(ni-1) ) { sigma=10.; }
	if ( ptbin==60 && i==0 ) { para[3]=1.; para[4]=0.6; para[5]=0.32; para[7]=-0.45; para[9]=0.025; para[10] = 1.;}
 	if ( ptbin==60 && i==(ni-1) ) { sigma=5.; istep[4]=0.01;}
	if ( ptbin>=85 && i==(ni-1) ){ sigma=3.; }
	if ( ptbin==300 ) { istep[2]=istep[3]=istep[4]=0.; }// para[7] = -5.11907e-02; istep[1]=0.; }
	float tmp8=0.;
	
// 	if( i!= (ni-1) ) {
	  gMinuit->mnparm(0,  "Signal yield"  ,   para[0],  1., para[0]-100.*tmp_errpara[0], para[0]+100.*tmp_errpara[0], ierflg);
	  gMinuit->mnparm(1,  "background yield", para[1],  1., para[1]-100.*tmp_errpara[1], para[1]+100.*tmp_errpara[1], ierflg);
	  gMinuit->mnparm(2,  "constant"     , para[2],  0., para[2]-100.*tmp_errpara[2], para[2]+100.*tmp_errpara[2], ierflg);
	  gMinuit->mnparm(6,  "constant"     , para[6],  0., para[6]-100.*tmp_errpara[6], para[6]+100.*tmp_errpara[6], ierflg);
	  gMinuit->mnparm(3,  "exp tail"     , para[3],  istep[4],  para[3]-sigma*tmp_errpara[3], para[3]+sigma*tmp_errpara[3], ierflg);
	  gMinuit->mnparm(4,  "exg mean"     , para[4],  istep[3],  para[4]-sigma*tmp_errpara[4], para[4]+sigma*tmp_errpara[4], ierflg);
	  gMinuit->mnparm(5,  "exg width"    , para[5],  istep[2],  para[5]-sigma*tmp_errpara[5], para[5]+sigma*tmp_errpara[5], ierflg);
	  gMinuit->mnparm(7,  "bg exp turnon", para[7],  istep[1],  para[7]-sigma*tmp_errpara[7], para[7]+sigma*tmp_errpara[7], ierflg);
	  gMinuit->mnparm(8,  "bg x offset  ", para[8],  tmp8    ,  para[8]-sigma*tmp_errpara[8], para[8]+sigma*tmp_errpara[8], ierflg);
	  gMinuit->mnparm(9,  "bg bend slope", para[9],  istep[0],  para[9]-sigma*tmp_errpara[9], para[9]+sigma*tmp_errpara[9], ierflg);      
	  float sigma10=5.;
	  if ( para[10]-sigma10*tmp_errpara[10] < 1. )// && i!=(ni-1))
	    gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], 1.,  para[10]+sigma10*tmp_errpara[10], ierflg);      
	  else
	    gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], para[10]-sigma10*tmp_errpara[10],  para[10]+sigma10*tmp_errpara[10], ierflg);      
// 	}else {
// 	  gMinuit->mnparm(2,  "constant"     , Para[0], TMath::Abs(Para[0]*0.0) ,  Para[0], Para[0], ierflg);
// 	  //gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.01) ,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg); 
// 	  gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.0) ,  0.8    , 1.3    , ierflg);
// 	  gMinuit->mnparm(4,  "exg mean"     , Para[2], TMath::Abs(Para[2]*0.1) ,  0.5    , 1.0    , ierflg);
// 	  gMinuit->mnparm(5,  "exg width"    , Para[3], TMath::Abs(Para[3]*0.1) ,  0.25   , 0.5    , ierflg);
// 	  gMinuit->mnparm(6,  "constant"     , Para[4], TMath::Abs(Para[4]*0.0) ,  Para[4], Para[4], ierflg);
// 	  gMinuit->mnparm(7,  "bg exp turnon", Para[5], TMath::Abs(Para[5]*0.0) ,  -0.7   , -0.3   , ierflg);
// 	  gMinuit->mnparm(8,  "bg x offset  ", Para[6], TMath::Abs(Para[6]*0.0) ,  -0.15  , -0.05  , ierflg);
// 	  gMinuit->mnparm(9,  "bg bend slope", Para[7], TMath::Abs(Para[7]*0.1) ,  0.01   , 0.05   , ierflg);
// 	  gMinuit->mnparm(10, "bg bend power", Para[8], TMath::Abs(Para[8]*0.1) ,  0.5    , 1.5    , ierflg);
// 	}


	if( ptbin >=300 ) { 
	  gMinuit->mnparm(3,  "exp tail"  , 1.257281,  0.0,  para[1]-3.*tmp_errpara[1], para[1]+3.*tmp_errpara[1], ierflg);
	  gMinuit->mnparm(4,  "exg mean"  , 0.856906,  0.0,  para[2]-3.*tmp_errpara[2], para[2]+3.*tmp_errpara[2], ierflg);
	  gMinuit->mnparm(5,  "exg width" , 0.320847,  0.0,  para[3]-3.*tmp_errpara[3], para[3]+3.*tmp_errpara[3], ierflg);
	}      

    }else{	

	sigma=10.;
	if ( i==0 ) { para[10] = bkg_bend_power; tmp_errpara[10] = 0.3; }
 	if ( i==(ni-1) ) { sigma=3.;istep[1]=istep[4]=0.; } //test of not changing signal template
     	if ( i==(ni-1) ) { istep[4]=0.;}

   	if ( ptbin==21 && i==(ni-1) ) { sigma=20.;}
  	if ( ptbin==23 && i==0 ) { sigma=5.;}
  	if ( ptbin==23 && i==(ni-1) ) { sigma=10.;}
	if ( ptbin<30 && ptbin>21 && i==1 ){ istep[1]=0.; istep[3]=0.01; }
 	if ( ptbin<30 && ptbin>21 && i==3 ){ istep[1]=0.01; istep[3]=0.0; }
	if ( ptbin==26 && i==1 ) { para[7] = -0.8; }
	if ( ptbin==26 && i==(ni-1) ) { sigma=10.; }
  	if ( ptbin==30 && i==(ni-1) ) { sigma=10.; }
 	if ( ptbin==35) {para[7] = -0.75;}
 	if ( ptbin==40 && i==0) {para[7] = -0.65; para[10] = 2.;}
	if ( ptbin==45 && i==(ni-1) ) {sigma=5.;}
	if ( ptbin==85 && i==(ni-1) ) {sigma=10.; istep[4]=0.01;}
	if (ptbin >= 85 ) { para[10] = bkg_bend_power; tmp_errpara[10] = 1.; }

	if ( ptbin==120 ) { para[7] = -0.615255; istep[1]=0.;}

	
//     	if ( ptbin==120 && i==0 ) { 
// 	  para[3] = 1.446454; para[4]=-0.016373; para[5]=0.163238;
// 	  istep[2]=istep[3]=istep[4]=0.; sigma=5.; tmp_errpara[10]=0.2;
// 	}
//     	if ( ptbin==120 && i==(ni-1) ) { istep[2]=istep[3]=istep[4]=0.; sigma=5.;}

	gMinuit->mnparm(0,  "Signal yield"  ,   para[0],  1., para[0]-100.*tmp_errpara[0], para[0]+100.*tmp_errpara[0], ierflg);
	gMinuit->mnparm(1,  "background yield", para[1],  1., para[1]-100.*tmp_errpara[1], para[1]+100.*tmp_errpara[1], ierflg);
	gMinuit->mnparm(2,  "constant"     , para[2],  0.,  para[2], para[2] , ierflg);
	gMinuit->mnparm(6,  "constant"     , para[6],  0.,  para[6], para[6], ierflg);	
	gMinuit->mnparm(3,  "exp tail"     , para[3],  istep[4],  para[3]-sigma*tmp_errpara[3], para[3]+sigma*tmp_errpara[3], ierflg);
	gMinuit->mnparm(4,  "exg mean"     , para[4],  istep[3],  para[4]-sigma*tmp_errpara[4], para[4]+sigma*tmp_errpara[4], ierflg);
	gMinuit->mnparm(5,  "exg width"    , para[5],  istep[2],  para[5]-sigma*tmp_errpara[5], para[5]+sigma*tmp_errpara[5], ierflg);
	gMinuit->mnparm(7,  "bg exp turnon", para[7],  istep[1],  para[7]-sigma*tmp_errpara[7], para[7]+sigma*tmp_errpara[7], ierflg);
	gMinuit->mnparm(8,  "bg x offset  ", para[8],  0.00,      para[8]-sigma*tmp_errpara[8], para[8]+sigma*tmp_errpara[8], ierflg);
	gMinuit->mnparm(9,  "bg bend slope", para[9],  istep[0],  para[9]-sigma*tmp_errpara[9], para[9]+sigma*tmp_errpara[9], ierflg);	
  
	float minerr=1.;
	//if ( tmp_errpara[10] > 0.5) tmp_errpara[10] = 0.5;
	float sigma10=5.;
	if ( para[10]-sigma10*tmp_errpara[10] < 1. ) 
	  gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], minerr,  para[10]+sigma10*tmp_errpara[10], ierflg);
	else 
	  gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], para[10]-sigma10*tmp_errpara[10],  para[10]+sigma10*tmp_errpara[10], ierflg);

      }
      printf(" ************ \n");
      printf("  do %d th fit  \n", i);
      if(i==5 && dataFile.find("toy")    != std::string::npos)
	{
	  cout << "dataResult = " << dataResult << "\t dataErr = " << dataErr << endl;
	  // fixed turn on at +- 1 sigma
	  gMinuit->mnparm(7,  "bg exp turnon", dataResult-(float)shift*dataErr,  0.00,  para[7]-sigma*tmp_errpara[7], para[7]+sigma*tmp_errpara[7], ierflg);

	}
      else if(dataFile.find("toy")    == std::string::npos)
	{
	  dataResult = para[7];
	  dataErr    = tmp_errpara[7];
	}
      arglist[0] = 500; // number of iteration
      gMinuit->mnexcm("MIGRAD", arglist ,1,ierflg);      
      if ( ierflg != 0 ) {
  	printf("fit failed at %d iteration \n", i);
  	c1->cd();	c1->Draw();  	hdata->Draw("phe");
  	return fitted;
      }
    }
  }
 
  Double_t amin,edm,errdef; 
  if ( ierflg == 0 ) {
    for(int j=0; j<=NPAR-1;j++) {
      gMinuit->GetParameter(j, para[j],errpara[j]);
      info.push_back(para[j]);
      info_err.push_back(errpara[j]);
      printf("Parameter  %d = %f +- %f\n",j,para[j],errpara[j]);	
    }
    para[NPAR] = dataColl.size();
    printf(" fitted yield %2.3f \n", (para[0]+para[1])/ndata );
    
    info.push_back(sigColl.size());
    
    for(int j=0; j<=NPAR-1;j++) {
      tmp_errpara[j] = errpara[j];
      if( tmp_errpara[j] == 0. ) tmp_errpara[j] = par[j]*.1;      
    }
    //do minos if fit sucessed.

  }
  if (ierflg != 0 )  {
    printf(" *********** Fit failed! ************\n");
    gMinuit->GetParameter(0, para[0],errpara[0]);
    gMinuit->GetParameter(1, para[1],errpara[1]);
    para[0]=0.; errpara[0]=0.;

    c1->cd();
    c1->Draw();  
    //gPad->SetLogy();
    hdata->SetNdivisions(505,"XY");
    hdata->SetXTitle("comb. ISO (GeV)");
    hdata->SetYTitle("Entries");
    hdata->SetTitle("");
    hdata->SetMarkerStyle(8);
    hdata->SetMinimum(0.);
    if ( hdata->GetMaximum()<10.) hdata->SetMaximum(15.);
    else hdata->SetMaximum(hdata->GetMaximum()*1.25);
    if ( strcmp(EBEE,"EE")==0 &&ptbin == 15 ) hdata->SetMaximum(hdata->GetMaximum()*1.25);
   
    hdata->Draw("phe");  

    return fitted;    
  }

  
  // Print results
//   Double_t amin,edm,errdef;
  Int_t nvpar,nparx,icstat;
  gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
  gMinuit->mnprin(1,amin);  
  gMinuit->mnmatu(1);
  printf(" ========= happy ending !? =========================== \n");
  
  printf("FCN =  %3.3f \n", amin);

  //use new PDF form
  double tmppar[12];
  for(int ii=0; ii<9; ii++){
    tmppar[ii] = para[ii+2];
    fmcsigfit->SetParameter(ii,tmppar[ii]);
    fbkgfit->SetParameter(ii,tmppar[ii]);
  }

  c101->cd(1);
  
  //fmcsigfit->SetParameters(tmppar);
  //fmcsigfit->SetParameter(2,0.1);
  //fmcsigfit->SetLineStyle(2);

  fmcsigfit->Draw("same");
  c101->cd(2);

  fbkgfit->SetParameter(4,fbkgfit->GetParameter(4)*fmcbkg->Integral(-1., 20.)/fbkgfit->Integral(-1., 20.));
  fbkgfit->Draw("same");

  char fname[100];
  sprintf(fname,"plots/template_Ifit%s_%d.pdf",EBEE,ptbin);
  c101->SaveAs(fname);


  f11->SetParameters(tmppar);
  SigPDFnorm = f11->Integral(-1., 20.);
  f12->SetParameters(tmppar);
  BkgPDFnorm = f12->Integral(-1., 20.);


  // plot
  c1->cd();
  c1->Draw();  
  //gPad->SetLogy();
   hdata->SetNdivisions(505,"XY");
   hdata->SetXTitle("comb. ISO (GeV)");
   hdata->SetYTitle("Entries");
   hdata->SetTitle("");
   hdata->SetMarkerStyle(8);
   hdata->SetMinimum(0.);
   if ( hdata->GetMaximum()<10.) hdata->SetMaximum(15.);
   else hdata->SetMaximum(hdata->GetMaximum()*1.5);
   if ( strcmp(EBEE,"EE")==0 &&ptbin == 15 ) hdata->SetMaximum(hdata->GetMaximum()*1.2);

   hdata->Draw("p e ");

  f11->SetParameter(0, para[0]*f11->GetParameter(0)/f11->Integral(-1., 20.)*hdata->GetBinWidth(2));
//   f11->SetFillColor(5);
  f11->SetLineColor(4);
  //f11->SetFillColor(603);
  f11->SetLineWidth(2);
//   f11->SetFillStyle(3001);
  f11->Draw("same");

  f12->SetParameter(4, para[1]*f12->GetParameter(4)/f12->Integral(-1., 20.)*hdata->GetBinWidth(2));
//   f12->SetFillColor(8);
  f12->SetLineColor(2);
  //f12->SetFillColor(603);
  f12->SetLineWidth(2);
//   f12->SetFillStyle(3013);
  f12->Draw("same");

  TF1 *f13 = new TF1("f13",sum_norm, -1., 20 ,11);
  f13->SetNpx(10000);
  f13->SetParameters(f12->GetParameters());
  f13->SetParameter(0, para[0]*f11->GetParameter(0)/f11->Integral(-1., 20.)*hdata->GetBinWidth(2));
  f13->SetParameter(4, para[1]*f12->GetParameter(4)/f12->Integral(-1., 20.)*hdata->GetBinWidth(2));  
  f13->SetLineWidth(2);
  f13->SetLineColor(1);
  f13->Draw("same");
  f11->Draw("same");
  hdata->Draw("pe same");

//   cout << "The number of bins are: " << endl;
//   cout << "hdata nbins = " << hdata->GetNbinsX() << endl;
//   cout << "hsig nbins = " << hsig->GetNbinsX() << endl;
//   cout << "hbkg nbins = " << hbkg->GetNbinsX() << endl;

  // get chi2/NDF
  double chi2ForThisBin=0;
  int nbinForThisBin=0;
  chi2Nbins(f13, hdata, chi2ForThisBin, nbinForThisBin);
  for(int epar=0; epar < 11; epar++)
    {
//       cout << "f11 parameter " << epar << " = " << 
// 	f11->GetParameter(epar) << endl;
      FitPar[epar] = f11->GetParameter(epar);
    }

  for(int epar=0; epar < 11; epar++)
    {
//       cout << "f12 parameter " << epar << " = " << 
// 	f12->GetParameter(epar) << endl;
      FitPar[epar+11] = f12->GetParameter(epar);
    }

  for(int epar=0; epar < 11; epar++)
    {
//       cout << "f13 parameter " << epar << " = " << 
// 	f13->GetParameter(epar) << endl;
      FitPar[epar+22] = f13->GetParameter(epar);

    }

//   cout << "hdata integral = " << hdata->Integral() << endl;
//   cout << endl;

//   printf("fit area %3.2f; sig area %3.2f; bg area %3.2f\n", f13->Integral(-1., 20.)/hdata->GetBinWidth(2),  f11->Integral(-1., 20.)/hdata->GetBinWidth(2),f12->Integral(-1., 20.)/hdata->GetBinWidth(2));

//   for(int i=0; i<12; i++){
//     printf(" fit para %d = %4.3f \n", i, f13->GetParameter(i));
//   }

   TLegend *tleg = new TLegend(0.5, 0.7, 0.93, 0.92);
   char text[50];
   sprintf(text,"%s Pt %d ~ %.0f GeV",EBEE, ptbin, ptmax);
   tleg->SetHeader(text);
   tleg->SetFillColor(0);
   tleg->SetShadowColor(0);
   tleg->SetBorderSize(0);
   sprintf(text,"#chi^{2}/NDF = %.1f/%d",chi2ForThisBin,nbinForThisBin);
   tleg->AddEntry(hdata,text,"");
   sprintf(text,"Data %.1f events",hdata->Integral());
   tleg->AddEntry(hdata,text,"pl");
   sprintf(text,"Fitted %.1f events",para[0]+para[1]);//f13->Integral(-1., 20.)/hdata->GetBinWidth(2));
   tleg->AddEntry(f13,text,"l");
   sprintf(text,"SIG %.1f #pm %.1f events",para[0], errpara[0]);
   tleg->AddEntry(f11,text,"f");
   sprintf(text,"BKG %.1f #pm %.1f events",para[1], errpara[1]);
   tleg->AddEntry(f12,text,"f");
   tleg->Draw();


   gPad->RedrawAxis();

   printf("%s, ptbin %d, Data %.1f events \n",EBEE, ptbin, hdata->Integral());
   printf("Fitted %.1f (in 5GeV) %.1f events \n",para[0]+para[1],f13->Integral(-1.,5.));
   printf("SIG %.1f #pm %.1f events \n",para[0], errpara[0]);
   printf("SIG (in 5GeV) %.1f #pm %.1f events \n",f11->Integral(-1.,5.)/hdata->GetBinWidth(2), f11->Integral(-1.,5.)*errpara[0]/para[0]/hdata->GetBinWidth(2));
   printf("BKG %.1f #pm %.1f events \n",para[1], errpara[1]);
   printf("BKG (in 5GeV) %.1f #pm %.1f events \n",f12->Integral(-1.,5.)/hdata->GetBinWidth(2), f12->Integral(-1.,5.)*errpara[1]/para[1]/hdata->GetBinWidth(2));
   
   float purity = f11->Integral(-1.,5.)/hdata->GetBinWidth(2)/(f11->Integral(-1.,5.)/hdata->GetBinWidth(2)+f12->Integral(-1.,5.)/hdata->GetBinWidth(2));
   float purity_err = purity*errpara[0]/para[0];
   printf("Purity (in 5GeV) %.3f #pm %.3f  \n", purity, purity_err);


//   hsig->Scale(para[0]/hsig->Integral());
//   hbkg->Scale(para[1]/hbkg->Integral());
//   hbkg->Add(hsig);

//   hsig->SetLineColor(1);
//   hsig->SetFillColor(5);
//   hsig->SetFillStyle(3001);

//   hbkg->SetLineWidth(2);


//   hsig->Draw("same");
//   hbkg->Draw("same");


  sprintf(fname,"plots/unbinned_free_Ifit%s_%d.pdf",EBEE,ptbin);
  if (para_index>0) sprintf(fname,"plots/unbinned_Ifit%s_%d_para%d_sigma%1.0f.pdf",EBEE,ptbin,para_index,para_sigma);
  if(Opt_SavePDF == 1) {
    c1->SaveAs(fname);


  } else {

   c1->Close();
   c10->Close();
   c101->Close();
   c11->Close();

  }

  printf("----- fit results with signal projection   ----------- \n");

  fitted[0] = para[0];
  fitted[1] = errpara[0];
  fitted[2] = para[1];
  fitted[3] = errpara[1];
  fitted[4] = f11->Integral(-1.,5.)/hdata->GetBinWidth(2);
  fitted[5] = f11->Integral(-1.,5.)*errpara[0]/para[0]/hdata->GetBinWidth(2);

  return fitted;
}
Example #30
0
void scan2() {

    /*  TFile f1("hist.root");
      TFile f2("SysTot.root");

      TH1D *datahist = (TH1D*)f1.Get("datahist");
      TH1D *fithist = (TH1D*)f1.Get("fithist");

      TH1D *totlow = (TH1D*)f2.Get("totlow");
      TH1D *tothigh = (TH1D*)f2.Get("tothigh");
    */

    TF1 *fun1 = new TF1("fun",fun,0,1000,3);

    TFile f("Output.root");
    TH1F *datahist = dynamic_cast<TH1F*> (f.Get("InvMass"));
    TH1F *fithist = dynamic_cast<TH1F*> (f.Get("hist_err"));
    TH1F *tothigh = dynamic_cast<TH1F*> (f.Get("SystPlus"));
    TH1F *totlow = dynamic_cast<TH1F*> (f.Get("SystMinus"));
    new TCanvas();
    datahist->DrawCopy();
    fithist->DrawCopy("same");
    gPad->SetEditable(0);

    /*	if (datahist->IsZombie()) { std::cout << "Err! datahist not found " << std::endl; return; }
    	if (fithist->IsZombie()) { std::cout << "Err! err_hist not found " << std::endl; return; }
    	if (tothigh->IsZombie()) { std::cout << "Err! syst_plus hist not found " << std::endl; return; }
    	if (totlow->IsZombie()) { std::cout << "Err! syst_minus hist not found " << std::endl; return; }
    */

    TH1D *p = new TH1D("p","Probability",100,150,900);

    for (int i = 1; i<=fithist->GetNbinsX(); i++)
    {
        double mass = fithist->GetBinCenter(i);

        if (mass>440 && mass<450)
        {
            double sigma = sqrt(2.0)*sqrt(pow(0.135*sqrt(mass/2.0),2)+
                                          pow(0.02*(mass/2.0),2));
            cout<< " ===================== mass +/- sigma = " << mass<<"+/-"<<sigma<<endl;
            int bin1 = fithist->FindBin(mass-sigma/2);
            int bin2 = fithist->FindBin(mass+sigma/2);
            cout<<mass<<" "<<bin1<<" "<<bin2<<endl;
            double data = 0;
            double bg = 0;
            double err = 0;

            for (int j = bin1; j<=bin2; j++)
            {
                data+=datahist->GetBinContent(j);
                bg+=fithist->GetBinContent(j);
                double err1 = -totlow->GetBinContent(j);
                double err2 = tothigh->GetBinContent(j);
                err+=TMath::Max(err1,err2)*bg; //why multiply by bg???
            }
            cout << "Total Data/Bg+/-err in mass window[" << mass << "] = "<< data <<"/ "<< bg << "+/-" << err <<endl;
            double prob = 0;
            fun1->SetParameter(0,bg);
            fun1->SetParameter(1,err);

            for (int j = int(data+0.001); j<100; j++) {
                fun1->SetParameter(2,j);
                //fun1->Print();
                //cout << "Evaluating Intrgral for j = " << j << " from x0= " << TMath::Max(0.0,bg-10*err) << " to x1 = " << bg+10*err << endl;
                double val = fun1->Integral(TMath::Max(0.0,bg-10*err),bg+10*err);
                //double val = fun1->Integral(TMath::Max(0.0,bg-2*err),bg+2*err);
                /*for (int z=TMath::Max(0.0,bg-2*err); z < bg+2*err; ++z)
                {
                	if (c<4)
                	{
                	std::cout << "func at [" << z << "]=" << 	fun1->Eval(z) << std::endl;
                	}
                }
                */
                prob += val;
            }
            cout<< "Prob for mass[" << mass<<"]="<< prob <<endl;
            p->SetBinContent(p->FindBin(mass),prob);
        }
    }
    /*
    delete gRandom;
    gRandom = (TRandom*) new TRandom3;
    gRandom->SetSeed(3);

    TH1D *minp = new TH1D("minp","Minimum Probability of Each PseudoExpt",100,0,0.2);

    //int nexp = 50000;
    int nexp = 10;

    TH1D *htemp = (TH1D*)datahist->Clone("htemp");

    for (int iexp = 0; iexp<nexp; iexp++){
      //if (iexp%10==0) cout<<iexp<<endl;
      //generate pseudo-experiments
      htemp->Reset();
      for (int i = 1; i<=htemp->GetNbinsX(); i++){
        double mass = htemp->GetBinCenter(i);
        if (mass>150&&mass<650){
    double bg = fithist->GetBinContent(i);
    double err1 = -totlow->GetBinContent(i);
    double err2 = tothigh->GetBinContent(i);
    double err = TMath::Max(err1,err2)*bg;
    double mean = gRandom->Gaus(bg,err);
    if (mean<0) mean = 0;
    htemp->SetBinContent(i,gRandom->Poisson(mean));
        }
      }
      double minprob = 2.;
      for (int i = 1; i<=fithist->GetNbinsX(); i++){
        double mass = fithist->GetBinCenter(i);
        if (mass>150&&mass<650){
    double sigma = sqrt(2.0)*sqrt(pow(0.135*sqrt(mass/2.0),2)+
    			      pow(0.02*(mass/2.0),2));
    //cout<<mass<<" "<<sigma<<endl;
    int bin1 = fithist->FindBin(mass-sigma/2);
    int bin2 = fithist->FindBin(mass+sigma/2);
    //cout<<mass<<" "<<bin1<<" "<<bin2<<endl;
    double data = 0;
    double bg = 0;
    double err = 0;
    for (int j = bin1; j<=bin2; j++){
      data+=htemp->GetBinContent(j);
      bg+=fithist->GetBinContent(j);
      double err1 = -totlow->GetBinContent(j);
      double err2 = tothigh->GetBinContent(j);
      err+=TMath::Max(err1,err2)*bg;
    }
    //cout<<mass<<" "<<data<<" "<<bg<<" "<<err<<endl;
    double prob = 0;
    fun1->SetParameter(0,bg);
    fun1->SetParameter(1,err);
    for (int j = int(data+0.001); j<100; j++){
      fun1->SetParameter(2,j);
      prob += fun1->Integral(TMath::Max(0.0,bg-10*err),bg+10*err);
    }
    if (prob<minprob) minprob=prob;
        }
      }
      minp->Fill(minprob);
    }
    */
    TCanvas *c1 = new TCanvas("c1","c1");
    TH2D *fr = new TH2D("fr","",100,150,900,100,1e-5,2);
    fr->SetStats(0);
    fr->SetXTitle("M(#gamma,lead jet)(GeV)");
    fr->SetYTitle("Prob of fluctuation #geq N_{obs}");
    fr->GetXaxis()->CenterTitle();
    fr->GetYaxis()->CenterTitle();
    fr->DrawCopy();
    p->SetLineWidth(2);
    p->DrawCopy("same");
    double minp=0;
    double mgg=0;
    double minc = 10;
    for (int i = 1; i<=p->GetNbinsX(); i++) {
        double bin = p->GetBinCenter(i);
        double binc = p->GetBinContent(i);
        if (binc<minc) {
            minp = binc;
            mgg = bin;
            minc = binc;
        }
    }
    cout<<mgg<<" "<<minp<<endl;
    gPad->SetLogy();
    double p1s = 0.00458319;
    double m1s = 0.0435982;
    double s3s = 0.000100319;
    TLine *l1 = new TLine(150,p1s,900,p1s);
    TLine *l2 = new TLine(150,m1s,900,m1s);
    TLine *l3 = new TLine(150,s3s,900,s3s);
    l1->SetLineColor(4);
    l2->SetLineColor(4);
    l3->SetLineColor(2);
    l1->SetLineWidth(2);
    l2->SetLineWidth(2);
    l3->SetLineWidth(2);
    l1->Draw();
    l2->Draw();
    l3->Draw();
    TLatex *t1 = new TLatex(250,m1s/4,"Expected Range for Min. Obs. Prob.");
    t1->SetTextColor(4);
    t1->SetTextSize(0.05);
    t1->Draw();
    TLatex *t2 = new TLatex(350,s3s*1.5,"3 #sigma evidence level");
    t2->SetTextColor(2);
    t2->SetTextSize(0.05);
    t2->Draw();

    TLatex *t3 = new TLatex(0.3,0.93,"CDF Run II Preliminary, 2.0 fb^{-1}");
    t3->SetNDC(true);
    t3->SetTextSize(0.06);
    t3->Draw();

//
//  TCanvas *c2 = new TCanvas("c2","c2");
//  minp->DrawCopy();
    //cout<<minp->GetMean()<<endl;
}