Exemple #1
0
Long64_t CalibTree::LoadTree(Long64_t entry) {
  // Set the environment to read one entry
  if (!fChain) return -5;
  Long64_t centry = fChain->LoadTree(entry);
  if (centry < 0) return centry;
  if (fChain->GetTreeNumber() != fCurrent) {
    fCurrent = fChain->GetTreeNumber();
    Notify();
  }
  return centry;
}
Exemple #2
0
int main(int argc, char** argv)
{
  string inputfile;
  string outputfile;
  vector<string> datafiles;

  /* Argument parsing */
  /* ---------------- */
  if( argc != 3 ) {
    Usage();
  } else {
    inputfile = argv[1];
    outputfile = argv[2];

    string extension = inputfile.substr( inputfile.length()-5, 5 );
    /* A single input file */
    if( extension == ".root" )  {
      cout<<"A single input file, "<<inputfile<<endl;
      datafiles.push_back(inputfile);
    }
    /* Input file is a list */
    else if( extension == ".list" )  {
      cout<<"A list of root files, "<<inputfile<<endl;
      /* Grab all the data files in the list */
      ifstream inlist( inputfile.c_str() );
      string line;
      while( getline( inlist, line ) )  {
        datafiles.push_back( line );
      }
    }
    /* Other errors */
    else {
      Usage();
    }
  }

  /* Load the StreamChain and initializa StreamChain Tree reader */
  /* ----------------------------------------------------------- */
  TChain* EventChain = new TChain("Event");

  for( unsigned int i =0; i<datafiles.size(); i++ ) {
    EventChain->Add( datafiles[i].c_str() );
  }
  cout<<datafiles.size()<<" data files will be processed."<<endl;


  // Load the ReadinChain Tree
  // Get the ReadinChain Tree reader
  TR = new TreeReader;
  TR->Init(EventChain);

  /* Begin Job */
  /* --------- */
  if( BeginJob() == 0 ) {
    cout<<"BeginJob failed"<<endl;
    return 0;
  }

  TFile f( outputfile.c_str(), "RECREATE" );
  TH1F* hDistOrg = new TH1F("DistOrg","DistOrg",1000,0,3500);
  TH1F* hDistNew = new TH1F("DistNew","DistNew",1000,0,3500);

  int nTot = 0;
  int nOrg = 0;
  int nNew = 0;

  TRandom rand;
  
  /* The main loop over every stream entries */
  /* --------------------------------------- */
  unsigned int entries = EventChain->GetEntries();
  for( unsigned int entry=0; entry<entries; entry++ )  {
    unsigned int localentry = EventChain->LoadTree(entry);
    int ret = TR->GetEntry( localentry );
    if( ret==0 ) { 
      cout<<"Warning: Read error"<<endl;
    }

    /*** Test each entry here ***/
    if( TR->Fold != 2 ) continue;
    if( TR->E[1] < 1.9988 ) continue;
    if( TR->E[1] > 2.9852 ) continue;
    
    nTot++;
    
    /* Original case */
    {
      /* Useful event left */
      double x0,y0,z0, x1,y1,z1;
      /* IBD primary vertex */
      x0 =  TR->XT[0];
      y0 =  TR->YT[0];
      z0 =  TR->ZT[0];
      /* Gamma dep center */
      x1 =  TR->XCpt[1];
      y1 =  TR->YCpt[1];
      z1 =  TR->ZCpt[1];
      
      /* Step 1, gamma range */

      /* Step 2, rec shrink */
      x0 *= 0.97;
      y0 *= 0.97;
      z0 *= 0.89;
     
      /* Step 3, resolution */
      x0 += rand.Gaus(0, 160);
      y0 += rand.Gaus(0, 160);
      z0 += rand.Gaus(0, 120);

      x1 += rand.Gaus(0, 160);
      y1 += rand.Gaus(0, 160);
      z1 += rand.Gaus(0, 120);
      
      double l = sqrt( pow((x1-x0),2) + pow((y1-y0),2) + pow((z1-z0),2) );
      hDistOrg->Fill(l);
      
      if( l<500 ) nOrg++;
    }

    /* New case */
    {
      /* Useful event left */
      double x0,y0,z0, x1,y1,z1;
      /* IBD primary vertex */
      x0 =  TR->XT[0];
      y0 =  TR->YT[0];
      z0 =  TR->ZT[0];
      /* Gamma dep center */
      x1 =  TR->XCpt[1];
      y1 =  TR->YCpt[1];
      z1 =  TR->ZCpt[1];

      /* Step 1, gamma range */
      x1 = x0 + (x1-x0)* (1-0.007);
      y1 = y0 + (y1-y0)* (1-0.007);
      z1 = z0 + (z1-z0)* (1-0.007);

      /* step 2, rec shrink */
      x0 *= 0.97;
      y0 *= 0.97;
      z0 *= 0.89;
      
      x0 *= (1-0.012);
      y0 *= (1-0.012);
      z0 *= (1-0.016);

      /* Step 3, resolution */
      x0 += rand.Gaus(0, 160 * (1-0.019));
      y0 += rand.Gaus(0, 160 * (1-0.019));
      z0 += rand.Gaus(0, 120 * (1-0.025));

      x1 += rand.Gaus(0, 160 * (1-0.019));
      y1 += rand.Gaus(0, 160 * (1-0.019));
      z1 += rand.Gaus(0, 120 * (1-0.025));

      double l = sqrt( pow((x1-x0),2) + pow((y1-y0),2) + pow((z1-z0),2) );
      hDistNew->Fill(l);

      if( l<500 ) nNew++;
    }

    /***  End of each entry   ***/

  }

  f.Write();

  double EffOrg = nOrg/double(nTot);
  double ErrOrg = sqrt( EffOrg*(1-EffOrg)/double(nTot) );
  
  double EffNew = nNew/double(nTot);
  double ErrNew = sqrt( EffNew*(1-EffNew)/double(nTot) );

  cout<<nTot<<"\t"<<nOrg<<"\t"<<nNew<<endl;
  cout<<EffOrg<<"+/-"<<ErrOrg<<" vs. "<<EffNew<<"+/-"<<ErrNew<<endl;
  

  
  /* End Job */
  /* ------- */
  if( EndJob() == 0 ) {
    cout<<"BeginJob failed"<<endl;
    return 0;
  }

  return 1;
}
void countMuonsPerRunD3PD(){

  //gInterpreter->GenerateDictionary("map<int, double >","map.h;map");
  int cutValue = 11;
  float ptmin = 10.0;
  //float ptmin = 4.;
  //TString fileNameMuonIn = "/afs/cern.ch/user/t/tbalestr/public/16.6.2.5/WorkArea/run/HISingleMuon.root";

///7.3 ub^-1 2010 data
  //TString fileNameMuonIn = "/tmp/tbalestr/HISingleMuon_Aug4_v2.root";
  ///2011 PbPb data
  //TString fileNameMuonIn = "/tmp/tbalestr/HISingleMuon_DPD_HP_merged_26May.root";
  //TString fileNameMuonIn = "/tmp/tbalestr/HISingleMuon_DPD_HP_30May.root";

  TString baseString = "/mnt/Lustre/cgrp/atlas_hi/tbalestri/";
  TString fileNameMuonIn = baseString+"HardProbesFiles/HISingleMuonHardProbesData.04.17.2013.root";  
  TFile* fMuIn = new TFile(fileNameMuonIn, "READ");
  if ( !fMuIn->IsOpen() ) {
    std::cout << fMuIn << " not found!" << std::endl;
  }

  TFile* outFile = new TFile("muonsPerRun.root","recreate");
  
  ///lumi in ub^-1
  std::vector<double> vLumi;
  vLumi.push_back(0.0137422);
  vLumi.push_back(0.126333);
  vLumi.push_back(1.28605451);
  vLumi.push_back(0.08307752);
  vLumi.push_back(3.948807);
  vLumi.push_back(2.766361);
  vLumi.push_back(3.606919);
  vLumi.push_back(3.809249);
  vLumi.push_back(4.11709);
  vLumi.push_back(4.88581);
  vLumi.push_back(2.50513);
  vLumi.push_back(0.0619227);
  vLumi.push_back(0.9694949);
  vLumi.push_back(0.582203);
  vLumi.push_back(5.42834);
  vLumi.push_back(4.20247);
  vLumi.push_back(0.38549);
  vLumi.push_back(5.50425);
  vLumi.push_back(3.15969);
  vLumi.push_back(4.19951);
  vLumi.push_back(5.24396);
  vLumi.push_back(5.30817);
  vLumi.push_back(0.0433861);
  vLumi.push_back(5.29888);
  vLumi.push_back(5.30346);
  vLumi.push_back(0.757212);
  vLumi.push_back(5.985104);
  vLumi.push_back(5.1515);
  vLumi.push_back(6.57761);
  vLumi.push_back(1.75062);
  vLumi.push_back(5.43771);
  vLumi.push_back(3.13928);
  vLumi.push_back(5.14981);
  vLumi.push_back(4.90751);
  vLumi.push_back(2.521785);
  vLumi.push_back(6.45269);
  vLumi.push_back(3.59951);
  vLumi.push_back(5.33795);
  vLumi.push_back(6.16766);
  vLumi.push_back(1.77379);
  vLumi.push_back(0.923454);
  vLumi.push_back(2.07656);

  std::vector<int> vRun;
  vRun.push_back(193211);
  vRun.push_back(193270);
  vRun.push_back(193291);
  vRun.push_back(193295);
  vRun.push_back(193321);
  vRun.push_back(193403);
  vRun.push_back(193412);
  vRun.push_back(193447);
  vRun.push_back(193463);
  vRun.push_back(193481);
  vRun.push_back(193491);
  vRun.push_back(193492);
  vRun.push_back(193493);
  vRun.push_back(193494);
  vRun.push_back(193546);
  vRun.push_back(193558);
  vRun.push_back(193599);
  vRun.push_back(193604);
  vRun.push_back(193641);
  vRun.push_back(193655);
  vRun.push_back(193662);
  vRun.push_back(193679);
  vRun.push_back(193687);
  vRun.push_back(193718);
  vRun.push_back(193795);
  vRun.push_back(193823);
  vRun.push_back(193825);
  vRun.push_back(193826);
  vRun.push_back(193834);
  vRun.push_back(193890);
  vRun.push_back(194017);
  vRun.push_back(194060);
  vRun.push_back(194061);
  vRun.push_back(194121);
  vRun.push_back(194160);
  vRun.push_back(194163);
  vRun.push_back(194179);
  vRun.push_back(194192);
  vRun.push_back(194193);
  vRun.push_back(194370);
  vRun.push_back(194374);
  vRun.push_back(194382);
  const int nRuns = vRun.size(); 

  TGraphErrors* grLumi = new TGraphErrors(nRuns);
  TGraphErrors* grMuPerLumi = new TGraphErrors(nRuns);

  int valNt[30], EF_mu4_MSonly_L1TE50_Matched20[30],EF_mu4_L1VTE50_Matched20[30],runNt, mu_muid_nNt;
  int EF_mu10_MSonly_EFFS_L1ZDC_Matched20[30], EF_mu10_MSonly_EFFS_L1TE10_Matched20[30],EF_mu10_MSonly_EFFS_L1TE20_Matched20[30];
  int EF_mu10_MSonly_EFFS_L1ZDC, EF_mu10_MSonly_EFFS_L1TE10, EF_mu10_MSonly_EFFS_L1TE20, EF_mu4_MSonly_L1TE50, EF_mu4_L1VTE50;
  float ptNt[30], centralityNt,etaNt[30],eLossNt[30],scatNt[30];

  TChain* tree = new TChain("tree","tree");
  std::cout << "Filling the tree for " << fileNameMuonIn << std::endl;
  tree->Add(fileNameMuonIn);
  // --- Set branch adresses ---
  tree->SetBranchAddress("val", &valNt);
  tree->SetBranchAddress("pt", &ptNt);
  tree->SetBranchAddress("eta", &etaNt);
  tree->SetBranchAddress("eLoss",&eLossNt);
  tree->SetBranchAddress("scat",&scatNt);
  tree->SetBranchAddress("mu_muid_n", &mu_muid_nNt);
  tree->SetBranchAddress("run", &runNt);
  tree->SetBranchAddress("centrality", &centralityNt); 
  tree->SetBranchAddress("EF_mu4_MSonly_L1TE50", &EF_mu4_MSonly_L1TE50); 
  tree->SetBranchAddress("EF_mu4_L1VTE50", &EF_mu4_L1VTE50); 
  tree->SetBranchAddress("EF_mu4_MSonly_L1TE50_Matched20", &EF_mu4_MSonly_L1TE50_Matched20); 
  tree->SetBranchAddress("EF_mu4_L1VTE50_Matched20", &EF_mu4_L1VTE50_Matched20); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1ZDC", &EF_mu10_MSonly_EFFS_L1ZDC); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1TE10", &EF_mu10_MSonly_EFFS_L1TE10); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1TE20", &EF_mu10_MSonly_EFFS_L1TE20); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1ZDC_Matched20", &EF_mu10_MSonly_EFFS_L1ZDC_Matched20); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1TE10_Matched20", &EF_mu10_MSonly_EFFS_L1TE10_Matched20); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1TE20_Matched20", &EF_mu10_MSonly_EFFS_L1TE20_Matched20); 

  tree->SetBranchStatus("*",0);
  tree->SetBranchStatus("val", 1);
  tree->SetBranchStatus("pt", 1);
  tree->SetBranchStatus("eta", 1);
  tree->SetBranchStatus("eLoss",1);
  tree->SetBranchStatus("scat",1);
  tree->SetBranchStatus("mu_muid_n", 1);
  tree->SetBranchStatus("run", 1);
  tree->SetBranchStatus("centrality", 1); 
  tree->SetBranchStatus("EF_mu4_MSonly_L1TE50", 1); 
  tree->SetBranchStatus("EF_mu4_L1VTE50", 1); 
  tree->SetBranchStatus("EF_mu4_MSonly_L1TE50_Matched20", 1); 
  tree->SetBranchStatus("EF_mu4_L1VTE50_Matched20", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1ZDC", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1TE10", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1TE20", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1ZDC_Matched20", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1TE10_Matched20", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1TE20_Matched20", 1); 

 std::cout << "Number of entries: " << tree->GetEntries() << std::endl; 
 
 ///map runnumber to #mu
 ///need to used multimap since >1 muon 
 ///value for each run number key
 std::multimap < int, int> runMap;

  ///loop over all events
  for ( int i = 0; i < tree->GetEntries(); ++i ) {
 //   if(i>10000) break;
    tree->LoadTree(i);
    tree->GetEntry(i);

    if(i%10000==0) std::cout << "Event " << i << std::endl;

        for(int imu = 0; imu<mu_muid_nNt; imu++){
            if (
                (valNt[imu]>cutValue) 
                && abs(etaNt[imu])>0.1 
                && abs(etaNt[imu])<2.4 
                && ptNt[imu]>ptmin 
                && centralityNt>=0. 
                && centralityNt<=0.8
                && ( (EF_mu10_MSonly_EFFS_L1ZDC&&EF_mu10_MSonly_EFFS_L1ZDC_Matched20[imu]) ||
                    (EF_mu10_MSonly_EFFS_L1TE10&&EF_mu10_MSonly_EFFS_L1TE10_Matched20[imu])
                    ||(EF_mu10_MSonly_EFFS_L1TE20&&EF_mu10_MSonly_EFFS_L1TE20_Matched20[imu]) )	
		        ){
                ///count number of muons in this run that pass
                runMap.insert(make_pair (runNt,1) );
               }
         } //imu
   } //i
                
   std::cout << std::endl;
   std::cout << "-------------------------  " << std::endl;
   std::cout << " S U M M A R Y " << std::endl;
   std::cout << "-------------------------  " << std::endl;

   TString spreadSheetName = "muonCountingSpreadSheet.csv";
   std::ofstream spreadSheet;
   spreadSheet.open(spreadSheetName);

   double totLumi = 0.0, totalMu = 0;
   for(int iRun = 0; iRun<nRuns; ++iRun){

        int muonsPassed = runMap.count( vRun[iRun] );
        ///Muons per nb^-1
        double muPerLumi = (double)muonsPassed/vLumi[iRun]/1000.0;
        ///Number of muons passed in run iRun
        std::cout << "Index: " << iRun+1 << "\tRun: " << vRun[iRun] << 
            "\tLumi: " << vLumi[iRun]/1000.0 << "\tMuons: " << muonsPassed << "\tMuons/nb^-1: " 
            << muPerLumi << std::endl;

        totLumi += vLumi[iRun]/1000.0;
        totalMu += muonsPassed;

        grMuPerLumi->SetPoint(iRun,vRun[iRun],muPerLumi);
        grMuPerLumi->SetPointError(iRun,0.5, TMath::Sqrt(muonsPassed)/vLumi[iRun]/1000.0);

        grLumi->SetPoint(iRun,totLumi,totalMu);
        grLumi->SetPointError(iRun, 0.0, 0.0);

        writeToSpreadsheet(spreadSheet,iRun+1,vRun[iRun],vLumi[iRun]/1000.,muonsPassed);
   }

   grMuPerLumi->Draw("ape");
   grLumi->Draw("ape");

   outFile->cd();
   grLumi->Write("muonLumiDependence");
   grMuPerLumi->Write("muonPerLumi");

   std::cout << " Total Luminosity: " << totLumi << " nb^-1 " << std::endl;
   std::cout << " Total Muons passed: " << totalMu << std::endl;

   spreadSheet.close();
                
/*
            
  cout << "Number of runs: " << runMap.size() << endl;
  cout << "Run \t" << "Luminosity(ub^-1) \t" << " #muons \t" << "muons/lumi" << endl;
  ///map run lumi to #mu
  //std::map < int, double> lumiMap;
  for (unsigned int j = 0; j<runMap.size(); ++j){
    int runTemp = vRun.at(j);
    double lumiTemp = vLumi.at(j);
    map <int,int>::const_iterator iPairFound = runMap.find(runTemp);
    cout << iPairFound->first << " \t " << lumiTemp << " \t " << " \t " << iPairFound->second << " \t " << " \t " << (double)iPairFound->second/lumiTemp << endl; 
    sum += runMap[runTemp];
  }

  cout << "Total Luminosity = " << totLumi << endl;
  cout << "Total = " << sum << endl;
  */
}
Exemple #4
0
void ctlMetXY()
{
  gStyle->SetOptStat(0);
  int metBin(6);
  int vtxBin(5);
   TChain * fChain = new TChain("metPhiCorrInfoWriter/Events","");
   //fChain->Add("histo_data.root/metPhiCorrInfoWriter/Events");
   fChain->Add("~/WorkDir/MetPhiCorrection/CMSSW_8_0_9/src/MetTools/MetPhiCorrections/test/histo_Run2016B_noMetcut.root/metPhiCorrInfoWriter/Events");

   if (fChain == 0) return;

   // Declaration of leaf types
   vector<int>     *Count_catagory;
   vector<int>     *Count_counts;
   vector<double>  *Count_MetX;
   vector<double>  *Count_MetY;
   vector<double>  *Count_pfMetT;
   vector<double>  *Count_pfMetX;
   vector<double>  *Count_pfMetY;
   vector<int>     *nVtx_catagory;
   vector<int>     *nVtx_nVtx;
   vector<double>  *nVtx_MetX;
   vector<double>  *nVtx_MetY;
   vector<double>  *nVtx_pfMetT;
   vector<double>  *nVtx_pfMetX;
   vector<double>  *nVtx_pfMetY;
   vector<int>     *sumPt_catagory;
   vector<double>  *sumPt_sumPt;
   vector<double>  *sumPt_MetX;
   vector<double>  *sumPt_MetY;
   vector<double>  *sumPt_pfMetT;
   vector<double>  *sumPt_pfMetX;
   vector<double>  *sumPt_pfMetY;

   // List of branches
   TBranch        *b_Count_catagory;   //!
   TBranch        *b_Count_counts;   //!
   TBranch        *b_Count_MetX;   //!
   TBranch        *b_Count_MetY;   //!
   TBranch        *b_Count_pfMetT;   //!
   TBranch        *b_Count_pfMetX;   //!
   TBranch        *b_Count_pfMetY;   //!
   TBranch        *b_nVtx_catagory;   //!
   TBranch        *b_nVtx_nVtx;   //!
   TBranch        *b_nVtx_MetX;   //!
   TBranch        *b_nVtx_MetY;   //!
   TBranch        *b_nVtx_pfMetT;   //!
   TBranch        *b_nVtx_pfMetX;   //!
   TBranch        *b_nVtx_pfMetY;   //!
   TBranch        *b_sumPt_catagory;   //!
   TBranch        *b_sumPt_sumPt;   //!
   TBranch        *b_sumPt_MetX;   //!
   TBranch        *b_sumPt_MetY;   //!
   TBranch        *b_sumPt_pfMetT;   //!
   TBranch        *b_sumPt_pfMetX;   //!
   TBranch        *b_sumPt_pfMetY;   //!

   // Set object pointer
   Count_catagory = 0;
   Count_counts = 0;
   Count_MetX = 0;
   Count_MetY = 0;
   Count_pfMetT = 0;
   Count_pfMetX = 0;
   Count_pfMetY = 0;
   nVtx_catagory = 0;
   nVtx_nVtx = 0;
   nVtx_MetX = 0;
   nVtx_MetY = 0;
   nVtx_pfMetT = 0;
   nVtx_pfMetX = 0;
   nVtx_pfMetY = 0;
   sumPt_catagory = 0;
   sumPt_sumPt = 0;
   sumPt_MetX = 0;
   sumPt_MetY = 0;
   sumPt_pfMetT = 0;
   sumPt_pfMetX = 0;
   sumPt_pfMetY = 0;

   fChain->SetBranchAddress("Count_catagory", &Count_catagory, &b_Count_catagory);
   fChain->SetBranchAddress("Count_counts", &Count_counts, &b_Count_counts);
   fChain->SetBranchAddress("Count_MetX", &Count_MetX, &b_Count_MetX);
   fChain->SetBranchAddress("Count_MetY", &Count_MetY, &b_Count_MetY);
   fChain->SetBranchAddress("Count_pfMetT", &Count_pfMetT, &b_Count_pfMetT);
   fChain->SetBranchAddress("Count_pfMetX", &Count_pfMetX, &b_Count_pfMetX);
   fChain->SetBranchAddress("Count_pfMetY", &Count_pfMetY, &b_Count_pfMetY);
   fChain->SetBranchAddress("nVtx_catagory", &nVtx_catagory, &b_nVtx_catagory);
   fChain->SetBranchAddress("nVtx_nVtx", &nVtx_nVtx, &b_nVtx_nVtx);
   fChain->SetBranchAddress("nVtx_MetX", &nVtx_MetX, &b_nVtx_MetX);
   fChain->SetBranchAddress("nVtx_MetY", &nVtx_MetY, &b_nVtx_MetY);
   fChain->SetBranchAddress("nVtx_pfMetT", &nVtx_pfMetT, &b_nVtx_pfMetT);
   fChain->SetBranchAddress("nVtx_pfMetX", &nVtx_pfMetX, &b_nVtx_pfMetX);
   fChain->SetBranchAddress("nVtx_pfMetY", &nVtx_pfMetY, &b_nVtx_pfMetY);
   fChain->SetBranchAddress("sumPt_catagory", &sumPt_catagory, &b_sumPt_catagory);
   fChain->SetBranchAddress("sumPt_sumPt", &sumPt_sumPt, &b_sumPt_sumPt);
   fChain->SetBranchAddress("sumPt_MetX", &sumPt_MetX, &b_sumPt_MetX);
   fChain->SetBranchAddress("sumPt_MetY", &sumPt_MetY, &b_sumPt_MetY);
   fChain->SetBranchAddress("sumPt_pfMetT", &sumPt_pfMetT, &b_sumPt_pfMetT);
   fChain->SetBranchAddress("sumPt_pfMetX", &sumPt_pfMetX, &b_sumPt_pfMetX);
   fChain->SetBranchAddress("sumPt_pfMetY", &sumPt_pfMetY, &b_sumPt_pfMetY);

   Long64_t nentries = fChain->GetEntriesFast();
   //nentries = 30;

   Long64_t nbytes = 0, nb = 0;

   TCanvas *myCan = new TCanvas("myCan","myCan");
   TProfile *pr_MEx_vtx         = new TProfile("pr_MEx_vtx","pr_MEx_vtx",20,0,40);
   TProfile *pr_MEy_vtx         = new TProfile("pr_MEy_vtx","pr_MEy_vtx",20,0,40);
   TProfile *pr_MEx_pfMetT_vtx[vtxBin];
   TProfile *pr_MEx_vtx_pfMetT[metBin];
   TProfile *pr_MEy_vtx_pfMetT[metBin];
   TProfile *pr_MEx_pfMetT = new TProfile("pr_MEx_pfMetT","pr_MEx_pfMetT",30,0,90);
   TString name;
   for(int i(0);i<vtxBin;i++){
     name = Form("pr_MEx_pfMetT_vtx%d", (i+1)*metBin);
     pr_MEx_pfMetT_vtx[i]  = new TProfile(name,name,30,0,90);
   }
   for(int i(0); i<metBin;i++){
     name = Form("pr_MEx_vtx_pfMetT%d", (i+1)*metBin);
     pr_MEx_vtx_pfMetT[i]  = new TProfile(name,name,20,0,40);
     pr_MEx_vtx_pfMetT[i]->SetMaximum(5);
     pr_MEx_vtx_pfMetT[i]->SetMinimum(-3);

     name = Form("pr_MEy_vtx_pfMetT%d", (i+1)*metBin);
     pr_MEy_vtx_pfMetT[i]  = new TProfile(name,name,20,0,40);
     pr_MEy_vtx_pfMetT[i]->SetMaximum(5);
     pr_MEy_vtx_pfMetT[i]->SetMinimum(-3);
   }
   TH1D *h_pfMetT                = new TH1D("h_pfMetT","h_pfMetT",50,0,100);

   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = fChain->LoadTree(jentry);
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      //cout<<"size catagory: "<<nVtx_catagory->size()<<endl; // size 16
      for(unsigned i(0); i < nVtx_catagory->size(); i++){
	if( (*nVtx_catagory)[i] % PtlTT == PtlIdx){ // 12(hHFMinus)
	  h_pfMetT->Fill((*nVtx_pfMetT)[i]);
	  pr_MEx_vtx->Fill((*nVtx_nVtx)[i],(*nVtx_MetX)[i]);
	  pr_MEy_vtx->Fill((*nVtx_nVtx)[i],(*nVtx_MetY)[i]);
	  pr_MEx_pfMetT->Fill((*nVtx_pfMetT)[i], (*nVtx_MetX)[i]);
	  for(int j(0); j<vtxBin;j++){ // As a ftn of MET
	    if((*nVtx_nVtx)[i] > j*5 && (*nVtx_nVtx)[i] <=(j+1)*5){
	      pr_MEx_pfMetT_vtx[j]->Fill((*nVtx_pfMetT)[i], (*nVtx_MetX)[i]);
	    }
	  }

	  for( int j(0); j<metBin; j++) // As a ftn of vtx
	  {
	    if(j==metBin-1){
	      if( (*nVtx_pfMetT)[i] > j*10 )
	      {
	        pr_MEx_vtx_pfMetT[j]->Fill((*nVtx_nVtx)[i], (*nVtx_MetX)[i]);
	        pr_MEy_vtx_pfMetT[j]->Fill((*nVtx_nVtx)[i], (*nVtx_MetY)[i]);
	      }
	    }else{
	      if( (*nVtx_pfMetT)[i] > j*10 && (*nVtx_pfMetT)[i] < (j+1)*10 )
	      {
	        pr_MEx_vtx_pfMetT[j]->Fill((*nVtx_nVtx)[i], (*nVtx_MetX)[i]);
	        pr_MEy_vtx_pfMetT[j]->Fill((*nVtx_nVtx)[i], (*nVtx_MetY)[i]);
	      }
	    }
	  }
	}
        //cout<<"nVtx_catagory: "<<(*nVtx_catagory)[i]<<endl;
      }
      // if (Cut(ientry) < 0) continue;
   }
   pr_MEx_vtx->Draw();
   myCan->SaveAs("prTest_MEx_vtx.png");
   h_pfMetT->Draw();
   myCan->SaveAs("h_pfMetT.png");
   pr_MEx_pfMetT->Draw();
   myCan->SaveAs("pr_MEx_pfMetT.png");

   TLegend *leg = new TLegend(0.5373563,0.7097458,0.8577586,0.8474576,NULL,"brNDC");
   leg->SetTextFont(62);
   leg->SetTextSize(0.03330866);
   leg->SetLineColor(1);
   leg->SetLineStyle(1);
   leg->SetLineWidth(1);
   leg->SetFillColor(0);
   leg->SetFillStyle(1001);
   leg->SetBorderSize(0);

   for(int i(0);i<vtxBin;i++)
   {
     pr_MEx_pfMetT_vtx[i]->SetLineColor(i+1);
     if(i == 0) pr_MEx_pfMetT_vtx[i]->Draw();
     else pr_MEx_pfMetT_vtx[i]->Draw("same");
     name = Form("pr_MEx_pfMetT_vtx_%d_%d",i*metBin, (i+1)*metBin);
     leg->AddEntry(pr_MEx_pfMetT_vtx[i],name,"lp");
   }

   leg->Draw("same");
   name = Form("pr_MEx_pfMetT_vtxes.png");
   myCan->SaveAs(name);

   TLegend *l_MEx_vtx = new TLegend(0.2373563,0.6097458,0.5577586,0.8474576,NULL,"brNDC");
   l_MEx_vtx->SetTextFont(62);
   l_MEx_vtx->SetTextSize(0.03330866);
   l_MEx_vtx->SetLineColor(1);
   l_MEx_vtx->SetLineStyle(1);
   l_MEx_vtx->SetLineWidth(1);
   l_MEx_vtx->SetFillColor(0);
   l_MEx_vtx->SetFillStyle(1001);
   l_MEx_vtx->SetBorderSize(0);

   for(int i(0);i<metBin;i++)
   {
     pr_MEx_vtx_pfMetT[i]->SetLineColor(i+1);
     pr_MEx_vtx_pfMetT[i]->SetMarkerColor(i+1);
     pr_MEx_vtx_pfMetT[i]->SetMarkerStyle(22);
     pr_MEx_vtx_pfMetT[i]->SetMarkerSize(1);

     if(i == 0){
       pr_MEx_vtx_pfMetT[i]->SetTitle("<MetX> vs vtx");
       pr_MEx_vtx_pfMetT[i]->Draw();
     }else pr_MEx_vtx_pfMetT[i]->Draw("same");

     if(i == metBin-1){
       name = Form("pfMetT_%d_%d",i*10, 100);
       l_MEx_vtx->AddEntry(pr_MEx_vtx_pfMetT[i],name,"lp");
     }else{
       name = Form("pfMetT_%d_%d",i*10, (i+1)*10);
       l_MEx_vtx->AddEntry(pr_MEx_vtx_pfMetT[i],name,"lp");
     }

   }
   pr_MEx_vtx->SetMarkerStyle(20);
   pr_MEx_vtx->Draw("same");
   l_MEx_vtx->AddEntry(pr_MEx_vtx,"all","lp");

   l_MEx_vtx->Draw("same");
   name = Form("pr_MEx_vtx_pfMetTes.png");
   myCan->SaveAs(name);

   TLegend *l_MEy_vtx = new TLegend(0.2373563,0.6097458,0.5577586,0.8474576,NULL,"brNDC");
   l_MEy_vtx->SetTextFont(62);
   l_MEy_vtx->SetTextSize(0.03330866);
   l_MEy_vtx->SetLineColor(1);
   l_MEy_vtx->SetLineStyle(1);
   l_MEy_vtx->SetLineWidth(1);
   l_MEy_vtx->SetFillColor(0);
   l_MEy_vtx->SetFillStyle(1001);
   l_MEy_vtx->SetBorderSize(0);

   for(int i(0);i<metBin;i++)
   {
     pr_MEy_vtx_pfMetT[i]->SetLineColor(i+1);
     pr_MEy_vtx_pfMetT[i]->SetMarkerColor(i+1);
     pr_MEy_vtx_pfMetT[i]->SetMarkerStyle(22);
     pr_MEy_vtx_pfMetT[i]->SetMarkerSize(1);

     if(i == 0){
       pr_MEy_vtx_pfMetT[i]->SetTitle("<MetY> vs vtx");
       pr_MEy_vtx_pfMetT[i]->Draw();
     }else pr_MEy_vtx_pfMetT[i]->Draw("same");

     if(i == metBin-1){
       name = Form("pfMetT_%d_%d",i*10, 100);
       l_MEy_vtx->AddEntry(pr_MEy_vtx_pfMetT[i],name,"lp");
     }else{
       name = Form("pfMetT_%d_%d",i*10, (i+1)*10);
       l_MEy_vtx->AddEntry(pr_MEy_vtx_pfMetT[i],name,"lp");
     }
   }
   pr_MEy_vtx->SetMarkerStyle(20);
   pr_MEy_vtx->Draw("same");
   l_MEy_vtx->AddEntry(pr_MEy_vtx,"all","lp");

   l_MEy_vtx->Draw("same");
   name = Form("pr_MEy_vtx_pfMetTes.png");
   myCan->SaveAs(name);
   
}
void execCheckErrors(bool what = 0)
{
  TTree *tree = 0;
  TFile *file = 0;
  if (what == 0) {
    tree = new TTree("ntuple","");
    float px = 0;
    tree->Branch("px",&px);
    TString str;
    tree->Branch("str",&str);
    tree->Fill();
    tree->ResetBranchAddresses(); 
  } else if (what == 1) {
    file = new TFile("hsimple.root");
    tree = (TTree*)file->Get("ntuple");
  } else {
    tree = new TChain("ntuple", "ntuple");
    ((TChain*)tree)->Add("hsimple.root");
  }
  // tree->SetBranchStatus("*", 1);
  // tree->SetBranchStatus("px", 1);
  // std::cout << "fTreeNumber = " << tree->GetTreeNumber() << std::endl;
  tree->LoadTree(0); // REQUIRED
  // std::cout << "fTreeNumber = " << tree->GetTreeNumber() << std::endl;
  
  TBranch *p = ((TBranch *)-1);
  Int_t r;
  
  Float_t px, fake_px;
  Float_t *pxp = new Float_t();
  Float_t *fake_pxp = new Float_t();
  
  Int_t ix;
  Int_t *ixp = new Int_t();
  
  TString s;
  TString *sp = new TString();
  
  TObjString os;
  TObjString *osp = new TObjString();
  
  // Float_t ... (should be fine)
  std::cout << std::endl << "ALL should be FINE ... " << std::endl;
  p = ((TBranch *)-1);
  r = tree->SetBranchAddress("px", &px, &p);
  std::cout << "Float_t ... " << r << std::endl;
  if (p==((TBranch*)-1)) {
     std::cout << "p unchanged\n";
  } else if (p==0) {
     std::cout << "p set to zero\n";
  } else {
     std::cout << "p set to the branch address\n";
  }
  r = tree->SetBranchAddress("px", &px);
  std::cout << "Float_t ... "  << r << std::endl;
  r = tree->SetBranchAddress("px", pxp);
  std::cout << "Float_t ... "  << r << std::endl;
  r = tree->SetBranchAddress("px", &pxp);
  std::cout << "Float_t ... "  << r << std::endl;
  
  // Int_t ...  (should fail)
  std::cout << std::endl << "ALL should FAIL ... " << std::endl;
  p = ((TBranch *)-1);
  r = tree->SetBranchAddress("px", &ix, &p);
  std::cout << "Int_t ...  "  << r << std::endl;
  if (p==((TBranch*)-1)) {
     std::cout << "p unchanged\n";
  } else if (p==0) {
     std::cout << "p set to zero\n";
  } else {
     std::cout << "p set to the branch address\n";
  }
  r = tree->SetBranchAddress("px", &ix);
  std::cout << "Int_t ...  "  << r << std::endl;
  r = tree->SetBranchAddress("px", ixp);
  std::cout << "Int_t ...  "  << r << std::endl;
  r = tree->SetBranchAddress("px", &ixp);
  std::cout << "Int_t ...  "  << r << std::endl;
  
  // TString ... (should fail)
  std::cout << std::endl << "ALL should FAIL ... " << std::endl;
  p = ((TBranch *)-1);
  r = tree->SetBranchAddress("px", &s, &p);
  std::cout << "TString ... "  << r << std::endl;
  if (p==((TBranch *)-1)) {
     std::cout << "p unchanged\n";
  } else if (p==0) {
     std::cout << "p set to zero\n";
  } else {
     std::cout << "p set to the branch address\n";
  }
  r = tree->SetBranchAddress("px", sp);
  std::cout << "TString ... "  << r << std::endl;
  r = tree->SetBranchAddress("px", &sp);
  std::cout << "TString ... "  << r << std::endl;
  
  // TObjString ... (should fail)
  std::cout << std::endl << "ALL should FAIL ... " << std::endl;
  p = ((TBranch *)-1);
  r = tree->SetBranchAddress("px", &os, &p);
  std::cout << "TObjString ... "  << r << std::endl;
  if (p==((TBranch*)-1)) {
     std::cout << "p unchanged\n";
  } else if (p==0) {
     std::cout << "p set to zero\n";
  } else {
     std::cout << "p set to the branch address\n";
  }
  r = tree->SetBranchAddress("px", osp);
  std::cout << "TObjString ... "  << r << std::endl;
  r = tree->SetBranchAddress("px", &osp);
  std::cout << "TObjString ... "  << r << std::endl;
  
  // nonexistent branch ... (should fail)
  std::cout << std::endl << "ALL should FAIL ... " << std::endl;
  p = ((TBranch *)-1);
  r = tree->SetBranchAddress("fake_px", &fake_px, &p);
  std::cout << "nonexistent branch ... "  << r << std::endl;
  if (p==((TBranch*)-1)) {
     std::cout << "p unchanged\n";
  } else if (p==0) {
     std::cout << "p set to zero\n";
  } else {
     std::cout << "p set to the branch address\n";
  }
  r = tree->SetBranchAddress("fake_px", &fake_px);
  std::cout << "nonexistent branch ... "  << r << std::endl;
  r = tree->SetBranchAddress("fake_px", fake_pxp);
  std::cout << "nonexistent branch ... "  << r << std::endl;
  r = tree->SetBranchAddress("fake_px", &fake_pxp);
  std::cout << "nonexistent branch ... "  << r << std::endl;

  // Float for TString ... (should fail)
  std::cout << std::endl << "ALL should FAIL ... " << std::endl;
  p = ((TBranch *)-1);
  r = tree->SetBranchAddress("str", &px, &p);
  std::cout << "Float ... "  << r << std::endl;
  if (p==((TBranch*)-1)) {
     std::cout << "p unchanged\n";
  } else if (p==0) {
     std::cout << "p set to zero\n";
  } else {
     std::cout << "p set to the branch address\n";
  }
  r = tree->SetBranchAddress("str", &px);
  std::cout << "Float ... "  << r << std::endl;
  r = tree->SetBranchAddress("str", pxp);
  std::cout << "Float ... "  << r << std::endl;
  r = tree->SetBranchAddress("str", &pxp);
  std::cout << "Float ... "  << r << std::endl;
  
   
  TChain *ch = new TChain("MonoData");
  ch->Add("memleak.root");
  ch->LoadTree(0);
  r = ch->SetBranchAddress("mono", &sp, &p);
  std::cout << "From chain, TString ... "  << r << std::endl;

  TTree *treech = ch;
  r = treech->SetBranchAddress("mono", &sp, &p);
  std::cout << "From tree, TString ... "  << r << std::endl;
   
}
Exemple #6
0
void GetOptimization() {
  struct path thisPath;
  std::vector<path> paths;
  std::vector<TString> pathNames;
  struct filter thisFilter;
  std::vector<filter> filters;
  std::vector<std::pair<std::vector<TString>,Double_t> > xSections;
  std::vector<TString> filenamesBkg;
  std::vector<TString> filenamesSig;
  /* Parameters */
  Int_t nCuts = 120;
  Bool_t doBandE = true; // if true, do seperate for cuts in barrel and endcap

  Double_t luminosity = 2.0E33; // in cm^-2 s^-1

  // Cross-sections in mb
  filenamesBkg.push_back("../test/QCD-HLTVars-1.root");
  // filenamesBkg.push_back("sameXSection");
  xSections.push_back(make_pair(filenamesBkg, 2.16E-2));
  filenamesBkg.clear();
  // filenamesBkg.push_back("newXSection.root");
  // ...
  // xSections.push_back(make_pair(filenamesBkg, xSection));
  // filenamesBkg.clear();
  filenamesSig.push_back("../test/ZEE-HLTVars.root");
  /* ********** */
  // Filters
  thisFilter.name = "l1Match";
  thisFilter.pathNum = 0;
  thisFilter.direction =  0;
  thisFilter.hltBarrelCut = 0.;
  thisFilter.hltEndcapCut = 0.;
  thisFilter.maxCut = 0.;
  filters.push_back(thisFilter);
  thisFilter.name = "Et";
  thisFilter.pathNum = 0;
  thisFilter.direction = 1;
  thisFilter.hltBarrelCut = 15.;
  thisFilter.hltEndcapCut = 15.;
  thisFilter.maxCut = 60.;
  filters.push_back(thisFilter);
  thisFilter.name = "IHcal";
  thisFilter.pathNum = 0;
  thisFilter.direction = -1;
  thisFilter.hltBarrelCut = 3.;
  thisFilter.hltEndcapCut = 3.;
  thisFilter.maxCut = 6.;
  filters.push_back(thisFilter);
  thisFilter.name = "pixMatch";
  thisFilter.pathNum = 0;
  thisFilter.direction = 1;
  thisFilter.hltBarrelCut = 0;
  thisFilter.hltEndcapCut = 0;
  thisFilter.maxCut = 0;
  filters.push_back(thisFilter);
  thisFilter.name = "Eoverp";
  thisFilter.pathNum = 1;
  thisFilter.direction = -1;
  thisFilter.hltBarrelCut = 1.5;
  thisFilter.hltEndcapCut = 2.45;
  thisFilter.maxCut = 5.;
  filters.push_back(thisFilter);
  thisFilter.name = "Itrack";
  thisFilter.pathNum = 1;
  thisFilter.direction = -1;
  thisFilter.hltBarrelCut = 0.06;
  thisFilter.hltEndcapCut = 0.06;
  thisFilter.maxCut = 0.24;
  filters.push_back(thisFilter);
  pathNames.push_back("SingleElecsPT.");
  pathNames.push_back("SingleElecs.");
  thisPath.names = pathNames;
  thisPath.nCandsCut = 1;
  thisPath.filters = filters;
  paths.push_back(thisPath);
  pathNames.clear(); 
  pathNames.push_back("RelaxedSingleElecsPT.");
  pathNames.push_back("RelaxedSingleElecs.");
  thisPath.names = pathNames;
  thisPath.nCandsCut = 1;
  thisPath.filters = filters;
  paths.push_back(thisPath);
  pathNames.clear();
  filters.clear();

  thisFilter.name = "l1Match";
  thisFilter.pathNum = 0;
  thisFilter.direction =  0;
  thisFilter.hltBarrelCut = 0.;
  thisFilter.hltEndcapCut = 0.;
  thisFilter.maxCut = 0.;
  filters.push_back(thisFilter);
  thisFilter.name = "Et";
  thisFilter.pathNum = 0;
  thisFilter.direction = 1;
  thisFilter.hltBarrelCut = 10.;
  thisFilter.hltEndcapCut = 10.;
  thisFilter.maxCut = 40.;
  filters.push_back(thisFilter);
  thisFilter.name = "IHcal";
  thisFilter.pathNum = 0;
  thisFilter.direction = -1;
  thisFilter.hltBarrelCut = 9.;
  thisFilter.hltEndcapCut = 9.;
  thisFilter.maxCut = 18.;
  filters.push_back(thisFilter);
  thisFilter.name = "pixMatch";
  thisFilter.pathNum = 0;
  thisFilter.direction = 1;
  thisFilter.hltBarrelCut = 0;
  thisFilter.hltEndcapCut = 0;
  thisFilter.maxCut = 0;
  filters.push_back(thisFilter);
  thisFilter.name = "Eoverp";
  thisFilter.pathNum = 1;
  thisFilter.direction = -1;
  thisFilter.hltBarrelCut = 15000;
  thisFilter.hltEndcapCut = 24500;
  thisFilter.maxCut = 5.;
  filters.push_back(thisFilter);
  thisFilter.name = "Itrack";
  thisFilter.pathNum = 1;
  thisFilter.direction = -1;
  thisFilter.hltBarrelCut = 0.4;
  thisFilter.hltEndcapCut = 0.4;
  thisFilter.maxCut = 0.12;
  filters.push_back(thisFilter);
  pathNames.push_back("DoubleElecsPT.");
  pathNames.push_back("DoubleElecs.");
  thisPath.names = pathNames;
  thisPath.nCandsCut = 2;
  thisPath.filters = filters;
  paths.push_back(thisPath);
  pathNames.clear(); 
  pathNames.push_back("RelaxedDoubleElecsPT.");
  pathNames.push_back("RelaxedDoubleElecs.");
  thisPath.names = pathNames;
  thisPath.nCandsCut = 2;
  thisPath.filters = filters;
  paths.push_back(thisPath);
  pathNames.clear();
  filters.clear();

  thisFilter.name = "l1Match";
  thisFilter.pathNum = 0;
  thisFilter.direction =  0;
  thisFilter.hltBarrelCut = 0.;
  thisFilter.hltEndcapCut = 0.;
  thisFilter.maxCut = 0.;
  filters.push_back(thisFilter);
  thisFilter.name = "Et";
  thisFilter.pathNum = 0;
  thisFilter.direction = 1;
  thisFilter.hltBarrelCut = 30.;
  thisFilter.hltEndcapCut = 30.;
  thisFilter.maxCut = 60.;
  filters.push_back(thisFilter);
  thisFilter.name = "IEcal";
  thisFilter.pathNum = 0;
  thisFilter.direction = -1;
  thisFilter.hltBarrelCut = 1.5;
  thisFilter.hltEndcapCut = 1.5;
  thisFilter.maxCut = 6.;
  filters.push_back(thisFilter);
  thisFilter.name = "IHcal";
  thisFilter.pathNum = 0;
  thisFilter.direction = -1;
  thisFilter.hltBarrelCut = 4.;
  thisFilter.hltEndcapCut = 6.;
  thisFilter.maxCut = 12.;
  filters.push_back(thisFilter);
  thisFilter.name = "Itrack";
  thisFilter.pathNum = 0;
  thisFilter.direction = -1;
  thisFilter.hltBarrelCut = 1;
  thisFilter.hltEndcapCut = 1;
  thisFilter.maxCut = 5;
  filters.push_back(thisFilter);
  pathNames.push_back("SinglePhots.");
  thisPath.names = pathNames;
  thisPath.nCandsCut = 1;
  thisPath.filters = filters;
  paths.push_back(thisPath);
  pathNames.clear(); 
  pathNames.push_back("RelaxedSinglePhots.");
  thisPath.names = pathNames;
  thisPath.nCandsCut = 1;
  thisPath.filters = filters;
  paths.push_back(thisPath);
  pathNames.clear();
  filters.clear();

  thisFilter.name = "l1Match";
  thisFilter.pathNum = 0;
  thisFilter.direction =  0;
  thisFilter.hltBarrelCut = 0.;
  thisFilter.hltEndcapCut = 0.;
  thisFilter.maxCut = 0.;
  filters.push_back(thisFilter);
  thisFilter.name = "Et";
  thisFilter.pathNum = 0;
  thisFilter.direction = 1;
  thisFilter.hltBarrelCut = 20.;
  thisFilter.hltEndcapCut = 20.;
  thisFilter.maxCut = 40.;
  filters.push_back(thisFilter);
  thisFilter.name = "IEcal";
  thisFilter.pathNum = 0;
  thisFilter.direction = -1;
  thisFilter.hltBarrelCut = 2.5;
  thisFilter.hltEndcapCut = 2.5;
  thisFilter.maxCut = 5.;
  filters.push_back(thisFilter);
  thisFilter.name = "IHcal";
  thisFilter.pathNum = 0;
  thisFilter.direction = -1;
  thisFilter.hltBarrelCut = 6.;
  thisFilter.hltEndcapCut = 8.;
  thisFilter.maxCut = 24.;
  filters.push_back(thisFilter);
  thisFilter.name = "Itrack";
  thisFilter.pathNum = 0;
  thisFilter.direction = -1;
  thisFilter.hltBarrelCut = 3;
  thisFilter.hltEndcapCut = 3;
  thisFilter.maxCut = 6;
  filters.push_back(thisFilter);
  pathNames.push_back("DoublePhots.");
  thisPath.names = pathNames;
  thisPath.nCandsCut = 2;
  thisPath.filters = filters;
  paths.push_back(thisPath);
  pathNames.clear(); 
  pathNames.push_back("RelaxedDoublePhots.");
  thisPath.names = pathNames;
  thisPath.nCandsCut = 2;
  thisPath.filters = filters;
  paths.push_back(thisPath);
  pathNames.clear();
  filters.clear();

  /* *********** */

  Int_t cutNum = 0, pathNum = 0, filterNum = 0, oldFilterNum = 0, fileNum = 0, xSecNum = 0;
  Double_t cut = 0.;
  Long64_t passSig = 0, totalSig = 0;
  Long64_t passBkg = 0, totalBkg = 0;
  Double_t effSig = 0., errSig = 0.;
  Double_t effBkg = 0., errBkg = 0., rateTotBkg = 0., errTotBkg = 0.;
  Double_t conversion = 1.0E-27;
  std::vector<std::pair<Double_t,Double_t> > sigPass;
  std::vector<std::pair<Double_t,Double_t> > bkgPass;

  TString cutText;
  TString cutTextEcap;
  TString baseCutText;
  TString baseCutTextEcap;
  TString cutBasePT1;
  TString cutBasePT2;
  TString cutBase1;
  TString cutBase2;
  //  cutBasePT1 = "ElecHLTCutVarsPreTracks_hltCutVars_";
  //  cutBasePT2 = "ElecsPT_EGAMMAHLT.obj.";
  //  cutBase1 = "";
  //  cutBase2 = "Elecs_EGAMMAHLT.obj.";

  std::vector<std::vector<TGraphErrors> > EffVBkg;
  std::vector<std::vector<TGraphErrors> > EffVBkgEcap;
  std::vector<TGraphErrors> pathEffVBkgs;
  TGraphErrors filterEffVBkgs(nCuts);
  for (pathNum = 0; pathNum < paths.size(); pathNum++) {
    for (filterNum = 0; filterNum < (paths[pathNum].filters).size(); filterNum++) {
      //      filterEffVBkgs = new TGraphErrors(nCuts);
      pathEffVBkgs.push_back(filterEffVBkgs);
    }
    EffVBkg.push_back(pathEffVBkgs);
    if (doBandE) {
      EffVBkgEcap.push_back(pathEffVBkgs);
    }
  }

  std::vector<std::pair<TChain*,Double_t> > bkgEvents;
  for (xSecNum = 0; xSecNum < xSections.size(); xSecNum++) {
    TChain *bkgProc = new TChain("Events");
    for (fileNum = 0; fileNum < (xSections[xSecNum].first).size(); fileNum++) {
      bkgProc->Add((xSections[xSecNum].first)[fileNum]);
    }
    bkgEvents.push_back(make_pair(bkgProc,xSections[xSecNum].second));
  }

  TChain *sigEvents = new TChain("Events");
  for (fileNum = 0; fileNum < filenamesSig.size(); fileNum++) {
    sigEvents->Add(filenamesSig[fileNum]);
  }

  Double_t testX, testY, testdX, testdY;
  Double_t thisBCut = 0., thisECut = 0.;
  TString pathName, filterName;
  for (cutNum = 0; cutNum < nCuts; cutNum++) {
    cout<<"Cut "<<cutNum<<endl;
    for (pathNum = 0; pathNum < paths.size(); pathNum++) {
      for (filterNum = 0; filterNum < (paths[pathNum].filters).size(); filterNum++) {
	if ((paths[pathNum].filters)[filterNum].maxCut != 0.) {
	  cutText = "(Sum$(";
	  for (oldFilterNum = 0; oldFilterNum < filterNum; oldFilterNum++) { 
	    pathName = (paths[pathNum].names)[(paths[pathNum].filters)[filterNum].pathNum];
	    filterName = (paths[pathNum].filters)[oldFilterNum].name;
	    thisBCut = (paths[pathNum].filters)[oldFilterNum].hltBarrelCut;
	    thisECut = (paths[pathNum].filters)[oldFilterNum].hltEndcapCut;
	    if (thisBCut == thisECut) {
  	      cutText += pathName;
	      cutText += filterName;
  	      switch ((paths[pathNum].filters)[oldFilterNum].direction) {
	      case -1:
	        cutText += " < ";
	        cutText += (paths[pathNum].filters)[oldFilterNum].hltBarrelCut;
  	        break;
	      case 0:
	        break;
	      case 1:
	        cutText += " > ";
	        cutText += (paths[pathNum].filters)[oldFilterNum].hltBarrelCut;
	        break;
	      default:
	        cout<<"Invalid value of direction in "<<pathName<<filterName<<endl;
	        break;
	      }
	    }
	    else {
	      cutText += "((";
  	      cutText += pathName;
	      cutText += filterName;
              switch ((paths[pathNum].filters)[oldFilterNum].direction) {
	      case -1:
	        cutText += " < ";
	        cutText += thisBCut;
  	        break;
	      case 0:
	        break;
	      case 1:
	        cutText += " > ";
	        cutText += thisBCut;
	        break;
	      default:
	        cout<<"Invalid value of direction in "<<pathName<<filterName<<endl;
	        break;
	      }
	      cutText += " && abs(";
	      cutText += pathName;
	      cutText += "eta) < 1.5) || (";
	      cutText += pathName;
	      cutText += filterName;
	      switch ((paths[pathNum].filters)[oldFilterNum].direction) {
              case -1:
                cutText += " < ";
                cutText += thisECut;
                break;
              case 0:
                break;
              case 1:
                cutText += " > ";
                cutText += thisECut;
                break;
              default:
                cout<<"Invalid value of direction in "<<pathName<<filterName<<endl;
                break;
              }
	      cutText += " && abs(";
              cutText += pathName;
              cutText += "eta) > 1.5 && abs(";
	      cutText += pathName;
	      cutText += "eta) < 2.5))";
	    }
	    if (oldFilterNum != filterNum - 1) cutText += " && ";
	  }
	  baseCutText = cutText;
	  pathName = paths[pathNum].names[(paths[pathNum].filters)[filterNum].pathNum];
	  filterName = (paths[pathNum].filters)[filterNum].name;
	  cutText += " && ";
	  cutText += pathName;
	  cutText += filterName;
	  cut = (Double_t)cutNum / (Double_t)nCuts * (paths[pathNum].filters)[oldFilterNum].maxCut;
	  switch ((paths[pathNum].filters)[filterNum].direction) {
	  case -1:
	    cutText += " < ";
	    cutText += cut;
	    break;
	  case 0:
	    break;
	  case 1:
	    cutText += " > ";
	    cutText += cut;
	    break;
	  default:
	    cout<<"Invalid value of direction in "<<pathName<<filterName<<endl;
	    break;
	  }
	  if (doBandE) {
	    cutTextEcap = cutText;
	    cutText += " && abs(";
	    cutText += pathName;
	    cutText += "eta) < 1.5";
	    cutTextEcap += " && abs(";
	    cutTextEcap += pathName;
	    cutTextEcap += "eta) > 1.5 && abs(";
	    cutTextEcap += pathName;
	    cutTextEcap += ") < 2.5";
	    baseCutText += " && abs(";
	    baseCutText += pathName;
	    baseCutTextEcap = baseCutText;
	    baseCutText += "eta) < 1.5";
	    baseCutTextEcap += "eta) > 1.5 && abs(";
	    baseCutTextEcap += pathName;
	    baseCutTextEcap += "eta) < 2.5";
	  }
	  cutText += ") >= ";
	  cutText += paths[pathNum].nCandsCut;
	  cutText += ")";
	  cutTextEcap += ") >= ";
	  cutTextEcap += paths[pathNum].nCandsCut;
	  cutTextEcap += ")";
	  baseCutText += ") >= ";
	  baseCutText += paths[pathNum].nCandsCut;
	  baseCutText += ")";
	  baseCutTextEcap += ") >= ";
	  baseCutTextEcap += paths[pathNum].nCandsCut;
	  baseCutTextEcap += ")";
   
	  cout<<cutText<<endl;
	  cout<<cutTextEcap<<endl;
	  //	  cout<<cutText<<endl;
	  //	  cout<<baseCutText<<endl;
	  passSig = sigEvents->Draw("",cutText);
	  totalSig = sigEvents->Draw("",baseCutText);
	  if (totalSig != 0) {
	    effSig = (Double_t)passSig / (Double_t)totalSig;
	    errSig = sqrt(effSig * (1. - effSig) / (Double_t)totalSig);
	  }
	  else {
	    effSig = 0.;
	    errSig = 0.;
	  }
	  rateTotBkg = 0.;
	  errTotBkg = 0.;
	  for (xSecNum = 0; xSecNum < bkgEvents.size(); xSecNum++) {
	    passBkg = bkgEvents[xSecNum].first->Draw("",cutText);
	    totalBkg = bkgEvents[xSecNum].first->Draw("","");
	    if (totalBkg != 0) {
	      effBkg = (Double_t)passBkg / (Double_t)totalBkg;
	      errBkg = sqrt(effBkg * (1. - effBkg) / (Double_t)totalBkg);
	    }
	    else {
	      effBkg = 0.;
	      errBkg = 0.;
	    }
	    rateTotBkg += effBkg * bkgEvents[xSecNum].second * luminosity * conversion;
	    errTotBkg = sqrt(errTotBkg * errTotBkg + errBkg * errBkg * bkgEvents[xSecNum].second * luminosity * conversion * bkgEvents[xSecNum].second * luminosity * conversion);
	  }
	    
	  if (cutNum == 6) {
	    cout<<cutText<<endl;
	    cout<<rateTotBkg<<" +- "<<errTotBkg<<", "<<effSig<<" +- "<<errSig<<endl;;
	  }
	  EffVBkg[pathNum][filterNum].SetPoint(cutNum, rateTotBkg, effSig);
	  EffVBkg[pathNum][filterNum].SetPointError(cutNum, errTotBkg, errSig);
	  if (cutNum == 6) {
	    EffVBkg[pathNum][filterNum].GetPoint(cutNum, testX, testY);
	    cout<<testX<<", "<<testY<<endl;
	  }

	  if (doBandE) {
	    passSig = sigEvents->Draw("",cutTextEcap);
	    totalSig = sigEvents->Draw("",baseCutText);
	    if (totalSig != 0) {
	      effSig = (Double_t)passSig / (Double_t)totalSig;
	      errSig = sqrt(effSig * (1. - effSig) / (Double_t)totalSig);
	    }
	    else {
	      effSig = 0.;
	      errSig = 0.;
	    }
	    rateTotBkg = 0.;
	    errTotBkg = 0.;
	    for (xSecNum = 0; xSecNum < bkgEvents.size(); xSecNum++) {
	      passBkg = bkgEvents[xSecNum].first->Draw("",cutText);
	      totalBkg = bkgEvents[xSecNum].first->Draw("","");
	      if (totalBkg != 0) {
		effBkg = (Double_t)passBkg / (Double_t)totalBkg;
		errBkg = sqrt(effBkg * (1. - effBkg) / (Double_t)totalBkg);
	      }
	      else {
		effBkg = 0.;
		errBkg = 0.;
	      }
	      rateTotBkg += effBkg * bkgEvents[xSecNum].second * luminosity * conversion;
	      errTotBkg = sqrt(errTotBkg * errTotBkg + errBkg * errBkg * bkgEvents[xSecNum].second * luminosity * conversion * bkgEvents[xSecNum].second * luminosity * conversion);
	    }
	    
	    if (cutNum == 6) {
	      cout<<cutText<<endl;
	      cout<<rateTotBkg<<" +- "<<errTotBkg<<", "<<effSig<<" +- "<<errSig<<endl;;
	    }
	    EffVBkgEcap[pathNum][filterNum].SetPoint(cutNum, rateTotBkg, effSig);
	    EffVBkgEcap[pathNum][filterNum].SetPointError(cutNum, errTotBkg, errSig);
	    if (cutNum == 6) {
	      EffVBkg[pathNum][filterNum].GetPoint(cutNum, testX, testY);
	      cout<<testX<<", "<<testY<<endl;
	    }
	  }
	}
      }
    }
  }
  TCanvas *myCanvas;
  TString tempPathName, canvasTitle, graphTitle, outFilename;
  Int_t n;
  Int_t nGraphs, curGraph;
  for (pathNum = 0; pathNum < paths.size(); pathNum++) {
    canvasTitle = "Efficiency vs. Background for ";
    tempPathName = paths[pathNum].names[paths[pathNum].filters[(paths[pathNum].filters).size()-1].pathNum];
    tempPathName.Resize(tempPathName.Index(".", 1, 0, TString::kExact));
    outFilename = "./images/";
    outFilename += tempPathName;
    outFilename += "EffVBkg.gif";
    n = 0;
    while (tempPathName.Contains(TRegexp("[a-z][A-Z]")) && n < 10) {
      tempPathName.Insert(tempPathName.Index(TRegexp("[a-z][A-Z]"))+1, " ");
      n++;
    }
    canvasTitle += tempPathName;
    nGraphs = 0;
    for (filterNum = 0; filterNum < (paths[pathNum].filters).size(); filterNum++) {
      if ((paths[pathNum].filters)[filterNum].maxCut != 0) nGraphs++;
    }
    myCanvas = new TCanvas("myCanvas", canvasTitle, 0, 0, 1000, 500*(nGraphs / 2 + 1));
    myCanvas->Divide(2,nGraphs / 2 + 1);
    curGraph = 0;
    for (filterNum = 0; filterNum < (paths[pathNum].filters).size(); filterNum++) {
      if ((paths[pathNum].filters)[filterNum].maxCut != 0.) {
        myCanvas->cd(curGraph+1);
	curGraph++;
        graphTitle = "Efficiency vs. Background for ";
	graphTitle += (paths[pathNum].filters)[filterNum].name;
	graphTitle += " Filter;Background Rate (Hz);Signal Eff.";
	EffVBkg[pathNum][filterNum].SetTitle(graphTitle);
	EffVBkg[pathNum][filterNum].Draw("AP");
      }
    }
    myCanvas->Print(outFilename);
    if (doBandE) {
      canvasTitle = "Efficiency vs. Background for ";
      tempPathName = paths[pathNum].names[paths[pathNum].filters[(paths[pathNum].filters).size()-1].pathNum];
      tempPathName.Resize(tempPathName.Index(".", 1, 0, TString::kExact));
      tempPathName += "Endcap";
      outFilename = "./images/";
      outFilename += tempPathName;
      outFilename += "EffVBkg.gif";
      n = 0;
      while (tempPathName.Contains(TRegexp("[a-z][A-Z]")) && n < 10) {
	tempPathName.Insert(tempPathName.Index(TRegexp("[a-z][A-Z]"))+1, " ");
	n++;
      }
      canvasTitle += tempPathName;
      nGraphs = 0;
      for (filterNum = 0; filterNum < (paths[pathNum].filters).size(); filterNum++) {
	if ((paths[pathNum].filters)[filterNum].maxCut != 0) nGraphs++;
      }
      myCanvas = new TCanvas("myCanvas", canvasTitle, 0, 0, 1000, 500*(nGraphs / 2 + 1));
      myCanvas->Divide(2,nGraphs / 2 + 1);
      curGraph = 0;
      for (filterNum = 0; filterNum < (paths[pathNum].filters).size(); filterNum++) {
	if ((paths[pathNum].filters)[filterNum].maxCut != 0.) {
	  myCanvas->cd(curGraph+1);
	  curGraph++;
	  graphTitle = "Efficiency vs. Background for ";
	  graphTitle += (paths[pathNum].filters)[filterNum].name;
	  graphTitle += " Filter in Endcap;Background Rate (Hz);Signal Eff.";
	  EffVBkgEcap[pathNum][filterNum].SetTitle(graphTitle);
	  EffVBkgEcap[pathNum][filterNum].Draw("AP");
	}
      }
      myCanvas->Print(outFilename);
    }
  }

  TH1F *timingSig = new TH1F("timingSig", "Timing of Single Electron Filters in Signal Events", 6, 0, 6);
  timingSig->SetCanExtend(TH1::kAllAxes);
  timingSig->SetStats(0);
  TTreeFormula *l1MatchTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.l1Match",sigEvents);
  TTreeFormula *EtTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.Et",sigEvents);
  TTreeFormula *IHcalTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.ElecIHcal",sigEvents);
  TTreeFormula *pixMatchTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.pixMatch",sigEvents);
  TTreeFormula *EoverpTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.Eoverp",sigEvents);
  TTreeFormula *ItrackTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.ElecItrack",sigEvents);
  Long64_t event = 0;
  Double_t avgL1Match = 0.;
  Double_t avgEt = 0.;
  Double_t avgIHcal = 0.;
  Double_t avgPixMatch = 0.;
  Double_t avgEoverp = 0.;
  Double_t avgItrack = 0.;
  for (event = 0; event < sigEvents->GetEntries(); event++) {
    sigEvents->LoadTree(event);
    avgL1Match = (event*avgL1Match + l1MatchTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
    avgEt = (event*avgEt + EtTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
    avgIHcal = (event*avgIHcal + IHcalTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
    avgPixMatch = (event*avgPixMatch + pixMatchTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
    avgEoverp = (event*avgEoverp + EoverpTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
    avgItrack = (event*avgItrack + ItrackTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
  }
  timingSig->Fill("L1 Match", avgL1Match);
  timingSig->Fill("Et", avgEt); 
  timingSig->Fill("IHcal", avgIHcal); 
  timingSig->Fill("Pix Match", avgPixMatch); 
  timingSig->Fill("E/p", avgEoverp); 
  timingSig->Fill("Itrack", avgItrack); 
  timingSig->LabelsDeflate("X");
  timingSig->LabelsOption("v");

  TH1F *timingBkg = new TH1F("timingBkg", "Timing of Single Electron Filters in Background Events", 6, 0, 6);
  timingBkg->SetCanExtend(TH1::kAllAxes);
  timingBkg->SetStats(0);
  avgL1Match = 0.;
  avgEt = 0.;
  avgIHcal = 0.;
  avgPixMatch = 0.;
  avgEoverp = 0.;
  avgItrack = 0.;
  for (xSecNum = 0; xSecNum < bkgEvents.size(); xSecNum++) {
    delete l1MatchTiming; l1MatchTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.l1Match",bkgEvents[xSecNum].first);
    delete EtTiming; EtTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.Et",bkgEvents[xSecNum].first);
    delete IHcalTiming; IHcalTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.ElecIHcal",bkgEvents[xSecNum].first);
    delete pixMatchTiming; pixMatchTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.pixMatch",bkgEvents[xSecNum].first);
    delete EoverpTiming; EoverpTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.Eoverp",bkgEvents[xSecNum].first);
    delete ItrackTiming; ItrackTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.ElecItrack",bkgEvents[xSecNum].first);
    event = 0;
    for (event = 0; event <  bkgEvents[xSecNum].first->GetEntries(); event++) {
      bkgEvents[xSecNum].first->LoadTree(event);
      avgL1Match = (event*avgL1Match + l1MatchTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
      avgEt = (event*avgEt + EtTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
      avgIHcal = (event*avgIHcal + IHcalTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
      avgPixMatch = (event*avgPixMatch + pixMatchTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
      avgEoverp = (event*avgEoverp + EoverpTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
      avgItrack = (event*avgItrack + ItrackTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
    }
  }
  timingBkg->Fill("L1 Match", avgL1Match);
  timingBkg->Fill("Et", avgEt); 
  timingBkg->Fill("IHcal", avgIHcal); 
  timingBkg->Fill("Pix Match", avgPixMatch); 
  timingBkg->Fill("E/p", avgEoverp); 
  timingBkg->Fill("Itrack", avgItrack); 
  timingBkg->LabelsDeflate("X");
  timingBkg->LabelsOption("v");

  myCanvas = new TCanvas("myCanvas", "Timing vs. Filter for Isolated Electron Filters", 1000, 500);
  myCanvas->Divide(2,1);
  myCanvas->cd(1);
  timingSig->Draw();
  myCanvas->cd(2);
  timingBkg->Draw();
  myCanvas->Print("images/TimingIso.gif");
  delete myCanvas;
  delete timingSig;
  delete timingBkg;

  timingSig = new TH1F("timingSig", "Timing of Single Photon Filters in Signal Events", 6, 0, 6);
  timingSig->SetCanExtend(TH1::kAllAxes);
  timingSig->SetStats(0);
  delete l1MatchTiming; l1MatchTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.l1Match",sigEvents);
  delete EtTiming; EtTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.Et",sigEvents);
  TTreeFormula *IEcalTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.IEcal",sigEvents);
  TTreeFormula *PhotIHcalTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.PhotIHcal",sigEvents);
  TTreeFormula *PhotItrackTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.PhotItrack",sigEvents);
  event = 0;
  avgL1Match = 0.;
  avgEt = 0.;
  Double_t avgIEcal = 0.;
  Double_t avgPhotIHcal = 0.;
  Double_t avgPhotItrack = 0.;
  for (event = 0; event < sigEvents->GetEntries(); event++) {
    sigEvents->LoadTree(event);
    avgL1Match = (event*avgL1Match + l1MatchTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
    avgEt = (event*avgEt + EtTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
    avgIEcal = (event*avgIEcal + IEcalTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
    avgPhotIHcal = (event*avgPhotIHcal + PhotIHcalTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
    avgPhotItrack = (event*avgPhotItrack + PhotItrackTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
  }
  timingSig->Fill("L1 Match", avgL1Match);
  timingSig->Fill("Et", avgEt); 
  timingSig->Fill("IEcal", avgIEcal); 
  timingSig->Fill("IHcal", avgPhotIHcal); 
  timingSig->Fill("Itrack", avgPhotItrack); 
  timingSig->LabelsDeflate("X");
  timingSig->LabelsOption("v");

  timingBkg = new TH1F("timingBkg", "Timing of Single Photon Filters in Background Events", 6, 0, 6);
  timingBkg->SetCanExtend(TH1::kAllAxes);
  timingBkg->SetStats(0);
  avgL1Match = 0.;
  avgEt = 0.;
  avgIEcal = 0.;
  avgPhotIHcal = 0.;
  avgPhotItrack = 0.;
  for (xSecNum = 0; xSecNum < bkgEvents.size(); xSecNum++) {
    delete l1MatchTiming; l1MatchTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.l1Match",bkgEvents[xSecNum].first);
    delete EtTiming; EtTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.Et",bkgEvents[xSecNum].first);
    delete IEcalTiming; IEcalTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.IEcal",bkgEvents[xSecNum].first);
    delete PhotIHcalTiming; PhotIHcalTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.PhotIHcal",bkgEvents[xSecNum].first);
    delete PhotItrackTiming; PhotItrackTiming = new TTreeFormula("Timing","HLTTiming_hltCutVars_IsoTiming_EGAMMAHLT.obj.PhotItrack",bkgEvents[xSecNum].first);
    event = 0;
    for (event = 0; event < bkgEvents[xSecNum].first->GetEntries(); event++) {
      bkgEvents[xSecNum].first->LoadTree(event);
      avgL1Match = (event*avgL1Match + l1MatchTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
      avgEt = (event*avgEt + EtTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
      avgIEcal = (event*avgIEcal + IEcalTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
      avgPhotIHcal = (event*avgPhotIHcal + PhotIHcalTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
      avgPhotItrack = (event*avgPhotItrack + PhotItrackTiming->EvalInstance(0))/ ((Double_t) (event+1)); 
    }
  }
  timingBkg->Fill("L1 Match", avgL1Match);
  timingBkg->Fill("Et", avgEt); 
  timingBkg->Fill("IEcal", avgIEcal); 
  timingBkg->Fill("IHcal", avgPhotIHcal); 
  timingBkg->Fill("Itrack", avgPhotItrack); 
  timingBkg->LabelsDeflate("X");
  timingBkg->LabelsOption("v");
    
  myCanvas = new TCanvas("myCanvas", "Timing vs. Filter for Isolated Photon Filters", 1000, 500);
  myCanvas->Divide(2,1);
  myCanvas->cd(1);
  timingSig->Draw();
  myCanvas->cd(2);
  timingBkg->Draw();
  myCanvas->Print("images/TimingIsoPhot.gif");
}
void readTree(TString filelist="/global/project/projectdirs/star/pwg/starhf/zamiller/minBiasTemplates101015/Trees.list",TString outFile="/global/project/projectdirs/star/pwg/starhf/zamiller/minBiasTemplates101015/readTreeOutSubmitTEST.root")
{

  //TString filelist=Form("%s/%s",localDir,fileIn);
  //TString outFile=Form("%s/%s",outDir,fileOut);

  TFile fout(outFile,"RECREATE");
  TH1F::SetDefaultSumw2(); 
  TH1D::SetDefaultSumw2(); 

  for(Int_t c=0; c< numPtBins; c++)
  {
    lowpt[c] = anaConst::lpt[c];
    highpt[c] = anaConst::hpt[c];
  }
  for(Int_t ptbin = 0; ptbin < numPtBins; ptbin++)
  {
    hdEtaRawce[ptbin] = new TH1D(Form("hdEtaRawce_%i",ptbin),"hdEtaRawce",100, -5,5);
    hdEtaRawbe[ptbin] = new TH1D(Form("hdEtaRawbe_%i",ptbin),"hdEtaRawbe",100, -5,5);
    hEventTallyce[ptbin] = new TH1D(Form("ceEventTally_%i",ptbin),"ceEvent Tally",1,0,1);
    hEventTallybe[ptbin] = new TH1D(Form("beEventTally_%i",ptbin),"beEvent Tally",1,0,1);
    hEventTallybce[ptbin] = new TH1D(Form("bceEventTally_%i",ptbin),"bceEvent Tally",1,0,1);
    hdPhiRawce[ptbin] = new TH1D(Form("hdPhiRawce_%i",ptbin),"hdPhiRawce",Phibin, -10,10);
    hdPhiRawbe[ptbin] = new TH1D(Form("hdPhiRawbe_%i",ptbin),"hdPhiRawbe",Phibin, -10,10);
    hdPhiRawbce[ptbin] = new TH1D(Form("hdPhiRawbce_%i",ptbin),"hdPhiRawbce",Phibin, -10,10);
    hept[ptbin] = new TH1D(Form("hept_%i",ptbin),"hept",200,0.,20.);
  }

  // Make Chain
  TChain* chain = new TChain("tree");
  int nfile = 0;
  /*  nfile += chain->Add("Oct30_set13/pythia_tree_Oct30_13.root");
      nfile += chain->Add("Oct30_set14/pythia_tree_Oct30_14.root");
      nfile += chain->Add("Oct30_set15/pythia_tree_Oct30_15.root");
      nfile += chain->Add("Oct30_set16/pythia_tree_Oct30_16.root");
      nfile += chain->Add("Oct30_set17/pythia_tree_Oct30_17.root");
  //  nfile += chain->Add("Oct30_set12/pythia_tree_Oct30_12.root");
  //  nfile += chain->Add("Oct26_set3/pythia_tree_Oct26_3.root");
  // nfile += chain->Add("Oct18_set4/pythia_tree_Oct18_4.root");
  //nfile += chain->Add("liweiTemplate_part2.root");*/
  char filename[1000];
  ifstream fstream(filelist.Data());
  int ifile = 0;
  while (fstream >> filename)
  {
    nfile+= chain->Add(filename);
    std::cout << "Got File: " << filename << std::endl;
  }

  std::cout <<"Added "<<nfile<<" files"<<std::endl;
  std::cout<<"# entries in chain: "<<chain->GetEntries()<<std::endl;
  if (chain == 0) return;

  int ceNtrigger=0;
  int beNtrigger=0;
  int bceNtrigger=0;
  int ptbin,maxptbin;

  //define variables
  Int_t   Event, numberofcElectrons, numberofbElectrons,numberofbcElectrons, numberofHadrons, noTracks;   //
  Float_t celectron_id,celectron_status,celectron_pt,celectron_pz,celectron_phi,celectron_eta,celectron_y;                //track info
  Float_t belectron_id,belectron_status,belectron_pt,belectron_pz,belectron_phi,belectron_eta,belectron_y;
  Float_t bcelectron_id,bcelectron_status,bcelectron_pt,bcelectron_pz,bcelectron_phi,bcelectron_eta,bcelectron_y;
  Float_t assoh_id,assoh_status,assoh_pt,assoh_pz,assoh_phi,assoh_eta,assoh_y;

  int goodEvent = 0;


  Long64_t nentries = chain->GetEntriesFast();
  int x = 0; int n = nentries; int w = 25;

  for(int i = 0; i < nentries; i++){
    Long64_t ientry = chain->LoadTree(i);
    if (ientry < 0) break;
    TBranch *b_destep = chain->GetBranch("hf2eDecay");

    TLeaf* leaf_Event_id            = b_destep->GetLeaf("Event_id");
    TLeaf* leaf_refMult             = b_destep->GetLeaf("refMult");
    TLeaf* leaf_numberofcElectrons  = b_destep->GetLeaf("numberofcElectrons");
    TLeaf* leaf_numberofbElectrons  = b_destep->GetLeaf("numberofbElectrons");
    TLeaf* leaf_numberofbcElectrons = b_destep->GetLeaf("numberofbcElectrons");
    TLeaf* leaf_numberofHadrons     = b_destep->GetLeaf("numberofHadrons");
    TLeaf* leaf_noTracks            = b_destep->GetLeaf("noTracks");

    TLeaf* leaf_ce_id               = b_destep->GetLeaf("ce_id");
    TLeaf* leaf_ce_status           = b_destep->GetLeaf("ce_status");
    TLeaf* leaf_ce_pt               = b_destep->GetLeaf("ce_pt");
    TLeaf* leaf_ce_pz               = b_destep->GetLeaf("ce_pz");
    TLeaf* leaf_ce_phi              = b_destep->GetLeaf("ce_phi");
    TLeaf* leaf_ce_eta              = b_destep->GetLeaf("ce_eta");
    TLeaf* leaf_ce_y                = b_destep->GetLeaf("ce_y");

    TLeaf* leaf_be_id               = b_destep->GetLeaf("be_id");
    TLeaf* leaf_be_status           = b_destep->GetLeaf("be_status");
    TLeaf* leaf_be_pt               = b_destep->GetLeaf("be_pt");
    TLeaf* leaf_be_pz               = b_destep->GetLeaf("be_pz");
    TLeaf* leaf_be_phi              = b_destep->GetLeaf("be_phi");
    TLeaf* leaf_be_eta              = b_destep->GetLeaf("be_eta");
    TLeaf* leaf_be_y                = b_destep->GetLeaf("be_y");

    TLeaf* leaf_bce_id              = b_destep->GetLeaf("bce_id");
    TLeaf* leaf_bce_status          = b_destep->GetLeaf("bce_status");
    TLeaf* leaf_bce_pt              = b_destep->GetLeaf("bce_pt");
    TLeaf* leaf_bce_pz              = b_destep->GetLeaf("bce_pz");
    TLeaf* leaf_bce_phi             = b_destep->GetLeaf("bce_phi");
    TLeaf* leaf_bce_eta             = b_destep->GetLeaf("bce_eta");
    TLeaf* leaf_bce_y               = b_destep->GetLeaf("bce_y");

    TLeaf* leaf_hadron_id           = b_destep->GetLeaf("hadron_id");
    TLeaf* leaf_hadron_status       = b_destep->GetLeaf("hadron_status");
    TLeaf* leaf_hadron_pt           = b_destep->GetLeaf("hadron_pt");
    TLeaf* leaf_hadron_pz           = b_destep->GetLeaf("hadron_pz");
    TLeaf* leaf_hadron_phi          = b_destep->GetLeaf("hadron_phi");
    TLeaf* leaf_hadron_eta          = b_destep->GetLeaf("hadron_eta");
    TLeaf* leaf_hadron_y            = b_destep->GetLeaf("hadron_y");

    x = i+1;
    // Process Completion bar
    if ( (x != n) && (x % (n/100) == 0) )
    {
      float ratio  =  (float)x/(float)n;
      int   c      =  ratio * w;

      if(ratio < 1){
        std::cout << (int)(ratio*100) << "% [";
        for (int x=0; x<c; x++) std::cout << "=";
        for (int x=c; x<w; x++) std::cout << " ";
        std::cout << "]\r" << std::flush ;
      }
    }


    // if(i%10000 == 0)
    //   std::cout <<"Entry: "<< i << std::endl;
    chain->GetEntry(i);

    Event   = (int)leaf_Event_id->GetValue(0);
    numberofcElectrons = (int)leaf_numberofcElectrons->GetValue(0);
    // std::cout << numberofcElectrons << " ";
    numberofbElectrons = (int)leaf_numberofbElectrons->GetValue(0);
    numberofbcElectrons = (int)leaf_numberofbcElectrons->GetValue(0);
    numberofHadrons = (int)leaf_numberofHadrons->GetValue(0);
    // std::cout << "numHad: " << numberofHadrons << std::endl;
    noTracks        = leaf_noTracks->GetValue(0);
    hrefmult -> Fill(noTracks);

    //loop through matched primary tracks electron find c decayed electron
    int ceNtrigcount=0;
    maxptbin = 0;
    for(int trki = 0; trki < numberofcElectrons; trki++){
      celectron_id      = (int)leaf_ce_id->GetValue(trki);
      celectron_status  = (int)leaf_ce_status->GetValue(trki);
      celectron_pt      = leaf_ce_pt->GetValue(trki);
      celectron_pz      = leaf_ce_pz->GetValue(trki);
      celectron_phi     = leaf_ce_phi->GetValue(trki);
      celectron_eta     = leaf_ce_eta->GetValue(trki);
      celectron_y       = leaf_ce_y->GetValue(trki);
      if(celectron_eta > EtaCut || celectron_eta < -EtaCut) continue;
      ptbin = getPtBin(celectron_pt);
      if(ptbin == -99) continue;
      if(ptbin > maxptbin)
        maxptbin = ptbin;
      hept[ptbin]->Fill(celectron_pt);
      hEventTallyce[maxptbin]->Fill(0.5); //fill for each NPE

      for(int trkj = 0; trkj < numberofHadrons; trkj++){

        assoh_id = (int)leaf_hadron_id->GetValue(trkj);
        assoh_status  = (int)leaf_hadron_status->GetValue(trkj);
        assoh_pt      = leaf_hadron_pt->GetValue(trkj);
        assoh_pz      = leaf_hadron_pz->GetValue(trkj);
        assoh_phi     = leaf_hadron_phi->GetValue(trkj);
        assoh_eta     = leaf_hadron_eta->GetValue(trkj);
        assoh_y       = leaf_hadron_y->GetValue(trkj);
        if(assoh_eta > hEtaCut || assoh_eta < -hEtaCut) continue;

        float deltPhi = assoh_phi - celectron_phi;
        float deltEta = assoh_eta - celectron_eta;
        if(deltPhi < -PI)  deltPhi += 2*PI;
        if(deltPhi >  PI) deltPhi -= 2*PI;
        if(abs(deltEta) > deletacut) continue;
        if(assoh_pt>hptCut)
        {
          hdPhiRawce[ptbin]->Fill(deltPhi); 
          hdEtaRawce[ptbin]->Fill(deltEta);
          ceNtrigcount++;
        }
      }
    }
    //if(ceNtrigcount>0)hEventTallyce[maxptbin]->Fill(0.5);
    //if(ceNtrigcount>0)ceNtrigger++;

    //b decayed electron-------------------------------------------------- 
    int beNtrigcount=0;
    maxptbin = 0;
    for(int trki = 0; trki < numberofbElectrons; trki++){
      belectron_id = (int)leaf_be_id->GetValue(trki);
      belectron_status  = (int)leaf_be_status->GetValue(trki);
      belectron_pt      = leaf_be_pt->GetValue(trki);
      belectron_pz      = leaf_be_pz->GetValue(trki);
      belectron_phi     = leaf_be_phi->GetValue(trki);
      belectron_eta     = leaf_be_eta->GetValue(trki);
      belectron_y        = leaf_be_y->GetValue(trki);
      if(belectron_eta > EtaCut || belectron_eta < -EtaCut) continue;
      ptbin = getPtBin(belectron_pt);
      if(ptbin == -99) continue;
      if(ptbin > maxptbin)
        maxptbin = ptbin;
      hept[ptbin]->Fill(belectron_pt);
      hEventTallybe[maxptbin]->Fill(0.5); //fill for each NPE
      for(int trkj = 0; trkj < numberofHadrons; trkj++){

        assoh_id = (int)leaf_hadron_id->GetValue(trkj);
        assoh_status  = (int)leaf_hadron_status->GetValue(trkj);
        assoh_pt      = leaf_hadron_pt->GetValue(trkj);
        assoh_pz      = leaf_hadron_pz->GetValue(trkj);
        assoh_phi     = leaf_hadron_phi->GetValue(trkj);
        assoh_eta     = leaf_hadron_eta->GetValue(trkj);
        assoh_y       = leaf_hadron_y->GetValue(trkj);
        if(assoh_eta > hEtaCut || assoh_eta < -hEtaCut) continue;

        float deltPhi = assoh_phi - belectron_phi;
        float deltEta = assoh_eta - belectron_eta;
        if(deltPhi < -PI)  deltPhi += 2*PI;
        if(deltPhi >  PI) deltPhi -= 2*PI;
        if(abs(deltEta) > deletacut) continue;
        if(assoh_pt>hptCut)
        {
          hdPhiRawbe[ptbin]->Fill(deltPhi);
          hdEtaRawbe[ptbin]->Fill(deltEta);  
          beNtrigcount++;
        }
      }
    }
    //    if(beNtrigcount>0)hEventTallybe[maxptbin]->Fill("be non photonic electron",1);
    //    if(beNtrigcount>0)beNtrigger++;
    //bce decayed electron-----------------------------------------------------------------                                                                                           
    int bceNtrigcount=0;
    maxptbin = 0;
    for(int trki = 0; trki < numberofbcElectrons; trki++){
      bcelectron_id = (int)leaf_bce_id->GetValue(trki);
      bcelectron_status  = (int)leaf_bce_status->GetValue(trki);
      bcelectron_pt      = leaf_bce_pt->GetValue(trki);
      bcelectron_pz      = leaf_bce_pz->GetValue(trki);
      bcelectron_phi     = leaf_bce_phi->GetValue(trki);
      bcelectron_eta     = leaf_bce_eta->GetValue(trki);
      bcelectron_y       = leaf_bce_y->GetValue(trki);
      if(bcelectron_eta > EtaCut || bcelectron_eta < -EtaCut) continue;
      ptbin = getPtBin(bcelectron_pt);
      if(ptbin == -99) continue;
      if(ptbin > maxptbin)
        maxptbin = ptbin;
      hept[ptbin]->Fill(bcelectron_pt);
      hEventTallybe[maxptbin]->Fill(0.5); //fill for each NPE
      for(int trkj = 0; trkj < numberofHadrons; trkj++){

        assoh_id = (int)leaf_hadron_id->GetValue(trkj);
        assoh_status  = (int)leaf_hadron_status->GetValue(trkj);
        assoh_pt      = leaf_hadron_pt->GetValue(trkj);
        assoh_pz      = leaf_hadron_pz->GetValue(trkj);
        assoh_phi     = leaf_hadron_phi->GetValue(trkj);
        assoh_eta     = leaf_hadron_eta->GetValue(trkj);
        assoh_y       = leaf_hadron_y->GetValue(trkj);
        if(assoh_eta > hEtaCut || assoh_eta < -hEtaCut) continue;

        float deltPhi = assoh_phi - bcelectron_phi;
        float deltEta = assoh_eta - celectron_eta;
        if(deltPhi < -PI)  deltPhi += 2*PI;
        if(deltPhi >  PI) deltPhi -= 2*PI;
        if(abs(deltEta) > deletacut) continue;
        if(assoh_pt>hptCut)
        {
          hdPhiRawbe[ptbin]->Fill(deltPhi);
          hdEtaRawbe[ptbin]->Fill(deltEta);  
          bceNtrigcount++;
        }
      }
    }
    //    if(bceNtrigcount>0)hEventTallybe[maxptbin]->Fill("be non photonic electron",1);
    //    if(bceNtrigcount>0)beNtrigger++;


    /* if(ceNtrigger+bceNtrigger+beNtrigger > 0){
       std::cout<<"ce Trigger electron number = "<<ceNtrigger<<std::endl;
       std::cout<<"be Trigger electron number = "<<beNtrigger<<std::endl;
       std::cout<<"bce Trigger electron number = "<<bceNtrigger<<std::endl;
       }*/
  }

  // After Fill Manipulations
  for(int qq = 0; qq < numPtBins; qq++)
  {
    hdPhiRawceN[qq] = (TH1D*)hdPhiRawce[qq]->Clone();
    hdPhiRawceN[qq] -> SetName(Form("hdPhiRawceN_%i",qq));
    hdPhiRawceN[qq] -> Sumw2();
    hdPhiRawceN[qq] -> Scale(1./(Double_t)hEventTallyce[qq]->GetBinContent(1));
    hdPhiRawbeN[qq] = (TH1D*)hdPhiRawbe[qq]->Clone();
    hdPhiRawbeN[qq] -> SetName(Form("hdPhiRawbeN_%i",qq));
    hdPhiRawbeN[qq] -> Sumw2();
    hdPhiRawbeN[qq] -> Scale(1./(Double_t)hEventTallybe[qq]->GetBinContent(1));
  }

  std::cout << "100% [";
  for (int x=0; x<w; x++) std::cout << "=";
  std::cout << "]" << std::endl;
  fout.Write();
  fout.Close();
  delete chain;
}
void trainElectronEnergyRegression_ECAL(char* trainingFile, char* outWeightFile, char* optionChar, int nTrees) {


  
  // Setting up training option
  std::string optionStr(optionChar);

  // ******** If option is V00, V01, V02, etc. ********* //
  if (optionStr == "V00" || optionStr == "V01") {

    GBRTrainer *traineb = new GBRTrainer;
    GBRTrainer *trainebvar = new GBRTrainer;
    GBRTrainer *trainee = new GBRTrainer;
    GBRTrainer *traineevar = new GBRTrainer;

    TTree *intree = 0;

    cout << "Training on file " << trainingFile << " with version " << optionChar << endl;
    TChain *chainele = new TChain("eleIDdir/T1");
    chainele->Add(trainingFile);
    chainele->LoadTree(0);    
    chainele->SetCacheSize(64*1024*1024);
    chainele->SetCacheLearnEntries();
    intree = chainele;

    traineb->AddTree(chainele);
    trainebvar->AddTree(chainele);
    trainee->AddTree(chainele);
    traineevar->AddTree(chainele);

    TCut traincut = "pt>0";////////////////////////////////

    TCut evtcut;
    TCut evtcutvar;
    TCut statusenergycut;

    //if you want to train also energy variance
    evtcut = "event%2==0 ";
    evtcutvar = "event%2==1 ";


    statusenergycut="(GeneratedEnergyStatus3-GeneratedEnergyStatus1)/GeneratedEnergyStatus3<0.01 && GeneratedEnergyStatus3>=GeneratedEnergyStatus1";

    traineb->SetTrainingCut(std::string(traincut && evtcut && statusenergycut && "abs(eta)<1.479 && mcmatch==1"));
    trainee->SetTrainingCut(std::string(traincut && evtcut && statusenergycut && "abs(eta)>1.479 && abs(eta)<2.5 && mcmatch==1"));
    //turn this off for now

    trainebvar->SetTrainingCut(std::string(traincut && evtcutvar && statusenergycut && "abs(eta)<1.479 && mcmatch==1"));
    traineevar->SetTrainingCut(std::string(traincut && evtcutvar && statusenergycut && "abs(eta)>1.479 && abs(eta)<2.5 && mcmatch==1"));
   

    const double maxsig = 3.0;
    const double shrinkage = 0.1;

    traineb->SetMinEvents(200);
    traineb->SetShrinkage(shrinkage);  
    traineb->SetMinCutSignificance(maxsig);

    trainebvar->SetMinEvents(200);
    trainebvar->SetShrinkage(shrinkage);  
    trainebvar->SetMinCutSignificance(maxsig);  

    trainee->SetMinEvents(200);
    trainee->SetShrinkage(shrinkage);  
    trainee->SetMinCutSignificance(maxsig);  

    traineevar->SetMinEvents(200);
    traineevar->SetShrinkage(shrinkage);  
    traineevar->SetMinCutSignificance(maxsig);    

    traineb->SetTargetVar("GeneratedEnergyStatus3/SCRawEnergy");
    trainebvar->SetTargetVar("abs( targeteb - GeneratedEnergyStatus3/SCRawEnergy) ");
    trainee->SetTargetVar("GeneratedEnergyStatus3/(SCRawEnergy*(1+PreShowerOverRaw))");
    traineevar->SetTargetVar("abs( targetee - GeneratedEnergyStatus3/(SCRawEnergy*(1+PreShowerOverRaw))) ");

    std::vector<std::string> *varsf = new std::vector<std::string>;
    varsf->push_back("SCRawEnergy");
    varsf->push_back("scEta");
    varsf->push_back("scPhi");
    varsf->push_back("R9");  
    varsf->push_back("E5x5Seed/SCRawEnergy");  
    varsf->push_back("etawidth");
    varsf->push_back("phiwidth");  
    varsf->push_back("NClusters");
    varsf->push_back("HoE");
    varsf->push_back("rho");
    varsf->push_back("vertices");  
    varsf->push_back("EtaSeed-scEta");
    varsf->push_back("atan2(sin(PhiSeed-scPhi),cos(PhiSeed-scPhi))");
    varsf->push_back("ESeed/SCRawEnergy");
    varsf->push_back("E3x3Seed/ESeed");
    varsf->push_back("E5x5Seed/ESeed");
    varsf->push_back("see");   
    varsf->push_back("spp");   
    //    varsf->push_back("sep");
    varsf->push_back("EMaxSeed/ESeed");
    varsf->push_back("E2ndSeed/ESeed");
    varsf->push_back("ETopSeed/ESeed");
    varsf->push_back("EBottomSeed/ESeed");
    varsf->push_back("ELeftSeed/ESeed");
    varsf->push_back("ERightSeed/ESeed");
    varsf->push_back("E2x5MaxSeed/ESeed");
    varsf->push_back("E2x5TopSeed/ESeed");
    varsf->push_back("E2x5BottomSeed/ESeed");
    varsf->push_back("E2x5LeftSeed/ESeed");
    varsf->push_back("E2x5RightSeed/ESeed");


    std::vector<std::string> *varseb = new std::vector<std::string>(*varsf);
    std::vector<std::string> *varsee = new std::vector<std::string>(*varsf);

    varseb->push_back("IEtaSeed");
    varseb->push_back("IPhiSeed");
    varseb->push_back("IEtaSeed%5");
    varseb->push_back("IPhiSeed%2");       
    varseb->push_back("(abs(IEtaSeed)<=25)*(IEtaSeed%25) + (abs(IEtaSeed)>25)*((IEtaSeed-25*abs(IEtaSeed)/IEtaSeed)%20)");
    varseb->push_back("IPhiSeed%20"); 
    varseb->push_back("EtaCrySeed");
    varseb->push_back("PhiCrySeed");

    varsee->push_back("PreShowerOverRaw");


    for (int i=0; i<varseb->size(); ++i) {
      cout << "var " << i << " = " << varseb->at(i) << endl;
      traineb->AddInputVar(varseb->at(i));
      trainebvar->AddInputVar(varseb->at(i));
    }

    for (int i=0; i<varsee->size(); ++i) {
      cout << "var " << i << " = " << varsee->at(i) << endl;
      trainee->AddInputVar(varsee->at(i));
      traineevar->AddInputVar(varsee->at(i));
    }

    ROOT::Cintex::Cintex::Enable();   

    //  TFile *ftmp = new TFile("tmpfile.root","RECREATE");    
    GBRApply gbrapply;


    //Train Barrel Energy Regression
    intree->LoadTree(0);  
    const GBRForest *foresteb = traineb->TrainForest(nTrees);
    delete traineb;

    //Apply Barrel Energy Regression
    intree->LoadTree(0);  
    gbrapply.ApplyAsFriend(intree, foresteb, *varseb, "targeteb");


    //Train Barrel Variance Regression
    intree->LoadTree(0);
    const GBRForest *forestebvar = trainebvar->TrainForest(nTrees);
    delete trainebvar;

    //Train Endcap Energy Regression
    intree->LoadTree(0);
    const GBRForest *forestee = trainee->TrainForest(nTrees);
    delete trainee;

    //Apply Endcap Energy Regression
    intree->LoadTree(0);
    gbrapply.ApplyAsFriend(intree, forestee, *varsee, "targetee");

    //Train Endcap Variance Regression
    intree->LoadTree(0);  
    const GBRForest *foresteevar = traineevar->TrainForest(nTrees);
    delete traineevar;  

    TString fname;

    fname = outWeightFile;



    TFile *fout = new TFile(fname,"RECREATE");  
    cout << "Saving weights to file " << fname << endl;

    fout->WriteObject(foresteb,"EBCorrection");
    fout->WriteObject(forestebvar,"EBUncertainty");
    fout->WriteObject(forestee,"EECorrection");
    fout->WriteObject(foresteevar,"EEUncertainty");

    fout->WriteObject(varseb, "varlisteb");
    fout->WriteObject(varsee, "varlistee");

    //  ftmp->Close();  
    //  fout->Close();
  }  



  // ******** If option is V10, V11, V12, etc. ******** //
  // *** Do training separately for low and high pT *** //
  if (optionStr == "V10" || optionStr == "V11") {

    GBRTrainer *traineb_lowPt = new GBRTrainer;
    GBRTrainer *traineb_highPt = new GBRTrainer;
    GBRTrainer *trainebvar_lowPt = new GBRTrainer;
    GBRTrainer *trainebvar_highPt = new GBRTrainer;
    GBRTrainer *trainee_lowPt = new GBRTrainer;
    GBRTrainer *trainee_highPt = new GBRTrainer;
    GBRTrainer *traineevar_lowPt = new GBRTrainer;
    GBRTrainer *traineevar_highPt = new GBRTrainer;

    TTree *intree = 0;

    cout << "Training on file " << trainingFile << " with version " << optionChar << endl;
    TChain *chainele = new TChain("eleIDdir/T1");
    chainele->Add(trainingFile);
    chainele->LoadTree(0);    
    chainele->SetCacheSize(64*1024*1024);
    chainele->SetCacheLearnEntries();
    intree = chainele;

    traineb_lowPt->AddTree(chainele);
    trainebvar_lowPt->AddTree(chainele);
    trainee_lowPt->AddTree(chainele);
    traineevar_lowPt->AddTree(chainele);
    traineb_highPt->AddTree(chainele);
    trainebvar_highPt->AddTree(chainele);
    trainee_highPt->AddTree(chainele);
    traineevar_highPt->AddTree(chainele);
    
    TCut traincut_lowPt = "pt>7 && pt<15";
    TCut traincut_highPt = "pt>=15";
    TCut statusenergycut;
    

    TCut evtcut;
    TCut evtcutvar;

    //if you want to train also energy variance
    evtcut = "event%2==0 ";
    evtcutvar = "event%2==1 ";

    statusenergycut="(GeneratedEnergyStatus3-GeneratedEnergyStatus1)/GeneratedEnergyStatus3<0.01 && GeneratedEnergyStatus3>=GeneratedEnergyStatus1";


    traineb_lowPt->SetTrainingCut(std::string(traincut_lowPt && evtcut && statusenergycut && "abs(eta)<1.479 && mcmatch==1"));
    trainee_lowPt->SetTrainingCut(std::string(traincut_lowPt && evtcut && statusenergycut && "abs(eta)>1.479 && abs(eta)<2.5 && mcmatch==1"));
    traineb_highPt->SetTrainingCut(std::string(traincut_highPt && evtcut && statusenergycut && "abs(eta)<1.479 && mcmatch==1"));	
    trainee_highPt->SetTrainingCut(std::string(traincut_highPt && evtcut && statusenergycut && "abs(eta)>1.479 && abs(eta)<2.5&& mcmatch==1"));


    //turn this off for now
    trainebvar_lowPt->SetTrainingCut(std::string(traincut_lowPt && evtcutvar && statusenergycut && "abs(eta)<1.479 && mcmatch==1"));		       
    traineevar_lowPt->SetTrainingCut(std::string(traincut_lowPt && evtcutvar && statusenergycut && "abs(eta)>1.479 && abs(eta)<2.5 && mcmatch==1")); 
    trainebvar_highPt->SetTrainingCut(std::string(traincut_highPt && evtcutvar && statusenergycut && "abs(eta)<1.479 && mcmatch==1"));	       
    traineevar_highPt->SetTrainingCut(std::string(traincut_highPt && evtcutvar && statusenergycut && "abs(eta)>1.479 && abs(eta)<2.5&& mcmatch==1"));

    const double maxsig = 3.0;
    const double shrinkage = 0.1;

    traineb_lowPt->SetMinEvents(200);
    traineb_lowPt->SetShrinkage(shrinkage);  
    traineb_lowPt->SetMinCutSignificance(maxsig);
    traineb_highPt->SetMinEvents(200);
    traineb_highPt->SetShrinkage(shrinkage);  
    traineb_highPt->SetMinCutSignificance(maxsig);

    trainebvar_lowPt->SetMinEvents(200);
    trainebvar_lowPt->SetShrinkage(shrinkage);  
    trainebvar_lowPt->SetMinCutSignificance(maxsig);  
    trainebvar_highPt->SetMinEvents(200);
    trainebvar_highPt->SetShrinkage(shrinkage);  
    trainebvar_highPt->SetMinCutSignificance(maxsig);  

    trainee_lowPt->SetMinEvents(200);
    trainee_lowPt->SetShrinkage(shrinkage);  
    trainee_lowPt->SetMinCutSignificance(maxsig);  
    trainee_highPt->SetMinEvents(200);
    trainee_highPt->SetShrinkage(shrinkage);  
    trainee_highPt->SetMinCutSignificance(maxsig);  

    traineevar_lowPt->SetMinEvents(200);
    traineevar_lowPt->SetShrinkage(shrinkage);  
    traineevar_lowPt->SetMinCutSignificance(maxsig);    
    traineevar_highPt->SetMinEvents(200);
    traineevar_highPt->SetShrinkage(shrinkage);  
    traineevar_highPt->SetMinCutSignificance(maxsig);    

    traineb_lowPt->SetTargetVar("GeneratedEnergyStatus3/SCRawEnergy");
    traineb_highPt->SetTargetVar("GeneratedEnergyStatus3/SCRawEnergy");
    trainebvar_lowPt->SetTargetVar("abs( targeteb_lowPt - GeneratedEnergyStatus3/SCRawEnergy) ");
    trainebvar_highPt->SetTargetVar("abs( targeteb_highPt - GeneratedEnergyStatus3/SCRawEnergy) ");
    trainee_lowPt->SetTargetVar("GeneratedEnergyStatus3/(SCRawEnergy*(1+PreShowerOverRaw))");
    trainee_highPt->SetTargetVar("GeneratedEnergyStatus3/(SCRawEnergy*(1+PreShowerOverRaw))");
    traineevar_lowPt->SetTargetVar("abs( targetee_lowPt - GeneratedEnergyStatus3/(SCRawEnergy*(1+PreShowerOverRaw))) ");
    traineevar_highPt->SetTargetVar("abs( targetee_highPt - GeneratedEnergyStatus3/(SCRawEnergy*(1+PreShowerOverRaw))) ");

    std::vector<std::string> *varsf = new std::vector<std::string>;
    varsf->push_back("SCRawEnergy");
    varsf->push_back("scEta");
    varsf->push_back("scPhi");
    varsf->push_back("R9");  
    varsf->push_back("E5x5Seed/SCRawEnergy");  
    varsf->push_back("etawidth");
    varsf->push_back("phiwidth");  
    varsf->push_back("NClusters");
    varsf->push_back("HoE");
    varsf->push_back("rho");
    varsf->push_back("vertices");  

    varsf->push_back("EtaSeed-scEta");
    varsf->push_back("atan2(sin(PhiSeed-scPhi),cos(PhiSeed-scPhi))");
    varsf->push_back("ESeed/SCRawEnergy");
    varsf->push_back("E3x3Seed/ESeed");
    varsf->push_back("E5x5Seed/ESeed");
    varsf->push_back("see");   
    varsf->push_back("spp");   
    //    varsf->push_back("sep");
    varsf->push_back("EMaxSeed/ESeed");
    varsf->push_back("E2ndSeed/ESeed");
    varsf->push_back("ETopSeed/ESeed");
    varsf->push_back("EBottomSeed/ESeed");
    varsf->push_back("ELeftSeed/ESeed");
    varsf->push_back("ERightSeed/ESeed");
    varsf->push_back("E2x5MaxSeed/ESeed");
    varsf->push_back("E2x5TopSeed/ESeed");
    varsf->push_back("E2x5BottomSeed/ESeed");
    varsf->push_back("E2x5LeftSeed/ESeed");
    varsf->push_back("E2x5RightSeed/ESeed");


    std::vector<std::string> *varseb = new std::vector<std::string>(*varsf);
    std::vector<std::string> *varsee = new std::vector<std::string>(*varsf);

    varseb->push_back("IEtaSeed");
    varseb->push_back("IPhiSeed");
    varseb->push_back("IEtaSeed%5");
    varseb->push_back("IPhiSeed%2");       
    varseb->push_back("(abs(IEtaSeed)<=25)*(IEtaSeed%25) + (abs(IEtaSeed)>25)*((IEtaSeed-25*abs(IEtaSeed)/IEtaSeed)%20)");
    varseb->push_back("IPhiSeed%20"); 
    varseb->push_back("EtaCrySeed");
    varseb->push_back("PhiCrySeed");

    varsee->push_back("PreShowerOverRaw");


    for (int i=0; i<varseb->size(); ++i) {
      cout << "var " << i << " = " << varseb->at(i) << endl;
      traineb_lowPt->AddInputVar(varseb->at(i));
      trainebvar_lowPt->AddInputVar(varseb->at(i));
    }

    for (int i=0; i<varseb->size(); ++i) {
      cout << "var " << i << " = " << varseb->at(i) << endl;
      traineb_highPt->AddInputVar(varseb->at(i));
      trainebvar_highPt->AddInputVar(varseb->at(i));
    }

    for (int i=0; i<varsee->size(); ++i) {
      cout << "var " << i << " = " << varsee->at(i) << endl;
      trainee_lowPt->AddInputVar(varsee->at(i));
      traineevar_lowPt->AddInputVar(varsee->at(i));
    }

    for (int i=0; i<varsee->size(); ++i) {
      cout << "var " << i << " = " << varsee->at(i) << endl;
      trainee_highPt->AddInputVar(varsee->at(i));
      traineevar_highPt->AddInputVar(varsee->at(i));
    }

    ROOT::Cintex::Cintex::Enable();   

    //  TFile *ftmp = new TFile("tmpfile.root","RECREATE");    
    GBRApply gbrapply;

    //Train Barrel Energy Regression (low pT)
    intree->LoadTree(0);  
    const GBRForest *foresteb_lowPt = traineb_lowPt->TrainForest(nTrees);
    delete traineb_lowPt;

    //Apply Barrel Energy Regression (low pT)
    intree->LoadTree(0);  
    gbrapply.ApplyAsFriend(intree, foresteb_lowPt, *varseb, "targeteb_lowPt");

    //Train Barrel Energy Regression (high pT)
    intree->LoadTree(0);  
    const GBRForest *foresteb_highPt = traineb_highPt->TrainForest(nTrees);
    delete traineb_highPt;

    //Apply Barrel Energy Regression (high pT)
    intree->LoadTree(0);  
    gbrapply.ApplyAsFriend(intree, foresteb_highPt, *varseb, "targeteb_highPt");

    //Train Barrel Variance Regression (low pT)
    intree->LoadTree(0);
    const GBRForest *forestebvar_lowPt = trainebvar_lowPt->TrainForest(nTrees);
    delete trainebvar_lowPt;

    //Train Barrel Variance Regression (high pT)
    intree->LoadTree(0);
    const GBRForest *forestebvar_highPt = trainebvar_highPt->TrainForest(nTrees);
    delete trainebvar_highPt;

    //Train Endcap Energy Regression (low pT)
    intree->LoadTree(0);
    const GBRForest *forestee_lowPt = trainee_lowPt->TrainForest(nTrees);
    delete trainee_lowPt;

    //Apply Endcap Energy Regression
    intree->LoadTree(0);
    gbrapply.ApplyAsFriend(intree, forestee_lowPt, *varsee, "targetee_lowPt");

    //Train Endcap Energy Regression (high pT)
    intree->LoadTree(0);
    const GBRForest *forestee_highPt = trainee_highPt->TrainForest(nTrees);
    delete trainee_highPt;

    //Apply Endcap Energy Regression
    intree->LoadTree(0);
    gbrapply.ApplyAsFriend(intree, forestee_highPt, *varsee, "targetee_highPt");

    //Train Endcap Variance Regression (low pT)
    intree->LoadTree(0);  
    const GBRForest *foresteevar_lowPt = traineevar_lowPt->TrainForest(nTrees);
      delete traineevar_lowPt;  

    //Train Endcap Variance Regression (high pT)
      intree->LoadTree(0);  
      const GBRForest *foresteevar_highPt = traineevar_highPt->TrainForest(nTrees);
      delete traineevar_highPt;  

    TString fname;
    fname = outWeightFile;


    TFile *fout = new TFile(fname,"RECREATE");  
    cout << "Saving weights to file " << fname << endl;

    fout->WriteObject(foresteb_lowPt,"EBCorrection_lowPt");
    fout->WriteObject(foresteb_highPt,"EBCorrection_highPt");
    fout->WriteObject(forestebvar_lowPt,"EBUncertainty_lowPt");
    fout->WriteObject(forestebvar_highPt,"EBUncertainty_highPt");
    fout->WriteObject(forestee_lowPt,"EECorrection_lowPt");
    fout->WriteObject(forestee_highPt,"EECorrection_highPt");
    fout->WriteObject(foresteevar_lowPt,"EEUncertainty_lowPt");
    fout->WriteObject(foresteevar_highPt,"EEUncertainty_highPt");

    fout->WriteObject(varseb, "varlisteb");
    fout->WriteObject(varsee, "varlistee");

    //  ftmp->Close();  
    //  fout->Close();
  }  
}