Esempio n. 1
0
void VetoEnergy3(Int_t Lo, Int_t Hi)
{
  TCanvas* Window;
  TTimer* Refresh;
  TH1F* Energy;
  TF1* Fit;
  Char_t Buff[256];
  Char_t* Keyb;
  Double_t Pos[438];
  Double_t Lower;
  Double_t Param[3];
  Int_t OK;

  Window = new TCanvas();
  Window->SetCrosshair();
  Window->ToggleEventStatus();
  Refresh = new TTimer("Flush()", 50, kFALSE);
  for(Int_t ch=Lo; ch<Hi+1; ch++)
  {
    sprintf(Buff, "Veto_Energy%d", ch);
    Energy = (TH1F*)gROOT->FindObject(Buff);
    Energy->Draw();
    Window->Update();

    Fit = new TF1("F1", "gaus", 0.7, 2.0);
    Energy->Fit("F1", "RQ");
    Fit->Draw("same");
    Window->Update();
    Fit->GetParameters(Param);

    Refresh->TurnOn();
    Refresh->Reset();
    sprintf(Buff, "OK for %d? ", ch);
    Keyb = Getline(Buff);
    Refresh->TurnOff();
    OK = atoi(Keyb);
    if(OK) goto Done;

Refit:
    Refresh->TurnOn();
    Refresh->Reset();
    sprintf(Buff, "Lower bound for %d: ", ch);
    Keyb = Getline(Buff);
    Refresh->TurnOff();
    Lower = atof(Keyb);

    Fit = new TF1("F1", "gaus", Lower, 2.0);
    Energy->Fit("F1", "RQ");
    Fit->Draw("same");
    Window->Update();
    Fit->GetParameters(Param);

    Refresh->TurnOn();
    Refresh->Reset();
    sprintf(Buff, "OK for %d? ", ch);
    Keyb = Getline(Buff);
    Refresh->TurnOff();
    OK = atoi(Keyb);
    if(!OK) goto Refit;

Done:
    Pos[ch] = Param[1];
  }
  for(Int_t ch=Lo; ch<Hi+1; ch++)
    printf("%8.6f\n", Pos[ch]);
}
int makePlot_EEMC_Lin_and_Res_v2()
{
  /*----------------Basic Configuration-------------------*/

  vector< float > v_pbeam;
  vector< float > v_pberr;
  vector< TString > v_fnames;

  v_pbeam.push_back(  5 );
  v_pbeam.push_back( 10 );
  v_pbeam.push_back( 15 );
  v_pbeam.push_back( 20 );
  v_pbeam.push_back( 25 );
  v_pbeam.push_back( 30 );

  v_pberr.push_back( 0 );
  v_pberr.push_back( 0 );
  v_pberr.push_back( 0 );
  v_pberr.push_back( 0 );
  v_pberr.push_back( 0 );
  v_pberr.push_back( 0 );
/*
  v_fnames.push_back( "./G4Shower_eEMCAL_p_5_5_GeV_eta_-2_-2.root" );
  v_fnames.push_back( "./G4Shower_eEMCAL_p_10_10_GeV_eta_-2_-2.root" );
  v_fnames.push_back( "./G4Shower_eEMCAL_p_15_15_GeV_eta_-2_-2.root" );
  v_fnames.push_back( "./G4Shower_eEMCAL_p_20_20_GeV_eta_-2_-2.root" );
  v_fnames.push_back( "./G4Shower_eEMCAL_p_25_25_GeV_eta_-2_-2.root" );
  v_fnames.push_back( "./G4Shower_eEMCAL_p_30_30_GeV_eta_-2_-2.root" );
*/    
  v_fnames.push_back( "./TowerAna_eEMCAL_p_5_5_GeV_eta_-2_-2.root" );
  v_fnames.push_back( "./TowerAna_eEMCAL_p_10_10_GeV_eta_-2_-2.root" );
  v_fnames.push_back( "./TowerAna_eEMCAL_p_15_15_GeV_eta_-2_-2.root" );
  v_fnames.push_back( "./TowerAna_eEMCAL_p_20_20_GeV_eta_-2_-2.root" );
  v_fnames.push_back( "./TowerAna_eEMCAL_p_25_25_GeV_eta_-2_-2.root" );
  v_fnames.push_back( "./TowerAna_eEMCAL_p_30_30_GeV_eta_-2_-2.root" );
    
  /*----------------Get Input Histograms-------------------*/

  vector< TH1F* > v_h_esum;

  TFile *f_in = NULL;
  for ( unsigned i = 0; i < v_fnames.size(); i++ )
    {

      f_in = new TFile( v_fnames.at(i), "OPEN" );
      v_h_esum.push_back( (TH1F*)f_in->Get("h_esum") );
      v_h_esum.at( i )->Print();
      
    }

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

  /*----------------Modify Histograms-------------------*/

  for ( unsigned i = 0; i < v_h_esum.size(); i++ )
    {
      v_h_esum.at( i )->Rebin( 700 ); //Sweet spot somewhere between 10 and 17... idk
    }

  /*----------Convert Digitized Photons to Energy--------------*/
  /*  
  vector< TH1F* > v_h_esum_v2;

  float NperMeV = 200;
  float EtoMeV = 1000;

  for ( unsigned i = 0; i < v_h_esum.size(); i++ )
    {
      TH1F* h_raw = v_h_esum.at( i );
      TH1F* h_digi = (TH1F*)h_raw->Clone("h_digi");
      h_digi->Reset();

	for ( int idx1 = 0; idx1 < h_raw->GetNbinsX(); idx1++ )
	  {
	    float eraw_i = h_raw->GetXaxis()->GetBinCenter( idx1 );
	    float craw_i = h_raw->GetBinContent( idx1 );

	    for ( int idx2 = 0; idx2 < craw_i; idx2++ )
	      {
		h_digi->Fill( eraw_i / (NperMeV * EtoMeV ) );
	      }
	  }
      v_h_esum_v2.push_back ( h_digi );
      }
  /*----------------AdHoc Digitization-------------------*/
  /*  
  vector< TH1F* > v_h_esum_v2;

  TRandom *rand = new TRandom();

  float NperMeV = 200;
  float EtoMeV = 1000;

  for ( unsigned i = 0; i < v_h_esum.size(); i++ )
    {

      TH1F* h_raw = v_h_esum.at( i );
      TH1F* h_digi = (TH1F*)h_raw->Clone("h_digi");
      h_digi->Reset();

      for ( int idx1 = 0; idx1 < h_raw->GetNbinsX(); idx1++ )
	{
	  float eraw_i = h_raw->GetXaxis()->GetBinCenter( idx1 );
	  float craw_i = h_raw->GetBinContent( idx1 );

	  for ( int idx2 = 0; idx2 < craw_i; idx2++ )
	    {
	      h_digi->Fill( rand->Poisson( NperMeV * EtoMeV * eraw_i ) / ( NperMeV * EtoMeV ) );
	    }
	}

      v_h_esum_v2.push_back( h_digi );
  
    }
  
  */
  /*----------------Gaussian Fits-------------------*/

  vector< float > v_gauss_mean;
  vector< float > v_gauss_merr;
  vector< float > v_gauss_sigm;
  vector< float > v_gauss_serr;

    for ( unsigned i = 0; i < v_h_esum.size(); i++ )
    //for ( unsigned i = 0; i < v_h_esum_v2.size(); i++ )
    {
      TCanvas *cfit = new TCanvas();
      cfit->cd();
      
      //without AdHoc Digitization
               v_h_esum.at( i )->Fit("gaus","","");
	    
	    v_gauss_mean.push_back( v_h_esum.at( i )->GetFunction("gaus")->GetParameter( 1 )/200 );
	    v_gauss_merr.push_back( v_h_esum.at( i )->GetFunction("gaus")->GetParError(1)/200);
	    v_gauss_sigm.push_back( v_h_esum.at( i )->GetFunction("gaus")->GetParameter( 2 ) / v_h_esum.at( i )->GetFunction("gaus")->GetParameter( 1 ) );

	    v_gauss_serr.push_back( v_gauss_sigm.at( i )*(sqrt(((v_gauss_merr.at(i))/(v_gauss_mean.at(i))) + ((v_h_esum.at( i )->GetFunction("gaus")->GetParError(2))/(v_h_esum.at( i )->GetFunction("gaus")->GetParameter(2))))));

	    //v_gauss_sigm.push_back( v_h_esum.at( i )->GetFunction("gaus")->GetParameter( 2 ) / v_pbeam.at( i ));
	  
	    /*          
	    //with AdHoc Digitization
	    
	    v_h_esum_v2.at( i )->Fit("gaus","","");

	    v_gauss_mean.push_back( v_h_esum_v2.at( i )->GetFunction("gaus")->GetParameter( 1 ) );
	    v_gauss_merr.push_back( v_h_esum_v2.at( i )->GetFunction("gaus")->GetParError(1));
      
	    //v_gauss_sigm.push_back( v_h_esum_v2.at( i )->GetFunction("gaus")->GetParameter( 2 ) / v_pbeam.at( i ));

	    v_gauss_sigm.push_back( v_h_esum_v2.at( i )->GetFunction("gaus")->GetParameter( 2 ) / v_h_esum_v2.at( i )->GetFunction("gaus")->GetParameter( 1 ) );

	    //v_gauss_serr.push_back( v_h_esum_v2.at(i)->GetFunction("gaus")->GetParError(2));

            v_gauss_serr.push_back( v_gauss_sigm.at( i )*(sqrt(((v_gauss_merr.at(i))/(v_gauss_mean.at(i))) + ((v_h_esum_v2.at( i )->GetFunction("gaus")->GetParError(2))/(v_h_esum_v2.at( i )->GetFunction("gaus")->GetParameter(2))))));
	    */
	    
    }
	    
  /*-----------------------------------------------*/

  /*-------------------Linearity-------------------*/

    TGraphErrors *eemc_lin = new TGraphErrors(v_pbeam.size(), &(v_pbeam[0]), &(v_gauss_mean[0]), &(v_pberr[0]), &(v_gauss_merr[0]));
    //TGraph *eemc_lin = new TGraph ( v_pbeam.size(), &(v_pbeam[0]), &(v_gauss_mean[0]) );
  eemc_lin->SetTitle("");
  eemc_lin->GetXaxis()->SetTitle("p_{Beam} [GeV]");
  //eemc_lin->GetXaxis()->SetTitleSize(0.06);
  //eemc_lin->GetXaxis()->SetLabelSize(0.06);
  eemc_lin->GetYaxis()->SetTitle("E_{Dep} [GeV]");
  //eemc_lin->GetYaxis()->SetTitleSize(0.06);

  //TF1 *lin_fit = new TF1("lin_fit", "[0]*x+0", 0, 40);

  TCanvas *c_eemc_lin = new TCanvas();
  c_eemc_lin->cd();
  eemc_lin->SetMarkerStyle(20);
  eemc_lin->SetMarkerSize(0.7);
  eemc_lin->SetLineWidth(1);
  //c_eemc_lin->SetLabelSize(0.07, "X");
  //c_eemc_lin->SetLabelOffset(1);
  eemc_lin->Draw("AP");
  eemc_lin->Fit("pol1","","");

  
  c_eemc_lin->Print("Plots/EEMC_Lin_Digi_e-_100.eps");
  c_eemc_lin->Print("Plots/EEMC_Lin_Digi_e-_100.png");

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

  /*----------------Resolution---------------------*/

  TGraphErrors *eemc_res = new TGraphErrors( v_pbeam.size(), &(v_pbeam[0]), &(v_gauss_sigm[0]), &(v_pberr[0]), &(v_gauss_serr[0]));
  //TGraph *eemc_res = new TGraph ( v_pbeam.size(), &(v_pbeam[0]), &(v_gauss_sigm[0]) );
  eemc_res->SetTitle("");
  eemc_res->GetXaxis()->SetTitle("p_{Beam} [GeV]");
  eemc_res->GetYaxis()->SetTitle("#sigma/E_{Dep}");

  TF1 *res_fit = new TF1("res_fit", "[0]*1/sqrt(x)", 0, 40);
  TF1 *res_the = new TF1("res_the", "0.02/sqrt(x)", 0 , 40);

  TCanvas *c_eemc_res = new TCanvas();
  c_eemc_res->cd();
  eemc_res->SetMarkerStyle(20);
  eemc_res->SetMarkerSize(0.7);
  eemc_res->Draw("AP");
  eemc_res->Fit("res_fit","","");
  
  res_the->Draw("SAME");
  res_the->SetLineColor(kBlue);
  res_fit->Print();

  c_eemc_res->Print("Plots/EEMC_Res_Digi_e-_100.eps");
  c_eemc_res->Print("Plots/EEMC_Res_Digi_e-_100.png");

  return 0;
}
Esempio n. 3
0
TF1* fit(Float_t ptmin, Float_t ptmax)
{
  TCanvas* c = new TCanvas(Form("c_%.0f_%.0f",ptmin,ptmax),"",600,600);
  TFile* infile = new TFile(Form("%s_%s_cent_%.0f_%.0f_pt_%.0f_%.0f.root",infname.Data(),collisionsystem.Data(),centmin,centmax,ptmin,ptmax));
  TH1D* h = (TH1D*)infile->Get("h");                    h->SetName(Form("h_%.0f_%.0f",ptmin,ptmax));
  TH1D* hMCSignal = (TH1D*)infile->Get("hMCSignal");    hMCSignal->SetName(Form("hMCSignal_%.0f_%.0f",ptmin,ptmax));
  TH1D* hMCSwapped = (TH1D*)infile->Get("hMCSwapped");  hMCSwapped->SetName(Form("hMCSwapped_%.0f_%.0f",ptmin,ptmax));
  TF1* f = new TF1(Form("f_%.0f_%.0f",ptmin,ptmax),"[0]*([7]*([9]*Gaus(x,[1],[2]*(1+[11]))/(sqrt(2*3.14159)*[2]*(1+[11]))+(1-[9])*Gaus(x,[1],[10]*(1+[11]))/(sqrt(2*3.14159)*[10]*(1+[11])))+(1-[7])*Gaus(x,[1],[8]*(1+[11]))/(sqrt(2*3.14159)*[8]*(1+[11])))+[3]+[4]*x+[5]*x*x+[6]*x*x*x", 1.7, 2.0);

  f->SetParLimits(4,-1000,1000);
  f->SetParLimits(10,0.001,0.05);
  f->SetParLimits(2,0.01,0.1);
  f->SetParLimits(8,0.02,0.2);
  f->SetParLimits(7,0,1);
  f->SetParLimits(9,0,1);
  
  f->SetParameter(0,setparam0);
  f->SetParameter(1,setparam1);
  f->SetParameter(2,setparam2);
  f->SetParameter(10,setparam10);
  f->SetParameter(9,setparam9);

  f->FixParameter(8,setparam8);
  f->FixParameter(7,1);
  f->FixParameter(1,fixparam1);
  f->FixParameter(3,0);
  f->FixParameter(4,0);
  f->FixParameter(5,0);
  f->FixParameter(6,0);
  f->FixParameter(11,0);
  h->GetEntries();
  
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"q","",minhisto,maxhisto);
  f->ReleaseParameter(1);
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L m q","",minhisto,maxhisto);
  
  f->FixParameter(1,f->GetParameter(1));
  f->FixParameter(2,f->GetParameter(2));
  f->FixParameter(10,f->GetParameter(10));
  f->FixParameter(9,f->GetParameter(9));
  f->FixParameter(7,0);
  f->ReleaseParameter(8);
  f->SetParameter(8,setparam8);
  
  hMCSwapped->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L m q","",minhisto,maxhisto);
  
  f->FixParameter(7,hMCSignal->Integral(0,1000)/(hMCSwapped->Integral(0,1000)+hMCSignal->Integral(0,1000)));
  f->FixParameter(8,f->GetParameter(8));
  f->ReleaseParameter(3);
  f->ReleaseParameter(4);
  f->ReleaseParameter(5);
  f->ReleaseParameter(6);

  f->SetLineColor(kRed);
  
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"q","",minhisto,maxhisto);
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"q","",minhisto,maxhisto);
  f->ReleaseParameter(1);
  f->SetParLimits(1,1.85,1.90);
  f->ReleaseParameter(11);
  f->SetParLimits(11,-1,1);
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  f->FixParameter(11,f->GetParameter(11)-f->GetParError(11));
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L m","",minhisto,maxhisto);
  
  TF1* background = new TF1(Form("background_%.0f_%.0f",ptmin,ptmax),"[0]+[1]*x+[2]*x*x+[3]*x*x*x");
  background->SetParameter(0,f->GetParameter(3));
  background->SetParameter(1,f->GetParameter(4));
  background->SetParameter(2,f->GetParameter(5));
  background->SetParameter(3,f->GetParameter(6));
  background->SetLineColor(4);
  background->SetRange(minhisto,maxhisto);
  background->SetLineStyle(2);
  
  TF1* mass = new TF1(Form("fmass_%.0f_%.0f",ptmin,ptmax),"[0]*([3]*([4]*Gaus(x,[1],[2]*(1+[6]))/(sqrt(2*3.14159)*[2]*(1+[6]))+(1-[4])*Gaus(x,[1],[5]*(1+[6]))/(sqrt(2*3.14159)*[5]*(1+[6]))))");
  mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(9),f->GetParameter(10),f->GetParameter(11));
  mass->SetParError(0,f->GetParError(0));
  mass->SetParError(1,f->GetParError(1));
  mass->SetParError(2,f->GetParError(2));
  mass->SetParError(3,f->GetParError(7));
  mass->SetParError(4,f->GetParError(9));
  mass->SetParError(5,f->GetParError(10));
  mass->SetFillColor(kOrange-3);
  mass->SetFillStyle(3002);
  mass->SetLineColor(kOrange-3);
  mass->SetLineWidth(3);
  mass->SetLineStyle(2);
  
  TF1* massSwap = new TF1(Form("fmassSwap_%.0f_%.0f",ptmin,ptmax),"[0]*(1-[2])*Gaus(x,[1],[3]*(1+[4]))/(sqrt(2*3.14159)*[3]*(1+[4]))");
  massSwap->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(7),f->GetParameter(8),f->GetParameter(11));
  massSwap->SetParError(0,f->GetParError(0));
  massSwap->SetParError(1,f->GetParError(1));
  massSwap->SetParError(2,f->GetParError(7));
  massSwap->SetParError(3,f->GetParError(8));
  massSwap->SetFillColor(kGreen+4);
  massSwap->SetFillStyle(3005);
  massSwap->SetLineColor(kGreen+4);
  massSwap->SetLineWidth(3);
  massSwap->SetLineStyle(1);
  
  h->SetXTitle("m_{#piK} (GeV/c^{2})");
  h->SetYTitle("Entries / (5 MeV/c^{2})");
  h->GetXaxis()->CenterTitle();
  h->GetYaxis()->CenterTitle();
  h->SetAxisRange(0,h->GetMaximum()*1.4*1.2,"Y");
  h->GetXaxis()->SetTitleOffset(1.3);
  h->GetYaxis()->SetTitleOffset(1.8);
  h->GetXaxis()->SetLabelOffset(0.007);
  h->GetYaxis()->SetLabelOffset(0.007);
  h->GetXaxis()->SetTitleSize(0.045);
  h->GetYaxis()->SetTitleSize(0.045);
  h->GetXaxis()->SetTitleFont(42);
  h->GetYaxis()->SetTitleFont(42);
  h->GetXaxis()->SetLabelFont(42);
  h->GetYaxis()->SetLabelFont(42);
  h->GetXaxis()->SetLabelSize(0.04);
  h->GetYaxis()->SetLabelSize(0.04);
  h->SetMarkerSize(0.8);
  h->SetMarkerStyle(20);
  h->SetStats(0);
  h->Draw("e");

  background->Draw("same");   
  mass->SetRange(minhisto,maxhisto);	
  mass->Draw("same");
  massSwap->SetRange(minhisto,maxhisto);
  massSwap->Draw("same");
  f->Draw("same");
  
  Float_t yield = mass->Integral(minhisto,maxhisto)/binwidthmass;
  Float_t yieldErr = mass->Integral(minhisto,maxhisto)/binwidthmass*mass->GetParError(0)/mass->GetParameter(0);
  
  std::cout<<"YIELD="<<yield<<std::endl;

  TLegend* leg = new TLegend(0.65,0.58,0.82,0.88,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextSize(0.04);
  leg->SetTextFont(42);
  leg->SetFillStyle(0);
  leg->AddEntry(h,"Data","pl");
  leg->AddEntry(f,"Fit","l");
  leg->AddEntry(mass,"D^{0}+#bar{D^{#lower[0.2]{0}}} Signal","f");
  leg->AddEntry(massSwap,"K-#pi swapped","f");
  leg->AddEntry(background,"Combinatorial","l");
  leg->Draw("same");

  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);
  texCms->Draw();

  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);
  texCol->Draw();

  TLatex* texPt = new TLatex(0.22,0.78,Form("%.1f < p_{T} < %.1f GeV/c",ptmin,ptmax));
  texPt->SetNDC();
  texPt->SetTextFont(42);
  texPt->SetTextSize(0.04);
  texPt->SetLineWidth(2);
  texPt->Draw();

  TLatex* texY = new TLatex(0.22,0.83,"|y| < 1.0");
  texY->SetNDC();
  texY->SetTextFont(42);
  texY->SetTextSize(0.04);
  texY->SetLineWidth(2);
  texY->Draw();

  TLatex* texYield = new TLatex(0.22,0.73,Form("N_{D} = %.0f #pm %.0f",yield,yieldErr));
  texYield->SetNDC();
  texYield->SetTextFont(42);
  texYield->SetTextSize(0.04);
  texYield->SetLineWidth(2);
  texYield->Draw();

  c->SaveAs(Form("plotFits/DMass_decreasewid_%s_cent_%.0f_%.0f_pt_%.0f_%.0f.pdf",collisionsystem.Data(),centmin,centmax,ptmin,ptmax));
  
  TCanvas* cPull = new TCanvas(Form("cPull_%.0f_%.0f",ptmin,ptmax),"",600,700);
  TH1D* hPull = (TH1D*)h->Clone("hPull");
  for(int i=0;i<h->GetNbinsX();i++)
    {
      Float_t nfit = f->Integral(h->GetBinLowEdge(i+1),h->GetBinLowEdge(i+1)+h->GetBinWidth(i+1))/h->GetBinWidth(i+1);
      if(h->GetBinError(i+1)==0)
        {
          hPull->SetBinContent(i+1,0.);
        }
      else hPull->SetBinContent(i+1,(h->GetBinContent(i+1)-nfit)/h->GetBinError(i+1));
      hPull->SetBinError(i+1,0);
    }
  hPull->SetMinimum(-4.);
  hPull->SetMaximum(4.);
  hPull->SetYTitle("Pull");
  hPull->GetXaxis()->SetTitleOffset(1.);
  hPull->GetYaxis()->SetTitleOffset(0.65);
  hPull->GetXaxis()->SetLabelOffset(0.007);
  hPull->GetYaxis()->SetLabelOffset(0.007);
  hPull->GetXaxis()->SetTitleSize(0.12);
  hPull->GetYaxis()->SetTitleSize(0.12);
  hPull->GetXaxis()->SetLabelSize(0.1);
  hPull->GetYaxis()->SetLabelSize(0.1);
  hPull->GetYaxis()->SetNdivisions(504);
  TLine* lPull = new TLine(1.7, 0, 2., 0);
  lPull->SetLineWidth(1);
  lPull->SetLineStyle(7);
  lPull->SetLineColor(1);
  TPad* pFit = new TPad("pFit","",0,0.3,1,1);
  pFit->SetBottomMargin(0);
  pFit->Draw();
  pFit->cd();
  h->Draw("e");
  background->Draw("same");   
  mass->Draw("same");
  massSwap->Draw("same");
  f->Draw("same");
  leg->Draw("same");
  texCms->Draw();
  texCol->Draw();
  texPt->Draw();
  texY->Draw();
  texYield->Draw();
  cPull->cd();
  TPad* pPull = new TPad("pPull","",0,0,1,0.3);
  pPull->SetTopMargin(0);
  pPull->SetBottomMargin(0.3);
  pPull->Draw();
  pPull->cd();
  hPull->Draw("p");
  lPull->Draw();
  cPull->cd();
  cPull->SaveAs(Form("plotFits/DMass_decreasewid_%s_cent_%.0f_%.0f_pt_%.0f_%.0f_Pull.pdf",collisionsystem.Data(),centmin,centmax,ptmin,ptmax));
  
  return mass;
}
Esempio n. 4
0
void draw_obj(std::string var="ptTau1", std::string cut="(ptTau2>45 && abs(etaTau1)<4.0 && abs(etaTau2)<4.0)", int chan_cat=1, int yTau=0, int yB=1, int nbins=10, double xmin=0, double xmax=500,std::string xtitle="leading #tau p_{T}", std::string ytitle="Events")
{
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  TH1::SetDefaultSumw2(1);

  std::string dir = "/afs/cern.ch/work/j/jlawhorn/public/comb_ntuples/";
  double sigscale = 1000;
  double sigscale1 = 10; 
  std::stringstream scale; scale << sigscale;
  std::stringstream scale1; scale1 << sigscale1;

  //Cut definitions
  double luminosity = 3000;
  std::stringstream lumi; lumi << luminosity;

  std::string ttcut = "(tauCat1==1 && tauCat2==1 && bTag1>0 && bTag2>0 && ptTau1>45 && ptTau2>45)";
  std::string mtcut = "((tauCat1==1 && tauCat2==3)||(tauCat2==1 && tauCat1==3))*(bTag1>0 && bTag2>0 && ptTau1>30 && ptTau2>30)";
  std::string etcut = "((tauCat1==1 && tauCat2==2)||(tauCat2==1 && tauCat1==2))*(bTag1>0 && bTag2>0 && ptTau1>30 && ptTau2>30)";
  std::string emcut = "((tauCat1==3 && tauCat2==2)||(tauCat2==3 && tauCat1==2))*(bTag1>0 && bTag2>0 && ptTau1>30 && ptTau2>30)";

  std::string taucut = "(abs(etaTau1)<4.0 && abs(etaTau2)<4.0)";
  std::string bcut = "(ptB1>30 && ptB2>30 && abs(etaB1)<4.0 && abs(etaB2)<4.0)";

  std::string optcut = cut;

  if (chan_cat==0) { //tt
    optcut = cut+"*"+ttcut;
    if (yTau==1) optcut+="*"+taucut+"*(ptTau1>45 && ptTau2>45)";
  }
  else if (chan_cat==1) { //mt
    optcut = cut+"*"+mtcut;
    if (yTau==1) optcut+="*"+taucut+"*(ptTau1>30 && ptTau2>30)";
  }
  else if (chan_cat==2) { //et
    optcut = cut+"*"+etcut;
    if (yTau==1) optcut+="*"+taucut+"*(ptTau1>30 && ptTau2>30)";
  }
  else if (chan_cat==3) { //em
    optcut = cut+"*"+emcut;
    if (yTau==1) optcut+="*"+taucut+"*(ptTau1>30 && ptTau2>30)";
  }

  if (yB==1) optcut+="*"+bcut;

  //cout << optcut << endl;
  
  //signal region
  std::string hhcut = optcut+"*"+scale.str()+"*eventWeight*(1)*"+lumi.str();
  std::string ttbarcut = optcut+"*eventWeight*(1)*"+lumi.str();
  std::string hcut = optcut+"*eventWeight*(1)*"+lumi.str();
  std::string zjetcut = optcut+"*eventWeight*(eventType==4)*"+lumi.str();
  std::string ewkcut = optcut+"*eventWeight*(eventType!=4)*"+lumi.str();
  
  //--------------------------------------------------------------------------
  
  //Get the trees
  TTree *ttbartree = load(dir+"tt.root"); 
  TTree *htree = load(dir+"H.root"); 
  TTree *ewktree = load(dir+"EWK.root"); 
  TTree *sigtree = load(dir+"HHToTTBB_14TeV.root"); 

  //-------------------------------------------------------------------------
  
  //Get histograms
  TCanvas *canv0 = MakeCanvas("canv", "histograms", 600, 600);
  canv0->cd();
  std::string vardraw;
  TH1F *sig = new TH1F("HH","",nbins,xmin,xmax);
  vardraw = var+">>"+"HH";
  sigtree->Draw(vardraw.c_str(),hhcut.c_str());
  InitSignal(sig);
  sig->SetLineColor(kBlack);
  TH1F *ttbar = new TH1F("TTbar","",nbins,xmin,xmax);
  vardraw = var+">>"+"TTbar";
  ttbartree->Draw(vardraw.c_str(),ttbarcut.c_str());
  InitHist(ttbar, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(155,152,204), 1001);
  TH1F *hbg = new TH1F("H","",nbins,xmin,xmax);
  vardraw = var+">>"+"H";
  htree->Draw(vardraw.c_str(),hcut.c_str());
  InitHist(hbg, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(141,201,159), 1001);
  TH1F *zjet = new TH1F("Zjets","",nbins,xmin,xmax);
  vardraw = var+">>"+"Zjets";
  ewktree->Draw(vardraw.c_str(),zjetcut.c_str());
  InitHist(zjet, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(222,90,106), 1001);
  TH1F *ewk = new TH1F("EWK","",nbins,xmin,xmax);
  vardraw = var+">>"+"EWK";
  ewktree->Draw(vardraw.c_str(),ewkcut.c_str());
  InitHist(ewk, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(248,206,104), 1001);

  cout << sig->GetEntries() << endl;
  cout << ttbar->GetEntries() << endl;
  cout << hbg->GetEntries() << endl;
  cout << zjet->GetEntries() << endl;
  cout << ewk->GetEntries() << endl;
  
  delete canv0;
  //-----------------------------------------------------------------------
  //Draw the histograms
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  zjet->Add(ewk); hbg->Add(zjet); ttbar->Add(hbg);
  //Error band stat
  TH1F* errorBand = (TH1F*)sig ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  //  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
  //     if(errorBand->GetBinContent(idx)>0){
  //       std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
  //       break;
  //     }
  //}
  ttbar->SetMaximum(1.2*std::max(maximum(ttbar, 0), maximum(ewk, 0)));
  //blind(sig,75,150);
  ttbar->Draw("hist");
  hbg->Draw("histsame");
  zjet->Draw("histsame");
  ewk->Draw("histsame");
  sig->Draw("histsame");
  //errorBand->Draw("e2same");
  canv->RedrawAxis();
  //---------------------------------------------------------------------------
  //Adding a legend
  TLegend* leg = new TLegend(0.53, 0.73, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(sig , TString::Format("%.0f#timeshh#rightarrow#tau#tau bb", sigscale)      , "L");
  leg->AddEntry(ttbar, "t#bar{t}"              , "F" );
  leg->AddEntry(hbg  , "H"  , "F" );
  leg->AddEntry(zjet  , "Z+jets"           , "F" );
  leg->AddEntry(ewk  , "EWK"           , "F" );
  //leg->AddEntry(errorBand,"bkg. uncertainty","F");
  leg->Draw();
  //---------------------------------------------------------------------------
  
  //CMS preliminary 
  const char* dataset = "CMS Preliminary, HH#rightarrow bb#tau#tau, 3.0 ab^{-1} at 14 TeV";

  char category[50];
  if (chan_cat==0) sprintf(category,"#tau_{h}#tau_{h}");
  if (chan_cat==1) sprintf(category,"#mu#tau_{h}");
  if (chan_cat==2) sprintf(category,"e#tau_{h}");
  if (chan_cat==3) sprintf(category,"e#mu");

  //CMSPrelim(dataset, "#tau_{h}#tau_{h}", 0.17, 0.835);
  //CMSPrelim(dataset, "#tau_{h}#tau_{h}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.26, 0.77, 0.37, 0.85, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->Draw();
  //-------------------------------------------------------------------------
  //Save histograms

  char outfile[50];
  if (chan_cat==0) sprintf(outfile, "%s_tt.png", var.c_str());
  if (chan_cat==1) sprintf(outfile, "%s_mt.png", var.c_str());
  if (chan_cat==2) sprintf(outfile, "%s_et.png", var.c_str());
  if (chan_cat==3) sprintf(outfile, "%s_em.png", var.c_str());

  canv->Print(outfile);

}
void 
HTT_MM_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="mumu_$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("mumu_0jet_low"             )){ category = "#mu#mu, 0 jet";          }    
  if(std::string(directory) == std::string("mumu_0jet_low"             )){ category_extra = "p_{T}(lep1) low";          }    
  if(std::string(directory) == std::string("mumu_0jet_high"            )){ category = "#mu#mu, 0 jet";          }    
  if(std::string(directory) == std::string("mumu_0jet_high"            )){ category_extra = "p_{T}(lep1) high";         }    
  if(std::string(directory) == std::string("mumu_1jet_low"          )){ category = "#mu#mu, 1 jet";          }    
  if(std::string(directory) == std::string("mumu_1jet_low"          )){ category_extra = "p_{T}(lep1) low";       }    
  if(std::string(directory) == std::string("mumu_1jet_high"          )){ category = "#mu#mu, 1 jet";          }    
  if(std::string(directory) == std::string("mumu_1jet_high"          )){ category_extra = "p_{T}(lep1) high";       }    
  if(std::string(directory) == std::string("mumu_vbf"            )){ category = "#mu#mu, 2 jet";          }    
  if(std::string(directory) == std::string("mumu_vbf"            )){ category_extra = "VBF";              }    
  if(std::string(directory) == std::string("mumu_nobtag"               )){ category = "#mu#mu";          }    
  if(std::string(directory) == std::string("mumu_nobtag"               )){ category_extra = "No B-Tag";                        }    
  if(std::string(directory) == std::string("mumu_btag"                 )){ category = "#mu#mu";          }    
  if(std::string(directory) == std::string("mumu_btag"                 )){ category_extra = "B-Tag";                           }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 19.8 fb^{-1} at 8 TeV";}
 
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* ZTT      = refill((TH1F*)input ->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"     ); InitHist(ZTT     , "", "", kOrange  -  4, 1001);
  TH1F* ZMM      = refill((TH1F*)input ->Get(TString::Format("%s/ZMM"     , directory)), "ZMM"     ); InitHist(ZMM     , "", "", kAzure   +  2, 1001);
  TH1F* TTJ      = refill((TH1F*)input ->Get(TString::Format("%s/TTJ"     , directory)), "TTJ"     ); InitHist(TTJ     , "", "", kBlue    -  8, 1001);
  TH1F* QCD      = refill((TH1F*)input ->Get(TString::Format("%s/QCD"     , directory)), "QCD"     ); InitHist(QCD     , "", "", kMagenta - 10, 1001);
  TH1F* Dibosons = refill((TH1F*)input ->Get(TString::Format("%s/Dibosons", directory)), "Dibosons"); InitHist(Dibosons, "", "", kRed     +  2, 1001);
  TH1F* WJets    = 0;
  if(!(std::string("mumu_nobtag") == std::string(directory))){
    // template has been removed from nobtag categories
    WJets = refill((TH1F*)input ->Get(TString::Format("%s/WJets"   , directory)), "WJets"   ); InitHist(WJets   , "", "", kGreen -4 , 1001);
  }
#ifdef MSSM
  TH1F* ggH      = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA"  , directory)), "ggH"     ); InitSignal(ggH); ggH->Scale($TANB);
  TH1F* bbH      = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA"  , directory)), "bbH"     ); InitSignal(bbH); bbH->Scale($TANB);
#else
#ifndef DROP_SIGNAL
  TH1F* ggH      = refill((TH1F*)input ->Get(TString::Format("%s/ggH125"  , directory)), "ggH"     ); InitSignal(ggH); ggH->Scale(SIGNAL_SCALE);
  TH1F* qqH      = refill((TH1F*)input ->Get(TString::Format("%s/qqH125"  , directory)), "qqH"     ); InitSignal(qqH); qqH->Scale(SIGNAL_SCALE);
  TH1F* VH       = refill((TH1F*)input ->Get(TString::Format("%s/VH125"   , directory)), "VH"      ); InitSignal(VH ); VH ->Scale(SIGNAL_SCALE);
#endif
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
#ifdef MSSM
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}" , "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);
#else
  InitHist(data, "#bf{D}", "#bf{dN/dD}"     ); InitData(data);
#endif

  TH1F* ref=(TH1F*)ZTT->Clone("ref");
  ref->Add(ZMM);
  ref->Add(TTJ);
  ref->Add(QCD);
  ref->Add(Dibosons);
  if(WJets){
    ref->Add(WJets);
  }
  double unscaled[9];
  unscaled[0] = ZTT->Integral();
  unscaled[1] = ZMM->Integral();
  unscaled[2] = TTJ->Integral();
  unscaled[3] = QCD->Integral();
  unscaled[4] = Dibosons->Integral();
  unscaled[5] = 0;
  if(WJets){
    unscaled[5] = WJets->Integral();
  }
#ifdef MSSM
  unscaled[6] = ggH->Integral();
  unscaled[7] = bbH->Integral();
  unscaled[8] = 0;
#else
#ifndef DROP_SIGNAL
  unscaled[6] = ggH->Integral();
  unscaled[7] = qqH->Integral();
  unscaled[8] = VH ->Integral();
#endif
#endif
  
  if(scaled){
    rescale(ZTT,  1); 
    rescale(ZMM,  2); 
    rescale(TTJ,  3); 
    rescale(QCD,  4); 
    rescale(Dibosons, 5); 
    if(WJets){
      rescale(WJets,  6);
    }
#ifdef MSSM 
    rescale(ggH,  7);
    rescale(bbH,  8);
#else
#ifndef DROP_SIGNAL
    rescale(ggH,  7);
    rescale(qqH,  8);
    rescale(VH,   9);
#endif
#endif
  }

  TH1F* scales[9];
  scales[0] = new TH1F("scales-ZTT", "", 9, 0, 9);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (ZTT->Integral()/unscaled[0]-1.)      : 0.);
  scales[1] = new TH1F("scales-ZMM"  , "", 9, 0, 9);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (ZMM->Integral()/unscaled[1]-1.)      : 0.);
  scales[2] = new TH1F("scales-TTJ", "", 9, 0, 9);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (TTJ->Integral()/unscaled[2]-1.)      : 0.);
  scales[3] = new TH1F("scales-QCD"  , "", 9, 0, 9);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (QCD->Integral()/unscaled[3]-1.)      : 0.);
  scales[4] = new TH1F("scales-Dibosons", "", 9, 0, 9);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (Dibosons->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-WJets"  , "", 9, 0, 9); scales[5]->SetBinContent(6, 0.);
  if(WJets){ 
    scales[5]->SetBinContent(6, unscaled[5]>0 ? (WJets->Integral()/unscaled[5]-1.)  : 0.);
  }
#ifdef MSSM
  scales[6] = new TH1F("scales-ggH"  , "", 9, 0, 9);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggH->Integral()/unscaled[6]-1.)      : 0.);
  scales[7] = new TH1F("scales-bbH"  , "", 9, 0, 9);
  scales[7]->SetBinContent(8, unscaled[7]>0 ? (bbH->Integral()/unscaled[7]-1.)      : 0.);
  scales[8] = new TH1F("scales-NONE" , "", 9, 0, 9);
  scales[8]->SetBinContent(9, 0.);
#else
#ifndef DROP_SIGNAL
  scales[6] = new TH1F("scales-ggH"  , "", 9, 0, 9);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggH->Integral()/unscaled[6]-1.)      : 0.);
  scales[7] = new TH1F("scales-qqH"  , "", 9, 0, 9);
  scales[7]->SetBinContent(8, unscaled[7]>0 ? (qqH->Integral()/unscaled[7]-1.)      : 0.);
  scales[8] = new TH1F("scales-VH"   , "", 9, 0, 9);
  scales[8]->SetBinContent(9, unscaled[8]>0 ? (VH ->Integral()/unscaled[8]-1.)      : 0.);
#endif
#endif

  if(WJets){
    Dibosons->Add(WJets);
  }
  QCD->Add(Dibosons);
  TTJ->Add(QCD);
  ZTT->Add(TTJ);
  ZMM->Add(ZTT);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM
    bbH  ->Add(ZMM);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    VH   ->Add(ZMM);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }


  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(345));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
#ifndef DROP_SIGNAL
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(ZMM, log)), maximum(ggH, log)));
#else
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(ZMM, log)));
#endif
  data->Draw("e");

  TH1F* errorBand = (TH1F*)ZMM->Clone("errorBand");
  errorBand->SetMarkerSize(0);
  errorBand->SetFillColor(1);
  errorBand->SetFillStyle(3013);
  errorBand->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    ZMM->Draw("histsame");
    ZTT->Draw("histsame");
    TTJ->Draw("histsame");
    QCD->Draw("histsame");
    Dibosons->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH->Draw("histsame");
#endif

  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
    ZMM->Draw("histsame");
    ZTT->Draw("histsame");
    TTJ->Draw("histsame");
    QCD->Draw("histsame");
    Dibosons->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{#mu}#tau_{#mu}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.20, (category_extra2 && category_extra2[0]=='\0') ? 0.65+0.061 : 0.65+0.061, 0.32, 0.75+0.161, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
  chan->AddText(category_extra2);
  chan->Draw();

/*  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();
*/
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.55, 0.50+0.061, 0.95, 0.50+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m^{h}_{max} (m_{A}=$MA GeV, tan#beta=$TANB)");
  massA->Draw();
#endif

#ifdef MSSM  
  TLegend* leg = new TLegend(0.55, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.50, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#endif
#ifdef ASIMOV
  leg->AddEntry(data    , "sum(bkg) + H(125)"           , "LP");
#else
  leg->AddEntry(data    , "observed"                    , "LP");
#endif
  leg->AddEntry(ZMM     , "Z#rightarrow#mu#mu"          , "F" );
  leg->AddEntry(ZTT     , "Z#rightarrow#tau#tau"        , "F" );
  leg->AddEntry(TTJ     , "t#bar{t}"                    , "F" );
  leg->AddEntry(QCD     , "QCD"                         , "F" );
  leg->AddEntry(Dibosons, "electroweak"                 , "F" );
  $ERROR_LEGEND
  leg->Draw();

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* model = (TH1F*)ZMM ->Clone("model");
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat1"); rat1->Reset("ICES");
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(data->GetBinContent(ibin+1) > 0){
      rat1->SetBinContent(ibin+1, ZMM->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/ZMM->GetBinContent(ibin+1) : 0);
      rat1->SetBinError  (ibin+1, ZMM->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/ZMM->GetBinContent(ibin+1) : 0);
    }
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, ZMM->GetBinContent(ibin+1)>0 ? ZMM ->GetBinError  (ibin+1)/ZMM->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
#ifdef MSSM
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}"); 
#else
  rat1->GetXaxis()->SetTitle("#bf{D}");
#endif
  rat1->Draw("E0");
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
  TH1F* rat2 = (TH1F*) ZMM->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? ZMM->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? ZMM->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(0, rat2->FindBin(345)); } else{ rat2->GetXaxis()->SetRange(0, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
#if defined MSSM
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}"); 
#else
  rat2->GetXaxis()->SetTitle("#bf{D}");
#endif
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kOrange  -  4, 1001);
  InitHist  (scales[1], "", "", kAzure   +  2, 1001);
  InitHist  (scales[2], "", "", kBlue    -  8, 1001);
  InitHist  (scales[3], "", "", kMagenta - 10, 1001);
  InitHist  (scales[4], "", "", kRed     +  2, 1001);
  InitHist  (scales[5], "", "", kGreen   -  4, 1001);  
#ifndef DROP_SIGNAL
  InitSignal(scales[6]);
  InitSignal(scales[7]);
  InitSignal(scales[8]);
#endif
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{ZTT}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{ZMM}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{TTJ}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{QCD}"  );
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{Dibosons}");
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{WJets}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(8, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(9, "#bf{NONE}" );
#else
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(8, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(9, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[0]->Draw();
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
  scales[4]->Draw("same");
  scales[5]->Draw("same");
#ifndef DROP_SIGNAL
  scales[6]->Draw("same");
  scales[7]->Draw("same");
  scales[8]->Draw("same");
#endif
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
 bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd();
  data ->Write("data_obs");
  ZTT->Write("Ztt"  );
  ZMM->Write("Zmm"  );
  TTJ->Write("ttbar");
  QCD->Write("Fakes");
  Dibosons->Write("EWK");
  if(WJets){
    WJets->Write("WJets");
  }
#ifdef MSSM
  ggH  ->Write("ggH");
  bbH  ->Write("bbH");
#else
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH");
  qqH  ->Write("qqH");
  VH   ->Write("VH" );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}
Esempio n. 6
0
void MultiHistoOverlap(TString namesandlabels, Int_t nOfFiles, const TString& outDir="./") {

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

//  gSystem->Load("libRooFit");
//  using namespace RooFit;
// preamble
    TPaveText *cmsprel = new TPaveText(0.19, 0.95, 0.95, 0.99, "NDC");
    cmsprel->SetTextSize(0.03);
    cmsprel->SetTextFont(42);
    cmsprel->SetFillColor(0);
    cmsprel->SetBorderSize(0);
    cmsprel->SetMargin(0.01);
    cmsprel->SetTextAlign(12); // align left
    TString text = "CMS Preliminary 2011";
    cmsprel->AddText(0.0, 0.5,text);
    TString text2 = "#sqrt{s} = 7 TeV  |#eta_{#mu}|<2.4";
    cmsprel->AddText(0.8, 0.5, text2);


    TList* FileList  = new TList();
    TList* LabelList = new TList();
    TObjArray *nameandlabelpairs = namesandlabels.Tokenize(",");
    for (Int_t i = 0; i < nameandlabelpairs->GetEntries(); ++i) {
        TObjArray *aFileLegPair = TString(nameandlabelpairs->At(i)->GetName()).Tokenize("=");
        if(aFileLegPair->GetEntries() == 2) {
            FileList->Add( TFile::Open(aFileLegPair->At(0)->GetName())  );
            LabelList->Add( aFileLegPair->At(1) );
        } else {
            std::cout << "Please give file name and legend entry in the following form:\n" 		<< " filename1=legendentry1,filename2=legendentry2\n";
        }
    }


    Int_t NOfFiles =  FileList->GetSize();
    if ( NOfFiles!=nOfFiles ) {
        std::cout<<"&MSG-e: NOfFiles = "<<nOfFiles<<std::endl;
        return;
    }


    TString LegLabels[nOfFiles];
    for(Int_t j=0; j < nOfFiles; j++) {
        TObjString* legend = (TObjString*)LabelList->At(j);
        LegLabels[j] = legend->String();
        std::cout<<"LegLabels["<<j<<"]"<<LegLabels[j]<<std::endl;
    }

    TLegend *leg=0;

    TCanvas* c0 = new TCanvas("c0", "c0",50, 20, 800,600);
    TCanvas* c1 = new TCanvas("c1", "c1",50, 20, 800,600);
    TCanvas* c2 = new TCanvas("c2", "c2",50, 20, 800,600);
    TCanvas* c3 = new TCanvas("c3", "c3",50, 20, 800,600);
    TCanvas* c4 = new TCanvas("c4", "c4",50, 20, 800,600);
    TCanvas* c5 = new TCanvas("c5", "c5",50, 20, 1200,800);
    TCanvas* c6 = new TCanvas("c6", "c6",50, 20, 1200,800);

    TCanvas* c0s = new TCanvas("c0s", "c0s",50, 20, 800,600);
    TCanvas* c1s = new TCanvas("c1s", "c1s",50, 20, 800,600);
    TCanvas* c2s = new TCanvas("c2s", "c2s",50, 20, 800,600);
    TCanvas* c3s = new TCanvas("c3s", "c3s",50, 20, 800,600);

    TCanvas* cFit = new TCanvas("cFit", "cFit",50, 20, 1600, 800);


//----------------- CANVAS C0 --------------//
    c0->SetFillColor(0);
    c0->cd();

    leg = new TLegend(0.50,0.25,0.90,0.40);
    leg->SetBorderSize(1);
    leg->SetFillColor(0);
    leg->SetTextFont(42);

// Mass VS muon phi plus -------------------------------
    TH1D *histoMassVsPhiPlus[nOfFiles];
    for(Int_t j=0; j < nOfFiles; j++) {

        TFile *fin = (TFile*)FileList->At(j);
        if ( histoMassVsPhiPlus[j] = (TH1D*)fin->Get("MassVsPhiPlus/allHistos/meanHisto")) {
            histoMassVsPhiPlus[j]->SetLineStyle(linestylelist[j]);
            histoMassVsPhiPlus[j]->SetMarkerColor(colorlist[j]);
            histoMassVsPhiPlus[j]->SetLineColor(colorlist[j]);
            histoMassVsPhiPlus[j]->SetMarkerStyle(markerstylelist[j]);
            //     histoMassVsPhiPlus[j]->SetMarkerSize(0.75);
            if ( j == 0 ) {
                histoMassVsPhiPlus[j]->GetXaxis()->SetTitle("positive muon #phi (rad)");
                histoMassVsPhiPlus[j]->GetYaxis()->SetTitle("M_{#mu#mu} (GeV)");
                //       histoMassVsPhiPlus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
                histoMassVsPhiPlus[j]->GetYaxis()->SetRangeUser(90.0,91.5);
                histoMassVsPhiPlus[j]->GetXaxis()->SetRangeUser(-3.14,3.14);
                histoMassVsPhiPlus[j]->Draw();
            } else {
                histoMassVsPhiPlus[j]->Draw("SAME");
            }
            leg->AddEntry(histoMassVsPhiPlus[j],LegLabels[j],"PL");
        }
    }
//cmsprel->Draw("same");
    leg->Draw("same");
    c0->SaveAs(outDir+"MassVsPhiPlus.png");


//----------------- CANVAS C1 --------------//
    c1->SetFillColor(0);
    c1->cd();

    leg = new TLegend(0.50,0.25,0.90,0.40);
    leg->SetBorderSize(1);
    leg->SetFillColor(0);
    leg->SetTextFont(42);

// Mass VS muon eta plus -------------------------------
    TH1D *histoMassVsEtaPlus[nOfFiles];
    for(Int_t j=0; j < nOfFiles; j++) {

        TFile *fin = (TFile*)FileList->At(j);
        if ( histoMassVsEtaPlus[j] = (TH1D*)fin->Get("MassVsEtaPlus/allHistos/meanHisto")) {
            histoMassVsEtaPlus[j]->SetLineStyle(linestylelist[j]);
            histoMassVsEtaPlus[j]->SetMarkerColor(colorlist[j]);
            histoMassVsEtaPlus[j]->SetLineColor(colorlist[j]);
            histoMassVsEtaPlus[j]->SetMarkerStyle(markerstylelist[j]);
            //     histoMassVsEtaPlus[j]->SetMarkerSize(0.75);
            if ( j == 0 ) {
                histoMassVsEtaPlus[j]->GetXaxis()->SetTitle("positive muon #eta");
                histoMassVsEtaPlus[j]->GetYaxis()->SetTitle("M_{#mu#mu} (GeV)");
                //       histoMassVsEtaPlus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
                histoMassVsEtaPlus[j]->GetYaxis()->SetRangeUser(90.0,91.5);
                histoMassVsEtaPlus[j]->GetXaxis()->SetRangeUser(-2.41,2.41);
                histoMassVsEtaPlus[j]->Draw();
            } else {
                histoMassVsEtaPlus[j]->Draw("SAME");
            }
            leg->AddEntry(histoMassVsEtaPlus[j],LegLabels[j],"PL");
        }
    }
//cmsprel->Draw("same");
    leg->Draw("same");
    c1->SaveAs(outDir+"MassVsEtaPlus.png");


//----------------- CANVAS C2 --------------//
    c2->SetFillColor(0);
    c2->cd();

    leg = new TLegend(0.50,0.25,0.90,0.40);
    leg->SetBorderSize(1);
    leg->SetFillColor(0);
    leg->SetTextFont(42);

// Mass VS muon eta plus - eta minus  -------------------------------
    TH1D *histoMassVsEtaPlusMinusDiff[nOfFiles];
    for(Int_t j=0; j < nOfFiles; j++) {

        TFile *fin = (TFile*)FileList->At(j);
        if ( histoMassVsEtaPlusMinusDiff[j] = (TH1D*)fin->Get("MassVsEtaPlusMinusDiff/allHistos/meanHisto")) {
            histoMassVsEtaPlusMinusDiff[j]->SetLineStyle(linestylelist[j]);
            histoMassVsEtaPlusMinusDiff[j]->SetMarkerColor(colorlist[j]);
            histoMassVsEtaPlusMinusDiff[j]->SetLineColor(colorlist[j]);
            histoMassVsEtaPlusMinusDiff[j]->SetMarkerStyle(markerstylelist[j]);
            //     histoMassVsEtaPlusMinusDiff[j]->SetMarkerSize(0.75);
            if ( j == 0 ) {
                histoMassVsEtaPlusMinusDiff[j]->GetXaxis()->SetTitle("#eta pos. muon  #eta neg. muon");
                histoMassVsEtaPlusMinusDiff[j]->GetYaxis()->SetTitle("M_{#mu#mu} (GeV)");
                //       histoMassVsEtaPlusMinusDiff[j]->GetYaxis()->SetRangeUser(88.0,96.0);
                histoMassVsEtaPlusMinusDiff[j]->GetYaxis()->SetRangeUser(90.0,91.5);
                histoMassVsEtaPlusMinusDiff[j]->GetXaxis()->SetRangeUser(-3,3);
                histoMassVsEtaPlusMinusDiff[j]->Draw();
            } else {
                histoMassVsEtaPlusMinusDiff[j]->Draw("SAME");
            }
            leg->AddEntry(histoMassVsEtaPlusMinusDiff[j],LegLabels[j],"PL");
        }
    }
//cmsprel->Draw("same");
    leg->Draw("same");
    c2->SaveAs(outDir+"MassVsEtaPlusMinusDiff.png");

//----------------- CANVAS C3 --------------//
    c3->SetFillColor(0);
    c3->cd();

    leg = new TLegend(0.50,0.25,0.90,0.40);
    leg->SetBorderSize(1);
    leg->SetFillColor(0);
    leg->SetTextFont(42);

// Mass VS muon phi minus -------------------------------
    TH1D *histoMassVsPhiMinus[nOfFiles];
    for(Int_t j=0; j < nOfFiles; j++) {

        TFile *fin = (TFile*)FileList->At(j);
        if ( histoMassVsPhiMinus[j] = (TH1D*)fin->Get("MassVsPhiMinus/allHistos/meanHisto")) {
            histoMassVsPhiMinus[j]->SetLineStyle(linestylelist[j]);
            histoMassVsPhiMinus[j]->SetMarkerColor(colorlist[j]);
            histoMassVsPhiMinus[j]->SetLineColor(colorlist[j]);
            histoMassVsPhiMinus[j]->SetMarkerStyle(markerstylelist[j]);
            //     histoMassVsPhiMinus[j]->SetMarkerSize(0.75);
            if ( j == 0 ) {
                histoMassVsPhiMinus[j]->GetXaxis()->SetTitle("negative muon #phi (rad)");
                histoMassVsPhiMinus[j]->GetYaxis()->SetTitle("M_{#mu#mu} (GeV)");
                //       histoMassVsPhiMinus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
                histoMassVsPhiMinus[j]->GetYaxis()->SetRangeUser(90.0,91.5);
                histoMassVsPhiMinus[j]->GetXaxis()->SetRangeUser(-3.14,3.14);
                histoMassVsPhiMinus[j]->Draw();
            } else {
                histoMassVsPhiMinus[j]->Draw("SAME");
            }
            leg->AddEntry(histoMassVsPhiMinus[j],LegLabels[j],"PL");
        }
    }
//cmsprel->Draw("same");
    leg->Draw("same");
    c3->SaveAs(outDir+"MassVsPhiMinus.png");


//----------------- CANVAS C4 --------------//
    c4->SetFillColor(0);
    c4->cd();

    leg = new TLegend(0.50,0.25,0.90,0.40);
    leg->SetBorderSize(1);
    leg->SetFillColor(0);
    leg->SetTextFont(42);

// Mass VS muon eta minus -------------------------------
    TH1D *histoMassVsEtaMinus[nOfFiles];
    for(Int_t j=0; j < nOfFiles; j++) {

        TFile *fin = (TFile*)FileList->At(j);
        if ( histoMassVsEtaMinus[j] = (TH1D*)fin->Get("MassVsEtaMinus/allHistos/meanHisto")) {
            histoMassVsEtaMinus[j]->SetLineStyle(linestylelist[j]);
            histoMassVsEtaMinus[j]->SetMarkerColor(colorlist[j]);
            histoMassVsEtaMinus[j]->SetLineColor(colorlist[j]);
            histoMassVsEtaMinus[j]->SetMarkerStyle(markerstylelist[j]);
            //     histoMassVsEtaMinus[j]->SetMarkerSize(0.75);
            if ( j == 0 ) {
                histoMassVsEtaMinus[j]->GetXaxis()->SetTitle("negative muon #eta");
                histoMassVsEtaMinus[j]->GetYaxis()->SetTitle("M_{#mu#mu} (GeV)");
                //       histoMassVsEtaMinus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
                histoMassVsEtaMinus[j]->GetYaxis()->SetRangeUser(90.0,91.5);
                histoMassVsEtaMinus[j]->GetXaxis()->SetRangeUser(-2.41,2.41);
                histoMassVsEtaMinus[j]->Draw();
            } else {
                histoMassVsEtaMinus[j]->Draw("SAME");
            }
            leg->AddEntry(histoMassVsEtaMinus[j],LegLabels[j],"PL");
        }
    }
//cmsprel->Draw("same");
    leg->Draw("same");
    c4->SaveAs(outDir+"MassVsEtaMinus.png");

//----------------- CANVAS C5 --------------//
    c5->SetFillColor(0);
    c5->cd();

    leg = new TLegend(0.50,0.25,0.90,0.40);
    leg->SetBorderSize(1);
    leg->SetFillColor(0);
    leg->SetTextFont(42);

// Mass VS muon phi plus -------------------------------
    TH2D *histoMassVsEtaPhiPlus[nOfFiles];

    TStyle *newStyle;
    newStyle->SetPalette(1);
// newStyle->SetOptTitle(1);

    Double_t zMin(82.);
    Double_t zMax(96.);
    for(Int_t j=0; j < nOfFiles; j++) {

        TFile *fin = (TFile*)FileList->At(j);
        if ( histoMassVsEtaPhiPlus[j] = (TH2D*)fin->Get("MassVsEtaPhiPlus/allHistos/meanHisto")) {
            if ( j == 0 ) {
                histoMassVsEtaPhiPlus[j]->SetTitle(LegLabels[j]);
                histoMassVsEtaPhiPlus[j]->GetXaxis()->SetTitle("positive muon #phi (rad)");
                histoMassVsEtaPhiPlus[j]->GetYaxis()->SetTitle("positive muon #eta");
                zMin = histoMassVsEtaPhiPlus[j]->GetMinimum();
                zMax = histoMassVsEtaPhiPlus[j]->GetMaximum();
                histoMassVsEtaPhiPlus[j]->Draw("COLZ");
                c5->SaveAs(outDir+"MassVsEtaPhiPlus_file0.png");
            } else {
                histoMassVsEtaPhiPlus[j]->SetTitle(LegLabels[j]);
                histoMassVsEtaPhiPlus[j]->SetMinimum(zMin);
                histoMassVsEtaPhiPlus[j]->SetMaximum(zMax);
                histoMassVsEtaPhiPlus[j]->Draw("COLZ");
                c5->SaveAs(outDir+"MassVsEtaPhiPlus_file"+(TString)Form("%d",(Int_t)j)+".png");
            }

        }
    }
//cmsprel->Draw("same");

//  //----------------- CANVAS C6 --------------//
//  c6->SetFillColor(0);
//  c6->cd();

//  leg = new TLegend(0.50,0.25,0.90,0.40);
//  leg->SetBorderSize(1);
//  leg->SetFillColor(0);
//  leg->SetTextFont(42);

//  // Mass VS muon phi minus -------------------------------
//  TH2D *histoMassVsEtaPhiMinus[nOfFiles];

//  for(Int_t j=0; j < nOfFiles; j++) {

//    TFile *fin = (TFile*)FileList->At(j);
//    if ( histoMassVsEtaPhiMinus[j] = (TH2D*)fin->Get("MassVsEtaPhiMinus/allHistos/meanHisto")){
//      if ( j == 0 ) {
//        histoMassVsEtaPhiMinus[j]->GetXaxis()->SetTitle("negative muon #phi (rad)");
//        histoMassVsEtaPhiMinus[j]->GetYaxis()->SetTitle("negative muon #eta");
//        zMin = histoMassVsEtaPhiMinus[j]->GetMinimum();
//        zMax = histoMassVsEtaPhiMinus[j]->GetMaximum();
//        histoMassVsEtaPhiMinus[j]->Draw();
//      } else {
//        histoMassVsEtaPhiMinus[j]->SetMinimum(zMin);
//        histoMassVsEtaPhiMinus[j]->SetMaximum(zMax);
//        histoMassVsEtaPhiMinus[j]->Draw("SAME");
//      }
//      leg->AddEntry(histoMassVsEtaPhiMinus[j],LegLabels[j],"PL");
//    }
//  }
//  //cmsprel->Draw("same");
//  leg->Draw("same");
//  c6->SaveAs(outDir+"MassVsEtaPhiMinus.png");

// newStyle->SetOptTitle(0);

    const Color_t colorlist_resol[7]= {kBlack,kGreen,kBlue,kMagenta,kCyan,kTeal,kRed};
    const Int_t linestylelist_resol[7]= {1,1,1,1,1,1,1};
    const Int_t stylelist_resol[7]= {1,1,1,1,1,1,1};
    const Style_t markerstylelist_resol[7]= {kOpenCircle,kOpenTriangleUp,kOpenTriangleUp,kOpenCircle,kOpenTriangleUp,kOpenCircle,kOpenTriangleUp};


//  //----------------- CANVAS C0S --------------//
//  c0s->SetFillColor(0);
//  c0s->cd();

//  leg = new TLegend(0.50,0.25,0.90,0.40);
//  leg->SetBorderSize(1);
//  leg->SetFillColor(0);
//  leg->SetTextFont(42);

// // Sigma VS muon phi plus -------------------------------
//  TH1D *histoSigmaVsPhiPlus[nOfFiles];
//  for(Int_t j=0; j < nOfFiles; j++) {

//    TFile *fin = (TFile*)FileList->At(j);
//    if ( histoSigmaVsPhiPlus[j] = (TH1D*)fin->Get("MassVsPhiPlus/allHistos/sigmaHisto")){
//      histoSigmaVsPhiPlus[j]->SetLineStyle(linestylelist_resol[j]);
//      histoSigmaVsPhiPlus[j]->SetMarkerColor(colorlist_resol[j]);
//      histoSigmaVsPhiPlus[j]->SetLineColor(colorlist_resol[j]);
//      histoSigmaVsPhiPlus[j]->SetMarkerStyle(markerstylelist_resol[j]);
//      //     histoSigmaVsPhiPlus[j]->SetMarkerSize(0.75);
//      if ( j == 0 ) {
//        histoSigmaVsPhiPlus[j]->GetXaxis()->SetTitle("positive muon #phi (rad)");
//        histoSigmaVsPhiPlus[j]->GetYaxis()->SetTitle("#sigma(M_{#mu#mu}) (GeV)");
//        //       histoSigmaVsPhiPlus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
//        histoSigmaVsPhiPlus[j]->GetYaxis()->SetRangeUser(0.,3.);
//        histoSigmaVsPhiPlus[j]->GetXaxis()->SetRangeUser(-3.14,3.14);
//        histoSigmaVsPhiPlus[j]->Draw();
//      } else {
//        histoSigmaVsPhiPlus[j]->Draw("SAME");
//      }
//      leg->AddEntry(histoSigmaVsPhiPlus[j],LegLabels[j],"PL");
//    }
//  }
//  //cmsprel->Draw("same");
//  leg->Draw("same");
//  c0s->SaveAs(outDir+"SigmaVsPhiPlus.png");


//----------------- CANVAS C1S --------------//
    c1s->SetFillColor(0);
    c1s->cd();

    leg = new TLegend(0.50,0.25,0.90,0.40);
    leg->SetBorderSize(1);
    leg->SetFillColor(0);
    leg->SetTextFont(42);


// Sigma VS muon eta plus -------------------------------
    TH1D *histoSigmaVsEtaPlus[nOfFiles];
    for(Int_t j=0; j < nOfFiles; j++) {

        TFile *fin = (TFile*)FileList->At(j);
        if ( histoSigmaVsEtaPlus[j] = (TH1D*)fin->Get("MassVsEtaPlus/allHistos/sigmaHisto")) {
            histoSigmaVsEtaPlus[j]->SetLineStyle(linestylelist_resol[j]);
            histoSigmaVsEtaPlus[j]->SetMarkerColor(colorlist_resol[j]);
            histoSigmaVsEtaPlus[j]->SetLineColor(colorlist_resol[j]);
            histoSigmaVsEtaPlus[j]->SetMarkerStyle(markerstylelist_resol[j]);
            //     histoSigmaVsEtaPlus[j]->SetMarkerSize(0.75);
            if ( j == 0 ) {
                histoSigmaVsEtaPlus[j]->GetXaxis()->SetTitle("positive muon #eta");
                histoSigmaVsEtaPlus[j]->GetYaxis()->SetTitle("#sigma(M_{#mu#mu}) (GeV)");
                //       histoSigmaVsEtaPlus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
                histoSigmaVsEtaPlus[j]->GetYaxis()->SetRangeUser(0.,3.);
                histoSigmaVsEtaPlus[j]->GetXaxis()->SetRangeUser(-2.41,2.41);
                histoSigmaVsEtaPlus[j]->Draw();
            } else {
                histoSigmaVsEtaPlus[j]->Draw("SAME");
            }
            leg->AddEntry(histoSigmaVsEtaPlus[j],LegLabels[j],"PL");
        }
    }
//cmsprel->Draw("same");
    leg->Draw("same");
    c1s->SaveAs(outDir+"SigmaVsEtaPlus.png");


//  //----------------- CANVAS C2S --------------//
//  c2s->SetFillColor(0);
//  c2s->cd();

//  leg = new TLegend(0.50,0.25,0.90,0.40);
//  leg->SetBorderSize(1);
//  leg->SetFillColor(0);
//  leg->SetTextFont(42);

// // Sigma VS muon eta plus - eta minus  -------------------------------
//  TH1D *histoSigmaVsEtaPlusMinusDiff[nOfFiles];
//  for(Int_t j=0; j < nOfFiles; j++) {

//    TFile *fin = (TFile*)FileList->At(j);
//    if ( histoSigmaVsEtaPlusMinusDiff[j] = (TH1D*)fin->Get("MassVsEtaPlusMinusDiff/allHistos/sigmaHisto")){
//      histoSigmaVsEtaPlusMinusDiff[j]->SetLineStyle(linestylelist_resol[j]);
//      histoSigmaVsEtaPlusMinusDiff[j]->SetMarkerColor(colorlist_resol[j]);
//      histoSigmaVsEtaPlusMinusDiff[j]->SetLineColor(colorlist_resol[j]);
//      histoSigmaVsEtaPlusMinusDiff[j]->SetMarkerStyle(markerstylelist_resol[j]);
//      //     histoSigmaVsEtaPlusMinusDiff[j]->SetMarkerSize(0.75);
//      if ( j == 0 ) {
//        histoSigmaVsEtaPlusMinusDiff[j]->GetXaxis()->SetTitle("#eta pos. muon - #eta neg. muon");
//        histoSigmaVsEtaPlusMinusDiff[j]->GetYaxis()->SetTitle("#sigma(M_{#mu#mu}) (GeV)");
//        //       histoSigmaVsEtaPlusMinusDiff[j]->GetYaxis()->SetRangeUser(88.0,96.0);
//        histoSigmaVsEtaPlusMinusDiff[j]->GetYaxis()->SetRangeUser(0.,3.);
//        //histoSigmaVsEtaPlusMinusDiff[j]->GetYaxis()->SetRangeUser(90.60,90.75);
//        histoSigmaVsEtaPlusMinusDiff[j]->GetXaxis()->SetRangeUser(-3.2,3.2);
//        histoSigmaVsEtaPlusMinusDiff[j]->Draw();
//      } else {
//        histoSigmaVsEtaPlusMinusDiff[j]->Draw("SAME");
//      }
//      leg->AddEntry(histoSigmaVsEtaPlusMinusDiff[j],LegLabels[j],"PL");
//    }
//  }
//  //cmsprel->Draw("same");
//  leg->Draw("same");
//  c2s->SaveAs(outDir+"SigmaVsEtaPlusMinusDiff.png");


//  //----------------- CANVAS C3S --------------//
//  c3s->SetFillColor(0);
//  c3s->cd();

//  leg = new TLegend(0.35,0.15,0.55,0.35);
//  leg->SetBorderSize(1);
//  leg->SetFillColor(0);
//  leg->SetTextFont(42);

// // Sigma VS muon pT  -------------------------------
//  TH1D *histoSigmaVsPt[nOfFiles];
//  for(Int_t j=0; j < nOfFiles; j++) {

//    TFile *fin = (TFile*)FileList->At(j);
//    if ( histoSigmaVsPt[j] = (TH1D*)fin->Get("MassVsPt/allHistos/sigmaHisto")){
//      histoSigmaVsPt[j]->SetLineStyle(linestylelist_resol[j]);
//      histoSigmaVsPt[j]->SetMarkerColor(colorlist_resol[j]);
//      histoSigmaVsPt[j]->SetLineColor(colorlist_resol[j]);
//      histoSigmaVsPt[j]->SetMarkerStyle(markerstylelist_resol[j]);
//      //     histoSigmaVsPt[j]->SetMarkerSize(0.75);
//      if ( j == 0 ) {
//        histoSigmaVsPt[j]->GetXaxis()->SetTitle("muon p_T (GeV)");
//        histoSigmaVsPt[j]->GetYaxis()->SetTitle("#sigma(M_{#mu#mu}) (GeV)");
//        //       histoSigmaVsPt[j]->GetYaxis()->SetRangeUser(88.0,96.0);
//        histoSigmaVsPt[j]->GetYaxis()->SetRangeUser(0.,3.);
//        //histoSigmaVsPt[j]->GetYaxis()->SetRangeUser(90.60,90.75);
//        histoSigmaVsPt[j]->GetXaxis()->SetRangeUser(15.,105.);
//        histoSigmaVsPt[j]->Draw();
//      } else {
//        histoSigmaVsPt[j]->Draw("SAME");
//      }
//      leg->AddEntry(histoSigmaVsPt[j],LegLabels[j],"PL");
//    }
//  }
//  //cmsprel->Draw("same");
//  leg->Draw("same");
//  c3s->SaveAs(outDir+"SigmaVsPt.png");

//----------------- CANVAS CFIT --------------//
    cFit->SetFillColor(0);
    cFit->cd();
    Float_t nN = TMath::Sqrt(nOfFiles);
    Int_t nX = (Int_t)nN;
    if ( nN-nX > 0.5 ) nX++;
    Int_t nY = (Int_t)(nOfFiles/nX);
    std::cout << nX << " ," << nY << std::endl;
    cFit->Divide(nOfFiles,1);

// Mass VS muon phi plus -------------------------------
    TFile *ZFitFile = new TFile("ZFitFile.root","RECREATE");
    RooPlot *histoLineShape[nOfFiles];
    for(Int_t j=0; j < nOfFiles; j++) {

        TFile *fin = (TFile*)FileList->At(j);
        if ( histoLineShape[j] = (RooPlot*)fin->Get("hRecBestResAllEvents_Mass_frame")) {
            std::cout<<"Writing fit histogrem file n. "<<j<<std::endl;
            histoLineShape[j]->Write();
            cFit->cd(j+1);
            histoLineShape[j]->SetTitle(LegLabels[j]);
            histoLineShape[j]->Draw();
            histoLineShape[j]->GetXaxis()->SetTitle("M_{#mu#mu} (GeV)");
//      TPaveText *cmsprel2 = new TPaveText(0.19, 0.95, 0.95, 0.99, "NDC");
//      cmsprel2->SetTextSize(0.03);
//      cmsprel2->SetTextFont(42);
//      cmsprel2->SetFillColor(0);
//      cmsprel2->SetBorderSize(0);
//      cmsprel2->SetMargin(0.01);
//      cmsprel2->SetTextAlign(12); // align left
//      cmsprel2->AddText(0.666666, 0.5, LegLabels[j]);

        }
    }
    ZFitFile->Close();
// cmsprel2->Draw("same");
    cFit->SaveAs("ZFitFile.root");



    return;
};
Esempio n. 7
0
//---------------------------------------------------------------
double *unbinnedFit(TString fiName, vector<double> xlim, double mtop, TLatex *channel_tex, TString outdir, double lumi)
//---------------------------------------------------------------
{
  using namespace RooFit;
  // reduce RooFit's verbosity on the INFO level
  RooMsgService::instance().getStream(1).removeTopic(Minimization);
  RooMsgService::instance().getStream(1).removeTopic(Plotting);
  RooMsgService::instance().getStream(1).removeTopic(ObjectHandling);
  RooMsgService::instance().getStream(1).removeTopic(Eval);
  RooMsgService::instance().getStream(1).removeTopic(Fitting);
  RooMsgService::instance().setSilentMode(true);
  RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);

  TFile *res = TFile::Open(fiName);

  RooRealVar mtl("mass", "M_{J/#psi+l}", 0., 250., "GeV");
  RooRealVar weight("weight", "weight", 0., 2.);
  //RooRealVar mean("mean", "mass", (xlim[1]+xlim[0])/2., (xlim[1]+3.*xlim[0])/4., (3.*xlim[1]+xlim[0])/4.);
  RooRealVar mean("mean", "mass", 70., 60., 80.);
  RooRealVar width("width", "width", 25., 15., 40.);

  TTree *tree = (TTree*)res->Get("MTriLept");
  RooDataSet *dataset = new RooDataSet("dataset", "dataset", RooArgSet(mtl, weight), Import(*tree), WeightVar(weight));
  RooGaussian pdf("gaus", "gaus", mtl, mean, width);
  pdf.fitTo(*dataset, Range(xlim[0], xlim[1]), SumW2Error(kTRUE), PrintLevel(-1), PrintEvalErrors(-1));

  TCanvas *cn = new TCanvas("cn", "cn", 800, 800);
  cn->cd();
  RooPlot *massframe = mtl.frame();
  if (mtop < 1e-6)
    dataset->plotOn(massframe, Binning(25), DataError(RooAbsData::SumW2));
  else
    dataset->plotOn(massframe, Binning(50), DataError(RooAbsData::SumW2));
  pdf.plotOn(massframe, Range(xlim[0], xlim[1]));
  massframe->Draw();
  TLegend *leg = new TLegend(0.58,0.82,0.93,0.92,NULL,"brNDC");
  if (mtop < 1e-6)
    leg->SetHeader(TString::Format("#tilde{M}_{J/#psi+l} = (%3.1f #pm %3.1f) GeV", mean.getVal(), mean.getError()));
  else
    leg->SetHeader(TString::Format("#splitline{M_{t}^{gen} = %3.1f GeV}{#tilde{M}_{J/#psi+l} = (%3.1f #pm %3.1f) GeV}", mtop+0.5, mean.getVal(), mean.getError()));
  leg_myStyle(leg);
  leg->Draw("same");
  channel_tex->Draw("same");
  if (mtop < 1e-6)
    cms_myStyle(lumi, true);
  else
    cms_myStyle(lumi, false);
  TString outFile = outdir;
  if (mtop < 1e-6)
    outFile += "GausianUnbinnedFit_Data";
  else
    outFile += TString::Format("GaussianUnbinnedFit_%d_5", (int)mtop);
  cn->SaveAs(outFile+".pdf");
  cn->SaveAs(outFile+".C");
  cn->SaveAs(outFile+".jpg");
  cn->SaveAs(outFile+".eps");

  res->Close();

  double *mean_err = new double[2];
  mean_err[0] = mean.getVal();
  mean_err[1] = mean.getError();

  return mean_err;
}
Esempio n. 8
0
//---------------------------------------------------------------------------
void __fastcall TFMain_11011981::ShowUnits(bool showUnk)
{
    int oldItemIdx = lbUnits->ItemIndex;
    DWORD selAdr = 0;
    if (oldItemIdx != -1)
    {
        String item = lbUnits->Items->Strings[oldItemIdx];
        sscanf(item.c_str() + 1, "%lX", &selAdr);
    }
    int oldTopIdx = lbUnits->TopIndex;

    lbUnits->Clear();
    lbUnits->Items->BeginUpdate();

    if (UnitsNum)
    {
        switch (UnitSortField)
        {
        case 0:
            Units->Sort(SortUnitsByAdr);
            break;
        case 1:
            Units->Sort(SortUnitsByOrd);
            break;
        case 2:
            Units->Sort(SortUnitsByNam);
            break;
        }
    }

    int     stringLen;
    int     newItemIdx = -1;
    int     wid, maxwid = 0;
    TCanvas *canvas = lbUnits->Canvas;
    char    ci, cf, orderS[256];

    for (int i = 0; i < UnitsNum; i++)
    {
        PUnitRec recU = (UnitRec*)Units->Items[i];
        if (recU->fromAdr == selAdr) newItemIdx = i;
        ci = (!recU->trivialIni) ? 'I' : ' ';
        cf = (!recU->trivialFin) ? 'F' : ' ';
        stringLen = sprintf(StringBuf, " %08lX #%03d %c%c ", (int)recU->fromAdr, recU->iniOrder, ci, cf);
        if (recU->names->Count)
        {
            for (int u = 0; u < recU->names->Count; u++)
            {
                if (stringLen + recU->names->Strings[u].Length() >= 256)
                {
                    stringLen += sprintf(StringBuf + stringLen, "...");
                    break;
                }
                if (u)
                {
                    StringBuf[stringLen] = ';';
                    stringLen++;
                }
                stringLen += sprintf(StringBuf + stringLen, "%s", recU->names->Strings[u].c_str());
            }
        }
        else
            stringLen += sprintf(StringBuf + stringLen, "_Unit%d", recU->iniOrder);

        if (i != UnitsNum - 1)
        {
            //Trivial units
            if (recU->trivial)
                StringBuf[0] = TRIV_UNIT;
            else if (!recU->kb)
                StringBuf[0] = USER_UNIT;
        }
        //Last unit is user's
        else
        	StringBuf[0] = USER_UNIT;

        //Unit has undefined bytes
        if (showUnk && ContainsUnexplored(recU)) StringBuf[0] |= UNEXP_UNIT;
        String line = String(StringBuf, stringLen);
        lbUnits->Items->Add(line);
        wid = canvas->TextWidth(line); if (wid > maxwid) maxwid = wid;
    }
    if (newItemIdx == -1)
        lbUnits->TopIndex = oldTopIdx;
    else
    {
        if (newItemIdx != oldItemIdx)
        {
            lbUnits->ItemIndex = newItemIdx;
            int newTopIdx = newItemIdx - (oldItemIdx - oldTopIdx);
            if (newTopIdx < 0) newTopIdx = 0;
            lbUnits->TopIndex = newTopIdx;
        }
        else
        {
            lbUnits->ItemIndex = newItemIdx;
            lbUnits->TopIndex = oldTopIdx;
        }
    }
    lbUnits->ItemHeight = lbUnits->Canvas->TextHeight("T");
    lbUnits->ScrollWidth = maxwid + 2;
    lbUnits->Items->EndUpdate();
}
Esempio n. 9
0
//---------------------------------------------------------------------------
void __fastcall TFMain_11011981::lbUnitItemsDrawItem(TWinControl *Control, int Index, TRect &Rect, TOwnerDrawState State)
{
    int         flags;
    TColor      _color;
    TListBox    *lb;
    TCanvas     *canvas;
    String      text, str;

    lb = (TListBox*)Control;
    canvas = lb->Canvas;
    SaveCanvas(canvas);

    if (Index < lb->Count)
    {
        flags = Control->DrawTextBiDiModeFlags(DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX);
        if (!Control->UseRightToLeftAlignment())
            Rect.Left += 2;
        else
            Rect.Right -= 2;
        canvas->FillRect(Rect);

        text = lb->Items->Strings[Index];
        //lb->ItemHeight = canvas->TextHeight(text);
        str = text.SubString(2, text.Length() - 1);
        //Procs with Xrefs
        if (text[1] & 6)
        {
            //Xrefs from user units
            if (text[1] & 4)
            {
                if (!State.Contains(odSelected))
                    _color = TColor(0x00B000); //Green
                else
                    _color = TColor(0xBBBBBB); //LightGray
            }
            //No Xrefs from user units, only from KB units 
            else
            {
                if (!State.Contains(odSelected))
                    _color = TColor(0xC08000); //Blue
                else
                    _color = TColor(0xBBBBBB); //LightGray
            }
        }
        //Unresolved items
        else if (text[1] & 1)
        {
            if (!State.Contains(odSelected))
                _color = TColor(0x8080FF); //Red
            else
                _color = TColor(0xBBBBBB); //LightGray
        }
        //Other
        else
        {
            if (!State.Contains(odSelected))
                _color = TColor(0);        //Black
            else
                _color = TColor(0xBBBBBB); //LightGray
        }
        Rect.Right = Rect.Left;
        DrawOneItem(str, canvas, Rect, _color, flags);
    }
    RestoreCanvas(canvas);
}
Esempio n. 10
0
//---------------------------------------------------------------------------
void __fastcall TFMain_11011981::lbUnitsDrawItem(
      TWinControl *Control, int Index, TRect &Rect, TOwnerDrawState State)
{
    char        *s, *pos;
    int         flags, len;
    TColor      _color;
    TListBox    *lb;
    TCanvas     *canvas;
    String      text, str1, str2;

    lb = (TListBox*)Control;
    canvas = lb->Canvas;
    SaveCanvas(canvas);

    if (Index < lb->Count)
    {
        flags = Control->DrawTextBiDiModeFlags(DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX);
        if (!Control->UseRightToLeftAlignment())
            Rect.Left += 2;
        else
            Rect.Right -= 2;

        text = lb->Items->Strings[Index];
        //lb->ItemHeight = canvas->TextHeight(text);
        canvas->FillRect(Rect);

        s = text.c_str();
        //*XXXXXXXX #XXX XX NAME
        pos = strrchr(s, ' ');
        len = pos - s;
        str1 = text.SubString(2, len - 1);
        str2 = text.SubString(len + 1, text.Length() - len);

        if (!State.Contains(odSelected))
            _color = TColor(0);        //Black
        else
            _color = TColor(0xBBBBBB); //LightGray
        Rect.Right = Rect.Left;
        DrawOneItem(str1, canvas, Rect, _color, flags);

        //Unit name
        //Trivial unit - red
        if (text[1] & TRIV_UNIT)
        {
            if (!State.Contains(odSelected))
                _color = TColor(0x0000B0); //Red
            else
                _color = TColor(0xBBBBBB); //LightGray
        }
        else
        {
            //User unit - green
            if (text[1] & USER_UNIT)
            {
                if (!State.Contains(odSelected))
                {
                	if (text[1] & UNEXP_UNIT)
                    	_color = TColor(0xC0C0FF); //Light Red
                    else
                    	_color = TColor(0x00B000); //Green
                }
                else
                    _color = TColor(0xBBBBBB); //LightGray
            }
            //From knowledge base - blue
            else
            {
                if (!State.Contains(odSelected))
                    _color = TColor(0xC08000); //Blue
                else
                    _color = TColor(0xBBBBBB); //LightGray
            }
        }
        DrawOneItem(str2, canvas, Rect, _color, flags);
    }
    RestoreCanvas(canvas);
}
Esempio n. 11
0
//---------------------------------------------------------------------------
void __fastcall TFMain_11011981::ShowUnitItems(PUnitRec recU, int topIdx, int itemIdx)
{
    bool        unk = false;
    bool	    imp, exp, emb, xref;
    int         wid, maxwid = 0;
    TCanvas     *canvas = lbUnitItems->Canvas;
    String      line, prefix;

    if (!CurUnitAdr) return;

    //if (AnalyzeThread) AnalyzeThread->Suspend();

    lbUnitItems->Clear();
    lbUnitItems->Items->BeginUpdate();

    for (DWORD adr = recU->fromAdr; adr < recU->toAdr; adr++)
    {
        int unknum, pos = Adr2Pos(adr);
        if (!IsFlagSet(~cfLoc, pos))
        {
            BYTE b0 = *(Code + pos);
        	if (!unk)
            {
                unknum = 0;
                BYTE b1 = *(Code + pos + 1); BYTE b2 = *(Code + pos + 2);
                if ((adr & 3) == 3 && (b0 == 0 || b0 == 0x90))
                    continue;
                if ((adr & 3) == 2 && ((b0 == 0 && b1 == 0) || (b0 == 0x8B && b1 == 0xC0) || (b0 == 0x90 && b1 == 0x90)))
                {
                    adr++;
                    continue;
                }
                if ((adr & 3) == 1 && ((b0 == 0 && b1 == 0 && b2 == 0) || (b0 == 0x8D && b1 == 0x40 && b2 == 0) || (b0 == 0x90 && b1 == 0x90 && b2 == 0x90)))
                {
                    adr += 2;
                    continue;
                }
                line = " " + Val2Str8(adr) + " ????"; line[1] ^= 1;
                line += " " + Val2Str2(b0); unknum++;
                unk = true;
            }
            else
            {
                if (unknum <= 16)
                {
                    if (unknum == 16)
                        line += "...";
                    else
                        line += " " + Val2Str2(b0);
                    unknum++;
                }
            }
            continue;
        }

        if (unk)
        {
            lbUnitItems->Items->Add(line);
            wid = canvas->TextWidth(line);
            if (wid > maxwid) maxwid = wid;
            unk = false;
        }

        if (adr == recU->iniadr) continue;
        if (adr == recU->finadr) continue;

        //EP
        if (adr == EP)
        {
            line = " " + Val2Str8(adr) + " <Proc> EntryPoint";
            lbUnitItems->Items->Add(line);
            wid = canvas->TextWidth(line);
            if (wid > maxwid) maxwid = wid;
            continue;
        }

        PInfoRec recN = GetInfoRec(adr);
        if (!recN) continue;

        BYTE kind = recN->kind;
        //Skip calls, that are in the body of some asm-procs (for example, FloatToText from SysUtils)
        //if (kind >= ikRefine && kind <= ikFunc && recN->procInfo && (recN->procInfo->flags & cfEmbedded)) continue;
        if (kind >= ikRefine && kind <= ikFunc && recN->procInfo && IsFlagSet(cfImport, pos)) continue;

        imp = IsFlagSet(cfImport, pos);
        exp = IsFlagSet(cfExport, pos);
        emb = false;
        if (IsFlagSet(cfProcStart, pos))
        {
            if (recN->procInfo)
            {
                emb = (recN->procInfo->flags & PF_EMBED);
            }
        }
        xref = false;

        line = "";

        switch (kind)
        {
		case ikInteger:
		case ikChar:
		case ikEnumeration:
		case ikFloat:
        case ikSet:
        case ikClass:
        case ikMethod:
        case ikWChar:
        case ikLString:
        case ikVariant:
        case ikArray:
        case ikRecord:
        case ikInterface:
        case ikInt64:
        case ikDynArray:
        case ikUString:
        case ikClassRef:
        case ikPointer:
        case ikProcedure:
        	line = "<" + TypeKind2Name(kind) + "> ";
        	if (recN->HasName())
            {
                if (recN->GetNameLength() <= MAXLEN)
                    line += recN->GetName();
                else
                {
                    line += recN->GetName().SubString(1, MAXLEN) + "...";
                }
            }
            break;
        case ikString:
        	if (!IsFlagSet(cfRTTI, pos))
                line = "<ShortString> ";
            else
                line = "<" + TypeKind2Name(kind) + "> ";
            if (recN->HasName())
            {
                if (recN->GetNameLength() <= MAXLEN)
                    line += recN->GetName();
                else
                {
                    line += recN->GetName().SubString(1, MAXLEN) + "...";
                }
            }
            break;
        case ikWString:
        	line = "<WideString> ";
        	if (recN->HasName())
            {
                if (recN->GetNameLength() <= MAXLEN)
                    line += recN->GetName();
                else
                {
                    line += recN->GetName().SubString(1, MAXLEN) + "...";
                }
            }
            break;
        case ikCString:
        	line = "<PAnsiChar> ";
        	if (recN->HasName())
            {
                if (recN->GetNameLength() <= MAXLEN)
                    line += recN->GetName();
                else
                {
                    line += recN->GetName().SubString(1, MAXLEN) + "...";
                }
            }    
            break;
        case ikWCString:
        	line = "<PWideChar> ";
        	if (recN->HasName())
            {
                if (recN->GetNameLength() <= MAXLEN)
                    line += recN->GetName();
                else
                {
                    line += recN->GetName().SubString(1, MAXLEN) + "...";
                }
            }    
        	break;
        case ikResString:
        	if (recN->HasName()) line += "<ResString> " + recN->GetName() + "=" + recN->rsInfo->value;
            break;
        case ikVMT:
        	line = "<VMT> ";
            if (recN->HasName()) line += recN->GetName();
            break;
        case ikConstructor:
            xref = true;
            line = "<Constructor> " + recN->MakePrototype(adr, false, true, false, true, false);
            break;
        case ikDestructor:
            xref = true;
            line = "<Destructor> " + recN->MakePrototype(adr, false, true, false, true, false);
            break;
        case ikProc:
            xref = true;
            line = "<";
            if (imp)
                line += "Imp";
            else if (exp)
                line += "Exp";
            else if (emb)
                line += "Emb";
            line += "Proc> " + recN->MakePrototype(adr, false, true, false, true, false);
            break;
        case ikFunc:
            xref = true;
            line = "<";
            if (imp)
                line += "Imp";
            else if (exp)
                line += "Exp";
            else if (emb)
                line += "Emb";
            line += "Func> " + recN->MakePrototype(adr, false, true, false, true, false);
            break;
        case ikGUID:
        	line = "<TGUID> ";
            if (recN->HasName()) line += recN->GetName();
            break;
        case ikRefine:
            xref = true;
            line = "<";
            if (imp)
                line += "Imp";
            else if (exp)
                line += "Exp";
            else if (emb)
                line += "Emb";
            line += "?> " + recN->MakePrototype(adr, false, true, false, true, false);
            break;
        default:
            if (IsFlagSet(cfProcStart, pos))
            {
                xref = true;
                if (recN->kind == ikConstructor)
                    line = "<Constructor> " + recN->MakePrototype(adr, false, true, false, true, false);
                else if (recN->kind == ikDestructor)
                    line = "<Destructor> " + recN->MakePrototype(adr, false, true, false, true, false);
                else
                {
                    line = "<";
                    if (emb) line += "Emb";
                    line += "Proc> " + recN->MakePrototype(adr, false, true, false, true, false);
                }
            }
        	break;
        }

        if (kind >= ikRefine && kind <= ikFunc)
        {
            if (recN->procInfo->flags & PF_VIRTUAL) line += " virtual";
            if (recN->procInfo->flags & PF_DYNAMIC) line += " dynamic";
            if (recN->procInfo->flags & PF_EVENT)   line += " event";
        }
        if (line != "")
        {
            prefix = " " + Val2Str8(adr);
            if (xref && recN->xrefs && recN->xrefs->Count)
            {
                prefix[1] ^= 2;
                for (int m = 0; m < recN->xrefs->Count; m++)
                {
                    PXrefRec recX = (PXrefRec)recN->xrefs->Items[m];
                    PUnitRec recU = GetUnit(recX->adr);
                    if (recU && !recU->kb)
                    {
                        prefix[1] ^= 4;
                        break;
                    }
                }
                prefix += " " + String(recN->xrefs->Count);
                if (recN->xrefs->Count <= 9)
                    prefix += "  ";
                else if (recN->xrefs->Count <= 99)
                    prefix += " ";
            }
            line = prefix + " " + line;
            lbUnitItems->Items->Add(line);
            wid = canvas->TextWidth(line);
            if (wid > maxwid) maxwid = wid;
        }
    }

    //Add initialization procedure
    if (recU->iniadr)
    {
        line = " " + Val2Str8(recU->iniadr) + " <Proc> Initialization;";
        lbUnitItems->Items->Add(line);
        wid = canvas->TextWidth(line);
        if (wid > maxwid) maxwid = wid;
    }
    //Add finalization procedure
    if (recU->finadr)
    {
        line = " " + Val2Str8(recU->finadr) + " <Proc> Finalization;";
        lbUnitItems->Items->Add(line);
        wid = canvas->TextWidth(line);
        if (wid > maxwid) maxwid = wid;
    }
    lbUnitItems->TopIndex = topIdx;
    lbUnitItems->ItemIndex = itemIdx;
    lbUnitItems->ScrollWidth = maxwid + 2;
    lbUnitItems->ItemHeight = lbUnitItems->Canvas->TextHeight("T");
    lbUnitItems->Items->EndUpdate();

    //if (AnalyzeThread) AnalyzeThread->Resume();
}
void DataRedux( double  db = -25., char * outfile = "output/sat_power.root", char * name_file = "SAT",  double  number_files = 5,   double xnbins = 1000,  double xbin_min = 0,  double xbin_max = 15,  double ynbins = 1000,  double ybin_min = -6,  double ybin_max = -8 )
//void DataRedux( double  db = -25., char * outfile = "output/sun_power.root", char * name_file = "SUN",  double  number_files = 5,  int xnbins = 1000,  double xbin_min = 0,  double xbin_max = 20.,  int ynbins = 50,  double ybin_min = -6.8,  double ybin_max = -7.4)
{

/**********************************************
* Global Variables
* ********************************************/

  const int numberfiles = number_files;
  const char namefile[1000] = name_file;
  const char output[1000] = outfile;
  
  char name[1000];
  char title[10000];
  
  TH2D* h[numberfiles];
  TH1D* h1D[numberfiles];
  TH1D* h1Dcut[numberfiles];
  
  ifstream f[numberfiles]; 
  
  TFile *output_root = new TFile(output,"RECREATE");


/***********************************************
 Opening ascii files and creating the root file 
************************************************/
 for(int i = 0; i < number_files; i++)
 {
   sprintf(name,"%s/%s%i.txt",namefile,name_file,i+1);
   f[i].open(name);
 }
 
  
/************************************************
  Filling histograms
*************************************************/

  for(int i = 0; i < numberfiles; i++)
  {
    double t, v, p, nlines=0, first;
    
    sprintf(name,"%s_%i", namefile, i+1);
    sprintf(title,"%s - Baseline %i", namefile, i+1);
    h[i] = new TH2D(name,title,xnbins, xbin_min, xbin_max, ynbins, ybin_min, ybin_max);

    sprintf(name,"%s_1D_%i", namefile, i+1);
    h1D[i] = new TH1D(name,title,xnbins, xbin_min, xbin_max);    
    
    sprintf(name,"%s_1D_cut_%i", namefile, i+1);
    h1Dcut[i] = new TH1D(name,title,xnbins, xbin_min, xbin_max);
    
    while (1) {
      f[i] >> t >> v ; 
      if (!f[i].good()) break;
      if(nlines==0) first = t; 
      p = VToP(v,db);
      h[i]->Fill(t-first,p);
      h1D[i]->Fill(t-first,p);
      Cut(h1Dcut[i],i,t-first,p);
      nlines++; 
    }
  }
  
 

/****************************************
 * Drawing and Saving 
 *****************************************/
  
  sprintf(name,"%s - P(t) vs t",namefile);
  TCanvas *c = new TCanvas("c",name,900,600);  
  
  TPad *pad1 = new TPad("pad1","",0.03,0.62,0.50,0.92,21);
  pad1->Draw();
  pad1->SetGridy();
  c->Clear();
  c->Divide(2,5);
 
  Style_Cosmetics();
  
  int canvas_number = 1;
  for(i=0; i<numberfiles; i++){
    c->SetGridy();
    // Plot Power vc t
    gStyle->SetOptLogy(1);
    c->cd(canvas_number);
      
      Style_Cosmetics();
    Power_Cosmetics(h1D[i], i);
    c->Update();

    // Plot FFT Magnitude
    gStyle->SetOptLogy(0);
    c->cd(canvas_number+1);
    TH1 *hm =0;
    FFT_Mag(h1Dcut[i],hm, i, namefile);
    c->Update();
    
    // Increment number camvas
    canvas_number = canvas_number + 2;
  }

  sprintf(name,"plots/%s_power.ps",namefile);
  c->SaveAs(name);
   
  output_root->Write();  
  f->close();  
}
Esempio n. 13
0
void makePassFail_QCDMC()
{

	//jetbins
	//
	vector<pair<unsigned, unsigned> > jetBins;
	vector<pair<float, float> > htBins, mhtBins;
	pair<float, float> jetbin1(2,2);	
	pair<float, float> jetbin2(3,5);	
	pair<float, float> jetbin3(6,7);	
	pair<float, float> jetbin4(8,1000);	

	pair<float, float> htbin1(500,750);	
	pair<float, float> htbin2(750,1000);	
	pair<float, float> htbin3(1000,1250);	
	pair<float, float> htbin4(1250,1500);	
	pair<float, float> htbin5(1500,8000);	


	pair<float, float> mhtbin1(0,8000);	
	
	jetBins.push_back(jetbin1);
	jetBins.push_back(jetbin2);
	jetBins.push_back(jetbin3);
	jetBins.push_back(jetbin4);
	
	htBins.push_back(htbin1);
	htBins.push_back(htbin2);
	htBins.push_back(htbin3);
	htBins.push_back(htbin4);

	mhtBins.push_back(mhtbin1);

	vector<string> dphibins;
//	dphibins.push_back("0.15");
	dphibins.push_back("0.20");
//	dphibins.push_back("0.25");
//	dphibins.push_back("0.30");
//	dphibins.push_back("0.35");
//	dphibins.push_back("0.40");

	OpenFiles();
	TCanvas *c = new TCanvas("print");	
	c->Draw();
	c->Print("ratios.eps[");
	
/*	for (unsigned d = 0; d < dphibins.size(); ++d)
	{	
		for (unsigned jetbin = 0; jetbin < jetBins.size(); ++jetbin)
		{	
			for (unsigned htbin = 0; htbin < htBins.size(); ++htbin)
			{
				for (unsigned mhtbin = 0; mhtbin < mhtBins.size(); ++mhtbin)
				{
					stringstream htrange;
					htrange << htBins.at(htbin).first << "<HT<" << htBins.at(htbin).second << " GeV, "
						<< mhtBins.at(mhtbin).first << "<MHT<" << mhtBins.at(mhtbin).second << " GeV";

					stringstream folder;
					folder << "Hist/Njet" << jetBins.at(jetbin).first << "to" << jetBins.at(jetbin).second 
						<< "HT"   << htBins.at(htbin).first << "to" << htBins.at(htbin).second 
						<< "MHT"  << mhtBins.at(mhtbin).first << "to" << mhtBins.at(mhtbin).second;

					stringstream njetlabel, title, numeHistName, denoHistName, signalHistName, controlHistName;
					njetlabel << jetBins.at(jetbin).first << "-" << jetBins.at(jetbin).second << " Jets";
					title << "Njet " << njetlabel.str() << ", " << htrange.str() << ", #Delta #Phi _{min}<" << dphibins.at(d);
					numeHistName << folder.str() << "/smear_signal";
					//denoHistName << folder.str() << "/smeared_fail1";
					denoHistName << folder.str() << "/smeared_fail" << d;
					signalHistName << folder.str() << "/smear_signalFineBin";
					controlHistName << folder.str() << "/smeared_failFineBin" << d;
					//makePassFail_QCDMC(numeHistName.str(), denoHistName.str(), 
					//		title.str(), htrange.str(), signalHistName.str(), controlHistName.str()); 
					makePassFail_QCDMC(numeHistName.str(), denoHistName.str(), 
							title.str(), htrange, signalHistName.str(), controlHistName.str(), jetBins.at(jetbin), 50, 150); 
				}

			}
		}
	}
*/	


	for (unsigned d = 0; d < dphibins.size(); ++d)
	{	
		for (unsigned jetbin = 0; jetbin < jetBins.size(); ++jetbin)
		{	
			stringstream folder;
			folder << "Hist/Njet" << jetBins.at(jetbin).first << "to" << jetBins.at(jetbin).second; 
			string htrange("HT>500 GeV");
			cout << folder.str() << endl;

			stringstream njetlabel, title, numeHistName, denoHistName, signalHistName, controlHistName;
			njetlabel << jetBins.at(jetbin).first << "-" << jetBins.at(jetbin).second << " Jets";
			title << "Njet " << njetlabel.str() << ", " << htrange << ", #Delta #Phi _{min}<" << dphibins.at(d);
			numeHistName << folder.str() << "/smear_signal";
			denoHistName << folder.str() << "/smeared_fail" << d;
			signalHistName << folder.str() << "/smear_signalFineBin";
			//signalHistName << folder.str() << "/smear_signal";
			controlHistName << folder.str() << "/smeared_failFineBin" << d;
			makePassFail_QCDMC(numeHistName.str(), denoHistName.str(), 
					title.str(), htrange, signalHistName.str(), controlHistName.str(), jetBins.at(jetbin), 50, 150); 
		}
	}


	c->Print("ratios.eps]");
}
void fillTree(TTree*& tree, TGraph*& graph, double& limit, unsigned int itype, std::map<double, std::string>& tanb_values, bool upper_exclusion, unsigned int verbosity)
{
  double value=-99;
  double tanb_help=-99;
  unsigned int ibin=0;
  // fill graph with scanned points
  for(std::map<double, std::string>::const_iterator tanb = tanb_values.begin(); tanb!=tanb_values.end(); ++tanb){
    value = singlePointLimit(tanb->second, tanb->first, itype, verbosity);
    if( value>0 ){
      graph->SetPoint(ibin++, tanb->first, value); 
    }
    tanb_help=tanb->first;
  }
  // determine smooth curve on graph for interpolation
  TSpline3* spline = new TSpline3("spline", graph, "r", 3., 10.);
  // linear polarisation func
  TF1 *fnc = 0;
  // determine all crossing points with y==1 
  std::vector<CrossPoint> points = crossPoints(graph);

  int dist = 1;
  bool filled = false;
  unsigned int np = 0;
  unsigned int steps = 10e6; 
  if(points.size()>0) limit = graph->GetX()[upper_exclusion ? points.begin()->first : points.end()->first];

  for(std::vector<CrossPoint>::const_reverse_iterator point = points.rbegin(); point!=points.rend(); ++point, ++np){
  //for(std::vector<CrossPoint>::iterator point = points.begin(); point!=points.end(); ++point, ++np){
    //double min = (point->first-dist)>0 ? graph->GetX()[point->first-dist] : graph->GetX()[0]; 
    double min = (point->first)>0 ? graph->GetX()[point->first] : graph->GetX()[0]; 
    double max = (point->first+dist)<graph->GetN() ? graph->GetX()[point->first+dist] : graph->GetX()[graph->GetN()-1];

    //double y_min = (point->first-dist)>0 ? graph->GetY()[point->first-dist] : graph->GetY()[0]; 
    double y_min = (point->first)>0 ? graph->GetY()[point->first] : graph->GetY()[0];
    double y_max = (point->first+dist)<graph->GetN() ? graph->GetY()[point->first+dist] : graph->GetY()[graph->GetN()-1];

    vector<double> crossing;
    crossing.push_back((min-max-y_max*min+y_min*max)/(y_min-y_max));
    //double crossing;
    //crossing = (1.-y_min)/(y_max-y_min)*(max-min); 
				  
    double deltaM = -999.;
    double offset = min; double step_size = (max-min)/steps;
    for(unsigned int scan=0; scan<=steps; ++scan){
      if(deltaM<0 || fabs(spline->Eval(offset+scan*step_size)-1.)<deltaM){
	limit=offset+scan*step_size;
	deltaM=fabs(spline->Eval(offset+scan*step_size)-1.);
      }
    }
    std::cout << "****************************************************************" << std::endl;
    std::cout << "* [" << np+1 << "|" << point->second << "] asymptotic limit(";
    std::cout << limitType(itype) << ") :" << crossing[np] << " -- " << limit << " deltaM : " << deltaM;
//     if(((upper_exclusion && point->second) || (!upper_exclusion && !(point->second))) && !filled){
//       //std::cout << "limit is taken from linear interpolation at the moment" << std::endl;
//       //limit = crossing;
//       std::cout << "    [-->to file]"; filled=true; tree->Fill();
//     }
    if(np==0){
      fnc = new TF1("fnc", "[0]*x+[1]", min, max);
      fnc->SetParameter(0, (y_min-y_max)/(min-max));
      fnc->SetParameter(1, (y_max*min-y_min*max)/(min-max));
      std::cout << std::endl;
      std::cout << "limit is taken from linear interpolation at the moment" << std::endl;
      limit = crossing[np];
      std::cout << limit << std::endl;
      std::cout << "    [-->to file]"; filled=true; tree->Fill();
    }
    std::cout << endl;
    std::cout << "****************************************************************" << std::endl;
  }
  // catch cases where no crossing point was found
  if(!filled){
    if(value<1)
      {
	std::cout << "WARNING: no crossing found - all tanb values excluded: " << value << std::endl;
	if(itype == observed)     { limit=3.00; }
	if(itype == plus_2sigma)  { limit=5.00; }
	if(itype == plus_1sigma)  { limit=4.00; }
	if(itype == expected)     { limit=3.00; }
	if(itype == minus_1sigma) { limit=2.50; }
	if(itype == minus_2sigma) { limit=2.00; }
	tree->Fill();
      }
    else
      {
	std::cout << "WARNING: no crossing found - no tanb value excluded: " << value << " -- " << tanb_help << std::endl;
	if(itype == observed)     { limit=tanb_help*value; }
	if(itype == plus_2sigma)  { limit=tanb_help*value; }
	if(itype == plus_1sigma)  { limit=tanb_help*value; }
	if(itype == expected)     { limit=tanb_help*value; }
	if(itype == minus_1sigma) { limit=tanb_help*value; }
	if(itype == minus_2sigma) { limit=tanb_help*value; }
	tree->Fill();
      }
  }
  if( verbosity>0 ){
    std::string monitor = std::string("SCAN-")+limitType(itype);
    TCanvas* canv = new TCanvas(monitor.c_str(), monitor.c_str(), 600, 600);
    TH1F* frame = canv->DrawFrame(graph->GetX()[0]-0.1, 0., graph->GetX()[graph->GetN()-1]+0.1, 10.);
    canv->SetGridx(1); canv->SetGridy(1); canv->cd(); 
    graph->SetMarkerStyle(20.); 
    graph->SetMarkerColor(kBlack); 
    graph->SetMarkerSize(1.3); 
    graph->Draw("P");
    //spline->SetLineColor(kBlue); 
    //spline->SetLineWidth(3.); 
    //spline->Draw("same");
    if(filled) fnc->SetLineColor(kRed);
    if(filled) fnc->SetLineWidth(3.);
    if(filled) fnc->Draw("same");
    canv->Print(monitor.append(".png").c_str(), "png");
    delete frame; delete canv; delete spline;
    if(filled) delete fnc;
  }
  return;
}
Esempio n. 15
0
void overlay_plots(const string& fFile0, const string& fFile1, const string& fPlot0, const string& fPlot1, const double fXmin, const double fXmax, const double fYmin, const double fYmax,const string& fXAxisLabel, const string& fYAxisLabel, const string& fTitle, const string& fName, const int doFit) {
  
   gStyle->SetOptStat(kFALSE);
 
   TH2F *h2[4];
   TH1F *h[2];
   
   TFile file0(fFile0.c_str());
   h2[0] = (TH2F*)file0.Get(fPlot0.c_str()); 
   h2[1] = (TH2F*)file0.Get(fPlot1.c_str()); 
   
   h2[0]->Add(h2[1],1.0);
   
   TFile file1(fFile1.c_str());
   h2[2] = (TH2F*)file1.Get(fPlot0.c_str()); 
   h2[3] = (TH2F*)file1.Get(fPlot1.c_str()); 
   
   h2[2]->Add(h2[3],1.0);
   
   h[0] = new TH1F("h0","h0",h2[0]->GetXaxis()->GetNbins(),h2[0]->GetXaxis()->GetXmin(),h2[0]->GetXaxis()->GetXmax());
   h[1] = new TH1F("h1","h1",h2[2]->GetXaxis()->GetNbins(),h2[2]->GetXaxis()->GetXmin(),h2[2]->GetXaxis()->GetXmax());
   
//    for(Int_t i=1; i<=h2[0]->GetNbinsX(); i++) {
     for(Int_t i=1; i<=14; i++) {

     TH1D* h_temp = h2[0]->ProjectionY("h_temp", i, i, "e");

     Int_t ngroup = 1;

     if( fTitle.find("900") != string::npos ) {
       if(i==10) ngroup = 2;
       else if(i==11) ngroup = 4;
       else if(i==12) ngroup = 4;
       else if(i==13) ngroup = 4;
       else if(i==14) ngroup = 8;
       else if(i==15) ngroup = 8;
     } else if( fTitle.find("2360") != string::npos ) {
       if(i==10) ngroup = 4;
       else if(i==11) ngroup = 4;
       else if(i==12) ngroup = 4;
       else if(i==13) ngroup = 4;
       else if(i==14) ngroup = 8;
       else if(i==15) ngroup = 8;
     }
     
     h_temp->Rebin(ngroup);
     
     TF1* f1= new TF1("f1", "gaus", h_temp->GetXaxis()->GetXmin(), h_temp->GetXaxis()->GetXmax());
     f1->SetParameters(h_temp->GetBinContent(h_temp->GetMaximumBin()),h_temp->GetMean(),h_temp->GetRMS());
     
     h_temp->Fit("f1","R", "",h_temp->GetXaxis()->GetXmin(),h_temp->GetXaxis()->GetXmax());
  
     h[0]->SetBinContent(i, f1->GetParameter(2));
     h[0]->SetBinError(i, f1->GetParError(2));
      
     delete f1;
     delete h_temp;
   }
   
//    for(Int_t i=1; i<=h2[2]->GetNbinsX(); i++) {
   for(Int_t i=1; i<=14; i++) {
    
     TH1D* h_temp = h2[2]->ProjectionY("h_temp", i, i, "e");
     
     Int_t ngroup = 1;

     if( fTitle.find("900") != string::npos ) {
       if(i==10) ngroup = 2;
       else if(i==11) ngroup = 4;
       else if(i==12) ngroup = 4;
       else if(i==13) ngroup = 4;
       else if(i==14) ngroup = 8;
       else if(i==15) ngroup = 8;
     } else if( fTitle.find("2360") != string::npos ) {
       if(i==10) ngroup = 4;
       else if(i==11) ngroup = 4;
       else if(i==12) ngroup = 4;
       else if(i==13) ngroup = 4;
       else if(i==14) ngroup = 8;
       else if(i==15) ngroup = 8;
     }
     
     h_temp->Rebin(ngroup);
  
     TF1* f1= new TF1("f1", "gaus", h_temp->GetXaxis()->GetXmin(), h_temp->GetXaxis()->GetXmax());
     f1->SetParameters(h_temp->GetBinContent(h_temp->GetMaximumBin()),h_temp->GetMean(),h_temp->GetRMS());
     h_temp->Fit("f1","R", "",h_temp->GetXaxis()->GetXmin(),h_temp->GetXaxis()->GetXmax());
  
     h[1]->SetBinContent(i, f1->GetParameter(2));
     h[1]->SetBinError(i, f1->GetParError(2));
      
     delete f1;
     delete h_temp;
   }
   
   h[1]->SetTitle(fTitle.c_str());
   h[1]->GetXaxis()->SetTitle(fXAxisLabel.c_str());
   h[1]->GetYaxis()->SetTitle(fYAxisLabel.c_str());
   h[1]->GetXaxis()->SetRangeUser(fXmin,fXmax);
   h[1]->GetYaxis()->SetRangeUser(fYmin,fYmax);

   h[1]->SetTitleOffset(1.,"X");
   h[1]->SetTitleOffset(1.,"Y");
//    h[1]->GetXaxis()->SetTitleSize(0.04);
//    h[1]->GetYaxis()->SetTitleSize(0.04);
   
   TCanvas *c = new TCanvas("c","",1200,800);
//    TCanvas *c = new TCanvas("c");
   c->cd();

   TF1 *fit = new TF1("fit","sqrt(pow([0],2)+pow([1],2)*(x-[3])+pow([2]*(x-[3]),2))",fXmin,(fXmax+1));
   fit->SetParName(0, "A");
   fit->SetParameter(0, 0.5);
   fit->SetParLimits(0, 0.1, 2);
   fit->SetParName(1, "B");
   fit->SetParameter(1, 0.5);
   fit->SetParLimits(1, 0, 1.5);
   fit->SetParName(2, "C");
   fit->SetParameter(2, 0.02);
   fit->SetParLimits(2, 0, 0.2);
   fit->SetParName(3, "D");
   fit->SetParameter(3, 3);
   fit->SetParLimits(3, 2, 5);
//    fit->FixParameter(3, 0);

   if(doFit==1) h[1]->Fit("fit","RV");

   h[0]->SetLineWidth(2);
   h[0]->SetLineStyle(2);
   h[0]->SetLineColor(kRed);
   h[0]->SetFillColor(kRed);
//    h[0]->SetMarkerSize(.6);
   h[0]->SetMarkerStyle(26);
   h[0]->SetMarkerColor(kRed);
   h[1]->SetLineWidth(2);
//    h[1]->SetLineStyle(3);
   h[1]->SetLineColor(kBlack);
//    h[1]->SetMarkerSize(.8);
   h[1]->SetMarkerStyle(20);
   h[1]->SetMarkerColor(kBlack);
   h[1]->Draw("");
   h[0]->Draw("same");
   if(doFit==1) fit->Draw("same");
   
   TLegend *legend = new TLegend(.65,.25,.95,.4);
   legend->SetBorderSize(0);
   legend->SetFillColor(0);
   legend->SetFillStyle(0);
   legend->SetTextFont(62);
   legend->AddEntry(h[1],"Data","lp");
   legend->AddEntry(h[0],"Simulation","lp");
   legend->Draw();
   
   TLatex l;
   l.SetTextAlign(12);
   l.SetTextSize(0.05);
   l.SetTextFont(62);
   l.SetNDC();
   l.DrawLatex(0.14,0.84,"CMS 2009 Preliminary");
   l.DrawLatex(0.14,0.79,("#sqrt{s}="+fTitle).c_str());
   l.DrawLatex(0.12,0.5,"f(x)=#sqrt{A^{2}+B^{2}(x-D)+C^{2}(x-D)^{2}}");

   c->SetGridx();
   c->SetGridy();

   c->SaveAs(fName.c_str());
   
   delete legend;
   delete h[0];
   delete h[1];
   delete c;
}
void showFunctions1d(std::vector<TF1*>& functions, const std::vector<std::string>& legendEntries,
		     const TString& xAxisTitle, double yMin, double yMax, const TString& yAxisTitle, 
		     const std::string& outputFileName)
{
  assert(functions.size() == legendEntries.size());

  TCanvas* canvas = new TCanvas("canvas", "canvas", 800, 600);
  canvas->SetFillColor(10);
  canvas->SetBorderSize(2);
  
  canvas->SetLeftMargin(0.12);
  canvas->SetBottomMargin(0.12);

  assert(functions.size() > 0);
  TF1* refFunction = functions[0];

  TH1* dummyHistogram = new TH1F("dummyHistogram", "dummyHistogram", 10, refFunction->GetXmin(), refFunction->GetXmax());
  dummyHistogram->SetStats(false);
  dummyHistogram->SetTitle("");
  dummyHistogram->SetMinimum(-TMath::Log(yMax));
  dummyHistogram->SetMaximum(-TMath::Log(yMax) + 5.);
  
  TAxis* xAxis = dummyHistogram->GetXaxis();
  xAxis->SetTitle(xAxisTitle.Data());
  xAxis->SetTitleOffset(1.15);

  TAxis* yAxis = dummyHistogram->GetYaxis();
  yAxis->SetTitle(Form("-log(%s)", yAxisTitle.Data()));
  yAxis->SetTitleOffset(1.30);

  dummyHistogram->Draw("axis");

  int colors[] = { 1, 2, 3, 4, 5, 6, 7, 15 };
  int numFunctions = functions.size();
  if ( numFunctions > 8 ) {
    std::cerr << "<showFunctions1d>:" << std::endl;
    std::cerr << "Number of functions must not exceed 8 !!" << std::endl;
    assert(0);
  }
  
  for ( int iFunction = 0; iFunction < numFunctions; ++iFunction ) {
    TF1* function = functions[iFunction];
    function->SetLineColor(colors[iFunction]);
    function->SetLineWidth(2);
    function->Draw("same");
  }

  TLegend* legend = new TLegend(0.68, 0.89 - (0.03 + 0.040*numFunctions), 0.89, 0.89, "", "brNDC"); 
  legend->SetBorderSize(0);
  legend->SetFillColor(0);
  legend->SetTextSize(0.035);
  for ( int iFunction = 0; iFunction < numFunctions; ++iFunction ) {
    TF1* function = functions[iFunction];
    const std::string& legendEntry = legendEntries[iFunction];
    legend->AddEntry(function, legendEntry.data(), "l");
  }
  legend->Draw();

  canvas->Update();
  size_t idx = outputFileName.find_last_of('.');
  std::string outputFileName_plot = std::string(outputFileName, 0, idx);
  if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName, idx)).data());
  canvas->Print(std::string(outputFileName_plot).append(".png").data());
  canvas->Print(std::string(outputFileName_plot).append(".pdf").data());

  delete dummyHistogram;
  delete legend;
  delete canvas;
}
Esempio n. 17
0
void overlay_plotsPAS(const string& fFile0, const string& fFile1, const string& fPlot0, const string& fPlot1, const double fXmin, const double fXmax, const double fYmin, const double fYmax,const string& fXAxisLabel, const string& fYAxisLabel, const string& fTitle, const string& fName, const int doFit) {
  
   gStyle->SetOptStat(kTRUE);
   gStyle->SetOptTitle(1);
 
   TH2F *h2[4];
   TH1F *h[2];
   
   TFile file0(fFile0.c_str());
   h2[0] = (TH2F*)file0.Get(fPlot0.c_str()); 
   h2[1] = (TH2F*)file0.Get(fPlot1.c_str()); 
   
   h2[0]->Add(h2[1],1.0);
   
   TFile file1(fFile1.c_str());
   h2[2] = (TH2F*)file1.Get(fPlot0.c_str()); 
   h2[3] = (TH2F*)file1.Get(fPlot1.c_str()); 
   
   h2[2]->Add(h2[3],1.0);
   
   h[0] = new TH1F("h0","h0",h2[0]->GetXaxis()->GetNbins(),h2[0]->GetXaxis()->GetXmin(),h2[0]->GetXaxis()->GetXmax());
   h[1] = new TH1F("h1","h1",h2[2]->GetXaxis()->GetNbins(),h2[2]->GetXaxis()->GetXmin(),h2[2]->GetXaxis()->GetXmax());
   
   TCanvas *c0 = new TCanvas("c0");
   c0->cd();
   
//    for(Int_t i=1; i<=h2[0]->GetNbinsX(); i++) {
   for(Int_t i=1; i<=14; i++) {

     string title;
    
     if( fTitle.find("900") != string::npos ) title = Form("h_SIM_900GeV_%i",i);
     else if( fTitle.find("2360") != string::npos ) title = Form("h_SIM_2360GeV_%i",i);
    
     TH1D* h_temp = h2[0]->ProjectionY(title.c_str(), i, i, "e");
     h_temp->SetTitle(title.c_str());
     h_temp->GetXaxis()->SetTitle("#slash{E}_{x,y}");
     
     Int_t ngroup = 1;

     if( fTitle.find("900") != string::npos ) {
       if(i==10) ngroup = 2;
       else if(i==11) ngroup = 4;
       else if(i==12) ngroup = 4;
       else if(i==13) ngroup = 4;
       else if(i==14) ngroup = 8;
       else if(i==15) ngroup = 8;
     } else if( fTitle.find("2360") != string::npos ) {
       if(i==10) ngroup = 4;
       else if(i==11) ngroup = 4;
       else if(i==12) ngroup = 4;
       else if(i==13) ngroup = 4;
       else if(i==14) ngroup = 8;
       else if(i==15) ngroup = 8;
     }
     
     h_temp->Rebin(ngroup);
     
     TF1* f1= new TF1("f1", "gaus", h_temp->GetXaxis()->GetXmin(), h_temp->GetXaxis()->GetXmax());
     f1->SetParameters(h_temp->GetBinContent(h_temp->GetMaximumBin()),h_temp->GetMean(),h_temp->GetRMS());
     h_temp->Fit("f1","R", "",h_temp->GetXaxis()->GetXmin(),h_temp->GetXaxis()->GetXmax());

//      h_temp->Draw();
//      c0->SetLogy();
//      c0->SaveAs((title+".png").c_str());
     
     h[0]->SetBinContent(i, f1->GetParameter(2));
     h[0]->SetBinError(i, f1->GetParError(2));
      
     delete f1;
     delete h_temp;
   }
   
//    for(Int_t i=1; i<=h2[2]->GetNbinsX(); i++) {
   for(Int_t i=1; i<=14; i++) {
    
     string title;
    
     if( fTitle.find("900") != string::npos ) title = Form("h_DATA_900GeV_%i",i);
     else if( fTitle.find("2360") != string::npos ) title = Form("h_DATA_2360GeV_%i",i);
    
     TH1D* h_temp = h2[2]->ProjectionY(title.c_str(), i, i, "e");
     h_temp->SetTitle(title.c_str());
     h_temp->GetXaxis()->SetTitle("#slash{E}_{x,y}");
          
     Int_t ngroup = 1;

     if( fTitle.find("900") != string::npos ) {
       if(i==10) ngroup = 2;
       else if(i==11) ngroup = 4;
       else if(i==12) ngroup = 4;
       else if(i==13) ngroup = 4;
       else if(i==14) ngroup = 8;
       else if(i==15) ngroup = 8;
     } else if( fTitle.find("2360") != string::npos ) {
       if(i==10) ngroup = 4;
       else if(i==11) ngroup = 4;
       else if(i==12) ngroup = 4;
       else if(i==13) ngroup = 4;
       else if(i==14) ngroup = 8;
       else if(i==15) ngroup = 8;
     }
     
     h_temp->Rebin(ngroup);
  
     TF1* f1= new TF1("f1", "gaus", h_temp->GetXaxis()->GetXmin(), h_temp->GetXaxis()->GetXmax());
     f1->SetParameters(h_temp->GetBinContent(h_temp->GetMaximumBin()),h_temp->GetMean(),h_temp->GetRMS());
     h_temp->Fit("f1","R", "",h_temp->GetXaxis()->GetXmin(),h_temp->GetXaxis()->GetXmax());
  
//      h_temp->Draw();
//      c0->SetLogy();
//      c0->SaveAs((title+".png").c_str());
     
     h[1]->SetBinContent(i, f1->GetParameter(2));
     h[1]->SetBinError(i, f1->GetParError(2));
      
     delete f1;
     delete h_temp;
   }
   
   h[0]->SetTitle(fTitle.c_str());
   h[0]->GetXaxis()->SetTitle(fXAxisLabel.c_str());
   h[0]->GetYaxis()->SetTitle(fYAxisLabel.c_str());
   h[0]->GetXaxis()->SetRangeUser(fXmin,fXmax);
   h[0]->GetYaxis()->SetRangeUser(fYmin,fYmax);

   h[0]->SetTitleOffset(1.,"X");
   h[0]->SetTitleOffset(1.,"Y");
//    h[0]->GetXaxis()->SetTitleSize(0.04);
//    h[0]->GetYaxis()->SetTitleSize(0.04);

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

//    TCanvas *c = new TCanvas("c","",1200,800);
   TCanvas *c = new TCanvas("c");
   c->cd();
  
   h[0]->SetLineWidth(2);
   h[0]->SetLineStyle(2);
   h[0]->SetLineColor(kRed);
   h[0]->SetFillColor(kRed);
   h[0]->SetMarkerSize(1.);
   h[0]->SetMarkerStyle(26);
   h[0]->SetMarkerColor(kRed);
   h[0]->Draw("");
   h[1]->SetLineWidth(2);
//    h[1]->SetLineStyle(3);
   h[1]->SetLineColor(kBlack);
   h[1]->SetMarkerSize(1.);
   h[1]->SetMarkerStyle(20);
   h[1]->SetMarkerColor(kBlack);
   h[1]->Draw("same");
   
   TLegend *legend = new TLegend(.61,.26,.91,.41);
   legend->SetBorderSize(1);
   legend->SetFillColor(0);
//    legend->SetFillStyle(0);
   legend->SetTextFont(42);
   legend->AddEntry(h[1],"Data","lp");
   legend->AddEntry(h[0],"Simulation","lp");
   legend->Draw();
   
   TLatex l;
   l.SetTextAlign(12);
   l.SetTextSize(0.04);
   l.SetTextFont(62);
   l.SetNDC();
   l.DrawLatex(0.15,0.88,("#splitline{CMS Preliminary 2009}{#sqrt{s}="+fTitle+"}").c_str());

   c->SetGridx();
   c->SetGridy();
   
   string fileName = fName;
   c->SaveAs(fileName.c_str());
   
   delete legend;
   delete h[0];
   delete h[1];
   delete c0;
   delete c;
}
Esempio n. 18
0
void Draw_Time_Hists(TTree* t) {
   // Draw processing time, CPU time, and latency per packet
   // distributions from the input tree

   if (!t) {
      cout << "Invalid input tree" << endl;
      return;
   }

   gROOT->SetStyle("Plain");
   gStyle->SetOptStat(0);
   gStyle->SetNdivisions(505);
   gStyle->SetTitleFontSize(0.1);

   if(!TString(gSystem->GetLibraries()).Contains("Proof"))
      gSystem->Load("libProof.so");

   TCanvas* canvas = new TCanvas("ProfHists","Profile Histograms",800,600);
   canvas->Divide(3,1);

   canvas->cd(1);
   gPad->SetLogy();
   t->Draw("fProcTime");
   TH1* h = dynamic_cast<TH1*>(gROOT->FindObject("htemp"));
   h->SetTitle("Processing Time per Packet");
   h->GetXaxis()->SetTitle("Processing Time [s]");

   gPad->Update();
   TPaveText* titlepave = 0;
   titlepave = dynamic_cast<TPaveText*>(gPad->GetListOfPrimitives()->FindObject("title"));
   if (titlepave) {
      Double_t x1ndc = titlepave->GetX1NDC();
      Double_t x2ndc = titlepave->GetX2NDC();
      titlepave->SetX1NDC((1.0-x2ndc+x1ndc)/2.);
      titlepave->SetX2NDC((1.0+x2ndc-x1ndc)/2.);
      titlepave->SetBorderSize(0);
      gPad->Update();
   }
   gPad->Modified();

   canvas->cd(2);
   gPad->SetLogy();
   t->Draw("fCpuTime");
   h = dynamic_cast<TH1*>(gROOT->FindObject("htemp"));
   h->SetTitle("CPU Time per Packet");
   h->GetXaxis()->SetTitle("CPU Time [s]");

   gPad->Update();
   titlepave = dynamic_cast<TPaveText*>(gPad->GetListOfPrimitives()->FindObject("title"));
   if (titlepave) {
      Double_t x1ndc = titlepave->GetX1NDC();
      Double_t x2ndc = titlepave->GetX2NDC();
      titlepave->SetX1NDC((1.0-x2ndc+x1ndc)/2.);
      titlepave->SetX2NDC((1.0+x2ndc-x1ndc)/2.);
      titlepave->SetBorderSize(0);
      gPad->Update();
   }
   gPad->Modified();

   canvas->cd(3);
   gPad->SetLogy();
   t->Draw("fLatency");
   h = dynamic_cast<TH1*>(gROOT->FindObject("htemp"));
   h->SetTitle("Request Packet Latency");
   h->GetXaxis()->SetTitle("Latency [s]");

   gPad->Update();
   titlepave = dynamic_cast<TPaveText*>(gPad->GetListOfPrimitives()->FindObject("title"));
   if (titlepave) {
      Double_t x1ndc = titlepave->GetX1NDC();
      Double_t x2ndc = titlepave->GetX2NDC();
      titlepave->SetX1NDC((1.0-x2ndc+x1ndc)/2.);
      titlepave->SetX2NDC((1.0+x2ndc-x1ndc)/2.);
      titlepave->SetBorderSize(0);
      gPad->Update();
   }
   gPad->Modified();

}
Esempio n. 19
0
	void fitpeaks(int bin){
		switch (bin)
		{
			case 0:
				cut_="abs(upsRapidity)<2.4";
				//cut_="( (muPlusPt>3.5 && abs(muPlusEta)<1.6) || (muPlusPt>2.5 && abs(muPlusEta)>=1.6 && abs(muPlusEta)<2.4) ) && ( (muMinusPt>3.5 && abs(muMinusEta)<1.6) || (muMinusPt>2.5 && abs(muMinusEta)>=1.6 && abs(muMinusEta)<2.4) ) && abs(upsRapidity)<2.0";   //pp acceptance for Upsilon 
				suffix_="";
				f2Svs1S_pp->setVal(0.5569);
				//f2Svs1S_pp->setVal(0);
				f3Svs1S_pp->setVal(0.4140);
				//f3Svs1S_pp->setVal(0);
				break;
			case 1:
				cut_="abs(upsRapidity)>=0.0 && abs(upsRapidity)<1.2";
				suffix_="_eta0-12"; binw_=0.14;
				break;
			case 2:
				cut_="abs(upsRapidity)>=1.2 && abs(upsRapidity)<2.4";
				suffix_="_eta12-24"; binw_=0.14;
				break;
			case 3:
				cut_="Centrality>=0 && Centrality<2";
				suffix_="_cntr0-5"; binw_=0.14;
				break;
			case 4:
				cut_="Centrality>=2 && Centrality<4";
				suffix_="_cntr5-10"; binw_=0.14;
				break;
			case 5:
				cut_="Centrality>=4 && Centrality<8";
				suffix_="_cntr10-20"; binw_=0.14;
				break;
			case 6:
				cut_="Centrality>=8 && Centrality<12";
				suffix_="_cntr20-30"; binw_=0.14;
				break;
			case 7:
				cut_="Centrality>=12 && Centrality<16";
				suffix_="_cntr30-40"; binw_=0.14;
				break;
			case 8:
				cut_="Centrality>=16 && Centrality<20";
				suffix_="_cntr40-50"; binw_=0.14;
				break;
			case 9:
				cut_="Centrality>=20 && Centrality<50";
				suffix_="_cntr50-100"; binw_=0.14;
				break;
			case 10:
				cut_="Centrality>=20 && Centrality<24";
				suffix_="_cntr50-60"; binw_=0.14;
				break;
			case 11:
				cut_="Centrality>=0 && Centrality<8";
				suffix_="_cntr0-20"; binw_=0.1;
				break;
			case 12:
				cut_="Centrality>=16 && Centrality<50";
				suffix_="_cntr40-100"; binw_=0.14;
				break;
			case 13:
				cut_="Centrality>=8 && Centrality<50";
				suffix_="_cntr20-100"; binw_=0.1;
				break;
			default:
				cout<<"error in binning"<<endl;
				break;
		}

		cout << "oniafitter processing"
			<< "\n\tInput:  \t" << finput
			<< "\n\tresults:\t" << figs_
			<< endl;
		ofstream outfile("fitresults.out", ios_base::app);
		outfile<<endl<<"**********"<<suffix_<<"**********"<<endl<<endl;

		//read the data
		TFile f(finput,"read");
		gDirectory->Cd(finput+":/"+dirname_);
		TTree* theTree     = (TTree*)gROOT->FindObject("UpsilonTree");
		TTree* allsignTree     = (TTree*)gROOT->FindObject("UpsilonTree_allsign");
		if (PR_plot) {TRKROT = 1; PbPb=1;}
		if (TRKROT) TTree* trkRotTree = (TTree*)gROOT->FindObject("UpsilonTree_trkRot");

		RooRealVar* mass  = new RooRealVar("invariantMass","#mu#mu mass",mmin_,mmax_,"GeV/c^{2}");
		RooRealVar* upsPt  = new RooRealVar("upsPt","p_{T}(#Upsilon)",0,60,"GeV");
		RooRealVar* upsEta = new RooRealVar("upsEta",  "upsEta"  ,-7,7);
		RooRealVar* upsRapidity = new RooRealVar("upsRapidity",  "upsRapidity"  ,-2.4,2.4);
		RooRealVar* vProb = new RooRealVar("vProb",  "vProb"  ,0.05,1.00);
		RooRealVar* QQsign = new RooRealVar("QQsign",  "QQsign"  ,-1,5);
		RooRealVar* weight = new RooRealVar("weight",  "weight"  ,-2,2);
		if (PbPb) RooRealVar* Centrality = new RooRealVar("Centrality",  "Centrality"  ,0,40);
		RooRealVar* muPlusPt = new RooRealVar("muPlusPt","muPlusPt",muonpTcut,50);
		RooRealVar* muPlusEta = new RooRealVar("muPlusEta","muPlusEta",-2.5,2.5);
		RooRealVar* muMinusPt = new RooRealVar("muMinusPt","muMinusPt",muonpTcut,50);
		RooRealVar* muMinusEta = new RooRealVar("muMinusEta","muMinusEta",-2.5,2.5);


		//import unlike-sign data set
		RooDataSet* data0, *data, *likesignData0, *likesignData, *TrkRotData0, *TrkRotData;
		if (PbPb) data0 = new RooDataSet("data","data",theTree,RooArgSet(*mass,*upsRapidity,*vProb,*upsPt,*Centrality,*muPlusPt,*muMinusPt));
		//data0 = new RooDataSet("data","data",theTree,RooArgSet(*mass,*upsRapidity,*upsPt,*muPlusPt,*muMinusPt,*QQsign,*weight));
		else data0 = new RooDataSet("data","data",theTree,RooArgSet(*mass,*upsRapidity,*vProb,*upsPt,*muPlusPt,*muMinusPt,*muPlusEta,*muMinusEta));
		data0->Print();
		data = ( RooDataSet*) data0->reduce(Cut(cut_));
		data->Print();

		//import like-sign data set
		if (PbPb) likesignData0 = new RooDataSet("likesignData","likesignData",allsignTree,RooArgSet(*mass,*upsRapidity,*vProb,*upsPt,*Centrality,*muPlusPt,*muMinusPt,*QQsign));
		else likesignData0 = new RooDataSet("likesignData","likesignData",allsignTree,RooArgSet(*mass,*upsRapidity,*vProb,*upsPt,*muPlusPt,*muMinusPt,*QQsign));
		likesignData0->Print();
		likesignData = ( RooDataSet*) likesignData0->reduce(Cut(cut_+" && QQsign != 0"));
		likesignData->Print();


		//import track-rotation data set
		if (TRKROT) {
			if (PbPb) TrkRotData0 = new RooDataSet("TrkRotData","TrkRotData",trkRotTree,RooArgSet(*mass,*upsRapidity,*vProb,*upsPt,*Centrality,*muPlusPt,*muMinusPt,*QQsign));
			else TrkRotData0 = new RooDataSet("TrkRotData","TrkRotData",trkRotTree,RooArgSet(*mass,*upsRapidity,*upsPt,*vProb,*muPlusPt,*muMinusPt,*QQsign));
			TrkRotData0->Print();
			if (PR_plot && RAA) TrkRotData = ( RooDataSet*) TrkRotData0->reduce(Cut(cut_+" && upsPt < 8.1"));
			else if (PR_plot && !RAA) TrkRotData = ( RooDataSet*) TrkRotData0->reduce(Cut(cut_+" && upsPt < 7.07"));
			else TrkRotData = ( RooDataSet*) TrkRotData0->reduce(Cut(cut_+" && QQsign != 0"));
			TrkRotData->Print();
		}

		mass->setRange("R1",7.0,10.2);
		mass->setRange("R2",7,14);
		mass->setRange("R3",10.8,14);
		const double M1S = 9.46;   //upsilon 1S pgd mass value
		const double M2S = 10.02;  //upsilon 2S pgd mass value
		const double M3S = 10.35;  //upsilon 3S pgd mass value

		RooRealVar *mean    = new RooRealVar("#mu_{#Upsilon(1S)}","#Upsilon mean",M1S,M1S-0.1,M1S+0.1);
		RooRealVar *shift21 = new RooRealVar("shift2","mass diff #Upsilon(1,2S)",M2S-M1S);
		RooRealVar *shift31 = new RooRealVar("shift3","mass diff #Upsilon(1,3S)",M3S-M1S);
		RooRealVar *mscale  = new RooRealVar("mscale","mass scale factor",1.,0.7,1.3);
		mscale->setConstant(kTRUE); /* the def. parameter value is fixed in the fit */
		RooFormulaVar *mean1S = new RooFormulaVar("mean1S","@0",
				RooArgList(*mean));
		RooFormulaVar *mean2S = new RooFormulaVar("mean2S","@0+@1*@2",
				RooArgList(*mean,*mscale,*shift21));
		RooFormulaVar *mean3S = new RooFormulaVar("mean3S","@0+@1*@2",
				RooArgList(*mean,*mscale,*shift31));

		RooRealVar *sigma1 = new RooRealVar("sigma","Sigma_1",0.10,0.01,0.30);    //detector resolution
		RooRealVar *sigma2 = new RooRealVar("#sigma_{#Upsilon(1S)}","Sigma_1S",0.08,0.01,0.30); //Y(1S) resolution
		RooFormulaVar *reso1S = new RooFormulaVar("reso1S","@0"             ,RooArgList(*sigma2));
		RooFormulaVar *reso2S = new RooFormulaVar("reso2S","@0*10.023/9.460",RooArgList(*sigma2));
		RooFormulaVar *reso3S = new RooFormulaVar("reso3S","@0*10.355/9.460",RooArgList(*sigma2));

		/// to describe final state radiation tail on the left of the peaks
		RooRealVar *alpha  = new RooRealVar("alpha","tail shift",0.982,0,2.4);   // minbias fit value
		//RooRealVar *alpha  = new RooRealVar("alpha","tail shift",1.6,0.2,4);   // MC value
		RooRealVar *npow   = new RooRealVar("npow","power order",2.3,1,3);       // MC value
		npow ->setConstant(kTRUE);
		if (!fitMB) alpha->setConstant(kTRUE);
		// relative fraction of the two peak components 
		RooRealVar *sigmaFraction = new RooRealVar("sigmaFraction","Sigma Fraction",0.3,0.,1.);
		sigmaFraction->setVal(0);
		sigmaFraction->setConstant(kTRUE);

		/// Upsilon 1S
		//RooCBShape  *gauss1S1 = new RooCBShape ("gauss1S1", "FSR cb 1s",
		//                  *mass,*mean1S,*sigma1,*alpha,*npow);
		RooCBShape  *gauss1S2 = new RooCBShape ("gauss1S2", "FSR cb 1s",
				*mass,*mean1S,*reso1S,*alpha,*npow);
		//RooAddPdf *sig1S      = new RooAddPdf  ("sig1S","1S mass pdf",
		//                  RooArgList(*gauss1S1,*gauss1S2),*sigmaFraction);

		//mean->setVal(9.46);
		//mean->setConstant(kTRUE);
		sigma1->setVal(0);
		sigma1->setConstant(kTRUE);
		if (!fitMB) {
			sigma2->setVal(width_);        //fix the resolution
			sigma2->setConstant(kTRUE);
		}
		/// Upsilon 2S
		RooCBShape  *gauss2S1 = new RooCBShape ("gauss2S1", "FSR cb 2s", 
				*mass,*mean2S,*sigma1,*alpha,*npow); 
		RooCBShape  *gauss2S2 = new RooCBShape ("gauss2S2", "FSR cb 2s", 
				*mass,*mean2S,*reso2S,*alpha,*npow); 
		RooAddPdf *sig2S      = new RooAddPdf  ("sig2S","2S mass pdf",
				RooArgList(*gauss2S1,*gauss2S2),*sigmaFraction);

		/// Upsilon 3S
		RooCBShape  *gauss3S1 = new RooCBShape ("gauss3S1", "FSR cb 3s", 
				*mass,*mean3S,*sigma1,*alpha,*npow); 
		RooCBShape  *gauss3S2 = new RooCBShape ("gauss3S2", "FSR cb 3s", 
				*mass,*mean3S,*reso3S,*alpha,*npow); 
		RooAddPdf *sig3S      = new RooAddPdf  ("sig3S","3S mass pdf",
				RooArgList(*gauss3S1,*gauss3S2),*sigmaFraction);

		/// Background
		RooRealVar *bkg_a1  = new RooRealVar("bkg_{a1}", "background a1", 0, -2, 2);
		RooRealVar *bkg_a2  = new RooRealVar("bkg_{a2}", "background a2", 0, -1, 1);
		//RooRealVar *bkg_a3  = new RooRealVar("bkg_{a3}", "background a3", 0, -1, 1);
		RooAbsPdf  *bkgPdf  = new RooChebychev("bkg","background",
				*mass, RooArgList(*bkg_a1,*bkg_a2));
		//bkg_a1->setVal(0);
		//bkg_a1->setConstant(kTRUE);
		//bkg_a2->setVal(0);
		//bkg_a2->setConstant(kTRUE); //set constant for liner background

		// only sideband region pdf, using RooPolynomial instead of RooChebychev for multiple ranges fit
		RooRealVar *SB_bkg_a1  = new RooRealVar("SB bkg_{a1}", "background a1", 0, -1, 1);
		RooRealVar *SB_bkg_a2  = new RooRealVar("SB bkg_{a2}", "background a2", 0, -1, 1);
		RooAbsPdf  *SB_bkgPdf  = new RooPolynomial("SB_bkg","side-band background",
				*mass, RooArgList(*SB_bkg_a1,*SB_bkg_a2));
		//SB_bkg_a1->setVal(0);
		//SB_bkg_a1->setConstant(kTRUE);
		//SB_bkg_a2->setVal(0);
		//SB_bkg_a2->setConstant(kTRUE);

		/// Combined pdf
		int nt = 100000;
		//bool fitfraction = true;
		RooRealVar *nbkgd = new RooRealVar("N_{bkg}","nbkgd",nt*0.75,0,10*nt);
		RooRealVar *SB_nbkgd = new RooRealVar("SB N_{bkg}","SB_nbkgd",nt*0.75,0,10*nt);
		RooRealVar *nsig1f  = new RooRealVar("N_{#Upsilon(1S)}","nsig1S",nt*0.25,0,10*nt);
		/*
		//use the YIELDs of 2S and 3S as free parameters
		RooRealVar *nsig2f  = new RooRealVar("N_{#Upsilon(2S)}","nsig2S",   nt*0.25,-1*nt,10*nt);
		RooRealVar *nsig3f  = new RooRealVar("N_{#Upsilon(3S)}","nsig3S",   nt*0.25,-1*nt,10*nt);
		 */
		//use the RATIOs of 2S and 3S as free parameters
		RooRealVar *f2Svs1S = new RooRealVar("N_{2S}/N_{1S}","f2Svs1S",0.21,-0.1,1);
		//RooRealVar *f3Svs1S = new RooRealVar("N_{3S}/N_{1S}","f3Svs1S",0.0,-0.1,0.5);
		RooRealVar *f23vs1S = new RooRealVar("N_{2S+3S}/N_{1S}","f23vs1S",0.45,-0.1,1);
		RooFormulaVar *nsig2f = new RooFormulaVar("nsig2S","@0*@1", RooArgList(*nsig1f,*f2Svs1S));
		//RooFormulaVar *nsig3f = new RooFormulaVar("nsig3S","@0*@1", RooArgList(*nsig1f,*f3Svs1S));
		RooFormulaVar *nsig3f = new RooFormulaVar("nsig3S","@0*@2-@0*@1", RooArgList(*nsig1f,*f2Svs1S,*f23vs1S));

		//f3Svs1S->setConstant(kTRUE);

		//force the ratio to the pp value
		f2Svs1S_pp->setConstant(kTRUE);
		f3Svs1S_pp->setConstant(kTRUE);
		RooFormulaVar *nsig2f_ = new RooFormulaVar("nsig2S_pp","@0*@1", RooArgList(*nsig1f,*f2Svs1S_pp)); 
		RooFormulaVar *nsig3f_ = new RooFormulaVar("nsig3S_pp","@0*@1", RooArgList(*nsig1f,*f3Svs1S_pp)); 

		//only sideband region pdf, using RooPolynomial instead of RooChebychev for multiple ranges fit
		RooAbsPdf  *SB_pdf = new RooAddPdf ("SB_pdf","sideband background pdf",
				RooArgList(*SB_bkgPdf),
				RooArgList(*SB_nbkgd));
		//only signal region pdf, using RooPolynomial instead of RooChebychev for multiple ranges fit
		RooAbsPdf  *S_pdf   = new RooAddPdf ("S_pdf","total signal+background pdf",
				RooArgList(*gauss1S2,*sig2S,*sig3S,*SB_bkgPdf),
				RooArgList(*nsig1f,*nsig2f,*nsig3f,*SB_nbkgd));

		//parameters for likesign
		RooRealVar m0shift("turnOn","turnOn",8.6,0,20.) ;
		RooRealVar width("width","width",2.36,0,20.) ;
		RooRealVar par3("decay","decay",6.8, 0, 20.) ;
		RooGaussian* m0shift_constr;
		RooGaussian* width_constr;
		RooGaussian* par3_constr;

		RooRealVar *nLikesignbkgd = new RooRealVar("NLikesign_{bkg}","nlikesignbkgd",nt*0.75,0,10*nt);
		if (TRKROT) {
			nLikesignbkgd->setVal(TrkRotData->sumEntries());
			nLikesignbkgd->setError(sqrt(TrkRotData->sumEntries()));
		}
		else {
			nLikesignbkgd->setVal(likesignData->sumEntries());
			nLikesignbkgd->setError(sqrt(likesignData->sumEntries()));
		}

		if (LS_constrain) {
			RooGaussian* nLikesignbkgd_constr = new RooGaussian("nLikesignbkgd_constr","nLikesignbkgd_constr",*nLikesignbkgd,RooConst(nLikesignbkgd->getVal()),RooConst(nLikesignbkgd->getError()));
		}
		else nLikesignbkgd->setConstant(kTRUE);

		RooFormulaVar *nResidualbkgd = new RooFormulaVar("NResidual_{bkg}","@0-@1",RooArgList(*nbkgd,*nLikesignbkgd));

		switch (bkgdModel) {
			case 1 :  //use error function to fit the like-sign, then fix the shape and normailization, 
				RooGenericPdf *LikeSignPdf = new  RooGenericPdf("Like-sign","likesign","exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",RooArgList(*mass,m0shift,width,par3));
				if (TRKROT) RooFitResult* fit_1st = LikeSignPdf->fitTo(*TrkRotData,Save()) ;
				else RooFitResult* fit_1st = LikeSignPdf->fitTo(*likesignData,Save()) ; // likesign data
				//LikeSignPdf.fitTo(*data) ;       // unlikesign data    
				//fit_1st->Print();
				if (LS_constrain) {
					m0shift_constr = new RooGaussian("m0shift_constr","m0shift_constr",m0shift,RooConst(m0shift.getVal()),RooConst(m0shift.getError()));
					width_constr = new RooGaussian("width_constr","width_constr",width,RooConst(width.getVal()),RooConst(width.getError()));
					par3_constr = new RooGaussian("par3_constr","par3_constr",par3,RooConst(par3.getVal()),RooConst(par3.getError()));
					//m0shift_constr = new RooGaussian("m0shift_constr","m0shift_constr",m0shift,RooConst(7.9),RooConst(0.34*2));
					//width_constr = new RooGaussian("width_constr","width_constr",width,RooConst(2.77),RooConst(0.38*2));
					//par3_constr = new RooGaussian("par3_constr","par3_constr",par3,RooConst(6.3),RooConst(1.0*2));
				}
				else {
					m0shift.setConstant(kTRUE);
					width.setConstant(kTRUE);
					par3.setConstant(kTRUE);
				}
				RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("pdf_combinedbkgd","total combined background pdf",
						RooArgList(*bkgPdf,*LikeSignPdf),
						RooArgList(*nResidualbkgd,*nLikesignbkgd));
				//RooArgList(*LikeSignPdf),
				//RooArgList(*nbkgd));
				break;

			case 2 : //use RooKeysPdf to smooth the like-sign, then fix the shape and normailization
				if (TRKROT) RooKeysPdf *LikeSignPdf = new RooKeysPdf("Like-sign","likesign",*mass,*TrkRotData,3,1.5);
				else RooKeysPdf *LikeSignPdf = new RooKeysPdf("Like-sign","likesign",*mass,*likesignData,3,1.7);
				RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("pdf_combinedbkgd","total combined background pdf",
						RooArgList(*bkgPdf,*LikeSignPdf),
						RooArgList(*nResidualbkgd,*nLikesignbkgd));
				break;

			case 3 : //use error function to fit the unlike-sign directly
				RooGenericPdf *LikeSignPdf = new  RooGenericPdf("Like-sign","likesign","exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",RooArgList(*mass,m0shift,width,par3));
				RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("pdf_combinedbkgd","total combined background pdf",
						RooArgList(*LikeSignPdf),
						RooArgList(*nbkgd));
				break;

			case 4 : //use polynomial to fit the unlike-sign directly
				RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("pdf_combinedbkgd","total combined background pdf",
						RooArgList(*bkgPdf),
						RooArgList(*nbkgd));
				break;


			case 5 : //use ( error function + polynomial ) to fit the unlike-sign directly
				RooGenericPdf *LikeSignPdf = new  RooGenericPdf("Like-sign","likesign","exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",RooArgList(*mass,m0shift,width,par3));
				RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("pdf_combinedbkgd","total combined background pdf",
						RooArgList(*bkgPdf,*LikeSignPdf),
						RooArgList(*nResidualbkgd,*nLikesignbkgd));
				break;

			default :
				break;
		}

		//pdf with fixed ratio of the pp ratio
		RooAbsPdf  *pdf_pp   = new RooAddPdf ("pdf_pp","total signal+background pdf",
				RooArgList(*gauss1S2,*sig2S,*sig3S,*pdf_combinedbkgd),
				RooArgList(*nsig1f,*nsig2f_,*nsig3f_,*nbkgd));

		//the nominal fit with default pdf 
		if (LS_constrain) {
			RooAbsPdf  *pdf_unconstr   = new RooAddPdf ("pdf_unconstr","total signal+background pdf",
					RooArgList(*gauss1S2,*sig2S,*sig3S,*pdf_combinedbkgd),
					RooArgList(*nsig1f,*nsig2f,*nsig3f,*nbkgd));
			RooProdPdf *pdf  = new RooProdPdf ("pdf","total constr pdf",
					RooArgSet(*pdf_unconstr,*m0shift_constr,*width_constr,*par3_constr,*nLikesignbkgd_constr));
			RooFitResult* fit_2nd = pdf->fitTo(*data,Constrained(),Save(kTRUE),Extended(kTRUE),Minos(doMinos));
		}
		else {
			RooAbsPdf  *pdf   = new RooAddPdf ("pdf","total signal+background pdf",
					RooArgList(*gauss1S2,*sig2S,*sig3S,*pdf_combinedbkgd),
					RooArgList(*nsig1f,*nsig2f,*nsig3f,*nbkgd));
			RooFitResult* fit_2nd = pdf->fitTo(*data,Save(kTRUE),Extended(kTRUE),Minos(doMinos));
		}


		//plot
		TCanvas c; c.cd();
		int nbins = ceil((mmax_-mmin_)/binw_); 
		RooPlot* frame = mass->frame(Bins(nbins),Range(mmin_,mmax_));
		data->plotOn(frame,Name("theData"),MarkerSize(0.8));
		pdf->plotOn(frame,Name("thePdf"));
		if (plotLikeSign) {
			if (TRKROT) TrkRotData->plotOn(frame,Name("theLikeSignData"),MarkerSize(0.8),MarkerColor(kMagenta),MarkerStyle(22));
			else likesignData->plotOn(frame,Name("theLikeSignData"),MarkerSize(0.8),MarkerColor(kRed),MarkerStyle(24));
			//LikeSignPdf->plotOn(frame,Name("theLikeSign"),VisualizeError(*fit_1st,1),FillColor(kOrange));
			//LikeSignPdf->plotOn(frame,Name("theLikeSign"),LineColor(kRed));
		}
		RooArgSet * pars = pdf->getParameters(data);
		//RooArgSet * pars = LikeSignPdf->getParameters(likesignData);

		//calculate chi2 in a mass range
		float bin_Min = (8.2-mmin_)/binw_;
		float bin_Max = (10.8-mmin_)/binw_;
		int binMin = ceil(bin_Min);
		int binMax = ceil(bin_Max);
		int nfloatpars = pars->selectByAttrib("Constant",kFALSE)->getSize();
		float myndof = ceil((10.8-8.2)/binw_) - nfloatpars;
		cout<<binMin<<" "<<binMax<<" "<<nfloatpars<<" "<<myndof<<endl;
		double mychsq = frame->mychiSquare("thePdf","theData",nfloatpars,true,binMin,binMax)*myndof;
		//double mychsq = frame->mychiSquare("theLikeSign","theLikeSignData",nfloatpars,true,binMin,binMax)*myndof;

		/*
		   int nfloatpars = pars->selectByAttrib("Constant",kFALSE)->getSize();
		   float myndof = frame->GetNbinsX() - nfloatpars;
		   double mychsq = frame->chiSquare("theLikeSign","theLikeSignData",nfloatpars)*myndof;
		 */
		//plot parameters
		if(plotpars) {
			paramOn_ = "_paramOn";
			pdf->paramOn(frame,Layout(0.15,0.6,0.4),Layout(0.5,0.935,0.97),Label(Form("#chi^{2}/ndf = %2.1f/%2.0f", mychsq,myndof)));
		}

		/*
		   mass->setRange("R1S",8.8,9.7);
		   mass->setRange("R2S",9.8,10.2);
		//pdf_combinedbkgd->fitTo(*data,Range("R1,R3"),Constrained(),Save(kTRUE),Extended(kTRUE),Minos(doMinos));
		RooAbsReal* integral_1S = pdf_combinedbkgd->createIntegral(*mass,NormSet(*mass),Range("R1S")) ;
		cout << "1S bkgd integral = " << integral_1S->getVal() * (nbkgd->getVal()) << endl ;
		RooAbsReal* integral_2S = pdf_combinedbkgd->createIntegral(*mass,NormSet(*mass),Range("R2S")) ;
		cout << "2S bkgd integral = " << integral_2S->getVal() * (nbkgd->getVal()) << endl ;
		cout << "1S range count: " << data->sumEntries("invariantMass","R1S") <<endl;
		cout << "2S range count: " << data->sumEntries("invariantMass","R2S") <<endl;
		cout << "1S signal yield: " << data->sumEntries("invariantMass","R1S") - integral_1S->getVal() * (nbkgd->getVal()) << endl;
		cout << "2S signal yield: " << data->sumEntries("invariantMass","R2S") - integral_2S->getVal() * (nbkgd->getVal()) << endl;
		 */
		outfile<<"Y(1S) yield  : = "<<nsig1f->getVal()<<" +/- "<<nsig1f->getError()<<endl<<endl;
		outfile<<"free parameter = "<< nfloatpars << ", mychi2 = " << mychsq << ", ndof = " << myndof  << endl << endl;

		//draw the fit lines and save plots
		data->plotOn(frame,Name("theData"),MarkerSize(0.8));
		pdf->plotOn(frame,Components("bkg"),Name("theBkg"),LineStyle(5),LineColor(kGreen));
		pdf->plotOn(frame,Components("pdf_combinedbkgd"),LineStyle(kDashed));
		if (plotLikeSign) {
			if (TRKROT) pdf->plotOn(frame,Components("Like-sign"),Name("theLikeSign"),LineStyle(9),LineColor(kMagenta));
			else  pdf->plotOn(frame,Components("Like-sign"),Name("theLikeSign"),LineStyle(9),LineColor(kRed));
		}
		pdf->plotOn(frame,Name("thePdf"));
		data->plotOn(frame,MarkerSize(0.8));
		if (plotLikeSign) {
			if (TRKROT) TrkRotData->plotOn(frame,Name("theTrkRotData"),MarkerSize(0.8),MarkerColor(kMagenta),MarkerStyle(22));
			else likesignData->plotOn(frame,Name("theLikeSignData"),MarkerSize(0.8),MarkerColor(kRed),MarkerStyle(24));
		}   


		frame->SetTitle( "" );
		frame->GetXaxis()->SetTitle("m_{#mu^{+}#mu^{-}} (GeV/c^{2})");
		frame->GetXaxis()->CenterTitle(kTRUE);
		frame->GetYaxis()->SetTitleOffset(1.3);
		if (PR_plot && RAA) frame->GetYaxis()->SetRangeUser(0,1200);
		//frame->GetYaxis()->SetLabelSize(0.05);
		frame->Draw();


		//plot parameters
		if(!plotpars) {
			paramOn_ = ""; 
			TLatex latex1;
			latex1.SetNDC();
			if (PbPb) {
				latex1.DrawLatex(0.46,1.-0.05*3,"CMS PbPb  #sqrt{s_{NN}} = 2.76 TeV");
				latex1.DrawLatex(0.5,1.-0.05*4.9,"L_{int} = 150 #mub^{-1}"); 
				switch (bin) {  
					case 0: latex1.DrawLatex(0.5,1.-0.05*6.2,"Cent. 0-100%, |y| < 2.4"); break;
					case 3: latex1.DrawLatex(0.5,1.-0.05*6.2,"Cent. 0-5%, |y| < 2.4"); break;
					case 4: latex1.DrawLatex(0.5,1.-0.05*6.2,"Cent. 5-10%, |y| < 2.4"); break;
					case 5: latex1.DrawLatex(0.5,1.-0.05*6.2,"Cent. 10-20%, |y| < 2.4"); break;
					case 6: latex1.DrawLatex(0.5,1.-0.05*6.2,"Cent. 20-30%, |y| < 2.4"); break;
					case 7: latex1.DrawLatex(0.5,1.-0.05*6.2,"Cent. 30-40%, |y| < 2.4"); break;
					case 8: latex1.DrawLatex(0.5,1.-0.05*6.2,"Cent. 40-50%, |y| < 2.4"); break;
					case 9: latex1.DrawLatex(0.5,1.-0.05*6.2,"Cent. 50-100%, |y| < 2.4"); break;
							default; break;
				}   
			}
			else {
Esempio n. 20
0
//
// Plot_Photon_Timing - plot the timing histograms for the two photons from pi0 decay
//
//                  fAna = output from eg2a DMS
//                  target = target name
//
void Plot_Photon_Timing(char *fAna="Ana.root", char *target)
{
    Int_t i, j, jj;

    char *TimingHists[3] = {"ECtimePhoton","ECpathtimePhoton","ECtime_ECl_Start_Photon"};
    TH1D *h1D[NPHOTONS][4];
    TH1D *hWOstart[NPHOTONS];
    
    // data files contain the trees
    printf("Analyzing file %s\n",fAna);
    TFile *fm = new TFile(fAna,"READ");
    TDirectory *dirKine = fm->GetDirectory("Kinematics");
    TDirectory *dirPhoton = fm->GetDirectory("PhotonID");
    
    // Canvas to plot histogram
    TCanvas *can[NPHOTONS];

    TCanvas *canWOstart = new TCanvas("canWOstart","Without the Start Time",800,0,800,400);;
    canWOstart->SetBorderMode(1);  //Bordermode (-1=down, 0 = no border, 1=up)
    canWOstart->SetBorderSize(5);
    gStyle->SetOptStat(1111);
    canWOstart->SetFillStyle(4000);
    canWOstart->Divide(2,1);
    
    for(j=0; j<NPHOTONS; j++){
        sprintf(cname,"can%i",j);
        sprintf(cname,"Photon Timing Canvas %i",j+1);
        can[j] = new TCanvas(cname,ctitle,j*50,0,800,800);
        can[j]->SetBorderMode(1);  //Bordermode (-1=down, 0 = no border, 1=up)
        can[j]->SetBorderSize(5);
        gStyle->SetOptStat(1111);
        can[j]->SetFillStyle(4000);
        can[j]->Divide(2,2);

 
        sprintf(hname,"StartTime");
        h1D[j][0] = (TH1D*)dirKine->Get(hname);
        
        can[j]->cd(1);
        gPad->SetLeftMargin(Lmar);
        gPad->SetRightMargin(Rmar);
        gPad->SetFillColor(0);
        
        h1D[j][0]->GetXaxis()->CenterTitle();
        h1D[j][0]->GetYaxis()->CenterTitle();
        h1D[j][0]->GetYaxis()->SetTitleOffset(yoff);
        h1D[j][0]->Draw();
        
        for(jj=1; jj<=3; jj++){
            sprintf(hname,"%s%i",TimingHists[jj-1],j+1);
            h1D[j][jj] = (TH1D*)dirPhoton->Get(hname);
            
            can[j]->cd(jj+1);
            gPad->SetLeftMargin(Lmar);
            gPad->SetRightMargin(Rmar);
            gPad->SetFillColor(0);
        
            h1D[j][jj]->GetXaxis()->CenterTitle();
            h1D[j][jj]->GetYaxis()->CenterTitle();
            h1D[j][jj]->GetYaxis()->SetTitleOffset(yoff);
            h1D[j][jj]->Draw();
        
        }
        sprintf(OutCan,"Plot_Photon%i_Timing_%s.gif",j+1,target);
        can[j]->Print(OutCan);
        sprintf(OutCan,"Plot_Photon%i_Timing_%s.eps",j+1,target);
        can[j]->Print(OutCan);
        
        canWOstart->cd(j+1);
        gPad->SetLeftMargin(Lmar);
        gPad->SetRightMargin(Rmar);
        gPad->SetFillColor(0);
        
        sprintf(hname,"ECtime_ECl_Photon%i",j+1);
        hWOstart[j] = (TH1D*)dirPhoton->Get(hname);
        hWOstart[j]->GetXaxis()->CenterTitle();
        hWOstart[j]->GetYaxis()->CenterTitle();
        hWOstart[j]->GetYaxis()->SetTitleOffset(yoff);
        hWOstart[j]->Draw();
        
    }
    sprintf(OutCan,"Plot_ECtime-ECl_%s.gif",target);
    canWOstart->Print(OutCan);
    sprintf(OutCan,"Plot_ECtime-ECl_%s.eps",target);
    canWOstart->Print(OutCan);
}
void draw_ToF_Calib_Sector() {

  const Int_t sectors = 8;
  ifstream fin("/phenix/plhf/zji/taxi/Run13pp510ERT/runlist.txt");
  Int_t nrun = 0;
  Int_t runnumber[1024];
  while(fin >> runnumber[nrun]) nrun++;
  fin.close();

  TGraphErrors* g_tof_runnumber[sectors];
  for(Int_t is=0; is<sectors; is++)
    g_tof_runnumber[is] = new TGraphErrors(nrun);

  for(Int_t ir=0; ir<nrun; ir++) {

    char buf[100];
    sprintf(buf, "/phenix/plhf/zji/taxi/Run13pp510ERT/8511/data/DirectPhotonPP-%d.root", runnumber[ir]);
    TFile* f = new TFile(buf);
    //TH2I* h_hitmap_tof_sector = (TH2I*)f->Get("tof_sector_raw");
    TH2I* h_hitmap_tof_sector = (TH2I*)f->Get("tof_sector");

    for(Int_t is=0; is<sectors; is++) {
      TH1D* hp_hitmap_tof_sector = (TH1D*)h_hitmap_tof_sector->ProjectionX("_px",is+1,is+1);
      hp_hitmap_tof_sector->GetXaxis()->SetRangeUser(-20.,20.);
      Double_t max = hp_hitmap_tof_sector->GetMaximum();
      Int_t bin1 = hp_hitmap_tof_sector->FindFirstBinAbove(max/2);
      Int_t bin2 = hp_hitmap_tof_sector->FindLastBinAbove(max/2);
      Double_t tof_peak = hp_hitmap_tof_sector->GetBinCenter((bin1+bin2)/2);
      Double_t fwhm = hp_hitmap_tof_sector->GetBinCenter(bin2) - hp_hitmap_tof_sector->GetBinCenter(bin1);
      //cout << "Max=" << max << " Left bin=" << bin1 << " Right bin=" << bin2 << " Tof peak=" << tof_peak << " FWHM=" << fwhm << endl;
      g_tof_runnumber[is]->SetPoint(ir, (Double_t)runnumber[ir], tof_peak);
      g_tof_runnumber[is]->SetPointError(ir, 0., fwhm/2);
      hp_hitmap_tof_sector->Delete();
    }

    h_hitmap_tof_sector->Delete();
    delete f;

  }

  TCanvas* c = new TCanvas("c", "Canvas", 1200, 2400);
  gStyle->SetOptStat(1);
  c->Divide(2,4);

  for(Int_t is=0; is<sectors; is++) {
    c->cd(is+1);
    char buf[100];
    sprintf(buf, "Sector %d", is);
    g_tof_runnumber[is]->SetTitle(buf);
    g_tof_runnumber[is]->GetXaxis()->SetTitle("Runnumber");
    g_tof_runnumber[is]->GetXaxis()->SetLimits(387000.,399000.);
    g_tof_runnumber[is]->GetYaxis()->SetTitle("ToF peak [ns]");
    g_tof_runnumber[is]->GetYaxis()->SetRangeUser(-50.,50.);
    g_tof_runnumber[is]->SetMarkerColor(1);
    g_tof_runnumber[is]->SetMarkerSize(1);
    g_tof_runnumber[is]->SetMarkerStyle(21);
    g_tof_runnumber[is]->Draw("AP");
  }

  //c->Print("ToF_NoCalib_Sector.pdf");
  c->Print("ToF_Calib_Sector.pdf");

}
void DarkSusy_mH_125_mGammaD_2000_cT_100_LHE_gammaD_M()
{
//=========Macro generated from canvas: cnv/cnv
//=========  (Sun May 24 15:18:26 2015) by ROOT version6.02/05
   TCanvas *cnv = new TCanvas("cnv", "cnv",1,1,904,904);
   gStyle->SetOptFit(1);
   gStyle->SetOptStat(0);
   gStyle->SetOptTitle(0);
   cnv->SetHighLightColor(2);
   cnv->Range(-1.526695,-0.2275,1.571513,1.5225);
   cnv->SetFillColor(0);
   cnv->SetBorderMode(0);
   cnv->SetBorderSize(2);
   cnv->SetLogx();
   cnv->SetTickx(1);
   cnv->SetTicky(1);
   cnv->SetLeftMargin(0.17);
   cnv->SetRightMargin(0.03);
   cnv->SetTopMargin(0.07);
   cnv->SetBottomMargin(0.13);
   cnv->SetFrameFillStyle(0);
   cnv->SetFrameBorderMode(0);
   cnv->SetFrameFillStyle(0);
   cnv->SetFrameBorderMode(0);
   
   TH1F *h_gammaD_1_M_dummy86 = new TH1F("h_gammaD_1_M_dummy86","h_gammaD_1_M_dummy",303,0.1,30.1);
   h_gammaD_1_M_dummy86->SetMaximum(1.4);
   h_gammaD_1_M_dummy86->SetLineStyle(0);
   h_gammaD_1_M_dummy86->SetMarkerStyle(20);
   h_gammaD_1_M_dummy86->GetXaxis()->SetTitle("Mass of #gamma_{D} [GeV]");
   h_gammaD_1_M_dummy86->GetXaxis()->SetLabelFont(42);
   h_gammaD_1_M_dummy86->GetXaxis()->SetLabelOffset(0.007);
   h_gammaD_1_M_dummy86->GetXaxis()->SetTitleSize(0.06);
   h_gammaD_1_M_dummy86->GetXaxis()->SetTitleOffset(0.95);
   h_gammaD_1_M_dummy86->GetXaxis()->SetTitleFont(42);
   h_gammaD_1_M_dummy86->GetYaxis()->SetTitle("Fraction of events / 0.1 GeV");
   h_gammaD_1_M_dummy86->GetYaxis()->SetLabelFont(42);
   h_gammaD_1_M_dummy86->GetYaxis()->SetLabelOffset(0.007);
   h_gammaD_1_M_dummy86->GetYaxis()->SetTitleSize(0.06);
   h_gammaD_1_M_dummy86->GetYaxis()->SetTitleOffset(1.35);
   h_gammaD_1_M_dummy86->GetYaxis()->SetTitleFont(42);
   h_gammaD_1_M_dummy86->GetZaxis()->SetLabelFont(42);
   h_gammaD_1_M_dummy86->GetZaxis()->SetLabelOffset(0.007);
   h_gammaD_1_M_dummy86->GetZaxis()->SetTitleSize(0.06);
   h_gammaD_1_M_dummy86->GetZaxis()->SetTitleFont(42);
   h_gammaD_1_M_dummy86->Draw("");
   
   TH1F *h_gammaD_1_M87 = new TH1F("h_gammaD_1_M87","h_gammaD_1_M",303,0.1,30.1);
   h_gammaD_1_M87->SetBinContent(201,1);
   h_gammaD_1_M87->SetBinError(201,0.002500016);
   h_gammaD_1_M87->SetEntries(159998);
   h_gammaD_1_M87->SetDirectory(0);

   Int_t ci;      // for color index setting
   TColor *color; // for color definition with alpha
   ci = TColor::GetColor("#0000ff");
   h_gammaD_1_M87->SetLineColor(ci);
   h_gammaD_1_M87->SetLineWidth(2);
   h_gammaD_1_M87->SetMarkerStyle(20);
   h_gammaD_1_M87->GetXaxis()->SetLabelFont(42);
   h_gammaD_1_M87->GetXaxis()->SetLabelOffset(0.007);
   h_gammaD_1_M87->GetXaxis()->SetTitleSize(0.06);
   h_gammaD_1_M87->GetXaxis()->SetTitleOffset(0.95);
   h_gammaD_1_M87->GetXaxis()->SetTitleFont(42);
   h_gammaD_1_M87->GetYaxis()->SetLabelFont(42);
   h_gammaD_1_M87->GetYaxis()->SetLabelOffset(0.007);
   h_gammaD_1_M87->GetYaxis()->SetTitleSize(0.06);
   h_gammaD_1_M87->GetYaxis()->SetTitleOffset(1.3);
   h_gammaD_1_M87->GetYaxis()->SetTitleFont(42);
   h_gammaD_1_M87->GetZaxis()->SetLabelFont(42);
   h_gammaD_1_M87->GetZaxis()->SetLabelOffset(0.007);
   h_gammaD_1_M87->GetZaxis()->SetTitleSize(0.06);
   h_gammaD_1_M87->GetZaxis()->SetTitleFont(42);
   h_gammaD_1_M87->Draw("SAMEHIST");
   
   TLegend *leg = new TLegend(0.4566667,0.82,0.7822222,0.9066667,NULL,"brNDC");
   leg->SetBorderSize(0);
   leg->SetTextSize(0.02777778);
   leg->SetLineColor(1);
   leg->SetLineStyle(1);
   leg->SetLineWidth(1);
   leg->SetFillColor(0);
   leg->SetFillStyle(0);
   TLegendEntry *entry=leg->AddEntry("NULL","#splitline{pp #rightarrow h #rightarrow 2n_{1} #rightarrow 2n_{D} + 2 #gamma_{D} #rightarrow 2n_{D} + 4#mu}{#splitline{m_{h} = 125 GeV, m_{n_{1}} = 50 GeV, m_{n_{D}} = 1 GeV}{m_{#gamma_{D}} = 20 GeV, c#tau_{#gamma_{D}} = 100 mm}}","h");
   entry->SetLineColor(1);
   entry->SetLineStyle(1);
   entry->SetLineWidth(1);
   entry->SetMarkerColor(1);
   entry->SetMarkerStyle(21);
   entry->SetMarkerSize(1);
   entry->SetTextFont(42);
   leg->Draw();
   
   leg = new TLegend(0.17,0.935,0.97,1,NULL,"brNDC");
   leg->SetBorderSize(0);
   leg->SetTextAlign(22);
   leg->SetTextSize(0.045);
   leg->SetLineColor(1);
   leg->SetLineStyle(1);
   leg->SetLineWidth(1);
   leg->SetFillColor(0);
   leg->SetFillStyle(0);
   entry=leg->AddEntry("NULL","CMS Simulation (LHE) 14 TeV","h");
   entry->SetLineColor(1);
   entry->SetLineStyle(1);
   entry->SetLineWidth(1);
   entry->SetMarkerColor(1);
   entry->SetMarkerStyle(21);
   entry->SetMarkerSize(1);
   entry->SetTextFont(42);
   leg->Draw();
   cnv->Modified();
   cnv->cd();
   cnv->SetSelected(cnv);
}
void compareSync(TString myGroup,TString myPath,TString myRootFile, TString myTree, TString group, TString groupPath, TString groupRootFile, TString groupTree,TString mySel="1",TString groupSel="1"){

//   TFile Fmine("/afs/cern.ch/user/b/benitezj/public/HTTSync/July28/eTau2012_VBFSync.root");
//   TTree*Tmine=(TTree*)Fmine.Get("TauCheck");
//   TFile Fother("/afs/cern.ch/user/s/swanson/public/Sync52XEleTau/eleTauPreselection.root");
//   TTree*Tother=(TTree*)Fother.Get("eventTree");

  TFile Fmine(myPath+"/"+myRootFile+".root");
  TTree*Tmine=(TTree*)Fmine.Get(myTree.Data());
  TFile Fother(groupPath+"/"+groupRootFile+".root");
  TTree*Tother=(TTree*)Fother.Get(groupTree.Data());

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

  cout<<"Mine: "<<Fmine.GetName()<<endl;
  cout<<"Other: "<<Fother.GetName()<<endl;
  TCanvas C;

  TString filename=myGroup+"_"+myRootFile+"_"+group+"_"+groupRootFile+"_diff.pdf";
  C.Print(filename+"[");  


  //inclusive
  TString selection="1";
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"run",140,190000,204000,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"npu",50,0,50,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"npv",50,0,50,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"pt_1",100,0,200,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"eta_1",60,-3,3,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,"inclusive",Tmine,Tother,"iso_1",60,-.02,0.12,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"pt_2",100,0,200,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"eta_2",60,-3,3,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"m_1",40,0,2,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"m_2",40,0,2,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"mt_1",50,0,100,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"mt_2",50,0,100,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"decayModeFinding_1",10,0,2,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"decayModeFinding_2",10,0,2,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"decayModeFindingNewDMs_1",10,0,2,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"decayModeFindingNewDMs_2",10,0,2,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"byCombinedIsolationDeltaBetaCorrRaw3Hits_1",200,0,10,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"byCombinedIsolationDeltaBetaCorrRaw3Hits_2",200,0,10,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"againstElectronTightMVA5_1",10,0,2,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"againstElectronTightMVA5_2",10,0,2,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"againstMuonTight3_1",10,0,2,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"againstMuonTight3_2",10,0,2,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"met",20,0,200,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"metphi",30,-3.5,3.5,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"mvamet",50,0,100,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"mvametphi",35,-3.5,3.5,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"mvacov00",50,0,2500,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"mvacov01",50,0,2500,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"mvacov10",50,0,2500,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"mvacov11",50,0,2500,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,"inclusive",Tmine,Tother,"uPerp",200,-100,100,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,"inclusive",Tmine,Tother,"uParl",200,-100,100,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,"inclusive",Tmine,Tother,"metParl",200,-100,100,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,"inclusive",Tmine,Tother,"metPerp",200,-100,100,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,"inclusive",Tmine,Tother,"metSigmaParl",200,-100,100,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,"inclusive",Tmine,Tother,"metSigmaPerp",200,-100,100,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,"inclusive",Tmine,Tother,"metPullParl",200,-100,100,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,"inclusive",Tmine,Tother,"metPullPerp",200,-100,100,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,"inclusive",Tmine,Tother,"m_sv",60,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"extraelec_veto",2,0,2,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,"inclusive",Tmine,Tother,"extramuon_veto",2,0,2,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);

  //drawHistos(&C,filename,"inclusive",Tmine,Tother,"puweight",25,-.1,0.9,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,"inclusive",Tmine,Tother,"effweight",80,.7,1.3,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,"inclusive",Tmine,Tother,"eventweight",50,0,5,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);

  ///Jets
  selection="(njets>=1)";
  drawHistos(&C,filename,selection,Tmine,Tother,"jpt_1",100,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,selection,Tmine,Tother,"jeta_1",100,-5,5,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //
  selection="(njets>=2)";
  drawHistos(&C,filename,selection,Tmine,Tother,"jpt_2",100,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,selection,Tmine,Tother,"jeta_2",100,-5,5,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,selection,Tmine,Tother,"mjj",100,0,3000,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,selection,Tmine,Tother,"jdeta",100,0,10,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,selection,Tmine,Tother,"visjeteta",100,0,10,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,selection,Tmine,Tother,"ptvis",100,0,500,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,selection,Tmine,Tother,"njetingap",4,-0.5,3.5,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,selection,Tmine,Tother,"jdphi",100,0,3.5,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,selection,Tmine,Tother,"dijetpt",100,0,500,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,selection,Tmine,Tother,"hdijetphi",100,0,3.5,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  //drawHistos(&C,filename,selection,Tmine,Tother,"mva",40,-1,1.001,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);


  /////b-jets
  selection="(nbtag>=1)";
  drawHistos(&C,filename,selection,Tmine,Tother,"bpt_1",100,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  drawHistos(&C,filename,selection,Tmine,Tother,"beta_1",100,-5,5,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);

  /*
  ///////////////////categories
  TString vbfcut="(njets>=2&&njetingap==0&&mjj>500&&abs(jdeta)>3.5)";
  TString notvbfcut=TString("(!")+vbfcut+")";
  TString boostcut="(njets>=1&&nbtag==0)";
  TString notboostcut=TString("(!")+boostcut+")";
  TString bjetcut="(njets<2&&nbtag>=1)";
  TString notbjetcut=TString("(!")+bjetcut+")";
  TString SMcut[7];
  SMcut[0]="(njets==0&&nbtag==0)";
  SMcut[2]=notvbfcut+"*"+boostcut;
  SMcut[4]=vbfcut;
  SMcut[5]=notvbfcut+"*"+notboostcut+"*"+bjetcut;
  
  selection=SMcut[0];
  drawHistos(&C,filename,TString("0-jet : ")+selection,Tmine,Tother,"m_sv",30,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  selection=SMcut[2];
  drawHistos(&C,filename,"Boosted",Tmine,Tother,"m_sv",30,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  selection=SMcut[4];
  drawHistos(&C,filename,TString("VBF : ")+selection,Tmine,Tother,"m_sv",30,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  selection=SMcut[5];
  drawHistos(&C,filename,"B-jet",Tmine,Tother,"m_sv",30,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);


  //with puweight
  TString weight="(puweight)";
  selection=SMcut[0]+"*"+weight;
  drawHistos(&C,filename,TString("0-jet ")+weight,Tmine,Tother,"m_sv",30,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  selection=SMcut[2]+"*"+weight;
  drawHistos(&C,filename,TString("Boosted ")+weight,Tmine,Tother,"m_sv",30,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  selection=SMcut[4]+"*"+weight;
  drawHistos(&C,filename,TString("VBF ")+weight,Tmine,Tother,"m_sv",30,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  selection=SMcut[5]+"*"+weight;
  drawHistos(&C,filename,TString("B-jet ")+weight,Tmine,Tother,"m_sv",30,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);

  //with trigger weight
  TString weight="(puweight*effweight)";
  selection=SMcut[0]+"*"+weight;
  drawHistos(&C,filename,TString("0-jet ")+weight,Tmine,Tother,"m_sv",30,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  selection=SMcut[2]+"*"+weight;
  drawHistos(&C,filename,TString("Boosted ")+weight,Tmine,Tother,"m_sv",30,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  selection=SMcut[4]+"*"+weight;
  drawHistos(&C,filename,TString("VBF ")+weight,Tmine,Tother,"m_sv",30,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  selection=SMcut[5]+"*"+weight;
  drawHistos(&C,filename,TString("B-jet ")+weight,Tmine,Tother,"m_sv",30,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);

  //with trigger weight and mT cut
  TString weight="(puweight*effweight)*(mt_1<20.)";
  selection=SMcut[0]+"*"+weight;
  drawHistos(&C,filename,TString("0-jet ")+weight,Tmine,Tother,"m_sv",30,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  selection=SMcut[2]+"*"+weight;
  drawHistos(&C,filename,TString("Boosted ")+weight,Tmine,Tother,"m_sv",30,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  selection=SMcut[4]+"*"+weight;
  drawHistos(&C,filename,TString("VBF ")+weight,Tmine,Tother,"m_sv",30,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  selection=SMcut[5]+"*"+weight;
  drawHistos(&C,filename,TString("B-jet ")+weight,Tmine,Tother,"m_sv",30,0,300,selection,myGroup,myRootFile,group,groupRootFile,mySel,groupSel);
  */

  C.Print(filename+"]");
  gROOT->ProcessLine(".q");
}
Esempio n. 24
0
void METopt()
{
//=========Macro generated from canvas: METopt/METopt
//=========  (Mon Nov 23 12:45:00 2015) by ROOT version6.02/05
   TCanvas *METopt = new TCanvas("METopt", "METopt",140,162,700,700);
   METopt->Range(-0.375,-6.432596,3.375,0.05191559);
   METopt->SetFillColor(0);
   METopt->SetBorderMode(0);
   METopt->SetBorderSize(2);
   METopt->SetLogy();
   METopt->SetFrameBorderMode(0);
   METopt->SetFrameBorderMode(0);
   
   THStack *METopt = new THStack();
   METopt->SetName("METopt");
   METopt->SetTitle("METopt");
   
   TH1F *METopt_stack_8 = new TH1F("METopt_stack_8","METopt",15,0,3);
   METopt_stack_8->SetMinimum(1.643823e-06);
   METopt_stack_8->SetMaximum(0.2532004);
   METopt_stack_8->SetDirectory(0);
   METopt_stack_8->SetStats(0);

   Int_t ci;      // for color index setting
   TColor *color; // for color definition with alpha
   ci = TColor::GetColor("#000099");
   METopt_stack_8->SetLineColor(ci);
   METopt_stack_8->GetXaxis()->SetTitle("METopt");
   METopt_stack_8->GetXaxis()->SetLabelFont(42);
   METopt_stack_8->GetXaxis()->SetLabelSize(0.035);
   METopt_stack_8->GetXaxis()->SetTitleSize(0.035);
   METopt_stack_8->GetXaxis()->SetTitleFont(42);
   METopt_stack_8->GetYaxis()->SetTitle("Events/pb");
   METopt_stack_8->GetYaxis()->SetLabelFont(42);
   METopt_stack_8->GetYaxis()->SetLabelSize(0.035);
   METopt_stack_8->GetYaxis()->SetTitleSize(0.035);
   METopt_stack_8->GetYaxis()->SetTitleFont(42);
   METopt_stack_8->GetZaxis()->SetLabelFont(42);
   METopt_stack_8->GetZaxis()->SetLabelSize(0.035);
   METopt_stack_8->GetZaxis()->SetTitleSize(0.035);
   METopt_stack_8->GetZaxis()->SetTitleFont(42);
   METopt->SetHistogram(METopt_stack_8);
   
   
   TH1D *METopt36 = new TH1D("METopt36","MET/p_{T}^{lead jet}",15,0,3);
   METopt36->SetBinContent(1,0.00068069);
   METopt36->SetBinContent(2,0.00952966);
   METopt36->SetBinContent(3,0.06912243);
   METopt36->SetBinContent(4,0.01104153);
   METopt36->SetBinContent(5,0.01663754);
   METopt36->SetBinContent(6,0.02495631);
   METopt36->SetBinError(1,0.00068069);
   METopt36->SetBinError(2,0.002546909);
   METopt36->SetBinError(3,0.02217717);
   METopt36->SetBinError(4,0.00842943);
   METopt36->SetBinError(5,0.01176452);
   METopt36->SetBinError(6,0.01440853);
   METopt36->SetEntries(48);

   ci = TColor::GetColor("#00cc00");
   METopt36->SetFillColor(ci);

   ci = TColor::GetColor("#00cc00");
   METopt36->SetLineColor(ci);

   ci = TColor::GetColor("#00cc00");
   METopt36->SetMarkerColor(ci);
   METopt36->SetMarkerStyle(22);
   METopt36->GetXaxis()->SetTitle("METopt");
   METopt36->GetXaxis()->SetLabelFont(42);
   METopt36->GetXaxis()->SetLabelSize(0.035);
   METopt36->GetXaxis()->SetTitleSize(0.035);
   METopt36->GetXaxis()->SetTitleFont(42);
   METopt36->GetYaxis()->SetTitle("Events/pb");
   METopt36->GetYaxis()->SetLabelFont(42);
   METopt36->GetYaxis()->SetLabelSize(0.035);
   METopt36->GetYaxis()->SetTitleSize(0.035);
   METopt36->GetYaxis()->SetTitleFont(42);
   METopt36->GetZaxis()->SetLabelFont(42);
   METopt36->GetZaxis()->SetLabelSize(0.035);
   METopt36->GetZaxis()->SetTitleSize(0.035);
   METopt36->GetZaxis()->SetTitleFont(42);
   METopt->Add(METopt,"");
   
   TH1D *METopt37 = new TH1D("METopt37","MET/p_{T}^{lead jet}",15,0,3);
   METopt37->SetBinContent(1,1.392893e-05);
   METopt37->SetBinContent(2,0.001351916);
   METopt37->SetBinContent(3,0.009267276);
   METopt37->SetBinContent(4,0.04333138);
   METopt37->SetBinContent(5,0.1226104);
   METopt37->SetBinContent(6,0.1345744);
   METopt37->SetBinContent(7,0.1072757);
   METopt37->SetBinContent(8,0.0786938);
   METopt37->SetBinContent(9,0.04683283);
   METopt37->SetBinContent(10,0.0271465);
   METopt37->SetBinContent(11,0.0117321);
   METopt37->SetBinContent(12,0.007680578);
   METopt37->SetBinContent(13,0.003504385);
   METopt37->SetBinContent(14,0.002544782);
   METopt37->SetBinContent(15,0.001871985);
   METopt37->SetBinContent(16,0.002029317);
   METopt37->SetBinError(1,1.392893e-05);
   METopt37->SetBinError(2,0.0001372687);
   METopt37->SetBinError(3,0.0003814526);
   METopt37->SetBinError(4,0.001364947);
   METopt37->SetBinError(5,0.003448717);
   METopt37->SetBinError(6,0.004099139);
   METopt37->SetBinError(7,0.004180275);
   METopt37->SetBinError(8,0.004584045);
   METopt37->SetBinError(9,0.003621192);
   METopt37->SetBinError(10,0.002726748);
   METopt37->SetBinError(11,0.001513075);
   METopt37->SetBinError(12,0.001337888);
   METopt37->SetBinError(13,0.001122201);
   METopt37->SetBinError(14,0.001068918);
   METopt37->SetBinError(15,0.001029262);
   METopt37->SetBinError(16,0.001037471);
   METopt37->SetEntries(12325);

   ci = TColor::GetColor("#00ffff");
   METopt37->SetFillColor(ci);

   ci = TColor::GetColor("#00ffff");
   METopt37->SetLineColor(ci);

   ci = TColor::GetColor("#00ffff");
   METopt37->SetMarkerColor(ci);
   METopt37->SetMarkerStyle(20);
   METopt37->GetXaxis()->SetTitle("METopt");
   METopt37->GetXaxis()->SetLabelFont(42);
   METopt37->GetXaxis()->SetLabelSize(0.035);
   METopt37->GetXaxis()->SetTitleSize(0.035);
   METopt37->GetXaxis()->SetTitleFont(42);
   METopt37->GetYaxis()->SetTitle("Events/pb");
   METopt37->GetYaxis()->SetLabelFont(42);
   METopt37->GetYaxis()->SetLabelSize(0.035);
   METopt37->GetYaxis()->SetTitleSize(0.035);
   METopt37->GetYaxis()->SetTitleFont(42);
   METopt37->GetZaxis()->SetLabelFont(42);
   METopt37->GetZaxis()->SetLabelSize(0.035);
   METopt37->GetZaxis()->SetTitleSize(0.035);
   METopt37->GetZaxis()->SetTitleFont(42);
   METopt->Add(METopt,"");
   
   TH1D *METopt38 = new TH1D("METopt38","MET/p_{T}^{lead jet}",15,0,3);
   METopt38->SetBinContent(1,5.851509e-06);
   METopt38->SetBinContent(2,0.0002960863);
   METopt38->SetBinContent(3,0.002055587);
   METopt38->SetBinContent(4,0.009485694);
   METopt38->SetBinContent(5,0.02637833);
   METopt38->SetBinContent(6,0.03542185);
   METopt38->SetBinContent(7,0.02902985);
   METopt38->SetBinContent(8,0.01931192);
   METopt38->SetBinContent(9,0.01045294);
   METopt38->SetBinContent(10,0.006260894);
   METopt38->SetBinContent(11,0.004006631);
   METopt38->SetBinContent(12,0.001811275);
   METopt38->SetBinContent(13,0.001055017);
   METopt38->SetBinContent(14,0.0003970447);
   METopt38->SetBinContent(15,0.0002648587);
   METopt38->SetBinContent(16,0.0002425362);
   METopt38->SetBinError(1,2.616874e-06);
   METopt38->SetBinError(2,1.861479e-05);
   METopt38->SetBinError(3,5.431574e-05);
   METopt38->SetBinError(4,0.0002770452);
   METopt38->SetBinError(5,0.000680549);
   METopt38->SetBinError(6,0.0009013724);
   METopt38->SetBinError(7,0.0009115706);
   METopt38->SetBinError(8,0.0007784417);
   METopt38->SetBinError(9,0.0005631055);
   METopt38->SetBinError(10,0.000447395);
   METopt38->SetBinError(11,0.0003988073);
   METopt38->SetBinError(12,0.0002844883);
   METopt38->SetBinError(13,0.0002045993);
   METopt38->SetBinError(14,0.0001303943);
   METopt38->SetBinError(15,8.467851e-05);
   METopt38->SetBinError(16,0.0001139839);
   METopt38->SetEntries(19290);

   ci = TColor::GetColor("#ffcc00");
   METopt38->SetFillColor(ci);

   ci = TColor::GetColor("#ffcc00");
   METopt38->SetLineColor(ci);

   ci = TColor::GetColor("#ffcc00");
   METopt38->SetMarkerColor(ci);
   METopt38->SetMarkerStyle(21);
   METopt38->GetXaxis()->SetTitle("METopt");
   METopt38->GetXaxis()->SetLabelFont(42);
   METopt38->GetXaxis()->SetLabelSize(0.035);
   METopt38->GetXaxis()->SetTitleSize(0.035);
   METopt38->GetXaxis()->SetTitleFont(42);
   METopt38->GetYaxis()->SetTitle("Events/pb");
   METopt38->GetYaxis()->SetLabelFont(42);
   METopt38->GetYaxis()->SetLabelSize(0.035);
   METopt38->GetYaxis()->SetTitleSize(0.035);
   METopt38->GetYaxis()->SetTitleFont(42);
   METopt38->GetZaxis()->SetLabelFont(42);
   METopt38->GetZaxis()->SetLabelSize(0.035);
   METopt38->GetZaxis()->SetTitleSize(0.035);
   METopt38->GetZaxis()->SetTitleFont(42);
   METopt->Add(METopt,"");
   
   TH1D *METopt39 = new TH1D("METopt39","MET/p_{T}^{lead jet}",15,0,3);
   METopt39->SetBinContent(2,1.542458e-05);
   METopt39->SetBinContent(3,9.254746e-05);
   METopt39->SetBinContent(4,0.0009717483);
   METopt39->SetBinContent(5,0.003146613);
   METopt39->SetBinContent(6,0.003840719);
   METopt39->SetBinContent(7,0.002637602);
   METopt39->SetBinContent(8,0.001758402);
   METopt39->SetBinContent(9,0.001326514);
   METopt39->SetBinContent(10,0.0007866534);
   METopt39->SetBinContent(11,0.0004781619);
   METopt39->SetBinContent(12,0.0003084915);
   METopt39->SetBinContent(13,0.0002159441);
   METopt39->SetBinContent(14,0.0001233966);
   METopt39->SetBinContent(15,0.0001233966);
   METopt39->SetBinContent(16,0.000107972);
   METopt39->SetBinError(2,1.542458e-05);
   METopt39->SetBinError(3,3.778234e-05);
   METopt39->SetBinError(4,0.0001224288);
   METopt39->SetBinError(5,0.000220307);
   METopt39->SetBinError(6,0.0002433957);
   METopt39->SetBinError(7,0.0002017025);
   METopt39->SetBinError(8,0.0001646894);
   METopt39->SetBinError(9,0.0001430416);
   METopt39->SetBinError(10,0.0001101535);
   METopt39->SetBinError(11,8.58804e-05);
   METopt39->SetBinError(12,6.89808e-05);
   METopt39->SetBinError(13,5.771348e-05);
   METopt39->SetBinError(14,4.362729e-05);
   METopt39->SetBinError(15,4.362729e-05);
   METopt39->SetBinError(16,4.080959e-05);
   METopt39->SetEntries(1033);

   ci = TColor::GetColor("#ff0000");
   METopt39->SetFillColor(ci);

   ci = TColor::GetColor("#ff0000");
   METopt39->SetLineColor(ci);

   ci = TColor::GetColor("#ff0000");
   METopt39->SetMarkerColor(ci);
   METopt39->SetMarkerStyle(20);
   METopt39->GetXaxis()->SetTitle("METopt");
   METopt39->GetXaxis()->SetLabelFont(42);
   METopt39->GetXaxis()->SetLabelSize(0.035);
   METopt39->GetXaxis()->SetTitleSize(0.035);
   METopt39->GetXaxis()->SetTitleFont(42);
   METopt39->GetYaxis()->SetTitle("Events/pb");
   METopt39->GetYaxis()->SetLabelFont(42);
   METopt39->GetYaxis()->SetLabelSize(0.035);
   METopt39->GetYaxis()->SetTitleSize(0.035);
   METopt39->GetYaxis()->SetTitleFont(42);
   METopt39->GetZaxis()->SetLabelFont(42);
   METopt39->GetZaxis()->SetLabelSize(0.035);
   METopt39->GetZaxis()->SetTitleSize(0.035);
   METopt39->GetZaxis()->SetTitleFont(42);
   METopt->Add(METopt,"");
   
   TH1D *METopt40 = new TH1D("METopt40","MET/p_{T}^{lead jet}",15,0,3);
   METopt40->SetBinContent(4,1.677165e-05);
   METopt40->SetBinError(4,1.677165e-05);
   METopt40->SetEntries(1);

   ci = TColor::GetColor("#0000ff");
   METopt40->SetFillColor(ci);

   ci = TColor::GetColor("#0000ff");
   METopt40->SetLineColor(ci);

   ci = TColor::GetColor("#0000ff");
   METopt40->SetMarkerColor(ci);
   METopt40->SetMarkerStyle(21);
   METopt40->GetXaxis()->SetTitle("METopt");
   METopt40->GetXaxis()->SetLabelFont(42);
   METopt40->GetXaxis()->SetLabelSize(0.035);
   METopt40->GetXaxis()->SetTitleSize(0.035);
   METopt40->GetXaxis()->SetTitleFont(42);
   METopt40->GetYaxis()->SetTitle("Events/pb");
   METopt40->GetYaxis()->SetLabelFont(42);
   METopt40->GetYaxis()->SetLabelSize(0.035);
   METopt40->GetYaxis()->SetTitleSize(0.035);
   METopt40->GetYaxis()->SetTitleFont(42);
   METopt40->GetZaxis()->SetLabelFont(42);
   METopt40->GetZaxis()->SetLabelSize(0.035);
   METopt40->GetZaxis()->SetTitleSize(0.035);
   METopt40->GetZaxis()->SetTitleFont(42);
   METopt->Add(METopt,"");
   METopt->Draw("nostack");
   
   TPaveText *pt = new TPaveText(0.398046,0.9342857,0.601954,0.995,"blNDC");
   pt->SetName("title");
   pt->SetBorderSize(0);
   pt->SetFillColor(0);
   pt->SetFillStyle(0);
   pt->SetTextFont(42);
   TText *AText = pt->AddText("METopt");
   pt->Draw();
   
   TLegend *leg = new TLegend(0.54023,0.639881,0.938218,0.924107,NULL,"brNDC");
   leg->SetBorderSize(1);
   leg->SetTextSize(0.034965);
   leg->SetLineColor(1);
   leg->SetLineStyle(1);
   leg->SetLineWidth(1);
   leg->SetFillColor(0);
   leg->SetFillStyle(1001);
   TLegendEntry *entry=leg->AddEntry("METopt","METopt_QCD","lp");

   ci = TColor::GetColor("#00cc00");
   entry->SetLineColor(ci);
   entry->SetLineStyle(1);
   entry->SetLineWidth(1);

   ci = TColor::GetColor("#00cc00");
   entry->SetMarkerColor(ci);
   entry->SetMarkerStyle(22);
   entry->SetMarkerSize(1);
   entry->SetTextFont(42);
   entry=leg->AddEntry("METopt","METopt_WJetsToLNu","lp");

   ci = TColor::GetColor("#00ffff");
   entry->SetLineColor(ci);
   entry->SetLineStyle(1);
   entry->SetLineWidth(1);

   ci = TColor::GetColor("#00ffff");
   entry->SetMarkerColor(ci);
   entry->SetMarkerStyle(20);
   entry->SetMarkerSize(1);
   entry->SetTextFont(42);
   entry=leg->AddEntry("METopt","METopt_ZJetsToNuNu","lp");

   ci = TColor::GetColor("#ffcc00");
   entry->SetLineColor(ci);
   entry->SetLineStyle(1);
   entry->SetLineWidth(1);

   ci = TColor::GetColor("#ffcc00");
   entry->SetMarkerColor(ci);
   entry->SetMarkerStyle(21);
   entry->SetMarkerSize(1);
   entry->SetTextFont(42);
   entry=leg->AddEntry("METopt","METopt_signal","lp");

   ci = TColor::GetColor("#ff0000");
   entry->SetLineColor(ci);
   entry->SetLineStyle(1);
   entry->SetLineWidth(1);

   ci = TColor::GetColor("#ff0000");
   entry->SetMarkerColor(ci);
   entry->SetMarkerStyle(20);
   entry->SetMarkerSize(1);
   entry->SetTextFont(42);
   entry=leg->AddEntry("METopt","METopt_ttbar","lp");

   ci = TColor::GetColor("#0000ff");
   entry->SetLineColor(ci);
   entry->SetLineStyle(1);
   entry->SetLineWidth(1);

   ci = TColor::GetColor("#0000ff");
   entry->SetMarkerColor(ci);
   entry->SetMarkerStyle(21);
   entry->SetMarkerSize(1);
   entry->SetTextFont(42);
   leg->Draw();
   METopt->Modified();
   METopt->cd();
   METopt->SetSelected(METopt);
}
Esempio n. 25
0
int main(int argc, char* argv[]){
  setstyle();

  char inputFileName[400];
  char outputFileName[400];
  
  if ( argc < 2 ){
    cout << "Error at Input: please specify an input .root file";
    cout << " and an (optional) output filename" << endl;
    cout << "Example:   ./Calibrate_xADC input_file.root" << endl;
    cout << "Example:   ./Calibrate_xADC input_file.root -o output_file.root" << endl;
    return 1;
  }

  sscanf(argv[1],"%s", inputFileName);
  bool user_output = false;
  for (int i=0;i<argc;i++){
    if (strncmp(argv[i],"-o",2)==0){
      sscanf(argv[i+1],"%s", outputFileName);
      user_output = true;
    }
  }

  string output_name;
  if(!user_output){
    string input_name = string(inputFileName);
    // strip path from input name
    while(input_name.find("/") != string::npos)
      input_name.erase(input_name.begin(),
		       input_name.begin()+
		       input_name.find("/")+1);
    if(input_name.find(".root") != string::npos)
      input_name.erase(input_name.find(".root"),5);
    output_name = input_name+"_xADCcalib.root";
    sprintf(outputFileName,"%s.root",inputFileName);
  } else {
    output_name = string(outputFileName);
  }

  TChain* tree = new TChain("xADC_fit");
  tree->AddFile(inputFileName);

  xADCfitBase* base = new xADCfitBase(tree);

  int N = tree->GetEntries();
  if(N == 0) return 0;

  map<pair<int,int>, int> MMFE8VMM_to_index;
  
  vector<int>             vMMFE8;  // board ID
  vector<int>             vVMM;    // VMM number
  vector<vector<double> > vmeanQ;
  vector<vector<double> > vmeanQerr;
  vector<vector<double> > vDAC;

  int MMFE8;
  int VMM;

  for(int i = 0; i < N; i++){
    base->GetEntry(i);

    MMFE8 = base->MMFE8;
    VMM   = base->VMM;

    // add a new MMFE8+VMM combination 
    if(MMFE8VMM_to_index.count(pair<int,int>(MMFE8,VMM)) == 0){
      int ind = int(vMMFE8.size());
      MMFE8VMM_to_index[pair<int,int>(MMFE8,VMM)] = ind;
      vMMFE8.push_back(MMFE8);
      vVMM.push_back(VMM);
      vmeanQ.push_back(vector<double>());
      vmeanQerr.push_back(vector<double>());
      vDAC.push_back(vector<double>());
    }

    // MMFE8+VMM index
    int index = MMFE8VMM_to_index[pair<int,int>(MMFE8,VMM)];

    vDAC[index].push_back(base->DAC);
    vmeanQ[index].push_back(base->meanQ);
    vmeanQerr[index].push_back(base->meanQerr);
  }

  int Nindex = vMMFE8.size();

  vector<TGraphErrors*> vgraph;
  vector<double> vsigma;
  vector<double> vQmin;
  for(int index = 0; index < Nindex; index++){
    int Npoint = vDAC[index].size();
    double DAC[Npoint];
    double meanQ[Npoint];
    double meanQerr[Npoint];
    double sigma = 0.;

    double Qmin = -1.;
    for(int p = 0; p < Npoint; p++){
      DAC[p] = vDAC[index][p];
      meanQ[p] = vmeanQ[index][p];
      meanQerr[p] = vmeanQerr[index][p];
      // if(meanQerr[p] > sigma)
      // 	sigma = meanQerr[p];
      sigma += meanQerr[p]/double(Npoint);

      if(meanQ[p] < Qmin || Qmin < 0.)
	Qmin = meanQ[p];
    }

    vgraph.push_back(new TGraphErrors(Npoint, DAC, meanQ, 0, meanQerr));
    vsigma.push_back(sigma);
    vQmin.push_back(Qmin);
  }

  TFile* fout = new TFile(output_name.c_str(), "RECREATE");

  // write xADCBase tree to outputfile
  //TChain* base_tree = new TChain("xADC_data");
  //base_tree->AddFile(inputFileName);
  //TTree* new_base_tree = base_tree->CloneTree();
  //fout->cd();
  //new_base_tree->Write();

  // add plots of charge v DAC for each
  // MMFE8+VMM combo to output file
  fout->mkdir("xADCfit_plots");
  fout->cd("xADCfit_plots");
  for(int i = 0; i < Nindex; i++){
    char stitle[50];
    sprintf(stitle, "Board #%d, VMM #%d", vMMFE8[i], vVMM[i]);
    char scan[50];
    sprintf(scan, "c_xADXfit_Board%d_VMM%d", vMMFE8[i], vVMM[i]);
    TCanvas* can = Plot_Graph(scan, vgraph[i], "Test Pulse DAC", "Input Charge (fC)", stitle);
    can->Write();
    delete can;
  }
  fout->cd("");

  // write xADCfitBase tree to outputfile
  TTree* newtree = tree->CloneTree();
  fout->cd();
  newtree->Write();
  delete newtree;
  delete base;
  delete tree;

  // Output xADC calib tree
  double calib_MMFE8;
  double calib_VMM;
  double calib_sigma;
  double calib_c0;
  double calib_A2;
  double calib_t02;
  double calib_d21;
  double calib_chi2;
  double calib_prob;
  
  TTree* calib_tree = new TTree("xADC_calib", "xADC_calib");
  calib_tree->Branch("MMFE8", &calib_MMFE8);
  calib_tree->Branch("VMM", &calib_VMM);
  calib_tree->Branch("sigma", &calib_sigma);
  calib_tree->Branch("c0", &calib_c0);
  calib_tree->Branch("A2", &calib_A2);
  calib_tree->Branch("t02", &calib_t02);
  calib_tree->Branch("d21", &calib_d21);
  calib_tree->Branch("chi2", &calib_chi2);
  calib_tree->Branch("prob", &calib_prob);

  // Perform fits on each vector of 
  // charge v DACMMFE8+VMM graphs
  fout->mkdir("xADCcalib_plots");
  fout->cd("xADCcalib_plots");

  vector<TF1*> vfunc;

  for(int index = 0; index < Nindex; index++){
    char fname[50];
    sprintf(fname, "funcP0P2P1_MMFE8-%d_VMM-%d", 
	    vMMFE8[index], vVMM[index]);
    int ifunc = vfunc.size();
    vfunc.push_back(new TF1(fname, P0_P2_P1, 0., 400., 4));

    vfunc[ifunc]->SetParName(0, "c_{0}");
    //vfunc[ifunc]->SetParameter(0, 20.);
    vfunc[ifunc]->SetParameter(0, vQmin[index]);
    vfunc[ifunc]->SetParName(1, "A_{2}");
    vfunc[ifunc]->SetParameter(1, 0.003);
    vfunc[ifunc]->SetParName(2, "t_{0 , 2}");
    vfunc[ifunc]->SetParameter(2, 50.);
    vfunc[ifunc]->SetParName(3, "d_{2 , 1}");
    vfunc[ifunc]->SetParameter(3, 50.);
    
    vfunc[ifunc]->SetParLimits(3, 0., 10000.);
    
    vgraph[index]->Fit(fname, "EQ");

    char stitle[50];
    sprintf(stitle, "Board #%d, VMM #%d", vMMFE8[index], vVMM[index]);
    char scan[50];
    sprintf(scan, "c_xADXcalib_Board%d_VMM%d", vMMFE8[index], vVMM[index]);
    TCanvas* can = Plot_Graph(scan, vgraph[index], "Test Pulse DAC", "Input Charge (fC)", stitle);
    can->Write();
    delete can;

   calib_MMFE8 = vMMFE8[index];
   calib_VMM = vVMM[index];
   calib_sigma = vsigma[index];
   calib_c0 = vfunc[ifunc]->GetParameter(0);
   calib_A2 = vfunc[ifunc]->GetParameter(1);
   calib_t02 = vfunc[ifunc]->GetParameter(2);
   calib_d21 = vfunc[ifunc]->GetParameter(3);
   calib_chi2 = vfunc[ifunc]->GetChisquare();
   calib_prob = vfunc[ifunc]->GetProb();

   calib_tree->Fill();
  }
  fout->cd("");

  // Write calib_tree to output file
  fout->cd("");
  calib_tree->Write();
  fout->Close();
}
void paulFit(TDirectory *mDir,TH1F* fMFitS,TH1F* hMFitS,TH2F* hFCovar, bool makePlots, string type){
      std::string label[global_nMaxMassBins]={"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14"};

      TH1F *hMRaw[global_nMaxMassBins],*hMFit[global_nMaxMassBins];
      TGraphErrors *hBRaw[global_nMaxBdtBins],*hBFit[global_nMaxBdtBins];
      TH1F *fMRaw[global_nMaxMassBins],*fMFit[global_nMaxMassBins];
      TGraphErrors *fBRaw[global_nMaxBdtBins],*fBFit[global_nMaxBdtBins];
      TH2F *hFCorr;
      TH1F *fBPar,*fBErr;



      for(int i(0);i<global_nMassBins;i++) {
	hMRaw[i]=new TH1F((std::string("hMass")+label[i]+"Raw").c_str(),
	     	     (std::string("Events Mass range ")+label[i]+" Raw ").c_str(),
	     	     global_nBdtBins,0.0,global_nBdtBins);
	hMFit[i]=new TH1F((std::string("hMass")+label[i]+"Fit").c_str(),
	     	     (std::string("Events Mass range ")+label[i]+" Fit ").c_str(),
	     	     global_nBdtBins,0.0,global_nBdtBins);
	fMRaw[i]=new TH1F((std::string("fMass")+label[i]+"Raw").c_str(),
	     	     (std::string("Fractions Mass range ")+label[i]+" Raw ").c_str(),
	     	     global_nBdtBins,0.0,global_nBdtBins);
	fMFit[i]=new TH1F((std::string("fMass")+label[i]+"Fit").c_str(),
			     (std::string("Fractions Mass range ")+label[i]+" Fit ").c_str(),
			     global_nBdtBins,0.0,global_nBdtBins);
	
	for(int j(0);j<global_nBdtBins;j++) {
	  hMRaw[i]->SetBinContent(j+1,global_parameters.fData[i][j]);
	  hMRaw[i]->SetBinError(j+1,sqrt(global_parameters.fData[i][j]));
	  fMRaw[i]->SetBinContent(j+1,double(global_parameters.fData[i][j])/global_parameters.nrm[i]);
	  fMRaw[i]->SetBinError(j+1,sqrt(global_parameters.fData[i][j])/global_parameters.nrm[i]);
	}
      }
      
      for(int j(0);j<global_nBdtBins;j++) {
	hBRaw[j]=new TGraphErrors((std::string("hBDT")+label[j]+"Raw").c_str(),
	     	     (std::string("Events BDT bin ")+label[j]+" Raw ").c_str());
	hBRaw[j]->SetName((std::string("hBDT")+label[j]+"Raw").c_str());
	hBFit[j]=new TGraphErrors((std::string("hBDT")+label[j]+"Fit").c_str(),
	     	     (std::string("Events BDT bin ")+label[j]+" Fit ").c_str());
	hBFit[j]->SetName((std::string("hBDT")+label[j]+"Fit").c_str());
	fBRaw[j]=new TGraphErrors((std::string("fBDT")+label[j]+"Raw").c_str(),
	     	     (std::string("Fractions BDT bin ")+label[j]+" Raw ").c_str());
	fBRaw[j]->SetName((std::string("fBDT")+label[j]+"Raw").c_str());
	fBFit[j]=new TGraphErrors((std::string("fBDT")+label[j]+"Fit").c_str(),
			     (std::string("Fractions BDT bin ")+label[j]+" Fit ").c_str());
	fBFit[j]->SetName((std::string("fBDT")+label[j]+"Fit").c_str());
	
	for(int i(0);i<global_nMassBins;i++) {
	  double xERR = global_parameters.fMass[i]*global_SIDEBANDWIDTH;
	  hBRaw[j]->SetPoint(i,global_parameters.fMass[i],global_parameters.fData[i][j]);
	  hBRaw[j]->SetPointError(i,xERR,sqrt(global_parameters.fData[i][j]));
	  fBRaw[j]->SetPoint(i,global_parameters.fMass[i],double(global_parameters.fData[i][j])/global_parameters.nrm[i]);
	  fBRaw[j]->SetPointError(i,xERR,sqrt(global_parameters.fData[i][j])/global_parameters.nrm[i]);
	}
      }

      hFCorr=new TH2F((std::string("fCorr")).c_str(),
			 Form("Fraction correlation matrix m %3.1f",global_mH),
			 global_nBdtBins,0.0,global_nBdtBins,global_nBdtBins,0.0,global_nBdtBins);
      
      fBPar=new TH1F((std::string("fBPar")).c_str(),
			(std::string("Relative fit slope ")).c_str(),
			global_nBdtBins,0.0,global_nBdtBins);      
      fBErr=new TH1F((std::string("fBErr")).c_str(),
			(std::string("Fraction error ")).c_str(),
			global_nBdtBins,0.0,global_nBdtBins);      

// Function taken directly from P. Dauncey to Perform Fits
    
      TMinuit tMinuit(maxPar);
      tMinuit.mninit(5,6,7);
      tMinuit.SetFCN(fcnFit);
    
      int ell[5]={0,0,0,0,0};
    
      static Double_t p0=0;
      static Double_t p1=1;
      static Double_t p3=3;
      static Double_t p5=5;
    

      for(int i(1);i<global_nMaxBdtBins;i++) {
	tMinuit.DefineParameter(2*i-2,(std::string("Par")+label[i]+"0").c_str(),
				global_parameters.npb[i]/global_parameters.ntot,global_parameters.npb[i]==0?1.0/global_parameters.ntot:sqrt(global_parameters.npb[i])/global_parameters.ntot,0.0,0.0);
	tMinuit.DefineParameter(2*i-1,(std::string("Par")+label[i]+"1").c_str(),
				0.0,0.0001,0.0,0.0);

	if(i>=global_nBdtBins) {
	  tMinuit.FixParameter(2*i-2);
	  tMinuit.FixParameter(2*i-1);
	}
      }


      for(int i(0);i<global_nMaxMassBins;i++) {
	tMinuit.DefineParameter(i+2*(global_nMaxBdtBins-1),(std::string("Nrm")+label[i]).c_str(),
				global_parameters.nrm[i],sqrt(global_parameters.nrm[i]),0.0,0.0);
	
	if(i>global_nMassBins-1) tMinuit.FixParameter(i+2*(global_nMaxBdtBins-1));
      }
    
      tMinuit.mnexcm("CALL FCN", &p1 ,1,ell[0]);

      tMinuit.mnexcm("SCAN"    , &p1 ,0,ell[1]);

      ell[3]=tMinuit.Migrad();
      if(ell[3]!=0) std::cout << "WARNING MINUIT ERROR FLAG = " << ell[3] << std::endl;
    
      /*
	for(int i(1);i<nPar[fitFcn];i+=2) {
	tMinuit.Release(i);
	tMinuit.Release(i+1);
	tMinuit.mnexcm("SCAN"    , &p1 ,0,ell[1]);
	ell[3]=tMinuit.Migrad();
	}
      */
    
      tMinuit.mnexcm("CALL FCN", &p5 ,1,ell[4]);

      for(int i(0);i<maxPar;i++) {
	tMinuit.GetParameter(i,global_parameters.parAll[i],global_parameters.errAll[i]);
	std::cout << "AFTER MINUIT PAR " << i << " = "
		  << global_parameters.parAll[i] << " +/- " << global_parameters.errAll[i] << std::endl;
      }
      
      tMinuit.mnemat(&(global_parameters.errMat[0][0]),maxPar);

   //   for(int i(0);i<2*(global_nBdtBins-1)+nMassBins;i++) {
//	std::cout << "AFTER MNEMAT ERR2 " << i << " = "
//		  << global_parameters.errMat[i][i] << ", ERR " << sqrt(global_parameters.errMat[i][i]) << std::endl;
  //    }
      
//      std::cout << "ERRMAT" << std::endl;
//      for(int i(0);i<nBdtBins-1;i++) {
//	for(int j(0);j<nBdtBins-1;j++) {
//	  std::cout << std::setw(14) << global_parameters.errMat[2*i][2*j];
//	}
//	std::cout << std::endl;
//    }
      
      std::cout << "DQ/DP" << std::endl;
      double dqdp[global_nBdtBins-1][global_nBdtBins];
      for(int i(0);i<global_nBdtBins-1;i++) {
	for(int j(0);j<global_nBdtBins;j++) {
	  if(j==0) dqdp[i][j]=-1.0;
	  else {
	    if(i+1==j) dqdp[i][j]=1.0;
	    else       dqdp[i][j]=0.0;
	  }
	  std::cout << std::setw(14) << dqdp[i][j];
	}
	std::cout << std::endl;
      }

      std::cout << "FRACERR" << std::endl;
      double fracErr[global_nBdtBins][global_nBdtBins];
      for(int i(0);i<global_nBdtBins;i++) {
	for(int j(0);j<global_nBdtBins;j++) {
	  fracErr[i][j]=0.0;	
	  for(int k(0);k<global_nBdtBins-1;k++) {
	    for(int l(0);l<global_nBdtBins-1;l++) {
	      fracErr[i][j]+=dqdp[k][i]*global_parameters.errMat[2*k][2*l]*dqdp[l][j];
	      
	    }
	  }
	  //std::cout << std::setw(14) << fracErr[i][j];
	}
	std::cout << std::endl;
      }

      // Add Global Error to error matrix -> Motivated from Bias studies of fits:
      for(int i(0);i<global_nBdtBins;i++) {
	for(int j(0);j<global_nBdtBins;j++) {
	  fracErr[i][j]*=(1.+global_SYSTEMATICBIAS)*(1.+global_SYSTEMATICBIAS);	
	  std::cout << std::setw(14) << fracErr[i][j];
	}
	std::cout << std::endl;
      }
      

      std::cout << "FRACCOR" << std::endl;
      double fracCor[global_nBdtBins][global_nBdtBins];
      for(int i(0);i<global_nBdtBins;i++) {
	for(int j(0);j<global_nBdtBins;j++) {
	  // Turns Error Matrix into Correlation Matrix
	  fracCor[i][j]=fracErr[i][j]/sqrt(fracErr[i][i]*fracErr[j][j]);
	  // Covariance Matrix
	
	  //std::cout << std::setw(14) << fracCor[i][j];

	  hFCovar->SetBinContent(i+1,j+1,fracErr[i][j]);
	  hFCorr->SetBinContent(i+1,j+1,fracCor[i][j]);
	}
	std::cout << std::endl;
      }

      for(int i(0);i<global_nBdtBins;i++) {
	std::cout << "AFTER DQ/DP  ERR2 " << i << " = "
		  << fracErr[i][i] << ", ERR " << sqrt(fracErr[i][i]) << std::endl;
      }

      for(int j(0);j<global_nBdtBins;j++) {
	fBErr->SetBinContent(j+1,sqrt(fracErr[j][j]));
      }

      double p00(1.0);
      double p01(0.0);

      // Extract fractions/yields for each mass and for each BDT bin
      for(int i(0);i<global_nMassBins;i++) {
	for(int j(1);j<global_nBdtBins;j++) {
	  hMFit[i]->SetBinContent(j+1,global_parameters.parAll[i+2*(global_nMaxBdtBins-1)]*(global_parameters.parAll[2*j-2]+global_parameters.parAll[2*j-1]*(global_parameters.fMass[i]-global_mH)));
	  fMFit[i]->SetBinContent(j+1,              global_parameters.parAll[2*j-2]+global_parameters.parAll[2*j-1]*(global_parameters.fMass[i]-global_mH) );
//	  hBFit[j]->SetBinContent(i+1,global_parameters.parAll[i+2*(global_nMaxBdtBins-1)]*(global_parameters.parAll[2*j-2]+global_parameters.parAll[2*j-1]*(global_parameters.fMass[i]-global_mH)));
//	  fBFit[j]->SetBinContent(i+1,              global_parameters.parAll[2*j-2]+global_parameters.parAll[2*j-1]*(global_parameters.fMass[i]-global_mH) );
	  fBFit[j]->SetPoint(i,global_parameters.fMass[i],global_parameters.parAll[2*j-2]+global_parameters.parAll[2*j-1]*(global_parameters.fMass[i]-global_mH));
	  hBFit[j]->SetPoint(i,global_parameters.fMass[i],global_parameters.parAll[i+2*(global_nMaxBdtBins-1)]*(global_parameters.parAll[2*j-2]+global_parameters.parAll[2*j-1]*(global_parameters.fMass[i]-global_mH)));


	  if(i==0) {
	    p00-=global_parameters.parAll[2*j-2];
	    p01-=global_parameters.parAll[2*j-1];
	  }
	}

	hMFit[i]->SetBinContent(  1,global_parameters.parAll[i+2*(global_nMaxBdtBins-1)]*(p00+p01*(global_parameters.fMass[i]-global_mH)));
	fMFit[i]->SetBinContent(  1,              p00+p01*(global_parameters.fMass[i]-global_mH) );
	hBFit[0]->SetPoint(i,global_parameters.fMass[i],global_parameters.parAll[i+2*(global_nMaxBdtBins-1)]*(p00+p01*(global_parameters.fMass[i]-global_mH)));
	fBFit[0]->SetPoint(i,global_parameters.fMass[i],p00+p01*(global_parameters.fMass[i]-global_mH) );
      }

      double pS00(1.0);
      // We are interested in the BDT bins in the signal region, so need those histograms ie setting mH=m0
      for(int j(1);j<global_nBdtBins;j++) {
	float binSFrac = global_parameters.parAll[2*(j-1)];
      	fMFitS->SetBinContent(j+1,binSFrac);
	fMFitS->SetBinError(j+1,fBErr->GetBinContent(j+1));
      	hMFitS->SetBinContent(j+1,binSFrac*global_nSignalRegion);
	hMFitS->SetBinError(j+1,global_nSignalRegion*fBErr->GetBinContent(j+1));
	pS00-=binSFrac;
      }

      fMFitS->SetBinContent(1,pS00);
      fMFitS->SetBinError(1,fBErr->GetBinContent(1));
      hMFitS->SetBinContent(1,pS00*global_nSignalRegion);
      hMFitS->SetBinError(1,global_nSignalRegion*fBErr->GetBinContent(1));

      fBPar->SetBinContent(1,p01/p00);
      fBPar->SetBinError(1,0.0);
      for(int j(1);j<global_nBdtBins;j++) {
	fBPar->SetBinContent(j+1,global_parameters.parAll[2*j-1]/global_parameters.parAll[2*j-2]);
	fBPar->SetBinError(j+1,(global_parameters.parAll[2*j-1]/global_parameters.parAll[2*j-2])*sqrt((global_parameters.errAll[2*j-1]*global_parameters.errAll[2*j-1]/(global_parameters.parAll[2*j-1]*global_parameters.parAll[2*j-1]))+(global_parameters.errAll[2*j-2]*global_parameters.errAll[2*j-2]/(global_parameters.parAll[2*j-2]*global_parameters.parAll[2*j-2]))));
      }

      // Write out the histos
      mDir->cd();

      for(int i(0);i<global_nMassBins;i++) {
	hMRaw[i]->Write();
	hMFit[i]->Write();
	fMRaw[i]->Write();
	fMFit[i]->Write();
      }	
      
      for(int j(0);j<global_nBdtBins;j++) {
	hBRaw[j]->Write();
	hBFit[j]->Write();
	fBRaw[j]->Write();
	fBFit[j]->Write();
      }
      // Make a plot of the points Fitted and the fitted graph
      gROOT->SetBatch(true);
      gROOT->SetStyle("Plain");
      for(int j(0);j<global_nBdtBins;j++) {
        TCanvas *can = new TCanvas(Form("Fit_BDT%d",j),"c1",305,95,800,550);
//        can->SetName(Form("Fit_BDT%d",j));
	can->SetBottomMargin(0.12);
	can->SetGrid(); 
        fBFit[j]->SetLineColor(4);
        fBFit[j]->SetLineWidth(3);
        fBRaw[j]->SetMarkerStyle(20);
        fBRaw[j]->SetMarkerSize(1.0);
        fBRaw[j]->GetXaxis()->SetTitle("m_{H} (GeV)");
        fBRaw[j]->GetXaxis()->SetTitleSize(0.055);
        fBRaw[j]->GetXaxis()->SetLabelSize(0.045);
        fBRaw[j]->GetYaxis()->SetTitle(Form("Fraction in bin %d",j+1));
        fBRaw[j]->GetYaxis()->SetTitleSize(0.05);
        fBRaw[j]->GetYaxis()->SetLabelSize(0.045);
        fBRaw[j]->GetYaxis()->SetNdivisions(508); 
        //fBRaw[j]->SetTitle(Form("Fit BDT Mass %3.1f Bin %d",global_mH,j));
        double FVal = fBFit[j]->Eval(global_mH);
        fBRaw[j]->GetYaxis()->SetRangeUser(floor(FVal*0.75*100)/100,floor(FVal*1.25*100)/100);

        TLine l(global_mH,floor(FVal*0.75*100)/100,global_mH,floor(FVal*1.25*100)/100);
        l.SetLineColor(46);
        l.SetLineStyle(7);
	l.SetLineWidth(3);
        fBRaw[j]->SetTitle("");
        fBRaw[j]->Draw("AP");
        fBFit[j]->Draw("L");
        fBRaw[j]->Draw("sameP");
        l.Draw();

	TText *text = new TText(0.6,0.8,"CMS Preliminary");
	text->SetNDC();
	text->Draw();
	text->SetTextSize(0.05); 

        can->Write();
        if (makePlots){
          can->Print(Form("BMplots/%s/fit_m%3.1f_bin%d.png",type.c_str(),global_mH,j));
          can->Print(Form("BMplots/%s/fit_m%3.1f_bin%d.pdf",type.c_str(),global_mH,j));
        }
      }
      
      fMFitS->Write();
      hMFitS->Write();

      hFCorr->Write();
      hFCovar->Write();
      fBPar->Write();
      fBErr->Write();

      if (makePlots){
        TCanvas *canv = new TCanvas();
        gStyle->SetOptStat(0);
        gPad->SetRightMargin(5.);
        hFCorr->SetMarkerColor(kGray+2);
        hFCorr->Draw("colz text");
        canv->Print(Form("BMplots/%s/fCorr_m%3.1f.png",type.c_str(),global_mH));
        canv->Print(Form("BMplots/%s/fCorr_m%3.1f.pdf",type.c_str(),global_mH));
        hFCovar->SetMarkerColor(kGray+2);
        hFCovar->Draw("colz text");
        canv->Print(Form("BMplots/%s/fCovar_m%3.1f.png",type.c_str(),global_mH));
        canv->Print(Form("BMplots/%s/fCovar_m%3.1f.pdf",type.c_str(),global_mH));
      }
	    
}
Esempio n. 27
0
void bkg(int seed = 37) {
    using namespace RooFit;
    using namespace std;
    int nbin = 50;
    bool binned = false;
    stringstream nSig;
    stringstream nBkg;
    stringstream bwRatio;
    stringstream bRatio;
    stringstream mass = "40";
    double bL = 20.;//std::atof(mass.str().c_str()) - 10;
    double bH = 70.;//std::atof(mass.str().c_str()) + 10;
    TString pf = "4_4";
    nSig <<3.45;
    nBkg << 552;
    double bkgUnc = 1;//(510-424.)/424.; //50%
    bwRatio << 0.2;
    bRatio << 0.8;
    stringstream range;
    range << bL << "," << bH;
    cout << "Mass: " << mass.str() << endl;
    cout << "Range: " << range.str() << endl;
    TString Range = range.str().c_str();
    TString Mass = mass.str().c_str();
    ///	Data-fit ////////////////
    TString fname = ""; 
    if(!binned)
	    fname = "hamb-shapes-UnbinnedParam-m" + Mass + "-Data-fit.root";
	else
	    fname = "hamb-shapes-BinnedParam-m" + Mass + "-Data-fit.root";		
	
	if(!binned){
		TString name = "test";
    	RooRealVar eventSelectionamassMu("eventSelectionamassMu", "eventSelectionamassMu", bL, bH);
    	TFile* fbkg = new TFile("DoubleMu2012_Summer12_final_CR_" + pf + ".root", "READ");
    	TTree* hbkg = (TTree*) fbkg->Get("rds_zbb");
	    RooDataSet bkgData("bkgData", "bkgData", hbkg, eventSelectionamassMu, "");
    	
    	RooKeysPdf bkg1("bkg1","nominal (1)",eventSelectionamassMu, bkgData,RooKeysPdf::MirrorBoth, 1);
    	RooKeysPdf bkg05("bkg05","doen (0.5)",eventSelectionamassMu, bkgData,RooKeysPdf::MirrorBoth, 0.5);
    	RooKeysPdf bkg2("bkg2","up (2)",eventSelectionamassMu, bkgData,RooKeysPdf::MirrorBoth, 2);
    	RooKeysPdf bkg03("bkg03","down (0.3)",eventSelectionamassMu, bkgData,RooKeysPdf::MirrorBoth, 0.3);
    	RooKeysPdf bkg3("bkg3","up (3)",eventSelectionamassMu, bkgData,RooKeysPdf::MirrorBoth, 3);   
    	RooKeysPdf bkg02("bkg04","down (0.2)",eventSelectionamassMu, bkgData,RooKeysPdf::MirrorBoth, 0.2);
    	RooKeysPdf bkg4("bkg4","up (4)",eventSelectionamassMu, bkgData,RooKeysPdf::MirrorBoth, 4);        	 	
    	
    	RooPlot * p =    eventSelectionamassMu.frame(RooFit::Title("#rho =  0.5, 1, 2"),RooFit::Bins(nbin));	
    	bkgData.plotOn(p,RooFit::MarkerStyle(24));
    	bkg1.plotOn(p, RooFit::LineColor(kRed));
    	bkg05.plotOn(p, RooFit::LineColor(kGreen));    	
    	bkg2.plotOn(p, RooFit::LineColor(kBlue)); 
    	
        RooPlot * p2 =    eventSelectionamassMu.frame(RooFit::Title("#rho =  0.3, 1, 3"),RooFit::Bins(nbin));	
    	bkgData.plotOn(p2,RooFit::MarkerStyle(24));
    	bkg1.plotOn(p2, RooFit::LineColor(kRed));
    	bkg03.plotOn(p2, RooFit::LineColor(kGreen));    	
    	bkg3.plotOn(p2, RooFit::LineColor(kBlue));      	
    	  
    	
        RooPlot * p3 =    eventSelectionamassMu.frame(RooFit::Title("#rho =  0.2, 1, 4"),RooFit::Bins(nbin));	
    	bkgData.plotOn(p3,RooFit::MarkerStyle(24));
    	bkg1.plotOn(p3,RooFit::FillColor(kWhite), RooFit::LineColor(kRed));
    	bkg02.plotOn(p3,RooFit::FillColor(kWhite), RooFit::LineColor(kGreen)/*, RooFit::LineStyle(kDashed)*/);    	
    	bkg4.plotOn(p3,RooFit::FillColor(kWhite), RooFit::LineColor(kBlue) /*, RooFit::LineStyle(kDashed)*/);  
    	
    	   	
    	TCanvas Can;
    	Can.Divide(3,1);
    	Can.cd(1);
    	p->Draw();  	
    	Can.cd(2);
    	p2->Draw();
    	Can.cd(3);
    	p3->Draw();
    	Can.SaveAs("bkgtemp.C");
    	
    	TFile* fsig = new TFile("input_4.root", "READ");
     	TTree* hsig = (TTree*) fsig->Get("rds_zbb");  
	    RooDataSet sigData("sigData", "sigData", hsig, eventSelectionamassMu, "");   
	    RooKeysPdf sig1("sig1","Signal CR",eventSelectionamassMu, sigData,RooKeysPdf::MirrorBoth, 1);  
	    double nbkg = hbkg->GetEntriesFast();
	    double nsig = 3.88*0.2528;
	    RooRealVar frac("frac","frac", (nsig/nbkg));	 	
	    RooAddPdf sum("sum","sum nominal",RooArgList(sig1,bkg1), RooArgList(frac));
	    RooPlot * p4 =    eventSelectionamassMu.frame(RooFit::Title("Signal + Background"),RooFit::Bins(nbin));	
   	    bkgData.plotOn(p4,RooFit::MarkerStyle(24));
	    sum.plotOn(p4,RooFit::FillColor(kWhite), RooFit::LineColor(kRed));
	    bkg05.plotOn(p4, RooFit::LineColor(kGreen));    	
    	bkg2.plotOn(p4, RooFit::LineColor(kBlue)); 
    	
    	RooPlot * p5 =    eventSelectionamassMu.frame(RooFit::Title("Signal + Background"),RooFit::Bins(nbin));	
    	bkgData.plotOn(p5,RooFit::MarkerStyle(24));
    	sum.plotOn(p5, RooFit::LineColor(kRed));
    	bkg03.plotOn(p5, RooFit::LineColor(kGreen));    	
    	bkg3.plotOn(p5, RooFit::LineColor(kBlue));      	
    	  
    	
        RooPlot * p6 =    eventSelectionamassMu.frame(RooFit::Title("Signal + Background"),RooFit::Bins(nbin));	
    	bkgData.plotOn(p6,RooFit::MarkerStyle(24));
    	sum.plotOn(p6,RooFit::FillColor(kWhite), RooFit::LineColor(kRed));
    	bkg02.plotOn(p6,RooFit::FillColor(kWhite), RooFit::LineColor(kGreen)/*, RooFit::LineStyle(kDashed)*/);    	
    	bkg4.plotOn(p6,RooFit::FillColor(kWhite), RooFit::LineColor(kBlue) /*, RooFit::LineStyle(kDashed)*/);  
    	
	    TCanvas Can2;
		Can2.Divide(3,1);
    	Can2.cd(1);
	    p4->Draw();
	    Can2.cd(2);
    	p5->Draw();
    	Can2.cd(3);
    	p6->Draw();
	    Can2.SaveAs("sumtemp.C");

	} 
}
void createCorrectedBackgroundModel(std::string fileName, int nsidebands=6, bool makePlots=false, std::string defaultPrepend="CMS-HGG" ){

     if (makePlots){
       system("mkdir -p BMplots/ada");
       system("mkdir -p BMplots/grad");
       gStyle->SetPalette(1);
       gStyle->SetOptStat(0);
     }

     global_nMassBins=nsidebands;

     double massMin = 120;
     double massMax = 130;
     double dM  = 0.1;
	
     // Open the original Workspace
     TFile *in = TFile::Open(fileName.c_str(),"UPDATE");
     RooWorkspace *work = (RooWorkspace*)in->Get("cms_hgg_workspace");
 
     std::string types[2]={"grad","ada"};

     for (int ty=0;ty<2;ty++){

	std::string type = types[ty];
	// Create An output file for the TF1 Sideband Fits
  	std::string pathToFile=fileName.substr(0,fileName.find(defaultPrepend.c_str()));
 	std::string fName=fileName.substr(fileName.find(defaultPrepend.c_str()),fileName.size());
	TFile *out = new TFile(Form("%sbdtSidebandFits_%s_%s",pathToFile.c_str(),type.c_str(),fName.c_str()),"RECREATE");
	for (double mH=massMin;mH<=massMax;mH+=dM){

		//TH1F *originalHist      = (TH1F*) in->Get(Form("th1f_bkg_%s_%3.1f_cat0",type.c_str(),mH)); // This histogram is normalized to the inclusive fit (will not include VBF cat)
		RooRealVar *nSignalVar = (RooRealVar*)work->var(Form("NBkgInSignal_mH%3.1f",mH));
		TH1F *dataHist  = (TH1F*) in->Get(Form("th1f_data_%s_%3.1f_cat0",type.c_str(),mH)); // Data Histogram, includes VBF category
		int nBins = dataHist->GetNbinsX();

		// Want to make a "corrected" histogram 
		TH1F *correctedHist = new TH1F(Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr",type.c_str(),mH),Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr",type.c_str(),mH),nBins,0,nBins);		     
		TH1F *correctedHistFR = new TH1F(Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr_frac",type.c_str(),mH),Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr_frac",type.c_str(),mH),nBins,0,nBins);		     
      	        TH2F *hFCovar=new TH2F(Form("fCovar_%3.1f",mH),
			 Form("Fraction covariance matrix m %3.1f",mH),
			 nBins,0.0,nBins,nBins,0.0,nBins);
		TH2F *uCorrErr = new TH2F(Form("fUncorrErr_%s_%3.1f",type.c_str(),mH),
			 Form("Uncorrelated Errors m %3.1f",mH),
			 nBins,0.0,nBins,nBins,0.0,nBins);
	
		TDirectory *mass_dir = out->mkdir(Form("mH_%3.1f",mH));

		// For a given mass point, need to set up globals
		global_nBdtBins=nBins;		
		global_mH=mH;
		global_nSignalRegion=nSignalVar->getVal();

		fillData(mH,in,type);
		paulFit(mass_dir,correctedHistFR,correctedHist,hFCovar,makePlots,type);
		
		// Finally Get the uncorrleated errors from the covariance matrix
		diagonalizeMatrix(hFCovar,uCorrErr);

		std::cout << "Final Check of Normalizations at mH="<<mH <<std::endl;
		std::cout << "Original - "<< global_nSignalRegion <<  ", After - " <<correctedHist->Integral() <<std::endl;
		
		// Write out the Hists into the original File
		in->cd();
		correctedHist->Write(correctedHist->GetName(),TObject::kOverwrite);
		correctedHistFR->Write(correctedHistFR->GetName(),TObject::kOverwrite);
		//hFCovar->Write();
		uCorrErr->Write(uCorrErr->GetName(),TObject::kOverwrite);
    out->cd();
    mass_dir->cd();
    uCorrErr->Write(uCorrErr->GetName(),TObject::kOverwrite);

    if (makePlots){
      TCanvas *canv = new TCanvas();
      uCorrErr->SetMarkerColor(kGray);
      gPad->SetRightMargin(2.);
      uCorrErr->Draw("colz text");
      canv->Print(Form("BMplots/%s/uncorrErr_m%3.1f.png",type.c_str(),mH));
      canv->Print(Form("BMplots/%s/uncorrErr_m%3.1f.pdf",type.c_str(),mH));
    }
	}
	std::cout << "Saving Fits to file -> " << out->GetName() << std::endl;
        out->Close();
     }
    
    std::cout << "Updated (with corrected background model) -> " << in->GetName() << std::endl;
    in->Close();
}
Esempio n. 29
0
void CalcPeriod(char *DataFile = "drs4_peds_5buffers.dat", Int_t nevt,
		Int_t startEv = 1, char *PedFile) {

	// create progress bar
	TGHProgressBar *gProgress = ProgressBar("Calcolo periodo");

	// Redefine DOMINO Depth in ADC counts
	const Float_t DominoDepthADC = pow(2, DOMINO_DEPTH);

	// open file

	FILE *fdata = OpenDataFile(DataFile);
	struct channel_struct *p;
	struct channel_struct *dep;

	// create list of graphs for pedestals
	TList *grPedList = new TList();
	TGraphErrors *grPed;

	// create period histogram

	TString title = "Period histogram";
	TH1 *hPeriod = new TH1F(title,title, 2*((Int_t) DOMINO_NCELL), (Double_t) -DOMINO_NCELL, (Double_t) DOMINO_NCELL);

	// calculate or read pedestals from file
	grPedList = OpenPedestals(PedFile);
	grPed = (TGraphErrors *) grPedList->At(anaChannel);


	// Count number of events in data file
	int nevtDataMax = 0;
	while (!feof(fdata)) {
		fread((void *) &event_data, 1, sizeof(event_data), fdata);
		nevtDataMax++;
	}
	printf("nevtDataMax: %d\n", nevtDataMax - 1);

	if (nevt > (nevtDataMax - startEv) || nevt == 0)
		nevt = nevtDataMax - startEv;
	cout << endl << "==>> Processing " << nevt << " events from file "
			<< DataFile << endl;

	rewind(fdata);


	Int_t ievt = 1;
	// go to first event (startEv)
	while (ievt < startEv) {
		fread((void *) &event_data, 1, sizeof(event_data), fdata);
		if (feof(fdata))
			break;
		ievt++;
	}

	ievt = 1;
	Int_t flagEnd = 0;
	Int_t fitusati = 0;
	Double_t chtmp;
	Double_t PedVal, itmp;
	Double_t mean, rms;
	Double_t ratio;



	//debug canvas
	TCanvas *cfitTest = new TCanvas("cfitTest", "fit tests", 1200, 780);
	cfitTest->Divide(1,nevt);

	// loop on events

	gProgress->Reset();
	gProgress->SetMax(nevt);

	gSystem->ProcessEvents();

	while (ievt <= nevt && !flagEnd) {
		fread((void *) &event_data, 1, sizeof(event_data), fdata);
		if (feof(fdata))
			flagEnd = 1;

		p = (struct channel_struct *) &event_data.ch[0]; // read bunch of data
		dep = (struct channel_struct *) &event_data.ch[1]; // read bunch of data
		// goes to channel to analyze
		p += anaChannel;

		// read data, subtract pedestals values and save results in grAnaChDataTemp graph with
		// fixed error for each point (x = 0.5 and y = 2.1). Also generate an array with Domino
		// X and Y values

		TGraphErrors *grAnaChDataTemp = new TGraphErrors(DOMINO_NCELL);

		for (int ch = 0; ch < DOMINO_NCELL; ch++) {
			// Read pedestal value for this cell
			grPed->GetPoint(ch, itmp, PedVal);
			chtmp = (Double_t)(p->data[ch]); // data value
			chtmp = chtmp - PedVal;
			grAnaChDataTemp->SetPoint(ch, (Double_t) ch, chtmp);
			grAnaChDataTemp->SetPointError(ch, 0.5, 2.1);
		}
		// create fit functions
		TF1 *fsin = new TF1("fsin", sigSin, 0., 1024., 4);
		fsin->SetParameters(600., 255., 150., 150.);
		fsin->SetParNames("amplitude", "Period", "Phase", "DC-Offset");

		grAnaChDataTemp->Fit("fsin", "Q");
		TF1 *fsinFit = grAnaChDataTemp->GetFunction("fsin");
		fsinFit->SetParNames("amplitude", "Period", "Phase", "DC-Offset");

		// debug
		cfitTest->cd(ievt);
		grAnaChDataTemp->SetMarkerStyle(20);
		grAnaChDataTemp->SetMarkerSize(0.3);
		grAnaChDataTemp->GetYaxis()->SetLabelSize(0.12);
		grAnaChDataTemp->GetXaxis()->SetLabelSize(0.12);
		grAnaChDataTemp->Draw("APE");

		Double_t fitPeriod, fitAmplitude, chisquare;
		fitPeriod = fsinFit->GetParameter("Period");
		fitAmplitude = TMath::Abs(fsinFit->GetParameter("amplitude"));
		chisquare = fsinFit->GetChisquare();

		cout << "period: " << fitPeriod << " amplitude: " << fitAmplitude << " chisquare: " << chisquare << endl;

		if(chisquare > 0.1e+06) {
			gProgress->Increment(1);
			gSystem->DispatchOneEvent(kTRUE);
			ievt++;
			continue;
		}

		gProgress->Increment(1);
		gSystem->DispatchOneEvent(kTRUE);

		hPeriod->Fill(fitPeriod);
		fitusati++;

		ievt++;

	}

	cout << "fit scartati :" << nevt - fitusati << endl;
	//draw
	TString Title = "Period distribution for nevt events";
	TCanvas *cPeriod = new TCanvas("cPeriod", Title, 700, 700);
	hPeriod->Draw();
	hPeriod->Fit("gaus");

	TF1 *fgausFit = hPeriod->GetFunction("gaus");
	//mean = fgausFit->GetParameter(1);
	//	rms = fgausFit->GetParameter(2);

	mean = hPeriod->GetMean();
	rms = hPeriod->GetRMS();

	TString OutFile = "Period";
	OutFile += nevt;
	OutFile += "events.dat";
	FILE *f = fopen(OutFile.Data(), "w");
	fwrite(&mean, sizeof(mean), 1, f);
	fwrite(&rms, sizeof(rms), 1, f);

	((TGMainFrame *) gProgress->GetParent())->CloseWindow();
	fclose(f);

	cout << "mean: " << mean << " rms: " << rms << endl;

	fclose(fdata);

}
void overlay_Merged_RecoSmeared()
{
	vector<string> folders, htbinlabels, hists;
	folders.push_back("Hist/HT0to7000MHT0to7000");
	/*folders.push_back("Hist/HT0to500MHT0to7000");
	folders.push_back("Hist/HT500to900MHT0to7000");
	folders.push_back("Hist/HT900to1300MHT0to7000");
	folders.push_back("Hist/HT1300to7000MHT0to7000");
	*/

	vector<hist_t> histlist;
	for (int i=0; ;++i)
	{
		hist_t h;
		h.normalizeByBinWidth = 0;
		if (i==0) {
			h.name = "_mht";
			h.title = "MHT;Events";
			h.rebin = 10;
		} else if (i==1) {
			h.name = "_ht";
			h.title = "HT;Events";
			h.rebin = 2;
		} else if (i==2) {
			h.name = "jet1_pt";
			h.title = "P_{T} [Jet1^{E_{T}>50, |#eta |<2.5}];Events;";
			h.rebin = 1;
		} else if (i==3) {
			h.name = "jet2_pt";
			h.title = "P_{T} [Jet2^{E_{T}>50, |#eta |<2.5}];Events;";
			h.rebin = 1;
		} else if (i==4) {
			h.name = "jet3_pt";
			h.title = "P_{T} [Jet3^{E_{T}>50, |#eta |<2.5}];Events;";
			h.rebin = 1;
		} else if (i==5) {
			h.name = "jet1_eta";
			h.title = "#eta [Jet1^{E_{T}>50, |#eta |<2.5}];Events;";
			h.rebin = 2;
		} else if (i==6) {
			h.name = "jet2_eta";
			h.title = "#eta [Jet2^{E_{T}>50, |#eta |<2.5}];Events;";
			h.rebin = 2;
		} else if (i==7) {
			h.name = "jet3_eta";
			h.title = "#eta [Jet3^{E_{T}>50, |#eta |<2.5}];Events;";
			h.rebin = 2;
		} else if (i==8) {
			h.name = "_njet50eta2p5";
			h.title = "N Jets [E_{T}>50 GeV && |#eta |<2.5];Events";
			h.rebin = 1;
		} else if (i==9) {
			h.name = "_dphimin";
			h.title = "#Delta #Phi_{min};Events";
			h.rebin = 5;
			h.normalizeByBinWidth = 1;
		} else if (i==10) {
			h.name = "_njet30eta5p0";
			h.title = "N Jets [E_{T}>30 GeV && |#eta |<5.0];Events";
			h.rebin = 1;
		} else if (i==11) {
			h.name = "jet1_dphi";
			h.title = "#Delta #Phi (Jet 1^{ pt>50,GeV | #eta | < 2.5}, MHT);Events";
			h.rebin = 2;
		} else if (i==12) {
			h.name = "jet2_dphi";
			h.title = "#Delta #Phi (Jet 2^{ pt>50 GeV, | #eta | < 2.5}, MHT);Events";
			h.rebin = 2;
		} else if (i==13) {
			h.name = "jet3_dphi";
			h.title = "#Delta #Phi (Jet 3^{ pt>50 GeV, |#eta | < 2.5}, MHT);Events";
			h.rebin = 2;
		} else if (i==14) {
			h.name = "jet4_pt";
			h.title = "P_{T} [Jet4^{E_{T}>50, |#eta |<2.5}];Events;";
			h.rebin = 1;
		} else if (i==15) {
			h.name = "jet5_pt";
			h.title = "P_{T} [Jet5^{E_{T}>50, |#eta |<2.5}];Events;";
			h.rebin = 1;
		} else if (i==16) {
			h.name = "jet6_pt";
			h.title = "P_{T} [Jet6^{E_{T}>50, |#eta |<2.5}];Events;";
			h.rebin = 1;
		} else if (i==17) {
			h.name = "jet7_pt";
			h.title = "P_{T} [Jet7^{E_{T}>50, |#eta |<2.5}];Events;";
			h.rebin = 1;
	/*	} else if (i==10) {
			h.name = "pass0";
			h.title = "MHT;Events with #Delta #Phi_{min}>0.15";
			h.rebin = 1;
			h.normalizeByBinWidth = 1;
		} else if (i==11) {
			h.name = "pass1";
			h.title = "MHT;Events with #Delta #Phi_{min}>0.20";
			h.rebin = 1;
			h.normalizeByBinWidth = 1;
		} else if (i==12) {
			h.name = "pass3";
			h.title = "MHT;Events with #Delta #Phi_{min}>0.30";
			h.rebin = 1;
			h.normalizeByBinWidth = 1;
		} else if (i==13) {
			h.name = "fail0";
			h.title = "MHT;Events with #Delta #Phi_{min}<0.15";
			h.rebin = 1;
			h.normalizeByBinWidth = 1;
		} else if (i==14) {
			h.name = "fail1";
			h.title = "MHT;Events with #Delta #Phi_{min}<0.20";
			h.rebin = 1;
			h.normalizeByBinWidth = 1;
		} else if (i==15) {
			h.name = "fail3";
			h.title = "MHT;Events with #Delta #Phi_{min}<0.30";
			h.rebin = 1;
			h.normalizeByBinWidth = 1;
		} else if (i==16) {
			h.name = "signal";
			h.title = "MHT;Events Passing RA2 #Delta #Phi cut";
			h.rebin = 1;
			h.normalizeByBinWidth = 1;
		} else if (i==17) {
			h.name = "_njet30eta5p0";
			h.title = "N Jets [E_{T}>30 GeV && |#eta |<5.0];Events";
			h.rebin = 1;
*/		} else { break; }
		histlist.push_back(h);
	}

	OpenFiles();
	TCanvas *c = new TCanvas("print");	
	c->Draw();
	c->Print("reco_gen_fullsprectrum_compare.eps[");

	for (unsigned h = 0; h < histlist.size(); ++h)
	{
		//if (h!=0) continue;
		cout << histlist.at(h).name << endl;

		TCanvas* c1 = overlay_Merged_RecoSmeared(folders, histlist.at(h)); 
		c1->Print("reco_gen_fullsprectrum_compare.eps");
	}
	c->Print("reco_gen_fullsprectrum_compare.eps]");
}