Example #1
0
void regressCovU2(std::string iName) {
  TString  lName       = iName; TFile *lInput = TFile::Open(lName); 
  //TString  lName       = "../Data/s12-zjets_v29b.root"; TFile *lInput = TFile::Open(lName); 
  //TString  lName       = "../Data/r11-dimu_jetv3_v29b.root"; TFile *lInput = TFile::Open(lName); 
  //TString  lName       = "../Data/f11-zjets_jetv4_v11.root"; TFile *lInput = TFile::Open(lName); 
  TTree   *lRegress    = (TTree*)lInput    ->Get("Flat");
  
  GBRTrainer *train = new GBRTrainer;
  train->AddTree(lRegress);
  train->SetTrainingCut("(nbtag == 0)*(pt_z > 0)");//*PtWeight");
  train->SetMinEvents(250);
  train->SetShrinkage(0.3);
  train->SetMinCutSignificance(3.0);  
  
  train->SetTargetVar( "abs(pt_z*sin(phi_z-uphix_mva))*sqrt(TMath::Pi()/2.)/ux_mva");
  
  std::vector<std::string> *lVec = new std::vector<std::string>;
  lVec->push_back( "sumet"      );
  lVec->push_back( "npv"        );
  lVec->push_back( "pfu"        );
  lVec->push_back( "pfuphi"     );
  lVec->push_back( "tksumet"    );
  lVec->push_back( "tku"        );
  lVec->push_back( "tkuphi"     );
  lVec->push_back( "nopusumet"  );
  lVec->push_back( "nopuu"      );
  lVec->push_back( "nopuuphi"   );
  lVec->push_back( "pusumet"    );
  lVec->push_back( "pumet"      );
  lVec->push_back( "pumetphi"   );
  lVec->push_back( "pucsumet"   );
  lVec->push_back( "pucu"       );
  lVec->push_back( "pucuphi"    );
  lVec->push_back( "jetpt1"     );
  lVec->push_back( "jeteta1"    );
  lVec->push_back( "jetphi1"    );
  lVec->push_back( "jetpt2"     );
  lVec->push_back( "jeteta2"    );
  lVec->push_back( "jetphi2"    );
  lVec->push_back( "nalljet"    );
  lVec->push_back( "njet"       );
  lVec->push_back( "uphix_mva"  );
  lVec->push_back( "ux_mva"     );

  for (int i=0; i<int(lVec->size()); ++i) {
     train->AddInputVar(lVec->at(i));
  }
  
  ROOT::Cintex::Cintex::Enable();   
  const GBRForest *forest = train->TrainForest(300);
  
  TFile *fout = new TFile("gbru2cov.root","RECREATE");    
  fout->WriteObject(forest,"CovU2");
  fout->WriteObject(lVec, "varlist");
  fout->Close();
}
Example #2
0
void test()
{

    TFile* fFakeFactorW  = TFile::Open("/afs/cern.ch/user/j/jsauvan/workspace/Projects/Htautau_Run2/Studies/FakeRate/ComputeFakeRates/plots/FakeFactors_Data_HighMT_2D/FakeFactors_Data_HighMT_2D.root");
    TFile* fFakeFactorQCD  = TFile::Open("/afs/cern.ch/user/j/jsauvan/workspace/Projects/Htautau_Run2/Studies/FakeRate/ComputeFakeRates/plots/FakeFactors_Data_QCDSS_2D/FakeFactors_Data_QCDSS_2D.root");
    TFile* fMtCorrection = TFile::Open("/afs/cern.ch/user/j/jsauvan/workspace/Projects/Htautau_Run2/Studies/FakeRate/ComputeMTCorrection/results/mtCorrections.root");
    TFile* fFractions    = TFile::Open("/afs/cern.ch/user/j/jsauvan/workspace/Projects/Htautau_Run2/Studies/FakeRate/ComputeBackgroundFractions/results/backgroundFraction_Iso_Medium_mvis_vs_mt.root");

    TH2F* fakeFactorW   = (TH2F*)fFakeFactorW->Get("FakeFactors_Data_HighMT_2D_Iso_Medium_InvertIso_Medium_tau_pt_vs_decayMode");
    TH2F* fakeFactorQCD = (TH2F*)fFakeFactorQCD->Get("FakeFactors_Data_QCDSS_2D_Iso_Medium_InvertIso_Medium_tau_pt_vs_decayMode");
    TGraph* mtCorrection = (TGraph*)fMtCorrection->Get("mt_correction");
    TH2F* fractionW = (TH2F*)fFractions->Get("h_backgroundFraction_Iso_Medium_mvis_vs_mt_W_Nom");
    TH2F* fractionQCD = (TH2F*)fFractions->Get("h_backgroundFraction_Iso_Medium_mvis_vs_mt_QCD_Nom");
    TH2F* fractionTT = (TH2F*)fFractions->Get("h_backgroundFraction_Iso_Medium_mvis_vs_mt_TT_Nom");
    TH2F* fractionVV = (TH2F*)fFractions->Get("h_backgroundFraction_Iso_Medium_mvis_vs_mt_VV_Nom");
    TH2F* fractionZJ = (TH2F*)fFractions->Get("h_backgroundFraction_Iso_Medium_mvis_vs_mt_ZJ_Nom");


    //wrappers
    WrapperTH2F* wFakeFactorW    = new WrapperTH2F(*fakeFactorW, "FF_W");
    WrapperTH2F* wFakeFactorQCD  = new WrapperTH2F(*fakeFactorQCD, "FF_QCD");
    WrapperTGraph* wMtCorrection = new WrapperTGraph(*mtCorrection, "MT_Corr");
    WrapperTH2F* wFractionW      = new WrapperTH2F(*fractionW, "f_W");
    WrapperTH2F* wFractionQCD    = new WrapperTH2F(*fractionQCD, "f_QCD");
    WrapperTH2F* wFractionTT     = new WrapperTH2F(*fractionTT, "f_TT");
    WrapperTH2F* wFractionVV     = new WrapperTH2F(*fractionVV, "f_VV");
    WrapperTH2F* wFractionZJ     = new WrapperTH2F(*fractionZJ, "f_ZJ");

    // formulas
    TFormula mtCorr("mtCorr", "x[0]*x[1]");
    WrapperTFormula* wFakeFactorWCorr = new WrapperTFormula(mtCorr, "FF_WCorr");

    TFormula combination("combination", "x[0]*x[2]+x[1]*(x[3]+x[4]+x[5]+x[6])");
    WrapperTFormula* wFakeFactorComb = new WrapperTFormula(combination, "FF_Comb");

    // fake factor
    // tau_pt = 0
    // tau_decay = 1
    // mt = 2
    // mvis = 3
    FakeFactor* factor = new FakeFactor();
    factor->addNode(wFakeFactorW, {}, {0,1});
    factor->addNode(wFakeFactorQCD, {}, {0,1});
    factor->addNode(wMtCorrection, {}, {2});
    factor->addNode(wFractionW, {}, {3,2});
    factor->addNode(wFractionQCD, {}, {3,2});
    factor->addNode(wFractionTT, {}, {3,2});
    factor->addNode(wFractionVV, {}, {3,2});
    factor->addNode(wFractionZJ, {}, {3,2});
    factor->addNode(wFakeFactorWCorr, {0,2}, {});
    factor->addNode(wFakeFactorComb, {1,8,4,3,5,6,7}, {});

    TFile* file = TFile::Open("test.root", "recreate");
    file->WriteObject(factor, "ff");
    file->Close();
    std::cout<<"Done\n";

}
void makeclassification() {
  
  Float_t *vars = new Float_t[10];
  
  //initialize TMVA Reader (example here is diphoton mva from higgs->gamma gamma mva analysis)
  TMVA::Reader* tmva = new TMVA::Reader();
  tmva->AddVariable("masserrsmeared/mass",            &vars[0]);
  tmva->AddVariable("masserrsmearedwrongvtx/mass",    &vars[1]);
  tmva->AddVariable("vtxprob",                        &vars[2]);
  tmva->AddVariable("ph1.pt/mass",                    &vars[3]);
  tmva->AddVariable("ph2.pt/mass",                    &vars[4]);
  tmva->AddVariable("ph1.eta",                        &vars[5]);
  tmva->AddVariable("ph2.eta",                        &vars[6]);
  tmva->AddVariable("TMath::Cos(ph1.phi-ph2.phi)"   , &vars[7]);
  tmva->AddVariable("ph1.idmva",                      &vars[8]);
  tmva->AddVariable("ph2.idmva",                      &vars[9]);
  
  tmva->BookMVA("BDTG","/afs/cern.ch/user/b/bendavid/cmspublic/diphotonmvaApr1/HggBambu_SMDipho_Jan16_BDTG.weights.xml");
  //tmva->BookMVA("BDTG","/scratch/bendavid/root/HggBambu_SMDipho_Jan16_BDTG.weights.xml");
  
  TMVA::MethodBDT *bdt = dynamic_cast<TMVA::MethodBDT*>(tmva->FindMVA("BDTG"));

 
  //enable root i/o for objects with reflex dictionaries in standalone root mode
  ROOT::Cintex::Cintex::Enable();   

  
  //open output root file
  TFile *fout = new TFile("gbrtest.root","RECREATE");
  
  //create GBRForest from tmva object
  GBRForest *gbr = new GBRForest(bdt);  
  
  //write to file
  fout->WriteObject(gbr,"gbrtest");

  fout->Close();
  
  
}
Example #4
0
TObjArray* PrepSummaryKMC(const char* sumf, int cls, const char* pref, const char* outF)
{
  if (!gROOT->GetClass("KMCDetector")) gROOT->LoadMacro("KMCDetector.cxx+");
  TFile* fl = TFile::Open(sumf);
  if (!fl) {printf("No file %s\n",sumf); return 0;}
  TObjArray* arrs = (TObjArray*)gDirectory->Get("trSum");
  if (!arrs) {printf("No summary in file %s\n",sumf); return 0;}
  //
  TObjArray* sums =  ProcessSummary(arrs,cls,pref);
  if (!sums) return 0;
  //
  if (outF) {
    TFile* flOut = TFile::Open(outF,"update");
    if (!flOut) {printf("Failed to open output file %s\n",outF);}
    else {
      flOut->WriteObject(sums,sums->GetName(),"kSingleKey");
      flOut->Close();
      delete flOut;
      printf("Stored array %s in %s\n",sums->GetName(), outF);
    }
  }
  //
  return sums;
}
Example #5
0
int main( int argc ,char *argv[] ){
  
  DataObject areas;
  areas.getDataFromFile("resources/static_resources/area_noise_CMSSW_IDS.txt",2);
  
  vector<double> rates;
  vector<double> valuesSilvia;
  map<string, double> areaMap;
  
  for (int i=1; i<= areas.getLenght(); i++){
    double area = atof(areas.getElementFromPropertyContainer(i,2).c_str());
    string roll = areas.getElementFromPropertyContainer(i,1);
    areaMap[roll] = area;
  }
  
  //Create a new Acquisition Registry
  TFile* contFile = TFile::Open("Container20062011.root");
  Acquisition Run2011(contFile);
  
  /*  ifstream json("./jsonFilesMu/Cert_160404-167913_7TeV_PromptReco_Collisions11_JSON_MuonPhys.txt");
      Run2011.LoadJSON(json);*/

    
  DataObject runFilter;
  int nColoumnsFilter = 6;
  int filterCol = 1;
  runFilter.getFastDataFromFile("./resources/Extensions/2011/replotmuondpg/tot_RE+3_2_10_2011.txt",nColoumnsFilter);
  for (int i=1; i<= runFilter.getLenght(); i++){
    valuesSilvia.push_back(atof(runFilter.getElementFromPropertyContainer(i,6).c_str()));
  }
  
  
  Run2011.LoadSelectionByDO(&runFilter, filterCol);
  
  //Run2011.PrintValidRuns();
  
  TFile* f = new TFile("Outputs/OutputFile.root", "RECREATE");
  TH2F* plot = new TH2F("RateVsLumi", "Rate Vs Lumi", 2000, 0, 2000, 100, 0, 10);
  
  plot->SetMarkerStyle(21);
  contFile->Close();
  
  int n=0; 
  int nSkip = 100;

  
  while (Run2011.hasNext()){
    
    n++;
    double NormalizedRate = 0;
    
    Run* currentRun = Run2011.next();
    //check on Runs
    //    if (n <= nSkip) continue;
    
    //otherwise no directories
    contFile = TFile::Open("Container20062011.root");
    currentRun->FillFromContainer(contFile, areaMap);
    contFile->Close();
    
    if (currentRun->getID() > 163869) break; //163869
    if (!Run2011.isValid(currentRun)) continue;
    
    //    cout << "continue on: " << currentRun->getID() << endl;
    double TotRate = 0;
    double TotArea = 0;
    int totAmount = 0;
    int k=0;    
    if (currentRun->isFilled() == true){
      
      const map<string,ExRoll* > barrelMap = currentRun->GetBarrel();
      
      for (map<string,ExRoll* >::const_iterator it = barrelMap.begin(); it != barrelMap.end(); it++){
	
	/*
	//Typical selection for Endcap
	//like RE+3_2_10
       	if (atoi(it->second->getRollID().c_str()) != 10) continue;
	if (it->second->getSector() != 2) continue;
	if (it->second->getWheel_Disk_Number() != 3) continue;
	*/

	
	//Typical selection for Barrel
	//like tot_W+1_RB4_04
	if (it->second->getWheel_Disk_Number() != 2) continue;
	if (it->second->getRollID() != "RB2in") continue;
	if (it->second->getSector() != 4) continue;
//	if ( it->second->getOptionalRollID().compare("F") ) continue;
//	cout << "SEC " << it->second->getSector()  << endl;
	cout << "OPT: " << it->second-> getOptionalRollID() << endl;
	cout << "PASS: "******" "
	     << currentRun->getLumi() << " "
	     <<  "; rate: " << TotRate << "; area: "
	     << TotArea << "; norm: " 
	     << NormalizedRate << endl;

 	plot->Fill(currentRun->getLumi(), NormalizedRate);
	k++;
      }
    }
  }
  
    
  f->WriteObject(plot, "Plot");
  
  return 0;
}
Example #6
0
int main(int argc, char** argv){

  if (argc < 5) {
	cout << "Usage: " << argv[0] << "SubDet RunNumber Wheel RID PartitionName [OutFile]" << endl;
	return 0;
  }
  
  string RollID = string(argv[4]);
  int WheelDiskNo = atoi(argv[3]);
  int runNumber = atoi(argv[2]);
  string subDet = argv[1];
  int partitionNumber = atoi(argv[5]);
  cout << "You're asking partition " << partitionNumber << endl;
  string ContainerName ="ContainerRun2011.root";
  //Load area map
  DataObject areas;
  areas.getDataFromFile("resources/static_resources/area_noise_CMSSW_IDS.txt",2);

  map<string, double> areaMap;

  for (int i=1; i<= areas.getLenght(); i++){
    double area = atof(areas.getElementFromPropertyContainer(i,2).c_str());
    string roll = areas.getElementFromPropertyContainer(i,1);
    areaMap[roll] = area;
  }

  TFile* contFile = TFile::Open(ContainerName.c_str());
  Acquisition Run2011(contFile);

  
  
  //  map<string, TGraph*> RollIDs;
  map<string, TGraph*> RollIDs;
  
  TFile* f;
  
  if (argc >= 7)
    f = new TFile(argv[6], "RECREATE");
  else
    f = new TFile("Outputs/OutputPlotOnPhiVR.root", "RECREATE");
  
  //  TGraph* plot = new TGraph();
  TGraph* plot = new TGraph();
  plot->SetName("RateVsPhi");
  
  //Load Run
  Run* currentRun = Run2011.getRunById(runNumber) ;
  
  contFile = TFile::Open(ContainerName.c_str());
  currentRun->FillFromContainer(contFile, areaMap);
  contFile->Close();
  currentRun->PrintStatistics();
  
  map<string,ExRoll* > Rolls; 
  vector<TGraph*> vPlot;
  int minSector = 1;
  int nSector;
  int emptyStrip = 0;
  int runIndex = -1;  

  
  cout << "Loading Sectors..." << endl;
  
  //Filling Plots
  if (subDet == "Barrel"){
    
    RollIDs["RB1in"] = new TGraph();
    RollIDs["RB2in"] = new TGraph();
    RollIDs["RB1out"] = new TGraph();
    RollIDs["RB2out"] = new TGraph();
    RollIDs["RB3"] = new TGraph();
    RollIDs["RB4"] = new TGraph();
    nSector = 12;
    Rolls = currentRun->GetBarrel();
  }
  
  else if (subDet == "EndCapPlus"){
    
    RollIDs["2"] = new TGraph();
    RollIDs["3"] = new TGraph();
    nSector = 36;
    
    Rolls = currentRun->GetEndCapPlus();
  }
  
  else if (subDet == "EndCapMinus"){
    
    RollIDs["2"] = new TGraph();
    RollIDs["3"] = new TGraph();
    nSector = 36;
    
    Rolls = currentRun->GetEndCapMinus();
  }
  
  //Filling                                                                                                         
  contFile = TFile::Open( ContainerName.c_str() );
  
  cout << "Begin Loop" << endl;  
  for (map<string, TGraph*>::const_iterator itRoll = RollIDs.begin(); itRoll != RollIDs.end(); itRoll++){
    int nPoint = 0;
  bool setSize = false;    
    string name;
    
    if (subDet == "Barrel")
      name = "Barrel_" + itRoll->first;
    else if (subDet == "EndCapPlus" || subDet == "EndCapMinus")
      name = "EndCap_" + itRoll->first;
    
    itRoll->second->SetName(name.c_str());


 
  for (int iSector = minSector; iSector <= nSector; iSector++){
    
    double TotRate = 0;
    double TotArea = 0;
    
    
    for (map<string,ExRoll* >::const_iterator it = Rolls.begin(); it != Rolls.end(); it++){

      string th1path = it->second->getTH1Path();
      
      if (subDet == "Barrel"){
	string opt1 = "F";
	string opt2 = "+F";
	string opt3 = "-F";

	if (it->second->getSector() != iSector) continue;     
	
	if (it->second->getRollID() != itRoll->first) continue;      
	

	if (WheelDiskNo != -9)
	  if (it->second->getWheel_Disk_Number() != WheelDiskNo) continue;

	if (it->second->getOptionalRollID().find(opt1) == string::npos && it->second->getOptionalRollID().find(opt2) == string::npos) {
		 continue;
	}	
	if (it->second->getOptionalRollID().find(opt3) != string::npos){
		continue;
	}	
	
	
      }
      
      else if (subDet == "EndCapPlus" || subDet == "EndCapMinus"){
	
	if (atoi(it->second->getRollID().c_str()) != iSector) continue;
        
	if (it->second->getSector() != atoi(itRoll->first.c_str())) continue;
	
	if (WheelDiskNo != -9)
	  if (it->second->getWheel_Disk_Number() != WheelDiskNo) continue;
      }
      int nClones = it->second->getClones();
      emptyStrip += it->second->getEmptyStrip();

      TH1F* histo = (TH1F*)(contFile->Get(th1path.c_str()));

      int cNumber = partitionNumber;
      if (partitionNumber > nClones-1) continue;
      cout << "This roll has " << nClones << endl;
      double TotRate = 0;
      double TotArea = 0;
      int cEffectiveNumber =  cNumber + 1;
      
      NoiseAnalyzer nAnalyzer;
      TH1F* cHisto = it->second->getRateHistoForClone(histo, cEffectiveNumber);
      TotRate = nAnalyzer.HealClone(it->second, cHisto, cEffectiveNumber);
      double cloneArea = it->second->getCloneArea(cNumber);
      TotArea += cloneArea;
     
      double NormalizedRate = (TotRate / TotArea);
      itRoll->second->SetPoint(nPoint, (iSector-1)*6.28/(double)nSector, NormalizedRate/2);
      cout << "\t\tPOINT: " << nPoint << " " << (iSector-1)*6.28/(double)nSector << " " << NormalizedRate/2 << endl;
      nPoint++;
    }
  }  
  }


  for (map<string, TGraph*>::const_iterator it = RollIDs.begin(); it != RollIDs.end(); it++)
    f->WriteObject( it->second, it->second->GetName() );
  
  f->Close();
  return 0;
}
Example #7
0
void eregmerge(bool doele) {
  
  TString dirname = "/afs/cern.ch/user/b/bendavid/CMSSWhgg/CMSSW_5_3_11_patch5/src/HiggsAnalysis/GBRLikelihoodEGTools/data/"; 
  gSystem->mkdir(dirname,true);
  gSystem->cd(dirname);    
  
  TString fnameeb;
  TString fnameee;
  if (doele) { 
    fnameeb = "wereg_ele_eb.root";
    fnameee = "wereg_ele_ee.root";
  }
  else if (!doele) {
    fnameeb = "wereg_ph_eb.root";
    fnameee = "wereg_ph_ee.root";
  }    
    
   
  TString infileeb = TString::Format("/afs/cern.ch/work/b/bendavid/bare/eregAug10RCalphafix/%s",fnameeb.Data());
  TString infileee = TString::Format("/afs/cern.ch/work/b/bendavid/bare/eregAug10RCalphafix/%s",fnameee.Data());
  
  TFile *fwseb = TFile::Open(infileeb); 
  TFile *fwsee = TFile::Open(infileee); 
  
  RooWorkspace *wseb = (RooWorkspace*)fwseb->Get("wereg");
  RooWorkspace *wsee = (RooWorkspace*)fwsee->Get("wereg");
  
  RooAbsPdf *sigpdfeborig = wseb->pdf("sigpdf");
  RooAbsPdf *sigpdfeeorig = wsee->pdf("sigpdf");
  
  RooAbsPdf *sigpdfeb = static_cast<RooAbsPdf*>(cloneRecursiveRename(sigpdfeborig,"EB"));
  RooAbsPdf *sigpdfee = static_cast<RooAbsPdf*>(cloneRecursiveRename(sigpdfeeorig,"EE"));
    
  RooWorkspace *wsout = new RooWorkspace("EGRegressionWorkspace");
  wsout->import(*sigpdfeb);
  wsout->import(*sigpdfee);
  
  TString outname;
  if (doele) outname = "regweights_v4_ele.root";
  else outname = "regweights_v4_ph.root";
  
  wsout->writeToFile(outname);
  
  RooArgList pdfeblist;
  RooArgSet *pdfebcomps = sigpdfeb->getComponents();
  RooArgSet *pdfebvars = sigpdfeb->getVariables();
  pdfeblist.add(*pdfebcomps);
  pdfeblist.add(*pdfebvars);
  delete pdfebcomps;
  delete pdfebvars;
  
  
  RooArgList pdfeelist;
  RooArgSet *pdfeecomps = sigpdfee->getComponents();
  RooArgSet *pdfeevars = sigpdfee->getVariables();
  pdfeelist.add(*pdfeecomps);
  pdfeelist.add(*pdfeevars);
  delete pdfeecomps;
  delete pdfeevars;  
  
  
//   RooArgList components(ws->components());
//   for (int iarg=0; iarg<components.getSize(); ++iarg) {
//     components.at(iarg)->SetName(TString::Format("%s_1",components.at(iarg)->GetName()));
//   }
  
  RooGBRFunction *funceb = static_cast<RooGBRFunction*>(pdfeblist.find("func_EB"));
  RooGBRFunction *funcee = static_cast<RooGBRFunction*>(pdfeelist.find("func_EE"));
  
//   funceb->Vars().Print("V");
//   funcee->Vars().Print("V");

  for (int ivar=0; ivar<funceb->Vars().getSize(); ++ivar) {
    printf("%i: %s, %s\n",ivar,funceb->Vars().at(ivar)->GetName(),funceb->Vars().at(ivar)->GetTitle());
  }
  
  for (int ivar=0; ivar<funcee->Vars().getSize(); ++ivar) {
    printf("%i: %s, %s\n",ivar,funcee->Vars().at(ivar)->GetName(),funcee->Vars().at(ivar)->GetTitle());
  }
  
  TString outnameforest;
  if (doele) outnameforest = "regweights_v4_forest_ele.root";
  else outnameforest = "regweights_v4_forest_ph.root";  
  
  TFile *fforest = new TFile(outnameforest,"RECREATE");
  fforest->WriteObject(funceb->Forest(),"EGRegressionForest_EB");
  fforest->WriteObject(funcee->Forest(),"EGRegressionForest_EE");
  fforest->Close();
  
}
Example #8
0
void compClusHitsMod2(int nev=-1)
{
  
  const int kSplit=0x1<<22;
  const int kSplCheck=0x1<<23;
  //
  gSystem->Load("libITSUpgradeBase");
  gSystem->Load("libITSUpgradeSim");
  gSystem->Load("libITSUpgradeRec");
  gROOT->SetStyle("Plain");

  AliCDBManager* man = AliCDBManager::Instance();
  man->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  man->SetSpecificStorage("GRP/GRP/Data",
        Form("local://%s",gSystem->pwd()));
  man->SetSpecificStorage("ITS/Align/Data",
        Form("local://%s",gSystem->pwd()));
  man->SetSpecificStorage("ITS/Calib/RecoParam",
        Form("local://%s",gSystem->pwd()));
  man->SetRun(0);

  TH1F* hL0A = new TH1F("hL0A", "Layer 0, polar angle", 20, 0, TMath::PiOver2());
  hL0A->SetDirectory(0);
  hL0A->GetXaxis()->SetTitle("#alpha");
  TH1F* hL0B = new TH1F("hL0B", "Layer 0, azimuthal angle", 20, 0, TMath::PiOver2());
  hL0B->SetDirectory(0);
  hL0B->GetXaxis()->SetTitle("#beta");

  TH1F* hL1A = new TH1F("hL1A", "Layer 1, polar angle", 20, 0, TMath::PiOver2());
  hL1A->SetDirectory(0);
  hL1A->GetXaxis()->SetTitle("#alpha");
  TH1F* hL1B = new TH1F("hL1B", "Layer 1, azimuthal angle", 20, 0, TMath::PiOver2());
  hL1B->SetDirectory(0);
  hL1B->GetXaxis()->SetTitle("#beta");

  TH1F* hL2A = new TH1F("hL2A", "Layer 2, polar angle", 20, 0, TMath::PiOver2());
  hL2A->SetDirectory(0);
  hL2A->GetXaxis()->SetTitle("#alpha");
  TH1F* hL2B = new TH1F("hL2B", "Layer 2, azimuthal angle", 20, 0, TMath::PiOver2());
  hL2B->SetDirectory(0);
  hL2B->GetXaxis()->SetTitle("#beta");

  TH1F* hL3A = new TH1F("hL3A", "Layer 3, polar angle", 20, 0, TMath::PiOver2());
  hL3A->SetDirectory(0);
  hL3A->GetXaxis()->SetTitle("#alpha");
  TH1F* hL3B = new TH1F("hL3B", "Layer 3, azimuthal angle", 20, 0, TMath::PiOver2());
  hL3B->SetDirectory(0);
  hL3B->GetXaxis()->SetTitle("#beta");

  TH1F* hL4A = new TH1F("hL4A", "Layer 4, polar angle", 20, 0, TMath::PiOver2());
  hL4A->SetDirectory(0);
  hL4A->GetXaxis()->SetTitle("#alpha");
  TH1F* hL4B = new TH1F("hL4B", "Layer 4, azimuthal angle", 20, 0, TMath::PiOver2());
  hL4B->SetDirectory(0);
  hL4B->GetXaxis()->SetTitle("#beta");

  TH1F* hL5A = new TH1F("hL5A", "Layer 5, polar angle", 20, 0, TMath::PiOver2());
  hL5A->SetDirectory(0);
  hL5A->GetXaxis()->SetTitle("#alpha");
  TH1F* hL5B = new TH1F("hL5B", "Layer 5, azimuthal angle", 20, 0, TMath::PiOver2());
  hL5B->SetDirectory(0);
  hL5B->GetXaxis()->SetTitle("#beta");

  TH1F* hL6A = new TH1F("hL6A", "Layer 6, polar angle", 20, 0, TMath::PiOver2());
  hL6A->SetDirectory(0);
  hL6A->GetXaxis()->SetTitle("#alpha");
  TH1F* hL6B = new TH1F("hL6B", "Layer 6, azimuthal angle", 20, 0, TMath::PiOver2());
  hL6B->SetDirectory(0);
  hL6B->GetXaxis()->SetTitle("#beta");

  gAlice=NULL;
  AliRunLoader* runLoader = AliRunLoader::Open("galice.root");
  runLoader->LoadgAlice();

  gAlice = runLoader->GetAliRun();

  runLoader->LoadHeader();
  runLoader->LoadKinematics();
  runLoader->LoadRecPoints();
  runLoader->LoadSDigits();
  runLoader->LoadHits();

  AliLoader *dl = runLoader->GetDetectorLoader("ITS");

  AliGeomManager::LoadGeometry("geometry.root");
  TObjArray algITS;
  AliGeomManager::LoadAlignObjsFromCDBSingleDet("ITS",algITS);
  AliGeomManager::ApplyAlignObjsToGeom(algITS);
  //
  AliITSUGeomTGeo* gm = new AliITSUGeomTGeo(kTRUE);
  AliITSMFTClusterPix::SetGeom(gm);
  //
  AliITSURecoDet *its = new AliITSURecoDet(gm, "ITSinterface");
  its->CreateClusterArrays();
  //
  Double_t xg1,yg1,zg1=0.,xg0,yg0,zg0=0.,tg0;
  Double_t xExit,yExit,zExit,xEnt,yEnt,zEnt,tof1;

  //
  TTree *cluTree = 0x0;
  TTree *hitTree = 0x0;
  TClonesArray *hitList=new TClonesArray("AliITSMFTHit");
  //
  Float_t xyzClGloF[3];
  Double_t xyzClGlo[3],xyzClTr[3];
  Int_t labels[3];
  int nLab = 0;
  int nlr=its->GetNLayersActive();
  int ntotev = (Int_t)runLoader->GetNumberOfEvents();

  printf("N Events : %i \n",ntotev);
  if (nev>0) ntotev = TMath::Min(nev,ntotev);
  //
  
  // output tree
  TFile* flOut = TFile::Open("clInfo.root","recreate");
  TTree* trOut = new TTree("clitsu","clitsu");
  clSumm cSum;
  trOut->Branch("evID", &cSum.evID ,"evID/I");
  trOut->Branch("volID",&cSum.volID,"volID/I");
  trOut->Branch("lrID", &cSum.lrID ,"lrID/I");  
  trOut->Branch("clID", &cSum.clID ,"clID/I");  
  trOut->Branch("nPix", &cSum.nPix ,"nPix/I");
  trOut->Branch("nX"  , &cSum.nX   ,"nX/I");
  trOut->Branch("nZ"  , &cSum.nZ   ,"nZ/I");
  trOut->Branch("q"   , &cSum.q    ,"q/I");
  trOut->Branch("pt"  , &cSum.pt   ,"pt/F");  
  trOut->Branch("eta"  ,&cSum.eta  ,"eta/F");  
  trOut->Branch("phi"  , &cSum.phi  ,"phi/F");  
  trOut->Branch("xyz",   cSum.xyz,  "xyz[3]/F");  
  trOut->Branch("dX"  , &cSum.dX   ,"dX/F");
  trOut->Branch("dY"  , &cSum.dY   ,"dY/F");
  trOut->Branch("dZ"  , &cSum.dZ   ,"dZ/F");  
  trOut->Branch("split",&cSum.split,"split/O");
  trOut->Branch("prim", &cSum.prim, "prim/O");
  trOut->Branch("pdg",  &cSum.pdg,  "pdg/I");
  trOut->Branch("ntr",  &cSum.ntr,  "ntr/I");
  trOut->Branch("alpha", &cSum.alpha, "alpha/F");
  trOut->Branch("beta", &cSum.beta, "beta/F");
  trOut->Branch("nRowPatt", &cSum.nRowPatt, "nRowPatt/I");
  trOut->Branch("nColPatt", &cSum.nColPatt, "nColPatt/I");

  TopDatabase DB;
  
  for (Int_t iEvent = 0; iEvent < ntotev; iEvent++) {
    printf("\n Event %i \n",iEvent);
    runLoader->GetEvent(iEvent);
    AliStack *stack = runLoader->Stack();
    cluTree=dl->TreeR();
    hitTree=dl->TreeH();
    hitTree->SetBranchAddress("ITS",&hitList);
    // 
    // read clusters
    for (int ilr=nlr;ilr--;) {
      TBranch* br = cluTree->GetBranch(Form("ITSRecPoints%d",ilr));
      if (!br) {printf("Did not find cluster branch for lr %d\n",ilr); exit(1);}
      br->SetAddress(its->GetLayerActive(ilr)->GetClustersAddress());
    }
    cluTree->GetEntry(0);
    its->ProcessClusters();
    //
    // read hits
    for(Int_t iEnt=0;iEnt<hitTree->GetEntries();iEnt++){//entries loop of the hits
      hitTree->GetEntry(iEnt);
      int nh = hitList->GetEntries();
      for(Int_t iHit=0; iHit<nh;iHit++){
        AliITSMFTHit *pHit = (AliITSMFTHit*)hitList->At(iHit);
        int mcID = pHit->GetTrack();
	//printf("MCid: %d %d %d Ch %d\n",iEnt,iHit, mcID, pHit->GetChip());
        TClonesArray* harr = arrMCTracks.GetEntriesFast()>mcID ? (TClonesArray*)arrMCTracks.At(mcID) : 0;
        if (!harr) {
          harr = new TClonesArray("AliITSMFTHit"); // 1st encounter of the MC track
          arrMCTracks.AddAtAndExpand(harr,mcID);
        }
        //
        new ( (*harr)[harr->GetEntriesFast()] ) AliITSMFTHit(*pHit);
      }
    }
    //    return;
    //
    // compare clusters and hits
    //
    printf(" tree entries: %lld\n",cluTree->GetEntries());
    //
    for (int ilr=0;ilr<nlr;ilr++) {
      AliITSURecoLayer* lr = its->GetLayerActive(ilr);
      TClonesArray* clr = lr->GetClusters();
      int nClu = clr->GetEntries();
      //printf("Layer %d : %d clusters\n",ilr,nClu);
      //
      for (int icl=0;icl<nClu;icl++) {
        AliITSMFTClusterPix *cl = (AliITSMFTClusterPix*)clr->At(icl);
        int modID = cl->GetVolumeId();

        //------------ check if this is a split cluster
        int sInL = modID - gm->GetFirstChipIndex(ilr);
        if (!cl->TestBit(kSplCheck)) {
          cl->SetBit(kSplCheck);
          // check if there is no other cluster with same label on this module
          AliITSURecoSens* sens = lr->GetSensor(sInL);
          int nclSn = sens->GetNClusters();
          int offs = sens->GetFirstClusterId();
          //  printf("To check for %d (mod:%d) N=%d from %d\n",icl,modID,nclSn,offs);
          for (int ics=0;ics<nclSn;ics++) {
            AliITSMFTClusterPix* clusT = (AliITSMFTClusterPix*)lr->GetCluster(offs+ics); // access to clusters
            if (clusT==cl) continue;
            for (int ilb0=0;ilb0<3;ilb0++) {
              int lb0 = cl->GetLabel(ilb0); if (lb0<=-1) break;
              for (int ilb1=0;ilb1<3;ilb1++) {
                int lb1 = clusT->GetLabel(ilb1); if (lb1<=-1) break;
                if (lb1==lb0) {
                  cl->SetBit(kSplit);
                  clusT->SetBit(kSplit);
                  /*
                  printf("Discard clusters of module %d:\n",modID);
                  cl->Print();
                  clusT->Print();
                  */
                  break;
                }
              }
            }
          }
        }
        //------------
        const AliITSMFTSegmentationPix* segm = gm->GetSegmentation(ilr);
        //
        cl->GetGlobalXYZ(xyzClGloF);
        int clsize = cl->GetNPix();
        for (int i=3;i--;) xyzClGlo[i] = xyzClGloF[i];
        const TGeoHMatrix* mat = gm->GetMatrixSens(modID);
        if (!mat) {printf("failed to get matrix for module %d\n",cl->GetVolumeId());}
        mat->MasterToLocal(xyzClGlo,xyzClTr);
        //
        int col,row;
        segm->LocalToDet(xyzClTr[0],xyzClTr[2],row,col); // effective col/row
        nLab = 0;
        for (int il=0;il<3;il++) {
          if (cl->GetLabel(il)>=0) labels[nLab++] = cl->GetLabel(il);
          else break;
        }
        // find hit info
        for (int il=0;il<nLab;il++) {
          TClonesArray* htArr = (TClonesArray*)arrMCTracks.At(labels[il]);
	  //printf("check %d/%d LB %d  %p\n",il,nLab,labels[il],htArr);
	  if (!htArr) {printf("did not find MChits for label %d ",labels[il]); cl->Print(); continue;}
          //
          int nh = htArr->GetEntriesFast();
          AliITSMFTHit *pHit=0;
          for (int ih=nh;ih--;) {
            AliITSMFTHit* tHit = (AliITSMFTHit*)htArr->At(ih);
            if (tHit->GetChip()!=modID) continue;
            pHit = tHit;
            break;
          }
          if (!pHit) {
            printf("did not find MChit for label %d on module %d ",il,modID); 
            cl->Print(); 
            htArr->Print();
            continue;
          }
          //
          pHit->GetPositionG(xg1,yg1,zg1);
          pHit->GetPositionG0(xg0,yg0,zg0,tg0);
          //
          double txyzH[3],gxyzH[3] = { (xg1+xg0)/2, (yg1+yg0)/2, (zg1+zg0)/2 };
          mat->MasterToLocal(gxyzH,txyzH);

          double rcl = TMath::Sqrt(xyzClTr[0]*xyzClTr[0]+xyzClTr[1]*xyzClTr[1]);
          double rht = TMath::Sqrt(txyzH[0]*txyzH[0]+txyzH[1]*txyzH[1]);
          //
          //Angles determination

          pHit->GetPositionL(xExit,yExit,zExit,gm);
          pHit->GetPositionL0(xEnt,yEnt,zEnt,tof1,gm);

          Double_t dirHit[3]={(xExit-xEnt),(yExit-yEnt),(zExit-zEnt)};

          /*double PG[3] = {(double)pHit->GetPXG(), (double)pHit->GetPYG(), (double)pHit->GetPZG()}; //Momentum at hit-point in Global Frame
          double PL[3];
          if (TMath::Abs(PG[0])<10e-7 && TMath::Abs(PG[1])<10e-7) {
            pHit->Dump();
            int lb = pHit->GetTrack();
            stack->Particle(lb)->Print();
            continue;
          }
          mat->MasterToLocalVect(PG,PL); //Momentum in local Frame
          //printf(">> %e %e   %e %e   %e %e\n",PG[0],PL[0],PG[1],PL[1],PG[2],PL[2]);*/

          Double_t alpha1 = TMath::ACos(TMath::Abs(dirHit[1])/TMath::Sqrt(dirHit[0]*dirHit[0]+dirHit[1]*dirHit[1]+dirHit[2]*dirHit[2])); //Polar Angle
          Float_t alpha2 = (Float_t) alpha1; //convert to float
          cSum.alpha = alpha2;

          Double_t beta1;
          beta1 = TMath::ATan2(dirHit[0],dirHit[2]); //Azimuthal angle, values from -Pi to Pi
          Float_t beta2 = (Float_t) beta1;
          cSum.beta = beta2;

	  if(ilr==0){
	    hL0A->Fill(alpha2);
	    hL0B->Fill(beta2);
	  }
	  
	  if(ilr==1){
	    hL1A->Fill(alpha2);
	    hL1B->Fill(beta2);
	  }

	  if(ilr==2){
	    hL2A->Fill(alpha2);
	    hL2B->Fill(beta2);
	  }

	  if(ilr==3){
	    hL3A->Fill(alpha2);
	    hL3B->Fill(beta2);
	  }

	  if(ilr==4){
	    hL4A->Fill(alpha2);
	    hL4B->Fill(beta2);
	  }

	  if(ilr==5){
	    hL5A->Fill(alpha2);
	    hL5B->Fill(beta2);
	  }

	  if(ilr==6){
	    hL6A->Fill(alpha2);
	    hL6B->Fill(beta2);
	  }
          
          GetHistoClSize(clsize,kDR,&histoArr)->Fill((rht-rcl)*1e4);
          if (cl->TestBit(kSplit)) {
            if (col%2) GetHistoClSize(clsize,kDTXoddSPL,&histoArr)->Fill((txyzH[0]-xyzClTr[0])*1e4);
            else       GetHistoClSize(clsize,kDTXevenSPL,&histoArr)->Fill((txyzH[0]-xyzClTr[0])*1e4);
            GetHistoClSize(clsize,kDTZSPL,&histoArr)->Fill((txyzH[2]-xyzClTr[2])*1e4);
            GetHistoClSize(0,kNPixSPL,&histoArr)->Fill(clsize);
          }
          if (col%2) GetHistoClSize(clsize,kDTXodd,&histoArr)->Fill((txyzH[0]-xyzClTr[0])*1e4);
          else       GetHistoClSize(clsize,kDTXeven,&histoArr)->Fill((txyzH[0]-xyzClTr[0])*1e4);
          GetHistoClSize(clsize,kDTZ,&histoArr)->Fill((txyzH[2]-xyzClTr[2])*1e4);
          GetHistoClSize(0,kNPixAll,&histoArr)->Fill(clsize);
          //
          cSum.evID = iEvent;
          cSum.volID = cl->GetVolumeId();
          cSum.lrID = ilr;
          cSum.clID = icl;
          cSum.nPix = cl->GetNPix();
          cSum.nX   = cl->GetNx();
          cSum.nZ   = cl->GetNz();
          cSum.q    = cl->GetQ();
          cSum.split = cl->TestBit(kSplit);
          cSum.dX = (txyzH[0]-xyzClTr[0])*1e4;
          cSum.dY = (txyzH[1]-xyzClTr[1])*1e4;
          cSum.dZ = (txyzH[2]-xyzClTr[2])*1e4;
          cSum.nRowPatt = cl-> GetPatternRowSpan();
          cSum.nColPatt = cl-> GetPatternColSpan();
	  DB.AccountTopology(*cl, cSum.dX, cSum.dZ, cSum.alpha, cSum.beta);
          
          GetHistoClSize(clsize,kDR,&histoArr)->Fill((rht-rcl)*1e4);
          if (cl->TestBit(kSplit)) {
            if (col%2) GetHistoClSize(clsize,kDTXoddSPL,&histoArr)->Fill((txyzH[0]-xyzClTr[0])*1e4);
            else       GetHistoClSize(clsize,kDTXevenSPL,&histoArr)->Fill((txyzH[0]-xyzClTr[0])*1e4);
            GetHistoClSize(clsize,kDTZSPL,&histoArr)->Fill((txyzH[2]-xyzClTr[2])*1e4);
            GetHistoClSize(0,kNPixSPL,&histoArr)->Fill(clsize);
          }
          if (col%2) GetHistoClSize(clsize,kDTXodd,&histoArr)->Fill((txyzH[0]-xyzClTr[0])*1e4);
          else       GetHistoClSize(clsize,kDTXeven,&histoArr)->Fill((txyzH[0]-xyzClTr[0])*1e4);
          GetHistoClSize(clsize,kDTZ,&histoArr)->Fill((txyzH[2]-xyzClTr[2])*1e4);
          GetHistoClSize(0,kNPixAll,&histoArr)->Fill(clsize);
          //
          cSum.evID = iEvent;
          cSum.volID = cl->GetVolumeId();
          cSum.lrID = ilr;
          cSum.clID = icl;
          cSum.nPix = cl->GetNPix();
          cSum.nX   = cl->GetNx();
          cSum.nZ   = cl->GetNz();
          cSum.q    = cl->GetQ();
          cSum.split = cl->TestBit(kSplit);
          cSum.dX = (txyzH[0]-xyzClTr[0])*1e4;
          cSum.dY = (txyzH[1]-xyzClTr[1])*1e4;
          cSum.dZ = (txyzH[2]-xyzClTr[2])*1e4;
          cSum.nRowPatt = cl-> GetPatternRowSpan();
          cSum.nColPatt = cl-> GetPatternColSpan();
 
                    
          int label = cl->GetLabel(0);
          TParticle* part = 0;
          if (label>=0 && (part=stack->Particle(label)) ) {
            cSum.pdg = part->GetPdgCode();
            cSum.eta = part->Eta();
            cSum.pt  = part->Pt();
            cSum.phi = part->Phi();
            cSum.prim = stack->IsPhysicalPrimary(label);
          } 
          cSum.ntr = 0;
          for (int ilb=0;ilb<3;ilb++) if (cl->GetLabel(ilb)>=0) cSum.ntr++;
          for (int i=0;i<3;i++) cSum.xyz[i] = xyzClGloF[i];
          //
          trOut->Fill();
          /*
          if (clsize==5) {
            printf("\nL%d(%c) Mod%d, Cl:%d | %+5.1f %+5.1f (%d/%d)|H:%e %e %e | C:%e %e %e\n",ilr,cl->TestBit(kSplit) ? 'S':'N',
             modID,icl,(txyzH[0]-xyzClTr[0])*1e4,(txyzH[2]-xyzClTr[2])*1e4, row,col,
             gxyzH[0],gxyzH[1],gxyzH[2],xyzClGlo[0],xyzClGlo[1],xyzClGlo[2]);
            cl->Print();
            pHit->Print();
            //
            double a0,b0,c0,a1,b1,c1,e0;
            pHit->GetPositionL0(a0,b0,c0,e0);
            pHit->GetPositionL(a1,b1,c1);
            float cloc[3];
            cl->GetLocalXYZ(cloc);
            printf("LocH: %e %e %e | %e %e %e\n",a0,b0,c0,a1,b1,c1);
            printf("LocC: %e %e %e | %e %e %e\n",cloc[0],cloc[1],cloc[2],xyzClTr[0],xyzClTr[1],xyzClTr[2]);
          }
          */
          //
        }
      }
    }
    
    //    layerClus.Clear();
    //
    arrMCTracks.Delete();
  }//event loop
  //
  DB.EndAndSort();
  DB.SetThresholdCumulative(0.95);
  cout << "Over threshold: : "<< DB.GetOverThr()<<endl;
  DB.Grouping(10,10);
  DB.PrintDB("Database1.txt"); 
  flOut->cd();
  trOut->Write();
  delete trOut;
  flOut->Close();
  flOut->Delete();
  DrawReport("clinfo.ps",&histoArr);
  TFile* flDB = TFile::Open("TopologyDatabase.root", "recreate");
  flDB->WriteObject(&DB,"DB","kSingleKey");
  flDB->Close();
  delete flDB;

  TCanvas* cnv123 = new TCanvas("cnv123","cnv123");
  cnv123->Divide(1,2);
  cnv123->Print("anglesdistr.pdf[");
  cnv123->cd(1);
  hL0A->Draw();
  cnv123->cd(2);
  hL0B->Draw();
  cnv123->Print("anglesdistr.pdf");
  cnv123->cd(1);
  hL1A->Draw();
  cnv123->cd(2);
  hL1B->Draw();
  cnv123->Print("anglesdistr.pdf");
  cnv123->cd(1);
  hL2A->Draw();
  cnv123->cd(2);
  hL2B->Draw();
  cnv123->Print("anglesdistr.pdf");
  cnv123->cd(1);
  hL3A->Draw();
  cnv123->cd(2);
  hL3B->Draw();
  cnv123->Print("anglesdistr.pdf");
  cnv123->cd(1);
  hL4A->Draw();
  cnv123->cd(2);
  hL4B->Draw();
  cnv123->Print("anglesdistr.pdf");
  cnv123->cd(1);
  hL5A->Draw();
  cnv123->cd(2);
  hL5B->Draw();
  cnv123->Print("anglesdistr.pdf");
  cnv123->cd(1);
  hL6A->Draw();
  cnv123->cd(2);
  hL6B->Draw();
  cnv123->Print("anglesdistr.pdf");
  cnv123->Print("anglesdistr.pdf]");
  //
}
Example #9
0
void MakeSnapshot(Int_t run, const char* defStorage, TMap* specStorages, const char* snapshotFileName)
{
    AliCDBManager *cdb = AliCDBManager::Instance();
    cdb->SetDefaultStorage(defStorage);
    cdb->SetRun(run);

    TIter iter(specStorages->GetTable());
    TPair *pair = 0;
    while((pair = dynamic_cast<TPair*> (iter.Next()))){
	TObjString* caltype = dynamic_cast<TObjString*> (pair->Key());
	TObjString* specstor= dynamic_cast<TObjString*> (pair->Value());
	if (caltype && specstor)
	    //TString calType = caltype->GetString();
	    //TString specStor = specstor->GetString();
	    //cdb->SetSpecificStorage(calType.Data(),specStor.Data());
	    cdb->SetSpecificStorage(caltype->GetString().Data(),specstor->GetString().Data());
	else
	    //AliFatal("Error reading info for specific storage")
	    Printf("Error reading info for specific storage");
    }

    // ********************************** GRP ******************************************
    cdb->Get("GRP/CTP/Config");
    cdb->Get("GRP/Calib/LHCClockPhase");
    cdb->Get("GRP/GRP/Data");
    cdb->Get("GRP/Align/Data");
    cdb->Get("GRP/Calib/MeanVertexSPD");
    cdb->Get("GRP/Calib/MeanVertex");
    cdb->Get("GRP/Calib/MeanVertexTPC");
    cdb->Get("GRP/Calib/CosmicTriggers");
    cdb->Get("GRP/CTP/Scalers");
    cdb->Get("GRP/CTP/CTPtiming");
    cdb->Get("GRP/CTP/TimeAlign");
    cdb->Get("GRP/GRP/LHCData");
    cdb->Get("GRP/Calib/RecoParam");

    // ********************************** ALL ******************************************
    TString detStr = ("ITS TPC TRD TOF PHOS HMPID EMCAL MUON ZDC PMD T0 VZERO");
    //TString detStr = ("ITS MUON TPC");
    TObjArray *arr = detStr.Tokenize(' ');
    for (Int_t iDet=0; iDet<arr->GetEntries(); iDet++) {
	TObjString *detOStr = dynamic_cast<TObjString*>(arr->At(iDet));
	AliCDBManager::Instance()->GetAll(Form("%s/Calib/*",detOStr->GetString().Data()));
	AliCDBManager::Instance()->Get(Form("%s/Align/Data",detOStr->GetString().Data()));
    }

    // ******************************** TRIGGER ****************************************
    // Temporary fix - one has to define the correct policy in order
    // to load the trigger OCDB entries only for the detectors that
    // in the trigger or that are needed in order to put correct
    // information in ESD
    AliCDBManager::Instance()->GetAll("TRIGGER/*/*");

    // ********************************** HLT ******************************************
    // cdb->Get("HLT/ConfigHLT/esdLayout");
    // cdb->Get("HLT/Calib/StreamerInfo");

    TMap* entriesMap = const_cast<TMap*>(cdb->GetEntryCache());
    Printf("\nentriesMap has %d entries!\n", entriesMap->GetEntries());

    TList* entriesList = const_cast<TList*>(cdb->GetRetrievedIds());
    Printf("\nentriesList has %d entries!\n", entriesList->GetEntries());

    //TString filename(TString::Format("CDBsnapshot_Run%d.root",run));
    TString filename(snapshotFileName);
    TFile *f = new TFile(filename.Data(),"recreate");
    f->cd();
    f->WriteObject(entriesMap,"entriesMap");
    f->WriteObject(entriesList,"entriesList");
    f->Close();
    entriesMap->SetOwnerKeyValue(kFALSE,kFALSE);
    entriesList->SetOwner(kFALSE);
}
Example #10
0
void plotRatio() {


  // set proper style for plots
  gROOT->ProcessLine(".L mystyle.C");
  setTDRStyle();
  tdrStyle->SetErrorX(0.5);
  tdrStyle->SetPadLeftMargin(0.18);
  tdrStyle->SetPadRightMargin(0.10);
  tdrStyle->SetPadBottomMargin(0.16);
  tdrStyle->SetLegendBorderSize(0);
  tdrStyle->SetTitleYOffset(1.5);


  TFile* f1 = new TFile("histograms_7TeV.root","read");
  TFile* f2 = new TFile("histograms_10TeV.root","read");
  gROOT->cd();
  TH1D ratioHist[nHists];
  for (int i=0; i<nHists; i++) {
    TH1D* numHist = (TH1D* ) f1->Get( histNames[i] );
    TH1D* denHist = (TH1D* ) f2->Get( histNames[i] );
    ratioHist[i] = (TH1D*) numHist->Clone(histNames[i]);
    ratioHist[i]->Divide( denHist );
    ratioHist[i]->GetYaxis()->SetTitle("Events @ 7 TeV / @ 10 TeV");
  }

  TFile* file = new TFile( "histograms_ratio.root", "RECREATE" );
  for (int i=0; i<nHists; i++) {
    file->WriteObject(ratioHist[i], histNames[i]);
  }

  TH1D* ZPt_Gen = (TH1D* ) file->Get("ZPt_Gen");
  TH1D* ZPt_Reco = (TH1D* ) file->Get("ZPt_Reco");
  TH1D* GenJetPt = (TH1D* ) file->Get("GenJetPt");
  TH1D* CaloJetPt = (TH1D* ) file->Get("CaloJetPt");
  TH1D* PFJetPt = (TH1D* ) file->Get("PFJetPt");

  TH1D* GenJetEta = (TH1D* ) file->Get("GenJetEta");
  TH1D* CaloJetEta = (TH1D* ) file->Get("CaloJetEta");
  TH1D* PFJetEta = (TH1D* ) file->Get("PFJetEta");
  
  TH1D* GenJetPt2 = (TH1D* ) file->Get("GenJetPt2");
  TH1D* CaloJetPt2 = (TH1D* ) file->Get("CaloJetPt2");
  TH1D* PFJetPt2 = (TH1D* ) file->Get("PFJetPt2");

  TH1D* GenJetPt3 = (TH1D* ) file->Get("GenJetPt3");
  TH1D* CaloJetPt3 = (TH1D* ) file->Get("CaloJetPt3");
  TH1D* PFJetPt3 = (TH1D* ) file->Get("PFJetPt3");

  TH1D* CaloJetPtRatio2over1 = (TH1D* ) file->Get("CaloJetPtRatio2over1");
  TH1D* CaloJetPtRatio3over2 = (TH1D* ) file->Get("CaloJetPtRatio3over2");
  TH1D* PFJetPtRatio2over1 = (TH1D* ) file->Get("PFJetPtRatio2over1");
  TH1D* PFJetPtRatio3over2 = (TH1D* ) file->Get("PFJetPtRatio3over2");
  TH1D* GenJetPtRatio2over1 = (TH1D* ) file->Get("GenJetPtRatio2over1");
  TH1D* GenJetPtRatio3over2 = (TH1D* ) file->Get("GenJetPtRatio3over2");


  TH1D* nJetsCalo = (TH1D* ) file->Get("nJetsCalo");
  TH1D* nJetsPF = (TH1D* ) file->Get("nJetsPF");
  TH1D* nJetsGen = (TH1D* ) file->Get("nJetsGen");


  makeplotTwo(*ZPt_Reco, *ZPt_Gen, "ZPt_spectrum", 1);
  makeplotThree(*CaloJetPt, *GenJetPt, *PFJetPt, "Jet_spectrum", 1);
  makeplotThree(*CaloJetPt2, *GenJetPt2, *PFJetPt2, "Jet_spectrum2", 1);
  makeplotThree(*CaloJetPt3, *GenJetPt3, *PFJetPt3, "Jet_spectrum3", 1);
  makeplotThree(*CaloJetEta, *GenJetEta, *PFJetEta, "Jet_eta_spectrum", 2);

  makeplotThree(*CaloJetPtRatio2over1, *GenJetPtRatio2over1, *PFJetPtRatio2over1, "JetPtRatio2over1", 0);
  makeplotThree(*CaloJetPtRatio3over2, *GenJetPtRatio3over2, *PFJetPtRatio3over2, "JetPtRatio3over2", 0);
  makeplotThree( *nJetsCalo, *nJetsGen, *nJetsPF, "JetMultiplicity", 1);

}
Example #11
0
int main( int argc ,char *argv[] ){
  
  DataObject areas;
  areas.getDataFromFile("resources/static_resources/area_noise_CMSSW_IDS.txt",2);
  
  map<string, double> areaMap;
  
  for (int i=1; i<= areas.getLenght(); i++){
    double area = atof(areas.getElementFromPropertyContainer(i,2).c_str());
    string roll = areas.getElementFromPropertyContainer(i,1);
    areaMap[roll] = area;
  }

  //Syntax:
  //EndCap RE(WDN)_SECTOR_RID
  //Barrel W(WDN)_RID_SECTOR

  if (argc < 5) {
    
    cout << "Usage: " << argv[0] << " Zone Wheel Sector RollID [OutFile]" << endl;
    cout << endl;
    cout << "  Conventions:"<< endl;
    cout << "    Barrel: W(WDN)_RID_SECTOR" << endl;
    cout << "    EndCap: RE(WDN)_SECTOR_RID" << endl;
    cout << endl;
    return 0;
  }
  bool corrected = true;
  /*  string zone = "EndCapPlus";
  string RollID = "10";
  int Sector = 2;
  int WheelDiskNo = 2;
  */

  string zone = argv[1];                                                                                                                                                  
  string RollID = argv[4]; 
  int Sector = atoi(argv[3]);                                                                                                                                          
  int WheelDiskNo = atoi(argv[2]);                                                                                                                                                            
  string optionalID = argv[5];

  string ContainerName = "ContainerRun2011.root";
  string jsonFile = "./jsonFilesMu/Cert_160404-180252_7TeV_PromptReco_Collisions11_JSON.txt";
  //Create a new Acquisition Registry

  TFile* contFile = TFile::Open( ContainerName.c_str() );
  
	Acquisition Run2011(contFile);
/*	ifstream json(jsonFile.c_str());
	Run2011.LoadJSON(json);*/


  DataObject filterRun;
  filterRun.getDataFromFile("filters/moreThan100.csv",1);  
  Run2011.LoadSelectionByDO(&filterRun, 1);

      TFile* f;
      if (argc >= 6){
	f = new TFile(argv[6], "RECREATE");
          cout << "Writing results on: " << argv[6] << endl;
}
      else{
	f = new TFile("Outputs/OutputFile.root", "RECREATE");
	cout << "Writing results on: Outputs/OutputFile.root"  << endl;
}

  TGraph* plot = new TGraph();
  TGraph* plotRun = new TGraph();

  plot->SetName("RateVsLumi");
  plotRun->SetName("RateVsRun");

  plot->SetMarkerStyle(21);
  contFile->Close();
    int k=0;    
    int emptyStrip = 0;

	cout << "Analysis of: " << zone << " - Wheel/Disk No." << WheelDiskNo << " ; Sector: " << Sector << " ; ID:" << RollID << endl;
	cout << "Correction activated: " << corrected<< endl;
	cout << "Dataset: " << ContainerName << endl;
	cout << "JSON File: " << jsonFile << endl;

// Run2011.PrintValidRuns();
  cout << "Number of runs: " << Run2011.numberOfRuns() << endl;
  while (Run2011.hasNext()){
    
    double NormalizedRate = 0;
    
    Run* currentRun = Run2011.next();

    //run selection
//    if ( currentRun->getID() > 163289 && currentRun->getID() < 163340 ) continue;
//    if (currentRun->getID() < 170000) continue;
//    if (currentRun->getLumiSection() < 100) continue;
//    if (currentRun->getID() < 178420) continue;
    if (!Run2011.isValid(currentRun, false)) continue;
    
    //Filling
      contFile = TFile::Open( ContainerName.c_str() );

    currentRun->FillFromContainer(contFile, areaMap);

        
    double TotRate = 0;
    double TotArea = 0;
    int totAmount = 0;
    if (currentRun->isFilled() == false){
	cout << "Not filled: " << currentRun->getID() << endl;
    }
    if (currentRun->isFilled() == true){

      map<string,ExRoll* > barrelMap;

      if (zone == "Barrel")
	barrelMap = currentRun->GetBarrel();

      else if (zone == "EndCapPlus")
	barrelMap = currentRun->GetEndCapPlus();

      else if (zone == "EndCapMinus")
	barrelMap = currentRun->GetEndCapMinus();

      for (map<string,ExRoll* >::const_iterator it = barrelMap.begin(); it != barrelMap.end(); it++){

	if (RollID != "-9")
	  if (it->second->getRollID().c_str() != RollID) continue;

	if (Sector != -9)
	  if (it->second->getSector() != Sector) continue;

	if (WheelDiskNo != -9)
	  if (it->second->getWheel_Disk_Number() != WheelDiskNo) continue;

	//When we will decide to plot partition by partition
	if (optionalID != "-9"){
//	cout << optionalID << endl;
//	cout << it->second->getOptionalRollID() << endl;
                if ( it->second->getOptionalRollID().compare(optionalID) ) continue;
	}

      
        emptyStrip += it->second->getEmptyStrip();
//	if ( it->second->getOptionalRollID().compare("B") ) continue;
//	cout << "SEC " << it->second->getSector()  << endl;
/*	cout << "OPT: " << it->second-> getOptionalRollID() << endl;
	cout << "RAW: " << it->second->getRawIDofClone(1) << endl;*/
//	cout << "PASS: "******"VALUE: " << nAnalyzer.HealCloneByClone(it->second) << endl;
        double rollArea = it->second->getRollArea();
        TotArea += rollArea;	
      }

      //Free RAM
      for (map<string,ExRoll* >::const_iterator it = barrelMap.begin(); it != barrelMap.end(); it++){
	delete it->second;
      }

      double NormalizedRate = TotRate / TotArea;
//       cout << NormalizedRate << endl;	      
  string zone = argv[1];                                                                                                                                                  
  string RollID = argv[4]; 
  int Sector = atoi(argv[3]);                                                                                                                                          
  int WheelDiskNo = atoi(argv[2]);     


        if (TotRate != 0 && TotArea != 0 && currentRun->getDelivered() != 0 && currentRun->isFilled()){
//	currentRun->PrintStatistics();	
             
             cout << currentRun->getID() <<
	     "\t" << currentRun->getLumiSection() << "\t" << currentRun->getDelivered() 
	     << "\t" << currentRun->getLumi() <<
	     "\t" << TotRate << "\t" << TotArea << "\t" << NormalizedRate/2 << endl;
		
// 	plot->SetBinContent(plot->FindBin(currentRun->getLumi()), NormalizedRate);
	cout << "POINT: " << k << " "  << currentRun->getLumi()<< " " << NormalizedRate / 2 << endl;; 
	plot->SetPoint(k , currentRun->getLumi(), NormalizedRate / 2);
	plotRun->SetPoint(k, currentRun->getID(), NormalizedRate / 2);
	k++;
	}
    }
    delete currentRun;
    contFile->Close();  
    contFile->Delete();
  }

  plot->SetDrawOption("P");
  f->WriteObject(plotRun, plotRun->GetName());
  f->WriteObject(plot, plot->GetName());

  
  return 0;
}
void plotTreeNorms(TTree *tree_, std::string selectString, bool do7TeV){

	// Create a map for plotting the pullsummaries:
	std::map < const char*, std::pair <double,double> > pullSummaryMap;
	int nPulls=0;

	TObjArray *l_branches = tree_->GetListOfBranches();
	int nBranches = l_branches->GetEntries();

	gStyle->SetPadTopMargin(0.01);

	TCanvas *c = new TCanvas("c","",960,800);

	std::string treename = tree_->GetName();
	c->SaveAs(Form("%s_normresiduals.pdf[",treename.c_str()));
	// File to store plots in 
	TFile *fOut = new TFile(Form("%s_normresiduals.root",treename.c_str()),"RECREATE");

        TH1F *bHd = new TH1F("bHd","",50,-1.0,1.0);
        TH1F *bHfd = new TH1F("bHfd","",50,-1.0,1.0);

	for (int iobj=0;iobj<nBranches;iobj++){

		TBranch *br =(TBranch*) l_branches->At(iobj);

		// Draw the normal histogram
		const char* name = br->GetName();

                // select only the normalizations
                string namestr(name);
                if(namestr.find("n_exp")==string::npos) continue;

                bool fitPull=true;
                bool fitPullf=true;

		double p_mean =0;

		int nToysInTree = tree_->GetEntries();
		// Find out if paramter is fitted value or constraint term.
                bool isFitted = true;
			
                p_mean = prenorms_[name].first;	// toy initial parameters from the datacards
                std::cout << "******* "<< name << " *******"<<std::endl;
                std::cout << p_mean << std::endl;
                std::cout << "******************************" <<std::endl;

                TH1F* bH = (TH1F*)bHd->Clone(Form("%s",name));
                TH1F* bHf = (TH1F*)bHfd->Clone(Form("%s_fail",name));
                
                const char* drawInput = Form("(%s-%f)/%f",name,p_mean,p_mean);
                tree_->Draw(Form("%s>>%s",drawInput,name),"");
                tree_->Draw(Form("%s>>%s_fail",drawInput,name),selectString.c_str(),"same");
                fitPull  = true;
                fitPullf = true;
                  
		bHf->SetLineColor(2);
		bH->GetXaxis()->SetTitle(bH->GetTitle());
		bH->GetYaxis()->SetTitle(Form("no toys (%d total)",nToysInTree));
		bH->GetYaxis()->SetTitleOffset(1.05);
		bH->GetXaxis()->SetTitleOffset(0.9);
		bH->GetYaxis()->SetTitleSize(0.05);
		bH->GetXaxis()->SetTitleSize(0.05);
		bH->GetXaxis()->SetTitle(Form("%s",name));
                
		
		bH->SetTitle("");	

		if ( bH->Integral() <=0 )  fitPull = false;
		if (fitPull) {bH->Fit("gaus"); bH->GetFunction("gaus")->SetLineColor(4);}
		
		if ( bHf->Integral() <=0 )  fitPullf = false;
		if (fitPullf) {bHf->Fit("gaus"); bHf->GetFunction("gaus")->SetLineColor(2);}

		c->Clear();
		
 		TPad pad1("t1","",0.01,0.01,0.66,0.95);
 		TPad pad2("t2","",0.70,0.20,0.98,0.80);

		pad1.SetNumber(1); pad2.SetNumber(2);

                if ( isFitted ) {pad2.Draw();}

		pad1.Draw();
		pad1.SetGrid(true);


		TLatex *titletext = new TLatex();titletext->SetNDC();

		
		c->cd(1); bH->Draw(); bHf->Draw("same");
		TLegend *legend = new TLegend(0.6,0.8,0.9,0.89);
		legend->SetFillColor(0);
		legend->AddEntry(bH,"All Toys","L");
		legend->AddEntry(bHf,selectString.c_str(),"L");
		legend->Draw();

		if (fitPull){
			c->cd(2);
			double gap;
			TLatex *tlatex = new TLatex(); tlatex->SetNDC(); 
			if (fitPullf) {tlatex->SetTextSize(0.09); gap=0.12;}
			else  {tlatex->SetTextSize(0.11);gap=0.14;}

			tlatex->SetTextColor(4);
			tlatex->DrawLatex(0.11,0.80,Form("Mean    : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParError(1)));
			tlatex->DrawLatex(0.11,0.80-gap,Form("Sigma   : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(2),bH->GetFunction("gaus")->GetParError(2)));

			if (fitPullf){ 
				tlatex->SetTextColor(2);
				tlatex->DrawLatex(0.11,0.60,Form("Mean    : %.3f #pm %.3f",bHf->GetFunction("gaus")->GetParameter(1),bHf->GetFunction("gaus")->GetParError(1)));
				tlatex->DrawLatex(0.11,0.60-gap,Form("Sigma   : %.3f #pm %.3f",bHf->GetFunction("gaus")->GetParameter(2),bHf->GetFunction("gaus")->GetParError(2)));
			}

			tlatex->SetTextSize(0.10);
			tlatex->SetTextColor(1);
				
                        tlatex->DrawLatex(0.11,0.33,Form("Pre-fit: %.3f",p_mean));
			
			pullSummaryMap[name]=std::make_pair<double,double>(bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParameter(2));
			nPulls++;

		}

		// double titleSize = isFitted ? 0.1 : 0.028;
		//titletext->SetTextSize(titleSize);titletext->SetTextAlign(21); titletext->DrawLatex(0.55,0.92,name);
		c->SaveAs(Form("%s_normresiduals_%s.pdf",treename.c_str(),(do7TeV ? "7TeV": "8TeV")));
                c->SaveAs(Form("mlfit/%s_residual_%s_%s.pdf",name,treename.c_str(),(do7TeV ? "7TeV": "8TeV")));
		fOut->WriteObject(c,Form("%s_%s",treename.c_str(),name));
	}
	
	if (nPulls>0){
	  
	    std::cout << "Generating Pull Summaries" <<std::endl; 
	    int nRemainingPulls = nPulls;
	    TCanvas *hc = new TCanvas("hc","",3000,2000); hc->SetGrid(0);
	    std::map < const char*, std::pair <double,double> >::iterator pull_it = pullSummaryMap.begin();
	    std::map < const char*, std::pair <double,double> >::iterator pull_end = pullSummaryMap.end();

	    int pullPlots = 1;
	    while (nRemainingPulls > 0){

		int nThisPulls = min(maxPullsPerPlot,nRemainingPulls);

		TH1F pullSummaryHist("pullSummary","",nThisPulls,0,nThisPulls);
		for (int pi=1;pull_it!=pull_end && pi<=nThisPulls ;pull_it++,pi++){
			pullSummaryHist.GetXaxis()->SetBinLabel(pi,(*pull_it).first);
			pullSummaryHist.SetBinContent(pi,((*pull_it).second).first);
			pullSummaryHist.SetBinError(pi,((*pull_it).second).second);
			nRemainingPulls--;
		}		

		pullSummaryHist.SetMarkerStyle(21);pullSummaryHist.SetMarkerSize(1.5);pullSummaryHist.SetMarkerColor(2);pullSummaryHist.SetLabelSize(pullLabelSize);
		pullSummaryHist.GetYaxis()->SetRangeUser(-1,1);pullSummaryHist.GetYaxis()->SetTitle("residual summary (relative)");pullSummaryHist.Draw("E1");
		hc->SaveAs(Form("%s_normresiduals_%s.pdf",treename.c_str(),(do7TeV ? "7TeV": "8TeV")));
                hc->SaveAs(Form("mlfit/residual_summary_%d_%s_%s.pdf",pullPlots,treename.c_str(),(do7TeV ? "7TeV": "8TeV")));
		fOut->WriteObject(hc,Form("comb_pulls_%s_%d",treename.c_str(),pullPlots));
	//	hc->SaveAs(Form("comb_pulls_%s_%d.pdf",treename.c_str(),pullPlots));
		pullPlots++;
	   }

	    delete hc;
	}

	c->SaveAs(Form("%s_normresiduals_%s.pdf]",treename.c_str(),(do7TeV ? "7TeV": "8TeV")));
	fOut->Close();
	delete c;
	return;


}
void plotTree(TTree *tree_, std::string whichfit, std::string selectString){

	// Create a map for plotting the pullsummaries:
	std::map < const char*, std::pair <double,double> > pullSummaryMap;
	int nPulls=0;

	TObjArray *l_branches = tree_->GetListOfBranches();
	int nBranches = l_branches->GetEntries();

	gStyle->SetPadTopMargin(0.01);

	TCanvas *c = new TCanvas("c","",960,800);

	std::string treename = tree_->GetName();
	c->SaveAs(Form("%s.pdf[",treename.c_str()));
	// File to store plots in 
	TFile *fOut = new TFile(Form("%s.root",treename.c_str()),"RECREATE");

	for (int iobj=0;iobj<nBranches;iobj++){

		TBranch *br =(TBranch*) l_branches->At(iobj);

		// Draw the normal histogram
		const char* name = br->GetName();

                // names with - are not allowed
                string namestr(name);
                if(namestr.find("-")!=string::npos) {
                  std::cout << "Variable " << name << " contains a bad character: -. Skipping. " << std::endl;
                  continue;
                }
		bool fitPull=false;
		bool fitPullf=false;

		bool plotLH=false;

		TGraph *gr=NULL;
		double p_mean =0;
		double p_err  =0;

		int nToysInTree = tree_->GetEntries();
		// Find out if paramter is fitted value or constraint term
		bool isFitted = findNuisancePre(name);
		if (doPull && isFitted){
			
			p_mean = bfvals_[name].first;	// toy constrainits thrown about best fit to data
			if(namestr.find("n_exp")==string::npos) p_err  = prevals_[name].second; // uncertainties taken from card
			std::cout << "******* "<< name << " *******"<<std::endl;
			std::cout << p_mean <<  " " << p_err << std::endl;
			std::cout << "******************************" <<std::endl;

			const char* drawInput;
                        // if the parameter is a normalization, the error is not available. Do the residual instead of the pull
                        if(namestr.find("n_exp")!=string::npos) drawInput = Form("(%s-%f)/%f",name,p_mean,p_mean);
                        else drawInput = Form("(%s-%f)/%f",name,p_mean,p_err);
			tree_->Draw(Form("%s>>%s",drawInput,name),"");
			tree_->Draw(Form("%s>>%s_fail",drawInput,name),selectString.c_str(),"same");
			fitPull  = true;
			fitPullf = true;
			if (doLH) {
			  gr = graphLH(name,p_err,whichfit);
			  if (gr) plotLH=true;
			}
			
		}

		else{
			tree_->Draw(Form("%s>>%s",name,name),"");
			tree_->Draw(Form("%s>>%s_fail",name,name),selectString.c_str(),"same");
		}
		

		TH1F* bH  = (TH1F*) gROOT->FindObject(Form("%s",name))->Clone();
		TH1F* bHf = (TH1F*) gROOT->FindObject(Form("%s_fail",name))->Clone();
		bHf->SetLineColor(2);
		bH->GetXaxis()->SetTitle(bH->GetTitle());
		bH->GetYaxis()->SetTitle(Form("no toys (%d total)",nToysInTree));
		bH->GetYaxis()->SetTitleOffset(1.05);
		bH->GetXaxis()->SetTitleOffset(0.9);
		bH->GetYaxis()->SetTitleSize(0.05);
		bH->GetXaxis()->SetTitleSize(0.05);
		if (isFitted) {bH->GetXaxis()->SetTitle(Form("(%s-#theta_{B})/#sigma_{#theta}",name));}
		else {bH->GetXaxis()->SetTitle(Form("%s",name));}
		
		bH->SetTitle("");	

		if ( bH->Integral() <=0 )  fitPull = false;
		if (fitPull) {bH->Fit("gaus"); bH->GetFunction("gaus")->SetLineColor(4);}
		
		if ( bHf->Integral() <=0 )  fitPullf = false;
		if (fitPullf) {bHf->Fit("gaus"); bHf->GetFunction("gaus")->SetLineColor(2);}

		c->Clear();
		//TPad pad1("t1","",0.01,0.02,0.59,0.98);
		// Pad 1 sizes depend on the parameter type ...
		double pad1_x1,pad1_x2,pad1_y1,pad1_y2;
		if ( !isFitted ) {
			 pad1_x1 = 0.01; 
			 pad1_x2 = 0.98; 
			 pad1_y1 = 0.045; 
			 pad1_y2 = 0.98; 
		} else {
			 pad1_x1 = 0.01; 
			 pad1_x2 = 0.59; 
			 pad1_y1 = 0.56; 
			 pad1_y2 = 0.98; 
		}
		
		TPad pad1("t1","",pad1_x1,pad1_y1,pad1_x2,pad1_y2);
		TPad pad1a("t1a","",0.01,0.045,0.59,0.522);
		TPad pad2("t2","",0.59,0.04,0.98,0.62);
		TPad pad3("t3","",0.55,0.64,0.96,0.95);

		pad1.SetNumber(1); pad2.SetNumber(2); pad3.SetNumber(3); pad1a.SetNumber(4);

		if ( isFitted ) {pad1a.Draw();pad2.Draw();pad3.Draw();}

		pad1.Draw();
		pad2.SetGrid(true);


		TLatex *titletext = new TLatex();titletext->SetNDC();

		if ( isFitted ){
			c->cd(4); 
			tree_->Draw(Form("%s:%s_In>>%s_%s_2d",name,name,name,tree_->GetName()),""); 
			//TH2D *h2d_corr = (TH2D*)gROOT->FindObject(Form("%s_2d",name));
			//h2d_corr->SetMarkerColor(4);
			//h2d_corr->SetTitle("");
			//h2d_corr->GetXaxis()->SetTitle(Form("%s_In",name));
			//h2d_corr->GetYaxis()->SetTitle(Form("%s",name));
			titletext->SetTextAlign(11);
			titletext->SetTextSize(0.05);
			titletext->DrawLatex(0.05,0.02,Form("%s_In",name));
			titletext->SetTextAngle(90);
			titletext->DrawLatex(0.04,0.06,Form("%s",name));
			titletext->SetTextAngle(0);
		}

		
		c->cd(1); bH->Draw(); bHf->Draw("same");
		TLegend *legend = new TLegend(0.6,0.8,0.9,0.89);
		legend->SetFillColor(0);
		legend->AddEntry(bH,"All Toys","L");
		legend->AddEntry(bHf,selectString.c_str(),"L");
		legend->Draw();

		if (doPull && plotLH) {
			c->cd(2); gr->Draw("ALP");
		}

		if (fitPull){
			c->cd(3);
			double gap;
			TLatex *tlatex = new TLatex(); tlatex->SetNDC(); 
			if (fitPullf) {tlatex->SetTextSize(0.09); gap=0.12;}
			else  {tlatex->SetTextSize(0.11);gap=0.14;}

			tlatex->SetTextColor(4);
			tlatex->DrawLatex(0.11,0.80,Form("Mean    : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParError(1)));
			tlatex->DrawLatex(0.11,0.80-gap,Form("Sigma   : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(2),bH->GetFunction("gaus")->GetParError(2)));

			if (fitPullf){ 
				tlatex->SetTextColor(2);
				tlatex->DrawLatex(0.11,0.60,Form("Mean    : %.3f #pm %.3f",bHf->GetFunction("gaus")->GetParameter(1),bHf->GetFunction("gaus")->GetParError(1)));
				tlatex->DrawLatex(0.11,0.60-gap,Form("Sigma   : %.3f #pm %.3f",bHf->GetFunction("gaus")->GetParameter(2),bHf->GetFunction("gaus")->GetParError(2)));
			}

			tlatex->SetTextSize(0.10);
			tlatex->SetTextColor(1);
				
                        if(namestr.find("n_exp")!=string::npos) tlatex->DrawLatex(0.11,0.33,Form("Pre-fit: %.3f",prevals_[name].first));
			else tlatex->DrawLatex(0.11,0.33,Form("Pre-fit #pm #sigma_{#theta}: %.3f #pm %.3f",prevals_[name].first, p_err));
			tlatex->DrawLatex(0.11,0.18,Form("Best-fit (#theta_{B})  : %.3f ",p_mean));
			tlatex->DrawLatex(0.11,0.03,Form("Best-fit (#theta_{S+B}): %.3f ",bfvals_sb_[name].first));
			
			pullSummaryMap[name]=std::make_pair<double,double>(bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParameter(2));
			nPulls++;

		}

		double titleSize = isFitted ? 0.1 : 0.028;
		titletext->SetTextSize(titleSize);titletext->SetTextAlign(21); titletext->DrawLatex(0.55,0.92,name);
		c->SaveAs(Form("%s.pdf",treename.c_str()));
		fOut->WriteObject(c,Form("%s_%s",treename.c_str(),name));
		//c->SaveAs(Form("%s_%s.pdf",treename.c_str(),name));
	}
	
	if (doPull && nPulls>0){
	  
	    std::cout << "Generating Pull Summaries" <<std::endl; 
	    int nRemainingPulls = nPulls;
	    TCanvas *hc = new TCanvas("hc","",3000,2000); hc->SetGrid(0);
	    std::map < const char*, std::pair <double,double> >::iterator pull_it = pullSummaryMap.begin();
	    std::map < const char*, std::pair <double,double> >::iterator pull_end = pullSummaryMap.end();

	    int pullPlots = 1;
	    while (nRemainingPulls > 0){

		int nThisPulls = min(maxPullsPerPlot,nRemainingPulls);

		TH1F pullSummaryHist("pullSummary","",nThisPulls,0,nThisPulls);
		for (int pi=1;pull_it!=pull_end && pi<=nThisPulls ;pull_it++,pi++){
			pullSummaryHist.GetXaxis()->SetBinLabel(pi,(*pull_it).first);
			pullSummaryHist.SetBinContent(pi,((*pull_it).second).first);
			pullSummaryHist.SetBinError(pi,((*pull_it).second).second);
			nRemainingPulls--;
		}		

		pullSummaryHist.SetMarkerStyle(21);pullSummaryHist.SetMarkerSize(1.5);pullSummaryHist.SetMarkerColor(2);pullSummaryHist.SetLabelSize(pullLabelSize);
		pullSummaryHist.GetYaxis()->SetRangeUser(-3,3);pullSummaryHist.GetYaxis()->SetTitle("pull summary (n#sigma)");pullSummaryHist.Draw("E1");
		hc->SaveAs(Form("%s.pdf",treename.c_str()));
		fOut->WriteObject(hc,Form("comb_pulls_%s_%d",treename.c_str(),pullPlots));
	//	hc->SaveAs(Form("comb_pulls_%s_%d.pdf",treename.c_str(),pullPlots));
		pullPlots++;
	   }

	    delete hc;
	}

	c->SaveAs(Form("%s.pdf]",treename.c_str()));
	fOut->Close();
	delete c;
	return;


}
Example #14
0
int main( int argc ,char *argv[] ){
  
  DataObject areas;
  areas.getDataFromFile("resources/static_resources/area_noise_CMSSW_IDS.txt",2);

  map<string, double> areaMap;
  
  for (int i=1; i<= areas.getLenght(); i++){
    double area = atof(areas.getElementFromPropertyContainer(i,2).c_str());
    string roll = areas.getElementFromPropertyContainer(i,1);
    areaMap[roll] = area;
  }

  //Create a new Acquisition Registry
  TFile* contFile = TFile::Open("Container.root");
  Acquisition Run2011(contFile);
  TFile* f = new TFile("OutputFile.root", "RECREATE");
  TH2F* plot = new TH2F("RateVsLumi", "Rate Vs Lumi", 2000, 0, 2000, 100, 0, 100);
  contFile->Close();
  while (Run2011.hasNext()){

    double NormalizedRate = 0;

    Run* currentRun = Run2011.next();
    //otherwise no directories
    contFile = TFile::Open("Container.root");
    currentRun->FillFromContainer(contFile, areaMap);
    contFile->Close();

    double TotRate = 0;
    double TotArea = 0;
    int totAmount = 0;

    if (currentRun->isFilled() == true){

      const map<string,ExRoll* > barrelMap = currentRun->GetBarrel();

      for (map<string,ExRoll* >::const_iterator it = barrelMap.begin(); it != barrelMap.end(); it++){

       //Roll Rate
        for (int k=1; k<=96; k++){
          ExStrip * strip = it->second->getStrip(k);
          TotRate = TotRate + strip->getRate();
       	}

      	//Roll Area
        double rollArea = it->second->getRollArea();
        TotArea = TotArea + rollArea;
      }
      double NormalizedRate = TotRate / TotArea;

      if (TotRate != 0 && currentRun->getDelivered() != 0 ){
        cout << currentRun->getID() << " " << currentRun->getLumi() << " " << TotRate << " " << TotArea << " " << NormalizedRate <<endl;
 	plot->Fill(currentRun->getLumi(), NormalizedRate);
	cout  << currentRun->getLumi() << " " << NormalizedRate << endl; 
  }
    }
  }
  f->WriteObject(plot, "Plot");
  return 0;
}
void TrigWeightFit1D(){
  TFile *f = new TFile("../data/scale_factors/HLTEffParkedABCD_1D.root");
  TFile *out = new TFile("HLTEffParkedABCD_1DFit.root","RECREATE");
  
  unsigned nVars=4;
  std::vector<std::string> histstofit[4];
  std::vector<std::string> mjjhists;
  mjjhists.push_back("hData_MJJ_1D_A");
  mjjhists.push_back("hData_MJJ_1D_BC");
  mjjhists.push_back("hData_MJJ_1D_D");
  std::vector<std::string> metl1hists;
  metl1hists.push_back("hData_MET_L1_A");
  metl1hists.push_back("hData_MET_L1_BC");
  metl1hists.push_back("hData_MET_L1_D");
  std::vector<std::string> methists;
  methists.push_back("hData_MET_1D_A");
  methists.push_back("hData_MET_1D_BC");
  methists.push_back("hData_MET_1D_D");
  std::vector<std::string> jet2hists;
  jet2hists.push_back("hData_JET2_1D_A");
  jet2hists.push_back("hData_JET2_1D_BC");
  jet2hists.push_back("hData_JET2_1D_D");

  histstofit[0]=mjjhists;
  histstofit[1]=metl1hists;
  histstofit[2]=methists;
  histstofit[3]=jet2hists;

  //create a function with 3 parameters in the range [-3,3]
  for(unsigned iVar=0;iVar<nVars;iVar++){
    for(unsigned iTurnon=0;iTurnon<histstofit[iVar].size();iTurnon++){
      TH1F *hpx = (TH1F*)f->Get(histstofit[iVar][iTurnon].c_str()); //LOOP OVER THE TRIG TURN ONS
      double rangelow,rangehigh;
      if(iVar==0){
	rangelow=600;
	rangehigh=2200;
      }
      else if(iVar==1){
	rangelow=60;
	rangehigh=400;
      }
      else if(iVar==2){
	rangelow=0;
	rangehigh=400;
      }
      else if(iVar==3){
	rangelow=0;
	rangehigh=100;
      }
      TF1 *func = new TF1("erf","0.5*(1+TMath::Erf((x-[0])/(sqrt([1]))))",rangelow,rangehigh);
      func->SetParameters(100,10000);
      func->SetParNames("Turn On","Sigma");
      func->SetParLimits(0,-10000,10000);
      func->SetParLimits(1,0,100000);
      hpx->Fit("erf","R");
      TCanvas *c1=new TCanvas();
      hpx->Draw();
      c1->SaveAs((histstofit[iVar][iTurnon]+".pdf").c_str());
      TF1 *fitresult=hpx->GetFunction("erf");
      //Get name to save as
      std::string outname=histstofit[iVar][iTurnon].substr(1);
      out->WriteObject(fitresult,("f"+outname).c_str());
    }
  }
}
Example #16
0
void MergeSetsOfIlcgnObjs(const char* filename1, const char* filename2, const char* det="ITS")
{
  // example macro: building an array by merging the non-SSD entries
  // from one file (or OCDB entry) with the remaining SSD entries taken
  // from another file (or OCDB entry); the first two arguments can be local filenames
  // or URLs of the OCDB folders 
  //  
  const char* macroname = "MergeSetsOfIlcgnObjs";
  
  TClonesArray* array1 = 0;
  TClonesArray* array2 = 0;

  TString arName(det);
  arName+="AlignObjs";
  TString path(det);
  path+="/Align/Data";
  
  TString f1(filename1);
  TString f2(filename2);
  
  IlcCDBStorage* stor1 = 0;
  IlcCDBStorage* stor2 = 0;
  
  Bool_t fromOcdb1=kFALSE;
  Bool_t fromOcdb2=kFALSE;

  if(f1.Contains("alien://folder=") || f1.Contains("local://")) fromOcdb1=kTRUE;
  if(f2.Contains("alien://folder=") || f2.Contains("local://")) fromOcdb2=kTRUE;

  
  IlcCDBManager* cdb = IlcCDBManager::Instance();
  cdb->SetDefaultStorage("local://$ILC_ROOT/OCDB");
  cdb->SetRun(0);
  
  if(fromOcdb1){
    stor1 = cdb->GetStorage(f1.Data());
    IlcCDBEntry* entry = stor1->Get(path.Data(),0);
    array1 = (TClonesArray*) entry->GetObject();
  }else{
    TFile* filein1 = TFile::Open(f1.Data(),"READ");
    if(!filein1)
    {
      Info(macroname,Form("Unable to open file %s! Exiting ...", f1.Data()));
      return;
    }
    array1 = (TClonesArray*) filein1->Get(arName.Data());
  }
  if(array1){
    Info(macroname,Form("First array has %d entries", array1->GetEntriesFast()));
  }else{
    Info(macroname,"Unable to get first array! Exiting ...");
    return;
  }

  if(fromOcdb2){
    stor2 = cdb->GetStorage(f2.Data());
    IlcCDBEntry* entry = stor2->Get(path.Data(),0);
    array2 = (TClonesArray*) entry->GetObject();
  }else{
    TFile* filein2 = TFile::Open(f2.Data(),"READ");
    if(!filein2)
    {
      Info(macroname,Form("Unable to open file %s! Exiting ...", f2.Data()));
      return;
    }
    array2 = (TClonesArray*) filein2->Get(arName.Data());
  }
  if(array2){
    Info(macroname,Form("Second array has %d entries", array2->GetEntriesFast()));
  }else{
    Info(macroname,"Unable to get second array! Exiting ...");
    return;
  }


  TClonesArray *mergedArr = new TClonesArray("IlcAlignObjParams",3000);

  Info(macroname,"Merging objects for SPD and SDD from the first array ...");
  // SSD starts from 500
  for(Int_t i=0; i<500; i++)
  {
    (*mergedArr)[i] = (IlcAlignObjParams*) array1->UncheckedAt(i);
  }
  
  Info(macroname,"Merging objects for SSD from the second array ...");
  for(Int_t i=500; i<array2->GetEntriesFast(); i++)
  {
    (*mergedArr)[i] = (IlcAlignObjParams*) array2->UncheckedAt(i);
  }
  
  TString foutName("merged");
  foutName+=det;
  foutName+="Alignment.root";
  Info(macroname,Form("... in a single array into the file %s", foutName.Data()));
  TFile* fileout = TFile::Open(foutName.Data(),"RECREATE");
  fileout->cd();
  fileout->WriteObject(mergedArr,arName.Data(),"kSingleKey");
  fileout->Close();
  
  mergedArr->Delete();
  
}
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();
  }  
}