void PlotParsDistr(TFile* f, TTree* tr, TString strMillepedeRes, TString strOutdir) { for (int isubd=PXB; isubd<=TEC; isubd++){ TString canvName="c_"; canvName+=strMillepedeRes; canvName+="_"; canvName+=StrPlotType(PARS); canvName+="_"; canvName+=subdLabels[isubd]; canvName.ReplaceAll(".res",""); f->cd(); TCanvas* canv = new TCanvas(canvName,canvName,600,600); canv->Divide(3,3); for (int parInd=1; parInd<=9; parInd++){ canv->cd(parInd); TString strCut="((label%20-1)%9+1)=="; strCut+=parInd; strCut+=" && label<700000 && "; strCut+=StrCutSubd(isubd); TString hName="hPars_"; hName+=subdLabels[isubd]; hName+="_"; hName+= StrPar(parInd); TTree* trCut = tr->CopyTree(strCut); float up = trCut->GetMaximum("parVal"); float low = trCut->GetMinimum("parVal"); std::cout<<"low="<<low<<", up="<<up<<", nent="<<trCut->GetEntries()<<std::endl; TH1F* h = new TH1F(hName,hName,100,10000*low,10000*up); TString strDraw="10000*parVal>>"; strDraw+=hName; trCut->Draw(strDraw,strCut,"goff"); h->SetMarkerStyle(2); h->Draw("EP"); }// end of loop over parInd canvName+=".png"; TString saveName=strOutdir+canvName; canv->SaveAs(saveName); saveName.ReplaceAll(".png",".pdf"); canv->SaveAs(saveName); }//end of loop over isubd }// end of PlotParsDistr
TGraphErrors* PlotLightYieldGraph() { string filename; vector<double> x,y,ex,ey; while(1){ cout<<"\n\nEnter next file to process; <enter> to finish."<<endl; getline(cin, filename); if(filename=="") break; //load the tree TTree* Events = GetEventsTree(filename.c_str()); if(!Events) continue; gROOT->ProcessLine(".x analysis/Aliases.C"); double start = Events->GetMinimum("timestamp"); double end = Events->GetMaximum("timestamp"); double error = 0; TString title = TString("Na22 Spectrum, ") + TString(filename)(TRegexp("Run......")); TH1F* hist = new TH1F("Na22Spec",title,200,1000,2500); Events->Draw("sumspec >> Na22Spec","min > 0","e"); double yield = Fit511Photopeak(hist,&error); x.push_back((start+end)/2.); ex.push_back((end-start)/2.); y.push_back(yield); ey.push_back(error); } if(x.size() == 0){ cerr<<"No valid points found!"<<endl; return 0; } TGraphErrors* graph = new TGraphErrors(x.size(),&x[0],&y[0],&ex[0],&ey[0]); graph->Draw("ape"); TAxis* xax = graph->GetXaxis(); xax->SetTitle("Run Time"); xax->SetTimeDisplay(1); xax->SetTimeFormat("%Y/%m/%d"); xax->SetTimeOffset(1,"gmt"); TAxis* yax = graph->GetYaxis(); yax->SetTitle("511 keV Light Yield [pe/keV]"); graph->Draw("ape"); return graph; }
void makePlotWithSelection(TTree* tr, TString varToPlot, TString canvName, TString xAxisName, TCut cutLoose, TCut cutAdditional) { TTree* trCutted = tr->CopyTree(cutLoose); TH1D* histLoose = new TH1D("hist",varToPlot,50,trCutted->GetMinimum(varToPlot)-0.1*fabs(trCutted->GetMinimum(varToPlot)),trCutted->GetMaximum(varToPlot)+0.1*fabs(trCutted->GetMaximum(varToPlot))); trCutted->Draw(varToPlot+TString(">>hist"),"1","goff"); TCanvas* canv = new TCanvas(canvName,canvName); //TAxis* xAxis = histLoose->GetXaxis(); histLoose->GetXaxis()->SetTitle(xAxisName); histLoose->GetYaxis()->SetRangeUser(0,histLoose->GetMaximumStored()); histLoose->SetFillStyle(3004); histLoose->SetFillColor(2); histLoose->Draw(); trCutted->SetFillStyle(1001); trCutted->SetFillColor(3); trCutted->Draw(varToPlot,cutAdditional,"same"); canv->SaveAs(canvName+".png"); delete histLoose; histLoose=0; trCutted=0; //xAxis=0; }
void paracoor( TString fin = "TMVA.root", Bool_t useTMVAStyle = kTRUE ) { // set style and remove existing canvas' TMVAGlob::Initialize( useTMVAStyle ); // checks if file with name "fin" is already open, and if not opens one TFile* file = TMVAGlob::OpenFile( fin ); TTree* tree = (TTree*)file->Get("TestTree"); if(!tree) { cout << "--- No TestTree saved in ROOT file. Parallel coordinates will not be plotted" << endl; return; } // first get list of leaves in tree TObjArray* leafList = tree->GetListOfLeaves(); vector<TString> vars; vector<TString> mvas; for (Int_t iar=0; iar<leafList->GetSize(); iar++) { TLeaf* leaf = (TLeaf*)leafList->At(iar); if (leaf != 0) { TString leafName = leaf->GetName(); if (leafName != "type" && leafName != "weight" && leafName != "boostweight" && leafName != "class" && leafName != "className" && leafName != "classID" && !leafName.Contains("prob_")) { // is MVA ? if (TMVAGlob::ExistMethodName( leafName )) { mvas.push_back( leafName ); } else { vars.push_back( leafName ); } } } } cout << "--- Found: " << vars.size() << " variables" << endl; cout << "--- Found: " << mvas.size() << " MVA(s)" << endl; TString type[2] = { "Signal", "Background" }; const Int_t nmva = mvas.size(); TCanvas* csig[nmva]; TCanvas* cbkg[nmva]; for (Int_t imva=0; imva<mvas.size(); imva++) { cout << "--- Plotting parallel coordinates for : " << mvas[imva] << " & input variables" << endl; for (Int_t itype=0; itype<2; itype++) { // create draw option TString varstr = mvas[imva] + ":"; for (Int_t ivar=0; ivar<vars.size(); ivar++) varstr += vars[ivar] + ":"; varstr.Resize( varstr.Last( ':' ) ); // create canvas TString mvashort = mvas[imva]; mvashort.ReplaceAll("MVA_",""); TCanvas* c1 = (itype == 0) ? csig[imva] : cbkg[imva]; c1 = new TCanvas( Form( "c1_%i",itype ), Form( "Parallel coordinate representation for %s and input variables (%s events)", mvashort.Data(), type[itype].Data() ), 50*(itype), 50*(itype), 750, 500 ); tree->Draw( varstr.Data(), Form("classID==%i",1-itype) , "para" ); c1->ToggleEditor(); gStyle->SetOptTitle(0); TParallelCoord* para = (TParallelCoord*)gPad->GetListOfPrimitives()->FindObject( "ParaCoord" ); TParallelCoordVar* mvavar = (TParallelCoordVar*)para->GetVarList()->FindObject( mvas[imva] ); Double_t minrange = tree->GetMinimum( mvavar->GetName() ); Double_t maxrange = tree->GetMaximum( mvavar->GetName() ); Double_t width = 0.2*(maxrange - minrange); Double_t x1 = minrange, x2 = x1 + width; TParallelCoordRange* parrange = new TParallelCoordRange( mvavar, x1, x2 ); parrange->SetLineColor(4); mvavar->AddRange( parrange ); para->AddSelection("-1"); for (Int_t ivar=1; ivar<TMath::Min(Int_t(vars.size()) + 1,3); ivar++) { TParallelCoordVar* var = (TParallelCoordVar*)para->GetVarList()->FindObject( vars[ivar] ); minrange = tree->GetMinimum( var->GetName() ); maxrange = tree->GetMaximum( var->GetName() ); width = 0.2*(maxrange - minrange); switch (ivar) { case 0: { x1 = minrange; x2 = x1 + width; break; } case 1: { x1 = 0.5*(maxrange + minrange - width)*0.02; x2 = x1 + width*0.02; break; } case 2: { x1 = maxrange - width; x2 = x1 + width; break; } } parrange = new TParallelCoordRange( var, x1, x2 ); parrange->SetLineColor( ivar == 0 ? 2 : ivar == 1 ? 5 : 6 ); var->AddRange( parrange ); para->AddSelection( Form("%i",ivar) ); } c1->Update(); TString fname = Form( "plots/paracoor_c%i_%s", imva, itype == 0 ? "S" : "B" ); TMVAGlob::imgconv( c1, fname ); } } }
//-------------------------------------- void FBI3D(TString namefile="", TString namefile2=""){ Int_t MaxNCoinc = 9e7; Int_t* POS = (Int_t*)malloc(MaxNCoinc*sizeof(Int_t)); FILE* fichero; FILE* fichero2; cout << namefile<<" "<<namefile2<<endl; // === STEP 1 === NORMALIZATION ================ if (namefile2=="normf.raw"){ // Allows reusing previous normalization image cout << "Using precalculated Normalization file" << endl; fichero2 = fopen(namefile2,"rb"); fread(SENS,sizeof(float),nvoxels,fichero2); fclose(fichero2); }else{ // Create normalization from ROOT file (filtered to reduce noise) int nt = 10; // Number of filter iterations SENS = normalization(namefile2,nt); // Storing the normalization image so that it can be used for other reconstructions of this scanner fichero2 = fopen("normf.raw","wb"); fwrite(SENS,sizeof(float),nvoxels,fichero2); fclose(fichero2); } // === STEP 2 === READ ROOT FILE ====== int posic; TFile *f1 = new TFile(namefile,"READ"); TTree *Coincidences = (TTree*)f1->Get("Coincidences"); ncoinc = Coincidences->GetEntries(); cout << "Simulated Coincidences = " << ncoinc << endl; define_branches(Coincidences); Scanner = (Coincidences->GetMaximum("globalPosX1")) - (Coincidences->GetMinimum("globalPosX1")); // Diameter of the scanner from the detected counts FOV_Z = (Coincidences->GetMaximum("globalPosZ1")) - (Coincidences->GetMinimum("globalPosZ1")); dz = float(NZS)/FOV_Z; // === STEP 3 === REFERENCE IMAGE (OPTIONAL) ==== for(Int_t iV=0; iV<nvoxels ; iV++){IMG_N[iV]=0.;} // Initial Image for(Int_t ic = 0; ic <= ncoinc; ic++){ // Coincidences->GetEntry(ic); ix = int(source_X*dxy + RESM); iy = int(source_Y*dxy + RESM); iz = int(source_Z*dz + NZM); if (ix>=0 && ix<RES && iy>=0 && iy<RES && iz>=0 && iz<NZS){ // Check voxel valid iV = iz*RES*RES+iy*RES+ix; IMG_N[iV]++; } } fichero = fopen("image_ref.raw","wb"); fwrite(IMG_N,sizeof(float),nvoxels,fichero); fclose(fichero); Float_t sens_corr = 0.; for(Int_t iV=0; iV<nvoxels ; iV++){ sens_corr = SENS[iV]; if (sens_corr>0){sens_corr = 1.0/sens_corr;} IMG_N[iV]*=sens_corr; } // Reference image corrected by sensitivity fichero = fopen("image_ref_senscor.raw","wb"); fwrite(IMG_N,sizeof(float),nvoxels,fichero); fclose(fichero); // === STEP 4 === INITIAL IMAGE ================ for(Int_t iV=0; iV<nvoxels ; iV++){IMG[iV]=0;} // Initial Image for(Int_t iV=0; iV<ncoinc; iV++){POS[iV]=-1;} // Initial Position // === STEP 5 === ITERATIONS ================== for(Int_t iter=1; iter<=niter ; iter++){ // Iterations (1 iteration consists of a whole loop over all data) for(Int_t ic = 0; ic<ncoinc; ic++){ Coincidences->GetEntry(ic); if ( ic % 100000 == 0 ) cout << "Iter= " << iter << " Processing " << ic << " coincidences " << endl; posic = POS[ic]; POS[ic] = Arek(posic,det1_X,det1_Y,det1_Z,det2_X,det2_Y,det2_Z,IMG,SENS); } // COINCIDENCES } // ITERATIONS f1->Close(); fichero = fopen("image.raw","wb"); if(fichero){ fwrite(IMG,sizeof(int),nvoxels,fichero); fclose(fichero); } // === STEP 6 === FINAL SENSITIVY NORMALIZATION ==== for(Int_t iV=0; iV<nvoxels ; iV++){ if (SENS[iV]>0){ IMG_N[iV] = float(IMG[iV])/SENS[iV]; }else{ IMG_N[iV] = 0.; } } fichero = fopen("image_norm.raw","wb"); if(fichero){ fwrite(IMG_N,sizeof(float),nvoxels,fichero); fclose(fichero); } IMG_N = MedianIMG(IMG_N); fichero = fopen("image_norm_med.raw","wb"); if(fichero){ fwrite(IMG_N,sizeof(float),nvoxels,fichero); fclose(fichero); } } // END
void PlotDecisionBoundary( TString weightFile = "weights/TMVAClassification_BDT.weights.xml",TString v0="var0", TString v1="var1", TString dataFileName = "/home/hvoss/TMVA/TMVA_data/data/data_circ.root") { //--------------------------------------------------------------- // default MVA methods to be trained + tested // this loads the library TMVA::Tools::Instance(); std::cout << std::endl; std::cout << "==> Start TMVAClassificationApplication" << std::endl; // // 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) that you use Float_t var0, var1; reader->AddVariable( v0, &var0 ); reader->AddVariable( v1, &var1 ); // // book the MVA method // reader->BookMVA( "M1", weightFile ); TFile *f = new TFile(dataFileName); TTree *signal = (TTree*)f->Get("TreeS"); TTree *background = (TTree*)f->Get("TreeB"); //Declaration of leaves types Float_t svar0; Float_t svar1; Float_t bvar0; Float_t bvar1; Float_t sWeight=1.0; // just in case you have weight defined, also set these branchaddresses Float_t bWeight=1.0*signal->GetEntries()/background->GetEntries(); // just in case you have weight defined, also set these branchaddresses // Set branch addresses. signal->SetBranchAddress(v0,&svar0); signal->SetBranchAddress(v1,&svar1); background->SetBranchAddress(v0,&bvar0); background->SetBranchAddress(v1,&bvar1); UInt_t nbin = 50; Float_t xmax = signal->GetMaximum(v0.Data()); Float_t xmin = signal->GetMinimum(v0.Data()); Float_t ymax = signal->GetMaximum(v1.Data()); Float_t ymin = signal->GetMinimum(v1.Data()); xmax = TMath::Max(xmax,background->GetMaximum(v0.Data())); xmin = TMath::Min(xmin,background->GetMinimum(v0.Data())); ymax = TMath::Max(ymax,background->GetMaximum(v1.Data())); ymin = TMath::Min(ymin,background->GetMinimum(v1.Data())); TH2D *hs=new TH2D("hs","",nbin,xmin,xmax,nbin,ymin,ymax); TH2D *hb=new TH2D("hb","",nbin,xmin,xmax,nbin,ymin,ymax); hs->SetXTitle(v0); hs->SetYTitle(v1); hb->SetXTitle(v0); hb->SetYTitle(v1); hs->SetMarkerColor(4); hb->SetMarkerColor(2); TH2F * hist = new TH2F( "MVA", "MVA", nbin,xmin,xmax,nbin,ymin,ymax); // 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. Float_t MinMVA=10000, MaxMVA=-100000; for (Int_t ibin=1; ibin<nbin+1; ibin++){ for (Int_t jbin=1; jbin<nbin+1; jbin++){ var0 = hs->GetXaxis()->GetBinCenter(ibin); var1 = hs->GetYaxis()->GetBinCenter(jbin); Float_t mvaVal=reader->EvaluateMVA( "M1" ) ; if (MinMVA>mvaVal) MinMVA=mvaVal; if (MaxMVA<mvaVal) MaxMVA=mvaVal; hist->SetBinContent(ibin,jbin, mvaVal); } } // creating a fine histograms containing the error rate const Int_t nValBins=100; Double_t sum = 0.; TH1F *mvaS= new TH1F("mvaS","",nValBins,MinMVA,MaxMVA); TH1F *mvaB= new TH1F("mvaB","",nValBins,MinMVA,MaxMVA); TH1F *mvaSC= new TH1F("mvaSC","",nValBins,MinMVA,MaxMVA); TH1F *mvaBC= new TH1F("mvaBC","",nValBins,MinMVA,MaxMVA); Long64_t nentries; nentries = TreeS->GetEntries(); for (Long64_t is=0; is<nentries;is++) { signal->GetEntry(is); sum +=sWeight; var0 = svar0; var1 = svar1; Float_t mvaVal=reader->EvaluateMVA( "M1" ) ; hs->Fill(svar0,svar1); mvaS->Fill(mvaVal,sWeight); } nentries = TreeB->GetEntries(); for (Long64_t ib=0; ib<nentries;ib++) { background->GetEntry(ib); sum +=bWeight; var0 = bvar0; var1 = bvar1; Float_t mvaVal=reader->EvaluateMVA( "M1" ) ; hb->Fill(bvar0,bvar1); mvaB->Fill(mvaVal,bWeight); } //SeparationBase *sepGain = new MisClassificationError(); //SeparationBase *sepGain = new GiniIndex(); SeparationBase *sepGain = new CrossEntropy(); Double_t sTot = mvaS->GetSum(); Double_t bTot = mvaB->GetSum(); mvaSC->SetBinContent(1,mvaS->GetBinContent(1)); mvaBC->SetBinContent(1,mvaB->GetBinContent(1)); Double_t sSel=mvaSC->GetBinContent(1); Double_t bSel=mvaBC->GetBinContent(1); Double_t separationGain=sepGain->GetSeparationGain(sSel,bSel,sTot,bTot); Double_t mvaCut=mvaSC->GetBinCenter(1); Double_t mvaCutOrientation=1; // 1 if mva > mvaCut --> Signal and -1 if mva < mvaCut (i.e. mva*-1 > mvaCut*-1) --> Signal for (Int_t ibin=2;ibin<nValBins;ibin++){ mvaSC->SetBinContent(ibin,mvaS->GetBinContent(ibin)+mvaSC->GetBinContent(ibin-1)); mvaBC->SetBinContent(ibin,mvaB->GetBinContent(ibin)+mvaBC->GetBinContent(ibin-1)); sSel=mvaSC->GetBinContent(ibin); bSel=mvaBC->GetBinContent(ibin); if (separationGain < sepGain->GetSeparationGain(sSel,bSel,sTot,bTot) && mvaSC->GetBinCenter(ibin)<0){ separationGain = sepGain->GetSeparationGain(sSel,bSel,sTot,bTot); mvaCut=mvaSC->GetBinCenter(ibin); if (sSel/bSel > (sTot-sSel)/(bTot-bSel)) mvaCutOrientation=-1; else mvaCutOrientation=1; } } cout << "Min="<<MinMVA << " Max=" << MaxMVA << " sTot=" << sTot << " bTot=" << bTot << " sepGain="<<separationGain << " cut=" << mvaCut << " cutOrientation="<<mvaCutOrientation << endl; delete reader; gStyle->SetPalette(1); plot(hs,hb,hist ,v0,v1,mvaCut); TCanvas *cm=new TCanvas ("cm","",900,1200); cm->cd(); cm->Divide(1,2); cm->cd(1); mvaS->SetLineColor(4); mvaB->SetLineColor(2); mvaS->Draw(); mvaB->Draw("same"); cm->cd(2); mvaSC->SetLineColor(4); mvaBC->SetLineColor(2); mvaBC->Draw(); mvaSC->Draw("same"); // TH1F *add=(TH1F*)mvaBC->Clone("add"); // add->Add(mvaSC); // add->Draw(); // errh->Draw("same"); // // write histograms // TFile *target = new TFile( "TMVAPlotDecisionBoundary.root","RECREATE" ); hs->Write(); hb->Write(); hist->Write(); target->Close(); }
void DrawErrors(Int_t NBINS=50, const char * filename="spin.root") { TFile * infile = new TFile(filename,"READ"); TTree * tr = (TTree*) infile->Get("asy"); // set binning // -- *_div = lower limit of each bin; last one is the upper limit // -- *_width = bin width Int_t phi_bins0, eta_bins0, pt_bins0, en_bins0; if(gSystem->Getenv("PHI")==NULL){fprintf(stderr,"ERROR: source env vars\n"); return;}; sscanf(gSystem->Getenv("PHI"),"%d",&phi_bins0); sscanf(gSystem->Getenv("ETA"),"%d",&eta_bins0); sscanf(gSystem->Getenv("PT"),"%d",&pt_bins0); sscanf(gSystem->Getenv("EN"),"%d",&en_bins0); const Double_t pi=3.1415; const Double_t phi_bins=phi_bins0; const Double_t eta_bins=eta_bins0; const Double_t eta_low=2.6; const Double_t eta_high=4.2; const Double_t pt_bins=pt_bins0; const Double_t pt_low=0; const Double_t pt_high=10; const Double_t en_bins=en_bins0; const Double_t en_low=0; const Double_t en_high=100; const Double_t phi_low = (-1*pi)-0.1; const Double_t phi_high = pi+0.1; Double_t phi_div[phi_bins+1]; Double_t phi_width = (phi_high - phi_low)/phi_bins; for(Int_t i=0; i<phi_bins; i++) phi_div[i] = phi_low + i * phi_width; Double_t eta_div[eta_bins+1]; Double_t eta_width = (eta_high - eta_low)/eta_bins; for(Int_t i=0; i<eta_bins; i++) eta_div[i] = eta_low + i * eta_width; Double_t pt_div[pt_bins+1]; Double_t pt_width = (pt_high - pt_low)/pt_bins; for(Int_t i=0; i<pt_bins; i++) pt_div[i] = pt_low + i * pt_width; Double_t en_div[en_bins+1]; Double_t en_width = (en_high - en_low)/en_bins; for(Int_t i=0; i<en_bins; i++) en_div[i] = en_low + i * en_width; eta_div[eta_bins] = eta_high; pt_div[pt_bins] = pt_high; en_div[en_bins] = en_high; Float_t R3_min, R3_max; Float_t R3_err_min, R3_err_max; Float_t PB_min, PB_max; Float_t PB_err_min, PB_err_max; Float_t PY_min, PY_max; Float_t PY_err_min, PY_err_max; Float_t A_LL_min, A_LL_max; Float_t A_LL_err_min, A_LL_err_max; R3_min = tr->GetMinimum("R3"); R3_max = tr->GetMaximum("R3"); R3_err_min = tr->GetMinimum("R3_err"); R3_err_max = tr->GetMaximum("R3_err"); PB_min = tr->GetMinimum("PB"); PB_max = tr->GetMaximum("PB"); PB_err_min = tr->GetMinimum("PB_err"); PB_err_max = tr->GetMaximum("PB_err"); PY_min = tr->GetMinimum("PY"); PY_max = tr->GetMaximum("PY"); PY_err_min = tr->GetMinimum("PY_err"); PY_err_max = tr->GetMaximum("PY_err"); A_LL_min = tr->GetMinimum("A_LL"); A_LL_max = tr->GetMaximum("A_LL"); A_LL_err_min = tr->GetMinimum("A_LL_err"); A_LL_err_max = tr->GetMaximum("A_LL_err"); TH2F * R3_dist = new TH2F("R3_dist","#sigma(R_{3}) vs. R_{3}", NBINS,R3_min,R3_max,NBINS,R3_err_min,R3_err_max); TH2F * PB_dist = new TH2F("PB_dist","#sigma(P_{B}) vs. P_{B}", NBINS,PB_min,PB_max,NBINS,PB_err_min,PB_err_max); TH2F * PY_dist = new TH2F("PY_dist","#sigma(P_{Y}) vs. P_{Y}", NBINS,PY_min,PY_max,NBINS,PY_err_min,PY_err_max); TH2F * A_LL_dist[eta_bins][pt_bins][en_bins]; TH2F * A_LL_dist_all = new TH2F("A_LL_dist_all","#sigma(A_{LL}) vs. A_{LL} :: all bins", NBINS,A_LL_min,A_LL_max,NBINS,A_LL_err_min,A_LL_err_max); char zero_bin[128]; strcpy(zero_bin,"phi_bin==1 && eta_bin==0 && pt_bin==0 && pt_bin==0"); tr->Project("R3_dist","R3_err:R3",zero_bin); tr->Project("PB_dist","PB_err:PB",zero_bin); tr->Project("PY_dist","PY_err:PY",zero_bin); tr->Project("A_LL_dist_all","A_LL_err:A_LL"); TFile * outfile = new TFile("error.root","RECREATE"); R3_dist->Write(); PB_dist->Write(); PY_dist->Write(); A_LL_dist_all->Write(); char A_LL_dist_n[eta_bins][pt_bins][en_bins][256]; char A_LL_dist_t[eta_bins][pt_bins][en_bins][256]; char A_LL_cut[eta_bins][pt_bins][en_bins][256]; for(Int_t g=0; g<eta_bins; g++) { for(Int_t p=0; p<pt_bins; p++) { for(Int_t e=0; e<en_bins; e++) { sprintf(A_LL_cut[g][p][e],"eta_bin==%d && pt_bin==%d && en_bin==%d",g,p,e); sprintf(A_LL_dist_n[g][p][e],"A_LL_dist_g%d_p%d_e%d",g,p,e); sprintf(A_LL_dist_t[g][p][e], "#sigma(A_{LL}) vs. A_{LL} :: #eta#in[%.2f,%.2f), p_{T}#in[%.2f,%.2f), E#in[%.2f,%.2f)", eta_div[g],eta_div[g+1],pt_div[p],pt_div[p+1],en_div[e],en_div[e+1]); A_LL_dist[g][p][e] = new TH2F(A_LL_dist_n[g][p][e],A_LL_dist_t[g][p][e], NBINS,A_LL_min,A_LL_max,NBINS,A_LL_err_min,A_LL_err_max); tr->Project(A_LL_dist_n[g][p][e],"A_LL_err:A_LL",A_LL_cut[g][p][e]); A_LL_dist[g][p][e]->Write(); }; }; }; }
double QAnalysis::GetMinimum(string name) { TTree* tree = ReadTree(file); double min = tree->GetMinimum(name.c_str()); return min; }
void eff_IdHlt(const TString configFile, TString triggerSetString) { // --------------------------------- // Preliminary checks // --------------------------------- // verify whether it was a compilation check if (configFile.Contains("_DebugRun_") || triggerSetString.Contains("_DebugRun_")) { std::cout << "eff_IdHlt: _DebugRun_ detected. Terminating the script\n"; return; } // fast check TriggerConstantSet triggerSet=DetermineTriggerSet(triggerSetString); assert ( triggerSet != TrigSet_UNDEFINED ); // --------------------------------- // Normal execution // --------------------------------- gBenchmark->Start("eff_IdHlt"); //-------------------------------------------------------------------------------------------------------------- // Settings //============================================================================================================== Double_t massLow = 60; Double_t massHigh = 120; // Read in the configuratoin file TString sampleTypeString = ""; TString effTypeString = ""; TString calcMethodString = ""; TString etBinningString = ""; TString etaBinningString = ""; TString dirTag; vector<TString> ntupleFileNames; ifstream ifs; ifs.open(configFile.Data()); if (!ifs.is_open()) { std::cout << "tried to open the configuration file <" << configFile << ">\n"; assert(ifs.is_open()); } string line; Int_t state=0; while(getline(ifs,line)) { if(line[0]=='#') continue; if(line[0]=='%') break; if(state==0){ // Read 1st line of content: data or MC? sampleTypeString = TString(line); state++; }else if(state==1) { // Read 2d content line: efficiency type string effTypeString = TString(line); state++; }else if(state==2) { // Read 3d content line: fitting mode calcMethodString = TString(line); state++; }else if(state==3) { // Read 4th content line: SC ET binning etBinningString = TString(line); state++; }else if(state==4) { // Read 5th content line: SC eta binning etaBinningString = TString(line); state++; }else if(state==5) { // Read 5th content line: SC eta binning dirTag = TString(line); state++; }else if(state==6) { ntupleFileNames.push_back(TString(line)); } } int calcMethod = 0; if(calcMethodString == "COUNTnCOUNT") calcMethod = COUNTnCOUNT; else if(calcMethodString == "COUNTnFIT") calcMethod = COUNTnFIT; else if(calcMethodString == "FITnFIT") calcMethod = FITnFIT; else assert(0); printf("Efficiency calculation method: %s\n", calcMethodString.Data()); int effType = 0; if(effTypeString == "ID") effType = ID; else if(effTypeString == "HLT") effType = HLT; else assert(0); printf("Efficiency type to measure: %s\n", effTypeString.Data()); int etBinning = 0; if(etBinningString == "ETBINS1") etBinning = ETBINS1; else if(etBinningString == "ETBINS5") etBinning = ETBINS5; else assert(0); printf("SC ET binning: %s\n", etBinningString.Data()); int etaBinning = 0; if(etaBinningString == "ETABINS1") etaBinning = ETABINS1; else if(etaBinningString == "ETABINS2") etaBinning = ETABINS2; else assert(0); printf("SC eta binning: %s\n", etaBinningString.Data()); int sample; if(sampleTypeString == "DATA") sample = DATA; else if(sampleTypeString == "MC") sample = MC; else assert(0); printf("Sample: %s\n", sampleTypeString.Data()); // Construct the trigger object TriggerSelection triggers(triggerSetString, (sample==DATA)?true:false, 0); if (effType==HLT) std::cout << "\tHLT efficiency calculation method " << triggers.hltEffCalcName() << ", triggerSet=" << triggers.triggerSetName() << "\n"; else triggers.hltEffCalcMethod(HLTEffCalc_2011Old); TRandom *rnd= new TRandom(); rnd->SetSeed(0); // The label is a string that contains the fields that are passed to // the function below, to be used to name files with the output later. TString label = getLabel(sample, effType, calcMethod, etBinning, etaBinning, triggers); //-------------------------------------------------------------------------------------------------------------- // Main analysis code //============================================================================================================== // // Set up histograms // TH1F* hMass = new TH1F("hMass" ,"",30,massLow,massHigh); TH1F* hMassTotal = new TH1F("hMassTotal","",30,massLow,massHigh); TH1F* hMassPass = new TH1F("hMassPass" ,"",30,massLow,massHigh); TH1F* hMassFail = new TH1F("hMassFail" ,"",30,massLow,massHigh); // Save MC templates if sample is MC TString tagAndProbeDir(TString("../root_files/tag_and_probe/")+dirTag); gSystem->mkdir(tagAndProbeDir,kTRUE); TFile *templatesFile = 0; vector<TH1F*> hPassTemplateV; vector<TH1F*> hFailTemplateV; if( sample != DATA) { // For simulation, we will be saving templates TString labelMC = getLabel(-1111, effType, calcMethod, etBinning, etaBinning, triggers); TString templatesLabel = tagAndProbeDir + TString("/mass_templates_")+labelMC+TString(".root"); templatesFile = new TFile(templatesLabel,"recreate"); for(int i=0; i<getNEtBins(etBinning); i++){ for(int j=0; j<getNEtaBins(etaBinning); j++){ TString hname = "hMassTemplate_Et"; hname += i; hname += "_eta"; hname += j; hPassTemplateV.push_back(new TH1F(hname+TString("_pass"),"",60,massLow,massHigh)); hFailTemplateV.push_back(new TH1F(hname+TString("_fail"),"",60,massLow,massHigh)); } } } else { // For data, we will be using templates, // however, if the request is COUNTnCOUNT, do nothing if( calcMethod != COUNTnCOUNT ){ TString labelMC = getLabel(-1111, effType, calcMethod, etBinning, etaBinning, triggers); TString templatesLabel = tagAndProbeDir+TString("/mass_templates_")+labelMC+TString(".root"); templatesFile = new TFile(templatesLabel); if( ! templatesFile->IsOpen() ) assert(0); } } // This file can be utilized in the future, but for now // opening it just removes complaints about memory resident // trees. No events are actually written. TFile *selectedEventsFile = new TFile("selectedEventsFile.root","recreate"); if (!selectedEventsFile) { assert(0); } TTree *passTree = new TTree("passTree","passTree"); Double_t storeMass, storeEt, storeEta; passTree->Branch("mass",&storeMass,"mass/D"); passTree->Branch("et",&storeEt ,"et/D"); passTree->Branch("eta",&storeEta ,"eta/D"); TTree *failTree = new TTree("failTree","failTree"); failTree->Branch("mass",&storeMass,"mass/D"); failTree->Branch("et",&storeEt ,"et/D"); failTree->Branch("eta",&storeEta ,"eta/D"); int nDivisions = getNEtBins(etBinning)*getNEtaBins(etaBinning); double ymax = 800; if(nDivisions <4 ) ymax = nDivisions * 200; TCanvas *c1 = MakeCanvas("c1","c1", 600, int(ymax)); c1->Divide(2,nDivisions); int eventsInNtuple = 0; int eventsAfterTrigger = 0; int totalCand = 0; int totalCandInMassWindow = 0; int totalCandInEtaAcceptance = 0; int totalCandEtAbove10GeV = 0; int totalCandMatchedToGen = 0; // Loop over files for(UInt_t ifile=0; ifile<ntupleFileNames.size(); ifile++){ // // Access samples and fill histograms // TFile *infile = 0; TTree *eventTree = 0; // Data structures to store info from TTrees mithep::TEventInfo *info = new mithep::TEventInfo(); mithep::TGenInfo *gen = new mithep::TGenInfo(); TClonesArray *dielectronArr = new TClonesArray("mithep::TDielectron"); // Read input file cout << "Processing " << ntupleFileNames[ifile] << "..." << endl; infile = new TFile(ntupleFileNames[ifile]); assert(infile); // Get the TTrees eventTree = (TTree*)infile->Get("Events"); assert(eventTree); // Set branch address to structures that will store the info eventTree->SetBranchAddress("Info",&info); TBranch *infoBr = eventTree->GetBranch("Info"); // check whether the file is suitable for the requested run range UInt_t runNumMin = UInt_t(eventTree->GetMinimum("runNum")); UInt_t runNumMax = UInt_t(eventTree->GetMaximum("runNum")); std::cout << "runNumMin=" << runNumMin << ", runNumMax=" << runNumMax << "\n"; if (!triggers.validRunRange(runNumMin,runNumMax)) { std::cout << "... file contains uninteresting run range\n"; continue; } // Define other branches eventTree->SetBranchAddress("Dielectron",&dielectronArr); TBranch *dielectronBr = eventTree->GetBranch("Dielectron"); TBranch *genBr = 0; if(sample != DATA){ eventTree->SetBranchAddress("Gen",&gen); genBr = eventTree->GetBranch("Gen"); } // loop over events eventsInNtuple += eventTree->GetEntries(); for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) { // for(UInt_t ientry=0; ientry<200000; ientry++) { // This is for faster turn-around in testing if(sample != DATA) genBr->GetEntry(ientry); // Check that the whole event has fired the appropriate trigger infoBr->GetEntry(ientry); /* Old code // For EPS2011 for both data and MC (starting from Summer11 production) // we use a special trigger for tag and probe that has second leg // unbiased with cuts at HLT ULong_t eventTriggerBit = kHLT_Ele17_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC8_Mass30 | kHLT_Ele32_CaloIdL_CaloIsoVL_SC17; // The tag trigger bit matches the "electron" of the trigger we // use for this tag and probe study: electron+sc ULong_t tagTriggerObjectBit = kHLT_Ele17_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC8_Mass30_EleObj | kHLT_Ele32_CaloIdL_CaloIsoVL_SC17_EleObj; // The probe trigger, however, is any of possibilities used in // the trigger that is used in the main analysis ULong_t probeTriggerObjectBit = kHLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL_Ele1Obj | kHLT_Ele17_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele8_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele1Obj | kHLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL_Ele2Obj | kHLT_Ele17_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele8_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele2Obj; */ ULong_t eventTriggerBit= triggers.getEventTriggerBit_TagProbe(info->runNum); if(!(info->triggerBits & eventTriggerBit)) continue; // no trigger accept? Skip to next event... eventsAfterTrigger++; ULong_t tagTriggerObjectBit= triggers.getTagTriggerObjBit(info->runNum); ULong_t probeTriggerObjectBit_Tight= triggers.getProbeTriggerObjBit_Tight(info->runNum); ULong_t probeTriggerObjectBit_Loose= triggers.getProbeTriggerObjBit_Loose(info->runNum); ULong_t probeTriggerObjectBit= probeTriggerObjectBit_Tight | probeTriggerObjectBit_Loose; // loop through dielectrons dielectronArr->Clear(); dielectronBr->GetEntry(ientry); for(Int_t i=0; i<dielectronArr->GetEntriesFast(); i++) { totalCand++; const mithep::TDielectron *dielectron = (mithep::TDielectron*)((*dielectronArr)[i]); // Tag and probe is done around the Z peak if((dielectron->mass < massLow) || (dielectron->mass > massHigh)) continue; totalCandInMassWindow++; // // Exclude ECAL gap region (should already be done for ntuple, but just to make sure...) if((fabs(dielectron->scEta_1)>kGAP_LOW) && (fabs(dielectron->scEta_1)<kGAP_HIGH)) continue; if((fabs(dielectron->scEta_2)>kGAP_LOW) && (fabs(dielectron->scEta_2)<kGAP_HIGH)) continue; // ECAL acceptance cut on supercluster Et if((fabs(dielectron->scEta_1) > 2.5) || (fabs(dielectron->scEta_2) > 2.5)) continue; // outside eta range? Skip to next event... totalCandInEtaAcceptance++; // None of the electrons should be below 10 GeV if((dielectron->scEt_1 < 10) || (dielectron->scEt_2 < 10)) continue; // below supercluster ET cut? Skip to next event... totalCandEtAbove10GeV++; // Next, we will do a loose kinematic matching to generator level // info. // For the data, this is not needed and not done. We take all // candidates, and take care of background by fitting. // For MC, however, we do not fit, but count pass/fail events. // So we need to make sure there is no background. However, even // in the signal Z->ee MC sample there jets and therefore fake // electrons. So we drop all candidates that do not have both leptons // matched. // if( sample != DATA ) if( ! dielectronMatchedToGeneratorLevel(gen, dielectron) ) continue; totalCandMatchedToGen++; // ECAL driven: this condition is NOT applied // Preliminary selection is complete. Now work on tags and probes. TElectron *ele1 = extractElectron(dielectron, 1); TElectron *ele2 = extractElectron(dielectron, 2); bool isTag1 = isTag(ele1, tagTriggerObjectBit); bool isTag2 = isTag(ele2, tagTriggerObjectBit); // Any electron that made it here is eligible to be a probe // for ID cuts. bool isIDProbe1 = true; bool isIDProbe2 = true; bool isIDProbePass1 = passID(ele1); bool isIDProbePass2 = passID(ele2); // Probes for HLT cuts: bool isHLTProbe1 = passID(ele1); bool isHLTProbe2 = passID(ele2); bool isHLTProbePass1 = ( isHLTProbe1 && (ele1 ->hltMatchBits & probeTriggerObjectBit) ); bool isHLTProbePass2 = ( isHLTProbe2 && (ele2 ->hltMatchBits & probeTriggerObjectBit) ); // // Apply tag and probe, and accumulate counters or histograms // bool isProbe1 = false; bool isProbe2 = false; bool isProbePass1 = false; bool isProbePass2 = false; if( effType == ID ){ isProbe1 = isIDProbe1; isProbe2 = isIDProbe2; isProbePass1 = isIDProbePass1; isProbePass2 = isIDProbePass2; }else if( effType == HLT ){ isProbe1 = isHLTProbe1; isProbe2 = isHLTProbe2; isProbePass1 = isHLTProbePass1; isProbePass2 = isHLTProbePass2; if (triggers.useRandomTagTnPMethod(info->runNum)) { if (rnd->Uniform() <= 0.5) { // tag is 1st electron if (!isTag1) continue; isTag2=0; // ignore whether ele2 can be a tag } else { if (!isTag2) continue; isTag1=0; // ignore whether ele1 can be a tag } } }else { printf("ERROR: unknown efficiency type requested\n"); } storeMass = dielectron->mass; // First electron is the tag, second is the probe if( isTag1 && isProbe2){ // total probes hMassTotal->Fill(dielectron->mass); storeEt = dielectron->scEt_2; storeEta = dielectron->scEta_2; int templateBin = getTemplateBin( findEtBin(storeEt,etBinning), findEtaBin(storeEta,etaBinning), etaBinning); if( isProbePass2 ){ // passed hMassPass->Fill(dielectron->mass); passTree->Fill(); if(sample != DATA && templateBin != -1) hPassTemplateV[templateBin]->Fill(dielectron->mass); }else{ // fail hMassFail->Fill(dielectron->mass); failTree->Fill(); if(sample != DATA && templateBin != -1) hFailTemplateV[templateBin]->Fill(dielectron->mass); } } // Second electron is the tag, first is the probe if( isTag2 && isProbe1 ){ // total probes hMassTotal->Fill(dielectron->mass); storeEt = dielectron->scEt_1; storeEta = dielectron->scEta_1; int templateBin = getTemplateBin( findEtBin(storeEt,etBinning), findEtaBin(storeEta,etaBinning), etaBinning); if( isProbePass1 ){ // passed hMassPass->Fill(dielectron->mass); passTree->Fill(); if(sample != DATA && templateBin != -1) hPassTemplateV[templateBin]->Fill(dielectron->mass); }else{ // fail hMassFail->Fill(dielectron->mass); failTree->Fill(); if(sample != DATA && templateBin != -1) hFailTemplateV[templateBin]->Fill(dielectron->mass); } } // In case the full selection is applied: // if( !(isTag1 && ele2_passID) && !(isTag2 && ele1_passID) ) continue; if( !(isTag1 && isIDProbePass2) && !(isTag2 && isIDProbePass1) ) continue; // if( !(isTag1) && !(isTag2) ) continue; // Fill histogram hMass->Fill(dielectron->mass); } // end loop over dielectron candidates } // end loop over events delete infile; infile=0; eventTree=0; delete gen; delete info; delete dielectronArr; } // end loop over files // // Efficiency analysis // // printf("Number of regular candidates: %15.0f\n", hMass->GetSumOfWeights()); printf("Total events in ntuple %15d\n",eventsInNtuple); printf(" events after event level trigger cut %15d\n",eventsAfterTrigger); printf("\nTotal candidates (no cuts) %15d\n",totalCand); printf(" candidates in 60-120 mass window %15d\n",totalCandInMassWindow); printf(" candidates witheta 0-1.4442, 1.566-2.5 %15d\n",totalCandInEtaAcceptance); printf(" candidates, both electrons above 10 GeV %15d\n",totalCandEtAbove10GeV); printf(" candidates matched to GEN level (if MC) %15d\n",totalCandMatchedToGen); printf("\nNumber of probes, total %15.0f\n", hMassTotal->GetSumOfWeights()); printf("Number of probes, passed %15.0f\n", hMassPass->GetSumOfWeights()); printf("Number of probes, failed %15.0f\n", hMassFail->GetSumOfWeights()); // Human-readbale text file to store measured efficiencies TString reslog = tagAndProbeDir+TString("/efficiency_TnP_")+label+TString(".txt"); ofstream effOutput; effOutput.open(reslog); // Print into the results file the header. effOutput << "Efficiency calculation method: " << calcMethodString.Data() << endl; effOutput << "Efficiency type to measure: " << effTypeString.Data() << endl; effOutput << "SC ET binning: " << etBinningString.Data() << endl; effOutput << "SC eta binning: " << etaBinningString.Data() << endl; effOutput << "Sample: " << sampleTypeString.Data() << endl; effOutput << "Files processed: " << endl; for(UInt_t i=0; i<ntupleFileNames.size(); i++) effOutput << " " << ntupleFileNames[i].Data() << endl; // ROOT file to store measured efficiencies in ROOT format TString resroot = tagAndProbeDir+TString("/efficiency_TnP_")+label+TString(".root"); TFile *resultsRootFile = new TFile(resroot,"recreate"); // Fit log TString fitlogname = tagAndProbeDir+TString("/efficiency_TnP_")+label+TString("_fitlog.dat"); ofstream fitLog; fitLog.open(fitlogname); // // Find efficiency // bool useTemplates = false; if(sample == DATA && effType == ID && (calcMethod == COUNTnFIT || FITnFIT) ) useTemplates = true; int NsetBins=120; bool isRECO=0; const char* setBinsType="cache"; measureEfficiency(passTree, failTree, calcMethod, etBinning, etaBinning, c1, effOutput, fitLog, useTemplates, templatesFile, resultsRootFile, NsetBins, isRECO, setBinsType, dirTag, triggers.triggerSetName()); effOutput.close(); fitLog.close(); TString command = "cat "; command += reslog; system(command.Data()); TString fitpicname = tagAndProbeDir+TString("/efficiency_TnP_")+label+TString("_fit.png"); c1->SaveAs(fitpicname); // Save MC templates if(sample != DATA){ templatesFile->cd(); for(int i=0; i<getNEtBins(etBinning); i++){ for(int j=0; j<getNEtaBins(etaBinning); j++){ int templateBin = getTemplateBin( i, j, etaBinning); hPassTemplateV[templateBin]->Write(); hFailTemplateV[templateBin]->Write(); } } templatesFile->Close(); } gBenchmark->Show("eff_IdHlt"); }
void csv(TString input="tmva.csvoutput.txt", TString par1="par2", TString par2="par3", TString par3="", TString value="eventEffScaled_5") { std::cout << "Usage:" << std::endl << ".x scripts/csv.C with default arguments" << std::endl << ".x scripts/csv.C(filename, par1, par2, value)" << std::endl << std::endl << " Optional arguments:" << std::endl << " filename path to CSV file" << std::endl << " par1 name of X-parameter branch" << std::endl << " par2 name of Y-parameter branch (if empty, efficiency is drawn as a function of par1)" << std::endl << " value name of result (efficiency) branch" << std::endl << std::endl; TTree *tree = new TTree("data", "data"); tree->ReadFile(input); gStyle->SetPalette(1); gStyle->SetPadRightMargin(0.14); TCanvas *canvas = new TCanvas("csvoutput", "CSV Output", 1200, 900); tree->SetMarkerStyle(kFullDotMedium); tree->SetMarkerColor(kRed); if(par2.Length() > 0) { //tree->Draw(Form("%s:%s", par2.Data(), par1.Data())); if(par3.Length() > 0) tree->Draw(Form("%s:%s:%s:%s", par1.Data(), par2.Data(), par3.Data(), value.Data()), "", "COLZ"); //, "", "Z"); else tree->Draw(Form("%s:%s:%s", par2.Data(), par1.Data(), value.Data()), "", "COLZ"); //, "", "Z"); TH1 *histo = tree->GetHistogram(); if(!histo) return; histo->SetTitle(Form("%s with different classifier parameters", value.Data())); histo->GetXaxis()->SetTitle(Form("Classifier parameter %s", par1.Data())); histo->GetYaxis()->SetTitle(Form("Classifier parameter %s", par2.Data())); if(par3.Length() > 0) histo->GetZaxis()->SetTitle(Form("Classifier parameter %s", par3.Data())); else histo->GetZaxis()->SetTitle(""); if(par3.Length() == 0) { float x = 0; float y = 0; float val = 0; double maxVal = tree->GetMaximum(value); double minVal = tree->GetMinimum(value); tree->SetBranchAddress(par1, &x); tree->SetBranchAddress(par2, &y); tree->SetBranchAddress(value, &val); TLatex l; l.SetTextSize(0.03); Long64_t nentries = tree->GetEntries(); for(Long64_t entry=0; entry < nentries; ++entry) { tree->GetEntry(entry); l.SetTextColor(textColor(val, maxVal, minVal)); l.DrawLatex(x, y, Form("%.3f", val*100)); } } } else { tree->Draw(Form("%s:%s", value.Data(), par1.Data())); TH1 *histo = tree->GetHistogram(); if(!histo) return; histo->SetTitle(Form("%s with different classifier parameters", value.Data())); histo->GetXaxis()->SetTitle(Form("Classifier parameter %s", par1.Data())); histo->GetYaxis()->SetTitle(value); } }
void PlotDecisionBoundary( TString weightFile = "weights/Zprime_vs_QCD_TMVAClassification_BDT.weights.xml",TString v0="lep_pt_ljet", TString v1="met_pt", TString dataFileNameS = "/nfs/dust/cms/user/karavdia/ttbar_semilep_13TeV/RunII_25ns_v1/test_03/uhh2.AnalysisModuleRunner.MC.Zp01w3000.root", TString dataFileNameB = "/nfs/dust/cms/user/karavdia/ttbar_semilep_13TeV/RunII_25ns_v1/test_03/uhh2.AnalysisModuleRunner.MC.QCD_EMEnriched.root") { //--------------------------------------------------------------- // default MVA methods to be trained + tested // this loads the library TMVA::Tools::Instance(); std::cout << std::endl; std::cout << "==> Start TMVAClassificationApplication" << std::endl; // // 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) that you use // Float_t var0, var1; // reader->AddVariable( v0, &var0 ); // reader->AddVariable( v1, &var1 ); Float_t lep_pt, lep_fbrem, MwT; Float_t log_ljet_pt, log_met_pt, log_lep_pt_ljet; Float_t log_dR_lep_cljet, log_dR_cljet_ljet; Float_t dPhi_lep_cljet; reader->AddVariable("lep_pt", &lep_pt); reader->AddVariable("lep_fbrem", & lep_fbrem); reader->AddVariable("MwT", &MwT); reader->AddVariable("log(ljet_pt)", &log_ljet_pt); reader->AddVariable("log(met_pt)",&log_met_pt); reader->AddVariable("log(lep_pt_ljet)",&log_lep_pt_ljet); reader->AddVariable("log(dR_lep_cljet)",&log_dR_lep_cljet_trans); reader->AddVariable("log(fabs((dR_cljet_ljet-3.14)/3.14))", &log_dR_cljet_ljet); reader->AddSpectator("dPhi_lep_cljet", &dPhi_lep_cljet); // // book the MVA method // reader->BookMVA( "BDT", weightFile ); TFile *fS = new TFile(dataFileNameS); TTree *signal = (TTree*)fS->Get("AnalysisTree"); TFile *fB = new TFile(dataFileNameS); TTree *background = (TTree*)fB->Get("AnalysisTree"); //Declaration of leaves types Float_t svar0; Float_t svar1; Float_t bvar0; Float_t bvar1; Float_t sWeight=1.0; // just in case you have weight defined, also set these branchaddresses Float_t bWeight=1.0*signal->GetEntries()/background->GetEntries(); // just in case you have weight defined, also set these branchaddresses // Set branch addresses. signal->SetBranchAddress(v0,&svar0); signal->SetBranchAddress(v1,&svar1); background->SetBranchAddress(v0,&bvar0); background->SetBranchAddress(v1,&bvar1); UInt_t nbin = 50; Float_t xmax = signal->GetMaximum(v0.Data()); Float_t xmin = signal->GetMinimum(v0.Data()); Float_t ymax = signal->GetMaximum(v1.Data()); Float_t ymin = signal->GetMinimum(v1.Data()); xmax = TMath::Max(xmax,(Float_t)background->GetMaximum(v0.Data())); xmin = TMath::Min(xmin,(Float_t)background->GetMinimum(v0.Data())); ymax = TMath::Max(ymax,(Float_t)background->GetMaximum(v1.Data())); ymin = TMath::Min(ymin,(Float_t)background->GetMinimum(v1.Data())); TH2D *hs=new TH2D("hs","",nbin,xmin,xmax,nbin,ymin,ymax); TH2D *hb=new TH2D("hb","",nbin,xmin,xmax,nbin,ymin,ymax); hs->SetXTitle(v0); hs->SetYTitle(v1); hb->SetXTitle(v0); hb->SetYTitle(v1); hs->SetMarkerColor(4); hb->SetMarkerColor(2); TH2F * hist = new TH2F( "MVA", "MVA", nbin,xmin,xmax,nbin,ymin,ymax); // 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. Float_t MinMVA=10000, MaxMVA=-100000; for (UInt_t ibin=1; ibin<nbin+1; ibin++){ for (UInt_t jbin=1; jbin<nbin+1; jbin++){ var0 = hs->GetXaxis()->GetBinCenter(ibin); var1 = hs->GetYaxis()->GetBinCenter(jbin); Float_t mvaVal=reader->EvaluateMVA( "BDT" ) ; if (MinMVA>mvaVal) MinMVA=mvaVal; if (MaxMVA<mvaVal) MaxMVA=mvaVal; hist->SetBinContent(ibin,jbin, mvaVal); } } // now you need to try to find the MVA-value at which you cut for the plotting of the decision boundary // (Use the smallest number of misclassifications as criterion) const Int_t nValBins=100; Double_t sum = 0.; TH1F *mvaS= new TH1F("mvaS","",nValBins,MinMVA,MaxMVA); mvaS->SetXTitle("MVA-ouput"); mvaS->SetYTitle("#entries"); TH1F *mvaB= new TH1F("mvaB","",nValBins,MinMVA,MaxMVA); mvaB->SetXTitle("MVA-ouput"); mvaB->SetYTitle("#entries"); TH1F *mvaSC= new TH1F("mvaSC","",nValBins,MinMVA,MaxMVA); mvaSC->SetXTitle("MVA-ouput"); mvaSC->SetYTitle("cummulation"); TH1F *mvaBC= new TH1F("mvaBC","",nValBins,MinMVA,MaxMVA); mvaBC->SetXTitle("MVA-ouput"); mvaBC->SetYTitle("cummulation"); Long64_t nentries; nentries = signal->GetEntries(); for (Long64_t is=0; is<nentries;is++) { signal->GetEntry(is); sum +=sWeight; var0 = svar0; var1 = svar1; Float_t mvaVal=reader->EvaluateMVA( "BDT" ) ; hs->Fill(svar0,svar1); mvaS->Fill(mvaVal,sWeight); } nentries = background->GetEntries(); for (Long64_t ib=0; ib<nentries;ib++) { background->GetEntry(ib); sum +=bWeight; var0 = bvar0; var1 = bvar1; Float_t mvaVal=reader->EvaluateMVA( "BDT" ) ; hb->Fill(bvar0,bvar1); mvaB->Fill(mvaVal,bWeight); } SeparationBase *sepGain = new MisClassificationError(); //SeparationBase *sepGain = new GiniIndex(); //SeparationBase *sepGain = new CrossEntropy(); Double_t sTot = mvaS->GetSum(); Double_t bTot = mvaB->GetSum(); mvaSC->SetBinContent(1,mvaS->GetBinContent(1)); mvaBC->SetBinContent(1,mvaB->GetBinContent(1)); Double_t sSel=mvaSC->GetBinContent(1); Double_t bSel=mvaBC->GetBinContent(1); Double_t sSelBest=0; Double_t bSelBest=0; Double_t separationGain=sepGain->GetSeparationGain(sSel,bSel,sTot,bTot); Double_t mvaCut=mvaSC->GetBinCenter(1); Double_t mvaCutOrientation=1; // 1 if mva > mvaCut --> Signal and -1 if mva < mvaCut (i.e. mva*-1 > mvaCut*-1) --> Signal for (UInt_t ibin=2;ibin<nValBins;ibin++){ mvaSC->SetBinContent(ibin,mvaS->GetBinContent(ibin)+mvaSC->GetBinContent(ibin-1)); mvaBC->SetBinContent(ibin,mvaB->GetBinContent(ibin)+mvaBC->GetBinContent(ibin-1)); sSel=mvaSC->GetBinContent(ibin); bSel=mvaBC->GetBinContent(ibin); if (separationGain < sepGain->GetSeparationGain(sSel,bSel,sTot,bTot)){ separationGain = sepGain->GetSeparationGain(sSel,bSel,sTot,bTot); mvaCut=mvaSC->GetBinCenter(ibin); if (sSel/bSel > (sTot-sSel)/(bTot-bSel)) mvaCutOrientation=-1; else mvaCutOrientation=1; sSelBest=sSel; bSelBest=bSel; } } cout << "Min="<<MinMVA << " Max=" << MaxMVA << " sTot=" << sTot << " bTot=" << bTot << " sSel=" << sSelBest << " bSel=" << bSelBest << " sepGain="<<separationGain << " cut=" << mvaCut << " cutOrientation="<<mvaCutOrientation << endl; delete reader; gStyle->SetPalette(1); plot(hs,hb,hist ,v0,v1,mvaCut); TCanvas *cm=new TCanvas ("cm","",900,1200); cm->cd(); cm->Divide(1,2); cm->cd(1); mvaS->SetLineColor(4); mvaB->SetLineColor(2); mvaS->Draw(); mvaB->Draw("same"); cm->cd(2); mvaSC->SetLineColor(4); mvaBC->SetLineColor(2); mvaBC->Draw(); mvaSC->Draw("same"); // TH1F *add=(TH1F*)mvaBC->Clone("add"); // add->Add(mvaSC); // add->Draw(); // errh->Draw("same"); // // write histograms // TFile *target = new TFile( "TMVAPlotDecisionBoundary.root","RECREATE" ); hs->Write(); hb->Write(); hist->Write(); target->Close(); }