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

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

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

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

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

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

  delete Hmine;
  delete Hother;
}
Example #2
0
void pv_dist(const string& fFile, const string& fTitle, const string& fNameExt) {
  
   TH1F *h;
    
   TFile file(fFile.c_str());
   TDirectoryFile *dir = (TDirectoryFile*)file.Get("offsetAnalysis");
   TDirectoryFile *subDir = (TDirectoryFile*)dir->Get("PrimaryVertices");

   h = (TH1F*)subDir->Get("h_NofPVs"); 
   
   string name = h->GetName();
   string fileName = name + "__" + fNameExt + ".png";
   
   h->SetTitle(fTitle.c_str());
   
   TCanvas *c = new TCanvas("c","",1120,800);
   c->cd();
     
   h->SetLineWidth(2);
   h->Draw();
   
   c->SetLogy();
   c->SaveAs(fileName.c_str());
   
   delete c;
}
void KVElasticCountRates::PrintResults(Double_t beam_intensity)
{
   // Print mean energy deposit & counting rate for given beam intensity in particles per second

   TIter it(&fHistos);
   TH1F* h;
   fRates.clear();

   std::vector<count_rate> count_rates;

   while ((h = (TH1F*)it())) {
      TString name = h->GetName();
      if (!name.EndsWith("_dW") && !name.EndsWith("_map")) {
         TH2F* map = (TH2F*)fHistos.FindObject(name + "_map");
         double rate = h->Integral() * fAtomicDensity * beam_intensity * fVolume / fNtirages;
         double emean = h->GetMean();
         KVDetector* det = gMultiDetArray->GetDetector(name);
         double fluence = rate / det->GetEntranceWindowSurfaceArea();
         double dissipation = emean * rate / det->GetEntranceWindowSurfaceArea();
         count_rates.push_back(
            count_rate(name, rate, emean, map->GetMean(), map->GetMean(2), fluence, dissipation)
         );
         fRates[name.Data()] = KVElasticCountRate(rate, emean, fluence, dissipation);
      }
   }
   std::sort(count_rates.begin(), count_rates.end(), compare_count_rates);

   for (std::vector<count_rate>::iterator it = count_rates.begin(); it != count_rates.end(); ++it) {
      it->print();
   }
}
void make_histos_syst_rawyield(TString file_syst, TString file_default, TString out_tag){

  TFile *f1 = new TFile(file_syst.Data(),"read");
  TFile *f2 = new TFile(file_default.Data(),"read");
  TDirectoryFile *dir1 = (TDirectoryFile*)(f1->Get("effunf"));
  TDirectoryFile *dir2 = (TDirectoryFile*)(f2->Get("effunf"));
  TList *list = dir1->GetListOfKeys();

  TFile *f = new TFile(Form("plots/ratiosyst_%s.root",out_tag.Data()),"recreate");

  for (int i=0; i<list->GetSize(); i++){
    TString name = dir1->GetListOfKeys()->At(i)->GetName();
    if (!(name.Contains("hreco_"))) continue;
    TObject *obj1 = dir1->Get(name.Data());
    assert(obj1);
    TObject *obj2 = dir2->Get(name.Data());
    assert(obj2);
    TString newname = name;
    newname.Append("_ratiosyst");
    if (name.EndsWith("_0")) newname.ReplaceAll("_0_","_EBEB_");
    if (name.EndsWith("_1")) newname.ReplaceAll("_1_","_EBEE_");
    if (name.EndsWith("_2")) newname.ReplaceAll("_2_","_EEEE_");
    TH1F *h = (TH1F*)(((TH1F*)obj1)->Clone(newname.Data()));
    h->SetTitle(h->GetName());
    h->Divide((TH1F*)obj2);
    for (int j=0; j<h->GetNbinsX(); j++) h->SetBinError(j+1,0);
    for (int j=0; j<h->GetNbinsX(); j++) h->SetBinContent(j+1,1+fabs(1-h->GetBinContent(j+1)));
    f->cd();
    h->Write();
  }

}
void example(double E0 = 50, int nevents = 100000)
{
   TStopwatch timer;

   // compound nucleus = carbon
   KVNucleus CN(6, 12);
   CN.SetExcitEnergy(E0);

   // decay products
   KVEvent decay;
   KVNucleus* n = decay.AddParticle();
   n->SetZandA(1, 2);
   n = decay.AddParticle();
   n->SetZandA(2, 4);
   n = decay.AddParticle();
   n->SetZandA(3, 6);

   MicroStat::mdweight gps;
   Double_t etot = E0 + decay.GetChannelQValue();
   Double_t total_mass = decay.GetSum("GetMass");

   if (etot <= 0) {
      printf("Break-up channel is not allowed\n");
      return;
   }
   gps.SetWeight(&decay, etot);
   gps.initGenerateEvent(&decay);

   std::cout << "Edisp = " << etot << " MeV" << std::endl;
   KVHashList histos;
   TH1F* h;

   while ((n = decay.GetNextParticle())) {
      Double_t kappa = total_mass / (total_mass - n->GetMass());
      std::cout << n->GetSymbol() << " : max KE = " << 1. / kappa << " * " << etot << " MeV" << std::endl;
      std::cout << n->GetSymbol() << " : m/M = " << n->GetMass() / total_mass << " k = " << kappa << std::endl;
      histos.Add(h = new TH1F(n->GetSymbol(), Form("Kinetic energy of %s", n->GetSymbol()), 200, 0, etot));
      h->Sumw2();
   }
   KVEvent event;

   while (nevents--) {
      gps.GenerateEvent(&decay, &event);
      while ((n = event.GetNextParticle()))((TH1F*)histos.FindObject(n->GetSymbol()))->Fill(n->GetE());
      gps.resetGenerateEvent();
   }

   TIter it(&histos);

   while ((h = (TH1F*)it())) {

      KVNucleus part(h->GetName());
      new TCanvas;
      FitEDist(h, etot, decay.GetMult(), total_mass, part.GetMass());

   }

   timer.Print();
}
Example #6
0
//================================================
void DeltaZVsPt(const Int_t save = 0)
{
  THnSparseF *hn = (THnSparseF*)f->Get(Form("mhTrkDzDy_%s",trigName[kTrigType]));
  TH2F *hTrkDzVsPt = (TH2F*)hn->Projection(1,0);
  c = draw2D(hTrkDzVsPt,Form("%s: #Deltaz of matched track-hit pairs",trigName[kTrigType]));
  if(save) 
    {
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/DeltaZ_vs_pt_%s.pdf",run_type,trigName[kTrigType]));
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/DeltaZ_vs_pt_%s.png",run_type,trigName[kTrigType]));
    }

  Double_t pt_cut = 1;
  hTrkDzVsPt->GetXaxis()->SetRangeUser(pt_cut+0.1,100);
  TH1F *hMthDz = (TH1F*)hTrkDzVsPt->ProjectionY(Form("hTrkDzVsPt_%s_proj",trigName[kTrigType]));
  hMthDz->SetTitle(Form("%s: #Deltaz of matched track-hit pairs (p_{T}>%1.1f GeV/c);#Deltaz (cm)",trigName[kTrigType],pt_cut));
  TH1F *hClone = (TH1F*)hMthDz->Clone(Form("%s_clone",hMthDz->GetName()));
  c = draw1D(hClone,"",kFALSE,kFALSE);
  if(save) 
    {
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/DeltaZ_%s.pdf",run_type,trigName[kTrigType]));
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/DeltaZ_%s.png",run_type,trigName[kTrigType]));
    }

  Double_t range = 50;
  TF1 *func = new TF1("func","gaus(0)+gaus(3)",-1*range,range);
  func->SetParameters(10000,0,10,1000,0,40);
  c = FitDeltaZ(hMthDz,func,range,20.);
  if(save) 
    {
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/FitDz_Pt%1.0f_%s.pdf",run_type,pt_cut,trigName[kTrigType]));
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/FitDz_Pt%1.0f_%s.png",run_type,pt_cut,trigName[kTrigType]));
    }

  // pt dependence
  Double_t pt_cuts[5] = {1,2,3,5,20};
  for(Int_t i=0; i<4; i++)
    {
      hTrkDzVsPt->GetXaxis()->SetRangeUser(pt_cuts[i]+0.1,pt_cuts[i+1]-0.1);
      TH1F *htmp = (TH1F*)hTrkDzVsPt->ProjectionY(Form("hTrkDz_pt%1.0f-%1.0f_%s",pt_cuts[i],pt_cuts[i+1],trigName[kTrigType]));
      htmp->SetTitle(Form("%s: #Deltaz of matched track-hit pairs (%1.0f < p_{T} < %1.0f GeV/c);#Deltaz (cm)",trigName[kTrigType],pt_cuts[i],pt_cuts[i+1]));

      TF1 *func = new TF1(Form("func_pt%1.0f-%1.0f",pt_cuts[i],pt_cuts[i+1]),"gaus(0)+gaus(3)",-1*range,range);
      if(i==0) func->SetParameters(100,0,100,1000,0,10);
      if(i==1) func->SetParameters(1000,0,15,1000,0,60);
      if(i==2) func->SetParameters(1000,0,15,1000,0,60);
      if(i==3) func->SetParameters(1000,0,60,1000,0,15);
      c = FitDeltaZ(htmp,func,range,20.);
      if(save) 
	{
	  c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/FitDz_Pt%1.0f_%1.0f_%s.pdf",run_type,pt_cuts[i],pt_cuts[i+1],trigName[kTrigType]));
	  c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/FitDz_Pt%1.0f_%1.0f_%s.png",run_type,pt_cuts[i],pt_cuts[i+1],trigName[kTrigType]));
	}
    }
 
}
Example #7
0
void superimposeHistos()
{
  TFile* bFile = TFile::Open("Electron_In_Jets_900GeV_bJets.root");
  TFile* cFile = TFile::Open("Electron_In_Jets_900GeV_cJets.root");
  TFile* udsgFile = TFile::Open("Electron_In_Jets_900GeV_udsgJets.root");
  
  TIter next(bFile->GetListOfKeys());
  TFile* newFile = new TFile("testFile.root", "RECREATE");
  while(TKey* key = (TKey*)next())
  {
    TH1F* bHist = (TH1F*)bFile->Get(key->GetName());
    bHist->SetFillColor(2);
    
    TH1F* cHist = (TH1F*)cFile->Get(key->GetName());
    cHist->SetFillColor(3);
    
    TH1F* udsgHist = (TH1F*)udsgFile->Get(key->GetName());
    udsgHist->SetFillColor(4);
    
    THStack* stack = new THStack(bHist->GetName(), bHist->GetTitle());
    stack->Add(udsgHist, "hist ][");
    stack->Add(cHist, "hist ][");
    stack->Add(bHist, "hist ][");
    
    TLegend* legend = new TLegend(0.5, 0.68, 0.88, 0.88);
    legend->AddEntry(bHist, "b-Jets");
    legend->AddEntry(cHist, "c-Jets");
    legend->AddEntry(udsgHist, "udsg-Jets");
    
    TCanvas* canvas = new TCanvas(bHist->GetName());
    stack->Draw();
    stack->GetXaxis()->SetTitle(bHist->GetXaxis()->GetTitle());
    legend->Draw();
    canvas->Write(canvas->GetName());
  }
  
  newFile->Close();
  bFile->Close();
  cFile->Close();
  udsgFile->Close();
}
Example #8
0
//loads single track pT efficiency from root file
TH1F *GetEfficiencyPt(TString effLoc){
  TFile *fIn = 0;
  TH1F *hEffPt = 0; 

  if(!fIn)fIn = TFile::Open(effLoc.Data());
  if(!fIn)Printf("%s%d no input data",(char*)__FILE__,__LINE__);
  if(!hEffPt)hEffPt = (TH1F*)fIn->Get("hSingleTrackEffPt");
  if(!hEffPt)Printf("%s%d no single track efficiency spectrum available",(char*)__FILE__,__LINE__);
  gROOT->cd();

  TH1F *hEffPtClone = (TH1F*)hEffPt->Clone(hEffPt->GetName()); 
  fIn->Close();
  return hEffPtClone;


}
void PileUpMaker() {
  // Access data file
  TFile *file = TFile::Open("ZmumuGammaNtuple_Full2012_MuCorr.root");
  TTree *Datatree = (TTree*)file->Get("ZmumuGammaEvent");

  // Set up histogram for data pile up
  TH1F *pileupraw = new TH1F("pileup","",40,0,80);
 
  // Fill pile up distribution
  Int_t nentries = Datatree->GetEntriesFast();
  Int_t nbytes = 0; 
  for (Int_t i=0; i<nentries;i++) {
    nbytes += Datatree->GetEvent(i);
    UInt_t NVertices;
    Datatree->SetBranchAddress("NVertices",&NVertices);
    pileupraw->Fill(float(NVertices)/0.7);
  }

  // Normalize the distribution
  TH1F* PU = (TH1F*)pileupraw->Clone("pileup");
  PU->Scale(1./PU->Integral());

  // Plot both the normalized and unnormalized pile up
  TCanvas *cv = 0;
  cv= new TCanvas("cv","cv",800, 600);
  pileupraw->Draw("");
  cv->SaveAs("DataPU.pdf");

  cv= new TCanvas("cv","cv",800,600);
  PU->Draw("");
  cv->SaveAs("DataPU_normalized.pdf");

  // Save the normalized distribution to a root file for weighting MC
  TFile *file = TFile::Open("2012_PhosphorData_PileUp.root","UPDATE");
  file->cd();
  file->WriteTObject(PU,PU->GetName(),"WriteDelete");
  file->Close();
  delete file;
}
Example #10
0
// Called just after the main event loop
// Can be used to write things out, dump a summary etc
// Return non-zero to indicate a problem
int IslandAmplitude::AfterLastEntry(TGlobalData* gData,const TSetupData *setup){

  // Print extra info if we're debugging this module:
  if(Debug()){
     cout<<"-----IslandAmplitude::AfterLastEntry(): I'm debugging!"<<endl;
  }

  double run_norm = fAmpNorm->Integral(0,-1);
  for(mapSH_t::iterator it = fAmpHist.begin(); it != fAmpHist.end(); ++it)
    {
      TH1F* h = it->second;
      TObject* obj = h->Clone((std::string(h->GetName()) + "_RunNorm").c_str());
      TH1* hn = static_cast<TH1*>(obj);
      hn->SetTitle((std::string(h->GetTitle()) + " (run normalized)").c_str());
      hn->Scale(1.0/run_norm);
    }

  for(mapSH_t::iterator it = fAmpHistNorm.begin(); it != fAmpHistNorm.end(); ++it)
    it->second->Scale(1.0/fNProcessed);

  return 0;
}
void plotProducer(const string& fFile, const string& fPlot, const string& fNameExt, const string& fExt, const string& fSwitch) {
  
   TH1F *h;
    
   TFile file(fFile.c_str());
   TDirectoryFile *dir = (TDirectoryFile*)file.Get("offsetAnalysis");
   TDirectoryFile *subDir = (TDirectoryFile*)dir->Get("PrimaryVertices");

   h = (TH1F*)subDir->Get(fPlot.c_str());

   string name = h->GetName();
   string fileName = name + "__" + fNameExt + "." + fExt;
   
   TCanvas *c = new TCanvas("c","",1120,800);
   c->cd();
     
   //h->SetLineWidth(2);
   h->Draw();
   
   if ( fSwitch.find("log") != string::npos ) c->SetLogy();
   c->SaveAs(fileName.c_str());
   
   delete c;
}
Example #12
0
int main(int argc, char* argv[])
{
        string htitle = "Events rate, cloud ";
        htitle = htitle+string(argv[1]);
	string drootpath;
    
        if (strcmp(argv[2],"ttreecache")==0)
	{
                htitle = htitle + ", TTreeCache enabled, protocol: WebDAV";
		drootpath = "../../../Histograms/TDavix/";
        }
	else if (strcmp(argv[2],"xrootd")==0)
        {
		htitle = htitle + ", TTreeCache enabled xrootd";
		drootpath = "../../../Histograms/xrootd/";
        }
	else
        {
	        htitle = htitle + ", TTreeCache disabled, protocol: WebDAV ";
		drootpath = "../../../Histograms/Davix/";
	}

	string cloudpath = argv[1] ;
	cloudpath = cloudpath + "/";
	DIR* dcloudrep = opendir(string2char(drootpath+cloudpath));
	struct dirent* dcloudfichier = NULL;
	string allgrid;
	allgrid = string(argv[3]);

	vector<ratioMatrixValue> th2array;
	
	while ((dcloudfichier = readdir(dcloudrep))!=0)
	{
		if (dcloudfichier->d_name[0]=='.')
			continue;
		string dcloudpath = cloudpath + dcloudfichier->d_name + "/";
		//DIR* drootfile = opendir(string2char(drootpath+dcloudpath));
		//struct dirent* drootfichier = NULL;

		string dfilepath = drootpath + dcloudpath + allgrid + "/" + dcloudfichier->d_name + ".root";
		ratioMatrixValue column;

		TFile *dfr = TFile::Open(string2char(dfilepath));
		if (dfr==NULL)
			continue;

		column.analy = dcloudfichier->d_name;

		for (int i=0;i<dfr->GetListOfKeys()->GetEntries();i++)
		{
			string dstrRead = string2char(dfr->GetListOfKeys()->At(i)->GetName());
			TH1F* dhist = (TH1F*)dfr->Get(string2char(dstrRead));
			if (dhist==NULL)
				continue;
			string otherTitle = string(dhist->GetName()) + "No Zero";
			TH1F* histSansZeros = new TH1F(string2char(otherTitle),dhist->GetTitle(),3000.,0,3000);
			for ( int l=2;l<3000;l++)
				for (int k=0;k<dhist->GetBinContent(l);k++)
					histSansZeros->Fill(l-1);
			column.datadisk.push_back(string2char(dstrRead));
			column.ratio.push_back(histSansZeros->GetMean());
			column.error.push_back(histSansZeros->GetRMSError());
		}
		th2array.push_back(column);
	}



        TCanvas * c = new TCanvas("c", "c");
        c->SetLeftMargin(0.20);
        c->SetBottomMargin(0.15);
        c->SetWindowSize(2100,1500);

	/*for (unsigned int i=0;i<th2array.size();i++)
	{
		cout << th2array[i].analy << "\t";
		for (unsigned int j=0;j<th2array[i].datadisk.size();j++)
			cout << th2array[i].datadisk[j] << "\t" ;
		cout << endl;
	}*/

	cout << "--------------------------" << endl;

	th2array = ordenate(th2array,string(argv[1]));

	cout << "--------------------------" << endl;

	/*for (unsigned int i=0;i<th2array.size();i++)
	{
		cout << th2array[i].analy << "\t";
		for (unsigned int j=0;j<th2array[i].datadisk.size();j++)
			cout << th2array[i].datadisk[j] << "\t" ;
		cout << endl;
	}*/

	unsigned int datadisk_number=0;
	unsigned int analy_number=0;
	for (unsigned int i=0;i<th2array.size();i++)
	{
		if (datadisk_number < th2array[i].datadisk.size())
		{
			datadisk_number = th2array[i].datadisk.size();
		}
		if (th2array[i].datadisk.size()!=0)
			analy_number++;
	}

	char *title = string2char(htitle);
	TH2F *h = new TH2F("eventMatrix",title,analy_number,0.,analy_number,datadisk_number,0.,datadisk_number);
	for (unsigned int i=0;i<th2array.size();i++)
	{
		//cout << "coucou  " << th2array[i].analy << " " << th2array[i].datadisk.size() << endl; 
		for (unsigned int j=0;j<th2array[i].datadisk.size();j++)
		{
			h->Fill(th2array[i].analy,th2array[i].datadisk[j],th2array[i].ratio[j]);
			//cout << i << " " << j << " " << th2array[i].error[j] << endl;
			h->SetCellError(i+1,j+1,th2array[i].error[j]);
			//cout << i << " " << j << " " << h->GetBinErrorLow(i+1,j+1) << " " << h->GetBinErrorUp(i+1,j+1) << endl;
		}
	}
	const Int_t Number = 5;
        Double_t Red[Number] = { 1.00, 0.75, 1.00, 0.25, 0.00 };
        Double_t Green[Number] = { 0.00, 0.25, 0.50, 0.75, 1.00 };
        Double_t Blue[Number] = { 0.00, 0.00, 0.00, 0.00, 0.00 };
        Double_t Stops[Number] = { 0.00, 0.34, 0.61, 0.84, 1.00 };
        Int_t nb=50;
        TColor::CreateGradientColorTable(Number,Stops,Red,Green,Blue,nb);
        h->GetXaxis()->SetTitle("Processing site");
        h->GetXaxis()->CenterTitle();
        h->GetYaxis()->SetTitle("Data source site");
        h->GetYaxis()->CenterTitle();
        h->SetLabelSize(0.03,"Y");
        h->SetTitleOffset(2.3,"Y");
        h->SetLabelSize(0.03,"X");
        h->SetTitleOffset(2.0,"X");
        h->GetYaxis()->SetTitle("Data source site");
        h->Draw("COLZ");
        h->Draw("TEXTE SAME");
        gStyle->SetOptStat(0);
        //gStyle->SetTitleY(0.1f);
        h->SetMaximum(750);
        h->SetMinimum(0);

	c->Print(Form("canvas.eps"));
        return 0;
}
int BDTInterpolation(std::string inFileName,bool Diagnose=false, bool doNorm=true, bool doSidebands=false){

  std::cout << getTime() << std::endl;

  system("rm -r plots");
  system("mkdir plots");

  //gROOT->SetBatch();
  gStyle->SetOptStat(0);

  // input flags
  bool all=0;
 
  if (Diagnose) {
    std::cout << "Diagnostics turned on \n Output plots available in \"plots\" directory \n Diagnostic log available in \"plots/BDTInterpolationDiagnostics.txt\"" << std::endl;
    all = true;
  }
  else std::cout << "Diagnostics turned off" << std::endl;
  if (doNorm) std::cout << "Normalization turned on" << std::endl;
  else std::cout << "Normalization turned off" << std::endl;
  if (doSidebands) std::cout << "Background model from sidebands turned on" << std::endl;
  else std::cout << "Background model from sidebands turned off" << std::endl;

  TFile *inFile = new TFile(inFileName.c_str());
  //TFile *inFile = new TFile("/vols/cms02/nw709/hgg/src_cvs/oct13/CMSSW_4_2_8/src/HiggsAnalysis/HiggsTo2photons/h2gglobe/Macros/CMS-HGG_1658pb_mva.root");
  //TFile *inFile = new TFile("RefWorkspaces/CMS-HGG_1658pb_mva.root");
  TFile *outFile = new TFile(Form("%s_interpolated.root",inFileName.c_str()),"RECREATE");
  TFile *systTestF = new TFile("systTest.root","RECREATE");
  ofstream diagFile("plots/BDTInterpolationDiagnostics.txt");

  const int nBDTs=2;
  const int nMasses=8;
  const int nProds=4;
  std::string BDTtype[nBDTs] = {"ada","grad"};
  std::string BDTmasses[nMasses] = {"110.0","115.0","120.0","125.0","130.0","135.0","140.0","150.0"};
  std::string productionTypes[nProds] = {"ggh","vbf","wzh","tth"};
// ----- else can just get rebinned histograms straight out of workspace

  std::cout << "Extracting histograms from workspace........." << std::endl;

  diagFile << "Diagnostics for Signal Interpolation run at " << getTime() << std::endl;
  diagFile << "---------------------------------------------------------------------" << std::endl;
  diagFile << "Following orginal histograms rewritten into new workspace: " << std::endl;
  
  // ------ stuff for interpolation systematic -------
  TH1F *systHists120[2][3];
  TH1F *systHists135[2][3];

  std::string syst120mass[3] = {"120.0","115.0","125.0"};
  std::string syst135mass[3] = {"135.0","130.0","140.0"};
  // ---------------------------------------------------
  
  // make plots of background model from sidebands
  if (doSidebands){
    for (int bdt=0; bdt<nBDTs; bdt++){
      for (double mass=110.; mass<=150.0; mass+=0.5){
        TList *bkgModelList = new TList();
        TH1F *bkgModel[7];
        bkgModel[0] = (TH1F*)inFile->Get(Form("th1f_bkg_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[1] = (TH1F*)inFile->Get(Form("th1f_bkg_3low_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[2] = (TH1F*)inFile->Get(Form("th1f_bkg_2low_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[3] = (TH1F*)inFile->Get(Form("th1f_bkg_1low_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[4] = (TH1F*)inFile->Get(Form("th1f_bkg_1high_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[5] = (TH1F*)inFile->Get(Form("th1f_bkg_2high_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[6] = (TH1F*)inFile->Get(Form("th1f_bkg_3high_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        for (int i=0; i<7; i++) {
          bkgModelList->Add(bkgModel[i]);
        }
        std::string name(Form("%3.1f",mass));
        plotBkgModel(bkgModelList,name);
      }
    }
  }
  
  // write original histograms in out file
  TList *HistList = inFile->GetListOfKeys();
  for (int j=0; j<HistList->GetSize(); j++){
    TH1F *temp = (TH1F*)inFile->Get(HistList->At(j)->GetName());
    TString name = temp->GetName();

    // store stuff for interpolation systematic
    for (int bdt=0; bdt<nBDTs; bdt++){
      for (int syst=0; syst<3; syst++){
        if (name.Contains(("th1f_sig_"+BDTtype[bdt]+"_"+productionTypes[0]+"_"+syst120mass[0]+"_"+syst120mass[syst]).c_str()) && !name.Contains("sigma")){
          systHists120[bdt][syst] = (TH1F*)inFile->Get(name.Data());
          systHists120[bdt][syst]->SetLineColor(syst+2);
        }
        if (name.Contains(("th1f_sig_"+BDTtype[bdt]+"_"+productionTypes[0]+"_"+syst135mass[0]+"_"+syst135mass[syst]).c_str()) && !name.Contains("sigma")){
          systHists135[bdt][syst] = (TH1F*)inFile->Get(name.Data());
          systHists135[bdt][syst]->SetLineColor(syst+2);
        }
      }
    }
    // ---------------------------------------------
    std::string tName = temp->GetName();
    for (int i=0; i<nMasses; i++){
      int ind = tName.find(BDTmasses[i]+"_"+BDTmasses[i]);
      if (ind>0) tName.replace(ind,11,BDTmasses[i]);
    }
    temp->SetName(tName.c_str());
      
    outFile->cd();
    temp->Write();
    diagFile << "Histo written: " << temp->GetName() << std::endl;
  }

  // ----------- Do stuff for interpolation systematic ------------
  std::cout << "Creating interpolation systematic templates......." << std::endl;

  diagFile << "---------------------------------------------------------------------" << std::endl;
  diagFile << "Writing following interpolation systematic templates: " << std::endl;
  
  for (int bdt=0; bdt<nBDTs; bdt++){
    double norm120 = GetNorm(115.0,systHists120[bdt][1],125.0,systHists120[bdt][2],120.0);
    double norm135 = GetNorm(130.0,systHists135[bdt][1],140.0,systHists135[bdt][2],135.0);
    if (doNorm) {
      systHists120[bdt][1]->Scale(1./(GetXsection(115.0)*GetBR(115.0)));
      systHists120[bdt][2]->Scale(1./(GetXsection(125.0)*GetBR(125.0)));
      systHists135[bdt][1]->Scale(1./(GetXsection(130.0)*GetBR(130.0)));
      systHists135[bdt][2]->Scale(1./(GetXsection(140.0)*GetBR(140.0)));
    }
    TH1F *int120 = Interpolate(115.0,systHists120[bdt][1],125.0,systHists120[bdt][2],120.0);
    TH1F *int135 = Interpolate(130.0,systHists135[bdt][1],140.0,systHists135[bdt][2],135.0);
    if (doNorm) {
      systHists120[bdt][1]->Scale(GetXsection(115.0)*GetBR(115.0));
      systHists120[bdt][2]->Scale(GetXsection(125.0)*GetBR(125.0));
      systHists135[bdt][1]->Scale(GetXsection(130.0)*GetBR(130.0));
      systHists135[bdt][2]->Scale(GetXsection(140.0)*GetBR(140.0));
    }
    if (doNorm) {
      int120->Scale(norm120/int120->Integral());
      int135->Scale(norm135/int135->Integral());
    }
    
    TList *int120list = new TList();
    int120list->Add(systHists120[bdt][1]);
    int120list->Add(systHists120[bdt][2]);
    int120list->Add(int120);
    plotFrac(int120list,systHists120[bdt][0],"syst120",false);
    
    TList *int135list = new TList();
    int135list->Add(systHists135[bdt][1]);
    int135list->Add(systHists135[bdt][2]);
    int135list->Add(int135);
    plotFrac(int135list,systHists135[bdt][0],"syst135",false);
    TH1F *frac=(TH1F*)systHists135[bdt][0]->Clone();
    frac->Add(int135,-1);
    frac->Divide(int135);
    TH1F *linFrac = (TH1F*)linearBin(frac);
    linFrac->GetYaxis()->SetRangeUser(-0.4,0.4);
    TCanvas *c = new TCanvas();
    systTestF->cd();
    linFrac->Write();
    linFrac->Draw();
    TF1 *fit = new TF1("fit","[0]*(x-36.)^2",0.,36.);
    linFrac->Fit(fit,"q");
    fit->DrawCopy("same");
    fit->SetLineColor(kGray);
    fit->SetLineStyle(2);
    double var = fit->GetParameter(0);
    double err = fit->GetParError(0);
    fit->SetParameter(0,var+err);
    fit->DrawCopy("same");
    fit->SetParameter(0,var-err);
    fit->DrawCopy("same");

    c->Print(Form("plots/%s/fracs/systTest135.png",BDTtype[bdt].c_str()),"png");

    // get plus and minus templates
    std::pair<TH1F*,TH1F*> result135 = GetPMSyst(systHists135[bdt][0],int135,"th1f_sig_"+BDTtype[bdt]+"_ggh_135.0_cat0_sigInt");
    TH1F* sigIntDown = (TH1F*)linearBin(result135.first);
    TH1F* sigIntUp = (TH1F*)linearBin(result135.second);
    TH1F* sigIntCent = (TH1F*)linearBin(int135);
    diagFile << (result135.first)->GetName() << std::endl;
    diagFile << (result135.second)->GetName() << std::endl;
    
    TCanvas *test = new TCanvas();
    sigIntDown->SetLineColor(2);
    sigIntUp->SetLineColor(4);
    sigIntDown->Draw();
    sigIntUp->Draw("same");
    sigIntCent->Draw("same'");
    test->Print(("plots/"+BDTtype[bdt]+"/fracs/PMsysts135.png").c_str(),"png");
   
    outFile->cd();
    (result135.first)->Write();
    (result135.second)->Write();
   
  }

    // -------------------- systematic stuff done ----------------------

  // get lists of middle, upper and lower templates for each mass
  TList *orgHistList[nBDTs][nProds][nMasses];
  TList *orgHistListBelow[nBDTs][nProds][nMasses];
  TList *orgHistListAbove[nBDTs][nProds][nMasses];
  for (int i=0; i<nBDTs; i++) {
   for (int pT=0;pT<nProds;pT++){
    for (int j=0; j<nMasses; j++) {
      orgHistList[i][pT][j]=new TList();
      orgHistListBelow[i][pT][j]=new TList();
      orgHistListAbove[i][pT][j]=new TList();
    }
   }
  }

  for (int j=0; j<HistList->GetSize(); j++){
    TString HistName(HistList->At(j)->GetName());
    for (int bdt=0; bdt<nBDTs; bdt++){
     for (int pT=0;pT<nProds;pT++){
      for (int bdtmass=0; bdtmass<nMasses; bdtmass++){
        for (int k=-1; k<2; k++){
          if ((bdtmass==0 && k==-1) || (bdtmass==nMasses-1 && k==1)) continue;
          if (HistName.Contains(("sig_"+BDTtype[bdt]+"_"+productionTypes[pT]+"_"+BDTmasses[bdtmass]+"_"+BDTmasses[bdtmass+k]).c_str())){
            TH1F *temp = (TH1F*)inFile->Get(HistName.Data());
            cout << temp->GetName() << " " << temp->GetEntries() << endl;
            if (k==-1) orgHistListBelow[bdt][pT][bdtmass]->Add(temp);
            if (k==0) orgHistList[bdt][pT][bdtmass]->Add(temp);
            if (k==1) orgHistListAbove[bdt][pT][bdtmass]->Add(temp);
          }
        }
       }
      }
    }
  }
  diagFile << "---------------------------------------------------------------------" << std::endl;
  diagFile << "Following histo's being used for interpolation: " << std::endl;
  for (int bdt=0; bdt<nBDTs; bdt++){
   for (int pT=0;pT<nProds;pT++){
    for (int mass=0; mass<nMasses; mass++){
      diagFile << "BDT: " << BDTtype[bdt] << std::endl;
      diagFile << "Production : " << productionTypes[pT] << std::endl;
      diagFile << "Mass: " << BDTmasses[mass] << std::endl;
      for (int syst=0; syst<orgHistList[bdt][pT][mass]->GetSize(); syst++){
        diagFile << "   Central: " << orgHistList[bdt][pT][mass]->At(syst)->GetName() << std::endl;
        if (mass!=0) diagFile << "   Lower:   " << orgHistListBelow[bdt][pT][mass]->At(syst)->GetName() << std::endl;
        if (mass!=nMasses-1) diagFile << "   Upper:   " << orgHistListAbove[bdt][pT][mass]->At(syst)->GetName() << std::endl;
      }
    }
   }
  }

  // now have orgHistList for each BDT and above and below signals.
  // the contain 17 histos - 1 for actual sig and 8 up and down for each systematic

  // ---------- at this points have signal hists for each mass points as well as +- models all rebinned at mass points --------

  std::cout << "Calculating interpolated signal templates........" << std::endl;
  diagFile << "---------------------------------------------------------------------" << std::endl;
  diagFile << "Interpolating intermediate signals from following lower and upper templates" << std::endl;

  const int nGlobalMs=81; // no of mass points between lowMass and highMass with 0.5 GeV steps
  TList *orgHistListInt[nBDTs][nProds][nGlobalMs];
  for (int i=0; i<nBDTs; i++) for (int pT=0; pT<nProds; pT++) for (int j=0; j<nGlobalMs; j++) orgHistListInt[i][pT][j] = new TList();
  TH1F *systUp, *systDown, *systTrue;
  TH1F *background, *data, *signal, *sig_ggh, *sig_vbf, *sig_wzh, *sig_tth;

  int i=0;
  // loop over mass points etc.
  for (double mass=110.; mass<=150.; mass+=0.5){
    if (int(mass)%2==0) std::cout << Form("%3.0f",((mass-110.)/40.)*100.) << "% done" << std::endl;
    //points we have signal for
    if (int(mass*2)%10==0 && mass!=145.0) {
     for (int pT=0;pT<nProds;pT++){
      for (int bdt=0; bdt<nBDTs; bdt++){  
        background = (TH1F*)inFile->Get(Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr",BDTtype[bdt].c_str(),mass));
      //  background = (TH1F*)inFile->Get(Form("th1f_bkg_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        data = (TH1F*)inFile->Get(Form("th1f_data_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        sig_ggh = (TH1F*)inFile->Get(Form("th1f_sig_%s_ggh_%3.1f_%3.1f_cat0",BDTtype[bdt].c_str(),mass,mass));
        sig_vbf = (TH1F*)inFile->Get(Form("th1f_sig_%s_vbf_%3.1f_%3.1f_cat0",BDTtype[bdt].c_str(),mass,mass));
        sig_wzh = (TH1F*)inFile->Get(Form("th1f_sig_%s_wzh_%3.1f_%3.1f_cat0",BDTtype[bdt].c_str(),mass,mass));
        sig_tth = (TH1F*)inFile->Get(Form("th1f_sig_%s_tth_%3.1f_%3.1f_cat0",BDTtype[bdt].c_str(),mass,mass));
	
        signal = (TH1F*)sig_ggh->Clone();
        signal->Add(sig_vbf);
        signal->Add(sig_wzh);
        signal->Add(sig_tth);

        std::string name = Form("%3.1f",mass);
        if (Diagnose) {
          plotDavid(background,signal,data,name);
          TList *systList = new TList();
          TH1F *central;
          int bdtmass = getIndex((findNearest(mass).first));
          for (int syst=0; syst<orgHistList[bdt][pT][bdtmass]->GetSize(); syst++){
            if (syst==0) central = (TH1F*)orgHistList[bdt][pT][bdtmass]->At(syst);
            else {
              TH1F *tempSig = (TH1F*)orgHistList[bdt][pT][bdtmass]->At(syst);
              systList->Add(tempSig);
            }
          }
          plotSystFracs(systList,central,Form("%3.1f_systFracs",mass));
        }
        // store some systematic histograms
        if (int(mass)>110 && int(mass)<150){
          int bdtmass = getIndex(int(mass));
          systTrue = (TH1F*)orgHistList[bdt][pT][bdtmass]->At(0)->Clone();
          systUp = (TH1F*)orgHistListAbove[bdt][pT][bdtmass]->At(0)->Clone();
          systDown = (TH1F*)orgHistListBelow[bdt][pT][bdtmass]->At(0)->Clone();

          double trueNorm = systTrue->Integral();
          systUp->Scale(trueNorm/systUp->Integral());
          systDown->Scale(trueNorm/systDown->Integral());
          systUp->SetName(Form("th1f_sig_%s_%s_%3.1f_cat0_sigIntNewUp01_sigma",BDTtype[bdt].c_str(),productionTypes[pT].c_str(),mass));
          systDown->SetName(Form("th1f_sig_%s_%s_%3.1f_cat0_sigIntNewDown01_sigma",BDTtype[bdt].c_str(),productionTypes[pT].c_str(),mass));
          
          outFile->cd();
          systUp->Write();
          systDown->Write();
          TCanvas *lil = new TCanvas();
          systUp->SetLineColor(kRed);
          systDown->SetLineColor(kBlue);
          systDown->Draw("e");
          systUp->Draw("same e");
          systTrue->Draw("same e");
          lil->Print(Form("plots/%s/systNew_%s_%3.1f.png",BDTtype[bdt].c_str(),productionTypes[pT].c_str(),mass),"png");
          delete lil;
        }
      }
     }
      continue;
    }
    std::pair<int,int> nearestPair = findNearest(mass);
    bool above;
    int nearest = nearestPair.first;
    int nextNear =nearestPair.second;
    if (nearest-nextNear < 0) above = true;
    else above = false;
    
    //std::cout << mass << " bracketed by: " << nearestPair.first << " " << nearestPair.second << " " << above << std::endl;

    int bdtmass = getIndex(nearest); // gives index of bdt to use

    // loop bdt type
    for (int bdt=0; bdt<nBDTs; bdt++){
     TH1F *combSignal;
     for (int pT=0;pT<nProds;pT++){
      diagFile << "Mass: " << mass << std::endl;
      diagFile << "BDT: " << BDTtype[bdt] << std::endl;
      // loop different histos in list (signal and systematics)
      background = (TH1F*)inFile->Get(Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr",BDTtype[bdt].c_str(),mass));
     // background = (TH1F*)inFile->Get(Form("th1f_bkg_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
      data = (TH1F*)inFile->Get(Form("th1f_data_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
      TList *systList = new TList();
      TH1F *central;
      for (int syst=0; syst<orgHistList[bdt][pT][bdtmass]->GetSize(); syst++){
        TH1F *tempSig = (TH1F*)orgHistList[bdt][pT][bdtmass]->At(syst);
        central = (TH1F*)tempSig->Clone();
        TH1F *tempAbove = (TH1F*)orgHistListAbove[bdt][pT][bdtmass]->At(syst);
        TH1F *tempBelow = (TH1F*)orgHistListBelow[bdt][pT][bdtmass]->At(syst);
        TH1F* tempInt;
        TList* plotList = new TList();
        if (above){
          if (doNorm) tempSig->Scale(1./(GetXsection(double(nearest))*GetBR(double(nearest))));
          if (doNorm) tempAbove->Scale(1./(GetXsection(double(nextNear))*GetBR(double(nextNear))));
          tempInt = Interpolate(double(nearest),tempSig,double(nextNear),tempAbove,mass);
          if (doNorm) tempSig->Scale(GetXsection(double(nearest))*GetBR(double(nearest)));
          if (doNorm) tempAbove->Scale(GetXsection(double(nextNear))*GetBR(double(nextNear)));
          double norm = GetNorm(double(nearest),tempSig,double(nextNear),tempAbove,mass);
          if (doNorm) tempInt->Scale(norm/tempInt->Integral());
          // diagnostic stuff
          diagFile << "   Interpolated:     " << tempInt->GetName() << std::endl;
          diagFile << "   from:             " << tempSig->GetName() << std::endl;
          diagFile << "   and:              " << tempAbove->GetName() << std::endl;
          std::string histName = tempSig->GetName();
          std::string systName = histName.substr(histName.rfind("cat0"),histName.size());
          plotList->Add(tempSig);
          plotList->Add(tempAbove);
          if (Diagnose){
            if (syst==0) plotFrac(plotList,tempInt,Form("%3.1f_%s",mass,systName.c_str()),true);
            else systList->Add(tempInt);
          }
        }
        else{
          if (doNorm) tempSig->Scale(1./(GetXsection(double(nearest))*GetBR(double(nearest))));
          if (doNorm) tempBelow->Scale(1./(GetXsection(double(nextNear))*GetBR(double(nextNear))));
          tempInt = Interpolate(double(nextNear),tempBelow,double(nearest),tempSig,mass);
          if (doNorm) tempSig->Scale(GetXsection(double(nearest))*GetBR(double(nearest)));
          if (doNorm) tempBelow->Scale(GetXsection(double(nextNear))*GetBR(double(nextNear)));
          double norm = GetNorm(double(nextNear),tempBelow,double(nearest),tempSig,mass);
          if (doNorm) tempInt->Scale(norm/tempInt->Integral());
          // diagnostic stuff
          diagFile << "   Interpolated:     " << tempInt->GetName() << std::endl;
          diagFile << "   from:             " << tempBelow->GetName() << std::endl;
          diagFile << "   and:              " << tempSig->GetName() << std::endl;
          std::string histName = tempSig->GetName();
          std::string systName = histName.substr(histName.rfind("cat0"),histName.size());
          plotList->Add(tempBelow);
          plotList->Add(tempSig);
          if (Diagnose){
            if (syst==0) plotFrac(plotList,tempInt,Form("%3.1f_%s",mass,systName.c_str()),true);
            else systList->Add(tempInt);
          }
        }
        orgHistListInt[bdt][pT][i]->Add(tempInt);
        if (syst==0 && Diagnose){
          if (pT==0) combSignal = (TH1F*)tempInt->Clone();
          else combSignal->Add(tempInt,1.);
          std::string name = Form("%3.1f",mass);
          if (pT==3) plotDavid(background,combSignal,data,name);
        }
        delete plotList;
      }
      if (Diagnose) plotSystFracs(systList,central,Form("%3.1f_systFracs",mass));
     }
    }
    i++;
  }
 
  outFile->cd();

  diagFile << "---------------------------------------------------------------------" << std::endl;
  diagFile << "Writing following interpolated histograms to file: " << std::endl;
  for (int l=0; l<nBDTs; l++) for (int pT=0; pT<nProds; pT++)for (int j=0; j<nGlobalMs; j++) for (int k=0; k<orgHistListInt[l][pT][j]->GetSize(); k++) {
    orgHistListInt[l][pT][j]->At(k)->Write();
    diagFile << orgHistListInt[l][pT][j]->At(k)->GetName() << std::endl;
  }
  
  TList* endList = outFile->GetListOfKeys();
  for (double mass=110.0; mass<=150.; mass+=0.5){
    diagFile << mass << std::endl;
    std::pair<int,int> nearestPair = findNearest(mass);
    double nearest = nearestPair.first;
    double nextNear = nearestPair.second;
    for (int k=0; k<endList->GetSize(); k++){
      TString hName = endList->At(k)->GetName();
      if (hName.Contains("sigma") || !hName.Contains("sig")) continue;
      if (hName.Contains(Form("a_%3.1f_cat0",nearest)) || hName.Contains(Form("d_%3.1f_cat0",nearest)) || hName.Contains(Form("%3.1f_%3.1f_cat0",nearest,nextNear)) || hName.Contains(Form("%3.1f_cat0",mass))) {
        TH1F *temp = (TH1F*)outFile->Get(hName);
        diagFile << "    " << setw(30) << temp->GetName();
        diagFile << "    " << setw(8) << temp->GetEntries();
        diagFile << "    " << setw(8) << temp->Integral() << std::endl;
      }
    }
  }
    
  outFile->Close();

  std::cout << "Diagnostics log written to \"BDTInterpolationDiagnostics.txt\"" << std::endl;
  if (davidCalls>0) std::cout << davidCalls << " plots written to: plots/ada/david/ \n                    plots/grad/david/ " << std::endl;
  if (davidCalls>0) std::cout << davidCalls << " plots written to: plots/ada/diff/ \n                    plots/grad/diff/ " << std::endl;
  if (fracCalls>0) std::cout << fracCalls << " plots written to: plots/ada/frac/ \n                      plots/grad/frac/" << std::endl;
  if (systCalls>0) std::cout << systCalls << " plots written to: plots/ada/syst/ \n                    plots/grad/syst/ " << std::endl;
  if (bkgCalls>0) std::cout << bkgCalls << " plots written to: plots/ada/bkgMod/ \n                    plots/grad/bkgMod/ " << std::endl;

  std::string TIME_DATE = getTime();
  if (Diagnose){
    /*
    system("whoami > temp.txt");
    std::ifstream temp("temp.txt");
    std::string result;
    temp >> result;
    temp.close();
    system("rm temp.txt");
    system(("python make_html.py "+result+" "+TIME_DATE+" "+inFileName).c_str());
    system(("mkdir -p ~/public_html/h2g/MVA/SigInt/Diagnostics/"+TIME_DATE+"/").c_str());
    system(("cp -r plots ~/public_html/h2g/MVA/SigInt/Diagnostics/"+TIME_DATE+"/").c_str());
    system(("rm ~/public_html/h2g/MVA/SigInt/Diagnostics/Current"));
    system(("ln -s ~/public_html/h2g/MVA/SigInt/Diagnostics/"+TIME_DATE+" ~/public_html/h2g/MVA/SigInt/Diagnostics/Current").c_str());
    std::cout << ("Plots avaiable to view in ~/public_html/h2g/MVA/SigInt/Diagnostics/"+TIME_DATE+"/").c_str() << std::endl;
    std::cout << "If working on /vols/ at IC plots avaliable to view at www.hep.ph.ic.ac.uk/~"+result+"/h2g/MVA/SigInt/Diagnostics/Current/plots/plots.html" << std::endl;
    */
  }
  std::cout << "Checking all relevant histograms have been written to workspace......" << std::endl;
  //system(("python checkOK.py "+string(outFile->GetName())).c_str());
  std::cout << "New workspace written to " << outFile->GetName() << std::endl;
  return 0;
}
void plotSystFracs(TList* HistList, TH1F* compT, std::string name){

  gROOT->SetBatch();
  system("mkdir -p plots/ada/systs");
  system("mkdir -p plots/grad/systs");

  std::string bdt;
  TString str = compT->GetName();
  if (str.Contains("ada")) bdt="ada";
  if (str.Contains("grad")) bdt="grad";

  int nHists=HistList->GetEntries();
  TH1F *comp = linearBin(compT);
  
  gROOT->SetStyle("Plain");
  gROOT->ForceStyle();
  gStyle->SetOptStat(0);
  TCanvas *canv = new TCanvas("","",700,700);
  
  TLegend *leg = new TLegend(0.6,0.6,0.88,0.88);
  leg->SetLineColor(0);
  leg->SetFillColor(0);
  
  TF1 *line = new TF1("line","0.0",0.,comp->GetBinLowEdge(comp->GetNbinsX()+1));
  line->SetLineColor(kBlack);
  TF1 *line1 = new TF1("line","10.0",0.,comp->GetBinLowEdge(comp->GetNbinsX()+1));
  line1->SetLineColor(kGray+2);
  line1->SetLineStyle(2);
  TF1 *line2 = new TF1("line","-10.0",0.,comp->GetBinLowEdge(comp->GetNbinsX()+1));
  line2->SetLineColor(kGray+2);
  line2->SetLineStyle(2);
  
  int colors[10] = {kBlue,kMagenta,kGreen,kCyan,kRed,kBlue+3,kOrange+1,kSpring-1,kMagenta+3,kGreen+3};
  int color=0;
  for (int i=0; i<nHists; i++){
    TH1F *systHist = linearBin((TH1F*)HistList->At(i));
    systHist->Add(comp,-1);
    systHist->Divide(comp);
    systHist->Scale(100.);
    std::string systStr = systHist->GetName();
    int ind = systStr.rfind("cat0");
    std::string systName = systStr.substr(ind+5,systStr.size());
    systHist->SetLineColor(colors[color]);
    systHist->SetTitle(Form("%s",name.c_str()));
    systHist->GetYaxis()->SetTitle("Difference over nominal %");
    systHist->GetYaxis()->SetTitleOffset(1.4);
    systHist->GetXaxis()->SetTitle("BDT output");
    systHist->GetYaxis()->SetRangeUser(-100.,250);
    if (int(systName.find("Up"))>0){
      systHist->SetLineStyle(1);
      systName = systName.substr(0,systName.rfind("Up"));
      leg->AddEntry(systHist,systName.c_str(),"l");
      color++;
    }
    else if (int(systName.find("Down"))>0){
      systHist->SetLineStyle(2);
      systName = systName.substr(0,systName.rfind("Down"));
    }
    if (i==0) systHist->DrawCopy("hist");
    else systHist->DrawCopy("same hist");
  }
  leg->Draw("same");
  line->Draw("same");
  line1->Draw("same");
  line2->Draw("same");
  canv->Print(("plots/"+bdt+"/systs/"+name+".png").c_str(),"png");
  
  delete canv;
  
  systCalls++;
  
}
void changeAxis(bool armed, TString iExprMatch,float iMin, const char* filename, const char* pattern="", unsigned int debug=0)
{
  std::vector<std::string> histnames; histnames.clear();
  if( debug>0 ){
    std::cout << "file  = " << filename             << std::endl;
    std::cout << "old   = " << iExprMatch.Data()    << std::endl;    
    std::cout << "armed = " << armed                << std::endl;
  }
  TFile* file = new TFile(filename, "update");
  TIter nextDirectory(file->GetListOfKeys());
  std::vector<std::string> buffer;
  TKey* idir;
  while((idir = (TKey*)nextDirectory())){
    buffer.clear();
    if( idir->IsFolder() ){
      file->cd(); // make sure to start in directory head 
      if( debug>0 ){ std::cout << "Found directory: " << idir->GetName() << std::endl; }
      if( file->GetDirectory(idir->GetName()) ){
	file->cd(idir->GetName()); // change to sub-directory
	buffer = signalList(idir->GetName(), pattern,iExprMatch.Data(), debug);
      }
      // append to the vector of histograms to be rescaled
      for(std::vector<std::string>::const_iterator elem=buffer.begin(); elem!=buffer.end(); ++elem){
	histnames.push_back(*elem);
      }
      if(debug>1){
	std::cout << "added " << buffer.size() << " elements to histnames [" << histnames.size() << "] for directory " << idir->GetName() << std::endl;
      }
    }
  }
  // pick up files which are not kept in an extra folder
  file->cd(); buffer.clear();
  buffer = signalList("", pattern,iExprMatch.Data(), debug);
  // append to the vector of histograms to be rescaled
  for(std::vector<std::string>::const_iterator elem=buffer.begin(); elem!=buffer.end(); ++elem){
    histnames.push_back(*elem);
  }
  if(debug>1){
    std::cout << "added " << buffer.size() << " elements to histnames [" << histnames.size() << "] for file head" << std::endl;
  }

  for(std::vector<std::string>::const_iterator hist=histnames.begin(); hist!=histnames.end(); ++hist){
    file->cd();
    TH1F* h = (TH1F*)file->Get(hist->c_str());
    std::string histName;
    if(hist->find("/")!=std::string::npos){
      histName = hist->substr(hist->find("/")+1);
    }
    else{
      histName = *hist;
    }
    TH1F* hout = (TH1F*)h->Clone(histName.c_str());
    if(debug>1){
      std::cout << "...folder    : " << hist->substr(0, hist->find("/")).c_str() << std::endl;
      std::cout << "...histogram : " << hout->GetName () << " / " << hist->c_str() << std::endl; 
    }
    for(int i0 = 0; i0 < hout->GetNbinsX()+1; i0++) if(hout->GetXaxis()->GetBinCenter(i0) < iMin) hout->SetBinContent(i0,0);
    if(debug>1){ 
      std::cout << "...new name  : " << hout->GetName() << std::endl; 
      std::cout << "...new title : " << hout->GetTitle() << std::endl; 
    }
    if(armed){
      if(hist->find("/")!=std::string::npos){
	file->cd(hist->substr(0, hist->find("/")).c_str());
      }
      else{
	file->cd();
      }
      std::cout << "writing to file: " << hout->GetName() << " -- " << hist->substr(hist->find("/")+1).c_str() << std::endl;
      hout->Write(hist->substr(hist->find("/")+1).c_str(), TObject::kOverwrite); 
    }
  }
  file->Close();
  return;
}
Example #16
0
void blindData(const char* filename, const char* background_patterns="Fakes, EWK, ttbar, Ztt", const char* signal_patterns="ggH125, qqH125, VH125", const char* directory_patterns="*", bool armed=false, int rnd=-1, float signal_scale=1., const char* outputLabel="", unsigned int debug=1)
{
  /// prepare input parameters
  std::vector<std::string> signals;
  string2Vector(cleanupWhitespaces(signal_patterns), signals);
  std::vector<std::string> samples;
  string2Vector(cleanupWhitespaces(background_patterns), samples);
  samples.insert(samples.end(), signals.begin(), signals.end());

  // check if mssm or sm input file
  bool sm=true;
  if(std::string(filename).find("mssm") != std::string::npos){
    sm=false;
    std::cerr << "INFO  : MSSM File " << std::endl;
  }
  
  // in case data_obs is supposed to be written to an extra output file
  // open the file, otherwise the data_obs in the input file will be
  // overwritten
  string used_filename=string(filename);
  TFile* outputFile = 0; 
  if(!std::string(outputLabel).empty()){
    std::string out = std::string(used_filename); 
    if(std::string(outputLabel).find("MSSM") != std::string::npos){
      outputFile = new TFile((out.substr(0, out.rfind("."))+".root").c_str(), "update"); 
    }
    // make sure data_obs in correct file for MSSM injection is changed
    // this is the old file which is overwritten 
    else{
      outputFile = new TFile((out.substr(0, out.rfind("."))+"_"+outputLabel+".root").c_str(), "update"); 
    }
  }

  TKey* idir;
  TH1F* buffer = 0;
  TH1F* blind_data_obs = 0;
  TFile* file = new TFile(used_filename.c_str(), "update");
  TIter nextDirectory(file->GetListOfKeys());
  while((idir = (TKey*)nextDirectory())){
    if( idir->IsFolder() ){
      file->cd(); // make sure to start in directory head 
      if( debug>0 ){ std::cerr << "Found directory: " << idir->GetName() << std::endl; }
      // check if we want to muck w/ this directory. For the vhtt case, we 
      // have different background types in the same root file, so we have 
      // to run blindData twice.
      if (!inPatterns(std::string(idir->GetName()), directory_patterns)) {
        if( debug>0 ){ 
	  std::cerr << "WARNING: Skipping directory: " << idir->GetName() << std::endl;
	  std::cerr << "         No match found in pattern: " << directory_patterns << std::endl; 
	}
        continue;
      }
      if( file->GetDirectory(idir->GetName()) ){
	file->cd(idir->GetName()); // change to sub-directory
	buffer = (TH1F*)file->Get((std::string(idir->GetName())+"/data_obs").c_str());
	if(!buffer){
	  std::cout << "WARNING: Did not find histogram data_obs in directory: " << idir->GetName() << std::endl;
	  std::cout << "         Will skip directory: " << std::endl;
	  continue;
	}
        blind_data_obs = (TH1F*)buffer->Clone("data_obs"); 
	if(!samples.empty()){
	  blind_data_obs->Reset();
	  std::cout << "INFO  : Blinding datacads now." << std::endl;
	  for(std::vector<std::string>::const_iterator sample = samples.begin(); sample!=samples.end(); ++sample){
	    if( debug>0 ){ std::cerr << "Looking for histogram: " << (std::string(idir->GetName())+"/"+(*sample)) << std::endl; }
	    // add special treatment for et/mt ZLL,ZJ,ZL here. You can run the
	    // macro with ZLL, ZL, ZJ in the background samples. Those samples,
	    // which do not apply for one or the other event category are 
	    // skipped here.
	    if(sm==true){
	      if(std::string(idir->GetName()).find("vbf") != std::string::npos  && (*sample == std::string("ZL") || *sample == std::string("ZJ"))){
		continue;
	      }
	      else if(std::string(idir->GetName()).find("vbf") == std::string::npos  && *sample == std::string("ZLL")){
		continue;
	      }
	    }
	    else{
	      if(std::string(idir->GetName()).find("nobtag") == std::string::npos && (*sample == std::string("ZL") || *sample == std::string("ZJ"))){
	      continue;
	      }
	      else if(std::string(idir->GetName()).find("nobtag") != std::string::npos && *sample == std::string("ZLL")){
	      continue;
	      }  
	    }
	    buffer = (TH1F*)file->Get((std::string(idir->GetName())+"/"+(*sample)).c_str()); 
	    if (!buffer) {
	      std::cerr << "ERROR : Could not get histogram from: " << std::string(idir->GetName())+"/"+(*sample) << std::endl;
	      std::cerr << "        Histogram will be skipped   : " << std::string(idir->GetName())+"/"+(*sample) << std::endl;
	      continue;
	    }
	    if(inPatterns(*sample, signal_patterns)) {
	      if( debug>1 ){
		std::cerr << "INFO  : Scale signal sample " << *sample << " by scale " << signal_scale << std::endl;
	      }
	      buffer->Scale(signal_scale);
	    }
	    blind_data_obs->Add(buffer);
	    if (debug > 1){
	      std::cerr << "INFO  : Adding: " << buffer->GetName() << " -- " << buffer->Integral() << " --> New value: " << blind_data_obs->Integral() << std::endl;
	    }
	  }
	}
	else{
	  std::cout << "INFO  : Data are not blinded." << std::endl;
	}
	if(rnd>=0){
	  // randomize histogram; this will automatically have integer integral
	  std::cerr << "-- R A N D O M I Z I N G --" << std::endl;
	  randomize(blind_data_obs, rnd, debug);
	}
	else{
	  // use expected mean with signal injected
	  blind_data_obs->Scale(TMath::Nint(blind_data_obs->Integral())/blind_data_obs->Integral());
	  // adjust uncertaintie
	  adjustUncerts(blind_data_obs);
	}
	std::cout << "INFO  : New data_obs yield: " << idir->GetName() << "   " << TMath::Nint(blind_data_obs->Integral()) << std::endl;
	if(armed){
          if (debug > 1){
            std::cerr << "INFO  : Writing to file: " << blind_data_obs->GetName() << std::endl;
	  }
	  if(outputFile){
	    // write to a dedicated new file with name output in case output has been specified
	    // make sure data_obs in correct file for MSSM injection is changed
	    // this is the old file which is overwritten 
	    if(std::string(outputLabel).find("MSSM") != std::string::npos){
	      outputFile->cd(idir->GetName());
	      blind_data_obs->Write("data_obs", TObject::kOverwrite);
	    }
	    else{
	      outputFile->mkdir(idir->GetName()); outputFile->cd(idir->GetName());
	      blind_data_obs->Write("data_obs"); 
	    }
	  }
	  else{
	    // override old data_obs in the inputfile otherwise
	    file->cd(idir->GetName());
	    blind_data_obs->Write("data_obs", TObject::kOverwrite); 
	  }
	}
      }
    }
  }
  file->Close();
  if(outputFile){
    outputFile->Close();
  }
  return;
}
Example #17
0
int main (int argc, char** argv)
{
  // check number of inpt parameters
  if (argc < 2)
    {
      cerr << "Forgot to put the cfg file --> exit " << endl ;
      return 1 ;
    }
  if (gConfigParser) return 1 ;
  gConfigParser = new ConfigParser () ;
  
  TString config ; 
  config.Form ("%s",argv[1]) ;
  if (! (gConfigParser->init (config)))
    {
      cout << ">>> parseConfigFile::Could not open configuration file " << config << endl ;
      return -1 ;
    }

  float lumi = gConfigParser->readFloatOption ("general::lumi") ;
  cout << "READING lumi " << lumi << endl ;

  int maxEvtsMC = -1;
  if (gConfigParser->isDefined ("general::maxEvtsMC"))
        maxEvtsMC = gConfigParser -> readIntOption ("general::maxEvtsMC");

  // get the samples to be analised
  // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

  // isolated samples
  // .... .... .... .... .... .... .... .... .... .... .... ....
  
  vector<string> sigSamplesList = gConfigParser->readStringListOption ("general::signals") ;
  vector<sample> sigSamples ;
  readSamples (sigSamples, sigSamplesList) ;

  vector<float> signalScales ;
  for (unsigned int i = 0 ; i < sigSamplesList.size () ; ++i)
    {
      string name = string ("samples::") + sigSamplesList.at (i) + string ("FACT") ;
      float scale = gConfigParser->readFloatOption (name.c_str ()) ;
      signalScales.push_back (scale) ;        
    }

  vector<string> bkgSamplesList = gConfigParser->readStringListOption ("general::backgrounds") ;
  vector<sample> bkgSamples ;
  readSamples (bkgSamples, bkgSamplesList) ;

  vector<string> DATASamplesList = gConfigParser->readStringListOption ("general::data") ;
  vector<sample> DATASamples ;
  readSamples (DATASamples, DATASamplesList) ;

/*
  // NOT isolated samples
  // not needed anymore from Skims_7_NI because we don't ask isolation during the skim
  // .... .... .... .... .... .... .... .... .... .... .... ....
  
  vector<string> NI_sigSamplesList = gConfigParser->readStringListOption ("general::NIsignals") ;
  vector<sample> NI_sigSamples ;
  readSamples (NI_sigSamples, NI_sigSamplesList) ;

  vector<string> NI_bkgSamplesList = gConfigParser->readStringListOption ("general::NIbackgrounds") ;
  vector<sample> NI_bkgSamples ;
  readSamples (NI_bkgSamples, NI_bkgSamplesList) ;

  vector<string> NI_DATASamplesList = gConfigParser->readStringListOption ("general::NIdata") ;
  vector<sample> NI_DATASamples ;
  readSamples (NI_DATASamples, NI_DATASamplesList) ;
*/

  // get the selections to be applied
  // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

  vector<string> activeSelections = gConfigParser->readStringListOption ("computeQCDratio::list") ;
  vector<pair <TString, TCut> > selections = readCutsFile (
      activeSelections,
      gConfigParser->readStringOption ("selections::selectionsFile")
    ) ;

  cout << "\n-====-====-====-====-====-====-====-====-====-====-====-====-====-\n\n" ;
  cout << "selections sequence: \n" ;
  for (unsigned int i = 0 ; i < selections.size () ; ++i)
    cout << selections.at (i).first << " : " << selections.at (i).second << endl ;

  // read thresholds for non iso WPs
  std::vector<float> dau1iso_thrLow = gConfigParser->readFloatListOption ("computeQCDratio::dau1isothrLow");
  std::vector<float> dau2iso_thrLow = gConfigParser->readFloatListOption ("computeQCDratio::dau2isothrLow"); // iso > thrLow

  vector <vector<pair <TString, TCut> > > vec_allselections_SS;
  vector <vector<pair <TString, TCut> > > vec_allselections_OS;

  // create SS and OS selections
  for (unsigned int ithr = 0; ithr < dau1iso_thrLow.size(); ithr++)
  {
    // OS
    vector<pair <TString, TCut> > this_selections_OS = selections ;
    for (unsigned int i = 0 ; i < this_selections_OS.size () ; ++i)
    {
      this_selections_OS.at (i).first = TString (Form("OSaiso_%f_%f_", dau1iso_thrLow.at(ithr), dau2iso_thrLow.at(ithr))) + this_selections_OS.at (i).first ;
      TString cut = Form("dau1_iso > %f && dau2_iso > %f && isOS != 0", dau1iso_thrLow.at(ithr), dau2iso_thrLow.at(ithr));
      cout << "OS anti-iso selecton: " << cut << endl;
      this_selections_OS.at (i).second = this_selections_OS.at (i).second && TCut(cut) ;
    }
    vec_allselections_OS.push_back(this_selections_OS);

    // SS
    vector<pair <TString, TCut> > this_selections_SS = selections ;
    for (unsigned int i = 0 ; i < this_selections_SS.size () ; ++i)
    {
      this_selections_SS.at (i).first = TString (Form("SSaiso_%f_%f_", dau1iso_thrLow.at(ithr), dau2iso_thrLow.at(ithr))) + this_selections_SS.at (i).first ;
      TString cut = Form("dau1_iso > %f && dau2_iso > %f && isOS == 0", dau1iso_thrLow.at(ithr), dau2iso_thrLow.at(ithr));
      cout << "SS anti-iso selecton: " << cut << endl;
      this_selections_SS.at (i).second = this_selections_SS.at (i).second && TCut(cut) ;
    }
    vec_allselections_SS.push_back(this_selections_SS);


  }

  // now merge all selections for different iso thresholds into a single one to be faster
  vector<pair <TString, TCut> > selections_OS;
  for (unsigned int iv = 0; iv < vec_allselections_OS.size(); iv++)
  {
    for (unsigned int isel = 0; isel < vec_allselections_OS.at(iv).size(); isel++)
    {
      pair <TString, TCut> thisPair = vec_allselections_OS.at(iv).at(isel);
      selections_OS.push_back (thisPair);
    }
  }

  vector<pair <TString, TCut> > selections_SS;
  for (unsigned int iv = 0; iv < vec_allselections_SS.size(); iv++)
  {
    for (unsigned int isel = 0; isel < vec_allselections_SS.at(iv).size(); isel++)
    {
      pair <TString, TCut> thisPair = vec_allselections_SS.at(iv).at(isel);
      selections_SS.push_back (thisPair);
    }
  }

  // check that everything is fine:
  for (unsigned int isel = 0; isel < selections_OS.size(); isel++)
    cout << selections_OS.at(isel).first << endl;
  for (unsigned int isel = 0; isel < selections_SS.size(); isel++)
    cout << selections_SS.at(isel).first << endl;


  // get the variables to be plotted -- will make OS / SS plot ratio for each
  // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

  vector<string> variablesList = gConfigParser->readStringListOption ("general::variables") ;
  
  vector<string> Buf_variables2DList(0); 
  if (gConfigParser->isDefined ("general::2Dvariables")) Buf_variables2DList = gConfigParser->readStringListOption ("general::2Dvariables") ;
  vector<pair<string,string> > variables2DList(0);
  for (unsigned int i = 0 ; i < Buf_variables2DList.size () ; ++i)
    {
      vector<string> dummy = split (Buf_variables2DList.at (i), ':') ;
      //cout << dummy.at (0) << " " << dummy.at (1) << " " << dummy.size () << endl ;
      variables2DList.push_back (make_pair(dummy.at (0), dummy.at (1)) ) ;
    }


  // calculate the QCD in the SS region as data - other_bkg
  // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

  cout << "--- MAIN reading DATA and filling SS histos" << endl ;

  // get the same-sign distributions from data
  plotContainer SS_DATA_plots ("SS_DATA", variablesList, variables2DList, selections_SS, DATASamplesList, 2) ;
  counters SS_DATACount = fillHistos (DATASamples, SS_DATA_plots, 
              variablesList, variables2DList,
              selections_SS,
              lumi,
              vector<float> (0),
              true, false) ;
 // SS_DATA_plots.AddOverAndUnderFlow () ;

  cout << "--- MAIN reading bkg and filling SS histos" << endl ;

  // get the same-sign distributions from bkg
  plotContainer SS_bkg_plots ("SS_bkg", variablesList, variables2DList, selections_SS, bkgSamplesList, 0) ;
  counters SS_bkgCount = fillHistos (bkgSamples, SS_bkg_plots, 
              variablesList, variables2DList,
              selections_SS,
              lumi,
              vector<float> (0),
              false, false, maxEvtsMC) ;
 // SS_bkg_plots.AddOverAndUnderFlow () ;

  cout << "--- MAIN preparing to loop on variables and selections to calc SS QCD" << endl ;

  // the index in the stack is based on variable ID (iv) and selection ID (isel):
  // iHisto = iv + nVars * isel
  vector<string> QCDsample ;
  QCDsample.push_back ("QCD") ;
  plotContainer SS_QCD ("SS_QCD", variablesList, variables2DList, selections_SS, QCDsample, 0) ;
  //  vector <TH1F *> SS_QCD ;
  for (unsigned int ivar = 0 ; ivar < variablesList.size () ; ++ivar)
    {
      for (unsigned int icut = 0 ; icut < selections_SS.size () ; ++icut)
        {
          THStack * D_stack = SS_DATA_plots.makeStack (variablesList.at (ivar),
                                  selections_SS.at (icut).first.Data ()) ;
          TH1F * tempo = (TH1F *) D_stack->GetStack ()->Last () ;
          TString name = tempo->GetName () ;
          name = TString ("DDQCD_") + name ;
          TH1F * dummy = (TH1F *) tempo->Clone (name) ;

          THStack * b_stack = SS_bkg_plots.makeStack (variablesList.at (ivar),
                                  selections_SS.at (icut).first.Data ()) ;
          TH1F * h_bkg = (TH1F *) b_stack->GetStack ()->Last () ;
          dummy->Add (h_bkg, -1) ;
          SS_QCD.m_histos[variablesList.at (ivar)][selections_SS.at (icut).first.Data ()]["QCD"] = dummy ;
        }
    }


  // calculate the QCD in the OS region as data - other_bkg
  // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
  cout << "--- MAIN reading DATA and filling OS histos" << endl ;

  // get the same-sign distributions from data
  plotContainer OS_DATA_plots ("OS_DATA", variablesList, variables2DList, selections_OS, DATASamplesList, 2) ;
  counters OS_DATACount = fillHistos (DATASamples, OS_DATA_plots, 
              variablesList, variables2DList,
              selections_OS,
              lumi,
              vector<float> (0),
              true, false) ;
  // OS_DATA_plots.AddOverAndUnderFlow () ;

  cout << "--- MAIN reading bkg and filling OS histos" << endl ;

  // get the same-sign distributions from bkg
  plotContainer OS_bkg_plots ("OS_bkg", variablesList, variables2DList, selections_OS, bkgSamplesList, 0) ;
  counters OS_bkgCount = fillHistos (bkgSamples, OS_bkg_plots, 
              variablesList, variables2DList,
              selections_OS,
              lumi,
              vector<float> (0),
              false, false, maxEvtsMC) ;
  // OS_bkg_plots.AddOverAndUnderFlow () ;

  cout << "--- MAIN preparing to loop on variables and selections to calc OS QCD" << endl ;

  // the index in the stack is based on variable ID (iv) and selection ID (isel):
  // iHisto = iv + nVars * isel
  //vector<string> QCDsample ;
  //QCDsample.push_back ("QCD") ;
  plotContainer OS_QCD ("OS_QCD", variablesList, variables2DList, selections_OS, QCDsample, 0) ;
  //  vector <TH1F *> OS_QCD ;
  for (unsigned int ivar = 0 ; ivar < variablesList.size () ; ++ivar)
    {
      for (unsigned int icut = 0 ; icut < selections_OS.size () ; ++icut)
        {
          THStack * D_stack = OS_DATA_plots.makeStack (variablesList.at (ivar),
                                  selections_OS.at (icut).first.Data ()) ;
          TH1F * tempo = (TH1F *) D_stack->GetStack ()->Last () ;
          TString name = tempo->GetName () ;
          name = TString ("DDQCD_") + name ;
          TH1F * dummy = (TH1F *) tempo->Clone (name) ;

          THStack * b_stack = OS_bkg_plots.makeStack (variablesList.at (ivar),
                                  selections_OS.at (icut).first.Data ()) ;
          TH1F * h_bkg = (TH1F *) b_stack->GetStack ()->Last () ;
          dummy->Add (h_bkg, -1) ;
          OS_QCD.m_histos[variablesList.at (ivar)][selections_OS.at (icut).first.Data ()]["QCD"] = dummy ;
        }
    }


  // calculate the QCD in the OS region as data - other_bkg
  // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
  cout << "--- MAIN calculating ratios OS / SS" << endl ;
  //gStyle->SetOptStat(0);

  TString outFolderNameBase = gConfigParser->readStringOption ("general::outputFolderName") ;
  outFolderNameBase += "/" ;
  system (TString ("mkdir -p ") + outFolderNameBase) ;
  outFolderNameBase += gConfigParser->readStringOption ("computeQCDratio::outputFolderName") ;
  outFolderNameBase += "/" ;  
  system (TString ("mkdir -p ") + outFolderNameBase) ;
  system (TString ("mkdir -p ") + outFolderNameBase + TString("ratioplots/")) ; 
  system (TString ("mkdir -p ") + outFolderNameBase + TString("num_denom_plots/")) ; 
  system (TString ("mkdir -p ") + outFolderNameBase + TString("num_denom_plots_log/")) ; 
  system (TString ("mkdir -p ") + outFolderNameBase + TString("events/")) ; 
  system (TString ("mkdir -p ") + outFolderNameBase + TString("events_log/")) ; 

  TFile* fOut = new TFile (outFolderNameBase + "ratioPlots.root", "RECREATE");
  fOut->cd();
  TCanvas* c1 = new TCanvas;

  gStyle->SetOptFit(1111);

  TF1* f = new TF1 ("f", "[0] + [1]*x");
  f->SetParameters (1.06, -0.0002);

  //for (unsigned int isample = 0; isample < samples.size(); isample++)
  for (unsigned int ivar = 0; ivar < variablesList.size(); ivar++)
  {
    for (unsigned int isel = 0; isel < selections.size(); isel++)
    {
      for (unsigned int ithr = 0; ithr < dau1iso_thrLow.size(); ithr++)
      {
          TH1F* thisRatio = makeRatio (OS_QCD, SS_QCD,
                 selections.at(isel),
                 variablesList.at(ivar),
                 QCDsample.at(0), // "QCD"
                 dau1iso_thrLow.at(ithr),
                 dau2iso_thrLow.at(ithr) );
     
          thisRatio -> SetMarkerStyle(8);
          thisRatio -> SetMarkerSize(1);
          thisRatio -> SetMarkerColor(kBlack);

          c1->SetLogy(false);
          thisRatio -> Draw();
          //thisRatio -> Fit("pol1");
          thisRatio -> Fit("f", "", "", 200, 1000);
          TString newName = outFolderNameBase + "ratioplots/ratio_" + variablesList.at(ivar) + "_" + selections.at(isel).first + Form("_%f_%f.pdf", dau1iso_thrLow.at(ithr), dau2iso_thrLow.at(ithr)) ;
          c1->Print (newName, "pdf");

          thisRatio -> Write();

          // now draw together SS and OS for this selection and draw plot
          pair <TH1F*, TH1F*> res = getPlotPair (OS_QCD, SS_QCD,
                 selections.at(isel),
                 variablesList.at(ivar),
                 QCDsample.at(0), // "QCD"
                 dau1iso_thrLow.at(ithr),
                 dau2iso_thrLow.at(ithr) );

          TH1F* hOS = res.first;
          TH1F* hSS = res.second;
          hOS->SetStats(false);
          hSS->SetStats(false);
          hOS->SetLineColor (kRed);
          hSS->SetLineColor (kBlue);
          hOS->SetMarkerColor (kRed);
          hSS->SetMarkerColor (kBlue);
          hOS->SetMarkerStyle (4);
          hSS->SetMarkerStyle (5);

          if (hSS->GetMaximum() > hOS->GetMaximum()) hOS->SetMaximum(hSS->GetMaximum());
          hOS->SetMaximum(1.2*hOS->GetMaximum());
      
          TLegend leg (0.41, 0.79, 0.89, 0.89);
          leg.SetNColumns(2);
          leg.SetFillColor(kWhite);
          leg.SetLineWidth(0);
          leg.SetBorderSize(0);
          leg.AddEntry(hOS, "OS", "lp");
          leg.AddEntry(hSS, "SS", "lp");
          hOS->Draw();
          hSS->Draw("same");
          leg.Draw();

          newName = outFolderNameBase + "num_denom_plots/ratio_" + variablesList.at(ivar) + "_" + selections.at(isel).first + Form("_%f_%f.pdf", dau1iso_thrLow.at(ithr), dau2iso_thrLow.at(ithr)) ;
          c1->Print (newName, "pdf");

          // ------- log ----
          c1->SetLogy(true);
          hOS->Draw();
          hSS->Draw("same");
          //leg.Draw();

          newName = outFolderNameBase + "num_denom_plots_log/ratio_" + variablesList.at(ivar) + "_" + selections.at(isel).first + Form("_%f_%f_log.pdf", dau1iso_thrLow.at(ithr), dau2iso_thrLow.at(ithr)) ;
          c1->Print (newName, "pdf");
          c1->SetLogy(false);

      }
    }
  }


  // ------------------------------------------------------------------
  cout << "--- MAIN printing event plots" << endl ;

  for (unsigned int ivar = 0 ; ivar < variablesList.size () ; ++ivar)
  {
    for (unsigned int icut = 0 ; icut < selections_OS.size () ; ++icut)
    {
      THStack * D_stack = OS_DATA_plots.makeStack (variablesList.at (ivar),
                              selections_OS.at (icut).first.Data ()) ;
      TH1F * D_histo = (TH1F *) D_stack->GetStack ()->Last () ;
      D_histo -> Sumw2(false);
      D_histo -> SetBinErrorOption(TH1::kPoisson);
      D_histo -> SetMarkerStyle (8);
      D_histo -> SetMarkerSize (1);
      D_histo -> SetMarkerColor (kBlack);
      D_histo->SetMinimum(1.);


      THStack * b_stack = OS_bkg_plots.makeStack (variablesList.at (ivar),
                              selections_OS.at (icut).first.Data ()) ;
      //TH1F * h_bkg = (TH1F *) b_stack->GetStack ()->Last () ;
      D_histo->SetStats(false);
      D_histo->Draw("E"); // data surely above bkg as it is QCD dominated
      b_stack->Draw("hist same"); // data surely above bkg as it is QCD dominated

      TString newName = outFolderNameBase + "events/plot_" + variablesList.at(ivar) + "_" + selections_OS.at (icut).first + "_OS.pdf" ;
      c1->Print (newName, "pdf");

      c1->SetLogy(true);
      newName = outFolderNameBase + "events_log/plot_" + variablesList.at(ivar) + "_" + selections_OS.at (icut).first + "_log_OS.pdf" ;
      c1->Print (newName, "pdf");
      c1->SetLogy(false);

    }
  } 


  for (unsigned int ivar = 0 ; ivar < variablesList.size () ; ++ivar)
  {
    for (unsigned int icut = 0 ; icut < selections_SS.size () ; ++icut)
    {
      THStack * D_stack = SS_DATA_plots.makeStack (variablesList.at (ivar),
                              selections_SS.at (icut).first.Data ()) ;
      TH1F * D_histo = (TH1F *) D_stack->GetStack ()->Last () ;
      D_histo -> Sumw2(false);
      D_histo -> SetBinErrorOption(TH1::kPoisson);
      D_histo -> SetMarkerStyle (8);
      D_histo -> SetMarkerSize (1);
      D_histo -> SetMarkerColor (kBlack);
      D_histo->SetMinimum(1.);

    
      THStack * b_stack = SS_bkg_plots.makeStack (variablesList.at (ivar),
                              selections_SS.at (icut).first.Data ()) ;
      //TH1F * h_bkg = (TH1F *) b_stack->GetStack ()->Last () ;

      D_histo->SetStats(false);
      D_histo->Draw("E"); // data surely above bkg as it is QCD dominated
      b_stack->Draw("hist same"); // data surely above bkg as it is QCD dominated

      TString newName = outFolderNameBase + "events/plot_" + variablesList.at(ivar) + "_" + selections_SS.at (icut).first + "_SS.pdf" ;
      c1->Print (newName, "pdf");

      c1->SetLogy(true);
      newName = outFolderNameBase + "events_log/plot_" + variablesList.at(ivar) + "_" + selections_OS.at (icut).first + "_log_SS.pdf" ;
      c1->Print (newName, "pdf");
      c1->SetLogy(false);


    }
  }  
//   /* NB if it has to be subtracted, it cannot be scaled! */

//   // get the SS-to-OS scale factor and scale the QCD distributions
//   // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

//   float SStoOS_scaleFactor = 1.06 ; // to be calculated here at a certain moment!!
//   SS_QCD.scale (SStoOS_scaleFactor) ;

//   int QCDcolor = gConfigParser->readIntOption ("colors::QCD") ;
//   SS_QCD.setHistosProperties (0, QCDcolor) ; 

//   // insert the QCD in the OS region
//   // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

//   cout << "--- MAIN reading DATA and filling OS histos" << endl ;

//   // get the opposite-sign distributions from data
//   plotContainer OS_DATA_plots ("OS_DATA", variablesList, variables2DList, selections_OS, DATASamplesList, 2) ;
//   counters OS_DATACount = fillHistos (DATASamples, OS_DATA_plots, 
//               variablesList, variables2DList,
//               selections_OS,
//               lumi,
//               vector<float> (0),
//               true, false) ;
//   OS_DATA_plots.AddOverAndUnderFlow () ;

//   cout << "--- MAIN reading bkg and filling OS histos" << endl ;

//   // get the opposite-sign distributions from bkg
//   plotContainer OS_bkg_plots ("OS_bkg", variablesList, variables2DList, selections_OS, bkgSamplesList, 0) ;
//   counters OS_bkgCount = fillHistos (bkgSamples, OS_bkg_plots, 
//               variablesList, variables2DList,
//               selections_OS,
//               lumi,
//               vector<float> (0),
//               false, false, maxEvtsMC) ;
//   OS_bkg_plots.AddOverAndUnderFlow () ;
//   OS_bkg_plots.addSample ("QCD", SS_QCD) ;
  
//   cout << "--- MAIN reading sig and filling OS histos" << endl ;

//   // get the opposite-sign distributions from sig
//   plotContainer OS_sig_plots ("OS_sig", variablesList, variables2DList, selections_OS, sigSamplesList, 1) ;
//   counters OS_sigCount = fillHistos (sigSamples, OS_sig_plots, 
//               variablesList, variables2DList,
//               selections_OS,
//               lumi,
//               vector<float> (0),
//               false, true) ;
//   OS_sig_plots.AddOverAndUnderFlow () ;

//   // Save the histograms
//   // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

//   cout << "--- MAIN before saving" << endl ;

//   TString outFolderNameBase = gConfigParser->readStringOption ("general::outputFolderName") ;
//   outFolderNameBase += "/" ;
//   system (TString ("mkdir -p ") + outFolderNameBase) ;
//   outFolderNameBase += gConfigParser->readStringOption ("evalQCD::outputFolderName") ;
//   outFolderNameBase += "/" ;  
//   system (TString ("mkdir -p ") + outFolderNameBase) ;

//   TString outString ;
//   outString.Form (outFolderNameBase + "outPlotter.root") ;
//   TFile * fOut = new TFile (outString.Data (), "RECREATE") ;
//   SS_DATA_plots.save (fOut) ;
//   SS_bkg_plots.save (fOut) ;
//   OS_DATA_plots.save (fOut) ;
//   OS_bkg_plots.save (fOut) ;
//   OS_sig_plots.save (fOut) ;
//   SS_QCD.save (fOut); // this is the estimated QCD after scaling to OS region 1.06

//   fOut->Close () ;

//   // Plot the histograms
//   // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

//   system (TString ("mkdir -p ") + outFolderNameBase + TString ("/events/")) ;
//   system (TString ("mkdir -p ") + outFolderNameBase + TString ("/shapes/")) ;

//   TCanvas * c = new TCanvas () ;

//   cout << "--- MAIN before plotting" << endl ;

//   // loop on selections
//   for (unsigned int isel = 0 ; isel < selections.size () ; ++isel)
//     {
//       // loop on variables
//       for (unsigned int iv = 0 ; iv < variablesList.size () ; ++iv)
//         {
//           c->cd () ;
//           TString outputName ; 
//           outputName.Form ("plot_%s_%s",
//             variablesList.at (iv).c_str (), selections.at (isel).first.Data ()) ;

//           TString outFolderName = outFolderNameBase + TString ("/events/") ;

//           // get the extremes for the plot
//           THStack * sig_stack = OS_sig_plots.makeStack ( variablesList.at (iv), 
//                                     selections_OS.at (isel).first.Data ()) ;
//           THStack * bkg_stack = OS_bkg_plots.makeStack ( variablesList.at (iv), 
//                                     selections_OS.at (isel).first.Data ()) ;
//           THStack * DATA_stack = OS_DATA_plots.makeStack ( variablesList.at (iv), 
//                                     selections_OS.at (isel).first.Data ()) ;

//           vector<float> extremes_bkg  = getExtremes (bkg_stack) ;
//           vector<float> extremes_sig  = getExtremes (sig_stack) ;
//           vector<float> extremes_DATA = getExtremes (DATA_stack) ;
//           TH1F * bkg = c->DrawFrame (
//               extremes_bkg.at (0) ,
//               0.9 * min3 (extremes_bkg.at (1), extremes_sig.at (1), 
//                           extremes_DATA.at (1)) ,
//               extremes_bkg.at (2) ,
//               1.3 * max3 (extremes_bkg.at (3), extremes_sig.at (3), 
//                           extremes_DATA.at (3) + sqrt (extremes_DATA.at (3)))
//             ) ;  
     
//           copyTitles (bkg, bkg_stack) ;

//           bkg->Draw () ;
//           bkg_stack->Draw ("hist same") ;
//           sig_stack->Draw ("nostack hist same") ;
//           TH1F * h_data = (TH1F *) DATA_stack->GetStack ()->Last () ;
//           // FIXME probably the data uncertainties need to be fixed
//           h_data->Draw ("same") ;
          
//           TString coutputName ;
//           coutputName.Form ("%s.pdf", (outFolderName + outputName).Data ()) ;
//           c->SaveAs (coutputName.Data ()) ;

//           c->SetLogy (1) ;
//           bkg->Draw () ;
//           bkg_stack->Draw ("hist same") ;
//           sig_stack->Draw ("nostack hist same") ;
//           h_data->Draw ("same") ;

//           coutputName.Form ("%s_log.pdf", (outFolderName + outputName).Data ()) ;
//           c->SaveAs (coutputName.Data ()) ;
//           c->SetLogy (0) ;
          
//           // plotting shapes
//           // ---- ---- ---- ---- ---- ---- ---- ---- ----

//           outFolderName = outFolderNameBase + TString ("/shapes/") ;
//           TString basename ;
//           basename.Form ("shape_%s_%s",
//                   variablesList.at (iv).c_str (),
//                   selections.at (isel).first.Data ()
//                 ) ;

//           THStack * hstack_bkg_norm = normaliseStack (bkg_stack) ;
//           TH1F * shape_bkg = (TH1F *) hstack_bkg_norm->GetStack ()->Last () ;
          
//           THStack * hstack_sig_norm = normaliseStack (sig_stack) ;
//           TH1F * shape_sig = (TH1F *) hstack_sig_norm->GetStack ()->Last () ;
          
//           if (shape_sig->GetMaximum () > shape_bkg->GetMaximum ()) 
//             hstack_sig_norm->Draw ("hist") ;
//           else   
//             hstack_bkg_norm->Draw ("hist") ;

//           hstack_bkg_norm->Draw ("hist same") ;
//           hstack_sig_norm->Draw ("hist same") ;
          
//           TString name = basename + "_norm" ;
//           coutputName.Form ("%s.pdf", (outFolderName + basename).Data ()) ;
//           c->SaveAs (coutputName.Data ()) ;
 
//           /*
//           // plotting 2D histos, one per sample as it is hard to superimpose them
//           // ---- ---- ---- ---- ---- ---- ---- ---- ----
//           outFolderName = outFolderNameBase + TString ("/plots2D/") ;
//           OS_sig_plots.         
//           */

//           delete hstack_bkg_norm;
//           delete hstack_sig_norm;
//           delete sig_stack;
//           delete bkg_stack;
//           delete DATA_stack;
          
     
//         } // loop on variables
//     } // loop on selections

//   delete c ;


//   // print yields
//   // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
//   TString yieldsFileName = outFolderNameBase + "/yields.txt";
//   std::ofstream yieldsFile (yieldsFileName.Data());

//   unsigned int NSpacesColZero = 16;
//   unsigned int NSpacesColumns = 10;
  
//   cout << "\n-====-====-====-====-====-====-====-====-====-====-====-====-====-\n\n" ;
//   cout << " EXPECTED NUMBER OF SIG EVENTS\n\n" ;
//   yieldsFile << "\n-====-====-====-====-====-====-====-====-====-====-====-====-====-\n\n" ;
//   yieldsFile << " EXPECTED NUMBER OF SIG EVENTS\n\n" ;
  
//   printTableTitle (std::cout,  sigSamples) ;
//   printTableTitle (yieldsFile, sigSamples) ;
//   printTableBody  (std::cout,  selections, OS_sigCount, sigSamples) ;
//   printTableBody  (yieldsFile, selections, OS_sigCount, sigSamples) ;

//   vector<string> DataDriven_names (1, string("QCD"));
//   vector <vector<float>> DataDriven_yields;
//   vector<float> QCD_yields;
//   // QCD -- prepare yields
//   for (unsigned int iSel = 0 ; iSel < selections.size () ; ++iSel)
//   {
//         int nQCD = SS_QCD.getHisto (variablesList.at(0), string(selections_SS.at(iSel).first.Data()), QCDsample.at(0)) -> Integral();
//         QCD_yields.push_back (nQCD);
//   }
//   DataDriven_yields.push_back (QCD_yields);

//   cout << "\n-====-====-====-====-====-====-====-====-====-====-====-====-====-\n\n" ;
//   cout << " EXPECTED NUMBER OF BKG EVENTS\n\n" ;
//   yieldsFile << "\n-====-====-====-====-====-====-====-====-====-====-====-====-====-\n\n" ;
//   yieldsFile << " EXPECTED NUMBER OF BKG EVENTS\n\n" ;
//   printTableTitle (std::cout,  bkgSamples, DataDriven_names) ;
//   printTableTitle (yieldsFile, bkgSamples, DataDriven_names) ;
//   printTableBody  (std::cout,  selections, OS_bkgCount, bkgSamples, DataDriven_yields) ;
//   printTableBody  (yieldsFile, selections, OS_bkgCount, bkgSamples, DataDriven_yields) ;

//   // mini debug to cjeck that each var has the same QCD yield
//   /*  
//   // QCD
//   for (unsigned int iSel = 0 ; iSel < selections.size () ; ++iSel)
//   {
//       for (int ivar = 0 ; ivar < variablesList.size(); ivar++)
//       {
//         int nQCD = SS_QCD.getHisto (variablesList.at(ivar), string(selections_SS.at(iSel).first.Data()), QCDsample.at(0)) -> Integral();
//         cout << nQCD << " ";
//       }
//       cout <<  "  --- " << endl;
//   }
//   */

//   cout << "\n-====-====-====-====-====-====-====-====-====-====-====-====-====-\n\n" ;
//   cout << " OBSERVED NUMBER OF EVENTS\n\n" ;
//   yieldsFile << "\n-====-====-====-====-====-====-====-====-====-====-====-====-====-\n\n" ;
//   yieldsFile << " OBSERVED NUMBER OF EVENTS\n\n" ;
//   printTableTitle (std::cout,  DATASamples) ;
//   printTableTitle (yieldsFile, DATASamples) ;
//   printTableBody  (std::cout,  selections, OS_DATACount, DATASamples) ;
//   printTableBody  (yieldsFile, selections, OS_DATACount, DATASamples) ;

//   cout << "\n-====-====-====-====-====-====-====-====-====-====-====-====-====-\n\n" ;
//   cout << " TOTALS\n\n" ;
//   yieldsFile << "\n-====-====-====-====-====-====-====-====-====-====-====-====-====-\n\n" ;
//   yieldsFile << " TOTALS\n\n" ;
//   vector<float> DATAtotal = OS_DATACount.getTotalCountsPerCut () ;
//   vector<float> bkgtotal = OS_bkgCount.getTotalCountsPerCut () ;
//   vector<string> titles ; titles.push_back ("DATA") ; titles.push_back ("bkg") ;
//   printTableTitle (std::cout, titles) ;
//   printTableTitle (yieldsFile, titles) ;
  
//   for (unsigned int iSel = 0 ; iSel < selections.size () ; ++iSel)
//     {
//       cout << selections.at (iSel).first ;
//       yieldsFile << selections.at (iSel).first ;
//       unsigned int nspacetojump = (NSpacesColZero > string(selections.at (iSel).first.Data ()).size () ? NSpacesColZero - string(selections.at (iSel).first.Data ()).size () : 0);
//       for (unsigned int i = 0 ; i < nspacetojump; ++i){
//         cout << " " ;
//         yieldsFile << " " ;
//       } 
//       cout << "|" ;
//       yieldsFile << "|" ;
      
//       float evtnum = DATAtotal.at (iSel+1) ;
//       int subtractspace = 0 ;
//       if (evtnum > 0) subtractspace = int (log10 (evtnum)) ;
//       for (unsigned int i = 0 ; i < NSpacesColumns - subtractspace ; ++i)
//       {
//         cout << " " ;
//         yieldsFile << " " ;
//       }
//       cout << setprecision (0) << fixed << evtnum
//            << " |" ;
//       yieldsFile << setprecision (0) << fixed << evtnum
//            << " |" ;

//       evtnum = bkgtotal.at (iSel+1);
//       for (unsigned int iDD = 0; iDD < DataDriven_yields.size(); iDD++) evtnum += DataDriven_yields.at(iDD).at(iSel);
//       subtractspace = 0 ;
//       if (evtnum > 0) subtractspace = int (log10 (evtnum)) ;
//       for (unsigned int i = 0 ; i < NSpacesColumns - subtractspace ; ++i)
//       {
//           cout << " " ;
//           yieldsFile << " " ;
//       }
//       cout << setprecision (0) << fixed << evtnum
//            << " |\n" ;
//       yieldsFile << setprecision (0) << fixed << evtnum
//            << " |\n" ;
//     }
// /*
//   cout << " ============ MINI DEBUG ON QCD YIELDS ============ " << endl;
//   for (unsigned int isel = 0 ; isel < selections.size () ; ++isel)
//     {
//       // loop on variables
//       for (unsigned int iv = 0 ; iv < variablesList.size () ; ++iv) 

//     }
// */

//   // save on root file for debug
//   //TFile* fRootOut = new TFile (outFolderNameBase + "/" + "SS_QCD_histos.root", "recreate");
//   //fRootOut->Close();

  return 0 ;
}  
void rescaleSignal(bool armed, double scale, const char* filename, const char* pattern="", unsigned int debug=0)
{
  std::vector<std::string> histnames; histnames.clear();
  if( debug>0 ){
    std::cout << "file  = " << filename << std::endl;
    std::cout << "scale = " << scale    << std::endl;
    std::cout << "armed = " << armed    << std::endl;
  }
  TFile* file = new TFile(filename, "update");
  TIter nextDirectory(file->GetListOfKeys());
  std::vector<std::string> buffer;
  TKey* idir;
  while((idir = (TKey*)nextDirectory())){
    buffer.clear();
    if( idir->IsFolder() ){
      file->cd(); // make sure to start in directory head 
      if( debug>0 ){ std::cout << "Found directory: " << idir->GetName() << std::endl; }
      if( file->GetDirectory(idir->GetName()) ){
	file->cd(idir->GetName()); // change to sub-directory
	buffer = signalList(idir->GetName(), pattern, debug);
      }
      // append to the vector of histograms to be rescaled
      for(std::vector<std::string>::const_iterator elem=buffer.begin(); elem!=buffer.end(); ++elem){
	histnames.push_back(*elem);
      }
      if(debug>1){
	std::cout << "added " << buffer.size() << " elements to histnames [" << histnames.size() << "] for directory " << idir->GetName() << std::endl;
      }
    }
  }
  // pick up files which are not kept in an extra folder
  file->cd(); buffer.clear();
  buffer = signalList("", pattern, debug);
  // append to the vector of histograms to be rescaled
  for(std::vector<std::string>::const_iterator elem=buffer.begin(); elem!=buffer.end(); ++elem){
    histnames.push_back(*elem);
  }
  if(debug>1){
    std::cout << "added " << buffer.size() << " elements to histnames [" << histnames.size() << "] for file head" << std::endl;
  }

  for(std::vector<std::string>::const_iterator hist=histnames.begin(); hist!=histnames.end(); ++hist){
    file->cd();
    TH1F* h = (TH1F*)file->Get(hist->c_str());
    std::string histName;
    if(hist->find("/")!=std::string::npos){
      histName = hist->substr(hist->find("/")+1);
    }
    else{
      histName = *hist;
    }
    TH1F* hout = (TH1F*)h->Clone(histName.c_str());
    if(debug>1){
      std::cout << "...folder    : " << hist->substr(0, hist->find("/")).c_str() << std::endl;
      std::cout << "...histogram : " << hout->GetName () << " / " << hist->c_str() << std::endl; 
      std::cout << "...old scale : " << hout->Integral() << std::endl; 
    }
    hout->Scale(scale);
    if(match(pattern, "data")){
      //make sure to have an integer integral when rescaling data yields
      hout->Scale(int(hout->Integral())/hout->Integral());
    }
    if(debug>1){ 
      std::cout << "...new scale : " << hout->Integral() << std::endl; 
    }
    if(armed){
      if(hist->find("/")!=std::string::npos){
	file->cd(hist->substr(0, hist->find("/")).c_str());
      }
      else{
	file->cd();
      }
      std::cout << "writing to file: " << hout->GetName() << std::endl;
      hout->Write(hist->substr(hist->find("/")+1).c_str(), TObject::kOverwrite); 
    }
  }
  file->Close();
  return;
}
Example #19
0
void ootpu_fit(TString files, TString comments="") {

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

  TH1::SetDefaultSumw2();

  TH1F* hrelIso = new TH1F("hrelIso","", 30, 0, 0.5);
  TH1F* hOOTPU = new TH1F("hOOTPU","", 75, 0, 75);
  TH1F* hOOTPUvsIso = new TH1F("hOOTPUvsIso",";Out-of-time ints.;Isolation cut efficiency", 15, 0, 75);

  hrelIso->StatOverflows(true);
  
  int n1(0), n2(0);
  if (files.Contains("20bx25")) {
    n1=15;
    n2=75;
  }
  else if (files.Contains("S14")) {
    n1=0;
    n2=120;
  }
  else { // default: 8 TeV scenario
    n1=0;
    n2=70;
  }


  TString mu("num_gen_muons==1&&muon_reco_match>=0");
  int low = 15; 
  for (int bin(1); bin<hOOTPUvsIso->GetNbinsX()+1; bin++) {
    if (bin<4) continue;
    if (bin>4) low=low+5;
    if (low>hOOTPUvsIso->GetBinLowEdge(hOOTPUvsIso->GetNbinsX())) break;
    TString cuts = Form("(%s)&&(oot_pu>=%d&&oot_pu<%d)",mu.Data(),low,low+4);
    cout << "Cuts: " << cuts.Data() << endl;
    chain->Project(hrelIso->GetName(), "muon_relIso", cuts);
    chain->Project(hOOTPU->GetName(), "oot_pu", cuts);
    hrelIso->Scale(1/hrelIso->GetEntries());
    Double_t left(0.), lerror(0.), right(0.), rerror(0.);
    left = hrelIso->IntegralAndError(1,12,lerror);
    right = hrelIso->IntegralAndError(13,31,rerror);
    float rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
    printf("bin1: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
    hOOTPUvsIso->SetBinContent(bin,left/(left+right));
    hOOTPUvsIso->SetBinError(bin,rat_error);
  }
  
  hOOTPUvsIso->SetLineColor(1);
  hOOTPUvsIso->SetMarkerColor(1);
  hOOTPUvsIso->SetMarkerStyle(20);

  TCanvas* c1 = new TCanvas();

  hOOTPUvsIso->Draw("e1");

  // do a linear fit
  TF1 *flin = new TF1("flin", "1 ++ x", 15, 75);
  hOOTPUvsIso->Fit(flin);
  flin=hOOTPUvsIso->GetFunction("flin");
  flin->SetLineColor(kBlue);
  flin->SetLineWidth(2);

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

  // cout << "Rejection rates" << endl;
  // Double_t left(0.), lerror(0.), right(0.), rerror(0.);
  // left = hA->IntegralAndError(1,12,lerror);
  // right = hA->IntegralAndError(13,31,rerror);
  // float rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  // printf("bin1: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  // left = hB->IntegralAndError(1,12,lerror);
  // right = hB->IntegralAndError(13,31,rerror);
  // rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  // printf("bin2: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  // left = hC->IntegralAndError(1,12,lerror);
  // right = hC->IntegralAndError(13,31,rerror);
  // rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  // printf("bin3: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  // left = hD->IntegralAndError(1,12,lerror);
  // right = hD->IntegralAndError(13,31,rerror);
  // rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  // printf("bin4: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
}
Example #20
0
void countPhotonID()
{
  const double fBinsEta[]={0,1.45,1.7,2.5};
  const double fBinsPt[]={15,20,30,50,80,120};
  const int nPtBin = 5;
  const int nEtaBin = 2;

  float data[nEtaBin][nPtBin][2]={{{0.}}}; // the last index is before and after cuts
  float mc[nEtaBin][nPtBin][2]={{{0.}}};  // the last index is before and after cuts

  
  TFile* inf_central = new TFile("TightEESBData_template.root");
  TFile* inf_vary    = new TFile("vary_showershape.root");

  char* dec[2] = {"EB","EE"};

  for(int ieta=0; ieta < nEtaBin; ieta++)
    {
      for(int ipt=0; ipt < nPtBin; ipt++)
	{
	  data[ieta][ipt][0]= data[ieta][ipt][1] = 
	    mc[ieta][ipt][0]= mc[ieta][ipt][1] = 0.;
	  
	  TH1F* htemp = (TH1F*)inf_central->FindObjectAny(
	  Form("h_%s_comb3Iso_EGdata_pt%d", dec[ieta], (int)fBinsPt[ipt]));	
	  cout << "Find " << htemp->GetName() << " in " << inf_central->GetName() << endl;
	  data[ieta][ipt][0] = htemp->Integral();

	  TH1F* htemp1 = (TH1F*)inf_vary->FindObjectAny(
	  Form("h_%s_comb3Iso_EGdata_pt%d", dec[ieta], (int)fBinsPt[ipt]));	  
	  cout << "Find " << htemp1->GetName() << " in " << inf_vary->GetName() << endl;
	  data[ieta][ipt][1] = htemp1->Integral();

	  float dataRatio=0, dataRatioErr=0;
	  errmc(data[ieta][ipt][1],data[ieta][ipt][0],dataRatio,dataRatioErr);
	  
	  TH1F* htemp2 = (TH1F*)inf_central->FindObjectAny(
	   Form("h_%s_comb3Iso_sig_pt%d", dec[ieta], (int)fBinsPt[ipt]));
	  cout << "Find " << htemp2->GetName() << " in " << inf_central->GetName() << endl;

	  TH1F* htemp2_1 = (TH1F*)inf_central->FindObjectAny(
	   Form("h_%s_comb3Iso_bkg_pt%d", dec[ieta], (int)fBinsPt[ipt]));
	  cout << "Find " << htemp2_1->GetName() << " in " << inf_central->GetName() << endl;

	  mc[ieta][ipt][0] = htemp2->Integral() + htemp2_1->Integral();
	  

	  TH1F* htemp3 = (TH1F*)inf_vary->FindObjectAny(
	   Form("h_%s_comb3Iso_sig_pt%d", dec[ieta], (int)fBinsPt[ipt]));
	  cout << "Find " << htemp3->GetName() << " in " << inf_vary->GetName() << endl;

	  TH1F* htemp3_1 = (TH1F*)inf_vary->FindObjectAny(
	   Form("h_%s_comb3Iso_bkg_pt%d", dec[ieta], (int)fBinsPt[ipt]));
	  cout << "Find " << htemp3_1->GetName() << " in " << inf_vary->GetName() << endl;

	  mc[ieta][ipt][1] = htemp3->Integral() + htemp3_1->Integral();

	  
	  float mcRatio=0, mcRatioErr=0;
	  errmc(mc[ieta][ipt][1],mc[ieta][ipt][0],mcRatio,mcRatioErr);
	  
	  cout << "For " << dec[ieta] << " and pt = " << fBinsPt[ipt] << " -- " << fBinsPt[ipt+1] << endl; 
	  float doubleRatio=0, doubleRatioErr=0;
	  errdataMC(dataRatio,dataRatioErr,mcRatio,mcRatioErr,
		    doubleRatio, doubleRatioErr);
	  
	} // end of loop over pt bins
    } // end of loop over eta bins
  
  


}
Example #21
0
int rdEztFeePed(
 int nEve=3000,
 Int_t nFiles  = 20,
 char* file="R5135068ezB.lis", 
 char* inDir   = "../oldPanitkin/muDst/",
 TString outPath="feePed4/"
 ){ 
  // file="st_physics_6008023_raw_1030001.MuDst.root";// pedestal, 1987eve
  file="st_physics_6008016_raw_1020001.MuDst.root";// commisCu, ~20Keve
  // inDir   = "./";

  gROOT->LoadMacro("$STAR/StRoot/StMuDSTMaker/COMMON/macros/loadSharedLibraries.C");
  loadSharedLibraries();
  cout << " loading done " << endl;
  assert( !gSystem->Load("StEEmcPoolmuEztFeePed")); 
  //  assert( !gSystem->Load("StEEmcUtil")); 

  // create chain    
  chain = new StChain("StChain"); 

  printf("adding muDst from '%s' ....\n",file);
  // Now we add Makers to the chain...   
  muMk = new StMuDstMaker(0,0,inDir,file,"MuDst.root",nFiles);
  TChain* tree=muMk->chain(); assert(tree); 
  int nEntries=tree->GetEntries();
  printf("total eve in chain =%d\n",nEntries);
  printf("in=%s%s=\n",inDir,file);
  //return;

  HList=new  TObjArray;

  myMk3=new StFeePedMaker("eeFeePed","MuDst");
  myMk3->SetHList(HList);
 
  gMessMgr->SwitchOff("D");
  gMessMgr->SwitchOn("I");
 

  muMk->SetStatus("*",0);
  muMk->SetStatus("EztAll",1);
  chain->Init();
  chain->ls(3);
  // muMk->printArrays();

  printf("All Ezt-branches set\n");
  int eventCounter=0;
  int stat=0;
  int t1=time(0);
  StMuTimer timer;
  timer.start();

  //---------------------------------------------------
  while ( 1) {// loop over events
    if(eventCounter>=nEve) break;
    eventCounter++;
    chain->Clear();
    stat = chain->Make();
    if(stat) break;
    if(eventCounter%1000!=0)continue;
    
    printf("\n\n ====================%d  processing  ==============\n", eventCounter);
    
  }
  printf("sorting done, nEve=%d of %d\n",nEve, nEntries);
  int t2=time(0);
  if(t1==t2) t2++;
  float rate=1.*eventCounter/(t2-t1);
  float nMnts=(t2-t1)/60.;
  printf("sorting done %d of   nEve=%d, elapsed rate=%.1f Hz, tot %.1f minutes\n",eventCounter,nEntries,rate,nMnts);
  
  if (eventCounter) {
    cout << "CPU time/event= " << timer.elapsedTime()/eventCounter << " sec  "
	 << " rate= " << eventCounter/timer.elapsedTime() <<  " Hz" << endl;
  }
  
  //--------------------  calculate FEE peds & produce output files ------
  
  printf("name   Nentries chi2  gaus_ampl gaus_mean gaus_sig err_ampl err_mean err_sig \n");

  TIterator* iter = HList->MakeIterator();

  TH1F* h;
  char oName[100];
  FILE *fo;
  oName[0]=0;
  int nPed=0;
  TString fName=outPath+"eemcPed4.dat";
  FILE *fo2=fopen(fName.Data(),"w");

  while((h=(TH1F*)iter->Next())) {
    char *txt=h->GetName();
    int cr=atoi(txt+2);
    int chan=atoi(txt+6);
    int ped4=0;
    if(chan%32==0) {
      if(oName[0]) fclose(fo);
      sprintf(oName,"%scrate%dboard%d.ped4",outPath.Data(),cr, 1+chan/32);
      FILE *fo=fopen(oName,"w");
      if(fo==0) {
        printf("\n\nDid you created dir=%s ???  ,JB\n\n",outPath.Data());
        printf("ABORT macro\n");
        assert(fo);
      }
      printf("  write to '%s'\n",oName);
    }
    
    int ret=-1;
    // Fit range max -low, max+high, default: max-5, max+4
    if(cr==4 && chan==127)  ret=myMk3->fitPed(h,20); // just example
    else   ret=myMk3->fitPed(h);
    
    if (ret) {
      printf("%s empty\n",h->GetName());
      fprintf(fo2," %d %3d 5000 %d\n",cr,chan,ped4);
      fprintf(fo," %d\n",ped4);
      continue;
    }
    TF1* fit= h->GetFunction("pedFun");
    assert(fit);
    nPed++;
    
    // fit->Print(); return; 
    
    float ped=fit->GetParameter(1);
    int ped4=(25-ped)/4;
    if(ped>24)  ped4=(22-ped)/4;
    fprintf(fo2,"%d %d %.1f %d\n",cr,chan,ped,ped4);
    fprintf(fo,"%d\n",ped4);
    
    printf("%s %8.0f %8.3f %9.3f %8.2f %7.2f %6.2f %7.2f %6.2f\n",
           h->GetName(),
           h->GetEntries(),
           fit->GetChisquare(),
           fit->GetParameter(0),
           fit->GetParameter(1),   // pedestal centroid
           fit->GetParameter(2),   // sigma of gaussian
           fit->GetParError(0),
           fit->GetParError(1),
           fit->GetParError(2));
    //     break;
  }
  
  myMk3->saveHisto(outPath+"feePed");
  fclose(fo2);
  fclose(fo);
  printf("Fit found %d pedestals\n",nPed);

  //  h=(TH1F*)HList->FindObject("cr5_ch095"); // this is 'stuck bit'  channel
  h=(TH1F*)HList->FindObject("cr5_ch094"); // a regular channel
  h->Draw(); gPad->SetLogy();

}
OptRes Optimization(string var = "topness", string signal = "T2tt_850_100", string region = "baseline", string channel = "allChannels", string filename = "plots/plotsProducer/1DStack.root"){

	OptRes res;
	
	//TFile* fplots = new TFile("plots/plotsProducer/1DStack.root","READ");
	TFile* fplots = new TFile(filename.c_str(),"READ");
	//string channel = "allChannels";
	//string region = "baseline";
	//string var = "topness";
	//string var = "topness_m5";
	//string signal = "T2tt_850_100";
	
	
	//retrieve canvas
	string cname = channel+"/"+region+"/"+var;
	TCanvas* c = fplots->Get(cname.c_str());
	//c->Draw();
	
	//signal
	string splot_name = "v:"+var+"|p:"+signal+"|r:"+region+"|c:"+channel+"|t:1DEntries";
	TH1F* h_sig = (TH1F*) c->GetPrimitive(splot_name.c_str());
	//sig->Draw();
	
	//////////////////////////////////////////////
	// Search the Stack that contains all bkg
	//////////////////////////////////////////////
	vector<TH1F*> h_bkgs;
	//c->GetListOfPrimitives()->Print();
	TIter next(c->GetListOfPrimitives());
	TObject* h;
	while ((h = (TH1F*) next())){
	//obj->Draw(next.GetOption());
		if(h->InheritsFrom("THStack")){
			THStack* stack = (THStack*) h;
			for(int i=0;i<stack->GetStack()->GetEntries();i++){
				TH1F* hist = (TH1F*) stack->GetStack()->At(i);
				//cout<<hist->IsA()->GetName()<<endl;
				//cout<<hist->GetName()<<" "<<hist->Integral()<<endl;
				//search tt_2l
				//if(string(hist->GetName()).find("W+jets")!=string::npos) continue;
				if(string(hist->GetName()).find("ttbar_2l")!=string::npos){
					//cout<<"mean = "<<hist->GetMean()<<" rms = "<<hist->GetRMS()<<" kurtosis = "<<hist->GetKurtosis()<<" skewness = "<<hist->GetSkewness()<<endl;
				}
				//else continue;
				//conly save the last one because plots are cumulative !!!
				// that's cheat ....
				if(i==stack->GetStack()->GetEntries()-1) h_bkgs.push_back(hist);
			}
			//cout<<((THStack*)h)->GetStack()->GetEntries()<<endl;
			//TH1* h_bkg = ((TH1*)(h->GetStack()->Last()));
		}
	}
	
	
	////////////////////////////////////////////////
	//     Loop over all bins and compute eff/sig
	////////////////////////////////////////////////
	
	res.h_eff_sig = (TH1F*) h_sig->Clone();	
	res.h_eff_bkg = (TH1F*) h_sig->Clone();	
	res.h_Zbi = (TH1F*) h_sig->Clone();	
	TH1F* h_ROC = new TH1F("h_ROC","ROC curve",10,0,1);

	//Compute the integral
	float integ_sig = res.h_eff_sig->Integral(0,res.h_eff_sig->GetNbinsX()+1);
	float integ_bkg = 0;
	for(unsigned ih=0;ih<h_bkgs.size();ih++){
		integ_bkg+=h_bkgs[ih]->Integral(0,h_bkgs[ih]->GetNbinsX()+1);
	}
	///////////////////////

	//-- efficiencoy for signal
	for(int i=1;i<res.h_eff_sig->GetNbinsX()+1;i++){
		float eff = 0;
		if(integ_sig!=0)  eff = res.h_eff_sig->Integral(i,res.h_eff_sig->GetNbinsX()+1)/integ_sig;
		res.h_eff_sig->SetBinContent(i,eff);
		res.h_eff_sig->SetBinError(i,0);
	}
	//-- efficiency for bkg
	for(int i=1;i<res.h_eff_sig->GetNbinsX()+1;i++){
		float eff = 0;
		for(unsigned ih=0;ih<h_bkgs.size();ih++){
			eff += h_bkgs[ih]->Integral(i,h_bkgs[ih]->GetNbinsX()+1);
		}
		if(integ_bkg!=0)  eff /= integ_bkg;
		res.h_eff_bkg->SetBinContent(i,eff);
		res.h_eff_bkg->SetBinError(i,0);
	}
	//-- compute significance
	//vector<pair<float,float> > roc_v;
	float* roc_sig = new float[res.h_eff_sig->GetNbinsX()];
	float* roc_bkg = new float[res.h_eff_sig->GetNbinsX()];
	int imax = 0;
	for(int i=1;i<res.h_eff_sig->GetNbinsX()+1;i++){
		float Ns = res.h_eff_sig->GetBinContent(i)*integ_sig;
		//float Ns = res.h_eff_sig->GetBinContent(i);
		//float Nb = res.h_eff_bkg->GetBinContent(i);
		float Nb = res.h_eff_bkg->GetBinContent(i)*integ_bkg;
		float signif = 0;
		if(Nb!=0) signif = Ns/sqrt(Nb);
		double zbi = Zbi(Ns, Nb);
		//res.h_Zbi->SetBinContent(i,signif);
		res.h_Zbi->SetBinContent(i,zbi);
		res.h_Zbi->SetBinError(i,0);
		

		//ROC curve
		//h_ROC->SetBinContent(h_ROC->FindBin(res.h_eff_sig->GetBinContent(i)),res.h_eff_bkg->GetBinContent(i));
		//h_ROC->SetBinContent(h_ROC->FindBin(res.h_eff_bkg->GetBinContent(i)),res.h_eff_sig->GetBinContent(i));
		//roc_v.push_back(pair<float,float>(res.h_eff_sig->GetBinContent(i),res.h_eff_bkg->GetBinContent(i));
		roc_sig[imax] = res.h_eff_sig->GetBinContent(i);
		roc_bkg[imax] = 1-res.h_eff_bkg->GetBinContent(i);
		imax++;
	}
	res.gROC = new TGraph(imax,roc_sig,roc_bkg);

	res.h_Zbi->GetXaxis()->SetTitle(var.c_str());
	res.h_Zbi->GetYaxis()->SetTitle("Zbi");

	res.h_eff_bkg->SetTitle("Efficiency on background");
	res.h_eff_bkg->GetXaxis()->SetTitle(var.c_str());
	res.h_eff_bkg->GetYaxis()->SetTitle("#epsilon_{bkg}");
	
	res.h_eff_sig->SetTitle("Efficiency on signal");
	res.h_eff_sig->GetXaxis()->SetTitle(var.c_str());
	res.h_eff_sig->GetYaxis()->SetTitle("#epsilon_{sig}");

	res.gROC->SetTitle("ROC");
	res.gROC->GetXaxis()->SetTitle("#epsilon_{signal}");
	res.gROC->GetYaxis()->SetTitle("1-#epsilon_{bkg}");
	res.gROC->SetLineWidth(2);

 	res.cplots = new TCanvas();
	res.cplots->Divide(2,2);
	res.h_eff_sig->GetYaxis()->SetRangeUser(0,1);
	res.cplots->cd(1);
	res.h_eff_sig->Draw();
	res.h_eff_bkg->SetLineColor(kRed);
	res.cplots->cd(2);
	res.h_eff_bkg->Draw("");
	res.cplots->cd(3);
	res.h_Zbi->Draw();
	res.cplots->cd(4);
   	//h_ROC->Draw();	
	res.gROC->Draw("ACP");
	
	int mbin = res.h_Zbi->GetMaximumBin();
	float maxZbi = -9999;
	for(int i=1;i<res.h_Zbi->GetNbinsX();i++){
		if(res.h_Zbi->GetBinContent(i)>maxZbi && res.h_eff_sig->GetBinContent(i)>0.1){
			maxZbi = res.h_Zbi->GetBinContent(i);
			mbin = i;
		}
	}
	cout<<"@max - Zbi = "<<res.h_Zbi->GetMaximum()<<" cut = "<<res.h_Zbi->GetBinLowEdge(mbin)<<" effs = "<<res.h_eff_sig->GetBinContent(mbin)<<" effb = "<<res.h_eff_bkg->GetBinContent(mbin)<<endl;
	cout<<"Ns = "<<res.h_eff_sig->GetBinContent(mbin)*integ_sig<<" Nb = "<<res.h_eff_bkg->GetBinContent(mbin)*integ_bkg<<endl;
	cout<<"ROC-integral: "<<res.gROC->Integral()<<endl;
	//looking for a bin with eff = XXX
	int mbin2 = 0;
	int mbin7 = 0;
	float eff_ref = 0.75;
	float d_eff_closest = 100;
	for(int i=1;i<res.h_eff_sig->GetNbinsX();i++){
		if(res.h_eff_sig->GetBinLowEdge(i) == 7) mbin7 = i;
		float eff = res.h_eff_sig->GetBinContent(i);
		if(fabs(eff-eff_ref)<d_eff_closest){
			d_eff_closest = fabs(eff-eff_ref);
			//cout<<eff<<" "<<d_eff_closest<<endl;
			mbin2 = i;
		}
	}	
	cout<<"ref - Zbi = "<<res.h_Zbi->GetBinContent(mbin2)<<" cut = "<<res.h_Zbi->GetBinLowEdge(mbin2)<<" effs = "<<res.h_eff_sig->GetBinContent(mbin2)<<" effb = "<<res.h_eff_bkg->GetBinContent(mbin2)<<endl;
	cout<<"Ns = "<<res.h_eff_sig->GetBinContent(mbin2)*integ_sig<<" Nb = "<<res.h_eff_bkg->GetBinContent(mbin2)*integ_bkg<<endl;
	
	//cout<<"cut@7 - Zbi = "<<res.h_Zbi->GetBinContent(mbin7)<<" cut = "<<res.h_Zbi->GetBinLowEdge(mbin7)<<" effs = "<<res.h_eff_sig->GetBinContent(mbin7)<<" effb = "<<res.h_eff_bkg->GetBinContent(mbin7)<<endl;
	//cout<<"Ns = "<<res.h_eff_sig->GetBinContent(mbin7)*integ_sig<<" Nb = "<<res.h_eff_bkg->GetBinContent(mbin7)*integ_bkg<<endl;
	
	//cout<<"Ns_tot = "<<integ_sig<<" Nb_tot = "<<integ_bkg<<endl;
	/*
	THStack* stack = c->GetPrimitive("");
	stack->Draw();
	cout<<stack<<endl;
	//TH1* h_bkg = stack->GetHistogram();
	//cout<<h_bkg<<endl;
	G//h_bkg->Draw();
	TH1* h_bkg = ((TH1*)(stack->GetStack()->Last()));
	h_bkg->Draw();
	cout<<h_bkg->GetNbinsX()<<endl;
*/
	
	/*
	//Compute eff
	TH1* h_eff_bkg = (TH1*) h_bkg->Clone("");
	cout<<h_eff_bkg->GetNbinsX()<<endl;
	for(int i=1;i<h_eff_bkg->GetNbinsX();i++){
		float num = h_bkg->Integral(i,h_bkg->GetNbinsX()+1);
		float den = h_bkg->Integral(0,h_bkg->GetNbinsX()+1);
		float eff = 0;
		if(den!=0) eff== num/den;
		h_eff_bkg->SetBinContent(i,eff);
	}
	h_eff_bkg->Draw();
	cout<<"max = "<<stack->GetHistogram()->GetMaximum()<<endl;
	cout<<c->GetPrimitive("::THStack")<<endl;
	cout<<h_bkg<<endl;
	*/

	return res;
	
}
Example #23
0
void fitTF1(TCanvas *canvas, TH1F h, double XMIN_, double XMAX_, double dX_, double params[], Color_t LC_=kBlack) { //double& FWHM_, double& x0_, double& x1_, double& x2_, double& y0_, double& y1_, double& INT_, double& YIELD_) {
//TCanvas* fitTF1(TH1F h, double HSCALE_, double XMIN_, double XMAX_) {
//TF1* fitTF1(TH1F h, double HSCALE_, double XMIN_, double XMAX_) {
	gROOT->ForceStyle();
	RooMsgService::instance().setSilentMode(kTRUE);
	for(int i=0;i<2;i++) RooMsgService::instance().setStreamStatus(i,kFALSE);

	//TCanvas *canvas = new TCanvas(TString::Format("canvas_%s",h.GetName()),TString::Format("canvas_%s",h.GetName()),1800,1200);

	RooDataHist *RooHistFit = 0;
	RooAddPdf *model = 0;

	RooWorkspace w = RooWorkspace("w","workspace");

	RooRealVar x("mbbReg","mbbReg",XMIN_,XMAX_);
	RooRealVar kJES("CMS_scale_j","CMS_scale_j",1,0.9,1.1);
	RooRealVar kJER("CMS_res_j","CMS_res_j",1,0.8,1.2);
	kJES.setConstant(kTRUE);
	kJER.setConstant(kTRUE);

	TString hname = h.GetName();

	RooHistFit = new RooDataHist("fit_"+hname,"fit_"+hname,x,&h);


	RooRealVar YieldVBF = RooRealVar("yield_"+hname,"yield_"+hname,h.Integral());
	RooRealVar m("mean_"+hname,"mean_"+hname,125,100,150);
	RooRealVar s("sigma_"+hname,"sigma_"+hname,12,3,30);
	RooFormulaVar mShift("mShift_"+hname,"@0*@1",RooArgList(m,kJES));
	RooFormulaVar sShift("sShift_"+hname,"@0*@1",RooArgList(m,kJER));
	RooRealVar a("alpha_"+hname,"alpha_"+hname,1,-10,10);
	RooRealVar n("exp_"+hname,"exp_"+hname,1,0,100);
	RooRealVar b0("b0_"+hname,"b0_"+hname,0.5,0.,1.);
	RooRealVar b1("b1_"+hname,"b1_"+hname,0.5,0.,1.);
	RooRealVar b2("b2_"+hname,"b2_"+hname,0.5,0.,1.);
	RooRealVar b3("b3_"+hname,"b3_"+hname,0.5,0.,1.);
	
	RooBernstein bkg("signal_bkg_"+hname,"signal_bkg_"+hname,x,RooArgSet(b0,b1,b2));
	RooRealVar fsig("fsig_"+hname,"fsig_"+hname,0.7,0.0,1.0);
	RooCBShape sig("signal_gauss_"+hname,"signal_gauss_"+hname,x,mShift,sShift,a,n);

	model = new RooAddPdf("signal_model_"+hname,"signal_model_"+hname,RooArgList(sig,bkg),fsig);

	//RooFitResult *res = model->fitTo(*RooHistFit,RooFit::Save(),RooFit::SumW2Error(kFALSE),"q");
	model->fitTo(*RooHistFit,RooFit::Save(),RooFit::SumW2Error(kFALSE),"q");

	//res->Print();
	//model->Print();
	
	canvas->cd();
	canvas->SetTopMargin(0.1);
	RooPlot *frame = x.frame();
// no scale
	RooHistFit->plotOn(frame);
	model->plotOn(frame,RooFit::LineColor(LC_),RooFit::LineWidth(2));//,RooFit::LineStyle(kDotted));
	model->plotOn(frame,RooFit::Components(bkg),RooFit::LineColor(LC_),RooFit::LineWidth(2),RooFit::LineStyle(kDashed));
// with scale
//	RooHistFit->plotOn(frame,RooFit::Normalization(HSCALE_,RooAbsReal::NumEvent));
//	model->plotOn(frame,RooFit::Normalization(HSCALE_,RooAbsReal::NumEvent),RooFit::LineWidth(1));
//	model->plotOn(frame,RooFit::Components(bkg),RooFit::LineColor(kBlue),RooFit::LineWidth(1),RooFit::LineStyle(kDashed),RooFit::Normalization(HSCALE_,RooAbsReal::NumEvent));
	 
	frame->GetXaxis()->SetLimits(50,200);
	frame->GetXaxis()->SetNdivisions(505);
	frame->GetXaxis()->SetTitle("M_{b#bar{b}} (GeV)");
	frame->GetYaxis()->SetTitle("Events");
	frame->Draw();
	h.SetFillColor(kGray);
	h.Draw("hist,same");
	frame->Draw("same");
	gPad->RedrawAxis();

	TF1 *tmp = model->asTF(x,fsig,x);
	//tmp->Print();

	double y0_ = tmp->GetMaximum();
	double x0_ = tmp->GetMaximumX();
	double x1_ = tmp->GetX(y0_/2.,XMIN_,x0_);
	double x2_ = tmp->GetX(y0_/2.,x0_,XMAX_);
	double FWHM_ = x2_-x1_;
	double INT_ = tmp->Integral(XMIN_,XMAX_);
	double YIELD_= YieldVBF.getVal();
	double y1_ = dX_*0.5*y0_*(YieldVBF.getVal()/tmp->Integral(XMIN_,XMAX_));

	params[0] = x0_;
	params[1] = x1_;
	params[2] = x2_;
	params[3] = y0_;
	params[4] = y1_;
	params[5] = FWHM_;
	params[6] = INT_;
	params[7] = YIELD_;

	//cout<<"Int = "<<tmp->Integral(XMIN_,XMAX_)<<", Yield = "<<YieldVBF.getVal()<<", y0 = "<<y0_<<", y1 = "<<y1_ <<", x0 = "<< x0_ << ", x1 = "<<x1_<<", x2 = "<<x2_<<", FWHM = "<<FWHM_<<endl;

	TLine ln = TLine(x1_,y1_,x2_,y1_);
	ln.SetLineColor(kMagenta+3);
	ln.SetLineStyle(7);
	ln.SetLineWidth(2);
	ln.Draw();
	
	canvas->Update();
	canvas->SaveAs("testC.png");
	
//	tmp->Delete();
//	frame->Delete();
//	res->Delete();
//	TF1 *f1 = model->asTF(x,fsig,x);
//	return f1;
	
	////tmp->Delete();
	////ln->Delete();
	////model->Delete();
	////RooHistFit->Delete();
	////w->Delete();
	////YieldVBF->Delete();
	////frame->Delete();
	////res->Delete();
	//delete tmp;
	//delete ln;
	//delete model;
	//delete RooHistFit;
	//delete w;
	//delete YieldVBF;
	//delete frame;
	//delete res;

//	return canvas;
}
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
int main (int argc, char ** argv) {

  // check number of inpt parameters
  if(argc < 2){
    cerr<<"Forgot to parse the cfg file --> exit "<<endl;
    return -1;
  }

  // Set Root style from global enviroment path                                                                                                                               
  string ROOTStyle;
  if(getenv ("ROOTStyle")!=NULL){
    ROOTStyle = getenv ("ROOTStyle");
    gROOT->ProcessLine((".x "+ROOTStyle+"/setTDRStyle.C").c_str());
  }

  gStyle->SetOptStat(0);
  gStyle->SetPadTopMargin(0.09);
  gStyle->SetPadLeftMargin(0.13);
  gStyle->SetErrorX(0.5);


  // parse config file parameter
  if (gConfigParser) return 1 ;
  gConfigParser = new ConfigParser();

  TString config ; 
  config.Form("%s",argv[1]);

  if(!(gConfigParser->init(config))){
      cout << ">>> parseConfigFile::Could not open configuration file " << config << endl;
      return -1;
  }

  // import base directory where samples are located and txt file with the directory name + other info
  string InputBaseDirectory  = gConfigParser -> readStringOption("Input::InputBaseDirectory");

  // import from cfg file the cross section value for this sample
  float CrossSection   = gConfigParser -> readFloatOption("Input::CrossSection");

  // total number of events
  int maxEventNumber   = gConfigParser -> readFloatOption("Input::EventsNumber");

  // treeName
  string treeName      = gConfigParser -> readStringOption("Input::TreeName");

  // take the cut list
  string InputCutList  = gConfigParser -> readStringOption("Input::InputCutList");

  // Read the cut file
  vector <cutContainer> CutList;
  if(ReadInputCutFile(InputCutList,CutList) <= 0){
    cerr<<" Empty Cut List File or not Exisisting --> Exit "<<endl; return -1;}

  // take the variable list to be plotted
  string InputVariableList  = gConfigParser -> readStringOption("Input::InputVariableList");
  vector<variableContainer> variableList;

  if(ReadInputVariableFile(InputVariableList,variableList) <= 0 ){
    cerr<<" Empty Variable List File or not Exisisting --> Exit "<<endl; return -1;}

  // take lumi and other parameters
  float lumi  =  gConfigParser -> readFloatOption("Option::Lumi"); // fb^(-1)
  lumi *= 1000. ;   // transform into pb^(-1)

  finalStateString    = gConfigParser -> readStringOption("Option::finalStateString");

  matchingCone        = gConfigParser -> readFloatOption("Option::matchingCone"); 
  minLeptonCleaningPt = gConfigParser -> readFloatOption("Option::minLeptonCleaningPt"); 
  minLeptonCutPt      = gConfigParser -> readFloatOption("Option::minLeptonCutPt");
  minJetCutPt         = gConfigParser -> readFloatOption("Option::minJetCutPt");
  usePuppiAsDefault   = gConfigParser -> readBoolOption("Option::usePuppiAsDefault");
  leptonIsoCut_mu     = gConfigParser -> readFloatOption("Option::leptonIsoCutMu");
  leptonIsoCut_el     = gConfigParser -> readFloatOption("Option::leptonIsoCutEl");
  leptonIsoCutLoose   = gConfigParser -> readFloatOption("Option::leptonIsoCutLoose");

  // output directory
  string outputPlotDirectory = gConfigParser -> readStringOption("Output::outputPlotDirectory");
  system(("mkdir -p output/"+outputPlotDirectory).c_str());
  system(("rm -r output/"+outputPlotDirectory+"/*").c_str());
  system(("mkdir -p output/"+outputPlotDirectory+"/xs").c_str());
  system(("mkdir -p output/"+outputPlotDirectory+"/norm").c_str());


  ///// Start the analysis  
  map<string,TH1F*> histoCutEff ;

  TChain* chain = new TChain (treeName.c_str()) ;  
  chain->Add ((InputBaseDirectory+"/*.root").c_str()) ;
  int totEvent = chain->GetEntries();

  readTree* reader  = new readTree((TTree*)(chain));

  cout<<"Lumi (fb-1) "<<lumi/1000<<" entries before "<<totEvent<<" cross section "<<CrossSection<<" Nevents before selections "<<lumi*CrossSection<<" weight "<<lumi*CrossSection/float(totEvent)<<endl;

  float weight = 1.0*lumi*CrossSection/float(totEvent) ;

  // make the plot container 
  vector<histoContainer> plotVector;

  for(size_t iCut = 0; iCut < CutList.size(); iCut++){
    histoCutEff["WW_EWK_pos_"+to_string(iCut)+"_"+CutList.at(iCut).cutLayerName] = new TH1F(("WW_EWK_pos_"+to_string(iCut)+"_"+CutList.at(iCut).cutLayerName).c_str(),"",15,0,15);
    for(size_t iVar = 0; iVar < variableList.size(); iVar++){
      plotVector.push_back(histoContainer(CutList.at(iCut).cutLayerName,variableList.at(iVar)));
    }
  }

  int passingLHEFilter = 0 ;
  
  int maximumEvents = chain->GetEntries () ;
  if (maxEventNumber > 0 && maxEventNumber < maximumEvents) 
    maximumEvents = maxEventNumber ;
  
  // Loop on the events
  for(int iEvent = 0; iEvent < maximumEvents ; iEvent++){

    reader->fChain->GetEntry(iEvent) ;

    if (iEvent % 100000 == 0) cout << "reading event " << iEvent << "\n" ;

    // filter LHE level leptons
    if(TString(finalStateString).Contains("UU")){
      if(fabs(reader->leptonLHEpid1) != 13 or fabs(reader->leptonLHEpid2) != 13)
        continue;
    }
    else if(TString(finalStateString).Contains("EE")){
      if(fabs(reader->leptonLHEpid1) != 11 or fabs(reader->leptonLHEpid2) != 11) continue;
    }
    else if(TString(finalStateString).Contains("EU")){
      if(fabs(reader->leptonLHEpid1) != 11 or fabs(reader->leptonLHEpid2) !=13) continue ;
    }
    else if(TString(finalStateString).Contains("UE")){
      if(fabs(reader->leptonLHEpid1) != 13 or fabs(reader->leptonLHEpid2) !=11) continue ;
    }
    else{
      cerr<<"problem with lhe level filter definition --> skip event"<<endl;
      continue;
    }

    passingLHEFilter++;

    // if an event pass the cut, fill the associated map                                                              
    leptonContainer lepton1,lepton2,parton1,parton2,neutrino1,neutrino2,vboson1,vboson2;

    lepton1.lepton4V_.SetPtEtaPhiM(reader->leptonLHEpt1,reader->leptonLHEeta1,reader->leptonLHEphi1,reader->leptonLHEm1);
    lepton1.charge_  = reader->leptonLHEch1;
    lepton1.flavour_ = reader->leptonLHEpid1;  

    lepton2.lepton4V_.SetPtEtaPhiM(reader->leptonLHEpt2,reader->leptonLHEeta2,reader->leptonLHEphi2,reader->leptonLHEm2);
    lepton2.charge_  = reader->leptonLHEch2;
    lepton2.flavour_ = reader->leptonLHEpid2;  

    parton1.lepton4V_.SetPtEtaPhiM(reader->jetLHEPartonpt1,reader->jetLHEPartoneta1,reader->jetLHEPartonphi1,0.);
    parton2.lepton4V_.SetPtEtaPhiM(reader->jetLHEPartonpt2,reader->jetLHEPartoneta2,reader->jetLHEPartonphi2,0.);

    neutrino1.lepton4V_.SetPtEtaPhiM(reader->neutrinoLHEpt1,reader->neutrinoLHEeta1,reader->neutrinoLHEphi1,0.);
    neutrino1.charge_  = 0.;
    neutrino1.flavour_ = reader->neutrinoLHEpid1;  

    neutrino2.lepton4V_.SetPtEtaPhiM(reader->neutrinoLHEpt2,reader->neutrinoLHEeta2,reader->neutrinoLHEphi2,0.);
    neutrino2.charge_  = 0.;
    neutrino2.flavour_ = reader->neutrinoLHEpid2;  

    vboson1.lepton4V_.SetPtEtaPhiM(reader->vbosonLHEpt1,reader->vbosonLHEeta1,reader->vbosonLHEphi1,reader->vbosonLHEm1);
    vboson1.charge_  = reader->vbosonLHEch1;
    vboson1.flavour_ = reader->vbosonLHEpid1;  
    
    vboson2.lepton4V_.SetPtEtaPhiM(reader->vbosonLHEpt2,reader->vbosonLHEeta2,reader->vbosonLHEphi2,reader->vbosonLHEm2);
    vboson2.charge_  = reader->vbosonLHEch2;
    vboson2.flavour_ = reader->vbosonLHEpid2;  

    float minDR_1 = 999;
    float minDR_2 = 999;

    vector<leptonContainer> lepton, neutrino;
    lepton.push_back(lepton1);
    lepton.push_back(lepton2);
    neutrino.push_back(neutrino1);
    neutrino.push_back(neutrino2);

    leptonContainer leptFromV1, leptFromV2, neuFromV1, neuFromV2;

    for(size_t iLep= 0; iLep < lepton.size(); iLep++){
      for(size_t iNeu = 0; iNeu < neutrino.size(); iNeu++){
	if((lepton.at(iLep).lepton4V_+neutrino.at(iNeu).lepton4V_).DeltaR(vboson1.lepton4V_) < minDR_1 ){
	  minDR_1    = (lepton.at(iLep).lepton4V_+neutrino.at(iNeu).lepton4V_).DeltaR(vboson1.lepton4V_);
	  leptFromV1 = lepton.at(iLep);
	  neuFromV1  = neutrino.at(iNeu);
	}

	if((lepton.at(iLep).lepton4V_+neutrino.at(iNeu).lepton4V_).DeltaR(vboson2.lepton4V_) < minDR_2){
	  minDR_2    = (lepton.at(iLep).lepton4V_+neutrino.at(iNeu).lepton4V_).DeltaR(vboson2.lepton4V_);
	  leptFromV2 = lepton.at(iLep);
	  neuFromV2  = neutrino.at(iNeu);
	}	

      }
    }

    if(leptFromV1.lepton4V_ == leptFromV2.lepton4V_ or neuFromV1.lepton4V_ == neuFromV2.lepton4V_){
      cerr<<" bad matching with gen W "<<endl;
      continue;
    }
		       

    double costheta1 = 0;
    double costheta2 = 0;
    double Phi  = 0;
    double costhetastar  = 0;
    double Phi1  = 0;

    double costheta1_vbf = 0;
    double costheta2_vbf = 0;
    double Phi_vbf = 0;
    double costhetastar_vbf = 0;
    double Phi1_vbf = 0;


    TLorentzVector VV = vboson1.lepton4V_ + vboson2.lepton4V_;

    if(leptFromV1.charge_ > 0  and leptFromV2.charge_ > 0){

      computeAnglesResonance(VV,vboson1.lepton4V_,neuFromV1.lepton4V_,leptFromV1.lepton4V_,vboson2.lepton4V_,neuFromV2.lepton4V_,leptFromV2.lepton4V_,
			     costheta1,costheta2,Phi,costhetastar,Phi1);

      computeAnglesVBF(VV,vboson1.lepton4V_,neuFromV1.lepton4V_,leptFromV1.lepton4V_,vboson2.lepton4V_,neuFromV2.lepton4V_,leptFromV2.lepton4V_,parton1.lepton4V_,
		       parton2.lepton4V_,costheta1_vbf,costheta2_vbf,Phi_vbf,costhetastar_vbf,Phi1_vbf);
    }
    else if(leptFromV1.charge_ < 0  and leptFromV2.charge_ < 0){

      computeAnglesResonance(VV,vboson1.lepton4V_,leptFromV1.lepton4V_,neuFromV1.lepton4V_,vboson2.lepton4V_,leptFromV2.lepton4V_,neuFromV2.lepton4V_,
			     costheta1,costheta2,Phi,costhetastar,Phi1);

      computeAnglesVBF(VV,vboson1.lepton4V_,leptFromV1.lepton4V_,neuFromV1.lepton4V_,vboson2.lepton4V_,leptFromV2.lepton4V_,neuFromV2.lepton4V_,parton1.lepton4V_,
		       parton2.lepton4V_,costheta1_vbf,costheta2_vbf,Phi_vbf,costhetastar_vbf,Phi1_vbf);

    }

    else if(leptFromV1.charge_ < 0  and leptFromV2.charge_ > 0){
      computeAnglesResonance(VV,vboson1.lepton4V_,leptFromV1.lepton4V_,neuFromV1.lepton4V_,vboson2.lepton4V_,neuFromV2.lepton4V_,leptFromV2.lepton4V_,
			     costheta1,costheta2,Phi,costhetastar,Phi1);

      computeAnglesVBF(VV,vboson1.lepton4V_,leptFromV1.lepton4V_,neuFromV1.lepton4V_,vboson2.lepton4V_,neuFromV2.lepton4V_,leptFromV2.lepton4V_,parton1.lepton4V_,
		       parton2.lepton4V_,costheta1_vbf,costheta2_vbf,Phi_vbf,costhetastar_vbf,Phi1_vbf);
    }
    else if(leptFromV1.charge_ > 0  and leptFromV2.charge_ < 0){

      computeAnglesResonance(VV,vboson1.lepton4V_,neuFromV1.lepton4V_,leptFromV1.lepton4V_,vboson2.lepton4V_,leptFromV2.lepton4V_,neuFromV2.lepton4V_,
			     costheta1,costheta2,Phi,costhetastar,Phi1);

      computeAnglesVBF(VV,vboson1.lepton4V_,neuFromV1.lepton4V_,leptFromV1.lepton4V_,vboson2.lepton4V_,leptFromV2.lepton4V_,neuFromV2.lepton4V_,parton1.lepton4V_,
		       parton2.lepton4V_,costheta1_vbf,costheta2_vbf,Phi_vbf,costhetastar_vbf,Phi1_vbf);

    }
    else{ cerr<<" wrong charge composition "<<endl;
      continue;
    }
    
    float mTR = 0;
    float mR  = 0;

    TLorentzVector L_met ,L_dijet, L_dilepton, L_LLmet; 

    L_met      = neutrino1.lepton4V_ + neutrino2.lepton4V_;
    L_dijet    = parton1.lepton4V_   + parton2.lepton4V_;
    L_dilepton = lepton1.lepton4V_   + lepton2.lepton4V_;
    L_LLmet    = L_dilepton + L_met ;

    computeRazor(lepton1.lepton4V_,lepton2.lepton4V_,L_met,mTR,mR);

    if(lepton1.lepton4V_.Pt() < minLeptonCutPt or lepton2.lepton4V_.Pt() < minLeptonCutPt) continue;

    // Loop  on the cut list --> one cut for each polarization
    for(size_t iCut = 0; iCut < CutList.size(); iCut++){

      // cut the events
      string name = "WW_EWK";
      if(!passCutContainerSelection(reader,
                                    CutList.at(iCut),
                                    name,
				    int(iCut),
                                    usePuppiAsDefault,
                                    minLeptonCutPt,
                                    minLeptonCleaningPt,
                                    leptonIsoCut_mu,
                                    leptonIsoCut_el,
                                    leptonIsoCutLoose,
                                    matchingCone,
                                    minJetCutPt,
                                    histoCutEff,
				    finalStateString)) continue;

      
      float asimL = (lepton1.lepton4V_.Pt()-lepton2.lepton4V_.Pt())/(lepton1.lepton4V_.Pt()+lepton2.lepton4V_.Pt()) ;


      float asimJ    = (parton1.lepton4V_.Pt()-parton2.lepton4V_.Pt())/(parton1.lepton4V_.Pt()+parton2.lepton4V_.Pt()) ;
      float Rvar     = (lepton1.lepton4V_.Pt()*lepton2.lepton4V_.Pt())/(parton1.lepton4V_.Pt()*parton2.lepton4V_.Pt()) ;

      // loop on variables
      for(size_t iVar = 0; iVar < variableList.size(); iVar++){
        histoContainer tmpPlot;
        tmpPlot.cutName = CutList.at(iCut).cutLayerName;
        tmpPlot.varName = variableList.at(iVar).variableName;
        vector<histoContainer>::iterator itVec ;
        itVec = find(plotVector.begin(),plotVector.end(),tmpPlot);
        if(itVec == plotVector.end()){
          cerr<<"Problem -->plot not found for "<<CutList.at(iCut).cutLayerName<<"  "<<variableList.at(iVar).variableName<<endl;
          continue ;
        }
	
	// vector boson info
	if(variableList.at(iVar).variableName == "ptV1"){
          itVec->histogram->Fill(vboson1.lepton4V_.Pt(),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "ptV2"){
          itVec->histogram->Fill(vboson2.lepton4V_.Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "etaV1"){
          itVec->histogram->Fill(vboson1.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "etaV2"){
          itVec->histogram->Fill(vboson2.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptVV"){
          itVec->histogram->Fill(L_dijet.Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "mVV"){
          itVec->histogram->Fill(L_dijet.M(),weight) ;
        }

	// decay information
	if(variableList.at(iVar).variableName == "costheta1"){
          itVec->histogram->Fill(fabs(costheta1),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "costheta2"){
          itVec->histogram->Fill(fabs(costheta2),weight) ;
        }
	if(variableList.at(iVar).variableName == "costheta1_vbf"){
          itVec->histogram->Fill(fabs(costheta1_vbf),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "costheta2_vbf"){
          itVec->histogram->Fill(fabs(costheta2_vbf),weight) ;
        }

	if(variableList.at(iVar).variableName == "Phi"){
          itVec->histogram->Fill(fabs(Phi),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "Phi1"){
          itVec->histogram->Fill(fabs(Phi1),weight) ;
        }
	if(variableList.at(iVar).variableName == "Phi_vbf"){
          itVec->histogram->Fill(fabs(Phi_vbf),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "Phi1_vbf"){
          itVec->histogram->Fill(fabs(Phi1_vbf),weight) ;
        }

	else if(variableList.at(iVar).variableName == "costhetastar"){
          itVec->histogram->Fill(fabs(costhetastar),weight) ;
        }
	else if(variableList.at(iVar).variableName == "costhetastar_vbf"){
          itVec->histogram->Fill(fabs(costhetastar_vbf),weight) ;
        }

	else if(variableList.at(iVar).variableName == "mTR"){
          itVec->histogram->Fill(mTR,weight) ;
	}

	else if(variableList.at(iVar).variableName == "mR"){
          itVec->histogram->Fill(mR,weight) ;
	}

	// jet info

	if(variableList.at(iVar).variableName == "ptj1"){
          itVec->histogram->Fill(parton1.lepton4V_.Pt(),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "ptj2"){
          itVec->histogram->Fill(parton2.lepton4V_.Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "etaj1"){
          itVec->histogram->Fill(parton1.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "etaj2"){
          itVec->histogram->Fill(parton2.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "detajj"){
          itVec->histogram->Fill(fabs(parton1.lepton4V_.Eta()-parton2.lepton4V_.Eta()),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptjj"){
          itVec->histogram->Fill(L_dijet.Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "mjj"){
          itVec->histogram->Fill(L_dijet.M(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "Asim_j"){
          itVec->histogram->Fill(asimJ,weight) ;
        }
	else if(variableList.at(iVar).variableName == "DeltaPhi_JJ"){
          itVec->histogram->Fill(fabs(parton1.lepton4V_.DeltaPhi(parton2.lepton4V_)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptl1"){
          itVec->histogram->Fill(lepton1.lepton4V_.Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptl2"){
          itVec->histogram->Fill(lepton2.lepton4V_.Pt(),weight) ;
        }
 
	else if(variableList.at(iVar).variableName == "etal1"){
          itVec->histogram->Fill(lepton1.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "etal2"){
          itVec->histogram->Fill(lepton2.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "mll"){
          itVec->histogram->Fill(L_dilepton.M(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptll"){
          itVec->histogram->Fill(L_dilepton.Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_LL"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(lepton2.lepton4V_)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "Asim_l"){
          itVec->histogram->Fill(asimL,weight) ;
        }

	else if(variableList.at(iVar).variableName == "met"){
          itVec->histogram->Fill(L_met.Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "R"){
          itVec->histogram->Fill(Rvar,weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_LMet"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptLMet"){
          itVec->histogram->Fill((lepton1.lepton4V_ + L_met).Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "DeltaPhi_TLMet"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptTLMet"){
          itVec->histogram->Fill((lepton2.lepton4V_ + L_met).Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "DeltaPhi_LLMet"){
          itVec->histogram->Fill(fabs(L_dilepton.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptLLMet"){
          itVec->histogram->Fill((L_dilepton + L_met).Pt(),weight) ;
        }
	///
	else if(variableList.at(iVar).variableName == "DeltaPhi_LJL"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(parton1.lepton4V_)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptLJL"){
          itVec->histogram->Fill((lepton1.lepton4V_+parton1.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_TJL"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(parton2.lepton4V_)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptTJL"){
          itVec->histogram->Fill((lepton1.lepton4V_+parton2.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_JJL"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(L_dijet)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptJJL"){
          itVec->histogram->Fill((lepton1.lepton4V_+L_dijet).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_LJTL"){
          itVec->histogram->Fill(fabs(lepton2.lepton4V_.DeltaPhi(parton1.lepton4V_)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_TJTL"){
          itVec->histogram->Fill(fabs(lepton2.lepton4V_.DeltaPhi(parton2.lepton4V_)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_JJTL"){
          itVec->histogram->Fill(fabs(lepton2.lepton4V_.DeltaPhi(L_dijet)),weight) ;
        }


	else if(variableList.at(iVar).variableName == "ptLJTL"){
          itVec->histogram->Fill((lepton2.lepton4V_+parton1.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptTJTL"){
          itVec->histogram->Fill((lepton2.lepton4V_+parton2.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptJJTL"){
          itVec->histogram->Fill((lepton2.lepton4V_+L_dijet).Pt(),weight) ;
        }

 
	else if(variableList.at(iVar).variableName == "DeltaPhi_LJLL"){
          itVec->histogram->Fill(fabs(L_dilepton.DeltaPhi(parton1.lepton4V_)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_TJLL"){
          itVec->histogram->Fill(fabs(L_dilepton.DeltaPhi(parton2.lepton4V_)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_JJLL"){
          itVec->histogram->Fill(fabs(L_dilepton.DeltaPhi(L_dijet)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptLJLL"){
          itVec->histogram->Fill((L_dilepton+parton1.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptTJLL"){
          itVec->histogram->Fill((L_dilepton+parton2.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptJJLL"){
          itVec->histogram->Fill((L_dilepton+L_dijet).Pt(),weight) ;
        }

	///
	else if(variableList.at(iVar).variableName == "DeltaPhi_JJMet"){
          itVec->histogram->Fill(fabs(L_dijet.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptJJMet"){
          itVec->histogram->Fill((L_dijet+L_met).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_LJMet"){
          itVec->histogram->Fill(fabs(parton1.lepton4V_.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptLJMet"){
          itVec->histogram->Fill((parton1.lepton4V_+L_met).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_TJMet"){
          itVec->histogram->Fill(fabs(parton2.lepton4V_.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptTJMet"){
          itVec->histogram->Fill((parton2.lepton4V_+L_met).Pt(),weight) ;
        }
 
	else if(variableList.at(iVar).variableName == "mlljj"){
          itVec->histogram->Fill((L_dilepton+L_dijet).M(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "mlljjmet"){
          itVec->histogram->Fill((L_dilepton+L_dijet+L_met).M(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "mTH"){
          itVec->histogram->Fill(sqrt(2*L_dilepton.Pt()*L_met.Pt()*(1-TMath::Cos(L_dilepton.DeltaPhi(L_met)))),weight) ;
        } 
      } // loop on variables
      
    } // Loop  on the cut list

  } // Loop on the events

  
  TFile* outputEfficiency = new TFile(("output/"+outputPlotDirectory+"/outputEfficiency.root").c_str(),"RECREATE");

  for(map<string,TH1F*>::const_iterator itMap = histoCutEff.begin(); itMap !=  histoCutEff.end(); itMap++){
    itMap->second->Scale(1./itMap->second->GetBinContent(1));
    itMap->second->Write();
  }

  outputEfficiency->Close();    

  
  // make the canvas and basic banners                                                                                                                                         
  TCanvas *cCanvas = new TCanvas("cCanvas","",1,52,550,550);
  cCanvas->SetTicks();
  cCanvas->SetFillColor(0);
  cCanvas->SetBorderMode(0);
  cCanvas->SetBorderSize(2);
  cCanvas->SetTickx(1);
  cCanvas->SetTicky(1);
  cCanvas->SetRightMargin(0.05);
  cCanvas->SetBottomMargin(0.12);
  cCanvas->SetFrameBorderMode(0);

  cCanvas->cd();

  TPad* upperPad = new TPad("upperPad", "upperPad", .005, .180, .995, .980);
  TPad* lowerPad = new TPad("lowerPad", "lowerPad", .005, .005, .995, .18);
  lowerPad->SetGridx();
  lowerPad->SetGridy();
  upperPad->SetLeftMargin(0.12);
  upperPad->SetRightMargin(0.1);
  lowerPad->SetLeftMargin(0.12);
  lowerPad->SetRightMargin(0.1);
  lowerPad->SetTopMargin(0.002);

  lowerPad->Draw();
  upperPad->Draw();

  TCanvas *cCanvasNorm = new TCanvas("cCanvasNorm","",1,52,550,550);
  cCanvasNorm->SetTicks();
  cCanvasNorm->SetFillColor(0);
  cCanvasNorm->SetBorderMode(0);
  cCanvasNorm->SetBorderSize(2);
  cCanvasNorm->SetTickx(1);
  cCanvasNorm->SetTicky(1);
  cCanvasNorm->SetRightMargin(0.05);
  cCanvasNorm->SetBottomMargin(0.12);
  cCanvasNorm->SetFrameBorderMode(0);

  TLatex * tex = new TLatex(0.88,0.92," 14 TeV");
  tex->SetNDC();
  tex->SetTextAlign(31);
  tex->SetTextFont(42);
  tex->SetTextSize(0.045);
  tex->SetLineWidth(2);
  TLatex * tex2 = new TLatex(0.14,0.92,"Delphes");
  tex2->SetNDC();
  tex2->SetTextFont(61);
  tex2->SetTextSize(0.045);
  tex2->SetLineWidth(2);
  TLatex * tex3 = new TLatex(0.295,0.92,"Simulation Preliminary");
  tex3->SetNDC();
  tex3->SetTextFont(52);
  tex3->SetTextSize(0.04);
  tex3->SetLineWidth(2);

  TLegend* legend = new TLegend(0.55,0.75,0.85,0.89);
  legend->SetBorderSize(0);
  legend->SetFillColor(0);
  legend->SetFillStyle(0);
  legend->SetTextSize(0.04);
  legend->SetTextFont(42);
  legend->SetNColumns (3) ;
 
  // make the plot on the same canvas for each variable (legend entry is the cut layer name)  
  vector<TH1F*>  numerator ;
  vector<TH1F*>  denominator ;
  for(size_t iVar = 0; iVar < variableList.size(); iVar++){ // loop on var
   
    numerator.clear();
    denominator.clear();

    for(size_t iCut = 0; iCut < CutList.size(); iCut++){ // loop on cuts
        histoContainer tmpPlot;
        tmpPlot.cutName = CutList.at(iCut).cutLayerName;
        tmpPlot.varName = variableList.at(iVar).variableName;
        vector<histoContainer>::iterator itVec ;
        itVec = find(plotVector.begin(),plotVector.end(),tmpPlot);
        if(itVec == plotVector.end()){
          cerr<<"Problem -->plot not found for "<<CutList.at(iCut).cutLayerName<<"  "<<variableList.at(iVar).variableName<<endl;
        }

       
        itVec->histogram->GetXaxis()->SetTitleSize(0.04);
        itVec->histogram->GetXaxis()->SetTitleOffset(1.16);
        itVec->histogram->GetXaxis()->SetLabelSize(0.04);

        itVec->histogram->GetYaxis()->SetRangeUser(0.001,itVec->histogram->GetMaximum()*1.25);
        itVec->histogram->GetYaxis()->SetTitleSize(0.05);
        itVec->histogram->GetYaxis()->SetTitleOffset(1.20);
        itVec->histogram->GetYaxis()->SetLabelSize(0.04);

        itVec->histogram->SetLineColor(iCut+1);

        if(iCut %2 == 0)
          itVec->histogram->SetLineStyle(1);
        else
          itVec->histogram->SetLineStyle(2);

        itVec->histogram->SetLineWidth(2);
        itVec->histogram->GetYaxis()->SetTitle("#sigma x lumi");

        upperPad->cd();

        if(iCut == 0) 
          itVec->histogram->Draw("hist");
        else
          itVec->histogram->Draw("hist same");

        legend->AddEntry(itVec->histogram,CutList.at(iCut).cutLayerName.c_str(),"l");

        if(itVec->findCutByLabel("LL")) numerator.push_back(itVec->histogram);
        denominator.push_back(itVec->histogram);

	cCanvasNorm->cd();

	TH1F* htempNorm = (TH1F*) itVec->histogram->Clone((string(itVec->histogram->GetName())+"_norm").c_str());
	htempNorm->Scale(1./itVec->histogram->Integral());

	htempNorm->GetYaxis()->SetRangeUser(0.,htempNorm->GetMaximum()*1.5);

        if(iCut == 0)
          htempNorm->Draw("hist");
        else
          htempNorm->Draw("hist same");
    }
    
    // make ratio plot
    lowerPad->cd();
    
    TH1F* numTotal = 0;
    TH1F* denTotal = 0;
    TH1F* ratio    = 0;
    TH1F* ratioW   = 0;

    for(size_t itNum = 0; itNum < numerator.size(); itNum ++){
      if(itNum == 0 and ratio == 0) 
        numTotal = (TH1F*) numerator.at(itNum)->Clone(("Num_"+string(numerator.at(itNum)->GetName())).c_str());
      else if(ratio !=0) 
        numTotal->Add(numerator.at(itNum));
    }

    for(size_t itDen = 0; itDen < denominator.size(); itDen ++){
      if(itDen == 0 and denTotal == 0 ) {
        denTotal = (TH1F*) denominator.at(itDen)->Clone(("Den_"+string(denominator.at(itDen)->GetName())).c_str());
      }
      else if(denTotal !=0){  
        denTotal->Add(denominator.at(itDen));
      }
    }
    
    ratio = new TH1F(("Ratio_"+string(denominator.at(0)->GetName())).c_str(),"",numTotal->GetNbinsX(),numTotal->GetBinLowEdge(1),numTotal->GetBinLowEdge(numTotal->GetNbinsX()+1));
    ratio->GetYaxis()->SetTitle("S/(#sqrt{S+B})");
    ratio->SetMarkerSize(1.1);

    ratioW = new TH1F(("ratioW_"+string(denominator.at(0)->GetName())).c_str(),"",numTotal->GetNbinsX(),numTotal->GetBinLowEdge(1),numTotal->GetBinLowEdge(numTotal->GetNbinsX()+1));
    ratioW->GetYaxis()->SetTitle("weighted S/(#sqrt{S+B})");
    ratioW->SetMarkerSize(1.1);

    TString name = "norm_" ;
    name += denTotal->GetName () ;
    TH1F * norm_denTotal = (TH1F *) denTotal->Clone (name) ;
    norm_denTotal->Scale (1. / norm_denTotal->GetMaximum ()) ; 
    // weight the S/sqrt (B) by the shape of the total, 
    // so that only bins with a lot of stats become visibly significant
    for(int iBin = 0; iBin < ratio->GetNbinsX()+1; iBin++){
      if(denTotal->GetBinContent(iBin) !=0){ 
        ratioW->SetBinContent(iBin,
			      norm_denTotal->GetBinContent (iBin) * numTotal->GetBinContent(iBin) / 
			      sqrt(denTotal->GetBinContent(iBin)));
        ratio->SetBinContent(iBin,
			     numTotal->GetBinContent(iBin) / sqrt(denTotal->GetBinContent(iBin)));
      }
      else 
	ratio->SetBinContent(iBin,0.);
    }
 
    ratio->GetXaxis()->SetTitle("");
    ratio->SetLineColor(kBlue);
    ratio->SetLineStyle(2);
    ratio->SetLineWidth(2);
    ratio->GetXaxis()->SetLabelOffset(999);
    ratio->GetXaxis()->SetLabelSize(0);
    ratio->GetYaxis()->SetLabelSize(0.15);
    ratio->GetYaxis()->SetTitleSize(0.15);
    ratio->GetYaxis()->SetTitleOffset(0.30);
    ratio->GetYaxis()->SetNdivisions(504);

    ratioW->GetXaxis()->SetTitle("");
    ratioW->SetLineColor(kBlack);
    ratioW->SetLineWidth(2);
    ratioW->GetXaxis()->SetLabelOffset(999);
    ratioW->GetXaxis()->SetLabelSize(0);
    ratioW->GetYaxis()->SetLabelSize(0.15);
    ratioW->GetYaxis()->SetTitleSize(0.15);
    ratioW->GetYaxis()->SetTitleOffset(0.30);
    ratioW->GetYaxis()->SetNdivisions(504);

    ratio->GetYaxis()->SetRange(min(ratio->GetMinimum(),ratioW->GetMinimum())*0.9,max(ratio->GetMaximum(),ratioW->GetMaximum())*1.1);    


    TH1F * frame = lowerPad->DrawFrame (ratio->GetXaxis ()->GetXmin (), 0., 
                                        ratio->GetXaxis ()->GetXmax (), 2.) ;
    frame->GetXaxis()->SetTitle (ratio->GetXaxis ()->GetTitle ()) ;
    frame->GetYaxis()->SetTitle (ratio->GetYaxis ()->GetTitle ()) ;
    frame->GetXaxis()->SetLabelOffset(999);
    frame->GetXaxis()->SetLabelSize(0);
    frame->GetYaxis()->SetLabelSize(0.15);
    frame->GetYaxis()->SetTitleSize(0.15);
    frame->GetYaxis()->SetTitleOffset(0.30);
    frame->GetYaxis()->SetNdivisions(504);

    ratio->Draw("P");    
    ratioW->Draw("Lsame");    
    
    upperPad->cd();
    
    tex->Draw("same");
    tex2->Draw("same");
    tex3->Draw("same");
    legend->Draw("same");

    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/xs/"+variableList.at(iVar).variableName+".pdf").c_str(),"pdf");
    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/xs/"+variableList.at(iVar).variableName+".png").c_str(),"png");
    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/xs/"+variableList.at(iVar).variableName+".root").c_str(),"root");

    cCanvasNorm->cd();

    tex->Draw("same");
    tex2->Draw("same");
    tex3->Draw("same");
    legend->Draw("same");

    cCanvasNorm->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+".pdf").c_str(),"pdf");
    cCanvasNorm->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+".png").c_str(),"png");
    cCanvasNorm->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+".root").c_str(),"root");

    
    legend->Clear();
    
  } // loop on var

  cout<<"LHE filter efficiency : "<<passingLHEFilter<<" totEvent "<<totEvent<<" efficiency "<<float(passingLHEFilter)/float(totEvent)*100<<" % "<<endl;
  
  //Normalize histograms
  for(size_t ihisto = 0; ihisto < plotVector.size(); ihisto++){
    if(plotVector.at(ihisto).varName == "DeltaPhi_LL")
      cout<<"Events Histo "<<plotVector.at(ihisto).histogram->GetName()<<" unweighted "<<plotVector.at(ihisto).histogram->GetEntries()<<" weighted "<<plotVector.at(ihisto).histogram->Integral(0,plotVector.at(ihisto).histogram->GetNbinsX()+1)<<endl;
  }	          

  return 0 ;
}  
void rescale2SM4(bool armed, const char* filename, double ecms=7., double mass=-1)
{
  unsigned int debug = 1;
  std::vector<std::string> histnames; histnames.clear();
  if( debug>0 ){
    std::cout << "file  = " << filename << std::setw(10);
    std::cout << "mass  = " << mass     << std::setw(10);
    std::cout << "armed = " << armed    << std::endl;
  }
  TFile* file = new TFile(filename, "update");
  TIter nextDirectory(file->GetListOfKeys());
  std::vector<std::string> buffer; TKey* idir;
  while((idir = (TKey*)nextDirectory())){
    buffer.clear();
    if( idir->IsFolder() ){
      file->cd(); // make sure to start in directory head 
      if( debug>1 ){ std::cout << "Found directory: " << idir->GetName() << std::endl; }
      if( file->GetDirectory(idir->GetName()) ){
	file->cd(idir->GetName()); // change to sub-directory
	buffer = signalList(idir->GetName(), "", debug);
      }
      // append to the vector of histograms to be rescaled
      for(std::vector<std::string>::const_iterator elem=buffer.begin(); elem!=buffer.end(); ++elem){
	histnames.push_back(*elem);
      }
      if(debug>1){
	std::cout << "added " << buffer.size() << " elements to histnames [" << histnames.size() << "] for directory " << idir->GetName() << std::endl;
      }
    }
  }
  // pick up histograms which are not kept in an extra folder
  file->cd(); buffer.clear();
  buffer = signalList("", "", debug);
  // append to the vector of histograms to be rescaled
  for(std::vector<std::string>::const_iterator elem=buffer.begin(); elem!=buffer.end(); ++elem){
    histnames.push_back(*elem);
  }
  if(debug>1){
    std::cout << "added " << buffer.size() << " elements to histnames [" << histnames.size() << "] for file head" << std::endl;
  }

  HiggsCSandWidth smx; HiggsCSandWidthSM4 sm4;
  for(std::vector<std::string>::const_iterator hist=histnames.begin(); hist!=histnames.end(); ++hist){
    int type = 0;
    // determine mass from hostogram name
    std::string strippedName = (hist->find("/")!=std::string::npos ? hist->substr(hist->find("/")+1) : *hist);
    std::string massName;
    if(strippedName.find("ggH")!=std::string::npos) {
      massName = strippedName.substr(3, 3); type = 1;
    }
    if(strippedName.find("qqH")!=std::string::npos) {
      massName = strippedName.substr(3, 3); type = 2;
    }
    if(strippedName.find("VH" )!=std::string::npos) {
      massName = strippedName.substr(2, 3); type = 3;
    }
    if( type==0 ) { 
      std::cout << "not supported process" << std::endl; 
      continue; 
    }
    else {
      file->cd();
      float mdx = atof(massName.c_str());
      TH1F* h = (TH1F*)file->Get(hist->c_str());
      float smxXS = type==1 ? smx.HiggsCS(type, mdx, ecms, true) : 0.; float smxBR = smx.HiggsBR(2, mdx, true); 
      float sm4XS = type==1 ? sm4.HiggsCS(type, mdx, ecms, true) : 0.; float sm4BR = sm4.HiggsBR(2, mdx, true);
      if( debug>1 ){
	std::cout << "  --  hist  = " << std::setw(10) << h->GetName() << std::endl
		  << "  --  type  = " << std::setw(10) << type << std::endl
		  << "  --  mass  = " << std::setw(10) << mdx << std::endl
		  << "  --  SM    = " << std::setw(10) << smxXS*smxBR << " (BR = " << smxBR << ")"  << std::endl
		  << "  --  SM4   = " << std::setw(10) << sm4XS*sm4BR << " (BR = " << sm4BR << ")"  << std::endl
		  << "  --  scale = " << std::setw(10) << (type==1 ? sm4XS*sm4BR/(smxXS*smxBR) : 0) << std::endl
		  << std::endl;
      }
      if( type==1 ){ h->Scale(sm4XS*sm4BR/(smxXS*smxBR)); }
      //scaling old style
      //if( type==2 ){ h->Scale(sm4BR/smxBR); }
      //if( type==3 ){ h->Scale(sm4BR/smxBR); }
      // scaling new style
      if( type==2 ){ h->Scale(0.); }
      if( type==3 ){ h->Scale(0.); }
      if(armed){
	if(hist->find("/")!=std::string::npos){
	  file->cd(hist->substr(0, hist->find("/")).c_str());
	}
	else{
	  file->cd();
	}
	h->Write(strippedName.c_str(), TObject::kOverwrite); 
      }
    }
  }
  file->Close();
  return;
}
Example #26
0
void plot_ljpsi(const char* fdata, const char* fmc) {
   TFile *tfd = TFile::Open(fdata);
   TFile *tfm = TFile::Open(fmc);

   TCanvas *c1 = new TCanvas();
   c1->cd();
   TPad *p1 = new TPad("p1","",0,0,1,0.33);
   p1->SetBottomMargin(2.*gStyle->GetPadBottomMargin());
   p1->SetTopMargin(0);
   p1->SetFrameBorderMode(0);
   p1->SetBorderMode(0);
   p1->SetBorderSize(0);
   p1->SetGridy();
   if (datamc) p1->Draw();
   TPad *p2 = new TPad("p2","",0,0.33,1,1);
   // p2->SetTopMargin(gStyle->GetPadTopMargin()/(1.-0.2));
   p2->SetBottomMargin(0);
   p2->SetFrameBorderMode(0);
   p2->SetBorderMode(0);
   p2->SetBorderSize(0);
   // p2->SetLogy();
   if (datamc) p2->Draw();
   p1->cd();
   if (!datamc) c1->cd();

   TF1 *dg = new TF1("f1","[0]*([1]*TMath::Gaus(x,[2],[3])+(1-[1])*TMath::Gaus(x,[4],[3]*[5]))",-0.2,0.04);
   dg->SetParLimits(0,0,1e15);
   dg->SetParLimits(1,0.5,1);
   dg->SetParLimits(2,-0.05,0.05);
   dg->SetParLimits(3,0,0.1);
   dg->SetParLimits(4,-0.05,0.05);
   dg->SetParLimits(5,0,100);
   dg->SetParameters(1000,0.8,1e-3,0.03,1e-4,2.);

   TIter next(tfd->GetListOfKeys()); TObject *obj;
   while ((obj = next())) {
      obj = ((TKey*) obj)->ReadObj();
      if (TString(obj->ClassName()) == "TH1F") {
         TH1F *hdata = (TH1F*) tfd->Get(obj->GetName());
         TH1F *hmc = (TH1F*) tfm->Get(obj->GetName());
         // hdata->Rebin(6);
         // hmc->Rebin(6);

         if (!integrate) {
            double int_data = hdata->Integral(hdata->FindBin(-0.015), hdata->FindBin(0.015));
            double int_mc = hmc->Integral(hmc->FindBin(-0.015), hmc->FindBin(0.015));
            hmc->Scale(int_data/int_mc);
         } else {
            double int_mc_all = hmc->Integral(0, hmc->GetNbinsX()+1);
            double int_data_all = hdata->Integral(0, hdata->GetNbinsX()+1);
            hmc->Scale(1./int_mc_all);
            hdata->Scale(1./int_data_all);
            double int_data = hdata->Integral(0, hdata->FindBin(0.));
            double int_mc = hmc->Integral(0, hmc->FindBin(0.));
            hdata->Scale(int_mc/int_data); 
            integrateHist(hdata);
            integrateHist(hmc);
         }
         hdata->GetXaxis()->SetTitle("#font[12]{l}_{J/#psi} [mm]");
         hdata->GetYaxis()->SetTitle("Entries");
         if (integrate) hdata->GetYaxis()->SetTitle("c.d.f.");

         // read the bin from the name
         TString thname(hdata->GetName());
         bool isfwd = (thname.Index("fwd") != kNPOS);
         int pos1 = thname.Index("pt")+2;
         int pos2 = thname.Index("-")-pos1;
         TString tsubstr(thname(pos1,pos2));
         float ptmin = atof(tsubstr.Data());
         pos1 = thname.Index("-")+1;
         pos2 = thname.Length();
         tsubstr = TString(thname(pos1,pos2));
         float ptmax = atof(tsubstr.Data());

         if (datamc) p2->cd();
         hdata->Draw();
         hmc->SetLineColor(kRed);
         hmc->SetMarkerColor(kRed);
         hmc->Draw("same");
         gPad->Update();

         // display the position of the ctau cut
         double a=1,b=1;
         if (!isfwd){a=ctaucut_a_mid_pp; b=ctaucut_b_mid_pp;} 
         else {a=ctaucut_a_fwd_pp; b=ctaucut_b_fwd_pp;}
         double cutmin = a + b / ptmin;
         double cutmax = a + b / ptmax;
         double xmin, xmax, ymin, ymax;
         TBox *tb = new TBox(cutmin,gPad->GetUymin(),cutmax,gPad->GetUymax());
         tb->SetFillColor(kBlack);
         tb->SetFillStyle(3003);
         tb->Draw();

         if (integrate) {
            TLine *tl = new TLine(hdata->GetXaxis()->GetXmin(),0.9,hdata->GetXaxis()->GetXmax(),0.9);
            tl->SetLineStyle(3);
            tl->SetLineColor(kBlack);
            tl->SetLineWidth(5);
            tl->Draw();
         }

         if (datamc) {
            p1->cd();
            TH1F *hratio = (TH1F*) hdata->Clone("hratio");
            hratio->Divide(hmc);
            hratio->GetYaxis()->SetTitle("data/MC");
            hratio->GetYaxis()->SetRangeUser(0.5,1.5);
            hratio->GetXaxis()->SetLabelSize(2.*hratio->GetXaxis()->GetLabelSize());
            hratio->GetXaxis()->SetTitleSize(2.*hratio->GetXaxis()->GetTitleSize());
            hratio->GetYaxis()->SetLabelSize(2.*hratio->GetYaxis()->GetLabelSize());
            hratio->GetYaxis()->SetTitleSize(2.*hratio->GetYaxis()->GetTitleSize());
            hratio->Draw();

            p2->cd();
         }

         // dg->SetParameters(1000,0.8,1e-3,0.03,1e-4,2.);
         // dg->SetParameter(0,int_data);
         // dg->SetParLimits(0,0,int_data*100.);
         // hdata->Fit(dg, "LERQ");
         // double sigma_data = dg->GetParameter(3);
         // double dsigma_data = dg->GetParError(3);
         // dg->SetRange(-5.*sigma_data,1.5*sigma_data);
         // hdata->Fit(dg, "LERQ");
         // sigma_data = dg->GetParameter(3);
         // dsigma_data = dg->GetParError(3);
         // dg->SetRange(-5.*sigma_data,1.5*sigma_data);
         // hdata->Fit(dg, "LERQ");
         // sigma_data = dg->GetParameter(3);
         // dsigma_data = dg->GetParError(3);
         // hmc->Fit(dg, "LERQ");
         // double sigma_mc = dg->GetParameter(3);
         // double dsigma_mc = dg->GetParError(3);

         double lx1=0.61, lx2=0.9, ly1=0.6, ly2=0.88;
         if (integrate) {ly1-=0.4; ly2-=0.4;}
         TLegend *tleg = new TLegend(lx1,ly1,lx2,ly2);
         tleg->SetBorderSize(0);
         TString header("#splitline{");
         header += isfwd ? "1.6<|y|<2.4" : "|y|<1.6";
         header += Form("}{%.1f<pt<%.1f GeV/c}",ptmin,ptmax);
         tleg->SetHeader(header);
         // tleg->AddEntry(hdata,Form("pp data (#sigma = %.3f +/- %.3f)",sigma_data,dsigma_data),"lp");
         // tleg->AddEntry(hmc,Form("pp prompt J/#psi mc (#sigma = %.3f +/- %.3f)",sigma_mc,dsigma_mc),"lp");
         tleg->AddEntry(hdata,"data","lp");
         tleg->AddEntry(hmc,"prompt J/#psi mc","lp");
         tleg->Draw();
         c1->SaveAs(Form("%s.pdf",hdata->GetName()));
         c1->SaveAs(Form("%s.png",hdata->GetName()));
      }
   }
}
Example #27
0
bool plot_tree(char* quantity,char* plotdim="(100,0.,3.)",bool log=true)
{
  char tmp1[250];
  char tmp2[300];
  char tmp3[100];
  sprintf(tmp2,"pythia.root");

  TFile* file;
  file=new TFile(tmp2);
  if(!file->IsOpen()) {
    cout << "No file "<<tmp2<<endl;
    return false;
  }
  file->cd();

  gROOT->SetStyle("Plain");
  const int maxjets=1+4;
  TH1F* hists[maxjets];
  sprintf(tmp3,"%s",quantity);
  TCanvas* c1=new TCanvas(tmp3,tmp3);
  c1->SetLogy();
  TLegend* leg=new TLegend(0.99,0.7,0.7,0.95);
  sprintf(tmp3,"l%s",quantity);
  leg->SetName(tmp3);
  int color[5]={2,4,3,5,6};
  int style[5]={2,3,4,3,4};

  //  bool ptw=false;
  TLeaf *leaf_Xsec = xsecs->FindLeaf("Xsecfact");
  Float_t Xsecfact;
  leaf_Xsec->SetAddress(&Xsecfact);
  xsecs->GetEntry(0);
  if (events->GetEntries()>0) {
  for(int i=0;i<maxjets;i++){
    events->SetLineWidth(2);
    events->SetLineColor(i+2);
    events->SetLineStyle(i+2);
    
    if(log) 
      sprintf(tmp1,"log10(%s)>>%s%i%s",quantity,quantity,i,plotdim);
    else 
      sprintf(tmp1,"%s>>%s%i%s",quantity,quantity,i,plotdim);
    sprintf(tmp2,"%e*(Npart==%i)",Xsecfact,i);

    cout << "events->Draw("<<tmp1<<","<<tmp2<<");"<<endl;
    events->Draw(tmp1,tmp2);

    sprintf(tmp3,"%s%i",quantity,i);
    hists[i]=(TH1F*)gROOT->FindObject(tmp3);
    if(!hists[i]){
      cout << "Failed to get object "<<tmp3<<endl;
      return false;
    }
  }
  }

  TH1F *hsum = (TH1F*)hists[0]->Clone();
  sprintf(tmp3,"%ssum",quantity);
  hsum->SetName(tmp3);
  for(int i=1;i<maxjets;i++)
    hsum->Add(hists[i]);
  cout << "Integral of "<<quantity<<": "<<hsum->Integral()<<endl;
  hsum->SetLineWidth(2);
  hsum->SetLineColor(1);
  hsum->SetLineStyle(1);
  //  hsum->SetMinimum(hsum->GetMaximum()*1e-3);
  hsum->SetStats(kFALSE);
  sprintf(tmp3,"%s",quantity);
  hsum->SetTitle(tmp3);
  sprintf(tmp3,"log10(%s)",quantity);
  hsum->GetXaxis()->SetTitle(tmp3);
  hsum->GetYaxis()->SetTitle("Cross section (pb/bin)");
  hsum->Draw();
  leg->AddEntry(hsum->GetName(),"Sum of contributions");

  for(int i=0;i<maxjets;i++){
    hists[i]->Draw("same");
    sprintf(tmp3,"%i-jet sample",i);
    leg->AddEntry(hists[i]->GetName(),tmp3);
  }

  leg->Draw();

  sprintf(tmp2,"%s.eps",quantity);
  cout << "Saving plot as " << tmp2 << endl;
  c1->SaveAs(tmp2);
  return true;
}
Example #28
0
void AlignTopAndBottomTOFs(string ArrayPart="NV",Float_t Start=-5,Float_t End=25){
  
  for (int bar=1;bar<13;bar++){
    stringstream nameTop;
    stringstream nameBottom;

    nameTop<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"_TopCutTOFPr";
    TH1F * CurrentTop = (TH1F*)gDirectory->Get(nameTop.str().c_str());


    nameBottom<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"_BottomCutTOFPr";
    TH1F * CurrentBottom = (TH1F*)gDirectory->Get(nameBottom.str().c_str());
  
    // TCanvas *c=new TCanvas("c");
    // c->cd(1);
    // CurrentTop->Draw();
    // CurrentBottom->Draw("same");

    int binsTop = CurrentTop->GetNbinsX();

    int binsBottom= CurrentBottom->GetNbinsX();
  
    if ( binsTop !=binsBottom){
      cout<<"Nubmer of bins for the top channel not the same as for the bottom channel"<<endl;
      cout<<"This was for "<<CurrentTop->GetName()<<" and "<<CurrentBottom->GetName()<<endl;
      return;
    }
  
    int bins=binsTop;
  
    double topLow = CurrentTop->GetBinLowEdge(1);//ROOT histograms start at bin 1. bin 0 is underflow
    double topHigh= CurrentBottom->GetBinLowEdge(binsTop) +CurrentBottom->GetBinWidth(binsTop);//ROOT histograms end at bin N. N+1 is overflow bin.

    double NanoSecsPerBin = ((topHigh-topLow)*4)/binsTop;
  
    //    cout<<topLow<<" "<<topHigh<<endl;
    //    cout<<"NanoSecsPerBin "<<NanoSecsPerBin<<endl;
  
 
    int ForthOfBins = TMath::Floor(0.25* bins);
    int EighthOfBins = TMath::Floor( (1.0/8)* bins);

    int NumberOfShifts = 2*EighthOfBins; // 1/8 of the number of bins *2 for left/right shifts
  
    int TopZeroBin = CurrentTop->GetMaximumBin();
  
    int StartBin = CurrentTop->FindBin(Start);
    int EndBin = CurrentTop->FindBin(End);

    //Find shift That moves Bottom -> Top
    vector <double> TheChi2s;
    vector <int> TheShifts;
    for (int i=0;i<NumberOfShifts;i++){
      double binShift = (i - NumberOfShifts/2);

      double chi2=0;
      // cout<<"Looking in bin range "<<TopZeroBin-EighthOfBins<<" "<<TopZeroBin+EighthOfBins<<endl;
      // cout<<"That is from "<<CurrentTop->GetBinCenter(TopZeroBin-EighthOfBins)<<" "<<CurrentTop->GetBinCenter(TopZeroBin+EighthOfBins)<<endl;

      for (int bin=StartBin ;bin<EndBin;bin++){
	double b = CurrentBottom->GetBinContent(bin + binShift);
	double t = CurrentTop->GetBinContent(bin);
	if (b !=0 && t!=0){
	  double temp =((b-t)*(b-t))/( TMath::Sqrt(t) );
	  chi2+=temp;
	}
      }
    
      TheChi2s.push_back(chi2);
      TheShifts.push_back(binShift);

    }
  
    ///Find miminum by linear search 
    double min = 9999999999.0;
    int MinSpot=-1;
    for (int i=0;i<NumberOfShifts;i++){
      if ( TheChi2s[i] < min){
	min=TheChi2s[i];
	MinSpot=i;
      }
    }

    cout<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"B  "<<"1  0  "<<fixed<<setw(6)<<setprecision(4)<<TheShifts[MinSpot]/4.0*NanoSecsPerBin<<endl;
    cout<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"T  "<<"1  0  0"<<endl;

  }


  cout<<"There were "<<NanoSecsPerBin<<" nano secs per bin"<<endl;
  // TGraph * graph = new TGraph();
  
  // cout<<"Size of Chi2s "<<TheChi2s.size()<<endl;
  // cout<<"Num "<<NumberOfShifts<<endl;

  // for (int i=0;i<NumberOfShifts;i++){
  //   graph->SetPoint(i,TheShifts[i],TheChi2s[i]);
  // }

  // TCanvas *c2 = new TCanvas("c2");
  // c2->cd(1);
  // graph->Draw("A*");


}
Example #29
0
void plottingmacro_IVF()
{


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

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

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

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

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

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

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

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

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

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


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

  std::string process;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    }

}
Example #30
0
void DrawMLPoutputMovie( TFile* file, const TString& methodType, const TString& methodTitle )
{
   gROOT->SetBatch( 1 );

   // define Canvas layout here!
   const Int_t width = 600;   // size of canvas

   // this defines how many canvases we need
   TCanvas* c = 0;

   Float_t nrms = 4;
   Float_t xmin = -1.2;
   Float_t xmax = 1.2;
   Float_t ymin = 0;
   Float_t ymax = 0;
   Float_t maxMult = 6.0;
   Int_t   countCanvas = 0;
   Bool_t  first = kTRUE;
            
   TString     dirname  = methodType + "/" + methodTitle + "/" + "EpochMonitoring";
   TDirectory *epochDir = (TDirectory*)file->Get( dirname );
   if (!epochDir) {
      cout << "Big troubles: could not find directory \"" << dirname << "\"" << endl;
      exit(1);
   }

   // now read all evolution histograms
   TIter keyItTit(epochDir->GetListOfKeys());
   TKey *titkeyTit;
   while ((titkeyTit = (TKey*)keyItTit())) {
      
      if (!gROOT->GetClass(titkeyTit->GetClassName())->InheritsFrom("TH1F")) continue;
      TString name = titkeyTit->GetName();
      
      if (!name.BeginsWith("convergencetest___")) continue;
      if (!name.Contains("_train_"))              continue; // only for training so far
      if (name.EndsWith( "_B"))                   continue;
      
      // must be signal histogram
      if (!name.EndsWith( "_S")) {
         cout << "Big troubles with histogram: " << name << " -> should end with _S" << endl;
         exit(1);
      }
      
      // create canvas
      countCanvas++;
      TString ctitle = Form("TMVA response %s",methodTitle.Data());
      c = new TCanvas( Form("canvas%d", countCanvas), ctitle, 0, 0, width, (Int_t)width*0.78 ); 
      
      TH1F* sig = (TH1F*)titkeyTit->ReadObj();
      sig->SetTitle( Form("TMVA response for classifier: %s", methodTitle.Data()) );
      
      TString dataType = (name.Contains("_train_") ? "(training sample)" : "(test sample)");
      
      // find background
      TString nbn = sig->GetName(); nbn[nbn.Length()-1] = 'B';            
      TH1F* bgd = dynamic_cast<TH1F*>(epochDir->Get( nbn ));
      if (bgd == 0) {
         cout << "Big troubles with histogram: " << bgd << " -> cannot find!" << endl;
         exit(1);
      }
      
      cout << "sig = " << sig->GetName() << endl;
      cout << "bgd = " << bgd->GetName() << endl;
      
      // set the histogram style
      TMVAGlob::SetSignalAndBackgroundStyle( sig, bgd );
      
      // normalise both signal and background
      TMVAGlob::NormalizeHists( sig, bgd );
      
      // set only first time, then same for all plots
      if (first) {
         if (xmin == 0 && xmax == 0) {
            xmin = TMath::Max( TMath::Min(sig->GetMean() - nrms*sig->GetRMS(), 
                                          bgd->GetMean() - nrms*bgd->GetRMS() ),
                               sig->GetXaxis()->GetXmin() );
            xmax = TMath::Min( TMath::Max(sig->GetMean() + nrms*sig->GetRMS(), 
                                          bgd->GetMean() + nrms*bgd->GetRMS() ),
                               sig->GetXaxis()->GetXmax() );
         }
         ymin = 0;
         ymax = TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*maxMult;
         first = kFALSE;
      }
      
      // build a frame
      Int_t nb = 100;
      TString hFrameName(TString("frame") + methodTitle);
      TObject *o = gROOT->FindObject(hFrameName);
      if(o) delete o;
      TH2F* frame = new TH2F( hFrameName, sig->GetTitle(), 
                              nb, xmin, xmax, nb, ymin, ymax );
      frame->GetXaxis()->SetTitle( methodTitle + " response" );
      frame->GetYaxis()->SetTitle("(1/N) dN^{ }/^{ }dx");
      TMVAGlob::SetFrameStyle( frame );
      
      // find epoch number (4th token)
      TObjArray* tokens = name.Tokenize("_");
      TString es = ((TObjString*)tokens->At(4))->GetString();
      if (!es.IsFloat()) {
         cout << "Big troubles in epoch parsing: \"" << es << "\" is not float" << endl;
         exit(1);
      }
      Int_t epoch = es.Atoi();
      
      // eventually: draw the frame
      frame->Draw();  
      
      c->GetPad(0)->SetLeftMargin( 0.105 );
      frame->GetYaxis()->SetTitleOffset( 1.2 );
      
      // Draw legend               
      TLegend *legend= new TLegend( c->GetLeftMargin(), 1 - c->GetTopMargin() - 0.12, 
                                    c->GetLeftMargin() + 0.5, 1 - c->GetTopMargin() );
      legend->SetFillStyle( 1 );
      legend->AddEntry(sig,TString("Signal ")     + dataType, "F");
      legend->AddEntry(bgd,TString("Background ") + dataType, "F");
      legend->SetBorderSize(1);
      legend->SetMargin( 0.15 );
      legend->Draw("same");
      
      TText* t = new TText();            
      t->SetTextSize( 0.04 );
      t->SetTextColor( 1 );
      t->SetTextAlign( 31 );
      t->DrawTextNDC( 1 - c->GetRightMargin(), 1 - c->GetTopMargin() + 0.015, Form( "Epoch: %i", epoch) );
      
      // overlay signal and background histograms
      sig->Draw("samehist");
      bgd->Draw("samehist");
      
      // save to file
      TString dirname  = "movieplots";
      TString foutname = dirname + "/" + name;
      foutname.Resize( foutname.Length()-2 );
      foutname.ReplaceAll("convergencetest___","");
      foutname += ".gif";
      
      cout << "storing file: " << foutname << endl;
      
      c->Update();
      c->Print(foutname);            
   }
}