Beispiel #1
0
void testLD(double scale=1.0){

  RooRealVar* zzmass = new RooRealVar("zzmass","m_{ZZ}",110,180);
  RooRealVar* z1mass = new RooRealVar("z1mass","m_{Z1}",0,180);
  RooRealVar* z2mass = new RooRealVar("z2mass","m_{Z2}",0,120);
  RooRealVar* costheta1 = new RooRealVar("costheta1","cos#theta_{1}",-1,1);  
  RooRealVar* costheta2 = new RooRealVar("costheta2","cos#theta_{2}",-1,1);
  RooRealVar* phi= new RooRealVar("phi","#Phi",-3.1415,3.1415);

  RooArgSet *argSet = new RooArgSet(*z1mass,*z2mass,*costheta1,*costheta2,*phi);

  vector<RooRealVar*> meas;
  meas.push_back(z1mass);
  meas.push_back(z2mass);
  meas.push_back(costheta1);
  meas.push_back(costheta2);
  meas.push_back(phi);

  cout << "Initializing PDFs" << endl;

  AngularPdfFactory SMHiggs(z1mass,z2mass,costheta1,costheta2,phi,zzmass);
  SMHiggs.makeSMHiggs();
  SMHiggs.makeParamsConst(true);

  AngularPdfFactory PSHiggs(z1mass,z2mass,costheta1,costheta2,phi,zzmass);
  PSHiggs.makePSHiggs();
  PSHiggs.makeParamsConst(true);

  LikelihoodToolbox<RooXZsZs_5D,RooXZsZs_5D> LD(SMHiggs.PDF,PSHiggs.PDF,NULL,meas);

  TFile* file1 = new TFile("../datafiles/SMHiggs_125_JHU.root");
  TTree* tree1 = (TTree*) file1->Get("angles");
  RooDataSet *data1 = new RooDataSet("data1","data1",tree1,RooArgSet(*zzmass,*z1mass,*z2mass,*costheta1,*costheta2,*phi));

  LD.LD_lineColor=4;
  LD.LD_bins=100;
  TH1F *SMLD =new TH1F("SMLD","SMLD",100,0,1);
  LD.makeLDdistribution(*SMLD,data1);

  TFile* file2 = new TFile("../datafiles/PSHiggs_125_JHU.root");
  TTree* tree2 = (TTree*) file2->Get("angles");
  RooDataSet *data2 = new RooDataSet("data2","data2",tree2,RooArgSet(*zzmass,*z1mass,*z2mass,*costheta1,*costheta2,*phi));

  LD.LD_lineColor=2;
  TH1F *PSLD = new TH1F("PSLD","PSLD",100,0,1);
  LD.makeLDdistribution(*PSLD,data2);

  if(SMLD->GetMaximum()>PSLD->GetMaximum()){
    SMLD->Draw();
    PSLD->Draw("SAME");
  }else{
    PSLD->Draw();
    SMLD->Draw("SAME");
  }
  
}
void drawHistos(TCanvas * C, TString filename, TString category, TTree* Tmine, TTree* Tother,TString var, int nbins, float xmin, float xmax, TString selection, TString myGroup, TString myRootFile, TString group, TString groupRootFile,TString mySel="1",TString groupSel="1"){
  TH1F* Hmine = new TH1F(TString("Hmine")+var,"",nbins,xmin,xmax); 
  Hmine->GetYaxis()->SetTitle(category);
  Hmine->GetXaxis()->SetTitle(var);
  Hmine->SetLineColor(1);
  Hmine->SetStats(0);
  TH1F* Hother = new TH1F(TString("Hother")+var,"",nbins,xmin,xmax); 
  Hother->GetYaxis()->SetTitle(category);
  Hother->GetXaxis()->SetTitle(var);
  Hother->SetLineColor(2);
  Hother->SetStats(0);

  TText TXmine;
  TXmine.SetTextColor(1);
  TXmine.SetTextSize(.04);
  TText TXother;
  TXother.SetTextColor(2);
  TXother.SetTextSize(.04);

  Tmine->Draw(var+">>"+Hmine->GetName(),selection+"*("+mySel+")");
  Tother->Draw(var+">>"+Hother->GetName(),selection+"*("+groupSel+")");

  ////Draw one histogram on top of the other
  C->Clear();
  //Hmine->Scale(1./Hmine->Integral());
  //Hother->Scale(1./Hother->Integral()); 
  //Hother->Scale(968134./688134.); //GGH e-tau
  if(Hmine->GetMaximum()>Hother->GetMaximum())
    Hmine->GetYaxis()->SetRangeUser(0,Hmine->GetMaximum()*1.1);
  else Hmine->GetYaxis()->SetRangeUser(0,Hother->GetMaximum()*1.1);
  Hmine->Draw("hist");
  Hother->Draw("histsame");

//   ///Draw the difference of the historgrams
//   TH1F*HDiff=(TH1F*)Hmine->Clone("HDiff");
//   HDiff->Add(Hother,-1);
//   int max= abs(HDiff->GetMaximum())>abs( HDiff->GetMinimum()) ?   abs(HDiff->GetMaximum()): abs( HDiff->GetMinimum());
//   HDiff->GetYaxis()->SetRangeUser(-2*(max>0?max:1),2*(max>0?max:1));
//   HDiff->Draw("hist");
//   TLine line;
//   line.DrawLine(HDiff->GetXaxis()->GetXmin(),0,HDiff->GetXaxis()->GetXmax(),0);

  //Print the integrals of the histograms a the top
  //TXmine.DrawTextNDC(.2,.965,myGroup+"_"+myRootFile+": "+(long)(Hmine->Integral(0,Hmine->GetNbinsX()+1)));
  //TXother.DrawTextNDC(.2,.93,group+"_"+groupRootFile+": "+(long)(Hother->Integral(0,Hother->GetNbinsX()+1)));
  TXmine.DrawTextNDC(.2,.965,myGroup+" : "+(long)(Hmine->Integral(0,Hmine->GetNbinsX()+1)));
  TXother.DrawTextNDC(.2,.93,group+": "+(long)(Hother->Integral(0,Hother->GetNbinsX()+1)));
  C->Print(filename);

  delete Hmine;
  delete Hother;
}
// 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;
}
Beispiel #4
0
void CompareGammaPoisson(float N=100)
{ 

    gStyle->SetOptStat(111111110);
    gStyle->SetStatW(0.3);                
    gStyle->SetStatH(0.25);                

    TRandom1 *frand = new TRandom1();
    TRandom3 rand(1234); // gamma

    int Nbins = (int)(N+TMath::Sqrt(N)*10);

    TH1F *hpoisson    = new TH1F("hpoisson",    "Poisson",   Nbins, -0.5,  Nbins-0.5);
    TH1F *hgamma      = new TH1F("hgamma",      "Gamma",     Nbins, -0.5,  Nbins-0.5);
    hpoisson->Sumw2();
    hgamma->Sumw2();

    for(int i=0; i<Npseudo; i++)  
    { 
        int checkpoint = (int)Npseudo/10;
        //if((i%checkpoint)==0) cout << "Generated " << i << "/" << Npseudo << " experiments " << endl;
        
        float Npoisson      = frand->Poisson(N);
        float Ngamma        = gsl_ran_gamma(2*N+1,0.5,rand);;

        hpoisson->Fill(Npoisson);
        hgamma->Fill(Ngamma);

    }
    hpoisson->Scale(1./hpoisson->Integral());
    hgamma->Scale(1./hgamma->Integral());

    h1cosmetic(hpoisson, Form("Poisson(black) and Gamma(red), N=%i",(int)N), kBlack, 3, 0, "");
    h1cosmetic(hgamma,   "Gamma", kRed, 3, 0, "");

    TCanvas *c = new TCanvas("c","c",400,400);
    c->cd(1);
    hpoisson->SetMaximum(hpoisson->GetMaximum()>hgamma->GetMaximum()?hpoisson->GetMaximum()*1.2:hgamma->GetMaximum()*1.2);
    hpoisson->Draw("HIST");
    hgamma->Draw("HIST SAME");
    c->Print(Form("fig/ComparePoissonGamma_N%i.pdf", (int)N));
}
Beispiel #5
0
void plotTrk() {
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(1);
  char c[50];
  c1->Clear();  
  c1->Divide(2,3); 
  for(int hid=0; hid<6; hid++){
    TVirtualPad* pad = c1->cd(hid+1); 
    pad->SetLogy(lTrkHist[hid]);
    double xmin, xmax, ymin=0.0, ymax=0.0;
    if(lTrkHist[hid]==1) ymin=0.1;
    for(int quad=0; quad<kFgtNumQuads; quad++){
      sprintf(c,"Quad%1s-%s",cquad[quad],cTrkHist[hid]);
      //printf("Getting %s\n",c);
      TH1F *h = histTrk[quad][hid] = (TH1F*)file->Get(c);
      xmin=h->GetXaxis()->GetXmin();
      xmax=h->GetXaxis()->GetXmax();
      double m=h->GetMaximum();
      if(ymax<m) ymax=m;
      //printf("quad=%d max=%6.1f ymax=%6.1f xmin=%6.1f xmax=%6.1f\n",quad,m,ymax,xmin,xmax);
    }
    ymax*=1.2; if(lTrkHist[hid]==1){ymax*=20.0;}
    sprintf(c,"%s",cTrkHist[hid]);
    TH2F *frame = new TH2F(c,c,1,xmin,xmax,1,ymin,ymax); frame->SetStats(0); frame->Draw();
    for(int quad=0; quad<kFgtNumQuads; quad++){
      TH1F *h=histTrk[quad][hid];
      h->SetLineColor(colorQuad[quad]); h->SetLineWidth(3); 
      if(hid<5){
	h->Draw("SAME");  
	float mean=h->GetMean();
	if(hid==1 || hid==4) {sprintf(c,"%s mean=%6.4f",cquad[quad],mean);}
	else                 {sprintf(c,"%s mean=%6.2f",cquad[quad],mean);}
      }else{
	h->SetMarkerColor(colorQuad[quad]); h->SetMarkerStyle(20); h->SetMarkerSize(1);
	h->Draw("SAME PL");
	sprintf(c,"Quad%s",cquad[quad]);
      }
      TText *t1;
      float x1= 0.2, x2= 0.55;
      float y1=0.8 - 0.07*quad;
      float y2=0.8 - 0.07*(quad-2);
      if(quad<2) { t1 = new TText(x1,y1,c); }
      else       { t1 = new TText(x2,y2,c); }
      t1->SetNDC();
      t1->SetTextSize(0.06); 
      t1->SetTextColor(colorQuad[quad]); 
      t1->Draw();
    }
  }
  c1->Update();
  save("trk");
}
Beispiel #6
0
void fithist() {
    //fit function ftotal to signal + background

    histgen();

    TFile *f = new TFile("background.root");
    background = (TH1F*)f->Get("background"); //pointer used in ftotal
    TH1F *result = (TH1F*)f->Get("result");

    TF1 *ftot = new TF1("ftot",ftotal,0,10,4);
    Double_t norm = result->GetMaximum();
    ftot->SetParameters(0.5*norm,5,.2,norm);
    ftot->SetParLimits(0,.3*norm,norm);

    result->Fit("ftot","b");
}
Beispiel #7
0
void plotMttResolution() {

  setTDRStyle();

  TCanvas *c = new TCanvas("c", "c", 800, 800);

  TH1F *mtt = (TH1F*) _file0->Get("mtt_resolution_mva");
  mtt->SetTitle("");
  mtt->SetName("m_{t#bar{t}}");
  mtt->GetXaxis()->SetTitle("m_{t#bar{t}} - m_{t#bar{t}}^{gen} (GeV)");
  mtt->SetLineColor(TColor::GetColor("#542437"));
  mtt->SetLineColor(TColor::GetColor("#8A9B0F"));
  mtt->SetLineColor(TColor::GetColor("#C02942"));
  mtt->SetFillColor(mtt->GetLineColor());
  mtt->SetFillStyle(3004);
  mtt->GetXaxis()->SetTitleOffset(1.2);

  TF1 *voigt = new TF1("voigt", "gaus", -100, 100);
	voigt->SetParName(0, "amp");
	voigt->SetParName(2, "mean");
	voigt->SetParName(1, "sigma");

  voigt->SetParameter(0, mtt->GetMaximum());
	voigt->SetParameter(2, 0);
	voigt->SetParameter(1, 100);

  mtt->Fit(voigt, "RVN");

  voigt->SetLineColor(TColor::GetColor("#8A9B0F"));
  voigt->SetLineWidth(2);

  mtt->Draw();
  voigt->Draw("same");

  TLatex* latex = new TLatex();
  latex->SetTextFont(42);
  latex->SetTextSize(0.033);
  latex->DrawLatexNDC(0.25, 0.84, TString::Format("mean = %.2f", voigt->GetParameter(1)));
  latex->DrawLatexNDC(0.25, 0.8, TString::Format("#sigma = %.2f", voigt->GetParameter(2)));

  gPad->Modified();
  gPad->Update();

  c->Print("mtt_resolution.pdf");
}
Beispiel #8
0
void test_TF1_FitErr2(){

  gStyle->SetOptFit(1111);
  gStyle->SetOptStat(0);

   histgen();
   TFile *f = new TFile("background.root");
   background = (TH1F*)f->Get("background"); //pointer used in ftotal
   TH1F *result = (TH1F*)f->Get("result");
   TF1 *ftot = new TF1("ftot",ftotal,0,10,5);
   Double_t norm = result->GetMaximum();
//   ftot->SetParameters(0.5*norm,5,.2,norm);
   ftot->SetParameters(0.5*norm,6,.5,5,-0.5);
   ftot->SetParLimits(0,.3*norm,norm);
//	 ftot->FixParameter(1,6);
//	 ftot->FixParameter(2,0.5);
	 ftot->SetParLimits(1,5.5,6.5);
	 ftot->SetParLimits(2,0.25,1);
//	 ftot->SetParLimits(4,-0.01,-50);
   result->Fit("ftot","b");
   result->Fit("ftot","b");
   result->Fit("ftot","b");
   result->Fit("ftot");
   result->Fit("ftot");
   result->Fit("ftot");

	 TFitResult fitResult=result->Fit("ftot");

	 double 


	 TF1 *bgf = TF1("bgf","pol1",0,10);
	 



}
Beispiel #9
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");
    
}
Beispiel #10
0
void th2polyEurope(Int_t npoints=500000)
{
   Int_t i,j;
   Double_t lon1 = -25;
   Double_t lon2 =  35;
   Double_t lat1 =  34;
   Double_t lat2 =  72;
   Double_t R = (lat2-lat1)/(lon2-lon1);
   Int_t W    = 800;
   Int_t H    = (Int_t)(R*800);
   gStyle->SetStatX(0.28);
   gStyle->SetStatY(0.45);
   gStyle->SetStatW(0.15);

   // Canvas used to draw TH2Poly (the map)
   TCanvas *ce = new TCanvas("ce", "ce",0,0,W,H);
   ce->ToggleEventStatus();
   ce->SetGridx();
   ce->SetGridy();

   // Real surfaces taken from Wikipedia.
   const Int_t nx = 36;
   // see http://en.wikipedia.org/wiki/Area_and_population_of_European_countries
   const char *countries[nx] = {
      "france",     "spain",  "sweden",  "germany",       "finland",
      "norway",     "poland", "italy",   "yugoslavia",    "united_kingdom",
      "romania",    "belarus","greece",  "czechoslovakia","bulgaria",
      "iceland",    "hungary","portugal","austria",       "ireland",
      "lithuania",  "latvia", "estonia", "denmark",       "netherlands",
      "switzerland","moldova","belgium", "albania",       "cyprus",
      "luxembourg", "andorra","malta",   "liechtenstein", "san_marino", "monaco" };
   Float_t surfaces[nx] = {
      547030,        505580,   449964,      357021,        338145,
      324220,        312685,   301230,      255438,        244820,
      237500,        207600,   131940,      127711,        110910,
      103000,         93030,    89242,       83870,         70280,
      65200,         64589,    45226,       43094,         41526,
      41290,         33843,    30528,       28748,          9250,
      2586,           468,      316,         160,            61, 2};

   TH1F *h = new TH1F("h","Countries surfaces (in km^{2})",3,0,3);
   for (i=0; i<nx; i++) h->Fill(countries[i], surfaces[i]);
   h->LabelsDeflate();

   TFile::SetCacheFileDir(".");
   TFile *f;
   f = TFile::Open("http://root.cern.ch/files/europe.root","cacheread");

   if (!f) {
      printf("Cannot access europe.root. Is internet working ?\n");
      return;
   }

   TH2Poly *p = new TH2Poly(
             "Europe",
             "Europe (bin contents are normalized to the surfaces in km^{2})",
             lon1,lon2,lat1,lat2);
   p->GetXaxis()->SetNdivisions(520);
   p->GetXaxis()->SetTitle("longitude");
   p->GetYaxis()->SetTitle("latitude");

   p->SetContour(100);

   TMultiGraph *mg;
   TKey *key;
   TIter nextkey(gDirectory->GetListOfKeys());
   while ((key = (TKey*)nextkey())) {
      TObject *obj = key->ReadObj();
      if (obj->InheritsFrom("TMultiGraph")) {
         mg = (TMultiGraph*)obj;
         p->AddBin(mg);
      }
   }

   TRandom r;
   Double_t longitude, latitude;
   Double_t x, y, pi4 = TMath::Pi()/4, alpha = TMath::Pi()/360;

   gBenchmark->Start("Partitioning");
   p->ChangePartition(100, 100);
   gBenchmark->Show("Partitioning");

   // Fill TH2Poly according to a Mercator projection.
   gBenchmark->Start("Filling");
   for (i=0; i<npoints; i++) {
      longitude = r.Uniform(lon1,lon2);
      latitude  = r.Uniform(lat1,lat2);
      x         = longitude;
      y         = 38*TMath::Log(TMath::Tan(pi4+alpha*latitude));
      p->Fill(x,y);
   }
   gBenchmark->Show("Filling");

   Int_t nbins = p->GetNumberOfBins();
   Double_t maximum = p->GetMaximum();


   // h2 contains the surfaces computed from TH2Poly.
   TH1F *h2 = (TH1F *)h->Clone("h2");
   h2->Reset();
   for (j=0; j<nx; j++) {
      for (i=0; i<nbins; i++) {
         if (strstr(countries[j],p->GetBinName(i+1))) {
            h2->Fill(countries[j],p->GetBinContent(i+1));
            h2->SetBinError(j, p->GetBinError(i+1));
         }
      }
   }

   // Normalize the TH2Poly bin contents to the real surfaces.
   Double_t scale = surfaces[0]/maximum;
   for (i=0; i<nbins; i++) p->SetBinContent(i+1, scale*p->GetBinContent(i+1));

   gStyle->SetOptStat(1111);
   p->Draw("COLZ");

   TCanvas *c1 = new TCanvas("c1", "c1",W+10,0,W-20,H);
   c1->SetRightMargin(0.047);

   scale = h->GetMaximum()/h2->GetMaximum();

   h->SetStats(0);
   h->SetLineColor(kRed-3);
   h->SetLineWidth(2);
   h->SetMarkerStyle(20);
   h->SetMarkerColor(kBlue);
   h->SetMarkerSize(0.8);
   h->Draw("LP");
   h->GetXaxis()->SetLabelFont(42);
   h->GetXaxis()->SetLabelSize(0.03);
   h->GetYaxis()->SetLabelFont(42);

   h2->Scale(scale);
   Double_t scale2=TMath::Sqrt(scale);
   for (i=0; i<nx; i++) h2->SetBinError(i+1, scale2*h2->GetBinError(i+1));
   h2->Draw("E SAME");
   h2->SetMarkerStyle(20);
   h2->SetMarkerSize(0.8);

   TLegend *leg = new TLegend(0.5,0.67,0.92,0.8,NULL,"NDC");
   leg->SetTextFont(42);
   leg->SetTextSize(0.025);
   leg->AddEntry(h,"Real countries surfaces from Wikipedia (in km^{2})","lp");
   leg->AddEntry(h2,"Countries surfaces from TH2Poly (with errors)","lp");
   leg->Draw();
   leg->Draw();

   Double_t wikiSum = h->Integral();
   Double_t polySum = h2->Integral();
   Double_t error = TMath::Abs(wikiSum-polySum)/wikiSum;
   printf("THPoly Europe surface estimation error wrt wikipedia = %f per cent when using %d points\n",100*error,npoints);
}
void pionContaminationVeta(){
  
  
	gStyle->SetOptStat(0);
	gStyle->SetOptFit(1);
	gStyle->SetPalette(1);
	
	char hist  [100];
	char hfile [100];
  
	
	sprintf(hfile,"~/Desktop/Research/2012IFF/rootFiles/nsigma20bintest35mil.root");  
  
	TFile* file = TFile::Open(hfile,"read");
	assert(file);
	
	
  double totalYieldWhole = 0;
  double pionYieldWhole = 0;
  double kpYieldWhole = 0;
  double electYieldWhile = 0;
	
	
	double pionFrac  [20];
	double kpFrac    [20];
	double electFrac [20];
	
	double pionCent  [20];
	double kpCent    [20];
	double electCent [20];
	
	double pionMax  [20];
	double kpMax    [20];
	double electMax [20];
	
	double pionSig  [20];
	double kpSig    [20];
	double electSig [20];
	
	
	double etastart[20];
	double etaend[20];
  
	double eta[20];
	
	
	double piYield[20];
	double highestYield = 0;
	
  double totalYeild[20];
	
	
	
  TH1F* hTotal = new TH1F("hTotal","hTotal",300,-10,10);

  
	for (int ihist=0; ihist<20; ihist++)
	{
		/*
     if (ihist != 0 || ihist != 1 || ihist != 2 || ihist != 3 ||)
     {
     cou
     }
     */
		sprintf(hist,"nSigmaPionBin_%i",ihist);
		cout << hist << endl;
		
		TH1F *hNsigma = (TH1F*) file->Get(hist);
	  assert(hNsigma);
    
    hTotal->Add(hNsigma, 1);
    cout << hTotal->GetEntries() << endl;
		
		TF1 *fitFunc = new TF1("fitFunc","gaus(0)+gaus(3)+gaus(6)",-10,10);
    TF1 *piFunc = new TF1("piFunc","gaus(0)",-10,10);
    TF1 *kpFunc = new TF1("kpFunc","gaus(0)",-10,10);
    TF1  *eFunc = new TF1( "eFunc","gaus(0)",-10,10);
    fitFunc->SetParName(0, "A_{#pi}");
    fitFunc->SetParName(1, "#LTn_{#pi}#GT");
    fitFunc->SetParName(2, "#sigma_{#pi}");
    fitFunc->SetParName(3, "A_{K/p}");
    fitFunc->SetParName(4, "#LTn_{K/p}#GT");
    fitFunc->SetParName(5, "#sigma_{K/p}");
    fitFunc->SetParName(6, "A_{e}");
    fitFunc->SetParName(7, "#LTn_{e}#GT");
    fitFunc->SetParName(8, "#sigma_{e}");
		
    fitFunc->SetParameter(0, hNsigma->GetMaximum());
    fitFunc->SetParameter(1, 0.);
    fitFunc->SetParameter(2, 1.);
		
    fitFunc->SetParameter(3, 0.05*hNsigma->GetMaximum());
    fitFunc->SetParameter(4,-3.);
    fitFunc->SetParameter(5, 1.5);
		
    fitFunc->SetParameter(6, 0.05*hNsigma->GetMaximum());
    fitFunc->SetParameter(7, 4.); //was at 5. but it seems like 4. works better
    fitFunc->SetParameter(8, 3.);
		
		hNsigma->Fit("fitFunc");
    
    float  ampPi = fitFunc->GetParameter(0);
    float centPi = fitFunc->GetParameter(1);
    float  sigPi = fitFunc->GetParameter(2);
    piFunc->SetParameters(ampPi,centPi,sigPi);
    piFunc->SetLineColor(kViolet+1);
    
    float  ampKP = fitFunc->GetParameter(3);
    float centKP = fitFunc->GetParameter(4);
    float  sigKP = fitFunc->GetParameter(5);
    kpFunc->SetParameters(ampKP,centKP,sigKP);
    kpFunc->SetLineColor(kGreen+2);
    
    float  ampE  = fitFunc->GetParameter(6);
    float centE  = fitFunc->GetParameter(7);
    float  sigE  = fitFunc->GetParameter(8);
    eFunc->SetParameters(ampE,centE,sigE);
    eFunc->SetLineColor(kBlue);
    
    piFunc->Draw("same");
    kpFunc->Draw("same");
    eFunc->Draw("same");
    
    TLine *l1 = new TLine( 2.5,0, 2.5,0.9*hNsigma->GetMaximum());
    TLine *l2 = new TLine(-1.0,0,-1.0,0.9*hNsigma->GetMaximum());
    l1->SetLineColor(kOrange+2);
    l2->SetLineColor(kOrange+2);
    l1->SetLineWidth(2);
    l2->SetLineWidth(2);
    
    l1->Draw();
    l2->Draw();
		
		//*
    float  totYield = fitFunc->Integral(-1.,2.5);
    float pionYield =  piFunc->Integral(-1.,2.5);
    float   kpYield =  kpFunc->Integral(-1.,2.5);
    float    eYield =   eFunc->Integral(-1.,2.5);
		//*/
		/*
     float  totYield = fitFunc->Integral(-2.,2.);
     float pionYield =  piFunc->Integral(-2.,2.);
     float   kpYield =  kpFunc->Integral(-2.,2.);
     float    eYield =   eFunc->Integral(-2.,2.);
     //*/
    
    
    
    totalYieldWhole += totYield;
    pionYieldWhole += pionYield;
    kpYieldWhole += kpYield;
    electYieldWhile += eYield;
    
    
    printf("\nTotal Yield\tPion Yield\tK/p Yield\tElect Yield\n");
    printf("%e\t%e\t%e\t%e\n",totYield,pionYield,kpYield,eYield);
    printf("Pion Fraction = %e\n",(pionYield/totYield));
    
		
		totalYeild[ihist] = totYield;
		
		pionFrac[ihist]  = pionYield/totYield;
		kpFrac[ihist]    = kpYield/totYield;
		electFrac[ihist] = eYield/totYield;
		
		etastart[ihist] = -2+ihist*0.2;
		etaend[ihist] = -2+(ihist+1)*0.2;
    
		eta[ihist] = (etastart[ihist]+etaend[ihist])*.5;
		
		piYield[ihist] = pionYield;
		
		if (highestYield < pionYield){highestYield = pionYield;}
		
		
	}
	
	
	double normlzd_PiYield[20];
	
	double sumPiYield = 0;
  
	for (int i=0; i<20; i++)
	{
		if (pionFrac[i] != pionFrac[i])
		{
			cout << i << "  " << eta[i] << "  testFailed" << " highyeild " << highestYield << endl;
			pionFrac[i] = -.2;
		}
		else
		{
			cout << i << "  " << eta[i] << "  " << pionFrac[i] << " highyeild " << highestYield << endl;
			
		}
		
		normlzd_PiYield[i] = piYield[i]/highestYield; 
		
    
		sumPiYield += piYield[i];
		
	}
	
  double pionFracErr[20];
  double kpFracErr[20];
  double electFracErr[20];
  
  for (int i=0; i<20; i++)
  {
    pionFracErr[i] = sqrt((1-pionFrac[i])*pionFrac[i]/totalYeild[i]);
    kpFracErr[i] = sqrt((1-kpFrac[i])*kpFrac[i]/totalYeild[i]);
    electFracErr[i] = sqrt((1-electFrac[i])*electFrac[i]/totalYeild[i]);
    
  }  
  
  
  
	
	cout << "total Pion Yield = " << sumPiYield << endl;
	
	
	TGraphErrors* gPionYield = new TGraphErrors(20,eta,normlzd_PiYield,0,0);
	gPionYield->SetMarkerColor(kRed+2);
	gPionYield->SetMarkerStyle(24);
	
	TGraphErrors* gPionFrac = new TGraphErrors(20,eta,pionFrac,0,pionFracErr);
	TGraphErrors* gKpFrac   = new TGraphErrors(20,eta,kpFrac,0,kpFracErr);	
	TGraphErrors* gElecFrac = new TGraphErrors(20,eta,electFrac,0,electFracErr);
	
	
	
	
	gPionFrac->SetMarkerColor(kViolet+1);
  gPionFrac->SetLineColor(kViolet+1);
  gPionFrac->SetLineWidth(2);
	gKpFrac->SetMarkerColor(kGreen+2);
  gKpFrac->SetLineColor(kGreen+2);
  gKpFrac->SetLineWidth(2);
	gKpFrac->SetMarkerStyle(22);	
	gElecFrac->SetMarkerColor(kBlue);
	gElecFrac->SetLineColor(kBlue);
	gElecFrac->SetLineWidth(2);
	gElecFrac->SetMarkerStyle(20);
	
	
	TMultiGraph* multiFracs = new TMultiGraph();
	multiFracs->Add(gPionFrac);
	multiFracs->Add(gKpFrac);
	multiFracs->Add(gElecFrac);
	//multiFracs->Add(gPionYield);
  
	TCanvas* cMultiG = new TCanvas();
	multiFracs->Draw("AP");
	multiFracs->GetXaxis()->SetTitle("#eta^{#pi^{+}#pi^{-}}");
	multiFracs->GetYaxis()->SetTitle("particle Fractions");
	gPad->Modified();
	
	TLegend* leg = new TLegend(0.52,0.17,0.89,0.30);
	leg->AddEntry(gPionFrac,"Pion","P");
	leg->AddEntry(gKpFrac,"K/P","P");
	leg->AddEntry(gElecFrac,"Electron","P");
	//  leg->Draw();
	
	TCanvas* cPiYeild = new TCanvas();
	TGraphErrors* gPionYield = new TGraphErrors(20,eta,piYield,0,0);
	
	
	gPionYield->Draw("AP");
	gPionYield->SetMarkerColor(kRed+2);
	gPionYield->SetMarkerStyle(24);
	gPionYield->GetXaxis()->SetTitle("#eta^{#pi^{+}#pi^{-}}");
	gPionYield->GetYaxis()->SetTitle("Pion Yield");
	
	
	
	
	
	cout << pionYieldWhole/totalYieldWhole << endl;
	
	
	
	
	hTotal->Draw();
	
  TF1 *fitFunc = new TF1("fitFunc","gaus(0)+gaus(3)+gaus(6)",-10,10);
  TF1 *piFunc = new TF1("piFunc","gaus(0)",-10,10);
  TF1 *kpFunc = new TF1("kpFunc","gaus(0)",-10,10);
  TF1  *eFunc = new TF1( "eFunc","gaus(0)",-10,10);
  fitFunc->SetParName(0, "A_{#pi}");
  fitFunc->SetParName(1, "#LTn_{#pi}#GT");
  fitFunc->SetParName(2, "#sigma_{#pi}");
  fitFunc->SetParName(3, "A_{K/p}");
  fitFunc->SetParName(4, "#LTn_{K/p}#GT");
  fitFunc->SetParName(5, "#sigma_{K/p}");
  fitFunc->SetParName(6, "A_{e}");
  fitFunc->SetParName(7, "#LTn_{e}#GT");
  fitFunc->SetParName(8, "#sigma_{e}");
  
  fitFunc->SetParameter(0, hTotal->GetMaximum());
  fitFunc->SetParameter(1, 0.);
  fitFunc->SetParameter(2, 1.);
  
  fitFunc->SetParameter(3, 0.05*hTotal->GetMaximum());
  fitFunc->SetParameter(4,-3.);
  fitFunc->SetParameter(5, 1.5);
  
  fitFunc->SetParameter(6, 0.05*hTotal->GetMaximum());
  fitFunc->SetParameter(7, 4.); //was at 5. but it seems like 4. works better
  fitFunc->SetParameter(8, 3.);
  
	
	
	
  hTotal->Fit("fitFunc");
  
  float  ampPi = fitFunc->GetParameter(0);
  float centPi = fitFunc->GetParameter(1);
  float  sigPi = fitFunc->GetParameter(2);
  piFunc->SetParameters(ampPi,centPi,sigPi);
  piFunc->SetLineColor(kViolet+1);
  
  float  ampKP = fitFunc->GetParameter(3);
  float centKP = fitFunc->GetParameter(4);
  float  sigKP = fitFunc->GetParameter(5);
  kpFunc->SetParameters(ampKP,centKP,sigKP);
  kpFunc->SetLineColor(kGreen+2);
  
  float  ampE  = fitFunc->GetParameter(6);
  float centE  = fitFunc->GetParameter(7);
  float  sigE  = fitFunc->GetParameter(8);
  eFunc->SetParameters(ampE,centE,sigE);
  eFunc->SetLineColor(kBlue);
  
  piFunc->Draw("same");
  kpFunc->Draw("same");
  eFunc->Draw("same");
  
  TLine *l1 = new TLine( 2.5,0, 2.5,0.9*hNsigma->GetMaximum());
  TLine *l2 = new TLine(-1.0,0,-1.0,0.9*hNsigma->GetMaximum());
  l1->SetLineColor(kOrange+2);
  l2->SetLineColor(kOrange+2);
  l1->SetLineWidth(2);
  l2->SetLineWidth(2);
  
  l1->Draw();
  l2->Draw();
  
  //*
  float  totYield = fitFunc->Integral(-1.,2.5);
  float pionYield =  piFunc->Integral(-1.,2.5);
  float   kpYield =  kpFunc->Integral(-1.,2.5);
  float    eYield =   eFunc->Integral(-1.,2.5);
  
  double pionerr = sqrt((1-pionYield/totYield)*pionYield/totYield/totalYeild);

  
	cout << pionYield/totYield << " " << pionerr << endl;
	
	
	
	
	
	
	
	
	
	
	
  
  
  
  
}
Beispiel #12
0
int main(int argc, char** argv){

 ///==================================================
 ///==== Draw Distribution with and without scale ====
 ///==================================================

 ///===============================================================================
 gROOT->Reset();
 gROOT->SetStyle("Plain");
 gStyle->SetPalette(1);
 gStyle->SetOptStat(0);
 gStyle->SetOptFit(0);

 const Int_t __NRGBs = 5;
 const Int_t __NCont = 76;
 Double_t __stops[__NRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 };
 Double_t __red[__NRGBs]   = { 0.00, 0.00, 0.87, 1.00, 0.51 };
 Double_t __green[__NRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 };
 Double_t __blue[__NRGBs]  = { 0.51, 1.00, 0.12, 0.00, 0.00 };

 TColor::CreateGradientColorTable(__NRGBs, __stops, __red, __green, __blue, __NCont);
 gStyle->SetNumberContours(__NCont);
 ///===============================================================================
 

 if(argc != 2)
 {
  std::cerr << ">>>>> analysis.cpp::usage: " << argv[0] << " configFileName" << std::endl ;
  return 1;
 }

 // Parse the config file
 parseConfigFile (argv[1]) ;

 std::string treeNameDATA  = gConfigParser -> readStringOption("InputDATA::treeName");
 std::string inputFileDATA = gConfigParser -> readStringOption("InputDATA::inputFile");
 double luminosity = gConfigParser -> readDoubleOption("InputDATA::luminosity");
 std::cout << ">>>>> InputDATA::treeName   " << treeNameDATA  << std::endl;
 std::cout << ">>>>> InputDATA::inputFile  " << inputFileDATA  << std::endl;
 std::cout << ">>>>> InputDATA::luminosity " << luminosity  << std::endl;

 std::string treeNameMC  = gConfigParser -> readStringOption("InputMC::treeName");
 std::vector< std::string > inputFileMC = gConfigParser -> readStringListOption("InputMC::inputFile");
 std::vector< std::string > inputSampleMC = gConfigParser -> readStringListOption("InputMC::nameSample");
 std::vector< double > xSecAndEfficiency = gConfigParser -> readDoubleListOption("InputMC::xsecEff");

 std::cout << ">>>>> InputMC::treeName  " << treeNameMC  << std::endl;
 std::cout << ">>>>> InputMC::inputFile size " << inputFileMC.size()  << std::endl;
 if (inputFileMC.size() != xSecAndEfficiency.size() || inputFileMC.size() != inputSampleMC.size()) {
     std::cerr << " >>>> Error: different number of samples and cross sections" << std::endl;
     return 0;
    }
 int nMC = inputFileMC.size();
 for (int iMC = 0; iMC < nMC; iMC++) {
    std::cout << ">>>>> InputMC::inputFile[" << iMC << "] = " << inputSampleMC.at(iMC) << " => " << inputFileMC.at(iMC)  << " : " << xSecAndEfficiency.at(iMC) << " : " << luminosity * xSecAndEfficiency.at(iMC) << std::endl;
 }


 int binX = gConfigParser -> readIntOption("Options::binX");
 double minX = gConfigParser -> readDoubleOption("Options::minX");
 double maxX = gConfigParser -> readDoubleOption("Options::maxX");
 std::string variableX = gConfigParser -> readStringOption("Options::variableX");
 std::cout << ">>>>> Options::binX      " << binX  << std::endl;
 std::cout << ">>>>> Options::minX      " << minX  << std::endl;
 std::cout << ">>>>> Options::maxX      " << maxX  << std::endl;
 std::cout << ">>>>> Options::variableX " << variableX.c_str() << std::endl;

 int binY = gConfigParser -> readIntOption("Options::binY");
 double minY = gConfigParser -> readDoubleOption("Options::minY");
 double maxY = gConfigParser -> readDoubleOption("Options::maxY");
 std::string variableY = gConfigParser -> readStringOption("Options::variableY");
 std::cout << ">>>>> Options::binY      " << binY  << std::endl;
 std::cout << ">>>>> Options::minY      " << minY  << std::endl;
 std::cout << ">>>>> Options::maxY      " << maxY  << std::endl;
 std::cout << ">>>>> Options::variableY " << variableY.c_str() << std::endl;
 
 int binRatio = gConfigParser -> readIntOption("Options::binRatio");
 double minRatio = gConfigParser -> readDoubleOption("Options::minRatio");
 double maxRatio = gConfigParser -> readDoubleOption("Options::maxRatio");
 std::cout << ">>>>> Options::minRatio      " << minRatio  << std::endl;
 std::cout << ">>>>> Options::maxRatio      " << maxRatio  << std::endl;
 
 
 std::string outputFile = gConfigParser -> readStringOption("Output::outputFile");
 std::cout << ">>>>> Output::outputFile  " << outputFile  << std::endl;


//  TString AdditionalCut = Form("eta > 1.5");// || eta < -1.5)");// && eleFBrem<0.5");
 TString AdditionalCut = Form("eta < -1.5");// || eta < -1.5)");// && eleFBrem<0.5");
//  TString AdditionalCut = Form("(eta > 1.5 || eta < -1.5)");// && abs(eleFBrem)<1");
 
 
 
 EColor vColor[100] = {
  kBlue,(EColor)(kBlue+1),(EColor) (kBlue+2),
  kRed,(EColor) (kRed+1),(EColor) (kRed+2),
  kGreen,(EColor) (kGreen+1),(EColor) (kGreen+2),
  kTeal,(EColor) (kTeal+1),
  kOrange,(EColor) (kOrange+1),
  kMagenta,(EColor) (kMagenta+1),(EColor) (kViolet),(EColor) (kYellow),(EColor) (kGray)};
 
 ///==== DATA ====
 TFile* fileInDATA = new TFile(inputFileDATA.c_str(),"READ");

 ///==== W ====
 TFile* fileInMC[nMC];
 for (int iMC = 0; iMC < nMC; iMC++) {
    fileInMC[iMC] = new TFile(inputFileMC.at(iMC).c_str(),"READ");
 }

 ///==== output ====
 TFile* outFile = new TFile(outputFile.c_str(),"RECREATE");
 outFile->cd();


 ///==== Prepare input trees ====
 TLegend* leg = new TLegend(0.55,0.7,0.95,0.95);
 leg->SetFillColor(0);

 TLegend* legDown = new TLegend(0.55,0.1,0.95,0.35);
 legDown->SetFillColor(0);

 TTree* MyTreeDATA = (TTree*) fileInDATA->Get(treeNameDATA.c_str());
 int initialNumber;
 TH2F* HistoDATA = new TH2F("DATA","DATA",binX,minX,maxX,binY,minY,maxY);
 TH1F* HistoRatioDATA = new TH1F("RatioDATA","RatioDATA",binRatio,minRatio,maxRatio);
 TString DrawDATA = Form("%s:%s >> DATA",variableY.c_str(),variableX.c_str());
 MyTreeDATA->Draw(DrawDATA.Data(),AdditionalCut.Data());
 HistoDATA->SetMarkerSize(1);
 HistoDATA->SetMarkerStyle(20); 
 HistoDATA->GetXaxis()->SetTitle(variableX.c_str());
 HistoDATA->GetYaxis()->SetTitle(variableY.c_str());
 leg->AddEntry(HistoDATA,HistoDATA->GetTitle(),"p");
 legDown->AddEntry(HistoDATA,HistoDATA->GetTitle(),"p");

 DrawDATA = Form("(%s) / (%s) >> RatioDATA",variableY.c_str(),variableX.c_str());
 MyTreeDATA->Draw(DrawDATA.Data(),AdditionalCut.Data());
 HistoRatioDATA->SetMarkerSize(1);
 HistoRatioDATA->SetMarkerStyle(20); 
 HistoRatioDATA->GetXaxis()->SetTitle(Form("(%s)/(%s)",variableY.c_str(),variableX.c_str()));
 
 TH2F* HistoMC[nMC];
 TH1F* HistoRatioMC[nMC];

 TH2F* HistoMC_SUM = new TH2F("HistoMC_SUM","HistoMC_SUM",binX,minX,maxX,binY,minY,maxY);
 TH1F* HistoRatioMC_SUM = new TH1F("HistoRatioMC_SUM","HistoRatioMC_SUM",binRatio,minRatio,maxRatio);
 
 SetColorAndStyleHisto(*(HistoRatioMC_SUM),kBlue); 
 
 TTree* MyTreeMC[nMC];
 THStack* hsMC = new THStack("hsMC","hsMC");
 
 double MC_Expected = 0;
 
 for (int iMC = 0; iMC < nMC; iMC++) {
// for (int iMC = nMC-1; iMC >= 0; iMC--) {
  MyTreeMC[iMC] = (TTree*) fileInMC[iMC]->Get(treeNameMC.c_str());
  MyTreeMC[iMC]->SetBranchAddress("initialNumber",&initialNumber);
  MyTreeMC[iMC]->GetEntry(0);
  xSecAndEfficiency.at(iMC) = xSecAndEfficiency.at(iMC) / initialNumber; ///==== normalize to initial number of events
  HistoMC[iMC] = new TH2F(inputSampleMC.at(iMC).c_str(),inputSampleMC.at(iMC).c_str(),binX,minX,maxX,binY,minY,maxY);
  HistoRatioMC[iMC] = new TH1F(Form("%s_Ratio",inputSampleMC.at(iMC).c_str()),Form("%s_Ratio",inputSampleMC.at(iMC).c_str()),binRatio,minRatio,maxRatio);
  
  TString Draw = Form("%s:%s >> %s",variableY.c_str(),variableX.c_str(),inputSampleMC.at(iMC).c_str());
  MyTreeMC[iMC]->Draw(Draw.Data(),AdditionalCut.Data());

  Draw = Form("(%s) / (%s) >> %s",variableY.c_str(),variableX.c_str(),Form("%s_Ratio",inputSampleMC.at(iMC).c_str()));
  MyTreeMC[iMC]->Draw(Draw.Data(),AdditionalCut.Data());  
  HistoRatioMC[iMC]->GetXaxis()->SetTitle(Form("(%s)/(%s)",variableY.c_str(),variableX.c_str()));
  
  std::cout << ">>>>>> " << inputSampleMC.at(iMC) << " : " << xSecAndEfficiency.at(iMC) << " : " << luminosity << " : " << HistoMC[iMC]->GetEntries() << " = " << luminosity * xSecAndEfficiency.at(iMC) * HistoMC[iMC]->GetEntries() << std::endl;
  std::cout << "    >> " << Draw.Data() << std::endl;
  std::cout << "    >> " << HistoMC[iMC]->GetEntries() << " Entries" << std::endl;
 
  MC_Expected += luminosity * xSecAndEfficiency.at(iMC) * HistoMC[iMC]->GetEntries();
  
  HistoMC[iMC]->Scale(luminosity * xSecAndEfficiency.at(iMC)); // / HistoMC[iMC]->GetEntries());
  HistoRatioMC[iMC]->Scale(luminosity * xSecAndEfficiency.at(iMC)); // / HistoMC[iMC]->GetEntries());
  
  SetColorAndStyleHisto(*(HistoMC[iMC]),vColor[iMC]);
  SetColorAndStyleHisto(*(HistoRatioMC[iMC]),vColor[iMC]);
  
  HistoMC[iMC]->GetXaxis()->SetTitle(variableX.c_str());
  HistoMC[iMC]->GetYaxis()->SetTitle(variableY.c_str());
  
  HistoMC_SUM->Add(HistoMC[iMC]);
  HistoMC_SUM->GetXaxis()->SetTitle(variableX.c_str());
  HistoMC_SUM->GetYaxis()->SetTitle(variableY.c_str());
  
  HistoRatioMC_SUM->Add(HistoRatioMC[iMC]);
  HistoRatioMC_SUM->GetXaxis()->SetTitle(Form("(%s)/(%s)",variableY.c_str(),variableX.c_str()));
  
  hsMC->Add(HistoMC[iMC]);
  if (iMC == 0) hsMC->Add(HistoMC[iMC]);
  leg->AddEntry(HistoMC[iMC],HistoMC[iMC]->GetTitle(),"f");
  legDown->AddEntry(HistoMC[iMC],HistoMC[iMC]->GetTitle(),"f");
 }
  
  
 ///==== make fit ====
 
 TH1D* htemp_prof = smartGausProfileXSQRTN(HistoDATA,2);  
 TGraphErrors grH = buildGEfromH_Personalized(*htemp_prof);
 grH.SetMarkerStyle(22);
 grH.SetMarkerSize(0.7);
 grH.SetMarkerColor(kBlue);
 grH.SetFillColor(kBlue);
 grH.SetFillStyle(3335);
 grH.SetLineWidth(1);
 grH.SetLineColor(kBlue);
 grH.GetXaxis()->SetTitle(variableX.c_str());
 grH.GetYaxis()->SetTitle(variableY.c_str());
 

 ///----------------------
 ///---- Plot results ----
 ///----------------------
 std::cerr << " MC expected : DATA = " << MC_Expected << " : " << HistoDATA->GetEntries() << std::endl;
 
 std::cerr << " HistoDATA->GetMaximum() = " << HistoDATA->GetMaximum() << std::endl;
 std::cerr << " HistoDATA->GetEntries() = " << HistoDATA->GetEntries() << std::endl;
 outFile->cd();
 
 TCanvas cResultDistro("cResultDistro","cResultDistro",900,900);
 cResultDistro.Divide(2,2);
 cResultDistro.cd(1);
 HistoDATA->DrawClone("colz");
 gPad->SetGrid();
 TString tLumiName = Form("#int L = %.4f pb^{-1}",luminosity);
 TLatex tLumi(1.5 * HistoDATA->GetMean(1),0.2 * HistoDATA->GetMaximum(),tLumiName.Data());
 tLumi.DrawClone();
 
 
 cResultDistro.cd(2);
 HistoRatioMC_SUM->Draw();
 HistoRatioDATA->Draw("E1same");
 TString tEleName = Form("%d electrons",(int) HistoDATA->GetEntries());
 TLatex tEle(2.0 * HistoRatioDATA->GetMean(1),0.3 * HistoRatioDATA->GetMaximum(),tEleName.Data());
 tEle.DrawClone();
 gPad->SetGrid();

 
 cResultDistro.cd(3);
 grH.Draw("APL");
 double minFit = gConfigParser -> readDoubleOption("Options::minFit");
 double maxFit = gConfigParser -> readDoubleOption("Options::maxFit");
 std::cout << ">>>>> Options::minFit      " << minFit  << std::endl;
 std::cout << ">>>>> Options::maxFit      " << maxFit  << std::endl;
 
 TF1* funz = new TF1 ("funz","pol1",minFit,maxFit);
//  funz->FixParameter(0,0);
 funz->SetParameter(0,0);
 funz->SetParameter(1,1);
 grH.Fit("funz","RMQ");
 std::cerr << " Y = [0] + [1] * X " << std::endl;
 std::cerr << " [0] = " << funz->GetParameter(0) << " +/- " << funz->GetParError(0) << std::endl;
 std::cerr << " [1] = " << funz->GetParameter(1) << " +/- " << funz->GetParError(1) << std::endl;
 double coeffDATA = funz->GetParameter(1);
 double errCoeffDATA = funz->GetParError(1);
 
 gPad->SetGrid();
 
 
 cResultDistro.cd(4);
 HistoRatioMC_SUM->Draw();
 HistoRatioDATA->Draw("E1same");
 tEle.DrawClone();
 gPad->SetGrid();
 gPad->SetLogy();
 
 
 TString nameImage = Form("%s_%s_%d.png",variableY.c_str(),variableX.c_str(),1);
 cResultDistro.SaveAs(nameImage.Data());
 TString nameImageRoot = Form("%s_%s_%d.root",variableY.c_str(),variableX.c_str(),1);
 cResultDistro.SaveAs(nameImageRoot.Data());

 
 
 TCanvas cResultDistroMC("cResultDistroMC","cResultDistroMC",800,800);
 cResultDistroMC.Divide(2,2);
 
 //  cResultDistroMC.Divide(2,nMC);
//  for (int iMC = 0; iMC < nMC; iMC++) {
//   cResultDistroMC.cd(2*iMC+1);
//   HistoMC[iMC]->DrawClone("colz");
//   HistoDATA->DrawClone("BOXsame");
//   cResultDistroMC.cd(2*iMC+2);
//   HistoRatioMC[iMC]->DrawNormalized("");
//   HistoRatioDATA->DrawNormalized("E1same");  
//  }

 cResultDistroMC.cd(1);
 HistoMC_SUM->DrawClone("colz");
 HistoDATA->DrawClone("BOXsame");
 gPad->SetGrid();
 
 ///==== make fit ====
 
 cResultDistroMC.cd(3);
 
 TH1D* MChtemp_prof = smartGausProfileXSQRTN(HistoMC_SUM,2);  
 TGraphErrors MCgrH = buildGEfromH_Personalized(*MChtemp_prof);
 MCgrH.SetMarkerStyle(22);
 MCgrH.SetMarkerSize(0.7);
 MCgrH.SetMarkerColor(kRed);
 MCgrH.SetFillColor(kRed);
 MCgrH.SetFillStyle(3335);
 MCgrH.SetLineWidth(1);
 MCgrH.SetLineColor(kRed);
 MCgrH.GetXaxis()->SetTitle(variableX.c_str());
 MCgrH.GetYaxis()->SetTitle(variableY.c_str());
 
 funz->SetParameter(0,0);
 funz->SetParameter(1,1);
 MCgrH.Fit("funz","RMQ");
 
 std::cerr << " ================= " << std::endl;
 std::cerr << " ======= MC ====== " << std::endl;
 std::cerr << " Y = [0] + [1] * X " << std::endl;
 std::cerr << " [0] = " << funz->GetParameter(0) << " +/- " << funz->GetParError(0) << std::endl;
 std::cerr << " [1] = " << funz->GetParameter(1) << " +/- " << funz->GetParError(1) << std::endl;
 double coeffMC = funz->GetParameter(1);
 double errCoeffMC = funz->GetParError(1);
 
 MCgrH.Draw("APL");
 gPad->SetGrid();
 
 
 cResultDistroMC.cd(4);
 MCgrH.Draw("APL");
 grH.Draw("PLSAME");
 gPad->SetGrid();
 
 
 TString nameImageLog = Form("%s_%s_%d_MC.png",variableY.c_str(),variableX.c_str(),1);
 cResultDistroMC.SaveAs(nameImageLog.Data());
  
 
 std::cerr << " 1 - alpha = " << coeffDATA / coeffMC 
           << " +/- " << sqrt( (errCoeffDATA/coeffMC)*(errCoeffDATA/coeffMC) + (errCoeffMC*coeffDATA/coeffMC/coeffMC)*(errCoeffMC*coeffDATA/coeffMC/coeffMC) )
           << std::endl;


 std::cerr << " alpha = " << 1-coeffDATA / coeffMC 
	   << " +/- " << sqrt( (errCoeffDATA/coeffMC)*(errCoeffDATA/coeffMC) + (errCoeffMC*coeffDATA/coeffMC/coeffMC)*(errCoeffMC*coeffDATA/coeffMC/coeffMC) )
	   << std::endl;
   
   

//  TCanvas cResultDistro_1("cResultDistro_1","cResultDistro_1",800,800);
//  HistoRatioMC_SUM->Draw();
//  HistoRatioDATA->Draw("E1same");
//  tEle.DrawClone();
//  gPad->SetGrid();
//  gPad->SetLogy();
   
}
Beispiel #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();
	}

}
//___________________________________________________________________________
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;
}
//------------------------------------------------------------------------------
// Draw projections and residuals
//------------------------------------------------------------------------------
void DrawWithRatio(TCanvas *canvas, char *cTitle,
                  TH1F *hNum, TH1F *hDen)
{
 
 // sanity check
 if (hNum->GetNbinsX() != hDen->GetNbinsX()){
   std::cout<< " *** Error: binning not consistent between data"
            << " and MC -> Exit!\n";
   return;
 }

 
 hNum->Sumw2();
 hDen->Sumw2();

 
 TH1F *hPull = (TH1F*)hNum ->Clone("hPull");
 hPull->Sumw2();
 hPull->Divide(hDen);
 
 //----------------------------------------------------------------------------
 // Create the pads
 //----------------------------------------------------------------------------
 TPad* pad1;
 TPad* pad2;
 
 pad1 = new TPad("pad1","This is pad1",0.02,0.30,0.98,0.98,0);
 pad2 = new TPad("pad2","This is pad2",0.02,0.01,0.98,0.29,0);
 
 pad1->SetLogx();
 pad2->SetLogx();
 pad1->SetBottomMargin(0.01);
 pad2->SetBottomMargin(0.33);
 pad2->SetTopMargin   (0.10);
 
 pad1->Draw(); // Projections pad
 pad2->Draw(); // Residuals   pad
        
        _leg2 = new TLegend(.68,.77,.98,.93);
        _leg2->AddEntry(hDen,"Gen ","l");
        _leg2->AddEntry(hNum,"Unfolded Reco","p");
 pad1->cd();
 hDen->Draw("histo");
 hNum->Draw("pe same");
 _leg2->Draw(); 
 PrintItLog(pad1,cTitle);

//   TLegend* leg = SetLegend(0.73, 0.7, 0.92, 0.89);
//   leg -> AddEntry(hDen," no mass cut","f");
//   leg -> AddEntry(hNum," 60 < M^{#mu #mu} < 120","p");
//   leg ->Draw("same");
 //----------------------------------------------------------------------------
 // Residuals pad
 //----------------------------------------------------------------------------
 pad2->cd();
 
 TAxis *xPull = NULL;
 TAxis *yPull = NULL;
 char xAxisName[200];
 sprintf(xAxisName,"%s",hDen->GetXaxis()->GetTitle());
 axis1F(hPull,xPull,yPull,xAxisName,"ratio");
 
 if (hPull->GetMaximum() > 100) {
   hPull->SetMinimum(-100);
   hPull->SetMaximum( 100);
 }
 
 hPull->GetXaxis()->SetLabelOffset(0.005);
 hPull->GetXaxis()->SetLabelSize  (0.11);
 hPull->GetXaxis()->CenterTitle(1);
 hPull->GetXaxis()->SetTitleOffset(1.10);
 hPull->GetXaxis()->SetTitleSize  (0.12);
 hPull->GetXaxis()->SetNdivisions(7);

 hPull->GetYaxis()->SetLabelSize  (0.09);
 hPull->GetYaxis()->CenterTitle(1);
 hPull->GetYaxis()->SetTitleOffset(0.5);
 hPull->GetYaxis()->SetTitleSize  (0.12);

 hPull->SetMaximum(1.5);
 hPull->SetMinimum(0.5);
 hPull->Draw("pe");

 pad2->Update();
 pad2->GetFrame()->DrawClone();

}
Beispiel #16
0
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void DrawPlots(){
    
    

    bool DoProtonsMomenta       = false;
    bool DoProtonsTrackLength   = false;
    bool DoSRCEvents            = false;
    bool DoAngles               = false;
    bool DoHighMomentumTail     = false;
    bool DothetaPPFinalInitial  = false;
    bool DoDrawQ                = true;
    
    //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
    TPlots  * tracks   = new TPlots("Ana.root","TracksTree");
    TPlots  * events   = new TPlots("Ana.root","EventsTree","events",false);
   
    
    //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
    if (DoProtonsMomenta) {
        TH1F * h = tracks -> H1("StartMomentum.P()","PdgCode==2212","",401,-1,1000
                             ,"proton momentum","p [MeV/c]","",38,38);
        analysis -> NormalizeHistogram(h);
        tracks -> Line(251,0,251,h->GetMaximum(),2,4,2);
        tracks -> Text(260,0.8*h->GetMaximum(),"Fermi momentum 251 MeV/c [e-scat.]");
    }
    //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
    if (DoProtonsTrackLength) {
        tracks -> H2("StartMomentum.P()","TrackLength","PdgCode==2212","colz",401,1,1000,401,-1,1000
                  ,"proton momentum","p [MeV/c]","track length [cm]");
    }
    //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
    if (DoSRCEvents){
        // identify v (np) -> µ p p events, and ask reconstruct BNL measurement
        // the angle between the two protons in the inital state vs. the recoil momentum
        TCanvas * c = plot -> CreateCanvas("c" , "DivideSquare");
        c -> cd(1);
        TH1F * Prec = events -> H1("Prec.Mag()",SRCcut&& "Prec.Mag()>0","colz",50,0,1000,"","recoil momentum [GeV/c]","",38,38);
        plot -> Line(pThresholdArgoNeuT,0,pThresholdArgoNeuT,Prec->GetMaximum(),2,2);
        c -> cd(2);
        events -> H1(plot->CosTheta("Pmiss","Prec"),SRCcut&& "Prec.Mag()>0","colz",50,-1.1,1.1,"","cos( #theta )","",38,38);
        c -> cd(3);
        events -> H2("Prec.Mag()",plot->CosTheta("Pmiss","Prec"),SRCcut&& "Prec.Mag()>0","colz"
                     ,50,1,1000,50,-1.01,1.01,"","recoil momentum [MeV/c]","#theta (p(miss) , p(recoil))");
        plot -> Line(pThresholdArgoNeuT,-1.01,pThresholdArgoNeuT,1.01,2,2);
    }
    
    //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
    if (DoAngles){
//        plot -> CreateCanvas("Theta_pn_i_Prec");
//        events -> H2("Prec.Mag()",plot->CosTheta("Pmiss","Prec"),cutCC2p,"colz"
//                     ,50,0,1000,50,-1.05,1.05,"","recoil momentum [MeV/c]","cos( #theta_{np}^{i} )");
//        plot -> CreateCanvas("Theta_pn_i_Theta_munu");
//        events -> H2(plot->CosTheta("neutrino.Vect()","muon.Vect()"),plot->CosTheta("Pmiss","Prec"),cutCC2p&&"Prec.Mag()>1","colz"
//                     ,50,-1.01,1.01,50,-1.01,1.01,"","cos( #theta_{#nu#mu} )","cos( #theta_{np}^{i} )");
        plot -> CreateCanvas("Theta_pp_f_Prec");
        events -> H2("Prec.Mag()",plot->CosTheta("protons[0].Vect()","protons[1].Vect()"),cutCC2p,"colz"
                     ,50,1,1000,50,-1.01,1.01,"","recoil momentum [MeV/c]","cos( #theta_{pp}^{f} )");
//        plot -> CreateCanvas("Theta_pp_Theta_numu");
//        events -> H2(plot->CosTheta("neutrino.Vect()","muon.Vect()"),plot->CosTheta("protons[0].Vect()","protons[1].Vect()"),cutCC2p,"colz"
//                     ,50,-1.01,1.01,50,-1.01,1.01,"","cos( #theta_{#nu#mu} )","cos( #theta_{pp}^{f} )");
//        plot -> CreateCanvas("Theta_numu_Prec");
//        events -> H2("Prec.Mag()",plot->CosTheta("neutrino.Vect()","muon.Vect()"),cutCC2p&&"Prec.Mag()>200","colz"
//                     ,50,1,1000,50,-1.01,1.01,"","recoil momentum [MeV/c]","cos( #theta_{#nu#mu} )");
    }
    
    
    //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
    if (DoHighMomentumTail){
        plot -> CreateCanvas("DoHighMomentumTail");
        float Max = 1300;
        TH1F * Prec = events -> H1("Prec.Mag()",cutCC2p,"",75,0,Max,"","recoil momentum [MeV/c]","",38,38);
        events -> H1("Prec.Mag()",cutCC2p&&"Prec.Mag()>270","same",75,0,Max,"","recoil momentum [MeV/c]","",48,48,3001);
        float Tail      = Prec -> Integral(Prec->GetXaxis()->FindBin(270),Prec->GetXaxis()->FindBin(Max));
        float TailErr   = sqrt(Tail);
        float Tot       = Prec -> Integral(Prec->GetXaxis()->FindBin(0),Prec->GetXaxis()->FindBin(Max));
        float TotErr    = sqrt(Tot);
        float fTail     = Tail / Tot;
        float fTailErr  = fTail * ( 1./Tail + 1./Tot );
        SHOW(Tail);
        SHOW(Tot);
        SHOW(fTail);
        SHOW(fTailErr);
        TString TailPercentage  = plot->PercentStr(fTail);
        TString TailPercenErr   = plot->PercentStr(fTailErr);
        plot -> Text(300,Prec->GetMaximum(),Form("high momentum tail (>270 MeV/c) %.2f(%.0f)%%",100*fTail,100*100*fTailErr));
    }
    
    //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
    if (DothetaPPFinalInitial){
        plot -> CreateCanvas("Theta_numu_Prec");
//        TString var = plot->CosTheta("Pmiss","Prec") , XTitle = "cos( #theta_{pn}^{i} )";
        TString var = plot->CosTheta("protons[0].Vect()","protons[1].Vect()") , XTitle = "cos( #theta_{pp}^{f} )";
        const int N = 5;
        TH1F    * h[N];
        TString Labels[N];
        float   PmissMin[N] = {0 , 100 , 200 , 400 , 600 } , PmissMax[N] = {100 , 200 , 400 , 600 , 1000 } ;
        for (int i = 0; i < N ; i++) {
            TCut cut = cutCC2p && Form("%f > Prec.Mag() && Prec.Mag() > %f",PmissMax[i],PmissMin[i]) ;
            Labels[i] = Form("%.0f > p(rec) > %.0f MeV/c",PmissMax[i],PmissMin[i]);
            cut.Print();
            h[i] = events -> H1(var,cut,"goff",50,-1.05,1.05,"",XTitle,"",(i!=4)?i+1:i+2,(i!=4)?i+1:i+2);
            analysis -> NormalizeHistogram(h[i]);
        }
        for (int i = N-1; i >= 0 ; i--){
            h[i] -> Draw((i==N-1)?"":"same");
        }
        plot -> AddLegend("recoil momentum cut",N,h,Labels,1,"f");
        
     }

    
    
    //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
    if(DoDrawQ){
        plot -> CreateCanvas("q");
        TString var = "TMath::RadToDeg()*q.Theta()";
//        TString var = plot->Theta("neutrino.Vect()","Pmiss"); //"TMath::RadToDeg()*q.Theta()"
        events -> H2("q.Vect().Mag()",var,cutCC2p,"colz"
                     ,50,1,1400,50,0,180,"","momentum transfer [MeV/c]","#theta_{q}");
//        events -> H2("Prec.Mag()",var,cutCC2p,"colz"
//                     ,50,1,1400,50,0,180,"","recoil momentum [MeV/c]","#theta_{q}");
        
    }
}
void melaDistributions_2D(int index=0,int altModelColor=4){

  gROOT->ProcessLine(".L  ~/tdrstyle.C");
  setTDRStyle();

  TChain* SMHiggs = new TChain("angles");
  TChain* altModel = new TChain("angles");

  TChain* qqZZ = new TChain("angles");

  SMHiggs->Add("/scratch0/hep/whitbeck/OLDHOME/4lHelicity/generatorJHU_V02-01-00/SMHiggs_store/SMHiggs_125GeV_wResolution_withDiscriminants.root");
  
  string fileName[7]={
    "/scratch0/hep/whitbeck/OLDHOME/4lHelicity/generatorJHU_V02-01-00/psScalar_store/psScalar_125GeV_wResolution_withDiscriminants.root",
    "/scratch0/hep/whitbeck/OLDHOME/4lHelicity/generatorJHU_V02-01-00/minGrav_store/minGrav_125GeV_wResolution_withDiscriminants.root",
    "/scratch0/hep/whitbeck/OLDHOME/4lHelicity/generatorJHU_V02-01-00/vector_store/vector_125GeV_wResolution_withDiscriminants.root",
    "/scratch0/hep/whitbeck/OLDHOME/4lHelicity/generatorJHU_V02-01-00/psVector_store/psVector_125GeV_wResolution_withDiscriminants.root",
    "/scratch0/hep/whitbeck/OLDHOME/4lHelicity/generatorJHU_V02-01-00/2hPlus_store/2hPlus_125GeV_wResolution_withDiscriminants.root",
    "/scratch0/hep/whitbeck/OLDHOME/4lHelicity/generatorJHU_V02-01-00/2hMinus_store/2hMinus_125GeV_wResolution_withDiscriminants.root",
    "/scratch0/hep/whitbeck/OLDHOME/4lHelicity/generatorJHU_V02-01-00/0hPlus_store/0hPlus_125GeV_wResolution_withDiscriminants.root"
  };

  string discrimName[7]={"pseudomelaLD","gravimelaLD","vectormelaLD","psVectormelaLD","2hPlusmelaLD","2hMinusmelaLD","0hPlusmelaLD"};

  string axisTitle[7]={"D_{0^{-}}","D_{2_{m}^{+}}","D_{1^{+}}","D_{1^{-}}","D_{2_{h}^{+}}","D_{2_{h}^{-}}","D_{0_{h}^{+}}"};

  altModel->Add( fileName[index].c_str() );

  qqZZ->Add("/scratch0/hep/whitbeck/4lHelicity/datafiles/7TeV/training/pwgevents_*_wResolution_withDiscriminants.root");

  char drawString[100];

  gStyle->SetPadRightMargin(0.12);

  TCanvas* qqZZcan = new TCanvas("qqZZcan","qqZZcan",600,600);
  TCanvas* SMHcan = new TCanvas("SMHcan","SMHcan",600,600);
  TCanvas* altModelcan = new TCanvas("altModelcan","altModelcan",600,600);

  char* binning;
  char* cutString;
  binning ="(30,110,140,20,0,1)";
  cutString="zzmass>110&&zzmass<140";
  
  sprintf(drawString,"%s:zzmass>>qqZZhisto%s",discrimName[index].c_str(),binning);
  qqZZ->Draw(drawString,cutString);

  sprintf(drawString,"%s:zzmass>>SMHhisto%s",discrimName[index].c_str(),binning);
  SMHiggs->Draw(drawString,cutString);

  sprintf(drawString,"%s:zzmass>>altModelhisto%s",discrimName[index].c_str(),binning);
  altModel->Draw(drawString,cutString);

  TH1F* qqZZhisto = (TH1F*) gDirectory->Get("qqZZhisto");
  qqZZhisto->Scale(1./qqZZhisto->GetMaximum());
  qqZZhisto->GetYaxis()->SetTitle( axisTitle[index].c_str() );
  qqZZhisto->GetXaxis()->SetTitle( "m_{4l}" );
  qqZZhisto->GetYaxis()->CenterTitle();
  qqZZhisto->GetXaxis()->SetNdivisions(-505);
  qqZZhisto->GetYaxis()->SetNdivisions(-505);
  qqZZhisto->GetZaxis()->SetNdivisions(-505);
  qqZZhisto->GetXaxis()->CenterTitle();
  
  TGaxis::SetMaxDigits(3);

  TH1F* SMHhisto = (TH1F*) gDirectory->Get("SMHhisto");
  SMHhisto->Scale(1./SMHhisto->GetMaximum());
  SMHhisto->GetYaxis()->SetTitle( axisTitle[index].c_str() );
  SMHhisto->GetXaxis()->SetTitle( "m_{4l}" );
  SMHhisto->GetYaxis()->CenterTitle();
  SMHhisto->GetXaxis()->SetNdivisions(-505);
  SMHhisto->GetYaxis()->SetNdivisions(-505);
  SMHhisto->GetZaxis()->SetNdivisions(-505);
  SMHhisto->GetXaxis()->CenterTitle();


  TH1F* altModelhisto = (TH1F*) gDirectory->Get("altModelhisto");
  altModelhisto->Scale(1./altModelhisto->GetMaximum());
  altModelhisto->GetYaxis()->SetTitle( axisTitle[index].c_str() );
  altModelhisto->GetXaxis()->SetTitle( "m_{4l}" );
  altModelhisto->GetYaxis()->CenterTitle();
  altModelhisto->GetXaxis()->SetNdivisions(-505);
  altModelhisto->GetYaxis()->SetNdivisions(-505);
  altModelhisto->GetZaxis()->SetNdivisions(-505);
  altModelhisto->GetXaxis()->CenterTitle();

  qqZZcan->cd();
  qqZZhisto->Draw("COLZ");

  SMHcan->cd();
  SMHhisto->Draw("COLZ");

  altModelcan->cd();
  altModelhisto->Draw("COLZ");

  char saveName[100];

  sprintf(saveName,"epsfiles/kinematics_2D_%s_qqZZ.eps",discrimName[index].c_str() );
  qqZZcan->SaveAs(saveName);
  sprintf(saveName,"pngfiles/kinematics_2D_%s_qqZZ.png",discrimName[index].c_str() );
  qqZZcan->SaveAs(saveName);

  sprintf(saveName,"epsfiles/kinematics_2D_%s_SMH.eps",discrimName[index].c_str() );
  SMHcan->SaveAs(saveName);
  sprintf(saveName,"pngfiles/kinematics_2D_%s_SMH.png",discrimName[index].c_str() );
  SMHcan->SaveAs(saveName);

  sprintf(saveName,"epsfiles/kinematics_2D_%s_altModel.eps",discrimName[index].c_str() );
  altModelcan->SaveAs(saveName);
  sprintf(saveName,"pngfiles/kinematics_2D_%s_altModel.png",discrimName[index].c_str() );
  altModelcan->SaveAs(saveName);

}
Beispiel #18
0
int plotAll(){

  TFile *file = new TFile("/hadoop/cms/store/group/snt/phys14/TTJets_MSDecaysCKM_central_Tune4C_13TeV-madgraph-tauola_Phys14DR-PU20bx25_PHYS14_25_V1-v1/V07-02-08/merged_ntuple_4.root");
  TTree *tree = (TTree*)file->Get("Events");

  int nEntries = tree->GetEntries();

  TList *t_list = tree->GetListOfAliases();

  for(int i = 0; i < t_list->GetSize(); i++) {
    TString aliasname(t_list->At(i)->GetName());
    cout << aliasname.Data() << endl;
    TString command = aliasname;

    //Support Lorentz Vectors
    TBranch *branch = tree->GetBranch(tree->GetAlias(aliasname.Data()));
    TString branchname(branch->GetName());
    if( branchname.Contains("LorentzVector") ) {
      command.Append(".Pt()");
    }
 
    //Don't support vectors of vectors
    if(branchname.BeginsWith("intss") || branchname.BeginsWith("floatss") || branchname.BeginsWith("doubless") || branchname.Contains("LorentzVectorss") || branchname.Contains("timestamp") ){
      cout << "Sorry, I dont support vector of vectors of objects, will be skipping " << aliasname << endl;
      continue;
    }

    //Don't support TStrings
    if(branchname.Contains("TString") ) {
      cout << "Sorry, I dont support strings, will be skipping " << aliasname << endl;
      continue;
    }

    TString histname = "hist_" + aliasname + ".pdf";
    TH1F* null = new TH1F("","",1,0,1);
    command.Append(">>hist");
    tree->Draw(command.Data(), (aliasname)+"!=-9999 &&"+(aliasname)+"!=-999");
    TH1F *hist = (TH1F*)gDirectory->Get("hist");
    if (hist->Integral() == 0) tree->Draw(command.Data());
    hist = (TH1F*)gDirectory->Get("hist");
    vector <TH1F*> hists; 
    hists.push_back(hist);
    vector <string> titles;
    titles.push_back("");
  
    //Overflow and Underflow
    hist->SetBinContent(1, hist->GetBinContent(1)+hist->GetBinContent(0));
    hist->SetBinContent(hist->GetNbinsX(), hist->GetBinContent(hist->GetNbinsX())+hist->GetBinContent(hist->GetNbinsX()+1));

    if (hist->GetXaxis()->GetXmax() == hist->GetXaxis()->GetXmin()){
      ofstream myfile;
      myfile.open("names.txt", ios_base::app);
      myfile << aliasname.Data() << "\n"; 
      myfile.close();  
    }

    float max = hist->GetMaximum()*100;

    string subtitle = aliasname.Data();
    string histname2 = histname.Data(); 

    dataMCplotMaker(null, hists, titles, subtitle, "CMS3 4.02 Validation", Form("--outputName %s --noFill --noLegend --setMaximum %f --energy 13 --lumi 0 --xAxisLabel %s --noXaxisUnit --noDivisionLabel", subtitle.c_str(), max, histname2.c_str())); 

  }
 
  system("mkdir plots");
  system("mv *.pdf plots/"); 
  system("gs -sDEVICE=pdfwrite     -dNOPAUSE -dBATCH -dSAFER     -sOutputFile=merged.pdf  plots/*pdf"); 

  return 0;

}
Float_t doCoinc(const char *fileIn="coincCERN_0102n.root",TCanvas *cout=NULL,Float_t &rate,Float_t &rateErr){

  // Print settings
  printf("SETTINGS\nAnalyze output from new Analyzer\n");
  printf("Input file = %s\n",fileIn);
  printf("School distance = %f m, angle = %f deg\n",distance,angle);
  printf("School orientation: tel1=%f deg, tel2=%f deg\n",phi1Corr,phi2Corr);
  printf("Max Chi2 = %f\n",maxchisquare);
  printf("Theta Rel Range = %f - %f deg\n",minthetarel,maxthetarel);
  printf("Range for N sattellite in each run = (tel1) %f - %f, (tel2) %f - %f \n",minAvSat[0],maxAvSat[0],minAvSat[1],maxAvSat[1]);
  printf("Min N satellite in a single event = %i\n",satEventThr);

  Int_t adayMin = (yearRange[0]-2014) * 1000 + monthRange[0]*50 + dayRange[0];
  Int_t adayMax = (yearRange[1]-2014) * 1000 + monthRange[1]*50 + dayRange[1];

  Float_t nsigPeak=0;
  Float_t nbackPeak=0;

  angle *= TMath::DegToRad();

  // define some histos
  TH1F *hDeltaTheta = new TH1F("hDeltaTheta","#Delta#theta below the peak (500 ns);#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhi = new TH1F("hDeltaPhi","#Delta#phi below the peak (500 ns);#Delta#phi (#circ)",200,-360,360);
  TH1F *hDeltaThetaBack = new TH1F("hDeltaThetaBack","#Delta#theta out of the peak (> 1000 ns) - normalized;#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhiBack = new TH1F("hDeltaPhiBack","#Delta#phi out of the peak (> 1000 ns)  - normalized;#Delta#phi (#circ)",200,-360,360);
  TH1F *hThetaRel = new TH1F("hThetaRel","#theta_{rel} below the peak (500 ns);#theta_{rel} (#circ)",100,0,120);
  TH1F *hThetaRelBack = new TH1F("hThetaRelBack","#theta_{rel} out of the peak (> 1000 ns)  - normalized;#theta_{rel} (#circ)",100,0,120);

  TH2F *hAngle = new TH2F("hAngle",";#Delta#theta (#circ);#Delta#phi (#circ}",20,-60,60,20,-360,360);
  TH2F *hAngleBack = new TH2F("hAngleBack",";#Delta#theta (#circ);#Delta#phi (#circ}",20,-60,60,20,-360,360);

  TProfile *hModulation = new  TProfile("hModulation","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulation2 = new  TProfile("hModulation2","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulationAv = new  TProfile("hModulationAv","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulationAvCorr = new  TProfile("hModulationAvCorr","#theta^{rel} < 10#circ;#phi - #alpha;diff (ns)",50,0,360);

  TH1F *hnsigpeak = new TH1F("hnsigpeak","",50,0,360);
  TH1F *hnbackpeak = new TH1F("hnbackpeak","",50,0,360);

  TProfile *hSinTheta = new  TProfile("hSinTheta",";#phi - #alpha;sin(#theta)",50,0,360);
  TProfile *hSinTheta2 = new  TProfile("hSinTheta2",";#phi - #alpha;sin(#theta)",50,0,360);

  TH1F *hRunCut[2];
  hRunCut[0] = new TH1F("hRunCut1","Reason for Run Rejection Tel-1;Reason;runs rejected",11,0,11);
  hRunCut[1] = new TH1F("hRunCut2","Reason for Run Rejection Tel-2;Reason;runs rejected",11,0,11);

  for(Int_t i=0;i<2;i++){
    hRunCut[i]->Fill("DateRange",0);
    hRunCut[i]->Fill("LowFractionGT",0);
    hRunCut[i]->Fill("TimeDuration",0);
    hRunCut[i]->Fill("rateGT",0);
    hRunCut[i]->Fill("RunNumber",0);
    hRunCut[i]->Fill("MissingHitFrac",0);
    hRunCut[i]->Fill("DeadStripBot",0);
    hRunCut[i]->Fill("DeadStripMid",0);
    hRunCut[i]->Fill("DeadStripTop",0);
    hRunCut[i]->Fill("NSatellites",0);
    hRunCut[i]->Fill("NoGoodWeather",0);  
  }

  TFile *f = new TFile(fileIn);
  TTree *t = (TTree *) f->Get("tree");
  
  TTree *tel[2];
  tel[0] = (TTree *) f->Get("treeTel1");
  tel[1] = (TTree *) f->Get("treeTel2");

  TTree *telC = (TTree *) f->Get("treeTimeCommon");
  
  // quality info of runs
  const Int_t nyearmax = 5;
  Bool_t runstatus[2][nyearmax][12][31][500]; //#telescope, year-2014, month, day, run
  Float_t effTel[2][nyearmax][12][31][500];
  Int_t nStripDeadBot[2][nyearmax][12][31][500];
  Int_t nStripDeadMid[2][nyearmax][12][31][500];
  Int_t nStripDeadTop[2][nyearmax][12][31][500];

  Float_t nstripDeadB[2]={0,0},nstripDeadM[2]={0,0},nstripDeadT[2]={0,0};

  // sat info
  Float_t NsatAv[2][nyearmax][12][31][500];

  // weather info
  Float_t pressureTel[2][nyearmax][12][31][500];
  Float_t TempInTel[2][nyearmax][12][31][500];
  Float_t TempOutTel[2][nyearmax][12][31][500];
  Float_t timeWeath[2][nyearmax][12][31][500];

  Float_t rateGT;

  Float_t phirelative;
  Float_t phirelative2;
  Float_t phirelativeAv;

  printf("Check Run quality\n");

  if(tel[0] && tel[1]){
    for(Int_t i=0;i < 2;i++){ // loop on telescopes
      printf("Tel-%i\n",i+1);
      for(Int_t j=0;j < tel[i]->GetEntries();j++){ // loop on runs
	tel[i]->GetEvent(j);
	rateGT = tel[i]->GetLeaf("FractionGoodTrack")->GetValue()*tel[i]->GetLeaf("rateHitPerRun")->GetValue();

	Int_t aday = (tel[i]->GetLeaf("year")->GetValue()-2014) * 1000 + tel[i]->GetLeaf("month")->GetValue()*50 + tel[i]->GetLeaf("day")->GetValue();

        if(i==1) printf("%f %f\n",rateGT , rateMin[i]);

	if(aday < adayMin || aday > adayMax){
	  hRunCut[i]->Fill("DateRange",1); continue;}
	if(tel[i]->GetLeaf("FractionGoodTrack")->GetValue() < fracGT[i]){
	  hRunCut[i]->Fill("LowFractionGT",1); continue;} // cut on fraction of good track
	if(tel[i]->GetLeaf("timeduration")->GetValue()*tel[i]->GetLeaf("rateHitPerRun")->GetValue() < hitevents[i]){
	  hRunCut[i]->Fill("TimeDuration",1); continue;} // cut on the number of event
	if(rateGT < rateMin[i] || rateGT > rateMax[i]){
	  hRunCut[i]->Fill("rateGT",1); continue;} // cut on the rate
	if(tel[i]->GetLeaf("run")->GetValue() > 499){
	  hRunCut[i]->Fill("RunNumber",1); continue;} // run < 500

        if(i==1) printf("GR\n");

	Float_t missinghitfrac = (tel[i]->GetLeaf("ratePerRun")->GetValue()-tel[i]->GetLeaf("rateHitPerRun")->GetValue()-2)/(tel[i]->GetLeaf("ratePerRun")->GetValue()-2);
	if(missinghitfrac < minmissingHitFrac[i] || missinghitfrac > maxmissingHitFrac[i]){
	  hRunCut[i]->Fill("MissingHitFrac",1); continue;}
		
	// active strip maps
	if(tel[i]->GetLeaf("maskB")) nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskB")->GetValue()));
	if(tel[i]->GetLeaf("maskM")) nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskM")->GetValue()));
	if(tel[i]->GetLeaf("maskT")) nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskT")->GetValue()));

	if(nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadBotMax[i] || nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadBotMin[i]) {
	  hRunCut[i]->Fill("DeadStripBot",1); continue;}
	if(nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadMidMax[i] || nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadMidMin[i]){
	  hRunCut[i]->Fill("DeadStripMid",1); continue;}
	if(nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadTopMax[i] || nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadTopMin[i]){
	  hRunCut[i]->Fill("DeadStripTop",1); continue;}
     
	// nsat averaged  per run
	if(tel[i]->GetLeaf("nSat")) NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("nSat")->GetValue();


	if(NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < minAvSat[i] || NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > maxAvSat[i]){
	 hRunCut[i]->Fill("NSatellites",1); continue;}

	// weather info
	if(tel[i]->GetLeaf("Pressure")) pressureTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("Pressure")->GetValue();
	if(tel[i]->GetLeaf("IndoorTemperature")) TempInTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("IndoorTemperature")->GetValue();
	if(tel[i]->GetLeaf("OutdoorTemperature")) TempOutTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("OutdoorTemperature")->GetValue();
	if(tel[i]->GetLeaf("TimeWeatherUpdate")) timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("TimeWeatherUpdate")->GetValue();

	if(timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < minWeathTimeDelay[i] ||  timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > maxWeathTimeDelay[i]){ hRunCut[i]->Fill("NoGoodWeather",1); continue;	}

	// Set good runs
	runstatus[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = kTRUE;
	effTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = 1;//rateGT/refRate[i];

      }
    }
  }
  else{
    telC = NULL;
  }

  printf("Start to process correlations\n");
  Int_t n = t->GetEntries();
  // counter for seconds
  Int_t nsec = 0;
  Int_t nsecGR = 0; // for good runs
  Int_t isec = -1; // used only in case the tree with time info is not available

  Float_t neventsGR = 0;
  Float_t neventsGRandSat = 0;

  if(telC){
    for(Int_t i=0; i < telC->GetEntries();i++){
      telC->GetEvent(i);
      nsec += telC->GetLeaf("timeduration")->GetValue(); 
      
      
      
      if(telC->GetLeaf("run")->GetValue() > 499 || telC->GetLeaf("run2")->GetValue() > 499) continue;
      
      if(!runstatus[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())]) continue;
      
      if(!runstatus[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run2")->GetValue())]) continue;
      
      nsecGR += telC->GetLeaf("timeduration")->GetValue(); 
      nstripDeadB[0] += countBits(nStripDeadBot[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadM[0] += countBits(nStripDeadMid[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadT[0] += countBits(nStripDeadTop[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();

      nstripDeadB[1] += countBits(nStripDeadBot[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadM[1] += countBits(nStripDeadMid[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadT[1] += countBits(nStripDeadTop[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
    }
    nstripDeadB[0] /= nsecGR;
    nstripDeadM[0] /= nsecGR;
    nstripDeadT[0] /= nsecGR;

    nstripDeadB[1] /= nsecGR;
    nstripDeadM[1] /= nsecGR;
    nstripDeadT[1] /= nsecGR;

    printf("Dead channel tel1 = %f - %f - %f\n",nstripDeadB[0],nstripDeadM[0],nstripDeadT[0]);
    printf("Dead channel tel2 = %f - %f - %f\n",nstripDeadB[1],nstripDeadM[1],nstripDeadT[1]);
  }
  
  char title[300];
  TH1F *h;
  
  sprintf(title,"correction assuming #Delta#phi = %4.2f, #DeltaL = %.1f m;#Deltat (ns);entries",angle,distance);
  
  h = new TH1F("hCoinc",title,nbint,tmin,tmax);
  
  Float_t DeltaT;
  Float_t phiAv,thetaAv,corr;
  
  Float_t Theta1,Theta2;
  Float_t Phi1,Phi2;
  Int_t nsatel1cur,nsatel2cur,ntrack1,ntrack2;

  Float_t v1[3],v2[3],vSP; // variable to recompute ThetaRel on the fly
  Float_t eff = 1; 
  
  for(Int_t i=0;i<n;i++){
    t->GetEvent(i);
    
    if(t->GetLeaf("RunNumber1") && (t->GetLeaf("RunNumber1")->GetValue() > 499 || t->GetLeaf("RunNumber2")->GetValue() > 499)) continue;
  
    if(tel[0] && !runstatus[0][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber1")->GetValue())]) continue;
    
    if(tel[1] && !runstatus[1][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())]) continue;


    eff = effTel[0][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber1")->GetValue())];
    eff *= effTel[1][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())];
    
    Int_t timec = t->GetLeaf("ctime1")->GetValue();
    
    if(! telC){
      if(isec == -1) isec = timec;
      
      if(timec != isec){
	if(timec - isec < 20){
	  //	printf("diff = %i\n",timec-isec);
	  nsec +=(timec - isec);
	  nsecGR +=(timec - isec);
	}
	isec = timec;
    }
    }

    Float_t thetarel = t->GetLeaf("ThetaRel")->GetValue();
    Theta1 = (t->GetLeaf("Theta1")->GetValue())*TMath::DegToRad();
    Theta2 = t->GetLeaf("Theta2")->GetValue()*TMath::DegToRad();
    Phi1 = t->GetLeaf("Phi1")->GetValue()*TMath::DegToRad();
    Phi2 = t->GetLeaf("Phi2")->GetValue()*TMath::DegToRad();
    
    nsatel1cur = t->GetLeaf("Nsatellite1")->GetValue();
    nsatel2cur = t->GetLeaf("Nsatellite2")->GetValue();
    ntrack1 = t->GetLeaf("Ntracks1")->GetValue();
    ntrack2 = t->GetLeaf("Ntracks2")->GetValue();

    if(recomputeThetaRel){ // recompute ThetaRel applying corrections
      Phi1 += phi1Corr*TMath::DegToRad();
      Phi2 += phi2Corr*TMath::DegToRad();
      if(Phi1 > 2*TMath::Pi()) Phi1 -= 2*TMath::Pi();
      if(Phi1 < 0) Phi1 += 2*TMath::Pi();
      if(Phi2 > 2*TMath::Pi()) Phi2 -= 2*TMath::Pi();
      if(Phi2 < 0) Phi2 += 2*TMath::Pi();
      
      v1[0] = TMath::Sin(Theta1)*TMath::Cos(Phi1);
      v1[1] = TMath::Sin(Theta1)*TMath::Sin(Phi1);
      v1[2] = TMath::Cos(Theta1);
      v2[0] = TMath::Sin(Theta2)*TMath::Cos(Phi2);
      v2[1] = TMath::Sin(Theta2)*TMath::Sin(Phi2);
      v2[2] = TMath::Cos(Theta2);
      
      v1[0] *= v2[0];
      v1[1] *= v2[1];
      v1[2] *= v2[2];
      
      vSP = v1[0] + v1[1] + v1[2];
      
      thetarel = TMath::ACos(vSP)*TMath::RadToDeg();
    }
    
    // cuts
    if(thetarel < minthetarel) continue;
    if(thetarel > maxthetarel) continue;
    if(t->GetLeaf("ChiSquare1")->GetValue() > maxchisquare) continue;
    if(t->GetLeaf("ChiSquare2")->GetValue() > maxchisquare) continue;
    

    neventsGR++;

    // reject events with not enough satellites
    if(nsatel1cur < satEventThr || nsatel1cur < satEventThr) continue;

    neventsGRandSat++;
    
    DeltaT = t->GetLeaf("DiffTime")->GetValue();
    
    // get primary direction
    if(TMath::Abs(Phi1-Phi2) < TMath::Pi()) phiAv = (Phi1+Phi2)*0.5;
    else phiAv = (Phi1+Phi2)*0.5 + TMath::Pi();

    thetaAv = (Theta1+Theta2)*0.5;
    
    // extra cuts if needed
    //    if(TMath::Cos(Phi1-Phi2) < 0.) continue;
    
    Float_t resFactor = 1;
    if(thetarel > 10 ) resFactor *= 0.5;
    if(thetarel > 20 ) resFactor *= 0.5;
    if(thetarel > 30 ) resFactor *= 0.5;

    corr = distance * TMath::Sin(thetaAv)*TMath::Cos(phiAv-angle)/2.99792458000000039e-01 + deltatCorr;

    phirelative = (Phi1-angle)*TMath::RadToDeg();
    if(phirelative < 0) phirelative += 360;
    if(phirelative < 0) phirelative += 360;
    if(phirelative > 360) phirelative -= 360;
    if(phirelative > 360) phirelative -= 360;

    phirelative2 = (Phi2-angle)*TMath::RadToDeg();
    if(phirelative2 < 0) phirelative2 += 360;
    if(phirelative2 < 0) phirelative2 += 360;
    if(phirelative2 > 360) phirelative2 -= 360;
    if(phirelative2 > 360) phirelative2 -= 360;

    phirelativeAv = (phiAv-angle)*TMath::RadToDeg();
    if(phirelativeAv < 0) phirelativeAv += 360;
    if(phirelativeAv < 0) phirelativeAv += 360;
    if(phirelativeAv > 360) phirelativeAv -= 360;
    if(phirelativeAv > 360) phirelativeAv -= 360;


    // if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment){
      
    // }

    if(thetarel < 10){//cos(thetarel*TMath::DegToRad())>0.98 && sin(thetaAv)>0.1){
      if(TMath::Abs(DeltaT- corr) < windowAlignment)
	hModulationAvCorr->Fill(phirelativeAv,DeltaT-corr);
      if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment){
	hModulation->Fill(phirelative,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hModulation2->Fill(phirelative2,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hModulationAv->Fill(phirelativeAv,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hSinTheta->Fill(phirelative,sin(thetaAv));
	hSinTheta2->Fill(phirelative2,sin(thetaAv));
	nsigPeak++;
	hnsigpeak->Fill(phirelativeAv);
      }
      else if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment*10){
	nbackPeak++;
	hnbackpeak->Fill(phirelativeAv);
      }
    }

    h->Fill(DeltaT-corr,1./eff);
    if(TMath::Abs(DeltaT-corr) < windowAlignment){
      hDeltaTheta->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhi->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRel->Fill(thetarel);
      hAngle->Fill((Theta1-Theta2)*TMath::RadToDeg(),(Phi1-Phi2)*TMath::RadToDeg());
    }
    else if(TMath::Abs(DeltaT-corr) > windowAlignment*2 && TMath::Abs(DeltaT-corr) < windowAlignment*12){
      hDeltaThetaBack->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhiBack->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRelBack->Fill(thetarel);
      hAngleBack->Fill((Theta1-Theta2)*TMath::RadToDeg(),(Phi1-Phi2)*TMath::RadToDeg());
    }
  }
  
  // compute (S+B)/S
  for(Int_t i=1;i<=50;i++){
    Float_t corrfactorPeak = 1;
    if(nsigPeak-nbackPeak*0.1 > 0)
      corrfactorPeak = hnsigpeak->GetBinContent(i)/(hnsigpeak->GetBinContent(i)-hnbackpeak->GetBinContent(i)*0.1);
    else
      printf("bin %i) not enough statistics\n",i);
    hnsigpeak->SetBinContent(i,corrfactorPeak);
  }

  TF1 *fpol0 = new TF1("fpol0","pol0");
  hnsigpeak->Fit(fpol0);

  hModulation->Scale(fpol0->GetParameter(0));
  hModulation2->Scale(fpol0->GetParameter(0));
  hModulationAv->Scale(fpol0->GetParameter(0));
  hModulationAvCorr->Scale(fpol0->GetParameter(0));
  
  TF1 *fmod = new TF1("fmod","[0] + [1]*cos((x-[2])*TMath::DegToRad())"); 
  hModulationAv->Fit(fmod); 

  printf("Estimates from time delay: Distance = %f +/- %f m -- Angle = %f +/- %f deg\n",fmod->GetParameter(1),fmod->GetParError(1),fmod->GetParameter(2),fmod->GetParError(2));

  h->SetStats(0);

  hDeltaThetaBack->Sumw2();
  hDeltaPhiBack->Sumw2();
  hThetaRelBack->Sumw2();
  hDeltaThetaBack->Scale(0.1);
  hDeltaPhiBack->Scale(0.1);
  hThetaRelBack->Scale(0.1);
  hAngleBack->Scale(0.1);
  hAngle->Add(hAngleBack,-1);

  printf("bin counting: SIGNAL = %f +/- %f\n",hDeltaPhi->Integral()-hDeltaPhiBack->Integral(),sqrt(hDeltaPhi->Integral()));
  rate = (hDeltaPhi->Integral()-hDeltaPhiBack->Integral())/nsecGR*86400;
  rateErr = sqrt(hDeltaPhi->Integral())/nsecGR*86400;


  Float_t val,eval;
  TCanvas *c1=new TCanvas();
  TF1 *ff = new TF1("ff","[0]*[4]/[2]/sqrt(2*TMath::Pi())*TMath::Exp(-(x-[1])*(x-[1])*0.5/[2]/[2]) + [3]*[4]/6/[2]");
  ff->SetParName(0,"signal");
  ff->SetParName(1,"mean");
  ff->SetParName(2,"sigma");
  ff->SetParName(3,"background");
  ff->SetParName(4,"bin width");
  ff->SetParameter(0,42369);
  ff->SetParameter(1,0);
  ff->SetParLimits(2,10,maxwidth);
  ff->SetParameter(2,350); // fix witdh if needed
  ff->SetParameter(3,319);
  ff->FixParameter(4,(tmax-tmin)/nbint); // bin width

  ff->SetNpx(1000);
  
  if(cout) cout->cd();
  h->Fit(ff,"EI","",-10000,10000);
  
  val = ff->GetParameter(2);
  eval = ff->GetParError(2);
  
  printf("significance = %f\n",ff->GetParameter(0)/sqrt(ff->GetParameter(0) + ff->GetParameter(3)));

  h->Draw();
  
  new TCanvas;

  TF1 *func1 = (TF1 *)  h->GetListOfFunctions()->At(0);
  
  func1->SetLineColor(2);
  h->SetLineColor(4);
  
  TPaveText *text = new TPaveText(1500,(h->GetMinimum()+(h->GetMaximum()-h->GetMinimum())*0.6),9500,h->GetMaximum());
  text->SetFillColor(0);
  sprintf(title,"width = %5.1f #pm %5.1f",func1->GetParameter(2),func1->GetParError(2));
  text->AddText(title);
  sprintf(title,"signal (S) = %5.1f #pm %5.1f",func1->GetParameter(0),func1->GetParError(0));
  text->AddText(title);
  sprintf(title,"background (B) (3#sigma) = %5.1f #pm %5.1f",func1->GetParameter(3),func1->GetParError(3));
  text->AddText(title);
  sprintf(title,"significance (S/#sqrt{S+B}) = %5.1f",func1->GetParameter(0)/sqrt(func1->GetParameter(0)+func1->GetParameter(3)));
  text->AddText(title);
  
  text->SetFillStyle(0);
  text->SetBorderSize(0);
  
  text->Draw("SAME");
  
  // correct nsecGR for the event rejected because of the number of satellites (event by event cut)
  nsecGR *= neventsGRandSat/neventsGR;

  printf("n_day = %f\nn_dayGR = %f\n",nsec*1./86400,nsecGR*1./86400);

  text->AddText(Form("rate = %f #pm %f per day",func1->GetParameter(0)*86400/nsecGR,func1->GetParError(0)*86400/nsecGR));

  TFile *fo = new TFile("outputCERN-01-02.root","RECREATE");
  h->Write();
  hDeltaTheta->Write();
  hDeltaPhi->Write();
  hThetaRel->Write();
  hDeltaThetaBack->Write();
  hDeltaPhiBack->Write();
  hThetaRelBack->Write();
  hAngle->Write();
  hModulation->Write();
  hModulation2->Write();
  hModulationAv->Write();
  hModulationAvCorr->Write();
  hSinTheta->Write();
  hSinTheta2->Write();
  hnsigpeak->Write();
  hRunCut[0]->Write();
  hRunCut[1]->Write();
  fo->Close();

  return nsecGR*1./86400;
  
}
void plotDavid(TH1F* bkgT, TH1F* sigT, TH1F* dataT, std::string name){
  
  gROOT->SetBatch();
  system("mkdir -p plots/ada/david");
  system("mkdir -p plots/grad/david");
  system("mkdir -p plots/ada/diff");
  system("mkdir -p plots/grad/diff");

  std::string bdt;
  TString str = dataT->GetName();
  if (str.Contains("ada")) bdt="ada";
  else if (str.Contains("grad")) bdt="grad";
  else std::cout << "Error find BDT type" << std::endl;
  assert (str.Contains("ada") || str.Contains("grad"));

  if (bkgT->GetNbinsX() != sigT->GetNbinsX() || sigT->GetNbinsX() != dataT->GetNbinsX()) std::cout << "Plot problem: calling plot for histograms with different number of bins" << std::endl;
  assert(bkgT->GetNbinsX() == sigT->GetNbinsX() || sigT->GetNbinsX() == dataT->GetNbinsX());
  
  TH1F *bkg = linearBin(bkgT);
  TH1F *sig2 = linearBin(sigT);
  TH1F *sig5 = (TH1F*)sig2->Clone();
  TH1F *sig10 = (TH1F*)sig2->Clone();
  TH1F *data = linearBin(dataT);
  TH1F *diff = (TH1F*)data->Clone();
  diff->Add(bkg,-1);

  gStyle->SetOptStat(0);
  gROOT->SetStyle("Plain");
  gROOT->ForceStyle();

  TCanvas *canv = new TCanvas();
  bkg->SetLineColor(kBlue);
  bkg->SetFillColor(kBlue-9);
  sig2->SetLineColor(kRed);
  sig2->SetLineStyle(3);
  sig2->Scale(1.);
  sig5->SetLineColor(kRed);
  sig5->SetLineStyle(7);
  sig5->Scale(3.);
  sig10->SetLineColor(kRed);
  sig10->Scale(5.);
  data->SetMarkerStyle(20);
  bkg->SetTitle(("Background, data and signal distributions for "+bdt+" "+name).c_str());
  sig2->SetTitle(("Background, data and signal distributions for "+bdt+" "+name).c_str());
  data->SetTitle(("Background, data and signal distributions for "+bdt+" "+name).c_str());
  bkg->GetXaxis()->SetTitle("");
  sig2->GetXaxis()->SetTitle("");
  data->GetXaxis()->SetTitle("");
  bkg->GetYaxis()->SetTitle("Events");
  sig2->GetYaxis()->SetTitle("Events");
  data->GetYaxis()->SetTitle("Events");

  TLegend *leg = new TLegend(0.45,0.6,0.85,0.85);
  leg->SetLineColor(0);
  leg->SetFillColor(0);
  leg->AddEntry(bkg,"Background","f");
  leg->AddEntry(data,"Data","lep");
  leg->AddEntry(sig10,"Signal (1, 3, 5 #times SM)","l");
  TPaveText *txt = new TPaveText(0.2,0.1,0.4,0.35,"NDC");
  txt->SetFillColor(0);
  txt->SetLineColor(0);
  txt->AddText("#int L = 4.76 fb^{-1}");

  bkg->GetYaxis()->SetRangeUser(1.0,2.*(data->GetMaximum()));

  bkg->Draw("e2");
  sig2->Draw("same hist");
  sig5->Draw("same hist");
  sig10->Draw("same hist");
  data->Draw("same e");
  leg->Draw("same");
  txt->Draw("same");

  canv->SetLogy();
  canv->Print(("plots/"+bdt+"/david/"+name+".png").c_str(),"png");
  canv->SetLogy(false);
  canv->Clear();
  TLegend *leg2 = new TLegend(0.45,0.6,0.85,0.85);
  leg2->SetFillColor(0);
  leg2->SetLineColor(0);
  sig10->GetYaxis()->SetRangeUser((-1*sig10->GetMaximum())+10,sig10->GetMaximum()+20);
  sig10->GetXaxis()->SetTitle("");
  sig10->GetYaxis()->SetTitle("Events");
  sig10->SetTitle(Form("Data, background difference compared to signal %s %s",bdt.c_str(),name.c_str()));
  diff->SetMarkerStyle(20);
  diff->GetXaxis()->SetTitle("");
  diff->GetYaxis()->SetTitle("Events");
  leg2->AddEntry(diff,"Data - background model","lep");
  leg2->AddEntry(sig10,"Signal (1, 3, 5 #times SM)","l");
  TF1 *line = new TF1("line","0.0",0.0,sig10->GetNbinsX()+1);
  line->SetLineColor(kBlue);
  sig10->Draw("hist");
  sig5->Draw("same hist");
  sig2->Draw("same hist");
  line->Draw("same");
  diff->Draw("p same");
  leg2->Draw("same");
  txt->Draw("same");
  canv->Print(("plots/"+bdt+"/diff/"+name+".png").c_str(),"png");

  delete canv;
  delete txt;
  delete leg;
  
  davidCalls++;
}
Beispiel #21
0
//void fitD(TString collsyst="PbPb",TString nominalcut="", TString varname_="", Int_t varbins=10, Float_t varmin=0.5, Float_t varmax=2,TString vartex_="", Int_t isLarger_=1, TString npfile="ROOTfiles/NPFitPP.root", TString outputfile="outfMasshisto/mass")
void fitD(TString collsyst="PbPb",TString nominalcut="", TString varname_="", Int_t varbins=10, Float_t varmin=0.5, Float_t varmax=2,TString vartex_="", Int_t isLarger_=1, TString npfit="0", TString outputfile="outfMasshisto/mass")
{
  _nominalcut = nominalcut;
  gStyle->SetTextSize(0.05);
  gStyle->SetTextFont(42);
  gStyle->SetPadRightMargin(0.043);
  gStyle->SetPadLeftMargin(0.18);
  gStyle->SetPadTopMargin(0.1);
  gStyle->SetPadBottomMargin(0.145);
  gStyle->SetTitleX(.0f);
  gStyle->SetOptStat(0);
  gStyle->SetMarkerStyle(20);
  gStyle->SetMarkerSize(0.8);

  collisionsystem = collsyst;
  infname = outputfile;
  varname=varname_;
  vartex=vartex_;
  isLarger=isLarger_;

  //TF1* fit(Float_t varval, Float_t ibin, Int_t isMC, float NPpar[]);
  TF1* fit(Float_t varval, Float_t ibin, Int_t isMC, TString npfit);
  //void getNPFnPar(TString npfname, float par[]);
  //float NPpar[2];
  //getNPFnPar(npfile, NPpar);
  //std::cout<<"NP parameter 0: "<<NPpar[0]<<std::endl;
  //std::cout<<"NP parameter 1: "<<NPpar[1]<<std::endl;
  
  Float_t varstep;
  if(varbins==1) varstep = 0.5;
  else varstep = (varmax-varmin)/(varbins-1);
  TH1F* hMCCut = new TH1F("hMCCut","",varbins,varmin,varmax+varstep);
  TH1F* hMCNoCut = new TH1F("hMCNoCut","",varbins,varmin,varmax+varstep);
  TH1F* hDaCut = new TH1F("hDaCut","",varbins,varmin,varmax+varstep);
  TH1F* hDaNoCut = new TH1F("hDaNoCut","",varbins,varmin,varmax+varstep);
  for(float i=0;i<varbins+1;i++)
    {
      Float_t yield,yieldErr;
      Float_t ivar = varmin+(i-1)*varstep;
      //TF1* fMC = fit(ivar,i,1, NPpar);
      TF1* fMC = fit(ivar,i,1, npfit);
      yield = fMC->Integral(minhisto,maxhisto)/binwidthmass;
      yieldErr = fMC->Integral(minhisto,maxhisto)/binwidthmass*fMC->GetParError(0)/fMC->GetParameter(0);
      if(i==0)
        {
          for(int j=0;j<varbins;j++)
            {
              hMCNoCut->SetBinContent(j+1,yield);
              hMCNoCut->SetBinError(j+1,yieldErr);
            }
        }
      else
        {
          hMCCut->SetBinContent(i,yield);
          hMCCut->SetBinError(i,yieldErr);
        }
      //TF1* fDa = fit(ivar,i,0, NPpar);
      TF1* fDa = fit(ivar,i,0, npfit);
      yield = fDa->Integral(minhisto,maxhisto)/binwidthmass;
      yieldErr = fDa->Integral(minhisto,maxhisto)/binwidthmass*fDa->GetParError(0)/fDa->GetParameter(0);
      if(i==0)
        {
          for(int j=0;j<varbins;j++)
            {
              hDaNoCut->SetBinContent(j+1,yield);
              hDaNoCut->SetBinError(j+1,yieldErr);
            }
        }
      else
        {
          hDaCut->SetBinContent(i,yield);
          hDaCut->SetBinError(i,yieldErr);
        }
    }

  TCanvas* cMCRatio = new TCanvas("cMCRatio","",600,600);
  TH1F* hMCRatio = (TH1F*)hMCCut->Clone("hMCRatio");
  hMCRatio->SetTitle(Form(";%s;hMCRatio",vartex.Data()));
  hMCRatio->Divide(hMCNoCut);
  hMCRatio->Draw();

  TCanvas* cDaRatio = new TCanvas("cDaRatio","",600,600);
  TH1F* hDaRatio = (TH1F*)hDaCut->Clone("hDaRatio");
  hDaRatio->SetTitle(Form(";%s;hDaRatio",vartex.Data()));
  hDaRatio->Divide(hDaNoCut);
  hDaRatio->Draw();

  TCanvas* chDoubleRatio = new TCanvas("chDoubleRatio","",600,600);
  TH1F* hDoubleRatio = (TH1F*)hDaRatio->Clone("hDoubleRatio");
  hDoubleRatio->SetTitle(Form(";%s;hDoubleRatio",vartex.Data()));
  hDoubleRatio->Divide(hMCRatio);
  hDoubleRatio->Draw();

  Float_t aDoubleRatio[varbins],aDoubleRatioErr[varbins],aX[varbins],aZero[varbins];
  Float_t AbsMax = max(fabs(hDoubleRatio->GetMaximum()-1), fabs(hDoubleRatio->GetMinimum()-1));
  for(int i=0;i<varbins;i++)
    {
      aDoubleRatio[i] = hDoubleRatio->GetBinContent(i+1);
      aDoubleRatioErr[i] = hDoubleRatio->GetBinError(i+1);
      aX[i] = varmin+i*varstep;
      aZero[i] = 0;
    }
  TGraphErrors* gDoubleRatio = new TGraphErrors(varbins,aX,aDoubleRatio,aZero,aDoubleRatioErr);
  TH2F* hemptyDoubleRatio = new TH2F("hemptyDoubleRatio","",20,varmin-0.5*varstep,varmax+0.5*varstep,10.,0.,2.);
  hemptyDoubleRatio->GetXaxis()->SetTitle(Form("%s",vartex.Data()));
  hemptyDoubleRatio->GetYaxis()->SetTitle("(Yield^{Data}_{Cuts}/Yield^{Data}_{NoCuts})/(Yield^{MC}_{Cuts}/Yield^{MC}_{NoCuts})");
  hemptyDoubleRatio->GetXaxis()->SetTitleOffset(1.);
  hemptyDoubleRatio->GetYaxis()->SetTitleOffset(1.4);
  hemptyDoubleRatio->GetXaxis()->SetTitleSize(0.045);
  hemptyDoubleRatio->GetYaxis()->SetTitleSize(0.045);
  hemptyDoubleRatio->GetXaxis()->SetTitleFont(42);
  hemptyDoubleRatio->GetYaxis()->SetTitleFont(42);
  hemptyDoubleRatio->GetXaxis()->SetLabelFont(42);
  hemptyDoubleRatio->GetYaxis()->SetLabelFont(42);
  hemptyDoubleRatio->GetXaxis()->SetLabelSize(0.04);
  hemptyDoubleRatio->GetYaxis()->SetLabelSize(0.04);
  TLine* lDoubleRatio = new TLine(varmin-0.5*varstep, 1., varmax+0.5*varstep, 1.);
  lDoubleRatio->SetLineWidth(1);
  lDoubleRatio->SetLineStyle(7);
  lDoubleRatio->SetLineColor(1);
  TLatex* texCms = new TLatex(0.18,0.93, "#scale[1.25]{CMS} Preliminary");
  texCms->SetNDC();
  texCms->SetTextAlign(12);
  texCms->SetTextSize(0.04);
  texCms->SetTextFont(42);
  TLatex* texCol = new TLatex(0.96,0.93, Form("%s #sqrt{s_{NN}} = 5.02 TeV",collisionsystem.Data()));
  texCol->SetNDC();
  texCol->SetTextAlign(32);
  texCol->SetTextSize(0.04);
  texCol->SetTextFont(42);
  TCanvas* cDoubleRatio = new TCanvas("cDoubleRatio","",600,600);
  hemptyDoubleRatio->Draw();
  gDoubleRatio->Draw("psame");
  lDoubleRatio->Draw();
  texCms->Draw();
  texCol->Draw();
  TLatex* texAbsMax = new TLatex(0.88,0.85, Form("max diff: %.3f",AbsMax));
  texAbsMax->SetNDC();
  texAbsMax->SetTextAlign(32);
  texAbsMax->SetTextSize(0.04);
  texAbsMax->SetTextFont(42);
  texAbsMax->Draw();
	
  cDoubleRatio->SaveAs(Form("plotRatios/%s_%s_DoubleRatio.pdf",collisionsystem.Data(),varname.Data()));

  TFile* outf = new TFile(Form("outfDoubleratio/f%s_%s_DoubleRatio.root",collisionsystem.Data(),varname.Data()),"recreate");
  outf->cd();
  hDoubleRatio->Write();
  outf->Close();
}
Beispiel #22
0
int main(int argc, char *argv[]) {

  // make sure command line arguments were supplied
  if (argc != 6) { cerr << "Usage: " << argv[0] << " [reference.root] [new-comparison.root] [root dir] [new-release] [old-release] \n"; return 1; }

  // create the comparison class
  PlotCompareUtility *pc = new PlotCompareUtility(argv[1],argv[2],argv[3],"METTask_");
  HistoData *hd;

  if (pc->GetStatus() != 0) { cout << "Final Result: no_data" << endl; return 0; }

  // add histogram information
  //Type = 0 (Do not rebin or zoom) , 1 (Rebin and Zoom, x-axis > 0 ) , 2 (Rebin and Zoom)
  hd = pc->AddHistoData("MET"); hd->SetType(1);
  hd = pc->AddHistoData("METPhi"); hd->SetType(2);
  hd = pc->AddHistoData("METSig"); hd->SetType(1);
  hd = pc->AddHistoData("MEx"); hd->SetType(2);
  hd = pc->AddHistoData("MEy"); hd->SetType(2);
  hd = pc->AddHistoData("SumET"); hd->SetType(2);

  if (pc->GetStatus() != 0) { cerr << "error encountered, exiting.\n"; return pc->GetStatus(); }

  int num_histos = pc->GetNumHistos();
  bool combinedFailed = false;
  float threshold = KS_TEST ?  pc->GetKSThreshold() : pc->GetChi2Threshold(); 

    // get the reference and comparison histograms
  int Nevents_ref = ((TH1F *)pc->GetRefHisto("Nevents"))->GetEntries();
  int Nevents_new = ((TH1F *)pc->GetNewHisto("Nevents"))->GetEntries();
  int Nevents = -1;
  if (Nevents_ref>Nevents_new) Nevents = Nevents_ref;
  else Nevents = Nevents_new;

  // create summary histograms
  TH1F h1dResults_passed("h1dResults_passed","",num_histos, 1, num_histos + 1);
  TH1F h1dResults_failed("h1dResults_failed","",num_histos, 1, num_histos + 1);

  // loop over the supplied list of histograms for comparison
  for (int index = 0; index < pc->GetNumHistos(); index++) {

    int number = index + 1;
    hd = pc->GetHistoData(number);
    //int type = hd->GetType();
    //types[index] = type;
    string name = hd->GetName();
    //string value = hd->GetValueX();
    cout << name << endl;

    // get the reference and comparison histograms
    TH1F *href = (TH1F *)pc->GetRefHisto(name);
    TH1F *hnew = (TH1F *)pc->GetNewHisto(name);


    // ignore if histogram is empty
    if (hnew->GetEntries() <= 1 || href->GetEntries() <= 1) {
      cerr << name << " error: no entries"; combinedFailed = true; continue;
    }

    // calculate and set range and number of bins
    double h1RMS =  hnew->GetRMS();
    double h2RMS =  href->GetRMS();
    double RMS = TMath::Max(h1RMS, h2RMS);
    double h1Mean =  hnew->GetMean();
    double h2Mean =  href->GetMean();
    double Mean = 0.5 * (h1Mean + h2Mean);
    double Nbins = href->GetNbinsX();
    double min = href->GetXaxis()->GetXmin();
    double max = href->GetXaxis()->GetXmax();
    double dX = max - min;
    double dNdX = 1;
    double NewMin = min;
    double NewMax = max;

    int rebinning = Nbins; 

    if (RMS>0 && hd->GetType() ) 
      {
	dNdX = 100. / ( 10 * RMS);
	NewMin = Mean - 10 * RMS;
	NewMax = Mean + 10 * RMS;
      }
    
    if ((dX * dNdX)>0  && hd->GetType() ) 
      rebinning = (int)(double(Nbins) / (dX * dNdX));
    
    if ( rebinning > 1 && hd->GetType() ) 
      {
	href->Rebin(rebinning);
	hnew->Rebin(rebinning);
      }

    if ( hd->GetType() == 1 )
      { 
	href->GetXaxis()->SetRangeUser(0.0, NewMax);
	hnew->GetXaxis()->SetRangeUser(0.0, NewMax);
      }
    else if ( hd->GetType() == 2 )
      {
	href->GetXaxis()->SetRangeUser(NewMin, NewMax);
	hnew->GetXaxis()->SetRangeUser(NewMin, NewMax);
      }

    // perform statistical tests
    double ks_score = hnew->KolmogorovTest(href,"D");
    double chi2_score = hnew->Chi2Test(href, "p");
    //double result = KS_TEST ? ks_score : chi2_score;
    double result = (ks_score>chi2_score) ? ks_score : chi2_score;
    
      href->SetNormFactor(Nevents_new);     	
      hnew->SetNormFactor(Nevents_new);
    //hnew->SetNormFactor(1);

    // ensure that the peaks of both histograms will be shown by making a dummy histogram
    float Nentries_ref = href->GetEntries();
    float Nentries_new = hnew->GetEntries();
    float XaxisMin_ref = 0, XaxisMax_ref = 0, YaxisMin_ref = 0, YaxisMax_ref = 0;
    float XaxisMin_new = 0, XaxisMax_new = 0, YaxisMin_new = 0, YaxisMax_new = 0;
    if (Nentries_ref>0) YaxisMax_ref = (href->GetMaximum()+TMath::Sqrt(href->GetMaximum()))*(Nentries_new/Nentries_ref);
    if (Nentries_new>0) YaxisMax_new = (hnew->GetMaximum()+TMath::Sqrt(hnew->GetMaximum()));

    XaxisMin_ref = href->GetXaxis()->GetXmin()>NewMin  ? href->GetXaxis()->GetXmin() : NewMin;
    XaxisMax_ref = href->GetXaxis()->GetXmax()<=NewMax ? href->GetXaxis()->GetXmax() : NewMax;
    YaxisMax_ref = (YaxisMax_ref>=YaxisMax_new) ? YaxisMax_ref : YaxisMax_new;

    if (TMath::Abs(XaxisMin_ref - XaxisMax_ref)<1E-6)
      {
	XaxisMin_ref = 0;
	XaxisMax_ref = 1;
      }
    
    TH1F *hdumb = new TH1F("hdumb","", rebinning, XaxisMin_ref, XaxisMax_ref);
    hdumb->SetMinimum(1E-1); //--For Rick
    hdumb->SetMaximum(1.05*YaxisMax_ref);
    //    if (href->GetMaximum() < hnew->GetMaximum())
    //  href->SetAxisRange(0, 1.1 * hnew->GetMaximum(), "Y");
        
    // set drawing options on the reference histogram
    href->SetStats(0);
    href->SetLineWidth(2);
    href->SetLineColor(14);
    href->SetMarkerColor(14);
    href->SetFillColor(17);
    //href->SetFillStyle(3004);
    href->GetXaxis()->SetTitle(name.c_str());
    href->GetYaxis()->SetTitle("Entries");
    href->GetYaxis()->SetTitleOffset(1.5);

    // set drawing options on the new histogram
    hnew->SetStats(0);
    hnew->SetLineWidth(2);
    hnew->SetFillStyle(3001);
    // set drawing options on the dummy histogram
    hdumb->SetStats(0);
    hdumb->GetXaxis()->SetTitle(name.c_str());
    hdumb->GetXaxis()->SetLabelSize(0.5 * hdumb->GetXaxis()->GetTitleSize());
    hdumb->GetYaxis()->SetTitle("Entries");
    hdumb->GetYaxis()->SetTitleOffset(1.5);
    hdumb->GetYaxis()->SetLabelSize(0.5 * hdumb->GetXaxis()->GetTitleSize());
    
    stringstream ss_title;
    ss_title.precision(5);
    if (ks_score>chi2_score)
      ss_title << "KS Score = " << ks_score;
    else
      ss_title << "Chi^2 Score = " << chi2_score;
    TText canvas_title(0.1,0.97,ss_title.str().c_str());


    // determine if test is a "pass" or a "fail"
    if (result <= threshold) {

      canvas_title.SetTextColor(kRed);

      // make this histogram red to denote failure
      hnew->SetFillColor(kRed);
      hnew->SetLineColor(206);
      hnew->SetMarkerColor(206);

      // mark the entire sample as being 'not-compatible'
      combinedFailed = true;

      // set the summary bin to failed (only need to set titles for passed h1dResults)
      h1dResults_passed.GetXaxis()->SetBinLabel(number, name.c_str());
      h1dResults_failed.SetBinContent(number, result);

    } else {

      canvas_title.SetTextColor(kGreen);

      // make this histogram green to denote passing score
      hnew->SetFillColor(kGreen);
      hnew->SetLineColor(103);  
      hnew->SetMarkerColor(103);

      // set the summary bin to passed
      h1dResults_passed.GetXaxis()->SetBinLabel(number, name.c_str());
      h1dResults_passed.SetBinContent(number, result);

    }

    // setup canvas for displaying the compared histograms
    TCanvas histo_c("histo_c","histo_c",785,800);
    histo_c.Draw();

    TPad histo_p("histo_p","histo_p",0,0,1,0.99);
    histo_p.Draw();

    histo_c.cd();
    canvas_title.SetTextSize(0.025);
    canvas_title.Draw();

    histo_p.cd();

    histo_p.SetLogy(1); //--This is just for Dr. Rick
    hdumb->Draw();
    href->Draw("SAME");
    hnew->Draw("SAME");
    hnew->Draw("E1SAME");

      stringstream legend_new;
      stringstream legend_ref;
      legend_new << argv[4] << ": " << Nentries_new << " entries, " << Nevents_new << " events";
      legend_ref << argv[5] << ": " << Nentries_ref << " entries, " << Nevents_ref << " events";		
	
      TLegend l1(0.15,0.001,0.33, 0.06);
      l1.SetTextSize(0.02);
      l1.AddEntry(hnew, legend_new.str().c_str(),"lF");
      l1.AddEntry(href, legend_ref.str().c_str(),"lF");
      l1.SetFillColor(kNone);      
      l1.Draw("SAME");


    // print the result to gif
    string histo_name = name + ".gif";
    histo_c.Print(histo_name.c_str(),"gif");
    cout << "Result of comparison for " << name << ": ks score = " << ks_score << " : chi2 score = " << chi2_score << endl << endl;

  }

  // create summary canvas
  int summary_height = int(780 * float(num_histos) / 11); // 780;
  TCanvas main_c("main_c","main_c",799,summary_height);
  main_c.Draw();

  TPad main_p("main_p","main_p",0.01,0.01,0.99,0.94);
  main_p.SetLeftMargin(0.30);
  main_p.SetBottomMargin(0.15);
  main_p.SetLogx(1);
  main_p.SetGrid();
  main_p.SetFrameFillColor(10);
  main_p.Draw();

  main_c.cd();
  TText summary_title(.01, .95, "");
  summary_title.Draw("SAME");

  main_p.cd();

  // setup the passing test bars
  h1dResults_passed.SetStats(0);
  h1dResults_passed.GetXaxis()->SetLabelSize(0.06);
  h1dResults_passed.GetYaxis()->SetLabelSize(0.04);
  h1dResults_passed.GetYaxis()->SetTitle("Compatibility");
  h1dResults_passed.SetBarWidth(0.7);
  h1dResults_passed.SetBarOffset(0.1);
  h1dResults_passed.SetFillColor(kGreen);
  h1dResults_passed.SetLineColor(1);
  h1dResults_passed.GetYaxis()->SetRangeUser(1E-7,2);
  h1dResults_passed.Draw("hbar0");

  // setup the failing test bars
  h1dResults_failed.SetStats(0);
  h1dResults_failed.GetXaxis()->SetLabelSize(0.06);
  h1dResults_failed.GetYaxis()->SetLabelSize(0.04);
  h1dResults_failed.GetYaxis()->SetTitle("Compatibility");
  h1dResults_failed.SetBarWidth(0.7);
  h1dResults_failed.SetBarOffset(0.1);
  h1dResults_failed.SetFillColor(kRed);
  h1dResults_failed.SetLineColor(1);
  h1dResults_failed.GetYaxis()->SetRangeUser(1E-7,2);
  h1dResults_failed.Draw("hbar0SAME");

  // draw the pass/fail threshold line
  TLine l(threshold, 1, threshold, num_histos+1);
  l.SetLineColor(kRed);
  l.SetLineWidth(2);
  l.SetLineStyle(2);
  l.Draw("SAME"); 

  // print the results
  main_c.Update();
  main_c.Print("AllResults-1dHistoCheck.gif","gif");

  if (combinedFailed) cout << "Final Result: fail" << endl;
  else cout << "Final Result: pass" << endl;

  //delete pc;
  return 0;

}
Beispiel #23
0
void validateInjectionSingle(TString inputcarddir = "../../", TString toydatadir="../../", TString ana="hww", int njet = 0)
{

  gROOT->Reset();
  gStyle->SetOptStat(0);

  int mH = 125;

  TCanvas *c1 = new TCanvas();

  // 
  // Get the input carddir
  // 
  TFile *_file_ref = TFile::Open(Form("%s/%i/%sof_%ij.input_8TeV.root", inputcarddir.Data(), mH, ana.Data(), njet));
  THStack hs("hs","processes");

  TH1F* ZH = (TH1F*) _file_ref->Get("histo_ZH");
  TH1F* WH = (TH1F*) _file_ref->Get("histo_WH");
  TH1F* ggH = (TH1F*) _file_ref->Get("histo_ggH");
  TH1F* qqH = (TH1F*) _file_ref->Get("histo_qqH");
  TH1F* ggWW = (TH1F*) _file_ref->Get("histo_ggWW");
  TH1F* qqWW = (TH1F*) _file_ref->Get("histo_qqWW");
  TH1F* VV = (TH1F*) _file_ref->Get("histo_VV");
  TH1F* Top = (TH1F*) _file_ref->Get("histo_Top");
  TH1F* WjetsE = (TH1F*) _file_ref->Get("histo_WjetsE");
  TH1F* WjetsM = (TH1F*) _file_ref->Get("histo_WjetsM");
  TH1F* Zjets = (TH1F*) _file_ref->Get("histo_Zjets");
  TH1F* Ztt = (TH1F*) _file_ref->Get("histo_Ztt");
  TH1F* Wgamma = (TH1F*) _file_ref->Get("histo_Wgamma");
  TH1F* Wg3l = (TH1F*) _file_ref->Get("histo_Wg3l");


  ZH->SetLineColor(kRed);
  WH->SetLineColor(kRed);
  ggH->SetLineColor(kRed);
  qqH->SetLineColor(kRed);
  ggWW->SetLineColor(kAzure-9);
  qqWW->SetLineColor(kAzure-9);
  VV->SetLineColor(kAzure-2);
  Top->SetLineColor(kYellow);
  WjetsE->SetLineColor(kGray+1);
  WjetsM->SetLineColor(kGray+1);
  Zjets->SetLineColor(kGreen+2);
  Ztt->SetLineColor(kGreen+2);
  Wgamma->SetLineColor(kGray+1);
  Wg3l->SetLineColor(kGray+1);
  ZH->SetFillColor(kRed);
  WH->SetFillColor(kRed);
  ggH->SetFillColor(kRed);
  qqH->SetFillColor(kRed);
  ggWW->SetFillColor(kAzure-9);
  qqWW->SetFillColor(kAzure-9);
  VV->SetFillColor(kAzure-2);
  Top->SetFillColor(kYellow);
  WjetsE->SetFillColor(kGray+1);
  WjetsM->SetFillColor(kGray+1);
  Zjets->SetFillColor(kGreen+2);
  Ztt->SetFillColor(kGreen+2);
  Wgamma->SetFillColor(kGray+1);
  Wg3l->SetFillColor(kGray+1);
  ZH->SetFillStyle(1001);
  WH->SetFillStyle(1001);
  ggH->SetFillStyle(1001);
  qqH->SetFillStyle(1001);
  ggWW->SetFillStyle(1001);
  qqWW->SetFillStyle(1001);
  VV->SetFillStyle(1001);
  Top->SetFillStyle(1001);
  WjetsE->SetFillStyle(1001);
  WjetsM->SetFillStyle(1001);
  Zjets->SetFillStyle(1001);
  Ztt->SetFillStyle(1001);
  Wgamma->SetFillStyle(1001);
  Wg3l->SetFillStyle(1001);

  hs.Add(ggWW);
  hs.Add(qqWW);
  hs.Add(VV);
  hs.Add(Top);
  hs.Add(WjetsE);
  hs.Add(WjetsM);
  hs.Add(Wgamma);
  hs.Add(Wg3l);
  hs.Add(Zjets);
  hs.Add(Ztt);
  hs.Add(ZH);
  hs.Add(WH);
  hs.Add(ggH);
  hs.Add(qqH);
  // hs.Draw("hist");
  
  TH1F* hinj = new TH1F("hinj","hinj", ggH->GetNbinsX(), ggH->GetXaxis()->GetXmin(), ggH->GetXaxis()->GetXmax()); 
  for (int i=0;i<1000;++i) {
    TFile *_file_inj = TFile::Open(Form("%s/125/%sof_%ij_shape_8TeV_PseudoData_sb_seed12344.root", toydatadir.Data(), ana.Data(), njet));
    TH1F* h = (TH1F*) _file_inj->Get(Form("j%iof_%i",njet,i));
    hinj->Add(h);
    _file_inj->Close();
  }
  hinj->Scale(1./1000.);
  hinj->SetLineWidth(2);
  hinj->SetTitle();
  hinj->GetXaxis()->SetTitle("unrolled");
  hinj->GetYaxis()->SetTitle("events");
  hinj->GetYaxis()->SetRangeUser(0, TMath::Max(hinj->GetMaximum(), hs.GetMaximum())*1.1);
  hinj->Draw();

  hs.Draw("samehist");
  hinj->Draw("same");
  
  c1->SaveAs(Form("toys_%sof_%ij_injmH%i.eps", ana.Data(), njet, mH));
  c1->SaveAs(Form("toys_%sof_%ij_injmH%i.png", ana.Data(), njet, mH));

}
Beispiel #24
0
int main(int argc, char* argv[]){
    UImanager uimanager(argc, argv, "dndt_fit");
//work directory    
    TString workdir(getenv("WORKDIR"));
//***************************set constant ****************************************
    Double_t acdntl_corr = 1., respf_corr = 1.;
	Double_t eff_corr = uimanager.get_adcerr() * uimanager.get_br_corr() * uimanager.get_ta_corr() * acdntl_corr * respf_corr;//	adcerr x tdiff_cut_eff x veto_eff x pi0 decay products abs. (set to 1, since included in current rmat) x bkg_in_fit (not in current rmat)
    if(uimanager.best_tdiff()) eff_corr *= uimanager.get_bit_corr();
    if(uimanager.ismc()) eff_corr = uimanager.get_ta_corr(); 

    cout << eff_corr << " " << uimanager.flux() << " " << uimanager.get_tgt_lumi() << endl;
	Double_t f_l = uimanager.flux() * uimanager.get_tgt_lumi() * eff_corr;

//************ start reading files *******************************
//read tables/eflux.dat [tables/effcor.dat] tables/dfp1_xx.dat or current_foler/dfp1_xx.dat
//get echn flux
	Double_t flw[180];
	ifstream eflux(workdir+"tables/eflux.dat");
	if (!eflux.is_open()) {
		cout << "eflux doesn't exist" << endl;
		exit(1);
 	}
	for(int i=0;i<180;i++)eflux>>flw[i];
//get efficiency table
    TString dfp;
    if (!uimanager.target()) dfp = Form("dfp%d", int(uimanager.isouter())) + uimanager.input_filename("mc") + "_si.dat";
    else dfp = Form("dfp%d", int(uimanager.isouter())) + uimanager.input_filename("mc") + "_c12.dat";

	ifstream profile;
    profile.open(dfp);
    if (profile.is_open()) {
        cout << "use local efficiency table: " << dfp << endl;
    } else {
        //profile.open(workdir+"efficiency2/tables/"+dfp);
        profile.open(workdir+"/tables/"+dfp);
        if(!profile.is_open()) cout << " can't open table " << dfp << endl;
        cout << " use efficiency table in tables: " << dfp << endl;
    }
	
    const int phy = 5;
	const int ech = 180;
	Double_t dfprob[phy][nangle][ech];
	Double_t coulm[nangle], ncohe[nangle], cosfiint[nangle], sinfiint[nangle], ninco[nangle];
	for(int i=0;i<nangle;i++){
		coulm[i]=0;
        ncohe[i]=0;
		cosfiint[i]=0;
		sinfiint[i]=0;
		ninco[i]=0;
	}

	for(int i = 0;i < 180;i++)
		for(int j = 0;j < nangle;j++)
			for(int k = 0;k < 5;k++){
				Double_t f_l_j=f_l;
				int ic = 0;
				int jc = 0;
				int kc = 0;
				profile>>ic>>jc>>kc>>dfprob[k][j][i];
                if(ic!=i+1||jc!=j+1||kc!=k+1){
					cout << i << " " << j << " " << k << endl;
					cout << ic << " " << jc << " " << kc << " " << dfprob[k][j][i] << endl;
					cout<<"Bad data given for dfprob"<<endl;
					exit(1);
				}
				if(kc==1)coulm[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else if(kc==2)cosfiint[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else if(kc==3)ncohe[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else if(kc==4)ninco[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else sinfiint[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
            }

	for(int i=1;i<=nangle;i++){
		hcoulm->SetBinContent(i,coulm[i-1]);
		hcosfiint->SetBinContent(i,cosfiint[i-1]);
		hncohe->SetBinContent(i,ncohe[i-1]);
		hninco->SetBinContent(i,ninco[i-1]);
		hsinfiint->SetBinContent(i,sinfiint[i-1]);
    }
//read yield
    TString inrootname("pi0alt" + uimanager.input_filename("fit") + ".root");

	TFile *yield = new TFile(inrootname);
    if (!yield->IsOpen()) exit(open_err(inrootname));
	TH1F *yieldhist = (TH1F*)yield->Get("hyield");
	//TH1F *yieldhist = (TH1F*)yield->Get("hyield_mc_nocut");
	yieldhist->SetDirectory(0);
	if (!uimanager.target() && !uimanager.isouter()) yieldhist->SetTitle("#pi^{0} yield (Si, crystal w/o tran.)");
    else if (!uimanager.target()) yieldhist->SetTitle("#pi^{0} yield (Si, crystal w/ tran.)");
    else if (!uimanager.isouter()) yieldhist->SetTitle("#pi^{0} yield (C12, crystal w/o tran.)");
    else yieldhist->SetTitle("#pi^{0} yield (C12, crystal w/ tran.)");
    
    double nyield = 0, nyield_err = 0;
    for(int i = 1; i<=125; i++) {
        nyield += yieldhist->GetBinContent(i);
        nyield_err += yieldhist->GetBinError(i)*yieldhist->GetBinError(i);
    }
    nyield_err = sqrt(nyield_err);
//***************** end reading files **************************************
    
	gStyle->SetOptFit(1);
	gStyle->SetOptStat(0);
	gStyle->SetPaperSize(12,24);
	//Double_t parameter[4] = {7.9, 1.0, 1.0, 0.8};
	Double_t parameter[4] = {7.7, 1.0, 0.8, 0.5};

	TF1 *ftot = new TF1("ftot", dndt, 0., dndt_fit_range, 4);
	ftot->SetParNames("#Gamma","C1","#phi","C2");

	ftot->SetParameter(0,parameter[0]);
	ftot->SetParameter(1,parameter[1]);
	ftot->SetParameter(2,parameter[2]);
	ftot->SetParameter(3,parameter[3]);
/*
	ftot->FixParameter(0,parameter[0]);
	ftot->FixParameter(1,parameter[1]);
	ftot->FixParameter(2,parameter[2]);
	ftot->FixParameter(3,parameter[3]);
*/
    ftot->SetParLimits(0, 3, 10);
    ftot->SetParLimits(1, 0.3, 1.5);
    ftot->SetParLimits(2, 0, 3.1415936/2);
    ftot->SetParLimits(3, 0., 10.0);

	yieldhist->Fit("ftot", "RMBE0");

	Double_t chi2 = ftot->GetChisquare()/ftot->GetNDF();
	parameter[0]=ftot->GetParameter(0);
	parameter[1]=ftot->GetParameter(1);
	parameter[2]=ftot->GetParameter(2);
	parameter[3]=ftot->GetParameter(3);
	
    Double_t e1 = ftot->GetParError(0);
    Double_t e2 = ftot->GetParError(1);
    Double_t e3 = ftot->GetParError(2);
    Double_t e4 = ftot->GetParError(3);

	//cout<<chi2<<" "<<parameter[0]<<" "<<parameter[1]<<" "<<parameter[2]<<" "<<parameter[3]<<endl;
    TString fname = "fitresult" + uimanager.input_filename("fit") + ".dat";
    ofstream output(fname);
    output<<nyield<<" "<<nyield_err<<" "<<chi2<<" "<<parameter[0]<<" "<<e1<<" "<<parameter[1]<<" "<<e2<<" "<<parameter[2]<<" "<<e3<<" "<<parameter[3]<<" "<<e4<<endl;

	TH1F *fithist = new TH1F("fithist", "fithist", fit_nangle, 0, dndt_fit_range);
	TH1F *fitcoulm = new TH1F("fitcolum", "fitcolum", fit_nangle, 0, dndt_fit_range);
	TH1F *fitncohe = new TH1F("fitncohe", "fitncohe", fit_nangle, 0, dndt_fit_range);
	TH1F *fitit = new TH1F("fitit", "fitit", fit_nangle, 0, dndt_fit_range);
	TH1F *fitninco = new TH1F("fitninco", "fitninco", fit_nangle, 0, dndt_fit_range);

	yieldhist->SetLineWidth(2);
	fithist->SetLineWidth(2);
	fitcoulm->SetLineWidth(2);
	fitncohe->SetLineWidth(2);
	fitit->SetLineWidth(2);
	fitninco->SetLineWidth(2);

	float accfit[fit_nangle], acchist[fit_nangle], acchisterr[fit_nangle], diff[fit_nangle];

	for(int i=1;i<=fit_nangle;i++){
		fithist->SetBinContent(i,ftot->Eval(max_angle/nangle*(i-0.5)));
		fitcoulm->SetBinContent(i,parameter[0]*hcoulm->GetBinContent(i));
		fitncohe->SetBinContent(i,parameter[1]*hncohe->GetBinContent(i));
		fitit->SetBinContent(i,TMath::Sqrt(parameter[0]*parameter[1])*(TMath::Cos(parameter[2])*hcosfiint->GetBinContent(i)+TMath::Sin(parameter[2])*hsinfiint->GetBinContent(i)));
		fitninco->SetBinContent(i,parameter[3]*hninco->GetBinContent(i));
		if (i == 1) {
			accfit[0] = fithist->GetBinContent(1);
			acchist[0] = yieldhist->GetBinContent(1);
			acchisterr[0] = yieldhist->GetBinError(1) * yieldhist->GetBinError(1);
		}
		if (i != fit_nangle) {
			acchist[i] = yieldhist->GetBinContent(i) + acchist[i - 1];
			accfit[i] = fithist->GetBinContent(i) + accfit[i - 1];
			acchisterr[i] = acchisterr[i - 1] + yieldhist->GetBinError(i) * yieldhist->GetBinError(i);
		}
	}

	for(int i = 0; i < fit_nangle; ++i) {
		
		diff[i] = acchist[i] - accfit[i];
		acchisterr[i] = sqrt(acchisterr[i]);
	}

	TString outfilename("fyield" + uimanager.input_filename("fit"));

	float angles[fit_nangle], ex[fit_nangle];
	for(int i=0;i<fit_nangle;i++) {
		angles[i] = 0.02*(i+0.5);
        ex[i] = 0;
    }

	TGraphErrors ge(fit_nangle, angles, diff, ex, acchisterr);
	TGraphErrors ge1(fit_nangle, angles, acchist, ex, acchisterr);
	TGraph ge2(fit_nangle, angles, accfit);

	TCanvas *c1 = new TCanvas("c1","c1",1600,1200);
	c1->SaveAs(outfilename+".pdf[");
	yieldhist->SetMinimum(0);
	yieldhist->SetMaximum(yieldhist->GetMaximum()*1.05);
	yieldhist->Draw("e1");
	fitcoulm->SetLineColor(kBlue);
	fitcoulm->Draw("sameC");
	fitncohe->SetLineColor(32);
	fitncohe->Draw("sameC");
	fitit->SetLineColor(kBlack);
	fitit->Draw("sameC");
	fitninco->SetLineColor(kYellow);
	fitninco->Draw("sameC");
	fithist->SetLineColor(kRed);
	fithist->Draw("sameC");

	TLegend *leg = new TLegend(0.1,0.7,0.45,0.9);
	leg->SetFillColor(0);
	leg->SetTextSize(0.03);
	leg->AddEntry(fitcoulm,"Primakoff","L");
	leg->AddEntry(fitncohe,"Nuclear Coherent","L");
	leg->AddEntry(fitit,"Interference","L");
	leg->AddEntry(fitninco,"Nuclear Incoherent","L");
	//leg->Draw();

	c1->SaveAs(outfilename+".pdf");

	ge.SetMarkerStyle(20);
	ge.SetMarkerColor(kBlue);
	ge.SetTitle("accumulated yield - fit vs. #theta");
	ge.Draw("ap");
	c1->SaveAs(outfilename + ".pdf");

	ge1.SetMarkerStyle(20);
	ge1.SetMarkerColor(kBlue);
	ge1.SetTitle("accumulated yield and fitting vs. #theta");
	ge1.Draw("ap");
	ge2.SetLineColor(kRed);
	ge2.Draw("sameC");
	c1->SaveAs(outfilename + ".pdf");

	c1->SaveAs(outfilename+".pdf]");

	TFile *ftyd = new TFile(outfilename+".root", "RECREATE");
	yieldhist->Write();
	fithist->Write();
	fitcoulm->Write();
	fitncohe->Write();
	fitit->Write();
	fitninco->Write();
    hcoulm->Write();
    hncohe->Write();
    hninco->Write();
	hcosfiint->Write();
    hsinfiint->Write();
    ftyd->Close();
    
	return 0;
}
Beispiel #25
0
void doCoinc3(const char *fileIn="SAVO-01-SAVO-02-SAVO-03-2016-01-26.root"){
  Int_t adayMin = (yearRange[0]-2007) * 1000 + monthRange[0]*50 + dayRange[0];
  Int_t adayMax = (yearRange[1]-2007) * 1000 + monthRange[1]*50 + dayRange[1];

  // define some histos
  TH1F *hDeltaTheta12 = new TH1F("hDeltaTheta12","#Delta#theta_{12} below the peak (500 ns);#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhi12 = new TH1F("hDeltaPhi12","#Delta#phi_{12} below the peak (500 ns);#Delta#phi (#circ)",200,-360,360);
  TH1F *hDeltaThetaBack12 = new TH1F("hDeltaThetaBack12","#Delta#theta_{12} out of the peak (> 1000 ns) - normalized;#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhiBack12 = new TH1F("hDeltaPhiBack12","#Delta#phi_{12} out of the peak (> 1000 ns)  - normalized;#Delta#phi (#circ)",200,-360,360);
  TH1F *hThetaRel12 = new TH1F("hThetaRel12","#theta_{rel}_{12} below the peak (500 ns);#theta_{rel} (#circ)",100,0,120);
  TH1F *hThetaRelBack12 = new TH1F("hThetaRelBack12","#theta_{rel}_{12} out of the peak (> 1000 ns)  - normalized;#theta_{rel} (#circ)",100,0,120);

  TH1F *hDeltaTheta13 = new TH1F("hDeltaTheta13","#Delta#theta_{13} below the peak (500 ns);#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhi13 = new TH1F("hDeltaPhi13","#Delta#phi_{13} below the peak (500 ns);#Delta#phi (#circ)",200,-360,360);
  TH1F *hDeltaThetaBack13 = new TH1F("hDeltaThetaBack13","#Delta#theta_{13} out of the peak (> 1000 ns) - normalized;#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhiBack13 = new TH1F("hDeltaPhiBack13","#Delta#phi_{13} out of the peak (> 1000 ns)  - normalized;#Delta#phi (#circ)",200,-360,360);
  TH1F *hThetaRel13 = new TH1F("hThetaRel13","#theta_{rel}_{13} below the peak (500 ns);#theta_{rel} (#circ)",100,0,120);
  TH1F *hThetaRelBack13 = new TH1F("hThetaRelBack13","#theta_{rel}_{13} out of the peak (> 1000 ns)  - normalized;#theta_{rel} (#circ)",100,0,120);


  TFile *f = new TFile(fileIn);
  TTree *t = (TTree *) f->Get("tree");
  
  TTree *tel[3];
  tel[0] = (TTree *) f->Get("treeTel1");
  tel[1] = (TTree *) f->Get("treeTel2");
  tel[2] = (TTree *) f->Get("treeTel3");
  
  TTree *telC = (TTree *) f->Get("treeTimeCommon");
  
  // quality info of runs
  Bool_t runstatus[3][10][12][31][500]; //#telescope, year-2007, month, day, run
  
  if(tel[0] && tel[1] && tel[2]){
    for(Int_t i=0;i < 3;i++){ // loop on telescopes
      for(Int_t j=0;j < tel[i]->GetEntries();j++){ // loop on runs
	tel[i]->GetEvent(j);
	Int_t aday = (tel[i]->GetLeaf("year")->GetValue()-2007) * 1000 + tel[i]->GetLeaf("month")->GetValue()*50 + tel[i]->GetLeaf("day")->GetValue();

	if(aday < adayMin || aday > adayMax) continue;
	if(tel[i]->GetLeaf("FractionGoodTrack")->GetValue() < fracGT[i]) continue; // cut on fraction of good track
	if(tel[i]->GetLeaf("timeduration")->GetValue()*tel[i]->GetLeaf("rateHitPerRun")->GetValue() < hitevents[i]) continue; // cut on the number of event
	if(tel[i]->GetLeaf("ratePerRun")->GetValue() < rateMin[i] || tel[i]->GetLeaf("ratePerRun")->GetValue() > rateMax[i]) continue; // cut on the rate
	if(tel[i]->GetLeaf("run")->GetValue() > 499) continue; // run < 500

	Float_t missinghitfrac = (tel[i]->GetLeaf("ratePerRun")->GetValue()-tel[i]->GetLeaf("rateHitPerRun")->GetValue()-2)/(tel[i]->GetLeaf("ratePerRun")->GetValue()-2);
	if(missinghitfrac < minmissingHitFrac[i] || missinghitfrac > maxmissingHitFrac[i]) continue;

	
	runstatus[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2007][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = kTRUE;
	
      }
    }
  }
  else{
    telC = NULL;
  }
  
  Int_t n = t->GetEntries();

  // counter for seconds
  Int_t nsec = 0;
  Int_t nsecGR = 0; // for good runs
  Int_t isec = -1; // used only in case the tree with time info is not available

  if(telC){
    for(Int_t i=0; i < telC->GetEntries();i++){
      telC->GetEvent(i);
      nsec += telC->GetLeaf("timeduration")->GetValue(); 
      
      
      
      if(telC->GetLeaf("run")->GetValue() > 499 || telC->GetLeaf("run2")->GetValue() > 499 || telC->GetLeaf("run3")->GetValue() > 499) continue;
      
      if(!runstatus[0][Int_t(telC->GetLeaf("year")->GetValue())-2007][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())]) continue;
      
      if(!runstatus[1][Int_t(telC->GetLeaf("year")->GetValue())-2007][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run2")->GetValue())]) continue;

      if(!runstatus[2][Int_t(telC->GetLeaf("year")->GetValue())-2007][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run2")->GetValue())]) continue;
      
      nsecGR += telC->GetLeaf("timeduration")->GetValue(); 
    }
  }
  
  char title[600];
  TH1F *h;
  TH2F *h2;

  sprintf(title,"correction assuming #Delta#phi_{12} = %4.2f, #DeltaL_{12} = %.1f m, #Delta#phi_{13} = %4.2f, #DeltaL_{13} = %.1f m;#Deltat_{13} (ns) when |#Deltat_{12}| < %i ns;entries",angle12,distance12,angle13,distance13,timeCutOn12);
  h = new TH1F("hCoinc",title,nbint,tmin,tmax);
  sprintf(title,"correction assuming #Delta#phi_{12} = %4.2f, #DeltaL_{12} = %.1f m, #Delta#phi_{13} = %4.2f, #DeltaL_{13} = %.1f m;#Deltat_{12} (ns);#Deltat_{13} (ns);entries",angle12,distance12,angle13,distance13,timeCutOn12);
  h2 = new TH2F("hCoinc2D",title,nbint,tmin,tmax,nbint,tmin,tmax);
  
  Float_t DeltaT12,DeltaT13;
  Float_t phiAv,thetaAv,corr12,corr13;
  
  Float_t Theta1,Theta2,Theta3;
  Float_t Phi1,Phi2,Phi3;
  
  Float_t v1[3],v2[3],v3[3],vSP12,vSP13; // variable to recompute ThetaRel on the fly
  
  for(Int_t i=0;i<n;i++){
    t->GetEvent(i);
    
    // if(t->GetLeaf("RunNumber1") && (t->GetLeaf("RunNumber1")->GetValue() > 499 || t->GetLeaf("RunNumber2")->GetValue() > 499) || t->GetLeaf("RunNumber3")->GetValue() > 499)) continue;
  
    // if(tel[0] && !runstatus[0][Int_t(t->GetLeaf("year")->GetValue())-2007][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber1")->GetValue())]) continue;
    
    // if(tel[1] && !runstatus[1][Int_t(t->GetLeaf("year")->GetValue())-2007][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())]) continue;
  
    // if(tel[2] && !runstatus[2][Int_t(t->GetLeaf("year")->GetValue())-2007][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())]) continue;
    
    Int_t timec = t->GetLeaf("ctime1")->GetValue();
    
    if(! telC){
      if(isec == -1) isec = timec;
      
      if(timec != isec){
	if(timec - isec < 20){
	  //	printf("diff = %i\n",timec-isec);
	  nsec +=(timec - isec);
	  nsecGR +=(timec - isec);
	}
	isec = timec;
      }
    }

    Float_t thetarel12 = t->GetLeaf("ThetaRel12")->GetValue();
    Float_t thetarel13 = t->GetLeaf("ThetaRel13")->GetValue();
    Theta1 = t->GetLeaf("Theta1")->GetValue()*TMath::DegToRad();
    Theta2 = t->GetLeaf("Theta2")->GetValue()*TMath::DegToRad();
    Theta3 = t->GetLeaf("Theta3")->GetValue()*TMath::DegToRad();
    Phi1 = t->GetLeaf("Phi1")->GetValue()*TMath::DegToRad();
    Phi2 = t->GetLeaf("Phi2")->GetValue()*TMath::DegToRad();
    Phi3 = t->GetLeaf("Phi3")->GetValue()*TMath::DegToRad();
    
    if(recomputeThetaRel){ // recompute ThetaRel applying corrections
      Phi1 -= phi1Corr*TMath::DegToRad();
      Phi2 -= phi2Corr*TMath::DegToRad();
      Phi3 -= phi3Corr*TMath::DegToRad();
      if(Phi1 > 2*TMath::Pi()) Phi1 -= 2*TMath::Pi();
      if(Phi1 < 0) Phi1 += 2*TMath::Pi();
      if(Phi2 > 2*TMath::Pi()) Phi2 -= 2*TMath::Pi();
      if(Phi2 < 0) Phi2 += 2*TMath::Pi();
      if(Phi3 > 2*TMath::Pi()) Phi3 -= 2*TMath::Pi();
      if(Phi3 < 0) Phi3 += 2*TMath::Pi();
      
      v1[0] = TMath::Sin(Theta1)*TMath::Cos(Phi1);
      v1[1] = TMath::Sin(Theta1)*TMath::Sin(Phi1);
      v1[2] = TMath::Cos(Theta1);
      v2[0] = TMath::Sin(Theta2)*TMath::Cos(Phi2);
      v2[1] = TMath::Sin(Theta2)*TMath::Sin(Phi2);
      v2[2] = TMath::Cos(Theta2);
      v3[0] = TMath::Sin(Theta3)*TMath::Cos(Phi3);
      v3[1] = TMath::Sin(Theta3)*TMath::Sin(Phi3);
      v3[2] = TMath::Cos(Theta3);
      
      v2[0] *= v1[0];
      v2[1] *= v1[1];
      v2[2] *= v1[2];
      v3[0] *= v1[0];
      v3[1] *= v1[1];
      v3[2] *= v1[2];
      
      vSP12 = v2[0] + v2[1] + v2[2];
      vSP13 = v3[0] + v3[1] + v3[2];
      
      thetarel12 = TMath::ACos(vSP12)*TMath::RadToDeg();
      thetarel13 = TMath::ACos(vSP13)*TMath::RadToDeg();
    }
    
    // cuts
    if(thetarel12 > maxthetarel) continue;
    if(thetarel13 > maxthetarel) continue;
    if(t->GetLeaf("ChiSquare1")->GetValue() > maxchisquare) continue;
    if(t->GetLeaf("ChiSquare2")->GetValue() > maxchisquare) continue;
    if(t->GetLeaf("ChiSquare3")->GetValue() > maxchisquare) continue;
    
    DeltaT12 = t->GetLeaf("DiffTime12")->GetValue();
    DeltaT13 = t->GetLeaf("DiffTime13")->GetValue();
    
    // get primary direction
    if(TMath::Abs(Phi1-Phi2) < TMath::Pi()) phiAv = (Phi1+Phi2)*0.5;
    else phiAv = (Phi1+Phi2)*0.5 + TMath::Pi();
    if(TMath::Abs(phiAv-Phi3) < TMath::Pi()) phiAv = (phiAv*2+Phi2)*0.33333333333;
    else if(phiAv > Phi3) phiAv = (phiAv*2+Phi3+2*TMath::Pi())*0.33333333333;
    else phiAv = (phiAv*2+4*TMath::Pi()+Phi3)*0.33333333333;


    thetaAv = (Theta1+Theta2+Theta3)*0.333333333333;
    
    // extra cuts if needed
    //    if(TMath::Cos(Phi1-Phi2) < 0.) continue;
    
    corr12 = distance12 * TMath::Sin(thetaAv)*TMath::Cos(phiAv-angle12)/2.99792458000000039e-01 + deltatCorr12;
    corr13 = distance13 * TMath::Sin(thetaAv)*TMath::Cos(phiAv-angle13)/2.99792458000000039e-01 + deltatCorr13;
    
    if(TMath::Abs(DeltaT12-corr12) < timeCutOn12) h->Fill(DeltaT13-corr13);
    h2->Fill(DeltaT12-corr12,DeltaT13-corr13);

    if(TMath::Abs(DeltaT12-corr12) < 500){
      hDeltaTheta12->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhi12->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRel12->Fill(thetarel12);
    }
    else if(TMath::Abs(DeltaT12-corr12) > 1000 && TMath::Abs(DeltaT12-corr12) < 6000){
      hDeltaThetaBack12->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhiBack12->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRelBack12->Fill(thetarel12);
    }

    if(TMath::Abs(DeltaT13-corr13) < 500){
      hDeltaTheta13->Fill((Theta1-Theta3)*TMath::RadToDeg());
      hDeltaPhi13->Fill((Phi1-Phi3)*TMath::RadToDeg());
      hThetaRel13->Fill(thetarel13);
    }
    else if(TMath::Abs(DeltaT13-corr13) > 1000 && TMath::Abs(DeltaT13-corr13) < 6000){
      hDeltaThetaBack13->Fill((Theta1-Theta3)*TMath::RadToDeg());
      hDeltaPhiBack13->Fill((Phi1-Phi3)*TMath::RadToDeg());
      hThetaRelBack13->Fill(thetarel13);
    }
  }
  
  h->SetStats(0);

  hDeltaThetaBack12->Sumw2();
  hDeltaPhiBack12->Sumw2();
  hThetaRelBack12->Sumw2();
  hDeltaThetaBack12->Scale(0.1);
  hDeltaPhiBack12->Scale(0.1);
  hThetaRelBack12->Scale(0.1);
  hDeltaThetaBack13->Sumw2();
  hDeltaPhiBack13->Sumw2();
  hThetaRelBack13->Sumw2();
  hDeltaThetaBack13->Scale(0.1);
  hDeltaPhiBack13->Scale(0.1);
  hThetaRelBack13->Scale(0.1);

  Float_t val,eval;
  TCanvas *c1=new TCanvas();
  TF1 *ff = new TF1("ff","[0]*[4]/[2]/sqrt(2*TMath::Pi())*TMath::Exp(-(x-[1])*(x-[1])*0.5/[2]/[2]) + [3]*[4]/6/[2]");
  ff->SetParName(0,"signal");
  ff->SetParName(1,"mean");
  ff->SetParName(2,"sigma");
  ff->SetParName(3,"background");
  ff->SetParName(4,"bin width");
  ff->SetParameter(0,42369);
  ff->SetParameter(1,0);
  ff->SetParLimits(2,10,1000);
  ff->SetParameter(2,150); // fix witdh if needed
  ff->SetParameter(3,319);
  ff->FixParameter(4,20000./nbint); // bin width
  
  ff->SetNpx(1000);
  
  h->Fit(ff);
  
  val = ff->GetParameter(2);
  eval = ff->GetParError(2);
  
  printf("significance = %f\n",ff->GetParameter(0)/sqrt(ff->GetParameter(0) + ff->GetParameter(3)));

  h->Draw();
  
  TF1 *func1 = (TF1 *)  h->GetListOfFunctions()->At(0);
  
  func1->SetLineColor(2);
  h->SetLineColor(4);
  
  TPaveText *text = new TPaveText(1500,(h->GetMinimum()+(h->GetMaximum()-h->GetMinimum())*0.6),9500,h->GetMaximum());
  text->SetFillColor(0);
  sprintf(title,"width = %5.1f #pm %5.1f",func1->GetParameter(2),func1->GetParError(2));
  text->AddText(title);
  sprintf(title,"signal (S) = %5.1f #pm %5.1f",func1->GetParameter(0),func1->GetParError(0));
  text->AddText(title);
  sprintf(title,"background (B) (3#sigma) = %5.1f #pm %5.1f",func1->GetParameter(3),func1->GetParError(3));
  text->AddText(title);
  sprintf(title,"significance (S/#sqrt{S+B}) = %5.1f",func1->GetParameter(0)/sqrt(func1->GetParameter(0)+func1->GetParameter(3)));
  text->AddText(title);
  
  text->SetFillStyle(0);
  text->SetBorderSize(0);
  
  text->Draw("SAME");
  
  printf("n_day = %f\nn_dayGR = %f\n",nsec*1./86400,nsecGR*1./86400);

  text->AddText(Form("rate = %f #pm %f per day",func1->GetParameter(0)*86400/nsecGR,func1->GetParError(0)*86400/nsecGR));

  TFile *fo = new TFile("output-SAVO-010203.root","RECREATE");
  h->Write();
  h2->Write();
  hDeltaTheta12->Write();
  hDeltaPhi12->Write();
  hThetaRel12->Write();
  hDeltaThetaBack12->Write();
  hDeltaPhiBack12->Write();
  hThetaRelBack12->Write();
  hDeltaTheta13->Write();
  hDeltaPhi13->Write();
  hThetaRel13->Write();
  hDeltaThetaBack13->Write();
  hDeltaPhiBack13->Write();
  hThetaRelBack13->Write();
  fo->Close();
  
}
void meson_pi0_normalization(){
  gROOT->Reset();
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);
  c1 = new TCanvas("c1","A Simple Graph with error bars",200,10,700,500);

  c1->SetFillColor(10);
  c1->SetGrid();
  c1->SetLogy();
  c1->SetTicks();

  float pt, mtpion, mtother;
  float weight = 1.0;
  int   nbins  = 5000;
  float ptmin  = 0.0;
  float ptmax  = 5.0;
  float binwidth = (ptmax-ptmin)/(double)nbins;
  TH1F * ptpion = new TH1F("ptpion","ptpion",nbins,ptmin,ptmax);
  TH1F * ptother = new TH1F("ptother","ptother",nbins,ptmin,ptmax);
  TH1F * ptothermt = new TH1F("ptothermt","ptothermt",nbins,ptmin,ptmax);
  TH1F * ratio = new TH1F("ratio","ratio",nbins,ptmin,ptmax);
  TH1F * ratiomt = new TH1F("ratiomt","ratiomt",nbins,ptmin,ptmax);

  TMath math1;

  double pi     = acos(-1.0);
  double pimass = 0.1349766;
  double omass  = 0.54730;
  double expected = 0.45;
  // double omass  = 0.7711;
  // double expected = 1.0;
  // double omass  = 0.78257;
  // double expected = 1.0;
  // double omass  = 0.95778;
  // double expected = 0.25;
  // double omass  = 1.019456;
  // double expected = 0.4;

  double t_fo = 0.122;
  double beta = 0.70;
  double norm = 1.0;
 
  double intpion    = 0.0;
  double intother   = 0.0;
  double intothermt = 0.0;

  for (int ibin=1; ibin<=nbins; ibin++ )
  {
    pt = ptmin+(double)(ibin-1)*binwidth+binwidth/2.0;
    mtpion  = sqrt(pt*pt+pimass*pimass);
    mtother = sqrt(pt*pt+omass*omass);

    // minimum bias:
    // double trans      = 1./(1.+exp(5.*pt-17.5));
    // double pihagedorn = 3.53e+07/pow(2.28+pt,13.7);
    // double pipower    = 33.9/pow(pt,8.16);
    // double otherhagedorn = 3.53e+07 / 
    //   pow(2.28+sqrt(mtother*mtother-pimass*pimass),13.7);
    // double otherpower = 33.9/pow(sqrt(mtother*mtother-pimass*pimass),8.16);
    // 0 - 10 % central
    // double trans      = 1./(1.+exp(5.*pt-17.5));
    // double pihagedorn = 1.41e+13/pow(3.48+pt,18.7);
    // double pipower    = 137.3/pow(pt,8.44);
    // double otherhagedorn = 1.41e+13 / 
    //   pow(3.48+sqrt(mtother*mtother-pimass*pimass),18.7);
    // double otherpower = 137.3/pow(sqrt(mtother*mtother-pimass*pimass),8.44);
    // 10 - 20 % central
    // double trans      = 1./(1.+exp(5.*pt-17.5));
    // double pihagedorn = 2.176e+09/pow(2.651+pt,15.170);
    // double pipower    = 92.46/pow(pt,8.326);
    // double otherhagedorn = 2.176e+09 / 
    //   pow(2.651+sqrt(mtother*mtother-pimass*pimass),15.170);
    // double otherpower = 92.46/pow(sqrt(mtother*mtother-pimass*pimass),8.326);    // 20 - 40 % central
    // double trans      = 1./(1.+exp(5.*pt-17.5));
    // double pihagedorn = 2.99e+06/pow(2.00+pt,12.45);
    // double pipower    = 51.28/pow(pt,8.21);
    // double otherhagedorn = 2.99e+06 / 
    //   pow(2.00+sqrt(mtother*mtother-pimass*pimass),12.45);
    // double otherpower = 51.28/pow(sqrt(mtother*mtother-pimass*pimass),8.21);
    // 40 - 60 % central
    // double trans      = 1./(1.+exp(5.*pt-17.5));
    // double pihagedorn = 3.00e+04/pow(1.56+pt,10.76);
    // double pipower    = 15.75/pow(pt,7.97);
    // double otherhagedorn = 3.00e+04 / 
    //   pow(1.56+sqrt(mtother*mtother-pimass*pimass),10.76);
    // double otherpower = 15.75/pow(sqrt(mtother*mtother-pimass*pimass),7.97);
    // 60 - 92 % central
    // double trans      = 1./(1.+exp(5.*pt-17.5));
    // double pihagedorn = 8.73e+02/pow(1.29+pt,9.94);
    // double pipower    = 5.28/pow(pt,8.28);
    // double otherhagedorn = 8.73e+02 / 
    //   pow(1.29+sqrt(mtother*mtother-pimass*pimass),9.94);
    // double otherpower = 5.28/pow(sqrt(mtother*mtother-pimass*pimass),8.28);
    // if ( pt<1.5 ) weight = 2.0 * pi * pt * pihagedorn;
    // if ( pt>=1.5 && pt<=5.5 ) 
    //   weight = 2.0 * pi * pt * (trans*pihagedorn + (1.-trans)*pipower);
    // if ( pt>5.5 ) weight = 2.0*pi*pt*pipower;

    // pp (Xinhua's Run-2 parameterization)
    // weight = 2.0*pi*pt * (485.0/42.) / pow(exp(-0.5187*pt) + pt/0.6631,8.163);
    // pp (Run-2 hard parameterization)
    weight = 2.0*pi*pt * (450.8/42.) / pow(exp(-0.5553*pt) + pt/0.6467,8.046);
    // pp (Run-3 parameterization)
    // weight = 2.0*pi*pt * (413.5/42.2) / pow(exp(-0.2614*pt) + pt/0.8144,8.807);
    // pp (average Run-2/3 parameterization)
    // weight = 2.0*pi*pt * (546.2/42.2) / pow(exp(-0.2664*pt) + pt/0.7703,8.718);
    //    weight = weight*(1+0.6362/exp(7.736*pt));

    ptpion->AddBinContent(ibin,weight);
    intpion = intpion + weight*binwidth;

    // if ( pt<1.5 ) weight = 2.0 * pi * pt * otherhagedorn;
    // if ( pt>=1.5 && pt<=5.5 ) 
    //   weight = 2.0 * pi * pt * (trans*otherhagedorn + (1.-trans)*otherpower);
    // if ( pt>5.5 ) weight = 2.0*pi*pt*otherpower;

    weight = 2.0*pi*pt * (450.8/42.2) / 
      pow(exp(-0.5553*sqrt(mtother*mtother-pimass*pimass)) + 
	  sqrt(mtother*mtother-pimass*pimass)/0.6467,8.046);

    ptothermt->AddBinContent(ibin,weight);
    intothermt = intothermt + weight*binwidth;

    weight = norm*InitializePtHydro(omass,t_fo,beta,pt);
    ptother->AddBinContent(ibin,weight);
    intother = intother + weight*binwidth;
  }

  cout << "Integral pion    (dN/dy): " << intpion << endl;
  cout << "Integral other   (dN/dy): " << intother << endl;
  cout << "Integral othermt (dN/dy): " << intothermt << endl;

  norm = intpion/intothermt;
  ptothermt->Scale(norm);
 
  for (int ibin=1; ibin<=nbins; ibin++ )
  {
    weight = ptothermt->GetBinContent(ibin)/ptpion->GetBinContent(ibin);
    ratiomt->AddBinContent(ibin,weight);
  }

  norm = expected/ratiomt->GetMaximum();
  ratiomt->Scale(norm);
  ptothermt->Scale(norm);
  cout << "meson/pion ratio should be set to: " << norm << endl;

  norm = expected*intothermt/intother;
  ptother->Scale(norm);
 
  for (int ibin=1; ibin<=nbins; ibin++ )
  {
    weight = ptother->GetBinContent(ibin)/ptpion->GetBinContent(ibin);
    ratio->AddBinContent(ibin,weight);
  }

  ptpion->SetXTitle("p_{t} [GeV/c]");
  ptpion->SetYTitle("(1/2#pi p_{t})dN/dp_{t}dy [(c/GeV)^{2}]");
  ptpion->SetLineWidth(5);
  ptpion->SetLineColor(1);
  ptother->SetLineWidth(5);
  ptother->SetLineColor(2);
  ptothermt->SetLineWidth(5);
  ptothermt->SetLineColor(4);
  ptpion->Draw("");
  ptothermt->Draw("same");
  ptother->Draw("same");

  TLatex *text_pion0 = new TLatex(3.2,1.5,"#pi^{0}");
  text_pion0->SetTextColor(1);
  text_pion0->Draw();
  TLatex *text_pionm = new TLatex(3.2,1.1,"#eta m_{t} scaled");
  text_pionm->SetTextColor(4);
  text_pionm->Draw();
  TLatex *text_pionp = new TLatex(3.2,0.7,"#eta hydro");
  text_pionp->SetTextColor(2);
  text_pionp->Draw();

   c2 = new TCanvas("c2","A Simple Graph with error bars",200,10,700,500);

   c2->SetFillColor(10);
   c2->SetGrid();
   c2->SetLogy(0);
   c2->SetTicks();
 
   c2->cd();

  ratiomt->SetXTitle("p_{t} [GeV/c]");
  ratiomt->SetYTitle("#eta / #pi^{0}");
  ratio->SetLineWidth(5);
  ratio->SetLineColor(2);
  ratiomt->SetLineWidth(5);
  ratiomt->SetLineColor(4);
  ratiomt->Draw();
  ratio->Draw("same");

  TLatex *text_pionm = new TLatex(3.2,0.42,"#eta m_{t} scaled");
  text_pionm->SetTextColor(4);
  text_pionm->Draw();
  TLatex *text_pionp = new TLatex(3.2,0.35,"#eta hydro");
  text_pionp->SetTextColor(2);
  text_pionp->Draw();

  return;
}
Beispiel #27
0
void plottingmacro_IVF()
{


  double fa = 0.46502;
  double fb = 0.53498;
  bool debug_ = true;

  //  std::string path("Nov10thFall11Plots/");
  //  std::string path("Nov10Fall1160MTopSlimPlots/");
  std::string path("Nov10Fall1160MTopIVFPlots_b/");

  if(debug_)
    std::cout << "Init the style form setTDRStyle" << std::endl;
  setTDRStyle();
  gStyle->SetErrorX(0.5);
  gROOT->ForceStyle();
  initOptions();
  

  if(debug_)
    std::cout << "Init the sample" << std::endl;
  //  std::vector<Sample> s = Nov10thDiJetPtUpdatedSlimHistos();
  //std::vector<Sample> s = Nov10Fall1160MTopSlimHistos();
  std::vector<Sample> s = Nov10Fall1160MTopIVFHistos();

  Sample data(1,"fake data","S1.root",0,true,1000);

  if(debug_)
    std::cout << "Init the data sample" << std::endl;
  for(size_t i=0;i< s.size();i++) if(s[i].data) {data=s[i];break;}

  if(debug_)
    std::cout << "Ls data sample" << std::endl;
  data.file()->ls(); 

  if(debug_)
    std::cout << "Init the mc sample" << std::endl;
  for(size_t i=0;i< s.size();i++) s[i].dump(1,fa,fb);

  std::vector<std::string> names;

  if(debug_)
    std::cout << "Get List of Keys" << std::endl;
  TList * subs = data.file()->GetListOfKeys();
  for(size_t i=0;i< subs->GetSize();i++)
    {
      TString nn = subs->At(i)->GetName();
      if( nn.Contains(TRegexp("Count*")) )
	continue;
      if(debug_)
	std::cout << "Get List of Keys in subdirs" << std::endl;
      TList * objs = ((TDirectoryFile *)data.file()->Get(subs->At(i)->GetName()))->GetListOfKeys();
      for(size_t j=0;j< objs->GetSize();j++)
	{
	  if(debug_)
	    std::cout << "Name = " << subs->At(i)->GetName()+std::string("/")  + objs->At(j)->GetName() << std::endl;
	  names.push_back(subs->At(i)->GetName()+std::string("/")  + objs->At(j)->GetName());
	  //      std::cout << subs->At(i)->GetName() << "/"  << objs->At(j)->GetName() << std::endl;
	  //TODO: select plots via regexp
	}
    }


  if(debug_)
    std::cout << "Starting plotting" << std::endl;

  std::string process;

  for(size_t i = 0 ; i < names.size() ; i++) 
    {
      
      std::map<std::string,TH1F *> grouped;
      TString n=names[i];
      //      if(!n.Contains(TRegexp("VlightRegionHZee/HiggsPtVlightRegionHZee"))) continue;
      //      if(!n.Contains(TRegexp("VlightRegionHZee/ZPtVlightRegionHZee"))) continue;
      //      if(!n.Contains(TRegexp("VlightRegionHZee"))) continue;
      //      if(!n.Contains(TRegexp("ZSVRegionZmmSV"))) continue;
      //      if(!n.Contains(TRegexp("ZSVRegionZeeSV"))) continue;
      //      if(!n.Contains(TRegexp("ZSVRegionZcombSV"))) continue;
      //      if(!n.Contains(TRegexp("ZSVPureRegionZcombSV"))) continue;
      //      if(!n.Contains(TRegexp("ZSVTTbarPureRegionZcombSV"))) continue;
      if(!n.Contains(TRegexp("TTbarRegionZeeSVJets"))) continue;

      if(n.Contains(TRegexp("RegionHZcomb")))
	process = "Z(l^{+}l^{-})H(b#bar{b})";
      if(n.Contains(TRegexp("RegionHZmm")))
	process = "Z(#mu^{+}#mu^{-})H(b#bar{b})";
      if(n.Contains(TRegexp("RegionHZee")))
	process = "Z(e^{+}e^{-})H(b#bar{b})";

      if(debug_)
	std::cout << "Creating the Canvas" << std::endl;

      TCanvas *c = new TCanvas();
      c->SetLogy(false);
      c->SetTitle(names[i].c_str());

      if(debug_)
	std::cout << "Creating histograms" << std::endl;
  
      TH1F *hd = ((TH1F*)data.file()->Get(names[i].c_str()));
      hd->Sumw2();
      Options o=options[names[i]];
      //      hd->Rebin(o.rebin);
      hd->SetMarkerStyle(20);
      hd->GetXaxis()->SetLabelOffset(99);
      hd->SetYTitle(o.yaxis.c_str());
      double nbin = hd->GetNbinsX();
      double min_bin = hd->GetXaxis()->GetXmin();
      double max_bin = hd->GetXaxis()->GetXmax();
      TH1F *hmc = new TH1F("hmc","hmc", nbin, min_bin, max_bin);
      hmc->SetFillColor(kWhite);
      hmc->Sumw2();
      //      hmc->Rebin(o.rebin);

      if(debug_)
	std::cout << "Creating the THStack and Legend" << std::endl;
      THStack * sta = new THStack("sta",hd->GetTitle());
      TLegend * l = new TLegend(o.legendx1,o.legendy1,o.legendx2,o.legendy2); //0.7,0.1,0.9,0.6);
      l->SetFillColor(kWhite);
      l->SetBorderSize(0);
      l->SetTextFont(62);
      l->SetTextSize(0.03);
      if(debug_)
	std::cout << "Adding data to the legend" << std::endl;  
      l->AddEntry(hd, "Data","P");
      if(debug_)
	std::cout << "Adding MC to the THStack" << std::endl;  

      //with the proper trigger eff
      //      double SF[] = {1.01,1.03,1.00};
      //      double SF[] = {1.03,1.054,1.032};
      double SF[] = {1.0,1.0,1.0};

      if(debug_){
	for(int i = 0; i< 3; ++i)
	  std::cout << "SF [" << i << "] = " << SF[i] << std::endl;
      }

      double mcIntegral=0;
      for(size_t j=0;j< s.size() ;j++) 
	{ 
	  if(!s[j].data) 
	    {
	      if(debug_)
		std::cout << "Creating TH1F from file " << s[j].name << std::endl;  
	      TH1F * h = ((TH1F*)s[j].file()->Get(names[i].c_str()));
	      h->Sumw2();
	      if(debug_){
		std::cout << "TH1F created from file " << s[j].name << std::endl;  
		std::cout << "Scaling : " << s[j].scale(data.lumi(),fa,fb) << std::endl;  
		std::cout << "Scaling with SF : " << s[j].scale(data.lumi(),fa,fb,SF) << std::endl;  
		std::cout << "Histo integral before scaling = " << h->Integral() << std::endl;
	      }
	      h->Scale(s[j].scale(data.lumi(),fa,fb,SF));
	      if(debug_){
		std::cout << "Histo integral after scaling = " << h->Integral() << std::endl;
		std::cout << "Managing style... " << std::endl;  
	      }
	      h->SetLineWidth(1.);
	      h->SetFillColor(s[j].color);
	      h->SetLineColor(s[j].color);
	      //	      h->Rebin(options[names[i]].rebin);
	      if(debug_)
		std::cout << "Cloning and update legend " << std::endl;  
	      if(grouped.find(s[j].name) == grouped.end()){
		l->AddEntry(h,s[j].name.c_str(),"F");
	      }
	      std::cout << "Sample : " << s[j].name << " - Integral for plot " << names[i] << " = " << h->Integral(-10000,10000) << std::endl;
	      mcIntegral += h->Integral();
	      sta->Add(h);
	      hmc->Add(h);	      
	      //TO FIX grouped map
	      // sovrascrive histo con lo stesso nome tipo VV o ST etc...
	      grouped[s[j].name]=(TH1F *)h->Clone(("_"+names[i]).c_str());
	    }
	}

      if(debug_){
	std::cout << "Data total = " << hd->Integral() << std::endl;
	std::cout << "MC = " << mcIntegral << std::endl;
	std::cout << "Data/MC = " << hd->Integral()/mcIntegral << std::endl;
      }

      TPad * TopPad = new TPad("TopPad","Top Pad",0.,0.3,1.,1. ) ;
      TPad * BtmPad = new TPad("BtmPad","Bottom Pad",0.,0.,1.,0.313 ) ;
      TopPad->SetBottomMargin(0.02);
      BtmPad->SetTopMargin(0.0);
      BtmPad->SetFillStyle(4000);
      TopPad->SetFillStyle(4000);
      BtmPad->SetFillColor(0);
      BtmPad->SetBottomMargin(0.35);
      TopPad->Draw() ;
      BtmPad->Draw() ;
      std::cout << "hd maximum = " << hd->GetMaximum() << "  sta maximum = " << sta->GetMaximum() << std::endl;
      double maxY;
      if(hd->GetMaximum() > sta->GetMaximum()) maxY = (hd->GetMaximum())*1.5;
      else maxY = (sta->GetMaximum())*1.5;
      TopPad->cd();
      hd->Draw("E1X0");
      sta->Draw("sameHIST");
      hmc->Draw("sameE2");
      hmc->SetFillColor(2);
      hmc->SetMarkerSize(0);
      hmc->SetFillStyle(3013);
      hd->Draw("E1X0same");
      l->Draw("same");
      std::cout << "Set Maximum to = " << maxY << std::endl;
      hd->GetYaxis()->SetRangeUser(0.,maxY);
      hd->GetXaxis()->SetRangeUser(options[names[i]].min,options[names[i]].max);

      BtmPad->cd();
      std::cout << "Division" << std::endl;

      TH1D * divisionErrorBand = (TH1D*)(hmc)->Clone("divisionErrorBand");
      divisionErrorBand->Sumw2();
      divisionErrorBand->Divide(hmc);
      divisionErrorBand->Draw("E2");      
      divisionErrorBand->SetMaximum(2.49);
      divisionErrorBand->SetMinimum(0);
      divisionErrorBand->SetMarkerStyle(20);
      divisionErrorBand->SetMarkerSize(0.55);
      divisionErrorBand->GetXaxis()->SetTitleOffset(1.12);
      divisionErrorBand->GetXaxis()->SetLabelSize(0.12);
      divisionErrorBand->GetXaxis()->SetTitleSize(0.5);
      divisionErrorBand->GetYaxis()->SetTitle("Data/MC");
      divisionErrorBand->GetYaxis()->SetLabelSize(0.12);
      divisionErrorBand->GetYaxis()->SetTitleSize(0.12);
      divisionErrorBand->GetYaxis()->SetTitleOffset(0.40);
      divisionErrorBand->GetYaxis()->SetNdivisions(505);
      //divisionErrorBand->UseCurrentStyle();
      divisionErrorBand->SetFillColor(2);
      divisionErrorBand->SetFillStyle(3001);
      divisionErrorBand->SetMarkerSize(0.);

      TH1D * division = (TH1D*)(hd)->Clone("division");
      division->Sumw2();
      division->Divide(hmc);
//       division->SetMaximum(2.5);
//       division->SetMinimum(0);
//       division->SetMarkerStyle(20);
//       division->SetMarkerSize(0.55);
//       division->GetXaxis()->SetLabelSize(0.12);
//       division->GetXaxis()->SetTitleSize(0.14);
//       division->GetYaxis()->SetLabelSize(0.10);
//       division->GetYaxis()->SetTitleSize(0.10);
//      division->GetYaxis()->SetTitle("Data/MC");
      Double_t min = division->GetXaxis()->GetXmin();
      Double_t max = division->GetXaxis()->GetXmax();
      division->Draw("E1X0same");

      TLine *line = new TLine(min, 1.0, max, 1.0);
      line->SetLineColor(kRed);
      line->Draw("same");
      
      TLegend * leg3 =new TLegend(0.50,0.86,0.69,0.96);
      leg3->AddEntry(divisionErrorBand,"MC uncert. (stat.)","f");
      leg3->SetFillColor(0);
      leg3->SetLineColor(0);
      leg3->SetShadowColor(0);
      leg3->SetTextFont(62);
      leg3->SetTextSize(0.06);
      leg3->Draw();

      TPaveText *pave = new TPaveText(0.15,0.85,0.32,0.96,"brNDC");
      pave->SetTextAlign(12);
      pave->SetLineColor(0);
      pave->SetFillColor(0);
      pave->SetShadowColor(0);
      //TText *text = pave->AddText(Form("#chi_{#nu}^{2} = %.3f, K_{s} = %.3f",histDt->Chi2Test(histCopyMC5,"UWCHI2/NDF"),histDt->KolmogorovTest(histCopyMC5))); // stat + sys
      TText *text = pave->AddText(Form("#chi_{#nu}^{2} = %.3f, K_{s} = %.3f",hd->Chi2Test(hmc,"UWCHI2/NDF"),hd->KolmogorovTest(hmc))); // stat only
      text->SetTextFont(62);
      text->SetTextSize(0.08);
      pave->Draw();

      TopPad->cd();
      TLatex latex;
      latex.SetNDC();
      latex.SetTextAlign(12);
      latex.SetTextSize(0.052);
      latex.DrawLatex(0.17,0.89,"CMS Preliminary");
      latex.SetTextSize(0.04);
      latex.DrawLatex(0.17,0.84,"#sqrt{s} = 7 TeV, L = 4.7 fb^{-1}");
      //      latex.DrawLatex(0.17,0.79,"Z(e^{+}e^{-})H(b#bar{b})");
      latex.DrawLatex(0.17,0.79,process.c_str());
      c->Update();
      std::string cName= hd->GetName();
      cName += "_bare.pdf";
      cName = path+cName;
      c->Print(cName.c_str(),"pdf");

//       std::cout << names[i] << " d: " <<  hd->Integral() << " ";
//       THStack * sta2 = new THStack("sta2",hd->GetTitle());
//       float tot=0;
//       float toterr2=0;

//       if(debug_)
// 	std::cout << "Putting the iterator in the for loop" << std::endl;
//       for(std::map<std::string,TH1F *>::reverse_iterator it=grouped.rbegin(); it!=grouped.rend();++it)
//  	{
// 	  if(debug_)
// 	    std::cout << "Using the iterator" << std::endl;
// 	  std::cout << (*it).first << " " << (*it).second->Integral() << " | " << std::endl ;
// 	  if((*it).second->GetEntries() > 0) {
// 	    float er=1.*sqrt((*it).second->GetEntries())/(*it).second->GetEntries()*(*it).second->Integral();
// 	    toterr2+=er*er;
// 	  }
// 	  tot+=(*it).second->Integral();
// 	  sta2->Add(it->second);
//  	}
//       std::cout << " Tot: " << tot << "+-" << sqrt(toterr2) <<  " SF: " << hd->Integral()/tot << std::endl;
//       TCanvas *c2 = new TCanvas();
//       c2->SetTitle(names[i].c_str());
//       std::cout << "hd maximum = " << hd->GetMaximum() << "  sta2 maximum = " << sta2->GetMaximum() << std::endl;
//       if(hd->GetMaximum() > sta2->GetMaximum()) maxY =  hd->GetBinContent(hd->GetMaximumBin()) * 1.5;
//       else maxY = ( sta2->GetMaximum())*1.5;
//       //      hd->Draw("E1"); 
//       sta2->Draw("PADSHIST");
//       //    hd->Draw("E1same");
//       //      l->Draw("same");
//       std::cout << "Set Maximum to = " << maxY << std::endl;
//       hd->GetYaxis()->SetRangeUser(0.,maxY);
//       hd->GetXaxis()->SetRangeUser(options[names[i]].min,options[names[i]].max);
//       c2->Update();

//       std::string c2Name = hd->GetName();
//       c2Name = path+c2Name;
//       c2Name += "_norm.pdf";
//       c2->Print(c2Name.c_str(),"pdf");  

    }

}
Beispiel #28
0
void ootpu_comparison(TString files, TString var, TString title, int nbins, float low, float high, TString comments="") {

  TChain* chain = new TChain("reduced_tree");
  chain->Add(files);

  TH1::SetDefaultSumw2();

  TH1F* hA = new TH1F("hA",title, nbins, low, high);
  TH1F* hB = new TH1F("hB",title, nbins, low, high);
  TH1F* hC = new TH1F("hC",title, nbins, low, high);
  TH1F* hD = new TH1F("hD",title, nbins, low, high);

  TH1F* hA_l = new TH1F("hA_l",title, nbins, low, high);
  TH1F* hB_l = new TH1F("hB_l",title, nbins, low, high);
  TH1F* hC_l = new TH1F("hC_l",title, nbins, low, high);
  TH1F* hD_l = new TH1F("hD_l",title, nbins, low, high);
  hA->SetStats(0);
  hA->GetYaxis()->SetLabelSize(0.04);
  //hA->GetYaxis()->SetTitleOffset(1.3);
  hA->GetXaxis()->SetTitleOffset(1.1);
  hA->GetXaxis()->SetTitleFont(132);
  hA->GetXaxis()->SetTitleSize(0.042);
  hA->GetXaxis()->SetLabelSize(0.04);
  hA->SetLineWidth(2);

  //  hA->StatOverflows(true);
  //  hB->StatOverflows(true);
  //  hC->StatOverflows(true);
  //  hD->StatOverflows(true);

  int n1(0), n2(0), n3(0), n4(0), n5(0);
  if (files.Contains("20bx25")) {
    n1=5;
    n2=17;
    n3=21;
    n4=25;
    n5=40;
  }
  else if (files.Contains("S14")) {
    n1=0;
    n2=25;
    n3=40;
    n4=55;
    n5=120;
  }
  else { // default: 8 TeV scenario
    n1=0;
    n2=15;
    n3=22;
    n4=32;
    n5=70;
  }


  TString mu("num_gen_muons==1&&muon_reco_match>=0");
  //if (files.Contains("PU_S10")) {
  TString cuts = Form("(%s)&&(eoot_pu>=%d&&eoot_pu<%d)",mu.Data(),n1,n2);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hA", var, cuts);
  cuts = Form("(%s)&&(loot_pu>=%d&&loot_pu<%d)",mu.Data(),n1,n2);
  chain->Project("hA_l", var, cuts);
  cuts = Form("(%s)&&(eoot_pu>=%d&&eoot_pu<%d)",mu.Data(),n2,n3);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hB", var, cuts);
  cuts = Form("(%s)&&(loot_pu>=%d&&loot_pu<%d)",mu.Data(),n2,n3);
  chain->Project("hB_l", var, cuts);
  cuts = Form("(%s)&&(eoot_pu>=%d&&eoot_pu<%d)",mu.Data(),n3,n4);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hC", var, cuts);
  cuts = Form("(%s)&&(loot_pu>=%d&&loot_pu<%d)",mu.Data(),n3,n4);
  chain->Project("hC_l", var, cuts);
  cuts = Form("(%s)&&(eoot_pu>=%d)",mu.Data(),n4);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hD", var, cuts);
  cuts = Form("(%s)&&(loot_pu>=%d)",mu.Data(),n4);
  chain->Project("hD_l", var, cuts);
  // }
  // else {
  //  }
  
  float avg1(hA->GetMean());
  float avg2(hB->GetMean());
  float avg3(hC->GetMean());
  float avg4(hD->GetMean());

  hA->Scale(1/hA->Integral());
  hB->Scale(1/hB->Integral());
  hC->Scale(1/hC->Integral());
  hD->Scale(1/hD->Integral());

  hA->SetLineColor(1);
  hB->SetLineColor(2);
  hC->SetLineColor(3);
  hD->SetLineColor(4);

  hA->SetLineWidth(2);
  hB->SetLineWidth(2);
  hC->SetLineWidth(2);
  hD->SetLineWidth(2);

  float avg1_l(hA_l->GetMean());
  float avg2_l(hB_l->GetMean());
  float avg3_l(hC_l->GetMean());
  float avg4_l(hD_l->GetMean());

  hA_l->Scale(1/hA_l->Integral());
  hB_l->Scale(1/hB_l->Integral());
  hC_l->Scale(1/hC_l->Integral());
  hD_l->Scale(1/hD_l->Integral());

  hA_l->SetLineColor(12);
  hB_l->SetLineColor(46);
  hC_l->SetLineColor(8);
  hD_l->SetLineColor(7);

  hA_l->SetLineWidth(2);
  hB_l->SetLineWidth(2);
  hC_l->SetLineWidth(2);
  hD_l->SetLineWidth(2);

  TCanvas* c1 = new TCanvas();
  float max = TMath::Max(hA->GetMaximum(), hB->GetMaximum());
  if (hC->GetMaximum()>max) max = hC->GetMaximum();
  if (hD->GetMaximum()>max) max = hD->GetMaximum();

  hA->SetMaximum(max*1.1);
  hA->Draw("hist");
  hB->Draw("hist,same");
  hC->Draw("hist,same");
  hD->Draw("hist,same");
  hA_l->Draw("hist,same");
  hB_l->Draw("hist,same");
  hC_l->Draw("hist,same");
  hD_l->Draw("hist,same");

  TLegend* leg = new TLegend(0.42,0.6,0.9,0.9);
  leg->SetFillStyle(0);
  char label[1000];
  sprintf(label,"%d#leqEarly Ints.<%d (#mu=%3.3f)",n1,n2,avg1);
  leg->AddEntry(hA,label,"lp");
  sprintf(label,"%d#leqEarly Ints.<%d (#mu=%3.3f)",n2,n3,avg2);
  leg->AddEntry(hB,label,"lp");
  sprintf(label,"%d#leqEarly Ints.<%d (#mu=%3.3f)",n3,n4,avg3);
  leg->AddEntry(hC,label,"lp");
  sprintf(label,"Early Ints.>%d (#mu=%3.3f)",n4,avg4);
  leg->AddEntry(hD,label,"lp");
  // leg->Draw();

  TString plotTitle ="relIso_vs_early_and_late_OOTPU_"+var+comments+".pdf";
  c1->Print(plotTitle);

  cout << "Rejection rates" << endl;
  Double_t left(0.), lerror(0.), right(0.), rerror(0.);
  left = hA->IntegralAndError(1,12,lerror);
  right = hA->IntegralAndError(13,31,rerror);
  float rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin1: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hB->IntegralAndError(1,12,lerror);
  right = hB->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin2: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hC->IntegralAndError(1,12,lerror);
  right = hC->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin3: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hD->IntegralAndError(1,12,lerror);
  right = hD->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin4: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
}
Beispiel #29
0
void displayAllBigPeaks(TString fdat) {

  gStyle->SetOptStat(0);

  TFile *f = new TFile(fdat);
  if (f->IsZombie()){
    cout << "Cannot open file: " << fdat << endl;
    return;
  }

  TBEvent *event = new TBEvent();
  TTree *t1041 = (TTree*)f->Get("t1041"); 
  TBranch *bevent = t1041->GetBranch("tbevent");
  bevent->SetAddress(&event);

  vector<TH1F*> waves_112, waves_113, waves_115, waves_116;

  TH1F * wave = new TH1F("wave", "wave", 120, 0, 120);

  int nplots = 0;

  for (Int_t i = 0; i < t1041->GetEntries(); i++) {
    t1041->GetEntry(i);
    
    for (int j = 0; j < event->NPadeChan(); j++){
      PadeChannel pch = event->GetPadeChan(j);
      
      pch.GetHist(wave);

      if(wave->GetMaximum() < 800) continue;
      
      nplots++;
      TH1F * wavecopy = (TH1F*)wave->Clone("wave_"+TString(Form("%d", nplots)));

      int board = (int)pch.GetBoardID();

      if(board == 112) waves_112.push_back(wavecopy);
      else if(board == 113) waves_113.push_back(wavecopy);
      else if(board == 115) waves_115.push_back(wavecopy);
      else if(board == 116) waves_116.push_back(wavecopy);
      
    }
    
  }

  TCanvas * canv = new TCanvas("canv", "canv", 2000, 2000);
  canv->Divide(2,2);

  canv->cd(1);
  
  TH1F * dummy_112 = new TH1F("dummy_112", "Board 112", 120, 0, 120);
  dummy_112->GetYaxis()->SetRangeUser(90, 2200);
  dummy_112->Draw();

  for(unsigned int ui = 0; ui < waves_112.size(); ui++) {

    if(waves_112[ui]->GetMaximum() > 1500) {
      waves_112[ui]->SetLineColor(kRed);
      //waves_112[ui]->SetLineWidth(3);
    }
    else {
      waves_112[ui]->SetLineColor(kBlack);
    }

    waves_112[ui]->Draw("same");
  }

  canv->cd(2);

  TH1F * dummy_113 = new TH1F("dummy_113", "Board 113", 120, 0, 120);
  dummy_113->GetYaxis()->SetRangeUser(90, 2200);
  dummy_113->Draw();

  for(unsigned int ui = 0; ui < waves_113.size(); ui++) {

    if(waves_113[ui]->GetMaximum() > 1500) {
      waves_113[ui]->SetLineColor(kRed);
      //waves_113[ui]->SetLineWidth(3);
    }
    else {
      waves_113[ui]->SetLineColor(kBlack);
    }

    waves_113[ui]->Draw("same");
  }

  canv->cd(3);

  TH1F * dummy_115 = new TH1F("dummy_115", "Board 115", 120, 0, 120);
  dummy_115->GetYaxis()->SetRangeUser(90, 2200);
  dummy_115->Draw();

  for(unsigned int ui = 0; ui < waves_115.size(); ui++) {

    if(waves_115[ui]->GetMaximum() > 1500) {
      waves_115[ui]->SetLineColor(kRed);
      //waves_115[ui]->SetLineWidth(3);
    }
    else {
      waves_115[ui]->SetLineColor(kBlack);
    }

    waves_115[ui]->Draw("same");
  }
  
  canv->cd(4);

  TH1F * dummy_116 = new TH1F("dummy_116", "Board 116", 120, 0, 120);
  dummy_116->GetYaxis()->SetRangeUser(90, 2200);
  dummy_116->Draw();

  for(unsigned int ui = 0; ui < waves_116.size(); ui++) {

    if(waves_116[ui]->GetMaximum() > 1500) {
      waves_116[ui]->SetLineColor(kRed);
      //waves_116[ui]->SetLineWidth(3);
    }
    else {
      waves_116[ui]->SetLineColor(kBlack);
    }

    waves_116[ui]->Draw("same");
  }

  canv->SaveAs("AllBigPeaks.gif");
  
}
Beispiel #30
0
// Function to draw EE, ME, MM channel and all channel merged plot
void cutStepPlots(const char* cutStep, const char* histNameTitle[2],
                  double minY, double maxY, bool doLogY)
{
 const char* histName = histNameTitle[0];
 const char* histTitle = histNameTitle[1];

  //cout << histName << " : " << histTitle << endl;

  TH1F* hDataEE = (TH1F*)fEE->Get(Form("%s/hData_%s_%s", cutStep, cutStep, histName));
  TH1F* hDataME = (TH1F*)fME->Get(Form("%s/hData_%s_%s", cutStep, cutStep, histName));
  TH1F* hDataMM = (TH1F*)fMM->Get(Form("%s/hData_%s_%s", cutStep, cutStep, histName));

  if ( !hDataEE ) { cout << Form("%s/hData_%s_%s", cutStep, cutStep, histName) << " for EE " << "\n"; return; }
  if ( !hDataME ) { cout << Form("%s/hData_%s_%s", cutStep, cutStep, histName) << " for ME " << "\n"; return; }
  if ( !hDataMM ) { cout << Form("%s/hData_%s_%s", cutStep, cutStep, histName) << " for MM " << "\n"; return; }


  TH1F* hDataLL = (TH1F*)hDataEE->Clone(Form("hData_%s_%s", cutStep, histName));
  hDataLL->Reset();
  hDataLL->Add(hDataEE);
  hDataLL->Add(hDataME);
  hDataLL->Add(hDataMM);

  THStack* hStackEE = new THStack(TString("hEE_")+cutStep+"_"+histName, histTitle);
  THStack* hStackME = new THStack(TString("hME_")+cutStep+"_"+histName, histTitle);
  THStack* hStackMM = new THStack(TString("hMM_")+cutStep+"_"+histName, histTitle);
  THStack* hStackLL = new THStack(TString("hLL_")+cutStep+"_"+histName, histTitle);

  TH1F* hSigEE = (TH1F*)fEE->Get(Form("%s/%s_%s_%s", cutStep, sigNames[0], cutStep, histName));
  TH1F* hSigME = (TH1F*)fME->Get(Form("%s/%s_%s_%s", cutStep, sigNames[0], cutStep, histName));
  TH1F* hSigMM = (TH1F*)fMM->Get(Form("%s/%s_%s_%s", cutStep, sigNames[0], cutStep, histName));

  hSigEE->SetFillColor(color_sig);
  hSigME->SetFillColor(color_sig);
  hSigMM->SetFillColor(color_sig);

  hSigEE->SetFillStyle(style_sig);
  hSigME->SetFillStyle(style_sig);
  hSigMM->SetFillStyle(style_sig);

  //hSigEE->SetLineColor(color_sig);
  //hSigME->SetLineColor(color_sig);
  //hSigMM->SetLineColor(color_sig);




  if ( !hSigEE || !hSigME || !hSigMM ) { cout << "No signal hist for " << histName << "\n"; return; }

  TH1F* hSigLL = (TH1F*)hSigEE->Clone(Form("%s_%s_%s", sigNames[0], cutStep, histName));
  hSigLL->Reset();
  hSigLL->Add(hSigEE);
  hSigLL->Add(hSigME);
  hSigLL->Add(hSigMM);

  if( stackSig ){
    hStackEE->Add(hSigEE);
    hStackME->Add(hSigME);
    hStackMM->Add(hSigMM);
    hStackLL->Add(hSigLL);
  }

  // Build legends
  TLegend* legEE = buildLegend();
  TLegend* legME = buildLegend();
  TLegend* legMM = buildLegend();
  TLegend* legLL = buildLegend();

  if ( hDataEE->GetEntries() > 0 ) legEE->AddEntry(hDataEE, "Data", "p");
  if ( hDataME->GetEntries() > 0 ) legME->AddEntry(hDataME, "Data", "p");
  if ( hDataMM->GetEntries() > 0 ) legMM->AddEntry(hDataMM, "Data", "p");
  if ( hDataLL->GetEntries() > 0 ) legLL->AddEntry(hDataLL, "Data", "p");

  TH1F* hEEs[nBkg];
  TH1F* hMEs[nBkg];
  TH1F* hMMs[nBkg];
  TH1F* hLLs[nBkg];

  for ( int i=0; i<nBkg; ++i )
  {
    TH1F* hEE = (TH1F*)fEE->Get(Form("%s/%s_%s_%s", cutStep, bkgNames[i], cutStep, histName));
    TH1F* hME = (TH1F*)fME->Get(Form("%s/%s_%s_%s", cutStep, bkgNames[i], cutStep, histName));
    TH1F* hMM = (TH1F*)fMM->Get(Form("%s/%s_%s_%s", cutStep, bkgNames[i], cutStep, histName));

    hEE->SetFillColor(color[i]);
    hME->SetFillColor(color[i]);
    hMM->SetFillColor(color[i]);

    hEE->SetFillStyle(style[i]);
    hME->SetFillStyle(style[i]);
    hMM->SetFillStyle(style[i]);

   // hEE->SetLineColor(color[i]);
   // hME->SetLineColor(color[i]);
   // hMM->SetLineColor(color[i]);


    if ( !hEE || !hME || !hMM ) { cout << "No bkg hist " << bkgNames[i] << endl; continue; }

    TH1F* hLL = (TH1F*)hEE->Clone(Form("%s_%s_%s", bkgNames[i], cutStep, histName));
    hLL->Reset();
    hLL->Add(hEE);
    hLL->Add(hME);
    hLL->Add(hMM);

    hEEs[i] = hEE;
    hMEs[i] = hME;
    hMMs[i] = hMM;
    hLLs[i] = hLL;

    hStackEE->Add(hEE);
    hStackME->Add(hME);
    hStackMM->Add(hMM);
    hStackLL->Add(hLL);
  }

  for ( int i=nBkg-1; i>=0; --i )
  {
    legEE->AddEntry(hEEs[i], bkgLabels[i], "f");
    legME->AddEntry(hMEs[i], bkgLabels[i], "f");
    legMM->AddEntry(hMMs[i], bkgLabels[i], "f");
    legLL->AddEntry(hLLs[i], bkgLabels[i], "f");
  }

  legEE->AddEntry(hSigEE, sigLabels[0], "f");
  legME->AddEntry(hSigME, sigLabels[0], "f");
  legMM->AddEntry(hSigMM, sigLabels[0], "f");
  legLL->AddEntry(hSigLL, sigLabels[0], "f");


  // Be ready for draw
  double YmaxEE = 0, YmaxMM=0, YmaxME=0, YmaxLL=0;
  YmaxEE = hDataEE->GetMaximum();
  YmaxMM = hDataMM->GetMaximum();
  YmaxME = hDataME->GetMaximum();
  YmaxLL = hDataLL->GetMaximum();

  hDataEE->SetMinimum(minY);
  hDataME->SetMinimum(minY);
  hDataMM->SetMinimum(minY);
  hDataLL->SetMinimum(minY);

  if(YmaxEE >YmaxMM) YmaxMM=YmaxEE;
  else               YmaxEE=YmaxMM;

  if(doLogY)
  {
    hDataEE->SetMaximum(YmaxEE*10000);
    hDataME->SetMaximum(YmaxME*10000);
    hDataMM->SetMaximum(YmaxMM*10000);
    hDataLL->SetMaximum(YmaxLL*10000);
  }
  else
  {
    hDataEE->SetMaximum(YmaxEE*2.5);
    hDataME->SetMaximum(YmaxME*2.5);
    hDataMM->SetMaximum(YmaxMM*2.5);
    hDataLL->SetMaximum(YmaxLL*2.5);
  }


  TCanvas* cEE = new TCanvas(TString("cEE_")+cutStep+"_"+histName, TString("cEE_")+cutStep+"_"+histName, 1);
  if ( doLogY ) cEE->SetLogy();
  hDataEE->Draw();
  legEE->Draw();
  getHeader(19.6, "ee channel")->Draw();
  hStackEE->Draw("same");
  hSigEE->Draw("same");
  hDataEE->Draw("same");
  hDataEE->Draw("sameaxis");

  if(doLogY)
  {
    cEE->Print(Form("%s/log/cEE_%s_%s.eps", outDirName.Data(), cutStep, histName));
    cEE->Print(Form("%s/log/cEE_%s_%s.pdf", outDirName.Data(), cutStep, histName));
    cEE->Print(Form("%s/log/cEE_%s_%s.png", outDirName.Data(), cutStep, histName));
  }
  else
  {
    cEE->Print(Form("%s/linear/cEE_%s_%s.eps", outDirName.Data(), cutStep, histName));
    cEE->Print(Form("%s/linear/cEE_%s_%s.pdf", outDirName.Data(), cutStep, histName));
    cEE->Print(Form("%s/linear/cEE_%s_%s.png", outDirName.Data(), cutStep, histName));
  }

  TCanvas* cME = new TCanvas(TString("cME_")+cutStep+"_"+histName, TString("cME_")+cutStep+"_"+histName, 1);
  if ( doLogY ) cME->SetLogy();
  hDataME->Draw();
  legME->Draw();
  getHeader(19.6, "#mue channel")->Draw();
  hStackME->Draw("same");
  if( nSig > 0 ) hSigME->Draw("same");
  hDataME->Draw("same");
  hDataME->Draw("sameaxis");

  if(doLogY)
  {
    cME->Print(Form("%s/log/cME_%s_%s.eps", outDirName.Data(), cutStep, histName));
    cME->Print(Form("%s/log/cME_%s_%s.pdf", outDirName.Data(), cutStep, histName));
    cME->Print(Form("%s/log/cME_%s_%s.png", outDirName.Data(), cutStep, histName));
  }
  else
  {
    cME->Print(Form("%s/linear/cME_%s_%s.eps", outDirName.Data(), cutStep, histName));
    cME->Print(Form("%s/linear/cME_%s_%s.pdf", outDirName.Data(), cutStep, histName));
    cME->Print(Form("%s/linear/cME_%s_%s.png", outDirName.Data(), cutStep, histName));
  }


  TCanvas* cMM = new TCanvas(TString("cMM_")+cutStep+"_"+histName, TString("cMM_")+cutStep+"_"+histName, 1);
  if ( doLogY ) cMM->SetLogy();
  hDataMM->Draw();
  legMM->Draw();
  getHeader(19.6, "#mu#mu channel")->Draw();
  hStackMM->Draw("same");
  hSigMM->Draw("same");
  hDataMM->Draw("same");
  hDataMM->Draw("sameaxis");

  if(doLogY)
  {
    cMM->Print(Form("%s/log/cMM_%s_%s.eps", outDirName.Data(), cutStep, histName));
    cMM->Print(Form("%s/log/cMM_%s_%s.pdf", outDirName.Data(), cutStep, histName));
    cMM->Print(Form("%s/log/cMM_%s_%s.png", outDirName.Data(), cutStep, histName));
  }
  else
  {
    cMM->Print(Form("%s/linear/cMM_%s_%s.eps", outDirName.Data(), cutStep, histName));
    cMM->Print(Form("%s/linear/cMM_%s_%s.pdf", outDirName.Data(), cutStep, histName));
    cMM->Print(Form("%s/linear/cMM_%s_%s.png", outDirName.Data(), cutStep, histName));
  } 

  TCanvas* cLL = new TCanvas(TString("cLL_")+cutStep+"_"+histName, TString("cLL_")+cutStep+"_"+histName, 1);
  if ( doLogY ) cLL->SetLogy();
  hDataLL->Draw();
  legLL->Draw();
  getHeader(19.6, "All channel")->Draw();
  hStackLL->Draw("same");
  if( !stackSig ) hSigLL->Draw("same");
  hDataLL->Draw("same");
  hDataLL->Draw("sameaxis");

  if(doLogY)
  {
    cLL->Print(Form("%s/log/cLL_%s_%s.eps", outDirName.Data(), cutStep, histName));
    cLL->Print(Form("%s/log/cLL_%s_%s.pdf", outDirName.Data(), cutStep, histName));
    cLL->Print(Form("%s/log/cLL_%s_%s.png", outDirName.Data(), cutStep, histName));
  } 
  else
  {
    cLL->Print(Form("%s/linear/cLL_%s_%s.eps", outDirName.Data(), cutStep, histName));
    cLL->Print(Form("%s/linear/cLL_%s_%s.pdf", outDirName.Data(), cutStep, histName));
    cLL->Print(Form("%s/linear/cLL_%s_%s.png", outDirName.Data(), cutStep, histName));
  }
}