Пример #1
0
// -----------------------------------------------------------------------------
//
TH1* getHisto( TString path,
	       TString nameHist,
	       TString nameFile,
	       TString Dirname, 
	       int rebin ) {
  TString name = path + nameFile;
  TFile* file =  new TFile(name);
  // file->ls();
  TDirectory* dir = (TDirectory*)file->Get(Dirname);
  //  dir->ls();

  if( !dir) {
    std::cout << " dir " << Dirname << std::endl;
  }
  TH1* hist = (TH1*)dir->Get(nameHist);
  if (!hist) {
    std::cout << " name: " << nameHist
	      << " file: " << nameFile
	      << " dir: " <<  Dirname
	      << std::endl;
    abort();

  }
  hist->SetLineWidth(1);
  if ( rebin > 0 ) { hist->Rebin(rebin); }
  hist->GetXaxis()->SetTitleSize(0.055);
  hist->GetYaxis()->SetTitleSize(0.055);
  hist->GetXaxis()->SetLabelSize(0.05);
  hist->GetYaxis()->SetLabelSize(0.05);
  hist->SetStats(kFALSE);
  return hist;
}
Пример #2
0
// -----------------------------------------------------------------------------
//
TH1* getHisto( std::string nameFile,
	       std::string nameHist,
	       std::string Dirname, 
	       int rebin ) {
  std::string name = nameFile;
  TFile* file =  new TFile(name.c_str());
  if (file) { std::cout << "Opened file: " << file->GetName() << std::endl; }
  else { 
    std::cout << "Could not find file: " << name << std::endl; 
    return 0; 
  }
  
  TDirectory* dir = (TDirectory*)file->Get(Dirname.c_str());
  if (dir) { std::cout << "Opened dir: " << dir->GetName() << std::endl; }
  else { 
    std::cout << "Could not find dir: " << Dirname << std::endl; 
    return 0; 
  }
  
  int low = 375;
  TH1* hist = 0;
  if ( false || nameHist.find("HtMultiplicity_HT375") == std::string::npos ) { 
    hist = (TH1*)dir->Get(nameHist.c_str());
  } else {
    
    for ( uint ii = low; ii <= 975; ii+=100 ) {
      std::stringstream tmp; tmp << "HtMultiplicity_HT" << ii << nameHist.substr(20);
      if ( !hist ) { 
	dir->cd();
	TH1D* temp = (TH1D*)dir->Get( "HtMultiplicity_HT375_aT0" );
	//TH1D* temp = (TH1D*)file->Get( tmp.str().c_str() );
	if (temp) { hist = (TH1D*)temp->Clone(); } 
	else { std::cout << "1 Unable to retrieve histo with name " << tmp.str() << std::endl; }
      } else { 
	dir->cd();
	TH1D* temp = (TH1D*)dir->Get( tmp.str().c_str() );
	if (temp) { hist->Add( (TH1D*)temp ); } 
	else { std::cout << "2 Unable to retrieve histo with name " << tmp.str() << std::endl; }
      }
    }

  }
  if (hist) { std::cout << "Opened histo: " << hist->GetName() << std::endl; }
  else { 
    std::cout << "Could not find histo: " << nameHist << std::endl; 
    return 0; 
  }

  hist->SetLineWidth(3);
  if ( rebin > 0 ) { hist->Rebin(rebin); }
  hist->GetXaxis()->SetTitleSize(0.055);
  hist->GetYaxis()->SetTitleSize(0.055);
  hist->GetXaxis()->SetLabelSize(0.05);
  hist->GetYaxis()->SetLabelSize(0.05);
  hist->SetStats(kFALSE);
  return hist;
}
TH1* loadHistogram(TFile* inputFile, const std::string& directory, const std::string& histogramName)
{
  std::string histogramName_full = Form("%s/%s", directory.data(), histogramName.data());
  TH1* histogram = dynamic_cast<TH1*>(inputFile->Get(histogramName_full.data()));
  if ( !histogram ) {
    std::cerr << "Failed to load histogram = " << histogramName_full << " from file = " << inputFile->GetName() << " !!" << std::endl;
    assert(0);
  }
  if ( !histogram->GetSumw2N() ) histogram->Sumw2();
  histogram->Rebin(4);
  return histogram;
}
TH1* getHistogram(TFile* inputFile, const TString& dqmDirectory, const TString& meName)
{  
  TString histogramName = dqmDirectory;
  if ( histogramName.Length() > 0 && !histogramName.EndsWith("/") ) histogramName.Append("/");
  histogramName.Append(meName);

  TH1* histogram = (TH1*)inputFile->Get(histogramName.Data());
  std::cout << "histogramName = " << histogramName.Data() << ": histogram = " << histogram;
  if ( histogram ) std::cout << ", integral = " << histogram->Integral();
  std::cout << std::endl; 

  if ( !histogram->GetSumw2N() ) histogram->Sumw2();

  if ( histogram->GetDimension() == 1 ) histogram->Rebin(5);

  return histogram;
}
Пример #5
0
// A function that get histogram and sets contents to 0 
// if entries are too small
TH1 * getHisto(TFile * file, const char * name, unsigned int rebin) {
  TObject * h = file->Get(name);
  if(h == 0)
    throw edm::Exception(edm::errors::Configuration) 
      << "Can't find object " << name << "\n";
  TH1 * histo = dynamic_cast<TH1*>(h);
  if(histo == 0)
    throw edm::Exception(edm::errors::Configuration) 
      << "Object " << name << " is of type " << h->ClassName() << ", not TH1\n";
  histo->Rebin(rebin);  
  for(int i = 1; i <= histo->GetNbinsX(); ++i) {
    if(histo->GetBinContent(i) < 0.1) {
      histo->SetBinContent(i, 0.0);
      histo->SetBinError(i, 0.0);
    }
  }
  return histo;
}
Пример #6
0
/** 
 * Draw the Poisson estimate of the occupancy in a given ring.
 * 
 * @param p            List 
 * @param d            Detector
 * @param r            Ring
 * 
 * @return The occupancy (in percent)
 *
 * @deprecated Use QATrender instead
 * @ingroup pwglf_forward_scripts_qa
 */
Double_t
DrawRingOccupancy(TList* p, UShort_t d, Char_t r)
{
  if (!p) return 0;

  TList* ring = static_cast<TList*>(p->FindObject(Form("FMD%d%c",d,r)));
  if (!ring) { 
    Error("DrawOccupancy", "List FMD%d%c not found in %s",d,r,p->GetName());
    return 0;
  }
  
  TH1* corr = static_cast<TH1*>(ring->FindObject("occupancy"));
  if (!corr) { 
    Error("DrawRingOccupancy", "Histogram occupancy not found in FMD%d%c",
	  d, r);
    return 0;
  }
  corr->Rebin(4);

  TPad* pad = static_cast<TPad*>(gPad);
  pad->SetGridy();
  pad->SetGridx();
  pad->SetLogy();
  pad->SetFillColor(0);
    pad->SetRightMargin(0.01);
#if 0
  if (d == 3) { 
    pad->SetPad(pad->GetXlowNDC(), pad->GetYlowNDC(), .99, 
		 pad->GetYlowNDC()+pad->GetHNDC());
    pad->SetRightMargin(0.15);
  }
#endif

  corr->Draw("hist");

  TLatex* ltx = new TLatex(.95, .95, Form("FMD%d%c", d, r));
  ltx->SetNDC();
  ltx->SetTextAlign(33);
  ltx->SetTextSize(.08);
  ltx->Draw();

  return corr->GetMean();
}
TH1* getMonitorElement(TFile* inputFile, const TString& dqmDirectory, const char* dqmSubDirectory, const TString& meName)
{
  TString meName_full = TString("DQMData").Append("/");
  if ( dqmDirectory != "") meName_full.Append(dqmDirectory).Append("/");
  meName_full.Append(dqmSubDirectory).Append("/").Append(meName);
  std::cout << "meName_full = " << meName_full << std::endl;
  
  TH1* me = (TH1*)inputFile->Get(meName_full);
  std::cout << "me = " << me <<  std::endl;
  
  //if ( !me->GetSumw2() ) me->Sumw2();
  me->Sumw2();

  me->Rebin(2);

  me->Scale(1./me->Integral());

  me->SetMaximum(1.);
  me->SetStats(false);

  return me;
}
TCanvas* overlay_Merged_RecoSmeared(const vector<string>& folders, 
								const hist_t& h
								)
{

	TLegend *leg  = new TLegend(0.6,0.65,0.9,0.9);
	leg->SetTextFont(42);
	vector<TH1*> hists;
	
	vector<string> jetcoll;
	jetcoll.push_back("reco");
	jetcoll.push_back("gen");
	jetcoll.push_back("smeared");

	stringstream title;
	const string njets("3-5");
	//const string eta("2.5");
	const string eta("5.0");
	title << njets
			<< " Jets, MHT from Jets with P_{T}>30 GeV, |#eta |<" 
			<< eta << ", L = 10 fb^{-1}" << ";" << h.title ;

	for (unsigned j=0; j< jetcoll.size(); ++j)
	{
		TH1* Hist = 0;
		for (unsigned i = 0; i < folders.size(); ++i)
		{
			stringstream histname;
			histname << folders.at(i) << "/" << jetcoll.at(j) << h.name;
			cout << __LINE__ << ": Looking for hist: " << histname.str().c_str() << endl;
			TH1* htemp = GetHist(histname.str());
			
			if (Hist == 0) Hist = htemp;
			else Hist->Add(htemp);
		}
		
		Hist->Rebin(h.rebin);
		Hist->SetTitle(title.str().c_str());
		Hist->SetMarkerStyle(20+j);
		Hist->SetLineWidth(2);
		Hist->SetStats(0);

		stringstream legname;
		if (j==0) 
		{
			legname << "Reco"; 
		} else if (j==1) 
		{
			legname << "Gen"; 
			Hist->SetLineColor(kBlue);
			Hist->SetMarkerColor(kBlue);
		} else if (j==2)
		{
			legname << "Smeared"; 
			Hist->SetLineColor(kRed);
			Hist->SetMarkerColor(kRed);
		}

		const double sum = Hist->Integral(); 
		legname << " (" << sum << ")";
		if (j!=1) leg->AddEntry(Hist, legname.str().c_str());

		hists.push_back(Hist);

	} //end jetcoll
	
	TH1* ratio = dynamic_cast<TH1*> (hists.at(2)->Clone("ratio"));
	ratio->GetYaxis()->SetTitle("Smeared/Reco");
	ratio->SetTitle("");
	ratio->Divide(hists.at(0));
	ratio->GetYaxis()->SetRangeUser(-0.01,2.01);
	//ratio->SetTickLength (+0.01,"Y");

   //TCanvas *c1 = new TCanvas("c1", "c1",15,60,550,600);
   TCanvas *c1 = new TCanvas("c1");
   c1->Range(0,0,1,1);
   c1->SetBorderSize(2);
   c1->SetFrameFillColor(0);
  
// ------------>Primitives in pad: c1_1
   TPad *c1_1 = new TPad("c1_1", "c1_1",0.01,0.30,0.99,0.99);
   c1_1->Draw();
   c1_1->cd();
   c1_1->SetBorderSize(2);
   c1_1->SetTickx(1);
   c1_1->SetTicky(1);
   c1_1->SetTopMargin(0.1);
   c1_1->SetBottomMargin(0.0);
   //c1_1->SetFrameFillColor(3);
	c1_1->SetLogy();
   
	hists.at(0)->GetYaxis()->CenterTitle(1);
	hists.at(0)->SetLabelFont(42,"XYZ");
	hists.at(0)->SetTitleFont(42,"XYZ");
	hists.at(0)->GetYaxis()->SetTitleOffset(0.8);
	hists.at(0)->SetLabelSize(0.05,"XYZ");
	hists.at(0)->SetTitleSize(0.06,"XYZ");
   hists.at(0)->Draw("P");
   hists.at(2)->Draw("same P");
	leg->Draw();

   c1_1->Modified();
   c1->cd();
  
// ------------>Primitives in pad: c1_2
   TPad *c1_2 = new TPad("c1_2", "c1_2",0.01,0.01,0.99,0.30);
   c1_2->Draw();
   c1_2->cd();
   c1_2->SetBorderSize(2);
   c1_2->SetTickx(1);
   c1_2->SetTicky(1);
   c1_2->SetTopMargin(0.0);
   c1_2->SetBottomMargin(0.24);
   c1_2->SetFrameFillColor(0);
	c1_2->SetGridx();
	c1_2->SetGridy();
   
	ratio->GetYaxis()->SetTitleOffset(0.4);
	ratio->GetXaxis()->SetTitleOffset(0.9);
	ratio->GetYaxis()->CenterTitle(1);
	ratio->GetXaxis()->CenterTitle(1);
	ratio->SetLabelSize(0.125,"XYZ");
	ratio->SetTitleSize(0.125,"XYZ");
//	ratio->SetLabelFont(labelfont,"XYZ");
//	ratio->SetTitleFont(titlefont,"XYZ");
   ratio->GetXaxis()->SetTickLength(0.07);
   ratio->Draw("");
   
   c1_2->Modified();
   c1->cd();
   //c1->Modified();
   //c1->cd();
   //c1->SetSelected(c1);
	return c1;

}
Пример #9
0
//______________________________________________________________________________
void CheckTime(const Char_t* loc)
{
    // Check time.

    Char_t t[256];

    // number of runs
    Int_t nRuns = gFiles->GetSize();

    // create arrays
    const Int_t nCh = 352;
    Double_t** pedPos = new Double_t*[nCh];
    Double_t* runNumbersD = new Double_t[nRuns];
    for (Int_t i = 0; i < nCh; i++) pedPos[i] = new Double_t[nRuns];

    // open the output files
    TFile* fROOTout = new TFile("/tmp/tagger_time.root", "RECREATE");

    // create directories
    for (Int_t i = 0; i < nCh; i++)
    {
        sprintf(t, "%03d", i);
        fROOTout->mkdir(t);
    }
    
    TF1* func = new TF1("func", "gaus(0)+pol1(3)", -1000 , 1000);

    // loop over runs
    for (Int_t i = 0; i < nRuns; i++)
    {   
        // get the file
        TFile* f = (TFile*) gFiles->At(i);

        // extract run number
        Int_t runNumber;
        sprintf(t, "%s/ARHistograms_CB_%%d.root", loc);
        sscanf(f->GetName(), t, &runNumber);
        runNumbersD[i] = (Double_t)runNumber;

        printf("Processing run %d (%d/%d)\n", runNumber, i+1, nRuns);

        fROOTout->cd();
        
        TH2* h2 = (TH2*) f->Get("CaLib_Tagger_Time");

        // loop over channels
        for (Int_t j = 0; j < nCh; j++)
        {
            // load histogram
            sprintf(t, "%03d", j);
            fROOTout->cd(t);
            sprintf(t, "%d_%d", i, j);
            TH1* h = h2->ProjectionX(t, j+1, j+1);
            h->Rebin(2);
            
            sprintf(t, "Run_%d", runNumber);
            TCanvas* c = new TCanvas(t, t);
            TLine* tline = 0;
            
            // check entries
            if (h->GetEntries())
            {
                // fit gaussian to peak
                Double_t maxPos = h->GetXaxis()->GetBinCenter(h->GetMaximumBin());
                func->SetParameters(1, maxPos, 0.5, 1, 0.1);
                func->SetRange(maxPos - 2, maxPos + 2);
                func->SetParLimits(0, 0, 1000);
                for (Int_t k = 0; k < 10; k++)
                    if (!h->Fit(func, "RBQ")) break;

                // save position in file and memory
                maxPos = func->GetParameter(1);
                pedPos[j][i] = maxPos;

                h->GetXaxis()->SetRangeUser(maxPos - 10, maxPos + 10);
                h->Draw();
                
                tline = new TLine(maxPos, 0, maxPos, 10000);
                tline->SetLineColor(kRed);
                tline->SetLineWidth(2);
                tline->Draw();
            }
            else
            {
                h->Draw();
            }

            c->Write(c->GetName(), TObject::kOverwrite);
    
            delete h;
            delete c;
            if (tline) delete tline;
        }
        
        delete h2;
    }
    
    // create pedestal evolution graphs
    fROOTout->cd();
    
    // loop over channels
    for (Int_t j = 0; j < nCh; j++)
    {
        printf("Creating time graph for channel %d\n", j);
        
        TGraph* g = new TGraph(nRuns, runNumbersD, pedPos[j]);
        sprintf(t, "Overview_%03d", j);
        g->SetName(t);
        g->SetTitle(t);
        //g->GetYaxis()->SetRangeUser(1200, 1300);
        g->Write(g->GetName(), TObject::kOverwrite);
        
        delete g;
    }

    printf("Saving output file\n");
    
    delete fROOTout;

    // cleanup
    for (Int_t i = 0; i < nCh; i++) delete [] pedPos[i];
    delete [] pedPos;
    delete [] runNumbersD;
}
Пример #10
0
void comparisonJetMCData(string plot,int rebin){
  string tmp;

  string dir="/gpfs/cms/data/2011/Observables/Approval/";
	
  if (isAngularAnalysis){
    mcfile=dir+"MC_zjets"+version;
    back_w=dir+"MC_wjets"+version;
    back_ttbar=dir+"MC_ttbar"+version;
    WW=dir+"MC_diW"+version;
    ZZ=dir+"MC_siZ"+version;
    WZ=dir+"MC_diWZ"+version;
    datafile=dir+"DATA"+version;
    mcfiletau=dir+"MC_zjetstau"+version;
  }
  // List of files

  TFile *dataf = TFile::Open(datafile.c_str()); //data file
  TFile *mcf = TFile::Open(mcfile.c_str()); //MC file
  TFile *mcftau = TFile::Open(mcfiletau.c_str()); //MC file
  TFile *ttbarf = TFile::Open(back_ttbar.c_str()); //MC background file
  TFile *wf = TFile::Open(back_w.c_str());


  TFile *qcd23emf = TFile::Open(qcd23em.c_str());
  TFile *qcd38emf = TFile::Open(qcd38em.c_str());
  TFile *qcd817emf = TFile::Open(qcd817em.c_str());

  TFile *qcd23bcf = TFile::Open(qcd23bc.c_str());
  TFile *qcd38bcf = TFile::Open(qcd38bc.c_str());
  TFile *qcd817bcf = TFile::Open(qcd817bc.c_str());

  TFile *WZf = TFile::Open(WZ.c_str());
  TFile *ZZf = TFile::Open(ZZ.c_str());
  TFile *WWf = TFile::Open(WW.c_str());


  // Canvas
  if (CanvPlot) delete CanvPlot;
  CanvPlot = new TCanvas("CanvPlot","CanvPlot",0,0,800,600);

  // Getting, defining ...
  dataf->cd("validationJEC");
  if (isMu && isAngularAnalysis) dataf->cd("validationJECmu");
	
  TObject * obj;
  gDirectory->GetObject(plot.c_str(),obj);

  TH1 *data;
  TH2F *data2; 
  TH1D *data3; 

  THStack *hs = new THStack("hs","Total MC");


  int flag=-1;
  if ((data = dynamic_cast<TH1F *>(obj)) ){
    flag=1;
    gROOT->Reset();
    gROOT->ForceStyle();
    gStyle->SetPadRightMargin(0.03);
    gPad->SetLogy(1);
    gPad->Modified();
    gPad->Update();
  }
  if ((data2 = dynamic_cast<TH2F *>(obj)) ){
    flag=2;
    gStyle->SetPalette(1);
    gStyle->SetPadRightMargin(0.15);
    gPad->Modified();
  }



  //===================
  // Dirty jobs :)
  if (flag==1){
    CanvPlot->cd();
    TPad *pad1 = new TPad("pad1","pad1",0.01,0.33,0.99,0.99);
    pad1->Draw();
    pad1->cd();
    pad1->SetTopMargin(0.1);
    pad1->SetBottomMargin(0.01);
    pad1->SetRightMargin(0.1);
    pad1->SetFillStyle(0);
    pad1->SetLogy(1);
    TString str=data->GetTitle();
    if (str.Contains("jet") && !str.Contains("zMass") && !str.Contains("Num") && !str.Contains("Eta") && !str.Contains("Phi") && !str.Contains("eld") && !str.Contains("meanPtZVsNjet")) {
      if (!isAngularAnalysis) rebin=1;
    }

    //======================
    // DATA
    Double_t dataint = data->Integral();
    data->SetLineColor(kBlack);
    data->Rebin(rebin);
    if(str.Contains("nJetVtx")) data->GetXaxis()->SetRangeUser(0,10);	
    if(str.Contains("zMass")) data->GetXaxis()->SetRangeUser(70,110);	
    data->SetMinimum(1.);
    data->Sumw2();

    //Canvas style copied from plotsHistsRatio.C
    data->SetLabelSize(0.0);
    data->GetXaxis()->SetTitleSize(0.00);
    data->GetYaxis()->SetLabelSize(0.07);
    data->GetYaxis()->SetTitleSize(0.08);
    data->GetYaxis()->SetTitleOffset(0.76);
    data->SetTitle("");
    gStyle->SetOptStat(0);

    data->GetYaxis()->SetLabelSize(0.06);
    data->GetYaxis()->SetTitleSize(0.06);
    data->GetYaxis()->SetTitleOffset(0.8);

    data->Draw("E1");


    TLegend* legend = new TLegend(0.725,0.27,0.85,0.72);
    legend->SetFillColor(0);
    legend->SetFillStyle(0);
    legend->SetBorderSize(0);
    legend->SetTextSize(0.060);
    legend->AddEntry(data,"data","p");

    // hack to calculate some yields in restricted regions...
    int num1=0, num2=0, num3=0, num4=0, num5=0;
    if(str.Contains("invMass") && !str.Contains("PF")){
      for(int j=1;j<=data->GetNbinsX();j++){
	num1 += data->GetBinContent(j); 		//conto quante Z ci sono tra 60 e 120 GeV
	if(j>10&&j<=50) num2 += data->GetBinContent(j); // ... tra 70 e 110
	if(j>15&&j<=45) num3 += data->GetBinContent(j); // ... tra 75 e 105
      }
      cout << "\n";
      cout << data->GetNbinsX() <<" Number of bins of the invmass histo\n";
      printf("Number of Z in 60-120 %i --- 70-110 %i --- 75-105 %i \n",num1,num2,num3);
      cout << "\n";
    }
    if(str.Contains("zYieldVsjets") && !str.Contains("Vtx")){
      for(int j=1;j<=data->GetNbinsX();j++){
	num1 += data->GetBinContent(j); 		//conto quante Z
	if(j>1) num2 += data->GetBinContent(j); // ... +1,2,3,4... jets
	if(j>2) num3 += data->GetBinContent(j); // ... +2,3,4... jets
	if(j>3) num4 += data->GetBinContent(j); // ..    if(str=="jet_pT"){
	if(j>4) num5 += data->GetBinContent(j); // ... +4... jets
      }
      cout << "\n";
      cout << data->GetNbinsX() <<" Number of bins of the zYieldVsjets histo\n";
      printf("Number of Z+n jet %i --- >1 %i --- >2 %i --- >3 %i --- >4 %i \n",num1,num2,num3,num4,num5);
      cout << "\n";
    }    

    //======================
    // Z + jets signal
    mcf->cd("validationJEC");
    if (isMu) mcf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcf->cd("validationJEC/");
      if (isMu) mcf->cd("validationJECmu/");
    }

    TH1F* mc;
    gDirectory->GetObject(plot.c_str(),mc);
    TH1F * hsum;
    if(mc){
      hsum =  (TH1F*) mc->Clone();
      hsum->SetTitle("hsum");
      hsum->SetName("hsum");
      hsum->Reset();

      Double_t mcint = mc->Integral();
      mc->SetFillColor(kRed);
      mc->Sumw2();
      if(lumiweights==0) mc->Scale(dataint/mcint);
		
      // Blocco da propagare negli altri MC
      if(zNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) mc->Scale( dataLumi2011pix / (zNumEvents / zjetsXsect));
	    else mc->Scale( dataLumi2011 / (zNumEvents / zjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) mc->Scale( dataLumi2011Apix / (zNumEvents / zjetsXsect));
	      else mc->Scale( dataLumi2011A / (zNumEvents / zjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) mc->Scale( dataLumi2011Bpix / (zNumEvents / zjetsXsect));
	      else mc->Scale( dataLumi2011B / (zNumEvents / zjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) mc->Scale(zjetsScale);
      }

      // fin qui
      if(lumiweights==1) mc->Scale(1./zwemean);  // perche' i Weights non fanno 1...
      mc->Rebin(rebin);
      if(lumiweights==0) mc->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(mc);
      legend->AddEntry(mc,"Z+jets","f");
    }

    //======================
    // ttbar
    ttbarf->cd("validationJEC");
    if (isMu) ttbarf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      ttbarf->cd("validationJEC/");
      if (isMu) ttbarf->cd("validationJECmu/");
    }

    TH1F* ttbar;
    gDirectory->GetObject(plot.c_str(),ttbar);
	
    if(ttbar){
      ttbar->SetFillColor(kBlue);
      ttbar->Sumw2();

      if(ttNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) ttbar->Scale( dataLumi2011pix / (ttNumEvents / ttbarXsect));
	    else ttbar->Scale( dataLumi2011 / (ttNumEvents / ttbarXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) ttbar->Scale( dataLumi2011Apix / (ttNumEvents / ttbarXsect));
	      else ttbar->Scale( dataLumi2011A / (ttNumEvents / ttbarXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) ttbar->Scale( dataLumi2011Bpix / (ttNumEvents / ttbarXsect));
	      else ttbar->Scale( dataLumi2011B / (ttNumEvents / ttbarXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) ttbar->Scale(ttwemean);
      }
      // fin qui
		
      if(lumiweights==1) ttbar->Scale(1./ttwemean);  // perche' i Weights non fanno 1...
      ttbar->Rebin(rebin);
      if(lumiweights==0) ttbar->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(ttbar);
      if(lumiweights==1)legend->AddEntry(ttbar,"ttbar","f");

      //////////
      //Storing the bckgrounds!
      //////////
      cout<<str<<endl;
      if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(ttbar,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(ttbar,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(ttbar,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(ttbar,"jet_pT4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(ttbar,"jet_Multiplicity");
      if(str=="jet_eta") evaluateAndFillBackgrounds(ttbar,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(ttbar,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(ttbar,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(ttbar,"jet_eta4");
      if(str=="HT") evaluateAndFillBackgrounds(ttbar,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(ttbar,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(ttbar,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(ttbar,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(ttbar,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(ttbar,"PhiStar");
      }
    }

    //======================
    // w+jets
    wf->cd("validationJEC");
    if (isMu) wf->cd("validationJECmu/");
    if (isAngularAnalysis) {
      wf->cd("validationJEC/");
      if (isMu) wf->cd("validationJECmu/");      
    }

    TH1F* w;
    gDirectory->GetObject(plot.c_str(),w);
    if(w){

      w->SetFillColor(kViolet+2);
      w->Sumw2();

      if(wNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) w->Scale( dataLumi2011pix / (wNumEvents / wjetsXsect));
	    else w->Scale( dataLumi2011 / (wNumEvents / wjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) w->Scale( dataLumi2011Apix / (wNumEvents / wjetsXsect));
	      else w->Scale( dataLumi2011A / (wNumEvents / wjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) w->Scale( dataLumi2011Bpix / (wNumEvents / wjetsXsect));
	      else w->Scale( dataLumi2011B / (wNumEvents / wjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) w->Scale(wwemean);
      }
      // fin qui
		
      if(lumiweights==1) w->Scale(1./wwemean);  // perche' i Weights non fanno 1...
      w->Rebin(rebin);
      if(lumiweights==0) w->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(w);
      if(lumiweights==1)legend->AddEntry(w,"W+jets","f");
    }

    //======================
    // wz+jets
    WZf->cd("validationJEC");
    if (isMu) WZf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      WZf->cd("validationJEC/");
      if (isMu) WZf->cd("validationJECmu/");
    }

    TH1F* wz;
    gDirectory->GetObject(plot.c_str(),wz);
    if(wz){
      wz->SetFillColor(kYellow+2);
      wz->Sumw2();

      if(wzEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) wz->Scale( dataLumi2011pix / (wzEvents / WZXsect));
	    else wz->Scale( dataLumi2011 / (wzEvents / WZXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) wz->Scale( dataLumi2011Apix / (wzEvents / WZXsect));
	      else wz->Scale( dataLumi2011A / (wzEvents / WZXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) wz->Scale( dataLumi2011Bpix / (wzEvents / WZXsect));
	      else wz->Scale( dataLumi2011B / (wzEvents / WZXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) wz->Scale(wzjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) wz->Scale(1./wzwemean);  // perche' i Weights non fanno 1...
      wz->Rebin(rebin);
      if(lumiweights==0) wz->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(wz);
      legend->AddEntry(wz,"WZ+jets","f");


      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(wz,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(wz,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(wz,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(wz,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(wz,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(wz,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(wz,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(wz,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(wz,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(wz,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(wz,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(wz,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(wz,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(wz,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(wz,"PhiStar");
     }
    }
    
		
    //======================
    // zz+jets
    ZZf->cd("validationJEC");
    if (isMu) ZZf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      ZZf->cd("validationJEC/");
      if (isMu) ZZf->cd("validationJECmu/");
    }

    TH1F* zz;
    gDirectory->GetObject(plot.c_str(),zz);
    if(zz){
      zz->SetFillColor(kOrange+2);
      zz->Sumw2();

      if(zzEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) zz->Scale( dataLumi2011pix / (zzEvents / ZZXsect));
	    else zz->Scale( dataLumi2011 / (zzEvents / ZZXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) zz->Scale( dataLumi2011Apix / (zzEvents / ZZXsect));
	      else zz->Scale( dataLumi2011A / (zzEvents / ZZXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) zz->Scale( dataLumi2011Bpix / (zzEvents / ZZXsect));
	      else zz->Scale( dataLumi2011B / (zzEvents / ZZXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) zz->Scale(zzjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) zz->Scale(1./zzwemean);  // perche' i Weights non fanno 1...
      zz->Rebin(rebin);
      if(lumiweights==0) zz->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(zz);
      legend->AddEntry(zz,"ZZ+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(zz,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(zz,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(zz,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(zz,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(zz,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(zz,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(zz,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(zz,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(zz,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(zz,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(zz,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(zz,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(zz,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(zz,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(zz,"PhiStar");
     }  
    }
    
    //======================
    // ww+jets
    WWf->cd("validationJEC");
    if (isMu) WWf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      WWf->cd("validationJEC/");
      if (isMu) WWf->cd("validationJECmu/");
    }

    TH1F* ww;
    gDirectory->GetObject(plot.c_str(),ww);
    if(ww){
      ww->SetFillColor(kBlack);
      ww->Sumw2();

      if(wwEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) ww->Scale( dataLumi2011pix / (wwEvents / WWXsect));
	    else ww->Scale( dataLumi2011 / (wwEvents / WWXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) ww->Scale( dataLumi2011Apix / (wwEvents / WWXsect));
	      else ww->Scale( dataLumi2011A / (wwEvents / WWXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) ww->Scale( dataLumi2011Bpix / (wwEvents / WWXsect));
	      else ww->Scale( dataLumi2011B / (wwEvents / WWXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) ww->Scale(wwjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) ww->Scale(1./wwwemean);  // perche' i Weights non fanno 1...
      ww->Rebin(rebin);
      if(lumiweights==0) ww->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(ww);
      legend->AddEntry(ww,"WW+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(ww,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(ww,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(ww,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(ww,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(ww,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(ww,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(ww,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(ww,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(ww,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(ww,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(ww,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(ww,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(ww,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(ww,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(ww,"PhiStar");
     }
    }

    /// Tau 

   //======================

    mcftau->cd("validationJEC");
    if (isMu) mcftau->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcftau->cd("validationJEC/");
      if (isMu) mcftau->cd("validationJECmu/");
    }

    TH1F* tau;
    gDirectory->GetObject(plot.c_str(),tau);
    if(tau){
      tau->SetFillColor(kGreen);
      tau->Sumw2();

      if(zNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) tau->Scale( dataLumi2011pix / (zNumEvents / zjetsXsect));
	    else tau->Scale( dataLumi2011 / (zNumEvents / zjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) tau->Scale( dataLumi2011Apix / (zNumEvents / zjetsXsect));
	      else tau->Scale( dataLumi2011A / (zNumEvents / zjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) tau->Scale( dataLumi2011Bpix / (zNumEvents / zjetsXsect));
	      else tau->Scale( dataLumi2011B / (zNumEvents / zjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) tau->Scale(zjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) tau->Scale(1./zwemean);  // perche' i Weights non fanno 1...
      tau->Rebin(rebin);
      if(lumiweights==0) tau->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      tau->Scale(1./1000.); //aaaaaaa
      hsum->Add(tau);
      legend->AddEntry(tau,"#tau#tau+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(tau,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(tau,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(tau,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(tau,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(tau,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(tau,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(tau,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(tau,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(tau,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(tau,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(tau,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(tau,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(tau,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(tau,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(tau,"PhiStar");
     }
    }


    /////////
    // Print the bkg contributions
    ////////

    for(int j=0;j<bckg_leadingJetPt.size();j++){      
      cout<<bckg_leadingJetPt[j]<<endl;
    }	

    //======================
    // QCD EM enriched
    qcd23emf->cd("validationJEC");
    TH1F* qcd23emp;
    gDirectory->GetObject(plot.c_str(),qcd23emp);

    if(qcd23emp){
      TH1D * qcdTotEM =  (TH1D*) qcd23emp->Clone(); 
      qcdTotEM->SetTitle("qcd em");
      qcdTotEM->SetName("qcd em");
      qcdTotEM->Reset();
      qcdTotEM->Rebin(rebin);

      qcd38emf->cd("validationJEC");
      TH1F* qcd38emp;
      gDirectory->GetObject(plot.c_str(),qcd38emp);


      qcd817emf->cd("validationJEC");
      TH1F* qcd817emp;
      gDirectory->GetObject(plot.c_str(),qcd817emp);

      qcd23emp->Rebin(rebin);
      qcd23emp->Sumw2();
      qcd23emp->Scale(qcd23emScale); 
      qcd38emp->Rebin(rebin);
      qcd38emp->Sumw2();
      qcd38emp->Scale(qcd38emScale); 
      qcd817emp->Rebin(rebin);
      qcd817emp->Sumw2();
      qcd817emp->Scale(qcd817emScale); 

      qcdTotEM->SetFillColor(kOrange+1);
      qcdTotEM->Add(qcd23emp);
      qcdTotEM->Add(qcd38emp);
      qcdTotEM->Add(qcd817emp);

      hsum->Add(qcdTotEM);

      //if(lumiweights==1)legend->AddEntry(qcdTotEM,"QCD em","f");
    }

    //======================
    // QCD bc
    qcd23bcf->cd("validationJEC");
    TH1F* qcd23bcp;
    TH1D * qcdTotBC;
    bool  qcdbcempty=true;
    gDirectory->GetObject(plot.c_str(),qcd23bcp);

    if(qcd23bcp){
      qcdTotBC =  (TH1D*) qcd23bcp->Clone(); 
      qcdTotBC->SetTitle("qcd bc");
      qcdTotBC->SetName("qcd bc");
      qcdTotBC->Reset();
      qcdTotBC->Rebin(rebin);

      qcd38bcf->cd("validationJEC");
      TH1F* qcd38bcp;
      gDirectory->GetObject(plot.c_str(),qcd38bcp);

      qcd817bcf->cd("validationJEC");
      TH1F* qcd817bcp;
      gDirectory->GetObject(plot.c_str(),qcd817bcp);

      qcd23bcp->Rebin(rebin);
      qcd23bcp->Sumw2();
      qcd23bcp->Scale(qcd23bcScale); 
      qcd38bcp->Rebin(rebin);
      qcd38bcp->Sumw2();
      qcd38bcp->Scale(qcd38bcScale); 
      qcd817bcp->Rebin(rebin);
      qcd817bcp->Sumw2();
      qcd817bcp->Scale(qcd817bcScale); 

      qcdTotBC->SetFillColor(kGreen+2);
      qcdTotBC->Add(qcd23bcp);
      qcdTotBC->Add(qcd38bcp);
      qcdTotBC->Add(qcd817bcp);

      hsum->Add(qcdTotBC);
      if (qcdTotBC->GetEntries()>0) qcdbcempty=false; 

      //if(lumiweights==1)legend->AddEntry(qcdTotBC,"QCD bc","f");
    }

    //======================
    // Add here other backgrounds


    //======================
    // Stacked Histogram
    //if(qcd23em) 	hs->Add(qcdTotEM);
    if(!qcdbcempty) 	hs->Add(qcdTotBC);
    if(w)  	        hs->Add(w);
    if (ww)         hs->Add(ww);
    if(tau)		hs->Add(tau); //Z+Jets
    if (zz)         hs->Add(zz);
    if (wz)         hs->Add(wz);
    if (ttbar)	hs->Add(ttbar);
    if(mc)		hs->Add(mc); //Z+Jets

    // per avere le statistiche
    if(lumiweights==1) hsum->Draw("HISTO SAME");


    //======================
    // Setting the stats
    //pad1->Update(); // altrimenti non becchi la stat
    
    //TPaveStats *r2;
    //if(lumiweights==0) r2 = (TPaveStats*)mc->FindObject("stats");
    //if(lumiweights==1) r2 = (TPaveStats*)hsum->FindObject("stats");
    //r2->SetY1NDC(0.875);     //Uncomment if you wonna add your statistics in the top right corner
    //r2->SetY2NDC(0.75); 
    //r2->SetTextColor(kRed);
		
    if(lumiweights==1) hs->Draw("HISTO SAME");
    gPad->RedrawAxis();
    data->Draw("E1 SAME");
    //r2->Draw(); //here to reactivate the stats
    legend->Draw();
    TLegend* lumi = new TLegend(0.45,0.3,0.75,0.2);
    lumi->SetFillColor(0);
    lumi->SetFillStyle(0);
    lumi->SetBorderSize(0);
    //lumi->AddEntry((TObject*)0,"#int L dt =4.9 1/fb","");
    lumi->Draw();
    string channel;
    if (isMu) channel="Z#rightarrow#mu#mu";
    if (!isMu) channel="Z#rightarrow ee";
    TLatex *latexLabel=CMSPrel(4.890,channel,0.55,0.85); // make fancy label
    latexLabel->Draw("same");

    CanvPlot->Update();

	


    //===============//
    // RATIO DATA MC //
    //===============//
    CanvPlot->cd();
    TPad *pad2 = new TPad("pad2","pad2",0.01,0.01,0.99,0.32);
    pad2->Draw();
    pad2->cd();
    pad2->SetTopMargin(0.01);
    pad2->SetBottomMargin(0.3);
    pad2->SetRightMargin(0.1);
    pad2->SetFillStyle(0);

    TH1D * ratio =  (TH1D*) data->Clone();
    ratio->SetTitle("");
    ratio->SetName("ratio");
    ratio->Reset();

    ratio->Sumw2();
    //data->Sumw2();
    hsum->Sumw2(); // FIXME controlla che sia corretto questo... 
    ratio->SetMarkerSize(.5);
    ratio->SetLineColor(kBlack);
    ratio->SetMarkerColor(kBlack);
    //gStyle->SetOptStat("m");
    TH1F* sumMC;

    hs->Draw("nostack"); 
 
   sumMC=(TH1F*) hs->GetHistogram();
    cout<<sumMC->GetEntries()<<endl;
    ratio->Divide(data,hsum,1.,1.);
    ratio->GetYaxis()->SetRangeUser(0.5,1.5);
    ratio->SetMarkerSize(0.8);
    //pad2->SetTopMargin(1);

   //Canvas style copied from plotsHistsRatio.C
    ratio->GetYaxis()->SetNdivisions(5);
    ratio->GetXaxis()->SetTitleSize(0.14);
    ratio->GetXaxis()->SetLabelSize(0.14);
    ratio->GetYaxis()->SetLabelSize(0.11);
    ratio->GetYaxis()->SetTitleSize(0.11);
    ratio->GetYaxis()->SetTitleOffset(0.43);
    ratio->GetYaxis()->SetTitle("ratio data/MC");   

    ratio->Draw("E1");
		
    TLine *OLine = new TLine(ratio->GetXaxis()->GetXmin(),1.,ratio->GetXaxis()->GetXmax(),1.);
    OLine->SetLineColor(kBlack);
    OLine->SetLineStyle(2);
    OLine->Draw();
 
    TLegend* label = new TLegend(0.60,0.9,0.50,0.95);
    label->SetFillColor(0);
    label->SetFillStyle(0);
    label->SetBorderSize(0);
    //horrible mess
    double binContent = 0;
    double binSum = 0;
    double weightSum = 0;
    double binError = 1;
    double totalbins = ratio->GetSize() -2;
    for(unsigned int bin=1;bin<=totalbins;bin++){
      binContent = ratio->GetBinContent(bin);
      binError = ratio->GetBinError(bin);
      if(binError!=0){
	binSum += binContent/binError;
	weightSum += 1./binError;
      }
    }
    double ymean = binSum / weightSum;
    //double ymean = ratio->GetMean(2);
    stringstream sYmean;
    sYmean << ymean;
    string labeltext=sYmean.str()+" mean Y";
    //label->AddEntry((TObject*)0,labeltext.c_str(),""); // mean on Y
    //label->Draw();
		
    //TPaveStats *r3 = (TPaveStats*)ratio->FindObject("stats");
    //r3->SetX1NDC(0.01);
    //r3->SetX2NDC(0.10); 
    //r3->SetY1NDC(0.20);
    //r3->SetY2NDC(0.50); 
    //gStyle->SetOptStat("mr");
    //r3->SetTextColor(kWhite);
    //r3->SetLineColor(kWhite);
    //r3->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+".png";
    CanvPlot->Print(tmp.c_str());

  }
  else if (flag==2){
    //CanvPlot.Divide(2,1);
    //CanvPlot.cd(1);

    // data
    dataf->cd("validationJEC");
    if (isMu && isAngularAnalysis) dataf->cd("validationJECmu");

    gDirectory->GetObject(plot.c_str(),data2);
    data2->Draw("COLZ");

    gPad->Update(); // altrimenti non becchi la stat
    TPaveStats *r1 = (TPaveStats*)data2->FindObject("stats");
    //r1->SetX1NDC(0.70); Uncomment if you wonna draw your stat in the top right corner
    //r1->SetX2NDC(0.85); 
    //r1->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+"data.png";
    CanvPlot->Print(tmp.c_str());


    //CanvPlot.cd(2);
    // montecarlo
    mcf->cd("validationJEC");
    if (isMu) mcf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcf->cd("validationJEC/");
      if (isMu) mcf->cd("validationJECmu/");
    }

    gDirectory->GetObject(plot.c_str(),data2);

    data2->SetMinimum(1);
    data2->Draw("COLZ");

    gPad->Update(); // altrimenti non becchi la stat
    //TPaveStats *r2 = (TPaveStats*)data2->FindObject("stats");
    //r2->SetX1NDC(0.70);
    //r2->SetX2NDC(0.85); 
    //r2->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+"mc.png";
    CanvPlot->Print(tmp.c_str());
  }
  //	else { cout << "You're getting an exception! Most likely there's no histogram here... \n"; }

  delete data;
  delete data2;
  delete hs;
  //delete CanvPlot;

  dataf->Close();
  mcf->Close();
  ttbarf->Close();
  wf->Close();
  qcd23emf->Close();
  qcd38emf->Close();
  qcd817emf->Close();
  qcd23bcf->Close();
  qcd38bcf->Close();
  qcd817bcf->Close();
  WZf->Close();
  ZZf->Close();
  
  if (isAngularAnalysis){
    if (bckg_leadingJetPt.size()>0 && bckg_2leadingJetPt.size()>0 && bckg_3leadingJetPt.size()>0 && bckg_4leadingJetPt.size()>0  && bckg_JetMultiplicity.size()>0 && bckg_HT.size()>0 && bckg_leadingJetEta.size()>0 && bckg_PhiStar.size()>0 && cold){
      fzj->cd();
      treeBKG_->Fill();
      treeBKG_->Write();
      TH1F *leadhisto=new TH1F("leadhisto","leading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto2=new TH1F("leadhisto2","subleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto3=new TH1F("leadhisto3","subsubleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto4=new TH1F("leadhisto4","subsubsubleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *multiphisto=new TH1F("multiphisto","jet multiplicity background contribution",bckg_JetMultiplicity.size(),0,bckg_JetMultiplicity.size());

      TH1F *HT=new TH1F("HT","HT background contribution",bckg_HT.size(),0,bckg_HT.size());
      TH1F *HT1=new TH1F("HT1","HT background contribution when >= 1 jet",bckg_HT1.size(),0,bckg_HT1.size());
      TH1F *HT2=new TH1F("HT2","HT background contribution when >= 2 jets",bckg_HT2.size(),0,bckg_HT2.size());
      TH1F *HT3=new TH1F("HT3","HT background contribution when >= 3 jets",bckg_HT3.size(),0,bckg_HT3.size());
      TH1F *HT4=new TH1F("HT4","HT background contribution when >= 4 jets",bckg_HT4.size(),0,bckg_HT4.size());

      TH1F *leadhistoeta=new TH1F("leadhistoeta","leading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta2=new TH1F("leadhistoeta2","subleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta3=new TH1F("leadhistoeta3","subsubleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta4=new TH1F("leadhistoeta4","subsubsubleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());

      TH1F *PhiStar=new TH1F("PhiStar","PhiStar background contribution",bckg_PhiStar.size(),0,bckg_PhiStar.size());

      for (int i=0; i< bckg_leadingJetPt.size(); i++){
	leadhisto->Fill(i,bckg_leadingJetPt[i]);
	leadhisto2->Fill(i,bckg_2leadingJetPt[i]);
	leadhisto3->Fill(i,bckg_3leadingJetPt[i]);
	leadhisto4->Fill(i,bckg_4leadingJetPt[i]);
      }
      leadhisto->Write();
      leadhisto2->Write();
      leadhisto3->Write();
      leadhisto4->Write();

      for (int i=0; i< bckg_leadingJetEta.size(); i++){
	leadhistoeta->Fill(i,bckg_leadingJetEta[i]);
	leadhistoeta2->Fill(i,bckg_2leadingJetEta[i]);
	leadhistoeta3->Fill(i,bckg_3leadingJetEta[i]);
	leadhistoeta4->Fill(i,bckg_4leadingJetEta[i]);
      }
      leadhistoeta->Write();
      leadhistoeta2->Write();
      leadhistoeta3->Write();
      leadhistoeta4->Write();
      //fzj->Close();

      for (int i=0; i< bckg_JetMultiplicity.size(); i++){
	multiphisto->Fill(i,bckg_JetMultiplicity[i]);
      }
      multiphisto->Write();
      
      ///////////////

      for (int i=0; i< bckg_HT.size(); i++){
	HT->Fill(i,bckg_HT[i]);
      }
      HT->Write();
      
      for (int i=0; i< bckg_HT1.size(); i++){
	HT1->Fill(i,bckg_HT1[i]);
      }
      HT1->Write();
      
      for (int i=0; i< bckg_HT2.size(); i++){
	HT2->Fill(i,bckg_HT2[i]);
      }
      HT2->Write();
      
      for (int i=0; i< bckg_HT3.size(); i++){
	HT3->Fill(i,bckg_HT3[i]);
      }
      HT3->Write();
      
      for (int i=0; i< bckg_HT4.size(); i++){
	HT4->Fill(i,bckg_HT4[i]);
      }
      HT4->Write();

      //Phi star
      for (int i=0; i< bckg_PhiStar.size(); i++){
	PhiStar->Fill(i,bckg_PhiStar[i]);
      }
      PhiStar->Write();

    cold=false;
    }
  }
  return;
}
Пример #11
0
void makePassFail_QCDMC(const string numeHistName, const string denoHistName, 
			const string title, const string HTbinlabel, 
			const string signalHistName, const string controlHistName,
			const pair<unsigned, unsigned>& jetBin,
			const float fitrange_xmin = 50, const float fitrange_xmax = 150) 
{
	incMHTBins.clear();
	for (int i=0; i<nMHTbins; ++i) incMHTBins.push_back(arrMHTbins[i]);
	const bool logScale = true;
	const float scaleTo = fDATA_LUMI; // pb-1

	TH1 *Hist_pass = GetHist(numeHistName, scaleTo);
	TH1 *Hist_fail = GetHist(denoHistName, scaleTo);

	Hist_pass->SetMarkerColor(kBlack);
	Hist_pass->SetLineColor(kBlack);
	/*new TCanvas();
	gPad->SetLogy();
	Hist_pass->SetLineColor(kRed);
	Hist_pass->SetMarkerColor(kRed);
	Hist_pass->DrawCopy();
	Hist_fail->DrawCopy("same");
	*/
	//gPad->Print("range.eps");
	cout << __LINE__ << ": Integrals= " << Hist_fail->Integral() << "/" << Hist_pass->Integral() << endl;
	if (Hist_fail->GetEntries()<1 || Hist_pass->GetEntries()<1) 
	{
		cout << __LINE__ << ": not enough intries to make the plots!!! " << Hist_fail->Integral() << "/" << Hist_pass->Integral() << endl;
		return;
	}

//	DumpHist(Hist_pass);
//	DumpHist(Hist_fail);

	Hist_pass->Divide(Hist_fail);

//	cout << ">>>>>>> AFTER DIVIDE <<<<< " << endl;
//	DumpHist(Hist_pass);
	const int maxbin = Hist_pass->GetMaximumBin();
	const double max = Hist_pass->GetBinContent(maxbin);
	//Hist_pass->GetYaxis()->SetRangeUser(-0.05, max+0.05);


	//fit range
	//const float fitrange_xmin = 50, fitrange_xmax = 120;
	stringstream newtitle;
	//newtitle << "Fit Range " << fitrange_xmin << "--" << fitrange_xmax << title;
	//newtitle << title << " (fit range = " <<  fitrange_xmin << "--" << fitrange_xmax << "), c = " << CONST_C << ";MHT [GeV];Ratio (r);";
	newtitle << title << " (fit range = " <<  fitrange_xmin << "-" << fitrange_xmax << ");MHT [GeV];Ratio (r);";


	gStyle->SetOptStat(0);	
	new TCanvas();
	//gPad->SetGridy();
	gPad->SetTickx();
	if (logScale) gPad->SetLogy();
	Hist_pass->SetLineColor(9);
	Hist_pass->SetTitle(newtitle.str().c_str());
	Hist_pass->SetLineWidth(2);

	gStyle->SetOptFit(1);
	//Hist_pass->SetStats(0);
	Hist_pass->Draw();
	//return;

	//do fittings exp and gaus
	/*float C_UPLIMIT = 0.04;
	float C_LOLIMIT = 0.02;
	if (jetBin.first == 2 && jetBin.second == 2)
	{
		C_UPLIMIT = 0.00235;
		C_LOLIMIT = 0.00232;
	} else if (jetBin.first == 3 && jetBin.second == 5)
	{
		C_UPLIMIT = 0.03;
		C_LOLIMIT = 0.025;
	} else if (jetBin.first == 6 && jetBin.second == 7)
	{
		C_UPLIMIT = 0.2;
		C_LOLIMIT = 0.17;
	} else if (jetBin.first == 8)
	{
		C_UPLIMIT = 0.4;
		C_LOLIMIT = 0.2;
	}
	*/

	const float mean_c_initial = GetAvgVal(Hist_pass, 350);

	//do fittings exp and gaus
	const float C_UPLIMIT = mean_c_initial+0.0001; //this only to get this values on the stat box
	const float C_LOLIMIT = mean_c_initial-0.0001;



	Hist_pass->SetMinimum(C_LOLIMIT/10);


	TF1 *expFit=new TF1("fit_1",expFitFunc,fitrange_xmin,fitrange_xmax,3);
	expFit->SetParameter(0,0.09);
	expFit->SetParameter(1,-0.0002);
	expFit->SetParameter(2,CONST_C);
	expFit->SetParLimits(2,C_LOLIMIT, C_UPLIMIT);
	Hist_pass->Fit(expFit,"E0","",fitrange_xmin, fitrange_xmax);
	gPad->Modified();
	gPad->Update();
	TPaveStats *e_stats = (TPaveStats*) Hist_pass->FindObject("stats");
	e_stats->SetTextColor(kRed);
	TPaveStats *exp_stats = (TPaveStats*) e_stats->Clone("exp_stats");

	TF1 *expFit2=new TF1("fit_2",expFitFunc,50,1000.0,3);
	expFit2->SetParameter(0,expFit->GetParameter(0));
	expFit2->SetParameter(1,expFit->GetParameter(1));
	expFit2->SetParameter(2,expFit->GetParameter(2));
	expFit2->SetLineColor(kRed+1);
	expFit2->SetLineWidth(2);

	//for unceratinty on c
	TF1 *expFit_sigma = new TF1("Exp_sigma",expFitFunc_Cup,50,1000.0,3);
	expFit_sigma->SetParameter(0,expFit->GetParameter(0));
	expFit_sigma->SetParameter(1,expFit->GetParameter(1));
	expFit_sigma->SetParameter(2,expFit->GetParameter(2)); //%100 error
	expFit_sigma->SetParLimits(2,C_LOLIMIT/2., C_UPLIMIT*2.);
	Hist_pass->Fit(expFit_sigma,"E0","",fitrange_xmin, fitrange_xmax);


	TF1 *gausFit=new TF1("fit_3",gausFitFunc,fitrange_xmin, fitrange_xmax,3);
	gausFit->SetParameter(0,0.09); 
	gausFit->SetParameter(1,-0.0002);
	gausFit->SetParameter(2,CONST_C);
	gausFit->SetParLimits(2,C_LOLIMIT,C_UPLIMIT);
	gausFit->SetLineColor(kGreen-2);
	Hist_pass->Fit(gausFit,"E0","", fitrange_xmin, fitrange_xmax);
	gPad->Modified();
	gPad->Update();
	TPaveStats *gaus_stats = (TPaveStats*) Hist_pass->FindObject("stats");
	gaus_stats->SetTextColor(kGreen);
	//TPaveStats *gaus_stats = (TPaveStats*) g_stats->Clone("gaus_stats");

	//TF1 *gausFit2=new TF1("fit_4",gausFitFunc,50,1000.0,2);
	TF1 *gausFit2=new TF1("fit_4",gausFitFunc,50,1000.0,3);
	gausFit2->SetParameter(0,gausFit->GetParameter(0)); 
	gausFit2->SetParameter(1,gausFit->GetParameter(1));
	gausFit2->SetParameter(2,gausFit->GetParameter(2));
	gausFit2->SetLineColor(kGreen);
	gausFit2->SetLineWidth(2);

	//for unceratinty on c
	TF1 *gausFit_sigma=new TF1("Gaus_sigma",gausFitFunc_Cup,50,1000.0,3);
	gausFit_sigma->SetParameter(0,gausFit->GetParameter(0)); 
	gausFit_sigma->SetParameter(1,gausFit->GetParameter(1));
	gausFit_sigma->SetParameter(2,gausFit->GetParameter(2) * 2); //100% error
	gausFit_sigma->SetParLimits(2,C_LOLIMIT/2., C_UPLIMIT*2.);
	Hist_pass->Fit(gausFit_sigma,"E0","", fitrange_xmin, fitrange_xmax);


	gausFit2->Draw("same");
	expFit2->Draw("same");
	/*gausFit_sigma->SetLineStyle(10);
	gausFit_sigma->SetLineColor(gausFit2->GetLineColor());
	expFit_sigma->SetLineStyle(10);
	expFit_sigma->SetLineWidth(2);
	expFit_sigma->SetLineColor(expFit2->GetLineColor());
	gausFit_sigma->Draw("same");
	expFit_sigma->Draw("same");
*/
	//TLegend *leg  = new TLegend(0.7,0.8,0.9,0.9);
	TLegend *leg  = new TLegend(0.7,0.7,0.9,0.9);
	leg->AddEntry(gausFit2,"Gaussian");
	leg->AddEntry(expFit2,"Exponential");
	leg->SetTextFont(42);
	leg->Draw();

	const float xmin=0.2, xmax=0.45, ymin=0.7, ymax=0.9;
	gaus_stats->SetX1NDC(xmin);
	gaus_stats->SetX2NDC(xmax);
	gaus_stats->SetY1NDC(ymin);
	gaus_stats->SetY2NDC(ymax);
	gaus_stats->Draw("same");
	exp_stats->SetX1NDC(xmax);
	exp_stats->SetX2NDC(xmax+0.25);
	exp_stats->SetY1NDC(ymin);
	exp_stats->SetY2NDC(ymax);
	exp_stats->Draw("same");

	//fit quality
	stringstream gaus_fit_res, exp_fit_res;
	const float gausFit_goodness =  gausFit->GetChisquare()/gausFit->GetNDF();
	gaus_fit_res << "#chi^{2}/ndof = " << gausFit->GetChisquare()
			 << "/"<< gausFit->GetNDF() << " = " << gausFit_goodness;
	const float expFit_goodness =  expFit->GetChisquare()/expFit->GetNDF();
	exp_fit_res << "#chi^{2}/ndof = " << expFit->GetChisquare()
			 << "/"<< expFit->GetNDF() << " = " << expFit_goodness;

	cout << gaus_fit_res.str() << endl;
	cout << exp_fit_res.str() << endl;

	TPaveText *pt1 = new TPaveText(0.5,0.8,0.7,0.9);
	pt1->AddText(gaus_fit_res.str().c_str());
	pt1->AddText(exp_fit_res.str().c_str());
//	pt1->Draw("same");

	//stringstream epsname;
	//epsname << "factnomht/HTbin" << HTbin << "_fitrange_" << fitrange_xmin << "to" << fitrange_xmax << ".eps";
	//epsname << "factnomht_" << HTbinlabel << ".eps";
	//gPad->Print(epsname.str().c_str());
	gPad->Print("ratios.eps");
	//return;

	 //make a predicion
	TH1 *sigHist      = GetHist(signalHistName, scaleTo);
	TH1 *controlHist  = GetHist(controlHistName, scaleTo);

	//temp hack to get # of bins the same for easy debugging
	sigHist->Rebin(2);

	cout << red << "sigHist/controlHist bins = " << sigHist->GetNbinsX() << "/" << controlHist->GetNbinsX() << clearatt << endl; 
//	new TCanvas();
//	sigHist->SetLineColor(kRed);
//	sigHist->Rebin(50);
//	controlHist->Rebin(50);
//	sigHist->Draw();
//	controlHist->Draw("same");


	//collect results
/*	Predictions_t pred_gaus       = GetPredictions(controlHist, gausFit2, sigHist); 
	Predictions_t pred_gaus_sigma = GetPredictions(controlHist, gausFit_sigma, sigHist); 
	Predictions_t pred_exp        = GetPredictions(controlHist, expFit2, sigHist); 
	Predictions_t pred_exp_sigma  = GetPredictions(controlHist, expFit_sigma, sigHist); 

//	PrintExclResults(pred_gaus);
//	PrintExclResults(pred_exp);
	PrintExclResults(pred_gaus, pred_exp, pred_gaus_sigma, pred_exp_sigma);
*/
	/*****************************************/
	// TEMP HACK TO GET RESULTS for all HT bins 
	// using these inclusive fits
	/*****************************************/
	vector<pair<float, float> > htBins_temp;
	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);	

	htBins_temp.push_back(htbin1);
	htBins_temp.push_back(htbin2);
	htBins_temp.push_back(htbin3);
	htBins_temp.push_back(htbin4);
	htBins_temp.push_back(htbin5);

	TFile file("qcd_all.root");
	if (file.IsZombie()) 
	{ 
		cout << __FUNCTION__ << ":" << __LINE__ 
				<< "File to get exlcusive HT prediction is not found!" << endl;assert (false);
	}

	for (unsigned htbin=0; htbin<htBins_temp.size(); ++htbin)
	{
		stringstream folder, control_hist_name, signal_hist_name;
		folder << "Hist/Njet" << jetBin.first << "to" << jetBin.second 
			<< "HT"   << htBins_temp.at(htbin).first << "to" << htBins_temp.at(htbin).second 
			<< "MHT0to8000";
		control_hist_name << folder.str() << "/smeared_failFineBin1"; 
		signal_hist_name << folder.str() << "/smear_signalFineBin"; 
		TH1* control_hist = (TH1*) (file.Get(control_hist_name.str().c_str())); 
		if (control_hist == NULL) { 
			cout << __LINE__ << ": control hist " << control_hist_name.str() << " not found for htbin " << htBins_temp.at(htbin).first 
				<< "-" << htBins_temp.at(htbin).second << endl; 
			assert(false);		
		} 
		TH1* signal_hist = (TH1*) (file.Get(signal_hist_name.str().c_str())); 
		if (signal_hist == NULL) { cout << __LINE__ << ": signal hist not found for htbin " << htBins_temp.at(htbin).first << "-" << htBins_temp.at(htbin).second << endl; } 

		control_hist->Print();
		signal_hist->Print();

		//temp hack to get # of bins the same for easy debugging
		signal_hist->Rebin(2);

		Predictions_t pred_gaus       = GetPredictions(control_hist, gausFit2, signal_hist); 
		Predictions_t pred_gaus_sigma = GetPredictions(control_hist, gausFit_sigma, signal_hist); 
		Predictions_t pred_exp        = GetPredictions(control_hist, expFit2, signal_hist); 
		Predictions_t pred_exp_sigma  = GetPredictions(control_hist, expFit_sigma, signal_hist); 

		cout << ">>>>>>>>>>>>>>> PREDICTIONS FOR " << jetBin.first << "-" << jetBin.second 
					<< ", HT=" << htBins_temp.at(htbin).first << "-" << htBins_temp.at(htbin).second << endl;
		PrintExclResults(pred_gaus, pred_exp, pred_gaus_sigma, pred_exp_sigma);
	}

	file.Close();

}
Пример #12
0
 void MejMassFits(TH1F* HistName) {

   // set up RooFit
   gSystem->Load("libRooFit");
   using namespace RooFit;
   
   gROOT->SetStyle("Plain");
   
   // get histogram and convert it to a RooFit understandble format
   TH1* hh = HistName->Clone("hh");
   hh->Rebin(1);
   RooRealVar Mej("Mej","Mej LQ",40.,1000,"GeV");
   RooDataHist RDH_data("RDH_data","dataset with Mej mass",Mej,hh);
   RooHistPdf Pdf_data("dataMej","dataMej" ,RooArgList(Mej),RDH_data); 

   //gen data accordingly to histo
   RooDataSet *data = Pdf_data.generate(Mej,5000) ;
   
   // make signal function
   //    RooRealVar mean("mean","mean",250,200,300);
   //    RooRealVar sigma("sigma","sigma",100,0.,200.);
   //    RooGaussian sig("sig","signal pdf",Mej,mean,sigma);
   
   RooRealVar mean("mean","mean",650,600.,700.);
   RooRealVar sigma("sigma","sigma",30,0.,100);
   RooRealVar alpha("alpha","alpha",0.1,0.,1.);
   RooRealVar n("n","n",0.1,0.,+100);
   RooCBShape sig("sig","signal pdf",Mej,mean,sigma,alpha,n);


   // make background function
   RooRealVar c0("c0","coeff #0",1.0,-5.,5.);
   RooRealVar c1("c1","coeff #1",0.1,-5.,5.);
   RooRealVar c2("c2","coeff #2",0.1,-5.,5.);
   RooRealVar c3("c3","coeff #3",0.1,-5.,5.); 
   RooChebychev bkg("bkg","bkgd pdf",Mej,RooArgList(c0,c1,c2,c3));

   // --- Build Argus background PDF ---
   //    RooRealVar argpar("argpar","argus shape parameter",-20.0,-100.,-1.) ;
   //    RooRealVar cutoff("cutoff","argus cutoff",1001,1000,2000) ;
   //    RooRealVar p("p","p",0.5,0,10);
   //    RooArgusBG bkg("argus","Argus PDF",Mej,cutoff,argpar,p);
   
   // we are interested in getting the number of signal/background events
   RooRealVar nsig("nsig","weel reco signal",500,0.,10000.);
   RooRealVar nbkg("nbkg","bad reco signal",500,0.,50000.);
   
   //define the model
   RooAddPdf model("model","signal+bkgd",RooArgList(sig,bkg),RooArgList(nsig,nbkg));
   
   //fit (notice use of Extended(true) - this is so that we can get nsig/nbkg
   RooFitResult *fitres = model.fitTo(*data,Extended(kTRUE),Minos(kFALSE),PrintLevel(0),Save(kTRUE));
   
   // make new canvas  
   TCanvas *TopMass = new TCanvas("TopMass","Top Mass");
   
   // make new frame and plot histogram and fit results on it 
   RooPlot *Massframe = Mej.frame();
   
   data.plotOn(Massframe,MarkerColor(kBlack));
   model.plotOn(Massframe,Components(sig),LineStyle(kDashed),LineColor(kRed));
   model.plotOn(Massframe,Components(bkg),LineStyle(kDashed),LineColor(kGreen));
   model.plotOn(Massframe,LineColor(kBlack));
   
   Massframe->Draw();
   
   // print the results of the fit   
   fitres->Print(); 
   
   // You have to get the chi-square of the fit from MassFrame - the 7 tells RooFit to take into account the 7 fit parameters when calculating the number of degrees of freedom
   cout<<" Fit chi square/dof = "<<Massframe->chiSquare(10)<<endl; 
   
 }
Пример #13
0
int ratio5() {

  // Constants and arrays

  Int_t multi = 2;

  const Int_t n_at = 3;
  Int_t at[n_at] = { 500, 510, 550 };
  //for ( int ii = 0; ii < n_at; ++ii ) { at[ii] = 500 + ii * 10; }

  TString eq = "Gt";

  const Int_t n = 4;
  float pt[n]     = { 50., 40., 30., 20. };
  Int_t colour[n] = { 1, 2, 3, 4 };

  const Int_t m = 2;
  Int_t style[m]  = { kOpenSquare, kFullSquare };
  
  const Int_t ngr = 1000;
  double x3[ngr];
  double r[ngr];

  int count = 0;

  // General style

  gStyle->SetOptStat(0);
  
//   // Canvas for RECO curves 
//   TCanvas* reco_canvas = new TCanvas("Reco");
//   reco_canvas->SetFillColor(0);
//   reco_canvas->SetLineColor(0); 
//   reco_canvas->SetLogy();
//   TLegend* reco_legend = new TLegend( 0.5, 0.7, 0.88, 0.88, NULL, "brNDC" );
//   reco_legend->SetFillColor(0);
//   reco_legend->SetLineColor(0); 
//   bool empty = true;
//   double reco_max = 1.e-15.;
//   double reco_min = 1.e15;
  
  // Loop through pt bins

  for ( Int_t i = 0; i < 1; ++i ) {

    std::stringstream pt_can;
    pt_can << "PtBin" << pt[i];
    
    // Canvas for Pt bin
    TCanvas* pt_canvas = new TCanvas(TString(pt_can.str()),"");
    pt_canvas->SetFillColor(0);
    pt_canvas->SetLineColor(0); 
    pt_canvas->SetLogy();
    TLegend* pt_legend = new TLegend( 0.82, 0.5, 0.98, 0.9, NULL, "brNDC" );

    pt_legend->SetFillColor(0);
    pt_legend->SetLineColor(0); 
    bool empty = true;
    double pt_max = 1.e-15.;
    double pt_min = 1.e15;
    std::vector<TH1*> pt_ratio;

    pt_canvas->SetRightMargin(0.2);

    // Open files
    std::stringstream ss;
    ss << "results/4/Reco" << pt[i] << "_QCDPythia6.root";
    TString name(ss.str());
    TFile* file = new TFile(name);
    if ( file->IsZombie() || !(file->IsOpen()) ) { continue; }
    file->cd();
    
    // Loop through AlphaT thresolds
    for ( Int_t iat = 0; iat < n_at; ++iat ) {
    
      // Loop through RECO and GEN
      for ( Int_t j = 0; j < m; ++j ) {
	
	// Define names of histos to open 
	std::stringstream pre;
	std::stringstream post;
	if ( j == 0 ) {
	  pre << "Ratio" << at[iat] << "/GenHt" << eq << "PreAlphaT" << at[iat] << "_" << multi;
	  post << "Ratio" << at[iat] << "/GenHt" << eq << "PostAlphaT" << at[iat] << "_" << multi;
	  std::cout << pre.str() << std::endl;
	  std::cout << post.str() << std::endl;
	} else if ( j == 1 ) {
	  pre << "Ratio" << at[iat] << "/Ht" << eq << "PreAlphaT" << at[iat] << "_" << multi;
	  post << "Ratio" << at[iat] << "/Ht" << eq << "PostAlphaT" << at[iat] << "_" << multi;
	  std::cout << pre.str() << std::endl;
	  std::cout << post.str() << std::endl;
	}
	
	// Create ratio histo
	TH1* denominator = his( (TH1*)file->Get(TString(pre.str())), 45, 200., 650. );
	TH1* numerator = his( (TH1*)file->Get(TString(post.str())), 45, 200., 650. );
	int rebin = 5;
	numerator->Rebin(rebin);
	denominator->Rebin(rebin);
	TH1* ratio = (TH1*)numerator->Clone();
	ratio->Divide(denominator);
	//ratio->Divide(numerator,denominator,1.,1.,"b"); //@@ poisson errors
	ratio->SetMarkerStyle(style[j]);
	ratio->SetMarkerSize(1.2);
	ratio->SetMarkerColor(iat+1);//colour[iat]);
	ratio->SetBarOffset(0.1*i);
	//ratio->GetXaxis()->SetRangeUser(100.,550.);
	ratio->GetYaxis()->SetRangeUser(1.e-7,1.e-1);

	ratio->GetXaxis()->SetTitle("HT_{reco} [GeV]");
	ratio->GetYaxis()->SetTitle("R(#alpha_{T})");
	
 	if ( ratio->GetMaximum() > 0. &&
 	     ratio->GetMaximum() > pt_max ) {
 	  pt_max = ratio->GetMaximum();
 	}
 	if ( ratio->GetMinimum() > 0. && 
 	     ratio->GetMinimum() < pt_min ) {
 	  pt_min = ratio->GetMinimum();
 	}

	pt_ratio.push_back(ratio);

	if ( empty ) { ratio->Draw(""); empty = false; }
        else { ratio->Draw("same"); }

	//ratio->GetYaxis()->SetRangeUser(pt_min/1.1,pt_max*1.1);


	// Text for legend
	std::stringstream pt_leg;
	if ( j == 0 ) { pt_leg << "#alpha_{T} = " << at[iat]/1000. << ", GEN"; }
	else if ( j == 1 ) { pt_leg << "#alpha_{T} = " << at[iat]/1000. << ", RECO"; }
	pt_legend->AddEntry( ratio, TString(pt_leg.str()), "lep" );
	
// 	// Draw histos on canvas for RECO only
// 	if ( j == 1 ) {
// 	  reco_canvas->cd();
// 	  if ( i == 0 ) ratio->Draw("");
// 	  else ratio->Draw("same");
// 	  std::stringstream reco_leg;
// 	  reco_leg << "p_{T}^{min} = " << pt[i];
// 	reco_legend->AddEntry( ratio, TString(reco_leg.str()), "lep" );
// 	}
	
      }
    }

//       if (0) {

// 	int nbins = ratio->GetNbinsX();
// 	int bin_width = ratio->GetBinWidth(1);
      
// 	double lower = 0.;
// 	double upper = 1400.;
      
// 	int bin_lower = int( ( lower - ratio->GetBinLowEdge(1) ) / bin_width );
// 	for ( Int_t ii = bin_lower; ii < ratio->GetNbinsX()-1; ++ii ) {
// 	  if ( ratio->GetBinContent(ii) > 0. ) { 
// 	    lower = ratio->GetBinCenter(ii);
// 	    break;
// 	  }
// 	}
// 	int bin_upper = int( ( upper - ratio->GetBinLowEdge(1) ) / bin_width );
// 	for ( Int_t ii = bin_upper; ii > 0; --ii ) {
// 	  if ( ratio->GetBinContent(ii) > 0. ) { 
// 	    upper = ratio->GetBinCenter(ii);
// 	    break;
// 	  }
// 	}
// 	if (0) {
// 	  std::cout << " bin_width: " << bin_width
// 		    << " bin_lower: " << bin_lower
// 		    << " bin_upper: " << bin_upper
// 		    << " lower: " << lower
// 		    << " upper: " << upper
// 		    << std::endl;
// 	}

// 	TF1* fit = new TF1(sample[i],"expo",lower,upper); 
// 	fit->SetLineColor(colour[i]);
// 	fit->SetLineWidth(1);
// 	ratio->Fit(sample[i],"QR","same");

//       }
      
     pt_canvas->cd();
//      for ( Int_t iii = 0; iii < pt_ratio.size(); ++iii ) {
//        TH1* ratio = pt_ratio[iii];
//        if ( !ratio ) { continue; }
//        if ( ii == 0 ) { ratio->Draw(""); }
//        else { ratio->Draw("same"); }
//        ratio->GetYaxis()->SetRangeUser(pt_min/1.1,pt_max*1.1);
//      }
     pt_legend->Draw("same");
     pt_canvas->Update();
     pt_canvas->SaveAs(TString(pt_can.str()+".png"));
//       pt_canvas->SaveAs(TString(pt_can.str()+".C"));
      
    }

//   reco_canvas->cd();
//   reco_legend->Draw("same");
//   reco_canvas->Update();
//   reco_canvas->SaveAs(TString("Reco.png"));
//   reco_canvas->SaveAs(TString("Reco.C"));
  
//   TCanvas* c2 = new TCanvas("C2");
//   c2->SetLogy();
//   c2->SetFillColor(0);
//   gStyle->SetOptStat(0);
//   if ( count > 0 ) {
//     TGraph* graph = new TGraph(count,x3,r); 
//     graph->Draw("a*");
//   }

  
}
Пример #14
0
void MakePi0Analysis(){

  gStyle->SetPadLeftMargin(0.15);
  gStyle->SetPadRightMargin(0.01);
  gStyle->SetPadTopMargin(0.09);
  gStyle->SetPadBottomMargin(0.11);
  //gStyle->SetOptStat(0);
  //gStyle->SetOptTitle(1);
  //gStyle->SetPadTickX(1);
  //gStyle->SetPadTickY(1);
  TGaxis::SetMaxDigits(3);
  
  Double_t bins[] = {1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0, 3.2, 3.4, 3.6,3.8,4.0,4.5, 5.0, 5.5,6.0,6.5,7.0,7.5,8.0,8.5,9.0,10.0,11,12}; //Nicolas LHC12d PHI
  const Int_t binnum = sizeof(bins)/sizeof(Double_t) - 1;
  
  TString cwd = gSystem->WorkingDirectory();

  TH1F* fHistPeakMean  = new TH1F("fHistPeakMean","",binnum,bins);
  TH1F* fHistPeakWidth = new TH1F("fHistPeakWidth","",binnum,bins);
  TH1F* fHistRawYield  = new TH1F("fHistRawYield","",binnum,bins);
  TH1F* fHistRawYieldPerEvent  = new TH1F("fHistRawYieldPerEvent","",binnum,bins);
  
  TCanvas *c1[binnum];
  TCanvas *c2[binnum];
  TCanvas *c3;

  TFile* ef     = TFile::Open("../AnalysisResults.root");
  TList* list   = (TList*)ef->Get("list_kINT7_Pi0");
  TList *listEv = (TList*)ef->Get("list_kINT7_Event");
  
  TH1F* fHistEvents = (TH1F*)listEv->FindObject("fHistAnalyzedEvents");
  Double_t nEvt = fHistEvents->GetEntries();
  
  TString tofName[] = {"","_TOFcut1","_TOFcut2"};
  TString fitName[] = {"CrystalBall","AsymmGauss"};
  TString modName[] = {"","_M1","_M3"};
  
  Int_t ntof = 3;
  
  Double_t signal_range_min=0.11;
  Double_t signal_range_max=0.15;
  Double_t bg_range_min=0.050;
  Double_t bg_range_max=0.250;
  
  for(Int_t itof=0; itof<ntof; ++itof){
    for(Int_t iMod=0; iMod<1; iMod++){
      for(Int_t iFit=0; iFit<2; iFit++){
	for(Int_t iPol=0; iPol<3; iPol++){
	  
	  Int_t pol = iPol;

	  TString fNameSame = "fHistMassTwoGammas"+tofName[itof]+modName[iMod];
	  TString fNameMix  = "fHistMixMassTwoGammas"+tofName[itof]+modName[iMod];
	  
	  THnSparse *fTHnSparseRecPi0;
	  THnSparse *fTHnSparseRecMixPi0;
	  THnSparse *fTHnSparseGeneratePi0;
	  
	  TH2* hPi0A08    = 0x0;
	  TH2* hMixPi0A08 = 0x0;
	  hPi0A08    = (TH2*)list->FindObject(fNameSame)->Clone();
	  hMixPi0A08 = (TH2*)list->FindObject(fNameMix)->Clone();

	  Int_t sbin = 0;
	  Int_t lbin = 0;
      
	  TH1F* fHistFinalRatio[binnum];
	  TH1F* fHistFinalSame[binnum];
	  TH1F* fHistFinalBG[binnum];
	  TH1F* fHistFinalSignal[binnum];
	  TH1F* fHistOnlyFitSignal[binnum];
	  
	  TF1* fFitFinalRatio[binnum];
	  TF1* fFitFinalSignal[binnum];
	  TF1* fFitOnlyFitSignal[binnum];

	  for(Int_t i=0; i<binnum; i++){    
	    
	    Double_t bin_width = (bins[i+1]-bins[i]);
	    Double_t bin_mean  = (bins[i+1]+bins[i])/2;
	    
	    Int_t rebin = 1;
	    
	    if(bin_mean>5.0){
	      rebin=10;
	    }
	    else{
	      rebin=5;
	    }
	    
	    Int_t sproj_bin = hPi0A08->GetYaxis()->FindBin(bins[i]);
	    Int_t lproj_bin = hPi0A08->GetYaxis()->FindBin(bins[i+1])-1;
	    
	    TH1* fHistBasicSame = (TH1*)hPi0A08   ->ProjectionX(Form("fHistBasicSame_No%d",i+1),sproj_bin,lproj_bin,""); 
	    TH1* fHistBasicMix  = (TH1*)hMixPi0A08->ProjectionX(Form("fHistBasicMix_No%d",i+1),sproj_bin,lproj_bin,""); 
	    fHistBasicSame->Rebin(rebin);
	    fHistBasicMix->Rebin(rebin);
	    fHistBasicSame->Sumw2();
	    fHistBasicMix->Sumw2();
	    fHistBasicSame->GetYaxis()->SetTitle(Form("dN/dM per %.0f MeV/c^{2}",fHistBasicSame->GetBinWidth(1)*1000));
	    fHistBasicMix->GetYaxis()->SetTitle(Form("dN/dM per %.0f MeV/c^{2}",fHistBasicSame->GetBinWidth(1)*1000));
	    fHistBasicSame->GetXaxis()->SetRange(fHistBasicSame->GetXaxis()->FindBin(0.),fHistBasicSame->GetXaxis()->FindBin(0.3)-1);
	    fHistBasicMix->GetXaxis()->SetRange(fHistBasicSame->GetXaxis()->FindBin(0.),fHistBasicSame->GetXaxis()->FindBin(0.3)-1);
	    fHistBasicSame->SetMarkerStyle(20);
	    fHistBasicMix->SetMarkerStyle(24);
	    fHistBasicSame->SetMarkerColor(kBlack);
	    fHistBasicMix->SetMarkerColor(kBlue);
	    fHistBasicSame->SetLineColor(kBlack);
	    fHistBasicMix->SetLineColor(kBlue);
	    
	    fHistFinalSame[i]     = (TH1F*)fHistBasicSame->Clone();
	    fHistOnlyFitSignal[i] = (TH1F*)fHistBasicSame->Clone();
	    fHistOnlyFitSignal[i]->SetName(Form("fHistOnlyFitSignal_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);


	    TH1F* fHistOnlyFit_Signal = (TH1F*)fHistOnlyFitSignal[i]->Clone();
	    TH1F* fHistOnlyFit_BG     = (TH1F*)fHistOnlyFitSignal[i]->Clone();
	    
	    TH1F* fHistRatio     = (TH1F*)fHistBasicSame->Clone();
	    fHistRatio->Divide(fHistBasicMix);
	    fHistRatio->SetName(Form("cRatioSameBG_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    
	    TH1F* fHistRatio_Signal = (TH1F*)fHistRatio->Clone();
	    TH1F* fHistRatio_BG     = (TH1F*)fHistRatio->Clone();
	    
	    Int_t ssignal_bin = fHistRatio_Signal->GetXaxis()->FindBin(signal_range_min);
	    Int_t lsignal_bin = fHistRatio_Signal->GetXaxis()->FindBin(signal_range_max);
	    Int_t sbg_bin = fHistRatio_BG->GetXaxis()->FindBin(bg_range_min);
	    Int_t lbg_bin = fHistRatio_BG->GetXaxis()->FindBin(bg_range_max);
	    
	    for(Int_t j=ssignal_bin; j<lsignal_bin; ++j){
	      fHistRatio_BG->SetBinContent(j,0);
	      fHistRatio_BG->SetBinError(j,0);
	      fHistOnlyFit_BG->SetBinContent(j,0);
	      fHistOnlyFit_BG->SetBinError(j,0);
	    }
	    for(Int_t j=sbg_bin; j<ssignal_bin; ++j){
	      fHistRatio_Signal->SetBinContent(j,0);
	      fHistRatio_Signal->SetBinError(j,0);
	      fHistOnlyFit_Signal->SetBinContent(j,0);
	      fHistOnlyFit_Signal->SetBinError(j,0);
	    }
	    for(Int_t j=lsignal_bin; j<lbg_bin; ++j){
	      fHistRatio_Signal->SetBinContent(j,0);
	      fHistRatio_Signal->SetBinError(j,0);
	      fHistOnlyFit_Signal->SetBinContent(j,0);
	      fHistOnlyFit_Signal->SetBinError(j,0);
	    }
	    
	    ///////////////////////////////////////////////////////////////////////////////////////////////////
	    // Combinatrial background analysis
	    ///////////////////////////////////////////////////////////////////////////////////////////////////
	    
	    TF1 *fFitRatio_Signal = NULL;
	    if(iFit==0){
	      fFitRatio_Signal = new TF1("fFitRatio_Signal",
					 "[4]*((x-[2])/[3] > -[0] ? 1.0:0.0 )*exp(-pow(x-[2],2)/(2*pow([3],2))) + ((x-[2])/[3] <= -[0] ? 1.0:0.0 )*[4]*pow([1]/[0],[1])*exp(-[0]*[0]/2) * pow([1]/[0]-[0]-(x-[2])/[3],-[1])+[5]",
					 signal_range_min,signal_range_max);
	      fFitRatio_Signal->SetParameters(1.,6.,0.135,0.005,0.01);
	      fFitRatio_Signal->FixParameter(0,1.16053);
	      fFitRatio_Signal->FixParameter(1,6.);
	      fFitRatio_Signal->SetParLimits(2,0.130,0.140);
	      fFitRatio_Signal->SetParLimits(3,0.005,0.03);
	    }
	    else if(iFit==1){//[0]=A, [1]=M_pi0, [2]=sigma, [3]=lamda
	      fFitRatio_Signal = new TF1("fFitRatio_Signal",
					 "[0] *( ([1]>x ? 1.0:0.0 ) * (1 - exp(-0.5*pow((x-[1])/[2],2))) * exp((x-[1])/[3]) + exp(-0.5*pow((x-[1])/[2],2)) )",
					 signal_range_min,signal_range_max);
	      fFitRatio_Signal->SetParameters(1,0.135,6.46624e-03,7.47626e-03);
	      fFitRatio_Signal->SetParLimits(1,0.130,0.140);
	      fFitRatio_Signal->SetParLimits(2,0.001,0.03);
	      fFitRatio_Signal->SetParLimits(3,0.001,0.03);
	    }
	    
	    fHistRatio_Signal->Fit(fFitRatio_Signal,"RNQ");
	    fHistRatio_Signal->Fit(fFitRatio_Signal,"RNQ");
	    fHistRatio_Signal->Fit(fFitRatio_Signal,"RNQ");
	    
	    TF1 *fFitRatio_BG = 0x0;
	    if(pol==0){
	      fFitRatio_BG = new TF1("fFitRatio_BG","[0]",0,1);
	    }
	    else if(pol==1){
	      fFitRatio_BG = new TF1("fFitRatio_BG","[0]+[1]*x",0,1);
	    }
	    else if(pol==2){
	      fFitRatio_BG = new TF1("fFitRatio_BG","[0]+[1]*x+[2]*x*x",0,1);
	    }
	    fHistRatio_BG->Fit(fFitRatio_BG,"RNQ","",bg_range_min,bg_range_max);
	    fHistRatio_BG->Fit(fFitRatio_BG,"RNQ","",bg_range_min,bg_range_max);
	    fHistRatio_BG->Fit(fFitRatio_BG,"RNQ","",bg_range_min,bg_range_max);
	    
	    TF1 *fFitRatio_SignalBG = 0x0;
	    TF1 *fFitScale = 0x0;
	    
	    if(iFit==0){
	      if(pol==0){
		fFitRatio_SignalBG= new TF1("fFitRatio_SignalBG",
					    "[4]*((x-[2])/[3] > -[0] ? 1.0:0.0 )*exp(-pow(x-[2],2)/(2*pow([3],2))) + ((x-[2])/[3] <= -[0] ? 1.0:0.0 )*[4]*pow([1]/[0],[1])*exp(-[0]*[0]/2) * pow([1]/[0]-[0]-(x-[2])/[3],-[1])+[5]",0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_Signal->GetParameter(4));
		fFitRatio_SignalBG->SetParameter(5,fFitRatio_BG->GetParameter(0));
		fFitScale = new TF1("fFitScale","pol0",0.,1);
	      }
	      else if(pol==1){
		fFitRatio_SignalBG = new TF1("fFitRatio_SignalBG",
					     "[4]*((x-[2])/[3] > -[0] ? 1.0:0.0 )*exp(-pow(x-[2],2)/(2*pow([3],2))) + ((x-[2])/[3] <= -[0] ? 1.0:0.0 )*[4]*pow([1]/[0],[1])*exp(-[0]*[0]/2) * pow([1]/[0]-[0]-(x-[2])/[3],-[1])+[5]+[6]*x",
					     0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_Signal->GetParameter(4));
		fFitRatio_SignalBG->SetParameter(5,fFitRatio_BG->GetParameter(0));
		fFitScale = new TF1("fFitScale","pol1",0,1);
	      }
	      else if(pol==2){
		fFitRatio_SignalBG = new TF1("fFitRatio_SignalBG",
					     "[4]*((x-[2])/[3] > -[0] ? 1.0:0.0 )*exp(-pow(x-[2],2)/(2*pow([3],2))) + ((x-[2])/[3] <= -[0] ? 1.0:0.0 )*[4]*pow([1]/[0],[1])*exp(-[0]*[0]/2) * pow([1]/[0]-[0]-(x-[2])/[3],-[1])+[5]+[6]*x+[7]*x*x",0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_Signal->GetParameter(4));
		fFitRatio_SignalBG->SetParameter(5,fFitRatio_BG->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(6,fFitRatio_BG->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(7,fFitRatio_BG->GetParameter(2));
		fFitScale = new TF1("fFitScale","pol2",0,1);
	      }
	      
	      fFitRatio_SignalBG->FixParameter(0,1.16053);
	      fFitRatio_SignalBG->FixParameter(1,6.);
	      fFitRatio_SignalBG->SetParLimits(2,0.130,0.140);
	      fFitRatio_SignalBG->SetParLimits(3,0.005,0.03);
	    }
	    
	    if(iFit==1){
	      if(pol==0){
		fFitRatio_SignalBG= new TF1("fFitRatio_SignalBG",
					    "[0] *( ([1]>x ? 1.0:0.0 ) * (1 - exp(-0.5*pow((x-[1])/[2],2))) * exp((x-[1])/[3]) + exp(-0.5*pow((x-[1])/[2],2)) ) + [4]",
					    0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_BG->GetParameter(0));
		fFitScale = new TF1("fFitScale","pol0",0,1);
	      }
	      else if(pol==1){
		fFitRatio_SignalBG = new TF1("fFitRatio_SignalBG",
					     "[0] *( ([1]>x ? 1.0:0.0 ) * (1 - exp(-0.5*pow((x-[1])/[2],2))) * exp((x-[1])/[3]) + exp(-0.5*pow((x-[1])/[2],2)) ) + [4]+[5]*x",
					     0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_BG->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(5,fFitRatio_BG->GetParameter(1));
		fFitScale = new TF1("fFitScale","pol1",0,1);
	      }
	      else if(pol==2){
		fFitRatio_SignalBG = new TF1("fFitRatio_SignalBG",
					     "[0] *( ([1]>x ? 1.0:0.0 ) * (1 - exp(-0.5*pow((x-[1])/[2],2))) * exp((x-[1])/[3]) + exp(-0.5*pow((x-[1])/[2],2)) ) + [4]+[5]*x+[6]*x*x",
					     0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_BG->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(5,fFitRatio_BG->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(6,fFitRatio_BG->GetParameter(2));
		fFitScale = new TF1("fFitScale","pol2",0,1);
	      }
	      fFitRatio_SignalBG->SetParLimits(1,0.130,0.140);
	      fFitRatio_SignalBG->SetParLimits(2,0.005,0.03);
	      fFitRatio_SignalBG->SetParLimits(3,0.005,0.03);
	    }

	    fHistRatio->Fit(fFitRatio_SignalBG,"NRQ","",bg_range_min,bg_range_max);
	    fHistRatio->Fit(fFitRatio_SignalBG,"NRQ","",bg_range_min,bg_range_max);
	    fHistRatio->Fit(fFitRatio_SignalBG,"NRQ","",bg_range_min,bg_range_max);
	    
	    fHistFinalRatio[i] = (TH1F*)fHistRatio->Clone();;
	    fFitFinalRatio[i]  = (TF1*)fFitRatio_SignalBG->Clone();
	    
	    if(iFit==0){
	      if(pol==0){
		fFitScale->SetParameter(0,fFitRatio_SignalBG->GetParameter(5));
	      }
	      else if(pol==1){
		fFitScale->SetParameters(fFitRatio_SignalBG->GetParameter(5),fFitRatio_SignalBG->GetParameter(6));
	      }
	      else if(pol==2){
		fFitScale->SetParameters(fFitRatio_SignalBG->GetParameter(5),fFitRatio_SignalBG->GetParameter(6),fFitRatio_SignalBG->GetParameter(7));
	      }
	    }	
	    if(iFit==1){
	      if(pol==0){
		fFitScale->SetParameter(0,fFitRatio_SignalBG->GetParameter(4));
	      }
	      else if(pol==1){
		fFitScale->SetParameters(fFitRatio_SignalBG->GetParameter(4),fFitRatio_SignalBG->GetParameter(5));
	      }
	      else if(pol==2){
		fFitScale->SetParameters(fFitRatio_SignalBG->GetParameter(4),fFitRatio_SignalBG->GetParameter(5),fFitRatio_SignalBG->GetParameter(6));
	      }
	    }	
	    
	    c3 = new TCanvas("c3","c3",600,600);
	    c3->cd();
	    fHistRatio->Draw();
	    fFitRatio_SignalBG->Draw("same");
	    fFitScale->Draw("same");
	    c3->SetName(Form("cRatioSameBG_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    tfout->WriteTObject(c3);

	    TH1F* fHistScaledMix = (TH1F*)fHistBasicMix->Clone();
	    fHistScaledMix->Multiply(fFitScale);
	    fHistFinalBG[i] = (TH1F*)fHistScaledMix->Clone();;
	    
	    TH1F* fHistSignal = (TH1F*)fHistBasicSame->Clone();
	    fHistSignal->SetName(Form("fHistSignal_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    fHistScaledMix->SetName(Form("fHistScaledMix_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    tfout->WriteTObject(fHistSignal);
	    tfout->WriteTObject(fHistScaledMix);
	    
	    for(Int_t j=0; j<fHistBasicSame->GetXaxis()->FindBin(0.3); ++j){
	      Double_t same   = fHistSignal->GetBinContent(j);
	      Double_t e_same = fHistSignal->GetBinError(j);
	      Double_t mix    = fHistScaledMix->GetBinContent(j);
	      Double_t e_mix  = fHistScaledMix->GetBinError(j);
	      
	      Double_t signal   = same - mix;
	      Double_t e_signal = sqrt(pow(e_same,2)+pow(e_mix,2));
	      
	      if(same>0){
		signal   = same - mix;
		e_signal = sqrt(pow(e_same,2)+pow(e_mix,2));
	      }
	      else{
		signal   = same;
		e_signal = e_same;
	      }
	      
	      fHistSignal->SetBinContent(j,signal);
	      fHistSignal->SetBinError(j,e_signal);
	    }
	    
	    fHistFinalSignal[i] = (TH1F*)fHistSignal->Clone();
	    fHistFinalSignal[i]->SetTitle(Form("%.2f < #it{p}_{T} %.2f (GeV/c)", bins[i], bins[i+1]));

	    TF1 *fFitSignal = NULL;
	    
	    if(iFit==0){
	      fFitSignal = new TF1("fFitSignal", "[4]*((x-[2])/[3] > -[0] ? 1.0:0.0 )*exp(-pow(x-[2],2)/(2*pow([3],2))) + ((x-[2])/[3] <= -[0] ? 1.0:0.0 )*[4]*pow([1]/[0],[1])*exp(-[0]*[0]/2) * pow([1]/[0]-[0]-(x-[2])/[3],-[1])",
				   0,0.3);
	      fFitSignal->SetParameters(1.,6.,0.135,0.005,0.01);

	      fFitSignal->FixParameter(0,1.16053);
	      fFitSignal->FixParameter(1,6.);

	      fFitSignal->SetParLimits(2,0.120,0.140);
	      fFitSignal->SetParLimits(3,0.005,0.03);
	    
	    }	
	    else if(iFit==1){
	      fFitSignal = new TF1("fFitSignal",
				   "[0] *( ([1]>x ? 1.0:0.0 ) * (1 - exp(-0.5*pow((x-[1])/[2],2))) * exp((x-[1])/[3]) + exp(-0.5*pow((x-[1])/[2],2)) )",
				   0,0.3);
	      fFitSignal->SetParameters(1,0.135,6.46624e-03,7.47626e-03);
	      fFitSignal->SetParLimits(1,0.125,0.140);
	      fFitSignal->SetParLimits(2,0.001,0.01);
	      fFitSignal->SetParLimits(3,0.001,0.01);
	    }
	    
	    fHistSignal->Fit(fFitSignal,"RNQ","",signal_range_min,signal_range_max);
	    fHistSignal->Fit(fFitSignal,"RNQ","",0.12,signal_range_max);
	    
	    
	    if(iFit==0){
	      fHistSignal->Fit(fFitSignal,"RNQ","",0.12,0.150);
	    }	
	    else{
	      fHistSignal->Fit(fFitSignal,"RNQ","",0.12,0.150);
	    }

	    fFitFinalSignal[i]  = (TF1*)fFitSignal->Clone();
	    
	    Double_t mean   = 0;
	    Double_t e_mean = 0;
	    Double_t signal_sigma   = 0;
	    Double_t e_signal_sigma = 0;
	    Double_t signal_window_min = 0;
	    Double_t signal_window_max = 0;
	    
	    if(iFit==0){
	      mean   = fFitSignal->GetParameter(2);
	      e_mean = fFitSignal->GetParError(2);
	      signal_sigma   = fabs(fFitSignal->GetParameter(3));
	      e_signal_sigma = fabs(fFitSignal->GetParError(3));
	      
	      signal_window_min = mean - signal_sigma*5;
	      signal_window_max = mean + signal_sigma*3;
	      
	    }
	    else if(iFit==1){
	      mean   = fFitSignal->GetParameter(1);
	      e_mean = fFitSignal->GetParError(1);
	      signal_sigma   = fabs(fFitSignal->GetParameter(2));
	      e_signal_sigma = fabs(fFitSignal->GetParError(2));
	      signal_window_min = mean - signal_sigma*5;
	      signal_window_max = mean + signal_sigma*3;
	    }
	  
	    fHistPeakMean->SetBinContent(i+1,mean);
	    fHistPeakMean->SetBinError(i+1,e_mean);
	    fHistPeakWidth->SetBinContent(i+1,signal_sigma);
	    fHistPeakWidth->SetBinError(i+1,e_signal_sigma);
	    
	    Int_t signal_window_bin_min = fHistSignal->GetXaxis()->FindBin(signal_window_min);
	    Int_t signal_window_bin_max = fHistSignal->GetXaxis()->FindBin(signal_window_max);
	    
	    Double_t num_pi0 = 0;
	    Double_t e_num_pi0 = 0;
	    
	    for(Int_t j=signal_window_bin_min; j<signal_window_bin_max; ++j){
	      num_pi0   += fHistSignal->GetBinContent(j);
	      e_num_pi0 += pow(fHistSignal->GetBinError(j),2);
	    }
	    e_num_pi0 = sqrt(e_num_pi0);
	    
	    fHistRawYield->SetBinContent(i+1,num_pi0/bin_width);
	    fHistRawYield->SetBinError(i+1,e_num_pi0/bin_width);
	    
	  }

	  fHistRawYield->SetName(Form("fHistRawYieldPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	  tfout->WriteTObject(fHistRawYield);
	  
	  fHistRawYieldPerEvent = (TH1F*)fHistRawYield->Clone();
	  fHistRawYieldPerEvent->Scale(1./nEvt);
	  fHistRawYieldPerEvent->SetName(Form("fHistRawYieldPerEventPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	  tfout->WriteTObject(fHistRawYieldPerEvent);
	  
	  fHistPeakMean->SetName(Form("fHistPeakMeanPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	  fHistPeakWidth->SetName(Form("fHistPeakWidthPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	  tfout->WriteTObject(fHistPeakMean);
	  tfout->WriteTObject(fHistPeakWidth);
	  
	  c1[itof] = new TCanvas("c1"+fitName[iFit]+tofName[itof],"",1200,1800);
	  c2[itof] = new TCanvas("c2"+fitName[iFit]+tofName[itof],"",1200,1800);
	  
	  c1[itof]->Divide(4,6);
	  for(Int_t i=0; i<binnum; ++i){
	    c1[itof]->cd(i+1);
	    fHistFinalSignal[i]->Draw();
	    fFitFinalSignal[i]->Draw("same");
	  }
	  
	  c1[itof]->SaveAs(Form("cInvariantMassSpectrumPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]+".eps");
	  
	  c2[itof]->Divide(4,6);
	  for(Int_t i=0; i<binnum; ++i){
	    c2[itof]->cd(i+1);
	    fHistFinalSame[i]->Draw();
	    fHistFinalBG[i]->Draw("same");
	  }
	  c2[itof]->SaveAs(Form("cSameScaledMixPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]+".eps");
	  
	  for(Int_t i=0; i<binnum; ++i){
	    
	    fHistFinalSignal[i]->SetName(Form("fHistFinalSignal_No%d_Pol%d",i+1,iPol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    fFitFinalSignal[i]->SetName(Form("fFitFinalSignal_No%d_Pol%d",i+1,iPol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    fHistFinalSame[i]->SetName(Form("fHistFinalSame_No%d_Pol%d",i+1,iPol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    fHistFinalBG[i]->SetName(Form("fHistFinalBG_No%d_Pol%d",i+1,iPol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    
	    tfout->WriteTObject(fHistFinalSignal[i]);
	    tfout->WriteTObject(fFitFinalSignal[i]);
	    tfout->WriteTObject(fHistFinalSame[i]);
	    tfout->WriteTObject(fHistFinalBG[i]);
	    
	    c3 = new TCanvas("c3","",600,600);
	    c3->cd(1);
	    fHistFinalSame[i]->Draw();
	    fHistFinalBG[i]->Draw("same");
	    c3->SetName(Form("cRawSignalBG_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    //tfout->WriteTObject(c3);
	  }
	  for(Int_t i=0; i<binnum; ++i){
	    c3 = new TCanvas("c3","",600,600);
	    c3->cd(1);
	    fHistFinalSignal[i]->Draw("");
	    fFitFinalSignal[i]->Draw("same");
	    c3->SetName(Form("cRawSignal_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    //tfout->WriteTObject(c3);
	  }
	  
	}	
      }
    }
  }  
  
}
Пример #15
0
//void makeHist(const int sample, const int dataset=1)
void makeHist(const string title="")
{
	vector<Hist> hist2print;
	TPaveText *tx = new TPaveText(.05,.1,.95,.8);
//	tx->AddText("Using Deafult JERs for all jets");
//	tx->AddText("Using b-Jet JERs");

/*	string title("QCD MG:");

	//if (sample==1) title += "NJet(70/50/30>=2/4/5), #slash{E}_{T}>175, Triplet>1, 80<TopMass<270, TOP+0.5*BJET>500, MT2>300, #Delta#Phi(.5,.5,.3), BJets>=1";
	if (sample==1)      title += "All Stop cuts applied (use default JERs for all jets)";
	else if (sample==2) title += "All Stop cuts applied + Inverted #Delta#Phi (use default JERs for all jets)";
	else if (sample==3) title += "All Stop cuts applied (use b-Jet JERs)";
	else if (sample==4) title += "All Stop cuts applied + Inverted #Delta#Phi (use b-Jet JERs)";
	else if (sample==5) title += "No cuts applied";
*/
	unsigned bitMaskArray[] = {0,1,2,3,129,130,131,195,257,258,269,323};
	vector<unsigned> vBitMaskArray(bitMaskArray, bitMaskArray + sizeof(bitMaskArray) / sizeof(unsigned));



	stringstream unclmet_title;
	unclmet_title << title << "Unclutered MET";
	hist2print.push_back(Hist("met",title,2,0.0, 400.0,1));
	hist2print.push_back(Hist("unclmet",unclmet_title.str().c_str(),2,0.0, 100.0,1));
	hist2print.push_back(Hist("mht",title,2,0.0, 400.0,1));
	hist2print.push_back(Hist("ht",title,2,0,2000,1));
	hist2print.push_back(Hist("njet30eta5p0",title,1,0,15,1));
	hist2print.push_back(Hist("nbjets",title,1,0,10,1));
//	hist2print.push_back(Hist("bjetPt",title,2));
	hist2print.push_back(Hist("M123",title,2));
//	hist2print.push_back(Hist("M23overM123",title));
	hist2print.push_back(Hist("MT2",title,2));
	hist2print.push_back(Hist("MTb",title,4));
	hist2print.push_back(Hist("MTt",title,4));
	hist2print.push_back(Hist("MTb_p_MTt",title,2,400,1000,1));
	//hist2print.push_back(Hist("jet1_pt",title,2));
	//hist2print.push_back("bjetPt");
//	hist2print.push_back(Hist("bjetMass",title,2,0,200));
//	hist2print.push_back(Hist("dphimin",title,4));


	TFile *outRootFile = new TFile("Merged.root");

	/*TPad *c1=0, *c2=0;
	TCanvas *c = GetCanvas(c1, c2);
	if (c ==NULL|| c1 == 0 ||c2 == 0)
	{
		cout << " A drawing pad is null !"<< endl;
		cout << "c = " << c << endl;
		cout << "c1 = " << c1 << endl;
		cout << "c2 = " << c2 << endl;
		assert(false);
	}*/
   TCanvas *c = new TCanvas("c1");
   c->Range(0,0,1,1);
   c->SetBorderSize(2);
   c->SetFrameFillColor(0);
  
// ------------>Primitives in pad: c1_1
   TPad *c1_1 = new TPad("c1_1", "c1_1",0.01,0.30,0.99,0.99);
   c1_1->Draw();
   c1_1->cd();
   c1_1->SetBorderSize(2);
   c1_1->SetTickx(1);
   c1_1->SetTicky(1);
   c1_1->SetTopMargin(0.1);
   c1_1->SetBottomMargin(0.0);
   //c1_1->SetFrameFillColor(3);
	//c1_1->SetLogy();
  
  c->cd();
// ------------>Primitives in pad: c1_2
   TPad *c1_2 = new TPad("c1_2", "c1_2",0.01,0.01,0.99,0.30);
   c1_2->Draw();
   c1_2->cd();
   c1_2->SetBorderSize(2);
   c1_2->SetTickx(1);
   c1_2->SetTicky(1);
   c1_2->SetTopMargin(0.0);
   c1_2->SetBottomMargin(0.24);
   c1_2->SetFrameFillColor(0);
	c1_2->SetGridx();
	c1_2->SetGridy();
	c->cd();
	gStyle->SetOptStat(0);
	gPad->Print("samples.eps[");

	for (unsigned i=0;i<vBitMaskArray.size(); ++i)
	{
		unsigned mask = vBitMaskArray.at(i);
		for (unsigned ihist=0; ihist < hist2print.size(); ++ihist)
		{
			stringstream path, reco_hist_name, gen_hist_name, smear_hist_name;
			stringstream reco_hist, gen_hist, smear_hist;
			stringstream folder;
			folder << "Hist/Mask"<< mask << "HT0to8000MHT0to8000/";
			//cout << "folder = " << folder.str() << endl;

			/*	if ((hist2print.at(ihist).Name()).find("Jet"))
				{
				reco_hist_name << folder.str() << "reco" << hist2print.at(ihist).Name() << "_copy";
				reco_hist << folder.str() << "reco" << hist2print.at(ihist).Name();
				smear_hist_name << folder.str() << "smeared" << hist2print.at(ihist).Name() << "_copy";
				smear_hist << folder.str() << "smeared" << hist2print.at(ihist).Name();
				gen_hist_name << folder.str() << "gen" << hist2print.at(ihist).Name() << "_copy";
				gen_hist << folder.str() << "gen" << hist2print.at(ihist).Name();
				} else
				*/	{
					reco_hist_name << folder.str() << "reco_" << hist2print.at(ihist).Name() << "_copy";
					reco_hist << folder.str() << "reco_" << hist2print.at(ihist).Name();
					smear_hist_name << folder.str() << "smeared_" << hist2print.at(ihist).Name() << "_copy";
					smear_hist << folder.str() << "smeared_" << hist2print.at(ihist).Name();
					gen_hist_name << folder.str() << "gen_" << hist2print.at(ihist).Name() << "_copy";
					gen_hist << folder.str() << "gen_" << hist2print.at(ihist).Name();
				}

				TH1* hreco = (TH1*) (outRootFile->Get(reco_hist.str().c_str()));
				if (hreco == NULL) { cout << "hreco = " << reco_hist.str() << " was not found!" << endl; assert(false); } 
				hreco->SetDirectory(0);
				TH1* hsmear = (TH1*) (outRootFile->Get(smear_hist.str().c_str()));
				if (hsmear == NULL) { cout << "hsmear = " << smear_hist.str() << " was not found!" << endl; assert(false); } 
				hsmear->SetDirectory(0);
				TH1* hgen = (TH1*) (outRootFile->Get(gen_hist.str().c_str()));
				//->Clone(gen_hist_name.str().c_str()));
				if (hgen == NULL) { cout << "hgen = " << gen_hist.str() << " was not found!" << endl; assert(false); } 
				hgen->SetDirectory(0);

				hreco->Sumw2();
				hsmear->Sumw2();
				hgen->Sumw2();

				const int rebin = hist2print.at(ihist).Rebin();
				const string title = hist2print.at(ihist).Title();
				const double xmin = hist2print.at(ihist).Xmin();
				const double xmax = hist2print.at(ihist).Xmax();

				if (rebin>1)
				{
					hreco->Rebin(rebin);
					hsmear->Rebin(rebin);
					hgen->Rebin(rebin);
				}
				if (title.length()>0)
				{
					hreco->SetTitle(title.c_str());
					hsmear->SetTitle(title.c_str());
					hgen->SetTitle(title.c_str());
				}
				if (xmin != LargeNegNum || xmax != LargeNegNum)
				{
					hreco->GetXaxis()->SetRangeUser(xmin,xmax);
					hsmear->GetXaxis()->SetRangeUser(xmin,xmax);
					hgen->GetXaxis()->SetRangeUser(xmin,xmax);
				}

				const double reco_max_y  = hreco->GetBinContent(hreco->GetMaximumBin());
				const double smear_max_y = hsmear->GetBinContent(hsmear->GetMaximumBin());
				const double y_max = max(reco_max_y, smear_max_y);
				double y_min = 9999.0;
				for (unsigned bin=1; bin<hreco->GetNbinsX(); ++bin)
				{
					const double v1 = hreco->GetBinContent(bin);
					const double v2 = hsmear->GetBinContent(bin);
					const double minv = min(v1,v2);
					if (minv != 0 && minv < y_min) y_min = minv;
					
				}

				cout << hreco->GetName() << "->ymin/max = " << y_min << "(" << y_min/2.0 << ")/" << y_max << "(" << y_max*2.0 << ")" << endl;
				hreco->GetYaxis()->SetRangeUser(y_min/2.0, y_max*2.0);
				hsmear->GetYaxis()->SetRangeUser(y_min/2.0, y_max*2.0);


				hgen->SetLineColor(kBlue);
				hgen->SetMarkerColor(kBlue);
				hgen->SetMarkerStyle(24);
				hgen->SetLineWidth(2);
				hsmear->SetLineColor(kRed);
				hsmear->SetMarkerColor(kRed);
				hsmear->SetMarkerStyle(24);
				hsmear->SetLineWidth(2);
				hreco->SetLineWidth(2);
				hreco->SetMarkerStyle(kDot);
				hreco->SetLineColor(kBlack);
				hreco->SetMarkerColor(kBlack);
				//hreco->GetXaxis()->SetRangeUser(0,300);
				//hsmear->GetXaxis()->SetRangeUser(0,300);


				hreco->GetYaxis()->CenterTitle(1);
				hreco->SetLabelFont(42,"XYZ");
				hreco->SetTitleFont(42,"XYZ");
				hreco->GetYaxis()->SetTitleOffset(0.8);
				hreco->SetLabelSize(0.05,"XYZ");
				hreco->SetTitleSize(0.06,"XYZ");


				TH1 *hsmeartoreco_ratio = (TH1*) (hsmear->Clone("hsmear_copy"));
				hsmeartoreco_ratio->Divide(hreco);
				hsmeartoreco_ratio->SetTitle("");
				hsmeartoreco_ratio->GetYaxis()->SetTitle("Smear/Reco");
				hsmeartoreco_ratio->GetYaxis()->SetRangeUser(0,2.);

				hsmeartoreco_ratio->GetYaxis()->SetTitleOffset(0.4);
				hsmeartoreco_ratio->GetXaxis()->SetTitleOffset(0.9);
				hsmeartoreco_ratio->GetYaxis()->CenterTitle(1);
				hsmeartoreco_ratio->GetXaxis()->CenterTitle(1);
				hsmeartoreco_ratio->SetLabelSize(0.125,"XYZ");
				hsmeartoreco_ratio->SetTitleSize(0.125,"XYZ");
				//	hsmeartoreco_ratio->SetLabelFont(labelfont,"XYZ");
				//	hsmeartoreco_ratio->SetTitleFont(titlefont,"XYZ");
				hsmeartoreco_ratio->GetXaxis()->SetTickLength(0.07);



				stringstream recoleg,smearleg, genleg;
				const double sum_reco  = hreco->Integral(1, hreco->GetNbinsX()+1);
				const double sum_smear = hsmear->Integral(1, hsmear->GetNbinsX()+1);
				const double sum_gen   = hgen->Integral(1, hgen->GetNbinsX()+1);
				const double err_reco  = StatErr(hreco);
				const double err_smear = StatErr(hsmear);


				cout << setprecision(1) << fixed;

				recoleg << "Reco (" << sum_reco << "#pm" << err_reco << ")";
				smearleg << "Smear (" << sum_smear << "#pm" << err_smear << ")";
				genleg << "Gen (" << sum_gen << ")";
				cout <<  smear_hist_name.str() << "::reco/smear = " << sum_reco << "/" << sum_smear << endl;

				TLegend *l2 = new TLegend(0.6,0.6,0.9,0.9);
				l2->AddEntry(hreco, recoleg.str().c_str());
				//l2->AddEntry(hgen, genleg.str().c_str());
				l2->AddEntry(hsmear, smearleg.str().c_str());

				c1_1->cd();
				gPad->SetLogy(hist2print.at(ihist).LogY());

				hreco->DrawCopy();
				//hgen->DrawCopy("same");
				hsmear->DrawCopy("same");
				l2->Draw();
				//tx->Draw();
				c1_2->cd();
				hsmeartoreco_ratio->DrawCopy();
				c->cd();
				gPad->Print("samples.eps");

		}
	}

	gPad->Print("samples.eps]");
}
void makeSplitQCDhist_PythiaBinned(vector<string> folders, const string histname, 
											const string htrange, const string htbinlabel,
											const hist_t histinfo)
{
	const float scaleTo = fDATA_LUMI; // pb

	TLegend *leg  = new TLegend(0.6,0.65,0.9,0.9);
	leg->SetTextFont(42);
	vector<TH1*> hists;
	new TCanvas();
	gPad->SetLogy();
	gPad->SetTickx();
	gPad->SetTicky();

		stringstream title;
		title << htrange << " [" << histinfo.name << "];" << histinfo.title;
		cout << title.str() << endl;
		TH1* Hist = GetHist(histname);

		Hist->SetTitle(title.str().c_str());
		Hist->SetMarkerStyle(20);
		Hist->SetStats(0);
		Hist->Rebin(histinfo.rebin);
		Hist->Draw("P");


/*
	for (unsigned i = 0; i < folders.size(); ++i)
	{	
		string njet("");
		if (i==0) njet += "[2-3]";
		else if (i==1) njet += "[4-5]";
		else if (i==2) njet += "[6-7]";
		else if (i==3) njet += "#geq 8";
*/		/*if (i==0) njet += "3";
		else if (i==1) njet += "4";
		else if (i==2) njet += "5";
		else if (i==3) njet += "6";
		else if (i==4) njet += "7";
		else if (i==5) njet += "8";*/

/*		stringstream title, histName;
		title << htrange << ";" << histinfo.title;
		cout << title.str() << endl;
		histName << folders.at(i) << "/" << histname;;
		hists.push_back(GetHist(histName.str()));
		hists.at(i)->SetTitle(title.str().c_str());
		hists.at(i)->SetMarkerStyle(20+i);
		hists.at(i)->SetMarkerColor(1+i*2);
		hists.at(i)->SetStats(0);
		hists.at(i)->Rebin(histinfo.rebin);
		if (histinfo.normalizeByBinWidth) NormByBinWidth(hists.at(i));

		stringstream legname;
		legname << "Njets " << njet;
		leg->AddEntry(hists.at(i), legname.str().c_str());
		if (i==0) hists.at(i)->Draw("P");
		else hists.at(i)->Draw("same P");
	}
	leg->Draw();
*/
}
Пример #17
0
TCanvas* WmunuOthers( int iV=0 )
{
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);

  TGaxis::SetMaxDigits(3);
  double intLumi(36);

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

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

  bool salamanderStyle=true; 
  if( salamanderStyle )
    {
      lineWidth1 = 2;
      lineWidth2 = 1;

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

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

  // log scale?
  bool logScaleY=false;
  bool logScaleX=false;

  // rebin?
  int rb = 1; 

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

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

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

  // canvas name
  TString cname;
  TString ctitle;

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

  // root file, where the data is
  //  TString fname("../Results/");
  TString fname = "./Wmunu_Fit_pfMet";
  TString dataHistName("data");
  double factor;
  // ***
  // Only the following is specific 
  if( iV==6 || iV==7 || iV==20 || iV ==22 || iV==21 || iV==23)
    {  
      if( iV==6 || iV==20 || iV==22)
	{
	  // MET plots in linear scale (inclusive)
	  if(iV==20) fname = "./Wmunu_PLUS_pfMet";
	  else if(iV==22) fname = "./Wmunu_MINUS_pfMet";
	  logScaleY = false;
	  
	  ctitle = "W to mu-nu analysis - MET linear scale";
	  
	  dataHistName = "DataMET";
	  
	  channels.push_back("WTemplateMET"); 
	  if(iV==6) {cname="Wmn_MET";hnames.push_back("  W #rightarrow #mu#nu"); factor=1;}
	  else if(iV==20) {cname="Wmn_MET_plus";hnames.push_back("  W^{+} #rightarrow #mu^{+}#nu"); factor=3./5.;}
	  else {cname="Wmn_MET_minus";hnames.push_back("  W^{-} #rightarrow #mu^{-}#nu");factor=2./5.;}
	  type.push_back("Signal"); 
      
	  channels.push_back("NonQCDMET");                  
	  hnames.push_back("  EWK+t#bar{t}"); 
	  type.push_back("EWK"); 

	  channels.push_back("QCDMET");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 

	  nbin_ = 100;
	  xmin_ = 0.;
	  xmax_ = 100.;

	  xtitle = "#slash{E}_{T} [GeV]";
	  ytitle = "number of events / 2 GeV";
	  ndivx = 506;
	  ndivy = 506;

	  markerSize = 1.1;

	  ymin_ = 0.;
	  xl_ = 0.6;
	  yl_ = 0.53;
	  
	  //ymax_ = 500.*intLumi*factor;
	  if(iV==6) ymax_ = 14e3;
	  else ymax_ = 8e3;
	}
      else if( iV==7 || iV==21 || iV==23)
	{
	  // MET plots in log scale (inclusive)
	  
	  logScaleY = true;
	  if(iV==21) fname = "./Wmunu_PLUS_pfMet";
	  else if(iV==23) fname = "./Wmunu_MINUS_pfMet";
	  
	  ctitle = "W to mu-nu analysis - MET log scale";

	  dataHistName = "DataMET";

	  channels.push_back("WTemplateMET"); 
	  if(iV==7) {cname="Wmn_MET";hnames.push_back("  W #rightarrow #mu#nu");}
	  else if(iV==21) {cname="Wmn_MET_plus";hnames.push_back("  W^{+} #rightarrow #mu^{+}#nu");}
	  else {cname="Wmn_MET_minus";hnames.push_back("  W^{-} #rightarrow #mu^{-}#nu");}
	  type.push_back("Signal"); 
      
	  channels.push_back("EWKMET");                  
	  hnames.push_back("  EWK"); 
	  type.push_back("EWK"); 

	  channels.push_back("TTbar_MCMET");                  
	  hnames.push_back("  t#bar{t}"); 
	  type.push_back("ttbar"); 
	  
	  channels.push_back("QCDMET");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 

	  nbin_ = 200;
	  xmin_ = 0.;
	  xmax_ = 200.;

	  xtitle = "#slash{E}_{T} [GeV]";
	  ytitle = "number of events / 2 GeV";
	  ndivx = 506;
	  ndivy = 506;

	  markerSize = 0.9;

	  yminl_ = 0.05;
	  ymaxl_ = 800.*intLumi;
	  xl_ = 0.6;
	  yl_ = 0.43;
	  
	}
    }
  else if( iV==8 || iV==9 )
    {
      if( iV==8 )
	{cname="pt";
	  // pT plots in linear scale (inclusive)
	  
	  logScaleY = false;
	  
	  ctitle = "W to mu-nu analysis - pT linear scale";

	  dataHistName = "DataPT";

	  channels.push_back("WTemplatePT"); 
	  hnames.push_back("  W #rightarrow #mu#nu"); 
	  type.push_back("Signal"); 
      
	  channels.push_back("NonQCDPT");                  
	  hnames.push_back("  EWK+t#bar{t}"); 
	  type.push_back("EWK"); 

	  channels.push_back("QCDPT");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 

	  nbin_ = 60;
	  xmin_ = 20.;
	  xmax_ = 80.;

	  xtitle = "p_{T}(#mu) [GeV]";
	  ytitle = "number of events / 2 GeV";
	  ndivx = 506;
	  ndivy = 506;

	  markerSize = 1.1;

	  ymin_ = 0.;
	  ymax_ = 500.*intLumi;
	  xl_ = 0.6;
	  yl_ = 0.53;

	}
      else if( iV==9 )
	{cname="pt";
	  // pT plots in log scale (inclusive)

	  logScaleY = true;

	  ctitle = "W to mu-nu analysis - pT log scale";

	  dataHistName = "DataPT";

	  channels.push_back("WTemplatePT"); 
	  hnames.push_back("  W #rightarrow #mu#nu"); 
	  type.push_back("Signal"); 
      
	  channels.push_back("EWKPT");                  
	  hnames.push_back("  EWK"); 
	  type.push_back("EWK"); 

	  channels.push_back("TTbar_MCPT");                  
	  hnames.push_back("  t#bar{t}"); 
	  type.push_back("ttbar"); 

	  channels.push_back("QCDPT");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 

	  nbin_ = 80;
	  xmin_ = 20.;
	  xmax_ = 100.;

	  xtitle = "p_{T}(#mu) [GeV]";
	  ytitle = "number of events / 2 GeV";
	  ndivx = 506;
	  ndivy = 506;

	  markerSize = 0.9;

	  yminl_ = 0.1;
	  ymaxl_ = 30000.*intLumi;
	  xl_ = 0.6;
	  yl_ = 0.45;

	}
    }
  else if( iV==13 || iV==14 )
    {
      if( iV==13 )
	{cname="ptw";
	  // pT plots in linear scale (inclusive)

	  logScaleY = false;

	  ctitle = "W to mu-nu analysis - W pT linear scale";

	  dataHistName = "DataPTW";

	  channels.push_back("WTemplatePTW"); 
	  hnames.push_back("  W #rightarrow #mu#nu"); 
	  type.push_back("Signal"); 
      
	  channels.push_back("NonQCDPTW");                  
	  hnames.push_back("  EWK+t#bar{t}"); 
	  type.push_back("EWK"); 

	  channels.push_back("QCDPTW");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 

	  nbin_ = 100;
	  xmin_ = 0.;
	  xmax_ = 100.;

	  xtitle = "p_{T}(W) [GeV]";
	  ytitle = "number of events / 2 GeV";
	  ndivx = 506;
	  ndivy = 506;

	  markerSize = 1.1;

	  ymin_ = 0.;
	  ymax_ = 500.*intLumi;
	  xl_ = 0.6;
	  yl_ = 0.53;

	}
      else if( iV==14 )
	{cname="ptw";
	  // pT plots in log scale (inclusive)
	  
	  logScaleY = true;

	  ctitle = "W to mu-nu analysis - pT log scale";

	  dataHistName = "DataPTW";

	  channels.push_back("WTemplatePTW"); 
	  hnames.push_back("  W #rightarrow #mu#nu"); 
	  type.push_back("Signal"); 
      
	  channels.push_back("EWKPTW");                  
	  hnames.push_back("  EWK"); 
	  type.push_back("EWK"); 

	  channels.push_back("TTbar_MCPTW");                  
	  hnames.push_back("  t#bar{t}"); 
	  type.push_back("ttbar"); 

	  channels.push_back("QCDPTW");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 

	  nbin_ = 100;
	  xmin_ = 0.;
	  xmax_ = 100.;

	  xtitle = "p_{T}(W) [GeV]";
	  ytitle = "number of events / 2 GeV";
	  ndivx = 506;
	  ndivy = 506;

	  markerSize = 0.9;

	  yminl_ = 0.1;
	  ymaxl_ = 45000.*intLumi;
	  xl_ = 0.6;
	  yl_ = 0.48;
	  
	}
    }
  else if( iV==10 || iV==11 || iV==12 )
    {
      if( iV==10 )
	{cname="iso";
	  // isolation plot in linear scale 
	  
	  logScaleY = false;

	  ctitle = "W to mu-nu analysis - isolation, linear scale";

	  dataHistName = "DataISO";

	  channels.push_back("WTemplateISO"); 
	  hnames.push_back("  W #rightarrow #mu#nu"); 
	  type.push_back("Signal"); 
      
	  channels.push_back("NonQCDISO");                  
	  hnames.push_back("  EWK+t#bar{t}"); 
	  type.push_back("EWK"); 

	  channels.push_back("QCDISO");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 

	  nbin_ = 25;
	  xmin_ = 0.;
	  xmax_ = 0.5;

	  xtitle = "I^{rel}_{comb}";
	  ytitle = "number of events";
      //ytitle = "CMS preliminary";
	  ndivx = 506;
	  ndivy = 506;

	  markerSize = 1.1;

	  titleOffset = 1.25;

	  ymin_ = 0.;
	  ymax_ = 5000.*intLumi;
	  xl_ = 0.6;
	  yl_ = 0.53;

	}
      else if( iV==11 )
	{cname="iso";
	  // isolation plot in log scale 
	  
	  logScaleY = true;

	  ctitle = "W to mu-nu analysis - isolation, log scale";

	  dataHistName = "DataISO";

	  channels.push_back("WTemplateISO"); 
	  hnames.push_back("  W #rightarrow #mu#nu"); 
	  type.push_back("Signal"); 
      
	  channels.push_back("EWKISO");                  
	  hnames.push_back("  EWK"); 
	  type.push_back("EWK"); 

	  channels.push_back("TTbar_MCISO");                  
	  hnames.push_back("  t#bar{t}"); 
	  type.push_back("ttbar"); 

	  channels.push_back("QCDISO");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 

	  nbin_ = 25;
	  xmin_ = 0.;
	  xmax_ = 0.5;

	  xtitle = "I^{rel}_{comb}";
	  ytitle = "number of events";
      //ytitle = "CMS preliminary";
	  ndivx = 506;
	  ndivy = 506;

	  markerSize = 0.9;

	  yminl_ = 50;
	  ymaxl_ = 30000.*intLumi;
	  xl_ = 0.6;
	  yl_ = 0.45;

	}
      else if( iV==12 )
	{cname="iso2";
	  // isolation plot in log scale 
	  
	  logScaleX = true;
	  logScaleY = true;

	  ctitle = "W to mu-nu analysis - isolation, log scale";
	  dataHistName = "DataISO";

	  channels.push_back("WTemplateISO"); 
	  hnames.push_back("  W #rightarrow #mu#nu"); 
	  type.push_back("Signal"); 
      
	  channels.push_back("EWKISO");                  
	  hnames.push_back("  EWK"); 
	  type.push_back("EWK"); 

	  channels.push_back("TTbar_MCISO");                  
	  hnames.push_back("  t#bar{t}"); 
	  type.push_back("ttbar"); 

	  channels.push_back("QCDISO");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 
	  
	  nbin_ = 200;
	  xmin_ = 0.;
	  xmax_ = 0.5;
	  
	  xtitle = "I^{rel}_{comb}";
	  ytitle = "number of events";
	  ndivx = 506;
	  ndivy = 506;
	  
	  markerSize = 0.9;
	  
	  yminl_ = 1;
	  ymaxl_ = 4000000.*intLumi;
	  xl_ = 0.6;
	  yl_ = 0.45;
	  
	}
      
      
      
    }
  else if( iV==15 )
    {cname="acop";
      // pT plots in linear scale (inclusive)
      
      logScaleY = false;
      
      ctitle = "W to mu-nu analysis - acop linear scale";
      
      dataHistName = "DataACOP";
      
      channels.push_back("WTemplateACOP"); 
      hnames.push_back("  W #rightarrow #mu#nu"); 
      type.push_back("Signal"); 
      
      channels.push_back("NonQCDACOP");                  
      hnames.push_back("  EWK+t#bar{t}"); 
      type.push_back("EWK"); 
      
      channels.push_back("QCDACOP");                  
      hnames.push_back("  QCD"); 
      type.push_back("QCD"); 
      
      nbin_ = 60;
      xmin_ = 0;
      xmax_ = 3.14;
      
      xtitle = "acop";
      ytitle = "number of events";
      ndivx = 506;
      ndivy = 506;
      
      markerSize = 1.1;
      
      ymin_ = 0.;
      ymax_ = 400.*intLumi;
      xl_ = 0.6;
      yl_ = 0.53;
      
    }
  else if( iV==16 )
    {cname="eta";
      
      // pT plots in linear scale (inclusive)
      
      logScaleY = false;
      
      ctitle = "W to mu-nu analysis - eta linear scale";
      
      dataHistName = "DataETA";
      
      channels.push_back("WTemplateETA"); 
      hnames.push_back("  W #rightarrow #mu#nu"); 
      type.push_back("Signal"); 
      
      channels.push_back("NonQCDETA");                  
      hnames.push_back("  EWK+t#bar{t}"); 
      type.push_back("EWK"); 
      
      channels.push_back("QCDETA");                  
      hnames.push_back("  QCD"); 
      type.push_back("QCD"); 
      
      nbin_ = 60;
      xmin_ = -3;
      xmax_ = 3;
      
      xtitle = "eta";
      ytitle = "number of events";
      ndivx = 506;
      ndivy = 506;
      
      markerSize = 1.1;
      
      ymin_ = 0.;
      ymax_ = 120.*intLumi;
      xl_ = 0.25;
      yl_ = 0.63;
      
    }
  else if( iV==17 )
    {cname="ptw_minus";
      fname = "./Wmunu_MINUS_pfMet";
      // pT plots in linear scale (inclusive)
      
      logScaleY = false;
      
      ctitle = "W to mu-nu analysis - eta linear scale";
      
      dataHistName = "DataPTW";
      
      channels.push_back("WTemplatePTW"); 
      hnames.push_back("  W^{-} #rightarrow #mu^{-}#nu"); 
      type.push_back("Signal"); 
      
      channels.push_back("NonQCDPTW");                  
      hnames.push_back("  EWK+t#bar{t}"); 
      type.push_back("EWK"); 
      
      channels.push_back("QCDPTW");                  
      hnames.push_back("  QCD"); 
      type.push_back("QCD"); 
      
      nbin_ = 100;
      xmin_ = 0;
      xmax_ = 100;
      
      xtitle = "W pt (GeV)";
      ytitle = "number of events / 2 GeV";
      ndivx = 506;
      ndivy = 506;
      
      markerSize = 1.1;
      
      ymin_ = 0.;
      ymax_ = 200.*intLumi;
      xl_ = 0.6;
      yl_ = 0.53;
      
    }
  else if( iV==18 )
    {cname="ptw_plus";
      fname = "./Wmunu_PLUS_pfMet";
      // pT plots in linear scale (inclusive)
      
      logScaleY = false;
      
      ctitle = "W to mu-nu analysis - eta linear scale";
      
      dataHistName = "DataPTW";
      
      channels.push_back("WTemplatePTW"); 
      hnames.push_back("  W^{+} #rightarrow #mu^{+}#nu"); 
      type.push_back("Signal"); 
      
      channels.push_back("NonQCDPTW");                  
      hnames.push_back("  EWK+t#bar{t}"); 
      type.push_back("EWK"); 
      
      channels.push_back("QCDPTW");                  
      hnames.push_back("  QCD"); 
      type.push_back("QCD"); 
      
      nbin_ = 100;
      xmin_ = 0;
      xmax_ = 100;
      
      xtitle = "W pt (GeV)";
      ytitle = "number of events / 2 GeV";
      ndivx = 506;
      ndivy = 506;
      
      markerSize = 1.1;
      
      ymin_ = 0.;
      ymax_ = 300.*intLumi;
      xl_ = 0.6;
      yl_ = 0.53;
      
    }
  else if( iV==19 )
    {cname="phi";
      //fname = "../Results/Wmunu__pfMet.root";
      // pT plots in linear scale (inclusive)
      
      logScaleY = false;
      
      ctitle = "W to mu-nu analysis - phi linear scale";
      
      dataHistName = "DataPHI";
      
      channels.push_back("WTemplatePHI"); 
      hnames.push_back("  W #rightarrow #mu#nu"); 
      type.push_back("Signal"); 
      
      channels.push_back("NonQCDPHI");                  
      hnames.push_back("  EWK+t#bar{t}"); 
      type.push_back("EWK"); 
      
      channels.push_back("QCDPHI");                  
      hnames.push_back("  QCD"); 
      type.push_back("QCD"); 
      
      nbin_ = 60;
      xmin_ = -3.5;
      xmax_ = 3.5;
      
      xtitle = "Phi";
      ytitle = "number of events";
      ndivx = 506;
      ndivy = 506;
      
      markerSize = 1.1;
      
      ymin_ = 0.;
      ymax_ = 100.*intLumi;
      xl_ = 0.25;
      yl_ = 0.63;
      
    }
   
  int nChan=channels.size();
  
  // open the root file containing histograms and graphs
  fname += ".root";
  TFile* f_ = TFile::Open(fname,"READ");
  
  // the canvas
  if( logScaleY ) cname += "_log";
//else            cname += "_lin";
  TCanvas* c_=new TCanvas(cname,ctitle,300,300,479,510);
  c_->SetLeftMargin(  87./479 );
  c_->SetRightMargin( 42./479 );
  c_->SetTopMargin(  30./510 );
  c_->SetBottomMargin( 80./510 ); 
  c_->SetFillColor(0);
  c_->SetTickx(1);
  c_->SetTicky(1);
  c_->SetFrameFillStyle(0);
  c_->SetFrameLineWidth(2);
  c_->SetFrameBorderMode(0);
  Double_t scale = 4;
  Double_t wbin = 42*scale;
  Double_t left  = 8*scale;
  Double_t right = 5*scale;
  Double_t h1 = 135*scale;
  Double_t h2 = 45*scale;
  Double_t top1 = 15*scale;
  Double_t bot1 = 3*scale;
  Double_t top2 = 3*scale;
  //  Double_t bot1 = 0*scale;
  //  Double_t top2 = 0*scale;
  Double_t bot2 = 80*scale;
  Double_t W = left + wbin + right;
  Double_t H = h1 + h2;
  Double_t s[2] = {1, h1/h2 };

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

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

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

  // a dummy histogram with the correct x axis
  // Warning: setTDRstyle() must be called before
  cout << nbin_<<endl;
  TH1F* h_= new TH1F( "bidon", "bidon", nbin_, xmin_, xmax_ );
  TAxis* ax_ = h_->GetXaxis();
  TAxis* ay_ = h_->GetYaxis();
  
  ax_->SetTitle(xtitle);
  ax_->CenterTitle();
  ax_->SetNdivisions(ndivx);
  ax_->SetTitleOffset(1.0);
  ax_->SetTitleSize( 1.4*ax_->GetTitleSize() );
  ax_->SetLabelSize( 1.2*ax_->GetLabelSize() );


  ay_->SetTitle(ytitle);
  ay_->CenterTitle();
  ay_->SetNdivisions(ndivy);
  /*if(logScaleY) */ titleOffset *=1.1;
  ay_->SetTitleOffset(titleOffset);
  ay_->SetLabelOffset(0.015);
  ay_->SetLabelSize( 1.2*ay_->GetLabelSize() );
  ay_->SetTitleSize( 1.4*ay_->GetTitleSize() );


  // fetch histograms and dress them
  vector<TH1F*> histos;
  for( int ii=0; ii<nChan; ii++ )
    {
      TH1F* tmp = (TH1F*)f_->Get(channels[ii]);
      tmp->Rebin(rb);
      tmp->SetStats(kFALSE);
      //      tmp->UseCurrentStyle();
      tmp->SetFillStyle( 1001 );
      tmp->SetFillColor( fillColor_[type[ii]] );
      tmp->SetLineColor( lineColor_[type[ii]] );
      tmp->SetLineWidth( lineWidth2 );
      histos.push_back(tmp);
    }

  TH1* h_sig = (TH1*) histos[0]->Clone();
  h_sig->SetFillStyle(0);
  h_sig->SetLineColor(lineColor_["Signal"]);
  h_sig->SetLineWidth( 2 );
  h_sig->SetLineStyle( kDashed );
  TH1* h_tot = (TH1*) histos[0]->Clone();
  h_tot->SetFillStyle(0);

  //
  // stack histogram
  //
  THStack* stackedHisto=new THStack("stackedHisto","XXX");
  TH1F* totalHisto(0);
  for(int ii=0;ii<nChan;ii++) 
    {
      stackedHisto->Add(histos[nChan-ii-1],"ah");
      
      if(ii==0)
	{
	  totalHisto = (TH1F*)histos[ii]->Clone();
	}
      else
	{
	  totalHisto->Add(histos[ii]);
	}
    }
  
  // colors the stacked histogram
  totalHisto->SetLineColor( lineColor_["Signal"] );
  totalHisto->SetFillColor( 0 );
  totalHisto->SetLineWidth( lineWidth1 );
  
  // The data points are presented as a TGraph 
  // possibly a TGraph with asymmetric errors where
  // - error bars indicate the Poisson confidence interval at 68%
  // - bins with zero entry are removed
  //  TGraphAsymmErrors* dataGraph = (TGraphAsymmErrors*)f_->Get("data");
  // The data points are presented as a TGraph 
  // possibly a TGraph with asymmetric errors where
  // - error bars indicate the Poisson confidence interval at 68%
  // - bins with zero entry are removed
  TH1* hdata = (TH1*) f_->Get( dataHistName );  
  assert( hdata );
  hdata->Rebin(rb);

  RooHist* roohist;
  TGraphAsymmErrors* dataGraph;

  roohist = new RooHist((*hdata));

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

  for(int ip=0;ip<roohist->GetN();ip++) {
    double Y,X;
    //    double eY[2],eX[2];
    roohist->GetPoint(ip,X,Y);

    if(Y!=0) 
      {
	Nn0++;
	
	vY.push_back(Y);
	vX.push_back(X);
	veX.push_back( roohist->GetErrorXlow(ip) );
	veX.push_back( roohist->GetErrorXhigh(ip) );
	veY.push_back( roohist->GetErrorYlow(ip) );
	veY.push_back( roohist->GetErrorYhigh(ip) );
      }
  }
  dataGraph=new TGraphAsymmErrors(Nn0);
  for(int ip=0;ip<Nn0;ip++) 
    {
      dataGraph->SetPoint(ip,vX[ip],vY[ip]);
      dataGraph->SetPointError(ip,veX[ip*2],veX[ip*2+1],veY[ip*2],veY[ip*2+1]);
    }
  
  dataGraph->SetName("data");
  dataGraph->SetMarkerStyle(kFullCircle);
  dataGraph->SetMarkerColor(kBlack);
  if(logScaleY) markerSize *= 0.45;
  else markerSize *= 0.7;
  dataGraph->SetMarkerSize(markerSize);
  
  TGraph* dummyGraph = (TGraph*) dataGraph->Clone("dummyGraph");
  dummyGraph->SetLineColor(0);
  dummyGraph->SetMarkerSize(1.5*markerSize);

  // Remove the null bins
  double x_(0), y_(0);
  for( int ii=0; ii<dataGraph->GetN(); ii++ )
    {
      dataGraph->SetPointEXlow(ii,0);
      dataGraph->SetPointEXhigh(ii,0);
      dataGraph->GetPoint(ii,x_,y_ );
      if( y_==0 )
	{
	  dataGraph->RemovePoint( ii );
	  ii--;
	}	  
    }

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

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

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

  if( logScaleY )
    {
      p_->SetLogy(true);
    }
  else
    {
      p_->SetLogy(false);
    }
  
  if( !logScaleY )
    {
      h_->GetYaxis()->SetRangeUser(ymin_+0.001*(ymax_-ymin_),rb*ymax_);
    }
  else
    {
      h_->GetYaxis()->SetRangeUser(yminl_,rb*ymaxl_);
    }

  h_->Draw("hist");
  
  float dxl_ = scalel_*3.5;
  float dyl_ = scalel_*(nChan+0.5);
  TLegend* legend=new TLegend(xl_,yl_,xl_+dxl_,yl_+dyl_);
  legend->SetTextFont(42);
  legend->SetTextSize(0.045);
  legend->SetLineColor(0);
  legend->SetFillColor(0);
  
  legend->AddEntry(dummyGraph,"  data","pl");
  legend->AddEntry(dummyGraph,"      ","0"); // skip a line

  for( int ii=0; ii<nChan; ii++ ) 
    {
      legend->AddEntry(histos[ii],hnames[ii],"f");
    }
  legend->Draw("same");

  stackedHisto->Draw("samehist");
  h_sig->Draw("samehist");
  totalHisto->Draw("samehist");

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

  // redraw axis
  p_->RedrawAxis();

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

    float txtSize2 = 0.05;
    float txtX2 = 0.85;
    float txtY2 = 0.83;
    
    TLatex latex;
    latex.SetNDC();
    latex.SetTextFont(txtFont);
    
    latex.SetTextSize(txtSize1);    
    latex.SetTextAlign(31); // align right
//  latex.DrawLatex(txtX1,txtY1,"CMS preliminary");
    latex.DrawLatex(txtX1,txtY1,"CMS");

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

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

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

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

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

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

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

  p_->RedrawAxis();

  c_->cd();
  c_->SaveAs("plot.pdf");

  return c_;
}
//void PaintOverflow(THStack *h);
void SamMacroModBinWidth(){
  float value = 2.5;
  TCanvas *c1 = new TCanvas("c1", "c1",800,500);
  TPad* spectrumPad=0;
  TPad* ratioPad=0;
  //c1->Divide(1,2);
  //gStyle->SetOptStat(111111);
  gStyle->SetOptFit(kFALSE);
  gStyle->SetOptStat(kFALSE);
  gStyle->SetStatX(0.457589);
  gStyle->SetStatY(0.312937);
  gStyle->SetStatW(0.29241/2+0.0185);
  gStyle->SetStatH(0.169580+0.05);
  gStyle->SetStatFontSize(0.0402098);
  gStyle->SetStatFont(0.02);
  gStyle->SetFitFormat("5.2g");
  gStyle->SetStatBorderSize(0);
  gStyle->SetStatFontSize(0.040209);
  gStyle->SetStatFontSize(0.035209);
  c1->Range(1.592761,-5.173913,3.533814,6.006211);
  c1->SetFillColor(0);
  c1->SetBorderMode(0);
  c1->SetBorderSize(2);
  c1->SetLogx(1);
  c1->SetLogy(1);
  c1->SetTickx(1);
  c1->SetTicky(1);
  c1->SetLeftMargin(0.13);
  c1->SetRightMargin(0.07);
  c1->SetFrameBorderMode(0);
  c1->SetFrameBorderMode(0);
  c1->SetTopMargin(0.085);
  c1->SetBottomMargin(0.11);
  
  // Build the histo with constant log bin width
  const int NMBINS = 100;
  const double MMIN = 60., MMAX = 3000.;
  double logMbins[NMBINS+1];
  float binNormNr=0.;
  for (int ibin = 0; ibin <= NMBINS; ibin++) {
    logMbins[ibin] = exp(log(MMIN) + (log(MMAX)-log(MMIN))*ibin/NMBINS);
    cout << logMbins[ibin] << endl;
  }
  TH1* hTTbarDiboson   = new TH1F("hTTbarDiboson","",NMBINS, logMbins);
  TH1* hDijetWjets     = new TH1F("hDijetWjets","",NMBINS, logMbins);
  TH1* ttbarHist       = new TH1F("ttbarHist","",NMBINS, logMbins);
  TH1* dibosonsBkgHist = new TH1F("dibosonsBkgHist","",NMBINS, logMbins);
  //========================================================== 
  //                                                              
  //               Get the histograms                                  
  //==========================================================
  //TFile *file1 = new TFile("h_ZprimeRecomass_DYBinWidth.root","READ");
  //TH1* zeeHist = (TH1*) file1->Get("ZprimeRecomassBinWidth");

  TFile *file1 = new TFile("DY-MuMu-MC-OS-allbins-MC-2673pb.root","READ");
  TH1* zeeHist = (TH1*) file1->Get("hMassDYAll6");

  TFile *file2 = new TFile("h_ZprimeRecomass_Tlike.root","READ");
  TH1* ttbarHist = (TH1*) file2->Get("ZprimeRecomassBinWidth");
  TFile *file3 = new TFile("h_ZprimeRecomass_DiBoson.root","READ");
  TH1* dibosonsBkgHist = (TH1*) file3->Get("ZprimeRecomassBinWidth");

  TFile *file4 = new TFile("h_ZprimeRecomass_data.root","READ");
  TH1* dataHistTempbar = (TH1*) file4->Get("ZprimeRecomassBinWidth");

  TFile *file5 = new TFile("FR-DiJets-Data-OS-BinWidth-2673pb.root","READ");
  TH1* jetBkgHist   = (TH1*) file5->Get("DataSub");

  TFile *file6 = new TFile("FR-Wjets-25nsMC-OS-BinWidth-2673pb.root","READ");
  TH1* WjetsBkgHist = (TH1*) file6->Get("WjetsHisto");
  std::cout<<"nbQCD(dijets,Data)  = "<<jetBkgHist->Integral()<<endl;
  std::cout<<"nb.Wjets(MC)  = "<<WjetsBkgHist->Integral()<<endl;

  hTTbarDiboson->Add(ttbarHist,dibosonsBkgHist,1,1);
  hDijetWjets->Add(jetBkgHist,WjetsBkgHist,1,1);

  
  zeeHist->Rebin(value);
  hTTbarDiboson->Rebin(value);
  dibosonsBkgHist->Rebin(value);
  dataHistTempbar->Rebin(value);
  hDijetWjets->Rebin(value);
  WjetsBkgHist->Rebin(value);

  
  float binWidthNorm=1;
  int zeeColour    =  TColor::GetColor("#99ccff");
  int jetBkgColour = TColor::GetColor("#ffff66"); 
  int ttbarColour  = TColor::GetColor("#ff6666");
  int bosonColour  = TColor::GetColorDark(3);
  int WjetsColour  = TColor::GetColorDark(5);
  int font = 42;
  //float xAxisMin = 60; //72
  //float xAxisMax = 1000.0;
  //float yAxisMin = 1e-4;
  //float yAxisMax = 1e3; 
  
  TGraphAsymmErrors* dataHist = makeDataGraph(dataHistTempbar,binWidthNorm,0);
  normHistToBinWidth(zeeHist,binWidthNorm);
  normHistToBinWidth(hTTbarDiboson,binWidthNorm);
  //normHistToBinWidth(dibosonsBkgHist,binWidthNorm);
  normHistToBinWidth(hDijetWjets,binWidthNorm);
  //normHistToBinWidth(WjetsBkgHist,binWidthNorm);
  
  //gStyle->SetOptStat(111111);
  //PaintOverflow(zeeHist);
  //PaintOverflow(ttbarHist);
  //PaintOverflow(dibosonsBkgHist);
  //PaintOverflow(dataHistTempbar);
  //PaintOverflow(jetBkgHist);
  //PaintOverflow(WjetsBkgHist);   
  

  THStack *axisHist = new THStack("axisHist","");
  zeeHist->SetFillColor(zeeColour);
  zeeHist->SetLineWidth(2);
  zeeHist->SetLineColor(1);
  zeeHist->SetTitle("");
  
  hTTbarDiboson->SetFillColor(ttbarColour);
  hTTbarDiboson->SetLineWidth(2); 
  hTTbarDiboson->SetLineColor(1);
  
  //dibosonsBkgHist->SetFillColor(bosonColour);
  //dibosonsBkgHist->SetLineWidth(2); 
  //dibosonsBkgHist->SetLineColor(1);
  
  //WjetsBkgHist->SetFillColor(WjetsColour);
  //WjetsBkgHist->SetFillColor(jetBkgColour);
  //WjetsBkgHist->SetLineWidth(2);
  //WjetsBkgHist->SetLineColor(1);

  hDijetWjets->SetFillColor(jetBkgColour);
  hDijetWjets->SetLineWidth(2);
  hDijetWjets->SetLineColor(1);


  


  axisHist->Add(hDijetWjets,"histo");
  //axisHist->Add(WjetsBkgHist,"histo");
  axisHist->Add(hTTbarDiboson);
  //axisHist->Add(dibosonsBkgHist);
  axisHist->Add(zeeHist);
  axisHist->Draw("histo");

  
  //axisHist->GetYaxis()->SetTitle("Events / 20 GeV");
  axisHist->GetXaxis()->SetTitle("M(#mu^{+}#mu^{-}) [GeV]");
  axisHist->GetYaxis()->SetTitle("Events/GeV");
  //axisHist->GetXaxis()->SetTitleOffset(1.1);
  //axisHist->GetYaxis()->SetTitleOffset(1.1);
  axisHist->GetXaxis()->SetTitleSize(0.047);
  axisHist->GetYaxis()->SetTitleSize(0.047);
  axisHist->GetXaxis()->SetLabelSize(0.050);
  axisHist->GetYaxis()->SetLabelSize(0.050);
  axisHist->GetXaxis()->SetMoreLogLabels();
  axisHist->GetXaxis()->SetNoExponent();
  axisHist->GetXaxis()->SetRangeUser(70.0,2999.0);
  
  //axisHist->SetMinimum(0.01);
  //axisHist->SetMaximum(20000.0);
  axisHist->SetMinimum(0.0001);
  axisHist->SetMaximum(2000.0);
  
  dataHist->SetMarkerStyle(20);
  dataHist->SetMarkerSize(0.9);
  dataHist->GetXaxis()->SetRange(5,83);
  dataHist->GetXaxis()->SetTitleSize(0.047);
  dataHist->GetXaxis()->SetTitleOffset(0.9);
  dataHist->GetYaxis()->SetTitleSize(0.047);
  dataHist->GetYaxis()->SetTitleOffset(1.2);
  dataHist->Draw("PZ");
  
  //==========================================================
  TLegend *leg = new TLegend(0.56741,0.62671,0.820536,0.87664,NULL,"brNDC"); //for lumi in plot
  leg->AddEntry(dataHist,"Data","PE");
  leg->AddEntry(zeeHist,"#gamma^{*}/Z#rightarrow#mu^{+}#mu^{-}","F");
  leg->AddEntry(hTTbarDiboson,"t#bar{t}, tW, WW, WZ, ZZ, #tau^{+}#tau^{-}","F");
  //leg->AddEntry(dibosonsBkgHist,"di-boson, #gamma^{*}/Z#rightarrow#tau^{+}#tau^{-}","F");
  //leg->AddEntry(WjetsBkgHist,"W+jets (FR)","F");
  leg->AddEntry(hDijetWjets,"Jets (data)","F");
  leg->SetBorderSize(0);
  leg->SetLineColor(1);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(19);
  leg->SetFillStyle(0);
  leg->SetTextFont(font);
  leg->SetTextSize(0.04);
  leg->Draw();
  //==========================================================
  TPaveText* tText1 = new TPaveText(0.75, 0.92, 0.87, 0.98, "brNDC");
  tText1->SetBorderSize(0);
  tText1->SetFillColor(0);
  tText1->SetFillStyle(0);
  TText *t1 = tText1->AddText("2.8 fb^{-1} (13 TeV)");
  tText1->SetTextSize(0.04);
  tText1->Draw(); 
  //==========================================================
  TPaveText* tText2 = new TPaveText(0.85, 0.86, 0.88, 0.87, "brNDC");
  tText2->SetBorderSize(0);
  tText2->SetFillColor(0);
  tText2->SetFillStyle(0);
  TText *t1 = tText2->AddText("CMS");
  tText2->SetTextSize(0.04);
  tText2->Draw(); 
  //==========================================================
  TPaveText* tText3 = new TPaveText(0.80, 0.81, 0.85, 0.83, "brNDC");
  tText3->SetBorderSize(0);
  tText3->SetFillColor(0);
  tText3->SetFillStyle(0);
  TText *t1 = tText3->AddText("#it{Preliminary}");
  tText3->SetTextSize(0.04);
  tText3->Draw(); 
  //---------------------------------------------------------------------
  //---------------------------------------------------------------------
  
  //=================================================================================== 
  c1->Print("Stack-DY-Spring15MCs-Data2015-mass-spectrum-MuMu-OS-2800pb_logx.png","png");
  c1->Print("Stack-DY-Spring15MCs-Data2015-mass-spectrum-MuMu-OS-2673pb_logx.pdf","pdf");
  //=========================================================================
  //=========================================================================
  //=========================================================================
  //=========================================================================
  //=========================================================================
  //=========================================================================
  TCanvas *c2 = new TCanvas("c2", "c2",800,500);
  TPad* spectrumPad=0;
  TPad* ratioPad=0;
  // Build the histo with constant log bin width
  const int NMBINS = 100;
  const double MMIN = 60., MMAX = 3000.;
  double logMbins[NMBINS+1];
  float binNormNr=0.;
  for (int ibin = 0; ibin <= NMBINS; ibin++) {
    logMbins[ibin] = exp(log(MMIN) + (log(MMAX)-log(MMIN))*ibin/NMBINS);
    cout << logMbins[ibin] << endl;
  }
  TH1* hTTbarDiboson   = new TH1F("hTTbarDiboson","",NMBINS, logMbins);
  TH1* hDijetWjets     = new TH1F("hDijetWjets","",NMBINS, logMbins);
  TH1* ttbarHist       = new TH1F("ttbarHist","",NMBINS, logMbins);
  TH1* dibosonsBkgHist = new TH1F("dibosonsBkgHist","",NMBINS, logMbins);
  TH1F* hDivideHisto2 = new TH1F("hDivideHisto2","",150,0.0,3000.0);
  //TH1F* hMass1    = new TH1F("hMass1","",150,0.0,3000.0);
  //TH1F* hMass2    = new TH1F("hMass2","",150,0.0,3000.0);
  //TH1F* hMass3    = new TH1F("hMass3","",150,0.0,3000.0);
  //TH1F* hMass5    = new TH1F("hMass5","",150,0.0,3000.0);
  //TH1F* hMass6    = new TH1F("hMass6","",150,0.0,3000.0);
  //TH1F* AllEKWbkg = new TH1F("AllEKWbkg","",150,0.0,3000.0);
  gStyle->SetOptFit(1111);
  gStyle->SetOptStat(0);
  gStyle->SetStatX(0.457589);
  gStyle->SetStatY(0.312937);
  gStyle->SetStatW(0.29241/2+0.0185);
  gStyle->SetStatH(0.169580+0.05);
  gStyle->SetStatFontSize(0.0402098);
  gStyle->SetStatFont(0.03);
  gStyle->SetFitFormat("5.2g");
  gStyle->SetStatBorderSize(0);
  gStyle->SetStatFontSize(0.040209);
  gStyle->SetStatFontSize(0.035209);
  c2->Range(1.592761,-5.173913,3.533814,6.006211);
  c2->SetFillColor(0);
  c2->SetBorderMode(0);
  c2->SetBorderSize(2);
  c2->SetLogx(1);
  c2->SetLogy(1);
  c2->SetTickx(1);
  c2->SetTicky(1);
  c2->SetLeftMargin(0.13);
  c2->SetRightMargin(0.07);
  c2->SetFrameBorderMode(0);
  c2->SetFrameBorderMode(0);
  c2->SetTopMargin(0.085);
  c2->SetBottomMargin(0.11);
   //========================================================== 
  //                                                              
  //               Get the histograms                                  
  //==========================================================
  //TFile *file1 = new TFile("h_ZprimeRecomass_DYBinWidth.root","READ");
  //TH1* zeeHist = (TH1*) file1->Get("ZprimeRecomassBinWidth");

  TFile *file1 = new TFile("DY-MuMu-MC-OS-allbins-MC-2673pb.root","READ");
  TH1* zeeHist = (TH1*) file1->Get("hMassDYAll6");

  TFile *file2 = new TFile("h_ZprimeRecomass_Tlike.root","READ");
  TH1* ttbarHist = (TH1*) file2->Get("ZprimeRecomassBinWidth");

  TFile *file3 = new TFile("h_ZprimeRecomass_DiBoson.root","READ");
  TH1* dibosonsBkgHist = (TH1*) file3->Get("ZprimeRecomassBinWidth");

  TFile *file4 = new TFile("h_ZprimeRecomass_data.root","READ");
  TH1* dataHistTempbar = (TH1*) file4->Get("ZprimeRecomassBinWidth");

  TFile *file5 = new TFile("FR-DiJets-Data-OS-BinWidth-2673pb.root","READ");
  TH1* jetBkgHist   = (TH1*) file5->Get("DataSub");

  TFile *file6 = new TFile("FR-Wjets-25nsMC-OS-BinWidth-2673pb.root","READ");
  TH1* WjetsBkgHist = (TH1*) file6->Get("WjetsHisto");
  std::cout<<"nbQCD(dijets,Data)  = "<<jetBkgHist->Integral()<<endl;
  std::cout<<"nb.Wjets(MC)  = "<<WjetsBkgHist->Integral()<<endl;

  hTTbarDiboson->Add(ttbarHist,dibosonsBkgHist,1,1);
  hDijetWjets->Add(jetBkgHist,WjetsBkgHist,1,1);

  
  //zeeHist->Rebin(value);
  //hTTbarDiboson->Rebin(value);
  //dibosonsBkgHist->Rebin(value);
  //dataHistTempbar->Rebin(value);
  //hDijetWjets->Rebin(value);
  //WjetsBkgHist->Rebin(value);

  float binWidthNorm2=-1;
  int zeeColour    =  TColor::GetColor("#99ccff");
  int jetBkgColour = TColor::GetColor("#ffff66"); 
  int ttbarColour  = TColor::GetColor("#ff6666");
  int bosonColour  = TColor::GetColorDark(3);
  int WjetsColour  = TColor::GetColorDark(5);
  int font = 42;
  float xAxisMin = 60; //72
  float xAxisMax = 1000.0;
  float yAxisMin = 1e-4;
  float yAxisMax = 1e4; 

  dataHistTempbar = makeIntHist(dataHistTempbar);
  zeeHist         = makeIntHist(zeeHist);
  hTTbarDiboson   = makeIntHist(hTTbarDiboson);
  hDijetWjets     = makeIntHist(hDijetWjets);
  TGraphAsymmErrors* dataHist = makeDataGraph(dataHistTempbar,binWidthNorm2,0);
  
  

  THStack *axisHist2 = new THStack("axisHist2","");
  zeeHist->SetFillColor(zeeColour);
  zeeHist->SetLineWidth(2);
  zeeHist->SetLineColor(1);
  zeeHist->SetTitle("");
    
  hTTbarDiboson->SetFillColor(ttbarColour);
  hTTbarDiboson->SetLineWidth(2); 
  hTTbarDiboson->SetLineColor(1);
    
  //dibosonsBkgHist->SetFillColor(bosonColour);
  //dibosonsBkgHist->SetLineWidth(2); 
  //dibosonsBkgHist->SetLineColor(1);
   
  hDijetWjets->SetFillColor(jetBkgColour);
  hDijetWjets->SetLineWidth(2);
  hDijetWjets->SetLineColor(1);

  //WjetsBkgHist->SetFillColor(WjetsColour);
  //WjetsBkgHist->SetLineWidth(2);
  //WjetsBkgHist->SetLineColor(1);
  
  
  axisHist2->Add(hDijetWjets,"histo");
  //axisHist2->Add(WjetsBkgHist,"histo");
  //axisHist2->Add(dibosonsBkgHist,"histo");
  axisHist2->Add(hTTbarDiboson,"histo");
  axisHist2->Add(zeeHist,"histo");
  axisHist2->Draw();
  axisHist2->GetXaxis()->SetTitle("M(#mu^{+}#mu^{-}) [GeV]");
  axisHist2->GetYaxis()->SetTitle("Events #geq M(#mu^{+}#mu^{-}) [GeV]");
  axisHist2->GetXaxis()->SetTitleOffset(1.1);
  axisHist2->GetYaxis()->SetTitleOffset(1.1);
  axisHist2->GetXaxis()->SetTitleSize(0.047);
  axisHist2->GetYaxis()->SetTitleSize(0.047);
  axisHist2->GetXaxis()->SetLabelSize(0.040);
  axisHist2->GetYaxis()->SetLabelSize(0.040);
  axisHist2->GetXaxis()->SetMoreLogLabels();
  axisHist2->GetXaxis()->SetNoExponent();
  axisHist2->GetXaxis()->SetRangeUser(70.0,4000.0);
  axisHist2->SetMinimum(0.01);
  axisHist2->SetMaximum(60000.0);
  
  dataHist->SetMarkerStyle(20);
  dataHist->SetMarkerSize(0.9);
  dataHist->Draw("PZsames");
  //==========================================================
  TLegend *leg = new TLegend(0.56741,0.62671,0.820536,0.87664,NULL,"brNDC"); //for lumi in plot
  leg->AddEntry(dataHist,"Data","PE");
  leg->AddEntry(zeeHist,"#gamma^{*}/Z#rightarrow#mu^{+}#mu^{-}","F");
  leg->AddEntry(hTTbarDiboson,"t#bar{t}, tW, WW, WZ, ZZ, #tau^{+}#tau^{-}","F");
  leg->AddEntry(hDijetWjets,"Jets (data)","F");
  leg->SetBorderSize(0);
  leg->SetLineColor(1);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(19);
  leg->SetFillStyle(0);
  leg->SetTextFont(font);
  leg->SetTextSize(0.04);
  leg->Draw();

  
  //==========================================================
  TPaveText* tText1 = new TPaveText(0.75, 0.92, 0.87, 0.98, "brNDC");
  tText1->SetBorderSize(0);
  tText1->SetFillColor(0);
  tText1->SetFillStyle(0);
  TText *t1 = tText1->AddText("2.8 fb^{-1} (13 TeV)");
  tText1->SetTextSize(0.04);
  tText1->Draw(); 
  //==========================================================
  TPaveText* tText2 = new TPaveText(0.85, 0.86, 0.88, 0.87, "brNDC");
  tText2->SetBorderSize(0);
  tText2->SetFillColor(0);
  tText2->SetFillStyle(0);
  TText *t1 = tText2->AddText("CMS");
  tText2->SetTextSize(0.04);
  tText2->Draw(); 
  //==========================================================
  TPaveText* tText3 = new TPaveText(0.80, 0.81, 0.85, 0.83, "brNDC");
  tText3->SetBorderSize(0);
  tText3->SetFillColor(0);
  tText3->SetFillStyle(0);
  TText *t1 = tText3->AddText("#it{Preliminary}");
  tText3->SetTextSize(0.04);
  tText3->Draw(); 
  //===================================================================================
 
  //=================================================================================== 
  c2->Print("Stack-DY-Spring15MCs-Data2015-cumulative-spectrum-MuMu-OS-2800pb-logx.png","png");
  //c2->Print("Stack-DY-Spring15MCs-Data2015-cumulative-spectrum-MuMu-OS-2673pb-logx.pdf","pdf");

}
Пример #19
0
int main(int argc, char** argv) {
    TH1* data;
    std::vector<TH2*> signalIID; // for munub t-processes
    std::vector<TH3*> signalIIID; // for munub t-processes
    TH1* bkginsignal = 0; //for t-processes other than munub
    TH1* bkg = 0; // for non-t processes
    TH1* wtemplate = 0;
    bool do3D = true;
    int nReBin = 10;
    TFile * file = 0;
    std::vector<double> pars;
    double nTop7 = 1.;
    double nW8 = 0;
    double nW7 = 0;
    //    cout << pars[0] << "\t" << pars[1] << "\t" << pars[2] << "\t" << pars[3] << "\t" << endl;
    double delStatF0 = 0;
    double delStatFL = 0;

    double delSystF0 = 0;
    double delSystFL = 0;
    double F0_ = 0;
    double FL_ = 0;
    double delTotF0 = 0;
    double delTotFL = 0;
    string channel = "";
    std::vector<string> namings;
    std::map<string, double> sampleinfo;
    double iRandom = 0;
    string addname = "";
    for (int f = 1; f < argc; f++) {
        std::string arg_fth(*(argv + f));
        cout << f << " ---- " << arg_fth << endl;
        if (arg_fth == "channel") {
            f++;
            std::string out(*(argv + f));
            channel = out; //e-mu
            namings.push_back(string("di") + channel);
            namings.push_back(channel + string("had"));
            namings.push_back(channel + string("tau"));
            namings.push_back("mue");
        } else if (arg_fth == "FL") {
            f++;
            std::string out(*(argv + f));
            FL_ = atof(out.c_str());
        } else if (arg_fth == "F0") {
            f++;
            std::string out(*(argv + f));
            F0_ = atof(out.c_str());
        } else if (arg_fth == "F0Stat") {
            f++;
            std::string out(*(argv + f));
            delStatF0 = atof(out.c_str());
        } else if (arg_fth == "FLStat") {
            f++;
            std::string out(*(argv + f));
            delStatFL = atof(out.c_str());
        } else if (arg_fth == "F0Syst") {
            f++;
            std::string out(*(argv + f));
            delSystF0 = atof(out.c_str());
        } else if (arg_fth == "FLSyst") {
            f++;
            std::string out(*(argv + f));
            delSystFL = atof(out.c_str());
        } else if (arg_fth == "F0Tot") {
            f++;
            std::string out(*(argv + f));
            delTotF0 = atof(out.c_str());
        } else if (arg_fth == "FLTot") {
            f++;
            std::string out(*(argv + f));
            delTotFL = atof(out.c_str());
        } else if (arg_fth == "nW7") {
            f++;
            std::string out(*(argv + f));
            nW7 = atof(out.c_str());
        } else if (arg_fth == "ntop7") {
            f++;
            std::string out(*(argv + f));
            nTop7 = atof(out.c_str());
        } else if (arg_fth == "signal") {
            f++;
            std::string out(*(argv + f));
            file = new TFile(out.c_str(), "read");
            bool muonfile = false;
            for (unsigned int i = 0; i < namings.size(); i++) {
                int pos = string(file->GetName()).find(namings[i].c_str());
                muonfile = (pos >= 0 && pos < string(file->GetName()).size());
                if (muonfile) {
                    if (iRandom == 0) {
                        cout << "I am in " << channel << " channel and I accept ";
                        cout << file->GetName() << " as signal" << endl;
                    }
                    break;
                }
            }

            if (!do3D || (do3D && !muonfile)) {
                signalIID.push_back(((TH2*) file->Get("Default_allW/Default_allWcosTheta2D"))->RebinY(nReBin));
                //                signalIID.at(signalIID.size() - 1)->Scale(ratio);
                //                cout << signalIID.at(signalIID.size() - 1)->GetName() << endl;
            }//                else
            //                signalIID.push_back(((TH2*) ((TH3D*) file->Get("Default_allW/Default_allWcosTheta3D"))->Project3D("yx"))->Rebin2D(1,1));
            if (do3D && muonfile) {
                //                cout << " in 3D :-)" << endl;
                signalIIID.push_back(((TH3D*) file->Get("Default_allW/Default_allWcosTheta3D"))->Rebin3D(1, nReBin, 1, "newname"));
                //                cout << signalIIID.at(signalIIID.size() - 1) << endl;
                //                signalIIID.at(signalIIID.size() - 1)->Scale(ratio);
            }
            if (bkginsignal == 0)
                bkginsignal = (((TH1*) file->Get("Default_allW/Default_allWcosTheta"))->Rebin(nReBin));
            else
                bkginsignal->Add(((TH1*) file->Get("Default_allW/Default_allWcosTheta"))->Rebin(nReBin));

            TH1 * myTemp = (TH1*) (((TH1*) file->Get("Default_allW/Default_allWcosTheta")))->Clone("myTemp");
            if (iRandom == 0) {
                if (!muonfile) {
                    cout << " : " << signalIID.at(signalIID.size() - 1)->Integral() << " + " << myTemp->Integral()
                            << " = " << signalIID.at(signalIID.size() - 1)->Integral() + myTemp->Integral() << endl;
                    sampleinfo[out] = signalIID.at(signalIID.size() - 1)->Integral() + myTemp->Integral();
                } else if (do3D) {
                    cout << " : " << signalIIID.at(signalIIID.size() - 1)->Integral() << " + " << myTemp->Integral()
                            << " = " << signalIIID.at(signalIIID.size() - 1)->Integral() + myTemp->Integral() << endl;
                    sampleinfo[out] = signalIIID.at(signalIIID.size() - 1)->Integral() + myTemp->Integral();
                }
            }
            delete myTemp;

        } else if (arg_fth == "data") {
            f++;
            std::string out(*(argv + f));
            cout << "data" << endl;
            file = new TFile(out.c_str(), "read");
            data = ((TH1*) file->Get("Default_allW/Default_allWcosTheta"))->Rebin(nReBin);
            cout << data << endl;
        } else if (arg_fth == "bkg") {
            f++;
            std::string out(*(argv + f));
            cout << "bkg" << endl;
            file = new TFile(out.c_str(), "read");
            if (bkg == NULL) {
                cout << "here .." << endl;
                bkg = ((TH1*) file->Get("Default_allW/Default_allWcosTheta"))->Rebin(nReBin);
            } else {
                bkg->Add(((TH1*) file->Get("Default_allW/Default_allWcosTheta"))->Rebin(nReBin));
            }
        } else if (arg_fth == "wtemplate") {
            f++;
            std::string out(*(argv + f));
            cout << "w template" << endl;
            file = new TFile(out.c_str(), "read");
            cout << out << "\t";
            wtemplate = ((TH1*) file->Get("Default_allW/Default_allWcosTheta"));
            cout << wtemplate << endl;
            wtemplate->Rebin(nReBin);
        } else if (arg_fth == "name") {
            f++;
            std::string out(*(argv + f));
            addname = out;
        }
    }
    cout << bkg << "\t" << data << "\t" << wtemplate << endl;
    wtemplate->Sumw2();
    wtemplate->Scale((double) 1. / (double) wtemplate->Integral());
    data->Print();

    cout << "In Bias fit: \n\tsize of 2D signal is " << signalIID.size() <<
            "\n\tsize of 3D signal is " << signalIIID.size() << endl;
    cout << "bkginsignal: " << bkginsignal->Integral() << " bkg: " << bkg->Integral() << endl;
    if (bkg != NULL && bkginsignal != NULL) {
        bkg->Add(bkginsignal);
    } else if (bkg == NULL && bkginsignal != NULL) {
        bkg = (TH1*) bkginsignal->Clone("myBkg");
    }
    //        bkg->Scale(ratio);
    cout << "bkg: " << bkg->Integral() << " data: " << data->Integral() << " signal: ";
    double nSignal = 0;
    for (unsigned int p = 0; p < signalIID.size(); p++) {
        nSignal += signalIID[p]->Integral();
        //            cout << signalIID[p]->Integral() << endl;
    }
    for (unsigned int p = 0; p < signalIIID.size(); p++) {
        nSignal += signalIIID[p]->Integral();
        //            cout << signalIIID[p]->Integral() << endl;
    }
    cout << nSignal << endl;
    WTempForCombination3D my3DInput;
    my3DInput.Wtemplate = (TH1*) wtemplate->Clone("Wtemp_Syst"); //normal
    my3DInput.rest.data = data;
    my3DInput.rest.nonRWs = bkg;
    my3DInput.rest.signalIID = signalIID;
    my3DInput.rest.signalIIID = signalIIID;


    pars.push_back(F0_);
    pars.push_back(FL_);
    pars.push_back(nTop7);
    pars.push_back(nW7);

    ChiSquaredCaculatorAndPlotter myChi2Syst(channel + string("_Chi2Syst_") + addname, pars, my3DInput, delSystF0, delSystFL);
    myChi2Syst.PrintOut();
    cout << "ChiSquared: " << myChi2Syst.GetChiSquared() << endl;
    cout << "NormalChiSquared: " << myChi2Syst.GetNormalizedChiSquared() << endl;
    myChi2Syst.WriteInfo();

    my3DInput.Wtemplate = (TH1*) wtemplate->Clone("Wtemp_Stat"); //normal
    ChiSquaredCaculatorAndPlotter myChi2Stat(channel + string("_Chi2Stat_") + addname, pars, my3DInput, delStatF0, delStatFL);
    myChi2Stat.PrintOut();
    cout << "ChiSquared: " << myChi2Stat.GetChiSquared() << endl;
    cout << "NormalChiSquared: " << myChi2Stat.GetNormalizedChiSquared() << endl;
    myChi2Stat.WriteInfo();

    my3DInput.Wtemplate = (TH1*) wtemplate->Clone("Wtemp_total"); //normal
    ChiSquaredCaculatorAndPlotter myChi2total(channel + string("_Chi2total_") + addname, pars, my3DInput, delTotF0, delTotFL);
    myChi2total.PrintOut();
    cout << "ChiSquared: " << myChi2total.GetChiSquared() << endl;
    cout << "NormalChiSquared: " << myChi2total.GetNormalizedChiSquared() << endl;
    myChi2total.WriteInfo();



    return 0;
}
Пример #20
0
void Process(TString fname, TString oldFolder, int toMass, int fromMass)
{




  std::string channels[] = {"data_obs", "WH", "TT",  "WjLF", "WjHF", "ZjLF", "ZjHF" , "VV" , "s_Top"};
  std::string systs[] = {"eff_b", "fake_b", "res_j", "scale_j" , "stat" };

  kount = 0;  

  gROOT->SetStyle("Plain");
  setTDRStyle();

  TFile * file = new TFile(fname.Data(), "READ");
  std::cout << "reading " << fname.Data() << std::endl;
  TString outname(massS[toMass]);
  outname.Append("_June8.root");
  fname.ReplaceAll(".root",outname.Data());
 
///BEGIN CHECK RBIN
  int addRightBin = 0, addRightBinm1 = 0 , rightBinNo = 0;
  float a,overflow;
  RooWorkspace *mytempWS =  (RooWorkspace*) file->Get(oldFolder.Data());
  RooRealVar BDT("CMS_vhbb_BDT_Wln", "BDT", -1, 1);

  float Signal = 0;
  float Background = 0;
  float Backgroundm1 = 0;
  float Data = 0;

  RooDataHist* tempRooDataHistNomS = (RooDataHist*)  mytempWS->data(channels[1].c_str());
  TH1 *tempHistNomS = tempRooDataHistNomS->createHistogram(channels[1].c_str(),BDT,RooFit::Binning(bins));
  tempHistNomS->Rebin(rebin);


  TH1 *tempHistNomD = tempRooDataHistNomS->createHistogram(channels[0].c_str(),BDT,RooFit::Binning(bins));
  tempHistNomD->Rebin(rebin);



  for(int i = 1; i <= tempHistNomS->GetNbinsX(); i++)
  { 
    if(tempHistNomS->GetBinContent(i) > 0)
      { rightBinNo = i; Signal = tempHistNomS->GetBinContent(i); Data = tempHistNomS->GetBinError(i); }
  }

  for(int i = 2; i < 9; i++)
  {
   RooDataHist* tempRooDataHistNom = (RooDataHist*)  mytempWS->data(channels[i].c_str());
   TH1 *tempHistNom = tempRooDataHistNom->createHistogram(channels[i].c_str(),BDT,RooFit::Binning(bins));
   tempHistNom->Rebin(rebin);
   Background += tempHistNom->GetBinContent(rightBinNo);
   

   //   if(tempHistNom->GetBinContent(rightBinNo-1) == 0)
   // {
   // Backgroundm1 = 0;  
   //std::cout << "ARGHGHGHGHGH bkg is 0 still at left" << std::endl;
   //   std::cin >> ;
   // }

   Backgroundm1+=  tempHistNom->GetBinContent(rightBinNo-1); 

   overflow = tempHistNom->GetBinContent(rightBinNo+1) ;
   
   if(tempHistNom->GetBinContent(rightBinNo+1) > 0)
   {
   std::cout << "ARGHGHGHGHGH overflow at right" << std::endl;
   //   std::cin >> ;
   }
   a+= overflow;
  }

  if( (Background ==0) ) addRightBin = 1;
else  addRightBin = 0;


std::cout << "################# folder" << oldFolder << std::endl;
 std::cout<< "################# CHECK RBIN:: right bin n  " << rightBinNo << " signal: " << Signal << " bkg: " << Background << " bkgm1: " <<  Backgroundm1  << " Data:  " << Data <<  " at right there is an overflow of: "<< a << std::endl;
std::cout << "########################### CHECK RBIN:: REBINNING: " << addRightBin << std::endl;  
 if ( (Backgroundm1 == 0)  ) 
   { addRightBinm1 =1 ;
     std::cout << "ARGHGHGHGHGH " << Backgroundm1 << " at left" << std::endl;
    
   }

std::cout << "########################### need to rebin further? " << addRightBinm1  << std::endl;  
///END CHECK RBIN



  TFile * outfile = new TFile(fname.Data(), "RECREATE");
  using namespace RooFit;
  RooWorkspace *myWS = new RooWorkspace(oldFolder.Data(),oldFolder.Data());
  myWS->factory("CMS_vhbb_BDT_Wln[-1.,1.]"); ///NEW VARIABLE NAME HERE 

  TString oldFolder2(oldFolder.Data());
  oldFolder2.Append("2");
  RooWorkspace *myWS2 = new RooWorkspace(oldFolder2.Data(),oldFolder2.Data());
  myWS2->factory("CMS_vhbb_BDT_Wln[-1.,1.]"); ///NEW VARIABLE NAME HERE 

///BEGIN CHECK RBIN
  int addRightBin2=0, rightBinNo2=0, addRightBin2m1=0;
  float a2,overflow2;
  RooWorkspace *mytempWS2 =  (RooWorkspace*) file->Get(oldFolder2.Data());
   RooRealVar BDT2("CMS_vhbb_BDT_Wln", "BDT", -1, 1);

  float Signal2 = 0;
  float Background2 = 0;
  float Background2m1 = 0;
  float Data2 = 0;
  RooDataHist* tempRooDataHistNomS2 = (RooDataHist*)  mytempWS2->data(channels[1].c_str());
  RooDataHist* tempRooDataHistNomD2 = (RooDataHist*)  mytempWS2->data(channels[0].c_str());

  TH1 *tempHistNomS2 = tempRooDataHistNomS2->createHistogram(channels[1].c_str(),BDT2,RooFit::Binning(bins));
  tempHistNomS2->Rebin(rebin);

  TH1 *tempHistNomD2 = tempRooDataHistNomD2->createHistogram(channels[0].c_str(),BDT2,RooFit::Binning(bins));
  tempHistNomD2->Rebin(rebin);


  for(int i = 1; i <= tempHistNomS2->GetNbinsX(); i++)
  { 
    //    std::cout << "############    signal in bin " << i << " is " << tempHistNomS2->GetBinContent(i) << std::endl;
    // std::cout << "############    data in bin " << i << " is " << tempHistNomD2->GetBinContent(i) << std::endl;
    if(tempHistNomS2->GetBinContent(i) > 0)
      { rightBinNo2 = i; Signal2 = tempHistNomS2->GetBinContent(i); Data2 = tempHistNomD2->GetBinContent(i) ;}

  }


  

  for(int i = 2; i < 9; i++)
  {
   RooDataHist* tempRooDataHistNom2 = (RooDataHist*)  mytempWS2->data(channels[i].c_str());
   TH1 *tempHistNom2 = tempRooDataHistNom2->createHistogram(channels[i].c_str(),BDT2,RooFit::Binning(bins));
   tempHistNom2->Rebin(rebin);
   Background2 += tempHistNom2->GetBinContent(rightBinNo2);
   
   overflow2 = tempHistNom2->GetBinContent(rightBinNo2+1) ;

    Background2m1+=  tempHistNom2->GetBinContent(rightBinNo2-1); 


 
   if(tempHistNom2->GetBinContent(rightBinNo2+1) > 0)
   {
   std::cout << "ARGHGHGHGHGH" << std::endl;
   //   std::cin >> ;
   }
   a2+= overflow2;
  }

  if( (Background2 ==0) ) addRightBin2 = 1;
else  addRightBin2 = 0;
    if( (Background2m1 ==0) ) addRightBin2m1 = 1;
std::cout << "################# folder" << oldFolder2 << std::endl;
 std::cout << "################# CHECK RBIN:: right bin n  " << rightBinNo2 << " signal: " << Signal2 << " bkg: " << Background2 <<   " bkgm1: " <<  Background2m1  << " Data:  " << Data2 <<   " at right there is an overflow of: "<< a2 << std::endl;
std::cout << "########################### CHECK RBIN:: REBINNING: " << addRightBin2 << std::endl;  
std::cout << "########################### need to rebin further? " << addRightBin2m1 << std::endl;  
///END CHECK RBIN

  
  
  for (int c =0; c<9; c++)
  {
     kount2 = 0;  
    for (int s =0; s<5 ; s++ ){
      makeSystPlot( file, oldFolder, myWS,  channels[c], systs[s], toMass, fromMass,  rightBinNo, addRightBin, addRightBinm1  );
      makeSystPlot( file, oldFolder2, myWS2,  channels[c], systs[s] , toMass, fromMass,  rightBinNo2, addRightBin2, addRightBin2m1 );
    }
  }


  if(!(IFILE.Contains("8TeV")))
  {
    makeSystPlot(file, oldFolder, myWS, "WjLF", "WModel",toMass, fromMass, rightBinNo, addRightBin ,addRightBinm1 );
    makeSystPlot(file, oldFolder, myWS, "WjHF", "WModel",toMass, fromMass, rightBinNo, addRightBin, addRightBinm1  );


    makeSystPlot(file, oldFolder2, myWS2, "WjLF", "WModel",toMass, fromMass, rightBinNo2, addRightBin2 , addRightBin2m1);
    makeSystPlot(file, oldFolder2, myWS2, "WjHF", "WModel",toMass, fromMass, rightBinNo2, addRightBin2, addRightBin2m1 );
  }

  myWS->writeToFile(fname.Data());  
  std::cout << std::endl << std::endl << std::endl << std::endl << "///////////////////////////" << std::endl;
  std::cout << fname.Data() << " written" << std::endl;
  std::cout << "///////////////////////////" << std::endl << std::endl << std::endl;


  outfile->Write();
  outfile->Close();
  fname.ReplaceAll("June8","June82");
  TFile * outfile2 = new TFile(fname.Data(), "RECREATE");
  myWS2->writeToFile(fname.Data());  
  std::cout << std::endl << std::endl << std::endl << std::endl << "///////////////////////////" << std::endl;
  std::cout << fname.Data() << " written" << std::endl;
  std::cout << "///////////////////////////" << std::endl << std::endl << std::endl;


}
Пример #21
0
void makeSystPlot( TFile * f, TString oldFolder, RooWorkspace *WS,  string channel, string syst, int toMassNo, int fromMassNo, int rightBinNo, int addRightBin,  int addRightBinm1) //massNo 0-51, see xSec7TeV.h 
{


  std::cout << "oldFolder,  channel , addRightBin, addRightBinm1: " << oldFolder << " , " <<channel << " , " << addRightBin  << " , "<< addRightBinm1 << std::endl;

  RooArgList  * hobs = new RooArgList("hobs");
  //  RooRealVar BDT("BDT", "BDT", -1, 1);///OLD VARIABLE NAME HERE
  RooRealVar BDT("CMS_vhbb_BDT_Wln", "CMS_vhbb_BDT_Wln", -1, 1);///OLD VARIABLE NAME HERE
  hobs->add(*WS->var("CMS_vhbb_BDT_Wln"));  ///NEW VARIABLE NAME HERE
  RooWorkspace *tempWS =  (RooWorkspace*) f->Get(oldFolder.Data());
  TString systT(syst);
  TString chanT(channel);

  if((kount < 3) && (channel=="data_obs"))
  {
    kount++;
    std::string namen  = channel;
    
    std::cout << oldFolder.Data() << std::endl;
    std::cout << namen << std::endl;
    RooDataHist* tempRooDataHistNom = (RooDataHist*)  tempWS->data(namen.c_str());
    TH1 *tempHistNom = tempRooDataHistNom->createHistogram(namen.c_str(),BDT,RooFit::Binning(bins));

   tempHistNom->Rebin(rebin);

 if(addRightBin == 1)
    {
     float  err0 = tempHistNom->GetBinError(rightBinNo);
     float  con0 = tempHistNom->GetBinContent(rightBinNo);
 
     float  err1 = tempHistNom->GetBinError(rightBinNo-1);
     float  con1 = tempHistNom->GetBinContent(rightBinNo-1);
       
     tempHistNom->SetBinContent(rightBinNo,0);
     tempHistNom->SetBinError(rightBinNo,0);
     tempHistNom->SetBinContent(rightBinNo-1,con0+con1);
     tempHistNom->SetBinError(rightBinNo-1,sqrt(err0*err0+err1*err1));
    }


 if(addRightBinm1 == 1)
    {
     float  err0 = tempHistNom->GetBinError(rightBinNo-1);
     float  con0 = tempHistNom->GetBinContent(rightBinNo-1);
 
     float  err1 = tempHistNom->GetBinError(rightBinNo-2);
     float  con1 = tempHistNom->GetBinContent(rightBinNo-2);
       
     tempHistNom->SetBinContent(rightBinNo-1,0);
     tempHistNom->SetBinError(rightBinNo-1,0);
     tempHistNom->SetBinContent(rightBinNo-2,con0+con1);
     tempHistNom->SetBinError(rightBinNo-2,sqrt(err0*err0+err1*err1));
    }





    RooDataHist *DHnom = new RooDataHist(channel.c_str(),"",*hobs,tempHistNom);  
    WS->import(*(new RooHistPdf(channel.c_str(),"",*hobs,*DHnom)));
 
 }

 if (channel!="data_obs")
{
  std::string nameUp; 
  std::string namen; 
  std::string nameDown;


  if(syst == "stat")
  {
   if(oldFolder.Contains("Wenu"))
   { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_WenuUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_WenuDown";

     if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_WenuUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_WenuDown";
     }

   }
   else
   {
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_WmunuUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_WmunuDown";

     if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_WmunuUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_WmunuDown";
     }


   }
  }
  else
  {
  nameUp  = channel + "_CMS_" + syst + "Up";
  namen  = channel;
  nameDown = channel + "_CMS_" + syst + "Down";
  }
 
  if((syst == "stat") && (oldFolder.Contains("2")))
  {
   if(oldFolder.Contains("Wenu"))
   { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_Wenu2Up";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wenu2Down";

     if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wenu2Up";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wenu2Down";
     }

   }
   else
   {
     nameUp  = channel + "_CMS_vhbb_stat" + channel +  "_Wmunu2Up";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wmunu2Down";

     if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wmunu2Up";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wmunu2Down";
     }


   }
  }

  if(systT.Contains("Model"))
  {
     nameUp  = channel + "_CMS_vhbb_WModelUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_WModelDown";
  }

  if( systT.Contains("stat") && (oldFolder.Contains("Wenu")) && IFILE.Contains("8TeV") && !(oldFolder.Contains("2")))
  { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_Wenu_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wenu_8TeVDown";

   if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wenu_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wenu_8TeVDown";
     }


  }

  if( systT.Contains("stat") && (oldFolder.Contains("Wmunu")) && IFILE.Contains("8TeV") && !(oldFolder.Contains("2")))
  { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_Wmnu_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wmnu_8TeVDown";

   if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wmnu_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wmnu_8TeVDown";
     }


  }


  if( systT.Contains("stat") && (oldFolder.Contains("Wenu")) && IFILE.Contains("8TeV") && (oldFolder.Contains("2")))
  { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_Wenu2_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wenu2_8TeVDown";

   if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wenu2_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wenu2_8TeVDown";
     }


  }

  if( systT.Contains("stat") && (oldFolder.Contains("Wmunu")) && IFILE.Contains("8TeV") && (oldFolder.Contains("2")))
  { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_Wmnu2_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wmnu2_8TeVDown";

   if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wmnu2_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wmnu2_8TeVDown";
     }


  }







  RooDataHist* tempRooDataHistUp = (RooDataHist*)  tempWS->data(nameUp.c_str());
  RooDataHist* tempRooDataHistDown = (RooDataHist*)  tempWS->data(nameDown.c_str());
  RooDataHist* tempRooDataHistNom = (RooDataHist*)  tempWS->data(namen.c_str());


  std::cout << oldFolder.Data() << std::endl; 
  std::cout << nameUp.c_str() << std::endl; 
  

  


  TH1 *tempHistUp = tempRooDataHistUp->createHistogram(nameUp.c_str(),BDT,RooFit::Binning(bins));
  TH1 *tempHistDown = tempRooDataHistDown->createHistogram(nameDown.c_str(),BDT,RooFit::Binning(bins));
  TH1 *tempHistNom = tempRooDataHistNom->createHistogram(namen.c_str(),BDT,RooFit::Binning(bins));
  
  if(chanT.Contains("WH") && IFILE.Contains("7TeV"))
  {
     tempHistUp->Scale(xSec7WH[toMassNo]/xSec7WH[fromMassNo]);
     tempHistDown->Scale(xSec7WH[toMassNo]/xSec7WH[fromMassNo]);
     tempHistNom->Scale(xSec7WH[toMassNo]/xSec7WH[fromMassNo]);
  }  
 
  if(chanT.Contains("WH") && IFILE.Contains("8TeV"))
  {
     tempHistUp->Scale(xSec8WH[toMassNo]/xSec8WH[fromMassNo]);
     tempHistDown->Scale(xSec8WH[toMassNo]/xSec8WH[fromMassNo]);
     tempHistNom->Scale(xSec8WH[toMassNo]/xSec8WH[fromMassNo]);
  }  
  
  std::cout<< "channel--> " << channel << std::endl;


    
  tempHistUp->SetLineColor(kRed);
  tempHistUp->SetLineWidth(3);
  tempHistUp->SetFillColor(0);
  
  tempHistDown->SetLineColor(kBlue);
  tempHistDown->SetFillColor(0);
  tempHistDown->SetLineWidth(3);
  
  tempHistNom->SetFillColor(0);
  tempHistNom->SetMarkerStyle(20);
    
  tempHistUp->SetTitle((channel + syst).c_str());
 
  tempHistNom->Rebin(rebin);
  tempHistUp->Rebin(rebin);
  tempHistDown->Rebin(rebin);


 if(addRightBin == 1)
    {
     float  err0 = tempHistNom->GetBinError(rightBinNo);
     float  con0 = tempHistNom->GetBinContent(rightBinNo);
 
     float  err1 = tempHistNom->GetBinError(rightBinNo-1);
     float  con1 = tempHistNom->GetBinContent(rightBinNo-1);
       
     tempHistNom->SetBinContent(rightBinNo,0);
     tempHistNom->SetBinError(rightBinNo,0);
     tempHistNom->SetBinContent(rightBinNo-1,con0+con1);
     tempHistNom->SetBinError(rightBinNo-1,sqrt(err0*err0+err1*err1));


     err0 = tempHistUp->GetBinError(rightBinNo);
     con0 = tempHistUp->GetBinContent(rightBinNo);
 
     err1 = tempHistUp->GetBinError(rightBinNo-1);
     con1 = tempHistUp->GetBinContent(rightBinNo-1);
       
     tempHistUp->SetBinContent(rightBinNo,0);
     tempHistUp->SetBinError(rightBinNo,0);
     tempHistUp->SetBinContent(rightBinNo-1,con0+con1);
     tempHistUp->SetBinError(rightBinNo-1,sqrt(err0*err0+err1*err1));



     err0 = tempHistDown->GetBinError(rightBinNo);
     con0 = tempHistDown->GetBinContent(rightBinNo);
 
     err1 = tempHistDown->GetBinError(rightBinNo-1);
     con1 = tempHistDown->GetBinContent(rightBinNo-1);
       
     tempHistDown->SetBinContent(rightBinNo,0);
     tempHistDown->SetBinError(rightBinNo,0);
     tempHistDown->SetBinContent(rightBinNo-1,con0+con1);
     tempHistDown->SetBinError(rightBinNo-1,sqrt(err0*err0+err1*err1));

    }



 if(addRightBinm1 == 1)
    {
     float  err0 = tempHistNom->GetBinError(rightBinNo-1);
     float  con0 = tempHistNom->GetBinContent(rightBinNo-1);
 
     float  err1 = tempHistNom->GetBinError(rightBinNo-2);
     float  con1 = tempHistNom->GetBinContent(rightBinNo-2);
       
     tempHistNom->SetBinContent(rightBinNo-1,0);
     tempHistNom->SetBinError(rightBinNo-1,0);
     tempHistNom->SetBinContent(rightBinNo-2,con0+con1);
     tempHistNom->SetBinError(rightBinNo-2,sqrt(err0*err0+err1*err1));


     err0 = tempHistUp->GetBinError(rightBinNo-1);
     con0 = tempHistUp->GetBinContent(rightBinNo-1);
 
     err1 = tempHistUp->GetBinError(rightBinNo-2);
     con1 = tempHistUp->GetBinContent(rightBinNo-2);
       
     tempHistUp->SetBinContent(rightBinNo-1,0);
     tempHistUp->SetBinError(rightBinNo-1,0);
     tempHistUp->SetBinContent(rightBinNo-2,con0+con1);
     tempHistUp->SetBinError(rightBinNo-2,sqrt(err0*err0+err1*err1));



     err0 = tempHistDown->GetBinError(rightBinNo-1);
     con0 = tempHistDown->GetBinContent(rightBinNo-1);
 
     err1 = tempHistDown->GetBinError(rightBinNo-2);
     con1 = tempHistDown->GetBinContent(rightBinNo-2);
       
     tempHistDown->SetBinContent(rightBinNo-1,0);
     tempHistDown->SetBinError(rightBinNo-1,0);
     tempHistDown->SetBinContent(rightBinNo-2,con0+con1);
     tempHistDown->SetBinError(rightBinNo-2,sqrt(err0*err0+err1*err1));

    }




  RooDataHist *DHnom;
  RooDataHist *DHup = new RooDataHist(nameUp.c_str(),"",*hobs,tempHistUp);  
  if(kount2 < 3) DHnom = new RooDataHist(namen.c_str(),"",*hobs,tempHistNom);
  RooDataHist *DHdown = new RooDataHist(nameDown.c_str(),"",*hobs,tempHistDown);  

  WS->import(*(new RooHistPdf(nameUp.c_str(),"",*hobs,*DHup)));
  WS->import(*(new RooHistPdf(nameDown.c_str(),"",*hobs,*DHdown)));
  if(kount2 < 3){ WS->import(*(new RooHistPdf(namen.c_str(),"",*hobs,*DHnom))); kount2++;}

 }


}
Пример #22
0
void ptBestFit(float BIN_SIZE=5.0,bool BLIND=false,TString MASS,TString NAME)
{
  gROOT->ProcessLine(".x ../../common/styleCMSTDR.C");
  gSystem->Load("libHiggsAnalysisCombinedLimit.so");
  gROOT->ForceStyle();
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);
  gROOT->SetBatch(1);
  gStyle->SetPadRightMargin(0.04);
  gStyle->SetPadLeftMargin(0.16);
  gStyle->SetPadTopMargin(0.06);
  gStyle->SetPadBottomMargin(0.10);
  gStyle->SetTitleFont(42,"XY");
  gStyle->SetTitleSize(0.0475,"XY");
  gStyle->SetTitleOffset(0.9,"X");
  gStyle->SetTitleOffset(1.5,"Y");
  gStyle->SetLabelSize(0.0375,"XY");

  RooMsgService::instance().setSilentMode(kTRUE);
  for(int i=0;i<2;i++) {
    RooMsgService::instance().setStreamStatus(i,kFALSE);
  }
  float XMIN = 80;
  float XMAX = 200; 

  TFile *f1 = TFile::Open("datacards/datacard_m"+MASS+"_"+NAME+".root");
  TFile *f2 = TFile::Open("combine/mlfit.vbfHbb_"+NAME+"_mH"+MASS+".root");
  TFile *f3 = TFile::Open("root/sig_shapes_workspace_B80-200.root");
  TFile *f4 = TFile::Open("root/data_shapes_workspace_"+NAME+".root");

  RooWorkspace *w = (RooWorkspace*)f1->Get("w");
  //w->Print();
  RooAbsPdf *bkg_model = (RooAbsPdf*)w->pdf("model_s");
  RooFitResult *res_s  = (RooFitResult*)f2->Get("fit_s"); 
  RooFitResult *res_b  = (RooFitResult*)f2->Get("fit_b");
  RooRealVar *rFit     = dynamic_cast<RooRealVar *>(res_s->floatParsFinal()).find("r");
  RooDataSet *data     = (RooDataSet*)w->data("data_obs");
  
  int nparS=0,nparB=0;
  cout << res_s->floatParsFinal().getSize() << endl;
  cout << res_b->floatParsFinal().getSize() << endl;
  nparS = res_s->floatParsFinal().getSize();
  nparB = res_b->floatParsFinal().getSize();  
  float chi2sumS = 0.;
  float chi2sumB = 0.;
  int nparsum = 0;
//  if (BLIND) {
//    res_b->Print();
//  }
//  else {
//    res_s->Print();
//  }
  
  w->allVars().assignValueOnly(res_s->floatParsFinal());
//  w->Print();
//  w->allVars()->Print();

  RooWorkspace *wSig = (RooWorkspace*)f3->Get("w"); 
  RooWorkspace *wDat = (RooWorkspace*)f4->Get("w"); 

  const RooSimultaneous *sim = dynamic_cast<const RooSimultaneous *> (bkg_model);
  const RooAbsCategoryLValue &cat = (RooAbsCategoryLValue &) sim->indexCat();
  TList *datasets = data->split(cat,true);
  TIter next(datasets);
  //int count = 0; 
  for(RooAbsData *ds = (RooAbsData*)next();ds != 0; ds = (RooAbsData*)next()) {
	 //if (count > 0) return 0;
	 //count++;
    RooAbsPdf *pdfi = sim->getPdf(ds->GetName());
    RooArgSet *obs = (RooArgSet*)pdfi->getObservables(ds);
    RooRealVar *x = dynamic_cast<RooRealVar *>(obs->first());

    RooRealVar *yield_vbf = (RooRealVar*)wSig->var("yield_signalVBF_mass"+MASS+"_"+TString(ds->GetName()));
    RooRealVar *yield_gf  = (RooRealVar*)wSig->var("yield_signalGF_mass"+MASS+"_"+TString(ds->GetName()));
    TString ds_name(ds->GetName());
    //----- get the QCD normalization -----------
    RooRealVar *qcd_norm_final = dynamic_cast<RooRealVar *>(res_s->floatParsFinal()).find("CMS_vbfbb_qcd_norm_"+ds_name);
    RooRealVar *qcd_yield      = (RooRealVar*)wDat->var("yield_data_"+ds_name);

    float Nqcd  = exp(log(1.5)*qcd_norm_final->getVal())*qcd_yield->getVal();
    float eNqcd = log(1.5)*qcd_norm_final->getError()*Nqcd;
    cout<<"QCD normalization = "<<Nqcd<<" +/- "<<eNqcd<<endl;
    
    TH1 *hCoarse = (TH1*)ds->createHistogram("coarseHisto_"+ds_name,*x);
    float norm = hCoarse->Integral();
  
	 int rebin = BIN_SIZE/hCoarse->GetBinWidth(1);
    hCoarse->Rebin(rebin);

    float MIN_VAL = TMath::Max(0.9*hCoarse->GetBinContent(hCoarse->GetMinimumBin()),1.0);
    float MAX_VAL = 1.3*hCoarse->GetBinContent(hCoarse->GetMaximumBin());
    RooDataHist ds_coarse("ds_coarse_"+ds_name,"ds_coarse_"+ds_name,*x,hCoarse);

    TH1F *hBlind = (TH1F*)hCoarse->Clone("blindHisto_"+ds_name);
    for(int i=0;i<hBlind->GetNbinsX();i++) {
      double x0 = hBlind->GetBinCenter(i+1);
      if (x0 > 100 && x0 < 150) {
        hBlind->SetBinContent(i+1,0);
        hBlind->SetBinError(i+1,0);
      }
    }
    
    RooDataHist ds_blind("ds_blind_"+ds_name,"ds_blind_"+ds_name,*x,hBlind); 
    
    RooHist *hresid,*hresid0;
    RooPlot *frame1 = x->frame();
    RooPlot *frame2 = x->frame();
    
    if (BLIND) {
		//cout << "Blind case: " << ds_coarse.GetName() << endl;
      ds_coarse.plotOn(frame1,LineColor(0),MarkerColor(0));
      pdfi->plotOn(frame1,Components("shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name),VisualizeError(*res_s,1,kTRUE),FillColor(0),MoveToBack());
      pdfi->plotOn(frame1,Components("shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name),LineWidth(2),LineStyle(3));
      ds_blind.plotOn(frame1);
      hresid = frame1->residHist();
      frame2->addPlotable(hresid,"pE1");
    }
    else {    
		//cout << "Non-blind case: " << ds_coarse.GetName() << endl;
		ds_coarse.plotOn(frame1);
      pdfi->plotOn(frame1);
		//cout << pdfi->getParameters(ds_coarse)->selectByAttrib("Constant",kFALSE)->getSize() << endl;
      cout<<"chi2/ndof (bkg+sig) = "<<frame1->chiSquare()<<endl;
		cout << ds_coarse.numEntries() << endl;
		chi2sumS += frame1->chiSquare()*ds_coarse.numEntries();
		nparsum += ds_coarse.numEntries();
		//hresid0 = frame1->residHist();
      //pdfi->plotOn(frame1,VisualizeError(*res_s,1,kTRUE),FillColor(0),MoveToBack());
      pdfi->plotOn(frame1,Components("shapeBkg_qcd_"+ds_name),LineWidth(2),LineStyle(5),LineColor(kGreen+2));
      pdfi->plotOn(frame1,Components("shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name),LineWidth(2),LineStyle(2),LineColor(kBlack)); 
      cout<<"chi2/ndof (bkg) = "<<frame1->chiSquare()<<endl;
		chi2sumB += frame1->chiSquare()*ds_coarse.numEntries();
		pdfi->plotOn(frame1,Components("shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name),LineWidth(2),LineStyle(2),LineColor(kBlack),VisualizeError(*res_s,1,kTRUE),FillColor(0),MoveToBack()); 
      hresid = frame1->residHist();
      frame2->addPlotable(hresid,"pE1");
    
      float yield_sig = rFit->getValV()*(yield_vbf->getValV()+yield_gf->getValV());
      RooAbsPdf *signal_pdf = (RooAbsPdf*)w->pdf("shapeSig_qqH_"+ds_name);
      signal_pdf->plotOn(frame2,LineWidth(2),LineColor(kRed),Normalization(yield_sig,RooAbsReal::NumEvent),MoveToBack());
    }
//	 hresid0->Print();
//	 hresid->Print();
//	 double x2,y2;
//	 for (int i=0; i<3; ++i) {
//		 hresid0->GetPoint(i,x2,y2);
//		 cout << "BKG+SIG\t" << x2 << "\t" << y2 << endl;
//		 hresid->GetPoint(i,x2,y2);
//		 cout << "BKG\t" << x2 << "\t" << y2 << endl;
//		 ds_coarse.get(i);
//		 cout << ds_coarse.weightError(RooAbsData::SumW2) << endl;
//		 cout << endl;
//	 }

    TCanvas* canFit = new TCanvas("Higgs_fit_"+ds_name,"Higgs_fit_"+ds_name,900,750);
    canFit->cd(1)->SetBottomMargin(0.4);
    frame1->SetMinimum(MIN_VAL);
    frame1->SetMaximum(MAX_VAL);
    frame1->GetYaxis()->SetNdivisions(510);
    frame1->GetXaxis()->SetTitleSize(0);
    frame1->GetXaxis()->SetLabelSize(0);
    frame1->GetYaxis()->SetTitle(TString::Format("Events / %1.1f GeV",BIN_SIZE));
    frame1->Draw();
    gPad->Update();
    
    TList *list = (TList*)gPad->GetListOfPrimitives();
    //list->Print();
    TH1F *hUncH  = new TH1F("hUncH"+ds_name,"hUncH"+ds_name,(XMAX-XMIN)/BIN_SIZE,XMIN,XMAX);
    TH1F *hUncL  = new TH1F("hUncL"+ds_name,"hUncL"+ds_name,(XMAX-XMIN)/BIN_SIZE,XMIN,XMAX);
    TH1F *hUnc2H = new TH1F("hUnc2H"+ds_name,"hUnc2H"+ds_name,(XMAX-XMIN)/BIN_SIZE,XMIN,XMAX);
    TH1F *hUnc2L = new TH1F("hUnc2L"+ds_name,"hUnc2L"+ds_name,(XMAX-XMIN)/BIN_SIZE,XMIN,XMAX); 
    TH1F *hUncC  = new TH1F("hUncC"+ds_name,"hUncC"+ds_name,(XMAX-XMIN)/BIN_SIZE,XMIN,XMAX); 
    
    RooCurve *errorBand,*gFit,*gQCDFit,*gBkgFit;
    
	//list->Print();
    if (BLIND) {
      errorBand = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]_errorband_Comp[shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name+"]");
      gFit = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]"+"_Comp[shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name+"]");
    }
    else {
      //errorBand = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]_errorband");
      errorBand = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]_errorband_Comp[shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name+"]");
      gFit = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]");
    } 
    gQCDFit = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]"+"_Comp[shapeBkg_qcd_"+ds_name+"]");  
    gBkgFit = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]"+"_Comp[shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name+"]");
    for(int i=0;i<hUncH->GetNbinsX();i++) {
      double x0 = hUncH->GetBinCenter(i+1);
      double e1 = fabs(errorBand->Eval(x0)-gBkgFit->Eval(x0));
      //double e1 = fabs(errorBand->Eval(x0)-gFit->Eval(x0));
      double e2 = eNqcd/hUncH->GetNbinsX();
      hUncH->SetBinContent(i+1,sqrt(pow(e2,2)+pow(e1,2)));
      hUnc2H->SetBinContent(i+1,2*sqrt(pow(e2,2)+pow(e1,2)));
      hUncL->SetBinContent(i+1,-sqrt(pow(e2,2)+pow(e1,2)));
      hUnc2L->SetBinContent(i+1,-2*sqrt(pow(e2,2)+pow(e1,2)));
		hUncC->SetBinContent(i+1,0.);
    }
   
    TPad* pad = new TPad("pad", "pad", 0., 0., 1., 1.);
    pad->SetTopMargin(0.63);
    pad->SetFillColor(0);
    pad->SetFillStyle(0);
    pad->Draw();
    pad->cd(0);
    hUnc2H->GetXaxis()->SetTitle("m_{bb} (GeV)");
    hUnc2H->GetYaxis()->SetTitle("Data - Bkg");
    //hUnc2H->GetYaxis()->SetTitle("Data - Fit");
    double YMAX = 1.1*frame2->GetMaximum();
    double YMIN = -1.1*frame2->GetMaximum();
    hUnc2H->GetYaxis()->SetRangeUser(YMIN,YMAX);
    hUnc2H->GetYaxis()->SetNdivisions(507);
//    hUnc2H->GetXaxis()->SetTitleOffset(0.9);
//    hUnc2H->GetYaxis()->SetTitleOffset(1.0);
    hUnc2H->GetYaxis()->SetTickLength(0.0);
//    hUnc2H->GetYaxis()->SetTitleSize(0.05);
//    hUnc2H->GetYaxis()->SetLabelSize(0.04);
    hUnc2H->GetYaxis()->CenterTitle(kTRUE);
    hUnc2H->SetFillColor(kGreen);
    hUnc2L->SetFillColor(kGreen);
    hUncH->SetFillColor(kYellow);
    hUncL->SetFillColor(kYellow);
	 hUncC->SetLineColor(kBlack);
	 hUncC->SetLineStyle(7);
    hUnc2H->Draw("HIST");
    hUnc2L->Draw("same HIST");
    hUncH->Draw("same HIST");
    hUncL->Draw("same HIST");
	 hUncC->Draw("same HIST");
	 frame2->GetYaxis()->SetTickLength(0.03/0.4);
    frame2->Draw("same");

    TList *list1 = (TList*)gPad->GetListOfPrimitives();
    //list1->Print();
    RooCurve *gSigFit = (RooCurve*)list1->FindObject("shapeSig_qqH_"+ds_name+"_Norm[mbbReg_"+ds_name+"]");

    TLegend *leg = new TLegend(0.70,0.61,0.94,1.-gStyle->GetPadTopMargin()-0.01);
	 leg->SetTextFont(42);
	 leg->SetFillStyle(-1);
	 //leg->SetHeader(ds_name+" (m_{H}="+MASS+")");
    leg->SetHeader(TString::Format("Category %d",atoi(ds_name(3,1).Data())+1));
    leg->AddEntry(hBlind,"Data","P");
    if (!BLIND) {
      leg->AddEntry(gSigFit,"Fitted signal","L");
    }
	 TLine *gEmpty = new TLine(0.0,0.0,0.0,0.0);
	 gEmpty->SetLineWidth(0);
	 TLegendEntry *l1 = leg->AddEntry(gEmpty,"(m_{H} = "+MASS+" GeV)","");
	 l1->SetTextSize(0.038*0.97*0.85);
    leg->AddEntry(gFit,"Bkg. + signal","L");
    leg->AddEntry(gBkgFit,"Bkg.","L");
    leg->AddEntry(gQCDFit,"QCD","L");
    leg->AddEntry(hUnc2H,"2#sigma bkg. unc.","F");
    leg->AddEntry(hUncH,"1#sigma bkg. unc.","F");
    leg->SetFillColor(0);
    leg->SetBorderSize(0);
    leg->SetTextFont(42);
    leg->SetTextSize(0.038*0.98);
    leg->Draw(); 
	 leg->SetY1(leg->GetY2()-leg->GetNRows()*0.045*0.96);
     
    TPaveText *paveCMS = new TPaveText(gStyle->GetPadLeftMargin()+0.02,0.7,gStyle->GetPadLeftMargin()+0.15,1.-gStyle->GetPadTopMargin()-0.01,"NDC");
	 paveCMS->SetTextFont(62);
	 paveCMS->SetTextSize(gStyle->GetPadTopMargin()*3./4.);
	 paveCMS->SetBorderSize(0);
	 paveCMS->SetFillStyle(-1);
	 paveCMS->SetTextAlign(12);
	 paveCMS->AddText("CMS");
	 paveCMS->Draw();
	 gPad->Update();
	 paveCMS->SetY1NDC(paveCMS->GetY2NDC()-paveCMS->GetListOfLines()->GetSize()*gStyle->GetPadTopMargin());

	 TPaveText *paveLumi = new TPaveText(0.5,1.-gStyle->GetPadTopMargin(),0.98,1.00,"NDC");
	 paveLumi->SetTextFont(42);
	 paveLumi->SetTextSize(gStyle->GetPadTopMargin()*3./4.);
	 paveLumi->SetBorderSize(0);
	 paveLumi->SetFillStyle(-1);
	 paveLumi->SetTextAlign(32);
	 paveLumi->AddText(TString::Format("%.1f fb^{-1} (8TeV)",(atoi(ds_name(3,1).Data())<4 ? 19.8 : 18.3)).Data());//+ 18.2 ;
	 paveLumi->Draw();

	 TString path=".";
	 //TString path="BiasV10_limit_BRN5p4_dX0p1_B80-200_CAT0-6/output/";
	 system(TString::Format("[ ! -d %s/plot ] && mkdir %s/plot",path.Data(),path.Data()).Data());
	 system(TString::Format("[ ! -d %s/plot/fits ] && mkdir %s/plot/fits",path.Data(),path.Data()).Data());
	 canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s.pdf",path.Data(),MASS.Data(),ds_name.Data()).Data());
	 canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s.png",path.Data(),MASS.Data(),ds_name.Data()).Data());
	 canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s.eps",path.Data(),MASS.Data(),ds_name.Data()).Data());
	 TText *l = (TText*)paveCMS->AddText("Preliminary");
	 l->SetTextFont(52);
	 paveCMS->Draw();
	 gPad->Update();
	 paveCMS->SetY1NDC(paveCMS->GetY2NDC()-paveCMS->GetListOfLines()->GetSize()*gStyle->GetPadTopMargin());
	 canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s_prelim.pdf",path.Data(),MASS.Data(),ds_name.Data()).Data());
	 canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s_prelim.png",path.Data(),MASS.Data(),ds_name.Data()).Data());
	 canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s_prelim.eps",path.Data(),MASS.Data(),ds_name.Data()).Data());

    delete ds;
  }

  cout << "chi2sumS: " << chi2sumS << endl;
  cout << "chi2sumB: " << chi2sumB << endl;
  cout << "nparS: " << nparS << endl;
  cout << "nparB: " << nparB << endl;
  cout << "nbinsum: " << nparsum << endl;
  cout << "chi2sumS/(nbinsum - nparS): " << chi2sumS / (float)(nparsum - nparS) << endl;
  cout << "chi2sumB/(nbinsum - nparB): " << chi2sumB / (float)(nparsum - nparB) << endl;
  delete datasets; 
}