Double_t calc_dNdY(const char *data_file = "pt_RFE", Bool_t show = kFALSE) { TGraphErrors *g = new TGraphErrors(data_file); if (g->IsZombie()) return; TF1 *flt = new TF1("flt", LevyTsallis, 0., 5., 4); flt->SetParameters(2.93483e-02, 2.80382e-01, 8.10224e+00, 1.01944e+00); flt->FixParameter(3, 1.019445); Double_t fitmin = 0.25, fitmax = 5.25; // !!! g->Fit(flt, "Q", "", fitmin, fitmax); g->Fit(flt, "Q", "", fitmin, fitmax); g->Fit(flt, "Q", "", fitmin, fitmax); Double_t first, last; // !!! bining sensibility !!! Int_t graph_range[2] = {2, 23}; // [2] = 0.05 - 0.01, [23] = 4.70 + 0.01 // interval 1 first = 0.0; // !!! last = g->GetX()[graph_range[0]] - g->GetErrorX(graph_range[0]); Double_t fi1 = flt->Integral(first, last); // interval 2 first = last; last = g->GetX()[graph_range[1]] + g->GetErrorX(graph_range[1]); Double_t fi2 = flt->Integral(first, last); Double_t gi2 = 0.0; for (Int_t ip = graph_range[0]; ip <= graph_range[1]; ip++) gi2 += g->GetY()[ip]*g->GetErrorX(ip)*2.0; // interval 3 first = last; last = 30.0; // !!! Double_t fi3 = flt->Integral(first, last); Double_t result = fi1 + gi2 + fi3; if (!show) { delete g; delete flt; return result; } Printf("function: %f \t %f \t %f", fi1, fi2, fi3); Printf("graph: \t \t \t %f", gi2); Printf("result => %f", result); g->Draw("AP"); gPad->SetLogy(); return result; }
TGraphErrors* ExtractCalCurve(vector<calData>& FitPositions, vector<Float_t>& Energies) //void ExtractCalCurve(vector<Float_t>& FitPositions, vector<Float_t>& Energies) { //TF1* calFit = new TF1("calFit","[0]*x + [1]",0,800E3); TGraphErrors* calCurve = new TGraphErrors(Energies.size()); //Get highest energy peak and estimate [0] std::vector<calData>::iterator pit; std::vector<Float_t>::iterator eit; pit = max_element(FitPositions.begin(),FitPositions.end(),CompareByadc); eit = max_element(Energies.begin(),Energies.end()); //Extrapolate coefficient and place first point int currPoint = 1; calCurve->SetPoint(currPoint,(*pit).fadc,*eit); calCurve->SetPointError(currPoint,(*pit).efadc,0.0); TFitResultPtr r = calCurve->Fit("pol1","SQ"); Float_t a = r->Parameter(1); Float_t CurrentPeak = 0.0; Float_t CurrentEnergy = 0.0; Float_t CurrentEnergyEst = 0.0; // Loop through found peaks and locate closest estimated energy // Assume fitted peaks are already ordered from lowest to highest for(std::vector<calData>::iterator i = --(FitPositions.end()); i!=FitPositions.begin(); --i) { currPoint++; CurrentPeak = (*i).fadc; CurrentEnergyEst = CurrentPeak*a; Float_t CurrentDelta = 800E3; for(std::vector<Float_t>::iterator j = Energies.begin(); j!=Energies.end(); j++) { if( abs(*j - CurrentEnergyEst) < CurrentDelta) { CurrentDelta = abs(*j - CurrentEnergyEst); CurrentEnergy = *j; } } calCurve->SetPoint(currPoint,CurrentPeak,CurrentEnergy); calCurve->SetPointError(currPoint,(*i).efadc,CurrentDelta); r = calCurve->Fit("pol1","SQ"); a = r->Parameter(1); } r->Print("V"); return calCurve; }
void draw() { gStyle->SetOptStat(0000); TGraphErrors* gr = new TGraphErrors("papel_um.txt", "%lg %lg %lg %lg"); gr->Draw("A"); gr->GetXaxis()->SetTitle("Diametro (mm)"); gr->GetYaxis()->SetTitle("Massa (u.m.)"); gr->SetTitle("Dimensao Fractal - Papel"); gr->SetMarkerStyle(20); gr->SetMarkerSize(gr->GetMarkerSize()/2.); TCanvas* c1 = new TCanvas(); gr->Draw("AP"); c1->Print("gr1.png"); TGraphErrors* grlog = new TGraphErrors(); for (int i=0; i<gr->GetN(); i++) { grlog->SetPoint(i, TMath::Log(gr->GetX()[i]), TMath::Log(gr->GetY()[i])); grlog->SetPointError(i, gr->GetEX()[i]/gr->GetX()[i], 0.0); } grlog->Draw("A"); grlog->GetXaxis()->SetTitle("Logaritmo do diametro (diametro em mm)"); grlog->GetYaxis()->SetTitle("Logaritmo da massa (massa em unidade arbitraria)"); grlog->SetTitle("Dimensao Fractal - Papel"); grlog->SetMarkerStyle(20); // grlog->SetMarkerSize(gr->GetMarkerSize()/2.); grlog->Fit("pol1"); TCanvas* c2 = new TCanvas(); grlog->Draw("AP"); c2->Print("gr2.png"); }
void LSF() { float x[100], y[100], ex[100], ey[100]; char filename[80]; printf("Enter filename.\n"); scanf("%s",filename); FILE *f = fopen(filename,"r"); if (f == NULL) { sprintf(line,"File %s not found.\n",filename); printf(line); return; } // Read data int i = 0; while (fscanf(f,"%f %f %f",&(x[i]),&(y[i]),&(ey[i])) == 3 ) { i++; } printf("Read %d data points.\n",i); TGraphErrors *tge = new TGraphErrors(i,x,y,ex,ey); tge->SetMarkerStyle(20); tge->SetMarkerColor(kBlue); tge->SetLineColor(kBlue); c1 = new TCanvas("c1","c1",600,600); tge->Draw("AP"); tge->Fit("pol1"); }
instrAsy() { gStyle->SetOptStat(0); gStyle->SetOptFit(0); TGraphErrors *gr =new TGraphErrors; gr->SetName("insyAsy"); gr->SetTitle("Instrumental Asymmetries"); //gr->SetMarkerColor(ampCol[iam]); gr->SetMarkerSize(0.8); gr->SetMarkerStyle(21); TGraphErrors *gr1=gr; TString wrkDir="final/"; TString fname=wrkDir+"defaultB-H/asyVer1.hist.root"; TFile *inpH=new TFile(fname); assert(inpH->IsOpen()); //inpH->ls(); const int nSel=5; char *selL[nSel]={ "a0*All","b0*All","a2*All","b2*All","c1*All"}; int isel; for (isel=0;isel<nSel;isel++) { TGraphErrors *gr =(TGraphErrors *) inpH->Get(selL[isel]); assert(gr); //gr->Print(); //gr->Draw("AP"); float x1=0; if(isel<2) x1=2189; gr->Fit("pol0","","",x1,3000); TF1 *ff=gr->GetFunction("pol0"); if(ff==0) continue; // no fit was made float val=ff->GetParameter(0); float err=ff->GetParError(0); printf("pol0= %f +/- %f\n",val,err); int n=gr1->GetN(); float x=isel+1; gr1->SetPoint(n,x,val); gr1->SetPointError(n,0,err); } gr1->Print(); // return; gr1->Draw("AP"); // save Tgraph TString fname=wrkDir+"instAsy.hist.root"; TFile *outH=new TFile(fname,"RECREATE"); assert(outH->IsOpen()); printf("save outH -->%s\n", fname.Data()); gr1->Write(); outH->ls(); outH->Write(); return; }
void YZFit(){ if (yerr[0] == 0 && yerr[1] == 0 && yerr[2] == 0 && zerr[0] == 0 && zerr[1] == 0 && zerr[2] == 0) {cout << "ERRORE: Incertezze non specificate" << endl;} else { delete yzfitfunc; delete yzgraph; yzgraph = new TGraphErrors(3,yv,zv,yerr,zerr); yzfitfunc = new TF1("yzfittingfunction","[0]+[1]*x",-1000,1000); yzfitfunc->SetParameters(300,-6); yzgraph->Fit(yzfitfunc,"0S"); } };
int main(int narg,char **arg) { int i; double x,y; ifstream file; TApplication myapp("App",NULL,NULL); TCanvas tela; TGraphErrors graf; TF1 fun("fun","[0]*exp(-x*x/(2*[1]*[1]))"); if(narg<2) { cerr<<"usa: "<<arg[0]<<" file"<<endl; exit(0); } file.open(arg[1]); if(file.good()==0) { cout<<"File: "<<arg[1]<<" inesistente!"<<endl; exit(0); } i=0; double dum,N=1; while(file>>x>>dum>>y) { if(i==0) N=y; graf.SetPoint(i,x,y); graf.SetPointError(i,0,0.0001); i++; } fun.SetParameter(0,N); fun.SetParameter(1,1); fun.SetParName(0,"N"); fun.SetParName(1,"S"); graf.Draw("AP"); graf.Fit("fun"); //graf.GetXaxis()->SetLimits(0,x); tela.Modified(); tela.Update(); myapp.Run(true); return 0; }
void gerrors() { TCanvas *mycanvas = new TCanvas("mycanvs","A Simple Graph with error bars",200,10,700,500); // mycanvas->SetFillColor(42); mycanvas->SetGrid(); // mycanvas->GetFrame()->SetFillColor(21); // mycanvas->GetFrame()->SetBorderSize(12); const int n_points =10; #double x_vals [ n_points]= {1,2,3,4,5,6,7,8,9,10}; double y_vals [ n_points]= {6 ,12 ,14 ,20 ,22 ,24 ,35 ,45 ,44 ,53}; double y_errs [ n_points]= {5 ,5 ,4.7 ,4.5 ,4.2 ,5.1,2.9,4.1,4.8,5.43}; TGraphErrors *gr = new TGraphErrors(n_points,x_vals,y_vals,NULL,y_errs); // TGraphErrors graph(n_points,x_vals,y_vals,NULL,y_errs); gROOT -> SetStyle("Plain"); gr->SetTitle("TGraphErrors Example; lengtht [cm];Arb. Units"); gr->SetMarkerColor(kBlue); gr->SetMarkerStyle(kOpenCircle); gr->SetLineColor ( kBlue ) ; gr->Draw("ALP"); //Define a linear function TF1 f("Linear law" ,"[0]+x*[1]" ,.5 ,10.5) ; // Let's make the funcion line nicer f.SetLineColor(kRed); f.SetLineStyle(2); // Fit it to the graph and draw it gr->Fit(&f); f.DrawClone("Same"); // Build and Draw a legend TLegend leg(.1 ,.7 ,.3 ,.9 ,"Lab. Lesson 1"); leg.SetFillColor (0) ; gr->SetFillColor (0) ; leg.AddEntry(gr,"Exp. Points"); leg.AddEntry(&f,"Th. Law"); leg.DrawClone("Same"); // Draw an arrow on the canvas TArrow arrow(8,8,6.2,23,0.02,"----|>"); arrow.SetLineWidth (2) ; arrow.DrawClone ( ) ; // Add some text to the plot TLatex text(8.2,7.5,"#splitline{Maximum}{Deviation}"); text.DrawClone ( ) ; mycanvas->Update(); mycanvas -> Print("example.pdf"); }
std::pair<double,double> plotVelocity(std::vector<double> positions, std::vector<double> means, int strip, std::vector<double> errors, char thresholdLabel) { TCanvas* c = new TCanvas(); TGraphErrors* vGraph = new TGraphErrors(positions.size(), &means[0], &positions[0], 0, &errors[0] ); vGraph->SetMarkerStyle(20); vGraph->SetMarkerSize(1); vGraph->Draw("AP"); vGraph->Fit("pol1"); TF1* fit = vGraph->GetFunction("pol1"); std::stringstream buf; buf << strip << "_" << thresholdLabel; c->SaveAs( (buf.str() + ".png").c_str() ); std::pair<double,double> resultOfFit = std::make_pair<double,double> ( (fit->GetParameter(1))*-0.2, (fit->GetParError(1))*-0.2 ); return resultOfFit; }
void XZFit(){ if (xerr[0] == 0 && xerr[1] == 0 && xerr[2] == 0 && zerr[0] == 0 && zerr[1] == 0 && zerr[2] == 0) {cout << "ERRORE: Incertezze non specificate" << endl;} else { // TGraphErrors *graph1 = new TGraphErrors(3,x,y,xerr,yerr); // TF1* fitfunc1 = new TF1("fittingfunction","[0]+[1]*x",-100,100); // xyfitfunc = fitfunc1; // xygraph = graph1; delete xzfitfunc; //Dealloca prima di riallocarne uno nuovo delete xzgraph; xzfitfunc = new TF1("xzfittingfunction", "[0]+[1]*x",-100,100); xzgraph = new TGraphErrors(3,xv,yv,xerr,zerr); xzfitfunc->SetParameters(30,-2); xzgraph->Fit(xzfitfunc,"0S"); } };
void super(){ TH1::StatOverflows(kTRUE); cout << "\n\nStarting process...\n\n"; TGraphErrors *data = readData("magneticField"); TF1 *f1 = new TF1("fitRight", "[0]+[1]*TMath::Abs(TMath::Sin( [2]*(x-[3]) )/( [2]*(x-[3]) ) )", -200, 200); f1->SetParameter(0, 0.); f1->SetParameter(1, 0.36); f1->SetParameter(2, 0.05); f1->SetParameter(3, -15); f1->SetParName(0, "C"); f1->SetParName(1, "N"); f1->SetParName(2, "#pi#Phi/#Phi_{0}I"); f1->SetParName(3, "x_{0}"); f1->SetLineColor(kBlue); TF1 *f2 = new TF1("fitLeft", "[0]+[1]*TMath::Abs(TMath::Sin( [2]*(x-[3]) )/( [2]*(x-[3]) ) )"); f2->SetParameter(0, 50./2000.); f2->SetParameter(1, 700./2000.); f2->SetParameter(2, 0.06283); f2->SetParameter(3, -15); f2->SetParName(0, "C"); f2->SetParName(1, "N"); f2->SetParName(2, "A"); f2->SetParName(3, "A"); f2->SetLineColor(kBlue); // data->Fit(f1, "ME", "", 18, 60); // data->Fit(f2, "ME", "", -200, -33); data->Fit(f1, "ME", "", -90, 70); Double_t pi = 3.1415926538, L = 7.5e-6, l = 1.75e-9, lambda = 39.78e-9, conv = 0.54e-4, t=2*lambda+l; Double_t fQauntaRight = pi*L*t*conv/f1->GetParameter(2);//, fQauntaLeft = pi*L*t*conv/f2->GetParameter(2); Double_t fQuantaError = f1->GetParError(2)*pi*L*t*conv/f1->GetParameter(2)/f1->GetParameter(2); cout << "Flux quanta from right is " << fQauntaRight << " +- " << fQuantaError << endl;//<< " and from left is " << fQauntaLeft << endl; TCanvas *can = new TCanvas("Canvas", "Canvas", 1600, 900); graph(data, "", can, "Solenoid current (mA)", "Zero-voltage current (mA)", "magField"); }
void TGraphFit(){ // // Draw a graph with error bars and fit a function to it // gStyle->SetOptFit(111) ; //superimpose fit results // make nice Canvas TCanvas *c1 = new TCanvas("c1" ,"Daten" ,200 ,10 ,700 ,500) ; c1->SetGrid( ) ; //define some data points ... const Int_t n = 10; Float_t x[n] = {-0.22, 0.1, 0.25, 0.35, 0.5, 0.61, 0.7, 0.85, 0.89, 1.1}; Float_t y[n] = {0.7, 2.9, 5.6, 7.4, 9., 9.6, 8.7, 6.3, 4.5, 1.1}; Float_t ey[n] = {.8 ,.7 ,.6 ,.5 ,.4 ,.4 ,.5 ,.6 ,.7 ,.8}; Float_t ex[n] = {.05 ,.1 ,.07 ,.07 ,.04 ,.05 ,.06 ,.07 ,.08 ,.05}; // and hand over to TGraphErros object TGraphErrors *gr = new TGraphErrors(n,x,y,ex,ey); gr->SetTitle("TGraphErrors with Fit") ; gr->Draw("AP"); // now perform a fit (with errors in x and y!) gr->Fit("gaus"); c1->Update(); }
int eicsmear_check_calorimeter( TString filename_mc, TString filename_mc_smeared = "") { /* Uncomment this line when running without compilation */ gSystem->Load("libeicsmear"); /* Open input files. */ TFile *file_mc = new TFile(filename_mc, "OPEN"); TFile *file_mc_smeared = new TFile(filename_mc_smeared, "OPEN"); /* Get trees from files. */ TTree *tree = (TTree*)file_mc->Get("EICTree"); TTree *tree_smeared = (TTree*)file_mc_smeared->Get("Smeared"); /* Add friend to match branches in trees. */ tree->AddFriend(tree_smeared); erhic::EventPythia *event = NULL; Smear::Event *eventS = NULL; tree->SetBranchAddress("event", &event); tree->SetBranchAddress("eventS", &eventS); /* Define base cut for reconstructed final state particles */ TCut cut_base("particles.KS==1 && Smeared.particles.p > 0 && (particles.id==11 || particles.id==22)"); /* colors array */ unsigned colors[7] = {1,2,3,4,6,7,14}; /* select how many eta settings to plot */ unsigned etas_plotmax = 7; /* Create vector of theta values to include */ vector< double > etas; etas.push_back(-2.75); etas.push_back(-2.25); etas.push_back(-1.75); etas.push_back(-0.25); etas.push_back( 0.25); etas.push_back( 1.75); etas.push_back( 2.25); /* Create fit function */ TF1* f_momres = new TF1("f_momres", "sqrt( ([0])**2 + ([1]/(x**0.5))**2 )" ); 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->GetXaxis()->SetTitle("Energy (GeV/c)"); hframe->GetYaxis()->SetTitle("#sigma_{E}/E"); /* Create 2Dhistogram */ unsigned nbinsp = 40; TH2F* h2tmp = new TH2F("h2tmp","",nbinsp,0,(float)nbinsp,50,-1,1); h2tmp->GetXaxis()->SetTitle("Energy (GeV)"); h2tmp->GetYaxis()->SetTitle("(#Delta E)/E"); /* create combined canvas plot */ TCanvas *c1 = new TCanvas(); hframe->Draw(); /* Create legend */ TLegend* leg_eta = new TLegend( 0.25, 0.40, 0.45, 0.90); /* Create resolution-vs-momentum plot with fits for each selected theta value */ for ( int i = 0; i < etas.size(); i++ ) { /* Switch to scratch canvas */ cscratch->cd(); double eta = etas.at(i); 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.25; double eta_max = eta + 0.25; /* Cut for tree */ TCut cutx( Form("particles.p > 1 && ( particles.eta > %f && particles.eta < %f )", eta_min, eta_max) ); cout << cutx.GetTitle() << endl; /* Fill 2D histogram and fit slices with gaussian to get track resolution */ h2tmp->Reset(); tree->Draw("(Smeared.particles.E-particles.E)/particles.E:particles.E >> h2tmp",cut_base && cutx,""); h2tmp->FitSlicesY(); /* Get histogram with sigma from gauss fits */ TH1D* h2tmp_2 = (TH1D*)gDirectory->Get("h2tmp_2"); /* Fill fit parameters in TGraphErrors */ TGraphErrors *gres = new TGraphErrors(nbinsp); gres->SetMarkerColor(colors[i]); for ( unsigned bini = 1; bini < nbinsp; bini++ ) { double sigm_i = h2tmp_2->GetBinContent(bini); double sigm_err_i = h2tmp_2->GetBinError(bini); gres->SetPoint( bini-1, h2tmp->GetXaxis()->GetBinCenter(bini), sigm_i ); gres->SetPointError( bini-1, 0, sigm_err_i ); } /* Only plot first few lines; if not plotting, still do the fit */ if ( i < etas_plotmax ) { /* Add graph to legend */ leg_eta->AddEntry(gres, Form("#eta = %.1f", eta), "P"); /* Add graph to plot */ c1->cd(); gres->Draw("Psame"); f_momres->SetLineColor(colors[i]); gres->Fit(f_momres); } else { gres->Fit(f_momres); } } /* Draw legend */ TCanvas *c2 = new TCanvas(); leg_eta->Draw(); return 0; }
void decovspeak(bool printgif = false){ //load macros and set style----------------------------------- //gROOT->SetStyle("Plain"); gStyle->SetPalette(1); //gStyle->SetOptStat("mr"); //gStyle->SetOptFit(0); gStyle->SetOptStat(0); int colors[] = {2,4,6,1}; vector<char*> filenames; vector<char*> types; //filenames.push_back("crabjobs/lpc/Commissioning10-GOODCOLL-v8_mintrkmom1_ALLPEAK/merged.root"); filenames.push_back("Commissioning10-GOODCOLL-v8_ALLPEAK/res/merged.root"); //filenames.push_back("crabjobs/lpc/Commissioning10-GOODCOLL-v8_mintrkmom1_copy/merged_2.root"); filenames.push_back("Commissioning10-GOODCOLL-v8/res/merged.root"); filenames.push_back("Commissioning10-GOODCOLL-v8_toblatebp06/res/merged.root"); //filenames.push_back("crabjobs/lpc/Spring10-START3X_V26A_356ReReco-v1_standard_geom_mintrkmom1/merged.root"); //filenames.push_back("crabjobs/lpc/Spring10-START3X_V26A_356ReReco-v1_standard_geom/merged.root"); //filenames.push_back("crabjobs/lpc/Commissioning10-GOODCOLL-v8_mintrkmom1_toblatebp063/merged.root"); types.push_back("peak"); types.push_back("deco"); types.push_back("deco (BP)"); //types.push_back("MC"); vector<char*> cantitles; //cantitles.push_back("du_dw"); //delta u, delta w TH1s //cantitles.push_back("duvsdth"); //v+/- split du vs. delta tan(theta) TH2s cantitles.push_back("duvsdth_tgraph"); //v+/- split du vs. delta tan(theta) TGraphs const unsigned int nfiles = filenames.size(); const unsigned int ncan = cantitles.size(); TCanvas *can[ncan]; int idx = 0; TFile* file[nfiles]; TH1F* hdu[nfiles]; TH1F* hdw[nfiles]; TH2F* hduthp[nfiles]; TH2F* hduthm[nfiles]; //dummy legend TLegend *leg1=new TLegend(0.15,0.65,0.35,0.85); for(unsigned int ifile = 0 ; ifile < nfiles ; ifile++){ TH1F *hdummy=new TH1F(Form("hdummy_%i",ifile),Form("hdummy_%i",ifile),1,0,1); hdummy->SetLineColor(colors[ifile]); hdummy->SetMarkerColor(colors[ifile]); leg1->AddEntry(hdummy,types.at(ifile)); } leg1->SetBorderSize(1); leg1->SetFillColor(0); cout << "Getting histos... " << endl; for(unsigned int ifile = 0 ; ifile < nfiles ; ifile++){ cout << "Opening " << types.at(ifile) <<" file " << filenames.at(ifile) << endl; file[ifile] = TFile::Open(filenames.at(ifile)); hdu[ifile] = (TH1F*) file[ifile]->Get("PeakDecoResiduals/PeakDecoResiduals/du_TOB"); hdw[ifile] = (TH1F*) file[ifile]->Get("PeakDecoResiduals/PeakDecoResiduals/dw_TOB"); // if( strcmp(types.at(ifile),"deco (BP)") == 0){ hduthp[ifile] = (TH2F*) file[ifile]->Get("PeakDecoResiduals/PeakDecoResiduals/duvsdtantheta_TOB_vp_wp_all"); TH2F* htp = (TH2F*) file[ifile]->Get("PeakDecoResiduals/PeakDecoResiduals/duvsdtantheta_TOB_vp_wm_all"); hduthp[ifile] -> Add(htp); hduthm[ifile] = (TH2F*) file[ifile]->Get("PeakDecoResiduals/PeakDecoResiduals/duvsdtantheta_TOB_vm_wp_all"); TH2F* htm = (TH2F*) file[ifile]->Get("PeakDecoResiduals/PeakDecoResiduals/duvsdtantheta_TOB_vm_wm_all"); hduthm[ifile] -> Add(htm); // }else{ // hduthp[ifile] = (TH2F*) file[ifile]->Get("PeakDecoResiduals/PeakDecoResiduals/duvsdtantheta_TOB_vp_wp"); // TH2F* htp = (TH2F*) file[ifile]->Get("PeakDecoResiduals/PeakDecoResiduals/duvsdtantheta_TOB_vp_wm"); // hduthp[ifile] -> Add(htp); // hduthm[ifile] = (TH2F*) file[ifile]->Get("PeakDecoResiduals/PeakDecoResiduals/duvsdtantheta_TOB_vm_wp"); // TH2F* htm = (TH2F*) file[ifile]->Get("PeakDecoResiduals/PeakDecoResiduals/duvsdtantheta_TOB_vm_wm"); // hduthm[ifile] -> Add(htm); // } } cout << "Plotting du, dw histos... " << endl; if(draw("du_dw",cantitles)){ can[idx]=new TCanvas(Form("can_%i",idx),"du_dw",1200,450); can[idx]->Divide(2,1); can[idx]->cd(1); setStats(hdu,nfiles,0.8,0.65,0.15); plotHists(hdu,nfiles,"TOB","#Delta u [#mum]",-1000,1000,10,3); leg1->Draw(); can[idx]->cd(2); setStats(hdw,nfiles,0.8,0.65,0.15); plotHists(hdw,nfiles,"TOB","#Delta w [#mum]",-2000,2000,10,3); leg1->Draw(); idx++; } cout << "Plotting du vs. delta tan theta split v+/v- histos... " << endl; //du vs. delta tan(theta) split v+/v- histos----------------------------------- if(draw("duvsdth",cantitles)){ can[idx]=new TCanvas(cantitles.at(idx),cantitles.at(idx),1200,450*nfiles); can[idx]->Divide(nfiles,2); for(unsigned int ifile = 0 ; ifile < nfiles ; ifile++){ plotHistsTH2(hduthp[ifile], Form("TOB %s (v+)",types.at(ifile)),"tan(#theta_{trk})-tan(#theta_{L})", "#Delta u [#mum]",-0.3,0.5,-200,200,0,can[idx],ifile+1); plotHistsTH2(hduthm[ifile], Form("TOB %s (v-)",types.at(ifile)),"tan(#theta_{trk})-tan(#theta_{L})", "#Delta u [#mum]",-0.5,0.3,-200,200,0,can[idx],ifile+2); } idx++; } cout << "Plotting du vs. delta tan theta split v+/v- TGraphs... " << endl; //TGraph du vs. delta tan theta---------------------------------------- if(draw("duvsdth_tgraph",cantitles)){ can[idx]=new TCanvas(cantitles.at(idx),cantitles.at(idx),1200,450); can[idx]->Divide(2,1); vector<float> thetabinsp; vector<float> thetabinsm; for(int ibin=14;ibin<=30;ibin++) thetabinsp.push_back(ibin*0.05-1); for(int ibin=10;ibin<=26;ibin++) thetabinsm.push_back(ibin*0.05-1); TLatex *t=new TLatex(); t->SetNDC(); TGraphErrors *gduthp[nfiles]; TGraphErrors *gduthm[nfiles]; TF1 *fduthp[nfiles]; TF1 *fduthm[nfiles]; stringstream sduthp1[nfiles]; stringstream sduthp2[nfiles]; stringstream sduthm1[nfiles]; stringstream sduthm2[nfiles]; bool fit = false; for(unsigned int ifile = 0 ; ifile < nfiles ; ifile++ ){ can[idx]->cd(1); hduthp[ifile]->SetName(Form("hduthp_%i",ifile)); gduthp[ifile] = getTGraphFromTH2(hduthp[ifile],thetabinsp, colors[ifile] ); fduthp[ifile]=new TF1(Form("fduthp_%i",ifile),"pol1"); fduthp[ifile]->SetLineColor( colors[ifile] ); if(fit) gduthp[ifile]->Fit(fduthp[ifile]); float dwp = fduthp[ifile]->GetParameter(1); float dwperr = fduthp[ifile]->GetParError(1); float bp = fduthp[ifile]->GetParameter(0); float bperr = fduthp[ifile]->GetParError(0); sduthp1[ifile] << "#DeltaW = " << fround(dwp,3) << " #pm " << fround(dwperr,3) << " #mum" << endl; sduthp2[ifile] << "#Deltatan(LA) = " << fround(bp/(235.-dwp),3) << " #pm " << fround(bperr/(235.-dwp),4) << endl; gduthp[ifile]->SetTitle("TOB (V+)"); gduthp[ifile]->Draw("AP"); gduthp[ifile]->GetXaxis()->SetTitle("<tan(#theta_{trk})-tan(#theta_{LA})>"); gduthp[ifile]->GetYaxis()->SetTitle("<#Deltau> [#mum]"); //gduthp[ifile]->GetXaxis()->SetLimits(-1,1); gduthp[ifile]->SetMinimum(-25); gduthp[ifile]->SetMaximum(20); can[idx]->cd(2); hduthm[ifile]->SetName(Form("hduthm_%i",ifile)); gduthm[ifile] = getTGraphFromTH2(hduthm[ifile],thetabinsm, colors[ifile] ); fduthm[ifile]=new TF1(Form("fduthm_%i",ifile),"pol1"); fduthm[ifile]->SetLineColor( colors[ifile] ); if(fit) gduthm[ifile]->Fit(fduthm[ifile]); float dwm = fduthm[ifile]->GetParameter(1); float dwmerr = fduthm[ifile]->GetParError(1); float bm = fduthm[ifile]->GetParameter(0); float bmerr = fduthm[ifile]->GetParError(0); sduthm1[ifile] << "#DeltaW = " << fround(dwm,3) << " #pm " << fround(dwmerr,3) << " #mum" << endl; sduthm2[ifile] << "#Deltatan(LA) = " << fround(bm/(235.-dwm),3) << " #pm " << fround(bmerr/(235.-dwm),4) << endl; gduthm[ifile]->SetTitle("TOB (V-)"); gduthm[ifile]->Draw("AP"); gduthm[ifile]->GetXaxis()->SetTitle("<tan(#theta_{trk})-tan(#theta_{LA})>"); gduthm[ifile]->GetYaxis()->SetTitle("<#Deltau> [#mum]"); //gduthm[ifile]->GetXaxis()->SetLimits(-1,1); gduthm[ifile]->SetMinimum(-35); gduthm[ifile]->SetMaximum(15); //leg1->Draw(); } for(unsigned int ifile = 0 ; ifile < nfiles ; ifile++ ){ can[idx]->cd(1); if( ifile == 0 ) gduthp[ifile]->Draw("AP"); else gduthp[ifile]->Draw("sameP"); leg1->Draw(); if(fit){ t->SetTextColor( colors[ifile] ); t->DrawLatex(0.15,0.85-ifile*0.2,sduthp1[ifile].str().c_str()); t->DrawLatex(0.15,0.75-ifile*0.2,sduthp2[ifile].str().c_str()); } can[idx]->cd(2); if( ifile == 0 ) gduthm[ifile]->Draw("AP"); else gduthm[ifile]->Draw("sameP"); //leg1->Draw(); if(fit){ t->SetTextColor( colors[ifile] ); t->DrawLatex(0.15,0.85-ifile*0.2,sduthm1[ifile].str().c_str()); t->DrawLatex(0.15,0.75-ifile*0.2,sduthm2[ifile].str().c_str()); } } TCanvas *cdiff = new TCanvas("cdiff","duvsdtanthetadiff",1200,450); cdiff->Divide(2,1); cdiff->cd(1); TGraphErrors *gduthpdiff = diffTGraph(gduthp[0],gduthp[2],"TOB DECO - PEAK (v+)","<tan(#theta_{trk})-tan(#theta_{LA})>","<#Deltau> (#mum)"); TF1* fduthpdiff=new TF1("fduthpdiff","pol1",-0.5,0.5); gduthpdiff->Fit(fduthpdiff,"R"); gduthpdiff->Draw("AP"); float dwp = fduthpdiff->GetParameter(1); float dwperr = fduthpdiff->GetParError(1); float bp = fduthpdiff->GetParameter(0); float bperr = fduthpdiff->GetParError(0); stringstream sduthp1diff; stringstream sduthp2diff; sduthp1diff << "#DeltaW = " << fround(dwp,3) << " #pm " << fround(dwperr,3) << " #mum" << endl; sduthp2diff << "#Deltatan(LA) = " << fround(bp/(235.-dwp),3) << " #pm " << fround(bperr/(235.-dwp),4) << endl; t->SetTextColor(1); t->DrawLatex(0.15,0.85,sduthp1diff.str().c_str()); t->DrawLatex(0.15,0.75,sduthp2diff.str().c_str()); cdiff->cd(2); TGraphErrors *gduthmdiff = diffTGraph(gduthm[0],gduthm[2],"TOB DECO - PEAK (v-)","<tan(#theta_{trk})-tan(#theta_{LA})>","<#Deltau> (#mum)"); TF1* fduthmdiff=new TF1("fduthmdiff","pol1",-0.5,0.5); gduthmdiff->Fit(fduthmdiff,"R"); gduthmdiff->Draw("AP"); float dwm = fduthmdiff->GetParameter(1); float dwmerr = fduthmdiff->GetParError(1); float bm = fduthmdiff->GetParameter(0); float bmerr = fduthmdiff->GetParError(0); stringstream sduthm1diff; stringstream sduthm2diff; sduthm1diff << "#DeltaW = " << fround(dwm,3) << " #pm " << fround(dwmerr,3) << " #mum" << endl; sduthm2diff << "#Deltatan(LA) = " << fround(bm/(235.-dwm),3) << " #pm " << fround(bmerr/(235.-dwm),4) << endl; t->DrawLatex(0.15,0.85,sduthm1diff.str().c_str()); t->DrawLatex(0.15,0.75,sduthm2diff.str().c_str()); idx++; } for(unsigned int ican=0;ican<ncan;ican++){ can[ican]->Modified(); can[ican]->Update(); if(printgif) can[ican]->Print(Form("plots/%s_TOB.gif",cantitles.at(ican))); } }
void fit_test(char name[]) { TCanvas *c1 = new TCanvas("c1","A Simple Graph Example",200,10,700,500); c1->SetGrid(); std::vector<double> xv; std::vector<double> yv; std::vector<double> xverr; std::vector<double> yverr; Double_t x, y, xerr, yerr; FILE *f = fopen(name,"r"); int counter = 1; while (!feof(f)) { fscanf(f,"%lf %lf lf %lf\n", &x, &y, &xerr, &yerr); xv.push_back(x*4); // in ns yv.push_back(y); xverr.push_back(xerr*4); yverr.push_back(yerr); } TGraphErrors * gr = new TGraphErrors(xv.size(), &xv[0], &yv[0], &xverr[0], &yverr[0]); TF1 *fitFcn = new TF1("fitFcn", fitFunction, 50, 300,5); double base_line = 0; for(int j = 0; j < 20; j++) { base_line += yv[j]; } base_line /= 20; //cout << base_line << endl; fitFcn->SetParLimits(0, 15, 40); fitFcn->SetParLimits(1, 85, 100); fitFcn->SetParLimits(2, 5, 40); fitFcn->SetParLimits(3, 1, 25); fitFcn->SetParameter(4, base_line); fitFcn->SetParLimits(4, base_line, base_line); //fitFcn->SetParameter(3, 153.622); //fitFcn->SetParameter(4, 502.345); //fitFcn->SetParameter(5, 86.9206); gr->Fit("fitFcn", "R"); gr->SetMarkerColor(4); gr->SetMarkerStyle(kFullCircle); //gr->Draw("APE"); gr->Draw("APE"); //gSystem->Sleep(3000); c1->Update(); for(int j =0; j < xv.size(); j++) { cout << xverr[j] << "\t" << yverr[j] << endl; } xv.clear(); yv.clear(); }
map<int,vector<double> > RPCChambersCluster::getReconstructedHits(vector<unsigned> vectorOfReferenceChambers, const int & timeWindow,const int & timeReference,bool & isVerticalTrack,map<int,double> & scintilatorsCoordinates,const bool & keepRecoTrack,TFile * fileForRecoTracks,const int & eventNum,const double & correlationFactor, const ESiteFileType & fileType){ // map<int,vector<double> > mapOfHits; // // the default value for Chi2goodness is 20 //double best_chi2goodnes_value = Chi2goodness+10 ; // this variable is used as reference so that it holds the best chi2 found for a track, so its used only a track with better chi2 to be accepted double currentBestCorrFact = -2; int lastFitPoint = 0; for (int i = 0 ; i < this->getNumberOfChambers() ; i++){ this->getChamberNumber(i+1)->findAllClustersForTriggerTimeReferenceAndTimeWindow(timeReference,timeWindow,5); //cout << "Chamber is " << i+1 << endl; } vector<vector<int> > vectorOfClusterNumberCombinations; if (fileType == kIsCERNrawFile ){ assert(vectorOfReferenceChambers.size() == 3 ); lastFitPoint = 9; for ( int i = 0 ; i < this->getChamberNumber(vectorOfReferenceChambers[0])->getNumberOfClusters() ; i++ ){ for( int j = 0 ; j < this->getChamberNumber(vectorOfReferenceChambers[1])->getNumberOfClusters() ; j++ ){ for( int k = 0 ; k < this->getChamberNumber(vectorOfReferenceChambers[vectorOfReferenceChambers.size()-1])->getNumberOfClusters() ; k++ ){ vector<int> singleCombination; singleCombination.push_back(i+1); singleCombination.push_back(j+1); singleCombination.push_back(k+1); for (int f = 0 ; f < singleCombination.size() ; f++){ if(this->getChamberNumber(vectorOfReferenceChambers[f])->getSizeOfCluster(singleCombination.at(f)) > 5 ) continue; // don't insert combination if there is too big cluster. } vectorOfClusterNumberCombinations.push_back(singleCombination); } } } } if (fileType == kIsBARCrawFile || fileType == kIsGENTrawFile ){ // add implementation for BARC and Ghent stand . lastFitPoint = 5; assert(vectorOfReferenceChambers.size() == 2); for ( int i = 0 ; i < this->getChamberNumber(vectorOfReferenceChambers[0])->getNumberOfClusters() ; i++ ){ for( int j = 0 ; j < this->getChamberNumber(vectorOfReferenceChambers[1])->getNumberOfClusters() ; j++ ){ vector<int> singleCombination; singleCombination.push_back(i+1); singleCombination.push_back(j+1); for (int f = 0 ; f < singleCombination.size() ; f++){ if(this->getChamberNumber(vectorOfReferenceChambers[f])->getSizeOfCluster(singleCombination.at(f)) > 5 ) continue; // don't insert combination if there is too big cluster. } vectorOfClusterNumberCombinations.push_back(singleCombination); } } } string topScintToString, botScintToString; for (int combinationsVectorElement = 0 ; combinationsVectorElement < vectorOfClusterNumberCombinations.size() ; combinationsVectorElement ++){ // the partition logic start here - track could pass more than one partition int direction = 0 ; // direction should describe how the partition changes from one reference chamber to another. It vector<int> RefChamberClusterPartition; bool positive = false; bool negative = false; int partitionPenetrated = 1; // the Y coordinate is the partition number (1 2 or 3 - A B or C) vector<int> clusterNum = vectorOfClusterNumberCombinations.at(combinationsVectorElement); for (int ii = 0; ii < clusterNum.size() ; ii++){ RefChamberClusterPartition.push_back(this->getChamberNumber(vectorOfReferenceChambers[ii])->getXYCoordinatesOfCluster(clusterNum.at(ii)).at(1)); } isVerticalTrack = true; for ( int ii = 0; ii < RefChamberClusterPartition.size() - 1 ; ii++ ){ direction = (RefChamberClusterPartition.at(ii) - RefChamberClusterPartition.at(ii+1)); if (direction != 0) { direction = direction/abs(direction); partitionPenetrated++; } // get only the sign ( +1 or -1) if (direction && direction == -1) { positive = true; isVerticalTrack = false; } if (direction && direction == 1 ) { negative = true; isVerticalTrack = false; } } if ( positive && negative ) continue; // cannot have a track that goes in both direction /* TH1F * histXZ = new TH1F("fitHistogram","XZ plane",110,0,11); histXZ->GetYaxis()->SetRangeUser(-20,52); histXZ->SetMarkerColor(kBlue); histXZ->SetMarkerStyle(kCircle); histXZ->GetXaxis()->SetTitle("Shelf number"); histXZ->GetYaxis()->SetTitle("Channel number"); */ TF1 * fitfunc = new TF1("FitTrack","[0]+x*[1]",0,lastFitPoint+1); TGraphErrors * graphXZ = new TGraphErrors(); graphXZ->GetXaxis()->SetTitle("Shelf number"); graphXZ->GetYaxis()->SetTitle("Channel number"); //graphXZ->SetLineColor(0); graphXZ->SetMarkerColor(kBlack); graphXZ->SetMarkerStyle(kFullCircle); graphXZ->SetName("fit graph"); graphXZ->SetTitle("XZ plane"); graphXZ->GetXaxis()->SetTitle("Muon station"); graphXZ->GetYaxis()->SetTitle("Channel number"); fitfunc->SetLineColor(kBlue); vector<double> coordinates; double xCoordinate = 0; int yCoordinate = 0; int zCoorinate = 0; for (int ii=0 ; ii < vectorOfReferenceChambers.size() ; ii++){ coordinates = this->getChamberNumber(vectorOfReferenceChambers[ii])->getXYCoordinatesOfCluster(clusterNum[ii]); xCoordinate = coordinates.at(0); yCoordinate = coordinates.at(1); zCoorinate = 10*vectorOfReferenceChambers[ii]; Double_t errorValue = this->getChamberNumber(vectorOfReferenceChambers[ii])->getSizeOfCluster(clusterNum[ii]); // histXZ->SetBinContent(zCoorinate,xCoordinate); // histXZ->SetBinError(zCoorinate,errorValue/2); //cout << xCoordinate << " " << yCoordinate << endl; graphXZ->SetPoint(ii,vectorOfReferenceChambers[ii],xCoordinate); graphXZ->SetPointError(ii,0,errorValue/2); } Double_t params[2]; graphXZ->Fit(fitfunc,"RFQ"); fitfunc->GetParameters(params); //cout << "par1 " << params[0] << " par2 " << params[1] << " chi2 " << fitfunc->GetChisquare() << endl; // The resudials - difference between estimated fit value and the middle of the nearest cluster int prevReference = 0 , nextReference = 0 , prevReferencePartition = 0 , nextReferencePartition = 0; bool currentChamberIsReference = false; int startCounter = 0, endCounter = 0; if ( abs(graphXZ->GetCorrelationFactor()) >= correlationFactor && abs(graphXZ->GetCorrelationFactor()) > currentBestCorrFact ) { // in case of only one partition, get the partition number of the first reference point currentBestCorrFact = abs(graphXZ->GetCorrelationFactor()); int referenceChambersIncrementor = 0; bool negativeChannelNumberIsFound = false; // --------- for ( int currentChNumber = 0 ; currentChNumber < this->getNumberOfChambers() ; currentChNumber++ ) { // check where the chamber is according to the reference chambers vector<double> vectorOfpartitionsAndHit; double channelNum = fitfunc->Eval(currentChNumber+1); /** four cases 1. the chamber is before the first reference 2. the chamber is after the last reference 3. the chamber is between two references 4. the chamber is a reference */ for(int refCheck = 0 ; refCheck < vectorOfReferenceChambers.size(); refCheck++){ // find the surounding references if (currentChNumber+1 == vectorOfReferenceChambers.at(refCheck)){ currentChamberIsReference = true; break; } if ( vectorOfReferenceChambers.at(refCheck) > currentChNumber+1 && refCheck == 0 ){ // its before the first reference chamber nextReference = vectorOfReferenceChambers.at(refCheck); nextReferencePartition = this->getChamberNumber(nextReference)->getXYCoordinatesOfCluster(clusterNum[refCheck]).at(1); break; } if ( vectorOfReferenceChambers.at(refCheck) < currentChNumber+1 && refCheck == vectorOfReferenceChambers.size() - 1 ){ // its after the last chamber prevReference = vectorOfReferenceChambers.at(refCheck); prevReferencePartition = this->getChamberNumber(prevReference)->getXYCoordinatesOfCluster(clusterNum[refCheck]).at(1); break; } if ( vectorOfReferenceChambers.at(refCheck) < currentChNumber+1 && vectorOfReferenceChambers.at(refCheck+1) > currentChNumber+1 ){ // its between two references prevReference = vectorOfReferenceChambers.at(refCheck) ; nextReference = vectorOfReferenceChambers.at(refCheck+1); prevReferencePartition = this->getChamberNumber(prevReference)->getXYCoordinatesOfCluster(clusterNum[refCheck]).at(1); nextReferencePartition = this->getChamberNumber(nextReference)->getXYCoordinatesOfCluster(clusterNum[refCheck+1]).at(1); break; } } // end of partition possibilities if(!currentChamberIsReference){ if (nextReference && prevReference == 0){ if (positive){ prevReferencePartition = 1; } if(negative){ prevReferencePartition = this->getChamberNumber(1)->getClones(); } } if (prevReferencePartition && nextReferencePartition == 0){ if (positive){ nextReferencePartition = this->getChamberNumber(1)->getClones(); } if(negative){ nextReferencePartition = 1; } } if (partitionPenetrated == 1 ){ prevReferencePartition = yCoordinate; nextReferencePartition = yCoordinate; int firstRef = vectorOfReferenceChambers.at(0); int lastRef = vectorOfReferenceChambers.at(vectorOfReferenceChambers.size() - 1); int ccham = currentChNumber+1; if(! (lastRef > ccham && firstRef < ccham) ){ // all partitions are possible, chambers are out of the reference scope prevReferencePartition = this->getChamberNumber(1)->getClones(); nextReferencePartition = 1; // 3 in case of ecap chamber } } if (positive){ startCounter = prevReferencePartition; endCounter = nextReferencePartition; } else { startCounter = nextReferencePartition ; endCounter = prevReferencePartition ; } for (int currentCounter = startCounter ; currentCounter <= endCounter; currentCounter ++ ){ assert(currentCounter > 0 && currentCounter < 4); vectorOfpartitionsAndHit.push_back(currentCounter); } } else{ vectorOfpartitionsAndHit.push_back(this->getChamberNumber(currentChNumber+1)->getXYCoordinatesOfCluster(clusterNum[referenceChambersIncrementor]).at(1)); referenceChambersIncrementor ++; } prevReference = 0 ; nextReference = 0 ; prevReferencePartition = 0 ; nextReferencePartition = 0; currentChamberIsReference = false; //cout << "Chamber " << l+1 << " " << coordinates.at(1) << " " << fitfunc->Eval(l+1) << " " << endl; int channelNumberToStore = channelNum; if (channelNumberToStore < 96/this->getChamberNumber(1)->getClones()){ channelNumberToStore += 1; } // add one to represent the fired channel, or none if the channel is on the right border vectorOfpartitionsAndHit.push_back(channelNumberToStore); // the last element is the number of the channel // Debug lines /** cout << "Chamber is " << currentChNumber+1 << " partitions " ; for (int thesize = 0 ; thesize < vectorOfpartitionsAndHit.size() - 1; thesize++){ cout << vectorOfpartitionsAndHit.at(thesize) << " " ; } cout << "channel " << vectorOfpartitionsAndHit.at(vectorOfpartitionsAndHit.size()-1) << endl; */ mapOfHits[currentChNumber+1] = vectorOfpartitionsAndHit; } // ---------- scintilators coordinates estimate for (int scintNum = 0 ; scintNum < 31 ; scintNum++){ if(this->getTriggerObjectNumber(1)->getChannel(scintNum+1)->hasHit() && vectorOfClusterNumberCombinations.size() == 1 ) { if (scintNum < 10) { scintilatorsCoordinates[scintNum+1] = graphXZ->Eval(0); topScintToString = boost::lexical_cast<string>(scintNum+1); } else { scintilatorsCoordinates[scintNum+1] = graphXZ->Eval(lastFitPoint+1); botScintToString = boost::lexical_cast<string>(scintNum+1); } } } } // get only vertical tracks from the A partition if there are only two scint hits if (keepRecoTrack && isVerticalTrack && !mapOfHits.empty() && scintilatorsCoordinates.size() == 2){ graphXZ->SetName(boost::lexical_cast<string>(eventNum).c_str()); string partition; if (mapOfHits.find(vectorOfReferenceChambers.at(0))->second.at(0) == 1) partition = "A"; else if (mapOfHits.find(vectorOfReferenceChambers.at(0))->second.at(0) == 2) partition = "B"; else partition = "C"; graphXZ->SetTitle(("Correlation factor is "+boost::lexical_cast<string>(graphXZ->GetCorrelationFactor()) + " trigger channels top: " + topScintToString + " bottom: " + botScintToString ).c_str()); if(abs(graphXZ->GetCorrelationFactor()) >= correlationFactor) { string scintCombination="_"+topScintToString+"_"+botScintToString+"_"+partition; TDirectory * dir = fileForRecoTracks->GetDirectory(scintCombination.c_str(),true); if(!dir) { //fileForRecoTracks->ls(); fileForRecoTracks->mkdir(scintCombination.c_str()) ; fileForRecoTracks->cd(""); } fileForRecoTracks->cd(scintCombination.c_str()); //cout << fileForRecoTracks->GetPath() << endl; } else{ fileForRecoTracks->cd("") ; fileForRecoTracks->cd("badTracks") ; } graphXZ->Write(graphXZ->GetName(),TObject::kOverwrite); fileForRecoTracks->cd(""); //fileForRecoTracks->Write(graphXZ->GetName(),TObject::kOverwrite); } fitfunc->Delete(); //histXZ->Delete(); graphXZ->Delete(); } return mapOfHits; }
void rateStudy() { const int NRUNS = 25; const int NCH = 32; const int NBINS = 32; TCanvas* c1 = new TCanvas("c1", "c1", 800, 600); TMultiGraph *mg = new TMultiGraph(); TLegend *legend=new TLegend(0.65,0.15,0.88,0.55); legend->SetNColumns(4); legend->SetFillColor(0); TH1F* hRate = new TH1F("hRate", "hist", 32.0, 0, 8.0); //Color buffer const int NCOLORS = 32; int color[NCOLORS] = {73, 2, 3, 4, 99, 6, 7, 8, 9, 12, 28, 32, 34, 28, 50, 51, 56, 58, 88, 99, 1, 208, 209, 218, 212, 210, 221, 224, 225, 226, 227, 228 }; ifstream fin; //fin.open("runlist.txt"); fin.open("filter_runlist.txt"); string line = ""; TFile* out = new TFile("outtemp.root", "REACREATE"); TH1F* h = new TH1F("h","hist", NBINS, 0, NBINS); TF1* pois = new TF1("pois","[0]*TMath::Poisson(x,[1])",0,50); TF1* ppp = new TF1("ppp","[0]*TMath::Power(0.5,x*[1])",0.01,1.0); for (int ch = 0; ch < NCH; ++ch) { //if ( ch==26 || ch==27 ) //continue; //Graph points and errors Double_t x[NRUNS]; Double_t y[NRUNS]; Double_t errX[NRUNS] = {0}; Double_t errY[NRUNS] = {0}; int fileCounter = 0; while(getline(fin, line)) { vector<double> data = parse(line); stringstream filePath; filePath << "pmtratestudy/run" << data[0] << "*.root"; cout << "opening file at " << filePath.str() << endl; cout << "file counter: " << fileCounter << " channel=" << ch << endl; //TFile* f = new TFile(filePath.str().c_str()); //TTree* t = (TTree *)f->Get("eventtree"); TChain* t = new TChain("eventtree"); t->Add( filePath.str().c_str() ); out->cd(); x[fileCounter] = data[1]; int nfires[NCH] = {0}; int samples = 0; float chmax = 0.0; t->SetBranchAddress("nfires", &nfires); t->SetBranchAddress("samples", &samples); t->SetBranchAddress("chmax", &chmax); h->Reset(); int nentries = t->GetEntries(); for (int entry = 0; entry < nentries; ++entry) { t->GetEntry(entry); if (chmax < 100.0) { h->Fill(nfires[ch]); } } pois->SetParameter(0,1); pois->SetParameter(1, h->GetMean()); h->Fit(pois,"RQ","",0,50); //TF1 *myfit = (TF1 *)h->GetFunction("pois"); TF1 *myfit = (TF1 *)pois; Double_t lambda = myfit->GetParameter(1); h->Draw(); stringstream histFileName; histFileName << "hist/h" << data[0] << "_ch" << ch << ".png"; c1->SaveAs(histFileName.str().c_str()); //Graph with poisson method #if 1 y[fileCounter] = lambda / ((samples - 1) * 15.625E-6); errY[fileCounter] = myfit->GetParError(1) / ((samples - 1) * 15.625E-6); #endif //Graph with mean method #if 0 y[fileCounter] = h->GetMean() / ((samples - 1) * 15.625E-6); errY[fileCounter] = h->GetMeanError() / ((samples - 1) * 15.625E-6); #endif cout << x[fileCounter] << ", " << y[fileCounter] << " | " << (samples - 1) << endl; delete t; //f->Close(); fileCounter++; } ppp->SetParameter(0,1); ppp->SetParameter(1,0.4); TGraphErrors* gr = new TGraphErrors(NRUNS, x, y, errX, errY); gr->SetLineColor(color[ch % NCOLORS]); cout << "color: " << color[ch % NCOLORS] << endl; gr->SetLineWidth(2); gr->SetMarkerStyle(7); gr->Fit("ppp","R0","Q0",0.045,2.0); TF1 *afit = (TF1 *)gr->GetFunction("ppp"); Double_t aRate = 1/afit->GetParameter(1); if (aRate > 0) { hRate->Fill(aRate); } gr->GetXaxis()->SetTitle("Run Date"); gr->GetYaxis()->SetTitle("Rate [kHz]"); stringstream entryName, fileName; entryName << "Channel" << ch; gr->SetTitle(entryName.str().c_str()); fileName << "plots/" << ch << ".png"; legend->AddEntry(gr, entryName.str().c_str()); gr->Draw("alp"); c1->SaveAs(fileName.str().c_str()); mg->Add(gr); cout << "added plot to mg\n"; fin.clear(); fin.seekg(0, ios::beg); } // loop over channel hRate->Draw(); hRate->Fit("gaus"); c1->SaveAs("hrate.pdf"); mg->Draw("alp"); mg->GetXaxis()->SetTitle("Days since first run"); mg->GetYaxis()->SetTitle("Rate [kHz]"); mg->SetTitle("All channels: Rate vs. Days since first Run"); legend->Draw(); c1->SaveAs("mg.pdf"); }
void howManyPe7_17_evening(){ cout << "Starting" << endl; const int numRuns = 6; const char* files[numRuns] = { "../../crunchedFiles/run_00480_crunched.root", "../../crunchedFiles/run_00481_crunched.root", "../../crunchedFiles/run_00482_crunched.root", "../../crunchedFiles/run_00483_crunched.root", "../../crunchedFiles/run_00484_crunched.root", "../../crunchedFiles/run_00485_crunched.root", }; gStyle->SetOptFit(1); gStyle->SetOptStat(0); double pes[16]; double peErrors[16]; double gains[16]; double gainErrors[16]; TCanvas* c1 = new TCanvas(); cout << "starting loop " << endl; for(int row = 2; row < 6; ++row){ for(int col = 2; col < 6; ++col){ vector<double> means; vector<double> sigs; vector<double> meanErrs; vector<double> sigErrs; for (int i = 0; i < numRuns; ++i){ TFile* f = new TFile(files[i]); TTree* t = (TTree*) f->Get("t"); t->Draw(Form("sipm%i%i.energy>>histo%i%i", row,col,row,col),Form("sipm%i%i.valid",row,col)); TH1F* h = (TH1F*) gROOT->FindObject(Form("histo%i%i",row,col)); h->Fit("gaus","0q"); if(h->GetFunction("gaus")->GetParameter(1)>250){ means.push_back(h->GetFunction("gaus")->GetParameter(1)); sigs.push_back(h->GetFunction("gaus")->GetParameter(2)); meanErrs.push_back(h->GetFunction("gaus")->GetParError(1)); sigErrs.push_back(h->GetFunction("gaus")->GetParError(2)); } } vector<double> variances; vector<double> varianceErrors; for(int i = 0; i < means.size(); ++i){ variances.push_back(sigs[i]*sigs[i]); varianceErrors.push_back(2*sigs[i]*sigErrs[i]); } if(means.size() > 1){ TGraphErrors* linGraph = new TGraphErrors(means.size(), &means[0], &variances[0], &meanErrs[0], &varianceErrors[0]); TGraphErrors* quadGraph = new TGraphErrors(means.size(), &means[0], &variances[0], &meanErrs[0], &varianceErrors[0]); linGraph->SetMarkerStyle(20); linGraph->Fit("pol1","q"); linGraph->SetTitle(Form("SiPM %i%i", row, col)); linGraph->GetFunction("pol1")->SetLineColor(kBlue); linGraph->GetXaxis()->SetTitle("Mean"); linGraph->GetYaxis()->SetTitle("#sigma^{2}"); quadGraph->SetMarkerStyle(20); quadGraph->Fit("pol2","q"); quadGraph->GetFunction("pol2")->SetLineColor(kRed); linGraph->Draw("ap"); quadGraph->Draw("psame"); UInt_t index = (row-2)*4 + (col-2); pes[index] = 1.0/linGraph->GetFunction("pol1")->GetParameter(1)*means[0]; gains[index] = linGraph->GetFunction("pol1")->GetParameter(1); gainErrors[index] = linGraph->GetFunction("pol1")->GetParError(1); peErrors[index] = TMath::Sqrt((1/gains[index]*meanErrs[0])*(1/gains[index]*meanErrs[0])+ (means[0]/(gains[index]*gains[index])*gainErrors[index])*(means[0]/(gains[index]*gains[index])*gainErrors[index])); /* pes[drs] = 1.0/quadGraph->GetFunction("pol2")->GetParameter(1)*means[0]; gains[drs] = quadGraph->GetFunction("pol2")->GetParameter(1); gainErrors[drs] = quadGraph->GetFunction("pol2")->GetParError(1); peErrors[drs] = TMath::Sqrt((1/gains[drs]*meanErrs[0])*(1/gains[drs]*meanErrs[0])+ (means[0]/(gains[drs]*gains[drs])*gainErrors[drs])*(means[0]/(gains[drs]*gains[drs])*gainErrors[drs])); */ delete linGraph; delete quadGraph; } else if (means.size()==1){ UInt_t index = (row-2)*4 + (col-2); UInt_t mean = means[0]; UInt_t sig = sigs[0]; UInt_t meanErr = meanErrs[0]; UInt_t sigErr = sigErrs[0]; pes[index] = mean*mean/sig/sig; gains[index] = mean/pes[index]; gainErrors[index] = TMath::Sqrt((2*sig/mean*sigErr)*(2*sig/mean*sigErr)+(sig*sig/mean/mean*meanErr)*(sig*sig/mean/mean*meanErr)); peErrors[index] = TMath::Sqrt((2*mean/sig/sig*sigErr)*(2*mean/sig/sig*sigErr)+(2*mean*mean/sig/sig/sig*sigErr)*(2*mean*mean/sig/sig/sig*sigErr)); } else{ UInt_t index = (row-2)*4 + (col-2); pes[index] = -1; gains[index] = -1; peErrors[index] = -1; gainErrors[index] = -1; } } } for(int i = 0; i <16; ++i){ cout << "SiPM " << 2+i/4 << 2+i%4 << " --- " << "p1 : " << gains[i] << ", " << pes[i] << " photoelectrons at open filter, " << gains[i]*pes[i] << "calibration constant." << endl; } TGraphErrors* peGainGraph = new TGraphErrors(16, gains, pes, gainErrors, peErrors); peGainGraph->SetMarkerStyle(20); peGainGraph->GetXaxis()->SetTitle("gain"); peGainGraph->GetYaxis()->SetTitle("PE at open filter"); c1->SetGridx(); c1->SetGridy(); peGainGraph->Draw("ap"); cout << "drew graph " << endl; TCanvas* c2 = new TCanvas(); TH2F* peMap = new TH2F("pes","PE Map", 4,0,4,4,0,4); for(int i = 0; i < 16; ++i){ peMap->Fill(.5+i%4, 3.5-i/4, pes[i]); } peMap->GetXaxis()->SetLabelOffset(99); peMap->GetYaxis()->SetLabelOffset(99); c2->SetTickx(0); c2->SetTicky(0); peMap->Draw("TEXT"); TCanvas* c3 = new TCanvas(); TH2F* gainMap = new TH2F("gains","Gain Map", 4,0,4,4,0,4); for(int i = 0; i < 16; ++i){ gainMap->Fill(.5+i%4, 3.5-i/4, gains[i]); } gainMap->GetXaxis()->SetLabelOffset(99); gainMap->GetYaxis()->SetLabelOffset(99); gainMap->Draw("TEXT"); }
void makePlots(vector<inputValues> b, vector<inputValues> t, vector<outputValues> o, double cut) { // Plot output values vs pulse width TGraphErrors * eLPlot = new TGraphErrors(); TGraphErrors * ePsiPlot = new TGraphErrors (); eLPlot->SetTitle("Average Number of LED-induced Photoelectrons per Trigger"); ePsiPlot->SetTitle("Single-photoelectron Response Mean Amplitude"); eLPlot->SetMarkerColor(4); ePsiPlot->SetMarkerColor(4); eLPlot->SetMarkerStyle(21); ePsiPlot->SetMarkerStyle(21); for (int i = 0; i < b.size(); i++) { for (int j = 0; j < t.size(); j++) { eLPlot->SetPoint((i+1)*j, t[j].pw, o[(i+1)*j].eL); eLPlot->SetPointError((i+1)*j, 0.02, sqrt(o[(i+1)*j].v_eL)); ePsiPlot->SetPoint((i+1)*j, t[j].pw, o[(i+1)*j].ePsi); ePsiPlot->SetPointError((i+1)*j, 0.02, sqrt(o[(i+1)*j].v_ePsi)); } } TCanvas * eL_c = new TCanvas("eL_c", "eL Canvas", 200, 10, 700, 500); eLPlot->GetXaxis()->SetTitle("LED Pulse Width / (ns)"); eLPlot->GetYaxis()->SetTitle("Photoelectrons / Trigger"); eLPlot->Draw("AP"); TCanvas * ePsi_c = new TCanvas("ePsi_c", "ePsi Canvas", 200, 10, 700, 500); ePsiPlot->GetXaxis()->SetTitle("LED Pulse Width / (ns)"); ePsiPlot->GetYaxis()->SetTitle("Mean Amplitude / (mV)"); ePsiPlot->GetYaxis()->SetRangeUser(0.3, 1.6); ePsiPlot->Draw("AP"); TF1 * fit = new TF1("fit", "[0]", 0, 10); ePsiPlot->Fit(fit); // Plot spectra TCanvas * spectra_c = new TCanvas("spectra_c", "Spectra Canvas", 200, 10, 700, 500); spectra_c->SetLogy(); for (int i = t.size() - 1; i >= 0; i--) { t[i].h->SetLineColor(i+2); t[i].h->SetLineWidth(2); t[i].h->Draw("SAME"); t[i].h->SetStats(0); t[i].h->SetTitle("PMT Spectra of Pulsed LED w/ Varying Pulse Width"); t[i].h->GetXaxis()->SetTitle("Amplitude / (mV)"); t[i].h->GetYaxis()->SetTitle("Events"); t[i].h->GetYaxis()->SetRangeUser(0.5, 20000); } b[0].h->SetLineColor(1); b[0].h->SetLineWidth(2); b[0].h->Draw("SAME"); b[0].h->SetStats(0); TLine * cutLine_t = new TLine(-1*cut, 0.0, -1*cut, 20000.0); cutLine_t->SetLineWidth(2); cutLine_t->SetLineColor(1); cutLine_t->SetLineStyle(2); cutLine_t->Draw(); TLine * meanLine_t = new TLine(b[0].e + 0.89, 0.0, b[0].e + 0.89, 20000.0); meanLine_t->SetLineWidth(2); meanLine_t->SetLineColor(2); meanLine_t->SetLineStyle(2); meanLine_t->Draw(); // Add legend //TLegend * leg = new TLegend(0.1, 0.7, 0.48, 0.9); //leg->SetHeader("Legend"); //leg->AddEntry(t[0].h, " // Plot background //TCanvas * b_c = new TCanvas("b_c", "Background Canvas", 200, 10, 700, 500); //b_c->SetLogy(); ////b[0].h->Sumw2(); ////b[0].h->Draw(); //b[0].h->GetYaxis()->SetRangeUser(1.0, 100000.0); //b[0].h->SetTitle("Background PMT Spectrum"); //b[0].h->GetXaxis()->SetTitle("Amplitude / (mV)"); //b[0].h->GetYaxis()->SetTitle("Events"); //TLine * cutLine_b = new TLine(cut, 0.0, cut, 1000000.0); //cutLine_b->SetLineWidth(2); //cutLine_b->Draw(); }
void makeNice(TString fileName, TString nice = "nicePlot"){ TFile *f = TFile::Open(fileName); // TFile *f = TFile::Open("out_Parameters_bkg1_3vtx.root"); TGraphErrors * gRgre = (TGraphErrors*)f->Get("gR"); TGraphErrors * gXgre = (TGraphErrors*)f->Get("gX"); TGraphErrors * gYgre = (TGraphErrors*)f->Get("gY"); TGraphErrors * rRgre = (TGraphErrors*)f->Get("rR"); TGraphErrors * rXgre = (TGraphErrors*)f->Get("rX"); TGraphErrors * rYgre = (TGraphErrors*)f->Get("rY"); //=========Macro generated from canvas: c1_n2/c1_n2 //========= (Fri May 27 11:43:08 2011) by ROOT version5.27/06b TCanvas *c1_n2 = new TCanvas("c1_n2","c1_n2",700,1500); gStyle->SetOptFit(0); gStyle->SetOptStat(0); c1_n2->Range(0,0,1,1); c1_n2->SetFillColor(0); c1_n2->SetBorderMode(0); c1_n2->SetBorderSize(2); c1_n2->SetTickx(1); c1_n2->SetTicky(1); c1_n2->SetLeftMargin(0.13); c1_n2->SetRightMargin(0.05); c1_n2->SetTopMargin(0.05); c1_n2->SetBottomMargin(0.13); c1_n2->SetFrameFillStyle(0); c1_n2->SetFrameBorderMode(0); // ------------>Primitives in pad: c1_n2_1 TPad *c1_n2_1 = new TPad("c1_n2_1", "c1_n2_1",0.01,0.67,0.99,0.99); c1_n2_1->Draw(); c1_n2_1->cd(); c1_n2_1->Range(-52.68293,-0.03170732,44.87805,0.2121951); c1_n2_1->SetFillColor(0); c1_n2_1->SetBorderMode(0); c1_n2_1->SetBorderSize(2); c1_n2_1->SetTickx(1); c1_n2_1->SetTicky(1); c1_n2_1->SetLeftMargin(0.12); c1_n2_1->SetRightMargin(0.02); c1_n2_1->SetTopMargin(0.05); c1_n2_1->SetBottomMargin(0.2); c1_n2_1->SetFrameFillStyle(0); c1_n2_1->SetFrameBorderMode(0); c1_n2_1->SetFrameFillStyle(0); c1_n2_1->SetFrameBorderMode(0); TH1D *PLOTTERX = new TH1D("PLOTTERX","",1,-40,40); PLOTTERX->SetMinimum(-0.19); PLOTTERX->SetMaximum(+0.19); PLOTTERX->SetFillColor(63); PLOTTERX->SetLineStyle(0); PLOTTERX->SetMarkerStyle(20); PLOTTERX->GetXaxis()->SetLabelFont(42); PLOTTERX->GetXaxis()->SetLabelOffset(0.007); PLOTTERX->GetXaxis()->SetLabelSize(0.09); PLOTTERX->GetXaxis()->SetTitleSize(0.1); PLOTTERX->GetXaxis()->SetTitleOffset(0.9); PLOTTERX->GetXaxis()->SetTitleFont(42); PLOTTERX->GetXaxis()->SetTitle("z [cm]"); PLOTTERX->GetYaxis()->SetNdivisions(505); PLOTTERX->GetYaxis()->SetTitle("x_{0} [cm] "); PLOTTERX->GetYaxis()->SetLabelFont(42); PLOTTERX->GetYaxis()->SetLabelOffset(0.007); PLOTTERX->GetYaxis()->SetLabelSize(0.09); PLOTTERX->GetYaxis()->SetTitleSize(0.1); PLOTTERX->GetYaxis()->SetTitleOffset(0.5); PLOTTERX->GetYaxis()->SetTitleFont(42); PLOTTERX->GetZaxis()->SetLabelFont(42); PLOTTERX->GetZaxis()->SetLabelOffset(0.007); PLOTTERX->GetZaxis()->SetLabelSize(0.05); PLOTTERX->GetZaxis()->SetTitleSize(0.06); PLOTTERX->GetZaxis()->SetTitleFont(42); PLOTTERX->Draw(""); gXgre->SetFillColor(kBlack); gXgre->SetMarkerStyle(20); gXgre->SetMarkerColor(kBlack); gXgre->SetLineColor(kBlack); gXgre->GetListOfFunctions()->RemoveLast(); //to remove parameters panel... gXgre->GetListOfFunctions()->RemoveLast(); //...and old fit gXgre->SetLineWidth(2); gXgre->Draw("P"); rXgre->SetFillColor(kBlue); rXgre->SetMarkerStyle(20); rXgre->SetMarkerColor(kBlue); rXgre->SetLineColor(kBlue); rXgre->GetListOfFunctions()->RemoveLast(); //to remove parameters panel... rXgre->GetListOfFunctions()->RemoveLast(); //...and old fit rXgre->SetLineWidth(2); rXgre->Draw("P"); TLatex *CMSPrel = new TLatex(-37.0,PLOTTERX->GetMaximum()-0.025,"CMS Preliminary 2011"); CMSPrel->SetTextSize(0.06); // CMSPrel->Draw(); c1_n2_1->Modified(); c1_n2->cd(); // ------------>Primitives in pad: c1_n2_2 TPad *c1_n2_2 = new TPad("c1_n2_1", "c1_n2_1",0.01,0.34,0.99,0.66); // TPad *c1_n2_1 = new TPad("c1_n2_1", "c1_n2_1",0.01,0.01,0.99,0.33); c1_n2_2->Draw(); c1_n2_2->cd(); c1_n2_2->Range(-52.68293,-0.3317073,44.87805,-0.08780488); c1_n2_2->SetFillColor(0); c1_n2_2->SetBorderMode(0); c1_n2_2->SetBorderSize(2); c1_n2_2->SetTickx(1); c1_n2_2->SetTicky(1); c1_n2_2->SetLeftMargin(0.12); c1_n2_2->SetRightMargin(0.02); c1_n2_2->SetTopMargin(0.05); c1_n2_2->SetBottomMargin(0.2); c1_n2_2->SetFrameFillStyle(0); c1_n2_2->SetFrameBorderMode(0); c1_n2_2->SetFrameFillStyle(0); c1_n2_2->SetFrameBorderMode(0); TH1D *PLOTTERY = new TH1D("PLOTTERY","",1,-40,40); PLOTTERY->SetMinimum(-0.29); PLOTTERY->SetMaximum(+0.09); PLOTTERY->SetFillColor(63); PLOTTERY->SetLineStyle(0); PLOTTERY->SetMarkerStyle(20); PLOTTERY->GetXaxis()->SetLabelFont(42); PLOTTERY->GetXaxis()->SetLabelOffset(0.007); PLOTTERY->GetXaxis()->SetLabelSize(0.09); PLOTTERY->GetXaxis()->SetTitleSize(0.1); PLOTTERY->GetXaxis()->SetTitleFont(42); PLOTTERY->GetXaxis()->SetTitleOffset(0.9); PLOTTERY->GetXaxis()->SetTitle("z [cm]"); PLOTTERY->GetYaxis()->SetNdivisions(505); PLOTTERY->GetYaxis()->SetTitle("y_{0} [cm] "); PLOTTERY->GetYaxis()->SetLabelFont(42); PLOTTERY->GetYaxis()->SetLabelOffset(0.007); PLOTTERY->GetYaxis()->SetLabelSize(0.09); PLOTTERY->GetYaxis()->SetTitleSize(0.1); PLOTTERY->GetYaxis()->SetTitleOffset(0.5); PLOTTERY->GetYaxis()->SetTitleFont(42); PLOTTERY->GetZaxis()->SetLabelFont(42); PLOTTERY->GetZaxis()->SetLabelOffset(0.007); PLOTTERY->GetZaxis()->SetLabelSize(0.05); PLOTTERY->GetZaxis()->SetTitleSize(0.06); PLOTTERY->GetZaxis()->SetTitleFont(42); PLOTTERY->Draw(""); gYgre->SetFillColor(kBlack); gYgre->SetMarkerStyle(20); gYgre->SetMarkerColor(kBlack); gYgre->SetLineColor(kBlack); gYgre->GetListOfFunctions()->RemoveLast(); //to remove parameters panel... gYgre->GetListOfFunctions()->RemoveLast(); //...and old fit gYgre->SetLineWidth(2); gYgre->Draw("P"); rYgre->SetFillColor(kBlue); rYgre->SetMarkerStyle(20); rYgre->SetMarkerColor(kBlue); rYgre->SetLineColor(kBlue); rYgre->GetListOfFunctions()->RemoveLast(); //to remove parameters panel... rYgre->GetListOfFunctions()->RemoveLast(); //...and old fit rYgre->SetLineWidth(2); rYgre->Draw("P"); TLatex *CMSPrel = new TLatex(-37.0,PLOTTERY->GetMaximum()-0.025,"CMS Preliminary 2011"); CMSPrel->SetTextSize(0.06); // CMSPrel->Draw(); c1_n2_2->Modified(); c1_n2->cd(); // ------------>Primitives in pad: c1_n2_2 TPad *c1_n2_3 = new TPad("c1_n2_1", "c1_n2_1",0.01,0.01,0.99,0.33); // TPad *c1_n2_1 = new TPad("c1_n2_1", "c1_n2_1",0.01,0.01,0.99,0.33); c1_n2_3->Draw(); c1_n2_3->cd(); c1_n2_3->Range(-52.68293,-0.3317073,44.87805,-0.08780488); c1_n2_3->SetFillColor(0); c1_n2_3->SetBorderMode(0); c1_n2_3->SetBorderSize(2); c1_n2_3->SetTickx(1); c1_n2_3->SetTicky(1); c1_n2_3->SetLeftMargin(0.12); c1_n2_3->SetRightMargin(0.02); c1_n2_3->SetTopMargin(0.05); c1_n2_3->SetBottomMargin(0.2); c1_n2_3->SetFrameFillStyle(0); c1_n2_3->SetFrameBorderMode(0); c1_n2_3->SetFrameFillStyle(0); c1_n2_3->SetFrameBorderMode(0); TH1D *PLOTTERR = new TH1D("PLOTTERR","",1,-40,40); PLOTTERR->SetMinimum(2.87); PLOTTERR->SetMaximum(2.97); PLOTTERR->SetFillColor(63); PLOTTERR->SetLineStyle(0); PLOTTERR->SetMarkerStyle(20); PLOTTERR->GetXaxis()->SetLabelFont(42); PLOTTERR->GetXaxis()->SetLabelOffset(0.007); PLOTTERR->GetXaxis()->SetLabelSize(0.09); PLOTTERR->GetXaxis()->SetTitleSize(0.1); PLOTTERR->GetXaxis()->SetTitleFont(42); PLOTTERR->GetXaxis()->SetTitleOffset(0.9); PLOTTERR->GetXaxis()->SetTitle("z [cm]"); PLOTTERR->GetYaxis()->SetNdivisions(505); PLOTTERR->GetYaxis()->SetTitle("R [cm] "); PLOTTERR->GetYaxis()->SetLabelFont(42); PLOTTERR->GetYaxis()->SetLabelOffset(0.007); PLOTTERR->GetYaxis()->SetLabelSize(0.09); PLOTTERR->GetYaxis()->SetTitleSize(0.1); PLOTTERR->GetYaxis()->SetTitleOffset(0.5); PLOTTERR->GetYaxis()->SetTitleFont(42); PLOTTERR->GetZaxis()->SetLabelFont(42); PLOTTERR->GetZaxis()->SetLabelOffset(0.007); PLOTTERR->GetZaxis()->SetLabelSize(0.05); PLOTTERR->GetZaxis()->SetTitleSize(0.06); PLOTTERR->GetZaxis()->SetTitleFont(42); PLOTTERR->Draw(""); gRgre->SetFillColor(kBlack); gRgre->SetMarkerStyle(20); gRgre->SetMarkerColor(kBlack); gRgre->SetLineColor(kBlack); gRgre->GetListOfFunctions()->RemoveLast(); //to remove parameters panel... gRgre->GetListOfFunctions()->RemoveLast(); //...and old fit gRgre->SetLineWidth(2); gRgre->Draw("P"); rRgre->SetFillColor(kBlue); rRgre->SetMarkerStyle(20); rRgre->SetMarkerColor(kBlue); rRgre->SetLineColor(kBlue); rRgre->GetListOfFunctions()->RemoveLast(); //to remove parameters panel... rRgre->GetListOfFunctions()->RemoveLast(); //...and old fit rRgre->SetLineWidth(2); rRgre->Draw("P"); TLatex *CMSPrel = new TLatex(-37.0,PLOTTERR->GetMaximum()-0.025,"CMS Preliminary 2011"); CMSPrel->SetTextSize(0.06); // CMSPrel->Draw(); c1_n2_3->Modified(); c1_n2->cd(); TF1* fX = new TF1("fX", "[0]+[1]*x", -35, 35); TF1* fY = new TF1("fY", "[0]+[1]*x", -35, 35); TF1* fR = new TF1("fR", "[0]+[1]*x", -35, 35); fX->SetParameter(0, 0.1); fX->SetParameter(1, -0.0007); fY->SetParameter(0, -0.2); fY->SetParameter(1, +0.0007); fR->SetParameter(0, 2.94); fR->SetParameter(1, 0.0); gXgre->Fit(fX); gYgre->Fit(fY); gRgre->Fit(fR); // c1_n2->cd(); c1_n2->Modified(); c1_n2->cd(); c1_n2->SetSelected(c1_n2); c1_n2->SaveAs(nice+".png"); //!Serve!!!! c1_n2->SaveAs(nice+".gif"); c1_n2->SaveAs(nice+".png"); }
void DrawVelocity() { gStyle->SetOptFit(11111111); TFile* tfCosmic = new TFile("CosmicOut_V4.root"); TTree* trCosmic = (TTree*)tfCosmic->Get("trOut"); Double_t FitP1[2]; Double_t FitP0[2]; Double_t FitChisq[2]; Int_t CosmicTrigUp; Int_t CosmicTrigDn; Double_t Theta; Double_t Roh; trCosmic->SetBranchAddress("FitP1" ,FitP1 ); trCosmic->SetBranchAddress("FitP0" ,FitP0 ); trCosmic->SetBranchAddress("FitChisq" ,FitChisq); trCosmic->SetBranchAddress("CosmicTrigUp",&CosmicTrigUp); trCosmic->SetBranchAddress("CosmicTrigDn",&CosmicTrigDn); trCosmic->SetBranchAddress("Theta" ,&Theta); trCosmic->SetBranchAddress("Roh" ,&Roh); std::cout<< "Output" << std::endl; //TFile* tfHist = new TFile("CosmicOut_V4_TrigHist.root","recreate"); TH1D* CosmicP1UpTrig[5]; TH1D* CosmicP1Trig[5][5]; TH1D* CosmicP1TrigLarge[5][5]; for( int i = 0; i< 5; i++){ CosmicP1UpTrig[i] = new TH1D( Form("CosmicP1UpTrig%d",i), Form("CosmicP1UpTrig%d",i), 100,-0.01,0.01); for( int j = 0; j< 5; j++){ CosmicP1Trig[i][j] = new TH1D( Form("CosmicP1_%d_%d",i,j), Form("CosmicP1_%d_%d",i,j), 100,-0.01,0.01); CosmicP1TrigLarge[i][j] = new TH1D( Form("CosmicP1Large_%d_%d",i,j), Form("CosmicP1Large_%d_%d",i,j), 100,-0.01,0.01); } } std::cout<< "LOOP" << std::endl; for( int ievent = 0; ievent < trCosmic->GetEntries(); ievent++){ trCosmic->GetEntry(ievent); if( TMath::Abs(Theta) < 5 ){ continue; } if( FitChisq[1] > 10 ){ continue; } CosmicP1UpTrig[ CosmicTrigUp ]->Fill( FitP1[1]*TMath::Cos(Theta*TMath::Pi()/180.)); CosmicP1Trig[CosmicTrigUp][CosmicTrigDn]->Fill( FitP1[1]*TMath::Cos(Theta*TMath::Pi()/180.) ); if( Roh > 600){ CosmicP1TrigLarge[CosmicTrigUp][CosmicTrigDn]->Fill( FitP1[1]*TMath::Cos(Theta*TMath::Pi()/180.) ); } } std::cout << "Draw" << std::endl; TGraphErrors* grSlope = new TGraphErrors(); TGraphErrors* grDelta = new TGraphErrors(); TGraphErrors* grSlopeLarge = new TGraphErrors(); grSlope->SetMarkerStyle( 7 ); grDelta->SetMarkerStyle( 7 ); grSlopeLarge->SetMarkerStyle( 7 ); TCanvas* can = new TCanvas("can","",1200,800); can->Divide(3,2); for( int i = 0; i< 5; i++){ for( int j = 0; j< 5; j++){ CosmicP1Trig[i][j]->Fit("gaus","Q","", CosmicP1Trig[i][j]->GetMean()-CosmicP1Trig[i][j]->GetRMS(), CosmicP1Trig[i][j]->GetMean()+CosmicP1Trig[i][j]->GetRMS()); TF1* func = CosmicP1Trig[i][j]->GetFunction("gaus"); grSlope->SetPoint( grSlope->GetN(),i*5+j+1, func->GetParameter(1)); grSlope->SetPointError( grSlope->GetN()-1, 0, func->GetParameter(2)); CosmicP1TrigLarge[i][j]->Fit("gaus","Q","", CosmicP1Trig[i][j]->GetMean()-1.5*CosmicP1Trig[i][j]->GetRMS(), CosmicP1Trig[i][j]->GetMean()+1.5*CosmicP1Trig[i][j]->GetRMS()); func = CosmicP1TrigLarge[i][j]->GetFunction("gaus"); grSlopeLarge->SetPoint( grSlopeLarge->GetN(), i*5+j+1, func->GetParameter(1)); grSlopeLarge->SetPointError( grSlopeLarge->GetN()-1,0,func->GetParameter(2)); } } for( int i = 0; i< 5; i++){ can->cd( i +1 ); CosmicP1UpTrig[i]->Draw(); for( int j = 0; j < 5; j++){ CosmicP1Trig[i][j]->SetLineColor(j+1); CosmicP1Trig[i][j]->Draw("same"); CosmicP1TrigLarge[i][j]->Draw("same"); } } double sol = 299.97;//[mm/ns] TLine* solLine = new TLine( -1, -1./sol, 25, -1./sol); //can->cd( 6 ); TCanvas* can1 = new TCanvas("can1","",800,400); can1->Divide( 2,1); can1->cd(1); grSlope->GetXaxis()->SetRangeUser( -1, 25); grSlope->Draw("AP"); solLine->SetLineStyle(2); solLine->Draw("same"); TCanvas* can2 = new TCanvas("can2","",1200,800); can2->Divide(3,2); for( int i = 0; i< 5; i++){ can2->cd( i+1 ); CosmicP1TrigLarge[i][0]->Draw(); for( int j = 0; j< 5; j++){ CosmicP1TrigLarge[i][j]->Draw("same"); } } can2->cd(6); grSlopeLarge->Draw("AP"); Double_t H_trig = 2800; Double_t R = 1200; TGraph* grDelta1 = new TGraph(); TGraph* grDelta2 = new TGraph(); TGraphErrors * grVCluster = new TGraphErrors(); for( int i = 0; i< 5; i++){ for( int j =0; j< 5; j++){ Double_t iv_0 = TMath::Abs(grSlope->GetY()[ i*5 +j ]); Double_t ive_0 = grSlope->GetEY()[ i*5 + j]; Double_t deltaZ = (i-j)*100*R/H_trig;//mm Double_t EdeltaZ = TMath::Sqrt(2)*50*R/H_trig; Double_t l = TMath::Sqrt( R*R + deltaZ*deltaZ); Double_t El = deltaZ*EdeltaZ/TMath::Sqrt( R*R + deltaZ*deltaZ); Double_t delta_t0 = l/sol; Double_t delta_t1 = iv_0*R - delta_t0; Double_t Edelta_t1 = QuadSum(ive_0*R, El/sol); Double_t V_CsI = deltaZ / delta_t1; Double_t EV_CsI = QuadSum( EdeltaZ / delta_t1, Edelta_t1/delta_t1); Double_t delta_t1_adj = deltaZ/70.; Double_t delta_t1_adj1 = deltaZ/80.; Double_t delta_t1_adj2 = deltaZ/90.; grDelta->SetPoint(grDelta->GetN(), (delta_t0+delta_t1_adj)/R , iv_0); grDelta1->SetPoint(grDelta1->GetN(), (delta_t0+delta_t1_adj1)/R , iv_0); grDelta2->SetPoint(grDelta2->GetN(), (delta_t0+delta_t1_adj2)/R , iv_0); if( TMath::Abs(deltaZ) <= 2*EdeltaZ ){ continue; } grVCluster->SetPoint( grVCluster->GetN(), i*5+j+1 , V_CsI); grVCluster->SetPointError( grVCluster->GetN()-1 , 0, EV_CsI); } } can1->cd(2); grVCluster->SetMarkerStyle( 6); grVCluster->Draw("AP"); grVCluster->Fit("pol0","","",0,26); /* grDelta1->SetMarkerColor(2); grDelta2->SetMarkerColor(3); grDelta1->SetMarkerStyle(6); grDelta2->SetMarkerStyle(6); can1->cd(2); grDelta->Draw("AP"); grDelta1->Draw("P"); grDelta2->Draw("P"); TF1* func = new TF1("func","x",0,0.1); func->Draw("same"); */ /* for( int i = 0; i< 5; i++){ CosmicP1UpTrig[i]->Write(); for( int j =0 ;j < 5; j++){ CosmicP1Trig[i][j]->Write(); } } tfHist->Close(); */ }
int main(int argc, char** argv){ ///================================================== ///==== Draw Distribution with and without scale ==== ///================================================== ///=============================================================================== gROOT->Reset(); gROOT->SetStyle("Plain"); gStyle->SetPalette(1); gStyle->SetOptStat(0); gStyle->SetOptFit(0); const Int_t __NRGBs = 5; const Int_t __NCont = 76; Double_t __stops[__NRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 }; Double_t __red[__NRGBs] = { 0.00, 0.00, 0.87, 1.00, 0.51 }; Double_t __green[__NRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 }; Double_t __blue[__NRGBs] = { 0.51, 1.00, 0.12, 0.00, 0.00 }; TColor::CreateGradientColorTable(__NRGBs, __stops, __red, __green, __blue, __NCont); gStyle->SetNumberContours(__NCont); ///=============================================================================== if(argc != 2) { std::cerr << ">>>>> analysis.cpp::usage: " << argv[0] << " configFileName" << std::endl ; return 1; } // Parse the config file parseConfigFile (argv[1]) ; std::string treeNameDATA = gConfigParser -> readStringOption("InputDATA::treeName"); std::string inputFileDATA = gConfigParser -> readStringOption("InputDATA::inputFile"); double luminosity = gConfigParser -> readDoubleOption("InputDATA::luminosity"); std::cout << ">>>>> InputDATA::treeName " << treeNameDATA << std::endl; std::cout << ">>>>> InputDATA::inputFile " << inputFileDATA << std::endl; std::cout << ">>>>> InputDATA::luminosity " << luminosity << std::endl; std::string treeNameMC = gConfigParser -> readStringOption("InputMC::treeName"); std::vector< std::string > inputFileMC = gConfigParser -> readStringListOption("InputMC::inputFile"); std::vector< std::string > inputSampleMC = gConfigParser -> readStringListOption("InputMC::nameSample"); std::vector< double > xSecAndEfficiency = gConfigParser -> readDoubleListOption("InputMC::xsecEff"); std::cout << ">>>>> InputMC::treeName " << treeNameMC << std::endl; std::cout << ">>>>> InputMC::inputFile size " << inputFileMC.size() << std::endl; if (inputFileMC.size() != xSecAndEfficiency.size() || inputFileMC.size() != inputSampleMC.size()) { std::cerr << " >>>> Error: different number of samples and cross sections" << std::endl; return 0; } int nMC = inputFileMC.size(); for (int iMC = 0; iMC < nMC; iMC++) { std::cout << ">>>>> InputMC::inputFile[" << iMC << "] = " << inputSampleMC.at(iMC) << " => " << inputFileMC.at(iMC) << " : " << xSecAndEfficiency.at(iMC) << " : " << luminosity * xSecAndEfficiency.at(iMC) << std::endl; } int binX = gConfigParser -> readIntOption("Options::binX"); double minX = gConfigParser -> readDoubleOption("Options::minX"); double maxX = gConfigParser -> readDoubleOption("Options::maxX"); std::string variableX = gConfigParser -> readStringOption("Options::variableX"); std::cout << ">>>>> Options::binX " << binX << std::endl; std::cout << ">>>>> Options::minX " << minX << std::endl; std::cout << ">>>>> Options::maxX " << maxX << std::endl; std::cout << ">>>>> Options::variableX " << variableX.c_str() << std::endl; int binY = gConfigParser -> readIntOption("Options::binY"); double minY = gConfigParser -> readDoubleOption("Options::minY"); double maxY = gConfigParser -> readDoubleOption("Options::maxY"); std::string variableY = gConfigParser -> readStringOption("Options::variableY"); std::cout << ">>>>> Options::binY " << binY << std::endl; std::cout << ">>>>> Options::minY " << minY << std::endl; std::cout << ">>>>> Options::maxY " << maxY << std::endl; std::cout << ">>>>> Options::variableY " << variableY.c_str() << std::endl; int binRatio = gConfigParser -> readIntOption("Options::binRatio"); double minRatio = gConfigParser -> readDoubleOption("Options::minRatio"); double maxRatio = gConfigParser -> readDoubleOption("Options::maxRatio"); std::cout << ">>>>> Options::minRatio " << minRatio << std::endl; std::cout << ">>>>> Options::maxRatio " << maxRatio << std::endl; std::string outputFile = gConfigParser -> readStringOption("Output::outputFile"); std::cout << ">>>>> Output::outputFile " << outputFile << std::endl; // TString AdditionalCut = Form("eta > 1.5");// || eta < -1.5)");// && eleFBrem<0.5"); TString AdditionalCut = Form("eta < -1.5");// || eta < -1.5)");// && eleFBrem<0.5"); // TString AdditionalCut = Form("(eta > 1.5 || eta < -1.5)");// && abs(eleFBrem)<1"); EColor vColor[100] = { kBlue,(EColor)(kBlue+1),(EColor) (kBlue+2), kRed,(EColor) (kRed+1),(EColor) (kRed+2), kGreen,(EColor) (kGreen+1),(EColor) (kGreen+2), kTeal,(EColor) (kTeal+1), kOrange,(EColor) (kOrange+1), kMagenta,(EColor) (kMagenta+1),(EColor) (kViolet),(EColor) (kYellow),(EColor) (kGray)}; ///==== DATA ==== TFile* fileInDATA = new TFile(inputFileDATA.c_str(),"READ"); ///==== W ==== TFile* fileInMC[nMC]; for (int iMC = 0; iMC < nMC; iMC++) { fileInMC[iMC] = new TFile(inputFileMC.at(iMC).c_str(),"READ"); } ///==== output ==== TFile* outFile = new TFile(outputFile.c_str(),"RECREATE"); outFile->cd(); ///==== Prepare input trees ==== TLegend* leg = new TLegend(0.55,0.7,0.95,0.95); leg->SetFillColor(0); TLegend* legDown = new TLegend(0.55,0.1,0.95,0.35); legDown->SetFillColor(0); TTree* MyTreeDATA = (TTree*) fileInDATA->Get(treeNameDATA.c_str()); int initialNumber; TH2F* HistoDATA = new TH2F("DATA","DATA",binX,minX,maxX,binY,minY,maxY); TH1F* HistoRatioDATA = new TH1F("RatioDATA","RatioDATA",binRatio,minRatio,maxRatio); TString DrawDATA = Form("%s:%s >> DATA",variableY.c_str(),variableX.c_str()); MyTreeDATA->Draw(DrawDATA.Data(),AdditionalCut.Data()); HistoDATA->SetMarkerSize(1); HistoDATA->SetMarkerStyle(20); HistoDATA->GetXaxis()->SetTitle(variableX.c_str()); HistoDATA->GetYaxis()->SetTitle(variableY.c_str()); leg->AddEntry(HistoDATA,HistoDATA->GetTitle(),"p"); legDown->AddEntry(HistoDATA,HistoDATA->GetTitle(),"p"); DrawDATA = Form("(%s) / (%s) >> RatioDATA",variableY.c_str(),variableX.c_str()); MyTreeDATA->Draw(DrawDATA.Data(),AdditionalCut.Data()); HistoRatioDATA->SetMarkerSize(1); HistoRatioDATA->SetMarkerStyle(20); HistoRatioDATA->GetXaxis()->SetTitle(Form("(%s)/(%s)",variableY.c_str(),variableX.c_str())); TH2F* HistoMC[nMC]; TH1F* HistoRatioMC[nMC]; TH2F* HistoMC_SUM = new TH2F("HistoMC_SUM","HistoMC_SUM",binX,minX,maxX,binY,minY,maxY); TH1F* HistoRatioMC_SUM = new TH1F("HistoRatioMC_SUM","HistoRatioMC_SUM",binRatio,minRatio,maxRatio); SetColorAndStyleHisto(*(HistoRatioMC_SUM),kBlue); TTree* MyTreeMC[nMC]; THStack* hsMC = new THStack("hsMC","hsMC"); double MC_Expected = 0; for (int iMC = 0; iMC < nMC; iMC++) { // for (int iMC = nMC-1; iMC >= 0; iMC--) { MyTreeMC[iMC] = (TTree*) fileInMC[iMC]->Get(treeNameMC.c_str()); MyTreeMC[iMC]->SetBranchAddress("initialNumber",&initialNumber); MyTreeMC[iMC]->GetEntry(0); xSecAndEfficiency.at(iMC) = xSecAndEfficiency.at(iMC) / initialNumber; ///==== normalize to initial number of events HistoMC[iMC] = new TH2F(inputSampleMC.at(iMC).c_str(),inputSampleMC.at(iMC).c_str(),binX,minX,maxX,binY,minY,maxY); HistoRatioMC[iMC] = new TH1F(Form("%s_Ratio",inputSampleMC.at(iMC).c_str()),Form("%s_Ratio",inputSampleMC.at(iMC).c_str()),binRatio,minRatio,maxRatio); TString Draw = Form("%s:%s >> %s",variableY.c_str(),variableX.c_str(),inputSampleMC.at(iMC).c_str()); MyTreeMC[iMC]->Draw(Draw.Data(),AdditionalCut.Data()); Draw = Form("(%s) / (%s) >> %s",variableY.c_str(),variableX.c_str(),Form("%s_Ratio",inputSampleMC.at(iMC).c_str())); MyTreeMC[iMC]->Draw(Draw.Data(),AdditionalCut.Data()); HistoRatioMC[iMC]->GetXaxis()->SetTitle(Form("(%s)/(%s)",variableY.c_str(),variableX.c_str())); std::cout << ">>>>>> " << inputSampleMC.at(iMC) << " : " << xSecAndEfficiency.at(iMC) << " : " << luminosity << " : " << HistoMC[iMC]->GetEntries() << " = " << luminosity * xSecAndEfficiency.at(iMC) * HistoMC[iMC]->GetEntries() << std::endl; std::cout << " >> " << Draw.Data() << std::endl; std::cout << " >> " << HistoMC[iMC]->GetEntries() << " Entries" << std::endl; MC_Expected += luminosity * xSecAndEfficiency.at(iMC) * HistoMC[iMC]->GetEntries(); HistoMC[iMC]->Scale(luminosity * xSecAndEfficiency.at(iMC)); // / HistoMC[iMC]->GetEntries()); HistoRatioMC[iMC]->Scale(luminosity * xSecAndEfficiency.at(iMC)); // / HistoMC[iMC]->GetEntries()); SetColorAndStyleHisto(*(HistoMC[iMC]),vColor[iMC]); SetColorAndStyleHisto(*(HistoRatioMC[iMC]),vColor[iMC]); HistoMC[iMC]->GetXaxis()->SetTitle(variableX.c_str()); HistoMC[iMC]->GetYaxis()->SetTitle(variableY.c_str()); HistoMC_SUM->Add(HistoMC[iMC]); HistoMC_SUM->GetXaxis()->SetTitle(variableX.c_str()); HistoMC_SUM->GetYaxis()->SetTitle(variableY.c_str()); HistoRatioMC_SUM->Add(HistoRatioMC[iMC]); HistoRatioMC_SUM->GetXaxis()->SetTitle(Form("(%s)/(%s)",variableY.c_str(),variableX.c_str())); hsMC->Add(HistoMC[iMC]); if (iMC == 0) hsMC->Add(HistoMC[iMC]); leg->AddEntry(HistoMC[iMC],HistoMC[iMC]->GetTitle(),"f"); legDown->AddEntry(HistoMC[iMC],HistoMC[iMC]->GetTitle(),"f"); } ///==== make fit ==== TH1D* htemp_prof = smartGausProfileXSQRTN(HistoDATA,2); TGraphErrors grH = buildGEfromH_Personalized(*htemp_prof); grH.SetMarkerStyle(22); grH.SetMarkerSize(0.7); grH.SetMarkerColor(kBlue); grH.SetFillColor(kBlue); grH.SetFillStyle(3335); grH.SetLineWidth(1); grH.SetLineColor(kBlue); grH.GetXaxis()->SetTitle(variableX.c_str()); grH.GetYaxis()->SetTitle(variableY.c_str()); ///---------------------- ///---- Plot results ---- ///---------------------- std::cerr << " MC expected : DATA = " << MC_Expected << " : " << HistoDATA->GetEntries() << std::endl; std::cerr << " HistoDATA->GetMaximum() = " << HistoDATA->GetMaximum() << std::endl; std::cerr << " HistoDATA->GetEntries() = " << HistoDATA->GetEntries() << std::endl; outFile->cd(); TCanvas cResultDistro("cResultDistro","cResultDistro",900,900); cResultDistro.Divide(2,2); cResultDistro.cd(1); HistoDATA->DrawClone("colz"); gPad->SetGrid(); TString tLumiName = Form("#int L = %.4f pb^{-1}",luminosity); TLatex tLumi(1.5 * HistoDATA->GetMean(1),0.2 * HistoDATA->GetMaximum(),tLumiName.Data()); tLumi.DrawClone(); cResultDistro.cd(2); HistoRatioMC_SUM->Draw(); HistoRatioDATA->Draw("E1same"); TString tEleName = Form("%d electrons",(int) HistoDATA->GetEntries()); TLatex tEle(2.0 * HistoRatioDATA->GetMean(1),0.3 * HistoRatioDATA->GetMaximum(),tEleName.Data()); tEle.DrawClone(); gPad->SetGrid(); cResultDistro.cd(3); grH.Draw("APL"); double minFit = gConfigParser -> readDoubleOption("Options::minFit"); double maxFit = gConfigParser -> readDoubleOption("Options::maxFit"); std::cout << ">>>>> Options::minFit " << minFit << std::endl; std::cout << ">>>>> Options::maxFit " << maxFit << std::endl; TF1* funz = new TF1 ("funz","pol1",minFit,maxFit); // funz->FixParameter(0,0); funz->SetParameter(0,0); funz->SetParameter(1,1); grH.Fit("funz","RMQ"); std::cerr << " Y = [0] + [1] * X " << std::endl; std::cerr << " [0] = " << funz->GetParameter(0) << " +/- " << funz->GetParError(0) << std::endl; std::cerr << " [1] = " << funz->GetParameter(1) << " +/- " << funz->GetParError(1) << std::endl; double coeffDATA = funz->GetParameter(1); double errCoeffDATA = funz->GetParError(1); gPad->SetGrid(); cResultDistro.cd(4); HistoRatioMC_SUM->Draw(); HistoRatioDATA->Draw("E1same"); tEle.DrawClone(); gPad->SetGrid(); gPad->SetLogy(); TString nameImage = Form("%s_%s_%d.png",variableY.c_str(),variableX.c_str(),1); cResultDistro.SaveAs(nameImage.Data()); TString nameImageRoot = Form("%s_%s_%d.root",variableY.c_str(),variableX.c_str(),1); cResultDistro.SaveAs(nameImageRoot.Data()); TCanvas cResultDistroMC("cResultDistroMC","cResultDistroMC",800,800); cResultDistroMC.Divide(2,2); // cResultDistroMC.Divide(2,nMC); // for (int iMC = 0; iMC < nMC; iMC++) { // cResultDistroMC.cd(2*iMC+1); // HistoMC[iMC]->DrawClone("colz"); // HistoDATA->DrawClone("BOXsame"); // cResultDistroMC.cd(2*iMC+2); // HistoRatioMC[iMC]->DrawNormalized(""); // HistoRatioDATA->DrawNormalized("E1same"); // } cResultDistroMC.cd(1); HistoMC_SUM->DrawClone("colz"); HistoDATA->DrawClone("BOXsame"); gPad->SetGrid(); ///==== make fit ==== cResultDistroMC.cd(3); TH1D* MChtemp_prof = smartGausProfileXSQRTN(HistoMC_SUM,2); TGraphErrors MCgrH = buildGEfromH_Personalized(*MChtemp_prof); MCgrH.SetMarkerStyle(22); MCgrH.SetMarkerSize(0.7); MCgrH.SetMarkerColor(kRed); MCgrH.SetFillColor(kRed); MCgrH.SetFillStyle(3335); MCgrH.SetLineWidth(1); MCgrH.SetLineColor(kRed); MCgrH.GetXaxis()->SetTitle(variableX.c_str()); MCgrH.GetYaxis()->SetTitle(variableY.c_str()); funz->SetParameter(0,0); funz->SetParameter(1,1); MCgrH.Fit("funz","RMQ"); std::cerr << " ================= " << std::endl; std::cerr << " ======= MC ====== " << std::endl; std::cerr << " Y = [0] + [1] * X " << std::endl; std::cerr << " [0] = " << funz->GetParameter(0) << " +/- " << funz->GetParError(0) << std::endl; std::cerr << " [1] = " << funz->GetParameter(1) << " +/- " << funz->GetParError(1) << std::endl; double coeffMC = funz->GetParameter(1); double errCoeffMC = funz->GetParError(1); MCgrH.Draw("APL"); gPad->SetGrid(); cResultDistroMC.cd(4); MCgrH.Draw("APL"); grH.Draw("PLSAME"); gPad->SetGrid(); TString nameImageLog = Form("%s_%s_%d_MC.png",variableY.c_str(),variableX.c_str(),1); cResultDistroMC.SaveAs(nameImageLog.Data()); std::cerr << " 1 - alpha = " << coeffDATA / coeffMC << " +/- " << sqrt( (errCoeffDATA/coeffMC)*(errCoeffDATA/coeffMC) + (errCoeffMC*coeffDATA/coeffMC/coeffMC)*(errCoeffMC*coeffDATA/coeffMC/coeffMC) ) << std::endl; std::cerr << " alpha = " << 1-coeffDATA / coeffMC << " +/- " << sqrt( (errCoeffDATA/coeffMC)*(errCoeffDATA/coeffMC) + (errCoeffMC*coeffDATA/coeffMC/coeffMC)*(errCoeffMC*coeffDATA/coeffMC/coeffMC) ) << std::endl; // TCanvas cResultDistro_1("cResultDistro_1","cResultDistro_1",800,800); // HistoRatioMC_SUM->Draw(); // HistoRatioDATA->Draw("E1same"); // tEle.DrawClone(); // gPad->SetGrid(); // gPad->SetLogy(); }
int main(int argc, char* argv[]) { TString filename(argv[1]); ifstream infile; infile.open(filename); if (!infile.good()) { cout << "Cannot open this file: " << filename << endl; return -1; } const int Num = 5; double EmptyNoise[Num]; double EmptySignal[Num]; double AttenNoise[Num]; double AttenSignal[Num]; int i=0; int NumEmpNoi = 0; int NumEmpSig = 0; int NumAttNoi = 0; int NumAttSig = 0; double column1; double column2; double column3; double column4; double column5; while (!infile.eof()) { i++; infile >> column1 >> column2 >> column3 >> column4 >> column5; if (!infile.eof()) { if (i%5==1) { EmptyNoise[NumEmpNoi] = (column1 + column2 + column3 + column4 + column5)/5.0; NumEmpNoi++; } if (i%5==2) { EmptySignal[NumEmpSig] = (column1 + column2 + column3 + column4 + column5)/5.0; NumEmpSig++; } if (i%5==3) { AttenNoise[NumAttNoi] = (column1 + column2 + column3 + column4 + column5)/5.0; NumAttNoi++; } if (i%5==4) { AttenSignal[NumAttSig] = (column1 + column2 + column3 + column4 + column5)/5.0; NumAttSig++; } } } infile.close(); ifstream infile2; infile2.open(filename); double StdEmptyNoise[Num]; double StdEmptySignal[Num]; double StdAttenNoise[Num]; double StdAttenSignal[Num]; int k=0; int NumStdEmpNoi = 0; int NumStdEmpSig = 0; int NumStdAttNoi = 0; int NumStdAttSig = 0; while (!infile2.eof()) { k++; infile2 >> column1 >> column2 >> column3 >> column4 >> column5; if (!infile2.eof()) { if (k%5==1) { StdEmptyNoise[NumStdEmpNoi] = (pow((column1 - EmptyNoise[NumStdEmpNoi]),2) + pow((column2 - EmptyNoise[NumStdEmpNoi]),2) + pow((column3 - EmptyNoise[NumStdEmpNoi]),2) + pow((column4 - EmptyNoise[NumStdEmpNoi]),2) + pow((column5 - EmptyNoise[NumStdEmpNoi]),2))/(Num-1); NumStdEmpNoi++; } if (k%5==2) { StdEmptySignal[NumStdEmpSig] = (pow((column1 - EmptySignal[NumStdEmpSig]),2) + pow((column2 - EmptySignal[NumStdEmpSig]),2) + pow((column3 - EmptySignal[NumStdEmpSig]),2) + pow((column4 - EmptySignal[NumStdEmpSig]),2) + pow((column5 - EmptySignal[NumStdEmpSig]),2))/(Num-1); NumStdEmpSig++; } if (k%5==3) { StdAttenNoise[NumStdAttNoi] = (pow((column1 - AttenNoise[NumStdAttNoi]),2) + pow((column2 - AttenNoise[NumStdAttNoi]),2) + pow((column3 - AttenNoise[NumStdAttNoi]),2) + pow((column4 - AttenNoise[NumStdAttNoi]),2) + pow((column5 - AttenNoise[NumStdAttNoi]),2))/(Num-1); NumStdAttNoi++; } if (k%5==4) { StdAttenSignal[NumStdAttSig] = (pow((column1 - AttenSignal[NumStdAttSig]),2) + pow((column2 - AttenSignal[NumStdAttSig]),2) + pow((column3 - AttenSignal[NumStdAttSig]),2) + pow((column4 - AttenSignal[NumStdAttSig]),2) + pow((column5 - AttenSignal[NumStdAttSig]),2))/(Num-1); NumStdAttSig++; } } } infile2.close(); double InPower[Num]; double OutPower[Num]; double InError[Num]; double OutError[Num]; for (int j=0;j<Num;j++) { InPower[j] = EmptySignal[j] - EmptyNoise[j]; InError[j] = TMath::Sqrt(StdEmptySignal[j] + StdEmptyNoise[j]); OutPower[j] = AttenSignal[j] - AttenNoise[j]; OutError[j] = TMath::Sqrt(StdAttenSignal[j] + StdAttenNoise[j]); } TCanvas* cc = new TCanvas("AbsoluteMeasurement","RayleighScattering",800,600); //gStyle->SetOptFit(kTRUE); gPad->SetLeftMargin(0.125); gStyle->SetOptFit(1111111); gStyle->SetStatY(0.85); gStyle->SetStatX(0.55); gStyle->SetStatW(0.18); gStyle->SetStatH(0.15); // gStyle->SetPadLeftMargin(0.2); TF1* fun = new TF1("fun","[0] * x + [1]", 0.0, 100000); // fun->FixParameter(1, 0.0); // TGraphErrors* tg = new TGraphErrors(Num, OutPower, InPower, OutError, InError); tg->Fit(fun,"EM0"); tg->GetXaxis()->SetTitle("Number of Scattering Photons"); tg->GetYaxis()->SetTitle("Number of Incident Photons"); tg->GetYaxis()->SetTitleOffset(1.5); tg->SetTitle(""); //tg->GetXaxis()->SetRangeUser(0.0,1500000.0); //tg->GetYaxis()->SetRangeUser(0.0,25000); tg->Draw("AP"); fun->SetLineColor(kBlack); fun->SetLineStyle(1); fun->SetLineWidth(1); //fun->GetParameters(); fun->Draw("same"); TString output = filename.Remove(filename.Length()-4); cc->SaveAs(output+".png"); return 0; }
// The actual job void signalEfficiency_w(int channel, double sqrts, int process, double JES, ofstream* txtYields) { TString schannel; if (channel == 1) schannel = "4mu"; else if (channel == 2) schannel = "4e"; else if (channel == 3) schannel = "2e2mu"; else cout << "Not a valid channel: " << channel << endl; TString schannelFilename = (schannel=="2e2mu"?"2mu2e":schannel); // adapt to naming convention of tree files TString sprocess; if (process == ggH) sprocess = "ggH"; else if (process == qqH) sprocess = "qqH"; else if (process == ZH) sprocess = "ZH"; else if (process == WH) sprocess = "WH"; else if (process == ttH) sprocess = "ttH"; else cout << "Not a valid channel: " << process << endl; TString sjes; if (JES==0.) sjes=""; else if (JES>0.) sjes="_up"; else if (JES<0.) sjes="_down"; TString ssqrts = (long) sqrts + TString("TeV"); // Print table with yields (*txtYields) << endl << endl << left << setw(7) << "*** Summary: " << sprocess << " process, sqrts = " << fixed << setprecision(0) <<sqrts << " TeV, channel = " << schannel << " ***" << endl << endl; (*txtYields) << left << setw(7) << "mH" << setw(13) << "XS*BR" << setw(13) << "Eff unt" << setw(13) << "Yield unt" << setw(13) << "Eff tag" << setw(13) << "Yield tag" << setw(13) << "Eff TOT" << setw(13) << "Yield TOT" << setw(13) << "Eff unt" << setw(13) << "Yield unt" << setw(13) << "Eff tag" << setw(13) << "Yield tag" << setw(13) << "Eff TOT" << setw(13) << "Yield TOT" << setw(13) << "n. raw" << setw(13) << "n. W pwg" << setw(13) << "n. W PU" << setw(13) << "n. W eff" << setw(13) << endl << left << setw(7) << " " << setw(13) << " " << setw(13) << "(in MW)" << setw(13) << "(in MW)" << setw(13) << "(in MW)" << setw(13) << "(in MW)" << setw(13) << "(in MW)" << setw(13) << "(in MW)" << setw(13) << "(full)" << setw(13) << "(full)" << setw(13) << "(full)" << setw(13) << "(full)" << setw(13) << "(full)" << setw(13) << "(full)" << setw(13) << "(full U+T)" << setw(13) << "(full U+T)" << setw(13) << "(full U+T)" << setw(13) << "(full U+T)" << endl << endl; cout << "process = " << sprocess << " schannel = " << schannel << " sqrts = " << sqrts << " JES = " << JES <<endl; TString totoutfile = "CardFragments/signalEfficiency_" + ssqrts + "_" + schannel + sjes + ".txt"; TString ratiooutfile = "CardFragments/signalEfficiency_" + ssqrts + "_" + schannel + sjes + "_ratio.txt"; TString jetyieldoutfile = "CardFragments/signalEfficiency_" + ssqrts + "_" + schannel + sjes + "_jetyields.txt"; // Create card fragments using new powheg samples ofstream oftot; ofstream ofrat; if (process==ggH) { oftot.open(totoutfile,ios_base::out); ofrat.open(ratiooutfile,ios_base::out); } else { oftot.open(totoutfile,ios_base::out | ios_base::app); ofrat.open(ratiooutfile,ios_base::out | ios_base::app); } ftot = new TFile("sigFigs" + ssqrts +"/eff_" + sprocess + "_" + schannel + sjes + (useNewGGHPowheg ? ".root" : "_oldPwg.root"),"RECREATE"); fratio = new TFile("sigFigs" + ssqrts +"/eff_" + sprocess + "_" + schannel + sjes + (useNewGGHPowheg ? "_ratio.root" : "_ratio_oldPwg.root"),"RECREATE"); gSystem->AddIncludePath("-I$ROOFITSYS/include"); setTDRStyle(false); gStyle->SetStatX(-0.5); int nPoints=0; int* masses=0; double* mHVal=0; // Pick the correct set of mass points, set subpath TString filepath; if (process==ggH){ if (useNewGGHPowheg) { if (sqrts==7) { nPoints = nPoints7TeV_p15; masses = masses7TeV_p15; mHVal = mHVal7TeV_p15; filepath = filePath7TeV; } else if (sqrts==8) { nPoints = nPoints8TeV_p15; masses = masses8TeV_p15; mHVal = mHVal8TeV_p15; filepath = filePath8TeV; } } else { // OLD powheg samples if (sqrts==7) { nPoints = nPoints7TeV; masses = masses7TeV; mHVal = mHVal7TeV; filepath = filePath7TeV; } else if (sqrts==8) { nPoints = nPoints8TeV; masses = masses8TeV; mHVal = mHVal8TeV; filepath = filePath8TeV; } } } else if (process==qqH) { if (sqrts==7) { nPoints = nVBFPoints7TeV; masses = VBFmasses7TeV; mHVal = mHVBFVal7TeV; filepath = filePath7TeV; } else if (sqrts==8) { nPoints = nVBFPoints8TeV; masses = VBFmasses8TeV; mHVal = mHVBFVal8TeV; filepath = filePath8TeV; } } else if (process==ZH || process==WH || process==ttH) { if (sqrts==7) { nPoints = nVHPoints7TeV; masses = VHmasses7TeV; mHVal = mHVHVal7TeV; filepath = filePath7TeV; } else if (sqrts==8) { nPoints = nVHPoints8TeV; masses = VHmasses8TeV; mHVal = mHVHVal8TeV; filepath = filePath8TeV; } } float xMax = masses[nPoints-1]+10; const int arraySize=200; assert (arraySize>=nPoints); double totefficiencyVal[arraySize]; double totefficiencyErr[arraySize]; double dijetratioVal[arraySize]; double dijetratioErr[arraySize]; double totefficiencyValInMW[arraySize]; double totefficiencyErrInMW[arraySize]; double dijetratioValInMW[arraySize]; double dijetratioErrInMW[arraySize]; // Define the object to compute XS and BRs HiggsCSandWidth *myCSW = new HiggsCSandWidth(gSystem->ExpandPathName("$CMSSW_BASE/src/Higgs/Higgs_CS_and_Width/txtFiles/")); TString infile; TGraph gJys(nPoints); for (int i = 0; i < nPoints; i++){ // Compute XS and BR double xsTimesBR = 0.; double BRH4e = myCSW->HiggsBR(12,masses[i]); double BRH2e2mu = myCSW->HiggsBR(13,masses[i]); double BRHZZ = myCSW->HiggsBR(11,masses[i]); double BR = BRHZZ; if (process==ggH || process==qqH) { if (channel==fs4mu || channel==fs4e) BR = BRH4e; else BR = BRH2e2mu; } if (process==ggH) xsTimesBR = BR*myCSW->HiggsCS(1,masses[i],sqrts); else if (process==qqH) xsTimesBR = BR*myCSW->HiggsCS(2,masses[i],sqrts); else if (process==ZH) xsTimesBR = BR*myCSW->HiggsCS(3,masses[i],sqrts); else if (process==WH) xsTimesBR = BR*myCSW->HiggsCS(4,masses[i],sqrts); else if (process==ttH) xsTimesBR = BR*myCSW->HiggsCS(5,masses[i],sqrts); if (process==ggH) { if (useNewGGHPowheg){ infile = filepath+ "/" + schannelFilename + "/HZZ4lTree_powheg15" + (masses[i]>200?"H":"jhuGenV3H") + (long)masses[i] + ".root"; } else { infile = filepath+ "/" + schannelFilename + "/HZZ4lTree_H" + (long)masses[i] + ".root"; } } else if (process==qqH) infile = filepath+ "/" + schannelFilename + "/HZZ4lTree_VBFH" + (long)masses[i] + ".root"; else if (process==WH || process==ZH || process==ttH) infile = filepath+ "/" + schannelFilename + "/HZZ4lTree_" + sprocess + (long)masses[i] + ".root"; TFile *f = TFile::Open(infile) ; TTree *t1 = (TTree*) f->Get("SelectedTree"); float MC_weight_norm, MC_weight_PUWeight, MC_weight_powhegWeight, MC_weight_dataMC; float MC_weight_noxsec; float GenHPt; //int NJets; short genProcessId=0; // short NJets30; vector<double> *JetPt=0; vector<double> *JetSigma=0; float ZZMass; t1->SetBranchAddress("MC_weight_norm",&MC_weight_norm); // For efficiency vs "proper" final state t1->SetBranchAddress("MC_weight_noxsec",&MC_weight_noxsec); // For efficiency vs all gen events t1->SetBranchAddress("MC_weight_powhegWeight",&MC_weight_powhegWeight); t1->SetBranchAddress("MC_weight_PUWeight",&MC_weight_PUWeight); t1->SetBranchAddress("MC_weight_dataMC",&MC_weight_dataMC); //t1->SetBranchAddress("NJets",&NJets); t1->SetBranchAddress("genProcessId",&genProcessId); t1->SetBranchAddress("JetPt",&JetPt); t1->SetBranchAddress("JetSigma",&JetSigma); // t1->SetBranchAddress("NJets30",&NJets30); t1->SetBranchAddress("GenHPt",&GenHPt); t1->SetBranchAddress("ZZMass",&ZZMass); //Initialize counters for non-dijet events Counts* untagInMW = new Counts(); Counts* untagAll = new Counts(); Counts* dijetInMW = new Counts(); Counts* dijetAll = new Counts(); // Find window width // FIXME move to external function double valueWidth = myCSW->HiggsWidth(0,masses[i]); double windowVal = max(valueWidth,1.); double lowside = 100.; double highside = 1000.0; if (masses[i] >= 275){ lowside = 180.0; highside = 650.0; } if (masses[i] >= 350){ lowside = 200.0; highside = 900.0; } if (masses[i] >= 500){ lowside = 250.0; highside = 1000.0; } if (masses[i] >= 700){ lowside = 350.0; highside = 1400.0; } double low_M = max( (masses[i] - 20.*windowVal), lowside); double high_M = min((masses[i] + 15.*windowVal), highside); // // Load Higgs pT weights for old powheg // TFile* fW; TH1D* h_HPtWeight; // TString fW_str = "./HPtWeights/weight_"; // fW_str += (long)masses[i]; // fW_str += (TString)".root"; // cout << fW_str << endl; // if (process==ggH) { // fW = TFile::Open(fW_str,"READ"); // h_HPtWeight = (TH1D*)fW->Get("h_weight"); // } for (int a = 0; a < t1->GetEntries(); a++){ t1->GetEntry(a); // Skip VH events that do not belong to the right gen prod mechanism. This is no longer necessary with the proper VH samples if ((process==ZH && genProcessId!=24) || (process==WH && genProcessId!=26) || (process==ttH && (genProcessId!=121 && genProcessId!=122))) continue; // We use the efficiency vs. generated events in the proper FS for ggH, VBF, and the efficiency vs all generated events for VH, ttH float effw = MC_weight_norm; if (process==ZH) { effw = MC_weight_noxsec*filter_eff_ZH_8TeV; } else if (process==WH){ effw = MC_weight_noxsec*filter_eff_WH_8TeV; } else if (process==ttH){ effw = MC_weight_noxsec*filter_eff_ttH_8TeV; } // double HPtWeight = 1.; // if (process==ggH) HPtWeight = h_HPtWeight->GetBinContent(h_HPtWeight->FindBin(GenHPt)); // //cout << "Higgs pT weight = " << HPtWeight << endl; // effw*=HPtWeight; int NJets=0; double jetptc=0; for (unsigned int j=0; j<JetPt->size();j++){ if (JES==0.) jetptc=JetPt->at(j); else if (JES!=0.) jetptc=JetPt->at(j)*(1+JES*JetSigma->at(j)); if (jetptc>30.) NJets++; } // Untagged if (NJets<2){ untagAll->incrCounters(effw, MC_weight_PUWeight, MC_weight_powhegWeight, MC_weight_dataMC); if ( (ZZMass>low_M && ZZMass<high_M) ) untagInMW->incrCounters(effw, MC_weight_PUWeight, MC_weight_powhegWeight, MC_weight_dataMC); } else{ // Dijet dijetAll->incrCounters(effw, MC_weight_PUWeight, MC_weight_powhegWeight, MC_weight_dataMC); if ( (ZZMass>low_M && ZZMass<high_M) ) dijetInMW->incrCounters(effw, MC_weight_PUWeight, MC_weight_powhegWeight, MC_weight_dataMC); } } // FIXME: the 7TeV old samples are assumed to have the ad-hoc correction factor for the mll>12 gen cut, // except for the 124,125,126 new samples. As this factor is accounted for in the x-section, we have to // apply it here. float m = masses[i]; if (!useNewGGHPowheg && process==ggH && sqrts==7 && m>=123.9 && m<=126.1) { float mllCorr = 0.5 + 0.5*erf((m-80.85)/50.42); untagAll->totalCtr = untagAll->totalCtr/mllCorr; untagAll->eff_noweight=untagAll->eff_noweight/mllCorr; untagInMW->totalCtr = untagInMW->totalCtr/mllCorr; untagInMW->eff_noweight=untagInMW->eff_noweight/mllCorr; dijetAll->totalCtr = dijetAll->totalCtr/mllCorr; dijetAll->eff_noweight=dijetAll->eff_noweight/mllCorr; dijetInMW->totalCtr = dijetInMW->totalCtr/mllCorr; dijetInMW->eff_noweight=dijetInMW->eff_noweight/mllCorr; } if (verbose) { cout << " m = " << masses[i] << " :" <<endl; cout << "Selected non-dijet events (all) = " << untagAll->numEventsRaw << " Powheg Wtd= " << untagAll->numEventsPowheg << " PU Wtd= " << untagAll->numEventsPU << " Data/MC Wtd= " << untagAll->numEventsDataMC << " Efficiency= " << untagAll->totalCtr << endl; cout << "Selected non-dijet events (in mass window) = " << untagInMW->numEventsRaw << " Powheg Wtd= " << untagInMW->numEventsPowheg << " PU Wtd= " << untagInMW->numEventsPU << " Data/MC Wtd= " << untagInMW->numEventsDataMC << " Efficiency= " << untagInMW->totalCtr << endl; cout << "Selected dijet events (all) = " << dijetAll->numEventsRaw << " Powheg Wtd= " << dijetAll->numEventsPowheg << " PU Wtd= " << dijetAll->numEventsPU << " Data/MC Wtd= " << dijetAll->numEventsDataMC << " Efficiency= " << dijetAll->totalCtr << endl; cout << "Selected dijet events (in mass window) = " << dijetInMW->numEventsRaw << " Powheg Wtd= " << dijetInMW->numEventsPowheg << " PU Wtd= " << dijetInMW->numEventsPU << " Data/MC Wtd= " << dijetInMW->numEventsDataMC << " Efficiency= " << dijetInMW->totalCtr << endl; } // All events totefficiencyVal[i] = untagAll->totalCtr + dijetAll->totalCtr; cout << "All events: " << sprocess << " " << m << " " << totefficiencyVal[i]<<endl; totefficiencyErr[i] = sqrt(untagAll->sumw2 + dijetAll->sumw2); dijetratioVal[i]=dijetAll->totalCtr/totefficiencyVal[i]; dijetratioErr[i]=sqrt(pow(untagAll->totalCtr,2)*dijetAll->sumw2 + pow(dijetAll->totalCtr,2)*untagAll->sumw2)/pow(totefficiencyVal[i],2); // FIXME: misses 1 term // Events inside the mass window totefficiencyValInMW[i] = untagInMW->totalCtr + dijetInMW->totalCtr; cout << "Events in mass window: " << sprocess << " " << m << " " << totefficiencyValInMW[i]<<endl; totefficiencyErrInMW[i] = sqrt(untagInMW->sumw2 + dijetInMW->sumw2); dijetratioValInMW[i]=dijetInMW->totalCtr/totefficiencyValInMW[i]; dijetratioErrInMW[i]=sqrt(pow(untagInMW->totalCtr,2)*dijetInMW->sumw2 + pow(dijetInMW->totalCtr,2)*untagInMW->sumw2)/pow(totefficiencyValInMW[i],2); // Write yields to output file double lumi = -1.; sqrts == 7 ? lumi = lumi7TeV*1000 : lumi = lumi8TeV*1000; double yieldTot = xsTimesBR*lumi*totefficiencyVal[i]; double yieldTag = xsTimesBR*lumi*dijetratioVal[i]*totefficiencyVal[i]; double yieldUnt = xsTimesBR*lumi*untagAll->totalCtr; double yieldTotInMW = xsTimesBR*lumi*totefficiencyValInMW[i]; double yieldTagInMW = xsTimesBR*lumi*dijetratioValInMW[i]*totefficiencyValInMW[i]; double yieldUntInMW = xsTimesBR*lumi*untagInMW->totalCtr; int prec = 3; if (process>=3) prec=5; (*txtYields) << left << setw(7) << fixed << setprecision(0) << masses[i] << setw(13) << fixed << setprecision(7) << xsTimesBR << setw(13) << fixed << setprecision(prec) << untagInMW->totalCtr << setw(13) << yieldUntInMW << setw(13) << dijetratioValInMW[i]*totefficiencyValInMW[i] << setw(13) << yieldTagInMW << setw(13) << fixed << setprecision(prec) << totefficiencyValInMW[i] << setw(13) << yieldTotInMW << setw(13) << fixed << setprecision(prec) << untagAll->totalCtr << setw(13) << yieldUnt << setw(13) << dijetratioVal[i]*totefficiencyVal[i] << setw(13) << yieldTag << setw(13) << totefficiencyVal[i] << setw(13) << yieldTot << setw(13) << fixed << setprecision(0) << untagAll->numEventsRaw + dijetAll->numEventsRaw << setw(13) << fixed << setprecision(2) << untagAll->numEventsRaw + dijetAll->numEventsPowheg << setw(13) << untagAll->numEventsPU + dijetAll->numEventsPU << setw(13) << untagAll->numEventsDataMC + dijetAll->numEventsDataMC << endl; f->Close(); gJys.SetPoint(i,masses[i],yieldTagInMW/yieldUntInMW); } TF1 *fitJys = new TF1("fitJys","pol3",100,1000); gJys.Fit(fitJys); (*txtYields) << endl << endl << endl; TGraphErrors* totgrEff; TGraphErrors* ratgrEff; if (process==ggH || process==qqH){ totgrEff = new TGraphErrors( nPoints, mHVal, totefficiencyVal, 0, totefficiencyErr); ratgrEff = new TGraphErrors( nPoints, mHVal, dijetratioVal, 0, dijetratioErr); } else { totgrEff = new TGraphErrors( nPoints, mHVal, totefficiencyValInMW, 0, totefficiencyErrInMW); ratgrEff = new TGraphErrors( nPoints, mHVal, dijetratioValInMW, 0, dijetratioErrInMW); } totgrEff->SetMarkerStyle(20); ratgrEff->SetMarkerStyle(20); //ICHEP parametrization //TF1 *polyFunc= new TF1("polyFunc","([0]+[1]*TMath::Erf( (x-[2])/[3] ))*([4]+[5]*x+[6]*x*x)", 110., xMax); //polyFunc->SetParameters(-4.42749e+00,4.61212e+0,-6.21611e+01,1.13168e+02,2.14321e+00,1.04083e-03,4.89570e-07); TF1 *polyFunctot= new TF1("polyFunctot","([0]+[1]*TMath::Erf( (x-[2])/[3] ))*([4]+[5]*x+[6]*x*x)+[7]*TMath::Gaus(x,[8],[9])", 110., xMax); polyFunctot->SetParameters(-4.42749e+00,4.61212e+0,-6.21611e+01,1.13168e+02,2.14321e+00,1.04083e-03,4.89570e-07, 0.03, 200, 30); polyFunctot->SetParLimits(7,0,0.2); polyFunctot->SetParLimits(8,160,210); polyFunctot->SetParLimits(9,10,70); if (process!=ggH && process!=qqH) { polyFunctot->FixParameter(7,0); polyFunctot->FixParameter(8,0); polyFunctot->FixParameter(9,1); } // if (channel==fs4mu && sqrts==7) { // polyFunctot->SetParLimits(7,0,0.035); // polyFunctot->SetParLimits(8,160,210); // polyFunctot->SetParLimits(9,30,50); // } polyFunctot->SetLineColor(4); TString cname = "eff" + sprocess + ssqrts + "_" + schannel; TCanvas *ctot = new TCanvas(cname,cname); ctot->SetGrid(); TString outname = "sigFigs" + ssqrts +"/eff_" + sprocess + "_" + schannel + "_" + sjes; if (!useNewGGHPowheg) outname+="_oldPwg"; totgrEff->Fit(polyFunctot,"Rt"); TString xaxisText = "m_{" + schannel + "}"; totgrEff->GetXaxis()->SetTitle(xaxisText); TString yaxisText = "Efficiency, " + sprocess + ", " + schannel; totgrEff->GetYaxis()->SetTitle(yaxisText); totgrEff->SetMinimum(0.0); totgrEff->SetMaximum(1.0); if (process>=3) totgrEff->SetMaximum(0.0035); totgrEff->Draw("AP"); polyFunctot->Draw("sames"); ctot->Print(outname+".eps"); //ctot->Print(outname+".png"); // Does not work in batch? ctot->Print(outname+".pdf"); //ctot->Print(outname+".root"); ftot->cd(); totgrEff->Write("TotalEfficiency"); ftot->Close(); cout << endl; cout << "------- Parameters for " << sprocess << " " << schannel << " sqrts=" << sqrts << endl; cout << " a1 = " << polyFunctot->GetParameter(0) << endl; cout << " a2 = " << polyFunctot->GetParameter(1) << endl; cout << " a3 = " << polyFunctot->GetParameter(2) << endl; cout << " a4 = " << polyFunctot->GetParameter(3) << endl; cout << " b1 = " << polyFunctot->GetParameter(4) << endl; cout << " b2 = " << polyFunctot->GetParameter(5) << endl; cout << " b3 = " << polyFunctot->GetParameter(6) << endl; cout << " g1 = " << polyFunctot->GetParameter(7) << endl; cout << " g2 = " << polyFunctot->GetParameter(8) << endl; cout << " g3 = " << polyFunctot->GetParameter(9) << endl; cout << "---------------------------" << endl << endl; // Create card fragments using new powheg samples string oftotprocess; if (process==ggH) oftotprocess=""; else oftotprocess=sprocess; if (process==ggH) { oftot << endl; oftot << "## signal efficiency ##" << endl; } oftot << "signalEff " << oftotprocess << "a1 " << polyFunctot->GetParameter(0) << endl; oftot << "signalEff " << oftotprocess << "a2 " << polyFunctot->GetParameter(1) << endl; oftot << "signalEff " << oftotprocess << "a3 " << polyFunctot->GetParameter(2) << endl; oftot << "signalEff " << oftotprocess << "a4 " << polyFunctot->GetParameter(3) << endl; oftot << "signalEff " << oftotprocess << "b1 " << polyFunctot->GetParameter(4) << endl; oftot << "signalEff " << oftotprocess << "b2 " << polyFunctot->GetParameter(5) << endl; oftot << "signalEff " << oftotprocess << "b3 " << polyFunctot->GetParameter(6) << endl; oftot << "signalEff " << oftotprocess << "g1 " << polyFunctot->GetParameter(7) << endl; oftot << "signalEff " << oftotprocess << "g2 " << polyFunctot->GetParameter(8) << endl; oftot << "signalEff " << oftotprocess << "g3 " << polyFunctot->GetParameter(9) << endl; oftot << endl; oftot.close(); cname = "eff" + sprocess + ssqrts + "_" + schannel + "_ratio"; TCanvas *crat = new TCanvas(cname,cname); crat->SetGrid(); outname = "sigFigs" + ssqrts +"/eff_" + sprocess + "_" + schannel + "_" + sjes + "_ratio"; if (!useNewGGHPowheg) outname+="_oldPwg"; TF1 *ratiofit=0; if (process==ggH || process==qqH) ratiofit = new TF1("ratiofit","([0]+[1]*x+[2]*x*x)",110.,xMax); if (process==ZH || process==WH || process==ttH ) ratiofit = new TF1("ratiofit","([0]+[1]*x)",110.,xMax); ratgrEff->Fit(ratiofit,"Rt"); ratgrEff->GetXaxis()->SetTitle(xaxisText); TString yaxisratio = "Dijet ratio, " + sprocess + ", " + schannel; ratgrEff->GetYaxis()->SetTitle(yaxisratio); ratgrEff->SetMinimum(0.0); ratgrEff->SetMaximum(1.0); ratgrEff->Draw("AP"); crat->Print(outname+".eps"); //crat->Print(outname+".png"); // Does not work in batch? crat->Print(outname+".pdf"); //crat->Print(outname+".root"); fratio->cd(); ratgrEff->Write("Ratio"); fratio->Close(); cout << endl; cout << "------- Parameters for " << sprocess << " " << schannel << " sqrts=" << sqrts << endl; cout << " a1 = " << ratiofit->GetParameter(0) << endl; cout << " a2 = " << ratiofit->GetParameter(1) << endl; if (process==ggH || process==qqH) cout << " a3 = " << ratiofit->GetParameter(2) << endl; cout << "---------------------------" << endl << endl; if (process==ggH) { ofrat<<"## jet tagged/untagged ratio"<<endl; ofrat<<"jetYieldRatio "<<fitJys->GetParameter(0)<<"+("<<fitJys->GetParameter(1)<<"*@0)+("<<fitJys->GetParameter(2)<<"*@0*@0)+("<<fitJys->GetParameter(3)<<"*@0*@0*@0)"<< endl <<endl; ofrat << "## signal efficiency ratios ##" << endl; } ofrat << "signalEff tagged_" << sprocess << "_ratio " << ratiofit->GetParameter(0) << "+(" << ratiofit->GetParameter(1) << "*@0)"; if (process==ggH || process==qqH) ofrat << "+(" << ratiofit->GetParameter(2) << "*@0*@0)" << endl; else if (process==ZH || process==WH ) ofrat << endl; else if (process==ttH) ofrat << endl << endl; ofrat.close(); // deviations cout << "Deviations..." << endl; double maxResidual=0; for (int i = 0; i < nPoints; i++){ double eval = polyFunctot->Eval(masses[i]); double residual = (eval - totefficiencyVal[i]); maxResidual = max(maxResidual,fabs(residual)); if (verbose) cout << "For mass, " << masses[i] << ": measured value is " << totefficiencyVal[i] << " and difference from function is " << residual <<endl; } cout << "Largest residual= " << maxResidual << endl; delete fitJys; delete myCSW; delete polyFunctot; delete ratiofit; }
void offsetpT(int n1=1, int n2=25, float topX=15, float topY=30){ setStyle(); const double R = 0.4; int Rlabel = R*10; string run_name; float luminosity; cout << "Run: " << " lumi " << endl; cin >> run_name >> luminosity; //TFile* mcFile = TFile::Open(Form("SN_campaign2018_Run%s_R4.root",run_name.c_str())); //TFile* dataFile = TFile::Open( Form("/uscms_data/d3/broozbah/2018_sep/CMSSW_10_2_0/src/L1Res/OffsetTreeMaker/Run%s_newcert_R4.root",run_name.c_str()) ); //TFile* dataFile = TFile::Open( Form("/uscms_data/d3/broozbah/2018_sep_RunCv3/CMSSW_10_1_8/src/L1/OffsetTreeMaker/RunCV3_R4.root",run_name.c_str()) ); //TFile* dataFile = TFile::Open( Form("/uscms_data/d3/broozbah/2018_sep_RunBs/CMSSW_10_1_7/src/L1/OffsetTreeMaker/Run%s_R4.root",run_name.c_str()) ); //TFile* dataFile = TFile::Open( Form("/uscms_data/d3/broozbah/2018_sep_RunBV11/CMSSW_10_1_6/src/L1/OffsetTreeMaker/Run%s_upto317885_R4.root",run_name.c_str()) ); //TFile* dataFile = TFile::Open( Form("/uscms_data/d3/broozbah/2018_DataMC/CMSSW_10_1_6/src/L1/OffsetTreeMaker/root_files_R48/Run%s_R4.root",run_name.c_str()) ); //TFile* mcFile = TFile::Open(Form("SN_campaign2018_Run%s_R4.root",run_name.c_str())); //TFile* dataFile = TFile::Open( Form("/uscms_data/d3/broozbah/2018_DataMC/CMSSW_10_1_6/src/L1/OffsetTreeMaker/root_files_R48/Run%s_R4.root",run_name.c_str()) ); TFile* mcFile = TFile::Open("SN_2018_hl_R4.root"); TFile* dataFile = TFile::Open( "RunA_rereco_R4.root" ); TString var_type = "nPU"; // nPU, nPV bool isIndirect = true; // indirectRho bool rhoCentral = false; const int nPoints = n2-n1; int pf_choice; cout << "\n1) All\n2) Assoc. Charged Hadron\n3) Lepton\n4) Photon\n5) Neutral Hadron\n6) HF Tower Hadron\n" << "7) HF Tower EM Particle\n8) Charged Hadron Subtraction\n\n### Enter PF Particle type: "; cin >> pf_choice; cout << endl; TString pf_type = "all"; //default choice if (pf_choice == 2) pf_type = "chm"; else if (pf_choice == 3) pf_type = "lep"; else if (pf_choice == 4) pf_type = "ne"; else if (pf_choice == 5) pf_type = "nh"; else if (pf_choice == 6) pf_type = "hfh"; else if (pf_choice == 7) pf_type = "hfe"; else if (pf_choice == 8) pf_type = "chs"; vector<TH1D*> mcProfiles; vector<TH1D*> dataProfiles; vector<TString> ids = {"ne", "hfe", "nh", "hfh", "chu", "chm"}; for (int n=0; n<nPoints; n++){ if (pf_type.EqualTo("all")){ //add up all histograms TString hname = Form("p_offset_eta_%s%i_", var_type.Data(), n1+n) + ids[ids.size()-1]; mcProfiles.push_back( ((TProfile*) mcFile->FindObjectAny(hname))->ProjectionX( ids[ids.size()-1]+Form("%i_mc",n1+n) ) ); dataProfiles.push_back( ((TProfile*) dataFile->FindObjectAny(hname))->ProjectionX( ids[ids.size()-1]+Form("%i_data",n1+n) ) ); for (int i=0; i<ids.size()-1; i++){ hname = Form("p_offset_eta_%s%i_", var_type.Data(), n1+n) + ids[i]; mcProfiles.back()->Add( ((TProfile*) mcFile->FindObjectAny(hname))->ProjectionX( ids[i]+Form("%i_mc",n1+n) ) ); dataProfiles.back()->Add( ((TProfile*) dataFile->FindObjectAny(hname))->ProjectionX( ids[i]+Form("%i_data",n1+n) ) ); } } else if (pf_type.EqualTo("chs")){ //add up all histograms except chm TString hname = Form("p_offset_eta_%s%i_", var_type.Data(), n1+n) + ids[ids.size()-2]; mcProfiles.push_back( ((TProfile*) mcFile->FindObjectAny(hname))->ProjectionX( ids[ids.size()-2]+Form("%i_mc",n1+n) ) ); dataProfiles.push_back( ((TProfile*) dataFile->FindObjectAny(hname))->ProjectionX( ids[ids.size()-2]+Form("%i_data",n1+n) ) ); for (int i=0; i<ids.size()-2; i++){ hname = Form("p_offset_eta_%s%i_", var_type.Data(), n1+n) + ids[i]; mcProfiles.back()->Add( ((TProfile*) mcFile->FindObjectAny(hname))->ProjectionX( ids[i]+Form("%i_mc",n1+n) ) ); dataProfiles.back()->Add( ((TProfile*) dataFile->FindObjectAny(hname))->ProjectionX( ids[i]+Form("%i_data",n1+n) ) ); } } else{ TString hname = Form("p_offset_eta_%s%i_", var_type.Data(), n1+n) + pf_type; mcProfiles.push_back( ((TProfile*) mcFile->FindObjectAny(hname))->ProjectionX( pf_type+Form("%i_mc",n1+n) ) ); dataProfiles.push_back( ((TProfile*) dataFile->FindObjectAny(hname))->ProjectionX( pf_type+Form("%i_data",n1+n) ) ); } } TProfile* NPUtoRho_mc; TProfile* NPUtoRho_data; if (isIndirect){ TString hname; if (var_type.EqualTo("nPU")) { if (rhoCentral) hname = "p_rhoCentral0_nPU"; else hname = "p_rho_nPU"; } else { if (rhoCentral) hname = "p_rhoCentral0_nPV"; else hname = "p_rho_nPV"; } NPUtoRho_mc = (TProfile*) mcFile->Get(hname); NPUtoRho_data = (TProfile*) dataFile->Get(hname); if (NPUtoRho_data->GetXaxis()->GetBinWidth(1) == 0.5){ NPUtoRho_mc->Rebin(); NPUtoRho_data->Rebin(); } var_type = "indirectRho"; } ofstream writeMC("./plots/" + var_type + "/" + pf_type + Form("_%s/Fall18_17Sep2018%s_V1_MC_L1RC_AK%iPF", run_name.c_str(), run_name.c_str(), Rlabel) + pf_type + ".txt"); ofstream writeData("./plots/" + var_type + "/" + pf_type + Form("_%s/Fall18_17Sep2018%s_V1_DATA_L1RC_AK%iPF", run_name.c_str(), run_name.c_str(), Rlabel) + pf_type + ".txt"); TString header; // changes w.r.t previous versions: 1) TFormula had a bug and we modified accordingly 2) based on Mikko's calculation 1.519 changed to 2.00 if ( var_type.EqualTo("nPV") || var_type.EqualTo("nPU") ) //header = "{1\tJetEta\t3\tJetPt\tJetA\t" + var_type + "\t\tmax(0.0001,1-y*([0]+[1]*(z-1)+[2]*pow(z-1,2))/x)\tCorrection L1Offset}"; //header = "{1\tJetEta\t3\tJetPt\tJetA\t" + var_type + "\t\tmax(0.0001,1-(y/x)*([0]+[1]*(z-1.519)+[2]*pow(z-1.519,2)))\tCorrection L1Offset}"; header = "{1\tJetEta\t3\tJetPt\tJetA\t" + var_type + "\t\tmax(0.0001,1-(y/x)*([0]+[1]*(z-2.00)+[2]*pow(z-2.00,2)))\tCorrection L1Offset}"; else //header = "{1 JetEta 3 JetPt JetA Rho max(0.0001,1-y*([0]+[1]*(z-1.519)+[2]*pow(z-1.519,2))/x) Correction L1FastJet}"; //header = "{1 JetEta 3 JetPt JetA Rho max(0.0001,1-(y/x)*([0]+[1]*(z-1.519)+[2]*pow(z-1.519,2))) Correction L1FastJet}"; header = "{1 JetEta 3 JetPt JetA Rho max(0.0001,1-(y/x)*([0]+[1]*(z-2.00)+[2]*pow(z-2.00,2))) Correction L1FastJet}"; writeMC << header << endl; writeData << header << endl; TF1* f_mc = new TF1("f_mc", "1++x++x*x"); TF1* f_data = new TF1("f_data", "1++x++x*x"); f_mc->SetLineColor(2); f_mc->SetLineWidth(2); f_data->SetLineColor(1); f_data->SetLineWidth(2); for (int i=0; i<ETA_BINS; i++) { vector<double> mc_x, data_x, mc_y, data_y, mc_error, data_error; for (int n=0; n<nPoints; n++){ double mcX = n1+n+0.5; double dataX = n1+n+0.5; if (isIndirect){ mcX = NPUtoRho_mc->GetBinContent( NPUtoRho_mc->FindBin(mcX) ); dataX = NPUtoRho_data->GetBinContent( NPUtoRho_data->FindBin(dataX) ); } mc_x.push_back( mcX ); data_x.push_back( dataX ); mc_y.push_back( mcProfiles[n]->GetBinContent(i+1) ); data_y.push_back( dataProfiles[n]->GetBinContent(i+1) ); mc_error.push_back( 0.02 * mc_y.back() ); data_error.push_back( 0.02 * data_y.back() ); } TGraphErrors* mcGraph = new TGraphErrors(mc_x.size(), &mc_x[0], &mc_y[0], 0, &mc_error[0]); TGraphErrors* dataGraph = new TGraphErrors(data_x.size(), &data_x[0], &data_y[0], 0, &data_error[0]); mcGraph->Fit(f_mc, "Q"); dataGraph->Fit(f_data, "Q"); double area = M_PI*R*R; double x = fabs(etabins[0]) - 0.5*fabs(etabins[i]+etabins[i+1]); if (x < R) { double theta = 2*acos(x/R); double area_seg = 0.5*R*R*theta - x*R*sin(theta/2); area -= area_seg; } writeMC << etabins[i] << setw(8) << etabins[i+1] << setw(8) << 9 << setw(6) << 1 << setw(6) << 3500 << setw(6) << 0 << setw(6) << 10 << setw(6) << 0 << setw(6) << 200 << setw(15) << f_mc->GetParameter(0)/area << setw(15) << f_mc->GetParameter(1)/area << setw(15) << f_mc->GetParameter(2)/area << endl; writeData << etabins[i] << setw(8) << etabins[i+1] << setw(8) << 9 << setw(6) << 1 << setw(6) << 3500 << setw(6) << 0 << setw(6) << 10 << setw(6) << 0 << setw(6) << 200 << setw(15) << f_data->GetParameter(0)/area << setw(15) << f_data->GetParameter(1)/area << setw(15) << f_data->GetParameter(2)/area << endl; TString xTitle = ""; if ( var_type.EqualTo("nPV") ) xTitle = "N_{PV}"; else if ( var_type.EqualTo("nPU") ) xTitle = "#mu"; else if ( var_type.EqualTo("indirectRho") ) xTitle = "<#rho> (GeV)"; TCanvas* c = new TCanvas("c", "c", 600, 600); TH1F* h = new TH1F("h", "h", 100, 0, topX); h->GetXaxis()->SetTitle(xTitle); h->GetYaxis()->SetTitle("Offset p_{T} (GeV)"); h->GetYaxis()->SetTitleOffset(1.05); h->GetYaxis()->SetRangeUser(0, topY); h->Draw(); dataGraph->SetMarkerStyle(20); dataGraph->SetMarkerColor(1); dataGraph->Draw("Psame"); mcGraph->SetMarkerStyle(24); mcGraph->SetMarkerColor(2); mcGraph->SetLineColor(2); mcGraph->Draw("Psame"); TLatex text; text.SetNDC(); text.SetTextSize(0.04); if (pf_type.EqualTo("all")) text.DrawLatex(0.17, 0.96, Form("AK%i PF %4.3f #leq #eta #leq %4.3f", Rlabel, etabins[i], etabins[i+1]) ); else text.DrawLatex(0.17, 0.96, Form("AK%i PF%s %4.3f #leq #eta #leq %4.3f", Rlabel, pf_type.Data(), etabins[i], etabins[i+1]) ); text.DrawLatex(0.2, 0.88, "Data"); text.DrawLatex(0.2, 0.84, Form("#chi^{2}/ndof = %4.2f/%i", f_data->GetChisquare(), f_data->GetNDF() ) ); text.DrawLatex(0.2, 0.8, Form("p0 = %4.3f #pm %4.3f", f_data->GetParameter(0), f_data->GetParError(0) ) ); text.DrawLatex(0.2, 0.76, Form("p1 = %4.3f #pm %4.3f", f_data->GetParameter(1), f_data->GetParError(1) ) ); text.DrawLatex(0.2, 0.72, Form("p2 = %4.4f #pm %4.4f", f_data->GetParameter(2), f_data->GetParError(2) ) ); text.SetTextColor(2); text.DrawLatex(0.2, 0.64, "MC"); text.DrawLatex(0.2, 0.6, Form("#chi^{2}/ndof = %4.2f/%i", f_mc->GetChisquare(), f_mc->GetNDF() ) ); text.DrawLatex(0.2, 0.56, Form("p0 = %4.3f #pm %4.3f", f_mc->GetParameter(0), f_mc->GetParError(0) ) ); text.DrawLatex(0.2, 0.52, Form("p1 = %4.3f #pm %4.3f", f_mc->GetParameter(1), f_mc->GetParError(1) ) ); text.DrawLatex(0.2, 0.48, Form("p2 = %4.4f #pm %4.4f", f_mc->GetParameter(2), f_mc->GetParError(2) ) ); text.SetTextSize(0.035); text.SetTextFont(42); text.SetTextColor(1); text.DrawLatex( 0.8, 0.96, "#sqrt{s} = 13 TeV" ); cout << f_data->GetChisquare() / f_data->GetNDF() << "\t" << f_mc->GetChisquare() / f_mc->GetNDF() << endl; c->Print("./plots/" + var_type + "/" + pf_type + Form("_%s/", run_name.c_str()) + pf_type + "_pT_" + var_type + Form("_eta%4.3f", etabins[i]) + ".pdf"); delete h; delete c; } writeMC.close(); writeData.close(); }
void plotvn(){ gStyle->SetOptStat(kFALSE); int icent = 0; int n = 2; int color[nsub] = {1,2,4,5,7,8,2,4}; int style[12] = {20,21,24,25,26,27,29,30,31,32,33,34}; TGraphErrors *gr[nsub][3][2]; TGraphErrors *grraw[nsub][3][2]; TString CNTEP, dire; for(int isub=0;isub<nsub;isub++){ for(int idire=0;idire<3;idire++){ for(int iCNTEP=0;iCNTEP<1;iCNTEP++){ if(iCNTEP==0) CNTEP = "NoUseCNTEP"; if(iCNTEP==1) CNTEP = "UseCNTEP"; if(idire==0) dire = ""; if(idire==1) dire = "_east"; if(idire==2) dire = "_west"; TString str = choosesub(isub); if(str=="ABORT") continue; gr[isub][idire][iCNTEP] = new TGraphErrors(Form("Result/%s/v%d_00_%d%s_%s.dat",CNTEP.Data(),n,icent,dire.Data(),str.Data()),"%lg %lg %lg"); grraw[isub][idire][iCNTEP] = new TGraphErrors(Form("Result/%s/v%draw_00_%d%s_%s.dat",CNTEP.Data(),n,icent,dire.Data(),str.Data()),"%lg %lg %lg"); SetStyle(*gr[isub][idire][iCNTEP], 1.2, color[idire+3*iCNTEP],style[isub]); SetStyle(*grraw[isub][idire][iCNTEP], 1.2, color[idire+3*iCNTEP],style[isub]); } } } TGraphErrors *grv2 = new TGraphErrors("Result/v2_pAu_0_5_asys.dat","%lg %lg %lg"); //p+Au TGraphErrors *gr3 = new TGraphErrors("../../Ridge3sub/v2_cent0.dat"); TGraphErrors *gr3sub = new TGraphErrors("../../Ridge3sub/v2_cent0_scale1.dat"); TGraphErrors *grpc3 = new TGraphErrors("../usephiweightpc3/Result/NoUseCNTEP/v2_00_2_FVTX2p4p1LS.dat","%lg %lg %lg"); TGraphErrors *grAngle36 = new TGraphErrors("../usephiweight/Result/NoUseCNTEP/v2_00_0_FVTX2p4p1LS.dat","%lg %lg %lg"); TGraphErrors *grLow = new TGraphErrors("../usephiweightLowLumi/Result/NoUseCNTEP/v2_00_0_FVTX2p4p1LS.dat","%lg %lg %lg"); TGraphErrors *grHigh = new TGraphErrors("../usephiweightHighLumi/Result/NoUseCNTEP/v2_00_0_FVTX2p4p1LS.dat","%lg %lg %lg"); TH1F* h = new TH1F("h","",50,0,5); h->GetXaxis()->SetRangeUser(0,3.2); /* TCanvas *c1 = new TCanvas("c1","c1",800,450); iCNTEP = 0; idire = 0; c1->Divide(2); c1->cd(1); h->SetMinimum(0); h->SetMaximum(0.3); h->GetXaxis()->SetRangeUser(0,3.2); //SetTitle(h,"","p_{T}","v_{2}^{raw}"); SetTitle(h,"","p_{T}","v_{2}"); h->DrawCopy(); TLegend *leg = new TLegend(0.2,0.7,0.5,0.9); leg->SetFillColor(0); leg->SetBorderSize(0); for(int ilay = 0;ilay<4;ilay++){ leg->AddEntry(gr[ilay+8][idire][iCNTEP],Form("FVTX layer %d",ilay)); gr[ilay+8][idire][iCNTEP]->Draw("Psame"); } gr[6][0][1]->Draw("Psame"); leg->AddEntry(gr[6][idire][iCNTEP],Form("FVTX -3.0<#eta<-1.0")); leg->Draw("Psame"); c1->cd(2); h->SetMinimum(0.8); h->SetMaximum(1.2); SetTitle(h,"","p_{T}","v_{2} ratio"); h->DrawCopy(); for(int ilay = 0;ilay<4;ilay++){ TGraphErrors *grr = (TGraphErrors*)DivideTwoGraphs(gr[ilay+8][idire][iCNTEP],gr[6][idire][iCNTEP]); SetStyle(*grr,1.2,color[idire+3*iCNTEP],style[ilay+8]); grr->Draw("Psame"); } */ TCanvas *c2 = new TCanvas("c2","c2",800,450); iCNTEP = 0; idire = 0; c2->Divide(2); c2->cd(1); h->SetMinimum(0); h->SetMaximum(0.3); SetTitle(*h,"p_{T}","v_{2}",""); h->DrawCopy(); TLegend *leg = new TLegend(0.2,0.7,0.5,0.9); leg->SetFillColor(0); leg->SetBorderSize(0); leg->SetTextSize(0.05); SetStyle(*gr[4][idire][iCNTEP], 1.2, 2,style[2]); SetStyle(*gr[5][idire][iCNTEP], 1.2, 4,style[4]); SetStyle(*gr3, 1.2, 1,style[1]); SetStyle(*gr3sub, 1.2, 1,style[3]); SetStyle(*grv2, 1.2, 1,style[2]); gr[4][idire][iCNTEP]->Draw("Psame"); gr[5][idire][iCNTEP]->Draw("Psame"); //grv2->Draw("Psame"); //gr3->Draw("Psame"); //gr3sub->Draw("Psame"); leg->AddEntry(gr[4][idire][iCNTEP],Form("BBCs")); leg->AddEntry(gr[5][idire][iCNTEP],Form("FVTXs -3.0<#eta<-1.0")); //leg->AddEntry(gr[5][idire][iCNTEP],Form("p+Al event plane")); //leg->AddEntry(gr3,Form("p+Al 3-sub event method")); //leg->AddEntry(grv2,Form("PPG191 p+Au v2")); //leg->AddEntry(gr3sub,Form("3-sub non-flow PP subtracted")); leg->Draw("Psame"); c2->cd(2); h->SetMinimum(0.); h->SetMaximum(2); SetTitle(*h,"p_{T}","v_{2} ratio BBCs/FVTXs",""); h->DrawCopy(); TGraphErrors *grr = (TGraphErrors*)DivideTwoGraphs(gr[4][idire][iCNTEP],gr[5][idire][iCNTEP]); SetStyle(*grr,1.2,color[idire+3*iCNTEP],style[2]); grr->Fit("pol0"); grr->GetFunction("pol0")->SetLineColor(1); grr->Draw("Psame"); c2->Print(Form("FVTXvsBBCv%d.png",n)); TCanvas *c3 = new TCanvas("c3","c3",800,450); idire = 0; isub=7; c3->Divide(2); c3->cd(1); h->SetMinimum(0); h->SetMaximum(0.3); SetTitle(*h,"p_{T}","v_{2}",""); h->DrawCopy(); TLegend *leg = new TLegend(0.2,0.7,0.5,0.88); leg->SetFillColor(0); leg->SetBorderSize(0); leg->SetTextSize(0.05); SetStyle(*grLow, 1.2, 2,style[2]); SetStyle(*grHigh, 1.2, 4,style[4]); grLow->Draw("Psame"); grHigh->Draw("Psame"); gr[isub][idire][0]->Draw("Psame"); leg->AddEntry(gr[isub][idire][0],Form("Inclusive")); leg->AddEntry(grLow,Form("Low lumi runs < 500kHz"),"P"); leg->AddEntry(grHigh,Form("High lumi runs > 500kHz"),"P"); leg->Draw("Psame"); c3->cd(2); h->SetMinimum(0.); h->SetMaximum(2.); SetTitle(*h,"p_{T}","v_{2} ratio over Total",""); h->DrawCopy(); TGraphErrors *grr = (TGraphErrors*)DivideTwoGraphs(grLow,gr[isub][idire][0]); grr->Fit("pol0"); grr->GetFunction("pol0")->SetLineColor(2); grr->Draw("Psame"); TGraphErrors *grr = (TGraphErrors*)DivideTwoGraphs(grHigh,gr[isub][idire][0]); grr->Fit("pol0"); grr->GetFunction("pol0")->SetLineColor(4); grr->Draw("Psame"); c3->Print(Form("v%dFVTXs%dLH.png",n,isub)); TCanvas *c4 = new TCanvas("c4","c4",800,450); isub=3; iCNTEP = 0; c4->Divide(2); c4->cd(1); h->SetMinimum(0); h->SetMaximum(0.3); SetTitle(*h,"p_{T} (GeV/c)","v_{2}",""); h->DrawCopy(); TLegend *leg = new TLegend(0.2,0.7,0.5,0.88); leg->SetFillColor(0); leg->SetBorderSize(0); leg->SetTextSize(0.04); gr[isub][0][iCNTEP]->Draw("Psame"); gr[isub][1][iCNTEP]->Draw("Psame"); gr[isub][2][iCNTEP]->Draw("Psame"); if(isub==5) leg->AddEntry(gr[isub][0][iCNTEP],Form("FVTXs -3.0<#eta<-1.0")); else if(isub<4) leg->AddEntry(gr[isub][0][iCNTEP],Form("FVTXs Layer %d -3.0<#eta<-1.0", isub+1)); else if(isub==6) leg->AddEntry(gr[isub][0][iCNTEP],Form("FVTXs Layer 2+4")); else if(isub==7) leg->AddEntry(gr[isub][0][iCNTEP],Form("FVTXs Layer 1+2+4")); leg->AddEntry(gr[isub][0][iCNTEP],Form("inclusive"),"P"); leg->AddEntry(gr[isub][1][iCNTEP],Form("East"),"P"); leg->AddEntry(gr[isub][2][iCNTEP],Form("West"),"P"); leg->Draw("Psame"); c4->cd(2); h->SetMinimum(0); h->SetMaximum(2); SetTitle(*h,"p_{T} (GeV/c)","v_{2} ratio",""); h->DrawCopy(); TGraphErrors *grr = (TGraphErrors*)DivideTwoGraphs(gr[isub][1][iCNTEP],gr[isub][0][iCNTEP]); SetStyle(*grr,1.2,color[1+3*iCNTEP],style[isub]); grr->Fit("pol0"); grr->GetFunction("pol0")->SetLineColor(2); grr->Draw("Psame"); TGraphErrors *grr = (TGraphErrors*)DivideTwoGraphs(gr[isub][2][iCNTEP],gr[isub][0][iCNTEP]); SetStyle(*grr,1.2,color[2+3*iCNTEP],style[isub]); grr->Fit("pol0"); grr->GetFunction("pol0")->SetLineColor(4); grr->Draw("Psame"); c4->Print(Form("v%dFVTXs%dEW.png",n,isub)); TCanvas *c5 = new TCanvas("c5","c5",800,450); isub=4; iCNTEP = 0; c5->Divide(2); c5->cd(1); h->SetMinimum(0); h->SetMaximum(0.3); SetTitle(*h,"p_{T}","v_{2}",""); h->DrawCopy(); TLegend *leg = new TLegend(0.2,0.7,0.5,0.9); leg->SetTextSize(0.05); leg->SetFillColor(0); leg->SetBorderSize(0); gr[isub][0][iCNTEP]->Draw("Psame"); gr[isub][1][iCNTEP]->Draw("Psame"); gr[isub][2][iCNTEP]->Draw("Psame"); leg->AddEntry(gr[isub][0][iCNTEP],Form("Using BBC event plane")); leg->AddEntry(gr[isub][0][iCNTEP],Form("inclusive"),"P"); leg->AddEntry(gr[isub][1][iCNTEP],Form("East"),"P"); leg->AddEntry(gr[isub][2][iCNTEP],Form("West"),"P"); leg->Draw("Psame"); c5->cd(2); h->SetMinimum(0); h->SetMaximum(2.); SetTitle(*h,"p_{T}","v_{2} ratio",""); h->DrawCopy(); TGraphErrors *grr = (TGraphErrors*)DivideTwoGraphs(gr[isub][1][iCNTEP],gr[isub][0][iCNTEP]); SetStyle(*grr,1.2,color[1+3*iCNTEP],style[isub]); grr->Fit("pol0"); grr->GetFunction("pol0")->SetLineColor(2); grr->Draw("Psame"); TGraphErrors *grr = (TGraphErrors*)DivideTwoGraphs(gr[isub][2][iCNTEP],gr[isub][0][iCNTEP]); SetStyle(*grr,1.2,color[2+3*iCNTEP],style[isub]); grr->Fit("pol0"); grr->GetFunction("pol0")->SetLineColor(4); grr->Draw("Psame"); c5->Print(Form("v%dBBCs%dEW.png",n,isub)); TCanvas *c6 = new TCanvas("c6","c6",800,450); iCNTEP = 0; c6->Divide(2); c6->cd(1); h->SetMinimum(0); h->SetMaximum(0.3); SetTitle(*h,"p_{T}","v_{2}",""); h->DrawCopy(); TLegend *leg = new TLegend(0.5,0.65,0.8,0.85); leg->SetFillColor(0); leg->SetBorderSize(0); leg->SetTextSize(0.04); SetStyle(*gr[0][0][iCNTEP], 1.2, color[0],style[0]); SetStyle(*gr[1][0][iCNTEP], 1.2, color[1],style[1]); SetStyle(*gr[2][0][iCNTEP], 1.2, color[2],style[2]); SetStyle(*gr[3][0][iCNTEP], 1.2, color[4],style[4]); SetStyle(*gr[5][0][iCNTEP], 1.2, color[5],style[5]); gr[0][0][iCNTEP]->Draw("Psame"); gr[1][0][iCNTEP]->Draw("Psame"); gr[2][0][iCNTEP]->Draw("Psame"); gr[3][0][iCNTEP]->Draw("Psame"); gr[5][0][iCNTEP]->Draw("Psame"); leg->AddEntry(gr[0][0][iCNTEP],Form("FVTX 1LS"),"P"); leg->AddEntry(gr[1][0][iCNTEP],Form("FVTX 2LS"),"P"); leg->AddEntry(gr[2][0][iCNTEP],Form("FVTX 3LS"),"P"); leg->AddEntry(gr[3][0][iCNTEP],Form("FVTX 4LS"),"P"); leg->AddEntry(gr[5][0][iCNTEP],Form("FVTX All"),"P"); leg->Draw("same"); c6->cd(2); h->SetMinimum(0.5); h->SetMaximum(1.5); SetTitle(*h,"p_{T}","v_{2} ratio",""); h->DrawCopy(); TGraphErrors *grr = (TGraphErrors *)DivideTwoGraphs(gr[0][0][iCNTEP],gr[5][0][iCNTEP]); grr->Draw("Psame"); TGraphErrors *grr = (TGraphErrors *)DivideTwoGraphs(gr[1][0][iCNTEP],gr[5][0][iCNTEP]); grr->Draw("Psame"); TGraphErrors *grr = (TGraphErrors *)DivideTwoGraphs(gr[2][0][iCNTEP],gr[5][0][iCNTEP]); grr->Draw("Psame"); TGraphErrors *grr = (TGraphErrors *)DivideTwoGraphs(gr[3][0][iCNTEP],gr[5][0][iCNTEP]); grr->Draw("Psame"); c6->Print(Form("FVTXeachlayerv%d.png",n)); TCanvas *c7 = new TCanvas("c7","c7",800,450); iCNTEP = 0; c7->Divide(2); c7->cd(1); h->SetMinimum(0); h->SetMaximum(0.3); SetTitle(*h,"p_{T}","v_{2}",""); h->DrawCopy(); TLegend *leg = new TLegend(0.5,0.75,0.8,0.85); leg->SetFillColor(0); leg->SetBorderSize(0); leg->SetTextSize(0.05); SetStyle(*gr[5][0][iCNTEP], 1.2, color[5],style[0]); SetStyle(*gr[6][0][iCNTEP], 1.2, color[6],style[1]); SetStyle(*gr[7][0][iCNTEP], 1.2, color[7],style[2]); gr[5][0][iCNTEP]->Draw("Psame"); gr[6][0][iCNTEP]->Draw("Psame"); gr[7][0][iCNTEP]->Draw("Psame"); leg->AddEntry(gr[5][0][iCNTEP],Form("FVTX All"),"P"); leg->AddEntry(gr[6][0][iCNTEP],Form("FVTX 2+4 layer"),"P"); leg->AddEntry(gr[7][0][iCNTEP],Form("FVTX 1+2+4 layer"),"P"); leg->Draw("same"); c7->cd(2); h->SetMinimum(0.5); h->SetMaximum(1.5); SetTitle(*h,"p_{T}","v_{2} ratio",""); h->DrawCopy(); TGraphErrors *grr = (TGraphErrors *)DivideTwoGraphs(gr[5][0][iCNTEP],gr[5][0][iCNTEP]); SetStyle(*grr,1.2,color[5],style[isub]); grr->Draw("Psame"); TGraphErrors *grr = (TGraphErrors *)DivideTwoGraphs(gr[6][0][iCNTEP],gr[5][0][iCNTEP]); SetStyle(*grr,1.2,color[6],style[isub]); grr->Draw("Psame"); TGraphErrors *grr = (TGraphErrors *)DivideTwoGraphs(gr[7][0][iCNTEP],gr[5][0][iCNTEP]); SetStyle(*grr,1.2,color[7],style[isub]); grr->Draw("Psame"); c7->Print(Form("FVTXlayerCombv%d.png",n)); TCanvas *c8 = new TCanvas("c8","c8",800,450); idire = 0; isub=7; c8->Divide(2); c8->cd(1); h->SetMinimum(0); h->SetMaximum(0.3); SetTitle(*h,"p_{T}","v_{2}",""); h->DrawCopy(); TLegend *leg = new TLegend(0.2,0.7,0.5,0.88); leg->SetFillColor(0); leg->SetBorderSize(0); leg->SetTextSize(0.05); SetStyle(*grAngle36, 1.2, 2,style[2]); gr[isub][idire][0]->Draw("Psame"); grAngle36->Draw("Psame"); leg->AddEntry(gr[isub][idire][0],Form("Angle=2.3mrad")); leg->AddEntry(grAngle36,Form("Angle=3.6mrad")); leg->Draw("Psame"); c8->cd(2); h->SetMinimum(0.); h->SetMaximum(2.); SetTitle(*h,"p_{T}","v_{2} ratio Angle=2.3mrad/Angle=2.6mrad",""); h->DrawCopy(); TGraphErrors *grr = (TGraphErrors*)DivideTwoGraphs(gr[isub][idire][0],grAngle36); grr->Fit("pol0"); grr->GetFunction("pol0")->SetLineColor(4); grr->Draw("Psame"); c8->Print(Form("v%dFVTXs%dAngle.png",n,isub)); }
void all(int channels=0, int categ=-1, int sample=2012 /*,bool doSfLepton=true*/){ double bwSigma[40]; int mass[40]; int id[40]; double xLow[40]; double xHigh[40]; int maxMassBin; float masses[1] = {125}; for(int i=0;i<1;++i) { mass[i] = masses[i]; id[i]=masses[i]; xLow[i] = 105.; // getFitEdge(masses[i],width,true); xHigh[i] = 140.; // getFitEdge(masses[i],width,false); //cout << "For mass = " << masses[i] << " width = " << width << "; => Fit Range = [" << xLow[i] << "," << xHigh[i] << "]" << endl; bwSigma[i] = 0.004; } maxMassBin = 1; // 29; // ----------------------- double massV[40],massE[40]; for(int i=0; i<maxMassBin;++i){ massV[i]=mass[i]; massE[i]=0; } double A1Val[40],A1Err[40]; double A2Val[40],A2Err[40]; double a1Val[40],a1Err[40]; double a2Val[40],a2Err[40]; double n1Val[40],n1Err[40]; double n2Val[40],n2Err[40]; double meanCBVal[40],meanCBErr[40]; double sigmaCBVal[40],sigmaCBErr[40]; double meanBWVal[40],meanBWErr[40]; double covQualVal[40]; double fitValues[10]; double fitErrors[10]; double covQual[1]; for(int i=0; i<maxMassBin;++i){ fitSignalShapeW(mass[i],id[i],channels,categ, sample,/* 10.,doSfLepton,*/xLow[i],xHigh[i],bwSigma[i], fitValues,fitErrors,covQual); cout << "a1 value,error: " << fitValues[0] << " , " << fitErrors[0] << endl; a1Val[i]=fitValues[0]; a1Err[i]=fitErrors[0]; cout << "a2 value,error: " << fitValues[1] << " , " << fitErrors[1] << endl; a2Val[i]=fitValues[1]; a2Err[i]=fitErrors[1]; cout << "n1 value,error: " << fitValues[4] << " , " << fitErrors[4] << endl; n1Val[i]=fitValues[4]; n1Err[i]=fitErrors[4]; cout << "n2 value,error: " << fitValues[5] << " , " << fitErrors[5] << endl; n2Val[i]=fitValues[5]; n2Err[i]=fitErrors[5]; cout << "meanCB value,error: " << fitValues[2] << " , " << fitErrors[2] << endl; meanCBVal[i]=fitValues[2]; meanCBErr[i]=fitErrors[2]; cout << "sigmaCB value,error: " << fitValues[6] << " , " << fitErrors[6] << endl; sigmaCBVal[i]=fitValues[6]; sigmaCBErr[i]=fitErrors[6]; cout << "meanBW value,error: " << fitValues[3] << " , " << fitErrors[3] << endl; meanBWVal[i]=fitValues[3]; meanBWErr[i]=fitErrors[3]; cout << "A1 value,error: " << fitValues[7] << " , " << fitErrors[7] << endl; A1Val[i]=fitValues[7]; A1Err[i]=fitErrors[7]; cout << "A2 value,error: " << fitValues[8] << " , " << fitErrors[8] << endl; A2Val[i]=fitValues[8]; A2Err[i]=fitErrors[8]; cout << "covQual of the fit: " << covQual[0] << endl; covQualVal[i] = covQual[0]; } stringstream namefile; namefile << "parameters_channel" << channels<< categ << ".root"; TFile *resultfile = TFile::Open(namefile.str().c_str(),"RECREATE"); TGraphErrors* gA1 = new TGraphErrors(maxMassBin,massV,a1Val,massE,a1Err); TGraphErrors* gA2 = new TGraphErrors(maxMassBin,massV,a2Val,massE,a2Err); TGraphErrors* gN1 = new TGraphErrors(maxMassBin,massV,n1Val,massE,n1Err); TGraphErrors* gN2 = new TGraphErrors(maxMassBin,massV,n2Val,massE,n2Err); TGraphErrors* gMeanCB = new TGraphErrors(maxMassBin,massV,meanCBVal,massE,meanCBErr); TGraphErrors* gSigmaCB = new TGraphErrors(maxMassBin,massV,sigmaCBVal,massE,sigmaCBErr); TGraphErrors* gMeanBW = new TGraphErrors(maxMassBin,massV,meanBWVal,massE,meanBWErr); TGraphErrors* gAA1 = new TGraphErrors(maxMassBin,massV,A1Val,massE,A1Err); TGraphErrors* gAA2 = new TGraphErrors(maxMassBin,massV,A2Val,massE,A2Err); TGraph* gCovQual = new TGraph(maxMassBin,massV,covQualVal); gA1->SetName("gA1"); gA1->SetMarkerStyle(20); gA1->SetMarkerSize(1); gA2->SetName("gA2"); gA2->SetMarkerStyle(20); gA2->SetMarkerSize(1); gN1->SetName("gN1"); gN1->SetMarkerStyle(20); gN1->SetMarkerSize(1); gN2->SetName("gN2"); gN2->SetMarkerStyle(20); gN2->SetMarkerSize(1); gMeanCB->SetName("gMeanCB"); gMeanCB->SetMarkerStyle(20); gMeanCB->SetMarkerSize(1); gSigmaCB->SetName("gSigmaCB"); gSigmaCB->SetMarkerStyle(20); gSigmaCB->SetMarkerSize(1); gMeanBW->SetName("gMeanBW"); gMeanBW->SetMarkerStyle(20); gMeanBW->SetMarkerSize(1); gAA1->SetName("gAA1"); gAA1->SetMarkerStyle(20); gAA1->SetMarkerSize(1); gAA2->SetName("gAA2"); gAA2->SetMarkerStyle(20); gAA2->SetMarkerSize(1); gCovQual->SetName("gCovQual"); gCovQual->SetMarkerStyle(20); gCovQual->SetMarkerSize(1); gA1->SetTitle(""); gA1->GetXaxis()->SetTitle("mass (GeV)"); gA1->GetYaxis()->SetTitle("CB a-parameter"); gA2->SetTitle(""); gA2->GetXaxis()->SetTitle("mass (GeV)"); gA2->GetYaxis()->SetTitle("CB a-parameter"); gN1->SetTitle(""); gN1->GetXaxis()->SetTitle("mass (GeV)"); gN1->GetYaxis()->SetTitle("CB n-parameter"); gN2->SetTitle(""); gN2->GetXaxis()->SetTitle("mass (GeV)"); gN2->GetYaxis()->SetTitle("CB n-parameter"); gMeanCB->SetTitle(""); gMeanCB->GetXaxis()->SetTitle("mass (GeV)"); gMeanCB->GetYaxis()->SetTitle("CB mean"); gSigmaCB->SetTitle(""); gSigmaCB->GetXaxis()->SetTitle("mass (GeV)"); gSigmaCB->GetYaxis()->SetTitle("CB sigma"); gMeanBW->SetTitle(""); gMeanBW->GetXaxis()->SetTitle("mass (GeV)"); gMeanBW->GetYaxis()->SetTitle("BW mean"); gAA1->SetTitle(""); gAA1->GetXaxis()->SetTitle("mass (GeV)"); gAA1->GetYaxis()->SetTitle("Chebyshev a1-parameter"); gAA2->SetTitle(""); gAA2->GetXaxis()->SetTitle("mass (GeV)"); gAA2->GetYaxis()->SetTitle("Chebyshev a2-parameter"); gCovQual->SetTitle(""); gCovQual->GetXaxis()->SetTitle("mass (GeV)"); gCovQual->GetYaxis()->SetTitle("cov. matrix qual."); resultfile->cd(); gA1->Fit("pol0"); gA1->Draw("Ap"); gA1->Write(); gA2->Fit("pol0"); gA2->Draw("Ap"); gA2->Write(); gN1->Fit("pol1"); gN1->Draw("Ap"); gN1->Write(); gN2->Fit("pol1"); gN2->Draw("Ap"); gN2->Write(); gMeanCB->Fit("pol1"); gMeanCB->Draw("Ap"); gMeanCB->Write(); gSigmaCB->Fit("pol1"); gSigmaCB->Draw("Ap"); gSigmaCB->Write(); gAA1->Fit("pol0"); gAA1->Draw("Ap"); gAA1->Write(); gAA2->Fit("pol0"); gAA2->Draw("Ap"); gAA2->Write(); gCovQual->Write(); resultfile->Close(); }
void histoLoader_new(char* arg){ //Take the arguments and save them into respective strings std::string infileName, outfileName; std::string inF, outF; std::string inPrefix, outPrefix; std::string layers; std::istringstream stm(arg); inPrefix = "/home/p180f/Do_Jo_Ol_Ma/Analysis/MainProcedure/testMain/analysisRoot/"; outPrefix = "/home/p180f/Do_Jo_Ol_Ma/Analysis/MainProcedure/testMain/moliRoot/"; outF = "moli_all.root"; outfileName = outPrefix + outF; Double_t p0 = 248.5; Double_t p1 = 222; Double_t p2 = 275; int i = 0; Double_t thetaRMS[4]; while(true){ if( std::getline(stm, layers, ' ') ){ inF = "errorAnalysis_" + layers + "layers.root"; infileName = inPrefix + inF; TFile *inFile = new TFile(infileName.c_str()); TF1 *func = (TF1*)inFile->Get("gausFuncCuts"); Double_t RMS1; Double_t RMS2; RMS1 = TMath::Abs(func->GetParameter("Sigma1")); RMS2 = TMath::Abs(func->GetParameter("Sigma2")); std::cout << "RMS1_" << i << " = " << RMS1 << std::endl; std::cout << "RMS2_" << i << " = " << RMS2 << std::endl; if( RMS1 > RMS2 ){ thetaRMS[i] = RMS2; } else thetaRMS[i] = RMS1; inFile->Close(); } else break; i++; } TFile *outFile = new TFile(outfileName.c_str(), "RECREATE"); Double_t x_data[4] = {2.54 / 4, 2.54 / 2, 2.54*3/4, 2.54}; Double_t xerr[4] = {0.005, 0.005, 0.005, 0.005}; Double_t yerr[4] = {0.197, 0.272, 0.351, 0.136}; Double_t x0[20] = {0}; Double_t y0[20] = {0}; Double_t x1[20] = {0}; Double_t y1[20] = {0}; Double_t x2[20] = {0}; Double_t y2[20] = {0}; int j=1; for (Double_t h=0.15; j<20; j++) { x0[j] = h; y0[j] = moliFunc(x0[j], p0); h+=0.15; std::cout << "x0[" << j << "] = " << x0[j] << std::endl; std::cout << "y0[" << j << "] = " << y0[j] << std::endl; } int k=1; for (Double_t h=0.15; k<20; k++) { x1[k] = h; y1[k] = moliFunc(x1[k], p1); h+=0.15; std::cout << "x1[" << k << "] = " << x1[k] << std::endl; std::cout << "y1[" << k << "] = " << y1[k] << std::endl; } int l=1; for (Double_t h=0.15; l<20; l++) { x2[l] = h; y2[l] = moliFunc(x2[l], p2); h+=0.15; std::cout << "x2[" << l << "] = " << x2[l] << std::endl; std::cout << "y2[" << l << "] = " << y2[l] << std::endl; } TGraph *moliGraph0 = new TGraph(20, x0, y0); TGraph *moliGraph1 = new TGraph(20, x1, y1); TGraph *moliGraph2 = new TGraph(20, x2, y2); TGraphErrors *dataGraph = new TGraphErrors(4, x_data, thetaRMS, xerr, yerr); TF1 *moliFit = new TF1("moliFit", moliFunc_Fit, 0, 10, 1); moliFit->SetLineColor(6); moliFit->SetLineWidth(2); moliFit->SetParameters(0, 13.6); moliFit->SetParNames("Constant"); moliFit->SetParLimits(0, 0, 30); // moliFit->SetParLimits(1, 0, 0.25); dataGraph->Fit("moliFit"); std::cout << "thetaRMS[0] = " << thetaRMS[0] << std::endl; std::cout << "thetaRMS[1] = " << thetaRMS[1] << std::endl; std::cout << "thetaRMS[2] = " << thetaRMS[2] << std::endl; std::cout << "thetaRMS[3] = " << thetaRMS[3] << std::endl; //std::cout << "thetaRMS[4] = " << thetaRMS[4] << std::endl; moliGraph0->SetLineColor(2); moliGraph0->SetLineWidth(1.5); moliGraph1->SetLineColor(8); moliGraph1->SetLineWidth(1.5); moliGraph2->SetLineColor(9); moliGraph2->SetLineWidth(1.5); dataGraph ->SetMarkerStyle(22); moliGraph0->Draw("AC"); moliGraph1->Draw("PC"); moliGraph2->Draw("PC"); dataGraph->Draw("P"); //moliFit->Draw("*"); TLegend *leg = new TLegend(0.1, 0.7, 0.48, 0.9); leg->SetHeader("Legend"); // gStyle->SetLegendFillColor(0); leg->AddEntry(moliGraph1, "Moliere Distribution for p = 222 MeV/c", "LP"); leg->AddEntry(moliGraph0, "Moliere Distribution for p = 248.5 MeV/c", "LP"); leg->AddEntry(moliGraph2, "Moliere Distribution for p = 275 MeV/c", "LP"); leg->AddEntry(dataGraph, "The angular RMS for varying Pb thicknesses", "LP"); leg->AddEntry(moliFit, "The angular RMS data fit to the Moliere Distribution", "LP"); leg->Draw(); moliGraph0->Write(); moliGraph1->Write(); moliGraph2->Write(); moliFit->Write(); dataGraph->Write(); outFile->Close(); }
void ratiofit_vbf() { const Int_t nbins = 11; double Bins[12] = {130.,200.,300.,400.,500.,600.,700.,800.,900.,1000.,1250.,1500.}; TString OutDir = "vbf_plots_pol1Func"; //TString OutDir = "vbf_plots_OneoversqrtXFunc"; //TString OutDir = "vbf_plots_OneoverXFunc"; gSystem->mkdir(OutDir); TFile *fname; fname = new TFile("mWW_sf_reweighted/scaleFactors.root"); char tmpName[50]; char a0Name[50]; char a1Name[50]; char histName[50]; char mWWrange[50]; //Histograms TH1D* h1_powheg_phantom[5]; TString pol1Func("pol1"); //TString pol2Func("pol2"); //TString ExpFunc("ExpFunc"); //TString sqrtFunc("sqrtFunc"); //TString OneoverXFunc("OneoverXFunc"); //TString OneoversqrtXFunc("OneoversqrtXFunc"); TFitResultPtr fitres; TF1 *fit_func = new TF1("fit_func",pol1Func,130,1620); //TFitResultPtr fitres; TF1 *fit_func = new TF1("fit_func",pol2Func,0,1500); //TFitResultPtr fitres; TF1 *fit_func = new TF1("fit_func",ExpFunc,130,1500,3); //TFitResultPtr fitres; TF1 *fit_func = new TF1("fit_func",sqrtFunc,130,1500,3); //TF1 *fit_func = new TF1("fit_func",OneoverXFunc,130,1620,2); //TF1 *fit_func = new TF1("fit_func",OneoversqrtXFunc,130,1620,2); TGraphErrors *grRatio = 0; Double_t xval[nbins]; Double_t xerr[nbins]; Double_t rMean[nbins]; Double_t rMeanErr[nbins]; TCanvas *c = MakeCanvas("c","c",900,900); TGraphErrors *errBand = new TGraphErrors(nbins+2); char fitparam[100]; char chi2ndf[50]; for(int i(0);i<5;i++) { sprintf(tmpName,"h1_powheg_phantom_%d",i); h1_powheg_phantom[i] = (TH1D*)fname->Get(tmpName)->Clone(tmpName);// h1_powheg_phantom[i]->Sumw2(); for(Int_t ibin=0; ibin<nbins; ibin++) { xval[ibin] = 0.5*(Bins[ibin+1]+Bins[ibin]); xerr[ibin] = 0.5*(Bins[ibin+1]-Bins[ibin]); rMean[ibin] = h1_powheg_phantom[i]->GetBinContent(ibin+1); rMeanErr[ibin] = h1_powheg_phantom[i]->GetBinError(ibin+1); } grRatio = new TGraphErrors(nbins,xval,rMean,xerr,rMeanErr); grRatio->SetName("grRatio"); //njet=0 set fit function parameter limits //fit_func->SetParLimits(0,0.93,0.97); //fit_func->SetParLimits(1,-0.00015,-0.000095); //njet=1 set fit function parameter limits //fit_func->SetParLimits(0,0.,5.); //fit_func->SetParLimits(1,-5.0,0.0); //fit_func->SetRange(300.,1000.); //fit_func->SetParameters(0.9582,-0.0001); //njet=0 fix fit function parameters //fit_func->SetParameter(0,0.95); //fit_func->SetParameter(1,1.52); //fit_func->SetParameter(2,-0.0041); //fit_func->FixParameter(0,0); //fit_func->SetParameter(0,1); //fit_func->SetParameter(1,-30); //fit_func->SetParameter(2,-0.00001); //fit_func->FixParameter(2,-0.00425127); //fit_func->SetParLimits(1,0.0,0.0); //fit_func->FixParameter(1,0); if(i==1) { //fit_func->SetParameter(0,1.1); //fit_func->SetParameter(1,0.0); } if(i==2) { fit_func->SetParameter(0,0.9); fit_func->SetParameter(1,0.00001); } if(i==3) { //fit_func->SetParLimits(1,-0.00015,-0.000095); fit_func->SetParameter(0,0.4); fit_func->SetParameter(1,0.000001); } fitres = grRatio->Fit("fit_func","QMRN0FBSE"); //fitres = grRatio->Fit("fit_func","QMRN0SE"); sprintf(chi2ndf,"#chi^{2}/ndf = %.4f",(fit_func->GetChisquare())/(fit_func->GetNDF())); //errBand->SetPoint(0,0.002*(xval[nbins-1]),fit_func->Eval(0.002*(xval[nbins-1]))); errBand->SetPoint(0,0,130); errBand->SetPointError(0,0,dpol1Func(fit_func,0.002*(xval[nbins-1]),fitres)); //errBand->SetPointError(0,0,dpol2Func(fit_func,0.002*(xval[nbins-1]),fitres)); //errBand->SetPointError(0,0,dExpFunc(fit_func,0.002*(xval[nbins-1]),fitres)); //errBand->SetPointError(0,0,dsqrtFunc(fit_func,0.002*(xval[nbins-1]),fitres)); //errBand->SetPointError(0,0,dOneoverXFunc(fit_func,0.002*(xval[nbins-1]),fitres)); //errBand->SetPointError(0,0,dOneoversqrtXFunc(fit_func,0.002*(xval[nbins-1]),fitres)); //cout <<"0\t" << 0.002*(xval[nbins-1])<<"\t"<<fit_func->Eval(0.002*(xval[nbins-1]))<<"\t"<<dOneoversqrtXFunc(fit_func,0.002*(xval[nbins-1]),fitres)<<endl; errBand->SetPoint(1,130,fit_func->Eval(130)); //errBand->SetPointError(1,0,dOneoverXFunc(fit_func,130,fitres)); //errBand->SetPointError(1,0,dOneoversqrtXFunc(fit_func,130,fitres)); errBand->SetPointError(1,0,dpol1Func(fit_func,130,fitres)); for(Int_t j=2; j<=nbins; j++) { errBand->SetPoint(j,xval[j-1],fit_func->Eval(xval[j-1])); //errBand->SetPointError(j,0,dExpFunc(fit_func,xval[j-1],fitres)); //errBand->SetPointError(j,0,dsqrtFunc(fit_func,xval[j-1],fitres)); //errBand->SetPointError(j,0,dOneoverXFunc(fit_func,xval[j-1],fitres)); //errBand->SetPointError(j,0,dOneoversqrtXFunc(fit_func,xval[j-1],fitres)); errBand->SetPointError(j,0,dpol1Func(fit_func,xval[j-1],fitres)); //cout <<j<<"\t"<<xval[j-1]<<"\t"<<fit_func->Eval(xval[j-1])<<"\t"<<dOneoversqrtXFunc(fit_func,xval[j-1],fitres)<<endl; } errBand->SetPoint(nbins+1,1.2*(xval[nbins-1]),fit_func->Eval(1.2*(xval[nbins-1]))); errBand->SetPointError(nbins+1,0,dpol1Func(fit_func,1.2*(xval[nbins-1]),fitres)); //errBand->SetPointError(nbins+1,0,dpol2Func(fit_func,1.2*(xval[nbins-1]),fitres)); //errBand->SetPointError(nbins+1,0,dExpFunc(fit_func,1.2*(xval[nbins-1]),fitres)); //errBand->SetPointError(nbins+1,0,dsqrtFunc(fit_func,1.2*(xval[nbins-1]),fitres)); //errBand->SetPointError(nbins+1,0,dOneoverXFunc(fit_func,1.2*(xval[nbins-1]),fitres)); //errBand->SetPointError(nbins+1,0,dOneoversqrtXFunc(fit_func,1.2*(xval[nbins-1]),fitres)); sprintf(histName,"Fit_%d_jet",i); CPlot plotFunc(histName,"","mWW","POWHEG/Phantom"); plotFunc.setOutDir(OutDir); if(i>6) { plotFunc.AddGraph(grRatio,""); plotFunc.AddGraph(errBand,"3",kAzure-9,kFullDotSmall); } plotFunc.AddGraph(grRatio,"",kBlack,kFullCircle); if(i>6) plotFunc.AddFcn(fit_func,kRed); sprintf(histName,"njet=%d",i); if(i==3) sprintf(histName,"njet#geq3"); if(i==4) sprintf(histName,"Inclusive jet bins"); plotFunc.AddTextBox(histName,0.68,0.9,0.88,0.86,0,kBlack,-1); if(i>6) { plotFunc.AddTextBox(chi2ndf,0.25,0.9,0.45,0.86,0,kBlack,-1); sprintf(fitparam,"a = %.4f #pm %.4f",fit_func->GetParameter(0),fit_func->GetParError(0)); plotFunc.AddTextBox(fitparam,0.25,0.86,0.45,0.82,0,kBlack,-1); sprintf(fitparam,"b = %.6f #pm %.6f",fit_func->GetParameter(1),fit_func->GetParError(1)); plotFunc.AddTextBox(fitparam,0.25,0.82,0.5,0.78,0,kBlack,-1); } //sprintf(fitparam,"c = %.8f #pm %.8f",fit_func->GetParameter(2),fit_func->GetParError(2)); //plotFunc.AddTextBox(fitparam,0.25,0.78,0.45,0.74,0,kBlack,-1); if(i==0) { // plotFunc.SetYRange(0.5,4.0); //plotFunc.AddLine(0,1.52049,1640,1.52049,kBlack,2); } if(i==1) { //plotFunc.SetYRange(0.8,1.5); //plotFunc.AddLine(0,0.97262,1640,0.97262,kBlack,2); } if(i==2) { //plotFunc.SetYRange(0.8,1.2); plotFunc.AddLine(0,0.993992,1640,0.993992,kBlack,2); } if(i==3) { //plotFunc.SetYRange(0.0,1.3); plotFunc.AddLine(0,0.720189,1640,0.720189,kBlack,2); } plotFunc.Draw(c,kTRUE,"png"); } }
void getCalibrationResults(TString url="TopMassCalibration.root",int nCategs=4) { TString mpts[]={"161.5","163.5","166.5","169.5","172.5","175.5","178.5","181.5","184.5"}; const size_t nmpts=sizeof(mpts)/sizeof(TString); std::vector<TString> labels; if(nCategs==2) { labels.push_back("1 b-tags"); labels.push_back("#geq 2 b-tags"); } else if(nCategs==4) { labels.push_back("1 b-tags (ee+#mu#mu)"); labels.push_back("#geq 2 b-tags (ee+#mu#mu)"); labels.push_back("1 b-tags (e#mu)"); labels.push_back("#geq 2 b-tags (e#mu)"); } else { labels.push_back("1 b-tags (ee)"); labels.push_back("#geq 2 b-tags (ee)"); labels.push_back("1 b-tags (#mu#mu)"); labels.push_back("#geq 2 b-tags (#mu#mu)"); labels.push_back("1 b-tags (e#mu)"); labels.push_back("#geq 2 b-tags (e#mu)"); } TString outDir=gSystem->DirName(url); report << "Plots will be stored at @ " << outDir << endl; TGraphErrors *lingr = new TGraphErrors; lingr->SetMarkerStyle(20); TGraphErrors *biasgr = new TGraphErrors; biasgr->SetMarkerStyle(20); std::vector<TGraphErrors *> categbiasgr; for(int icat=0; icat<nCategs; icat++) categbiasgr.push_back( new TGraphErrors ); TObjArray statUncResults; TObjArray pullResults; //get results from file TFile *fin=TFile::Open(url); for(size_t i=0; i<nmpts; i++) { Float_t trueMass=mpts[i].Atof(); TH1D *massFitH=(TH1D *)fin->Get(mpts[i]+"/massfit"); if(massFitH==0) continue; TF1 *ffunc=massFitH->GetFunction("gaus"); float avgMass=ffunc->GetParameter(1); float avgMassErr=ffunc->GetParError(1); int ipt=lingr->GetN(); lingr->SetPoint(ipt,trueMass,avgMass); lingr->SetPointError(ipt,0,avgMassErr); for(int icat=0; icat<=nCategs;icat++) { TString postfix(""); TGraphErrors *gr=biasgr; if(icat<nCategs){ postfix ="_"; postfix +=( icat+1); gr=categbiasgr[icat]; } TH1D *biasH=(TH1D *)fin->Get(mpts[i]+"/bias"+postfix); ffunc=biasH->GetFunction("gaus"); float avgBias=ffunc->GetParameter(1); float avgBiasErr=ffunc->GetParError(1); ipt=gr->GetN(); gr->SetPoint(ipt,trueMass,avgBias); gr->SetPointError(ipt,0,avgBiasErr); if(trueMass==172.5) { TH1D *h=(TH1D *)fin->Get(mpts[i]+"/statunc"+postfix); h->SetDirectory(0); h->SetLineColor(icat==nCategs? 1 : icat+2); h->SetMarkerColor(icat==nCategs? 1 : icat+2); h->SetMarkerStyle(1); h->SetLineWidth(2); statUncResults.Add(h); } } TH1D *pullH=(TH1D *)fin->Get(mpts[i]+"/pull"); pullH->SetDirectory(0); pullResults.Add(pullH); } fin->Close(); //plot results setStyle(); gStyle->SetOptFit(0); TCanvas *c=new TCanvas("linc","linc",600,600); c->SetWindowSize(600,600); c->Divide(1,2); TPad *p=(TPad *)c->cd(1); p->SetPad(0,0.3,1.0,1.0); lingr->Draw("ap"); lingr->GetXaxis()->SetTitle("Generated m_{top} [GeV/c^{2}]"); lingr->GetXaxis()->SetTitle("Fitted m_{top} [GeV/c^{2}]"); TLine *l=new TLine(lingr->GetXaxis()->GetXmin(),lingr->GetYaxis()->GetXmin(), lingr->GetXaxis()->GetXmax(),lingr->GetYaxis()->GetXmax()); l->SetLineColor(kGray); l->SetLineStyle(6); l->Draw("same"); TLegend *leg = p->BuildLegend(); formatForCmsPublic(p,leg,"CMS simulation",3); leg->Delete(); p=(TPad *)c->cd(2); p->SetPad(0,0.0,1.0,0.28); p->SetTopMargin(0); p->SetBottomMargin(0.5); float yscale = (1.0-0.3)/(0.28-0); biasgr->Draw("ap"); biasgr->GetXaxis()->SetTitle("Generated m_{top} [GeV/c^{2}]"); biasgr->GetYaxis()->SetTitle("Bias"); biasgr->GetYaxis()->SetRangeUser(-5.2,5.2); biasgr->GetXaxis()->SetTitleOffset(0.85); biasgr->GetXaxis()->SetLabelSize(0.04 * yscale); biasgr->GetXaxis()->SetTitleSize(0.05 * yscale); biasgr->GetXaxis()->SetTickLength( 0.03 * yscale ); biasgr->GetYaxis()->SetTitleOffset(0.5); biasgr->GetYaxis()->SetLabelSize(0.04 * yscale); biasgr->GetYaxis()->SetTitleSize(0.04 * yscale); biasgr->Fit("pol1"); float a=biasgr->GetFunction("pol1")->GetParameter(1); float b=biasgr->GetFunction("pol1")->GetParameter(0); report << "[Inclusive bias correction] resslope:" << (a+1.) << " resbias:" << b << endl; c->Modified(); c->Update(); c->SaveAs(outDir+"/TopMassCalibrationResults.C"); c->SaveAs(outDir+"/TopMassCalibrationResults.png"); c->SaveAs(outDir+"/TopMassCalibrationResults.pdf"); // delete c; //biases per category c=new TCanvas("biasc","biasc",600,600); c->SetWindowSize(600,600); c->Divide(1,nCategs+1); c->cd(nCategs+1)->Delete(); float ystep=(1.0)/(nCategs+1); for(int icat=nCategs-1; icat>=0; --icat) { TGraphErrors *gr=categbiasgr[icat]; gr->SetMarkerStyle(20); TPad *p=(TPad *)c->cd(icat+1); p->SetFillStyle(1001); p->SetFillColor(0); float ymin=(icat+1)*ystep-0.05; float ymax=(icat+2)*ystep-0.05; if(icat==0) { ymin=icat*ystep; } p->SetPad(0,ymin,1.0,ymax); p->SetTopMargin(0.0); p->SetBottomMargin(icat==0?0.4:0.0); gr->Draw("ap"); float yscale = (0.95-ystep)/(ystep-0.0); if(icat==0) yscale=(0.95-2*ystep)/(1.2*ystep-0); if(icat==0) gr->GetXaxis()->SetTitle("Generated m_{top} [GeV/c^{2}]"); else gr->GetXaxis()->SetNdivisions(0); gr->GetYaxis()->SetTitle("Bias"); gr->GetYaxis()->SetRangeUser(-5.2,5.2); gr->GetXaxis()->SetTitleOffset(0.85); gr->GetXaxis()->SetLabelSize(0.04 * yscale); gr->GetXaxis()->SetTitleSize(0.05 * yscale); gr->GetXaxis()->SetTickLength( 0.03 * yscale ); gr->GetYaxis()->SetTitleOffset(icat==0?0.5:0.3); gr->GetYaxis()->SetLabelSize(0.04 * yscale); gr->GetYaxis()->SetTitleSize(0.04 * yscale); gr->Fit("pol1"); float a=gr->GetFunction("pol1")->GetParameter(1); float b=gr->GetFunction("pol1")->GetParameter(0); report << "[Bias correction #" << icat+1 << "] resslope:" << (a+1.) << " resbias:" << b << endl; //prepare label TPaveText *pave = new TPaveText(0.70,0.65,0.8,0.92,"NDC"); pave->SetTextFont(42); pave->SetFillStyle(0); pave->SetBorderSize(0); pave->AddText( labels[icat] )->SetTextAlign(11); pave->Draw(); if(icat==nCategs-1) { pave = new TPaveText(0.2,0.75,0.45,0.92,"NDC"); pave->SetTextFont(42); pave->SetFillStyle(0); pave->SetBorderSize(0); pave->AddText( "CMS simulation" )->SetTextAlign(11); pave->Draw(); } } c->Modified(); c->Update(); c->SaveAs(outDir+"/TopMassCalibrationBiases.C"); c->SaveAs(outDir+"/TopMassCalibrationBiases.png"); c->SaveAs(outDir+"/TopMassCalibrationBiases.pdf"); //delete c; //stat uncertainty c=new TCanvas("statc","statc",600,600); c->SetWindowSize(600,600); for(int i=0; i<statUncResults.GetEntriesFast(); i++) { int idx=statUncResults.GetEntriesFast()-1-i; statUncResults.At(idx)->Draw(i==0?"hist":"histsame"); ((TH1*)statUncResults.At(idx))->SetTitle( i==0 ? "combined" :labels[idx] ); } leg = c->BuildLegend(); formatForCmsPublic(c,leg,"CMS simulation",3); c->Modified(); c->Update(); c->SaveAs(outDir+"/TopMassCalibrationStat.C"); c->SaveAs(outDir+"/TopMassCalibrationStat.png"); c->SaveAs(outDir+"/TopMassCalibrationStat.pdf"); //delete c; //pulls TGraphErrors *avgPull = new TGraphErrors; avgPull->SetMarkerStyle(20); TGraphErrors *sigmaPull = new TGraphErrors; sigmaPull->SetMarkerStyle(20); c=new TCanvas("pullsc","pullsc",1600,(pullResults.GetEntriesFast()/4+1)*400); c->SetWindowSize(1600,(pullResults.GetEntriesFast()/4+1)*400); c->Divide(4,pullResults.GetEntriesFast()/4+1); for(int i=0; i<pullResults.GetEntriesFast(); i++) { TPad *p=(TPad *)c->cd(i+1); TH1 *pullH=(TH1 *)pullResults.At(i); pullH->Draw("e1"); Float_t trueMass=mpts[i].Atof(); TF1 *gaus=pullH->GetFunction("gaus"); avgPull->SetPoint(i,trueMass,gaus->GetParameter(1)); avgPull->SetPointError(i,0,gaus->GetParError(1)); sigmaPull->SetPoint(i,trueMass,gaus->GetParameter(2)); sigmaPull->SetPointError(i,0,gaus->GetParError(2)); if(i==0) { leg = p->BuildLegend(); formatForCmsPublic(p,leg,"CMS simulation",3); leg->Delete(); } TPaveText *pave = new TPaveText(0.2,0.8,0.35,0.88,"NDC"); pave->SetTextFont(42); pave->SetFillStyle(0); pave->SetBorderSize(0); pave->AddText( mpts[i] )->SetTextAlign(11); pave->Draw(); } c->Modified(); c->Update(); c->SaveAs(outDir+"/TopMassCalibrationPulls.C"); c->SaveAs(outDir+"/TopMassCalibrationPulls.png"); c->SaveAs(outDir+"/TopMassCalibrationPulls.pdf"); //delete c; //pull momenta c=new TCanvas("pullsmomc","pullsmomc",600,600); c->SetWindowSize(600,600); c->Divide(1,2); p=(TPad *)c->cd(1); avgPull->Draw("ap"); avgPull->GetYaxis()->SetRangeUser(-3,3); avgPull->GetXaxis()->SetTitle("Generated m_{top} [GeV/c^{2}]"); avgPull->GetYaxis()->SetTitle("Average pull"); leg = p->BuildLegend(); formatForCmsPublic(p,leg,"CMS simulation",3); leg->Delete(); c->cd(2); sigmaPull->GetYaxis()->SetRangeUser(0.9,1.2); sigmaPull->Draw("ap"); sigmaPull->GetXaxis()->SetTitle("Generated m_{top} [GeV/c^{2}]"); sigmaPull->GetYaxis()->SetTitle("Pull width"); c->Modified(); c->Update(); c->SaveAs(outDir+"/TopMassCalibrationPullsMomenta.C"); c->SaveAs(outDir+"/TopMassCalibrationPullsMomenta.png"); c->SaveAs(outDir+"/TopMassCalibrationPullsMomenta.pdf"); //delete c; cout << report.str() << endl; }