Example #1
0
void FinishBatch(TString sInput="", TString sOutput="ARHist"){

  // Stuff to do at the end of an analysis run
  // Here all spectra are saved to disk
  printf("Events: %d      Events Accepted: %d\n",
	 gAN->GetNEvent(), gAN->GetNEvAnalysed() );
  printf("End-of-Run macro executing\n");

  TString sDir = gAR->GetTreeDir();
  TString sFile;
  if (gAR->IsOnline()) sFile = gAR->GetFileName();
  else sFile = gAR->GetTreeFile()->GetName();
  while(sFile.Contains("/")) sFile.Remove(0,1+sFile.Index("/"));
  sFile.ReplaceAll(".dat",".root");
  if(sInput.Length() && sFile.BeginsWith(sInput)) sFile.Remove(0,sInput.Length());
  else sFile.Prepend("_");
  sFile.Prepend(sOutput);
  sFile.Prepend(sDir);
  
  // Save histograms to file and close it
  TFile f(sFile, "recreate");
  if( !f ){
    printf("Open file %s for histogram save FAILED!!\n",sFile.Data());
    return;
  }
  gROOT->GetList()->Write();
  f.Close();
  printf("All histograms saved to %s\n",sFile.Data());

  if (!(gAR->IsOnline())) gSystem->Exit(0);

}
Example #2
0
void Finish(TString sDir = "")
{

  // Finishing Macro for running with Worker
  printf("Events: %d      Events Accepted: %d\n", 
	gAN->GetNEvent(), gAN->GetNEvAnalysed() );

  printf("\nEnd-of-Run macro executing\n");

  // If user has not specified output directory, pull from AR
  if(sDir.Length() == 0) sDir = gAR->GetTreeDir();
  if(sDir.Length() == 0) sDir = "~/";
  
  // Append "/" to Directory if unspecified
  if(!(sDir.EndsWith("/"))) sDir.Append("/");

  // Create output filename from input file name
  TString sFile;
  if (gAR->IsOnline()) sFile = gAR->GetFileName();
  else sFile = gAR->GetTreeFile()->GetName();
  while(sFile.Contains("/")) sFile.Remove(0,1+sFile.Index("/"));
  sFile.ReplaceAll(".dat",".root");
  sFile.Prepend("Hist_");
  sFile.Prepend(sDir);

  // Save histograms to file and close it
  TFile f(sFile, "recreate");
  f.SetCompressionLevel(4);
  gROOT->GetList()->Write();
  f.Close();
  cout << "All histograms saved to " << sFile << endl;

  gSystem->Exit(0);

}
Example #3
0
void RecoQA(const char* inFile) {
  gROOT->LoadMacro("bfcread_hist_prefixes_add_to_ps.C");

  TString baseName = inFile;
  if (baseName.EndsWith(".daq"))
    baseName.ReplaceAll(".daq",".hist.root");
  else if (baseName.EndsWith(".event.root"))
    baseName.ReplaceAll(".event.root",".hist.root");
  else if (baseName.EndsWith(".MuDst.root"))
    baseName.ReplaceAll(".MuDst.root",".hist.root");

  TString histFile = baseName;

  baseName.Remove(0,baseName.Last('/')+1);

  TString outputName = baseName;
  outputName.ReplaceAll(".root",".CC");

  TString histList = "StRoot/St_QA_Maker/QAhlist_Reco.h";
  if (! gSystem->Which(".",histList.Data()))
    histList.Prepend(gSystem->ExpandPathName("$STAR/"));
  
  bfcread_hist_prefixes_add_to_ps(histFile.Data(),"EventQA",
    "bfcTree",outputName.Data(),baseName.Data(),histList.Data());
}
Example #4
0
Bool_t RunPromptOffline(Int_t run, Int_t gdcNumber, TString trg="" )
{
    //
    //  origin: Mikolaj Krzewicki, Nikhef, Mikolaj.Krzewicki@cern.ch
    //

    //check arguments
    if (gdcNumber>999) return kFALSE;

    gROOT->LoadMacro("/local/home/daq/ilcsoft/macros/grp.C");
    Int_t grpRetCode = grp(run);
    if (grpRetCode<=0) return kFALSE;

    TString gdcNumberStr = "";
    gdcNumberStr += gdcNumber;
    if (gdcNumberStr.Length()==2) gdcNumberStr.Prepend("0");
    TString datasource = "mem://@aldaqpc";
    datasource.Append(gdcNumberStr);
    datasource.Append(":");  //no trg, do nothing

    //handle the low-level trigger selection
    if (trg!="")
    {
      datasource.Append("?Trigger=");
      datasource.Append(trg);
    }

    cout<<endl<<"RunPromptOffline datasource: "<<datasource<<endl<<endl;

    gROOT->LoadMacro("./rec.C");
    rec(datasource);
}
Example #5
0
Bool_t SETUP_LoadLibraries(const TString &libs) {

  // Loads a list of colon-separated libraries. Returns kTRUE on success, kFALSE
  // if at least one library couldn't load properly. Does not check for double
  // loads (but ROOT does).

  TString l;
  Ssiz_t from;

  while ( libs.Tokenize(l, from, ":") ) {
    if (l.IsNull()) continue;
    if (!l.BeginsWith("lib")) l.Prepend("lib");
    if (l.EndsWith(".so")) l.Remove(l.Length()-3, l.Length());

    ::Info(gMessTag.Data(), ">> Loading library %s...", l.Data());

    if (gSystem->Load(l.Data()) < 0) {
       ::Error(gMessTag.Data(), "Error loading %s, aborting", l.Data());
       return kFALSE;  // failure
    }
  }

  return kTRUE;  // success

  return 0;
}
Example #6
0
void RsnSetData(AliAnalysisAlien *plugin,TString dsConf,Int_t numRuns = 1000,Int_t numRunsSkip=0,Int_t maxRunsPerMaster = 1000) {

   Bool_t dsFound = kTRUE;
   Int_t nRunsPerMaster = 0;

   Bool_t valid = kTRUE;
   TString legoTrainPath = AliAnalysisManager::GetGlobalStr("rsnLegoTrainPath",valid);

   if (gSystem->AccessPathName(dsConf.Data())) dsConf.Prepend(Form("%s/",legoTrainPath.Data()));
   dsConf = gSystem->ExpandPathName(dsConf.Data());

   if (dsConf.Contains(".txt")) {
      ifstream in;
      in.open(dsConf.Data());
      if (!in.is_open()) Fatal("RsnSetData",Form("File %s was not found !!!",dsConf.Data()));
      Printf("DS config file : %s",dsConf.Data());
      TString line;
      Bool_t isRun = kFALSE;
      while (in.good())
      {
         in >> line;
         if (line.IsNull()) continue;
         if (line.Contains("BASE")) {
            GetParameterFromConfig(line);
            plugin->SetGridDataDir(line.Data());
            Printf("BASE -> %s",line.Data());
            continue;
         }
         if (line.Contains("PREFIX")) {
            GetParameterFromConfig(line);
            plugin->SetRunPrefix(line.Data());
            Printf("PREFIX -> %s",line.Data());
            continue;
         }
         if (line.Contains("DATA_PATTERN")) {
            GetParameterFromConfig(line);
            plugin->SetDataPattern(line.Data());
            Printf("DATA_PATTERN -> %s",line.Data());
            continue;
         }
         if (!line.CompareTo("RUNS")) {
            isRun = kTRUE;
            in >> line;
         }
         if (isRun) {
            if (numRunsSkip>0) {
               numRunsSkip--;
               continue;
            } else {
               if (nRunsPerMaster < numRuns ) {
                  Printf("Adding RUN : %s",line.Data());
                  plugin->AddRunNumber(line.Data());
                  nRunsPerMaster++;
               } else {
                  break;
               }

            }
         }
      }
Example #7
0
void FinishData( TString proc, TString tgt, TString name)
{
	TString path;

	cout << "End-of-Run macro executing";
	cout << endl;

	path =  "histograms/";

	if ( proc == "comp") path.Append( "Compton/");
	else if ( proc == "pi0") path.Append( "Pi0/");
	if ( tgt == "full") path.Append( "Full/");
	else if ( tgt == "empty") path.Append( "Empty/");

	path.Append( name);
	path.Append( ".root");
	TFile f( path, "recreate");
	gROOT->GetList()->Write();
	f.Close();

	path.Prepend( "All histograms saved to \"");
	path.Append( "\"");
	cout << path;
	cout << endl;
}
Example #8
0
//___________________________________________________
void KVClassFactory::WritePreProc(ofstream & file)
{
   //Write pre-processor directives in file
   //i.e. '#ifndef __TOTO_H' etc.
   //If this class has inheritance, we add '#include "base_class.h"' for each of the base classes.
   //and any other include files added using AddHeaderIncludeFile

   TString tmp = fClassName;
   tmp.ToUpper();
   tmp.Prepend("__");
   tmp.Append("_H");
   file << "#ifndef " << tmp.Data() << endl;
   file << "#define " << tmp.Data() << "\n" << endl;
   //base class(es) ?
   if (fHasBaseClass) {
		if(WithMultipleBaseClasses()){
			fBaseClassName.Begin(",");
			while( !fBaseClassName.End() )
				file << "#include \"" << fBaseClassName.Next(kTRUE) << ".h\"" << endl;
			file << endl;
		}
		else
	file << "#include \"" << fBaseClassName.Data() << ".h\"\n" << endl;
   }
   if( fHeadInc.GetSize() ){
      TIter next(&fHeadInc); TObjString* str;
      while( (str = (TObjString*)next()) ){
         file << "#include \"" << str->String().Data() << "\"\n" << endl;
      }
   }
}
Example #9
0
//_______________________________________
void PlotDataResults(const char* filenameData, const char* filenameMC="", Bool_t save=kFALSE)
{
  if (!addToName.IsNull()) addToName.Prepend("-");
  AliDielectronCFdraw d(filenameData);
  AliDielectronCFdraw dCorr("corrCont","corrCont");
  TString nameCorr(filenameMC);
  if (!nameCorr.IsNull()) d.SetCFContainers(nameCorr.Data());
  TFile f(filenameData);
  TH1 *hStats=(TH1*)f.Get("hEventStat");
  if (!f.IsOpen() || f.IsZombie() || !hStats) return;
  hStats->SetDirectory(0);
  f.Close();
  
  Int_t stepFirst=0, stepAny=1, stepTOFmix=2;
  
  gStyle->SetOptStat(0);
  //Set common Ranges
  d.SetRangeUser("Leg1_NclsTPC",70.,170.);
  d.SetRangeUser("Leg2_NclsTPC",70.,170.);
  d.SetRangeUser("Leg1_Pt",1.01,100000);
  d.SetRangeUser("Leg2_Pt",1.01,100000);
  d.SetRangeUser("Leg1_Eta",-0.899,0.899);
  d.SetRangeUser("Leg2_Eta",-0.899,0.899);

  d.SetRangeUser("Leg1_TPC_nSigma_Electrons",-3.,2.99);
  d.SetRangeUser("Leg2_TPC_nSigma_Electrons",-3.,2.99);
  d.SetRangeUser("Leg1_TPC_nSigma_Pions",3.51,20); 
  d.SetRangeUser("Leg2_TPC_nSigma_Pions",3.51,20); 
  d.SetRangeUser("Leg1_TPC_nSigma_Protons",3.01,20); 
  d.SetRangeUser("Leg2_TPC_nSigma_Protons",3.01,20);

//   d.SetRangeUser("Pt",0,1000);
  
  d.SetRangeUser("M",0.5,5.);
  //============================
  //SPD first
  //
  
  //--- Like sign subtraction
  AliDielectronSignalBase *sigFirst=GetSignalLS(d,stepFirst);
  SetStyle(sigFirst,"ITS First - Like Sign subtraction");
  DrawSpectra(sigFirst,"cFirst",hStats,save);
  //--- Like sign subtraction Arithmetic mean
  AliDielectronSignalBase *sigFirstArith=GetSignalLS(d,stepFirst,AliDielectronSignalBase::kLikeSignArithm);
  SetStyle(sigFirstArith,"ITS FirstArith - Like Sign subtraction");
  DrawSpectra(sigFirstArith,"cFirstArith",hStats,save);
  
  //============================
  //SPD any
  //
  AliDielectronSignalBase *sigAny=GetSignalLS(d,stepAny);
  SetStyle(sigAny,"ITS Any - Like Sign subtraction");
  DrawSpectra(sigAny,"cAny",hStats,save);
  //--- like sign with arithmetic mean
  AliDielectronSignalBase *sigAnyArith=GetSignalLS(d,stepAny,AliDielectronSignalBase::kLikeSignArithm);
  SetStyle(sigAnyArith,"ITS Any - Like Sign subtraction (Arithm. mean)");
  DrawSpectra(sigAnyArith,"cAnyArith",hStats,save);
  
  if (hStats) delete hStats;
}
Example #10
0
Bool_t KVINDRAPulserDataTree::OpenGeneData(Int_t run, ifstream &f)
{
	// Open gene data for one run
	// We look for file 'runXXXX.gene' in the directory given by
	// environment variable KVINDRAPulserDataTree.GeneDetDir.

	TString fname; fname.Form("/run%d.gene", run);
	fname.Prepend(gDataSet->GetDataSetEnv("KVINDRAPulserDataTree.GeneDetDir",""));
	return gDataSet->OpenDataSetFile(fname.Data(),f);
}
Example #11
0
void PublishCanvas(TList *qaList, const char* det, const char* name, TString nadd)
{
  //
  // draw all nSigma + signal histo
  //


  TObjArray arrHistos;

  TPaveText pt(.1,.1,.9,.9,"NDC");
  pt.SetBorderSize(1);
  pt.SetFillColor(0);
  pt.SetTextSizePixels(16);
  pt.AddText(Form("%s PID QA",det));
  if (!nadd.IsNull()){
    pt.AddText(nadd.Data());
    nadd.Prepend("_");
  }
  arrHistos.Add(&pt);

  TH2 *hSig=Get2DHistogramfromList(qaList,det,Form("hSigP_%s",det));
  if (hSig){
    hSig->SetOption("colz");
    arrHistos.Add(hSig);
  }

  for (Int_t i=0;i<AliPID::kSPECIESC;++i){
    //     for (Int_t i=0;i<AliPID::kSPECIES;++i){
    if (i==(Int_t)AliPID::kMuon) continue;
    TH2 *h=Get2DHistogramfromList(qaList,det,Form(name,AliPID::ParticleName(i)));
    if (!h) continue;
    h->SetOption("colz");
    AddFit(h);
    arrHistos.Add(h);
  }

  Int_t nPads=arrHistos.GetEntriesFast();
  Int_t nCols = (Int_t)TMath::Ceil( TMath::Sqrt(nPads) );
  Int_t nRows = (Int_t)TMath::Ceil( (Double_t)nPads/(Double_t)nCols );

  
  fCanvas->Divide(nCols,nRows);


  for (Int_t i=0; i<nPads;++i) {
    fCanvas->cd(i+1);
    SetupPadStyle();
    arrHistos.At(i)->Draw();
  }

  fCanvas->Update();
  fCanvas->Clear();

}
Example #12
0
Bool_t KVINDRAPulserDataTree::OpenPinData(Int_t run, ifstream &f)
{
	// Open pin data for one run
	// We look for one of the following files in the directory given by
	// environment variable KVINDRAPulserDataTree.GenePinDir:
	//
	// 	runXXXX.genepin
	// OR	runXXXX.laserpin
	// OR	runXXXX.genelaserpin

	TString fname;
	fname.Form("/run%d.genepin", run);
	TString pindir(gDataSet->GetDataSetEnv("KVINDRAPulserDataTree.GenePinDir",""));
	fname.Prepend(pindir);
	if(gDataSet->OpenDataSetFile(fname.Data(),f)) return kTRUE;
	fname.Form("/run%d.laserpin", run);
	fname.Prepend(pindir);
	if(gDataSet->OpenDataSetFile(fname.Data(),f)) return kTRUE;
	fname.Form("/run%d.genelaserpin", run);
	fname.Prepend(pindir);
	return gDataSet->OpenDataSetFile(fname.Data(),f);
}
Example #13
0
void FinishMC5( TString process, Int_t energy, Int_t chan)
{
	TString name;

	name = Form( "histograms/MonteCarlo/%s_e%d_t%d.root",
			process.Data(), energy, chan);

	printf( "End-of-Run macro executing\n");

	TFile f( name, "recreate");
	gROOT->GetList()->Write();
	f.Close();

	name.Prepend( "All histograms saved to ");
	cout << name << endl;
}
void misalignmentDependence(Int_t nFiles,TString *files,TString *names,TString misalignment,Double_t *values,Double_t *phases,TString xvar,TString yvar,
                            TString function,Int_t nParameters,Int_t *parameters,TString *parameternames,TString functionname = "",
                            Bool_t resolution = false,
                            TString saveas = "")
{
    for (int i = 0; i < nParameters; i++)
    {
        TString saveasi = saveas;
        TString insert = nPart(1,parameternames[i]);
        insert.Prepend(".");
        saveasi.Insert(saveasi.Last('.'),insert);    //insert the parameter name before the file extension
        misalignmentDependence(nFiles,files,names,misalignment,values,phases,xvar,yvar,
                               function,parameters[i],parameternames[i],functionname,
                               resolution,
                               saveasi);
    }
}
Example #15
0
void FinishMC3( TString savedir, TString encl, TString process, TString tgt,
		UInt_t eg)
{
	TString name;

	name = "End-of-Run macro executing";
	cout << name << endl;

	name = Form( "histograms/MonteCarlo/%s/%s/%s_%s_%d.root",
			savedir.Data(), encl.Data(), process.Data(),
			tgt.Data(), eg);

	TFile f( name, "recreate");
	gROOT->GetList()->Write();
	f.Close();

	name.Prepend( "All histograms save to ");
	cout << name << endl;
}
Example #16
0
void FinishBasic( TString name)
{
	TString path;

	cout << "End-of-Run macro executing";
	cout << endl;

	path =  "histograms/";

	path.Append( name);
	path.Append( ".root");
	TFile f( path, "recreate");
	gROOT->GetList()->Write();
	f.Close();

	path.Prepend( "All histograms saved to \"");
	path.Append( "\"");
	cout << path;
	cout << endl;
}
Example #17
0
void FinishMC2( TString proc, Int_t eg, TString cond)
{
	TString name;

	name = Form( "histograms/MonteCarlo/%s_%d_%s.root", proc.Data(), eg,
			cond.Data());

	printf( "End-of-Run macro executing\n");

	TFile f( name, "recreate");
	gROOT->GetList()->Write();
	f.Close();

	name.Prepend( "All histograms saved to ");
	cout << name << endl;

//	gROOT->ProcessLine( ".L ThetaEff.C");
//	ThetaEffBatch2( tgt, eg, cond);
//	printf( "Theta efficiencies calculated for %s %d %s\n", tgt, eg, cond);
}
Example #18
0
void FinishTE()
{
	Int_t run;
	TString name;

	run = GetRunDave();

	name = Form( "histograms/TaggEff/TaggEff_%d.root", run);

	cout << "End-of-Run macro executing";
	cout << endl;

	TFile f( name, "recreate");
	gROOT->GetList()->Write();
	f.Close();

	name.Prepend( "All histograms saved to \"");
	name.Append( "\"");
	cout << name;
	cout << endl;
}
Example #19
0
//##################################################
bool LoadLibList ( const TString& list, TString& listlibs, TString& listlibsextra ) {
  TObjArray* arr = list.Tokenize(" ");
  TObjString *objstr = NULL;

  cout << "Loading library list (-2 = version mismatch, -1 = not found or error, 0 = success, 1 = already loaded) :" << endl;
  TIter next(arr);
  while ( (objstr=(TObjString*)next()) ) {
      TString module = objstr->GetString();
      if (module.IsNull()) { continue; }
      module.Prepend("lib");
      if(module.EndsWith(".so")) { module.Remove( module.Index(".so")); }
      std::cout << "loading module :" << module.Data() << " ... " ;
      int result = gSystem->Load(module.Data(), "", kTRUE);
      std::cout << result << std::endl; ;
      if (result < 0) { std::cout << "EmcalJetCDF::LoadLibList - Could not load library >>>"  << module.Data() << "<<< ; Error = " << result << std::endl; return false; }

      TString lib_in_list = module + ".so "; // blank after .so
      listlibs      += lib_in_list;
      listlibsextra += lib_in_list;
      }
  delete arr;
  return true;
  }
bool createPlot(TString hname, TString dirname, TFile *V1file, TString relstring1, TFile *V2file, TString relstring2, TCanvas *canvas, int scale) {
  setTDRStyle();

  // don't look at non-zero bin
  Int_t range_upper = histV1->GetXaxis()->GetLast();
  histV1->GetXaxis()->SetRangeUser(1,range_upper);
  histV2->GetXaxis()->SetRangeUser(1,range_upper);

  int SetScale = scale;

  //IF =0 --> No scale applied ('direct' comparison)
  //IF =1 --> Scale INDIVIDUALLY (scale histograms individually) 
  //IF =2 --> Scale all GLOBALLY (scale all histograms to #tracks=1)
  //IF =3 --> Scale all GLOBALLY nEVENTS (scale all histos to nEntries in nTracks per Event)

  bool DrawRatio = true;
  canvas->cd();
  TPad* mainpad = new TPad("mainpad","mainpad",0.0,0.0,1.0,0.8);
  mainpad->Draw();
  mainpad->cd();

  // ************ Get name of histos and get histos ************* //
  
  TString basename1 = "DQMData/Run ";
  basename1.Append("1");

  TString hnameV1 = basename1;
  hnameV1.Append(dirname+"/");
  hnameV1.Append(hname);

  if (hname != "vtxNbr"){
    hnameV1.Append("_GenTk");
  }

  TH1F * histV1 = (TH1F*)V1file->Get(hnameV1);
  if ( histV1 == (TH1F*) NULL ) {
    cout << "histV1 failed on " << hnameV1  << endl << " for file " << V1file->GetName() << endl;
    exit(1);
  }

  TString basename2 = "DQMData/Run ";
  basename2.Append("1");

  TString hnameV2 = basename2;
  hnameV2.Append(dirname+"/");
  hnameV2.Append(hname);
  
  if (hname != "vtxNbr"){
    hnameV2.Append("_GenTk");
  }

  TH1F * histV2 = (TH1F*)V2file->Get(hnameV2);
  if ( histV2 == (TH1F*) NULL ) {
    cout << "histV2 failed on " << hnameV2  << endl << " for file " << V2file->GetName() << endl;
    exit(1);
  }

  //******************* Get histo integrals ***********************//
  double V1_integral = 1.0;
  double V2_integral = 1.0;

  TH1F * hTempV1 = 0;
  TH1F * hTempV2 = 0;

  if (SetScale==1){    
    V1_integral = histV1->Integral();
    V2_integral = histV2->Integral();
  }
  else if ( (SetScale==2) || (SetScale==3) ){
    if (hname != "NumberOfTracks"){
      TString hTempNameV1 = basename1;
      hTempNameV1.Append("/Tracking/Run summary/TrackParameters/generalTracks/GeneralProperties/NumberOfTracks_GenTk");
      hTempV1 = (TH1F*)V1file->Get(hTempNameV1);
      
      TString hTempNameV2 = basename2;
      hTempNameV2.Append("/Tracking/Run summary/TrackParameters/generalTracks/GeneralProperties/NumberOfTracks_GenTk");
      hTempV2 = (TH1F*)V2file->Get(hTempNameV2);
    }
    else{
      hTempV1 = (TH1F*)histV1->Clone("hTempV1");
      hTempV2 = (TH1F*)histV2->Clone("hTempV2");
    }

    if (SetScale==2){
      V1_integral = hTempV1->GetBinContent(2);
      V2_integral = hTempV2->GetBinContent(2);

      std::cout << "The number of single tracks for V1 is " << V1_integral << std::endl;
      std::cout << "The number of single tracks for V2 is " << V2_integral << std::endl;
    }
    else if (SetScale==3){
      V1_integral = hTempV1->GetEntries();
      V2_integral = hTempV2->GetEntries();

      std::cout << "The number of events for V1 is " << V1_integral << std::endl;
      std::cout << "The number of events for V2 is " << V2_integral << std::endl;
    }
  }

  //*****NORMALIZING V1-V2****************************************

  if(V1_integral>V2_integral) {
    histV1->Scale(V2_integral / V1_integral);
    histV2->Scale(1);
  } 
  else if(V2_integral>V1_integral){
    histV1->Scale(1);
    histV2->Scale(V1_integral / V2_integral);
  }

  //*****NORMALIZING V1-V2*end***************************************

  //***Name the files under comparison***
  TString V1_V1run = "Run 1 ("+relstring1+")";
  TString V2_V2run = "Run 1 ("+relstring2+")";

  histV1->SetName(V1_V1run);
  histV2->SetName(V2_V2run);

  TString x_title = "";
  if( hname.Contains("vtxNbr"))                               x_title="Number of Primary Vertices per Event";

  histV1->SetLineWidth(5);
  histV1->SetLineStyle(1);
  histV1->SetLineColor(kRed);
  histV1->GetYaxis()->SetLabelSize(0.038);

  histV2->SetLineWidth(3);
  histV2->SetLineStyle(1);
  histV2->SetLineColor(kBlue);

  if ( hname.Contains("NumberOfTracks",TString::kExact)
      || hname.Contains("NumberOfGoodTracks",TString::kExact)
      || hname.Contains("TrackPt",TString::kExact)
      || hname.Contains("Chi2Prob",TString::kExact)
       ){
    mainpad->SetLogy(1);
  }
  else {
    mainpad->SetLogy(0);
  }

  if (hname.Contains("NumberOfGoodTracks",TString::kExact)) {
    histV1->GetXaxis()->SetRangeUser(0,200);
    histV2->GetXaxis()->SetRangeUser(0,200);
  }

  if (hname.Contains("Chi2oNDF",TString::kExact)) {
    histV1->GetXaxis()->SetRangeUser(0,10);
    histV2->GetXaxis()->SetRangeUser(0,10);
  }

  if (hname.Contains("vtxNbr")){
    histV1->GetXaxis()->SetTitle(x_title);
    histV1->GetYaxis()->SetTitle("Number of Events");
  }

  if ( hname.Contains("NumberOfTracks",TString::kExact)){
    histV1->GetXaxis()->SetRangeUser(125,range_upper);
    histV2->GetXaxis()->SetRangeUser(125,range_upper);
  }

  double max = 0;
  double V1max = histV1->GetBinContent(histV1->GetMaximumBin());
  double V2max = histV2->GetBinContent(histV2->GetMaximumBin());

  max = (V1max>V2max) ? V1max : V2max;
  histV1->SetMaximum(max*(1.1));

  histV1->Draw();
  histV2->Draw("sames");

  mainpad->Update();

  TPaveStats *st1 = (TPaveStats*)(histV1->GetListOfFunctions()->FindObject("stats"));

  st1->SetX1NDC(0.77);
  st1->SetY1NDC(0.80);

  st1->SetX2NDC(0.98);
  st1->SetY2NDC(0.97);
  Double_t defaulth = st1->GetY2NDC() - st1->GetY1NDC();
  Double_t gaph = 0.02;
  TPaveStats *st2 = (TPaveStats*)(histV2->GetListOfFunctions()->FindObject("stats"));
  st2->SetX1NDC(0.77);  
  st2->SetY1NDC(st1->GetY1NDC() - 1.0*defaulth - gaph);
  st2->SetX2NDC(0.98);    
  st2->SetY2NDC(st1->GetY1NDC() - gaph);

  TLegend *leg = new TLegend(0.32,0.86,0.76,0.97);
  leg->SetTextSize(0.042);
  leg->SetTextFont(42);
  leg->SetFillColor(10); 
  leg->SetBorderSize(1); // no frame, no shadow
  leg->AddEntry(histV1, V1_V1run, "L" );
  leg->AddEntry(histV2, V2_V2run, "L" );
  leg->Draw("SAME");

  // Draw ratio histogram
  if (DrawRatio){
    canvas->cd();
    TPad* respad = new TPad("respad","respad",0.0,0.78,1.0,0.95);
    respad->SetTopMargin(1.05);
    respad->Draw();
    respad->cd();
    TH1F* hratio = (TH1F*) histV2->Clone("hratio");
    hratio->Divide(histV1);
    hratio->SetMaximum(hratio->GetMaximum()*1.01);
    //if (hratio->GetMinimum()==0.0) hratio->SetMinimum(1.0/hratio->GetMaximum());
    hratio->SetMinimum(1.0/hratio->GetMaximum());
    hratio->GetYaxis()->SetLabelSize(0.1);
    hratio->GetYaxis()->SetRangeUser(0,2);
    hratio->GetXaxis()->SetLabelSize(0);
    hratio->GetXaxis()->SetTitleSize(0);
    hratio->GetYaxis()->SetTitleSize(0.22);
    hratio->GetYaxis()->SetTitleOffset(0.26);
    hratio->GetYaxis()->SetLabelSize(0.2);
    hratio->GetYaxis()->SetNdivisions(5);
    hratio->GetYaxis()->SetTitle("PM/SM");
 
    hratio->Draw();
  }

  // Compare parameters of histograms
  double Entries1 = histV1->GetEntries();
  double Entries2 = histV2->GetEntries();
  if (Entries1 != Entries2) {
    std::cout<<" Difference in # of ENTRIES for " <<hname<< std::endl;
    std::cout<<"\t Entries1 = " << Entries1 << "\t Entries2 = " << Entries2 << std::endl;
  }

  double Mean1 = histV1->GetMean();
  double Mean2 = histV2->GetMean();
  if (Mean1 != Mean2) {
    std::cout<<" Difference in MEANS for " <<hname<< std::endl;
    std::cout<<"\t Mean1 = " << Mean1 << "\t Mean2 = " << Mean2 << std::endl;
  }

  double RMS1 = histV1->GetRMS();
  double RMS2 = histV2->GetRMS();
  if (RMS1 != RMS2) {
    std::cout<<" Difference in RMS for " <<hname<< std::endl;
    std::cout<<"\t RMS1 = " << RMS1 << "\t RMS2 = " << RMS2 << std::endl;
  }

  TString filename = hname;

  if (hname.Contains("vtxNbr")){
    filename = "NumberOfPrimaryVertices";
  }

  if (dirname.Contains("highPurityTracks/pt_1/GeneralProperties",TString::kExact))
    filename.Prepend("RunComparison/GoodTracks_");
  else filename.Prepend("RunComparison/");

  filename.Append(".png");

  canvas->Print(filename);

  if ( histV1 ) {histV1->Delete();}
  if ( histV2 ) {histV2->Delete();}

  if ( hTempV1 ) {hTempV1->Delete();}
  if ( hTempV2 ) {hTempV2->Delete();}

  return true;
}
void plot_BSM_MCFM(int SignalOnly=0){
  gROOT->ProcessLine(".x tdrstyle.cc");
  double mPOLE = 125.6;

  TString OUTPUT_NAME;
  OUTPUT_NAME = "HtoZZ4l_MCFM_125p6_BSMPlots";
  if (SignalOnly==0) OUTPUT_NAME.Append(".root");
  else OUTPUT_NAME.Append("_SignalOnly.root");
  TString coutput_common = user_TemplateswithTrees_dir + "../BSMReweight_GenLevel/Plots/";
  gSystem->Exec("mkdir -p " + coutput_common);
  TString coutput = coutput_common + OUTPUT_NAME;
  TFile* foutput = new TFile(coutput, "recreate");

  foutput->cd();

  float ZZMass = 0;
  float p0plus_VAJHU;
  float p0hplus_VAJHU;
  float p0minus_VAJHU;
  float p0_g1prime2_VAJHU;
  float p0_g1prime4_VAJHU;
  float pg1g2_VAJHU;
  float pg1g4_VAJHU;
  float pg1g1prime2_VAJHU;
  float pg1g1prime4_VAJHU;

  TChain* tc[2][3][4];
  TH1F* hfill[4][9];
  int nbinsx = 73;
  double xlimits[2]={ 160, 1620 };
  if (SignalOnly==1){
    xlimits[0]=100;
    nbinsx = 76;
  }
  for (int t=0; t<4; t++){
    for (int ac=0; ac<9; ac++){
      hfill[t][ac]= new TH1F(Form("hSum_BSI%i_Hypo%i", t, ac), "", nbinsx, xlimits[0], xlimits[1]);
      hfill[t][ac]->SetXTitle("m_{4l} (GeV)");
      hfill[t][ac]->SetYTitle(Form("Events / %.0f GeV", (xlimits[1]-xlimits[0])/nbinsx));
    }
  }
  double nCounted[2][3][9]={ { { 0 } } };
  double nCountedScaled[2][3][9]={ { { 0 } } };
  for (int erg_tev=7; erg_tev<9; erg_tev++){
    for (int folder=0; folder<3; folder++){
      TString comstring;
      comstring.Form("%iTeV", erg_tev);
      TString erg_dir;
      erg_dir.Form("LHC_%iTeV/", erg_tev);

      int EnergyIndex = 1;
      if (erg_tev == 7) EnergyIndex = 0;
      TString cinput_common = user_TemplateswithTrees_dir + "../BSMReweight_GenLevel/";
      cinput_common.Append(+erg_dir);
      cinput_common += user_folder[folder] + "/";
      cout << cinput_common << endl;
      for (int t=0; t<4; t++){
        TString INPUT_NAME;
        INPUT_NAME = "HtoZZ4l_MCFM_125p6_BSMTrees_";
        INPUT_NAME += sample_suffix[t] + ".root";
        INPUT_NAME.Prepend(cinput_common);

        tc[EnergyIndex][folder][t] = new TChain("GenTree");
        if (t!=3) tc[EnergyIndex][folder][t]->Add(INPUT_NAME);
        tc[EnergyIndex][folder][t]->SetBranchAddress("ZZMass", &ZZMass);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0plus_VAJHU", &p0plus_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0hplus_VAJHU", &p0hplus_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0minus_VAJHU", &p0minus_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0_g1prime2_VAJHU", &p0_g1prime2_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0_g1prime4_VAJHU", &p0_g1prime4_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("pg1g2_VAJHU", &pg1g2_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("pg1g4_VAJHU", &pg1g4_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("pg1g1prime2_VAJHU", &pg1g1prime2_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("pg1g1prime4_VAJHU", &pg1g1prime4_VAJHU);
      }

      double nsig_counted[9] ={ 0 };
      for (int ev=0; ev<tc[EnergyIndex][folder][0]->GetEntries(); ev++){
        tc[EnergyIndex][folder][0]->GetEntry(ev);
        if (fabs(ZZMass-mPOLE)<0.1){
          nsig_counted[0] += p0plus_VAJHU;
          nsig_counted[1] += p0hplus_VAJHU;
          nsig_counted[2] += p0minus_VAJHU;
          nsig_counted[3] += p0_g1prime2_VAJHU;
          nsig_counted[4] += p0_g1prime4_VAJHU;
          nsig_counted[5] += (2.*(p0plus_VAJHU+p0hplus_VAJHU)-pg1g2_VAJHU);
          nsig_counted[6] += pg1g4_VAJHU;
          nsig_counted[7] += pg1g1prime2_VAJHU;
          nsig_counted[8] += pg1g1prime4_VAJHU;
        }
      }

      for (int ac=0; ac<9; ac++) nCounted[EnergyIndex][folder][ac] = nsig_counted[ac];

    }
  }


  for (int erg_tev=7; erg_tev<9; erg_tev++){
    for (int folder=0; folder<3; folder++){
      int EnergyIndex = 1;
      if (erg_tev == 7) EnergyIndex = 0;

      double nsig_SM = nSM_ScaledPeak[EnergyIndex][folder];
      double SMscale = nsig_SM/nCounted[EnergyIndex][folder][0];
      double scale=1;
      for (int t=0; t<4; t++){
        for (int ev=0; ev<tc[EnergyIndex][folder][t]->GetEntries(); ev++){
          tc[EnergyIndex][folder][t]->GetEntry(ev);
          if (ZZMass<xlimits[0]) continue;
          if (ZZMass>=xlimits[1]) ZZMass=xlimits[1]*0.999;

          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][0] = nCounted[EnergyIndex][folder][0]*scale;
          hfill[t][0]->Fill(ZZMass, p0plus_VAJHU*scale);
          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][1] = nCounted[EnergyIndex][folder][1]*scale;
          hfill[t][1]->Fill(ZZMass, p0hplus_VAJHU*scale);
          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][2] = nCounted[EnergyIndex][folder][2]*scale;
          hfill[t][2]->Fill(ZZMass, p0minus_VAJHU*scale);
          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][3] = nCounted[EnergyIndex][folder][3]*scale;
          hfill[t][3]->Fill(ZZMass, p0_g1prime2_VAJHU*scale);
          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][4] = nCounted[EnergyIndex][folder][4]*scale;
          hfill[t][4]->Fill(ZZMass, p0_g1prime4_VAJHU*scale);
          scale = SMscale;
          if (t>0){
            hfill[t][5]->Fill(ZZMass, pg1g2_VAJHU*scale);
          }
          else{
            scale *= (nCounted[0][2][0]+nCounted[1][2][0])/(nCounted[0][2][5]+nCounted[1][2][5]);
            hfill[t][5]->Fill(ZZMass, (2.*(p0plus_VAJHU+p0hplus_VAJHU)-pg1g2_VAJHU)*scale);
          }
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][5] = nCounted[EnergyIndex][folder][5]*scale;
          scale = SMscale;
          if (t==0) scale *= (nCounted[0][2][0]+nCounted[1][2][0])/(nCounted[0][2][6]+nCounted[1][2][6]);
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][6] = nCounted[EnergyIndex][folder][6]*scale;
          hfill[t][6]->Fill(ZZMass, pg1g4_VAJHU*scale);
          scale = SMscale;
          if (t==0) scale *= (nCounted[0][2][0]+nCounted[1][2][0])/(nCounted[0][2][7]+nCounted[1][2][7]);
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][7] = nCounted[EnergyIndex][folder][7]*scale;
          hfill[t][7]->Fill(ZZMass, pg1g1prime2_VAJHU*scale);
          scale = SMscale;
          //          if (t==0) scale *= (nCounted[0][2][0]+nCounted[1][2][0])/(nCounted[0][2][8]+nCounted[1][2][8]);
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][8] = nCounted[EnergyIndex][folder][8]*scale;
          hfill[t][8]->Fill(ZZMass, pg1g1prime4_VAJHU*scale);
        }
        delete tc[EnergyIndex][folder][t];
      }
    }
  }
  for (int ac=1; ac<9; ac++){
    double nTotal[2]={ 0 };
    for (int erg_tev=7; erg_tev<9; erg_tev++){
      for (int folder=0; folder<3; folder++){
        int EnergyIndex = 1;
        if (erg_tev == 7) EnergyIndex = 0;

        nTotal[0] += nCountedScaled[EnergyIndex][folder][0];
        nTotal[1] += nCountedScaled[EnergyIndex][folder][ac];
      }
    }
    if (ac!=8) hfill[0][ac]->Scale(nTotal[0]/nTotal[1]);
    else hfill[0][ac]->Scale(0.5);
  }


  double maxplot=0;
  for (int t=0; t<4; t++){
    for (int ac=0; ac<9; ac++){
      if (SignalOnly==0 && ac<5) maxplot = max(maxplot, hfill[t][ac]->GetMaximum());
      else if (SignalOnly==1 && !(ac<5 && ac>0) && t==0) maxplot = max(maxplot, hfill[t][ac]->GetMaximum());
      hfill[t][ac]->SetLineWidth(2);
      if (t==0 && ac>=5){
        hfill[t][ac]->SetLineStyle(7);
        //        hfill[t][ac]->Add(hfill[1][ac]);
      }
      if (t==1) hfill[t][ac]->SetLineStyle(3);
      if (t==3) hfill[t][ac]->SetLineStyle(9);
      hfill[t][ac]->GetXaxis()->SetLabelFont(42);
      hfill[t][ac]->GetXaxis()->SetLabelOffset(0.007);
      hfill[t][ac]->GetXaxis()->SetLabelSize(0.04);
      hfill[t][ac]->GetXaxis()->SetTitleSize(0.06);
      hfill[t][ac]->GetXaxis()->SetTitleOffset(0.9);
      hfill[t][ac]->GetXaxis()->SetTitleFont(42);
      hfill[t][ac]->GetYaxis()->SetNdivisions(505);
      hfill[t][ac]->GetYaxis()->SetLabelFont(42);
      hfill[t][ac]->GetYaxis()->SetLabelOffset(0.007);
      hfill[t][ac]->GetYaxis()->SetLabelSize(0.04);
      hfill[t][ac]->GetYaxis()->SetTitleSize(0.06);
      hfill[t][ac]->GetYaxis()->SetTitleOffset(1.1);
      hfill[t][ac]->GetYaxis()->SetTitleFont(42);
    }
  }

  TPaveText* pt = new TPaveText(0.15, 0.93, 0.85, 1, "brNDC");
  pt->SetBorderSize(0);
  pt->SetFillStyle(0);
  pt->SetTextAlign(12);
  pt->SetTextFont(42);
  pt->SetTextSize(0.045);
  TText* text = pt->AddText(0.025, 0.45, "#font[61]{CMS}");
  text->SetTextSize(0.044);
  text = pt->AddText(0.165, 0.42, "#font[52]{Simulation}");
  text->SetTextSize(0.0315);
  TString cErgTev = "#font[42]{19.7 fb^{-1} (8 TeV) + 5.1 fb^{-1} (7 TeV)}";
  text = pt->AddText(0.537, 0.45, cErgTev);
  text->SetTextSize(0.0315);

  float lxmin = 0.22;
  float lxwidth = 0.38;
  float lymax = 0.9;
  float lywidth = 0.3;
  float lxmax = lxmin + lxwidth;
  float lymin = lymax;
  if (SignalOnly==0) lymin -= lywidth*4./5.;
  else lymin -= lywidth;

  float lxmin2 = 0.22+0.39;
  float lymax2 = lymax;
  float lxmax2 = lxmin2 + lxwidth;
  float lymin2 = lymax2;
  if (SignalOnly==0) lymin2 -= lywidth*2./5.;
  else lymin2 -= lywidth*4./5.;

  if (SignalOnly==1){
    float lxmin3 = lxmin2;
    float lymax3 = lymax2;
    float lxmax3 = lxmax2;
    float lymin3 = lymin2;

    lxmin2 = lxmin;
    lxmax2 = lxmax;
    lymin2 = lymin;
    lymax2 = lymax;
    lxmin = lxmin3;
    lxmax = lxmax3;
    lymin = lymin3;
    lymax = lymax3;
  }

  float pxmin = 0.756;
  float pymin = 0.76;
  float pxmax = 0.85;
  if (SignalOnly==1){
    pymin -= 0.12;
  }
  float pymax = pymin+0.05;
  TPaveText* ptx = new TPaveText(pxmin, pymin, pxmax, pymax, "brNDC");
  ptx->SetBorderSize(0);
  ptx->SetTextFont(42);
  ptx->SetTextSize(0.04);
  ptx->SetLineColor(1);
  ptx->SetLineStyle(1);
  ptx->SetLineWidth(1);
  ptx->SetFillColor(0);
  ptx->SetFillStyle(0);
  text = ptx->AddText(0.01, 0.01, "gg#rightarrow4l");
  text->SetTextSize(0.04);

  TString canvasname = "cCanvas_MCFMBSM_GenLevel";
  if (SignalOnly==1) canvasname.Append("_SignalOnly");
  TCanvas* cc = new TCanvas(canvasname, "", 8, 30, 800, 800);
  cc->cd();
  gStyle->SetOptStat(0);
  cc->SetFillColor(0);
  cc->SetBorderMode(0);
  cc->SetBorderSize(2);
  cc->SetTickx(1);
  cc->SetTicky(1);
  cc->SetLeftMargin(0.17);
  cc->SetRightMargin(0.05);
  cc->SetTopMargin(0.07);
  cc->SetBottomMargin(0.13);
  cc->SetFrameFillStyle(0);
  cc->SetFrameBorderMode(0);
  cc->SetFrameFillStyle(0);
  cc->SetFrameBorderMode(0);
  cc->SetLogy();

  TLegend* ll;
  TLegend* ll2;

  ll = new TLegend(lxmin2, lymin2, lxmax2, lymax2);
  ll2 = new TLegend(lxmin, lymin, lxmax, lymax);

  ll->SetBorderSize(0);
  ll->SetTextFont(42);
  ll->SetTextSize(0.04);
  ll->SetLineColor(1);
  ll->SetLineStyle(1);
  ll->SetLineWidth(1);
  ll->SetFillColor(0);
  ll->SetFillStyle(0);
  ll2->SetBorderSize(0);
  ll2->SetTextFont(42);
  ll2->SetTextSize(0.04);
  ll2->SetLineColor(1);
  ll2->SetLineStyle(1);
  ll2->SetLineWidth(1);
  ll2->SetFillColor(0);
  ll2->SetFillStyle(0);

  TString strACtitle[9]={ "",
    "f_{a2}=1", "f_{a3}=1", "f_{#Lambda1}=1", "f_{#LambdaQ}=1",
    "f_{a2}=0.5, #phi_{#lower[-0.2]{a2}}=#pi", "f_{a3}=0.5", "f_{#Lambda1}=0.5", "f_{#LambdaQ}=0.5"
  };

  int iDraw = 2 - 2*SignalOnly;

  if (SignalOnly==0) hfill[iDraw][0]->GetYaxis()->SetRangeUser(7e-3, maxplot*15.);
  else{
    double histmin = 7e-3;
    if (hfill[iDraw][0]->GetMinimum()>0) histmin = hfill[iDraw][0]->GetMinimum();
    hfill[iDraw][0]->GetYaxis()->SetRangeUser(histmin, maxplot*2000.);
  }
  hfill[iDraw][0]->GetXaxis()->SetRangeUser(xlimits[0], 800.);

  hfill[iDraw][0]->SetLineColor(kBlack);
  if (SignalOnly==0){
    hfill[iDraw][0]->SetFillColor(kAzure-2);
    hfill[iDraw][0]->SetFillStyle(1001);
  }
  hfill[iDraw][0]->Draw("hist");

  hfill[iDraw][1]->SetLineColor(kBlue);
  hfill[iDraw][1]->Draw("histsame");

  hfill[iDraw][2]->SetLineColor(kRed);
  hfill[iDraw][2]->Draw("histsame");

  hfill[iDraw][3]->SetLineColor(kViolet);
  hfill[iDraw][3]->Draw("histsame");

  hfill[iDraw][4]->SetLineColor(kGreen+2);
  hfill[iDraw][4]->Draw("histsame");

  if (SignalOnly==1){
    hfill[iDraw][5]->SetLineColor(kBlue);
    hfill[iDraw][5]->Draw("histsame");

    hfill[iDraw][6]->SetLineColor(kRed);
    hfill[iDraw][6]->Draw("histsame");

    hfill[iDraw][7]->SetLineColor(kViolet);
    hfill[iDraw][7]->Draw("histsame");

    hfill[iDraw][8]->SetLineColor(kGreen+2);
    hfill[iDraw][8]->Draw("histsame");
  }

  if (SignalOnly==0){
    hfill[1][0]->SetLineColor(kBlack);
    hfill[1][0]->SetLineStyle(3);
    hfill[1][0]->Draw("histsame");
  }

  hfill[iDraw][0]->Draw("histsame");

  TLegendEntry* legendtext;
  if (SignalOnly==0){
    legendtext = ll->AddEntry(hfill[iDraw][0], "SM total", "f");
    legendtext = ll->AddEntry(hfill[1][0], "SM bkg.", "f");
    legendtext->SetFillStyle(1001);
    legendtext->SetFillColor(hfill[1][0]->GetFillColor());
  }
  else{
    legendtext = ll->AddEntry(hfill[iDraw][0], "SM signal", "f");
    legendtext->SetFillStyle(3001);
  }

  if (SignalOnly==0){
    legendtext = ll2->AddEntry(hfill[iDraw][4], Form("#Gamma_{H}=#Gamma^{SM}_{H}, %s", strACtitle[4].Data()), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][4]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][2], Form("#Gamma_{H}=#Gamma^{SM}_{H}, %s", strACtitle[2].Data()), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][2]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][1], Form("#Gamma_{H}=#Gamma^{SM}_{H}, %s", strACtitle[1].Data()), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][1]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][3], Form("#Gamma_{H}=#Gamma^{SM}_{H}, %s", strACtitle[3].Data()), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][3]->GetFillColor());
  }
  else{
    legendtext = ll->AddEntry(hfill[iDraw][4], strACtitle[4].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][4]->GetFillColor());
    legendtext = ll->AddEntry(hfill[iDraw][2], strACtitle[2].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][2]->GetFillColor());
    legendtext = ll->AddEntry(hfill[iDraw][1], strACtitle[1].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][1]->GetFillColor());
    legendtext = ll->AddEntry(hfill[iDraw][3], strACtitle[3].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][3]->GetFillColor());
  }
  if (SignalOnly==1){
    legendtext = ll2->AddEntry(hfill[iDraw][8], strACtitle[8].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][8]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][5], strACtitle[5].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][5]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][7], strACtitle[7].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][7]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][6], strACtitle[6].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][6]->GetFillColor());
  }

  ll->Draw("same");
  ll2->Draw("same");
  ptx->Draw();
  pt->Draw();
  cc->RedrawAxis();
  cc->Update();

  canvasname.Prepend(coutput_common);
  TString canvasname_pdf = canvasname;
  TString canvasname_eps = canvasname;
  TString canvasname_png = canvasname;
  TString canvasname_root = canvasname;
  TString canvasname_c = canvasname;
  canvasname_pdf.Append(".pdf");
  canvasname_eps.Append(".eps");
  canvasname_png.Append(".png");
  canvasname_root.Append(".root");
  canvasname_c.Append(".C");
  cc->SaveAs(canvasname_pdf);
  cc->SaveAs(canvasname_eps);
  cc->SaveAs(canvasname_png);
  cc->SaveAs(canvasname_root);
  cc->SaveAs(canvasname_c);

  foutput->WriteTObject(cc);
  delete ll2;
  delete ll;
  cc->Close();
  delete ptx;
  delete pt;
  for (int t=0; t<4; t++){
    for (int ac=0; ac<5; ac++){
      foutput->WriteTObject(hfill[t][ac]);
      delete hfill[t][ac];
    }
  }
  foutput->Close();
}
void computeOSWeights_CR(int erg_tev, int iCR, double m4l_low, double m4l_high){
//  if (iCR>2 || iCR==1) return;
  char TREE_NAME[]="SelectedTree";

  int EnergyIndex=0; if (erg_tev==8)EnergyIndex=1;
  double my_luminosity = luminosity[EnergyIndex];

  TString erg_dir;
  erg_dir.Form("LHC_%iTeV", erg_tev);
  TString comstring;
  comstring.Form("%iTeV", erg_tev);

  TChain* tc = new TChain(TREE_NAME);

  TString cinput_common_noSIP = user_dir_hep + "No_SIP/" + erg_dir + "/CR/";
  if (iCR<2){
    int sampleindex = kAllSamples-1 + iCR;
    TString cinput = cinput_common_noSIP;
    cinput = cinput + sample_FullSim[sampleindex] + ".root";
    tc->Add(cinput);
  }
  else{
    for (int smp=kGGSamples; smp<kQQBZZSamples; smp++){
      TString cinput = cinput_common_noSIP;
      cinput = cinput + sample_FullSim[smp] + "_CRZLLTree.root";
      tc->Add(cinput);
    }
  }

  if (tc->GetEntries() == 0){
    cout << "Could not find any files, aborting..." << endl; return;
  }
  else if (iCR==2) cout << "qqZZ CR: " << tc->GetEntries() << endl;

  TString coutput_common = user_dir_hep + "Analysis/Auxiliary/";

  TFile* frecord;
  TString fname = "OSfakeweights_";
  if (iCR==0) fname.Append("ZLL_");
  else if (iCR==1) fname.Append("ZL_");
  else if (iCR==2) fname.Append("QQBZZ_");
  fname += comstring;
  fname.Append(Form("_m4l_%.1f_%.1f%s", m4l_low, m4l_high, ".root"));
  fname.Prepend(coutput_common);
  frecord = new TFile(fname, "recreate");

  TFile* foutput[3];

  TH1F* hOS[4];
  TFile* fweight[2] ={
    new TFile(Form("./data/Zmu_OS_%iTeV.root", erg_tev)),
    new TFile(Form("./data/Ze_OS_%iTeV.root", erg_tev))
  };
  hOS[0] = (TH1F*)fweight[0]->Get("h1D_FRmu_EB");
  hOS[1] = (TH1F*)fweight[0]->Get("h1D_FRmu_EE");
  hOS[2] = (TH1F*)fweight[1]->Get("h1D_FRel_EB");
  hOS[3] = (TH1F*)fweight[1]->Get("h1D_FRel_EE");

  frecord->cd();

  TString hname = "htemp";

  float GenHMass;
  float ZXfake_weight,MC_weight,MC_weight_QQBZZEWK;
  int CRflag;
  float Lep1combRelIsoPF, Lep2combRelIsoPF, Lep3combRelIsoPF, Lep4combRelIsoPF;
  bool Lep1isID, Lep2isID, Lep3isID, Lep4isID;
  short Z1ids;
  short Z2ids;
  float PFMET;

  float Lep1_Z1SIP, Lep2_Z1SIP, Lep3_Z1SIP, Lep4_Z1SIP;
  float Lep1SIP, Lep2SIP, Lep3SIP, Lep4SIP;
  int Lep1ID, Lep2ID, Lep3ID, Lep4ID;

  float Z1Mass, Z2Mass, ZZMass, ZZPt, ZZEta, ZZPhi;
  float KalmanCandVtx_x, KalmanCandVtx_y, KalmanCandVtx_z, KalmanCandVtx_chi2;
  float OfflinePrimaryVtx_x, OfflinePrimaryVtx_y, OfflinePrimaryVtx_z;

  float Lep1Pt, Lep2Pt, Lep3Pt, Lep4Pt;
  float Lep1Eta, Lep2Eta, Lep3Eta, Lep4Eta;

  tc->SetBranchAddress("ZXfake_weight", &ZXfake_weight);
  tc->SetBranchAddress("CRflag", &CRflag);

  tc->SetBranchAddress("Z1ids", &Z1ids);
  tc->SetBranchAddress("Z2ids", &Z2ids);
  tc->SetBranchAddress("Lep1ID", &Lep1ID);
  tc->SetBranchAddress("Lep1isID", &Lep1isID);
  tc->SetBranchAddress("Lep1combRelIsoPF", &Lep1combRelIsoPF);
  tc->SetBranchAddress("Lep2ID", &Lep2ID);
  tc->SetBranchAddress("Lep2isID", &Lep2isID);
  tc->SetBranchAddress("Lep2combRelIsoPF", &Lep2combRelIsoPF);
  tc->SetBranchAddress("Lep3ID", &Lep3ID);
  tc->SetBranchAddress("Lep3isID", &Lep3isID);
  tc->SetBranchAddress("Lep3combRelIsoPF", &Lep3combRelIsoPF);

  tc->SetBranchAddress("PFMET", &PFMET);
  tc->SetBranchAddress("Z1Mass", &Z1Mass);
  tc->SetBranchAddress("Z2Mass", &Z2Mass);
  tc->SetBranchAddress("ZZMass", &ZZMass);
  tc->SetBranchAddress("ZZPt", &ZZPt);
  tc->SetBranchAddress("ZZEta", &ZZEta);
  tc->SetBranchAddress("ZZPhi", &ZZPhi);
  tc->SetBranchAddress("OfflinePrimaryVtx_x", &OfflinePrimaryVtx_x);
  tc->SetBranchAddress("OfflinePrimaryVtx_y", &OfflinePrimaryVtx_y);
  tc->SetBranchAddress("OfflinePrimaryVtx_z", &OfflinePrimaryVtx_z);
  tc->SetBranchAddress("KalmanCandVtx_x", &KalmanCandVtx_x);
  tc->SetBranchAddress("KalmanCandVtx_y", &KalmanCandVtx_y);
  tc->SetBranchAddress("KalmanCandVtx_z", &KalmanCandVtx_z);

  tc->SetBranchAddress("Lep1Pt", &Lep1Pt);
  tc->SetBranchAddress("Lep2Pt", &Lep2Pt);
  tc->SetBranchAddress("Lep3Pt", &Lep3Pt);
  tc->SetBranchAddress("Lep1Eta", &Lep1Eta);
  tc->SetBranchAddress("Lep2Eta", &Lep2Eta);
  tc->SetBranchAddress("Lep3Eta", &Lep3Eta);


  tc->SetBranchAddress("KalmanCandVtx_chi2", &KalmanCandVtx_chi2);
  tc->SetBranchAddress("Lep1_Z1SIP", &Lep1_Z1SIP);
  tc->SetBranchAddress("Lep2_Z1SIP", &Lep2_Z1SIP);
  tc->SetBranchAddress("Lep3_Z1SIP", &Lep3_Z1SIP);
  tc->SetBranchAddress("Lep1SIP", &Lep1SIP);
  tc->SetBranchAddress("Lep2SIP", &Lep2SIP);
  tc->SetBranchAddress("Lep3SIP", &Lep3SIP);

  if (iCR!=1){
    tc->SetBranchAddress("Lep4ID", &Lep4ID);
    tc->SetBranchAddress("Lep4isID", &Lep4isID);
    tc->SetBranchAddress("Lep4combRelIsoPF", &Lep4combRelIsoPF);
    tc->SetBranchAddress("Lep4_Z1SIP", &Lep4_Z1SIP);
    tc->SetBranchAddress("Lep4SIP", &Lep4SIP);
    tc->SetBranchAddress("Lep4Pt", &Lep4Pt);
    tc->SetBranchAddress("Lep4Eta", &Lep4Eta);
  }
  if (iCR==2){
    tc->SetBranchAddress("MC_weight", &MC_weight);
    tc->SetBranchAddress("GenHMass", &GenHMass);
  }

  for (int iwgt=0; iwgt<2; iwgt++){
    if (iCR==1 && iwgt==1) continue;
    for (int isocut=0; isocut<4; isocut++){
      if (iCR==1 && isocut>=2) continue;
      if (isocut<2) continue;

      for (int iM1cut=0; iM1cut<1; iM1cut++){
        if (iM1cut==2 && iCR!=1) continue;
        if (iwgt==0) cout << "Un-weighted";
        else cout << "Weighted";
        if (isocut>=1) cout << ", " << strLepIsoCut_label[isocut-1];
        cout << ", " << Z1masswidth_label[iM1cut] << endl;
        cout << "\t"; for (int icut=0; icut<nSIPCuts; icut++) cout << cutLabel[icut] << '\t' << cutLabel[icut] << " Error\t";
        cout << endl;
        for (int catZ1=0; catZ1<2; catZ1++){
          for (int catZ2=0; catZ2<(iCR!=1 ? 3 : 2); catZ2++){
//          for (int catZ2=0; catZ2<(iCR!=1 ? 6 : 2); catZ2++){
            cout << strZ1Category_label[catZ1] << " ";
            if (iCR!=1) cout << strZ2Category_label[catZ2];
            else cout << strLep3Category_label[catZ2];
            for (int icut=0; icut<nSIPCuts; icut++){
              gStyle->SetTitleFont(62, "t");
              gROOT->SetStyle(gStyle->GetName());
              gROOT->ForceStyle();

              TH1F* hsip = new TH1F(hname, "", 1, 0, 1000);
              hsip->Sumw2();

              double ptbins[9]={ 0, 5, 7, 10, 20, 30, 40, 50, 80 };
              double etabins[3]={ 0, 1.2, 2.5 };
              if ((iCR==1 && catZ2==1) || (iCR!=1 && (catZ2==2 || catZ2==3))) etabins[1]=1.45;

//              const int nbinsTxy = 60;
//              double Txybins[nbinsTxy+1];
//              for (int bin=0; bin<=nbinsTxy; bin++)Txybins[bin] = -1400.+2800.*bin/nbinsTxy;
              const int nbinsTxy = 7;
              double Txybins[nbinsTxy+1]={-2000,-500,-200,-50,50,200,500,2000};
/*              const int nbinsmZZ = 4;
              double mZZbins[nbinsmZZ+1]={ 100, 140.6, 170, 250, m4l_high };
              const int nbinsmZ1 = 10;
              double mZ1bins[nbinsmZ1+1];
              for (int bin=0; bin<=nbinsmZ1; bin++)mZ1bins[bin] = 0.+120.*bin/nbinsmZ1;
              const int nbinsmZ2 = 6;
              double mZ2bins[nbinsmZ2+1];
              for (int bin=0; bin<=nbinsmZ2; bin++)mZ2bins[bin] = 12.+132.*bin/nbinsmZ2;
*/
              const int nbinsmZZ = 4;
              double mZZbins[nbinsmZZ+1]={ 0, 100, 140, 170, 3000 };
              const int nbinsmZ1 = 5;
              double mZ1bins[nbinsmZ1+1]={ 0, 40, 62.5, 85, 97.5, 120 };
              const int nbinsmZ2 = 3;
              double mZ2bins[nbinsmZ2+1]={ 0, 35, 65, 150 };

              TH2F* hmZZTxyOS;
              TH2F* hmZZTxyOS_extra;
              TH3F* hmZZmZ1mZ2OS;
              TH3F* hmZZmZ1mZ2OS_extra;
              if (iCR!=1 && isocut>1 && catZ2<3){
                hmZZTxyOS = new TH2F(produceCRname(iCR, iwgt, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_Txy_OS"), "", nbinsmZZ, mZZbins, nbinsTxy, Txybins);
                hmZZTxyOS->Sumw2();
                hmZZTxyOS->SetXTitle("m_{4l} (GeV)");
                hmZZTxyOS->SetYTitle("T_{xy} (#mum)");
                hmZZTxyOS->SetZTitle("Events / bin");
                hmZZTxyOS->SetOption("colz");

                hmZZmZ1mZ2OS = new TH3F(produceCRname(iCR, iwgt, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_mZ1mZ2_OS"), "", nbinsmZZ, mZZbins, nbinsmZ1, mZ1bins, nbinsmZ2, mZ2bins);
                hmZZmZ1mZ2OS->Sumw2();
                hmZZmZ1mZ2OS->SetXTitle("m_{4l} (GeV)");
                hmZZmZ1mZ2OS->SetYTitle("m_{1} (GeV)");
                hmZZmZ1mZ2OS->SetZTitle("m_{2} (GeV)");
                hmZZmZ1mZ2OS->SetOption("box");
                if (isocut==2 && iwgt>0){
                  hmZZTxyOS_extra = new TH2F(produceCRname(iCR, iwgt, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_Txy_OS_2p2fin3p1f"), "", nbinsmZZ, mZZbins, nbinsTxy, Txybins);
                  hmZZTxyOS_extra->Sumw2();
                  hmZZTxyOS_extra->SetXTitle("m_{4l} (GeV)");
                  hmZZTxyOS_extra->SetYTitle("T_{xy} (#mum)");
                  hmZZTxyOS_extra->SetZTitle("Events / bin");
                  hmZZTxyOS_extra->SetOption("colz");

                  hmZZmZ1mZ2OS_extra = new TH3F(produceCRname(iCR, iwgt, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_mZ1mZ2_OS_2p2fin3p1f"), "", nbinsmZZ, mZZbins, nbinsmZ1, mZ1bins, nbinsmZ2, mZ2bins);
                  hmZZmZ1mZ2OS_extra->Sumw2();
                  hmZZmZ1mZ2OS_extra->SetXTitle("m_{4l} (GeV)");
                  hmZZmZ1mZ2OS_extra->SetYTitle("m_{1} (GeV)");
                  hmZZmZ1mZ2OS_extra->SetZTitle("m_{2} (GeV)");
                  hmZZmZ1mZ2OS_extra->SetOption("box");
                }
              }


              for (int ev=0; ev<tc->GetEntries(); ev++){
                MC_weight=1;
                MC_weight_QQBZZEWK=1;
                
                tc->GetEntry(ev);

                if (iCR==2){
                  MC_weight*=my_luminosity;
                  MC_weight_QQBZZEWK = getQQZZEWKCorrection(GenHMass);
                  MC_weight*=MC_weight_QQBZZEWK;
                  ZXfake_weight = ZXfake_weight*MC_weight;
                }

                int option[7]={
                  iCR, icut, catZ1, catZ2, iwgt, isocut, iM1cut
                };
                int LepID[4]={
                  Lep1ID, Lep2ID, Lep3ID, Lep4ID
                };
                float Lep_Z1SIP[4]={
                  Lep1_Z1SIP, Lep2_Z1SIP, Lep3_Z1SIP, Lep4_Z1SIP
                };
                float LepSIP[4]={
                  Lep1SIP, Lep2SIP, Lep3SIP, Lep4SIP
                };

                float wgt = applyCRselection(
                  option,

                  m4l_low, m4l_high,

                  CRflag,
                  Lep1combRelIsoPF, Lep2combRelIsoPF, Lep3combRelIsoPF, Lep4combRelIsoPF,
                  Lep1isID, Lep2isID, Lep3isID, Lep4isID,
                  Z1ids,
                  Z2ids,
                  PFMET,

                  Lep_Z1SIP,
                  KalmanCandVtx_chi2,
                  LepSIP,
                  LepID,

                  Z1Mass, ZZMass,

                  1
//                  ZXfake_weight
                  );
                if (wgt==0) continue;
                float wgterror=0;


                float strdraw = Z1Mass;

                float strdraw_Txy = ((KalmanCandVtx_x - OfflinePrimaryVtx_x)*cos(ZZPhi) + (KalmanCandVtx_x - OfflinePrimaryVtx_x)*sin(ZZPhi))*10000.0*ZZMass / ZZPt;
                float strdraw_mZZ = ZZMass;
                float strdraw_mZ1 = Z1Mass;
                float strdraw_mZ2 = Z2Mass;
                float strdraw_pteta_ld[2] ={
                  fabs(Lep3Eta), Lep3Pt
                };
                float strdraw_pteta_subld[2] ={
                  fabs(Lep4Eta), Lep4Pt
                };
                if (iCR!=1 && Lep3Pt<=Lep4Pt){
                  strdraw_pteta_ld[0] = fabs(Lep4Eta);
                  strdraw_pteta_ld[1] = fabs(Lep4Pt);
                  strdraw_pteta_subld[0] = fabs(Lep3Eta);
                  strdraw_pteta_subld[1] = fabs(Lep3Pt);
                }

                float OSSFweight[2] ={ 0 };
                float OSSFweighterror[2] ={ 0 };
                if (iCR!=1 && isocut>1 && catZ2<3 && wgt>0){

                  OSSFweight[0] = applyOSSFweight(
                    hOS, // Zmu, Zmu, Ze, Ze (B, E)

                    CRflag,
                    Z1ids, Z2ids,
                    Lep3combRelIsoPF,
                    Lep3isID,

                    Lep3ID,
                    Lep3Pt,
                    Lep3Eta,

                    OSSFweighterror[0]
                    );

                  OSSFweight[1] = applyOSSFweight(
                    hOS, // Zmu, Zmu, Ze, Ze (B, E)

                    CRflag,
                    Z1ids, Z2ids,
                    Lep4combRelIsoPF,
                    Lep4isID,

                    Lep4ID,
                    Lep4Pt,
                    Lep4Eta,

                    OSSFweighterror[1]
                    );

                  if (isocut==2 && (OSSFweight[0]==0 || OSSFweight[1]==0)) cout << "WARNING: 2p2f OSSF weights are not all positive!" << endl;
                  if (isocut==3 && (OSSFweight[0]==0 && OSSFweight[1]==0)) cout << "WARNING: 3p1f OSSF weights are all zero!" << endl;
                  if (isocut==3 && (OSSFweight[0]!=0 && OSSFweight[1]!=0)) cout << "WARNING: 3p1f OSSF weights are all non-zero!" << endl;

                  float totalOS = 1;
                  float sumOS = 0;

                  float totalOSerror=0;
                  float sumOSerror=0;

                  if (iwgt>0){
                    if (OSSFweight[0]>0){
                      totalOS *= OSSFweight[0];
                      totalOSerror += pow(OSSFweighterror[0]/OSSFweight[0], 2);
                    }
                    if (OSSFweight[1]>0){
                      totalOS *= OSSFweight[1];
                      totalOSerror += pow(OSSFweighterror[1]/OSSFweight[1], 2);
                    }
                    totalOSerror = sqrt(totalOSerror) * totalOS;
                    if (isocut==2){
                      sumOS = OSSFweight[0] + OSSFweight[1];
                      sumOSerror = sqrt(pow(OSSFweighterror[0], 2) + pow(OSSFweighterror[1], 2));
                    }
                    if (iCR==2){
                      totalOS*=MC_weight;
                      sumOS*=MC_weight;
                      totalOSerror*=MC_weight;
                      sumOSerror*=MC_weight;
                    }
                    wgt = totalOS;
                    wgterror = totalOSerror;
                  }
                  else{
                    if (iCR==2){
                      totalOS*=MC_weight;
                      sumOS*=MC_weight;
                    }
                  }

                  hmZZTxyOS->Fill(strdraw_mZZ, strdraw_Txy, totalOS);
                  hmZZmZ1mZ2OS->Fill(strdraw_mZZ, strdraw_mZ1, strdraw_mZ2, totalOS);

                  if (iwgt>0){
/*
                    int binx = hmZZTxyOS->GetXaxis()->FindBin(strdraw_mZZ);
                    int biny = hmZZTxyOS->GetYaxis()->FindBin(strdraw_Txy);
                    hmZZTxyOS->SetBinError(binx, biny, sqrt(pow(hmZZTxyOS->GetBinError(binx, biny), 2)+pow(totalOSerror, 2)));

                    binx = hmZZmZ1mZ2OS->GetXaxis()->FindBin(strdraw_mZZ);
                    biny = hmZZmZ1mZ2OS->GetYaxis()->FindBin(strdraw_mZ1);
                    int binz = hmZZmZ1mZ2OS->GetZaxis()->FindBin(strdraw_mZ2);
                    hmZZmZ1mZ2OS->SetBinError(binx, biny, binz, sqrt(pow(hmZZmZ1mZ2OS->GetBinError(binx, biny, binz), 2)+pow(totalOSerror, 2)));
*/
                    if (isocut==2){
                      hmZZTxyOS_extra->Fill(strdraw_mZZ, strdraw_Txy, sumOS);
                      hmZZmZ1mZ2OS_extra->Fill(strdraw_mZZ, strdraw_mZ1, strdraw_mZ2, sumOS);
/*
                      int binx = hmZZTxyOS_extra->GetXaxis()->FindBin(strdraw_mZZ);
                      int biny = hmZZTxyOS_extra->GetYaxis()->FindBin(strdraw_Txy);
                      hmZZTxyOS_extra->SetBinError(binx, biny, sqrt(pow(hmZZTxyOS_extra->GetBinError(binx, biny), 2)+pow(sumOSerror, 2)));

                      binx = hmZZmZ1mZ2OS_extra->GetXaxis()->FindBin(strdraw_mZZ);
                      biny = hmZZmZ1mZ2OS_extra->GetYaxis()->FindBin(strdraw_mZ1);
                      int binz = hmZZmZ1mZ2OS_extra->GetZaxis()->FindBin(strdraw_mZ2);
                      hmZZmZ1mZ2OS_extra->SetBinError(binx, biny, binz, sqrt(pow(hmZZmZ1mZ2OS_extra->GetBinError(binx, biny, binz), 2)+pow(sumOSerror, 2)));
*/
                    }
                  }

                }

                hsip->Fill(strdraw, wgt);
                if (iwgt>0){
                  int binx = hsip->GetXaxis()->FindBin(strdraw);
                  hsip->SetBinError(binx, sqrt(pow(hsip->GetBinError(binx), 2)+pow(wgterror, 2)));
                }

              }

              if (iCR!=1 && isocut>1 && catZ2<3){
                frecord->WriteTObject(hmZZTxyOS);
                delete hmZZTxyOS;
                frecord->WriteTObject(hmZZmZ1mZ2OS);
                delete hmZZmZ1mZ2OS;
                if (isocut==2 && iwgt>0){
                  frecord->WriteTObject(hmZZTxyOS_extra);
                  delete hmZZTxyOS_extra;
                  frecord->WriteTObject(hmZZmZ1mZ2OS_extra);
                  delete hmZZmZ1mZ2OS_extra;
                }
              }

              double totalerror = 0;
              double totalintegral = hsip->IntegralAndError(1,hsip->GetNbinsX(),totalerror);

              cout << '\t' << totalintegral << '\t' << totalerror;

              delete hsip;
            }
            cout << endl;
          }
        }
        cout << endl;
      }
      cout << endl;
    }
    cout << endl;
  }
  delete tc;

  for (int ww=0; ww<2; ww++) fweight[ww]->Close();
  frecord->Close();
}
bool createPlot(TString hname, TString dirname, TFile *V1file, TString runstring1, TString relstring1, TFile *V2file, TString runstring2, TString relstring2, TCanvas *canvas, int scale) {
  setTDRStyle();

  int SetScale = scale;

  //IF =0 --> No scale applied ('direct' comparison)
  //IF =1 --> Scale INDIVIDUALLY (scale histograms individually) 
  //IF =2 --> Scale all GLOBALLY (scale all histograms to #tracks=1)
  //IF =3 --> Scale all GLOBALLY nEVENTS (scale all histos to nEntries in nTracks per Event)

  bool DrawRatio = true;
  canvas->cd();
  TPad* mainpad = new TPad("mainpad","mainpad",0.0,0.0,1.0,0.8);
  mainpad->Draw();
  mainpad->cd();

  // ************ Get name of histos and get histos ************* //

  if (dirname.Contains("GeneralProperties/GoodTracks",TString::kExact)){
    if ((hname != "FractionOfGoodTracks") && (hname != "NumberOfGoodTracks")){
      hname.Prepend("GoodTrack");
    }
  }
  
  TString basename1 = "DQMData/Run ";
  basename1.Append(runstring1);

  TString hnameV1 = basename1;
  hnameV1.Append(dirname+"/");
  hnameV1.Append(hname);

  if (hname != "vtxNbr"){
    hnameV1.Append("_GenTk");
  }

  TH1F * hBinTempV1 = (TH1F*)V1file->Get(hnameV1);
  if ( hBinTempV1 == (TH1F*) NULL ) {
    cout << "histV1 failed on " << hnameV1  << endl << " for file " << V1file->GetName() << endl;
    exit(1);
  }

  TString basename2 = "DQMData/Run ";
  basename2.Append(runstring2);

  TString hnameV2 = basename2;
  hnameV2.Append(dirname+"/");
  hnameV2.Append(hname);
  
  if (hname != "vtxNbr"){
    hnameV2.Append("_GenTk");
  }

  TH1F * hBinTempV2 = (TH1F*)V2file->Get(hnameV2);
  if ( hBinTempV2 == (TH1F*) NULL ) {
    cout << "histV2 failed on " << hnameV2  << endl << " for file " << V2file->GetName() << endl;
    exit(1);
  }

  // Check that bins match for ratio plot

  TH1F * histV1 = 0;
  TH1F * histV2 = 0;

  Double_t h1_xlow = hBinTempV1->GetXaxis()->GetBinLowEdge(hBinTempV1->GetXaxis()->GetFirst());
  Double_t h2_xlow = hBinTempV2->GetXaxis()->GetBinLowEdge(hBinTempV2->GetXaxis()->GetFirst());

  Double_t h1_xup = hBinTempV1->GetXaxis()->GetBinUpEdge(hBinTempV1->GetXaxis()->GetLast());
  Double_t h2_xup = hBinTempV2->GetXaxis()->GetBinUpEdge(hBinTempV2->GetXaxis()->GetLast());

  Int_t h1_nbins = hBinTempV1->GetNbinsX();
  Int_t h2_nbins = hBinTempV2->GetNbinsX();

  Double_t h1_binWidth = (h1_xup - h1_xlow) / (Double_t)h1_nbins;
  Double_t h2_binWidth = (h2_xup - h2_xlow) / (Double_t)h2_nbins;

  if ((h1_xlow == h2_xlow) && (h1_xup == h2_xup) && (h1_binWidth == h2_binWidth)){
    histV1 = (TH1F*)V1file->Get(hnameV1);
    histV2 = (TH1F*)V2file->Get(hnameV2);
  }
  else if((h1_xlow == h2_xlow) && (h1_xup < h2_xup) && (h1_binWidth == h2_binWidth)){ // Fill h1 from h1xlow to h1high with h1 info, and up to h2high, fill zero 
    histV2 = (TH1F*)V2file->Get(hnameV2); // copy histV2 

    histV1 = new TH1F(hBinTempV1->GetName(),hBinTempV1->GetTitle(),h2_nbins,h2_xlow,h2_xup);
    histV1->SetXTitle(hBinTempV1->GetXaxis()->GetTitle());
    histV1->SetYTitle(hBinTempV1->GetYaxis()->GetTitle());
    for (Int_t ibin = 1; ibin <= h2_nbins; ibin++){
      if (ibin <= h1_nbins){
	histV1->SetBinContent(ibin,hBinTempV1->GetBinContent(ibin));
      }
      else if (ibin > h1_nbins){
	histV1->SetBinContent(ibin,0.0); 
      }
    }
  }
  else if((h1_xlow == h2_xlow) && (h1_xup > h2_xup) && (h1_binWidth == h2_binWidth)){ // Fill h1 from h1xlow to h1high with h1 info, and up to h2high, fill zero 
    histV1 = (TH1F*)V1file->Get(hnameV1); // copy histV1 

    histV2 = new TH1F(hBinTempV2->GetName(),hBinTempV2->GetTitle(),h1_nbins,h1_xlow,h1_xup);
    histV2->SetXTitle(hBinTempV2->GetXaxis()->GetTitle());
    histV2->SetYTitle(hBinTempV2->GetYaxis()->GetTitle());
    for (Int_t ibin = 1; ibin <= h1_nbins; ibin++){
      if (ibin <= h2_nbins){
	histV2->SetBinContent(ibin,hBinTempV2->GetBinContent(ibin));
      }
      else if (ibin > h2_nbins){
	histV2->SetBinContent(ibin,0.0); 
      }
    }
  }
  else{
    cout << "Bin Check Failed... here's what happened: " << endl;
    cout << "histV1 failed on " << hnameV1  << endl << " for file " << V1file->GetName() << endl;
    cout << "       bin info: " << h1_xlow << " " << h1_xup << " " << h1_nbins << endl;
    cout << "histV2 failed on " << hnameV2  << endl << " for file " << V2file->GetName() << endl;
    cout << "       bin info: " << h2_xlow << " " << h2_xup << " " << h2_nbins << endl;
    exit(1);
  }

  // Don't look at zero bin -- > Also could use this for truncation and bin setting -->Range is binlower to upper
  //  Int_t range_upper = histV1->GetXaxis()->GetLast();
  //  histV1->GetXaxis()->SetRangeUser(1,range_upper);
  //  histV2->GetXaxis()->SetRangeUser(1,range_upper);

  //******************* Get histo integrals ***********************//
  double V1_integral = 1.0;
  double V2_integral = 1.0;

  TH1F * hNormTempV1 = 0;
  TH1F * hNormTempV2 = 0;

  if (SetScale==1){    
    V1_integral = histV1->Integral();
    V2_integral = histV2->Integral();
  }
  else if ( (SetScale==2) || (SetScale==3) ){
    if (hname != "NumberOfTracks"){
      TString hTempNameV1 = basename1;
      hTempNameV1.Append("/Tracking/Run summary/TrackParameters/GeneralProperties/NumberOfTracks_GenTk");
      hNormTempV1 = (TH1F*)V1file->Get(hTempNameV1);
      
      TString hTempNameV2 = basename2;
      hTempNameV2.Append("/Tracking/Run summary/TrackParameters/GeneralProperties/NumberOfTracks_GenTk");
      hNormTempV2 = (TH1F*)V2file->Get(hTempNameV2);
    }
    else{
      hNormTempV1 = (TH1F*)histV1->Clone("hNormTempV1");
      hNormTempV2 = (TH1F*)histV2->Clone("hNormTempV2");
    }

    if (SetScale==2){
      V1_integral = hNormTempV1->GetBinContent(2);
      V2_integral = hNormTempV2->GetBinContent(2);

      std::cout << "The number of single tracks for V1 is " << V1_integral << std::endl;
      std::cout << "The number of single tracks for V2 is " << V2_integral << std::endl;
    }
    else if (SetScale==3){
      V1_integral = hNormTempV1->GetEntries();
      V2_integral = hNormTempV2->GetEntries();

      std::cout << "The number of events for V1 is " << V1_integral << std::endl;
      std::cout << "The number of events for V2 is " << V2_integral << std::endl;
    }
  }

  //*****NORMALIZING V1-V2****************************************

  if(V1_integral>V2_integral) {
    histV1->Scale(V2_integral / V1_integral);
    histV2->Scale(1);
  } 
  else if(V2_integral>V1_integral){
    histV1->Scale(1);
    histV2->Scale(V1_integral / V2_integral);
  }

  //*****NORMALIZING V1-V2*end***************************************

  //***Name the files under comparison***
  TString V1_V1run = "Run "+runstring1+" ("+relstring1+")";
  TString V2_V2run = "Run "+runstring2+" ("+relstring2+")";

  histV1->SetName(V1_V1run);
  histV2->SetName(V2_V2run);

  double max = 0;
  double V1max = histV1->GetBinContent(histV1->GetMaximumBin());
  double V2max = histV2->GetBinContent(histV2->GetMaximumBin());

  max = (V1max>V2max) ? V1max : V2max;
  histV1->Draw();
  histV1->SetLineStyle(1);
  histV1->GetYaxis()->SetLabelSize(0.038);
  histV1->SetLineWidth(5);
  histV1->SetLineColor(kRed);
  histV1->SetMaximum(max*(1.1));
  histV2->Draw();
  histV2->SetLineWidth(3);
  histV2->SetLineStyle(1);
  histV2->SetLineColor(kBlue);



  if( hname.Contains("NumberOfTracks",TString::kExact)
      || hname.Contains("NumberOfGoodTracks",TString::kExact)
      || hname.Contains("TrackPt",TString::kExact)
      || hname.Contains("Chi2Prob",TString::kExact)
      ){
    mainpad->SetLogy(1);
  }
  else{
    mainpad->SetLogy(0);
  }

  if (hname.Contains("NumberOfTracks",TString::kExact)){
    histV1->GetXaxis()->SetRangeUser(0,500);
    histV2->GetXaxis()->SetRangeUser(0,500);
  }
  
  if (hname.Contains("NumberOfGoodTracks",TString::kExact)) {
    histV1->GetXaxis()->SetRangeUser(0,200);
    histV2->GetXaxis()->SetRangeUser(0,200);
  }

  if (hname.Contains("Chi2oNDF",TString::kExact)) {
    histV1->GetXaxis()->SetRangeUser(0,10);
    histV2->GetXaxis()->SetRangeUser(0,10);
  }

  if (hname.Contains("vtxNbr")){
    histV1->GetXaxis()->SetTitle("Number of Primary Vertices per Event");
    histV1->GetYaxis()->SetTitle("Number of Events");
  }

  histV1->Draw(); // Draw old histo first, ratio is new/old
  histV2->Draw("sames");

  mainpad->Update();

  TPaveStats *st1 = (TPaveStats*)(histV1->GetListOfFunctions()->FindObject("stats"));

  st1->SetX1NDC(0.77);
  st1->SetY1NDC(0.80);

  st1->SetX2NDC(0.98);
  st1->SetY2NDC(0.97);
  Double_t defaulth = st1->GetY2NDC() - st1->GetY1NDC();
  Double_t gaph = 0.02;
  TPaveStats *st2 = (TPaveStats*)(histV2->GetListOfFunctions()->FindObject("stats"));
  st2->SetX1NDC(0.77);  
  st2->SetY1NDC(st1->GetY1NDC() - 1.0*defaulth - gaph);
  st2->SetX2NDC(0.98);    
  st2->SetY2NDC(st1->GetY1NDC() - gaph);

  TLegend *leg = new TLegend(0.32,0.86,0.76,0.97);
  leg->SetTextSize(0.042);
  leg->SetTextFont(42);
  leg->SetFillColor(10); 
  leg->SetBorderSize(1); // no frame, no shadow
  leg->AddEntry(histV1, V1_V1run, "L" );
  leg->AddEntry(histV2, V2_V2run, "L" );
  leg->Draw("SAME");

  // Draw ratio histogram
  if (DrawRatio){
    canvas->cd();
    TPad* respad = new TPad("respad","respad",0.0,0.78,1.0,0.95);
    respad->SetTopMargin(1.05);
    respad->Draw();
    respad->cd();
    TH1F* hratio = (TH1F*) histV2->Clone("hratio");
    hratio->Divide(histV1);
    hratio->SetMaximum(hratio->GetMaximum()*1.1);
    hratio->SetMinimum(hratio->GetMinimum()/1.1);
    //if (hratio->GetMinimum()==0.0) hratio->SetMinimum(1.0/hratio->GetMaximum());
    //    hratio->SetMinimum(1.0/hratio->GetMaximum());
    hratio->GetYaxis()->SetLabelSize(0.1);
    //    hratio->GetYaxis()->SetRangeUser(0,2);
    hratio->GetXaxis()->SetLabelSize(0);
    hratio->GetXaxis()->SetTitleSize(0);
    hratio->GetYaxis()->SetTitleSize(0.22);
    hratio->GetYaxis()->SetTitleOffset(0.26);
    hratio->GetYaxis()->SetLabelSize(0.2);
    hratio->GetYaxis()->SetNdivisions(5);
    hratio->GetYaxis()->SetTitle("NEW/REF");
    hratio->Draw();
  }

  // Compare parameters of histograms
  double Entries1 = histV1->GetEntries();
  double Entries2 = histV2->GetEntries();
  if (Entries1 != Entries2) {
    std::cout<<" Difference in # of ENTRIES for " <<hname<< std::endl;
    std::cout<<"\t Entries1 = " << Entries1 << "\t Entries2 = " << Entries2 << std::endl;
  }

  double Mean1 = histV1->GetMean();
  double Mean2 = histV2->GetMean();
  if (Mean1 != Mean2) {
    std::cout<<" Difference in MEANS for " <<hname<< std::endl;
    std::cout<<"\t Mean1 = " << Mean1 << "\t Mean2 = " << Mean2 << std::endl;
  }

  double RMS1 = histV1->GetRMS();
  double RMS2 = histV2->GetRMS();
  if (RMS1 != RMS2) {
    std::cout<<" Difference in RMS for " <<hname<< std::endl;
    std::cout<<"\t RMS1 = " << RMS1 << "\t RMS2 = " << RMS2 << std::endl;
  }

  TString filename = hname;

  if (hname.Contains("vtxNbr")){
    filename = "NumberOfPrimaryVertices";
  }

  if (dirname.Contains("GeneralProperties/GoodTracks",TString::kExact))
    filename.Prepend("RunComparison/GoodTracks_");
  else filename.Prepend("RunComparison/");

  filename.Append(".png");

  canvas->Print(filename);

  if ( histV1 ) {histV1->Delete();}
  if ( histV2 ) {histV2->Delete();}

  if ( hNormTempV1 ) {hNormTempV1->Delete();}
  if ( hNormTempV2 ) {hNormTempV2->Delete();}

  //  if ( hBinTempV1 ) {hBinTempV1->Delete();} // why cant this work?! 
  //  if ( hBinTempV2 ) {hBinTempV2->Delete();}

  return true;
}
void combineOSWeights(int erg_tev, double m4l_low, double m4l_high){
  TString erg_dir;
  erg_dir.Form("LHC_%iTeV", erg_tev);
  TString comstring;
  comstring.Form("%iTeV", erg_tev);

  TString cinput_common = user_dir_hep + "Analysis/Auxiliary/";
  TString coutput_common = user_dir_hep + "Analysis/Auxiliary/";

  TFile* finput[2];
  for (int iCR=0; iCR<2; iCR++){
    TString fname = "OSfakeweights_";
    if (iCR==0) fname.Append("ZLL_");
    else fname.Append("QQBZZ_");
    fname += comstring;
    fname.Append(Form("_m4l_%.1f_%.1f%s", m4l_low, m4l_high, ".root"));
    fname.Prepend(cinput_common);
    finput[iCR] = new TFile(fname, "read");
  }

  TString coutput = "OSfakeweights_AfterCorrection_";
  coutput += comstring;
  coutput.Prepend(coutput_common);
  coutput.Append(".root");
  TFile* foutput = new TFile(coutput, "recreate");

  TH3F* hOSweight_ZLL_unweighted[nSIPCuts][3*2];
  TH3F* hOSweight_ZLL_2p2fin3p1f[nSIPCuts][3*2];
  TH3F* hOSweight_ZLL_weighted[nSIPCuts][3*2];
  TH3F* hOSweight_qqZZ[nSIPCuts][3*2];
  TH3F* hOSweight_3p1fFinal[nSIPCuts][3*2];

  int iM1cut=0;
  int isocut=3;
  for (int icut=0; icut<nSIPCuts; icut++){
    for (int catZ1=0; catZ1<2; catZ1++){
      for (int catZ2=0; catZ2<3; catZ2++){
        int index_catZ = 3*catZ1+catZ2;
        TString strOSweight_ZLL_unweighted = produceCRname(0, 0, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_mZ1mZ2_OS");
        TString strOSweight_ZLL_2p2fin3p1f = produceCRname(0, 1, 2, iM1cut, catZ1, catZ2, icut, "mZZ_mZ1mZ2_OS_2p2fin3p1f");
        TString strOSweight_ZLL_weighted = produceCRname(0, 1, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_mZ1mZ2_OS");
        TString strOSweight_qqZZ = produceCRname(2, 0, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_mZ1mZ2_OS");

        cout << strOSweight_ZLL_unweighted << endl;
        hOSweight_ZLL_unweighted[icut][index_catZ] = (TH3F*)finput[0]->Get(strOSweight_ZLL_unweighted);
        cout << strOSweight_ZLL_2p2fin3p1f << endl;
        hOSweight_ZLL_2p2fin3p1f[icut][index_catZ] = (TH3F*)finput[0]->Get(strOSweight_ZLL_2p2fin3p1f);
        cout << strOSweight_ZLL_weighted << endl;
        hOSweight_ZLL_weighted[icut][index_catZ] = (TH3F*)finput[0]->Get(strOSweight_ZLL_weighted);
        cout << strOSweight_qqZZ << endl;
        hOSweight_qqZZ[icut][index_catZ] = (TH3F*)finput[1]->Get(strOSweight_qqZZ);
/*
        cout << "Nbins hOSweight_ZLL_unweighted: " << hOSweight_ZLL_unweighted[icut][index_catZ]->GetNbinsX()*hOSweight_ZLL_unweighted[icut][index_catZ]->GetNbinsY()*hOSweight_ZLL_unweighted[icut][index_catZ]->GetNbinsZ() << endl;
        cout << "Nbins hOSweight_ZLL_2p2fin3p1f: " << hOSweight_ZLL_2p2fin3p1f[icut][index_catZ]->GetNbinsX()*hOSweight_ZLL_2p2fin3p1f[icut][index_catZ]->GetNbinsY()*hOSweight_ZLL_2p2fin3p1f[icut][index_catZ]->GetNbinsZ() << endl;
        cout << "Nbins hOSweight_ZLL_weighted: " << hOSweight_ZLL_weighted[icut][index_catZ]->GetNbinsX()*hOSweight_ZLL_weighted[icut][index_catZ]->GetNbinsY()*hOSweight_ZLL_weighted[icut][index_catZ]->GetNbinsZ() << endl;
        cout << "Nbins hOSweight_qqZZ: " << hOSweight_qqZZ[icut][index_catZ]->GetNbinsX()*hOSweight_qqZZ[icut][index_catZ]->GetNbinsY()*hOSweight_qqZZ[icut][index_catZ]->GetNbinsZ() << endl;
*/
        TString strOSweight_3p1fFinal = "OSfakeweight_";
        if (catZ1==0) strOSweight_3p1fFinal.Append("_Zmumu");
        else strOSweight_3p1fFinal.Append("_Zee");
        if (catZ2==0) strOSweight_3p1fFinal.Append("_mumuOS");
        else if (catZ2==1) strOSweight_3p1fFinal.Append("_emuOS");
        else if (catZ2==2) strOSweight_3p1fFinal.Append("_eeOS");
        strOSweight_3p1fFinal.Append("_");
        strOSweight_3p1fFinal += cutNames[icut];
        strOSweight_3p1fFinal.Append("_");
        strOSweight_3p1fFinal += strLepIsoCut_label[isocut-1];

        hOSweight_3p1fFinal[icut][index_catZ] = (TH3F*)hOSweight_ZLL_weighted[icut][index_catZ]->Clone(strOSweight_3p1fFinal);
        hOSweight_3p1fFinal[icut][index_catZ]->Sumw2();
        for (int binz=0; binz<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsZ()+1; binz++){
          for (int biny=0; biny<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsY()+1; biny++){
            for (int binx=0; binx<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsX()+1; binx++){
              hOSweight_3p1fFinal[icut][index_catZ]->SetBinContent(binx, biny, binz, 1);
              hOSweight_3p1fFinal[icut][index_catZ]->SetBinError(binx, biny, binz, 0);
            }
          }
        }

        for (int binz=0; binz<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsZ()+1; binz++){
          for (int biny=0; biny<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsY()+1; biny++){
            for (int binx=0; binx<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsX()+1; binx++){
              hOSweight_ZLL_unweighted[icut][index_catZ]->SetBinError(binx, biny, binz, 0);
              hOSweight_ZLL_2p2fin3p1f[icut][index_catZ]->SetBinError(binx, biny, binz, 0);
            }
          }
        }

        hOSweight_qqZZ[icut][index_catZ]->Divide(hOSweight_ZLL_unweighted[icut][index_catZ]);
        hOSweight_ZLL_2p2fin3p1f[icut][index_catZ]->Divide(hOSweight_ZLL_unweighted[icut][index_catZ]);
        hOSweight_3p1fFinal[icut][index_catZ]->Add(hOSweight_qqZZ[icut][index_catZ], -1);
        hOSweight_3p1fFinal[icut][index_catZ]->Add(hOSweight_ZLL_2p2fin3p1f[icut][index_catZ], -1);
        int nzeros=0;
        for (int binz=0; binz<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsZ()+1; binz++){
          for (int biny=0; biny<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsY()+1; biny++){
            for (int binx=0; binx<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsX()+1; binx++){
              double bincontent = hOSweight_3p1fFinal[icut][index_catZ]->GetBinContent(binx, biny, binz);
              double binerror = hOSweight_3p1fFinal[icut][index_catZ]->GetBinError(binx, biny, binz);

              if (binerror>=fabs(bincontent)){
                cout << "Bin error larger than content: " << strOSweight_3p1fFinal << '\t' << bincontent << '\t' << binerror
                  << '\t' << hOSweight_3p1fFinal[icut][index_catZ]->GetXaxis()->GetBinCenter(binx)
                  << '\t' << hOSweight_3p1fFinal[icut][index_catZ]->GetYaxis()->GetBinCenter(biny)
                  << '\t' << hOSweight_3p1fFinal[icut][index_catZ]->GetZaxis()->GetBinCenter(binz)
                  << endl;
              }

              if (bincontent<0){
                cout << "Bin content <0: " << strOSweight_3p1fFinal << '\t' << bincontent
                  << '\t' << hOSweight_3p1fFinal[icut][index_catZ]->GetXaxis()->GetBinCenter(binx)
                  << '\t' << hOSweight_3p1fFinal[icut][index_catZ]->GetYaxis()->GetBinCenter(biny)
                  << '\t' << hOSweight_3p1fFinal[icut][index_catZ]->GetZaxis()->GetBinCenter(binz)
                  << endl;
                hOSweight_3p1fFinal[icut][index_catZ]->SetBinContent(binx, biny, binz,0);
                hOSweight_3p1fFinal[icut][index_catZ]->SetBinError(binx, biny, binz, (fabs(bincontent)>binerror?bincontent:binerror));
              }
              if (bincontent<1 && bincontent>0)nzeros++;
            }
          }
        }

        cout << "Nvalid: " << nzeros << '/' << hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsX()*hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsY()*hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsZ() << endl;

        hOSweight_ZLL_weighted[icut][index_catZ]->Multiply(hOSweight_3p1fFinal[icut][index_catZ]);
        hOSweight_ZLL_weighted[icut][index_catZ]->SetName(Form("%s_corrected", hOSweight_ZLL_weighted[icut][index_catZ]->GetName()));
        foutput->WriteTObject(hOSweight_3p1fFinal[icut][index_catZ]);
        foutput->WriteTObject(hOSweight_ZLL_weighted[icut][index_catZ]);
      }
    }
  }

  TH1F* hOS[4];
  TFile* fweight[2] ={
    new TFile(Form("./data/Zmu_OS_%iTeV.root", erg_tev)),
    new TFile(Form("./data/Ze_OS_%iTeV.root", erg_tev))
  };
  hOS[0] = (TH1F*)fweight[0]->Get("h1D_FRmu_EB");
  hOS[1] = (TH1F*)fweight[0]->Get("h1D_FRmu_EE");
  hOS[2] = (TH1F*)fweight[1]->Get("h1D_FRel_EB");
  hOS[3] = (TH1F*)fweight[1]->Get("h1D_FRel_EE");
  hOS[0]->SetName("Zmu_Barrel_FakeRate");
  hOS[1]->SetName("Zmu_Endcap_FakeRate");
  hOS[2]->SetName("Ze_Barrel_FakeRate");
  hOS[3]->SetName("Ze_Endcap_FakeRate");

  for (int hh=0; hh<4; hh++) foutput->WriteTObject(hOS[hh]);
  for (int hh=0; hh<2; hh++) fweight[hh]->Close();



  foutput->Close();
  for (int iCR=0; iCR<2; iCR++) finput[iCR]->Close();
}
Example #25
0
void MakePIDqaReport(const char* inputFile, const char* outputFile="PIDqaReport.pdf", TString dirInFile = "")
{
  //
  // Make a pdf file with the efficiency report
  //

  LoadLibs();
  SetupStyle();

  TFile f(inputFile);
  if (!f.IsOpen()){
    printf("Could not open file '%s'\n",f.GetName());
    return;
  }
  
  TString listName = "PIDqa";
  if (dirInFile != "")
    listName = listName.Prepend(Form("%s/", dirInFile.Data()));
  
  printf("%s", listName.Data());
  TList *qaList = (TList*) f.Get(listName.Data());
  if (!qaList){
    printf("Could not find list '%s' in file '%s'\n",listName.Data(), f.GetName());
    return;
  }

  fCanvas=new TCanvas;

  TPDF p(outputFile);

  //
  // Invariant mass plots
  //


  //
  // Make QA info
  //

  // ITS PID
  PublishCanvas(qaList,"ITS","hNsigmaP_ITS_%s");

  // TPC PID
  TList *qaListTPC = (TList*)qaList->FindObject("TPC");
  if (qaListTPC){
    PublishCanvas(qaListTPC,"TPCBasic","hNsigmaP_TPC_Basic_%s");
    PublishCanvas(qaListTPC,"TPCV0","hNsigmaP_TPC_V0_%s");
    //   if (man->GetCurrentPeriod()=="11h"){
      //     PublishCanvas(qaListTPC,"TPC","hNsigmaP_TPC_Basic_%s_Hybrid","Hybrid");
    //     PublishCanvas(qaListTPC,"TPC","hNsigmaP_TPC_Basic_%s_OROChigh","OROChigh");
    //   }
  }
  else {
    printf("Could not find list '%s/TPC' in file '%s'\n", listName.Data(), f.GetName());
  }

  // TPC PID after 3 sigma TOF cut
  PublishCanvas(qaList,"TPC_TOF","hNsigmaP_TPC_TOF_%s");

  // TOF PID
  PublishCanvas(qaList,"TOF","hNsigmaP_TOF_%s");

  // TRD PID
  fCanvas->Divide(2,3);
  TH2 *hLikeP_TRD_3tls_electron=Get2DHistogramfromList(qaList,"TRD","hLikeP_TRD_3tls_electron");
  TH2 *hLikeP_TRD_3tls_pion=Get2DHistogramfromList(qaList,"TRD","hLikeP_TRD_3tls_pion");
  TH2 *hLikeP_TRD_4tls_electron=Get2DHistogramfromList(qaList,"TRD","hLikeP_TRD_4tls_electron");
  TH2 *hLikeP_TRD_4tls_pion=Get2DHistogramfromList(qaList,"TRD","hLikeP_TRD_4tls_pion");
  TH2 *hLikeP_TRD_5tls_electron=Get2DHistogramfromList(qaList,"TRD","hLikeP_TRD_5tls_electron");
  TH2 *hLikeP_TRD_5tls_pion=Get2DHistogramfromList(qaList,"TRD","hLikeP_TRD_5tls_pion");

  /*
   *  cTRDnsigma[countcanvas]->cd(1);
   *  TPaveText pt3TRD(.02,.02,.49,.52);
   *  pt3TRD.SetTextAlign(11);
   *  pt3TRD.SetTextSizePixels(16);
   *  pt3TRD.AddText(Form(" TRD PID QA %s.%s.%d", first.Data(), man->GetCurrentPeriod().Data(), pass));
   *  pt3TRD.Draw();
   */
  fCanvas->cd(1);
  SetupPadStyle();
  hLikeP_TRD_3tls_electron->Draw("colz");
  fCanvas->cd(2);
  SetupPadStyle();
  hLikeP_TRD_3tls_pion->Draw("colz");
  fCanvas->cd(3);
  SetupPadStyle();
  hLikeP_TRD_4tls_electron->Draw("colz");
  fCanvas->cd(4);
  SetupPadStyle();
  hLikeP_TRD_4tls_pion->Draw("colz");
  fCanvas->cd(5);
  SetupPadStyle();
  hLikeP_TRD_5tls_electron->Draw("colz");
  fCanvas->cd(6);
  SetupPadStyle();
  hLikeP_TRD_5tls_pion->Draw("colz");

  fCanvas->Update();
  fCanvas->Clear();

  // TPC Response info
  TObjArray *qaInfo=(TObjArray*)qaList->FindObject("QAinfo");
  TObjArray *tpcInfo=0x0;
  if (qaInfo && (tpcInfo=(TObjArray*)qaInfo->FindObject("TPC_info"))){
    TObjArray *tpcSplineInfo=(TObjArray*)tpcInfo->FindObject("TPC_spline_names");
    TObjArray *tpcConfigInfo=(TObjArray*)tpcInfo->FindObject("TPC_config_info");
    fCanvas->Divide(1,2);
  
    TPaveText pt(.1,.1,.9,.9,"NDC");
    pt.SetBorderSize(1);
    pt.SetFillColor(0);
    pt.SetTextSizePixels(16);

    if (tpcSplineInfo){
      for (Int_t i=0; i<tpcSplineInfo->GetEntriesFast();++i) pt.AddText(tpcSplineInfo->At(i)->GetName());
    }
    
    TPaveText pt2(.1,.1,.9,.9,"NDC");
    pt2.SetBorderSize(1);
    pt2.SetFillColor(0);
    pt2.SetTextSizePixels(16);
    if (tpcConfigInfo){
      for (Int_t i=0; i<tpcConfigInfo->GetEntriesFast();++i) pt2.AddText(tpcConfigInfo->At(i)->GetName());
    }

    fCanvas->cd(1);
    pt.Draw();
    fCanvas->cd(2);
    pt2.Draw();
    
    fCanvas->Update();
    fCanvas->Clear();
  }
  
  delete qaList;

  p.Close();
  delete fCanvas;
}
Example #26
0
int MC_Ratio(int leptonId, double par_low, double par_upp, int nbins, TString sel_den , TString sel_num, double cut_den = 0., double cut_num = 0., TString par_x = "Pt", TString option = ""){

	setTDRStyle();

	///////////////
	//Get the TTree
	///////////////

	//Location of the .root file
	TString location = "/Users/GLP/Desktop/CERN_data/2014-11-13_skim2ll-mva-softbtag/postprocessed/";

	//Reading the tree 
	//
	TChain* tree = new TChain("treeProducerSusyMultilepton");

	//DY events
	tree->Add(location+"DYJetsToLLM50_PU_S14_POSTLS170.root");

	//Plot the result

	Long64_t n = tree->GetEntries();

	//Path for input and output file. Written in FitDataPath.txt
	TString _path = "/Users/GLP/Dropbox/Physique/Master_Thesis/plots_root/MC_ratio/";

	//////////////////////
	//Name for the plots//
	//////////////////////

	TString pname;
	TString _pname;
	TString _par;
	TString _sel_num;
	TString _sel_den;
	TString _cut_den;
	TString _option;

	//Writing string
	if (leptonId == 11) {pname = "e";_pname = "e";}
	else if (leptonId == 13){pname = " #mu";_pname = "mu";}
	if(par_x == "Pt"){_par = "P_{t}";}
	else if(par_x == "eta"){_par = "#eta";}
	else if(par_x == "phi"){_par = "#phi";}
	else{cout<<"ERROR: wrong parameter name !";return 1;}
	if(sel_num == ""){_sel_num = "unsel";}
	else if(sel_num == "tight"){_sel_num = "tight";}
	else if(sel_num == "tightmva"){_sel_num = "tightmva";}
	if((sel_num == "tightmva")&&(leptonId == 13)){cout<<"ERROR: no tightId MVA defined for the muon !";return 1;}
	//else if(sel_num == "mvaid"){_sel_num = Form("tightmva%0.3lf",cut_num) ;}
	else if(sel_num == "loose"){_sel_num = "loose";}
	else if(sel_num == "reliso3"){_sel_num = Form("reliso3_%0.3lf",cut_num);}
	else if(sel_num == "reliso4"){_sel_num = Form("reliso4_%0.3lf",cut_num);}
	else if(sel_num == "chiso3"){_sel_num = Form("chiso3_%0.3lf",cut_num);}
	else if(sel_num == "chiso4"){_sel_num = Form("chiso4_%0.3lf",cut_num);}
	else if(sel_num == "dxy"){_sel_num = Form("dxy_%0.3lf",cut_num);}
	else if(sel_num == "dz"){_sel_num = Form("dz_%0.3lf",cut_num);}
	else{cout<<"ERROR: wrong numerator name !";return 1;}
	//Selection on the denominator
	if(sel_den == ""){_sel_den = "unsel";}
	else if(sel_den == "tight"){_sel_den = "tight";}
	else if(sel_den == "tightmva"){_sel_den = "tightmva";}
	if((sel_den == "tightmva")&&(leptonId == 13)){cout<<"ERROR: no tightId MVA defined for the muon !";return 1;}
	//else if(sel_den == "mvaid"){_sel_den = Form("tightmva%0.3lf",cut_den) ;}
	else if(sel_den == "loose"){_sel_den = "loose";}
	else{cout<<"ERROR: wrong denominator selection name !";return 1;}
	option.Append(" ");
	option.Prepend(" ");
	if(option.Contains(" ll ")){_option += "_ll";}
	if(option.Contains(" unmatched ")){_option += "_unmatched";}
	if(option.Contains(" alleta ")){_option += "_alleta";}
	_option += "_";

	//Name of the output

	//TString _fname = file_name("eff3",leptonId, par_low,par_upp,sel_den,sel_num,cut_den,cut_num,par_x,option);
	//TString _output= _path+_fname + ".root";
	TString _output = _path+"eff4"+_option+_pname+"_den_"+_sel_den+"_num_"+_sel_num+"_"+par_x+".root";

	//Declaration of histogram
	
	//
	//Preparation for general range in eta/pt
	//TH1D **histo_num = new TH1D*[nrange];
	//TH1D **histo_den = new TH1D*[nrange];
	//TH1D **eff = new TH1D*[nrange];
	//int nrange = 3;
	//double par2[nrange] = {0,1.2,2.4};
	//for(int _i = 0; _i < nrange; ++_i){ 

	//	//Barrel
	//	histo_num[_i] = new TH1D("histo_num","Pt",nbins,min(par_low,0.),par_upp);
	//	histo_den[_i] = new TH1D("histo_den","Pt",nbins,min(par_low,0.),par_upp);
	//	eff[_i] = new TH1D("eff","Pt",nbins,min(par_low,0.),par_upp);
	//	
	//}
	
	
	//efficiency of the isolation cut
	TH1D *histo_numB= new TH1D("histo_numB","Pt",nbins,min(par_low,0.),par_upp);
	TH1D *histo_denB= new TH1D("histo_denB","Pt",nbins,min(par_low,0.),par_upp);
	TH1D *histo_numE= new TH1D("histo_numE","Pt",nbins,min(par_low,0.),par_upp);
	TH1D *histo_denE= new TH1D("histo_denE","Pt",nbins,min(par_low,0.),par_upp);

	//Histo in all eta region
	TH1D *histo_num= new TH1D("histo_num","Pt",nbins,min(par_low,0.),par_upp);
	TH1D *histo_den= new TH1D("histo_den","Pt",nbins,min(par_low,0.),par_upp);

	//efficiency of the selection
	TH1D* effB = new TH1D ("effB","Pt",nbins,min(par_low,0.),par_upp);
	TH1D* effE = new TH1D ("effE","Pt",nbins,min(par_low,0.),par_upp);

	//efficiency all eta 
	TH1D* eff = new TH1D ("eff","Pt",nbins,min(par_low,0.),par_upp);k
	//Event variables
	Int_t evt_id;
	Float_t scale;
	//Generated
	Float_t gen_phi[200];
	Float_t gen_eta[200];
	Float_t Pt[200];
	Float_t m[200];
	Int_t Id[200];
	Int_t Mo[200];
	Float_t charge[200];
	Int_t status[200];
	Int_t GrMa[200];
	Int_t ngenPart;
	Int_t source[200];
	Int_t pile_up;
	//not loose
	Int_t On;
	Int_t Oid[200];
	Float_t Opt[200];
	Float_t Om[200];
	Float_t Oeta[200];
	Float_t Ophi[200];
	Int_t   Oq[200];
	Int_t Otight[200];
	Int_t Otighte[200];
	//Float_t Omvaid[200];
	Int_t Oloose[200];
	Float_t Oiso3[200];
	Float_t Oiso4[200];
	Float_t Ochiso3[200];
	Float_t Ochiso4[200];
	Float_t Odxy[200];
	Float_t Odz[200];
	//loose
	Int_t Gn;
	Int_t Gid[200];
	Float_t Gpt[200];
	Float_t Gm[200];
	Float_t Geta[200];
	Float_t Gphi[200];
	Int_t   Gq[200];
	Int_t Gtight[200];
	Int_t Gtighte[200];
	//Float_t Gmvaid[200];
	Int_t Gloose[200];
	Float_t Giso3[200];
	Float_t Giso4[200];
	Float_t Gchiso3[200];
	Float_t Gchiso4[200];
	Float_t Gdxy[200];
	Float_t Gdz[200];

	//Assigne branches tree->SetBranchAddress("evt_scale1fb", &scale);
	tree->SetBranchAddress("evt_id", &evt_id);
	//generated
	tree->SetBranchAddress("ngenLep", &ngenPart);
	tree->SetBranchAddress("genLep_pdgId", &Id);
	tree->SetBranchAddress("genLep_sourceId", &source);
	tree->SetBranchAddress("genLep_eta", &gen_eta);
	tree->SetBranchAddress("genLep_phi", &gen_phi);
	tree->SetBranchAddress("genLep_pt", &Pt);
	tree->SetBranchAddress("genLep_mass", &m);
	tree->SetBranchAddress("genLep_charge", &charge);
	tree->SetBranchAddress("genLep_status", &status);
	tree->SetBranchAddress("nTrueInt",&pile_up);
	//not loose
	tree->SetBranchAddress("nLepOther",&On);
	tree->SetBranchAddress("LepOther_pdgId",&Oid);
	tree->SetBranchAddress("LepOther_pt",&Opt);
	tree->SetBranchAddress("LepOther_mass",&Om);
	tree->SetBranchAddress("LepOther_eta",&Oeta);
	tree->SetBranchAddress("LepOther_phi",&Ophi);
	tree->SetBranchAddress("LepOther_charge",&Oq);
	tree->SetBranchAddress("LepOther_tightId",&Otight);
	tree->SetBranchAddress("LepOther_eleCutIdCSA14_50ns_v1",&Otighte);
	//tree->SetBranchAddress("LepOther_mvaId",&Omvaid);
	tree->SetBranchAddress("LepOther_looseIdSusy",Oloose);
	tree->SetBranchAddress("LepOther_relIso03",&Oiso3);
	tree->SetBranchAddress("LepOther_relIso04",&Oiso4);
	tree->SetBranchAddress("LepOther_chargedHadRelIso03",&Ochiso3);
	tree->SetBranchAddress("LepOther_chargedHadRelIso04",&Ochiso4);
	tree->SetBranchAddress("LepOther_dxy",&Odxy);
	tree->SetBranchAddress("LepOther_dz",&Odz);
	//Loose
	tree->SetBranchAddress("nLepGood",&Gn);
	tree->SetBranchAddress("LepGood_pdgId",&Gid);
	tree->SetBranchAddress("LepGood_pt",&Gpt);
	tree->SetBranchAddress("LepGood_mass",&Gm);
	tree->SetBranchAddress("LepGood_eta",&Geta);
	tree->SetBranchAddress("LepGood_phi",&Gphi);
	tree->SetBranchAddress("LepGood_charge",&Gq);
	tree->SetBranchAddress("LepGood_tightId",&Gtight);
	tree->SetBranchAddress("LepGood_eleCutIdCSA14_50ns_v1",&Gtighte);
	//tree->SetBranchAddress("LepGood_mvaId",&Gmvaid);
	tree->SetBranchAddress("LepGood_looseIdSusy",&Gloose);
	tree->SetBranchAddress("LepGood_relIso03",&Giso3);
	tree->SetBranchAddress("LepGood_relIso04",&Giso4);
	tree->SetBranchAddress("LepGood_chargedHadRelIso03",&Gchiso3);
	tree->SetBranchAddress("LepGood_chargedHadRelIso04",&Gchiso4);
	tree->SetBranchAddress("LepGood_dxy",&Gdxy);
	tree->SetBranchAddress("LepGood_dz",&Gdz);

	int count = 0;

	//Start loop over all events
	for (int k = 0; k < 100000; ++k) {

		if( 100*(double)k/n> count){cout<<count<<endl;++count;}

		tree->GetEntry(k);

		//loop on loose 
	if(sel_den != "loose"){
		for(int j=0; j<On;++j){
			if((!option.Contains(" ll "))||((option.Contains(" ll "))&&(On == 2)&&(Oid[0] == -Oid[1]))){
				if(abs(Oid[j]) == leptonId){
					if((sel_den != "tight")||((sel_den == "tight")&&(Otight[j] == 1 ))){
					//if((sel_den != "mvaid")||((sel_den == "mvaid")&&(abs(Omvaid[j]) > cut_den))){
						//Veto the EE-EB gape

						//Variable for matching
						double R = 999;
						double delta_P = 999;
						double delta_charge = 999;

						//Parameter on the xaxis

						double par;

						//loop over all generated particles to do the matching
						for (int i = 0; i < ngenPart; ++i) {
							if((abs(Id[i]) == leptonId)&&(status[i]== 1)){ 

								//Electrons selection
								double R2 = DeltaR(gen_eta[i],Oeta[j],gen_phi[i],Ophi[j] );

								//Minimise DeltaR and Fill the other variables
								if (R > R2) {

									R = R2;
									delta_P = abs(Opt[j]-Pt[i])/Pt[i];
									delta_charge = abs(Oq[j] - charge[i]);
								}
							}
						}

						//Choose the parameter to be filled for the eff.
						if(par_x == "Pt"){par = Opt[j];}
						else if(par_x == "eta"){par = Oeta[j];}
						else if(par_x == "phi"){par = Ophi[j];}

						//Fill Pt only for matched events
						if(((R<0.1)&&(delta_P < 0.2)&&(delta_charge < 0.5))||option.Contains("unmat")){
							//Filling the den
									if(option.Contains(" alleta ")){
											histo_den->Fill(par);
											}else{
							if(abs(Oeta[j]) < 1.2){histo_denB->Fill(par);}
							if(abs(Oeta[j]) >= 1.2){histo_denE->Fill(par);}
											}

							//Additional cut on the numerator
							int a = 0;

							if((sel_num == "tight")&&(Otight[j] == 1)){a = 1;}
							if((sel_num == "reliso3")&&(Oiso3[j] <= cut_num)){a = 2;}
							if((sel_num == "reliso4")&&(Oiso4[j] <= cut_num)){a = 3;}
							if((sel_num == "chiso3")&&(Ochiso3[j] <= cut_num)){a = 4;}
							if((sel_num == "chiso4")&&(Ochiso4[j] <= cut_num)){a = 5;}
							if((sel_num == "dxy")&&(abs(Odxy[j]) <= cut_num)){a = 6;}
							if((sel_num == "dz")&&(abs(Odz[j]) <= cut_num)){a = 7;}
							//Never filled here
							if(sel_num == "loose"){a = 8;}
							//cout<<"again, the mva value is"<<abs(Omvaid[j])<<endl;
							//if((sel_num == "mvaid")&&(abs(Omvaid[j]) >= cut_num)){a = 9;}
			

							switch(a){

								case 0:

									break;

								case 1:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
											if(abs(Oeta[j]) < 1.2){histo_numB->Fill(par);}
											if(abs(Oeta[j]) >= 1.2){histo_numE->Fill(par);};
											}
									break;

								case 2:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Oeta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Oeta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
								case 3:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Oeta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Oeta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
								case 4:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Oeta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Oeta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
								case 5:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Oeta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Oeta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
								case 6:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Oeta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Oeta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;

								case 7:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Oeta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Oeta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;

								case 8:
									//Nothing to fill
									break;

								case 9:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Oeta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Oeta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
							}
						}
					}
				}
			}
		}
	}
	//}

		//loop on tight 
		for(int j=0; j<Gn;++j){
			if((!option.Contains(" ll "))||((option.Contains(" ll "))&&(Gn == 2)&&(Gid[0] == -Gid[1]))){
				if(abs(Gid[j]) == leptonId){
					//Cut on the denominator
					if((sel_den != "tight")||((sel_den == "tight")&&(Gtight[j] == 1 ))){
					//if((sel_den != "mvaid")||((sel_den == "mvaid")&&(abs(Gmvaid[j]) > cut_den))){
						//Veto the EE-EB gape

						//Variable for matching
						double R = 999;
						double delta_P = 999;
						double delta_charge = 999;

						//Parameter on the xaxis

						double par;

						//loop over all generated particles to do the matching
						for (int i = 0; i < ngenPart; ++i) {
							if((abs(Id[i]) == leptonId)&&(status[i]== 1)){ 

								//Electrons selection
								double R2 = DeltaR(gen_eta[i],Geta[j],gen_phi[i],Gphi[j] );

								//Minimise DeltaR and Fill the other variables
								if (R > R2) {

									R = R2;
									delta_P = abs(Gpt[j]-Pt[i])/Pt[i];
									delta_charge = abs(Gq[j] - charge[i]);
								}
							}
						}

						//Choose the parameter to be filled for the eff.
						if(par_x == "Pt"){par = Gpt[j];}
						else if(par_x == "eta"){par = Geta[j];}
						else if(par_x == "phi"){par = Gphi[j];}

						//Fill Pt only for matched events
						if(((R<0.1)&&(delta_P < 0.2)&&(delta_charge < 0.5))||option.Contains("unmat")){
							//Filling the den
									if(option.Contains(" alleta ")){
											histo_den->Fill(par);
											}else{
							if(abs(Geta[j]) < 1.2){histo_denB->Fill(par);}
							if(abs(Geta[j]) >= 1.2){histo_denE->Fill(par);}
											}

							//Additional cut on the numerator
							int a = 0;

							if((sel_num == "tight")&&(Gtight[j] == 1)){a = 1;}
							if((sel_num == "reliso3")&&(Giso3[j] <= cut_num)){a = 2;}
							if((sel_num == "reliso4")&&(Giso4[j] <= cut_num)){a = 3;}
							if((sel_num == "chiso3")&&(Gchiso3[j] <= cut_num)){a = 4;}
							if((sel_num == "chiso4")&&(Gchiso4[j] <= cut_num)){a = 5;}
							if((sel_num == "dxy")&&(abs(Gdxy[j]) <= cut_num)){a = 6;}
							if((sel_num == "dz")&&(abs(Gdz[j]) <= cut_num)){a = 7;}
							//Only loose leptons here, so this is filled anyway
							if((sel_num == "loose")){a = 8;}
							//if((sel_num == "mvaid")&&(abs(Gmvaid[j]) >= cut_num)){a = 9;}


							switch(a){

								case 0:

									break;

								case 1:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2){histo_numB->Fill(par);}
									if(abs(Geta[j]) >= 1.2){histo_numE->Fill(par);}
											}
									break;

								case 2:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Geta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
								case 3:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Geta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
								case 4:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Geta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
								case 5:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Geta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
								case 6:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Geta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;

								case 7:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Geta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;

								case 8:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Geta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;

								case 9:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Geta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
							}
						}
					}
				}
			}
		}
	}
	//}

	if(option.Contains(" alleta ")){
	histo_num->Sumw2();
	histo_den->Sumw2();

	//Divide histograms to get the efficiency
	eff->Divide(histo_num,histo_den,1,1,"B"); 

	//Efficiency of the iso cut.
	TCanvas* c = new TCanvas("c","c");
	eff->Draw();
	eff->GetYaxis()->SetTitle("#epsilon");
	eff->GetXaxis()->SetTitle(_par);
	//eff->GetXaxis()->SetRangeUser(0,250);
	eff->SetMarkerStyle(20);
	eff->SetMarkerSize(1);
	eff->SetMarkerColor(4);
	eff->SetLineColor(4);
	eff->SetTitle(_sel_num+" for "+_sel_den+" "+pname);

	//Define the name of the canvas
	TString cname = "eff4"+option+_pname+"_den_"+_sel_den+"_num_"+_sel_num+"_"+par_x;

	c->SaveAs(_path+"PDF/"+cname+".pdf");

	TFile* output = new TFile(_output,"recreate");
	eff->Write("eff");
	output->Close();

	}else{
		//cout<<"Problem"<<endl;

	histo_numB->Sumw2();
	histo_numE->Sumw2();
	histo_denB->Sumw2();
	histo_denE->Sumw2();

	//Divide histograms to get the efficiency
	effB->Divide(histo_numB,histo_denB,1,1,"B"); 
	effE->Divide(histo_numE,histo_denE,1,1,"B"); 

	//Efficiency of the iso cut.
	TCanvas* c1 = new TCanvas("c1","c1");
	effB->Draw();
	effB->GetYaxis()->SetTitle("#epsilon");
	effB->GetXaxis()->SetTitle(_par);
	//effB->GetXaxis()->SetRangeUser(0,250);
	effB->SetMarkerStyle(20);
	effB->SetMarkerSize(1);
	effB->SetMarkerColor(4);
	effB->SetLineColor(4);
	effB->SetTitle(_sel_num+" for "+_sel_den+" "+pname+" #||{#eta}<1.2");
	TCanvas* c2 = new TCanvas("c2","c2");
	effE->Draw();
	effE->GetYaxis()->SetRangeUser(0,1.1);
	effE->GetYaxis()->SetTitle("#epsilon");
	effE->GetXaxis()->SetTitle(_par);
	//effE->GetXaxis()->SetRangeUser(0,250);
	effE->SetMarkerStyle(20);
	effE->SetMarkerSize(1);
	effE->SetMarkerColor(4);
	effE->SetLineColor(4);
	effE->SetTitle(_sel_num+" for "+_sel_den+" "+pname+" #||{#eta}>1.2");

	//Define the name of the canvas
	TString c1name = "eff4"+option+_pname+"_den_"+_sel_den+"_num_"+_sel_num+"_"+par_x+"_eta<1.2";
	TString c2name = "eff4"+option+_pname+"_den_"+_sel_den+"_num_"+_sel_num+"_"+par_x+"_eta>1.2";

	c1->SaveAs(_path+"PDF/"+c1name+".pdf");
	c2->SaveAs(_path+"PDF/"+c2name+".pdf");

	TFile* output = new TFile(_output,"recreate");
	//c1->Write();
	//c2->Write();
	effB->Write("eff_eta<1.2");
	effE->Write("eff_eta>1.2");
	output->Close();

	}

	return 0;

}
Example #27
0
  /** 
   * Analyse the reweighting option string and set options on task
   * appropriately.  The string is a comma or space separated list of
   * what to reweigh and how to do it. 
   *
   * What to reweigh can be specfied using one or more of the strings 
   *
   * - pt  Reweight in pT 
   * - pid Reweight particle abundance of pi, K, proton 
   * - str Reweight particles from strange weak decays 
   *
   * How to reweigh can be specifed as 
   *
   * - + or up   Increase weights (for pt < 0.05 by +30%)
   * - - or down Decrease weights (for pt < 0.05 by -30%)
   * - If none of these are given, then the weights are used as is. 
   * 
   * If pid rewighting is done and one of up or down are given, then
   * one can specify which particle type to reweigh
   *
   * - pi or pion    Reweight (up or down) pions 
   * - K  or kaon    Reweight (up or down) kaons
   * - p  or proton  Reweight (up or down) protons 
   *
   * Note, if PID, with explicit selection of pions, and strangeness
   * reweighting are specified, then the up/down flag applies to both
   * PID reweighting and the strangeness reweighting
   * 
   * @param task The task to modify 
   */
  void SetupReweighting(AliAnalysisTaskSE* task)
  {
    TString sel = fOptions.AsString("reweight");
    sel.ToLower();
    if (sel.IsNull() || sel.BeginsWith("no"))
      return;

    TList       files;
    Int_t       what = 0;
    Int_t       opt  = 0;
    TObjArray*  tokens = sel.Tokenize(", ");
    TIter       next(tokens);
    TObjString* ostr;
    // First find what should be done 
    while ((ostr = static_cast<TObjString*>(next()))) {
      const TString& token = ostr->String();
      
      if      (token.EqualTo("pt"))   {
	what |= 0x1;
	files.Add(new TObjString("REWEIGHTpt.root"));
	Printf("Will reweigh in pT");
      }
      else if (token.EqualTo("pid")) {
	what |= 0x2;
	Printf("Will reweigh particle species");
      }
      else if (token.EqualTo("str"))  {
	what |= 0x4;
	Printf("Will reweight particles from strange weak decays");
      }
    }
    if (what == 0x0) return;
    
    // Now figure out how to do it 
    next.Reset();
    TString part;
    while ((ostr = static_cast<TObjString*>(next()))) {
      const TString& token = ostr->String();
      Int_t aOpt = TMath::Abs(opt);
      if      (token.EqualTo("up")   || token.EqualTo("+")) 
	opt = (aOpt==0 ? +1 : +aOpt); 
      else if (token.EqualTo("down") || token.EqualTo("-"))
	opt = (aOpt==0 ? -1 : -aOpt);
      else if (token.EqualTo("pi")   || token.EqualTo("pion")){
	  opt = 1; part = "pi";
      }
      else if (token.EqualTo("k")    || token.EqualTo("kaon")) {
	opt = 2; part = "ka";
      }
      else if (token.EqualTo("p")    || token.EqualTo("proton")) {	  
	opt = 3; part = "pr";
      }
    }
    if (opt != 0)
      Printf("Will reweigh %s (%c30%% for pT<0.05)",
	     opt < 0 ? "down" : "up", opt < 0 ? '-' : '+');
    if (what & 0x2) {
      if (!part.IsNull()) {
	Printf("Will reweight %s in particular", part.Data());
	part.Prepend("_");
	part.Append(opt < 0 ? "-" : "+");
      }
      files.Add(new TObjString(Form("REWEIGHTpid%s.root", part.Data())));
    }
    if (what & 0x4)
      files.Add(new TObjString(Form("REWEIGHTstr%s.root",
				    opt == -1 ? "-" :
				    opt == +1 ? "+" : "")));
    delete tokens;

    Printf("Setting reweighing flag=0x%x with option=%d", what, opt);
    SetOnTask(task, "ReweightStack", what);
    SetOnTask(task, "ReweightFlag",  opt);

    TIter nextF(&files);
    while ((ostr = static_cast<TObjString*>(nextF()))) {
      Printf("Loading reweighting file %s", ostr->GetName());
      fRailway->LoadAux(ostr->GetName());
    }
  }
//--------------------------------------------------------------------------------------------------
void plot(long int xStart, long int xStop, TString text, TString save)
{
  // Save names (after machine name)
  TString sc1 = TString("lagTime")       + save + TString(".png");
  TString sc2 = TString("downloadSpeed") + save + TString(".png");
  TString sc  = save + (".png");

  // Rates file, pruned by shell script
  TString inName("./requests.txt");

  // File contents
  TString  file, content, version;
  long int n1, tRequest, n2, tReceived, tComplete;
  Double_t size;
  TString  machine;

  // Variables
  Double_t tLag   = 0, tDown   = 0, rate    = 0;
  Double_t maxLag = 0, maxDown = 0, maxRate = 0;

  Int_t nLines = 0, e = 0;
  bool empty = 0;

  printf("\nPreview of input file (%s) contents:\n",inName.Data());

  ifstream input;
  input.open(inName.Data());

  // First loop to find limits
  while (1) {

    // Read file
    input >> file >> content >> version >> n1 >> tRequest >> n2 >> tReceived >> tComplete
	  >> size >> machine;

    // Good file?
    if (! input.good())
      break;

    // During time interval?
    if (xStart > tReceived)
      continue;
    if (xStop  < tReceived)
      continue;

    // Filter invalid older data
    if (rejectT3btch(machine))
      continue;

    appendMachine(machine);

    tLag  = tReceived - tRequest;
    tDown = tComplete - tReceived;

    rate  = size/double(tDown);

    if (tDown <= 0) {
      e++;
      continue;
    }

    if (size <= 0)
      continue;

    // Preview of input file
    if (nLines < 5)
      printf("%s %s %s %d %d %d %d %d %f %s\n",
	     file.Data(),content.Data(),version.Data(),
	     n1,tRequest,n2,tReceived,tComplete,size,machine.Data());

    // Find limits
    if (tLag > maxLag)
      maxLag = tLag;
    if (tDown > maxDown)
      maxDown = tDown;
    if (rate > maxRate)
      maxRate = rate;

    nLines++;
  }
  input.close();

  printf("\n");
  printf("Found %i good requests in interval",nLines);
  printf("\nMaximum download rate [GB/sec] = %f",maxRate);
  printf("\nMaximum time for request receipt [sec] = %f",maxLag);
  printf("\n");
  printf("\nFound %i files with negative download time",e);
  printf("\n");

  // Prepare histograms
  MitRootStyle::Init();
  MitRootStyle::SetStyleWide();
  gStyle->SetPadRightMargin(0.07); // to make sure the exponent is on the picture

  TString hist1("hist1"), hist2("hist2");
  hist1.Prepend(save.Data());
  hist2.Prepend(save.Data());

  TH1D* h1 = new TH1D(hist1.Data(),"Lag time between request and start",100,0,maxLag);
  MitRootStyle::InitHistWide(h1,"","",kBlack);

  TH1D* h2 = new TH1D(hist2.Data(),"Average download speed",100,0,maxRate);
  MitRootStyle::InitHistWide(h2,"","",kBlack);

  const Int_t n = Int_t(machines.size());
  Int_t i = 0;
  Double_t null = 0;

  TH1D* h[n];
  for (int i=0; i<machines.size(); i++) {
    TString machineName = TString(machines[i]);
    machineName.Prepend(save.Data());
    h[i] = new TH1D(machineName.Data(),"Average download speed",100,0,maxRate);
    MitRootStyle::InitHistWide(h[i],"","",kBlack);
  }

  if (nLines < 1) {
    empty   = 1;
    printf("\nFound no good requests in interval :(\n");
    goto go;
  }

  input.open(inName.Data());

  // Second loop to fill histograms
  while (1) {

    // Read file
    input >> file >> content >> version >> n1 >> tRequest >> n2 >> tReceived
	  >> tComplete >> size >> machine;

    // Good file?
    if (! input.good())
      break;

    // During time interval?
    if (xStart > tReceived)
      continue;
    if (xStop 	< tComplete)
      continue;

    // Filter invalid older data
    if (rejectT3btch(machine))
      continue;

    tLag  = tReceived - tRequest;
    tDown = tComplete - tReceived;
    rate  = size/double(tDown);

    if (tDown <= 0)
      continue;

    if (size <= 0)
      continue;

    if (tLag != 0)
      h1->Fill(float(tLag));

    h2->Fill(rate,size);

    for (int i=0; i<machines.size(); i++) {
      TString machineName = TString(machines[i]);
      if (machineName == machine) {
        h[i]->Fill(rate,size);
        break;
      }
    }

    i++;
  }
  input.close();

 go:

  if (empty) {
    h1->Fill(null,null);
    h2->Fill(null,null);
  }

  if (empty) {
    for (int i=0; i<machines.size(); i++) {
      h[i]->Fill(null,null);
    }
  }

  // Draw the histograms, each to its own canvas
  TCanvas *c1 = new TCanvas("c1","Overall lag time between request and receipt");
  TCanvas *c2 = new TCanvas("c2","Overall average download speed");

  c1->cd();
  h1->GetXaxis()->SetTitle("Lag time [sec]");
  h1->GetYaxis()->SetTitle("Number of requests");
  h1->Draw();
  //overlayFrame(TString("t3 cluster"),1);
  overlayFrame(text,0);
  c1->SaveAs(sc1.Data());

  c2->cd();
  h2->GetXaxis()->SetTitle("Speed [GB/sec]");
  h2->GetYaxis()->SetTitle("Data downloaded [GB]");
  h2->Draw();
  overlayFrame(TString("t3 cluster"),1);
  overlayFrame(text,0);
  c2->SaveAs(sc2.Data());

  for (int i=0; i<machines.size(); i++) {
    TString machineName = TString(machines[i]);

    TCanvas *c = new TCanvas("c",machineName.Data());

    TString s = machineName.Append(sc.Data());
    c->cd();
    h[i]->GetXaxis()->SetTitle("Speed [GB/sec]");
    h[i]->GetYaxis()->SetTitle("Data downloaded [GB]");
    h[i]->Draw();
    overlayFrame(TString(machines[i]),1);
    overlayFrame(text,0);
    c->SaveAs(s.Data());
  }

  return;
}
Example #29
0
int MC_Ratio(int leptonId, double* par1, int npar1bins, double* par2, int npar2bins, TString sel_den , TString sel_num, double cut_num , TString par_x , TString par_y , TString option ){

  setTDRStyle();

  ///////////////
  //Get the TTree
  ///////////////

  //Location of the .root file
  TString location2 = "/Users/GLP/Desktop/CERN_data/dyjetsnew/postprocessed/";

  //Reading the tree 
  //
  TChain* tree = new TChain("treeProducerSusyMultilepton");

  //DY events
  //tree->Add(location+"DYJetsToLLM50_PU_S14_POSTLS170.root");
  tree->Add(location2+"dyjets_good.root");

  //Plot the result

  Long64_t n = tree->GetEntries();

  //Path for input and output file. Written in FitDataPath.txt
  TString _path = "/Users/GLP/Dropbox/Physique/Master_Thesis/plots_root/MC_eff/";

  //////////////////////
  //Name for the plots//
  //////////////////////

  TString _filetag = "";

  TString pname;
  TString _pname;
  TString _par;
  TString _sel_num;
  TString _sel_den;
  TString _option;

  ////Writing string
  //particle string
  if(abs(leptonId) == 11){pname = "e"; _pname = "e";}
  if(abs(leptonId) == 13){pname = " #mu"; _pname = "mu";}
  //Parameter string
  if(par_x == "Pt"){_par = "P_{t}";}
  else if(par_x == "eta"){_par = "#eta";}
  else if(par_x == "phi"){_par = "#phi";}
  //sel_den string
  if((sel_den == "tightmva")&&(leptonId == 13)){cout<<"ERROR: no tightId MVA defined for the muon !"<<endl;return 1;}
  if(sel_den == "tightcut"){_sel_den = "tightcut";}
  else if(sel_den == "tightmva"){_sel_den = "tightmva";}
  else if(sel_den == "loose"){_sel_den = "loose";}
  else if(sel_den == ""){_sel_den = "";}
  else{cout<<"ERROR: wrong sel_denion !";return 1;}
  //sel_num string
  if((sel_num == "tightmva")&&(leptonId == 13)){cout<<"ERROR: no tightId MVA defined for the muon !"<<endl;return 1;}
  if(sel_num == "tightcut"){_sel_num = "tightcut";}
  else if(sel_num == "tightmva"){_sel_num = "tightmva";}
  else if(sel_num == ""){_sel_num = "";}
  else if(sel_num == "loose"){_sel_num = "loose";}
  else if(sel_num == "reliso3"){_sel_num = Form("reliso3_%0.3lf",cut_num);}
  else if(sel_num == "reliso4"){_sel_num = Form("reliso4_%0.3lf",cut_num);}
  else if(sel_num == "chiso3"){_sel_num = Form("chiso3_%0.3lf",cut_num);}
  else if(sel_num == "chiso4"){_sel_num = Form("chiso4_%0.3lf",cut_num);}
  else if(sel_num == "dxy"){_sel_num = Form("dxy_%0.3lf",cut_num);}
  else if(sel_num == "dz"){_sel_num = Form("dz_%0.3lf",cut_num);}
  else{cout<<"ERROR: wrong numerator name !";return 1;}
  //option string
  option.Append(" ");
  option.Prepend(" ");
  if(option.Contains(" ll ")){_option += "_ll";}
  if(option.Contains(" unmatched ")){_option += "_unmatched";}
  if(option.Contains(" alleta ")){_option += "_alleta";}
  if(option.Contains(" short ")){_option += "_short";}
  _option += "_";
  //parameter range string
  TString _par1range;
  _par1range = Form("%0.3f_"+par_x+"%0.3f",par1[0],par1[npar1bins]);
  TString _par2range;
  _par2range = Form("%0.3f_"+par_y+"%0.3f",par2[0],par2[npar2bins]);

  /////////////////////////////////////
  //Write the name of the output file//
  /////////////////////////////////////

  TString _fname = "MCeff"+_filetag+_option+_pname+_par1range+"_"+_par2range+"_den_"+_sel_den+"_num_"+_sel_num;

  //Output file
  cout<<"going to create the file"<<endl;
  //Check if the file exists
  TFile *fcheck = TFile::Open(_path+_fname+".root", "READ");
  if (fcheck) {
    cout << "File "<<_fname<<" exists ! Please change name" << endl;
    return 1;
  }

  TFile* file_out = new TFile(_path+_fname+".root","recreate");
  cout<<"done ! "<<endl;

  //Declaration of histogram
  TH1D **histo_num = new TH1D*[npar2bins];
  TH1D **histo_den = new TH1D*[npar2bins];
  TH1D **eff = new TH1D*[npar2bins];


  //Par1 distribution histogram
  TH1D** histo_par1 = new TH1D*[npar2bins];

  //Distribution of the cut parameter whose efficiency is studied
  TH1D *histo_other_sel = new TH1D("histo_other_sel","h",5,0,5);
  TH1D *histo_good_sel = new TH1D("histo_good_sel","h",5,0,5);

//Histo separate in Lep_good Lep_other
  //
  TH1D **histo_num_O = new TH1D*[npar2bins];
  TH1D **histo_den_O = new TH1D*[npar2bins];
  TH1D **eff_O = new TH1D*[npar2bins];
  TH1D **histo_num_G = new TH1D*[npar2bins];
  TH1D **histo_den_G = new TH1D*[npar2bins];
  TH1D **eff_G = new TH1D*[npar2bins];

  //Counter LepGood vs LepOther

  TH1D **histo_counter = new TH1D*[npar2bins];
  TH1D **histo_counter_G_par1 = new TH1D*[npar2bins];
  TH1D **histo_counter_O_par1 = new TH1D*[npar2bins];
  TH1D **histo_counter_par1 = new TH1D*[npar2bins];


  for(int _i = 0; _i < npar2bins; ++_i){ 

    histo_num[_i] = new TH1D("histo_num","Pt",npar1bins,par1[0],par1[npar1bins]);
    histo_den[_i] = new TH1D("histo_den","Pt",npar1bins,par1[0],par1[npar1bins]);
    eff[_i] = new TH1D("eff","Pt",npar1bins,par1[0],par1[npar1bins]);

    //
    histo_par1[_i] = new TH1D("histo_par1","par1",npar1bins*25,par1[0],par1[npar1bins]);

    //
    histo_num_O[_i] = new TH1D("histo_num_O","Pt",npar1bins,par1[0],par1[npar1bins]);
    histo_den_O[_i] = new TH1D("histo_den_O","Pt",npar1bins,par1[0],par1[npar1bins]);
    eff_O[_i] = new TH1D("eff_O","Pt",npar1bins,par1[0],par1[npar1bins]);

    histo_num_G[_i] = new TH1D("histo_num_G","Pt",npar1bins,par1[0],par1[npar1bins]);
    histo_den_G[_i] = new TH1D("histo_den_G","Pt",npar1bins,par1[0],par1[npar1bins]);
    eff_G[_i] = new TH1D("eff_G","Pt",npar1bins,par1[0],par1[npar1bins]);

    histo_counter_G_par1[_i] = new TH1D("histo_counter_G_par1","count",npar1bins,par1[0],par1[npar1bins]);
    histo_counter_O_par1[_i] = new TH1D("histo_counter_O_par1","count",npar1bins,par1[0],par1[npar1bins]);
    histo_counter_par1[_i] = new TH1D("histo_counter_par1","count",npar1bins,par1[0],par1[npar1bins]);

    histo_counter[_i] = new TH1D("histo_counter","count",2,0,2); 

  }

  //Event variables
  Int_t evt_id;
  Double_t scale;
  //Generated
  Double_t gen_phi[200];
  Double_t gen_eta[200];
  Double_t Pt[200];
  Double_t m[200];
  Int_t Id[200];
  Int_t Mo[200];
  Double_t charge[200];
  Int_t status[200];
  Int_t GrMa[200];
  Int_t ngenPart;
  Int_t source[200];
  Int_t pile_up;
  //not loose
  Int_t On;
  Int_t Oid[200];
  Double_t Opt[200];
  Double_t Om[200];
  Double_t Oeta[200];
  Double_t Ophi[200];
  Int_t   Oq[200];
  Int_t Otight[200];
  Int_t Otighte[200];
  //Double_t Omvaid[200];
  Int_t Oloose[200];
  Double_t Oiso3[200];
  Double_t Oiso4[200];
  Double_t Ochiso3[200];
  Double_t Ochiso4[200];
  Double_t Odxy[200];
  Double_t Odz[200];
  //loose
  Int_t 	Gn;
  Int_t 	Gid[200];
  Double_t 	Gpt[200];
  Double_t 	Gm[200];
  Double_t 	Geta[200];
  Double_t 	Gphi[200];
  Int_t   	Gq[200];
  Int_t 	Gtight[200];
  Int_t 	Gtighte[200];
  Int_t 	Gloose[200];
  Double_t 	Giso3[200];
  Double_t 	Giso4[200];
  Double_t 	Gchiso3[200];
  Double_t 	Gchiso4[200];
  Double_t 	Gdxy[200];
  Double_t 	Gdz[200];

  //Assigne branches tree->SetBranchAddress("evt_scale1fb", &scale);
  tree->SetBranchAddress("evt_id", &evt_id);
  //generated
  tree->SetBranchAddress("nGenPart", &ngenPart);
  tree->SetBranchAddress("GenPart_pdgId", &Id);
  tree->SetBranchAddress("GenPart_sourceId", &source);
  tree->SetBranchAddress("GenPart_eta", &gen_eta);
  tree->SetBranchAddress("GenPart_phi", &gen_phi);
  tree->SetBranchAddress("GenPart_pt", &Pt);
  tree->SetBranchAddress("GenPart_mass", &m);
  tree->SetBranchAddress("GenPart_charge", &charge);
  tree->SetBranchAddress("GenPart_status", &status);
  //not loose
  tree->SetBranchAddress("nLepOther",&On);
  tree->SetBranchAddress("LepOther_pdgId",&Oid);
  tree->SetBranchAddress("LepOther_pt",&Opt);
  tree->SetBranchAddress("LepOther_mass",&Om);
  tree->SetBranchAddress("LepOther_eta",&Oeta);
  tree->SetBranchAddress("LepOther_phi",&Ophi);
  tree->SetBranchAddress("LepOther_charge",&Oq);
  tree->SetBranchAddress("LepOther_tightId",&Otight);
  tree->SetBranchAddress("LepOther_eleCutIdCSA14_50ns_v1",&Otighte);
  tree->SetBranchAddress("LepOther_relIso03",&Oiso3);
  tree->SetBranchAddress("LepOther_relIso04",&Oiso4);
  tree->SetBranchAddress("LepOther_chargedHadRelIso03",&Ochiso3);
  tree->SetBranchAddress("LepOther_chargedHadRelIso04",&Ochiso4);
  tree->SetBranchAddress("LepOther_dxy",&Odxy);
  tree->SetBranchAddress("LepOther_dz",&Odz);
  //Loose
  tree->SetBranchAddress("nLepGood",&Gn);
  tree->SetBranchAddress("LepGood_pdgId",&Gid);
  tree->SetBranchAddress("LepGood_pt",&Gpt);
  tree->SetBranchAddress("LepGood_mass",&Gm);
  tree->SetBranchAddress("LepGood_eta",&Geta);
  tree->SetBranchAddress("LepGood_phi",&Gphi);
  tree->SetBranchAddress("LepGood_charge",&Gq);
  tree->SetBranchAddress("LepGood_tightId",&Gtight);
  tree->SetBranchAddress("LepGood_eleCutIdCSA14_50ns_v1",&Gtighte);
  tree->SetBranchAddress("LepGood_relIso03",&Giso3);
  tree->SetBranchAddress("LepGood_relIso04",&Giso4);
  tree->SetBranchAddress("LepGood_chargedHadRelIso03",&Gchiso3);
  tree->SetBranchAddress("LepGood_chargedHadRelIso04",&Gchiso4);
  tree->SetBranchAddress("LepGood_dxy",&Gdxy);
  tree->SetBranchAddress("LepGood_dz",&Gdz);

  int count = 0;

  //Count lepgood/other

  int goodcount = 0;
  int othercount = 0;


  if(option.Contains(" short ")){n = 100000;}

  //Start loop over all events
  for (int k = 0; k < n; ++k) {

    //Declaration of event parameters
    Int_t 	evtn;
    Int_t 	evtloose[200];
    Int_t 	evtid[200];
    Double_t 	evtpt[200];
    Double_t 	evtm[200];
    Double_t 	evteta[200];
    Double_t 	evtphi[200];
    Int_t   	evtq[200];
    Int_t 	evttight[200];
    Int_t 	evttighte[200];
    Double_t 	evtiso3[200];
    Double_t 	evtiso4[200];
    Double_t 	evtchiso3[200];
    Double_t 	evtchiso4[200];
    Double_t 	evtdxy[200];
    Double_t 	evtdz[200];

    if( 100*(double)k/n> count){cout<<count<<endl;++count;}

    tree->GetEntry(k);

    //Selection on denominator
    for(int j = 0; j < Gn+On; ++j){

      //Separate here other from loose
      if(j < On){

        evtloose[j]			  = 0;
        evtid[j]                      = Oid[j];
        evtpt[j]                      = Opt[j];
        evtm[j]                       = Om[j];
        evteta[j]                     = Oeta[j];
        evtphi[j]                     = Ophi[j];
        evtq[j]                       = Oq[j];
        evttight[j]                   = Otight[j];
        evttighte[j]                  = Otighte[j];
        evtiso3[j]                    = Oiso3[j];
        evtiso4[j]                    = Oiso4[j];
        evtchiso3[j]                  = Ochiso3[j];
        evtchiso4[j]                  = Ochiso4[j];
        evtdxy[j]                     = Odxy[j];
        evtdz[j]                      = Odz[j];


      }else if((j >=  On)&&(j < Gn+On)){

        evtloose[j]		       = 1;
        evtid[j]                   = Gid[j-On];
        evtpt[j]                   = Gpt[j-On];
        evtm[j]                    = Gm[j-On];
        evteta[j]                  = Geta[j-On];
        evtphi[j]                  = Gphi[j-On];
        evtq[j]                    = Gq[j-On];
        evttight[j]                = Gtight[j-On];
        evttighte[j]               = Gtighte[j-On];
        evtiso3[j]                 = Giso3[j-On];
        evtiso4[j]                 = Giso4[j-On];
        evtchiso3[j]               = Gchiso3[j-On];
        evtchiso4[j]               = Gchiso4[j-On];
        evtdxy[j]                  = Gdxy[j-On];
        evtdz[j]                   = Gdz[j-On];

      }

      if((!option.Contains(" ll "))||((option.Contains(" ll "))&&(Gn+On == 2)&&(evtq[0] == -evtq[1]))){
	if(abs(evtid[j]) == leptonId){
	  //Cut on the denominator
	  //if((sel_den != "loose")||(evtloose[j] == 1)){
	  //if(evtloose[j] == 1){
	    if((sel_den != "tightcut")||(((abs(evtid[j]) == 13)&&(sel_den == "tightcut")&&(evttight[j] == 1 ))||((abs(evtid[j]) == 11)&&(sel_den == "tightcut")&&(evttighte[j] >= 3)))){
	      if((sel_den != "tightmva")||((abs(evtid[j]) == 11)&&(sel_den == "tightmva")&&(evttight[j] == 1))){
		//Veto the EE-EB gape

		//Variable for matching
		double R = 999;
		double delta_P = 999;
		double delta_charge = 999;

		//Parameter on the xaxis

		double par;
		double par_2;


		//loop over all generated particles to do the matching
		for (int i = 0; i < ngenPart; ++i) {
		  if((abs(Id[i]) == leptonId)){ 

		    //Electrons selection
		    double R2 = DeltaR(gen_eta[i],evteta[j],gen_phi[i],evtphi[j] );

		    //Minimise DeltaR and Fill the other variables
		    if (R > R2) {

		      R = R2;
		      delta_P = abs(evtpt[j]-Pt[i])/Pt[i];
		      delta_charge = abs(evtq[j] - charge[i]);
		    }
		  }
		}

		//Choose the parameter to be filled for the eff.
		if(par_x == "Pt"){par = evtpt[j];}
		else if(par_x == "eta"){par = evteta[j];}
		else if(par_x == "phi"){par = evtphi[j];}
		if(par_y == "Pt"){par_2 = evtpt[j];}
		else if(par_y == "eta"){par_2 = abs(evteta[j]);}
		else if(par_y == "phi"){par_2 = abs(evtphi[j]);}

		//Fill Pt only for matched events
		if(((R<0.1)&&(delta_P < 0.2)&&(delta_charge < 0.5))||option.Contains(" unmatched ")){

		  for(int ii = 0; ii < npar2bins; ++ii){
		    if((par_2 > par2[ii])&&(par_2 <= par2[ii+1])){histo_den[ii]->Fill(par);histo_par1[ii]->Fill(par);
		      
		      if(evtloose[j] == 1){histo_good_sel->Fill(evttighte[j]);}
		      else if(evtloose[j] == 0){histo_other_sel->Fill(evttighte[j]);}
		      else{cout<<"Error !"<<endl; return 1;}
			
			
			}
		  }

		  //Additional cut on the numerator
		  int a = 0;

		  if((sel_num == "tightcut")&&(abs(evtid[j]) == 13)&&(evttight[j] == 1)){a = 1;}
		  if((sel_num == "tightcut")&&(abs(evtid[j]) == 11)&&(evttighte[j] >= 3)){a = 1;}
		  if((sel_num == "reliso3")&&(evtiso3[j] <= cut_num)){a = 2;}
		  if((sel_num == "reliso4")&&(evtiso4[j] <= cut_num)){a = 3;}
		  if((sel_num == "chiso3")&&(evtchiso3[j] <= cut_num)){a = 4;}
		  if((sel_num == "chiso4")&&(evtchiso4[j] <= cut_num)){a = 5;}
		  if((sel_num == "dxy")&&(abs(evtdxy[j]) <= cut_num)){a = 6;}
		  if((sel_num == "dz")&&(abs(evtdz[j]) <= cut_num)){a = 7;}
		  if((sel_num == "tightmva")&&(abs(evtid[j]) == 11)&&(evttight[j] == 1)){a = 9;}
		  if((sel_num == "loose")&&(evtloose[j]) == 1){a = 8;}

		  //Find the corresponding histogram for par2
		  TH1D* hist;
		  TH1D* hist_evt;

		  bool found = false;
		  for(int _i = 0; _i < npar2bins; ++_i){
		    if((par_2 > par2[_i])&&(par_2 <= par2[_i+1])){hist = histo_num[_i];found = true;}
		  }
		  if(!found){a = 0;}

		  switch(a){

		    case 0:

		      break;

		    case 1:
		      hist->Fill(par);
		      break;

		    case 2:
		      hist->Fill(par);
		      break;
		    case 3:
		      hist->Fill(par);
		      break;
		    case 4:
		      hist->Fill(par);
		      break;
		    case 5:
		      hist->Fill(par);
		      break;
		    case 6:
		      hist->Fill(par);
		      break;

		    case 7:
		      hist->Fill(par);
		      break;

		    case 8:
		      hist->Fill(par);
		      break;

		    case 9:
		      hist->Fill(par);
		      break;
		  }
		}
	      }
	    }
	  }
	
	//}
	}
      }
    }

    mkdir(_path+_fname+"_PDF/", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

    ///////////////////
    //Draw histograms//
    ///////////////////

    //Canvas declaration
    for(int i = 0; i < npar2bins; ++i){

      ////////////////////
      //Build histograms//
      ////////////////////

      histo_num[i]->Sumw2();
      histo_den[i]->Sumw2();
      eff[i]->Divide(histo_num[i],histo_den[i],1,1,"B");

      //histo_num_O[i]->Sumw2();
      //histo_den_O[i]->Sumw2();
      //eff_O[i]->Divide(histo_num_O[i],histo_den_O[i],1,1,"B");

      //histo_num_G[i]->Sumw2();
      //histo_den_G[i]->Sumw2();
      //eff_G[i]->Divide(histo_num_G[i],histo_den_G[i],1,1,"B");

      //histo_counter_G_par1[i]->Sumw2();
      //histo_counter_O_par1[i]->Sumw2();
      //histo_counter_par1[i]->Divide(histo_counter_O_par1[i],histo_counter_G_par1[i],1,1,"B");

      //histo_counter[i]->Fill(0.5,goodcount);
      //histo_counter[i]->Fill(1.5,othercount);

      //String for name of the ouput files and histograms titles
      //

      TString _parybin;

      //Parameter string
      if(par_y == "Pt"){_parybin = Form("%0.f_Pt%0.f",par2[i],par2[i+1]);}
      else if(par_y == "eta"){_parybin = Form("%0.3f_eta%0.3f",par2[i],par2[i+1]);cout<<"it works !"<<endl;}
      else if(par_y == "phi"){_parybin = Form("%0.3f_phi%0.3f",par2[i],par2[i+1]);}

      TString _parytitle;

      //Title string
      if(par_y == "Pt"){_parytitle = Form("%0.f #leq P_{t} #leq %0.f",par2[i],par2[i+1]);}
      else if(par_y == "eta"){_parytitle = Form("%0.3f #leq #||{#eta}  #leq %0.3f",par2[i],par2[i+1]);cout<<"it works !"<<endl;}
      else if(par_y == "phi"){_parytitle = Form("%0.3f #leq #||{#phi}  #leq %0.3f",par2[i],par2[i+1]);}

      //Draw histograms
      TCanvas* c1 = new TCanvas("c1","c1");
      c1->cd();
      eff[i]->Draw();
      eff[i]->GetYaxis()->SetTitle("#epsilon");
      eff[i]->GetXaxis()->SetTitle(_par);
      eff[i]->GetYaxis()->SetRangeUser(0,1.1);
      eff[i]->SetMarkerStyle(20);
      eff[i]->SetMarkerSize(1);
      eff[i]->SetMarkerColor(4);
      eff[i]->SetLineColor(4);
      eff[i]->SetTitle(_sel_num+" for "+_sel_den+" "+pname+" "+_parytitle);

      TCanvas* c_par1 = new TCanvas("cpar1","cpar1");
      TString _partitle = _par + (TString)" distribution for "+pname+", "+_parytitle+", "+sel_num;
      c_par1->cd();
      histo_par1[i]->Draw();
      histo_par1[i]->SetTitle(_partitle);
      histo_par1[i]->GetXaxis()->SetTitle(_par);
      histo_par1[i]->SetLineWidth(2);
      histo_par1[i]->SetLineColor(4);
      histo_par1[i]->SetMarkerColor(4);

      histo_good_sel->Add(histo_other_sel);
      TCanvas* csel = new TCanvas("csel","csel");
      csel->cd();
      histo_good_sel->Draw();


      /////////////////////
      //Saving the output//
      /////////////////////

      //Write pdf
      TString cname = "eff"+_filetag+_option+_pname+_par1range+"_"+_parybin+"_den_"+_sel_den+"_num_"+_sel_num;
      c1->SaveAs(_path+_fname+"_PDF/"+cname+".pdf");
      c_par1->SaveAs(_path+_fname+"_PDF/"+cname+"par_distr.pdf");
      csel->SaveAs(_path+_fname+"_PDF/"+cname+"sel.pdf");

      //Write in output file
      file_out->cd();
      eff[i]->Write("eff"+_parybin);
      histo_good_sel->Write("sel"+_parybin);
      //histo_par1[i]->Write("histo_par1_"+_parybin);
      

    }

    file_out->Close();

    return 0;


  }
Example #30
0
void MakeLHCDataEntry(char* storageUri="local://$ALICE_ROOT/../AliRoot/OCDB", Int_t firstRun=0, Int_t lastRun=999999999)
{
  AliCDBManager *cdb = AliCDBManager::Instance();
  cdb->SetDefaultStorage(storageUri);

  // Get time start from the simulated LHCData file
  Double_t timeStart = 0.0;
  Double_t timeEnd = 1.0e+10;

  TString fileName(gSystem->ExpandPathName("$ALICE_ROOT/../AliRoot/GRP/ShuttleInput/testShuttle_GRP_run_number_testShuttle_data.txt"));
  Printf("Getting the file %s", fileName.Data());

  const Int_t fgknLHCDP = 9;   // number of dcs dps from LHC data
  const char* fgkLHCDataPoints[fgknLHCDP] = {
    "LHC_Beam_Energy",
    "LHC_MachineMode",
    "LHC_BeamMode",
    "LHC_Beams_Particle_Type",
    "BPTX_Phase_Shift_B1",
    "BPTX_Phase_Shift_B2",
    "LHC_Particle_Type_B1",
    "LHC_Particle_Type_B2",
    "LHC_Data_Quality_Flag"
  };

  AliGRPObject *grpobj = new AliGRPObject();
	// grpobj->SetBeamEnergyIsSqrtSHalfGeV(); // new format
  //
  //Getting the LHC Data from DCS FXS
  //
  AliLHCReader lhcReader;

  // Processing data to be put in AliGRPObject

		// Energy
		Printf("*************Energy ");
		TObjArray* energyArray = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[0]);
		if (energyArray){			
			Float_t energy = ProcessEnergy(energyArray,timeStart);
			if (energy != -1.) {
				grpobj->SetBeamEnergy(energy);
				grpobj->SetBeamEnergyIsSqrtSHalfGeV(kTRUE);
			}
			delete energyArray;
		}
		else {
			AliError("Energy not found in LHC Data file!!!");
		}	

  Double_t timeBeamModeEnd = timeEnd;        // max validity for Beam Mode 
  Double_t timeMachineModeEnd = timeEnd;     // max validity for Machine Mode
  Double_t timeBeamEnd = timeEnd;            // max validity for Beam Type
  Double_t timeBeamTypeEnd[2] = {timeEnd, timeEnd}; // max validity for Beam Type1,2
  Double_t timeBeamModeStart = -1;    // min validity for Beam Mode
  Double_t timeMachineModeStart = -1; // min validity for Machine Mode
  Double_t timeBeamStart = -1;        // min validity for Beam Type
  Double_t timeBeamTypeStart[2] = {-1,-1};        // min validity for Beam Type1,2
  Int_t indexBeamMode = -1;                  // index of measurement used to set Beam Mode
  Int_t indexMachineMode = -1;               // index of measurement used to set Machine Mode
  Int_t indexBeam = -1;                      // index of measurement used to set Beam Type
  Int_t indexBeamType[2] = {-1, -1};                      // index of measurement used to set Beam Type1,2
  Bool_t foundBeamModeStart = kFALSE;        // flag to be set in case an entry for the Beam Mode is found before (or at) SOR
  Bool_t foundMachineModeStart = kFALSE;     // flag to be set in case an entry for the Machine Mode is found before (or at) SOR
  Bool_t foundBeamStart = kFALSE;            // flag to be set in case an entry for the Beam Type is found before (or at) SOR
  Bool_t foundBeamTypeStart[2] = {kFALSE, kFALSE};            // flag to be set in case an entry for the Beam Type1,2 is found before (or at) SOR
  Bool_t flagBeamMode = kFALSE;  //flag set true if a changed occurred in BeamMode
  Bool_t flagMachineMode = kFALSE;  //flag set true if a changed occurred in MachineMode
  Bool_t flagBeam = kFALSE;  //flag set true if a changed occurred in BeamType
  Bool_t flagBeamType[2] = {kFALSE, kFALSE};  //flag set true if a changed occurred in BeamType1,2

  Double_t arrayTimes[5]={2.E9, 2.E9, 2.E9, 2.E9, 2.E9}; // array to keep track of the times of the possible changes of the LHC DPs; each entry set to Wed May 18 2033, 03:33:20 GMT (ALICE should not be running anymore...)
  // arrayTimes elements order correspond to the one used in the array of the strings fgkLHCDataPoints, i.e.:
  // arrayTimes[0] --> MachineMode
  // arrayTimes[1] --> BeamMode
  // arrayTimes[2] --> BeamType (when written together)
  // arrayTimes[3] --> BeamType1 (when written separate)
  // arrayTimes[4] --> BeamType2 (when written separate)

  // BeamMode
  Printf("*************BeamMode (LHCState) ");
  TObjArray* beamModeArray = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[2]);
  Int_t nBeamMode = -1;
  if (beamModeArray){	
    nBeamMode = beamModeArray->GetEntries();	
    if (nBeamMode==0){
      Printf("Found zero entries for the Beam Mode, leaving it empty");
    }
    else{
      for (Int_t iBeamMode = 0; iBeamMode<nBeamMode; iBeamMode++){
        AliDCSArray* beamMode = (AliDCSArray*)beamModeArray->At(iBeamMode);
        if (beamMode){
          if (beamMode->GetTimeStamp()<=timeStart && beamMode->GetTimeStamp()>=timeBeamModeStart){// taking always the very last entry: of two measurements have the same timestamp, the last one is taken
            timeBeamModeStart = beamMode->GetTimeStamp();
            indexBeamMode = iBeamMode;
            foundBeamModeStart = kTRUE;
          }
          else {
            break;

          }
        }
      }
      if (!foundBeamModeStart){
        Printf("No value for the Beam Mode found before start of run, the Beam Mode will remain empty");
      }
      else {
        AliDCSArray* beamMode = (AliDCSArray*)beamModeArray->At(indexBeamMode);
        TObjString* beamModeString = beamMode->GetStringArray(0);
        Printf(Form("LHC State (corresponding to BeamMode) = %s (set at %f)",(beamModeString->String()).Data(),beamMode->GetTimeStamp()));
        grpobj->SetLHCState(beamModeString->String());
        if (indexBeamMode < nBeamMode-1){
          AliDCSArray* beamMode1 = (AliDCSArray*)beamModeArray->At(indexBeamMode+1);
          if (beamMode1){
            if (beamMode1->GetTimeStamp()<=timeStart){
              Printf("ERROR: you did not choose the correct value! there is still something before (or at) SOR, but later than this!");
            }
            else if (beamMode1->GetTimeStamp()>timeStart && beamMode1->GetTimeStamp()<=timeEnd){
              timeBeamModeEnd = beamMode1->GetTimeStamp();
              TObjString* beamModeString1 = beamMode1->GetStringArray(0);
              TString bmString0 = beamModeString->String();
              TString bmString1 = beamModeString1->String();
              if (bmString0.CompareTo(bmString1.Data(),TString::kIgnoreCase) == -1){
                Printf("WARNING: The beam mode changed from %s to %s during the run at timestamp %f! Setting it to %s and keeping track of the time of the change to set MaxTimeLHCValidity afterward",bmString0.Data(), bmString1.Data(), timeBeamModeEnd, bmString0.Data());
                flagBeamMode = kTRUE;
                arrayTimes[1]=timeBeamModeEnd;

              }
            }
          }
          else {
            Printf("Invalid pointer for the first entry for Beam Mode after the first valid one, not considering anything after what has already been found");
          }
        }
      }
    }
    delete beamModeArray;
  }
  else{
    Printf("ERROR: Beam mode array not found in LHC Data file!!!");
  }
		
  // MachineMode
  Printf("*************MachineMode ");
  TObjArray* machineModeArray = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[1]);
  Int_t nMachineMode = -1;
  if (machineModeArray){
    nMachineMode = machineModeArray->GetEntries();
    if (nMachineMode==0){
      Printf("No Machine Mode found, leaving it empty");
    }
    else{
      for (Int_t iMachineMode = 0; iMachineMode<nMachineMode; iMachineMode++){
        AliDCSArray* machineMode = (AliDCSArray*)machineModeArray->At(iMachineMode);
        if (machineMode){
          if (machineMode->GetTimeStamp()<=timeStart && machineMode->GetTimeStamp()>=timeMachineModeStart){// taking always the very last entry: of two measurements have the same timestamp, the last one is taken
            timeMachineModeStart = machineMode->GetTimeStamp();
            indexMachineMode = iMachineMode;
            foundMachineModeStart = kTRUE;
          }
          else{
            break;
          }
        }
      }
      if (!foundMachineModeStart){
        Printf("No value for the Machine Mode found before start of run, the Machine Mode will remain empty");
      }
      else {
        AliDCSArray* machineMode = (AliDCSArray*)machineModeArray->At(indexMachineMode);
        TObjString* machineModeString = machineMode->GetStringArray(0);
        Printf(Form("MachineMode = %s (set at %f)",(machineModeString->String()).Data(),machineMode->GetTimeStamp()));
        grpobj->SetMachineMode(machineModeString->String());
        if (indexMachineMode < nMachineMode-1){
          AliDCSArray* machineMode1 = (AliDCSArray*)machineModeArray->At(indexMachineMode+1);
          if (machineMode1){
            if (machineMode1->GetTimeStamp()>timeStart && machineMode1->GetTimeStamp()<=timeEnd){
              timeMachineModeEnd = machineMode1->GetTimeStamp();
              TObjString* machineModeString1 = machineMode1->GetStringArray(0);
              TString mmString0 = machineModeString->String();
              TString mmString1 = machineModeString1->String();
              if (mmString0.CompareTo(mmString1.Data(),TString::kIgnoreCase) == -1){
                Printf("WARNING: The machine mode changed from %s to %s during the run at timestamp %f! Setting it to %s and keeping track of the time of the change to set MaxTimeLHCValidity afterward",mmString0.Data(),mmString1.Data(),timeMachineModeEnd,mmString0.Data());
                flagMachineMode = kTRUE;
                arrayTimes[0]=timeMachineModeEnd;
              }
            }
          }
          else {
            Printf("Invalid pointer for the first entry for Machine Mode after the first valid one, not considering anything after what has already been found");
          }
        }
      }
    }
    delete machineModeArray;
  }
  else{
    Printf("ERROR: Machine mode array not found in LHC Data file!!!");
  }

  // BeamType1 and BeamType2 - both put in the same string
  Printf("*************BeamType ");
  TObjArray* beamArray = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[3]);
  if (beamArray){			
    Int_t nBeam = beamArray->GetEntries();
    if (nBeam==0){
      Printf("No Beam Type found, leaving it empty");
    }
    else{
      for (Int_t iBeam = 0; iBeam<nBeam; iBeam++){
        AliDCSArray* beam = (AliDCSArray*)beamArray->At(iBeam);
        if (beam){
          if (beam->GetTimeStamp()<=timeStart && beam->GetTimeStamp()>=timeBeamStart){// taking always the very last entry: of two measurements have the same timestamp, the last one is taken
            timeBeamStart = beam->GetTimeStamp();
            indexBeam = iBeam;
            foundBeamStart = kTRUE;
          }
          else{
            break;
          }
        }
      }
      if (!foundBeamStart){
        Printf("No value for the Beam Type found before start of run, the (common) Beam Type will remain empty");
      }
      else {
        AliDCSArray* beam = (AliDCSArray*)beamArray->At(indexBeam);
        TObjString* beamString = beam->GetStringArray(0);
        TString beamType = beamString->String();
        Printf(Form("Beam Type = %s",beamType.Data()));	
        if (beamType.CompareTo("PROTON",TString::kIgnoreCase) == 0){
          Printf("Setting beam type to p-p");
          grpobj->SetBeamType("p-p");
        }
        else { // if there is no PROTON beam, we suppose it is Pb, and we put A-A
          Printf("Setting beam type to A-A");
          grpobj->SetBeamType("A-A");
        }
        /*
           else if (beamType.CompareTo("LEAD82",TString::kIgnoreCase) == 0){
           Printf("Setting beam type to Pb-Pb");
           grpobj->SetBeamType("Pb-Pb");
           }
           else{
           Printf("ERROR: Beam Type not known, leaving it empty");
           }
           */
        if (indexBeam < nBeam-1){
          AliDCSArray* beam1 = (AliDCSArray*)beamArray->At(indexBeam+1);
          if (beam1){
            if (beam1->GetTimeStamp()>timeStart && beam1->GetTimeStamp()<=timeEnd){
              timeBeamEnd = beam1->GetTimeStamp();
              TObjString* beamString1 = beam1->GetStringArray(0);
              TString beamType1 = beamString1->String();
              if (beamType.CompareTo(beamType1.Data(),TString::kIgnoreCase) == -1){
                Printf("WARNING: The Beam Type changed from %s to %s during the run at timestamp %f! Setting it to %s and keeping track of the time of the change to set MaxTimeLHCValidity afterward",beamType.Data(),(beamString1->String()).Data(),timeBeamEnd,beamType.Data());
                flagBeam = kTRUE;
                arrayTimes[2] = timeBeamEnd;
              }
            }
          }
          else {
            Printf("Invalid pointer for the first entry for Beam Type after the first valid one, not considering anything after what has already been found");
          }
        }
      }
    }
    delete beamArray;
  }
  else{
    Printf("ERROR: Beam Type array not found in LHC Data file!!!");
  }		

  // BeamType1 and BeamType2 - in separete string
  Printf("*************BeamType, 1 and 2 ");
  Int_t indexBeamTypeString = 6;  // index of the string with the alias of BeanType1 in the array fgkLHCDataPoints
  TString combinedBeamType = "-";  // combined beam type, built from beam type 1 and beam type 2
  TString combinedBeamTypeFromLHC = "-";  // combined beam type, built from beam type 1 and beam type 2 AS SENT FROM LHC
  for (Int_t ibeamType = 0; ibeamType<2; ibeamType++){
    beamArray = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[indexBeamTypeString+ibeamType]);
    if (beamArray){			
      Int_t nBeam = beamArray->GetEntries();
      if (nBeam==0){
        Printf(Form("No Beam Type %s found, leaving it empty",fgkLHCDataPoints[indexBeamTypeString+ibeamType]));
      }
      else{
        for (Int_t iBeam = 0; iBeam<nBeam; iBeam++){
          AliDCSArray* beam = (AliDCSArray*)beamArray->At(iBeam);
          if (beam){
            if (beam->GetTimeStamp()<=timeStart && beam->GetTimeStamp()>=timeBeamTypeStart[ibeamType]){// taking always the very last entry: of two measurements have the same timestamp, the last one is taken
              timeBeamTypeStart[ibeamType] = beam->GetTimeStamp();
              indexBeamType[ibeamType] = iBeam;
              foundBeamTypeStart[ibeamType] = kTRUE;
            }
            else{
              break;
            }
          }
        }
        if (!foundBeamTypeStart[ibeamType]){
          Printf(Form("No value for the Beam Type %s found before start of run, the Beam Type %d will remain empty", fgkLHCDataPoints[indexBeamTypeString+ibeamType], ibeamType));
        }
        else {
          AliDCSArray* beam = (AliDCSArray*)beamArray->At(indexBeam);
          TObjString* beamString = beam->GetStringArray(0);
          TString beamType = beamString->String();
          Printf(Form("Beam Type (for %s) = %s", fgkLHCDataPoints[indexBeamTypeString+ibeamType], beamType.Data()));
          TString singleBeam = ParseBeamTypeString(beamType,ibeamType);
          Printf(Form("Single Beam Type for beam %d set to %s", ibeamType, singleBeam.Data()));
          grpobj->SetSingleBeamType(ibeamType, singleBeam);
          if (beamType.CompareTo("PROTON",TString::kIgnoreCase) == 0){
            Printf(Form("Setting beam %d for combined beam type to p", ibeamType));
            if (ibeamType == 0) combinedBeamType.Prepend("p"); 
            else combinedBeamType.Append("p");
          }
          else { // if there is no PROTON beam, we suppose it is Pb, and we put A-A
            Printf(Form("Setting beam %d for combined beam type to A",ibeamType));
            if (ibeamType == 0) combinedBeamType.Prepend("A");
            else combinedBeamType.Append("A");
          }
          if (ibeamType == 0) combinedBeamTypeFromLHC.Prepend(beamType); 
          else combinedBeamTypeFromLHC.Append(beamType);
          /*
             else if (beamType.CompareTo("LEAD82",TString::kIgnoreCase) == 0){
             Printf("Setting beam type to Pb-Pb");
             grpobj->SetSingleBeamType(ibeamType, "Pb-Pb");
             }
             else{
             Printf("ERROR: Beam Type not known, leaving it empty");
             }
             */
          if (indexBeamType[ibeamType] < nBeam-1){
            AliDCSArray* beam1 = (AliDCSArray*)beamArray->At(indexBeam+1);
            if (beam1){
              if (beam1->GetTimeStamp()>timeStart && beam1->GetTimeStamp()<=timeEnd){
                timeBeamTypeEnd[ibeamType] = beam1->GetTimeStamp();
                TObjString* beamString1 = beam1->GetStringArray(0);
                TString beamType1 = beamString1->String();
                if (beamType.CompareTo(beamType1.Data(),TString::kIgnoreCase) == -1){
                  Printf("WARNING: The Beam Type for %s changed from %s to %s during the run at timestamp %f! Setting it to %s and keeping track of the time of the change to set MaxTimeLHCValidity afterward",fgkLHCDataPoints[indexBeamTypeString+ibeamType],beamType.Data(),(beamString1->String()).Data(),timeBeamEnd,beamType.Data());
                  flagBeamType[ibeamType] = kTRUE;
                  arrayTimes[3+ibeamType] = timeBeamTypeEnd[ibeamType];
                }
              }
            }
            else {
              Printf(Form("Invalid pointer for the first entry for Beam Type %s after the first valid one, not considering anything after what has already been found",fgkLHCDataPoints[indexBeamTypeString+ibeamType]));
            }
          }
        }
      }
      delete beamArray;
    }
    else{
      AliError(Form("Beam Type %s array not found in LHC Data file!!!",fgkLHCDataPoints[indexBeamTypeString+ibeamType]));
    }		
  }
  Printf(Form("Setting combined beam type to %s",combinedBeamType.Data()));
  grpobj->SetBeamType(combinedBeamType);
  Printf(Form("Setting combined beam type form LHC to %s",combinedBeamTypeFromLHC.Data()));
  grpobj->SetBeamTypeFromLHC(combinedBeamTypeFromLHC);

  // Setting minTimeLHCValidity
  if (flagBeamMode == kTRUE || flagMachineMode == kTRUE || flagBeam == kTRUE || flagBeamType[0] == kTRUE || flagBeamType[1] == kTRUE){ 
    Double_t minTimeLHCValidity= TMath::MinElement(5,arrayTimes);
    Printf("WARNING: Setting MaxTimeLHCValidity to %f",minTimeLHCValidity);
    grpobj->SetMaxTimeLHCValidity(minTimeLHCValidity);
  }
  /* 
  // Old way to determine the Maximum Time during which the LHC info is valid
  if (timeBeamModeEnd!=0 || timeMachineModeEnd!=0 || timeBeamEnd !=0){
  Double_t minTimeLHCValidity;
  if (flagBeamMode == kFALSE && flagMachineMode == kFALSE && flagBeam == kTRUE){ // flagBeam only true --> it is the only one that changed
  minTimeLHCValidity = timeBeamEnd;
  }
  else if (flagBeamMode == kFALSE && flagMachineMode == kTRUE && flagBeam == kFALSE){ // flagMachineMode only true
  minTimeLHCValidity = timeMachineModeEnd;
  }
  else if (flagBeamMode == kTRUE && flagMachineMode == kFALSE && flagBeam == kFALSE){ // flagBeamMode only true
  minTimeLHCValidity = timeBeamModeEnd;
  }
  else if (flagBeamMode == kFALSE && flagMachineMode == kTRUE && flagBeam == kTRUE){ // flagBeam and flagMachineMode only true
  minTimeLHCValidity= TMath::Min(timeBeamEnd,timeMachineModeEnd);
  }
  else if (flagBeamMode == kTRUE && flagMachineMode == kFALSE && flagBeam == kTRUE){ // flagBeam and flagBeamMode only true
  minTimeLHCValidity= TMath::Min(timeBeamEnd,timeBeamModeEnd);
  }
  else if (flagBeamMode == kTRUE && flagMachineMode == kTRUE && flagBeam == kFALSE){ // flagMachineMode and flagBeamMode only true
  minTimeLHCValidity= TMath::Min(timeMachineModeEnd,timeBeamModeEnd);
  }
  else {
  Double_t arrayTimes[3] = {timeBeamModeEnd,timeMachineModeEnd,timeBeamEnd};// flagMachineMode and flagBeamMode and flagBeam 
  minTimeLHCValidity= TMath::MinElement(3,arrayTimes);
  }
  Printf("WARNING: Setting MaxTimeLHCValidity to %f",minTimeLHCValidity));
  grpobj->SetMaxTimeLHCValidity(minTimeLHCValidity);
  }
  */

  // Data Quality Flag --> storing start and end values of periods within the run during which the value was found to be FALSE
  Printf("*************Data Quality Flag ");
  TObjArray* dataQualityArray = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[8]);
  Int_t nDataQuality = -1;
  Double_t timeDataQualityStart = -1; // min validity for Data Quality Flag
  Int_t indexDataQuality = -1;               // index of first measurement used to set Data Quality Flag
  Bool_t foundDataQualityStart = kFALSE;     // flag to be set in case an entry for the Data Quality Flag is found before (or at) SOR

  if (dataQualityArray){
    nDataQuality = dataQualityArray->GetEntries();
    if (nDataQuality==0){
      Printf("No Data Quality Flag found, leaving it empty");
    }
    else{
      for (Int_t iDataQuality = 0; iDataQuality<nDataQuality; iDataQuality++){
        AliDCSArray* dataQuality = (AliDCSArray*)dataQualityArray->At(iDataQuality);
        if (dataQuality){
          if (dataQuality->GetTimeStamp()<=timeStart && dataQuality->GetTimeStamp()>=timeDataQualityStart){// taking always the very last entry: if two measurements have the same timestamp, the last one is taken
            timeDataQualityStart = dataQuality->GetTimeStamp();
            indexDataQuality = iDataQuality;
            foundDataQualityStart = kTRUE;
          }
          else{
            // we suppose here that if the first measurement is not before SOR, then none will be (they MUST be in chronological order!!!) 
            break;
          }
        }
      }
      if (!foundDataQualityStart){
        // The Data Quality Flag should be found and TRUE at the start of the run. For the time being, if it is not found, don't do anything, but it means there is a problem..
        Printf("No value for the Data Quality Flag found before start of run, the Data Quality Flag will remain empty");
      }
      else {
        // counting how many FALSE values there are
        Bool_t foundEndOfFalse = kFALSE;
        Int_t nFalse = 0;
        for (Int_t iDataQuality = indexDataQuality; iDataQuality < nDataQuality; iDataQuality ++){
          AliDCSArray* dataQuality = (AliDCSArray*)dataQualityArray->At(iDataQuality);
          Printf("dataQuality->GetTimeStamp() = %f, timeDataQualityStart = %f, timeEnd = %f", dataQuality->GetTimeStamp(), timeDataQualityStart, timeEnd );
          if (dataQuality->GetTimeStamp()>=timeDataQualityStart && dataQuality->GetTimeStamp()<=timeEnd){ // considering only values between the first valid and the end of the run
            Bool_t dataQualityFlag = dataQuality->GetBool(0);
            Printf("DataQuality = %d (set at %f)",(Int_t)dataQualityFlag,dataQuality->GetTimeStamp());
            if (dataQualityFlag != kTRUE){
              if (iDataQuality == indexDataQuality) {  // the first Data Quality value should be TRUE, but ignoring the problem now...
                Printf("ERROR: The first value for the Data Quality MUST be TRUE! Ignoring for now...");
              }
              nFalse++;
            }
          }
        }

        Printf(Form("Found %d FALSE values for the Data Quality Flag",nFalse));
        Double_t falses[nFalse*2];  // dimensioning this to the maximum possible, as if each false value was followed by a true one --> the false periods correspond to the number of falses

        Int_t iDataQuality = indexDataQuality;
        if (nFalse > 0){
          Int_t iFalse = 0;
          // filling the info about the periods when the flag was set to FALSE
          // starting, like for the other DPS, from the measurement closest to SOR (the index of which is iDataQuality)
          while (iDataQuality < nDataQuality){
            Printf("iDataQuality = %d",iDataQuality);
            AliDCSArray* dataQuality = (AliDCSArray*)dataQualityArray->At(iDataQuality);
            if (dataQuality->GetTimeStamp()>=timeDataQualityStart && dataQuality->GetTimeStamp()<=timeEnd){ // considering only values between the first valid and the end of the run
              Bool_t dataQualityFlag = dataQuality->GetBool(0);
              Printf("DataQuality = %d (set at %f)",(Int_t)dataQualityFlag,dataQuality->GetTimeStamp());
              if (dataQualityFlag == kTRUE){
                // found TRUE value, continuing
                iDataQuality++;
                continue;
              }
              else{
                /*
                // the check was already done before
                if (iDataQuality == indexDataQuality) {  // the first Data Quality value should be TRUE, but ignoring the problem now...
                Printf("ERROR: The first value for the Data Quality MUST be TRUE! Ignoring for now...");
                }
                */
                falses[iFalse*2] = dataQuality->GetTimeStamp();
                foundEndOfFalse = kFALSE;
                Int_t iDataQualityNext = iDataQuality+1;
                while (iDataQualityNext < nDataQuality){
                  AliDCSArray* dataQualityNext = (AliDCSArray*)dataQualityArray->At(iDataQualityNext);
                  if (dataQualityNext->GetTimeStamp()>timeDataQualityStart && dataQualityNext->GetTimeStamp()<=timeEnd && dataQualityNext->GetTimeStamp() > dataQuality->GetTimeStamp()){ // considering only values between the first valid and the end of the run, and subsequent to the current value
                    Bool_t dataQualityFlagNext = dataQualityNext->GetBool(0);
                    Printf("DataQualityNext = %d (set at %f)",(Int_t)dataQualityFlagNext,dataQualityNext->GetTimeStamp());
                    if (dataQualityFlagNext == kTRUE){
                      // found TRUE value, first FALSE period completed
                      foundEndOfFalse = kTRUE;
                      falses[iFalse*2+1] = dataQualityNext->GetTimeStamp();
                      iFalse++;
                      break;
                    }
                    iDataQualityNext++;
                  }
                }
                if (!foundEndOfFalse) {
                  Printf("Please, note that the last FALSE value lasted until the end of the run");
                  falses[iFalse*2+1] = timeEnd;
                  iFalse++;
                  break;
                }
                iDataQuality = iDataQualityNext+1;
              }
            }
          }
          grpobj->SetNFalseDataQualityFlag(iFalse);
          grpobj->SetFalseDataQualityFlagPeriods(falses);
        }
      }
    }
    delete dataQualityArray;
  }
  else{
    Printf("ERROR: Data Quality Flag array not found in LHC Data file!!!");
  }

  // Processing data to go to AliLHCData object
  AliLHCData* dt = new AliLHCData(fileName.Data(),timeStart,timeEnd);
  // storing AliLHCData in OCDB
  if (dt){
    Printf(Form("Filled %d records to AliLHCData object",dt->GetData().GetEntriesFast()));
    AliCDBMetaData md;
    md.SetResponsible("Ruben Shahoyan");
    md.SetComment("LHC data from the GRP preprocessor.");
    Bool_t result = kTRUE;
    AliCDBId id("GRP/GRP/LHCData", 0, AliCDBRunRange::Infinity());
    result = cdb->Put(dt, id, &md); 
    delete dt;
    if (!result){
      Printf("Problems in storing LHC Data - but not going into Error");
    }
  }

  // processing LHC Phase

  TObjArray *beam1phase = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[4]);
  TObjArray *beam2phase = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[5]);
  if (beam1phase == 0x0 || beam2phase == 0x0){
    Printf(Form("Problems in retrieving LHC Clock data from LHC file"));
    return 4;
  }			
  AliLHCClockPhase *phaseObj = ProcessLHCClockPhase(beam1phase,beam2phase,timeEnd);
  delete beam1phase;
  delete beam2phase;
  if (phaseObj){
    Printf(Form("LHC Phase found"));
    AliCDBMetaData mdPhase;
    mdPhase.SetResponsible("Cvetan Cheshkov");
    mdPhase.SetComment("LHC Clock Phase");
    Bool_t result = kTRUE;
    AliCDBId id("GRP/Calib/LHCClockPhase", 0, AliCDBRunRange::Infinity());
    result = cdb->Put(phaseObj, id, &mdPhase); 
    delete phaseObj;
    if (!result) return 3;
  }
  else return 4;

  return 0;
}