void execCreateAndMerge() { 
//-------------------------------------------------------------------------- 
for ( Int_t ifile = 0 ; ifile < 4 ; ifile++ ) { 
   TFile* outputFile = TFile::Open(Form("a_file_%d.root",ifile),"RECREATE"); 
   TNamed* namedObj = new TNamed(Form("namedObj%d",ifile),Form("namedObj%d",ifile)); 
   namedObj->Write(); 
   outputFile->Close(); 
} 
cout << "4 a files created" << endl; 
//-------------------------------------------------------------------------- 
//-------------------------------------------------------------------------- 
for ( Int_t ifile = 0 ; ifile < 4 ; ifile++ ) { 
   TFile* outputFile = TFile::Open(Form("b_file_%d.root",ifile),"RECREATE"); 
   TNamed* namedObj = new TNamed("namedObj","namedObj"); 
   namedObj->Write(); 
   outputFile->Close(); 
} 
cout << "4 b files created" << endl; 
//-------------------------------------------------------------------------- 
//-------------------------------------------------------------------------- 
TFileMerger* aMerger = new TFileMerger(kFALSE); 
 for ( Int_t ifile = 0 ; ifile < 4 ; ifile++ ) { 
    TFile* inFile = TFile::Open(Form("a_file_%d.root",ifile)); 
    aMerger->AddFile(inFile); 
 } 
 aMerger->OutputFile("a_file.root"); 
 aMerger->Merge(); 
 cout << "4 a files merged" << endl; 
//-------------------------------------------------------------------------- 
//-------------------------------------------------------------------------- 
 TFileMerger* bMerger = new TFileMerger(kFALSE); 
 for ( Int_t ifile = 0 ; ifile < 4 ; ifile++ ) { 
    TFile* inFile = TFile::Open(Form("b_file_%d.root",ifile)); 
    bMerger->AddFile(inFile); 
 } 
 bMerger->OutputFile("b_file.root"); 
 bMerger->Merge(); 
cout << "4 b files merged" << endl; 
//-------------------------------------------------------------------------- 
//-------------------------------------------------------------------------- 
TFile* inAFile = TFile::Open("a_file.root"); 
cout << "******* MERGED A FILE ******** 4 objects with different names" << endl; 
inAFile->ls(); 
cout << "******************************" << endl; 
//-------------------------------------------------------------------------- 
//-------------------------------------------------------------------------- 
TFile* inBFile = TFile::Open("b_file.root"); 
cout << "******* MERGED B FILE ******** 4 objects with the same names" << endl; 
inBFile->ls(); 
cout << "******************************" << endl; 
//-------------------------------------------------------------------------- 
} 
TGraph2DErrors* GetGraph(std::string fname)
{
    TGraph2DErrors* gr = 0;

    std::string fGrName = "mygraph";

    TFile *f = new TFile(fname.data());
    if (!f->IsOpen())
    {
        std::cerr << "Failed to open " << fname << std::endl;
        return gr;
    }

    f->ls();

    std::cout << "Enter name of graph : ";
    if (std::cin.peek()=='\n') std::cin.get();
    std::getline(std::cin, fGrName);

    f->GetObject(fGrName.data(), gr);
    if (gr!=NULL)
    {

        TGraph2DErrors* tgr = (TGraph2DErrors*) gr->Clone("mygraph_0");
        gr=tgr;
        gr->SetDirectory(0);
    }

    return gr;
}
void makeSVfitMEM_xSectionPlot()
{
  gROOT->SetBatch(true);

  std::string inputFilePath = "/afs/cern.ch/user/v/veelken/scratch0/SVfitMEM_with_vamp/CMSSW_7_4_6/src/TauAnalysis/SVfitMEM/data/";
  std::string inputFileName = "svFitMEM_xSection_and_AccCorr_13TeV_fitted.root";
  std::string inputFileName_full = Form("%s%s", inputFilePath.data(), inputFileName.data());
  TFile* inputFile = new TFile(inputFileName_full.data());
  if ( !inputFile ) {
    std::cerr << "Failed to open input file = '" << inputFileName_full << "' !!" << std::endl;
    assert(0);
  }
  
  std::string graphName = "graph_Xsection_woAcc_13TeV_hadhad_vamp_fitted";
  TGraph* graph = dynamic_cast<TGraph*>(inputFile->Get(graphName.data()));
  if ( !graph ) {
    std::cerr << "Failed to load graph = '" << graphName << "' from file = '" << inputFileName.data() << "' !!" << std::endl;
    inputFile->ls();
    assert(0);
  }

  std::string outputFileName = "./makeSVfitMEM_xSectionPlot.pdf";
  showGraph(800, 650,
	    graph, 
	    false, 50., 5000., "m_{H} [GeV]", 1.30,
	    true, 1.e-4, 1.e+2, "#sigma(gg #rightarrow H) [pb]", 1.35,
	    outputFileName);

  delete inputFile;
}
//_______________________________________ 
 int OpenDataThisFile(TString fname ) {
 
 	int success = 0 ;

       // open the ROOT file to process
   TString path ="./data1/moukaddam/SpiceTestSep2014/Calibration/Files/";
   TString inFileName = fname+".root";
   TFile *inFile = new TFile(path + inFileName);
   
   if ( !inFile->IsOpen() )  { //try present directory
   cout << "File doesn't exist in the directory  : " << path << endl ; 
   cout << "Trying the present working directory : ./" << endl ; 
   path ="./";
   inFile = new TFile(path + inFileName);
   }
   
   if ( inFile->IsOpen() ) {
       success = 1 ;
   	   cout << "Opening the root file and grabing the histograms from " << inFile->GetName() << endl ; 
   	   inFile->ls(); 
   }
   else {
   cout << "File is not found.. EXIT!"<< endl;
   exit(-1);
   } 
	   
	 gFolderHistos = (TFolder*)(inFile->FindObjectAny("histos"));
	 
	 return success ;
   }  
Example #5
0
int testMergedFile(const char *filename, Int_t compSetting, Long64_t fileSize)
{
   TFile *file = TFile::Open(filename);
   if (file == nullptr || file->IsZombie()) {
      Error("testSimpleFile", "Could not open %s.",filename);
      return 1;
   }
   file->ls();
   file->cd("hist");
   gDirectory->ls();
   gDirectory->Get("Gaus")->Print();
   file->cd("named");
   gDirectory->ls();
   file->Get("MyList")->Print();

   if (file->GetCompressionSettings() != compSetting) {
      Error("execTestMultiMerge","Compression level of %s should have been %d but is %d\n",file->GetName(), 206, file->GetCompressionSettings() );
      return 3;
   }
   if (file->GetSize() != fileSize) {
      Error("execTestMultiMerge","Disk size of %s should have been %lld but is %lld\n",file->GetName(), fileSize, file->GetSize() );
      return 4;
   }

   delete file;

   return 0;
}
Example #6
0
//__________________________________________________________________________
Bool_t BuildUniformField(const TGeoHMatrix& matrix)
{
   // Create a Uniform Magnetic field and write it to file
   cout << "Building Uniform Mag Field" << endl;
   MagFieldArray* magFieldArray = new MagFieldArray();
   // -- Define solenoid field - uniform magnetic field
   // Define shape of field
   TGeoShape* fieldShape = new Tube("SolenoidFieldShape",hvCellRMin, hvCellRMax, hvCellHalfZ);
   // Define transformation that locates field in geometry
   TGeoMatrix* fieldPosition = new TGeoHMatrix(matrix);
   // Define field vector in Coordinate system of Field
   TVector3 fieldStrength(solenoidBx, solenoidBy, solenoidBz);
   cout << "Local Coordinates - ";
   cout << "Bx: " << fieldStrength[0] << "\t By: " << fieldStrength[1];
   cout << "\t Bz: " << fieldStrength[2] << endl;
   // Define field object
   MagField* uniformField = new UniformMagField("SolenoidField", fieldStrength, fieldShape, fieldPosition);
   // Add field to magfield manager
   magFieldArray->AddField(uniformField);
   
   // -- Write magfieldmanager to geometry file
   const char *magFileName = "$(UCN_GEOM)/fields.root";
   TFile *f = TFile::Open(magFileName,"recreate");
   if (!f || f->IsZombie()) {
     Error("Export","Cannot open file: %s", magFileName);
     return kFALSE;
   }
   magFieldArray->Write(magFieldArray->GetName());
   f->ls();
   f->Close();
   if (magFieldArray) delete magFieldArray;
   magFieldArray = 0;
   return kTRUE;
}
Example #7
0
void evtime() {
  vector<int> runs;
  vector<int> marks;
  vector<int> mcols;
  runs.push_back(13893);
  marks.push_back(2);
  mcols.push_back(2);
  runs.push_back(14009);
  marks.push_back(24);
  mcols.push_back(4);
  runs.push_back(14085);
  marks.push_back(25);
  mcols.push_back(3);
  runs.push_back(14234);
  marks.push_back(5);
  mcols.push_back(3);
  runs.push_back(14434);
  marks.push_back(28);
  mcols.push_back(3);
  string pre = "run";
  string suf = "evt.root";
  double tmax = 160;
  double emax = 180;
  new TCanvas;
  TH1* ph = new TH2F("hevtime", "Event vs. time; Time [sec]; Event",
                     tmax, 0, tmax, emax, 0, emax);
  ph->SetStats(0);
  ph->Draw("axis");
  TLegend* pleg = new TLegend(0.65,0.15,0.85,0.37);
  pleg->SetBorderSize(0);
  for ( unsigned int isam=0; isam<runs.size(); ++isam ) {
    int run = runs[isam];
    int icol = dsindex(run);
    int col = colormap(icol);
    ostringstream ssrun;
    ssrun << run;
    string srun = ssrun.str();
    ostringstream sst0;
    sst0 << t0map(run);
    string fname = pre + srun + suf;
    TFile* pfile = TFile::Open(fname.c_str(), "READ");
    TTree* ptree = dynamic_cast<TTree*>(pfile->Get("DXDisplay/EventTree"));
    ptree->SetMarkerStyle(marks[isam]);
    ptree->SetMarkerColor(col);
cout << run << " " << col << " " << sst0.str() <<  endl;
    if ( ptree == 0 ) {
      cout << "Tree not found" << endl;
      pfile->ls();
      return;
    }
    string sarg = "event:tlo-";
    sarg += sst0.str();
    sarg += ">>hevtime";
    ptree->Draw(sarg.c_str(), "", "same");
    pleg->AddEntry(ptree, srun.c_str(), "p");
  }
  pleg->Draw();
}
Example #8
0
//________________________________________________________________________________
void MergeSimpleHistogramFile( const Char_t *TargetName=0, const Char_t *inputFilesPattern=0) 
{
   // This is the deprecated version. To be dleted after debugging
  if (TargetName && TargetName[0] && inputFilesPattern && inputFilesPattern[0] ) {
    TStopwatch time;
    Int_t fileCounter = 0;
    Int_t histogramCounter = 0;
     // Create the output file
     TFile *outFile = TFile::Open(TargetName,"RECREATE");     
     TDirIter listOfFiles(inputFilesPattern);
     const char *fileName = 0;
     while ( (fileName =  listOfFiles.NextFile() ) ) {
        printf(".");
        fileCounter++;
        TFileIter file(fileName);
        TObject *obj = 0;
        while ( (obj = *file) ) {
           if ( obj->IsA()->InheritsFrom( "TH1" ) ) {
              // descendant of TH1 -> merge it
              // printf("Merging histogram: %s\n",obj->GetName() ); 
//              std::cout << "Merging histogram " << obj->GetName() << std::endl;
              TH1 *h1 = (TH1*)obj;
              TH1 *dstHistogram = 0;
              // Check whether we found the new histogram
              if ( (dstHistogram = (TH1 *)outFile->FindObject(h1->GetName()))) {
                 // Accumulate  the  histogram
                  dstHistogram->Add(h1);
                  delete h1;  // Optional, to reduce the memory consumption
                  printf("+");
              } else {
                // First time - move the histogram
                h1->SetDirectory(outFile);
                printf(" The new Histogram found: %s \n", h1->GetName() );
                histogramCounter++;
              }
           } else {
              // printf("Skipping object: %s\n",obj->GetName() ); 
           }
           ++file;
        }
              
     }
     printf("\n Finishing  . . . \n");
     outFile->ls();
     outFile->Write();
     outFile->Close();     
     delete outFile;
     printf(" Total files merged: %d \n", fileCounter);
     printf(" Total histograms merged: %d \n", histogramCounter);
     time.Print("Merge");
  } else {
     printf("\nUsage: root MergeHistogramFile.C(\"DestinationFileName\",\"InputFilesPattern\",kTRUE)\n");     
     printf("------        where InputFilesPattern  ::= <regexp_pattern_for_the_input_files>|@indirect_file_list\n");
     printf("                    indirect_file_list ::= a text file with the list of the files\n");
     printf("                    indirect_file_list can be create by the shell command:\n");
     printf("                         ls -1 --color=never *.root>indirect_file_list \n\n");
  }
}
Example #9
0
File: fit1.C Project: dawehner/root
void fit1() {
   //Simple fitting example (1-d histogram with an interpreted function)
   //To see the output of this macro, click begin_html <a href="gif/fit1.gif">here</a>. end_html
   //Author: Rene Brun
   
   TCanvas *c1 = new TCanvas("c1_fit1","The Fit Canvas",200,10,700,500);
   c1->SetGridx();
   c1->SetGridy();
   c1->GetFrame()->SetFillColor(21);
   c1->GetFrame()->SetBorderMode(-1);
   c1->GetFrame()->SetBorderSize(5);

   gBenchmark->Start("fit1");
   //
   // We connect the ROOT file generated in a previous tutorial
   // (see begin_html <a href="fillrandom.C.html">Filling histograms with random numbers from a function</a>) end_html
   //
   TString dir = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName());
   dir.ReplaceAll("fit1.C","");
   dir.ReplaceAll("/./","/");
   TFile *fill = TFile::Open("fillrandom.root");
   if (!fill) {
      gROOT->ProcessLine(Form(".x %s../hist/fillrandom.C",dir.Data()));
      fill = TFile::Open("fillrandom.root");
      if (!fill) return;
   }
      
   //
   // The function "ls()" lists the directory contents of this file
   //
   fill->ls();

   //
   // Get object "sqroot" from the file. Undefined objects are searched
   // for using gROOT->FindObject("xxx"), e.g.:
   // TF1 *sqroot = (TF1*) gROOT.FindObject("sqroot")
   //
   sqroot->Print();

   //
   // Now fit histogram h1f with the function sqroot
   //
   h1f->SetFillColor(45);
   h1f->Fit("sqroot");

   // We now annotate the picture by creating a PaveText object
   // and displaying the list of commands in this macro
   //
   fitlabel = new TPaveText(0.6,0.3,0.9,0.80,"NDC");
   fitlabel->SetTextAlign(12);
   fitlabel->SetFillColor(42);
   fitlabel->ReadFile(Form("%sfit1_C.C",dir.Data()));
   fitlabel->Draw();
   c1->Update();
   gBenchmark->Show("fit1");
}
Example #10
0
void runmergeWithDir()
#endif
{
  TChain *tph;
   tph = new TChain("CBNT/t3333");
   tph->AddFile("file1.root");
   tph->AddFile("file2.root");
   tph->Merge("merged.root");
   TFile *fil = new TFile("merged.root");
   fil->ls();
}
void xrootdTestVanderbilt(const int iOption=0) {

  TDatime *dateTime = new TDatime;
  int iDate = dateTime->GetDate();
  int iTime = dateTime->GetTime();
  cout << "  Begin Vanderbilt access testing " << iDate << " at " << iTime << endl;

  if(iOption == 0 || iOption == 1) {
    TFile *f = TFile::Open("root://cmsxrootd.fnal.gov//store/test/xrootd/T2_US_Vanderbilt//store/mc/SAM/GenericTTbar/GEN-SIM-RECO/CMSSW_5_3_1_START53_V5-v1/0013/CE4D66EB-5AAE-E111-96D6-003048D37524.root");
    if(f) {
      cout << "\n cmsxrootd.fnal.gov successful access to Vanderbilt" << endl;
      f->ls();
      f->Close();
    }
    else {
      cout << "\n cmsxrootd.fnal.gov unsuccessful access to Vanderbilt" << endl;
    }
    dateTime->Set();     // set to system date/time
    iDate = dateTime->GetDate();
    iTime = dateTime->GetTime();
    cout << "  Completed Vanderbilt access test from FNAL on " << iDate << " at " << iTime << endl;
  } // check on iOption = 0 or iOption = 1
  if(iOption == 0 || iOption == 2) {
    TFile *g = TFile::Open("root://cms-xrd-global.cern.ch//store/test/xrootd/T2_US_Vanderbilt//store/mc/SAM/GenericTTbar/GEN-SIM-RECO/CMSSW_5_3_1_START53_V5-v1/0013/CE4D66EB-5AAE-E111-96D6-003048D37524.root");
    if(g) {
      cout << "\n cms-xrd-global.cern.ch successful access to Vanderbilt" << endl;
      g->ls();
      g->Close();
    }
    else {
      cout << "\n cms-xrd-global.cern.ch unsuccessful access to Vanderbilt" << endl;
    }
    dateTime->Set();     // set to system date/time
    iDate = dateTime->GetDate();
    iTime = dateTime->GetTime();
    cout << "  Completed Vanderbilt access test from CERN on " << iDate << " at " << iTime << endl;
  } // check on iOption = 0 or iOption = 2
  dateTime->Set();     // set to system date/time
  cout << "\n  Completed Vanderbilt access testing " << iDate << " at " << iTime << endl;
return;
}
Example #12
0
int execTestMultiMerge()
{
   TFile *file = TFile::Open("mfile1-4.root");
   file->ls();
   file->cd("hist");
   gDirectory->ls();
   gDirectory->Get("Gaus")->Print();
   file->cd("named");
   gDirectory->ls();
   file->Get("MyList")->Print();
   return 0;
}
Example #13
0
TFile *createRootFile(TString fileName,TString STlepCut,TString HTCut,TH1D *hIn,TString histoName)  {

  TH1::SetDefaultSumw2();

  TFile *fout = new TFile(fileName,"UPDATE");
  fout->mkdir("ANplots"+STlepCut+"_NOLPsecondD"+HTCut);
  fout->ls(); 
  fout->cd("ANplots"+STlepCut+"_NOLPsecondD"+HTCut);
  fout->pwd();

  TH1D *hOut = (TH1D*)hIn->Clone(histoName); hOut->SetName(histoName);
  hOut->Write(histoName);
  fout->Close();

  return fout;
}
Example #14
0
//__________________________________________________________________________
Bool_t BuildFieldMap(const TGeoHMatrix& matrix)
{
   // Create a Uniform Magnetic field and write it to file
   string filename = "runs/polarisation/guide_tube/C8=9 A +SQUIDs Coil =26_4 mA +D1=2 A + 6WS TC guide tube -100 z +80 cm.txt";
   // Define shape of field
   TGeoShape* magFieldShape = new Box("FieldShape",0.031, 0.031, 3.0);
   // Define transformation that locates field in geometry
   TGeoMatrix* magFieldPosition = new TGeoHMatrix(matrix);
   magFieldPosition->Print();
   MagFieldMap* field = new MagFieldMap("Field", magFieldShape, magFieldPosition);
   if (field->BuildMap(filename) == kFALSE) {
      Error("BuildFieldMap","Cannot open file: %s", filename);
      return kFALSE;
   }
   // Add field to magfield manager
   MagFieldArray* magFieldArray = new MagFieldArray();
   magFieldArray->AddField(field);
   
/*   // Elec Field
   // Define shape of field
   TGeoShape* elecFieldShape = new Tube("SolenoidFieldShape",hvCellRMin, hvCellRMax, hvCellHalfZ);
   // Define transformation that locates field in geometry
   TGeoMatrix* elecFieldPosition = new TGeoHMatrix(matrix);
   TVector3 elecFieldStrength(hvCellEx, hvCellEy, hvCellEz);
   ElecField* elecField = new UniformElecField("ElectricField", elecFieldStrength, elecFieldShape, elecFieldPosition);
   // Add field to electric field manager
   ElecFieldArray* elecFieldArray = new ElecFieldArray();
   elecFieldArray->AddField(elecField);
*/   
   // -- Write magfieldmanager to geometry file
   const char *magFileName = "geom/fields.root";
   TFile *f = TFile::Open(magFileName,"recreate");
   if (!f || f->IsZombie()) {
     Error("BuildFieldMap","Cannot open file: %s", magFileName);
     return kFALSE;
   }
   magFieldArray->Write(magFieldArray->GetName());
//   elecFieldArray->Write(elecFieldArray->GetName());
   f->ls();
   f->Close();
   delete magFieldArray;
//   delete elecFieldArray;
   magFieldArray = 0;
//   elecFieldArray = 0;
   return kTRUE;
}
Example #15
0
mkplots(){
   gStyle->SetOptStat(1);

   TFile * f = new TFile("plots.root");
   f->ls();

   TH1F * hpn = (TH1F *) f->Get("hpn");
   TH1F * hpt = (TH1F *) f->Get("hpt");
   TH1F * hpp = (TH1F *) f->Get("hpp");
   TH1F * hde = (TH1F *) f->Get("hde");
   TH1F * hdp = (TH1F *) f->Get("hdp");
   TH1F * hdt = (TH1F *) f->Get("hdt");

   TCanvas * c1 = new TCanvas;
   hpn->SetXTitle("pull shower log(N)");
   hpn->Draw("ep");
   c1->SaveAs("plots/pn.png");

   TCanvas * c2 = new TCanvas;
   hpt->SetXTitle("pull shower eta)");
   hpt->Draw("ep");
   c2->SaveAs("plots/pt.png");

   TCanvas * c3 = new TCanvas;
   hpp->SetXTitle("pull shower phi");
   hpp->Draw("ep");
   c3->SaveAs("plots/pp.png");

   TCanvas * c4 = new TCanvas;
   hde->SetXTitle("shower E fractional difference");
   hde->Draw("ep");
   c4->SaveAs("plots/dn.png");

   TCanvas * c5 = new TCanvas;
   hdt->SetXTitle("shower theta fractional difference");
   hdt->Draw("ep");
   c5->SaveAs("plots/dt.png");

   TCanvas * c6 = new TCanvas;
   hdp->SetXTitle("shower phi fractional difference");
   hdp->Draw("ep");
   c6->SaveAs("plots/dp.png");


}
Example #16
0
//__________________________________________________________________________
Bool_t BuildFieldMap(const TGeoHMatrix& matrix)
{
   // Create a Uniform Magnetic field and write it to file
   string filename = "runs/ramseycell/fieldmap/scv/corrected/config3/fieldmap_config3_offset.txt";
   // Define shape of field
   TGeoShape* magFieldShape = new Tube("SolenoidFieldShape",hvCellRMin, hvCellRMax, hvCellHalfZ);
   // Define transformation that locates field in geometry
   TGeoMatrix* magFieldPosition = new TGeoHMatrix(matrix);
   MagFieldMap* field = new MagFieldMap("SolenoidField", magFieldShape, magFieldPosition);
   if (field->BuildMap(filename) == kFALSE) {
      Error("BuildFieldMap","Cannot open file: %s", filename);
      return kFALSE;
   }
   // Add field to magfield manager
   MagFieldArray* magFieldArray = new MagFieldArray();
   magFieldArray->AddField(field);
   
/*   // Elec Field
   // Define shape of field
   TGeoShape* elecFieldShape = new Tube("SolenoidFieldShape",hvCellRMin, hvCellRMax, hvCellHalfZ);
   // Define transformation that locates field in geometry
   TGeoMatrix* elecFieldPosition = new TGeoHMatrix(matrix);
   TVector3 elecFieldStrength(hvCellEx, hvCellEy, hvCellEz);
   ElecField* elecField = new UniformElecField("ElectricField", elecFieldStrength, elecFieldShape, elecFieldPosition);
   // Add field to electric field manager
   ElecFieldArray* elecFieldArray = new ElecFieldArray();
   elecFieldArray->AddField(elecField);
*/   
   // -- Write magfieldmanager to geometry file
   const char *magFileName = "runs/ramseycell/fieldmap/scv/corrected/config5/fields_config5.root";
   TFile *f = TFile::Open(magFileName,"recreate");
   if (!f || f->IsZombie()) {
     Error("BuildFieldMap","Cannot open file: %s", magFileName);
     return kFALSE;
   }
   magFieldArray->Write(magFieldArray->GetName());
//   elecFieldArray->Write(elecFieldArray->GetName());
   f->ls();
   f->Close();
   delete magFieldArray;
//   delete elecFieldArray;
   magFieldArray = 0;
//   elecFieldArray = 0;
   return kTRUE;
}
Example #17
0
TH1F* readHist(TString nameHist,TString nameFile, TString nameDir, int rebin)
{
 TFile* file = new TFile(nameFile);
 file->ls();
 TDirectory *dir=(TDirectory*)file->Get(nameDir);
 
 TH1F* hist = (TH1F*)dir->Get(nameHist);
 // if (hist==0) return;
 hist->GetSumw2();
 // hist->SetLineWidth(2);
 if(rebin>0) hist->Rebin(rebin);
 hist->GetXaxis()->SetTitleSize(.055);
 hist->GetYaxis()->SetTitleSize(.055);
 hist->GetXaxis()->SetLabelSize(.05);
 hist->GetYaxis()->SetLabelSize(.05);
 hist->SetStats(kFALSE);
 return hist;
}
void diphoton_makeClass() {
  // load file
  TFile *f = TFile::Open("root://cmsxrootd.fnal.gov//store/user/abuccill/diphoton-analysis/fake_rate_real_templates/diphoton_fake_rate_real_templates_GGJets_M-4000To6000_Pt-50_13TeV-sherpa_76X_MiniAOD_merged.root");
  
  // list the contents of this file
  f->ls();

  // get tree
  TTree *tree = (TTree *) f->Get("diphoton/fTree");

  // print tree contents
  tree->Print();

  // list the total number of entries in tree
  cout << "Entries: " << tree->GetEntries() << endl;
  
  // make class
  tree->MakeClass("MCFakeRateAnalysis");
}
Example #19
0
   void run_ws_cls_hybrid2n() {

      gROOT->LoadMacro("workspace-macros-v1/ws_cls_hybrid2n.c+") ;

      TFile* outf = new TFile("cls-newfit-test-1000.root","recreate") ;

      gDirectory->pwd() ;

      bool isBgonlyStudy ;
      double poiVal ;
      int nToys ;
      bool makeTtree ;
      int verbLevel = 1 ;
      bool oneSidedTestStat = false ;

      makeTtree = true ;

      nToys = 1000 ;

    //-------

      for ( int poii=0; poii<1; poii++ ) {

         //poiVal = 15. + 15*poii ;
         poiVal = 0 ;

         isBgonlyStudy = false ;
         ws_cls_hybrid2n( "output-files/ws-newfit-lm9-1BL.root", isBgonlyStudy, poiVal, nToys, makeTtree, verbLevel, oneSidedTestStat ) ;

         isBgonlyStudy = true ;
         ws_cls_hybrid2n( "output-files/ws-newfit-lm9-1BL.root", isBgonlyStudy, poiVal, nToys, makeTtree, verbLevel, oneSidedTestStat ) ;

      }



      outf->ls() ;


      outf->Close() ;

   }
void ChangeDataTreeName(std::string suffix){

  // Define names
  TString filename = "", treename = "", histname = "";
  filename.Form("central_%s.root",suffix.c_str());
  treename.Form("id_%s",suffix.c_str());
  histname.Form("sumOfMcWeights_%s",suffix.c_str());

  TString _pathFile(string(getenv("WORKAREA")) + "/histoAna" + "/SusyAna/histos_110312_13fb_n0111_DD_MMtrial9_SYS_HFT/HFTOutputs_merge/");
  filename = _pathFile+filename;
  cout << "open " << filename << endl;

  // Open file
  TFile* file         = new TFile(filename,"UPDATE");
  if(file->IsOpen()==kFALSE){
    cerr << "Cannot open file " << filename << endl;
    abort();
  }
  file->ls();
  TTree* treeOriginal = (TTree*) file->Get(treename);
  TH1D*  histOriginal = (TH1D*)  file->Get(histname);
  TTree* treeNew      = (TTree*) treeOriginal->Clone();
  TH1D*  histNew      = (TH1D*)  histOriginal->Clone();

  // Set-Write-Delete
  histNew->SetName ("sumOfMcWeights_Data" );
  histNew->SetTitle("sumOfMcWeights_Data" );
  histNew->Write   ("",TObject::kOverwrite);
  treeNew->SetName ("id_Data"             );
  treeNew->SetTitle("id_Data"             );
  treeNew->Write   ("",TObject::kOverwrite);
  file->Delete     (histname+";1"         );
  file->Delete     (treename+";1"         );

  // Close file
  file->Close();
}
void get_nn_ptpt_FROM_FB_TREE() // TString inputFileName = "MergedOutput.root")
{
    //            TFile *myFile = new TFile( "/Users/macbook/alice/aliceAnalysis/results/task_2016_02_09_PbPb_Data_AOD_3etaWins_phi1_pt02_20_FB_TREE_blocks123/block1/AnalysisResults.139465.root" );
    TFile *myFile = new TFile( "/Users/macbook/alice/aliceAnalysis/results/task_2016_02_21_PbPb_Data_AOD_3etaWins_phi1_pt02_20_FB_TREE_TEST_NEW_DATA_5_02TeV_tryAOD2/MergedOutput.root" );
    if (!myFile)
    {
        cout << "No input file!" << endl;
        return;
    }
    myFile->ls();
    TList *listKeys = myFile->GetListOfKeys();
    cout << "going into list: " << listKeys->At(1)->GetName() << endl;

    //return;
    myFile->cd( listKeys->At(1)->GetName() );
    TList *listKeys2 = gDirectory->GetListOfKeys();
    TList *myTask = (TList*) gDirectory->Get( listKeys2->At(0)->GetName() );
    TTree *t1 = (TTree*)  myTask->FindObject( "treeFB" );


    //    cout << t1->GetEntries() << endl;
    //t1->Print();
    //return;
    //    TFile *f = new TFile( "file_event_tree_merged_impPar_2files.root" );
    //    TTree *t1 = (TTree*) f->Get( "t1" );

    //    TFile *f = new TFile( "output_1_list.grid.root" );
    //    TList *list = (TList*) f->Get( "coutput_V0_mult_0.000000_100000.000000" );
    //    TTree *t1 = (TTree*) list->FindObject( "t1" );

    //other vars:
    //    const int nVars = 3;
    //    TString strVarName[] = {
    //        "centr_V0M" ,
    //        "centr_CL1" ,
    //        "centr_ZEMvsZDC"     ,
    //    };
    //    Float_t varBranch[nVars];

    //    for(Int_t var = 0; var < nVars; var++)
    //        t1->SetBranchAddress(strVarName[var],&varBranch[var]);

    Float_t brV0M;
    //    t1->SetBranchAddress( "centr_V0M", &brV0M );
    t1->SetBranchAddress( "centrV0M_NEW_MULT_SEL", &brV0M );

    Float_t brZEMvsZDC;
    t1->SetBranchAddress( "centr_ZEMvsZDC", &brZEMvsZDC );

    //        const int nCW = 1; //nCentrWidths
    //        const double cWidths[nCW] = { 10 }; //width of the centrality bins
    //        const double cStep[nCW] = { 5 }; //centrality bins step
    //        const int nCentrBins[nCW] = { 17 }; //n centrality bins

//    const int nCW = 2; //nCentrWidths
//    const double cWidths[nCW] = { 10, 5.001 }; //width of the centrality bins
//    const double cStep[nCW] = { 5, 2.5 }; //centrality bins step
//    const int nCentrBins[nCW] = { 17, 35 }; //n centrality bins

    const int nCW = 2; //nCentrWidths
    const double cWidths[nCW] = { 10, 5 }; //width of the centrality bins
    const double cStep[nCW] = { 10, 5 }; //centrality bins step
    const int nCentrBins[nCW] = { 9, 18 }; //n centrality bins


    //    const int nCW = 5; //nCentrWidths
    //    const double cWidths[nCW] = { 10, 5, 2.5, 1.0, 0.5 }; //width of the centrality bins
    //    const double cStep[nCW] = { 5, 2.5, 2.5, 1.0, 1.0 }; //centrality bins step
    //    const int nCentrBins[nCW] = { 17, 35, 36, 90, 90 }; //n centrality bins

    const int nEtaWins = 3;
    const int nPhiWins = 1;

    const int maxNCentrBins = 100; //TMath::MaxElement(nCW, &nCentrBins);
    WinPair wins[nCW][maxNCentrBins][nEtaWins][nPhiWins];
    CentralityOccupancy cOccupancy[nCW][maxNCentrBins];

    for ( int cW = 0; cW < nCW; cW++ )
        for ( int cBin = 0; cBin < nCentrBins[cW]; cBin++ )
        {
            float cBinMin = cStep[cW] * cBin;
            float cBinMax = cWidths[cW] + cStep[cW] * cBin;

            cOccupancy[cW][cBin].cBinMin = cBinMin;
            cOccupancy[cW][cBin].cBinMax = cBinMax;

            for ( int etaW = 0; etaW < nEtaWins; etaW++ )
                for ( int phiW = 0; phiW < nPhiWins; phiW++ )
                    wins[cW][cBin][etaW][phiW].init(cBinMin, cBinMax, etaW, phiW);
        }


    BranchFB br[nEtaWins][nPhiWins];

    for ( int etaW = 0; etaW < nEtaWins; etaW++ )
        for ( int phiW = 0; phiW < nPhiWins; phiW++ )
        {
            int ptW = 0;
            TString brNamePostfix = Form("eta_%d_phi%d_pt_%d"
                                         , etaW, phiW, ptW );
            t1->SetBranchAddress( Form("nF_%s", brNamePostfix.Data() ),  &br[etaW][phiW].nF );
            t1->SetBranchAddress( Form("nB_%s", brNamePostfix.Data() ),  &br[etaW][phiW].nB );
            t1->SetBranchAddress( Form("PtF_%s", brNamePostfix.Data() ), &br[etaW][phiW].PtF );
            t1->SetBranchAddress( Form("PtB_%s", brNamePostfix.Data() ), &br[etaW][phiW].PtB );
        }



    TH1D *hist1D_QA_percentilesEstimator = new TH1D( "hist1D_QA_percentilesEstimator", "hist1D_QA_percentilesEstimator;percentile;entries", 3001, -0.5, 300.5);
    TH1D *hist1D_QA_multALL = new TH1D( "hist1D_QA_multALL", "hist1D_QA_multALL;mult;entries", 3001, -0.5, 3000.5);


    // ##### prepare for tree loop
    int nEvents = t1->GetEntries();
    cout <<"nEvents = " << nEvents << endl;

    //    float **BS_Nf = new float*[nPhiWins];
    //    float **BS_Nb = new float*[nPhiWins];
    //    for ( int w = 0; w < nPhiWins; w++ )
    //    {
    //        BS_Nf[w] = new float[nEvents];
    //        BS_Nb[w] = new float[nEvents];
    //    }

    // ##### main loop over events
    int flag_V0M_ZDC = 0;//1;
    int nAccepted = 0;
    for (Long64_t i=0; i < nEvents; i++)
    {
        if ( i % 100000 == 0 )
            cout << "getting " << (int)i << endl;
        //                cout <<"getting " << (int)i << "\r"; cout.flush();

        t1->GetEntry( i );
        //            t1->GetEntry( TMath::Nint( gRandom->Uniform(-0.5,nEvents-0.5) ) );

        float cEstimator = -1;
        if ( flag_V0M_ZDC==0 )
        {
            if ( brV0M > 90 ) //V0M cut
                continue;
            cEstimator = brV0M;
        }
        else
        {
            if ( brZEMvsZDC > 50 ) //ZDCvsZEM cut
                continue;
            cEstimator = brZEMvsZDC;
        }
        hist1D_QA_percentilesEstimator->Fill(cEstimator);


        //calc mult in whole TPC using wins:
        int multTPC = 0;
        for ( int phiW = 0; phiW < nPhiWins; phiW++ )
            multTPC += (br[0][phiW].nF + br[2][phiW].nF) + (br[0][phiW].nB + br[2][phiW].nB);
        hist1D_QA_multALL->Fill(multTPC);


        //        for ( int w = 0; w < nPhiWins; w++ )
        //        {
        //            BS_Nf[w][nAccepted] = Nf[w];
        //            BS_Nb[w][nAccepted] = Nb[w];
        //        }

        for ( int cW = 0; cW < nCW; cW++ )
            for ( int cBin = 0; cBin < nCentrBins[cW]; cBin++ )
            {
                cOccupancy[cW][cBin].fill(brV0M, brZEMvsZDC);
                for ( int etaW = 0; etaW < nEtaWins; etaW++ )
                    for ( int phiW = 0; phiW < nPhiWins; phiW++ )
                        wins[cW][cBin][etaW][phiW].fill( cEstimator, br[etaW][phiW].nF, br[etaW][phiW].nB, br[etaW][phiW].PtF, br[etaW][phiW].PtB );
            }

        nAccepted++;


    } // end of events
    cout << "nAccepted = " << nAccepted << endl;
    cout << "nAccepted/nAll = " << (float)nAccepted/nEvents << endl;


    // ########## QA PLOTTING:
    TCanvas *canv_estimatorPercentiles_QA_all = new TCanvas("canv_estimatorPercentiles_QA_all","canv_estimatorPercentiles_QA_all",0,0,700,600 );
    hist1D_QA_percentilesEstimator->DrawCopy();

    TCanvas *canv_hist1D_QA_multALL = new TCanvas("canv_hist1D_QA_multALL","canv_hist1D_QA_multALL",50,50,700,600 );
    hist1D_QA_multALL->DrawCopy();


    // MULT BINNING:
    int nCentrBinsMult = 10;
    cout << "nCentrBins=" << nCentrBinsMult << endl;
    double *estBounds = new double[nCentrBinsMult]; // array to contain the quantiles
    getQuantiles(hist1D_QA_multALL, nCentrBinsMult, estBounds);
    drawCanvasWithClasses( hist1D_QA_multALL, "byMultTPC", nCentrBinsMult, estBounds );




    // ##########MAIN PLOTTING FOR CORRS:

    TGraphErrors *grNN [nCW][nEtaWins];
    TGraphErrors *grPtPt[nCW][nEtaWins];
    TGraphErrors *grPtN[nCW][nEtaWins];

    TGraphErrors *grFractEstByV0M[nCW];
    TGraphErrors *grFractEstByZDC[nCW];

    for ( int cW = 0; cW < nCW; cW++ )
    {
        grFractEstByV0M[cW] = new TGraphErrors;
        grFractEstByZDC[cW] = new TGraphErrors;
        for ( int etaW = 0; etaW < nEtaWins; etaW++ )
        {
            grNN[cW][etaW] = new TGraphErrors;
            grPtPt[cW][etaW] = new TGraphErrors;
            grPtN[cW][etaW] = new TGraphErrors;
        }
    }


    //calc (1) - occupancies in centr bins, (2) - corr coeffs
    for ( int cW = 0; cW < nCW; cW++ )
        for ( int cBin = 0; cBin < nCentrBins[cW]; cBin++ )
        {
            if ( cOccupancy[cW][cBin].nEventsV0M > 0 )
            {
                CentralityOccupancy *c = &cOccupancy[cW][cBin];
                float centr = c->cBinMin + (c->cBinMax - c->cBinMin)/2;
                float cRatio = 0;
                if (c->nEventsV0M>0)
                    cRatio = (float)c->nEventsV0M_and_ZDCZEM / c->nEventsV0M;
                grFractEstByV0M[cW]->SetPoint(grFractEstByV0M[cW]->GetN(), centr, cRatio);
                if (c->nEventsZDCZEM>0)
                    cRatio = (float)c->nEventsV0M_and_ZDCZEM / c->nEventsZDCZEM;
                grFractEstByZDC[cW]->SetPoint(grFractEstByZDC[cW]->GetN(), centr, cRatio);
            }
            for ( int etaW = 0; etaW < nEtaWins; etaW++ )
                for ( int phiW = 0; phiW < nPhiWins; phiW++ )
                {
                    WinPair *w = &wins[cW][cBin][etaW][phiW];
                    float centr = w->cBinMin + (w->cBinMax - w->cBinMin)/2;
                    w->calcCorrCoeffs();
                    if(0)cout << "cMin=" << w->cBinMin << ", cMax=" << w->cBinMax << ", etaW=" << etaW
                              << ", NN_bCorr= " << w->NN_bCorr
                              << ", PtPt_bCorr= " << w->PtPt_bCorr
                              << endl;

                    //fill graphs
                    TGraphErrors *gr;
                    //gr NN
                    gr = grNN[cW][etaW];
                    if ( fabs(w->NN_bCorr) < 10 )
                        gr->SetPoint(gr->GetN(), centr, w->NN_bCorr);
                    //gr PtPt
                    gr = grPtPt[cW][etaW];
                    if ( fabs(w->PtPt_bCorr) < 10 )
                        gr->SetPoint(gr->GetN(), centr, w->PtPt_bCorr);
                    //gr PtN
                    gr = grPtN[cW][etaW];
                    if ( fabs(w->PtN_bCorr) < 10 )
                        gr->SetPoint(gr->GetN(), centr, w->PtN_bCorr);

                }
        }

    int colors[] = { kBlack, kBlack, kBlue, kRed, kMagenta };
    int markers[] = { 20, 24, 5, 2, 21 };

    // NN
    TCanvas *canv_grNN = new TCanvas("canv_grNN","canv_grNN",20,50,700,600 );
    tuneCanvas(canv_grNN);
    grNN[0][0]->SetTitle( ";centrality percentile;b_{corr}" ); //C_{2}
    tuneGraphAxisLabels(grNN[0][0]);


    //centr 10
    drawGraph(grNN[0][0], 20, kBlack, "AP");
    //    drawGraph(grNN[0][1], 21, kBlack, "P");
    //    drawGraph(grNN[0][2], 22, kBlack, "P");

    for ( int cW = 1; cW < nCW; cW++ )
        drawGraph(grNN[cW][0], markers[cW], colors[cW], "P");

    grNN[0][0]->SetMinimum( 0 );

    TLegend *leg = new TLegend(0.65,0.65,0.999,0.95);
    leg->SetFillColor(kWhite);
    leg->SetFillStyle(0);
    leg->SetBorderSize(0);
    for ( int cW = 0; cW < nCW; cW++ )
        leg->AddEntry(grNN[cW][0], Form("class width %.1f", cWidths[cW]), "p");
    leg->Draw();

    TLatex *tex = new TLatex(0.7,0.4, "#eta_{gap}=0.8, #delta#eta=0.4");
    drawTex(tex, 0.045);

    tex = new TLatex(0.4,0.89, "NN");
    drawTex(tex, 0.045);


    TString strPostfix;

    if (flag_V0M_ZDC==0)
        strPostfix = Form("V0M.eps");
    else
        strPostfix = Form("ZDCZEM.eps");

    canv_grNN->SaveAs( Form("NN_%s", strPostfix.Data() ) );

    // PtPt
    TCanvas *canv_grPtPt = new TCanvas("canv_grPtPt","canv_grPtPt",250,50,700,600 );
    tuneCanvas(canv_grPtPt);
    grPtPt[0][0]->SetTitle( ";centrality percentile;b_{corr}" ); //C_{2}
    tuneGraphAxisLabels(grPtPt[0][0]);


    //centr 10
    drawGraph(grPtPt[0][0], 20, kBlack, "AP");
    //    drawGraph(grPtPt[0][1], 21, kBlack, "P");
    //    drawGraph(grPtPt[0][2], 22, kBlack, "P");

    for ( int cW = 1; cW < nCW; cW++ )
        drawGraph(grPtPt[cW][0], markers[cW], colors[cW], "P");

    grPtPt[0][0]->SetMinimum( 0 );

    leg = new TLegend(0.65,0.65,0.999,0.95);
    leg->SetFillColor(kWhite);
    leg->SetFillStyle(0);
    leg->SetBorderSize(0);
    for ( int cW = 0; cW < nCW; cW++ )
        leg->AddEntry(grPtPt[cW][0], Form("class width %.1f", cWidths[cW]), "p");
    leg->Draw();

    tex = new TLatex(0.7,0.4, "#eta_{gap}=0.8, #delta#eta=0.4");
    drawTex(tex, 0.045);

    tex = new TLatex(0.4,0.89, "PtPt");
    drawTex(tex, 0.045);


    canv_grNN->SaveAs( Form("PtPt_%s", strPostfix.Data() ) );

    // PtN
    TCanvas *canv_grPtN = new TCanvas("canv_grPtN","canv_grPtN",450,50,700,600 );
    tuneCanvas(canv_grPtN);
    grPtN[0][0]->SetTitle( ";centrality percentile;b_{corr}" ); //C_{2}
    tuneGraphAxisLabels(grPtN[0][0]);


    //centr 10
    drawGraph(grPtN[0][0], 20, kBlack, "AP");
    //    drawGraph(grPtN[0][1], 21, kBlack, "P");
    //    drawGraph(grPtN[0][2], 22, kBlack, "P");

    for ( int cW = 1; cW < nCW; cW++ )
        drawGraph(grPtN[cW][0], markers[cW], colors[cW], "P");

    grPtN[0][0]->SetMinimum( 0 );
    leg = new TLegend(0.65,0.65,0.999,0.95);
    leg->SetFillColor(kWhite);
    leg->SetFillStyle(0);
    leg->SetBorderSize(0);
    for ( int cW = 0; cW < nCW; cW++ )
        leg->AddEntry(grPtN[cW][0], Form("class width %.1f", cWidths[cW]), "p");
    leg->Draw();

    tex = new TLatex(0.7,0.4, "#eta_{gap}=0.8, #delta#eta=0.4");
    drawTex(tex, 0.045);

    tex = new TLatex(0.4,0.89, "PtN");
    drawTex(tex, 0.045);


    canv_grNN->SaveAs( Form("PtN_%s", strPostfix.Data() ) );



    TCanvas *canv_grPtN_2D = new TCanvas("canv_grPtN_2D","canv_grPtN_2D",450,50,700,600 );
    tuneCanvas(canv_grPtN_2D);


    //    wins[0][0][0][0].hist2D_PtN->DrawCopy();
    wins[0][0][0][0].hist2D_PtN->ProfileX()->DrawCopy();



    // CENTR ESTIMATOR EVENT RATIO:
    TCanvas *canv_grCentrRatio = new TCanvas("canv_grCentrRatio","canv_grCentrRatio",450,250,700,600 );
    tuneCanvas(canv_grCentrRatio);
    grFractEstByV0M[0]->SetTitle(";centrality percentile;ratio");
    tuneGraphAxisLabels(grFractEstByV0M[0]);
    //centr 10
    drawGraph(grFractEstByV0M[0], 20, kBlack, "AP");
    //    drawGraph(grFractEstByZDC[0], 20, kBlack, "L");

    for ( int cW = 1; cW < nCW; cW++ )
        drawGraph(grFractEstByV0M[cW], markers[cW], colors[cW], "P");

    leg = new TLegend(0.65,0.65,0.999,0.95,"ratio #frac{V0M-and-ZEMZDC}{V0M}");
    leg->SetFillColor(kWhite);
    leg->SetFillStyle(0);
    leg->SetBorderSize(0);

    for ( int cW = 0; cW < nCW; cW++ )
        leg->AddEntry(grFractEstByV0M[cW], Form("class width %.1f", cWidths[cW]), "p");
    leg->Draw();
    //    leg->SetHeader("ratio #frac{V0M-and-ZEMZDC}/{V0M}");

    canv_grCentrRatio->SaveAs("ratio_V0M-and-ZEMZDC_by_V0M.eps");

    // CENTR ESTIMATOR PERCENTILES QA:
    TCanvas *canv_estimatorPercentiles_QA = new TCanvas("canv_estimatorPercentiles_QA","canv_estimatorPercentiles_QA",50,350,700,600 );
    for ( int cBin = 0; cBin < nCentrBins[0]; cBin++ )
    {
        TH1D *h = wins[0][cBin][0][0].hist1D_EstimatorEntries;
        h->SetLineColor(kOrange-9+cBin);
        if ( cBin == 0 )
            h->DrawCopy();
        else
            h->DrawCopy("same");
    }


    // MULT F IN CENTR CLASSES QA:
    TCanvas *canv_mult_F_in_centr_QA = new TCanvas("canv_mult_F_in_centr_QA","canv_mult_F_in_centr_QA",50,400,700,600 );
    gPad->SetLogy();
    for ( int cBin = 0; cBin < nCentrBins[0]; cBin++ )
    {
        TH1D *h = wins[0][cBin][0][0].hist1D_multDistrF;
        h->SetLineColor(kOrange-9+cBin);

        if ( cBin == 0 )
        {
            h->SetLineColor(kRed);
            h->GetYaxis()->SetRangeUser(1,100000);
        }

        if ( cBin == 0 )
            h->DrawCopy();
        else
            h->DrawCopy("same");
    }


    // Check entries in centrality bins:
    for ( int cW = 0; cW < nCW; cW++ )
    {
        cout << " ###### cW = " << cW << endl;
        for ( int cBin = 0; cBin < nCentrBins[cW]; cBin++ )
        {
            TH1D *h = wins[cW][cBin][0][0].hist1D_multDistrF;
            cout << "cBin = " << h->GetEntries() << endl;
//            h->SetLineColor(kOrange-9+cBin);
//            if ( cBin == 0 )
//                h->DrawCopy();
//            else
//                h->DrawCopy("same");
        }
    }

    return;
}
void rebinmacro() {
  for (int filecounter = 0; filecounter < 5; filecounter++) { //FILE LOOP
    if (filecounter == 0) {
      TFile *MyFile = new TFile("balanceout1234.root", "Read"); // 40 TO 60 PT AVERAGE
      if (MyFile->IsOpen()) printf("File Opened Successfully.\n");
      gFile = MyFile;
      MyFile->ls();
      TH1F *balance = (TH1F *)MyFile->Get("balance");
      TH1F *outereta = (TH1F *)MyFile->Get("outereta");
      TH1F *innereta = (TH1F *)MyFile->Get("innereta");
      TFile *rebinfile = new TFile("rebinout1234.root", "Recreate"); // 40 TO 60 PT AVERAGE
    }
    if (filecounter == 1) {
      TFile *MyFile = new TFile("balanceout123.root", "Read"); // 60 TO 80 PT AVERAGE
      if (MyFile->IsOpen()) printf("File Opened Successfully.\n");
      gFile = MyFile;
      MyFile->ls();
      TH1F *balance = (TH1F *)MyFile->Get("balance");
      TH1F *outereta = (TH1F *)MyFile->Get("outereta");
      TH1F *innereta = (TH1F *)MyFile->Get("innereta");
      TFile *rebinfile = new TFile("rebinout123.root", "Recreate"); // 60 TO 80 PT AVERAGE
    }
    if (filecounter == 2) {
      TFile *MyFile = new TFile("balanceout1.root", "Read"); // 80 TO 100 PT AVERAGE
      if (MyFile->IsOpen()) printf("File Opened Successfully.\n");
      gFile = MyFile;
      MyFile->ls();
      TH1F *balance = (TH1F *)MyFile->Get("balance");
      TH1F *outereta = (TH1F *)MyFile->Get("outereta");
      TH1F *innereta = (TH1F *)MyFile->Get("innereta");
      TFile *rebinfile = new TFile("rebinout1.root", "Recreate"); // 80 TO 100 PT AVERAGE
    }
    if (filecounter == 3) {
      TFile *MyFile = new TFile("balanceout.root", "Read"); // 100 TO 140 PT AVERAGE
      if (MyFile->IsOpen()) printf("File Opened Successfully.\n");
      gFile = MyFile;
      MyFile->ls();
      TH1F *balance = (TH1F *)MyFile->Get("balance");
      TH1F *outereta = (TH1F *)MyFile->Get("outereta");
      TH1F *innereta = (TH1F *)MyFile->Get("innereta");
      TFile *rebinfile = new TFile("rebinout.root", "Recreate"); // 100 TO 140 PT AVERAGE
    }
    if (filecounter == 4) {
      TFile *MyFile = new TFile("balanceout12.root", "Read"); // 140 TO 200 PT AVERAGE
      if (MyFile->IsOpen()) printf("File Opened Successfully.\n");
      gFile = MyFile;
      MyFile->ls();
      TH1F *balance = (TH1F *)MyFile->Get("balance");
      TH1F *outereta = (TH1F *)MyFile->Get("outereta");
      TH1F *innereta = (TH1F *)MyFile->Get("innereta");
      TFile *rebinfile = new TFile("rebinout12.root", "Recreate"); // 140 TO 200 PT AVERAGE
    }
 
  Float_t  cms_hcal_edge_pseudorapidity[83] = {-5.191, -4.889, -4.716, -4.538, -4.363, -4.191, -4.013, -3.839, -3.664, -3.489, -3.314, -3.139, -2.964, -2.853, -2.650, -2.500, -2.322, -2.172, -2.043, -1.930, -1.830, -1.740, -1.653, -1.566, -1.479, -1.392, -1.305, -1.218, -1.131, -1.044, -0.957, -0.879, -0.783, -0.696, -0.609, -0.522, -0.435, -0.348, -0.261, -0.174, -0.087, 0.000, 0.087,  0.174,  0.261,  0.348,  0.435,  0.522,  0.609, 0.696,  0.783,  0.879,  0.957,  1.044,  1.131,  1.218, 1.305,  1.392,  1.479,  1.566,  1.653,  1.740,  1.830, 1.930,  2.043,  2.172,  2.322,  2.500,  2.650,  2.853, 2.964,  3.139,  3.314,  3.489,  3.664,  3.839,  4.013, 4.191,  4.363,  4.538,  4.716,  4.889,  5.191};
  Float_t xcoordinate[82];
  Float_t intbalance[82];
  Float_t intinnereta[82];
  Float_t intoutereta[82];
 

  for (int count = 0; count < 82; count++) {
    Float_t lowerbound = cms_hcal_edge_pseudorapidity[count];
    Float_t upperbound = cms_hcal_edge_pseudorapidity[count + 1]; 
    Int_t lowerbin = balance->FindBin(lowerbound);
    Int_t upperbin = balance->FindBin(upperbound);
    Float_t integral = balance->Integral(lowerbin, upperbin);
    Float_t integral1 = innereta->Integral(lowerbin, upperbin);
    Float_t integral2 = outereta->Integral(lowerbin, upperbin);
    xcoordinate[count] = (lowerbound + upperbound)/2; 
    intbalance[count] = integral;
    //cout << "My x-coordinate is " << xcoordinate[count] << " and my integral is " << intbalance[count] << endl;
    intinnereta[count] = integral1;
    intoutereta[count] = integral2;
    //balancerebin->Fill(integral);
    //inneretarebin->Fill(integral1);
    //outeretarebin->Fill(integral2);
  }
TGraph *balancerebin = new TGraph(82, xcoordinate, intbalance);
TGraph *inneretarebin = new TGraph(82, xcoordinate, intinnereta);
TGraph *outeretarebin = new TGraph(82, xcoordinate, intoutereta);

balancerebin->SetTitle("Rebin Full Eta Range");
balancerebin->GetXaxis()->SetTitle("Dijet Balance");
balancerebin->GetYaxis()->SetTitle("Event Fraction");
balancerebin->SetMarkerStyle(8);
balancerebin->SetLineColor(0);
inneretarebin->SetTitle("Rebin Inner Eta Range");
inneretarebin->GetXaxis()->SetTitle("Dijet Balance");
inneretarebin->GetYaxis()->SetTitle("Event Fraction");
inneretarebin->SetMarkerStyle(8);
inneretarebin->SetLineColor(0);
outeretarebin->SetTitle("Rebin Outer Eta Range");
outeretarebin->GetXaxis()->SetTitle("Dijet Balance");
outeretarebin->GetYaxis()->SetTitle("Event Fraction");
outeretarebin->SetMarkerStyle(8);
outeretarebin->SetLineColor(0);

//balancerebin->Draw("ACP");
//inneretarebin->Draw("ACP");
//outeretarebin->Draw("ACP");
  
TCanvas *brebin = new TCanvas(1);
brebin->cd();
balancerebin->Draw("ACP");

TCanvas *binnerrebin = new TCanvas(2);
binnerrebin->cd();
inneretarebin->Draw("ACP");

TCanvas *bouterrebin = new TCanvas(3);
bouterrebin->cd();
outeretarebin->Draw("ACP");
  //Double_t scalerebin = 1/balancerebin->Integral();
  //Double_t scaleinnerrebin = 1/inneretarebin->Integral();
  //Double_t scaleouterrebin = 1/outeretarebin->Integral();

  //balancerebin->Scale(scalerebin);
  //inneretarebin->Scale(scaleinnerrebin);
  //outeretarebin->Scale(scaleouterrebin);
  
  rebinfile->cd();
  balancerebin->Write();
  inneretarebin->Write();
  outeretarebin->Write();
  rebinfile->Close();
  MyFile->Close();

}
} //END FILE LOOP
void 
StandardHypoTestInvDemo(const char * infile = 0,
                        const char * wsName = "combined",
                        const char * modelSBName = "ModelConfig",
                        const char * modelBName = "",
                        const char * dataName = "obsData",                 
                        int calculatorType = 0,
                        int testStatType = 0, 
                        bool useCLs = true ,  
                        int npoints = 6,   
                        double poimin = 0,  
                        double poimax = 5, 
                        int ntoys=1000,
                        bool useNumberCounting = false,
                        const char * nuisPriorName = 0){
/*

  Other Parameter to pass in tutorial
  apart from standard for filename, ws, modelconfig and data

  type = 0 Freq calculator 
  type = 1 Hybrid calculator
  type = 2 Asymptotic calculator  
  type = 3 Asymptotic calculator using nominal Asimov data sets (not using fitted parameter values but nominal ones)

  testStatType = 0 LEP
  = 1 Tevatron 
  = 2 Profile Likelihood
  = 3 Profile Likelihood one sided (i.e. = 0 if mu < mu_hat)
  = 4 Profiel Likelihood signed ( pll = -pll if mu < mu_hat) 
  = 5 Max Likelihood Estimate as test statistic
  = 6 Number of observed event as test statistic

  useCLs          scan for CLs (otherwise for CLs+b)    

  npoints:        number of points to scan , for autoscan set npoints = -1 

  poimin,poimax:  min/max value to scan in case of fixed scans 
  (if min >  max, try to find automatically)                           

  ntoys:         number of toys to use 

  useNumberCounting:  set to true when using number counting events 

  nuisPriorName:   name of prior for the nnuisance. This is often expressed as constraint term in the global model
  It is needed only when using the HybridCalculator (type=1)
  If not given by default the prior pdf from ModelConfig is used. 

  extra options are available as global paramwters of the macro. They major ones are: 

  plotHypoTestResult   plot result of tests at each point (TS distributions) (defauly is true)
  useProof             use Proof   (default is true) 
  writeResult          write result of scan (default is true)
  rebuild              rebuild scan for expected limits (require extra toys) (default is false)
  generateBinned       generate binned data sets for toys (default is false) - be careful not to activate with 
  a too large (>=3) number of observables 
  nToyRatio            ratio of S+B/B toys (default is 2)
    

*/

  
  
   TString fileName(infile);
   if (fileName.IsNull()) { 
      fileName = "results/example_combined_GaussExample_model.root";
      std::cout << "Use standard file generated with HistFactory : " << fileName << std::endl;
   }
  
   // open file and check if input file exists
   TFile * file = TFile::Open(fileName); 
  
   // if input file was specified but not found, quit
   if(!file && !TString(infile).IsNull()){
      cout <<"file " << fileName << " not found" << endl;
      return;
   } 
  
   // if default file not found, try to create it
   if(!file ){
      // Normally this would be run on the command line
      cout <<"will run standard hist2workspace example"<<endl;
      gROOT->ProcessLine(".! prepareHistFactory .");
      gROOT->ProcessLine(".! hist2workspace config/example.xml");
      cout <<"\n\n---------------------"<<endl;
      cout <<"Done creating example input"<<endl;
      cout <<"---------------------\n\n"<<endl;
    
      // now try to access the file again
      file = TFile::Open(fileName);
    
   }
  
   if(!file){
      // if it is still not there, then we can't continue
      cout << "Not able to run hist2workspace to create example input" <<endl;
      return;
   }
  


   HypoTestInvTool calc;

   // set parameters
   calc.SetParameter("PlotHypoTestResult", plotHypoTestResult);
   calc.SetParameter("WriteResult", writeResult);
   calc.SetParameter("Optimize", optimize);
   calc.SetParameter("UseVectorStore", useVectorStore);
   calc.SetParameter("GenerateBinned", generateBinned);
   calc.SetParameter("NToysRatio", nToysRatio);
   calc.SetParameter("MaxPOI", maxPOI);
   calc.SetParameter("UseProof", useProof);
   calc.SetParameter("NWorkers", nworkers);
   calc.SetParameter("Rebuild", rebuild);
   calc.SetParameter("ReuseAltToys", reuseAltToys);
   calc.SetParameter("NToyToRebuild", nToyToRebuild);
   calc.SetParameter("MassValue", massValue.c_str());
   calc.SetParameter("MinimizerType", minimizerType.c_str());
   calc.SetParameter("PrintLevel", printLevel);
   calc.SetParameter("InitialFit",initialFit);
   calc.SetParameter("ResultFileName",resultFileName);
   calc.SetParameter("RandomSeed",randomSeed);
   calc.SetParameter("AsimovBins",nAsimovBins);


   RooWorkspace * w = dynamic_cast<RooWorkspace*>( file->Get(wsName) );
   HypoTestInverterResult * r = 0;  
   std::cout << w << "\t" << fileName << std::endl;
   if (w != NULL) {
      r = calc.RunInverter(w, modelSBName, modelBName,
                           dataName, calculatorType, testStatType, useCLs,
                           npoints, poimin, poimax,  
                           ntoys, useNumberCounting, nuisPriorName );    
      if (!r) { 
         std::cerr << "Error running the HypoTestInverter - Exit " << std::endl;
         return;          
      }
   }
   else { 
      // case workspace is not present look for the inverter result
      std::cout << "Reading an HypoTestInverterResult with name " << wsName << " from file " << fileName << std::endl;
      r = dynamic_cast<HypoTestInverterResult*>( file->Get(wsName) ); //
      if (!r) { 
         std::cerr << "File " << fileName << " does not contain a workspace or an HypoTestInverterResult - Exit " 
                   << std::endl;
         file->ls();
         return; 
      }
   }		
  
   calc.AnalyzeResult( r, calculatorType, testStatType, useCLs, npoints, infile );
  
   return;
}
void photonContainmentAnalysis() {

  gStyle->SetOptFit(1111);
  
  TFile *infile = new TFile("contCorrAnalyzer.root");
  infile->ls();
  
  TH1F *theHistos[2];
  theHistos[0] = (TH1F*)infile->Get("contCorrAnalyzer/EB_e25EtrueReference");
  theHistos[1] = (TH1F*)infile->Get("contCorrAnalyzer/EE_e25EtrueReference");
  
  // fitting the distributions to extract the parameter
  TF1 *gausa;
  TF1 *cb_p;
  for(int myH=0; myH<2; myH++) {
  
    // histos parameters
    int peakBin   = theHistos[myH]->GetMaximumBin();
    double h_norm = theHistos[myH]->GetMaximum();
    double h_rms  = theHistos[myH]->GetRMS();
    double h_mean = theHistos[myH]->GetMean();
    double h_peak = theHistos[myH]->GetBinCenter(peakBin);
    
    // gaussian fit to initialize
    gausa = new TF1 ("gausa","[0]*exp(-1*(x-[1])*(x-[1])/2/[2]/[2])",h_peak-10*h_rms,h_peak+10*h_rms);
    gausa ->SetParameters(h_norm,h_peak,h_rms);
    theHistos[myH]->Fit("gausa","","",h_peak-3*h_rms,h_peak+3*h_rms);
    double gausNorm  = gausa->GetParameter(0);
    double gausMean  = gausa->GetParameter(1);
    double gausSigma = fabs(gausa->GetParameter(2));
    double gausChi2  = gausa->GetChisquare()/gausa->GetNDF();
    if (gausChi2>100){ gausMean = h_peak; gausSigma = h_rms; }
    
    // crystalball limits
    double myXmin = gausMean - 7.*gausSigma;
    double myXmax = gausMean + 5.*gausSigma;
    
    // crystalball fit
    cb_p = new TF1 ("cb_p",crystalball,myXmin,myXmax, 5) ;
    cb_p->SetParNames ("Mean","Sigma","alpha","n","Norm","Constant");
    cb_p->SetParameter(0, gausMean);
    cb_p->SetParameter(1, gausSigma);
    cb_p->SetParameter(2, 1.);
    cb_p->SetParLimits(2, 0.1, 5.);
    cb_p->FixParameter(3, 5.);
    cb_p->SetParameter(4, gausNorm);
    theHistos[myH]->Fit("cb_p","lR","",myXmin,myXmax);
    theHistos[myH]->GetXaxis()->SetRangeUser(0.95,1.05); 
    double matrix_gmean      = cb_p->GetParameter(0);
    double matrix_gmean_err  = cb_p->GetParError(0);
    
    c1->Update();
    if(myH == 0) { 
      c1->SaveAs("e25EtrueReference_EB.eps");
      std::cout << "E25 barrel containment: " << matrix_gmean << " +/- " << matrix_gmean_err << std::endl; 
    }
    if(myH == 1) { 
      c1->SaveAs("e25EtrueReference_EE.eps");
      std::cout << "E25 endcap containment: " << matrix_gmean << " +/- " << matrix_gmean_err << std::endl; 
    }
  }
}
void makePlot(const std::string& inputFilePath, const std::string& canvasName, const std::string& sample, int massPoint, const std::string& channel, double k, 
	      const std::string& inputFileName, const std::string& outputFilePath, const std::string& outputFileName)
{
  std::string inputFileName_full = Form("%s%s", inputFilePath.data(), inputFileName.data());
  TFile* inputFile = new TFile(inputFileName_full.data());
  if ( !inputFile ) {
    std::cerr << "Failed to open input file = " << inputFileName_full << " !!" << std::endl;
    assert(0);
  }

  inputFile->ls();

  TCanvas* canvas = dynamic_cast<TCanvas*>(inputFile->Get(canvasName.data()));
  if ( !canvas ) {
    std::cerr << "Failed to load canvas = " << canvasName << " !!" << std::endl;
    assert(0);
  }

  int idxPad = -1;
  if ( massPoint ==  90 ) idxPad = 1;
  if ( massPoint == 125 ) idxPad = 2;
  if ( massPoint == 200 ) idxPad = 3;
  if ( massPoint == 300 ) idxPad = 4;
  if ( massPoint == 500 ) idxPad = 5;
  if ( massPoint == 800 ) idxPad = 6;  
  if ( !(idxPad >= 1 && idxPad <= 6) ) {
    std::cerr << "Invalid sample = " << sample << " !!" << std::endl;
    assert(0);
  }
  TVirtualPad* pad = canvas->GetPad(idxPad);
  std::cout << "pad = " << pad << ": ClassName = " << pad->ClassName() << std::endl;

  TCanvas* canvas_new = new TCanvas("canvas_new", "canvas_new", 900, 800);
  canvas_new->SetFillColor(10);
  canvas_new->SetBorderSize(2);
  canvas_new->SetTopMargin(0.065);
  canvas_new->SetLeftMargin(0.17);
  canvas_new->SetBottomMargin(0.165);
  canvas_new->SetRightMargin(0.015);
  canvas_new->SetLogx(true);
  canvas_new->SetLogy(true);
  canvas_new->Draw();
  canvas_new->cd();

  //TList* pad_primitives = canvas->GetListOfPrimitives();
  TList* pad_primitives = pad->GetListOfPrimitives();

  TH1* histogramCA            = 0;
  TH1* histogramSVfit         = 0;
  TH1* histogramSVfitMEMkEq0  = 0;
  TH1* histogramSVfitMEMkNeq0 = 0;

  TIter pad_nextObj(pad_primitives);
  while ( TObject* obj = pad_nextObj() ) {
    std::string objName = "";
    if ( dynamic_cast<TNamed*>(obj) ) objName = (dynamic_cast<TNamed*>(obj))->GetName();    
    std::cout << "obj = " << obj << ": name = " << objName << ", type = " << obj->ClassName() << std::endl;

    TH1* tmpHistogram = dynamic_cast<TH1*>(obj);
    if ( tmpHistogram ) {
      std::cout << "tmpHistogram:" 
		<< " fillColor = " << tmpHistogram->GetFillColor() << ", fillStyle = " << tmpHistogram->GetFillStyle() << ","
		<< " lineColor = " << tmpHistogram->GetLineColor() << ", lineStyle = " << tmpHistogram->GetLineStyle() << ", lineWidth = " << tmpHistogram->GetLineWidth() << ","
		<< " markerColor = " << tmpHistogram->GetMarkerColor() << ", markerStyle = " << tmpHistogram->GetMarkerStyle() << ", markerSize = " << tmpHistogram->GetMarkerSize() << ","
		<< " integral = " << tmpHistogram->Integral() << std::endl;
      std::cout << "(mean = " << tmpHistogram->GetMean() << ", rms = " << tmpHistogram->GetRMS() << ": rms/mean = " << (tmpHistogram->GetRMS()/tmpHistogram->GetMean()) << ")" << std::endl;
      if ( tmpHistogram->GetLineColor() == 416 ) histogramCA            = tmpHistogram;
      if ( tmpHistogram->GetLineColor() == 600 ) histogramSVfit         = tmpHistogram;
      if ( tmpHistogram->GetLineColor() == 616 ) histogramSVfitMEMkEq0  = tmpHistogram;
      if ( tmpHistogram->GetLineColor() == 632 ) histogramSVfitMEMkNeq0 = tmpHistogram;
    }
  }

  if ( !(histogramCA && histogramSVfit && histogramSVfitMEMkEq0 && histogramSVfitMEMkNeq0) ) {
    std::cerr << "Failed to load histograms !!" << std::endl;
    assert(0);
  }

  //gStyle->SetLineStyleString(2,"40 10 10 10 10 10 10 10");
  //gStyle->SetLineStyleString(3,"25 15");
  //gStyle->SetLineStyleString(4,"60 25");

  //int colors[4] = { kBlack, kGreen - 6, kBlue - 7, kMagenta - 7  };
  int colors[4] = { 28, kGreen - 6, kBlue - 7, kBlack };
  //int lineStyles[4] = { 2, 3, 4, 1 };
  int lineStyles[4] = { 7, 1, 1, 1 };
  //int lineWidths[4] = { 3, 3, 4, 3 };
  int lineWidths[4] = { 3, 3, 1, 1 };
  int markerStyles[4] = { 20, 25, 21, 24 };
  int markerSizes[4] = { 2, 2, 2, 2 };

  histogramCA->SetFillColor(0);
  histogramCA->SetFillStyle(0);
  histogramCA->SetLineColor(colors[0]);
  histogramCA->SetLineStyle(lineStyles[0]);
  histogramCA->SetLineWidth(lineWidths[0]);
  histogramCA->SetMarkerColor(colors[0]);
  histogramCA->SetMarkerStyle(markerStyles[0]);
  histogramCA->SetMarkerSize(markerSizes[0]);

  histogramSVfit->SetFillColor(0);
  histogramSVfit->SetFillStyle(0);
  histogramSVfit->SetLineColor(colors[1]);
  histogramSVfit->SetLineStyle(lineStyles[1]);
  histogramSVfit->SetLineWidth(lineWidths[1]);
  histogramSVfit->SetMarkerColor(colors[1]);
  histogramSVfit->SetMarkerStyle(markerStyles[1]);
  histogramSVfit->SetMarkerSize(markerSizes[1]);

  histogramSVfitMEMkEq0->SetFillColor(0);
  histogramSVfitMEMkEq0->SetFillStyle(0);
  histogramSVfitMEMkEq0->SetLineColor(colors[2]);
  histogramSVfitMEMkEq0->SetLineStyle(lineStyles[2]);
  histogramSVfitMEMkEq0->SetLineWidth(lineWidths[2]);
  histogramSVfitMEMkEq0->SetMarkerColor(colors[2]);
  histogramSVfitMEMkEq0->SetMarkerStyle(markerStyles[2]);
  histogramSVfitMEMkEq0->SetMarkerSize(markerSizes[2]);
  // CV: fix pathological bins at high mass for which dN/dm increases
  int numBins = histogramSVfitMEMkEq0->GetNbinsX();
  for ( int idxBin = 1; idxBin <= numBins; ++idxBin ) {
    double binCenter = histogramSVfitMEMkEq0->GetBinCenter(idxBin);
    if ( (channel == "#tau_{h}#tau_{h}" && massPoint == 500 && binCenter > 1500.) ||
	 (channel == "#tau_{h}#tau_{h}" && massPoint == 800 && binCenter > 2000.) ||
	 (channel == "#mu#tau_{h}"      && massPoint == 500 && binCenter > 1500.) ||
	 (channel == "#mu#tau_{h}"      && massPoint == 800 && binCenter > 2500.) ) {
      histogramSVfitMEMkEq0->SetBinContent(idxBin, 0.);
    }
  }

  histogramSVfitMEMkNeq0->SetFillColor(0);
  histogramSVfitMEMkNeq0->SetFillStyle(0);
  histogramSVfitMEMkNeq0->SetLineColor(colors[3]);
  histogramSVfitMEMkNeq0->SetLineStyle(lineStyles[3]);
  histogramSVfitMEMkNeq0->SetLineWidth(lineWidths[3]);
  histogramSVfitMEMkNeq0->SetMarkerColor(colors[3]);
  histogramSVfitMEMkNeq0->SetMarkerStyle(markerStyles[3]);
  histogramSVfitMEMkNeq0->SetMarkerSize(markerSizes[3]);

  TAxis* xAxis = histogramCA->GetXaxis();
  xAxis->SetTitle("m_{#tau#tau} [GeV]");
  xAxis->SetTitleOffset(1.15);
  xAxis->SetTitleSize(0.070);
  xAxis->SetTitleFont(42);
  xAxis->SetLabelOffset(0.010);
  xAxis->SetLabelSize(0.055);
  xAxis->SetLabelFont(42);
  xAxis->SetTickLength(0.040);
  xAxis->SetNdivisions(510);

  //double xMin = 20.;
  //double xMax = xAxis->GetXmax();
  //xAxis->SetRangeUser(xMin, xMax);

  TAxis* yAxis = histogramCA->GetYaxis();
  yAxis->SetTitle("dN/dm_{#tau#tau} [1/GeV]");
  yAxis->SetTitleOffset(1.20);
  yAxis->SetTitleSize(0.070);
  yAxis->SetTitleFont(42);
  yAxis->SetLabelOffset(0.010);
  yAxis->SetLabelSize(0.055);
  yAxis->SetLabelFont(42);
  yAxis->SetTickLength(0.040);  
  yAxis->SetNdivisions(505);

  double massPoint_double = 0.;
  if ( massPoint == 90 ) massPoint_double = 91.2;
  else massPoint_double = massPoint;
  double dLog = (TMath::Log(5.*massPoint_double) - TMath::Log(50.))/25.; // xMin = 50, xMax = 5*massPoint, numBins = 25
  double binWidth = TMath::Exp(TMath::Log(massPoint_double) + 0.5*dLog) - TMath::Exp(TMath::Log(massPoint_double) - 0.5*dLog);
  double sf_binWidth = 1./binWidth;
  std::cout << "massPoint = " << massPoint << ": sf_binWidth = " << sf_binWidth << std::endl;

  histogramCA->SetTitle("");
  histogramCA->SetStats(false);
  histogramCA->SetMaximum(sf_binWidth*0.79);
  histogramCA->SetMinimum(sf_binWidth*1.1e-4);
  histogramCA->Draw("hist");
  histogramSVfit->Draw("histsame");
  //histogramSVfitMEMkEq0->Draw("histsame");
  histogramSVfitMEMkEq0->Draw("epsame");
  //histogramSVfitMEMkNeq0->Draw("histsame");
  histogramSVfitMEMkNeq0->Draw("epsame");
  histogramCA->Draw("axissame");

  //TPaveText* label_sample = new TPaveText(0.21, 0.86, 0.46, 0.94, "NDC");
  TPaveText* label_sample = new TPaveText(0.1700, 0.9475, 0.4600, 1.0375, "NDC");
  label_sample->SetFillStyle(0);
  label_sample->SetBorderSize(0);
  label_sample->AddText(sample.data());
  label_sample->SetTextFont(42);
  label_sample->SetTextSize(0.055);
  label_sample->SetTextColor(1);
  label_sample->SetTextAlign(13);
  label_sample->Draw();

  //TLegend* legend_new = new TLegend(0.225, 0.52, 0.41, 0.82, NULL, "brNDC");
  TLegend* legend_new = new TLegend(0.30, 0.30, 0.80, 0.80, NULL, "brNDC");
  legend_new->SetFillColor(10);
  legend_new->SetFillStyle(0);
  legend_new->SetBorderSize(0);
  legend_new->SetTextFont(42);
  legend_new->SetTextSize(0.055);
  legend_new->SetTextColor(1);
  legend_new->SetMargin(0.20);
  legend_new->AddEntry(histogramCA, "CA", "l");
  legend_new->AddEntry(histogramSVfit, "SVfit", "l");
  //legend_new->AddEntry(histogramSVfitMEMkEq0, "SVfitMEM (k=0)", "l");
  legend_new->AddEntry(histogramSVfitMEMkEq0, "SVfitMEM (k=0)", "p");
  //legend_new->AddEntry(histogramSVfitMEMkNeq0, Form("SVfitMEM(k=%1.0f)", k), "l");
  legend_new->AddEntry(histogramSVfitMEMkNeq0, Form("SVfitMEM (k=%1.0f)", k), "p");
  //legend_new->Draw();

  double label_channel_y0;
  if      ( channel == "e#mu"             ) label_channel_y0 = 0.9275;
  else if ( channel == "#mu#tau_{h}"      ) label_channel_y0 = 0.9400;
  else if ( channel == "#tau_{h}#tau_{h}" ) label_channel_y0 = 0.9350;
  else {
    std::cerr << "Invalid channel = " << channel << " !!" << std::endl;
    assert(0);
  }
  TPaveText* label_channel = new TPaveText(0.895, label_channel_y0, 0.975, label_channel_y0 + 0.055, "NDC");
  label_channel->SetFillStyle(0);
  label_channel->SetBorderSize(0);
  label_channel->AddText(channel.data());
  label_channel->SetTextFont(62);
  label_channel->SetTextSize(0.055);
  label_channel->SetTextColor(1);
  label_channel->SetTextAlign(31);
  label_channel->Draw();

  canvas_new->Update();

  std::string outputFileName_full = Form("%s%s", outputFilePath.data(), outputFileName.data());
  size_t idx = outputFileName_full.find_last_of('.');
  std::string outputFileName_plot = std::string(outputFileName_full, 0, idx);
  canvas_new->Print(std::string(outputFileName_plot).append(".pdf").data());
  canvas_new->Print(std::string(outputFileName_plot).append(".root").data());

  std::string channel_string;
  if      ( channel == "e#mu"             ) channel_string = "emu";
  else if ( channel == "#mu#tau_{h}"      ) channel_string = "muhad";
  else if ( channel == "#tau_{h}#tau_{h}" ) channel_string = "hadhad";
  else {
    std::cerr << "Invalid channel = " << channel << " !!" << std::endl;
    assert(0);
  }
  std::string outputFileName_legend = Form("makeSVfitMEM_PerformancePlots_legend_%s.pdf", channel_string.data());
  makePlot_legend(legend_new, outputFilePath, outputFileName_legend);

  delete label_sample;
  delete legend_new;
  delete label_channel;
  delete canvas_new;

  delete inputFile;
}
Example #26
0
void createPlotsReco(const char * reco_file, const char * label, TH1D ** cumulative_matbdg) {
  std::vector<std::string> sDETS = {"Phase2PixelBarrel", "Phase22OTBarrel", "Phase2PixelEndcap", "Phase2OTForward" };
  std::vector<unsigned int> sLAYS = {4, 6, 12, 5};
  std::vector<std::string> sPREF = {"Original_RadLen_vs_Eta_", "RadLen_vs_Eta_"};
  std::vector<int> sCOLORS = {kRed, kBlue, kGreen, kYellow, kOrange, kPink};
  std::vector<TProfile*> profs;
  std::vector<TH1D*> histos;
  std::vector<TH1D*> diffs;
  std::vector<THStack *> stack;
  char name[1000];

  TCanvas * c = new TCanvas("c", "c", 1024, 1024);
  struct stat sb;
  if (stat(reco_file, &sb) == -1 ) {
    std::cerr << "Error opening file: " << reco_file << std::endl;
    return;
  }
  TFile * file = new TFile(reco_file);
  char prefix[100] = "/DQMData/Run 1/RecoMaterialFromRecoTracks/Run summary/";
  file->cd(prefix);
  file->ls();
  THStack *hs = new THStack("hs","");
  for (unsigned int s = 0; s < sPREF.size(); ++s) {
    histos.clear();
    profs.clear();
    stack.push_back(new THStack("hs",""));
    THStack * hs = stack.back();
    for (unsigned int i = 0; i < sDETS.size(); ++i) {
      for (unsigned int j = 1; j <= sLAYS[i]; ++j) {
        memset(name, 0, sizeof(name));
        snprintf(name, sizeof(name), "%s%s%s%d", prefix, sPREF[s].data(), sDETS[i].data(), j);
        profs.push_back((TProfile*)file->Get(name));
        if (profs.back()) {
          histos.push_back(profs.back()->ProjectionX("_px", "hist"));
          diffs.push_back(histos.back());
          histos.back()->SetFillColor(sCOLORS[i]+j);
          histos.back()->SetLineColor(sCOLORS[i]+j+1);
        } else {
          std::cout << "Missing profile " << name << std::endl;
        }
      }  // end of sLAYS
    }  // end of sDETS

    memset(name, 0, sizeof(name));
    snprintf(name, sizeof(name), "CumulativeRecoMatBdg_%s", sPREF[s].data());
    if (sPREF[s] == "RadLen_vs_Eta_") {
      *cumulative_matbdg = new TH1D(name,
                                    name,
                                    histos.front()->GetNbinsX(),
                                    histos.front()->GetXaxis()->GetXmin(),
                                    histos.front()->GetXaxis()->GetXmax());
    }
    for (auto h : histos) {
      hs->Add(h);
      if (*cumulative_matbdg)
        (*cumulative_matbdg)->Add(h, 1.);
    }
    hs->Draw();
    hs->GetYaxis()->SetTitle("RadLen");
    c->Update();
    c->Modified();
    c->SaveAs(std::string(sPREF[s]+std::string("stacked_")+std::string(label)+std::string(".png")).data());
  }  // end of sPREF
  stack.push_back(new THStack("diff",""));
  hs = stack.back();
  for (unsigned int d = 0; d < diffs.size()/2; ++d) {
    diffs[d+diffs.size()/2]->Add(diffs[d], -1.);
    hs->Add(diffs[d+diffs.size()/2]);
  }  // end of diffs
  hs->Draw();
  hs->GetYaxis()->SetTitle("RadLen");
  c->Update();
  c->Modified();
  std::string outfile("RadLen_difference_");
  outfile += label;
  outfile += ".png";
  c->SaveAs(outfile.data());
}
int main( int argc, char **argv ) {

  std::cout << "\nThis program converts efficiencies from Root to txt format." << std::endl;
  char* eff ;
  char* bins;
  float min=-100;
  float max=100; 
  bool sig = true;
  bool bkg = true;

  if(argc<5 ){
    std::cout << "\nlacking arguments. Usage:    efficiencyRoot2Txt <path/efficiencyFileName.root> <path/effFileName.txt> <eff name> <efftype> Min Max doSig doBkg\n" << std::endl;
    return -1;
  }
  else if (argc == 9){
    eff = argv[3];
    bins= argv[4];
    min = atof(argv[5]);
    max = atof(argv[6]);
    sig = atof(argv[7]);
    bkg = atof(argv[8]);
  }
  else if (argc == 7 || argc == 5){
    eff = argv[3];
    bins= argv[4];
    sig = 1;
    bkg = 1;
    if (argc == 7)
      {
	min = atof(argv[5]);
	max = atof(argv[6]);	
      }
  }
  else if (argc >9){
    std::cout << "too many arguments.   Usage: efficiencyFileHisto <path/efficiencyFileName.root> <path/effFile.txt> Efficiency  EffType Min Max doSig doBkg \n" << std::endl;
    return -1;
  }
  else if (argc == 8 || argc == 6){
    std::cout << "one more argument.   Usage: efficiencyFileHisto <path/efficiencyFileName.root> <path/effFile.txt> Efficiency   EffType Min Max DoSig DoBkg\n" << std::endl;
    return -1;
  }


  std::string effRootFileName = argv[1];
  std::string effTxtFileName = argv[2];

  std::string effTxtFileNameSig = "Sig"+effTxtFileName;
  std::string effTxtFileNameBkg = "Bkg"+effTxtFileName;
  
  std::cout << "root file containing efficiency is: " << effRootFileName << std::endl;
  std::cout << "txt file for signal histo efficiency is: " << effTxtFileNameSig << std::endl;
  std::cout << "txt file for backround histo efficiency is: " << effTxtFileNameBkg << std::endl;
  std::cout << "Type of Efficicnecy (eta,pt,rap) is: " << bins << std::endl;
  std::cout << "Min and Max for other variable is: " << min << " " << max << std::endl;

  TFile * effFile = new TFile(effRootFileName.c_str());

  if (effFile){     
    std::cout << "This is the content of the root file:\n\n" << std::endl;
    effFile->ls();
  }
  else
    {
      std::cout << "in efficienncyFileHisto program, file: " << effRootFileName << " not found" << std::endl;      
      return -1;
    }
  
  
  // created with root file in constructor
  SignalBackgroundExtraction Root2TxtObject(effFile, eff,bins,sig,bkg,true,60,120);

  //std::string textFileName(effTxtFileName.c_str());
  Root2TxtObject.setVarMinMax(min,max); //I should only do this is there are actually 7 args....
  Root2TxtObject.produceTxtFile(effTxtFileNameSig,"signal");
  Root2TxtObject.produceTxtFile(effTxtFileNameBkg,"background");


}
int main(int argc, char ** argv) {
	TStopwatch comulativeWatch;
	comulativeWatch.Start(true);
	readInputs(argc,argv);
	cout<<"Currrent Subversion Revision: "<<SVN_REV<<endl;
	cout << "starting main loop.." << endl;
	RunListOK = ReadRunList();
	if(!RunListOK)exit(-1);
	TSystem* sys = gSystem;
	std::string currentDir = sys->pwd();
	for (unsigned int i = 0; i < RunParameters.size(); i++) {
		cout << RunParameters[i].getRunNumber();
		if (i+1 < RunParameters.size()) cout << ", ";
	}
	cout << " will be analysed.." << endl;

	if (!RunListOK) return 0;

	/**Start with Analyising, read RunParameteres of the Run and start analysis with that parameters
	 */
	for (unsigned int i = 0; i < RunParameters.size(); i++) {
		TStopwatch runWatch;
		runWatch.Start(true);
		RunParameters[i].Print();
		bool DO_ALIGNMENT = RunParameters[i].doAlignment();
		bool DO_ALIGNMENTANALYSIS = RunParameters[i].doAlignmentAnalysis();
		bool DO_TRANSPARENT_ANALYSIS = RunParameters[i].doTransparentAnalysis();

		time_t rawtime;
		tm *timestamp;
		time (&rawtime);
		timestamp = gmtime(&rawtime);

		ostringstream logfilename;
		logfilename << "analyse_log_" << RunParameters[i].getRunNumber() << "_" << timestamp->tm_year << "-" << timestamp->tm_mon << "-" << timestamp->tm_mday << "." << timestamp->tm_hour << "." << timestamp->tm_min << "." << timestamp->tm_sec << ".log";
		//
		//		FILE *log;
		//		log = freopen(logfilename.str().c_str(), "w", stdout);


		TSettings *settings = 0;
		cout<<"settings"<<endl;
		settings = new TSettings((TRunInfo*)&RunParameters[i]);

		TResults *currentResults =new TResults(settings);
		currentResults->Print();


		TRawEventSaver *eventSaver;
		eventSaver = new TRawEventSaver(settings);
		eventSaver->saveEvents(RunParameters[i].getEvents());
		delete eventSaver;

		//Calculate Pedestal
		sys->cd(currentDir.c_str());
		TPedestalCalculation* pedestalCalculation;
		pedestalCalculation = new TPedestalCalculation(settings);
		pedestalCalculation->calculateSlidingPedestals(RunParameters[i].getEvents());
		delete pedestalCalculation;

		if(RunParameters[i].doPedestalAnalysis()){
			sys->cd(currentDir.c_str());
			TAnalysisOfPedestal *analysisOfPedestal;
			analysisOfPedestal = new TAnalysisOfPedestal(settings);
			analysisOfPedestal->setResults(currentResults);
			analysisOfPedestal->doAnalysis(RunParameters[i].getEvents());
			delete analysisOfPedestal;
		}

		THTMLGenerator *htmlGen = new THTMLGenerator(settings);
		htmlGen->setFileGeneratingPath(settings->getAbsoluteOuputPath(true));
		htmlGen->setMainPath("./");
		htmlGen->setSubdirPath("");
		htmlGen->setFileName("overview.html");
		htmlGen->addSection("Pedestal","<a href=\"./pedestalAnalysis/pedestal.html\">PEDESTAL</a>");
		htmlGen->addSection("Clustering","<a href=\"./clustering/clustering.html\">CLUSTERING</a>");
		htmlGen->addSection("Selection","<a href=\"./selections/selection.html\">SELECTION</a>");
		htmlGen->addSection("Alignment","<a href=\"./alignment/alignment.html\">ALIGNMENT</a>");
		htmlGen->addSection("Landau","<a href=\"./selectionAnalysis/landaus.html\">LANDAU-DISTRIBUTIONS</a>");
		htmlGen->generateHTMLFile();
		delete htmlGen;

		sys->cd(currentDir.c_str());
		TClustering* clustering;
		clustering=new TClustering(settings);//int seedDetSigma=10,int hitDetSigma=7,int seedDiaSigma=5, int hitDiaSigma=3);
		clustering->ClusterEvents(RunParameters[i].getEvents());
		delete clustering;

		if(RunParameters[i].doClusterAnalysis()){
			sys->cd(currentDir.c_str());
			TAnalysisOfClustering* analysisClustering;
			analysisClustering = new TAnalysisOfClustering(settings);
			analysisClustering->setResults(currentResults);
			analysisClustering->doAnalysis(RunParameters[i].getEvents());
			delete analysisClustering;
		}

		sys->cd(currentDir.c_str());
		TSelectionClass* selectionClass = new TSelectionClass(settings);
		selectionClass->SetResults(currentResults);
		selectionClass->MakeSelection(RunParameters[i].getEvents());
		delete selectionClass;

		if(RunParameters[i].doSelectionAnalysis()){
			sys->cd(currentDir.c_str());
			TAnalysisOfSelection *analysisSelection=new TAnalysisOfSelection(settings);
			analysisSelection->doAnalysis(RunParameters[i].getEvents());
			delete analysisSelection;
		}

		if (DO_ALIGNMENT){
			sys->cd(currentDir.c_str());
			TAlignment *alignment = new TAlignment(settings);
			//			alignment->setSettings(settings);
			//alignment->PrintEvents(1511,1501);
			alignment->Align(RunParameters[i].getEvents());
			delete alignment;
		}

		if(DO_ALIGNMENTANALYSIS){
			sys->cd(currentDir.c_str());
			TAnalysisOfAlignment *anaAlignment;
			anaAlignment=new TAnalysisOfAlignment(settings);
			anaAlignment->doAnalysis(RunParameters[i].getEvents());
			delete anaAlignment;
		}

		if (DO_TRANSPARENT_ANALYSIS) {
			TTransparentAnalysis *transpAna;
			transpAna = new TTransparentAnalysis(settings);
			transpAna->setResults(currentResults);
			transpAna->analyze(RunParameters[i].getEvents(),RunParameters.at(i).getStartEvent());
			delete transpAna;
		}

		if (settings && settings->doTransparentAlignmnet()){
			sys->cd(currentDir.c_str());
			TAlignment *alignment = new TAlignment(settings,TSettings::transparentMode);
			alignment->createTransparentEventVectors(RunParameters[i].getEvents());
			//			alignment->setSettings(settings);
			//alignment->PrintEvents(1511,1501);
			alignment->Align(RunParameters[i].getEvents(),0,TAlignment::diaAlignment);
			delete alignment;

			TTransparentAnalysis *transpAna;
			transpAna = new TTransparentAnalysis(settings,TSettings::transparentMode);
			transpAna->setResults(currentResults);
			transpAna->analyze(RunParameters[i].getEvents(),RunParameters.at(i).getStartEvent());
			delete transpAna;
		}
		cout<<"PRINT RESULTS"<<endl;
		currentResults->Print();
		cout<<"SAVE RESULTS"<<endl;
//		currentResults->saveResults(settings->getResultsRootFilePath());
		TFile* file = new TFile (settings->getResultsRootFilePath().c_str(),"RECREATE");
		file->Print();
		file->ls();
		file->SetName("fileName");
		file->cd();
		cout<<"KEYS: "<<file->GetNkeys()<<endl;
		file->GetListOfKeys()->Print();
		cout<<"Write"<<endl;

		currentResults->Write("test");
		cout<<"CLOSE FILE"<<endl;
		file->Close();
//		if (currentResults){
//			cout<<"DELETE RESULTS"<<endl;
//			delete currentResults;
//			cout<<"#"<<endl;;
//		}
		cout<<"saved results..."<<endl;


		runWatch.Stop();
		cout<<"needed Time for Run "<<RunParameters[i].getRunNumber()<<":"<<endl;
		runWatch.Print();
   
        cout<<"needed Time for Run "<<RunParameters[i].getRunNumber()<<":\n\t"<<flush;
        runWatch.Print();
        if (settings!=NULL){
            cout<<"delete Settings..."<<endl;
            delete settings;
            cout<<"DONE_SETTINGS"<<endl;
                                                           
        }
        cout<<"DONE with Analysis of Run "<< RunParameters[i].getRunNumber();
        cout<<": "<<i+1<<"/"<<RunParameters.size()<<endl;
   }
   cout<<"DONE with Analysis of all "<<RunParameters.size()<<" Runs from RunList.ini"<<endl;
   cout<<"total time for all analysis:\n\t"<<flush;

	cout<<"time for all analysis:"<<endl;
	comulativeWatch.Print();
	cout<<"DONE_ALL"<<endl;

	return 0;
}
Example #29
0
void plotFile_timing() {

	// Data file
	TString input = "data/SingleGEM/time_0.0.root";
	
	// Output filename
	TString output = "data/SingleGEM/time_0.0.pdf";	
	
	// Settings
	TString title = "";
	TString xaxis = "Time [ns]";
	TString yaxis = "signal [fC / ns]";
	

	TFile *File = new TFile(input, "READ");
	if(!File->IsOpen()) {
		std::cout << "Problem while opening the file" << std::endl;
		exit();
	}

	File->ls(); // List root file contents
	

	TCanvas *c1 = (TCanvas *)File->Get("c1");
	TH1D *h1= (TH1D*)c1->FindObject("hSignal");
	

	
	TCanvas *c2 = new TCanvas("c1", "plot", 750, 500);
	c2->cd();
	h1->GetXaxis()->SetTitle(xaxis);
	h1->GetYaxis()->SetTitle(yaxis);
	TString rmstitle;
	rmstitle = "RMS: " + double2str(h1->GetRMS());
	h1->SetTitle(rmstitle);
	h1->Scale(-1);
	h1->GetXaxis()->SetRange(0., 300.);

	
	// Style
	h1->SetLineColor(kRed);
	h1->SetLabelSize(0.04, "xyz");
	h1->SetTitleSize(0.04, "xyz");
	h1->SetTitleOffset(1.6, "y");
	
	gStyle->SetPadLeftMargin(0.12);
	gStyle->SetOptStat(0);
	gStyle->SetTitleAlign(33);
	gStyle->SetTitleX(0.925);
	gStyle->SetTitleY(0.95);

	
	h1->Draw();

	
	c2->Update();
	c2->SaveAs(output);
	
	
	//File->Close();


	
}
Example #30
0
//______________________________________________________________________________
void processJpsi2eeQAplots(const Char_t* filename="jpsi_Default.root", 
			   TString suffix = "eps",
			   const Char_t* outfile="Jpsi2eeQAplots_output.root") {
  //
 
  //  
  TFile* file = TFile::Open(filename);
  
  // event wise histograms 
  TH1F* zDistrib = (TH1F*)GetHistogram(file, "default", "Event", "Z");
  
  // electron candidate histograms
  TH2F* tpcDedx = (TH2F*)GetHistogram(file, "default", "Track_ev1+", "P_InnerParam_TPC_signal");
  tpcDedx->Add((TH2F*)GetHistogram(file, "default", "Track_ev1-", "P_InnerParam_TPC_signal"));
  TH2F* tpcNsigmaEle = (TH2F*)GetHistogram(file, "default", "Track_ev1+", "P_InnerParam_TPC_nSigma_Electrons");
  tpcNsigmaEle->Add((TH2F*)GetHistogram(file, "default", "Track_ev1-", "P_InnerParam_TPC_nSigma_Electrons"));
  
  // pair candidate histograms
  TH1F* invmass_pp = (TH1F*)GetHistogram(file, "default", "Pair_ev1+_ev1+", "pM");
  TH1F* invmass_pm = (TH1F*)GetHistogram(file, "default", "Pair_ev1+_ev1-", "pM");
  TH1F* invmass_mm = (TH1F*)GetHistogram(file, "default", "Pair_ev1-_ev1-", "pM");
    
  // draw stuff
  TLatex* latex=new TLatex();
  latex->SetNDC();
  latex->SetTextSize(0.04);
  latex->SetTextFont(42);
  TCanvas* c1=new TCanvas("fig_dq_tpcDedx", "");
  if(tpcDedx) {
    tpcDedx->SetStats(kFALSE);
    tpcDedx->GetXaxis()->SetRangeUser(0.0,10.0);
    tpcDedx->GetYaxis()->SetRangeUser(40.0,120.0);
    tpcDedx->SetTitle("");
    tpcDedx->Draw("colz");
    latex->DrawLatex(0.12, 0.83, "J/#psi electron candidates");
  }
  
  TCanvas* c2=new TCanvas("fig_dq_tpcNsigmaElectron", "");
  if(tpcNsigmaEle) {
    tpcNsigmaEle->SetStats(kFALSE);
    tpcNsigmaEle->GetYaxis()->SetRangeUser(-5.0,5.0);
    tpcNsigmaEle->GetXaxis()->SetRangeUser(0.0,10.0);
    tpcNsigmaEle->SetTitle("");
    tpcNsigmaEle->Draw("colz");
    latex->DrawLatex(0.12, 0.83, "J/#psi electron candidates");
  }
  
  TCanvas* c3=new TCanvas("fig_dq_eeInvMass", "");
  if(invmass_pm) {
    invmass_pm->SetStats(kFALSE);
    invmass_pm->SetTitle("");
    invmass_pm->SetLineColor(1);
    invmass_pm->GetYaxis()->SetTitle(Form("Pairs per %.0f MeV/c^{2}", 1000.0*invmass_pm->GetXaxis()->GetBinWidth(1)));
    invmass_pm->GetXaxis()->SetTitle("m_{e^{+}e^{-}} (GeV/c^{2})");
    invmass_pm->Draw();
  }
  if(invmass_pp) {
    invmass_pp->SetLineColor(2);
    invmass_pp->Draw((invmass_pm ? "same" : ""));
  }
  if(invmass_mm) {
    invmass_mm->SetLineColor(4);
    invmass_mm->Draw((invmass_mm ? "same" : ""));
  }
  if(invmass_pm || invmass_mm || invmass_pp)
    latex->DrawLatex(0.12, 0.85, "J/#psi candidates");
  if(invmass_pm && zDistrib && zDistrib->Integral()>1.);
    latex->DrawLatex(0.12, 0.80, Form("candidates / event = %.3f", invmass_pm->Integral() / zDistrib->Integral()));
  TLegend* legend=new TLegend(0.7,0.7,0.89,0.89);
  legend->SetTextFont(42);
  legend->SetBorderSize(0);
  legend->SetFillColor(0);
  if(invmass_pm) legend->AddEntry(invmass_pm, "+- pairs", "l");
  if(invmass_pp) legend->AddEntry(invmass_pp, "++ pairs", "l");
  if(invmass_mm) legend->AddEntry(invmass_mm, "-- pairs", "l");
  if(invmass_mm || invmass_pm || invmass_pp) legend->Draw();
  
  c1->SaveAs(Form("fig_dq_tpcDedx.%s",suffix.Data()));
  c2->SaveAs(Form("fig_dq_tpcNsigmaElectron.%s",suffix.Data()));
  c3->SaveAs(Form("fig_dq_eeInvMass.%s",suffix.Data()));


  //  TFile* save=new TFile(outputName, "RECREATE");
  // c1->Write();
  // c2->Write();
  // c3->Write();
  // save->Close();


  // Added by jsatya

  TFile *fout = TFile::Open(outfile,"UPDATE");
  fout->ls();
  
  TDirectoryFile *cdd = NULL;
  cdd = (TDirectoryFile*)fout->Get("DQ");
  if(!cdd) {
    Printf("Warning: DQ <dir> doesn't exist, creating a new one");
    cdd = (TDirectoryFile*)fout->mkdir("DQ");
  }
  cdd->cd();
  cdd->ls();



  if (invmass_pp){
    invmass_pp->SetName(Form("fig_dq_%s_pp", invmass_pp->GetName()));
    invmass_pp->Write();
  }
  
  if (invmass_pm){
    invmass_pm->SetName(Form("fig_dq_%s_pm", invmass_pm->GetName()));
    invmass_pm->Write();
  }
  if (invmass_mm){
    invmass_mm->SetName(Form("fig_dq_%s_mm", invmass_mm->GetName()));
    invmass_mm->Write();
  }
  
  tpcNsigmaEle->SetName(Form("fig_dq_%s", tpcNsigmaEle->GetName()));
  tpcNsigmaEle->Write();
  
  tpcDedx->SetName(Form("fig_dq_%s", tpcDedx->GetName()));
  tpcDedx->Write();
  
  fout->cd();
  fout->Close();
  
}