void multifit() { const Int_t np = 49; Float_t x[np] = {1.913521, 1.953769, 2.347435, 2.883654, 3.493567, 4.047560, 4.337210, 4.364347, 4.563004, 5.054247, 5.194183, 5.380521, 5.303213, 5.384578, 5.563983, 5.728500, 5.685752, 5.080029, 4.251809, 3.372246, 2.207432, 1.227541, 0.8597788,0.8220503,0.8046592, 0.7684097,0.7469761,0.8019787,0.8362375,0.8744895, 0.9143721,0.9462768,0.9285364,0.8954604,0.8410891, 0.7853871,0.7100883,0.6938808,0.7363682,0.7032954, 0.6029015,0.5600163,0.7477068,1.188785, 1.938228, 2.602717, 3.472962, 4.465014, 5.177035}; TH1F *h = new TH1F("h","Example of several fits in subranges",np,85,134); h->SetMaximum(7); for (int i=0;i<np;i++) { h->SetBinContent(i+1,x[i]); } Double_t par[9]; TF1 *g1 = new TF1("g1","gaus",85,95); TF1 *g2 = new TF1("g2","gaus",98,108); TF1 *g3 = new TF1("g3","gaus",110,121); TF1 *total = new TF1("total","gaus(0)+gaus(3)+gaus(6)",85,125); total->SetLineColor(2); h->Fit(g1,"R"); h->Fit(g2,"R+"); h->Fit(g3,"R+"); g1->GetParameters(&par[0]); g2->GetParameters(&par[3]); g3->GetParameters(&par[6]); total->SetParameters(par); h->Fit(total,"R+"); }
void EtaMinv(Char_t* Spect) { TH1F* Hist = gROOT->FindObject(Spect); Double_t par[5]; TF1* f2 = new TF1("f2", "expo", 200, 700); TF1* f3 = new TF1("f3", "gaus", 500, 600); f2->SetLineWidth(1); f2->SetLineColor(8); Hist->Fit(f2,"R0"); f3->SetLineWidth(1); f3->SetLineColor(6); Hist->Fit(f3,"R0+"); TF1 *to= new TF1("to", "expo(0)+gaus(2)", 200, 700); f2->GetParameters(&par[0]); f3->GetParameters(&par[2]); to->SetParameters(par); to->SetLineWidth(2); to->SetLineColor(2); Hist->Fit(to,"R+"); }
double Alignment::Fit(TH1F &beta){ double xmin=beta.GetXaxis()->GetXmin(); double xmax=beta.GetXaxis()->GetXmax(); double prev_norma=-1; double norma,mean,sigma; for(int i=0;i<10;i++){ if(xmin>beta.GetXaxis()->GetXmax() || xmax<beta.GetXaxis()->GetXmin() || xmin>=xmax) return 0; // Fail // beta.Fit("gaus","0q","",xmin,xmax); beta.Fit("gaus","0q","",xmin,xmax); TF1 *func=beta.GetFunction("gaus"); norma=func->GetParameter(0); mean=func->GetParameter(1); sigma=fabs(func->GetParameter(2)); xmin=mean-1.0*sigma; xmax=mean+2.0*sigma; if(fabs(norma-prev_norma)<1e-3) break; prev_norma=norma; } return -norma; // This have to be minimized }
TF1 * iterateFitter(TH1F * histo, int i, TF1 * previousResiduals = 0, TCanvas * inputCanvas = 0) { TCanvas * canvas = inputCanvas; std::stringstream ss; int iCanvas = i; ss << i; int nBins = histo->GetNbinsX(); TF1 * functionToFit; if( previousResiduals == 0 ) { // functionToFit = relativisticBWFit(ss.str()); // functionToFit = relativisticBWintFit(ss.str()); // functionToFit = relativisticBWintPhotFit(ss.str()); functionToFit = expRelativisticBWintPhotFit(ss.str()); // functionToFit = crystalBallFit(); // functionToFit = reversedCrystalBallFit(); // functionToFit = lorentzianFit(); // functionToFit = relativisticBWFit(); } else { functionToFit = combinedFit(previousResiduals->GetParameters(), ss.str()); } histo->Fit(functionToFit, "MN", "", 60, 120); double xMin = histo->GetXaxis()->GetXmin(); double xMax = histo->GetXaxis()->GetXmax(); double step = (xMax-xMin)/(double(nBins)); TH1F * functionHisto = new TH1F(("functionHisto"+ss.str()).c_str(), "functionHisto", nBins, xMin, xMax); for( int i=0; i<nBins; ++i ) { functionHisto->SetBinContent( i+1, functionToFit->Eval(xMin + (i+0.5)*step) ); } if( canvas == 0 ) { canvas = new TCanvas(("canvasResiduals"+ss.str()).c_str(), ("canvasResiduals"+ss.str()).c_str(), 1000, 800); canvas->Divide(2,1); canvas->Draw(); iCanvas = 0; } canvas->cd(1+2*iCanvas); histo->Draw(); functionToFit->SetLineColor(kRed); functionToFit->Draw("same"); // functionHisto->Draw("same"); // functionHisto->SetLineColor(kGreen); canvas->cd(2+2*iCanvas); TH1F * residuals = (TH1F*)histo->Clone(); residuals->Add(functionHisto, -1); residuals->SetName("Residuals"); // TF1 * residualFit = new TF1("residualFit", "-[0] + [1]*x+sqrt( ([1]-1)*([1]-1)*x*x + [0]*[0] )", 0., 1000. ); // TF1 * residualFit = new TF1("residualFit", "[0]*(x - [1])/([2]*x*x + [3]*x + [4])", 0., 1000. ); TF1 * residualFitFunction = residualFit(ss.str()); residuals->Fit(residualFitFunction, "ME", "", 90.56, 120); residuals->Draw(); return residualFitFunction; }
void fitcont() { //be sure default is Minuit since we will use gMinuit TVirtualFitter::SetDefaultFitter("Minuit"); TCanvas *c1 = new TCanvas("c1"); TH1F *h = new TH1F("h","My histogram",100,-3,3); h->FillRandom("gaus",6000); h->Fit("gaus"); c1->Update(); TCanvas *c2 = new TCanvas("c2","contours",10,10,600,800); c2->Divide(1,2); c2->cd(1); /*get first contour for parameter 1 versus parameter 2*/ TGraph *gr12 = (TGraph*)gMinuit->Contour(40,1,2); gr12->Draw("alp"); c2->cd(2); /*Get contour for parameter 0 versus parameter 2 for ERRDEF=2*/ gMinuit->SetErrorDef(4); //note 4 and not 2! TGraph *gr2 = (TGraph*)gMinuit->Contour(80,0,2); gr2->SetFillColor(42); gr2->Draw("alf"); /*Get contour for parameter 0 versus parameter 2 for ERRDEF=1*/ gMinuit->SetErrorDef(1); TGraph *gr1 = (TGraph*)gMinuit->Contour(80,0,2); gr1->SetFillColor(38); gr1->Draw("lf"); }
void plotMuFromToys(std::string inputFile, std::string selectString="fit_status==0"){ // Some Global preferences gROOT->SetStyle("Plain"); gSystem->Load("$CMSSW_BASE/lib/$SCRAM_ARCH/libHiggsAnalysisCombinedLimit.so"); gStyle->SetOptFit(1111); gStyle->SetOptStat(1111); gStyle->SetPalette(1,0); TFile *fi_ = TFile::Open(inputFile.c_str()); TTree *tree_sb = (TTree*) fi_->Get("tree_fit_sb"); TH1F *mures = new TH1F("mures","",25,-2.,2.); mures->SetLineColor(kBlue+3); mures->SetMarkerStyle(kOpenCircle); mures->SetLineWidth(2); mures->GetXaxis()->SetTitle("#mu - 1"); mures->GetYaxis()->SetTitle(Form("no toys (%d total)",int(tree_sb->GetEntries()))); mures->GetYaxis()->SetTitleOffset(1.05); mures->GetXaxis()->SetTitleOffset(0.9); mures->GetYaxis()->SetTitleSize(0.05); mures->GetXaxis()->SetTitleSize(0.05); TCanvas *c = new TCanvas("c","",960,800); tree_sb->Draw("mu>>mures",selectString.c_str()); mures->Fit("gaus"); mures->GetFunction("gaus")->SetLineColor(kCyan+3); mures->Draw("pe1"); c->SaveAs("mlfit/mu_residual.pdf"); }
void myfit() { TString dir = gSystem->UnixPathName(__FILE__); dir.ReplaceAll("myfit.C","../hsimple.C"); dir.ReplaceAll("/./","/"); if (!gInterpreter->IsLoaded(dir.Data())) gInterpreter->LoadMacro(dir.Data()); TFile *hsimple = (TFile*)gROOT->ProcessLineFast("hsimple(1)"); if (!hsimple) return; TCanvas *c1 = new TCanvas("c1","the fit canvas",500,400); TH1F *hpx = (TH1F*)hsimple->Get("hpx"); // Creates a Root function based on function fitf above TF1 *func = new TF1("fitf",fitf,-2,2,3); // Sets initial values and parameter names func->SetParameters(100,0,1); func->SetParNames("Constant","Mean_value","Sigma"); // Fit histogram in range defined by function hpx->Fit(func,"r"); // Gets integral of function between fit limits printf("Integral of function = %g\n",func->Integral(-2,2)); }
vector<double> one_fit(bool do_fit) { TH1F* h = new TH1F("h","h", 20, -10, 10); h->FillRandom("gaus"); vector<double> ret; if (do_fit) { h->Fit("gaus",""); TF1* g = h->GetFunction("gaus"); h->Draw(); canvas->Modified(); canvas->Update(); for (int ind=0; ind < 3; ++ind) { ret.push_back(g->GetParameter(ind)); } } else { for (int ind=0; ind < 3; ++ind) { ret.push_back(0.0); } } ret.push_back(h->GetMean()); ret.push_back(h->GetRMS()); delete h; return ret; }
void ThrowPSEME(int me_i, bool use_old=false){ // ==================================================== // Create a fit // ==================================================== TF1 *ftot = new TF1("fitFunction",fitFunction,-100,0,2); //threw one data PSE and fill it if (use_old){ cout<<"OLD"<<endl; siggnal = MEWH_old[me_i]; background = MEWBB_old[me_i]; }else{ cout<<"NEW"<<endl; siggnal = MEWH[me_i]; background = MEWBB[me_i]; } TH1F * Err = new TH1F("Err","Err",1000,0,1); for (int pse=0;pse<100;pse++){ //Get one PSE TH1F * data = MakeOnePSE(siggnal,1000,background,2000); //fit it data->Fit("fitFunction","b"); Err->Fill(ftot->GetParError(1)); delete data; } Err->Draw(); }//ThrowPSEME
void peaks(Int_t np=10) { npeaks = TMath::Abs(np); TH1F *h = new TH1F("h","test",500,0,1000); //generate n peaks at random Double_t par[3000]; par[0] = 0.8; par[1] = -0.6/1000; Int_t p; for (p=0;p<npeaks;p++) { par[3*p+2] = 1; par[3*p+3] = 10+gRandom->Rndm()*980; par[3*p+4] = 3+2*gRandom->Rndm(); } TF1 *f = new TF1("f",fpeaks,0,1000,2+3*npeaks); f->SetNpx(1000); f->SetParameters(par); TCanvas *c1 = new TCanvas("c1","c1",10,10,1000,900); c1->Divide(1,2); c1->cd(1); h->FillRandom("f",200000); h->Draw(); TH1F *h2 = (TH1F*)h->Clone("h2"); //Use TSpectrum to find the peak candidates TSpectrum *s = new TSpectrum(2*npeaks); Int_t nfound = s->Search(h,2,"",0.10); printf("Found %d candidate peaks to fit\n",nfound); //Estimate background using TSpectrum::Background TH1 *hb = s->Background(h,20,"same"); if (hb) c1->Update(); if (np <0) return; //estimate linear background using a fitting method c1->cd(2); TF1 *fline = new TF1("fline","pol1",0,1000); h->Fit("fline","qn"); //Loop on all found peaks. Eliminate peaks at the background level par[0] = fline->GetParameter(0); par[1] = fline->GetParameter(1); npeaks = 0; Double_t *xpeaks = s->GetPositionX(); for (p=0;p<nfound;p++) { Double_t xp = xpeaks[p]; Int_t bin = h->GetXaxis()->FindBin(xp); Double_t yp = h->GetBinContent(bin); if (yp-TMath::Sqrt(yp) < fline->Eval(xp)) continue; par[3*npeaks+2] = yp; par[3*npeaks+3] = xp; par[3*npeaks+4] = 3; npeaks++; } printf("Found %d useful peaks to fit\n",npeaks); printf("Now fitting: Be patient\n"); TF1 *fit = new TF1("fit",fpeaks,0,1000,2+3*npeaks); //we may have more than the default 25 parameters TVirtualFitter::Fitter(h2,10+3*npeaks); fit->SetParameters(par); fit->SetNpx(1000); h2->Fit("fit"); }
void Fit::process(const string &output_file) { file = new TFile(output_file.c_str(), "RECREATE"); TF1 *f1 = new TF1("f1", "gaus", fit_start, fit_end); hist->Fit("f1", "R"); file->cd(); hist->Write(); file->Close(); }
void fit(const string &input_file) { TChain *chain = new TChain("SmearEnergy"); chain->Add(input_file.c_str()); TH1F *h = new TH1F("energy", "Energy", 500, 0, 70); chain->Draw("smearEnergy>>energy", "smearEnergy>0"); TF1 *g1 = new TF1("g1", "gaus", 4, 12); TF1 *g2 = new TF1("g2", "gaus", 14, 32); TF1 *g3 = new TF1("g3", "gaus", 36, 54); g1->SetLineColor(2); g2->SetLineColor(3); g3->SetLineColor(4); h->Fit(g1, "R"); cout << "Integral(4,12): " << g1->Integral(4, 12) << endl; h->Fit(g2, "R+"); cout << "Integral(14,32): " << g2->Integral(14, 32) << endl; h->Fit(g3, "R+"); cout << "Integral(36,54): " << g3->Integral(36, 54) << endl; }
void proton_pion(){ r = new TRandom(); TCanvas *c1 = new TCanvas(); TH1F *Epion = new TH1F("Epion", "Epion", 100, 0, 140); TH1F *Npion = new TH1F("Npion", "Npion", 100, 0, 50); for (int i = 0; i < 100000; ++i) { double E_init_proton = 1000; // GeV double E_proton; double E_init_pion; twosplit(E_init_proton, E_proton, E_init_pion); double pion_branch[n_branches]; Nsplit(E_init_pion, pion_branch, n_branches); int n_pion = 0; for (int i = 0; i < n_branches; ++i) { double energy_in = pion_branch[i]; while(energy_in > 0){ double E_a, E_b; twosplit(energy_in, E_a, E_b); double pion_E = E_a + M_pion; Epion->Fill(pion_E); energy_in = E_b - M_pion; if (energy_in>0) { n_pion++; } // double frac = r->Rndm(); // double A = E_init_pion*frac; // pizza_mass = pizza_mass*(1-frac)-tax; // n_pis++; // h1->Fill(A); } } Npion->Fill(n_pion); } c1->Divide(2,1); c1->cd(1); Epion->Draw(); c1->cd(2); Npion->Draw(); Npion->Fit("gaus"); }
void fitCauchy() { TCanvas * c1 = new TCanvas("mycan","mycan",800,600); TFile * data = new TFile("~/unpacker/sort.root"); fstream file1; file1.open("gaus3.par"); TH1F * dist = (TH1F*)data->Get("/corr/Li7/Li7_theta_reactCoM_12C")->Clone("1"); Double_t fparams[9] = {6.,1.,12.,1.,18.,1.,20000,15000,10000}; TF1 * f = new TF1("f",Cauchy3,0,180,9); TF1 * f2 = new TF1("f2",Gaus3,0,180,9); f2->SetParameters(fparams); f->SetParameters(fparams); dist->Fit("f2","M0"); dist->Draw(); f2->Draw("same"); if(file1.is_open()) cout <<"file1 is open" << endl; else cout << "failed to load file1" << endl; for(int i=0;i<9;i++) { file1 << f2->GetParameter(i) << endl; } TCanvas * c2 = new TCanvas("mycan2","mycan2",800,600); TH1F * check = new TH1F("check","",125,0,40); for(int i =0;i<300000;i++) { float r = f2->GetRandom(); check->Fill(r); } check->Draw(); Double_t par[9]; // for(int i=0;i<9;i++) //{ // file1 >> par[i] >> endl; // cout << "par[" << i << "] = " << par[i] << endl; //} //cout << "what" << endl; //file1.close(); return; }
void ZVXT1HF0() { NCanvas(1,1,"data"); NCanvas(1,1,"ratio"); TH1F * HDatHF0; TH1F * HDat; TFile *fzee = new TFile("ZDiffOutputfile_DataOnly_2010_2011.root"); // TFile *fzee = new TFile("ZDiffOutputfile.root"); HDat = (TH1F*)fzee->Get("NVTX1_InstLumiPerBx_DATA10"); HDatHF0 = (TH1F*)fzee->Get("HF0NVTX1_InstLumiPerBx_DATA10"); data->cd(1); HDat->Draw(); NSetTitle(HDat,"Luminosity [10^{-30} cm^{-2} s^{-1}]", "Entries"); HDat->SetTitle("Number of Z produced in events without PU"); HDatHF0->Draw("SAME HIST"); NHSetMarker(HDat,2,20,0.4); TLegend *legend = new TLegend(0.6,0.7,0.9,0.8); legend->SetTextFont(72); legend->SetTextSize(0.03); legend->SetBorderSize(0); legend->AddEntry(HDat,"All Z","p"); legend->AddEntry(HDatHF0,"Z with minE_HF=0","l"); legend->Draw(); TH1F * Hra = (TH1F * ) HDatHF0->Clone(); // Hra->GetXaxis->SetRange(0,12); NStat(Hra,0); Hra->Divide(HDat); NLogAxis(0,1); ratio->cd(1); Hra->Draw(); Hra->SetTitle("Fraction of Z with (PU=0 && E_HF=0)"); Hra->Fit("expo","","",0.,1.2); NSetTitle(Hra,"Luminosity [10^{-30} cm^{-2} s^{-1}]", "Fraction"); NLogAxis(0,1); NText(.05,0.1, "0.62"); NText(0.3,0.1, "2.47"); NText(0.7,0.1, "4.93"); NText(1.1,0.1, "7.4"); NText(1.4,0.1, "<Number of Int.>"); }
pair <float,float> find_interpolated_point(TH2F* histo, int xbin, bool mSUGRA=true) { int minaccept=4; TCanvas *flatcan = new TCanvas("flatcan","flatcan"); stringstream histoname; histoname << "exclusion shape for x bin " << xbin; TH1F *flathisto; if(mSUGRA) flathisto = new TH1F("flat",histoname.str().c_str(),histo->GetNbinsY(),histo->GetYaxis()->GetBinLowEdge(1),histo->GetYaxis()->GetBinLowEdge(histo->GetNbinsY())+histo->GetYaxis()->GetBinWidth(histo->GetNbinsY())); else flathisto = new TH1F("flat",histoname.str().c_str(),histo->GetNbinsX(),histo->GetXaxis()->GetBinLowEdge(1),histo->GetXaxis()->GetBinLowEdge(histo->GetNbinsX())+histo->GetXaxis()->GetBinWidth(histo->GetNbinsX())); int acceptedpoints=0; int nbins=histo->GetNbinsY(); if(!mSUGRA) histo->GetNbinsX(); for(int i=1;i<nbins;i++) { float value=0; if(i<=nbins-2) value=((1/3.0)*(histo->GetBinContent(xbin,i)+histo->GetBinContent(xbin+1,i)+histo->GetBinContent(xbin+2,i))); if(i==nbins-1) value=((1/2.0)*(histo->GetBinContent(xbin,i)+histo->GetBinContent(xbin,i+1))); if(i==nbins) value=(histo->GetBinContent(xbin,i)); if(value<20&&value>0) { flathisto->SetBinContent(i,value); flathisto->SetBinError(i,TMath::Sqrt(value)); acceptedpoints++; } } float pointone=-100; TLine *excluded; if(acceptedpoints>minaccept) { flathisto->Fit("expo","Q"); TF1 *fitfunc = (TF1*)flathisto->GetFunction("expo"); pointone=-(fitfunc->GetParameter(0)/fitfunc->GetParameter(1)); excluded=new TLine(pointone,0,pointone,10); } pair <float,float> anything; anything.first=histo->GetXaxis()->GetBinCenter(xbin); anything.second=pointone; stringstream flatname; flathisto->GetYaxis()->SetRangeUser(0,10); flathisto->Draw(); if(acceptedpoints>minaccept) excluded->SetLineColor(kGreen); if(acceptedpoints>minaccept) excluded->SetLineStyle(2); if(acceptedpoints>minaccept) excluded->SetLineWidth(2); if(acceptedpoints>minaccept) excluded->Draw("same"); flatname << "Limits/partials/partial_" << xbin << "___" << histo->GetName() << ".png"; if(draweachone) CompleteSave(flatcan,flatname.str()); delete flatcan; delete flathisto; return anything; }
void plotHisto(TTree *t, string hname, string valtitle, string valunit, string toPlot, int nBins, double lo, double hi) { string plotstring = makePlotsString(toPlot, hname, nBins, lo, hi); cout << "Thisplot: " << hname << endl; cout << plotstring << endl; t->Draw(plotstring.c_str()); TH1F *h = (TH1F*)gDirectory->GetList()->FindObject(hname.c_str()); h->SetTitle(("Distribution of " + valtitle).c_str()); h->GetXaxis()->SetTitle(valueWithUnit(valtitle,valunit).c_str()); h->Fit("gaus"); gStyle->SetOptFit(1); gPad->SaveAs((fileprefix+"_"+hname+".pdf").c_str()); }
void plotPulls(TTree *t, string hname, string valtitle, string toPlot, double trueVal, int nBins, double lo, double hi) { string plotstring = makePlotsString("("+toPlot+"-"+toString(trueVal)+")/"+toPlot+"_err", hname, nBins, lo, hi); cout << plotstring << endl; t->Draw(plotstring.c_str()); cout << "Thisplot: " << hname << endl; TH1F *h = (TH1F*)gDirectory->GetList()->FindObject(hname.c_str()); h->SetTitle(("Pull distribution of " + valtitle).c_str()); h->GetXaxis()->SetTitle(("pull "+valtitle).c_str()); h->Fit("gaus"); gStyle->SetOptFit(1); gPad->SaveAs((fileprefix+"_"+hname+".pdf").c_str()); }
void eff_hs_overlap(TString f_name, TString p_name, TString pt) { // efficiency vs half-strip - including overlaps in odd&even TCut ok_eta = "TMath::Abs(eta)>1.64 && TMath::Abs(eta)<2.12"; TTree *t = getTree(f_name); TH1F* ho = draw_eff(t, " GEM reconstruction efficiency CMS Simulation;LCT half-strip number;Efficiency", "h_odd", "(130,0.5,130.5)", "hs_lct_odd", ok_lct1 && ok_eta , ok_pad1_overlap, "", kRed); TH1F* he = draw_eff(t, " GEM reconstruction efficiency CMS Simulation;LCT half-strip number;Efficiency", "h_evn", "(130,0.5,130.5)", "hs_lct_even", ok_lct2 && ok_eta , ok_pad2_overlap, "same"); TF1 fo("fo", "pol0", 6., 123.); ho->Fit("fo","RN"); TF1 fe("fe", "pol0", 6., 123.); he->Fit("fe","RN"); TLegend *leg = new TLegend(0.25,0.23,.75,0.5, NULL, "brNDC"); leg->SetBorderSize(0); leg->SetFillStyle(0); leg->SetTextSize(0.06); leg->AddEntry((TObject*)0,"muon p_{T} = " + pt + " GeV/c",""); leg->AddEntry(he, "\"Close\" chamber pairs","l"); leg->AddEntry(ho, "\"Far\" chamber pairs","l"); leg->Draw(); // Print additional information TLatex* tex2 = new TLatex(.67,.8," L1 Trigger"); tex2->SetTextSize(0.05); tex2->SetNDC(); tex2->Draw(); TLatex * tex = new TLatex(.66,.73,"1.64<|#eta|<2.12"); tex->SetTextSize(0.05); tex->SetNDC(); tex->Draw(); gPad->Print(p_name); }
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); }
void EflowCASTOR() { NCanvas(1,2,"data"); TH1F * HDat; TH1F * HZ2; // TFile *fzee = new TFile("ZDiffOutputfile_73Weight2010.root"); TFile *fzee = new TFile("ZDiffOutputfile.root"); // TFile *fzee = new TFile("ZDiffOutputfile.root"); HDat = (TH1F*)fzee->Get("NVTX1_EnergyCastorModule_DATA"); HZ2 = (TH1F*)fzee->Get("NVTX1_EnergyCastorModule_Z2PY6"); data->cd(1); NHSetMarker(HDat,2,20,0.8); HDat->SetMinimum(10); HDat->Draw(); NStat(HDat,0); NSetTitle(HDat,"CASTOR Modules", "Entries"); HDat->SetTitle("CASTOR Module Energy 2010"); HZ2->Draw("SAME HIST"); NHSetMarker(HDat,2,20,0.4); TLegend *legend = new TLegend(0.6,0.7,0.9,0.8); legend->SetTextFont(72); legend->SetTextSize(0.06); legend->SetBorderSize(0); legend->AddEntry(HDat,"Data2010","p"); legend->AddEntry(HZ2,"Z2","l"); legend->Draw(); TH1F * Hra = (TH1F * ) HDat->Clone(); // Hra->GetXaxis->SetRange(0,12); NStat(Hra,0); NHSetMarker(Hra,4,20,0.8); Hra->SetMinimum(1); Hra->Divide(HZ2); NLogAxis(0,0); data->cd(2); Hra->Draw(); Hra->SetTitle("Ratio DATA/MC"); Hra->Fit("pol0"); NSetTitle(Hra,"CASTOR Modules", "Ratio"); NLogAxis(0,1); }
void Hist_FitAsymmetry() { TFile *filepara = TFile::Open("hist_p2gamma_para.acc.root"); TFile *fileperp = TFile::Open("hist_p2gamma_perp.acc.root"); TH2F *h2para = (TH2F*)filepara->Get("phi_t"); h2para->Rebin2D(10, 5); TH2F *h2perp = (TH2F*)fileperp->Get("phi_t"); h2perp->Rebin2D(10, 5); // phi distributions integrated over |t| TCanvas *cc1 = new TCanvas("cc1", "cc1", 800, 600); cc1->Divide(2,2); TH1F *hpara = (TH1F*)h2para->ProjectionY("phi_para"); TH1F *hperp = (TH1F*)h2perp->ProjectionY("phi_perp"); TH1F *hasym = (TH1F*)hperp->GetAsymmetry(hpara); TH1F *hsum = (TH1F*)hpara->Clone(); hsum->Add(hperp); cc1->cd(1); TF1* fpara = new TF1("fitpara","[0]*(1.0 + [1]*cos(2*(x + [2])/180.*3.14159))"); fpara->SetLineColor(kRed); hpara->Fit(fpara, "", ""); hpara->Draw("e"); cc1->cd(2); TF1* fperp = new TF1("fitperp","[0]*(1.0 + [1]*cos(2*(x + [2])/180.*3.14159))"); fperp->SetLineColor(kRed); hperp->Fit(fperp, "", ""); hperp->Draw("e"); cc1->cd(3); TF1* fitasym = new TF1("fitasym","[1]*cos(2*(x + [2])/180.*3.14159)"); fitasym->SetLineColor(kRed); hasym->Fit(fitasym, "", ""); hasym->Draw("e"); cc1->cd(4); hsum->Draw(); return; }
Int_t mp102_readNtuplesFillHistosAndFit() { // No nuisance for batch execution gROOT->SetBatch(); // Perform the operation sequentially --------------------------------------- TChain inputChain("multiCore"); inputChain.Add("mp101_multiCore_*.root"); TH1F outHisto("outHisto", "Random Numbers", 128, -4, 4); { TimerRAII t("Sequential read and fit"); inputChain.Draw("r >> outHisto"); outHisto.Fit("gaus"); } // We now go MP! ------------------------------------------------------------ // TProcPool offers an interface to directly process trees and chains without // the need for the user to go through the low level implementation of a // map-reduce. // We adapt our parallelisation to the number of input files const auto nFiles = inputChain.GetListOfFiles()->GetEntries(); // This is the function invoked during the processing of the trees. auto workItem = [](TTreeReader & reader) { TTreeReaderValue<Float_t> randomRV(reader, "r"); auto partialHisto = new TH1F("outHistoMP", "Random Numbers", 128, -4, 4); while (reader.Next()) { partialHisto->Fill(*randomRV); } return partialHisto; }; // Create the pool of processes TProcPool workers(nFiles); // Process the TChain { TimerRAII t("Parallel execution"); TH1F *sumHistogram = workers.ProcTree(inputChain, workItem, "multiCore"); sumHistogram->Fit("gaus", 0); } return 0; }
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"); }
void BackgroundFit() { TFile* inputFile = new TFile("0_MuScleFit.root", "READ"); TH1F* histo = (TH1F*)inputFile->FindObjectAny("hRecBestRes_Mass"); histo->Rebin(30); histo->Scale(1/histo->GetEntries()); // TF1 * functionToFit = lorentzianFit(); // TF1 * functionToFit = crystalBallFit(); // TF1 * functionToFit = powerLawFit(); // TF1 * functionToFit = lorentzianAndPowerLaw(); // TF1 * functionToFit = exponentialFit(); TF1 * functionToFit = lorenzianAndExponentialFit(); histo->Fit(functionToFit, "M", "", 42, 160); }
void MyMacro(){ cout<< "this is a ROOT macro template"<<endl; TFile *file1 = new TFile("./gauss.root"); myc1 = new TCanvas("myc1","My Canvas"); TH1F *histo = (TH1F*) file1->Get("h1"); histo->GetXaxis()->SetTitle("X-Axis"); histo->GetXaxis()->CenterTitle(1); histo->Fit("gaus"); //histo->Draw(); //histo->Write(); myc1->Modified(); myc1->Update(); TFile *hfile = new TFile("fit_gauss.root","RECREATE"); hfile->Append(myc1); hfile->Write(); };
TH1F* makehist( string id, int ndf ) { int hits_count = ndf + 2; TString hist_name, cut, title; hist_name += id; hist_name += "_chisq_"; hist_name += hits_count; hist_name += "hits"; cut += id; cut += "_hits_count == "; cut += hits_count; float min_x = 0; float max_x = (ndf == 2) ? 2.0 : 0.5; TH1F *hist = new TH1F(hist_name.Data(), cut, 1000, min_x, max_x); events->Draw(Form("%s_chisq >> %s", id.c_str(), hist_name.Data()), cut); if (hits_count > 3) { TF1 *func = new TF1("func", "[0]*exp([1]*x)+[2]"); TFitResultPtr fit = hist->Fit(func, "SQ", "", 0.0, 0.5); // S - return fit result, Q - quiet std::cout << hist_name << "\tslope: " << fit->Parameter(1) << "\tadd const: " << fit->Parameter(2) << std::endl; } if (id[1] == '3') { title += "Left "; } else { title += "Right "; } title += id[2]; title += " ("; title += cut; title += ")"; hist->SetTitle(title); hist->SetLabelSize(0.04, "X"); hist->SetLabelSize(0.04, "Y"); hist->SetTitleSize(0.05, "X"); hist->SetTitleSize(0.05, "Y"); hist->SetTitleOffset(0.9, "X"); hist->SetTitleOffset(1.1, "Y"); hist->GetXaxis()->SetTitle("#chi^2, [mm]"); hist->GetYaxis()->SetTitle("N"); return hist; }
void plotMttResolution() { setTDRStyle(); TCanvas *c = new TCanvas("c", "c", 800, 800); TH1F *mtt = (TH1F*) _file0->Get("mtt_resolution_mva"); mtt->SetTitle(""); mtt->SetName("m_{t#bar{t}}"); mtt->GetXaxis()->SetTitle("m_{t#bar{t}} - m_{t#bar{t}}^{gen} (GeV)"); mtt->SetLineColor(TColor::GetColor("#542437")); mtt->SetLineColor(TColor::GetColor("#8A9B0F")); mtt->SetLineColor(TColor::GetColor("#C02942")); mtt->SetFillColor(mtt->GetLineColor()); mtt->SetFillStyle(3004); mtt->GetXaxis()->SetTitleOffset(1.2); TF1 *voigt = new TF1("voigt", "gaus", -100, 100); voigt->SetParName(0, "amp"); voigt->SetParName(2, "mean"); voigt->SetParName(1, "sigma"); voigt->SetParameter(0, mtt->GetMaximum()); voigt->SetParameter(2, 0); voigt->SetParameter(1, 100); mtt->Fit(voigt, "RVN"); voigt->SetLineColor(TColor::GetColor("#8A9B0F")); voigt->SetLineWidth(2); mtt->Draw(); voigt->Draw("same"); TLatex* latex = new TLatex(); latex->SetTextFont(42); latex->SetTextSize(0.033); latex->DrawLatexNDC(0.25, 0.84, TString::Format("mean = %.2f", voigt->GetParameter(1))); latex->DrawLatexNDC(0.25, 0.8, TString::Format("#sigma = %.2f", voigt->GetParameter(2))); gPad->Modified(); gPad->Update(); c->Print("mtt_resolution.pdf"); }
void FillGoodRun(int ihar){ float pi = acos(-1.0); TString str; TFile *fin; int nrun = GetTotalRun(); if(nrun<0) exit(1); for(int icent=0;icent<ncent;icent++){ // for(int ihar=0;ihar<nhar;ihar++){ // if(ihar!=1) continue; for(int isub=0;isub<nsub;isub++){ str = choosesub(isub); if(str=="ABORT") continue; for(int irun=0;irun<nrun;irun++){ //std::cout<<icent<<" "<<ihar<<" "<<isub<<" "<<irun<<std::endl; //fin = TFile::Open(Form("/phenix/plhf/xuq/taxi/%s%s/%d/data/%s.root",dataset.Data(),pro.Data(),taxi,GetRun(irun).Data())); fin = TFile::Open(Form("/gpfs/mnt/gpfs02/phenix/plhf/plhf1/xuq/phenix/flow/Run16dAu/work/62GeV/output/%s",GetRun(irun).Data())); TH1F* hpsi = new TH1F("psi","psi",100,-pi,pi); for(int ibbcz=0;ibbcz<nbbcz;ibbcz++){ TH1F* hpsitemp = (TH1F*)fin->Get(Form("psiFla_0_0_%d_%d_%d_%d",icent,ibbcz,ihar,isub)); hpsi->Add(hpsitemp); } TF1 *fun = new TF1("fun","pol0",-pi,pi); if(hpsi->GetEntries()>1000){ //hpsi->SetMarkerStyle(20); //hpsi->SetMarkerSize(0.6); //hpsi->SetMarkerColor(4); hpsi->SetMinimum(10); hpsi->Fit("fun","QR0"); //float par=fun->GetParameter(0); //hpsi->SetMaximum(1.5*par); //hpsi->Draw(); GoodRunFit[icent][ihar][isub][irun] = fun->GetChisquare()/fun->GetNDF(); fin->Close(); } else{ GoodRunFit[icent][ihar][isub][irun] = -9999; fin->Close(); } // GoodRunFit[icent][ihar][isub][irun] = 1.; } } // } } }
void tree2ar() { //read the Tree generated by tree2w and fill one histogram //we are only interested by the destep branch. //note that we use "new" to create the TFile and TTree objects ! //because we want to keep these objects alive when we leave //this function. TFile *f = new TFile("tree2.root"); TTree *t2 = (TTree*)f->Get("t2"); Gctrak *gstep = 0; t2->SetBranchAddress("track",&gstep); TBranch *b_destep = t2->GetBranch("destep"); //create one histogram TH1F *hdestep = new TH1F("hdestep","destep in Mev",100,1e-5,3e-5); //read only the destep branch for all entries Long64_t nentries = t2->GetEntries(); for (Long64_t i=0;i<nentries;i++) { b_destep->GetEntry(i); hdestep->Fill(gstep->destep); } //we do not close the file. //We want to keep the generated histograms //We fill a 3-d scatter plot with the particle step coordinates TCanvas *c1 = new TCanvas("c1","c1",600,800); c1->SetFillColor(42); c1->Divide(1,2); c1->cd(1); hdestep->SetFillColor(45); hdestep->Fit("gaus"); c1->cd(2); gPad->SetFillColor(37); t2->SetMarkerColor(kRed); t2->Draw("vect[0]:vect[1]:vect[2]"); if (gROOT->IsBatch()) return; // invoke the x3d viewer gPad->GetViewer3D("x3d"); }