void treegraph(TString filename) { gROOT->SetStyle("Plain"); gStyle->SetOptDate(); Double_t x, y; Int_t nlines = 0; TFile *f = new TFile("graph.root","RECREATE"); TCanvas *canvas_graph = new TCanvas("canvas_graph", "y vs x",467,89,400,700); TTree t; t.ReadFile(filename,"x:y"); t.Draw("x:y","","goff"); TGraph *g = new TGraph(t.GetSelectedRows(),t.GetV1(),t.GetV2()); g->SetTitle(filename+": Y vs X"); g->GetXaxis()->SetTitle("x[a.u.]"); g->GetYaxis()->SetTitle("y[a.u.]"); g->SetMarkerStyle(21); g->Draw("AP"); f->Write(); }
void CheckOutput(){ // // // TFile * f = TFile::Open("Filtered.root"); TTree * highPt = (TTree*)f->Get("highPt"); TTree * treeV0s = (TTree*)f->Get("V0s"); // // Export variable: // Double_t ratioHighPtV0Entries=treeV0s->GetEntries()/Double_t(treeV0s->GetEntries()+highPt->GetEntries()+0.000001); Double_t ratioHighPtV0Size=treeV0s->GetZipBytes()/Double_t(treeV0s->GetZipBytes()+highPt->GetZipBytes()+0.000001); printf("#UnitTest:\tAliAnalysisTaskFiltered\tRatioPtToV0Entries\t%f\n",ratioHighPtV0Entries); printf("#UnitTest:\tAliAnalysisTaskFiltered\tRatioPtToV0Size\t%f\n",ratioHighPtV0Size); // // Double_t ratioPointsV0 = 2*treeV0s->GetBranch("friendTrack0.fCalibContainer")->GetZipBytes()/Double_t(0.00001+treeV0s->GetZipBytes()); Double_t ratioPointsHighPt = highPt->GetBranch("friendTrack.fCalibContainer")->GetZipBytes()/Double_t(0.00001+highPt->GetZipBytes()); printf("#UnitTest:\tAliAnalysisTaskFiltered\tRatioPointsV0\t%f\n",ratioPointsV0); printf("#UnitTest:\tAliAnalysisTaskFiltered\tRatioPointsHighPt\t%f\n",ratioPointsHighPt); // // a.) Check track correspondence // Int_t entries= highPt->Draw("(friendTrack.fTPCOut.fP[3]-esdTrack.fIp.fP[3])/sqrt(friendTrack.fTPCOut.fC[9]+esdTrack.fIp.fC[9])","friendTrack.fTPCOut.fP[3]!=0",""); // here we should check if the tracks Double_t pulls=TMath::RMS(entries, highPt->GetV1()); printf("#UnitTest:\tAliAnalysisTaskFiltered\tFriendPull\t%2.4f\n",pulls); printf("#UnitTest:\tAliAnalysisTaskFiltered\tFriendOK\t%d\n",pulls<10); }
/* * The Ferromagnet_Scan function reads in * a data file of magentic field scans * from within the ferromagnet and returns * a graph of the magnetic permeability * of the ferromagnet vs the external field * provided by the Helmholtz coil. */ TGraphErrors* plot_uvB( const TString scan_file, TF1* calib_fit, double R, double R_sig ) { /*Read in Data File to ROOT Tree*/ cout<< "processing file " << scan_file <<endl; TTree *TData = new TTree(); TData->ReadFile(scan_file, "t/D:I:B"); /*Use TTree Draw command to write branches to usable arrays*/ int n = TData->Draw("I:TMath::Abs(B):0.0:0.005", "", "goff"); vector<double> B_ext, B_in, Bratio, u; for(int i = 0; i < n; i++) { B_ext.push_back( calib_fit->Eval(TData->GetV1()[i]) ); B_in.push_back( TData->GetV2()[i] ); Bratio.push_back( B_in[i] / B_ext[i]); u.push_back( (Bratio[i]*(R**2) + Bratio[i] - 2 - 2*sqrt((Bratio[i]**2)*(R**2) - Bratio[i]*(R**2) - Bratio[i] + 1 ) ) / (Bratio[i]*(R**2) - Bratio[i]) ); } TGraphErrors *g_uvB = new TGraphErrors(n, &B_ext[0], &u[0], TData->GetV3(), TData->GetV4()); /* g_uvB->Fit("pol1", "", "", 10, 60); cout << "Permeability at 50: " << g_uvB->GetFunction("pol1")->Eval(50) << endl; cout << "Permeability at 40: " << g_uvB->GetFunction("pol1")->Eval(40) << endl; cout << "Permeability at 30: " << g_uvB->GetFunction("pol1")->Eval(30) << endl; */ return g_uvB; }
/*! * ### Example usage: \code .L $AliRoot_SRC/STAT/Macros/aliExternalInfo.C+ drawLogbook("LHC15o","pass1","QA.TPC.meanTPCncl>0","runDuration:totalEventsPhysics:totalNumberOfFilesMigrated:MonALISA.RCT.tpc_value"); drawLogbook("LHC10h","pass2","totalEventsPhysics>1000&&totalNumberOfFilesMigrated>20","runDuration:totalEventsPhysics:totalNumberOfFilesMigrated:MonALISA.RCT.tpc_value"); drawLogbook("LHC11h","pass2","totalEventsPhysics>1000&&totalNumberOfFilesMigrated>20","runDuration:totalEventsPhysics:totalNumberOfFilesMigrated:MonALISA.RCT.tpc_value"); \endcode */ void drawLogbook(TString period, TString pass,TString runSelection="", TString varSelection="runDuration:totalEventsPhysics:totalNumberOfFilesMigrated"){ TTree * treeLogbook = info.GetTree("Logbook",period,pass,"QA.TPC;QA.TRD;QA.ITS;MonALISA.RCT"); TObjArray *varList=0; if (varSelection[0]=='['){ //variable list using class selection // Use class selection to select variables varList=AliTreePlayer::selectMetadata(treeLogbook,varSelection,0); Int_t nvars=varList->GetEntries(); for (Int_t i=0; i<nvars;i++){ TString vname=varList->At(i)->GetName(); vname.ReplaceAll(".class",""); } // varList=AliTreePlayer::selectMetadata(treeLogbook, "[class==\"Logbook&&Time\"]",0); }else{ varList=varSelection.Tokenize(":"); } Int_t nvars=varList->GetEntries(); TCanvas * canvas = new TCanvas("drawLogbook","drawLogbook",1200,1000); canvas->Divide(1,nvars); for (Int_t i=0; i<nvars; i++){ canvas->cd(i+1); TString var=TString::Format("%s:run",varList->At(i)->GetName()); TStatToolkit::MakeGraphSparse(treeLogbook,var,runSelection,25,1,1)->Draw("ap"); Double_t mean = TMath::Mean(treeLogbook->GetSelectedRows(),treeLogbook->GetV1()); Double_t sum = treeLogbook->GetSelectedRows()*mean; latex.DrawLatexNDC(0.15,0.8,TString::Format("Mean=%0.0f",mean)); latex.DrawLatexNDC(0.15,0.7,TString::Format("Sum=%0.0f",sum)); } canvas->SaveAs(TString::Format("%s_%s.png",pass.Data(),period.Data()).Data()); }
void histogram() { // Read data from ASCII file and create histogram/ntuple combo ifstream in; in.open("/users/ronnie/git/Journal-Analysis/data.txt"); Text_t month; Float_t date, day, words; TFile *file = new TFile("histogramTest.root", "CREATE"); TH1F *histo = new TH1F("histo", "writing distribution", 100, 0, 2); TTree *Tree = new TTree("ntuple", "data from file"); Tree->ReadFile(Form("/users/ronnie/git/Journal-Analysis/Daily Journals/data.txt"), "month:date:day:words"); graph = new TGraph(200, &words, &day); // Get the total number of words written and print out to CLI Tree->Print(); Int_t numEntries = (Int_t)(Tree->GetEntries()); TBranch *wordsBranch = Tree->GetBranch("words"); for(Int_t i = 0; i < numEntries; i++) { Tree->GetEntry(i, 0); } // Draw the Tree (words vs. day) on canvas Tree->SetEstimate(Tree->GetEntries()); Tree->Draw("words:day"); // Have to loop back through drawn tree to get values and count number of words total Float_t numWords = 0.0; Double_t *array = Tree->GetV1(); for (Int_t i = 0; i < numEntries; i++) { numWords += array[i]; } cout << numWords << endl; }
makePlot_check_all() { gStyle->SetOptStat(0); vector< TString > v_infile; // v_infile.push_back( TString("output/fitResults_run001_1layer_sheath.root") ); // v_infile.push_back( TString("output/fitResults_run002_1layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run003_1layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run004_2layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run005_2layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run006_3layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run007_4layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run008_2layer_cylinder.root") ); v_infile.push_back( TString("output/fitResults_run009_2layer_cylinder.root") ); // v_infile.push_back( TString("output/fitResults_run010_1layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run011_1layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run012_1layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run013_1layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run014_1layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run015_1layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run016_1layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run017_2layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run018_1layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run019_1layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run020_1layer_sheath.root") ); v_infile.push_back( TString("output/fitResults_run021_1layer.root") ); for ( unsigned f = 0; f < v_infile.size(); f++ ) { cout << "Plot " << v_infile.at(f) << endl; TCanvas *c0 = new TCanvas(); TFile *fin = new TFile( v_infile.at(f) ); TTree *tin = (TTree*)fin->Get("fitResults"); tin->Draw("bshield:bext:bshield_err:bext_err"); TGraphErrors *gshield = new TGraphErrors( tin->GetEntries(), tin->GetV2(), tin->GetV1(), tin->GetV4(), tin->GetV3() ); gshield->SetTitle(v_infile.at(f)); gshield->GetXaxis()->SetTitle("B_{ext} [mT]"); gshield->GetYaxis()->SetTitle("B_{shield} [mT]"); gshield->Draw("AP"); fin->Close(); if ( f == 0 ) c0->Print("plot_check_all.ps("); else if ( f == v_infile.size() - 1 ) c0->Print("plot_check_all.ps)"); else c0->Print("plot_check_all.ps"); } }
/// \brief Cache MC production trees, store summary information in formated text files -> root trees /// \param dataType - /// \param fileList void CacheTestMCProductions(TString dataType, const char *fileList=NULL){ AliExternalInfo info; info.fLoadMetadata=kFALSE; TObjArray* periodList = NULL; TArrayI nRuns; if (fileList!=NULL) { periodList=(gSystem->GetFromPipe(TString::Format("cat %s", fileList).Data())).Tokenize("\n"); nRuns.Set(periodList->GetEntries()); }else{ TTree * tree = info.GetTree("MonALISA.ProductionMC","",""); Int_t nProd=tree->GetEntries(); periodList = new TObjArray(nProd); nRuns.Set(nProd); TLeaf *leaf = tree->GetLeaf("Tag"); TLeaf *leafRuns = tree->GetLeaf("Number_of_runs"); for (Int_t iProd=0; iProd<nProd; iProd++){ tree->GetEntry(iProd); TString prodName=((char*)leaf->GetValuePointer()); if (prodName.Contains("LHC")==0) continue; periodList->AddAt(new TObjString(((char*)leaf->GetValuePointer())),iProd); nRuns[iProd]=leafRuns->GetValue(); } delete tree; } for (Int_t iPeriod=0; iPeriod<periodList->GetEntriesFast(); iPeriod++){ TObjString * pName= (TObjString*)periodList->At(iPeriod); if (pName==NULL) continue; TTree* tree = info.GetTree(dataType.Data(),periodList->At(iPeriod)->GetName(),"passMC"); if (tree){ Int_t entries=tree->Draw("run","1","goff"); TString sInfo=periodList->At(iPeriod)->GetName(); sInfo+="\t"; sInfo+=dataType; sInfo+="\t"; sInfo+=TString::Format("%d\t",entries); sInfo+=TString::Format("%d\t",nRuns[iPeriod]); for (Int_t j=0; j<entries; j++) { sInfo+=TString::Format("%2.0f,",tree->GetV1()[j]); ::Info("CacheTestMCProductionsRun:","%s\t%s\t%d\t%d\t%d\t%2.0f",periodList->At(iPeriod)->GetName(),dataType.Data(),entries,nRuns[iPeriod],j, tree->GetV1()[j]); } sInfo+="0"; ::Info("CacheTestMCProductionsPeriod:","%s\n",sInfo.Data()); delete tree; }else{ ::Error("CacheTestMCProductionsPeriod:","%s\t%s\t-1\t%d\t0",periodList->At(iPeriod)->GetName(), dataType.Data(),nRuns[iPeriod]); } } }
/* * The Calibration function reads in the * calibration file and returns a graph * that is used to find the relation * between current and magentic field * for the Helmholtz coil. */ TF1* Calibrate( const char* f_calib ) { /*Read in Calibration File*/ cout<< "processing file " << f_calib <<endl; TTree *TCalib = new TTree(); TCalib->ReadFile(f_calib, "t/D:I:B"); int n = TCalib->Draw("I:TMath::Abs(B)", "", "goff"); TGraph *g_calib = new TGraph(n, TCalib->GetV1(), TCalib->GetV2() ); g_calib->SetTitle(""); // g_calib->Draw("AP"); g_calib->Fit("pol1", "q"); TF1* calib_fit = g_calib->GetFunction("pol1"); return calib_fit; }
TGraphErrors* plot_ramp( const TString scan_file, double R, double R_sig ) { /*Read in Data File to ROOT Tree*/ cout<< "processing file " << scan_file <<endl; TTree *TData = new TTree(); TData->ReadFile(scan_file, "t/D:x:y:z:B1:B1Range:B2:B2Range:B3:B3Range:V:T1:T2:T3:T4:T5:T6:T7:T8"); /*Use TTree Draw command to write branches to usable vector*/ int n = TData->Draw("TMath::Abs(B2):TMath::Abs(B3):0.0:0.005", "", "goff"); vector<double> B_ext, B_in, Bratio, u, u_err; for(int i = 0; i < n; i++) { // if(i == 0) // { // B_ext.push_back(100.00); // } // else{ // B_ext.push_back( TData->GetV1()[i]); // } B_ext.push_back( TData->GetV1()[i] ); B_in.push_back( TData->GetV2()[i]); // B_in.push_back( 90.53); // if(TMath::Abs(B_in[i]) <= TMath::Abs(B_ext[i])) // { Bratio.push_back( B_in[i] / B_ext[i]); u.push_back( (Bratio[i]*(R**2) + Bratio[i] - 2 - 2*sqrt((Bratio[i]**2)*(R**2) - Bratio[i]*(R**2) - Bratio[i] + 1 ) ) / (Bratio[i]*(R**2) - Bratio[i]) ); // u_err.push_back( u[i]*( 5.5*((0.005/Bratio[i])**2.) + 10*((R_sig/R)**2.) )**0.5 ); u_err.push_back( 0.01 ); // u_err.push_back( u[i]*( 5.5*((0.01/Bratio[i])**2.)) )**0.5 ); // } } TGraphErrors *g_uvB = new TGraphErrors(n, &B_ext[0], &u[0], TData->GetV3(), &u_err[0]); return g_uvB; }
int evaluate( std::string filelist, std::string outfile ) { gStyle->SetOptStat(0); TCanvas *ctemp = new TCanvas(); TCanvas *cres = new TCanvas("TimeDependence"); TH1F* hres = new TH1F("hres","",100,0,650); hres->GetYaxis()->SetRangeUser(0,50); hres->SetTitle(""); hres->GetXaxis()->SetTitle("time (s)"); hres->GetYaxis()->SetTitle("B_{int} (mT)"); hres->Draw(); leg = new TLegend(0.2,0.6,0.9,0.9); // leg->SetHeader("The Legend Title"); // option "C" allows to center the header leg->SetNColumns(5); vector< double > v_Bint; vector< double > v_BintErr; vector< double > v_Bext; vector< double > v_BextErr; /* Loop over all lines in input file */ std::ifstream infilelist(filelist); std::string line; unsigned colorcounter=38; while (std::getline(infilelist, line)) { // skip lines with '#' and empty lines if ( line.find("#") != string::npos ) { cout << "Skip line " << line << endl; continue; } if ( line == "" ) continue; //cout << "Processing file " << line << endl; TString infilename("data_calib/"); infilename.Append(line); TFile *fin = new TFile( infilename ); TTree *tin = (TTree*)fin->Get("t"); ctemp->cd(); tin->Draw("Bi:time"); TGraph *gtime = new TGraph(tin->GetEntries(), &(tin->GetV2()[0]), &(tin->GetV1()[0])); gtime->SetLineColor(colorcounter); colorcounter++; TH1F* hBext = new TH1F("hBext","",100,0,1000); tin->Draw("Bo >> hBext"); cres->cd(); gtime->Draw("lsame"); double Bext_i = hBext->GetMean(); double BextErr_i = hBext->GetRMS(); double Bint_i = gtime->Eval(590); double BintErr_i = 0; /* add legend entry */ TString legname("B_ext ~ "); legname += (int)Bext_i; leg->AddEntry(gtime,legname,"l"); cout << "B_ext: " << Bext_i << " \t B_int: " << Bint_i << endl; v_Bint.push_back(Bint_i); v_BintErr.push_back(BintErr_i); v_Bext.push_back(Bext_i); v_BextErr.push_back(BextErr_i); } cres->cd(); leg->Draw(); TGraphErrors *gfinal = new TGraphErrors(v_Bext.size(), &(v_Bext[0]), &(v_Bint[0]), &(v_BextErr[0]), &(v_BintErr[0])); gfinal->Sort(); gfinal->SetName("Bint_Vs_Bext"); gfinal->SetTitle(""); gfinal->GetXaxis()->SetTitle("B_{ext} (mT)"); gfinal->GetYaxis()->SetTitle("B_{int} (mT)"); TCanvas *cfinal = new TCanvas(); gfinal->Draw("APL"); /* Save output graph */ TString outfilename("output/"); outfilename.Append(outfile); TFile *fout = new TFile(outfilename,"RECREATE"); cres->Write(); gfinal->Write(); fout->Close(); /* Write result to txt output file */ TString outfilenametxt = outfilename; outfilenametxt.ReplaceAll(".root",".txt"); ofstream foutxt; foutxt.open( outfilenametxt ); foutxt << "# Bo sig_Bo Bi sig_Bi shield sig_shield sf sig_sf time_dependent" << endl; for ( int i = 0; i < gfinal->GetN(); i++ ) { double Bo = gfinal->GetX()[i]; double sig_Bo = gfinal->GetEX()[i]; double Bi = gfinal->GetY()[i]; double sig_Bi = gfinal->GetEY()[i]; double shield = 0; double sig_shield = 0; double sf = 0; double sig_sf = 0; double time_dependent = 0; foutxt << Bo << " " << sig_Bo << " " << Bi << " " << sig_Bi << " " << shield << " " << sig_shield << " " << sf << " " << sig_sf << " " << time_dependent << endl; } return 0; }
void fillGraphFromTreeVar(std::string& treedrawspec,int index,wGraph_t *&pwg) { // Sample treedrawspec: // mytree:"TDCwinstart[%d]:runnum","evtnum==1","P" // vector<string> v_tokens; string tid; TString drawspec; Tokenize(treedrawspec,v_tokens,":",true); if( (v_tokens.size() < 2) || (!v_tokens[0].size()) || (!v_tokens[2].size()) ) { cerr << "malformed root tree draw spec treeid:\"varexp\",\"selection\",option: " << treedrawspec << endl; return; } tid = v_tokens[0]; for (size_t i=2; i<v_tokens.size(); i++) { drawspec += v_tokens[i]; } int fmtcnt = drawspec.CountChar('%'); if (fmtcnt) { // use index for tree array var switch(fmtcnt) { case 1: drawspec = Form(drawspec,index); break; case 2: drawspec = Form(drawspec,index,index); break; case 3: drawspec = Form(drawspec,index,index,index); break; case 4: drawspec = Form(drawspec,index,index,index,index); break; case 5: drawspec = Form(drawspec,index,index,index,index,index); break; case 6: drawspec = Form(drawspec,index,index,index,index,index,index); break; default: cerr << "More than six fmt specifiers in drawspec found, fix me! " << drawspec <<endl; exit(-1); } } if( gl_verbose) cout<<"drawspec="<<drawspec<<endl; TTree *tree = findTree(tid); assert (tree); // can't use comma as delimiter since histo with binning spec may be supplied TObjArray *tokens = drawspec.Tokenize("\""); TString hname; TString varexp = ((TObjString *)(*tokens)[0])->GetString(); if( gl_verbose) cout<<"varexp="<<varexp<<endl; switch(tokens->GetEntriesFast()) { case 1: tree->Draw(varexp,"","goff"); break; case 3: { TString cut = ((TObjString *)(*tokens)[2])->GetString(); tree->Draw(varexp,cut,"goff"); } break; case 4: // assume the cut string is blank { TString gopt = ((TObjString *)(*tokens)[3])->GetString(); gopt = gopt + " goff"; tree->Draw(varexp,"",gopt); } break; case 5: { TString cut = ((TObjString *)(*tokens)[2])->GetString(); TString gopt = ((TObjString *)(*tokens)[4])->GetString(); gopt = gopt + " goff"; tree->Draw(varexp,cut,gopt); } break; default: cerr << "malformed root tree draw spec treeid:varexp,selection,option"; for (int i=0; i<tokens->GetEntriesFast(); i++) cerr << i<<": "<< ((TObjString *)(*tokens)[i])->GetString() << " "; cerr << endl; break; } assert(tree->GetSelectedRows()); if (!pwg) pwg = new wGraph_t(); assert(pwg); pwg->gr = new TGraph(tree->GetSelectedRows(), tree->GetV2(), tree->GetV1()); } // fillGraphFromTreeVar
/*#include "TTree.h" #include "TCanvas.h" #include "TGraph.h" #include "TMultiGraph.h" #include "TRint.h" #include <time.h> #include <stdio.h> const short MaxNN = 6; */ void make_scatterplot(TString data_file, TString plot_name, TString header) { //TApplication program = new TRInt(); //pull in data TTree *t = new TTree(); t->ReadFile(data_file); t->SetName("t"); //TString name = "run2.png"; TCanvas *BG = new TCanvas("c1", "Read Velocity on Local Disk for CMS3 Files", 1920, 1080); BG->cd(); TPad *c = new TPad("MainPad", "My main pad", 0, 0, 1, 0.9); c->Draw(); c->Divide(2,2); //In first slot have Time vs. Buffer for 1 Concurrent Read c->cd(1); int n1 = t->Draw("VelocityMBps:BufferSize", "ConcurrentReads==1", "goff"); TGraph *ghist1 = new TGraph(n1, t->GetV2(), t->GetV1()); ghist1->SetName("ghist1"); ghist1->SetMarkerStyle(3); ghist1->SetMarkerColor(1); ghist1->SetTitle("Single File Read"); ghist1->GetXaxis()->SetTitle("Buffer Size (Bytes)"); ghist1->GetYaxis()->SetTitle("Read Velocity (MB/s)"); ghist1->Draw("ap"); //In second slot have Time vs. Buffer for 3 Concurrent Reads c->cd(2); int n2 = t->Draw("VelocityMBps:BufferSize", "ConcurrentReads==3", "goff"); TGraph *ghist2 = new TGraph(n2, t->GetV2(), t->GetV1()); Double_t DP2x[n2], DP2y[n2]; ghist2->SetName("ghist2"); ghist2->SetMarkerStyle(3); ghist2->SetMarkerColor(1); ghist2->SetTitle("3 Concurrent Reads"); ghist2->GetXaxis()->SetTitle("Buffer Size (Bytes)"); ghist2->GetYaxis()->SetTitle("Read Velocity (MB/s)"); ghist2->Draw("ap"); //In third slot have Time vs. Buffer for 3 Concurrent Reads c->cd(3); int n3 = t->Draw("VelocityMBps:BufferSize", "ConcurrentReads==6", "goff"); TGraph *ghist3 = new TGraph(n3, t->GetV2(), t->GetV1()); Double_t DP3x[n3], DP3y[n3]; ghist3->SetName("ghist3"); ghist3->SetMarkerStyle(3); ghist3->SetMarkerColor(1); ghist3->SetTitle("6 Concurrent Reads"); ghist3->GetXaxis()->SetTitle("Buffer Size (Bytes)"); ghist3->GetYaxis()->SetTitle("Read Velocity (MB/s)"); ghist3->Draw("ap"); //In fourth slot have Time vs. Buffer for 10 Concurrent Reads c->cd(4); int n4 = t->Draw("VelocityMBps:BufferSize", "ConcurrentReads==10", "goff"); TGraph *ghist4 = new TGraph(n4, t->GetV2(), t->GetV1()); ghist4->SetMarkerStyle(3); ghist4->SetName("ghist4"); ghist4->SetMarkerColor(1); ghist4->SetTitle("10 Concurrent Reads"); ghist4->GetXaxis()->SetTitle("Buffer Size (Bytes)"); ghist4->GetYaxis()->SetTitle("Read Velocity (MB/s)"); ghist4->Draw("ap"); //Draw to screen //Initialize Canvas c->cd(0); c->Draw(); BG->cd(); TText *title = new TText(.5,.95, header); title->SetTextAlign(22); title->Draw(); gDirectory->Add(ghist1); gDirectory->Add(ghist2); gDirectory->Add(ghist3); gDirectory->Add(ghist4); gDirectory->Add(t); gPad->SaveAs(plot_name); }
/// Cache MC production information void CacheTrendingProductions(TString dataType){ AliExternalInfo info; info.fLoadMetadata=kFALSE; TObjArray* periodList = NULL, *idList=NULL; // TTree * tree = info.GetTree("MonALISA.ProductionCycle","",""); Int_t nProd=tree->GetEntries(); periodList = new TObjArray(nProd); idList= new TObjArray(nProd); TLeaf *leafTag = tree->GetLeaf("Tag"); TLeaf *leafID = tree->GetLeaf("ID"); for (Int_t iProd=0; iProd<nProd; iProd++){ tree->GetEntry(iProd); TString prodName=((char*)leafTag->GetValuePointer()); TString idName =TString::Format("%d",TMath::Nint(leafID->GetValue())); if (prodName.Contains("LHC")==0) continue; periodList->AddAt(new TObjString(prodName),iProd); idList->AddAt(new TObjString(idName),iProd); } delete tree; // for (Int_t iPeriod=0; iPeriod<periodList->GetEntriesFast(); iPeriod++) { TObjString * pName= (TObjString*)idList->At(iPeriod); if (pName==NULL) continue; TTree* treeP = info.GetTreeProdCycleByID(idList->At(iPeriod)->GetName()); if (treeP==NULL) continue; TLeaf *leafOutput = treeP->GetLeaf("outputdir"); Int_t nRuns= treeP->GetEntries(); treeP->GetEntry(0); TString path=((char*)leafOutput->GetValuePointer()); TObjArray *pArray = path.Tokenize("/"); if (pArray==NULL) continue; Int_t nElems=pArray->GetEntries(); if (nElems<4) continue; TString aperiod=pArray->At(3)->GetName(); TString apass =pArray->At(nElems-1)->GetName(); delete pArray; ::Info("CacheTrendingProductions","%s\t%s\t%s\t%s\t%d",idList->At(iPeriod)->GetName(),path.Data(), aperiod.Data(),apass.Data(),nRuns); delete treeP; TTree* treeQA = info.GetTree(dataType.Data(),aperiod.Data(),apass.Data()); if (treeQA){ Int_t entries=treeQA->Draw("run","1","goff"); TString sInfo=aperiod; sInfo+="\t"; sInfo+=apass; sInfo+="\t"; sInfo+=dataType; sInfo+="\t"; sInfo+=TString::Format("%d\t",entries); sInfo+=TString::Format("%d\t",nRuns); for (Int_t j=0; j<entries; j++) { sInfo+=TString::Format("%2.0f,",treeQA->GetV1()[j]); ::Info("CacheTrendingProductionsRun:","%s\t%s\t%s\t%d\t%d\t%2.0f",aperiod.Data(),apass.Data(),dataType.Data(),entries,nRuns,treeQA->GetV1()[j]); } sInfo+="0"; ::Info("CacheTrendingProductionsPeriod:","%s\n",sInfo.Data()); delete treeQA; }else{ ::Error("CacheTrendingProductionsPeriod:","%s\t%s\t%s\t-1\t%d\t0",aperiod.Data(),apass.Data(), dataType.Data(),nRuns); } } }
int plot_compare_fun4all_eicroot() { /**** Chose input files ****/ /* File with IR mangets configuration*/ TString fname_irmag("example/proton-magnets-250GeV-opt2.dat"); /* File with Fun4All output*/ TString fname_fun4all("example/eRHIC_proton-magnets-250GeV-opt2_250GeV_0mrad.root"); /* File with EICROOT output*/ TString fname_eicroot("example/eicroot-track_proton-magnets-250GeV-opt2_250GeV_0mrad.txt"); /* Open iput file with trajectories from GEANT4 */ TFile *fin = new TFile(fname_fun4all); /* Get tree from file */ TTree *tin = (TTree*)fin->Get("T"); int nhits = 0; tin->SetBranchAddress("n_G4HIT_FWDDISC",&nhits); /* create graph of particle trajectory */ /* Use only first event (for now) */ tin->GetEntry(0); cout << "hits: " << nhits << endl; tin->Draw("G4HIT_FWDDISC.x:G4HIT_FWDDISC.z","Entry$==0",""); TGraph* g1 = new TGraph(nhits*2, &(tin->GetV2()[0]), &(tin->GetV1()[0])); g1->SetMarkerStyle(7); g1->SetMarkerSize(1); g1->SetMarkerColor(kRed); /* Get tree from file */ TTree *tin2 = new TTree(); tin2->ReadFile(fname_eicroot,"x/F:y:z"); int nhits = tin2->GetEntries(); tin2->Draw("x:z","",""); TGraph* g2 = new TGraph(nhits, &(tin2->GetV2()[0]), &(tin2->GetV1()[0])); g2->SetMarkerStyle(7); g2->SetMarkerSize(1); g2->SetMarkerColor(kGreen+1); /* Create frame histogram for plot */ TH1F *h1 = new TH1F("h1","",10,0,15000); h1->GetXaxis()->SetRangeUser(0,5000); h1->GetYaxis()->SetRangeUser(-50,70); h1->GetXaxis()->SetTitle("Z(cm)"); h1->GetYaxis()->SetTitle("X(cm)"); /* Plot frame histogram */ TCanvas *c1 = new TCanvas(); h1->Draw("AXIS"); /* Read IR configuration file- this needs to go somewhere else using parameters and a .root file to store them */ ifstream irstream(fname_irmag); if(!irstream.is_open()) { cout << "ERROR: Could not open IR configuration file " << fname_irmag << endl; return -1; } while(!irstream.eof()){ string str; getline(irstream, str); if(str[0] == '#') continue; //for comments stringstream ss(str); string name; double center_z, center_x, center_y, aperture_radius, length, angle, B, gradient; ss >> name >> center_z >> center_x >> center_y >> aperture_radius >> length >> angle >> B >> gradient; if ( name == "" ) continue; //for empty lines // convert units from m to cm center_x *= 100; center_y *= 100; center_z *= 100; aperture_radius *= 100; length *= 100; // define magnet outer radius float outer_radius = 30.0; // cm //flip sign of dipole field component- positive y axis in Geant4 is defined as 'up', // positive z axis as the hadron-going direction // in a right-handed coordinate system x,y,z B *= -1; // convert angle from millirad to rad angle = (angle / 1000.); // Place IR component cout << "New IR component: " << name << " at z = " << center_z << endl; string volname = "IRMAGNET_"; volname.append(name); /* Draw box for magnet position on canvas */ TPolyLine *b1 = TraceBox( angle, center_z, center_x, length, aperture_radius, outer_radius ); //upper box TPolyLine *b2 = TraceBox( angle, center_z, center_x, length, -1 * aperture_radius, -1 * outer_radius ); //lower box if(B != 0 && gradient == 0.0){ //dipole magnet b1->SetFillColor(kOrange+1); b2->SetFillColor(kOrange+1); } else if( B == 0 && gradient != 0.0){ //quad magnet b1->SetFillColor(kBlue+1); b2->SetFillColor(kBlue+1); } else{ //placeholder magnet b1->SetFillColor(kGray+1); b2->SetFillColor(kGray+1); } b1->Draw("Fsame"); b2->Draw("Fsame"); } /* draw particle trajectory */ g2->Draw("LPsame"); g1->Draw("LPsame"); return 0; }
int TrackParametrization( TString csvfile="fitslices_out.csv" ) { /* Read data from input file */ TTree *tres = new TTree(); tres->ReadFile( csvfile, "ptrue:etatrue:psig:psig_err:pmean:pmean_err:norm", ',' ); /* Print read-in tree */ tres->Print(); /* colors array */ unsigned colors[8] = {1,2,3,4,6,7,14,16}; /* Create vector of theta values to include for visualization*/ vector< double > etas_vis; etas_vis.push_back(-2.75); etas_vis.push_back(-2.25); etas_vis.push_back(-1.75); etas_vis.push_back(-0.25); etas_vis.push_back( 0.25); etas_vis.push_back( 1.75); etas_vis.push_back( 2.25); // etas_vis.push_back(-3.25); // etas_vis.push_back(-2.25); // etas_vis.push_back(-1.25); // etas_vis.push_back(-0.25); // etas_vis.push_back( 0.25); // etas_vis.push_back( 1.25); // etas_vis.push_back( 2.25); // etas_vis.push_back( 3.25); /* Create vector of theta values to include for fitting*/ vector< double > etas_fit; for ( double eta = -4.45; eta < 4.5; eta += 0.1 ) etas_fit.push_back( eta ); /* Create fit function */ TF1* f_momres = new TF1("f_momres", "sqrt( [0]*[0] + [1]*[1]*x*x )" ); cout << "\nFit function: " << f_momres->GetTitle() << "\n" << endl; /* Create scratch canvas */ TCanvas *cscratch = new TCanvas("cscratch"); /* Create framehistogram */ TH1F* hframe = new TH1F("hframe","",100,0,40); hframe->GetYaxis()->SetRangeUser(0,0.15); hframe->GetYaxis()->SetNdivisions(505); hframe->GetXaxis()->SetTitle("Momentum (GeV/c)"); hframe->GetYaxis()->SetTitle("#sigma_{p}/p"); /* create combined canvas plot */ TCanvas *c1 = new TCanvas(); hframe->Draw(); /* Create legend */ TLegend* leg_eta = new TLegend( 0.2, 0.6, 0.5, 0.9); leg_eta->SetNColumns(2); /* Create ofstream to write fit parameter results */ ofstream ofsfit("track_momres_new.csv"); ofsfit<<"eta,par1,par1err,par2,par2err"<<endl; /* Create resolution-vs-momentum plot with fits for each selected theta value */ for ( int i = 0; i < etas_fit.size(); i++ ) { /* Switch to scratch canvas */ cscratch->cd(); double eta = etas_fit.at(i); /* No tracking outside -4 < eta < 4 */ if ( eta < -4 || eta > 4 ) continue; cout << "\n***Eta = " << eta << endl; /* Define range of theta because float comparison with fixed value doesn't work too well for cuts in ROOT trees */ double eta_min = eta * 0.999; double eta_max = eta * 1.001; /* Cut for tree */ TCut cutx( Form("ptrue > 1 && ( (etatrue > 0 && (etatrue > %f && etatrue < %f)) || (etatrue < 0 && (etatrue < %f && etatrue > %f)) )", eta_min, eta_max, eta_min, eta_max) ); /* "Draw" tree on scratch canvas to fill V1...V4 arrays */ tres->Draw("psig:ptrue:psig_err:0", cutx ); /* Create TGraphErrors with selected data from tree */ TGraphErrors *gres = new TGraphErrors( tres->GetEntries(cutx), &(tres->GetV2())[0], &(tres->GetV1())[0], &(tres->GetV4())[0], &(tres->GetV3())[0] ); /* reset function parameters before fit */ f_momres->SetParameter(0,0.1); f_momres->SetParameter(1,0.1); /* Only plot pseudorapidities listed on etas_vis; if not plotting, still do the fit */ bool vis = false; int vi = 0; for ( vi = 0; vi < etas_vis.size(); vi++ ) { if ( abs( etas_vis.at(vi) - eta ) < 0.001 ) { vis = true; break; } } if ( vis ) { /* Add graph to legend */ leg_eta->AddEntry(gres, Form("#eta = %.1f", eta), "P"); /* Add graph to plot */ c1->cd(); gres->SetMarkerColor(colors[vi]); gres->Draw("Psame"); f_momres->SetLineColor(colors[vi]); gres->Fit(f_momres); } else { gres->Fit(f_momres); } /* Write fir results to file */ double par1 = f_momres->GetParameter(0); double par1err = f_momres->GetParError(0); double par2 = f_momres->GetParameter(1); double par2err = f_momres->GetParError(1); ofsfit << eta << "," << par1 << "," << par1err << "," << par2 << "," << par2err << endl; } /* Draw legend */ c1->cd(); //TCanvas *c2 = new TCanvas(); //hframe->Draw(); leg_eta->Draw(); /* Print plots */ c1->Print("track_momres_vareta.eps"); //c2->Print("track_momres_vareta_legend.eps"); /* Close output stream */ ofsfit.close(); return 0; }
int main() { Int_t nbins = 800, count = 0; Double_t integral; TFile *input = new TFile("FilterRMSComparison.root"); TFile *templatefile = new TFile("/home/marko/Desktop/H4Analysis/ntuples/Templates_APDs.old.root"); TTree *MyTree = (TTree*) input->Get("RMS"); TCanvas *can1 = new TCanvas("can1", "canvas", 1200,900); TCanvas *can2 = new TCanvas("can2", "canvas", 1200,1200); TCanvas *can3 = new TCanvas("can3", "canvas", 1200,1200); can1->Divide(1,3); can2->Divide(1,2); can3->Divide(1,2); MyTree->SetEntryList(0); TString listcut = "abs(unfilteredbslope)<6 && unfilteredampfit>700"; MyTree->Draw(">>myList", listcut, "entrylist"); TEntryList *myList = (TEntryList*) gDirectory->Get("myList"); MyTree->SetEntryList(myList); Int_t nevents = myList->GetN(); MyTree->Draw("unfilteredevent", "abs(unfilteredbslope)<6 && unfilteredampfit>700", "goff"); Double_t *vTemp = MyTree->GetV1(); Int_t *vEvent = new Int_t[nevents]; for (int iEntry = 0; iEntry<nevents; iEntry++) { vEvent[iEntry] = vTemp[iEntry]; } TString plot, plot2, cut; char name[50]; TH1F *histoave = new TH1F("histoave","Wave Pulse Average", nbins, -40, 120); TH1F *histoavefft = new TH1F("histoavefft","Wave Pulse Average FFT", nbins, 0, 5); TH1F *histoaveph = new TH1F("histoaveph","Wave Pulse Average Phase", nbins, 0, 800); TH1F *originaltemplate = (TH1F*) templatefile->Get("APD2_E50_G50_prof"); originaltemplate->Rebin(16); TH1F *templatehisto = new TH1F("templatehisto", "Template = Green, Average = Red", nbins, -40, 120); TH1F *difference = new TH1F("difference","Template vs. Average Difference", nbins, -40, 120); TH1F *percentdifference = new TH1F("percentdifference","Template vs. Average Percent Difference", nbins, -40, 120); for (Int_t i=0;i<nbins;i++) { templatehisto->SetBinContent(i+1, originaltemplate->GetBinContent(i+1)); } templatehisto->SetLineColor(kGreen+3); templatehisto->SetLineWidth(4); can2->cd(2); histoave->GetYaxis()->SetRangeUser(-.120,1.2); //templatehisto->Draw(); histoave->SetStats(0); histoave->Draw(); for (Int_t i=0;i<nevents;i++) { //for (Int_t i=0;i<10;i++) { if (vEvent[i]==513) continue; //event for which electronics die out for a bit halfway through TString histoname = "TempHisto_"; histoname += i; TString histoname2 = "TempHisto2_"; histoname2 += i; TH2F* TempHisto = new TH2F (histoname, "Temp Histo", nbins, -40, 120, 1000, -120, 800); //nanoseconds TH2F* TempHisto2 = new TH2F (histoname2, "Temp Histo", nbins, -40, 120, 1000, -120, 800); //nanoseconds TString h1name = "h1001_"; h1name += i; TString h1name2 = "h1002_"; h1name2 += i; TString h1name2fft = "h1002fft_"; h1name2 += i; TString h1name2ph = "h1002ph_"; h1name2 += i; TString h1name3 = "h1003_"; h1name3 += i; TString h1name4 = "h1004_"; h1name4 += i; TH1F *h1001 = new TH1F(h1name,"Red = Unfiltered, Blue = Filtered", nbins, -40, 120); TH1F *h1002 = new TH1F(h1name2,"h1002", nbins, -40, 120); TH1F *h1002fft = new TH1F(h1name2fft,"h1002fft", nbins, 0, 5); TH1F *h1002ph = new TH1F(h1name2ph,"h1002ph", nbins, 0, 800); TH1F *h1003 = new TH1F(h1name3,"Filtered WF - Unfiltered WF", nbins, -40, 120); TH1F *h1004 = new TH1F(h1name4,"Percent Change in Filtered WF - Unfiltered WF", nbins, -40, 120); plot = "unfilteredwfval:(unfilteredwftime-unfilteredtimeref)>>"; plot += histoname; plot2 = "filteredwfval:(filteredwftime-filteredtimeref)>>"; plot2 += histoname2; cut = "abs(unfilteredbslope)<6 && unfilteredampfit>700 && unfilteredevent=="; cut += vEvent[i]; MyTree->Draw(plot, cut, "goff"); TempHisto = (TH2F*) gDirectory->Get(histoname); h1001 = transform2Dto1D(TempHisto); MyTree->Draw(plot2, cut, "goff"); TempHisto2 = (TH2F*) gDirectory->Get(histoname2); h1002 = transform2Dto1D(TempHisto2); if (h1002->GetBinCenter(h1002->GetMaximumBin()) < 30) continue; sprintf(name, "Good Events/Event%d", vEvent[i]); strcat(name, ".png"); h1001->SetLineColor(kRed); h1002->SetLineColor(kBlue); h1001->SetStats(0); h1002->SetStats(0); //can1->cd(1); can1->cd(); h1001->GetXaxis()->SetTitle("Time (ns)"); h1001->GetYaxis()->SetTitle("Amplitude"); h1001->Draw(); h1002->Draw("same"); //for (Int_t i=0;i<nbins;i++) { // h1003->SetBinContent(i+1, (h1002->GetBinContent(i+1))-(h1001->GetBinContent(i+1))); // if (h1001->GetBinContent(i+1) != 0) h1004->SetBinContent(i+1, ((h1002->GetBinContent(i+1))-(h1001->GetBinContent(i+1)))/(h1001->GetBinContent(i+1))); // else h1004->SetBinContent(i+1, 0); //} //can1->cd(2); //h1003->Draw(); //can1->cd(3); //h1004->Draw(); //h1004->GetYaxis()->SetRangeUser(-0.1,0.1); //gPad->SetGrid(); can1->SaveAs(name); //h1002->FFT(h1002fft, "MAG"); //h1002->FFT(h1002ph, "PH"); //histoavefft->Add(histoavefft, h1002fft); //histoaveph->Add(histoaveph, h1002ph); histoave->Add(histoave, h1002); can2->cd(2); h1002->Scale(1./(h1002->GetMaximum())); h1002->Draw("same"); count++; delete TempHisto, TempHisto2, h1001, h1002, h1003, h1004, histoname, histoname2, h1name, h1name2, h1name3, h1name4; gDirectory->Clear(); } can2->cd(1); //histoavefft->Scale(1./count); //histoaveph->Scale(1./count); histoave->Scale(1./count); //Double_t *re_full = new Double_t[nbins]; //Double_t *im_full = new Double_t[nbins]; //TH1 *Throwaway = 0; //TH1F *invhistoave = new TH1F(invhistoave, "Average Pulse", nbins, -40, 120); //TVirtualFFT *invFFT = TVirtualFFT::FFT(1, &nbins, "C2R M K"); //for (Int_t n=0; n<nbins; n++) { // (re_full)[n]=(histoavefft->GetBinContent(n+1)*cos(histoaveph->GetBinContent(n+1))); // (im_full)[n]=(histoavefft->GetBinContent(n+1)*sin(histoaveph->GetBinContent(n+1))); //} //invFFT->SetPointsComplex(re_full, im_full); //invFFT->Transform(); //Throwaway = TH1::TransformHisto(invFFT, Throwaway, "Re"); //for (Int_t p=0; p<nbins; p++) { // histoave->SetBinContent(p+1, Throwaway->GetBinContent(p+1)/nbins); //} histoave->Scale(1./(histoave->GetMaximum())); histoave->SetLineColor(kRed); histoave->SetLineWidth(4); integral = templatehisto->Integral(); templatehisto->Scale(1./integral); templatehisto->SetStats(0); templatehisto->Draw(); integral = histoave->Integral(); histoave->Scale(1./integral); histoave->DrawClone("same"); histoave->Scale(integral); can2->cd(2); histoave->GetXaxis()->SetTitle("Time (ns)"); histoave->GetYaxis()->SetTitle("Normalized Amplitude"); histoave->DrawClone("same"); can2->SaveAs("AmpSpread.png"); can2->SaveAs("AmpSpreadRoot.root"); TFile *output = new TFile("Alignment.root", "recreate"); output->cd(); originaltemplate->Write(); histoave->Write(); templatehisto->Write(); output->Close(); can3->cd(1); histoave->Scale(1./integral); for (int i=0;i<nbins;i++) { difference->SetBinContent(i+1, histoave->GetBinContent(i+1) - templatehisto->GetBinContent(i+1)); if (templatehisto->GetBinContent(i+1) != 0) percentdifference->SetBinContent(i+1, (histoave->GetBinContent(i+1) - templatehisto->GetBinContent(i+1))/templatehisto->GetBinContent(i+1)); else percentdifference->SetBinContent(i+1, 0); } difference->GetXaxis()->SetTitle("Time (ns)"); difference->GetYaxis()->SetTitle("Average - Template"); difference->SetStats(0); difference->Draw(); can3->cd(2); percentdifference->GetXaxis()->SetTitle("Time (ns)"); percentdifference->GetYaxis()->SetTitle("Percent Difference Average - Template"); percentdifference->SetStats(0); percentdifference->Draw(); percentdifference->GetYaxis()->SetRangeUser(-0.1,0.1); gPad->SetGrid(); can3->SaveAs("Difference.png"); can3->SaveAs("Difference.root"); }
int plot_Fun4All_All_DeltaEta_DeltaPhi() { const std::string inFile = "LeptoAna_1000events_All.root"; const std::string inDirectory = "/gpfs/mnt/gpfs02/phenix/scratch/jlab/Leptoquark/"; std::string inputFile = inDirectory+inFile; TFile *f = TFile::Open(inputFile.c_str()); TTree *t = (TTree*)f->Get("ntp_leptoquark"); // const int Nevent = t->GetMaximum("event"); const int Nevent = 100; cout << "Running " << Nevent << " events" << endl; const int Nentries1 = t->Draw("isMaxEnergyJet","(isMaxEnergyJet<10)*(calorimeterid<10)","goff"); Double_t *arr_jet = t->GetV1(); vector<int> v_jet(Nentries1); for(int i = 0; i < Nentries1; i++) { v_jet[i] = (int)arr_jet[i]; } const int Nentries = t->Draw("towereta:towerphi:towerenergy:event","(isMaxEnergyJet<10)*(calorimeterid<10)","goff"); Double_t *arr_eta = t->GetV1(); Double_t *arr_phi = t->GetV2(); Double_t *arr_e = t->GetV3(); Double_t *arr_event = t->GetV4(); if(Nentries1 != Nentries) { cerr << "ERROR: Draw commands to not return the same dimensions. Check that your logical expressions are the same." << endl; return -1; } vector<double> v_DeltaEta, v_DeltaPhi, v_DeltaTheta, v_Energy; vector<double> v_DeltaEta_j2, v_DeltaPhi_j2, v_DeltaTheta_j2, v_Energy_j2; for(int i = 0; i < Nevent; i++) { double Emax = 0; int Emax_i = 0; double Emax_j2 = 0; int Emax_i_j2 = 0; for(int j = 0; j < Nentries; j++) { if((t->GetV4()[j]-1 == i) && (v_jet[j] == 1)) { if(t->GetV3()[j] > Emax) { Emax = t->GetV3()[j]; Emax_i = j; } } if((t->GetV4()[j]-1 == i) && (v_jet[j] == 2)) { if(t->GetV3()[j] > Emax_j2) { Emax_j2 = t->GetV3()[j]; Emax_i_j2 = j; } } } for(int j = 0; j < Nentries; j++) { if((t->GetV4()[j]-1 == i) && (v_jet[j] == 1)) { v_DeltaEta.push_back(t->GetV1()[j] - t->GetV1()[Emax_i]); v_DeltaTheta.push_back(2*TMath::ATan(TMath::Power(TMath::E(),-1*t->GetV1()[j])) - 2*TMath::ATan(TMath::Power(TMath::E(),-1*t->GetV1()[Emax_i]))); v_DeltaPhi.push_back(t->GetV2()[j] - t->GetV2()[Emax_i]); v_Energy.push_back(t->GetV3()[j]); } if((t->GetV4()[j]-1 == i) && (v_jet[j] == 2)) { v_DeltaEta_j2.push_back(t->GetV1()[j] - t->GetV1()[Emax_i_j2]); v_DeltaTheta_j2.push_back(2*TMath::ATan(TMath::Power(TMath::E(),-1*t->GetV1()[j])) - 2*TMath::ATan(TMath::Power(TMath::E(),-1*t->GetV1()[Emax_i_j2]))); v_DeltaPhi_j2.push_back(t->GetV2()[j] - t->GetV2()[Emax_i_j2]); v_Energy_j2.push_back(t->GetV3()[j]); } } } //----------------------------------------------------------------------------------------------------------- gStyle->SetOptStat(0); double xmin = -1; double xmax = 1; double ymin = -0.5; double ymax = 0.5; std::string title = "isMaxJetEnergy = 1"; TCanvas *c1 = new TCanvas(); TH2D *h1 = new TH2D("h1",title.c_str(),40,xmin,xmax,40,ymin,ymax); for(int i = 0; (unsigned)i < v_DeltaEta.size(); i++) { h1->Fill(v_DeltaEta[i],v_DeltaPhi[i], v_Energy[i]/Nevent); } c1->SetLogz(); h1->Draw("colz"); // h1->SetMinimum(1); // h1->SetMaximum(1000); h1->GetXaxis()->SetTitle("#Delta#eta"); h1->GetYaxis()->SetTitle("#Delta#phi"); c1->Update(); //----------------------------------------------------------------------------------------------------------- std::string title2 = "isMaxJetEnergy = 2"; TCanvas *c2 = new TCanvas(); TH2D *h2 = new TH2D("h2",title2.c_str(),40,xmin,xmax,40,ymin,ymax); for(int i = 0; (unsigned)i < v_DeltaEta_j2.size(); i++) { h2->Fill(v_DeltaEta_j2[i],v_DeltaPhi_j2[i], v_Energy_j2[i]/Nevent); } c2->SetLogz(); h2->Draw("colz"); // h2->SetMinimum(1); // h2->SetMaximum(1000); h2->GetXaxis()->SetTitle("#Delta#eta"); h2->GetYaxis()->SetTitle("#Delta#phi"); c2->Update(); //----------------------------------------------------------------------------------------------------------- TCanvas *c3 = new TCanvas(); TH1D *h3 = h1->ProjectionY(); h3->SetLineColor(kGreen+3); TH1D *h4 = h2->ProjectionY(); h4->SetLineColor(kBlue); TF1 *f3 = new TF1("f3", "gaus", ymin, ymax); f3->SetLineColor(kGreen+3); h3->Fit("f3","Q R"); TF1 *f4 = new TF1("f4", "gaus", ymin, ymax); f4->SetLineColor(kBlue+2); h4->Fit("f4","Q R"); h3->Draw(); h4->Draw("SAME"); TLegend *leg = new TLegend(0.2,0.9,0.7,0.75); leg->SetBorderSize(1); leg->AddEntry(h3,title.c_str(),"l"); leg->AddEntry(h4,title2.c_str(),"l"); leg->Draw("SAME"); c3->Update(); cout << endl; cout << "*******************************************************" << endl; cout << "Ratio of Gaussian Width to Max Energy:" << endl; cout << " for: " << title << " -> " << f3->GetParameter(2) << " / " << h3->GetBinContent(h3->GetMaximumBin()) << " = " << f3->GetParameter(2) / h3->GetBinContent(h3->GetMaximumBin()) << endl; cout << " for: " << title2 << " -> " << f4->GetParameter(2) << " / " << h4->GetBinContent(h4->GetMaximumBin()) << " = " << f4->GetParameter(2) / h4->GetBinContent(h4->GetMaximumBin()) << endl; cout << " Ratio of ratios: " << (f3->GetParameter(2) / h3->GetBinContent(h3->GetMaximumBin())) / (f4->GetParameter(2) / h4->GetBinContent(h4->GetMaximumBin())) << endl; cout << "*******************************************************" << endl; cout << endl; c1->Close(); c2->Close(); c3->Close(); //----------------------------------------------------------------------------------------------------------- vector<double> v_Ratios; for(int i = 0; i < Nevent; i++) { TH1D *h5 = new TH1D("h5","",20,ymin*2,ymax*2); TH1D *h6 = new TH1D("h6","",20,ymin*2,ymax*2); for(int j = 0; j < Nentries/100; j++) { if((t->GetV4()[j]-1 == i) && (v_jet[j] == 1)) { h5->Fill(v_DeltaPhi[j], v_Energy[j]); } if((t->GetV4()[j]-1 == i) && (v_jet[j] == 2)) { h6->Fill(v_DeltaPhi_j2[j], v_Energy_j2[j]); } } TF1 *f5 = new TF1("f5", "gaus", ymin, ymax); f3->SetLineColor(kGreen+3); h5->Fit("f5","Q"); TF1 *f6 = new TF1("f6", "gaus", ymin, ymax); f6->SetLineColor(kBlue+2); h6->Fit("f6","Q"); TCanvas *c5 = new TCanvas(); h5->Draw(); TCanvas *c6 = new TCanvas(); h6->Draw(); // cout << endl; // cout << "Ratio of Gaussian Width to Max Energy:" << endl; // cout << " for: " << title << " -> " << f5->GetParameter(2) << " / " << h5->GetBinContent(h5->GetMaximumBin()) // << " = " << f5->GetParameter(2) / h5->GetBinContent(h5->GetMaximumBin()) << endl; // cout << " for: " << title2 << " -> " << f6->GetParameter(2) << " / " << h6->GetBinContent(h6->GetMaximumBin()) // << " = " << f6->GetParameter(2) / h6->GetBinContent(h6->GetMaximumBin()) << endl; cout << " Ratio of ratios for event " << i+1 << " : " << (f5->GetParameter(2) / h5->GetBinContent(h5->GetMaximumBin())) / (f6->GetParameter(2) / h6->GetBinContent(h6->GetMaximumBin())) << endl; if((f5->GetParameter(2) / h5->GetBinContent(h5->GetMaximumBin())) / (f6->GetParameter(2) / h6->GetBinContent(h6->GetMaximumBin())) != NAN) v_Ratios.push_back((f5->GetParameter(2) / h5->GetBinContent(h5->GetMaximumBin())) / (f6->GetParameter(2) / h6->GetBinContent(h6->GetMaximumBin()))); delete h5; delete h6; c5->Close(); c6->Close(); } TCanvas *c7 = new TCanvas(); TH1D *h7 = new TH1D("h7","",400,-200,200); for(int i = 0; (unsigned)i < v_Ratios.size(); i++) { h7->Fill(v_Ratios[i]); } h7->Draw(); return 0; }
plot_stability_mean(){ gStyle->SetOptStat(0); TTree *tfit = new TTree(); tfit->ReadFile("pi0peak_fit_Run13pp510ERT_reformat.txt","run_index/F:run_number:nevents:sector:mean:dmean:sigma:dsigma:chisquare"); TTree *tfit_raw = new TTree(); tfit_raw->ReadFile("pi0peak_fit_raw_Run13pp510ERT_reformat.txt","run_index/F:run_number:nevents:sector:mean:dmean:sigma:dsigma:chisquare"); TLine *lpi0 = new TLine( 0, 0.137, tfit->GetEntries("sector==0"), 0.137 ); lpi0->SetLineColor(kRed); // frame TH1F* hframe = new TH1F("hframe","",875,0,875); hframe->GetYaxis()->SetRangeUser(0.12,0.16); hframe->GetXaxis()->SetTitle("run"); hframe->GetYaxis()->SetTitle("mean [GeV]"); hframe->SetLineColor(kWhite); // sectors PbSc-West tfit->Draw("mean:run_index:dmean","sector==0"); TGraphErrors *g_mean_PbScW = new TGraphErrors( tfit->GetEntries("sector==0"), tfit->GetV2(), tfit->GetV1(), 0, tfit->GetV3()); tfit_raw->Draw("mean:run_index:dmean","sector==0"); TGraphErrors *g_mean_PbScW_raw = new TGraphErrors( tfit_raw->GetEntries("sector==0"), tfit_raw->GetV2(), tfit_raw->GetV1(), 0, tfit_raw->GetV3()); // sectors PbSc-East tfit->Draw("mean:run_index:dmean","sector==1"); TGraphErrors *g_mean_PbScE = new TGraphErrors( tfit->GetEntries("sector==1"), tfit->GetV2(), tfit->GetV1(), 0, tfit->GetV3()); tfit_raw->Draw("mean:run_index:dmean","sector==1"); TGraphErrors *g_mean_PbScE_raw = new TGraphErrors( tfit_raw->GetEntries("sector==1"), tfit_raw->GetV2(), tfit_raw->GetV1(), 0, tfit_raw->GetV3()); // sectors PbGl-East tfit->Draw("mean:run_index:dmean","sector==2"); TGraphErrors *g_mean_PbGlE = new TGraphErrors( tfit->GetEntries("sector==2"), tfit->GetV2(), tfit->GetV1(), 0, tfit->GetV3()); tfit_raw->Draw("mean:run_index:dmean","sector==2"); TGraphErrors *g_mean_PbGlE_raw = new TGraphErrors( tfit_raw->GetEntries("sector==2"), tfit_raw->GetV2(), tfit_raw->GetV1(), 0, tfit_raw->GetV3()); // Plotting TCanvas *c_PbScW = new TCanvas(); hframe->Draw(); g_mean_PbScW->Draw("Psame"); lpi0->Draw("same"); c_PbScW->Print("plots-escale-check/mpi0_mean_PbScW.png"); TCanvas *c_PbScW_raw = new TCanvas(); hframe->Draw(); g_mean_PbScW_raw->Draw("Psame"); lpi0->Draw("same"); c_PbScW_raw->Print("plots-escale-check/mpi0_mean_PbScW_raw.png"); TCanvas *c_PbScE = new TCanvas(); hframe->Draw(); g_mean_PbScE->Draw("Psame"); lpi0->Draw("same"); c_PbScE->Print("plots-escale-check/mpi0_mean_PbScE.png"); TCanvas *c_PbScE_raw = new TCanvas(); hframe->Draw(); g_mean_PbScE_raw->Draw("Psame"); lpi0->Draw("same"); c_PbScE_raw->Print("plots-escale-check/mpi0_mean_PbScE_raw.png"); TCanvas *c_PbGlE = new TCanvas(); hframe->Draw(); g_mean_PbGlE->Draw("Psame"); lpi0->Draw("same"); c_PbGlE->Print("plots-escale-check/mpi0_mean_PbGlE.png"); TCanvas *c_PbGlE_raw = new TCanvas(); hframe->Draw(); g_mean_PbGlE_raw->Draw("Psame"); lpi0->Draw("same"); c_PbGlE_raw->Print("plots-escale-check/mpi0_mean_PbGlE_raw.png"); }
void plotL1Digis(Long64_t entryNum=1) { TH1::SetDefaultSumw2(); TString inputFile = "L1UpgradeAnalyzer.root"; TString inputFileunp = "L1UnpackedUnpacker.root"; TFile *inFile = TFile::Open(inputFile); TFile *inFileunp = TFile::Open(inputFileunp); TTree *emulatorResults = (TTree*)inFile->Get("L1UpgradeAnalyzer/L1UpgradeTree"); TTree *unpackerResults = (TTree*)inFileunp->Get("UnpackerResults/L1UpgradeTree"); //TCut entryCut = Form("Entry$ == %i", entryNum); //TCut entryCutUnpacker = Form("Entry$ == %i",entryNum+179); TEntryList* elist = new TEntryList(unpackerResults); for ( int bx(0); bx<100; bx++) { if ( !unpackerResults->Draw("Entry$",Form("FEDBXID == %i", bx), "nodraw" ) ) continue; elist->Enter(unpackerResults->GetV1()[0], unpackerResults); } unpackerResults->SetEntryList(elist); elist->Print(); const int nHISTS = 30; TString labels[nHISTS] = {"region_et", "region_eta", "region_phi", "egcand_rank", "egcand_eta", "egcand_phi", "central_jet_hwPt", "central_jet_hwEta", "central_jet_hwPhi", "forward_jet_hwPt", "forward_jet_hwEta", "forward_jet_hwPhi", "ETT", "HTT", "MET_Rank", "MET_Phi", "MHT_Rank", "MHT_Phi", "iso_egamma_hwPt", "iso_egamma_hwEta", "iso_egamma_hwPhi", "noniso_egamma_hwPt", "noniso_egamma_hwEta", "noniso_egamma_hwPhi", "tau_hwPt", "tau_hwEta", "tau_hwPhi", "isotau_hwPt", "isotau_hwEta", "isotau_hwPhi"}; TString projectionnames[nHISTS] = {"legacyregion_et", "legacyregion_gctEta", "legacyregion_gctPhi", "legacyemcand_rank", "legacyemcand_regionEta", "legacyemcand_regionPhi", "jet_hwPt", "jet_hwEta", "jet_hwPhi", "jet_hwPt", "jet_hwEta", "jet_hwPhi", "etsum_hwPt", "etsum_hwPt", "etsum_hwPt","etsum_hwPhi","etsum_hwPt","etsum_hwPhi", "egamma_hwPt", "egamma_hwEta", "egamma_hwPhi", "egamma_hwPt", "egamma_hwEta", "egamma_hwPhi", "tau_hwPt", "tau_hwEta", "tau_hwPhi", "isotau_hwPt", "isotau_hwEta", "isotau_hwPhi"}; TCut projectioncuts[nHISTS] = {"", "", "", "", "", "", "(jet_hwQual&0x2)!=0x2&&jet_bx==0","(jet_hwQual&0x2)!=0x2&&jet_bx==0","(jet_hwQual&0x2)!=0x2&&jet_bx==0", "(jet_hwQual&0x2)==0x2&&jet_bx==0","(jet_hwQual&0x2)==0x2&&jet_bx==0","(jet_hwQual&0x2)==0x2&&jet_bx==0", "etsum_type==0&&etsum_bx==0","etsum_type==1&&etsum_bx==0", "etsum_type==2&&etsum_bx==0","etsum_type==2&&etsum_bx==0","etsum_type==3&&etsum_bx==0","etsum_type==3&&etsum_bx==0", "egamma_hwIso==1&&egamma_bx==0", "egamma_hwIso==1&&egamma_bx==0", "egamma_hwIso==1&&egamma_bx==0", "egamma_hwIso==0&&egamma_bx==0", "egamma_hwIso==0&&egamma_bx==0", "egamma_hwIso==0&&egamma_bx==0", "tau_bx==0", "tau_bx==0", "tau_bx==0", "isotau_bx==0", "isotau_bx==0", "isotau_bx==0"}; Int_t minBin[nHISTS] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Int_t maxBin[nHISTS] = {40, 22, 25, 64, 22, 25, 64,22,25, 64,22,25, 600, 300, 200, 70, 200, 30, 64, 22, 25, 64, 22, 25, 64, 22, 25, 64, 25, 25}; TH1I *hists[nHISTS][2]; TH1D *divs[nHISTS]; TCanvas *c[nHISTS]; for(int i = 0; i < nHISTS; ++i) { hists[i][0] = new TH1I(labels[i], ";"+labels[i], maxBin[i]-minBin[i], minBin[i], maxBin[i]); hists[i][1] = (TH1I*)hists[i][0]->Clone(labels[i]+"unpacked"); divs[i] = new TH1D(labels[i]+"div", ";"+labels[i], maxBin[i]-minBin[i], minBin[i], maxBin[i]); //emulatorResults->Project(hists[i][0]->GetName(), projectionnames[i], projectioncuts[i]&&entryCut); //unpackerResults->Project(hists[i][1]->GetName(), projectionnames[i], projectioncuts[i]&&entryCutUnpacker); emulatorResults->Project(hists[i][0]->GetName(), projectionnames[i], projectioncuts[i]); unpackerResults->Project(hists[i][1]->GetName(), projectionnames[i], projectioncuts[i]); divs[i]->Divide(hists[i][1], hists[i][0]); for (int m=1;m<=hists[i][1]->GetNbinsX();m++){ if(hists[i][1]->GetBinContent(m)==hists[i][0]->GetBinContent(m)) divs[i]->SetBinContent(m,1); } hists[i][0]->SetLineWidth(5); hists[i][0]->SetMarkerColor(kRed); hists[i][0]->SetLineColor(kRed); hists[i][1]->SetLineWidth(2); c[i] = new TCanvas(); c[i]->Divide(1,2); c[i]->cd(1); hists[i][0]->Draw("hist"); hists[i][1]->Draw("hist same"); TLegend* legend= new TLegend(0.72578,0.7917988,0.9002463,0.9371476); legend->SetFillColor(0); legend->SetLineColor(kGray+2); legend->SetTextFont(42); ent=legend->AddEntry(hists[i][0],"Emulator","F"); ent=legend->AddEntry(hists[i][1],"Unpacked","F"); legend->Draw(); c[i]->cd(2); divs[i]->SetLineWidth(3); divs[i]->GetYaxis()->SetTitle("Ratio unpacked/emulated"); divs[i]->Draw("hist"); c[i]->SaveAs(Form("figs/%s.pdf",labels[i].Data())); } }
int plot_track_multi() { /* Select input files (output from Fun4All) for plotting */ vector<string> v_filenames; v_filenames.push_back( "data/eRHIC_updated-magnets-2017_proton_275GeV_22mrad.root" ); v_filenames.push_back( "data/eRHIC_updated-magnets-2017_proton_275GeV_27mrad.root" ); v_filenames.push_back( "data/eRHIC_updated-magnets-2017_proton_275GeV_17mrad.root" ); TObjArray* graphs = new TObjArray(); for ( i = 0; i < v_filenames.size(); i++ ) { /* Open iput file with trajectories from GEANT4 */ TFile *fin = new TFile( v_filenames.at(i).c_str(), "OPEN" ); /* Get tree from file */ TTree *tin = (TTree*)fin->Get("T"); int nhits = 0; tin->SetBranchAddress("n_G4HIT_FWDDISC",&nhits); /* create graph of particle trajectory */ /* Use only first event (for now) */ tin->GetEntry(0); cout << "hits: " << nhits << endl; tin->Draw("G4HIT_FWDDISC.x:G4HIT_FWDDISC.z","Entry$==0",""); TGraph* g1 = new TGraph(nhits*2, &(tin->GetV2()[0]), &(tin->GetV1()[0])); g1->SetMarkerStyle(7); g1->SetMarkerSize(1); graphs->Add( g1 ); } /* Create frame histogram for plot */ TH1F *h1 = new TH1F("h1","",10,0,15000); h1->GetXaxis()->SetRangeUser(0,12000); h1->GetYaxis()->SetRangeUser(-50,200); h1->GetXaxis()->SetTitle("Z(cm)"); h1->GetYaxis()->SetTitle("X(cm)"); /* Plot frame histogram */ TCanvas *c1 = new TCanvas(); h1->Draw("AXIS"); /* Read IR configuration file- this needs to go somewhere else using parameters and a .root file to store them */ string irfile = "data/updated-magnets-2017.dat"; ifstream irstream(irfile.c_str()); while(!irstream.eof()){ string str; getline(irstream, str); if(str[0] == '#') continue; //for comments stringstream ss(str); string name; double center_z, center_x, center_y, aperture_radius, length, angle, B, gradient; ss >> name >> center_z >> center_x >> center_y >> aperture_radius >> length >> angle >> B >> gradient; if ( name == "" ) continue; //for empty lines // convert units from m to cm center_x *= 100; center_y *= 100; center_z *= 100; aperture_radius *= 100; length *= 100; // define magnet outer radius float outer_radius = 30.0; // cm //flip sign of dipole field component- positive y axis in Geant4 is defined as 'up', // positive z axis as the hadron-going direction // in a right-handed coordinate system x,y,z B *= -1; // convert angle from millirad to rad angle = (angle / 1000.); // Place IR component cout << "New IR component: " << name << " at z = " << center_z << endl; string volname = "IRMAGNET_"; volname.append(name); /* Draw box for magnet position on canvas */ TPolyLine *b1 = TraceBox( angle, center_z, center_x, length, aperture_radius, outer_radius ); //upper box TPolyLine *b2 = TraceBox( angle, center_z, center_x, length, -1 * aperture_radius, -1 * outer_radius ); //lower box if(B != 0 && gradient == 0.0){ //dipole magnet b1->SetFillColor(kOrange+1); b2->SetFillColor(kOrange+1); } else if( B == 0 && gradient != 0.0){ //quad magnet b1->SetFillColor(kBlue+1); b2->SetFillColor(kBlue+1); } else{ //placeholder magnet b1->SetFillColor(kGray+1); b2->SetFillColor(kGray+1); } b1->Draw("Fsame"); b2->Draw("Fsame"); } /* draw particle trajectory */ for ( int i = 0; i < graphs->GetEntries(); i++ ) { graphs->At(i)->Draw("LPsame"); } c1->Print("multitrack_new.eps"); return 0; }
///**** LL **** void doMC_LL(){ TTree* MyTreeMC = (TTree*) fileInMC->Get(treeNameMC.c_str()); for (nIter = 0; nIter<maxIter; nIter++){ if (!(nIter%1)) std::cerr << ">>> nIter = " << nIter << " : " << maxIter << std::endl; vET_data.clear(); outFile->cd(); TString nameDATA = Form("hDATA_%d_%d_%.5f",Data_or_MC,nIter,ScaleTrue); TH1F hDATA(nameDATA,nameDATA,numBINS,minBINS,maxBINS); MyTreeMC->Draw(">> myListMC",(AdditionalCut+Form("&& (ET * (1+(%f)))>%f",ScaleTrue,minET)).Data(),"entrylist"); TEntryList *myListMC = (TEntryList*)gDirectory->Get("myListMC"); MyTreeMC->SetEntryList(0); TEntryList *listMCHere = new TEntryList("listMCHere","listMCHere"); for (int iEvt = 0; iEvt < numSelectedData; iEvt ++){ listMCHere->Enter(myListMC->GetEntry(gRandom->Uniform(0,myListMC->GetN()))); } MyTreeMC->SetEntryList(listMCHere); MyTreeMC->Draw(Form("(1+%f) * %s >> %s",ScaleTrue,variableName.c_str(),nameDATA.Data())); ConvertStdVectDouble(vET_data,MyTreeMC->GetV1(),numSelectedData); ///==== likelihood ==== std::cerr << " === LL === " << std::endl; std::cerr << " === pseudo vET_data.size() = " << vET_data.size() << std::endl; minuit->SetFunction(functorLL); TGraph * grLL_temp = new TGraph(iNoSteps); minuit->Scan(iPar_NoBG,iNoSteps,grLL_temp->GetX(),grLL_temp->GetY(),MinScan,MaxScan); TGraph * grLL = new TGraph(); int nPointLL = 0; for (unsigned int iStep = 0; iStep < iNoSteps; iStep++){ double x = MinScan + (MaxScan - MinScan) / iNoSteps * (iStep+0.5); double y = LLFunc(&x); if (y != numberDATA * numEvents) { grLL->SetPoint(nPointLL,x,y); nPointLL++; } } grLL->Draw("AL"); outFile->cd(); minuit->PrintResults(); const double *outParametersTemp2 = minuit->X(); const double *errParametersTemp2 = minuit->Errors(); double *outParametersLL = new double; double *errParametersLL = new double; outParametersLL[0] = outParametersTemp2[0]; errParametersLL[0] = errParametersTemp2[0]; std::cerr << " nPointLL = " << nPointLL << std::endl; double minLL = grLL->Eval(outParametersLL[0]); ///==== end likelihood ==== ///==== Save the whole shape of LL/Chi2 ==== for (unsigned int ii=0; ii < iNoSteps; ii++){ double X_ii = (MaxScan - MinScan) / iNoSteps * ii + MinScan; Alpha = X_ii; Chi2 = 0; LL = grLL->Eval(X_ii); NewChi2 = 0; myTreeChi2->Fill(); } ///===== Look for minima ===== double a; double b; double c; double errX_low = -9999; double errX_up = 9999; int err_low = 0; int err_up = 0; for (unsigned int ii=0; ii < iNoSteps; ii++){ double X_ii = (MaxScan - MinScan) / iNoSteps * ii + MinScan; double here = grLL->Eval(X_ii); if (err_low == 0){ if (here < (minLL + DELTA_LL)){ errX_low = X_ii; err_low = 1; } } else if (err_up == 0 && here > (minLL + DELTA_LL) && X_ii > outParametersLL[0]){ errX_up = X_ii; err_up = 1; } } AlphaMean = outParametersLL[0]; AlphaMinus = errX_low; AlphaPlus = errX_up; grLL->Fit("fitMin","RMQ"); c = fitMin->GetParameter(0); b = fitMin->GetParameter(1); a = fitMin->GetParameter(2); AlphaMean_Fit = -b / (2*a); AlphaMinus_Fit = (-b + sqrt(2*a)) / (2*a); ///==== delta LL = 0.5 AlphaPlus_Fit = (-b - sqrt(2*a)) / (2*a); ///==== delta LL = 0.5 myTreeLL_Result->Fill(); grLL->Write(); //delete listMCHere; } }
int main(int argc, char** argv){ ///======================================================================================= ///==== Calculate Scale from Data (minimization Chi2 and more) ///==== then perform toy MC to see the error on THAT scale with THAT statistics available ///======================================================================================= if(argc != 2) { std::cerr << ">>>>> analysis.cpp::usage: " << argv[0] << " configFileName" << std::endl ; return 1; } // Parse the config file std::string fileName (argv[1]) ; boost::shared_ptr<edm::ProcessDesc> processDesc = edm::readConfigFile(fileName) ; boost::shared_ptr<edm::ParameterSet> parameterSet = processDesc->getProcessPSet () ; edm::ParameterSet subPSetInput = parameterSet->getParameter<edm::ParameterSet> ("inputTree") ; std::string treeNameDATA = subPSetInput.getParameter<std::string> ("treeNameDATA") ; std::string inputFileDATA = subPSetInput.getParameter<std::string> ("inputFileDATA") ; treeNameMC = subPSetInput.getParameter<std::string> ("treeNameMC") ; std::string inputFileMC = subPSetInput.getParameter<std::string> ("inputFileMC") ; std::cout << ">>>>> InputDATA::treeName " << treeNameDATA << std::endl; std::cout << ">>>>> InputDATA::inputFile " << inputFileDATA << std::endl; std::cout << ">>>>> InputMC::treeName " << treeNameMC << std::endl; std::cout << ">>>>> InputMC::inputFile " << inputFileMC << std::endl; edm::ParameterSet subPSetOutput = parameterSet->getParameter<edm::ParameterSet> ("outputTree") ; std::string outputFile = subPSetOutput.getParameter<std::string> ("outputFile") ; std::cout << ">>>>> Output::outputFile " << outputFile << std::endl; edm::ParameterSet subPSetOptions = parameterSet->getParameter<edm::ParameterSet> ("options") ; MinScan = subPSetOptions.getParameter<double> ("MinScan") ; MaxScan = subPSetOptions.getParameter<double> ("MaxScan") ; iNoSteps = subPSetOptions.getParameter<int> ("iNoSteps") ; std::cout << ">>>>> Options::MinScan " << MinScan << std::endl; std::cout << ">>>>> Options::MaxScan " << MaxScan << std::endl; std::cout << ">>>>> Options::iNoSteps " << iNoSteps << std::endl; MinScanRange = subPSetOptions.getParameter<double> ("MinScanRange") ; MaxScanRange = subPSetOptions.getParameter<double> ("MaxScanRange") ; std::cout << ">>>>> Options::MinScanRange " << MinScanRange << std::endl; std::cout << ">>>>> Options::MaxScanRange " << MaxScanRange << std::endl; minBINS = subPSetOptions.getParameter<double> ("minBINS") ; maxBINS = subPSetOptions.getParameter<double> ("maxBINS") ; numBINS = subPSetOptions.getParameter<int> ("numBINS") ; std::cout << ">>>>> Options::numBINS " << numBINS << std::endl; std::cout << ">>>>> Options::minBINS " << minBINS << std::endl; std::cout << ">>>>> Options::maxBINS " << maxBINS << std::endl; NBINTemplate = 10 * numBINS; MinTemplate = minBINS; MaxTemplate = maxBINS; Delta = (MaxTemplate - MinTemplate) / NBINTemplate; variableName = subPSetOptions.getParameter<std::string> ("variableName") ; std::cout << ">>>>> Options::variableName " << variableName.c_str() << std::endl; double minET = subPSetOptions.getParameter<double> ("minET") ; std::cout << ">>>>> Options::minET " << minET << std::endl; std::string temp_cut = subPSetOptions.getParameter<std::string> ("cut") ; std::cout << ">>>>> Options::cut " << temp_cut.c_str() << std::endl; AdditionalCut = Form("%s",temp_cut.c_str()); std::cout << ">>>>> Options::AdditionalCut " << AdditionalCut.Data() << std::endl; EEEB = subPSetOptions.getParameter<int> ("EEorEB"); std::cout << ">>>>> Options::EEEB " << EEEB << std::endl; ///==== 0 = EE+EB ///==== 1 = EE ///==== 2 = EB ///==== 3 = EE+ ///==== 4 = EE- if (EEEB == 1) { ///==== EE AdditionalCut = Form("%s && (eta > 1.5 || eta < -1.5)",AdditionalCut.Data()); } if (EEEB == 2) { ///==== EB AdditionalCut = Form("%s && (eta < 1.5 && eta > -1.5)",AdditionalCut.Data()); } if (EEEB == 3) { ///==== EE+ AdditionalCut = Form("%s && (eta > 1.5)",AdditionalCut.Data()); } if (EEEB == 4) { ///==== EE- AdditionalCut = Form("%s && (eta < -1.5)",AdditionalCut.Data()); } if (EEEB == 5) { ///==== EB mod 1 AdditionalCut = Form("%s && (abs(eta) < 0.435)",AdditionalCut.Data()); } if (EEEB == 6) { ///==== EB mod 2 AdditionalCut = Form("%s && (abs(eta) < 0.783 && abs(eta) > 0.435)",AdditionalCut.Data()); } if (EEEB == 7) { ///==== EB mod 3 AdditionalCut = Form("%s && (abs(eta) < 1.131 && abs(eta) > 0.783)",AdditionalCut.Data()); } if (EEEB == 8) { ///==== EB mod 4 AdditionalCut = Form("%s && (abs(eta) < 1.479 && abs(eta) > 1.131)",AdditionalCut.Data()); } if (EEEB == 9) { ///==== EE No ES AdditionalCut = Form("%s && (abs(eta) > 2.5)",AdditionalCut.Data()); } if (EEEB == 10) { ///==== EE + ES AdditionalCut = Form("%s && (abs(eta) < 2.5 && abs(eta) > 1.5)",AdditionalCut.Data()); } if (EEEB == 11) { ///==== EE- + ES AdditionalCut = Form("%s && (eta > -2.5 && eta < -1.5)",AdditionalCut.Data()); } if (EEEB == 12) { ///==== EE+ + ES AdditionalCut = Form("%s && (eta < 2.5 && eta > 1.5)",AdditionalCut.Data()); } std::cout << ">>>>> :: " << AdditionalCut.Data() << std::endl; maxIter = subPSetOptions.getParameter<int> ("numToyMC") ; std::cout << ">>>>> Options::numToyMC " << maxIter << std::endl; ///==== DATA ==== fileInDATA = new TFile(inputFileDATA.c_str(),"READ"); ///==== W ==== fileInMC = new TFile(inputFileMC.c_str(),"READ"); ///==== output ==== outFile = new TFile(outputFile.c_str(),"RECREATE"); outFile->cd(); double ScaleTrue_Chi2; double ScaleTrue_Chi2_Fit; double ScaleTrue_LL; double ScaleTrue_LL_Fit; double ScaleTrue_NewChi2; double ScaleTrue_NewChi2_Fit; ///==== Prepare output trees ==== myTreeChi2 = new TTree("myTreeChi2","myTreeChi2"); myTreeChi2->Branch("Data_or_MC",&Data_or_MC,"Data_or_MC/I"); myTreeChi2->Branch("Alpha",&Alpha,"Alpha/D"); myTreeChi2->Branch("Chi2",&Chi2,"Chi2/D"); myTreeChi2->Branch("NewChi2",&NewChi2,"NewChi2/D"); myTreeChi2->Branch("LL",&LL,"LL/D"); myTreeChi2->Branch("ScaleTrue",&ScaleTrue,"ScaleTrue/D"); myTreeChi2_Result = new TTree("myTreeChi2_Result","myTreeChi2_Result"); myTreeChi2_Result->Branch("Data_or_MC",&Data_or_MC,"Data_or_MC/I"); myTreeChi2_Result->Branch("AlphaMean",&AlphaMean,"AlphaMean/D"); myTreeChi2_Result->Branch("AlphaMinus",&AlphaMinus,"AlphaMinus/D"); myTreeChi2_Result->Branch("AlphaPlus",&AlphaPlus,"AlphaPlus/D"); myTreeChi2_Result->Branch("AlphaMean_Fit",&AlphaMean_Fit,"AlphaMean_Fit/D"); myTreeChi2_Result->Branch("AlphaMinus_Fit",&AlphaMinus_Fit,"AlphaMinus_Fit/D"); myTreeChi2_Result->Branch("AlphaPlus_Fit",&AlphaPlus_Fit,"AlphaPlus_Fit/D"); myTreeChi2_Result->Branch("ScaleTrue",&ScaleTrue,"ScaleTrue/D"); myTreeLL_Result = new TTree("myTreeLL_Result","myTreeLL_Result"); myTreeLL_Result->Branch("Data_or_MC",&Data_or_MC,"Data_or_MC/I"); myTreeLL_Result->Branch("AlphaMean",&AlphaMean,"AlphaMean/D"); myTreeLL_Result->Branch("AlphaMinus",&AlphaMinus,"AlphaMinus/D"); myTreeLL_Result->Branch("AlphaPlus",&AlphaPlus,"AlphaPlus/D"); myTreeLL_Result->Branch("AlphaMean_Fit",&AlphaMean_Fit,"AlphaMean_Fit/D"); myTreeLL_Result->Branch("AlphaMinus_Fit",&AlphaMinus_Fit,"AlphaMinus_Fit/D"); myTreeLL_Result->Branch("AlphaPlus_Fit",&AlphaPlus_Fit,"AlphaPlus_Fit/D"); myTreeLL_Result->Branch("ScaleTrue",&ScaleTrue,"ScaleTrue/D"); myTreeNewChi2_Result = new TTree("myTreeNewChi2_Result","myTreeNewChi2_Result"); myTreeNewChi2_Result->Branch("Data_or_MC",&Data_or_MC,"Data_or_MC/I"); myTreeNewChi2_Result->Branch("AlphaMean",&AlphaMean,"AlphaMean/D"); myTreeNewChi2_Result->Branch("AlphaMinus",&AlphaMinus,"AlphaMinus/D"); myTreeNewChi2_Result->Branch("AlphaPlus",&AlphaPlus,"AlphaPlus/D"); myTreeNewChi2_Result->Branch("AlphaMean_Fit",&AlphaMean_Fit,"AlphaMean_Fit/D"); myTreeNewChi2_Result->Branch("AlphaMinus_Fit",&AlphaMinus_Fit,"AlphaMinus_Fit/D"); myTreeNewChi2_Result->Branch("AlphaPlus_Fit",&AlphaPlus_Fit,"AlphaPlus_Fit/D"); myTreeNewChi2_Result->Branch("ScaleTrue",&ScaleTrue,"ScaleTrue/D"); ///==== Prepare input trees ==== TTree* MyTreeDATA = (TTree*) fileInDATA->Get(treeNameDATA.c_str()); MyTreeDATA->SetBranchAddress("pT",&pT); MyTreeDATA->SetBranchAddress("ET",&ET); MyTreeDATA->SetBranchAddress("MT",&MT); MyTreeDATA->SetBranchAddress("EoP",&EoP); MyTreeDATA->SetBranchAddress("eta",&eta); MyTreeDATA->SetBranchAddress("E5x5",&E5x5); MyTreeDATA->SetBranchAddress("p",&p); MyTreeDATA->SetBranchAddress("eleES",&eleES); MyTreeDATA->SetBranchAddress("eleFBrem",&eleFBrem); TTree* MyTreeMC = (TTree*) fileInMC->Get(treeNameMC.c_str()); MyTreeMC->SetBranchAddress("pT",&pT); MyTreeMC->SetBranchAddress("ET",&ET); MyTreeMC->SetBranchAddress("MT",&MT); MyTreeMC->SetBranchAddress("EoP",&EoP); MyTreeMC->SetBranchAddress("eta",&eta); MyTreeMC->SetBranchAddress("E5x5",&E5x5); MyTreeMC->SetBranchAddress("p",&p); MyTreeMC->SetBranchAddress("eleES",&eleES); MyTreeMC->SetBranchAddress("eleFBrem",&eleFBrem); numEntriesMC = MyTreeMC->GetEntries(); ///==== prepare minuit ==== fitMin->SetRange(MinScanRange,MaxScanRange); double step[1] = {0.001}; double variable[1] = {0.0}; minuit->SetLimitedVariable(0,"Scale" , variable[0] , step[0] , MinScan , MaxScan ); ///=========================== ///==== DATA Scale search ==== ScaleTrue = -1000; ///==== default Data_or_MC = 1; ///=== 1 = Data; 0 = MC; numEvents = MyTreeDATA->GetEntries(); //==== number of events in Data sample outFile->cd(); vET_data.clear(); nIter = 1000000000; ///==== less than 1000000000 iterations at the end !!! TString nameDATA = Form("hDATA_%d_%d_%.5f",Data_or_MC,nIter,ScaleTrue); TH1F hDATA(nameDATA,nameDATA,numBINS,minBINS,maxBINS); MyTreeDATA->Draw(">> myList",(AdditionalCut + Form(" && ET > %f",minET)).Data(),"entrylist"); TEntryList *mylist = (TEntryList*)gDirectory->Get("myList"); MyTreeDATA->SetEntryList(mylist); MyTreeDATA->Draw(Form("%s >> %s",variableName.c_str(),nameDATA.Data())); ConvertStdVectDouble(vET_data,MyTreeDATA->GetV1(),mylist->GetN()); hDATA.Write(); std::cerr << "... I'm minimizing ... DATA analysis" << std::endl; std::cerr << ">>>>>>> numEvents = " << numEvents << " => " << vET_data.size() << " selected (=" << mylist->GetN() << ")" << std::endl; numSelectedData = vET_data.size(); ///===== Chi2 ==== std::cerr << " === Chi2 === " << std::endl; minuit->SetFunction(functorChi2); TGraph * grChi2 = new TGraph(iNoSteps); minuit->Scan(iPar_NoBG,iNoSteps,grChi2->GetX(),grChi2->GetY(),MinScan,MaxScan); // TGraph * grChi2 = new TGraph(); // for (int iStep = 0; iStep < iNoSteps; iStep++){ // double x = MinScan + (MaxScan - MinScan) / iNoSteps * (iStep+0.5); // double y = Chi2F(&x); // grChi2->SetPoint(iStep+1,x,y); // } grChi2->Draw("AL"); outFile->cd(); minuit->PrintResults(); outFile->cd(); grChi2->SetTitle("grChi2"); grChi2->Write(); const double *outParametersTemp = minuit->X(); const double *errParametersTemp = minuit->Errors(); double *outParameters = new double; double *errParameters = new double; outParameters[0] = outParametersTemp[0]; errParameters[0] = errParametersTemp[0]; double minChi2 = grChi2->Eval(outParameters[0]); std::cerr << " numEvents = " << numEvents << " Scale = " << outParameters[0] << " +/- " << errParameters[0] << std::endl; ///===== end Chi2 ==== ///==== likelihood ==== std::cerr << " === LL === " << std::endl; minuit->SetFunction(functorLL); TGraph * grLL_temp = new TGraph(iNoSteps); minuit->Scan(iPar_NoBG,iNoSteps,grLL_temp->GetX(),grLL_temp->GetY(),MinScan,MaxScan); TGraph * grLL = new TGraph(); grLL->SetName("grLL"); int nPointLL = 0; for (unsigned int iStep = 0; iStep < iNoSteps; iStep++){ double x = MinScan + (MaxScan - MinScan) / iNoSteps * (iStep+0.5); double y = LLFunc(&x); // std::cerr << " y = " << y << std::endl; if (y != numberDATA * numEvents) { std::cerr << " Ok y = " << y << std::endl; grLL->SetPoint(nPointLL,x,y); nPointLL++; } } std::cerr << " finito " << std::endl; grLL->Draw("AL"); outFile->cd(); minuit->PrintResults(); outFile->cd(); grLL->SetTitle("grLL"); grLL->Write(); std::cerr << " done " << std::endl; const double *outParametersTemp2 = minuit->X(); const double *errParametersTemp2 = minuit->Errors(); std::cerr << " done 2 " << std::endl; double *outParametersLL = new double; double *errParametersLL = new double; outParametersLL[0] = outParametersTemp2[0]; errParametersLL[0] = errParametersTemp2[0]; double minLL = grLL->Eval(outParametersLL[0]); std::cerr << " numEvents = " << numEvents << " Scale = " << outParametersLL[0] << " +/- " << errParametersLL[0] << std::endl; ///==== end likelihood ==== ///==== newChi2 ==== std::cerr << " === newChi2 === " << std::endl; minuit->SetFunction(functorNewChi2); TGraph * grNewChi2 = new TGraph(iNoSteps); minuit->Scan(iPar_NoBG,iNoSteps,grNewChi2->GetX(),grNewChi2->GetY(),MinScan,MaxScan); grNewChi2->Draw("AL"); outFile->cd(); minuit->PrintResults(); outFile->cd(); grNewChi2->SetTitle("grNewChi2"); grNewChi2->Write(); const double *outParametersNewChi2 = minuit->X(); const double *errParametersNewChi2 = minuit->Errors(); double minNewChi2 = grNewChi2->Eval(outParametersNewChi2[0]); std::cerr << " numEvents = " << numEvents << " Scale = " << outParametersNewChi2[0] << " +/- " << errParametersNewChi2[0] << std::endl; ///==== end newChi2 ==== std::cerr << "... Minimized with all methods ..." << std::endl; ///==== Save the whole shape of LL/Chi2 ==== for (unsigned int ii=0; ii < iNoSteps; ii++){ double X_ii = (MaxScan - MinScan) / iNoSteps * ii + MinScan; Alpha = X_ii; Chi2 = grChi2->Eval(X_ii); LL = grLL->Eval(X_ii); NewChi2 = grNewChi2->Eval(X_ii); myTreeChi2->Fill(); } ///===== Look for minima ===== ///===== Chi2 ==== std::cerr << " === Chi2 === " << std::endl; std::cerr << "==== min Scan = " << minChi2 << std::endl; double errX_low = -9999; double errX_up = 9999; int err_low = 0; int err_up = 0; for (unsigned int ii=0; ii < iNoSteps; ii++){ double X_ii = (MaxScan - MinScan) / iNoSteps * ii + MinScan; double here = grChi2->Eval(X_ii); if (err_low == 0){ if (here < (minChi2 + DELTA_CHI2)){ errX_low = X_ii; err_low = 1; } } else if (err_up == 0 && here > (minChi2 + DELTA_CHI2) && X_ii > outParameters[0]){ errX_up = X_ii; err_up = 1; } } AlphaMean = outParameters[0]; AlphaMinus = errX_low; AlphaPlus = errX_up; grChi2->Fit("fitMin","RMQ"); c = fitMin->GetParameter(0); b = fitMin->GetParameter(1); a = fitMin->GetParameter(2); AlphaMean_Fit = -b / (2*a); AlphaMinus_Fit = (-b + 2 * sqrt(a)) / (2*a); ///==== delta Chi2 = 1 AlphaPlus_Fit = (-b - 2 * sqrt(a)) / (2*a); ///==== delta Chi2 = 1 myTreeChi2_Result->Fill(); ScaleTrue_Chi2 = AlphaMean; ScaleTrue_Chi2_Fit = AlphaMean_Fit; ///===== LogLikelihood ==== std::cerr << " === LL === " << std::endl; std::cerr << "==== min Scan = " << minLL << std::endl; errX_low = -9999; errX_up = 9999; err_low = 0; err_up = 0; for (unsigned int ii=0; ii < iNoSteps; ii++){ double X_ii = (MaxScan - MinScan) / iNoSteps * ii + MinScan; double here = grLL->Eval(X_ii); if (err_low == 0){ if (here < (minLL + DELTA_LL)){ errX_low = X_ii; err_low = 1; } } else if (err_up == 0 && here > (minLL + DELTA_LL) && X_ii > outParametersLL[0]){ errX_up = X_ii; err_up = 1; } } AlphaMean = outParametersLL[0]; AlphaMinus = errX_low; AlphaPlus = errX_up; grLL->Fit("fitMin","RMQ"); c = fitMin->GetParameter(0); b = fitMin->GetParameter(1); a = fitMin->GetParameter(2); AlphaMean_Fit = -b / (2*a); AlphaMinus_Fit = (-b + sqrt(2*a)) / (2*a); ///==== delta LL = 0.5 AlphaPlus_Fit = (-b - sqrt(2*a)) / (2*a); ///==== delta LL = 0.5 myTreeLL_Result->Fill(); ScaleTrue_LL = AlphaMean; ScaleTrue_LL_Fit = AlphaMean_Fit; ///===== NewChi2 ==== std::cerr << " === NewChi2 === " << std::endl; std::cerr << "==== min Scan = " << minNewChi2 << std::endl; errX_low = -9999; errX_up = 9999; err_low = 0; err_up = 0; for (unsigned int ii=0; ii < iNoSteps; ii++){ double X_ii = (MaxScan - MinScan) / iNoSteps * ii + MinScan; double here = grNewChi2->Eval(X_ii); if (err_low == 0){ if (here < (minNewChi2 + DELTA_CHI2)){ errX_low = X_ii; err_low = 1; } } else if (err_up == 0 && here > (minNewChi2 + DELTA_CHI2) && X_ii > outParametersNewChi2[0]){ errX_up = X_ii; err_up = 1; } } AlphaMean = outParametersNewChi2[0]; AlphaMinus = errX_low; AlphaPlus = errX_up; grNewChi2->Fit("fitMin","RMQ"); c = fitMin->GetParameter(0); b = fitMin->GetParameter(1); a = fitMin->GetParameter(2); AlphaMean_Fit = -b / (2*a); AlphaMinus_Fit = (-b + 2 * sqrt(a)) / (2*a); ///==== delta Chi2 = 1 AlphaPlus_Fit = (-b - 2 * sqrt(a)) / (2*a); ///==== delta Chi2 = 1 myTreeNewChi2_Result->Fill(); ScaleTrue_NewChi2 = AlphaMean; ScaleTrue_NewChi2_Fit = AlphaMean_Fit; std::cerr << " ================ End DATA Scale search ================ " << std::endl; ///==== MC analysis ==== Scale search ==== Data_or_MC = 0; ///=== 1 = Data; 0 = MC; -1 = MC Fit std::cerr << " ==== MC Scale search ==== " << std::endl; ///==== cycle on number of Toy MC experiments ==== ///=== Chi2 === std::cerr << "======================= Chi2 " << ScaleTrue_Chi2 << " =====================" << std::endl; // ScaleTrue = ScaleTrue_Chi2; // doMC_Chi2(); ///=== LogLikelihood === std::cerr << "======================= LL " << ScaleTrue_LL << " =====================" << std::endl; // ScaleTrue = ScaleTrue_LL; // doMC_LL(); ///=== NewChi2 === std::cerr << "======================= NewChi2 " << ScaleTrue_NewChi2 << " =====================" << std::endl; // ScaleTrue = ScaleTrue_NewChi2; // doMC_NewChi2(); Data_or_MC = -1; ///=== 1 = Data; 0 = MC; -1 = MC Fit std::cerr << " ==== MC Scale search ==== " << std::endl; ///==== cycle on number of Toy MC experiments ==== ///=== Chi2 === std::cerr << "======================= Chi2 FIT " << ScaleTrue_Chi2_Fit << " =====================" << std::endl; // ScaleTrue = ScaleTrue_Chi2_Fit; // doMC_Chi2(); ///=== LogLikelihood === std::cerr << "======================= LL FIT " << ScaleTrue_LL_Fit << " =====================" << std::endl; ScaleTrue = ScaleTrue_LL_Fit; doMC_LL(); ///=== NewChi2 === std::cerr << "======================= NewChi2 FIT " << ScaleTrue_NewChi2_Fit << " =====================" << std::endl; // ScaleTrue = ScaleTrue_NewChi2_Fit; // doMC_NewChi2(); ///---------------------- ///---- Plot results ---- ///---------------------- outFile->cd(); myTreeChi2->Write(); myTreeLL_Result->Write(); myTreeChi2_Result->Write(); myTreeNewChi2_Result->Write(); delete fitMin; }
///**** NewChi2 **** void doMC_NewChi2(){ TTree* MyTreeMC = (TTree*) fileInMC->Get(treeNameMC.c_str()); for (nIter = 0; nIter<maxIter; nIter++){ if (!(nIter%1)) std::cerr << ">>> nIter = " << nIter << " : " << maxIter << std::endl; vET_data.clear(); outFile->cd(); TString nameDATA = Form("hDATA_%d_%d_%.5f",Data_or_MC,nIter,ScaleTrue); TH1F hDATA(nameDATA,nameDATA,numBINS,minBINS,maxBINS); MyTreeMC->Draw(">> myListMC",(AdditionalCut+Form("&& (ET * (1+(%f)))>%f",ScaleTrue,minET)).Data(),"entrylist"); TEntryList *myListMC = (TEntryList*)gDirectory->Get("myListMC"); MyTreeMC->SetEntryList(0); TEntryList *listMCHere = new TEntryList("listMCHere","listMCHere"); for (int iEvt = 0; iEvt < numSelectedData; iEvt ++){ listMCHere->Enter(myListMC->GetEntry(gRandom->Uniform(0,myListMC->GetN()))); } MyTreeMC->SetEntryList(listMCHere); MyTreeMC->Draw(Form("(1+%f) * %s >> %s",ScaleTrue,variableName.c_str(),nameDATA.Data())); ConvertStdVectDouble(vET_data,MyTreeMC->GetV1(),numSelectedData); ///==== newChi2 ==== minuit->SetFunction(functorNewChi2); TGraph * grNewChi2 = new TGraph(iNoSteps); minuit->Scan(iPar_NoBG,iNoSteps,grNewChi2->GetX(),grNewChi2->GetY(),MinScan,MaxScan); grNewChi2->Draw("AL"); outFile->cd(); minuit->PrintResults(); const double *outParametersNewChi2 = minuit->X(); const double *errParametersNewChi2 = minuit->Errors(); double minNewChi2 = grNewChi2->Eval(outParametersNewChi2[0]); ///==== end newChi2 ==== ///==== Save the whole shape of LL/Chi2 ==== for (unsigned int ii=0; ii < iNoSteps; ii++){ double X_ii = (MaxScan - MinScan) / iNoSteps * ii + MinScan; Alpha = X_ii; Chi2 = 0; LL = 0; NewChi2 = grNewChi2->Eval(X_ii); myTreeChi2->Fill(); } ///===== Look for minima ===== double a; double b; double c; double errX_low = -9999; double errX_up = 9999; int err_low = 0; int err_up = 0; for (unsigned int ii=0; ii < iNoSteps; ii++){ double X_ii = (MaxScan - MinScan) / iNoSteps * ii + MinScan; double here = grNewChi2->Eval(X_ii); if (err_low == 0){ if (here < (minNewChi2 + DELTA_CHI2)){ errX_low = X_ii; err_low = 1; } } else if (err_up == 0 && here > (minNewChi2 + DELTA_CHI2) && X_ii > outParametersNewChi2[0]){ errX_up = X_ii; err_up = 1; } } AlphaMean = outParametersNewChi2[0]; AlphaMinus = errX_low; AlphaPlus = errX_up; grNewChi2->Fit("fitMin","RMQ"); c = fitMin->GetParameter(0); b = fitMin->GetParameter(1); a = fitMin->GetParameter(2); AlphaMean_Fit = -b / (2*a); AlphaMinus_Fit = (-b + 2 * sqrt(a)) / (2*a); ///==== delta Chi2 = 1 AlphaPlus_Fit = (-b - 2 * sqrt(a)) / (2*a); ///==== delta Chi2 = 1 myTreeNewChi2_Result->Fill(); // delete listMCHere; } }