void makePlots_InvariantMass_ElEl(){ gROOT->SetStyle("Plain"); TCanvas *c1 = new TCanvas("c1_fit1","The Fit Canvas",200,10,700,500); c1->SetGridx(); c1->SetGridy(); c1->GetFrame()->SetFillColor(21); c1->GetFrame()->SetBorderMode(-1); c1->GetFrame()->SetBorderSize(5); TFile* file = TFile::Open("Output_LowPtSUSY_Tree_PPZ.root"); TH1F *h_InvMass = (TH1F*) file->Get("h_InvariantMass_ElEl"); h_InvMass->SetLineColor(kBlue); h_InvMass->SetLineWidth(2); h_InvMass->Rebin(60); h_InvMass->GetYaxis()->SetTitle("Events/2.0 GeV"); h_InvMass->GetYaxis()->SetTitleOffset(1.4); h_InvMass->GetXaxis()->SetRangeUser(70, 110); TF1 *fSignal = new TF1("fSignal","gaus",70.0,110.0); fSignal->SetParLimits(0, 11500.0, 15000.0); fSignal->SetParLimits(1, 80.0, 95.0); fSignal->SetParLimits(2, 0.0, 1.0); h_InvMass->Draw("HIST"); h_InvMass->Fit("fSignal", "", "", 70.0, 110.0); c1->SaveAs("h_InvariantMass_ElEl.pdf"); c1->SaveAs("h_InvariantMass_ElEl.png"); }
TH2D* GetJetCorrFunc2D_doublegaussian(int itrg, int jass) { TH2D* hcorr = (TH2D*)GetRawCorrFunc2D_ratio(itrg,jass); TH2D* hcorr_clone = (TH2D*)hcorr->Clone(Form("corr_clone_itrg%d_jass%d",itrg,jass)); hcorr_clone->Reset(); for(int ietabin=1;ietabin<=hcorr->GetNbinsX();ietabin++) { TH1D* hcorrphi = (TH1D*)hcorr->ProjectionY(Form("corrphi_%d",ietabin),ietabin,ietabin,"e"); float min = hcorrphi->GetMinimum(); hcorrphi->SetAxisRange(-1,1,"X"); float nearmax = hcorrphi->GetMaximum(); hcorrphi->SetAxisRange(PI-1,PI+1,"X"); float awaymax = hcorrphi->GetMaximum(); TF1* fitfunc = new TF1("fitfunc",doubleGaussian,-PI/2.,3.*PI/2.,5); fitfunc->SetParameters(min,nearmax-min,0.3,awaymax-min,0.5); fitfunc->SetParLimits(0,0,100000); fitfunc->SetParLimits(1,0,100000); fitfunc->SetParLimits(2,0,100000); fitfunc->SetParLimits(3,0,100000); fitfunc->SetParLimits(4,0,100000); for(int ifit=0;ifit<3;ifit++) hcorrphi->Fit(Form("fitfunc_%d",ietabin),"RNO"); float level = fitfunc->GetParameter(0); for(int iphibin=1;iphibin<=hcorr->GetNbinsY();iphibin++) hcorr_clone->SetBinContent(ietabin,iphibin,hcorr->GetBinContent(ietabin,iphibin)-level); delete fitfunc; } float max = hcorr_clone->GetBinContent(hcorr_clone->GetMaximumBin()); hcorr_clone->SetAxisRange(ymin,max*1.3,"Z"); return hcorr_clone; }
Bool_t misalignmentDependence(TCanvas *c1old, Int_t nFiles,TString *names,TString misalignment,Double_t *values,Double_t *phases,TString xvar,TString yvar, Bool_t drawfits = true, Bool_t resolution = false, TString saveas = "") { TF1 *f = 0; TString functionname = ""; //if only one parameter is of interest TString parametername = ""; Int_t parameter = 9999; //if multiple parameters are of interest Int_t nParameters = -1; TString *parameternames = 0; Int_t *parameters = 0; if (misalignment == "breitwigner") { if (xvar == "" && yvar == "ZZMass") { f = new TF1("breitwigner","[2]*TMath::BreitWigner(x,[0],[1])"); f->SetParameters(91,2); f->SetParLimits(0,70,105); f->SetParLimits(1,0,10); nParameters = 2; Int_t tempParameters[2] = {0,1}; TString tempParameterNames[2] = {"M;GeV","#gamma;GeV"}; parameters = tempParameters; parameternames = tempParameterNames; functionname = "Breit Wigner"; } } if (xvar == "" && functionname == "") { if (c1old == 0 || misalignment == "" || values == 0) return false; misalignmentDependence(c1old,nFiles,names,misalignment,values,phases,xvar,yvar,(TF1*)0,0,"","",resolution,saveas); return true; } if (functionname == "") return false; if (drawfits) { parameter = -parameter-1; for (int i = 0; i < nParameters; i++) parameters[i] = -parameters[i]-1; } if (nParameters > 0) misalignmentDependence(c1old,nFiles,names,misalignment,values,phases,xvar,yvar, f,nParameters,parameters,parameternames,functionname,resolution,saveas); else misalignmentDependence(c1old,nFiles,names,misalignment,values,phases,xvar,yvar, f,parameter,parametername,functionname,resolution,saveas); delete f; return true; }
/************************************************************ * Fit ADC spectrum ************************************************************/ int FitAdcHist(TH1F *h, float data[NDATA], const int print ) { TF1 *fadc; TPaveText *adcPT; // Protect for null histograms if( h == 0 || h->GetEntries()<1000. ) return -1; printf("Fitting %s\n",h->GetName()); gStyle->SetOptStat("emr"); adcPT = new TPaveText(0.58,0.315,0.98,0.635,"NDC"); // Refit ADC Double_t n = h->GetEntries(); Double_t rms = h->GetRMS(); Double_t mean = h->GetMean(); Double_t ymin = mean-2*rms; if( ymin < 60. ) ymin=60.; Double_t ymax = mean+1.5*rms; fadc = new TF1("adc_fun",skewnormal,ymin,ymax,4); fadc->SetParameters(n,mean,rms,1.5); fadc->SetParLimits(1,mean-rms,mean+0.5*rms); fadc->SetParLimits(2,rms*0.5,rms*1.5); fadc->SetParLimits(3,1.,4.); h->Fit("adc_fun","r"); // If skew is too high refit with fixed skew if( fadc->GetParameter(3) > 2.5 ) { printf("REFIT %s\n",h->GetName()); fadc->SetParameter(3,1.6); fadc->SetParLimits(3,1.6,1.6); h->Fit("adc_fun","r") ; } // if have enough hits use fit results if( n > MINHITS ) { data[13] = fadc->GetParameter(1); data[14] = fadc->GetParError(1); data[15] = fadc->GetParameter(2); data[16] = fadc->GetParError(2); data[17] = fadc->GetParameter(3); data[18] = fadc->GetParError(3); double dof = fadc->GetNDF(); if( dof > 0. ) data[19] = fadc->GetChisquare()/dof; adcPT->AddText(Form("Peak %.1lf #pm %.1lf",data[13],data[14])); adcPT->AddText(Form("Width %.1lf #pm %.1lf",data[15],data[16])); adcPT->AddText(Form("Skew %.2lf #pm %.2lf", data[17],data[18])); if( dof > 0. ) adcPT->AddText(Form("#Chi^{2}/DoF %.2lf",data[19])); adcPT->SetTextColor(2); adcPT->Draw(); // if have too few hits use fit stats instead of fit results } else { data[12] = mean; data[13] = h->GetMeanError(); data[14] = rms; data[15] = h->GetRMSError(); data[16] = h->GetSkewness(); } if( print ) c1->Print(Form("%s_%s.png",fname,h->GetName())); return 0; } //end FitAdcHist
void example(double E0 = 50, int nevents = 100000) { TStopwatch timer; // 12C* -> 3(4He) // compound nucleus = carbon KVNucleus CN(6, 12); CN.SetExcitEnergy(E0); // decay products KVEvent decay; KVNucleus* n = decay.AddParticle(); n->SetZandA(2, 4); n = decay.AddParticle(); n->SetZandA(2, 4); n = decay.AddParticle(); n->SetZandA(2, 4); MicroStat::mdweight gps; Double_t etot = E0 + decay.GetChannelQValue(); if (etot <= 0) { printf("Break-up channel is not allowed\n"); return; } gps.SetWeight(&decay, etot); gps.initGenerateEvent(&decay); TH1F* h1 = new TH1F("h1", "Kinetic energy of alpha particle 3", 200, 0, etot * 2. / 3.); h1->Sumw2(); KVEvent event; while (nevents--) { gps.GenerateEvent(&decay, &event); h1->Fill(event.GetParticle(3)->GetKE()); gps.resetGenerateEvent(); } h1->Draw(); TF1* EDis = new TF1("EDis", edist, 0., etot, 3); EDis->SetNpx(500); EDis->SetParLimits(0, 0, 1.e+08); EDis->SetParLimits(1, 0, 2 * etot); EDis->FixParameter(2, 3); gStyle->SetOptFit(1); h1->Fit(EDis, "EM"); timer.Print(); }
TF1* fitPixelBeam(TH1D* hist, double pixelWidth, double beamSigma, bool display) { TF1* conv = new TF1("conv", "[2] + [4] * 0.5 * ( TMath::Erf(([0]/2 + [3] - x)/(sqrt(2)*[1])) + TMath::Erf(([0]/2 + [3] + x)/(sqrt(2)*[1])) )"); conv->SetParNames("Width", "Sigma", "Background", "Offset", "Scale"); const unsigned int numBins = hist->GetNbinsX(); const double limitLow = hist->GetXaxis()->GetBinLowEdge(1); const double limitHigh = hist->GetXaxis()->GetBinUpEdge(numBins); // Estimate the background using the +/- 10% edges of the histogram double background = 0; const unsigned int numBackgroundBins = numBins * 0.1 + 1; for (unsigned int n = 0; n < numBackgroundBins; n++) { background += hist->GetBinContent(n + 1); background += hist->GetBinContent(numBins - n); } background /= (double)(2 * numBackgroundBins); // Estimate the scale double scale = 0; for (unsigned int bin = 1; bin <= numBins; bin++) if (hist->GetBinContent(bin) > scale) scale = hist->GetBinContent(bin); double offset = 0; conv->SetRange(limitLow, limitHigh); conv->SetParameters(pixelWidth, beamSigma, background, offset, scale); conv->SetParLimits(0, 0.1 * pixelWidth, 100 * pixelWidth); conv->SetParLimits(1, 0, 100 * beamSigma); conv->SetParLimits(2, 0, scale); conv->SetParLimits(3, -pixelWidth, pixelWidth); conv->SetParLimits(4, 0.1 * scale, 10 * scale); hist->Fit("conv", "QR0B"); if (display) { TCanvas* can = new TCanvas(); conv->SetLineColor(46); conv->SetLineWidth(1); hist->Draw(); conv->Draw("SAME"); can->Update(); can->WaitPrimitive(); } return conv; }
TF1* GetFitFunc_ZYAM_MC(TH1D* h) { TH1D* hcorrphi = (TH1D*)h->Clone(h->GetName()); double histminY = hcorrphi->GetBinContent(10); double histminX = 1.0; //hcorrphi->SetAxisRange(-0.01,1.2,"X"); TF1* fitfunc = new TF1(Form("fitfunc_%s",h->GetName()),"[0]+[1]*(x-[2])*(x-[2])",0.8,2.8); //std 0.15-1.8 fitfunc->SetParameters(histminY,0.0002,histminX); fitfunc->SetParLimits(1,0,1000); fitfunc->SetParLimits(2,0.05,1000); for(int ifit=0;ifit<3;ifit++) hcorrphi->Fit(Form("fitfunc_%s",h->GetName()),"RNO"); return fitfunc; }
TF1* GetFitFunc_ZYAM_AllPhysics(TH1D* h) { TH1D* hcorrphi = (TH1D*)h->Clone(h->GetName()); double histminY = hcorrphi->GetBinContent(10); double histminX = 1.0; hcorrphi->SetAxisRange(-0.01,1.5,"X"); TF1* fitfunc = new TF1(Form("fitfunc_%s",h->GetName()),"[0]+[1]*(x-[2])*(x-[2])+[3]*(x-[2])*(x-[2])*(x-[2])",0.5,1.65); //std 0.6 1.55 vs pT ; 0.6 1.8 vs eta fitfunc->SetParameters(histminY,0.0002,histminX,0.0001); fitfunc->SetParLimits(1,0,1000); fitfunc->SetParLimits(2,0.5,1000); // fitfunc->SetParLimits(3,0,1000); for(int ifit=0;ifit<3;ifit++) hcorrphi->Fit(Form("fitfunc_%s",h->GetName()),"RNO"); return fitfunc; }
TF1* linLorentzianFit(TH1* histoY){ TString name = histoY->GetName() + TString("Fit"); // Fit slices projected along Y from bins in X TF1 *fit = new TF1(name,lorentzianPlusLinear,70,110,5); fit->SetParameters(histoY->GetMaximum(),histoY->GetRMS(),histoY->GetMean(),10,-0.1); fit->SetParNames("norm","width","mean","offset","slope"); fit->SetParLimits(1,-10,10); //fit->SetParLimits(2,85,95); //fit->SetParLimits(2,90,93); fit->SetParLimits(2,2,4); fit->SetParLimits(3,0,100); fit->SetParLimits(4,-1,0); fit->SetLineWidth(2); //histoY -> Fit(name,"0","",85,97); histoY -> Fit(name,"0","",2,4); return fit; }
TF1* GetFit(const char *address, int lyr, double xinit) { const char *bgr = Form("[6]*TMath::Exp([7]*(x-%f))",xinit); const char *la1 = "(1-[3]-[4]-[5])*TMath::Landau(x,[1],[2],1)"; const char *la2 = "[3]*TMath::Landau(x,2*[1]+1.4*[2],2.0*[2],1)"; const char *la3 = "[4]*TMath::Landau(x,3*[1]+3.3*[2],3.0*[2],1)"; const char *la4 = "[5]*TMath::Landau(x,4*[1]+5.6*[2],4.0*[2],1)"; TF1 *ret = new TF1("fit_H1", Form("[0]*(%s+%s+%s+%s)+%s",la1,la2,la3,la4,bgr) ); ret->SetParName(0,"A"); ret->SetParName(1,"lambda"); ret->SetParName(2,"sigma"); ret->SetParName(3,"f2"); ret->SetParameter(0,1e4); ret->SetParLimits(0,1e2,1e7); ret->SetParameter(1,21); ret->SetParLimits(1,13,25.0); ret->SetParameter(2,3.0); ret->SetParLimits(2,1.5,5.0); if(lyr>1) { ret->SetParameter(1,15); ret->SetParLimits(1,2,30); ret->SetParameter(2,5.0); ret->SetParLimits(2,0.8,10.0); } ret->SetParameter(3,0.20); ret->SetParLimits(3,0,0.40); ret->SetParameter(4,0.0); ret->SetParameter(5,0.0); ret->SetParameter(6,500); ret->SetParLimits(6,1e2,1e7); ret->SetParameter(7,-1); ret->SetParLimits(7,-10,-0.1); ret->SetLineColor(kRed-3); ifstream infit; infit.open( address ); double tmp; bool found=false; for(int n=0; n!=ret->GetNpar(); ++n) { infit >> tmp; if(!infit.good()) break; ret->SetParameter(n,tmp); infit >> tmp; found = true; } infit.close(); if(found) { cout << " Previous fit results found" << endl; ret->SetParLimits(4,0,0.40); ret->SetParLimits(5,0,0.40); } else { ret->SetParLimits(4,+1,-1); ret->SetParLimits(5,+1,-1); } return ret; }
TH1D* GetJetCorrFunc1D_doublegaussian(int itrg, int jass) { TH1D* hcorrphi = (TH1D*)GetRawCorrFunc1D_ratio(itrg,jass); TF1* fitfunc = new TF1("fitfunc",doubleGaussian,-PI/2.,3.*PI/2.,5); fitfunc->SetParameters(hcorrphi->GetMinimum(),hcorrphi->GetMaximum()-hcorrphi->GetMinimum(),0.3,hcorrphi->GetMaximum(hcorrphi->GetMaximum())-hcorrphi->GetMinimum(),0.5); fitfunc->SetParLimits(0,0,100000); fitfunc->SetParLimits(1,0,100000); fitfunc->SetParLimits(2,0,100000); fitfunc->SetParLimits(3,0,100000); fitfunc->SetParLimits(4,0,100000); for(int ifit=0;ifit<3;ifit++) hcorrphi->Fit("fitfunc","RNO"); TH1D* hcorrphi_clone = (TH1D*)hcorrphi->Clone(Form("corrphi_clone_itrg%d_jass%d",itrg,jass)); float level = fitfunc->GetParameter(0); for(int ibin=1;ibin<=hcorrphi_clone->GetNbinsX();ibin++) hcorrphi_clone->SetBinContent(ibin,hcorrphi_clone->GetBinContent(ibin)-level); float max = hcorrphi_clone->GetBinContent(hcorrphi_clone->GetMaximumBin()); hcorrphi_clone->SetAxisRange(ymin,max*1.3,"Y"); delete fitfunc; return hcorrphi_clone; }
TF1* GetFitFunc_ZYAM_pp(TH1D* h) { TH1D* hcorrphi = (TH1D*)h->Clone(h->GetName()); // double histminY = hcorrphi->GetBinContent(hcorrphi->GetMinimumBin()); // double histminX = hcorrphi->GetBinCenter(hcorrphi->GetMinimumBin()); double histminY = hcorrphi->GetBinContent(hcorrphi->FindBin(1.2)); double histminX = hcorrphi->GetBinCenter(hcorrphi->FindBin(1.2)); //hcorrphi->SetAxisRange(-0.01,1.2,"X"); TF1* fitfunc = new TF1(Form("fitfunc_%s",h->GetName()),"[0]+[1]*(x-[2])*(x-[2])+[3]*abs((x-[2])*(x-[2])*(x-[2]))",0.5,2.5); //std 0.6 1.55 vs pT ; 0.6 1.8 vs eta fitfunc->SetParameters(histminY,0.002,histminX,0.0); fitfunc->SetParLimits(1,0,1000); fitfunc->SetParLimits(2,0.2,2.0); // fitfunc->SetParLimits(3,0,100); fitfunc->FixParameter(3,0); for(int ifit=0;ifit<3;ifit++) hcorrphi->Fit(Form("fitfunc_%s",h->GetName()),"NO","",histminX-0.6,histminX+0.6); fitfunc->SetName(Form("fitfunc_%s_%.3f",h->GetName(),fitfunc->GetParameter(0))); return fitfunc; }
TF1* fitTools::fitResolutionGraph( TGraphErrors* graph, std::string funcType, std::string funcName, const std::string& option, float rangeMax, float rangeMin) { TF1* fitFunction; if( funcType=="NSC" ) { fitFunction = new TF1(funcName.c_str(), NSC, rangeMin, rangeMax, 3); fitFunction->SetParameters( 0., 1., 0.05); fitFunction->SetParLimits( 0, -2., 11.); fitFunction->SetParLimits( 1, -2., 2.); fitFunction->SetParLimits( 2, -0.3, 0.3 ); } else if( funcType=="NSCPF" ) { fitFunction = new TF1(funcName.c_str(), NSCPF, rangeMin, rangeMax, 4); fitFunction->SetParameters( 0., 1., 0.05, 0.); fitFunction->SetParLimits( 0, -2., 5.); fitFunction->SetParLimits( 1, 0., 1.1); fitFunction->SetParLimits( 2, 0., 0.12 ); fitFunction->SetParLimits( 3, -1., 1.); } else { std::cout << "Function '" << funcType << "' not implemented yet for fitResolutionGraph. Exiting." << std::endl; exit(119); } graph->Fit(fitFunction, option.c_str()); return fitFunction; }
//______________________________________________________________________________ void Fit(TH1* h, Double_t* outPos, Double_t* outFWHM) { // Perform fit. Char_t tmp[256]; Double_t x1 = 50; Double_t x2 = 230; TF1* func = new TF1("func", "gaus(0)+pol5(3)", x1, x2); func->SetParameters(h->GetMaximum(), 135, 8, 1, 1, 0.1, 0.1); func->SetLineColor(kBlue); func->SetParLimits(1, 130, 140); func->SetParLimits(2, 1, 15); h->Fit(func, "RBQO"); // get position and FWHM fPi0Pos = func->GetParameter(1); *outPos = fPi0Pos; *outFWHM = 2.35*func->GetParameter(2); // indicator line TLine* line = new TLine(); line->SetLineWidth(2); line->SetX1(fPi0Pos); line->SetX2(fPi0Pos); line->SetY1(0); line->SetY2(h->GetMaximum()); TF1* fBG = new TF1("funcBG", "pol5", x1, x2); for (Int_t i = 0; i < 6; i++) fBG->SetParameter(i, func->GetParameter(3+i)); fBG->SetLineColor(kRed); // draw h->GetXaxis()->SetRangeUser(0, 300); h->Draw(); func->Draw("same"); fBG->Draw("same"); line->Draw("same"); }
TF1 * relativisticBWintFit(const std::string & index) { RelativisticBWwithZGammaInterference * fobj = new RelativisticBWwithZGammaInterference; TF1 * functionToFit = new TF1(("functionToFit"+index).c_str(), fobj, 60, 120, fobj->parNum(), "RelativisticBWwithZGammaInterference"); functionToFit->SetParameter(0, 2.); functionToFit->SetParameter(1, 90.); functionToFit->SetParameter(2, 1.); functionToFit->SetParameter(3, 1.); functionToFit->SetParLimits(3, 0., 1.); return functionToFit; }
//-------------------------------------------------------------------------------------------------- // Fit histogram with function //-------------------------------------------------------------------------------------------------- TF1* fitFakeRatePtHist(TH1F *FakeRatePt) { TF1 *fitFunction = new TF1("fitFunction", "[0]*(1 - exp(-1*[1]*(x - [2])))",-10,10); fitFunction->SetParameter(0,0.05); fitFunction->SetParameter(1,0.07); fitFunction->SetParameter(2,10.0); fitFunction->SetParLimits(2,9.5,10.5); FakeRatePt->Fit("fitFunction"); return fitFunction; }
TF1* fitTools::fitResponseGraph( TGraphErrors* graph, std::string funcType, std::string funcName, const std::string& option, float rangeMax, float rangeMin) { TF1* fitFunction; if( funcType=="rpf" ) { fitFunction = new TF1(funcName.c_str(), rpf, rangeMin, rangeMax, 6); //will have to fix the range issue! fitFunction->SetParameters(100,0.85,4.2,80,250,1.); fitFunction->SetParLimits(1,0.5,1.0); fitFunction->SetParLimits(2,1.,10.); fitFunction->SetParLimits(4, 100., 500.); fitFunction->SetParameter(0, 0.6); fitFunction->SetParameter(5, 1.); //fitFunction->SetParameter(1, -0.6); } else if( funcType=="powerlaw" ) { fitFunction = new TF1(funcName.c_str(), "[0] - [1]/(pow(x, [2]))"); fitFunction->SetRange(rangeMin, rangeMax); fitFunction->SetParameters(1., 1., 0.3); } else if( funcType=="powerlawL2L3" ) { fitFunction = new TF1(funcName.c_str(), "1. + [0]/(pow(x, [1]))"); fitFunction->SetRange(rangeMin, rangeMax); fitFunction->SetParameters(0.7, 0.7); //fitFunction->SetParLimits(0, 0.5, 2.); //fitFunction->SetParLimits(1, 0.5, 2.); } else if( funcType=="powerlaw_corr" ) { fitFunction = new TF1(funcName.c_str(), "[0] - [1]/(pow(x, [2])) + [3]/x"); fitFunction->SetRange(rangeMin, rangeMax); fitFunction->SetParameters(1., 1., 0.3, 1.); } else { std::cout << "Function '" << funcType << "' not implemented yet for fitResponseGraph. Exiting." << std::endl; exit(119); } graph->Fit(fitFunction, option.c_str()); return fitFunction; }
void countZs(const char* filename, int run1=1, int run2=0, float lumi=0, bool add=false) { TFile *file = new TFile(filename); if (!file) return; TCanvas *c1 = new TCanvas(); c1->cd(); TH1F *h = (TH1F*) file->Get("Run summary/DiMuonHistograms/GlbGlbMuon_HM"); h->GetYaxis()->SetRangeUser(0,200); h->Draw(); TF1 *f = new TF1("f","gaus(0)+pol2(3)",70,110); f->SetParName(0,"norm"); f->SetParName(1,"mass"); f->SetParName(2,"width"); f->SetParameters(1.16028e+02,9.07785e+01,2.11556e+00,-2.17600e+01,9.67443e-01,-6.98382e-03); f->SetParLimits(0,0,1e6); f->SetParLimits(1,85,95); f->SetParLimits(2,1.5,5); h->Fit(f,"","",70,110); h->GetYaxis()->SetRangeUser(0,200); c1->Update(); TF1 *f2 = new TF1("f2","gaus(0)",70,110); f2->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2)); int integral = (int) (f2->Integral(70,110) / h->GetBinWidth(2)); TLatex *tl = new TLatex(); tl->DrawLatexNDC(0.1,0.95,Form("pPb 8TeV [%i-%i, %.1f nb^{-1}]",run1,run2,lumi)); tl->DrawLatexNDC(0.18,0.75,Form("%i Z bosons",integral)); tl->DrawLatexNDC(0.18,0.7,Form("(#sigma = %.1f nb)",integral/lumi)); if (!add) c1->SaveAs(Form("plotZ_%i_%i.pdf",run1,run2)); else c1->SaveAs("plotZ.gif+100"); file->Close(); }
void test_TF1_FitErr2(){ gStyle->SetOptFit(1111); gStyle->SetOptStat(0); histgen(); TFile *f = new TFile("background.root"); background = (TH1F*)f->Get("background"); //pointer used in ftotal TH1F *result = (TH1F*)f->Get("result"); TF1 *ftot = new TF1("ftot",ftotal,0,10,5); Double_t norm = result->GetMaximum(); // ftot->SetParameters(0.5*norm,5,.2,norm); ftot->SetParameters(0.5*norm,6,.5,5,-0.5); ftot->SetParLimits(0,.3*norm,norm); // ftot->FixParameter(1,6); // ftot->FixParameter(2,0.5); ftot->SetParLimits(1,5.5,6.5); ftot->SetParLimits(2,0.25,1); // ftot->SetParLimits(4,-0.01,-50); result->Fit("ftot","b"); result->Fit("ftot","b"); result->Fit("ftot","b"); result->Fit("ftot"); result->Fit("ftot"); result->Fit("ftot"); TFitResult fitResult=result->Fit("ftot"); double TF1 *bgf = TF1("bgf","pol1",0,10); }
int main(int argc, char const *argv[]) { TFile *myFile = new TFile("output.root","RECREATE"); Float_t E1,Px1,Py1,Pz1,E2,Px2,Py2,Pz2; Double_t mass = 0; TH1D *m12 = new TH1D("m12","m12",60,0.99,1.08); TF1 *myBW = new TF1("myBW","TMath::BreitWigner(x,[0],[1])", 1.01, 1.03); myBW->SetParName(0,"Mass"); myBW->SetParName(1,"#Gamma"); TFile *inputFile = new TFile("data.root"); TTree *data_tree = (TTree*)inputFile->Get("data"); data_tree->SetBranchAddress("E1", &E1); data_tree->SetBranchAddress("Px1", &Px1); data_tree->SetBranchAddress("Py1", &Py1); data_tree->SetBranchAddress("Pz1", &Pz1); data_tree->SetBranchAddress("E2", &E2); data_tree->SetBranchAddress("Px2", &Px2); data_tree->SetBranchAddress("Py2", &Py2); data_tree->SetBranchAddress("Pz2", &Pz2); TLorentzVector vec1(0.0,0.0,0.0,0.0); TLorentzVector vec2(0.0,0.0,0.0,0.0); int count = data_tree->GetEntries(); for (int i = 0; i < count; i++) { data_tree->GetEntry(i); vec1.SetPxPyPzE(Px1,Py1,Pz1,E1); vec2.SetPxPyPzE(Px2,Py2,Pz2,E2); mass = (vec1 + vec2).M(); m12->Fill(mass); } myBW->SetParameters(0,1.02,0.05); myBW->SetParLimits(0,1.01,1.03); m12->Fit("myBW","","",0,2); m12->GetXaxis()->SetTitle("Mass (GeV)"); gStyle->SetOptFit(1111); myFile->cd(); myFile->Write(); myFile->Close(); return 0; }
void extracttageffExt(int n0, int n1, int n2, int n3, int n4) { // n3 information is not used in the fit h1=new TH1F("h1", "h1",5, 0.0, 5.0); h1->Fill(0, n0); h1->Fill(1, n1); h1->Fill(2, n2); h1->Fill(3, n3); h1->Fill(4, n4); ntotal = n0+n1+n2+n3+n4; double eb_initial = eb; double el_initial = el; double acc_initial = acc; double eb2_initial= eb2; double frac_initial= 0.01; TF1 *ftot = new TF1("ftot", nball, 0.0, 5.0, 5); ftot->SetParameters(eb_initial, el_initial, acc_initial, eb2_initial, frac_initial); //ftot->SetParLimits(0, eb, eb); //ftot->SetParLimits(1, el, el); ftot->SetParLimits(2, acc, acc); //ftot->SetParLimits(0, 1, 1); //ftot->SetParLimits(1, 1, 1); //ftot->SetParLimits(2, 0.98, 0.98); ftot->SetParLimits(3, 0, 1); //ftot->SetParLimits(4, 0.0, 1000.0); h1->Fit("ftot","R","same",0,5); h1->Draw("e"); }
TF1 * expRelativisticBWintPhotFit(const std::string & index) { ExpRelativisticBWwithZGammaInterferenceAndPhotonPropagator * fobj = new ExpRelativisticBWwithZGammaInterferenceAndPhotonPropagator; TF1 * functionToFit = new TF1(("functionToFit"+index).c_str(), fobj, 60, 120, fobj->parNum(), "ExpRelativisticBWwithZGammaInterferenceAndPhotonPropagator"); functionToFit->SetParameter(0, 2.); functionToFit->SetParameter(1, 90.); functionToFit->SetParameter(2, 1.); functionToFit->SetParameter(3, 1.); functionToFit->SetParameter(4, 0.); functionToFit->SetParameter(5, 0.); functionToFit->SetParLimits(3, 0., 1.); functionToFit->SetParLimits(4, 0., 1.); return functionToFit; }
void fithist() { //fit function ftotal to signal + background histgen(); TFile *f = new TFile("background.root"); background = (TH1F*)f->Get("background"); //pointer used in ftotal TH1F *result = (TH1F*)f->Get("result"); TF1 *ftot = new TF1("ftot",ftotal,0,10,4); Double_t norm = result->GetMaximum(); ftot->SetParameters(0.5*norm,5,.2,norm); ftot->SetParLimits(0,.3*norm,norm); result->Fit("ftot","b"); }
TF1 *langaufit(TH1F *his, Double_t *fitrange, Double_t *startvalues, Double_t *parlimitslo, Double_t *parlimitshi, Double_t *fitparams, Double_t *fiterrors, Double_t *ChiSqr, Int_t *NDF) { // Once again, here are the Landau * Gaussian parameters: // par[0]=Width (scale) parameter of Landau density // par[1]=Most Probable (MP, location) parameter of Landau density // par[2]=Total area (integral -inf to inf, normalization constant) // par[3]=Width (sigma) of convoluted Gaussian function // // Variables for langaufit call: // his histogram to fit // fitrange[2] lo and hi boundaries of fit range // startvalues[4] reasonable start values for the fit // parlimitslo[4] lower parameter limits // parlimitshi[4] upper parameter limits // fitparams[4] returns the final fit parameters // fiterrors[4] returns the final fit errors // ChiSqr returns the chi square // NDF returns ndf Int_t i; Char_t FunName[100]; sprintf(FunName,"Fitfcn_%s",his->GetName()); TF1 *ffitold = (TF1*)gROOT->GetListOfFunctions()->FindObject(FunName); if (ffitold) delete ffitold; TF1 *ffit = new TF1(FunName,langaufun,fitrange[0],fitrange[1],4); ffit->SetParameters(startvalues); ffit->SetParNames("Width","MP","Area","GSigma"); for (i=0; i<4; i++) { ffit->SetParLimits(i, parlimitslo[i], parlimitshi[i]); } his->Fit(FunName,"RB0"); // fit within specified range, use ParLimits, do not plot ffit->GetParameters(fitparams); // obtain fit parameters for (i=0; i<4; i++) { fiterrors[i] = ffit->GetParError(i); // obtain fit parameter errors } ChiSqr[0] = ffit->GetChisquare(); // obtain chi^2 NDF[0] = ffit->GetNDF(); // obtain ndf return (ffit); // return fit function }
TF1* GetFit(const char *run, const char *inname, const char *outname) { ifstream infit; infit.open( Form("%s/fit/%s.dat",run,inname) ); double tmp; bool found; infit >> alp >> tmp >> lda >> elda >> sgm >> esgm >> f2 >> tmp >> f3 >> tmp >> f4; infit.close(); cout << alp << endl; cout << lda << endl; cout << sgm << endl; cout << f2 << endl; cout << f3 << endl; cout << f4 << endl; double f1 = 1-f2-f3-f4; if(1-f2<0.01) return NULL; const char *la1 = Form("%f*TMath::Landau(x,1.00*%f*[0],1.0*%f*[1],1)",f1,lda,sgm); const char *la2 = Form("%f*TMath::Landau(x,2.14*%f*[0],2.0*%f*[1],1)",f2,lda,sgm); const char *la3 = Form("%f*TMath::Landau(x,3.33*%f*[0],3.0*%f*[1],1)",f3,lda,sgm); const char *la4 = Form("%f*TMath::Landau(x,4.55*%f*[0],4.0*%f*[1],1)",f4,lda,sgm); TF1 *ret = new TF1("fit_H1", Form("%f*(%s+%s+%s+%s)",alp,la1,la2,la3,la4) ); ret->SetParName(0,"sLDA"); ret->SetParName(1,"SSGM"); ret->SetParameter(0,1.0); ret->SetParLimits(0,1e-3,2.0); ret->SetParameter(1,1.0); ret->SetParLimits(1,1e-3,2.0); ret->SetLineColor(kRed-3); infit.open( Form("%s/fit/%s.dat",run,outname) ); tmp; found=false; for(int n=0; n!=ret->GetNpar(); ++n) { infit >> tmp; if(!infit.good()) break; ret->SetParameter(n,tmp); infit >> tmp; found = true; } infit.close(); if(found) { cout << " Previous fit results found" << endl; } cout << lda << endl; return ret; }
double GetV2(int itrg, int jass) { TH2D* hsignal = (TH2D*) gInputfile->Get(Form("%ssignal_trg%d_ass%d",subdir.Data(),itrg,jass)); TH1D* hsignalphi = (TH1D*)hsignal->ProjectionY(Form("signalphi_trg%d_ass%d",itrg,jass),-1,hsignal->GetXaxis()->FindBin(-1.0),"e"); hsignalphi->Scale(1.0/hsignalphi->Integral()); TH2D* hmulttrg = (TH2D*) gInputfile->Get(Form("%smult_trg_%d",subdir.Data(),itrg)); TH1D* hmulttrg_proj = (TH1D*)hmulttrg->ProjectionY(Form("mult_trg_proj_%d",itrg),-1,-1); float multtrg_mean = hmulttrg_proj->GetMean(); cout<<multtrg_mean<<endl; TF1* fitfunc = new TF1("fitfunc","1+2*[0]*TMath::Cos(2*x)",-PI/2.,3.*PI/2.); fitfunc->SetParameter(0,0.01); fitfunc->SetParLimits(0,0.0,1.0); hsignalphi->Fit(fitfunc,"RNO"); float V2=fitfunc->GetParameter(0)*(multtrg_mean-1); // float V2 = 0; // for(int i=1;i<=hsignalphi->GetNbinsX();i++) // V2 = V2 + TMath::Cos(2*hsignalphi->GetBinCenter(i))*hsignalphi->GetBinContent(i); //V2 = V2 / hsignalphi->Integral(); //* (multtrg_mean-1); return sqrt(V2); }
void vertexAssociationAnalysis(TH1* fraction, unsigned int index, double& slope,double& slopeError,double& constNorm,double& constError,TGraphErrors*& graph,TFitResultPtr fitRes) { // do the fit if(constrainSlope) { fraction->Fit("expo","LS","",xminfit[index],xmaxfit[index]); TF1* expo = (TF1*)gROOT->FindObjectAny("expo"); expo->FixParameter(1,contrainedSlopeParameters[0]+contrainedSlopeParameters[1]*(index+1)); fitRes = fraction->Fit("expo","LSB","",xminfit[index],xmaxfit[index]); expo->SetParLimits(1,-10000,10000); } else { // fitRes = fraction->Fit("expo","LS","",xminfit[index],xmaxfit[index]); fitRes = fraction->Fit("expo","LS","",getConstrainedMinimum(fraction,0.1,0.3),getConstrainedMaximum(fraction,0.7,0.9)); } // estimate efficiency and purity as a function of the cut double *efficiency, *purity, *efferror, *purerror; efficiency = new double[nSteps]; purity = new double[nSteps]; efferror = new double[nSteps]; purerror = new double[nSteps]; unsigned int step = 0; for(float cut=cutmin; cut<cutmax; cut += (cutmax-cutmin)/float(nSteps), ++step) { estimateEfficiencyAndPurity(fraction,cut,efficiency[step],purity[step],efferror[step],purerror[step],fitRes); } // output: the graph with efficiency and purity vs cut and the expo slope slope = fraction->GetFunction("expo")->GetParameter(1); slopeError = fraction->GetFunction("expo")->GetParError(1); constNorm = fraction->GetFunction("expo")->GetParameter(0); constError = fraction->GetFunction("expo")->GetParError(0); //slope = result->Parameter(1); graph = new TGraphErrors(nSteps,purity,efficiency,purerror,efferror); //graph = new TGraph(nSteps,purity,efficiency); delete[] efficiency; delete[] purity; delete[] efferror; delete[] purerror; }
TF1* gaussianFit(TH1* histoY, const TString & resonanceType){ TString name = histoY->GetName() + TString("Fit"); // Fit slices projected along Y from bins in X // ------------------------------------------- TF1 *fit = 0; // Set parameters according to the selected resonance if( resonanceType == "JPsi" ) { fit = new TF1(name,gaussian,2,4,3); fit->SetParLimits(2, 3.09, 3.15); } if( resonanceType.Contains("Upsilon") ) { fit = new TF1(name,gaussian,8.5,10.5,3); // fit = new TF1(name,gaussian,9,11,3); fit->SetParLimits(2, 9.2, 9.6); fit->SetParLimits(1, 0.09, 0.1); } if( resonanceType == "Z" ) { fit = new TF1(name,gaussian,80,100,3); fit->SetParLimits(2, 80, 100); fit->SetParLimits(1, 0.01, 1); } if( resonanceType == "reso" ) { fit = new TF1(name,gaussian,-0.05,0.05,3); fit->SetParLimits(2, -0.5, 0.5); fit->SetParLimits(1, 0, 0.5); } fit->SetParameters(histoY->GetMaximum(),histoY->GetRMS(),histoY->GetMean()); // fit->SetParLimits(1, 0.01, 1); // fit->SetParLimits(1, 40, 60); fit->SetParNames("norm","width","mean"); fit->SetLineWidth(2); if( histoY->GetNbinsX() > 1000 ) histoY->Rebin(10); histoY->Fit(name,"R0"); return fit; }
void massfitvn_Jpsi() { double fit_range_low = 2.6; double fit_range_high = 3.5; double JPsi_mass = 3.097; int npt = 7; TFile* file1 = TFile::Open("HM185_JpsivnHist_etagap1p5_v30_eff_extdeta.root"); TFile ofile("v2vspt_fromfit_jpsi_HM185_250_deta1p5_doubleCB_v30_eff_exp_extdeta.root","RECREATE"); //v12 double alpha_fit[14] = {4.30986,3.50841,3.03436,2.73741,2.37934,2.10685,2.03615}; double n_fit[14] = {1.88853,1.9839,2.03198,2.07295,2.11001,2.15234,2.10154}; TF1* fmasssig[9]; TF1* fmassbkg[9]; TF1* fmasstotal[9]; TF1* fvn[9]; double pt[13]; double KET_ncq[13]; double v2[13]; double v2e[13]; double v2_bkg[13]; double v2_ncq[13]; double v2e_ncq[13]; double ptbin[14] = {0.2, 1.8, 3.0, 4.5, 6.0, 8.0, 10, 20}; double a[13]; double b[13]; double sigfrac[13]; TCanvas* c[10]; for(int i=0;i<npt;i++) { c[i] = new TCanvas(Form("c_%d",i),Form("c_%d",i),800,400); c[i]->Divide(2,1); } for(int i=0;i<npt;i++) { c[i]->cd(1)->SetTopMargin(0.06); c[i]->cd(1)->SetLeftMargin(0.18); c[i]->cd(1)->SetRightMargin(0.043); c[i]->cd(1)->SetBottomMargin(0.145); c[i]->cd(2)->SetTopMargin(0.06); c[i]->cd(2)->SetLeftMargin(0.18); c[i]->cd(2)->SetRightMargin(0.043); c[i]->cd(2)->SetBottomMargin(0.145); } TCanvas* c2 = new TCanvas("c2","c2",100,100); TLatex* tex = new TLatex; tex->SetNDC(); tex->SetTextFont(42); tex->SetTextSize(0.045); tex->SetLineWidth(2); TLatex* texCMS = new TLatex; texCMS->SetNDC(); texCMS->SetTextFont(42); texCMS->SetTextSize(0.05); texCMS->SetTextAlign(12); TH1D* hist = new TH1D("hist","",10,2.6,3.5); hist->SetLineWidth(0); //hist->GetYaxis()->SetRangeUser(0,0.3); hist->GetXaxis()->SetTitle("#it{m}_{#mu#mu} (GeV)"); hist->GetYaxis()->SetTitle("v_{2}^{S+B}"); hist->GetXaxis()->CenterTitle(); hist->GetYaxis()->CenterTitle(); hist->GetXaxis()->SetTitleOffset(1.3); hist->GetYaxis()->SetTitleOffset(2); hist->GetXaxis()->SetLabelOffset(0.007); hist->GetYaxis()->SetLabelOffset(0.007); hist->GetXaxis()->SetTitleSize(0.045); hist->GetYaxis()->SetTitleSize(0.045); hist->GetXaxis()->SetTitleFont(42); hist->GetYaxis()->SetTitleFont(42); hist->GetXaxis()->SetLabelFont(42); hist->GetYaxis()->SetLabelFont(42); hist->GetXaxis()->SetLabelSize(0.04); hist->GetYaxis()->SetLabelSize(0.04); hist->SetMinimum(0.01); hist->SetMaximum(0.33); c2->cd(); hist->Draw(); for(int i=0;i<npt;i++) { TH1D* h_data = (TH1D*)file1->Get(Form("massjpsi_pt%d",i)); h_data->SetMinimum(0); h_data->SetMarkerSize(0.8); h_data->SetMarkerStyle(20); h_data->SetLineWidth(1); h_data->SetOption("e"); h_data->Rebin(2); h_data->GetXaxis()->SetRangeUser(2.6,3.5); h_data->GetXaxis()->SetTitle("#it{m}_{#mu#mu} (GeV)"); h_data->GetYaxis()->SetTitle("Entries / 10 MeV"); h_data->GetXaxis()->CenterTitle(); h_data->GetYaxis()->CenterTitle(); h_data->GetXaxis()->SetTitleOffset(1.3); h_data->GetYaxis()->SetTitleOffset(2); h_data->GetXaxis()->SetLabelOffset(0.007); h_data->GetYaxis()->SetLabelOffset(0.007); h_data->GetXaxis()->SetTitleSize(0.045); h_data->GetYaxis()->SetTitleSize(0.045); h_data->GetXaxis()->SetTitleFont(42); h_data->GetYaxis()->SetTitleFont(42); h_data->GetXaxis()->SetLabelFont(42); h_data->GetYaxis()->SetLabelFont(42); h_data->GetXaxis()->SetLabelSize(0.04); h_data->GetYaxis()->SetLabelSize(0.04); h_data->GetXaxis()->SetNoExponent(true); ((TGaxis*)h_data->GetXaxis())->SetMaxDigits(7); h_data->SetMaximum(h_data->GetMaximum()*1.5); TH1D* h_pt = (TH1D*)file1->Get(Form("Ptjpsi_eff_pt%d",i)); TH1D* h_KET = (TH1D*)file1->Get(Form("KETjpsi_eff_pt%d",i)); pt[i] = h_pt->GetMean(); KET_ncq[i] = h_KET->GetMean()/2.0; c[i]->cd(1); /*p definitions [0] CB1 yield; [1] Common mean of CB and Gaus; [2] CB1 sigma; [3] CB n; [4] CB alpha; [5] CB2 yield; [6] CB2 sigma; [7-10] poly 3; [11] v2 signal; [12-13] v2 bkg; */ TF1* f = new TF1(Form("f_%d",i), crystalball_function_total, fit_range_low, fit_range_high, 11); f->SetLineColor(2); f->SetLineWidth(1); f->SetParNames("CB1_Yield","common_mean","CB1_sigma","CB_N","CB_Alpha","CB2_Yield","CB2_Sigma","Pol0","Pol1","Pol2","Pol3"); //first fit data mass signal + bkg f->SetParameter(0,10000.); f->SetParameter(1,JPsi_mass); f->SetParameter(2,0.03); f->SetParameter(3,1.0); f->SetParameter(4,1.0); f->SetParameter(5,10000); f->SetParameter(6,0.03); f->SetParLimits(2,0.01,0.1); f->SetParLimits(6,0.01,0.1); //fix alpha & n from MC f->FixParameter(4,alpha_fit[i]); f->FixParameter(3,n_fit[i]); f->FixParameter(1,JPsi_mass); //for first few attempt fix mean of gaussian to get reasonable estimation of other pars; later open it up h_data->Fit(Form("f_%d",i),"q","",fit_range_low,fit_range_high); h_data->Fit(Form("f_%d",i),"q","",fit_range_low,fit_range_high); f->ReleaseParameter(1); //now let gaussian mean float h_data->Fit(Form("f_%d",i),"L q","",fit_range_low,fit_range_high); h_data->Fit(Form("f_%d",i),"L q","",fit_range_low,fit_range_high); h_data->Fit(Form("f_%d",i),"L m","",fit_range_low,fit_range_high); //draw D0 signal separately TF1* f1 = new TF1(Form("f_sig_%d",i), crystalball_function_signal, fit_range_low, fit_range_high, 7); f1->SetLineColor(kOrange-3); f1->SetLineWidth(1); f1->SetLineStyle(2); f1->SetFillColorAlpha(kOrange-3,0.3); f1->SetFillStyle(1001); f1->FixParameter(0,f->GetParameter(0)); f1->FixParameter(1,f->GetParameter(1)); f1->FixParameter(2,f->GetParameter(2)); f1->FixParameter(3,f->GetParameter(3)); f1->FixParameter(4,f->GetParameter(4)); f1->FixParameter(5,f->GetParameter(5)); f1->FixParameter(6,f->GetParameter(6)); fmasssig[i] = (TF1*)f1->Clone(); fmasssig[i]->SetName(Form("masssigfcn_pt%d",i)); fmasssig[i]->Write(); f1->Draw("LSAME"); //draw poly bkg separately TF1* f3 = new TF1(Form("f_bkg_%d",i),"[7] + [8]*x + [9]*x*x + [10]*x*x*x", fit_range_low, fit_range_high); f3->SetLineColor(4); f3->SetLineWidth(1); f3->SetLineStyle(2); f3->FixParameter(7,f->GetParameter(7)); f3->FixParameter(8,f->GetParameter(8)); f3->FixParameter(9,f->GetParameter(9)); f3->FixParameter(10,f->GetParameter(10)); fmassbkg[i] = (TF1*)f3->Clone(); fmassbkg[i]->SetName(Form("massbkgfcn_pt%d",i)); fmassbkg[i]->Write(); f3->Draw("LSAME"); tex->DrawLatex(0.22,0.86,"185 #leq N_{trk}^{offline} < 250"); tex->DrawLatex(0.22,0.80,Form("%.1f < p_{T} < %.1f GeV",ptbin[i],ptbin[i+1])); tex->DrawLatex(0.22,0.74,"-2.86 < y_{cm} < -1.86 or 0.94 < y_{cm} < 1.94"); texCMS->DrawLatex(.18,.97,"#font[61]{CMS} #it{Preliminary}"); //texCMS->DrawLatex(.18,.97,"#font[61]{CMS}"); texCMS->DrawLatex(0.73,0.97, "#scale[0.8]{pPb 8.16 TeV}"); TLegend* leg = new TLegend(0.21,0.4,0.5,0.65,NULL,"brNDC"); leg->SetBorderSize(0); leg->SetTextSize(0.045); leg->SetTextFont(42); leg->SetFillStyle(0); leg->AddEntry(h_data,"data","p"); leg->AddEntry(f,"Fit","L"); leg->AddEntry(f1,"J/#psi Signal","f"); leg->AddEntry(f3,"Combinatorial","l"); leg->Draw("SAME"); sigfrac[i] = f1->Integral(2.94,3.24)/f->Integral(2.94,3.24); //c->Print(Form("plots/massfit_pt%d.pdf",i)); //fit vn //[9] is vn_sig //[10-11] is vn bkg, const + linear vn(pT) TGraphErrors* vn_data = (TGraphErrors*)file1->Get(Form("v2_mass_pt%d",i)); c[i]->cd(2); hist->Draw(); TF1* fmass_combinemassvnfit = new TF1(Form("fmass_combinemassvnfit_%d",i),crystalball_function_total, fit_range_low, fit_range_high, 11); TF1* fvn_combinemassvnfit = new TF1(Form("fvn_combinemassvnfit_%d",i), crystalball_function_v2, fit_range_low, fit_range_high, 15); fmass_combinemassvnfit->SetLineColor(2); fmass_combinemassvnfit->SetLineWidth(1); fvn_combinemassvnfit->SetLineColor(2); fvn_combinemassvnfit->SetLineWidth(1); ROOT::Math::WrappedMultiTF1 wfmass_combinemassvnfit(*fmass_combinemassvnfit,1); ROOT::Math::WrappedMultiTF1 wfvn_combinemassvnfit(*fvn_combinemassvnfit,1); ROOT::Fit::DataOptions opt; ROOT::Fit::DataRange range_massfit; range_massfit.SetRange(fit_range_low,fit_range_high); ROOT::Fit::BinData datamass(opt,range_massfit); ROOT::Fit::FillData(datamass, h_data); ROOT::Fit::DataRange range_vnfit; range_vnfit.SetRange(fit_range_low,fit_range_high); ROOT::Fit::BinData datavn(opt,range_vnfit); ROOT::Fit::FillData(datavn, vn_data); ROOT::Fit::Chi2Function chi2_B(datamass, wfmass_combinemassvnfit); ROOT::Fit::Chi2Function chi2_SB(datavn, wfvn_combinemassvnfit); GlobalChi2_poly3bkg_floatwidth globalChi2(chi2_B, chi2_SB); ROOT::Fit::Fitter fitter; const int Npar = 15; double par0[Npar]; for( int ipar = 0; ipar < f->GetNpar(); ipar++ ) par0[ipar] = f->GetParameter(ipar); par0[11] = 0.01; par0[12] = 0.10; par0[13] = 0.05; par0[14] = 0.01; fitter.Config().SetParamsSettings(Npar,par0); // fix parameter fitter.Config().ParSettings(0).Fix(); fitter.Config().ParSettings(1).Fix(); fitter.Config().ParSettings(2).Fix(); fitter.Config().ParSettings(3).Fix(); fitter.Config().ParSettings(4).Fix(); fitter.Config().ParSettings(5).Fix(); fitter.Config().ParSettings(6).Fix(); fitter.Config().ParSettings(7).Fix(); fitter.Config().ParSettings(8).Fix(); fitter.Config().ParSettings(9).Fix(); fitter.Config().ParSettings(10).Fix(); fitter.Config().MinimizerOptions().SetPrintLevel(0); fitter.Config().SetMinimizer("Minuit2","Migrad"); fitter.FitFCN(Npar,globalChi2,0,datamass.Size()+datavn.Size(),true); ROOT::Fit::FitResult result = fitter.Result(); result.Print(std::cout); fmass_combinemassvnfit->SetFitResult( result, iparmassfit_poly3bkg_floatwidth); fmass_combinemassvnfit->SetRange(range_massfit().first, range_massfit().second); fmass_combinemassvnfit->SetLineColor(kRed); h_data->GetListOfFunctions()->Add(fmass_combinemassvnfit); //c->cd(); //h_data->Draw(); fvn_combinemassvnfit->SetFitResult( result, iparvnfit_poly3bkg_floatwidth); fvn_combinemassvnfit->SetRange(range_vnfit().first, range_vnfit().second); fvn_combinemassvnfit->SetLineColor(2); //fvn_combinemassvnfit->SetLineStyle(2); vn_data->GetListOfFunctions()->Add(fvn_combinemassvnfit); vn_data->SetTitle(""); vn_data->SetMarkerSize(0.8); vn_data->SetLineWidth(1); //c1->cd(); vn_data->Draw("PESAME"); fvn[i] = (TF1*)fvn_combinemassvnfit->Clone(); fvn[i]->SetName(Form("vnfit_pt%d",i)); fvn[i]->Write(); fmasstotal[i] = (TF1*)fmass_combinemassvnfit->Clone(); fmasstotal[i]->SetName(Form("masstotalfcn_pt%d",i)); fmasstotal[i]->Write(); tex->DrawLatex(0.22,0.86,"185 #leq N_{trk}^{offline} < 250"); tex->DrawLatex(0.22,0.80,Form("%.1f < p_{T} < %.1f GeV",ptbin[i],ptbin[i+1])); //tex->DrawLatex(0.22,0.74,"1.4 < |y_{cm}+0.46| < 2.4"); tex->DrawLatex(0.22,0.74,"-2.86 < y_{cm} < -1.86 or 0.94 < y_{cm} < 1.94"); //tex->DrawLatex(0.22,0.68,"|#Delta#eta| > 2"); //texCMS->DrawLatex(.18,.97,"#font[61]{CMS}"); texCMS->DrawLatex(.18,.97,"#font[61]{CMS} #it{Preliminary}"); texCMS->DrawLatex(0.73,0.97, "#scale[0.8]{pPb 8.16 TeV}"); v2[i] = fvn_combinemassvnfit->GetParameter(11); v2e[i] = fvn_combinemassvnfit->GetParError(11); v2_bkg[i] = fvn_combinemassvnfit->GetParameter(12) + fvn_combinemassvnfit->GetParameter(13) * JPsi_mass; v2_ncq[i] = v2[i]/2.0; v2e_ncq[i] = v2e[i]/2.0; a[i] = fvn_combinemassvnfit->GetParameter(12); b[i] = fvn_combinemassvnfit->GetParameter(13); TF1* fvnbkg = new TF1(Form("fvnbkg_%d",1),"( [0] + [1] * x)", fit_range_low, fit_range_high); fvnbkg->FixParameter(0,fvn_combinemassvnfit->GetParameter(12)); fvnbkg->FixParameter(1,fvn_combinemassvnfit->GetParameter(13)); fvnbkg->SetName(Form("fvnbkg_fcn_pt%d",i)); fvnbkg->Write(); fvnbkg->SetLineStyle(7); //fvnbkg->Draw("LSAME"); TF1* fvnsig = new TF1(Form("fvnsig_%d",i),function_v2_sig,fit_range_low,fit_range_high,12); for(int k=0;k<12;k++) { fvnsig->FixParameter(k,fvn_combinemassvnfit->GetParameter(k)); } fvnsig->SetLineColor(kOrange-3); fvnsig->SetLineWidth(1); fvnsig->SetLineStyle(2); fvnsig->SetFillColorAlpha(kOrange-3,0.3); fvnsig->SetFillStyle(1001); //fvnsig->Draw("LSAME"); TLegend* leg1 = new TLegend(0.72,0.525,0.91,0.65,NULL,"brNDC"); leg1->SetBorderSize(0); leg1->SetTextSize(0.045); leg1->SetTextFont(42); leg1->SetFillStyle(0); leg1->AddEntry(h_data,"data","p"); leg1->AddEntry(fvn_combinemassvnfit,"Fit","l"); //leg1->AddEntry(fvnsig,"#alpha(#it{m}_{#mu#mu})v_{2}^{S}","f"); leg1->Draw("SAME"); double xmass[200]; double pullmass[200]; float Chi2=0; int ndf = (fit_range_high - fit_range_low)/0.01 - 8; for(int k=0;k<h_data->GetNbinsX();k++) { xmass[k] = h_data->GetBinCenter(k); pullmass[k] = (h_data->GetBinContent(k) - fmass_combinemassvnfit->Eval(xmass[k]))/h_data->GetBinError(k); if(fabs(pullmass[k])<5) { //cout<<pullmass[k]<<endl; Chi2 += pullmass[k]*pullmass[k]; } } c[i]->cd(1); tex->DrawLatex(0.22,0.67,Form("#chi^{2}/ndf = %.0f/%d",Chi2,ndf)); double xv2[200]; double pullv2[200]; double v2y[200]; float Chi2v2=0; int ndfv2 = 8 - 4; //Nbin - Npar for(int k=0;k<vn_data->GetN()-1;k++) { vn_data->GetPoint(k,xv2[k],v2y[k]); //xv2[k] = vn_dara->GetBinCenter(k); pullv2[k] = (v2y[k] - fvn_combinemassvnfit->Eval(xv2[k]))/vn_data->GetErrorY(k); cout<<k<<": "<<pullv2[k]<<endl; if(fabs(pullv2[k])<1000) { //cout<<pullmass[k]<<endl; Chi2v2 += pullv2[k]*pullv2[k]; } cout<<"fcn: "<<fvn_combinemassvnfit->Eval(xv2[k])<<endl; cout<<"data: "<<v2y[k]<<endl; } c[i]->cd(2); tex->DrawLatex(0.22,0.67,Form("#chi^{2}/ndf = %.1f/%d",Chi2v2,ndfv2)); } for(int i=0;i<npt;i++) { c[i]->Print(Form("plots/v30/eff/exp/JPsi_mass_vnfit_combine_pt%d.pdf",i)); c[i]->Print(Form("plots/v30/eff/exp/JPsi_mass_vnfit_combine_pt%d.gif",i)); } TGraphErrors* v2plot = new TGraphErrors(npt,pt,v2,0,v2e); TGraphErrors* v2ncqplot = new TGraphErrors(npt,KET_ncq,v2_ncq,0,v2e_ncq); TGraphErrors* v2bkgplot = new TGraphErrors(npt,pt,v2_bkg,0,0); v2plot->SetName("v2vspt"); v2ncqplot->SetName("v2vsKET_ncq"); v2bkgplot->SetName("v2bkgvspt"); v2plot->Write(); v2ncqplot->Write(); v2bkgplot->Write(); }
void SPEFit(char * fLEDname, char * fPEDname, int run, int LED_amp, double cutmax = 250.0) { //set plotting styles gStyle->SetCanvasColor(0); gStyle->SetPadColor(0); gStyle->SetCanvasBorderMode(0); gStyle->SetFrameBorderMode(0); gStyle->SetStatColor(0); gStyle->SetPadTickX(1); gStyle->SetPadTickY(1); //set file names stringstream out_fname; stringstream out_fname1; out_fname<<"SPEconstants_Run_"<<run<<".txt"; out_fname1<<"SPEspec_Run_"<<run<<".txt"; ofstream constants_file(out_fname.str().c_str(),ios_base::trunc); //ofstream constants_file1(out_fname1.str().c_str(),ios_base::trunc); constants_file<<"Run "<<run<<endl; constants_file<<"type SPE"<<endl; constants_file<<"LED_amplitude "<<LED_amp<<endl<<endl; constants_file<<endl<<"LED_amplitude Depth Phi Eta Ped_mean Ped_mean_err Ped_RMS Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl; out_fname.str(""); out_fname<<"SPEdistributions_Run_"<<run<<".txt"; out_fname.str(""); out_fname<<"SPEextra_Run_"<<run<<".txt"; //ofstream extra_file(out_fname.str().c_str(),ios_base::trunc); double scale = 1.0; scale = 2.6; //Need to scale up HF charge double fC2electrons = 6240.; //convert fC to #electrons char spename[128], pedname[128], spehistname[128]; TFile *tfLED = new TFile(fLEDname); TFile *tfPED = new TFile(fPEDname); //const int NnewBins = 106; //double binsX[NnewBins] = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500}; const int NnewBins = 80; double binsX[NnewBins] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,114,117,120,123,126,129,132,135,138,141,144,147,150,153,156,159,162,165,168,171,174,177,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500}; TH1F* hspe = new TH1F("hspe","hspe",NnewBins-1,binsX); int NDepth = 2; //number of depths int MinDepth = 1; int MaxDepth = 2; int MinEta = 29; int MaxEta = 41; int MinPhi = 41; int MaxPhi = 53; TCanvas *Carray[NDepth+1][MaxPhi+1]; bool drawflag[NDepth+1][MaxPhi+1]; TH1F *LED[NDepth+1][MaxEta+1][MaxPhi+1]; TH1F *PED[NDepth+1][MaxEta+1][MaxPhi+1]; for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){ for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){ bool nonNull = false; for(int iEta = MinEta; iEta <= MaxEta; iEta++){ sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi); LED[iDepth][iEta][iPhi]=(TH1F *)tfLED->Get(spename); if(LED[iDepth][iEta][iPhi]) nonNull = true; sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi); PED[iDepth][iEta][iPhi]=(TH1F *)tfPED->Get(spename); } drawflag[iDepth][iPhi] = false; char canvname[16]; sprintf(canvname, "c_%d_%d", iDepth,iPhi); if(nonNull){ //only create canvas if distributions exist Carray[iDepth][iPhi] = new TCanvas(canvname,canvname,1200,700); Carray[iDepth][iPhi]->Divide(5,3); } } } int HV=0; for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){ for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){ for(int iEta = MinEta; iEta <= MaxEta; iEta++){ //cout<<iDepth<<" "<<iPhi<<" "<<iEta<<endl; if(!LED[iDepth][iEta][iPhi]) continue; sprintf(spehistname,"led %d %d %d",iDepth,iEta,iPhi); TH1F *hspe_temp = (TH1F *)LED[iDepth][iEta][iPhi]->Clone(spehistname); sprintf(spehistname,"ped %d %d %d",iDepth,iEta,iPhi); TH1F *hped = (TH1F *)PED[iDepth][iEta][iPhi]->Clone(spehistname); hspe->Reset(); sprintf (spehistname, "SumLED_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi); hspe->SetTitle(spehistname); //combine bins of original SPE histogram for(int ib=1; ib<=hspe_temp->GetNbinsX(); ib++) { double bin_center = hspe_temp->GetBinCenter(ib); if(bin_center>hspe->GetXaxis()->GetXmax()) continue; int newbin = hspe->FindBin(bin_center); double new_content = hspe->GetBinContent(newbin) + hspe_temp->GetBinContent(ib); double new_error = sqrt(pow(hspe->GetBinError(newbin),2)+pow(hspe_temp->GetBinError(ib),2)); hspe->SetBinContent(newbin,new_content); hspe->SetBinError(newbin,new_error); } TH1F* hspe_unscaled = (TH1F*)hspe->Clone("hspe_unscaled"); //renormalize bins of new SPE histogram for(int ib=1; ib<=hspe->GetNbinsX(); ib++) { double new_content = hspe->GetBinContent(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1); double new_error = hspe->GetBinError(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1); hspe->SetBinContent(ib,new_content); hspe->SetBinError(ib,new_error); } if(hspe_temp->Integral()==0) continue; else drawflag[iDepth][iPhi] = true; Nev = hspe_temp->Integral()*hspe_temp->GetXaxis()->GetBinWidth(1); TF1 *fped = new TF1("fped","gaus",0, 80); hped->Fit(fped,"NQR"); double pploc = fped->GetParameter(1), ppwidth = fped->GetParameter(2); hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + ppwidth); //estimate SPE peak location int max_SPE_bin, maxbin, Nbins; double max_SPE_height=0, minheight, max_SPE_location; bool minflag = false; maxbin=hspe->FindBin(fped->GetParameter(1)); //location of pedestal peak minheight=hspe->GetBinContent(maxbin); //initialize minheight Nbins = hspe->GetNbinsX(); for(int j=maxbin+1; j<Nbins-1; j++) { //start from pedestal peak and loop through bins if(hspe->GetBinContent(j) > minheight && !minflag) minflag=true; //only look for SPE peak when minflag=true if(hspe->GetBinContent(j) < minheight ) minheight = hspe->GetBinContent(j); if(minflag && hspe->GetBinContent(j) > max_SPE_height){ max_SPE_bin = j; max_SPE_location = hspe->GetBinCenter(max_SPE_bin); max_SPE_height = hspe->GetBinContent(j); } } //start from pedestal peak and loop through bins //find minimum bin between pedestal and SPE peaks hspe->GetXaxis()->SetRange(maxbin,max_SPE_bin); int minbin = hspe->GetMinimumBin(); double minbin_location = hspe->GetBinCenter(minbin); hspe->GetXaxis()->SetRange(1,Nbins); TF1 *fit = new TF1("fit", FitFun, 0, 500, 5); double mu = - log(fped->Integral(0,100)/Nev); if(mu<0) mu=0.01; double gain_est = max_SPE_location-1.0*fped->GetParameter(1); if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, 20, 1, gain_est, gain_est*0.5); else fit->SetParameters(mu, 20, 1, 2.1*fped->GetParameter(2), 10); //case of no clear minimum; start looking for SPE peak at 2sigma away from pedestal peak fit->SetParLimits(0, 0, 10); fit->FixParameter(1, fped->GetParameter(1)); fit->FixParameter(2, fped->GetParameter(2)); fit->SetParLimits(3, fped->GetParameter(2)*2, 350); fit->SetParLimits(4, fped->GetParameter(2)*1.01, 250); double maxfitrange = 500.; double minfitrange = 0.; hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange); maxfitrange = fped->GetParameter(1)+4*fit->GetParameter(3)+fit->GetParameter(4); if(500<maxfitrange) maxfitrange = 500; hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange); //calculate NDOF of fit excluding bins with 0 entries int myNDOF=-3; //three free parameters for(int j=hspe->FindBin(minfitrange); j<=hspe->FindBin(maxfitrange); j++) { //loop through fitted spe bins if(hspe->GetBinContent(j)) myNDOF++; } //loop through fitted spe bins //calculate means and integrals of the fit and data double fint, fint_error, hint, favg, havg; int temp_lowbin, temp_highbin; temp_lowbin = hspe->FindBin(minfitrange); temp_highbin = hspe->FindBin(maxfitrange); hspe_unscaled->GetXaxis()->SetRangeUser(minfitrange, maxfitrange); havg = hspe_unscaled->GetMean(); hint = hspe->Integral(temp_lowbin,temp_highbin,"width"); double min_frange = hspe->GetBinLowEdge(temp_lowbin); favg = fit->Mean(min_frange, maxfitrange); fint = fit->Integral(min_frange, maxfitrange); //fint_error = fit->IntegralError(min_frange, maxfitrange); double PE5int = 0; //integral of events with >=5 PE double PE5loc = fped->GetParameter(1)+ 5*fit->GetParameter(3); if(PE5loc>500) PE5int = 0; else { int PE5bin = hspe_temp->FindBin(PE5loc); temp_highbin = hspe_temp->FindBin(maxfitrange)-1; PE5int = hspe_temp->Integral(PE5bin,temp_highbin,"width"); } int PE5flag = 0; if(PE5int/hint>0.05) PE5flag = 1; //set flag if more than 5% of events in the fit correspond to >=5PE //========================================= //for(int i1=1;i1<hspe->GetNbinsX();i1++){ //constants_file1<<HV<<"\t"<<iDepth<<"\t"<<iEta<<"\t"<<iPhi<<"\t"<<2.6*hspe->GetBinCenter(i1)<<"\t"<<hspe->GetBinContent(i1)<<"\t"<<fit->Eval(hspe->GetBinCenter(i1))<<"\n"; //} //========================================= //printf("%d\n",myNDOF); //output calibrations constants //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl; constants_file<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl; /* if(iDepth==2 && iPhi==53 && iEta==36){ cout<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<gain_est<<" "<<fit->GetParameter(3)<<endl; cout<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl; } */ Carray[iDepth][iPhi]->cd(iEta-MinEta+1); gPad->SetBorderMode(0); gPad->SetBorderSize(0); gPad->SetRightMargin(0.01); gPad->SetBottomMargin(0.1); gPad->SetLogy(true); hspe->GetXaxis()->SetRangeUser(0, 200 /*300*//*508*/); hspe->SetLineColor(kBlue); hspe->DrawClone("hist"); fit->SetLineWidth(2); fit->Draw("same"); } if(drawflag[iDepth][iPhi]) { //draw plots of fit if data for the HV is present stringstream plot_name; plot_name<<"Plots/SPEFits_Run_"<<run<<"_Depth"<<iDepth<<"_Phi"<<iPhi<<".pdf"; Carray[iDepth][iPhi]->SaveAs(plot_name.str().c_str()); plot_name.str( std::string() ); } } } constants_file.close(); //constants_file1.close(); }