void updateweight(TString filename) { auto f = new TFile(filename,"update"); auto nt = (TTree *)f->Get("nt"); float prew, weight; TBranch *bw; bw = nt->Branch("weight",&weight); nt->SetBranchAddress("prew",&prew); int n = nt->GetEntries(); int onep = n/100; for (int i=0;i<n;i++) { if (i%onep==0) cout<<i/onep<<endl; nt->GetEntry(i); weight = prew; bw->Fill(); } nt->Write(); f->Close(); }
void ResultFormatter::AddBranch( TTree* inputTree, const string& BranchName, const vector<double>& DoubleData ) { if( inputTree->GetEntries() != 0 ) { if( inputTree->GetEntries() != (int) DoubleData.size() ) { cerr << "CANNOT ADD DOUBLE BRANCH: " << BranchName << " TO: " << inputTree->GetName() << endl; return; } } TString branchName( BranchName ); TString branchLabel=branchName; branchLabel.Append("/D"); double thisValue=0.; TBranch* newBranch = inputTree->Branch( branchName, &thisValue, branchLabel ); inputTree->SetEntries( (int) DoubleData.size() ); for( unsigned int i=0; i< DoubleData.size(); ++i ) { thisValue=DoubleData[i]; newBranch->Fill(); } return; }
int reader_wrapper::GetEntry(Long64_t e) { /// don't care about spectators here for (auto b: m_branches) { b->GetEntry(e); } for (auto& v : m_variables) { v.value = v.ttreeformula->EvalInstance(); } m_response = m_reader->EvaluateMVA(m_methodName.Data()); m_responseBranch->Fill(); return 0; }
void addBranchToTreesInFiles() { //************************************************************ // Variables // vector<TString> fileName; fileName.push_back( "PhotonJetPt15_realPhotons.root" ); fileName.push_back( "PhotonJetPt30_realPhotons.root" ); // The following 4 variables set the scale float invLuminosityToScaleTo = 200; // in pb-1 vector<float> crossSection; crossSection.push_back( 2.9E5 ); crossSection.push_back( 3.2E4 ); vector<float> filterEffeciency; filterEffeciency.push_back( 1.0 ); filterEffeciency.push_back( 1.0 ); vector<float> eventsAnalyzied; eventsAnalyzied.push_back( 950E3 ); eventsAnalyzied.push_back( 670E3 ); // END of setting scale TString treeName = "TreePhotonMatched"; // END of Variables // //************************************************************ // Loop over all the Files for (int i=0; i < fileName.size(); i++) { TFile* currentFile = new TFile(fileName[i],"update"); // this is the variable to be added Float_t scale=crossSection[i]*invLuminosityToScaleTo*filterEffeciency[i]/eventsAnalyzied[i]; cout << "Opened " << fileName[i] << ", adding new branch with value=" << scale; TTree *tree = (TTree*)currentFile->Get(treeName); TBranch *newBranch = tree->Branch("weight", &scale,"weight/F"); // Loop over all the entries, and add the new branch Int_t numEntries = (Int_t)tree->GetEntries(); for (Int_t j=0; j<numEntries; j++) { newBranch->Fill(); } tree->Write("",TObject::kOverwrite); // save new version only currentFile->Close(); cout << "...closed file." << endl; } }
void addDiMuMassPrimeBranchZPt(DiMuPlottingSystem* dps) { TTree* newtree = new TTree("newtree", "new tree"); newtree->AddFriend(dps->treename, dps->infilename); TBranch *newBranch = newtree->Branch("recoCandMassPrime",&dps->recoCandMassPrime,"recoCandMassPrime/F"); Int_t nentries = dps->tree->GetEntries(); std::cout << "nentries: " << nentries << std::endl; for (Int_t i = 0; i < nentries; i++) { dps->tree->GetEntry(i); if(dps->recoCandPt > 20 && dps->recoCandPt < 60) dps->recoCandMassPrime = dps->recoCandMass + 0.0000917686*(dps->recoCandPt*dps->recoCandPt)*TMath::Sin(-6.43015*TMath::Sqrt(dps->recoCandPt) + 0.210496); else dps->recoCandMassPrime = dps->recoCandMass; newBranch->Fill(); } dps->tree = newtree; }
void addMCWeight(TString filename, TString treename) { using namespace std; cout << "adding MCWeight to:"<< filename << endl; double scale_w; float mcWeight; int npv; TFile *file = new TFile(filename,"UPDATE"); TTree *oldtree = (TTree*)file->Get(treename); if(oldtree==NULL) { cout << "Could not find tree " << treeDir << "/" << treename << endl << "in file " << file->GetName() << endl; return; } oldtree->SetBranchAddress("scale_w",&scale_w); oldtree->SetBranchAddress("mcWeight",&mcWeight); oldtree->SetBranchAddress("npv",&npv); double scaleMC_w = 1.0; TBranch *branch = oldtree->Branch("scaleMC_w",&scaleMC_w,"scaleMC_w/D"); for(int i = 0; i < oldtree->GetEntries(); i++) { oldtree->GetEntry(i); double w_npv = (3.57041 + -1.49846*npv + 0.515829*npv*npv + -0.0839209*npv*npv*npv + 0.00719964*npv*npv*npv*npv + -0.000354548*npv*npv*npv*npv*npv + 1.01544e-05*npv*npv*npv*npv*npv*npv + -1.58019e-07*npv*npv*npv*npv*npv*npv*npv + 1.03663e-09*npv*npv*npv*npv*npv*npv*npv*npv); scaleMC_w = scale_w*mcWeight*w_npv; branch->Fill(); } file->cd(); oldtree->CloneTree()->Write(treename, TObject::kOverwrite); file->Close(); }
void addMCWeight_data(TString filename, TString treename) { using namespace std; cout << "Data adding MCWeight to:"<< filename << endl; double scale_w; float mcWeight; TFile *file = new TFile(filename,"UPDATE"); TTree *oldtree = (TTree*)file->Get(treename); if(oldtree==NULL) { cout << "Could not find tree " << treeDir << "/" << treename << endl << "in file " << file->GetName() << endl; return; } oldtree->SetBranchAddress("scale_w",&scale_w); oldtree->SetBranchAddress("mcWeight",&mcWeight); double scaleMC_w = 1.0; TBranch *branch = oldtree->Branch("scaleMC_w",&scaleMC_w,"scaleMC_w/D"); for(int i = 0; i < oldtree->GetEntries(); i++) { oldtree->GetEntry(i); scaleMC_w = scale_w*mcWeight; branch->Fill(); } file->cd(); oldtree->CloneTree()->Write(treename, TObject::kOverwrite); file->Close(); }
void addBranch() { //TFile *f = TFile::Open("TTbar_madgraphMLM_1000pb_weighted.root","update"); //TFile *f = TFile::Open("QCD_1000pb_weighted.root","update"); TFile *f = TFile::Open("GluGluHToBB_M125_13TeV_powheg_pythia8_1000pb_weighted.root","update"); TTree *T = (TTree*)f->Get("otree"); double AK8Puppijet0_tau21,AK8Puppijet0_msd,AK8Puppijet0_pt; double AK8Puppijet0_tau21DDT = 999; TBranch *bpt = T->Branch("AK8Puppijet0_tau21DDT",&AK8Puppijet0_tau21DDT,"AK8Puppijet0_tau21DDT/D"); T->SetBranchAddress("AK8Puppijet0_tau21",&AK8Puppijet0_tau21); T->SetBranchAddress("AK8Puppijet0_msd",&AK8Puppijet0_msd); T->SetBranchAddress("AK8Puppijet0_pt",&AK8Puppijet0_pt); Long64_t nentries = T->GetEntries(); for (Long64_t i=0;i<nentries;i++) { T->GetEntry(i); if (AK8Puppijet0_pt > 0. && AK8Puppijet0_msd > 0.) AK8Puppijet0_tau21DDT = AK8Puppijet0_tau21 + 0.063*TMath::Log(AK8Puppijet0_msd*AK8Puppijet0_msd/AK8Puppijet0_pt); bpt->Fill(); } T->Print(); T->Write(); delete f; }
void updatePbPbBtriggerweight(TString filename, vector<float> w) { auto f = new TFile(filename,"update"); auto nt = (TTree *)f->Get("nt"); float csv60, csv80; float triggermatched; float weight; TBranch *bw; bw = nt->Branch("weight",&weight); nt->SetBranchAddress("hltCSV60",&csv60); nt->SetBranchAddress("hltCSV80",&csv80); nt->SetBranchAddress("triggermatched",&triggermatched); int n = nt->GetEntries(); int onep = n/100; for (int i=0;i<n;i++) { if (i%onep==0) cout<<i/onep<<endl; nt->GetEntry(i); weight = 0; if (triggermatched && csv80) weight = w[1]; if (triggermatched && csv60 && !csv80) weight = w[0]; bw->Fill(); } nt->Write(); f->Close(); }
void TMVAClassificationApplication_TX(TString myMethodList = "" , TString iFileName = "", TString sampleLocation = "", TString outputLocation = "") { #ifdef __CINT__ gROOT->ProcessLine( ".O0" ); // turn off optimization in CINT #endif //--------------------------------------------------------------- // This loads the library TMVA::Tools::Instance(); // Default MVA methods to be trained + tested std::map<std::string,int> Use; // --- Cut optimisation Use["Cuts"] = 0; Use["CutsD"] = 0; Use["CutsPCA"] = 0; Use["CutsGA"] = 0; Use["CutsSA"] = 0; // // // --- Boosted Decision Trees Use["BDT"] = 1; // uses Adaptive Boost std::cout << std::endl; std::cout << "==> Start TMVAClassificationApplication" << std::endl; // Select methods (don't look at this code - not of interest) if (myMethodList != "") { for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0; std::vector<TString> mlist = gTools().SplitString( myMethodList, ',' ); for (UInt_t i=0; i<mlist.size(); i++) { std::string regMethod(mlist[i]); if (Use.find(regMethod) == Use.end()) { std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl; for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) { std::cout << it->first << " "; } std::cout << std::endl; return; } Use[regMethod] = 1; } } // -------------------------------------------------------------------------------------------------- // --- Create the Reader object TMVA::Reader *reader = new TMVA::Reader("!Color:!Silent" ); // Create a set of variables and declare them to the reader // - the variable names MUST corresponds in name and type to those given in the weight file(s) used Float_t var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, var11, var12, var13, var14, var15, var16, var17, var18, var19, var20, var21, var22, var23, var24, var25, var26, var27, var28, var29; //reader->AddVariable( "Alt$(jet_pt_singleLepCalc[0],0)", &var1); //reader->AddVariable( "Alt$(jet_pt_singleLepCalc[1],0)", &var2 ); //reader->AddVariable( "Alt$(jet_pt_singleLepCalc[2],0)", &var3 ); reader->AddVariable( "Alt$(bJetPt_CATopoCalc[0],0)", &var4 ); reader->AddVariable( "Alt$(bJetPt_CATopoCalc[1],0)", &var5 ); //reader->AddVariable( "corr_met_singleLepCalc", &var6 ); //reader->AddVariable( "muon_1_pt_singleLepCalc", &var7 ); //reader->AddVariable( "nBJets_CATopoCalc", &var8 ); //reader->AddVariable( "nSelJets_CommonCalc", &var9 ); //reader->AddVariable( "LeptonJet_DeltaR_LjetsTopoCalcNew", &var10); reader->AddVariable( "Mevent_LjetsTopoCalcNew", &var11); //reader->AddVariable( "W_Pt_LjetsTopoCalcNew", &var12 ); reader->AddVariable( "Jet1Jet2_Pt_LjetsTopoCalcNew", &var13 ); //reader->AddVariable( "BestTop_LjetsTopoCalcNew", &var14 ); //reader->AddVariable( "BTagTopMass_LjetsTopoCalcNew", &var15 ); //reader->AddVariable( "Alt$(CAHEPTopJetMass_JetSubCalc[0],0)", &var16 ); //reader->AddVariable( "Alt$(CAWCSVMSubJets_JetSubCalc[0],0)", &var17 ); //reader->AddVariable( "Alt$(CAWCSVLSubJets_JetSubCalc[0],0)", &var18 ); reader->AddVariable( "Alt$(CAWJetPt_JetSubCalc[0],0)", &var19 ); reader->AddVariable( "Alt$(CAWJetMass_JetSubCalc[0],0)", &var20 ); //reader->AddVariable( "Alt$(CAHEPTopJetMass_JetSubCalc[1],0)", &var21 ); //reader->AddVariable( "Hz_LjetsTopoCalcNew", &var22 ); //reader->AddVariable( "Centrality_LjetsTopoCalcNew", &var23 ); reader->AddVariable( "SqrtsT_LjetsTopoCalcNew", &var24 ); reader->AddVariable( "CAMindrBMass_CATopoCalc", &var28 ); reader->AddVariable( "minDRCAtoB_CATopoCalc", &var29 ); //reader->AddVariable( "HT2prime_LjetsTopoCalcNew", &var25 ); reader->AddVariable( "HT2_LjetsTopoCalcNew", &var26 ); //reader->AddVariable( "dphiLepMet_LjetsTopoCalcNew", &var27 ); // Spectator variables declared in the training have to be added to the reader, too // Float_t spec1,spec2; // reader->AddSpectator( "spec1 := var1*2", &spec1 ); // reader->AddSpectator( "spec2 := var1*3", &spec2 ); // Float_t Category_cat1, Category_cat2, Category_cat3; // if (Use["Category"]){ // // Add artificial spectators for distinguishing categories // reader->AddSpectator( "Category_cat1 := var3<=0", &Category_cat1 ); // reader->AddSpectator( "Category_cat2 := (var3>0)&&(var4<0)", &Category_cat2 ); // reader->AddSpectator( "Category_cat3 := (var3>0)&&(var4>=0)", &Category_cat3 ); // } // --- Book the MVA methods // Book method(s) TString weightFileName = "weights/TMVAClassification_BDT.weights"; reader->BookMVA("BDT method", weightFileName+".xml" ); // Book output histograms UInt_t nbin = 100; TH1F *histBdt(0); histBdt = new TH1F( "MVA_BDT_TX", "MVA_BDT_TX", nbin, -1.0, 1.0); // Prepare input tree (this must be replaced by your data source) // in this example, there is a toy tree with signal and one with background events // we'll later on use only the "signal" events for the test in this example. // TFile *input(0); TString fileName = iFileName; TString fname = sampleLocation+"/"; fname += fileName; TString oFileName = fileName; if (!gSystem->AccessPathName( fname )) input = TFile::Open( fname ); // check if file in local directory exists if (!input) { std::cout << "ERROR: could not open data file" << std::endl; exit(1); } std::cout << "--- TMVAClassificationApp : Using input file: " << input->GetName() << std::endl; // --- Event loop // Prepare the event tree // - here the variable names have to corresponds to your tree // - you can use the same variables as above which is slightly faster, // but of course you can use different ones and copy the values inside the event loop // std::cout << "--- Select signal sample" << std::endl; TTree* theTree = (TTree*)input->Get("ljmet"); gSystem->mkdir( outputLocation ); TFile *target = new TFile( outputLocation+"/"+oFileName,"RECREATE" ); TTree *newTree = theTree->CloneTree(); Float_t BDT; TBranch *branchBDT = newTree->Branch("__BDT_TX__",&BDT,"__BDT_TX__/F"); std::vector<Double_t> *vecVar1; std::vector<Double_t> *vecVar4; std::vector<Double_t> *vecVar16; std::vector<Int_t> *vecVar17; std::vector<Int_t> *vecVar18; std::vector<Double_t> *vecVar19; std::vector<Double_t> *vecVar20; Int_t *intVar5, *intVar8, *intVar9; Double_t *dVar2, *dVar3, *dVar6, *dVar7, *dVar10, *dVar11, *dVar12, *dVar13, *dVar14, *dVar15, *dVar22, *dVar23, *dVar24, dVar25, *dVar26, *dVar27, *dVar28, *dVar29; theTree->SetBranchAddress( "jet_pt_singleLepCalc", &vecVar1); theTree->SetBranchAddress( "bJetPt_CATopoCalc", &vecVar4 ); theTree->SetBranchAddress( "corr_met_singleLepCalc", &dVar6 ); theTree->SetBranchAddress( "muon_1_pt_singleLepCalc", &dVar7 ); theTree->SetBranchAddress( "nBJets_CATopoCalc", &intVar8 ); theTree->SetBranchAddress( "nSelJets_CommonCalc", &intVar9 ); theTree->SetBranchAddress( "LeptonJet_DeltaR_LjetsTopoCalcNew", &dVar10); theTree->SetBranchAddress( "Mevent_LjetsTopoCalcNew", &dVar11); theTree->SetBranchAddress( "W_Pt_LjetsTopoCalcNew", &dVar12 ); theTree->SetBranchAddress( "Jet1Jet2_Pt_LjetsTopoCalcNew", &dVar13 ); theTree->SetBranchAddress( "BestTop_LjetsTopoCalcNew", &dVar14 ); theTree->SetBranchAddress( "BTagTopMass_LjetsTopoCalcNew", &dVar15 ); theTree->SetBranchAddress( "CAHEPTopJetMass_JetSubCalc", &vecVar16 ); theTree->SetBranchAddress( "CAWCSVMSubJets_JetSubCalc", &vecVar17 ); theTree->SetBranchAddress( "CAWCSVLSubJets_JetSubCalc", &vecVar18 ); theTree->SetBranchAddress( "CAWJetPt_JetSubCalc", &vecVar19 ); theTree->SetBranchAddress( "CAWJetMass_JetSubCalc", &vecVar20 ); theTree->SetBranchAddress( "Hz_LjetsTopoCalcNew", &dVar22 ); theTree->SetBranchAddress( "Centrality_LjetsTopoCalcNew", &dVar23 ); theTree->SetBranchAddress( "SqrtsT_LjetsTopoCalcNew", &dVar24 ); theTree->SetBranchAddress( "HT2prime_LjetsTopoCalcNew", &dVar25 ); theTree->SetBranchAddress( "HT2_LjetsTopoCalcNew", &dVar26 ); theTree->SetBranchAddress( "dphiLepMet_LjetsTopoCalcNew", &dVar27 ); theTree->SetBranchAddress( "CAMindrBMass_CATopoCalc", &dVar28 ); theTree->SetBranchAddress( "minDRCAtoB_CATopoCalc", &dVar29 ); // Efficiency calculator for cut method Int_t nSelCutsGA = 0; Double_t effS = 0.7; std::vector<Float_t> vecVar(4); // vector for EvaluateMVA tests std::cout << "--- Processing: " << theTree->GetEntries() << " events" << std::endl; TStopwatch sw; sw.Start(); for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) { if (ievt%1000 == 0) std::cout << "--- ... Processing event: " << ievt << std::endl; theTree->GetEntry(ievt); if(vecVar1->size()>0){ var1 = vecVar1->at(0); } if(vecVar1->size()>1){ var2 = vecVar1->at(1); } if(vecVar1->size()>2){ var3 = vecVar1->at(2); } if(vecVar4->size()>0){ var4 = vecVar4->at(0); } if(vecVar4->size()>1){ var5 = vecVar4->at(1); } var6 = dVar6; var7 = dVar7; var8 = intVar8; var9 = intVar9; var10 = dVar10; var11 = dVar11; var12 = dVar12; var13 = dVar13; var14 = dVar14; var15 = dVar15; if(vecVar16->size()>0){ var16 = vecVar16->at(0); } else{ var16 = 0; } if(vecVar17->size()>0){ var17 = vecVar17->at(0); } else{ var18 = 0; } if(vecVar19->size()>0){ var19 = vecVar19->at(0); } else{ var19 = 0; } if(vecVar20->size()>0){ var20 = vecVar20->at(0); } else{ var20 = 0; } if(vecVar16->size()>1){ var21 = vecVar16->at(1); } else{ var21 = 0; } var22 = dVar22; var23 = dVar23; var24 = dVar24; var25 = dVar25; var26 = dVar26; var27 = dVar27; var28 = dVar28; var29 = dVar29; // --- Return the MVA outputs and fill into histograms if (Use["CutsGA"]) { // Cuts is a special case: give the desired signal efficienciy Bool_t passed = reader->EvaluateMVA( "CutsGA method", effS ); if (passed) nSelCutsGA++; } BDT = reader->EvaluateMVA( "BDT method"); histBdt->Fill(BDT); branchBDT->Fill(); } // Get elapsed time sw.Stop(); std::cout << "--- End of event loop: "; sw.Print(); // Get efficiency for cuts classifier if (Use["CutsGA"]) std::cout << "--- Efficiency for CutsGA method: " << double(nSelCutsGA)/theTree->GetEntries() << " (for a required signal efficiency of " << effS << ")" << std::endl; if (Use["CutsGA"]) { // test: retrieve cuts for particular signal efficiency // CINT ignores dynamic_casts so we have to use a cuts-secific Reader function to acces the pointer TMVA::MethodCuts* mcuts = reader->FindCutsMVA( "CutsGA method" ) ; if (mcuts) { std::vector<Double_t> cutsMin; std::vector<Double_t> cutsMax; mcuts->GetCuts( 0.7, cutsMin, cutsMax ); std::cout << "--- -------------------------------------------------------------" << std::endl; std::cout << "--- Retrieve cut values for signal efficiency of 0.7 from Reader" << std::endl; for (UInt_t ivar=0; ivar<cutsMin.size(); ivar++) { std::cout << "... Cut: " << cutsMin[ivar] << " < \"" << mcuts->GetInputVar(ivar) << "\" <= " << cutsMax[ivar] << std::endl; } std::cout << "--- -------------------------------------------------------------" << std::endl; } } // --- Write histograms newTree->Write("",TObject::kOverwrite); target->Close(); std::cout << "--- Created root file: \""<<oFileName<<"\" containing the MVA output histograms" << std::endl; delete reader; std::cout << "==> TMVAClassificationApplication is done!" << endl << std::endl; }
int main(int argc, char** argv){ //Check if all nedeed arguments to parse are there if(argc != 2) { std::cerr << ">>>>> analysis.cpp::usage: " << argv[0] << " configFileName" << std::endl ; return 1; } std::cout << " " << std::endl; std::cout << " " << std::endl; std::cout << " \\ | | \\ \\ / _) | | " << std::endl; std::cout << " _ \\ _` | _` | \\ \\ \\ / _ \\ | _` | __ \\ __| " << std::endl; std::cout << " ___ \\ ( | ( | \\ \\ \\ / __/ | ( | | | | | " << std::endl; std::cout << " _/ _\\ \\__,_| \\__,_| \\_/\\_/ \\___| _| \\__, | _| |_| \\__| " << std::endl; std::cout << " |___/ " << std::endl; std::cout << " " << std::endl; std::cout << " " << std::endl; std::cout << " " << std::endl; // Parse the config file parseConfigFile (argv[1]) ; std::string treeName = gConfigParser -> readStringOption("Input::treeName"); std::string treeNameDir = ""; try { treeNameDir = gConfigParser -> readStringOption("Input::treeNameDir"); } catch (char const* exceptionString){ std::cerr << " exception = " << exceptionString << std::endl; } std::cout << ">>>>> input::treeNameDir " << treeNameDir << std::endl; std::string fileSamples = gConfigParser -> readStringOption("Input::fileSamples"); std::string inputDirectory = gConfigParser -> readStringOption("Input::inputDirectory"); TTree *treeJetLepVect[1000]; char nameFileIn[1000]; char *nameSample[1000]; int PUScenarioIndex[1000]; sprintf(nameFileIn,"%s",fileSamples.c_str()); int numberOfSamples = ReadFileWeight(nameFileIn, nameSample, PUScenarioIndex); std::cout << std::endl; std::cout << " numberOfSamples = " << numberOfSamples << std::endl; std::cout << std::endl; // std::cout << " PUScenarioIndex[0] = " << PUScenarioIndex[0] << std::endl; ///==== PU reweight (begin) ==== int numPUScenarios = gConfigParser -> readIntOption("PU::PUScenarios"); std::vector<std::string> PUVAR; std::vector<double> PUMC[100]; std::vector<double> PUDATA[100]; PUclass PU[100]; for (int iScPU = 0; iScPU < numPUScenarios; iScPU++) { TString namePU; namePU = Form("PU::PUMC%d",iScPU); PUMC[iScPU] = gConfigParser -> readDoubleListOption(namePU.Data()); namePU = Form("PU::PUDATA%d",iScPU); PUDATA[iScPU] = gConfigParser -> readDoubleListOption(namePU.Data()); namePU = Form("PU::PUVAR%d",iScPU); std::string tempName = gConfigParser -> readStringOption(namePU.Data()); PUVAR.push_back(tempName); if (PUMC[iScPU].size() != PUDATA[iScPU].size()) { std::cout << " PUVAR[" << iScPU << "] = " << PUVAR.at(iScPU) << std::endl; std::cout << " PUMC[" << iScPU << "].size() = " << PUMC[iScPU].size() << std::endl; std::cout << " PUDATA[" << iScPU << "].size() = " << PUDATA[iScPU].size() << std::endl; std::cerr << " ERROR " << std::endl; return 1; } double sumPUMC = 0; for (int itVPU = 0; itVPU < PUMC[iScPU].size(); itVPU++ ){ sumPUMC += PUMC[iScPU].at(itVPU); } double sumPUDATA = 0; for (int itVPU = 0; itVPU < PUDATA[iScPU].size(); itVPU++ ){ sumPUDATA += PUDATA[iScPU].at(itVPU); } for (int itVPU = 0; itVPU < PUMC[iScPU].size(); itVPU++ ){ PU[iScPU].PUWeight.push_back(PUDATA[iScPU].at(itVPU) / PUMC[iScPU].at(itVPU) * sumPUMC / sumPUDATA); } } ///==== PU reweight (end) ==== ///==== debug flag ==== bool debug = false; try { debug = gConfigParser -> readBoolOption("Input::debug"); } catch (char const* exceptionString){ std::cerr << " exception = " << exceptionString << std::endl; } std::cout << ">>>>> input::debug " << debug << std::endl; for (int iSample=0; iSample<numberOfSamples; iSample++){ std::cout << " nameSample[" << iSample << ":" << numberOfSamples << "] = " << nameSample[iSample] << std::endl; ///==== GetTree (begin) ==== char nameFile[20000]; sprintf(nameFile,"%s/out_%s.root",inputDirectory.c_str(),nameSample[iSample]); std::cout << " nameFile = " << nameFile << std::endl; TFile* f = new TFile(nameFile, "update"); f->cd(treeNameDir.c_str()); treeJetLepVect[iSample] = (TTree*) f->Get(treeName.c_str()); // char nameTreeJetLep[100]; // sprintf(nameTreeJetLep,"treeJetLep_%d",iSample); // treeJetLepVect[iSample]->SetName(nameTreeJetLep); ///==== GetTree (end) ==== std::cout << " >>>>> GetEntries " << treeJetLepVect[iSample]->GetEntries() << std::endl; double weight; // TBranch *newBranch; ///==== add new branch ==== TBranch *newBranch = treeJetLepVect[iSample] -> Branch("weight_PU",&weight,"weight_PU/D"); int numPUMC; treeJetLepVect[iSample] -> SetBranchAddress(PUVAR.at(PUScenarioIndex[iSample]).c_str(),&numPUMC); Long64_t nentries = treeJetLepVect[iSample]->GetEntries(); for (Long64_t iEntry = 0; iEntry < nentries; iEntry++){ if((iEntry%((nentries+10)/10)) == 0) std::cout << ">>>>> analysis::GetEntry " << iEntry << " : " << nentries << std::endl; treeJetLepVect[iSample]->GetEntry(iEntry); weight = PU[ PUScenarioIndex[iSample] ].getPUWeight(numPUMC); newBranch->Fill(); } // save only the new version of the tree treeJetLepVect[iSample]->Write("", TObject::kOverwrite); } std::cout << " *** end *** " << std::endl; }
void flagMultCands( TString fname, TString tname ) { TFile *inFile = new TFile( fname, "UPDATE" ); TTree *tree = (TTree*)inFile->Get( tname ); if ( tree->FindBranch( "pass_multcand" ) ) { cout << "pass_multcand branch already exists so I won't add it" << endl; delete inFile; return; } ULong64_t eventNumber; int itype; bool pass_bdt; bool pass_pid; bool pass_rhokst; bool pass_massveto; UInt_t nCandidate; ULong64_t totCandidates; tree->SetBranchAddress( "eventNumber" , &eventNumber ); tree->SetBranchAddress( "itype" , &itype ); tree->SetBranchAddress( "pass_bdt" , &pass_bdt ); tree->SetBranchAddress( "pass_pid" , &pass_pid ); tree->SetBranchAddress( "pass_rhokst" , &pass_rhokst ); tree->SetBranchAddress( "pass_massveto" , &pass_massveto ); tree->SetBranchAddress( "totCandidates" , &totCandidates ); tree->SetBranchAddress( "nCandidate" , &nCandidate ); map< ULong64_t, ULong64_t > multCandEventNumbers; cout << "Finding multiple candidates" << endl; // first loop tree and save number of all multiple candidates for ( int ev=0; ev<tree->GetEntries(); ev++ ) { tree->GetEntry(ev); if ( ev%10000==0 ) cout << ev << "/" << tree->GetEntries() << endl; //if ( itype>0 && pass_bdt && pass_pid && (!pass_rhokst) && (!pass_massveto) && totCandidates > 1 ) { if ( itype>0 && pass_bdt && pass_pid && (!pass_massveto) && totCandidates > 1 ) { multCandEventNumbers[eventNumber] = totCandidates; } } // now randomly select which one to keep map< ULong64_t, UInt_t > eventToKeep; TRandom3 rand; rand.SetSeed(2016); for ( map<ULong64_t,ULong64_t>::iterator it=multCandEventNumbers.begin(); it!=multCandEventNumbers.end(); it++) { UInt_t keep = rand.Integer( it->second ); eventToKeep[it->first] = keep; } cout << "Adding flag pass_multcand to tree" << endl; // then loop again and write the random choice back in bool pass_multcand; TBranch *bpt = tree->Branch( "pass_multcand", &pass_multcand, "pass_multcand/O" ); for ( int ev=0; ev<tree->GetEntries(); ev++ ) { tree->GetEntry(ev); if ( ev%10000==0 ) cout << ev << "/" << tree->GetEntries() << endl; pass_multcand = true; if ( totCandidates > 1 && eventToKeep[eventNumber] != nCandidate ) pass_multcand = false; bpt->Fill(); } tree->Write(); delete inFile; }
void TMVAClassificationApplication_new(TString myMethodList = "" , TString iFileName = "", TString bkgSample = "", TString sampleLocation = "", TString massPoint = "", TString oFileLocation = "") { #ifdef __CINT__ gROOT->ProcessLine( ".O0" ); // turn off optimization in CINT #endif //--------------------------------------------------------------- // This loads the library TMVA::Tools::Instance(); // Default MVA methods to be trained + tested std::map<std::string,int> Use; // --- Cut optimisation Use["Cuts"] = 0; Use["CutsD"] = 0; Use["CutsPCA"] = 0; Use["CutsGA"] = 0; Use["CutsSA"] = 0; // // // --- Boosted Decision Trees Use["BDT"] = 1; // uses Adaptive Boost std::cout << std::endl; std::cout << "==> Start TMVAClassificationApplication" << std::endl; // Select methods (don't look at this code - not of interest) if (myMethodList != "") { for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0; std::vector<TString> mlist = gTools().SplitString( myMethodList, ',' ); for (UInt_t i=0; i<mlist.size(); i++) { std::string regMethod(mlist[i]); if (Use.find(regMethod) == Use.end()) { std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl; for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) { std::cout << it->first << " "; } std::cout << std::endl; return; } Use[regMethod] = 1; } } // -------------------------------------------------------------------------------------------------- // --- Create the Reader object TMVA::Reader *reader = new TMVA::Reader("!Color:!Silent" ); TString weightTail = "_"; weightTail = weightTail + massPoint; // Create a set of variables and declare them to the reader // - the variable names MUST corresponds in name and type to those given in the weight file(s) used Float_t var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, var11, var12, var13, var14, var15, var16, var17, var18; reader->AddVariable( "svMass", &var1); reader->AddVariable( "dRTauTau", &var3 ); reader->AddVariable( "dRJJ", &var4 ); // reader->AddVariable( "svPt", &var5 ); // reader->AddVariable( "dRhh", &var6 ); reader->AddVariable( "met", &var7 ); reader->AddVariable( "mJJ", &var8 ); // reader->AddVariable( "metTau1DPhi", &var9 ); // reader->AddVariable( "metTau2DPhi", &var10); // reader->AddVariable( "metJ1DPhi", &var11); // reader->AddVariable( "metJ2DPhi", &var12 ); // reader->AddVariable( "metTauPairDPhi", &var13 ); // reader->AddVariable( "metSvTauPairDPhi", &var14 ); // reader->AddVariable( "metJetPairDPhi", &var15 ); // reader->AddVariable( "CSVJ1", &var16 ); // reader->AddVariable( "CSVJ2", &var17 ); reader->AddVariable( "fMassKinFit", &var2 ); reader->AddVariable( "chi2KinFit2", &var18 ); // Spectator variables declared in the training have to be added to the reader, too // Float_t spec1,spec2; // reader->AddSpectator( "spec1 := var1*2", &spec1 ); // reader->AddSpectator( "spec2 := var1*3", &spec2 ); // Float_t Category_cat1, Category_cat2, Category_cat3; // if (Use["Category"]){ // // Add artificial spectators for distinguishing categories // reader->AddSpectator( "Category_cat1 := var3<=0", &Category_cat1 ); // reader->AddSpectator( "Category_cat2 := (var3>0)&&(var4<0)", &Category_cat2 ); // reader->AddSpectator( "Category_cat3 := (var3>0)&&(var4>=0)", &Category_cat3 ); // } // --- Book the MVA methods // Book method(s) TString weightFileName = "/nfs_scratch/zmao/test/CMSSW_5_3_15/src/TMVA-v4.2.0/test/weights/TMVAClassification_BDT.weights_"; weightFileName += bkgSample; weightFileName += weightTail; reader->BookMVA("BDT method", weightFileName+".xml" ); // Book output histograms UInt_t nbin = 200; TH1F *histBdt(0); histBdt = new TH1F( "MVA_BDT", "MVA_BDT", nbin, -1.0, 1.0); // Prepare input tree (this must be replaced by your data source) // in this example, there is a toy tree with signal and one with background events // we'll later on use only the "signal" events for the test in this example. // TFile *input(0); TString fileName = iFileName; TString fname = sampleLocation; fname += fileName; TString oFileName = oFileLocation; oFileName += "ClassApp_" + bkgSample; oFileName += "_"; oFileName += fileName; if (!gSystem->AccessPathName( fname )) input = TFile::Open(fname); // check if file in local directory exists if (!input) { std::cout << "ERROR: could not open data file" << std::endl; exit(1); } std::cout << "--- TMVAClassificationApp : Using input file: " << input->GetName() << std::endl; // --- Event loop // Prepare the event tree // - here the variable names have to corresponds to your tree // - you can use the same variables as above which is slightly faster, // but of course you can use different ones and copy the values inside the event loop // std::cout << "--- Select signal sample" << std::endl; TTree* theTree = (TTree*)input->Get("eventTree"); TFile *target = new TFile( oFileName,"RECREATE" ); TTree *newTree = theTree->CloneTree(); Float_t BDT; TBranch *branchBDT = newTree->Branch("BDT_"+bkgSample,&BDT,"BDT/F"); std::vector<Double_t> *vecVar1; std::vector<Double_t> *vecVar5; std::vector<Double_t> *vecVar7; theTree->SetBranchAddress( "svMass", &vecVar1); theTree->SetBranchAddress( "dRTauTau", &var3); theTree->SetBranchAddress( "dRJJ", &var4 ); // theTree->SetBranchAddress( "svPt", &vecVar5 ); // theTree->SetBranchAddress( "dRhh", &var6 ); theTree->SetBranchAddress( "met", &vecVar7 ); theTree->SetBranchAddress( "mJJ", &var8 ); // theTree->SetBranchAddress( "metTau1DPhi", &var9 ); // theTree->SetBranchAddress( "metTau2DPhi", &var10); // theTree->SetBranchAddress( "metJ1DPhi", &var11); // theTree->SetBranchAddress( "metJ2DPhi", &var12 ); // theTree->SetBranchAddress( "metTauPairDPhi", &var13 ); // theTree->SetBranchAddress( "metSvTauPairDPhi", &var14 ); // theTree->SetBranchAddress( "metJetPairDPhi", &var15 ); // theTree->SetBranchAddress( "CSVJ1", &var16 ); // theTree->SetBranchAddress( "CSVJ2", &var17 ); theTree->SetBranchAddress( "fMassKinFit", &var2); theTree->SetBranchAddress( "chi2KinFit2", &var18); //to get initial pre-processed events TH1F* cutFlow = (TH1F*)input->Get("preselection"); // Efficiency calculator for cut method Int_t nSelCutsGA = 0; Double_t effS = 0.7; std::vector<Float_t> vecVar(4); // vector for EvaluateMVA tests std::cout << "--- Processing: " << theTree->GetEntries() << " events" << std::endl; TStopwatch sw; sw.Start(); for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) { if (ievt%1000 == 0) std::cout << "--- ... Processing event: " << ievt << std::endl; theTree->GetEntry(ievt); var1 = vecVar1->at(0); // var5 = vecVar5->at(0); var7 = vecVar7->at(0); // --- Return the MVA outputs and fill into histograms if (Use["CutsGA"]) { // Cuts is a special case: give the desired signal efficienciy Bool_t passed = reader->EvaluateMVA( "CutsGA method", effS ); if (passed) nSelCutsGA++; } BDT = reader->EvaluateMVA( "BDT method"); histBdt->Fill(BDT); branchBDT->Fill(); } // Get elapsed time sw.Stop(); std::cout << "--- End of event loop: "; sw.Print(); // Get efficiency for cuts classifier if (Use["CutsGA"]) std::cout << "--- Efficiency for CutsGA method: " << double(nSelCutsGA)/theTree->GetEntries() << " (for a required signal efficiency of " << effS << ")" << std::endl; if (Use["CutsGA"]) { // test: retrieve cuts for particular signal efficiency // CINT ignores dynamic_casts so we have to use a cuts-secific Reader function to acces the pointer TMVA::MethodCuts* mcuts = reader->FindCutsMVA( "CutsGA method" ) ; if (mcuts) { std::vector<Double_t> cutsMin; std::vector<Double_t> cutsMax; mcuts->GetCuts( 0.7, cutsMin, cutsMax ); std::cout << "--- -------------------------------------------------------------" << std::endl; std::cout << "--- Retrieve cut values for signal efficiency of 0.7 from Reader" << std::endl; for (UInt_t ivar=0; ivar<cutsMin.size(); ivar++) { std::cout << "... Cut: " << cutsMin[ivar] << " < \"" << mcuts->GetInputVar(ivar) << "\" <= " << cutsMax[ivar] << std::endl; } std::cout << "--- -------------------------------------------------------------" << std::endl; } } // --- Write histograms histBdt->Write(); cutFlow->Write(); newTree->Write(); target->Close(); std::cout << "--- Created root file: \""<<oFileName<<"\" containing the MVA output histograms" << std::endl; delete reader; std::cout << "==> TMVAClassificationApplication is done!" << endl << std::endl; }
//Arguments: a comma-separated list of energies, a comma-separated list of //beam heights. void CollectRuns(string Energies, string Heights){ vector<string> theEnergy; vector<string> theHeight; vector<double> valEnergy; vector<double> valHeight; string line; //Get the energies istringstream ssEn(Energies); //ssEn << (Energies); while(getline(ssEn, line, ',')){ theEnergy.push_back(line); //now cast line to a double: stringstream ss; double dummy; ss << line; ss >> dummy; valEnergy.push_back(dummy); } //Get the heights istringstream ssHgt(Heights); while(getline(ssHgt, line, ',')){ theHeight.push_back(line); //now cast line to a double: stringstream ss; double dummy; ss << line; ss >> dummy; valHeight.push_back(dummy); } //Initialise the output tree. TChain* OutChain = new TChain("ChainResults", "The collected run results"); for(size_t i=0; i<theEnergy.size(); i++){ for(size_t j=0; j<theHeight.size(); j++){ string fname = "Edep_" + theEnergy.at(i) + "MeV_" + theHeight.at(j) + "cm.root"; cout << "Processing File: " << fname << "... "; TFile* infile = TFile::Open(fname.c_str(), "update"); TTree* inTree = (TTree*)infile->Get("Results"); //Clean up any old branches... //TBranch* OldBranch; //if(inTree->GetListOfBranches()->FindObject("BeamEn")){ //OldBranch = inTree->GetBranch("BeamEn"); //inTree->GetListOfBranches()->Remove(OldBranch); //inTree->Write(); //} //if(inTree->GetListOfBranches()->FindObject("BeamHgt")){ //OldBranch = inTree->GetBranch("BeamHgt"); //inTree->GetListOfBranches()->Remove(OldBranch); //inTree->Write(); //} //if(inTree->GetListOfBranches()->FindObject("MeanPE_T1")){ //OldBranch = inTree->GetBranch("MeanPE_T1"); //inTree->GetListOfBranches()->Remove(OldBranch); //inTree->Write(); //} //if(inTree->GetListOfBranches()->FindObject("MeanPE_T2")){ //OldBranch = inTree->GetBranch("MeanPE_T2"); //inTree->GetListOfBranches()->Remove(OldBranch); //inTree->Write(); //} float BeamEn = 0; float BeamHgt = 0; float MeanT1 = 0; float MeanT2 = 0; //Add an energy and beam height branch to the tree. TBranch* EnBranch = inTree->Branch("BeamEn", &BeamEn, "BeamEn/F"); TBranch* HgtBranch = inTree->Branch("BeamHgt", &BeamHgt, "BeamHgt/F"); TBranch* MeanPE_T1 = inTree->Branch("MeanPE_T1", &MeanT1, "MeanPE_T1/F"); TBranch* MeanPE_T2 = inTree->Branch("MeanPE_T2", &MeanT2, "MeanPE_T2/F"); unsigned long long int measPE_T1 = 0; unsigned long long int measPE_T2 = 0; double Edep_H1 =0; double Edep_H2 = 0; inTree->SetBranchAddress("MeasNumPhotons_PMTT1", &measPE_T1); inTree->SetBranchAddress("MeasNumPhotons_PMTT2", &measPE_T2); inTree->SetBranchAddress("Edep_H1", &Edep_H1); inTree->SetBranchAddress("Edep_H2", &Edep_H2); Long64_t nentries = inTree->GetEntries(); int numAvg = 0; for(int k = 0; k<nentries; k++){ inTree->GetEntry(k); //Calculate means if((Edep_H1!=0)&&(Edep_H2!=0)){ MeanT1 += measPE_T1; MeanT2 += measPE_T2; numAvg++; } } MeanT1 = MeanT1/numAvg; MeanT2 = MeanT2/numAvg; for(int k = 0; k<nentries; k++){ BeamEn = valEnergy.at(i); BeamHgt = valHeight.at(j); EnBranch->Fill(); HgtBranch->Fill(); MeanPE_T1->Fill(); MeanPE_T2->Fill(); } inTree->Write("", TObject::kOverwrite); fname = fname + "/Results"; OutChain->Add(fname.c_str()); infile->Close(); cout << "Done!" << endl; } } cout << "OutChain has " << OutChain->GetEntries() << " entries." << endl; TFile* OutFile = new TFile("ChainedRuns.root", "RECREATE"); OutChain->Write(); OutFile->Close(); return; }
int mergeDigits(TString digitdir, Int_t /*simEvOffset*/) { AliRunLoader *rl = AliRunLoader::Open(digitdir+TString("/galice.root")); AliPHOSLoader *prl = (AliPHOSLoader*)rl->GetDetectorLoader("PHOS"); prl->LoadDigits("UPDATE"); //prl->LoadDigits(); Int_t nEvents = rl->GetNumberOfEvents(); TClonesArray *mydigits = 0; simTree->SetBranchAddress("Digits", &mydigits); Int_t nDigits = 0; Int_t nEmbedDigits = 0; Int_t nOverlappingDigits = 0; Int_t nNewDigits = 0; Int_t nPhosDigits = prl->Digits()->GetEntries(); Int_t nMyEvents = simTree->GetEntries(); std::cout << "Number of real events: " << nEvents << std::endl; std::cout << "Number of sim events: " << nMyEvents << std::endl; nEvents = TMath::Min(nEvents, nMyEvents); std::cout << "Looping over: " << nEvents << std::endl; for (Int_t ev = 0; ev < nEvents; ev++) { rl->GetEvent(ev); simTree->GetEntry(ev); Int_t nMyDigits = mydigits->GetEntries(); //Int_t nDigsFound = 0; nEmbedDigits += nMyDigits; TClonesArray *phosDigits = prl->Digits(); nPhosDigits = prl->Digits()->GetEntries(); for (Int_t iDig = 0; iDig < nPhosDigits; iDig++) { //const AliPHOSDigit *digit = prl->Digit(iDig); AliPHOSDigit *digit = (AliPHOSDigit*)phosDigits->At(iDig); nDigits++; for (Int_t n = 0; n < nMyDigits; n++) { AliPHOSDigit *myDigit = (AliPHOSDigit*)mydigits->At(n); if (digit->GetId() == myDigit->GetId()) { nOverlappingDigits++; break; } } } if(nOverlappingDigits == nMyDigits) { std::cout << "Digits alredy embedded!" << std::endl; continue; } for (Int_t iDig = 0; iDig < nMyDigits; iDig++) { AliPHOSDigit *myDigit = (AliPHOSDigit*)mydigits->At(iDig); if (myDigit) { for (Int_t n = 0; n < nPhosDigits; n++) { //const AliPHOSDigit *digit = prl->Digit(n); AliPHOSDigit *digit = (AliPHOSDigit*)phosDigits->At(n); if (digit->GetId() == myDigit->GetId()) { digit->SetALTROSamplesHG(0, 0); digit->SetALTROSamplesLG(0, 0); *digit += *myDigit; myDigit = 0; break; } } if (myDigit) { TClonesArray *digArray = prl->Digits(); AliPHOSDigit *newDig = new((*digArray)[nPhosDigits+nNewDigits]) AliPHOSDigit(*myDigit); newDig->SetALTROSamplesHG(0, 0); newDig->SetALTROSamplesLG(0, 0); nNewDigits++; } } } phosDigits->Compress(); Int_t ndigits = phosDigits->GetEntries() ; phosDigits->Sort(); // Remove digits that are flagged bad in BCM. Then remove digits that are below threshold for (Int_t i = 0 ; i < ndigits ; i++) { AliPHOSDigit *digit = static_cast<AliPHOSDigit*>( phosDigits->At(i) ) ; //std::cout << digit->GetId() << std::endl; if(digit->GetId()) { vector<Int_t>::iterator it; it = std::find (badChannels.begin(), badChannels.end(), digit->GetId() ); if(*it) { digit->SetEnergy(0.0); } } if(digit->GetEnergy() <= recoParam->GetGlobalAltroThreshold()) { phosDigits->RemoveAt(i); } } //Set indexes in list of digits and make true digitization of the energy phosDigits->Compress(); phosDigits->Sort(); ndigits = phosDigits->GetEntries(); for (Int_t i = 0 ; i < ndigits ; i++) { AliPHOSDigit *digit = static_cast<AliPHOSDigit*>( phosDigits->At(i) ) ; digit->SetIndexInList(i) ; } // -- create Digits branch Int_t bufferSize = 32000 ; TObjArray *branchList = prl->TreeD()->GetListOfBranches(); branchList->RemoveAt(0); TBranch * digitsBranch = prl->TreeD()->Branch("PHOS","TClonesArray",&phosDigits,bufferSize); digitsBranch->Fill() ; prl->WriteDigits("OVERWRITE"); } prl->WriteDigits("OVERWRITE"); std::cout << "# Digits: " << nDigits << std::endl; std::cout << "# Embedded digits: " << nEmbedDigits << std::endl; std::cout << "# Overlapping digits: " << nOverlappingDigits << std::endl; std::cout << "# New digits: " << nNewDigits << std::endl; return 0; }
int weighPthat(TString ifname = "/data/wangj/MC2015/Dntuple/pp/ntD_pp_Dstar_D0kpi/ntD_EvtBase_20160112_Dfinder_20151229_pp_Pythia8D0kpi_noweight.root", TString ofname = "/afs/cern.ch/work/w/wangj/public/RunII/weighPthat/ntD_EvtBase_20160112_Dfinder_20151229_pp_Pythia8D0kpi_withweight.root") { Bool_t isInsidebin(Float_t xpthat, Int_t i); cout<<endl; cout<<" -- Checking if input and output files are same"<<endl; if(ifname==ofname) { cout<<" Error: Input file will be overwritten."<<endl; return 0; } cout<<" -- Opening unweighed sample"<<endl; TFile* inf = TFile::Open(ifname); TTree* ntHi = (TTree*)inf->Get("ntHi"); Float_t pthat; ntHi->SetBranchAddress("pthat",&pthat); Float_t weight[nBins],nweight[nBins]; for(Int_t j=0; j<nBins; j++) { weight[j]=0; nweight[j]=0; } Int_t nentries = ntHi->GetEntries(); cout<<" -- Calculating weights"<<endl; for(Int_t i=0; i<nentries; i++) { ntHi->GetEntry(i); if(i%100000==0) cout<<" Processing event "<<setiosflags(ios::left)<<setw(7)<<i<<" / "<<nentries<<endl; for(Int_t j=0; j<nBins; j++) { if(isInsidebin(pthat,j)) nweight[j]++; } } cout<<" -- Weight results"<<endl; for(Int_t j=0; j<nBins; j++) { if(nweight[j]==0) { cout<<" Error: Weight fails."<<endl; return 0; } weight[j] = (crosssec[j]-crosssec[j+1])/nweight[j]; cout<<" Pthat"<<setiosflags(ios::left)<<setw(3)<<pthatBin[j]<<": "<<weight[j]<<endl; } cout<<" -- Building weight branch"<<endl; TFile* otf = TFile::Open(ofname,"update"); TTree* ntHinew = (TTree*)otf->Get("ntHi"); Float_t pthatweight; TBranch* newBranch = ntHinew->Branch("pthatweight", &pthatweight, "pthatweight/F"); cout<<" -- Filling weight branch"<<endl; for(Int_t i=0; i<nentries; i++) { ntHi->GetEntry(i); if(i%100000==0) cout<<" Processing event "<<setiosflags(ios::left)<<setw(7)<<i<<" / "<<nentries<<endl; pthatweight=0; for(Int_t j=0; j<nBins; j++) { if(isInsidebin(pthat,j)) pthatweight = weight[j]; } newBranch->Fill(); } ntHinew->Write("", TObject::kOverwrite); cout<<" -- End"<<endl; cout<<endl; return 1; }
void TMVAClassificationApplication_cc1pcoh_bdt_ver3noveractFFFSI( TString myMethodList = "", TString fname) { #ifdef __CINT__ gROOT->ProcessLine( ".O0" ); // turn off optimization in CINT #endif //--------------------------------------------------------------- // This loads the library TMVA::Tools::Instance(); // Default MVA methods to be trained + tested std::map<std::string,int> Use; // // --- Boosted Decision Trees Use["BDT"] = 1; // uses Adaptive Boost std::cout << std::endl; std::cout << "==> Start TMVAClassificationApplication" << std::endl; // Select methods (don't look at this code - not of interest) if (myMethodList != "") { for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0; std::vector<TString> mlist = gTools().SplitString( myMethodList, ',' ); for (UInt_t i=0; i<mlist.size(); i++) { std::string regMethod(mlist[i]); if (Use.find(regMethod) == Use.end()) { std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl; for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) { std::cout << it->first << " "; } std::cout << std::endl; return; } Use[regMethod] = 1; } } // -------------------------------------------------------------------------------------------------- // --- Create the Reader object TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" ); // Create a set of variables and declare them to the reader // - the variable names MUST corresponds in name and type to those given in the weight file(s) used Float_t mumucl, pmucl; Float_t pang_t, muang_t; Float_t veract; Float_t ppe, mupe; Float_t range, coplanarity; Float_t opening;//newadd reader->AddVariable( "mumucl", &mumucl ); reader->AddVariable( "pmucl", &pmucl ); reader->AddVariable( "pang_t", &pang_t ); reader->AddVariable( "muang_t", &muang_t ); //reader->AddVariable( "veract", &veract ); reader->AddVariable( "ppe", &ppe); reader->AddVariable( "mupe", &mupe); reader->AddVariable( "range", &range); reader->AddVariable( "coplanarity", &coplanarity); reader->AddVariable( "opening", &opening);//newadd // Spectator variables declared in the training have to be added to the reader, too Int_t fileIndex, inttype; Float_t nuE, norm, totcrsne; reader->AddSpectator( "fileIndex", &fileIndex ); reader->AddSpectator( "nuE", &nuE ); reader->AddSpectator( "inttype", &inttype ); reader->AddSpectator( "norm", &norm ); reader->AddSpectator( "totcrsne", &totcrsne ); reader->AddSpectator( "veract", &veract ); // --- Book the MVA methods TString dir = "weights/"; TString prefix = "TMVAClassification_ver3noveractFFFSI";//newchange // Book method(s) for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) { if (it->second) { TString methodName = TString(it->first) + TString(" method"); TString weightfile = dir + prefix + TString("_") + TString(it->first) + TString(".weights.xml"); reader->BookMVA( methodName, weightfile ); } } // Prepare input tree (this must be replaced by your data source) // in this example, there is a toy tree with signal and one with background events // we'll later on use only the "signal" events for the test in this example. // //for prange/pang_t corrected and other information included //TString fname = "/home/cvson/scraid2/cc1picoh/FIT/datafsi/datamc_merged_ccqe_addpidFFnew.root"; //TString fname = "/home/cvson/scraid2/cc1picoh/FIT/datafsi/datamc_genie_merged_ccqe_addpidFFnew.root"; //TString fname = "/home/cvson/scraid2/cc1picoh/FIT/datafsi/mc_merged_ccqe_addpidFFnew.root"; //TString fname = "/home/cvson/scraid2/cc1picoh/FIT/datafsi/mcgenie_merged_ccqe_tot_addpidFFnew.root"; //TString fname = "/home/cvson/scraid2/cc1picoh/FIT/datafsi/merged_ccqe_forResponseFunction.root"; //TString fname = "/home/cvson/scraid2/cc1picoh/FIT/datafsi/pmnue_merged_ccqe_tot_addpidFFnew.root"; std::cout << "--- Selecting data sample" << std::endl; TFile *pfile = new TFile(fname,"update"); TTree* theTree = (TTree*)pfile->Get("tree"); theTree->SetBranchAddress( "mumucl", &mumucl ); theTree->SetBranchAddress( "pmucl", &pmucl ); theTree->SetBranchAddress( "pang_t", &pang_t ); theTree->SetBranchAddress( "muang_t", &muang_t ); theTree->SetBranchAddress( "veract", &veract ); theTree->SetBranchAddress( "ppe", &ppe); theTree->SetBranchAddress( "mupe", &mupe); theTree->SetBranchAddress( "range", &range); theTree->SetBranchAddress( "coplanarity", &coplanarity); theTree->SetBranchAddress( "opening", &opening); Int_t Ntrack; theTree->SetBranchAddress( "Ntrack", &Ntrack ); Float_t pidfsi; TBranch *bpidfsi = theTree->Branch("pidfsi",&pidfsi,"pidfsi/F"); std::vector<Float_t> vecVar(9); // vector for EvaluateMVA tests Long64_t nentries = theTree->GetEntriesFast(); Long64_t iprintProcess = Long64_t(nentries/100.); std::cout << "--- Processing: " << nentries << " events" << std::endl; TStopwatch sw; sw.Start(); for (Long64_t ievt=0; ievt<nentries;ievt++) { if (ievt%iprintProcess == 0) cout<<"Processing "<<int(ievt*100./nentries)<<"% of events"<<endl; theTree->GetEntry(ievt); Float_t pidfsi_tem; if (Use["BDT"]) { //if (Ntrack!=2) pidfsi_tem = -999;//changehere if (Ntrack<2) pidfsi_tem = -999; else pidfsi_tem = reader->EvaluateMVA("BDT method"); } pidfsi = pidfsi_tem; bpidfsi->Fill(); } theTree->Write(); delete pfile; // Get elapsed time sw.Stop(); std::cout << "--- End of event loop: "; sw.Print(); delete reader; std::cout << "==> TMVAClassificationApplication is done!" << endl << std::endl; }
void makeJetP4(TString InRootFile, double Rparam=0.5) { cout << " ... Processing file = " << InRootFile << endl; cout << " ... Rparam = " << Rparam << endl; cout << " ................................................................." << endl; // // Get tree from a cfA ntuple // TFile *f = TFile::Open("../cfA/"+InRootFile, "UPDATE"); TDirectory* dir = f->GetDirectory("configurableAnalysis"); dir->cd(); TTree *eventB = (TTree*)dir->Get("eventB"); // // set address of variables to read // UInt_t event_ = 0; eventB->SetBranchAddress("event", &event_); UInt_t run_ = 0; eventB->SetBranchAddress("run", &run_); UInt_t lumiblock_ = 0; eventB->SetBranchAddress("lumiblock", &lumiblock_); vector<float> *fastjets_AK5PF_px_ = 0; eventB->SetBranchAddress("jets_AK5PF_px", &fastjets_AK5PF_px_); vector<float> *fastjets_AK5PF_py_ = 0; eventB->SetBranchAddress("jets_AK5PF_py", &fastjets_AK5PF_py_); vector<float> *fastjets_AK5PF_pz_ = 0; eventB->SetBranchAddress("jets_AK5PF_pz", &fastjets_AK5PF_pz_); vector<float> *fastjets_AK5PF_energy_ = 0; eventB->SetBranchAddress("jets_AK5PF_energy", &fastjets_AK5PF_energy_); vector<float> *fastjets_AK5PF_phi_ = 0; eventB->SetBranchAddress("jets_AK5PF_phi", &fastjets_AK5PF_phi_); vector<float> *fastjets_AK5PF_eta_ = 0; eventB->SetBranchAddress("jets_AK5PF_eta", &fastjets_AK5PF_eta_); // // Define new variables to write // // need this line because ROOT does not know vector<float> // one needs to generate dictionary using rootcint or // just include this line // [ref] http://root.cern.ch/phpBB3/viewtopic.php?t=8467 gROOT->ProcessLine("#include <vector>"); vector<float> *fastjets_AK5PF_R1p2_px = 0; TBranch *pxb = eventB->Branch(Form("fastjets_AK5PF_R1p2_pT%i_px",R0p5JetpTcut), &fastjets_AK5PF_R1p2_px); vector<float> *fastjets_AK5PF_R1p2_py = 0; TBranch *pyb = eventB->Branch(Form("fastjets_AK5PF_R1p2_pT%i_py",R0p5JetpTcut), &fastjets_AK5PF_R1p2_py); vector<float> *fastjets_AK5PF_R1p2_pz = 0; TBranch *pzb = eventB->Branch(Form("fastjets_AK5PF_R1p2_pT%i_pz",R0p5JetpTcut), &fastjets_AK5PF_R1p2_pz); vector<float> *fastjets_AK5PF_R1p2_energy = 0; TBranch *energyb = eventB->Branch(Form("fastjets_AK5PF_R1p2_pT%i_energy",R0p5JetpTcut), &fastjets_AK5PF_R1p2_energy); vector<float> *fastjets_AK5PF_R1p2_phi = 0; TBranch *phib = eventB->Branch(Form("fastjets_AK5PF_R1p2_pT%i_phi",R0p5JetpTcut), &fastjets_AK5PF_R1p2_phi); vector<float> *fastjets_AK5PF_R1p2_eta = 0; TBranch *etab = eventB->Branch(Form("fastjets_AK5PF_R1p2_pT%i_eta",R0p5JetpTcut), &fastjets_AK5PF_R1p2_eta); // // Histgrom : to draw eta-phi plot of energy deposit // (1) Bin size is 0.087x0.087 to mimic the size of hcal tower // (2) Bin Entry is the sum over energies of PF candidates in a given bin // TH2F *h2 = new TH2F("h2","h2", 115, -5.0, 5.0, 72, -3.141592, 3.141592); // // Loop over entries // Int_t nentries = (Int_t)eventB->GetEntries(); if(DEBUG) nentries = 10; cout<<"The number of entries is: "<<nentries<<endl; // main event loop for(int ib = 0; ib<nentries; ib++) { // Counting to see progress if(ib%100==0) cout << " ...... " << ib << " events processed "<< endl; // get the entry of event ib eventB->GetEntry(ib); // --------------------------------------- // Block 1 // --------------------------------------- // Open a text file to write information about PF candidates ofstream fout; fout.open(Form("OneEvent_FastjetsR0p5_tmp_%i.dat", ib)); // loop over Fastjets with R=0.5 for(int ifastjets = 0; ifastjets < (int)fastjets_AK5PF_px_->size(); ifastjets++) { if(TMath::Sqrt( fastjets_AK5PF_px_->at(ifastjets)*fastjets_AK5PF_px_->at(ifastjets) +fastjets_AK5PF_py_->at(ifastjets)*fastjets_AK5PF_py_->at(ifastjets)) < R0p5JetpTcut) continue; fout.width(15); fout << fastjets_AK5PF_px_->at(ifastjets) << "\t"; fout.width(15); fout << fastjets_AK5PF_py_->at(ifastjets) << "\t"; fout.width(15); fout << fastjets_AK5PF_pz_->at(ifastjets) << "\t"; fout.width(15); fout << fastjets_AK5PF_energy_->at(ifastjets) << endl; float pt = TMath::Sqrt(fastjets_AK5PF_px_->at(ifastjets)*fastjets_AK5PF_px_->at(ifastjets) +fastjets_AK5PF_py_->at(ifastjets)*fastjets_AK5PF_py_->at(ifastjets)); h2->Fill( fastjets_AK5PF_eta_->at(ifastjets), fastjets_AK5PF_phi_->at(ifastjets), pt); } fout.close(); // --------------------------------------- // Block 2 // --------------------------------------- // // Run Fastjet to reconstuct jets // // Using the example code "fastjet_example.cc" // It takes OneEvent_PFCands_tmp_%i.dat as an input // and writes p4 of reconstructed jets in OneEvent_PFJets_tmp_%i.dat. // For the details about the code, take a look at fastjet_example.cc. gSystem->Exec(Form("../fastjet_example %f < OneEvent_FastjetsR0p5_tmp_%i.dat > OneEvent_FastjetsR1p2_tmp_%i.dat", Rparam, ib, ib)); // --------------------------------------- // Block 3 // --------------------------------------- // // Get p4 of the reconstructed jets // string line; double id, px, py , pz, energy, eta, phi, ncand; ifstream fin(Form("OneEvent_FastjetsR1p2_tmp_%i.dat", ib)); if(fin.is_open()) { while(fin.good()){ // get a line from fin getline(fin, line); if(line=="") break; // need this to avoid line without entry // Store each element in the line to the defined variables stringstream stream(line); stream >> id >> px >> py >> pz >> energy >> eta >> phi >> ncand; // store only when pT > 3 GeV // (same as CMS jet reconstruction cut) if(TMath::Sqrt(px*px+py*py)>(DEBUG?30:3)) { fastjets_AK5PF_R1p2_px->push_back(px); fastjets_AK5PF_R1p2_py->push_back(py); fastjets_AK5PF_R1p2_pz->push_back(pz); fastjets_AK5PF_R1p2_energy->push_back(energy); fastjets_AK5PF_R1p2_eta->push_back(eta); fastjets_AK5PF_R1p2_phi->push_back(phi); if(DEBUG) { cout << event_ << " " << id << " " << TMath::Sqrt(px*px+py*py) << " " << eta << " " << phi << " " << endl; } } } } // Fill the branches pxb->Fill(); pyb->Fill(); pzb->Fill(); energyb->Fill(); phib->Fill(); etab->Fill(); // // Draw a lego plot (eta, phi) // if(DEBUG) { TCanvas *c = new TCanvas(); c->cd(1); h2->Draw("colz"); h2->SetTitle(Form("run=%i lumi=%i event=%i R=%.1f", run_, lumiblock_, event_, Rparam)); h2->SetMaximum(50); h2->SetStats(0); h2->SetXTitle("#eta"); h2->SetYTitle("#phi"); //Draw circles around jets TEllipse *cone[fastjets_AK5PF_R1p2_eta->size()]; for(int ijets=0; ijets<(int)fastjets_AK5PF_R1p2_eta->size(); ijets++){ cone[ijets] = new TEllipse(fastjets_AK5PF_R1p2_eta->at(ijets), fastjets_AK5PF_R1p2_phi->at(ijets), Rparam, Rparam); cone[ijets]->SetFillStyle(3003); cone[ijets]->SetFillColor(kYellow); cone[ijets]->Draw(); } c->SaveAs(Form("EtaPhiViewPFCand_Run%i_Lumi%i_Event%i_R%.1f_usingR0p5.pdf", run_, lumiblock_, event_, Rparam)); h2->Reset(); for(int ijets=0; ijets<(int)fastjets_AK5PF_R1p2_eta->size(); ijets++) delete cone[ijets]; } // Clear vectors for the next event fastjets_AK5PF_R1p2_px->clear(); fastjets_AK5PF_R1p2_py->clear(); fastjets_AK5PF_R1p2_pz->clear(); fastjets_AK5PF_R1p2_energy->clear(); fastjets_AK5PF_R1p2_eta->clear(); fastjets_AK5PF_R1p2_phi->clear(); // remove text files if(!DEBUG) gSystem->Exec("'rm' OneEvent_Fastjets*.dat"); } // event loop // update the tree and close file if(!DEBUG) eventB->Write(); f->Close(); // // cleanup // delete f; }