/*============================================================================*/ void gaus1peakfit(Char_t *s, Float_t x1, Float_t x2, Float_t x3, Float_t x4) { Double_t par[5],epar[5],x[4],y[4]; TH1 *hist; hist = (TH1 *) gROOT->FindObject(s); setcanvas(1); TCanvas *c1=(TCanvas*) gROOT->FindObject("c1"); if(c1==NULL)setcanvas(1); c1->Clear(); hist->SetAxisRange(x1-30,x4+30); hist->Draw(); //--**-- Linear background estimation --**--// x[0] = x1; x[1] = x2; x[2] = x3; x[3] = x4; Int_t bin1 = hist->FindBin(x1); y[0] = hist->GetBinContent(bin1); Int_t bin2 = hist->FindBin(x2); y[1] = hist->GetBinContent(bin2); Int_t bin3 = hist->FindBin(x3); y[2] = hist->GetBinContent(bin3); Int_t bin4 = hist->FindBin(x4); y[3] = hist->GetBinContent(bin4); TGraph *g = new TGraph(4,x,y); TF1 *fpol1 = new TF1("POL1","pol1",x1,x4); g->Fit(fpol1,"RQN"); par[3]=fpol1->GetParameter(0); par[4]=fpol1->GetParameter(1); //--**-- Gaussian Peak estimation without background --**--// TF1 *fgaus = new TF1("GAUS","gaus",x2,x3); hist->Fit(fgaus,"RQN"); fgaus->GetParameters(&par[0]); //--**-- Final Peak Fit with Background --**--// TF1 *func = new TF1("FGAUS","gaus(0)+pol1(3)",x1,x4); func->SetParameters(par); hist->Fit(func,"R+QN"); func->GetParameters(par); epar[0]=func->GetParError(0); epar[1]=func->GetParError(1); epar[2]=func->GetParError(2); Double_t fwhm = par[2]*TMath::Sqrt(8*TMath::Log(2)); Double_t efwhm = epar[2]*TMath::Sqrt(8*TMath::Log(2)); Double_t N0 = par[0]*(TMath::Sqrt(TMath::TwoPi())*par[2]); Double_t r0 = epar[0]/par[0]; Double_t r2 = epar[2]/par[2]; Double_t eN0= N0*TMath::Sqrt(r0*r0+r2*r2); printf("Peak = %f +- %f; FFHM = %f +- %f; Area = %f +- %f\n", par[1],epar[1],fwhm,efwhm,N0,eN0); //printf("%11.4f %11.4f %11.0f %11.0f\n", // par[1],epar[1],N0,eN0); func->SetLineWidth(0.5); func->SetLineStyle(1); func->SetLineColor(4); func->SetFillColor(4); func->Draw("same"); }
void problem_1() { //Declare variable for energy Float_t energy; //declare a histogram for the energy TH1D *energy_hist = new TH1D("Energy","Energy",50,100,160); //declare the canvas to display hist TCanvas *c1 = new TCanvas("c1","c1",10,10,900,900); TF1 *fitFcn = new TF1("fitFcn",fitFunction,90,180,6); //get the input file TFile *inputFile = new TFile("data.root"); //get the correct tree from the input file //depending on the tree name change "data" TTree *data_tree = (TTree*)inputFile->Get("data"); //Get the branch named E1 and put it into the varialbe energy data_tree->SetBranchAddress("E", &energy); //Get the number of events for the for loop int count = data_tree->GetEntries(); for (int i = 0; i < count; i++) { //get the current event i data_tree->GetEntry(i); //Fill the histogram energy_hist->Fill(energy); } //label the axis and draw the histogram after it's filled energy_hist->GetXaxis()->SetTitle("E (GeV)"); energy_hist->Draw(); // first try without starting values for the parameters // this defaults to 1 for each param. energy_hist->Fit("fitFcn"); // this results in an ok fit for the polynomial function however // the non-linear part (Lorentzian) does not respond well // second try: set start values for some parameters fitFcn->SetParameter(4,1.66); // width fitFcn->SetParameter(5,126.5); // peak energy_hist->Fit("fitFcn"); // improve the picture: TF1 *backFcn = new TF1("backFcn",background,100,160,3); backFcn->SetLineColor(1); backFcn->SetLineStyle(3); TF1 *signalFcn = new TF1("signalFcn",gaussian,100,160,3); signalFcn->SetLineColor(4); Double_t par[6]; // writes the fit results into the par array fitFcn->GetParameters(par); backFcn->SetParameters(par); backFcn->Draw("same"); signalFcn->SetParameters(&par[4]); signalFcn->Draw("same"); gStyle->SetOptFit(1111); }
TF1 * getDoubleFit(TH1 * hist, bool autorange, double inner, double outer, int which=1){ /** * @brief performes a double gaussian Fit */ Double_t parameters[6] = {0,0,0,0,0,0}; Double_t parameters_new[6] = {0,0,0,0,0,0}; double center = hist->GetMean(); if (autorange){ double inner = fabs(center - hist->GetXaxis()->GetXmax()) /10; double outer = fabs(center - hist->GetXaxis()->GetXmax()) /10*8; } TF1 * fit1 = new TF1("fit1", "gaus", center-inner, center+inner ); hist->Fit(fit1, "Q0R"); fit1->GetParameters(¶meters[0]); TF1 * fit2 = new TF1("fit2", "gaus", center-outer, center+outer ); hist->Fit(fit2, "Q0R"); fit2->GetParameters(¶meters[3]); TF1 * fitproper = new TF1("fitproper", "gaus(0)+gaus(3)", center-outer, center+outer); fitproper->SetParameters(parameters); fitproper->SetParName(0, "Const.(inner)"); fitproper->SetParName(1, "Mean (inner)"); fitproper->SetParName(2, "Sigma (inner)"); fitproper->SetParName(3, "Const.(outer)"); fitproper->SetParName(4, "Mean (outer)"); fitproper->SetParName(5, "Sigma (outer)"); hist->Fit(fitproper, "Q0R"); fitproper->GetParameters(¶meters_new[0]); fitproper->SetLineColor(hist->GetLineColor()); fitproper->SetLineWidth(hist->GetLineWidth()); fitproper->SetLineStyle(2); if (which==1){ TF1 * Gausinner = new TF1("Gausinner", "gaus(0)", center-inner, center+inner); Gausinner->SetParameters(parameters_new); return Gausinner; } else{ TF1 * Gausouter = new TF1("Gausouter", "gaus(3)", center-outer, center+outer); Gausouter->SetParameters(parameters_new); return Gausouter; } }
TF1 * tripleGaussFit(TH1 * hist, bool autorange, double inner=0.01, double outer=0.1){ /** * @brief performes a double gaussian Fit */ Double_t parameters[9] = {0,0,0,0,0,0,0,0,0}; double center = hist->GetMean(); if (autorange){ double inner = fabs(center - hist->GetXaxis()->GetXmax()) /10; double outer = fabs(center - hist->GetXaxis()->GetXmax()) /10*8; } double middle = (outer - inner)/2; TF1 * fit1 = new TF1("fit1", "gaus", center-inner, center+inner ); hist->Fit(fit1, "0R"); fit1->GetParameters(¶meters[0]); TF1 * fitmid = new TF1("fitmid", "gaus", center-middle, center+middle ); fitmid->SetParameter(1, parameters[1]); hist->Fit(fitmid, "0R"); fitmid->GetParameters(¶meters[3]); TF1 * fit2 = new TF1("fit2", "gaus", center-outer, center+outer ); fit2->SetParameter(1, parameters[1]); hist->Fit(fit2, "0R"); fit2->GetParameters(¶meters[6]); TF1 * fitproper = new TF1("fitproper", "gaus(0)+gaus(3)+gaus(6)", center-outer, center+outer); fitproper->SetParameters(parameters); fitproper->SetParName(0, "Const.(inner)"); fitproper->SetParName(1, "Mean (inner)"); fitproper->SetParName(2, "Sigma (inner)"); fitproper->SetParName(3, "Const.(middle)"); fitproper->SetParName(4, "Mean (middle)"); fitproper->SetParName(5, "Sigma (middle)"); fitproper->SetParName(6, "Const.(outer)"); fitproper->SetParName(7, "Mean (outer)"); fitproper->SetParName(8, "Sigma (outer)"); hist->Fit(fitproper, "0R"); // fitproper->SetLineColor(hist->GetLineColor()); // fitproper->SetLineWidth(hist->GetLineWidth()); //// fitproper->SetLineStyle(2); return fitproper; }
int BBCEfficiency::FitAcceptance(float left_low = -60., float left_high = 0., float right_low = 0., float right_high = 60.) { // these fit ranges should encompass any vertex cut range. TF1* left = new TF1("left","gaus",left_low,left_high); left->SetLineColor(kGreen); TF1* right = new TF1("right","gaus",right_low,right_high); right->SetLineColor(kBlue); Double_t par[6]; Derivative(trigger_acceptance_, acceptance_first_derivative_); // Needs parameter settings, etc, but we've already successfully fit. // left_erf_ = new TF1("left_erf_","[0]+[1]*TMath::Erf((x-[2])/[3])",-60,0); // right_erf_ = new TF1("right_erf_","[0]+[1]*TMath::Erf((x-[2])/[3])",0,60); for(int i = 0; i < acceptance_first_derivative_->GetNbinsX(); i++) { abs_acceptance_first_derivative_->SetBinContent(i+1,fabs(acceptance_first_derivative_->GetBinContent(i+1))); abs_acceptance_first_derivative_->SetBinError(i+1,acceptance_first_derivative_->GetBinError(i+1)); } abs_acceptance_first_derivative_->Fit(left,"R"); abs_acceptance_first_derivative_->Fit(right,"R+"); left->GetParameters(&par[0]); right->GetParameters(&par[3]); // store for access later in the class to member variables. left_gaus_ = left; right_gaus_ = right; z_vtx_cut_min_ = left_gaus_->GetParameter(1); z_vtx_cut_max_ = right_gaus_->GetParameter(1); std::cout << "Trigger vertex cut: " << z_vtx_cut_min_ << ", " << z_vtx_cut_max_ << std::endl; plot_registry_.push_back(left); plot_registry_.push_back(right); return 0; }
void RRootHistRead_v1(){ TFile *inputFile = new TFile("pPb_MBSpectra_Combine_-1_1.root"); cout << "Is the file Open " << inputFile->IsOpen() << endl; //Copy the histogram TString hName = "Spectra_NtrkOffline0_inf"; TH1D *h = (TH1D*)inputFile->Get(hName); cout << "Number of bins in the histogram: " << h->GetSize() << "\n"; h->Draw(); double nhBins = h->GetSize(); for (int i=0; i < nhBins; i++) cout << h->GetBinWidth(i) << ", "; cout << endl; // Fit function double nParam = 2, maxValue = 5, minValue = 0; TF1 *fitFn = new TF1("fitFn", fitFunction, minValue, maxValue, nParam); // Set parameters for Fit fitFn->SetParameter(0, 0.008); // Get parameters from Fit double paramFromFit[2]; fitFn->GetParameters(paramFromFit); // Generate data from fit double nBins = 27, pT[27], spectraFromFit[27]; // From the Xi for (int i=0; i < nBins; i++){ spectraFromFit[i] = paramFromFit[0]*exp(-i) + paramFromFit[1]; cout << spectraFromFit[i] << ", "; pT[i] = i; } // Using Integral for the Fit h->Fit(fitFn, "I"); TGraph *g = new TGraph(nBins, pT, spectraFromFit); g->SetMarkerStyle(7); g->SetMarkerSize(1.5); g->SetMarkerColor(kGreen); g->Draw("ALP"); h->Draw("same"); }
void GetFitParameterDoubleFit(TH1* &histo, bool autorange = true, double innerRange=0.1 , double outerRange=1, bool excludeCenter=false){ Double_t parameter[6] = {0,0,0,0,0,0}; TF1 * fit; if(excludeCenter){ fit = andi::doubleGaussFitExcludeCenter(histo, false, innerRange, outerRange); } else{ fit = doubleGaussFit(histo, autorange, innerRange, outerRange); } fit->GetParameters(¶meter[0]); }
void fitExclude() { //Create a source function TF1 *f1 = new TF1("f1","[0] +[1]*x +gaus(2)",0,5); f1->SetParameters(6,-1,5,3,0.2); // create and fill histogram according to the source function TH1F *h = new TH1F("h","background + signal",100,0,5); h->FillRandom("f1",2000); TF1 *fl = new TF1("fl",fline,0,5,2); fl->SetParameters(2,-1); //fit only the linear background excluding the signal area reject = kTRUE; h->Fit(fl,"0"); reject = kFALSE; //store 2 separate functions for visualization TF1 *fleft = new TF1("fleft",fline,0,2.5,2); fleft->SetParameters(fl->GetParameters()); h->GetListOfFunctions()->Add(fleft); gROOT->GetListOfFunctions()->Remove(fleft); TF1 *fright = new TF1("fright",fline,3.5,5,2); fright->SetParameters(fl->GetParameters()); h->GetListOfFunctions()->Add(fright); gROOT->GetListOfFunctions()->Remove(fright); h->Draw(); }
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 * gaussFit(TH1 * hist, double inner) { Double_t parameters[6] = {0,0,0,0,0,0}; double center =0;// hist->GetMean(); TF1 * fit = new TF1("fit", "gaus", center-inner, center+inner ); hist->Fit(fit, "Q0R"); fit->GetParameters(¶meters[0]); fit->SetParameters(parameters); fit->SetParName(0, "Const."); fit->SetParName(1, "Mean"); fit->SetParName(2, "Sigma"); return fit; }
void LadderTimes() { TH1F* Time; Double_t par[4]; Double_t Max; Char_t Buff[256]; for(Int_t ch=0; ch<352; ch++) { sprintf(Buff, "Ladder_Time%d", ch); Time = (TH1F*)gROOT->FindObject(Buff); Max = Time->GetMaximumBin()*Time->GetBinWidth(Time->GetMaximumBin()) - 1000.0; TF1* gauss = new TF1("gauss", "gaus", Max-8, Max+8); Time->Fit(gauss, "RQ+"); gauss->GetParameters(&par[0]); printf("%5.2f\n", par[1]/0.117710); } }
scalePair energyCorrectionDiff(TCut centCut1, float lowPt, float highPt, float lowEta, float highEta,TCut addCut) { TString fname1 = "forest/barrelHiForestPhoton_MCphoton50_51k.root"; if ( lowPt > 90 ) fname1 = "forest/barrelHiForestPhoton_MCphoton80_28k.root"; TFile *f1 =new TFile(fname1.Data()); TTree *photon1 = (TTree*)f1->Get("yongsunPhotonTree"); photon1->AddFriend("yEvt=yongsunHiEvt" ,fname1.Data()); photon1->AddFriend("ySkim=yongsunSkimTree" ,fname1.Data()); photon1->AddFriend("yHlt=yongsunHltTree" ,fname1.Data()); TCut collisionCut = "ySkim.pcollisionEventSelection==1"; TCut hoeCut = "hadronicOverEm<0.2"; TCut isoCut = "cc4 + cr4 + ct4j20 < 5 && sigmaIetaIeta<0.011"; TCut ptCut = Form("genMatchedPt>%.f && genMatchedPt <%.f",lowPt, highPt); TCut etaCut = Form("abs(eta)>%f && abs(eta)<%f",lowEta,highEta); TCut finalCut1 = genMatchCut1 && collisionCut && centCut1 && hoeCut && isoCut && ptCut && etaCut && addCut ; TString variable1 = "pt/genMatchedPt"; TH1D* hScale = new TH1D("hScale","",100,.5,1.5); TH1D* hdpt = new TH1D("hdpt","",100,-20,20); photon1->Draw(Form("%s>>%s",variable1.Data(),hScale->GetName()), finalCut1); photon1->Draw(Form("pt-genMatchedPt>>%s",hdpt->GetName()), finalCut1); cout << "cut = " << finalCut1.GetTitle() <<endl; hScale->Draw(); hdpt->Draw(); TF1* ff = cleverGaus(hScale); scalePair ret; double *ps = ff->GetParameters(); ret.val = ps[1]; ret.err = ff->GetParError(1); // resErr = ff->GetParError(2); ret.res = ps[2]; ret.resErr = ff->GetParError(2); ret.absVal = hdpt->GetMean(); cout <<"scale = " << ret.val << " +-" << ret.err << endl; return ret; }
TF1 * GetVoigtFit(TH1 * hist, double lower, double upper){ /** * @brief performes a Fit with a Breit-Wigner-Distribution. */ double parameter[3]; double max = hist->GetMaximum(); int bin1 = hist->FindFirstBinAbove(max-1); double center = hist->GetBinCenter(bin1); TString func = TString::Format("TMath::Voigt(x-%.4f, [0], [1])", center); TF1 * fit = new TF1("fit", func, lower, upper); hist->Fit(fit, "0R"); fit->GetParameters(¶meter[0]); TF1 * voigt = new TF1("voigt", func+"*[2]", lower, upper); voigt->SetParameter(0, parameter[0]); voigt->SetParameter(1, parameter[1]); voigt->SetParName(0, "#sigma"); voigt->SetParName(1, "#Gamma"); voigt->SetParName(2, "A"); // voigt->SetParName(3, "B"); // voigt->SetParName(4, "C"); hist->Fit(voigt, "0R"); return voigt; }
void fitmmp(TH1 *hmmp, bool verbose = false) { TString options; if (verbose) options = ""; else options = "Q"; TF1 *fbg = f_pol4("fbg",0.4,2,true); hmmp->Fit(fbg,options.Data(),"",0.42,2); //printf("%s\n",gMinuit->fCstatu.Data()); if (true) { //gMinuit->fCstatu.Contains("CONVER")) { TF1 *fbg2 = f_pol4("fbg",0.4,2,false); fbg2->SetParameters(fbg->GetParameters()); //fbg2->Draw("same"); fbg2->SetParameter(5,0); fbg2->SetParameter(6,0); TH1 *htmp = (TH1*)hmmp->Clone("hmmp_bgsub"); htmp->Add(fbg2,-1); //htmp->Draw(); TF1 *fgaus = new TF1("fgaus","gaus",0.4,2); htmp->Fit(fgaus,options.Data(),"",0.74,0.85); TF1 *f = f_pol4gaus("f",0.4,2,fbg2,fgaus); f->SetNpx(500); hmmp->Fit(f,options.Data(),"",0.42,2); fgaus->SetRange(0.4,2); for (int i = 0; i < 3; i++) fgaus->SetParameter(i,f->GetParameter(i+5)); for (int i = 0; i < 5; i++) fbg2->SetParameter(i,f->GetParameter(i)); fbg2->SetLineStyle(2); fbg2->SetLineColor(kRed+1); fgaus->SetLineStyle(2); fgaus->SetLineColor(kGreen+1); hmmp->GetListOfFunctions()->Add(fbg2->Clone()); hmmp->GetListOfFunctions()->Add(fgaus->Clone()); delete fbg2; delete htmp; delete fgaus; delete f; } else hmmp->GetListOfFunctions()->Delete(); delete fbg; }
//void pi0_mfitpeak(char *FileName, char *HistName, Int_t etapi0flag) void pi0_mfitpeak(TH1F *mh1, Int_t etapi0flag, float xmin, float xmax, int npol,float res[],int posFlag, const char *dirName, const char *histName, float text_x, float text_y, const char *texName) { TGaxis::SetMaxDigits(3); // TVirtualFitter::SetDefaultFitter("Minuit"); // This script attempts to fit any pi0 peak so that the freaking fit function would converge // currently background is fitted to a pol4 function and the peak by a gaussian; // results are not very nice // usage .x pi0_mfitpeak.C++ ("pi0calib.root","minv_spb") // or eg. .x pi0_mfitpeak.C ("../pi0anal/pi0ana_punorm.root","minv_spb",0) gROOT->Reset(); // gStyle->SetOptFit(); // gStyle->SetOptFit(0); // gStyle->SetOptStat(0); // gStyle->SetOptTitle(0); Bool_t NOTE=1; if(NOTE) gStyle->SetCanvasBorderMode(0); gStyle->SetPadTopMargin(0.08); gStyle->SetPadBottomMargin(0.12); gStyle->SetPadLeftMargin(0.15); gStyle->SetPadRightMargin(0.08); mh1->GetXaxis()->SetRangeUser(xmin,xmax); Int_t highx=500; TCanvas *c2 = new TCanvas("c2","",200,10,highx,500); // cout<<FileName<<" "<<HistName<<endl; // TFile f(FileName); // TH1F *mh1 = (TH1F*) f.Get(HistName); mh1->SetMarkerStyle(20); mh1->SetMarkerSize(1.); mh1->SetStats(0); // 1/0 to set the stat box mh1->GetXaxis()->SetTitle("Invariant Mass of Photon Pairs (GeV/c^{2})"); float binwidth = mh1->GetBinWidth(1); char *ytitle = new char[100]; sprintf(ytitle,"Photon Pairs / %4.3f GeV/c^{2}",binwidth); mh1->GetYaxis()->SetTitle(ytitle); mh1->GetXaxis()->SetTitleSize(0.055); mh1->GetYaxis()->SetTitleSize(0.055); mh1->GetXaxis()->SetLabelSize(0.045); mh1->GetYaxis()->SetLabelSize(0.045); mh1->GetXaxis()->SetTitleOffset(0.90); mh1->GetXaxis()->CenterTitle(); mh1->GetYaxis()->SetTitleOffset(1.32); // First work with the histogram and find the peak and fit ranges TAxis *xaxis = mh1->GetXaxis(); Float_t binsiz= xaxis->GetBinCenter(3) - xaxis->GetBinCenter(2); Int_t nbins = xaxis->GetNbins(); Float_t nevtperbin0[10000]; Float_t errorbin0[10000]; Float_t nevttot; Float_t maxbin=0; Int_t nmaxbin=0, nminbord=0, nmaxbord=nbins; for (Int_t nn=1; nn <= nbins; nn++) { nevtperbin0[nn] = mh1->GetBinContent(nn); if(nevtperbin0[nn] > maxbin) { maxbin=nevtperbin0[nn]; nmaxbin=nn; } errorbin0[nn] = mh1->GetBinError(nn); nevttot+=nevtperbin0[nn]; if(nevtperbin0[nn] > 0 && nminbord == 0) nminbord=nn; if(nevtperbin0[nn] == 0 && (nn > nminbord +10) && nmaxbord==0 && nminbord > 0) nmaxbord=nn; } cout<<"Minbordl "<<nminbord<<" with events: "<<nevtperbin0[nminbord]<<endl; cout<<"Maxbordl "<<nmaxbord<<" with events: "<<nevtperbin0[nmaxbord]<<endl; nminbord+=0; nmaxbord-=0; Int_t nmin0=nminbord; while(nevtperbin0[nminbord] < nevtperbin0[nmaxbin]*0.025) nminbord++; while(nevtperbin0[nmaxbord] < nevtperbin0[nmaxbin]*0.025) nmaxbord--; // the above was just to get the info and low/high bins // Set the fit range ! This is for total fit ! Float_t fitl=xmin; float fith=xmax; // Float_t fitl=0.07, fith=0.2;// this works better for pileup // Float_t fitl=0.08, fith=0.18;// this works even better for pileup // if(etapi0flag == 1) // { // fitl=0.35; fith=0.75; //} // if(fitl < xaxis->GetBinCenter(nmin0)) fitl = xaxis->GetBinCenter(nmin0); //if(fith > xaxis->GetBinCenter(nmaxbord)) fith = xaxis->GetBinCenter(nmaxbord); cout<<" fit range "<<fitl<<" -- "<<fith<<endl; cout <<"Bin size "<<binsiz<<endl; cout<<"Total events "<<nevttot<<endl; cout<<"MaxBin "<<nmaxbin<<" with events: "<<nevtperbin0[nmaxbin]<<endl; cout<<"Minbord "<<nminbord<<" with events: "<<nevtperbin0[nminbord]<<endl; cout<<"Maxbord "<<nmaxbord<<" with events: "<<nevtperbin0[nmaxbord]<<endl; mh1->DrawCopy("sep"); Float_t lowgauss=0.135-4.*0.010; Float_t highgauss=0.135+4.*0.010; if(etapi0flag == 1) { lowgauss=0.55-5.*0.025; highgauss=0.55+5.*0.025; } Int_t nlowgauss=Int_t((lowgauss-xaxis->GetBinCenter(1))/Float_t(binsiz)+0.5); Int_t nhighgauss=Int_t((highgauss-xaxis->GetBinCenter(1))/Float_t(binsiz)+0.5); cout <<xaxis->GetBinCenter(nlowgauss)<<" "<<xaxis->GetBinCenter(nhighgauss)<<endl; // now make the "background" histogram and fit it with p4 Float_t lowvalgauss=nevtperbin0[nlowgauss]; Float_t increm=(nevtperbin0[nhighgauss]-nevtperbin0[nlowgauss])/Float_t(nhighgauss-nlowgauss); TH1F *hbkg = (TH1F*)mh1->Clone(); hbkg->SetName("bkg_clone"); for (Int_t nn=nlowgauss; nn<=nhighgauss; nn++) { hbkg->SetBinContent(nn,Float_t(lowvalgauss+(nn-nlowgauss)*increm)); hbkg->SetBinError(nn,sqrt(lowvalgauss+(nn-nlowgauss)*increm)); } hbkg->DrawCopy("samesep"); // break; // Now define the "gaussian" histogram TH1F *hgauss = (TH1F*)mh1->Clone(); hgauss->SetName("gauss_clone"); hgauss->Sumw2(); hgauss->Add(mh1,hbkg,1,-1); // if errors are independent Add needs to be used ! for (Int_t nn=1; nn <= nbins; nn++) { if(hgauss->GetBinContent(nn) < 0.) hgauss->SetBinContent(nn,0.001*nevtperbin0[nmaxbin]); hgauss->SetBinError(nn,sqrt(hgauss->GetBinContent(nn))); } // Declare function with wich to fit TF1 *g1 = new TF1("g1","gaus",lowgauss,highgauss); hgauss->Fit(g1,"R0"); hgauss->DrawCopy("sep"); g1->Draw("same"); // break; char *polff = new char[20]; sprintf(polff,"pol%d",npol); TF1 *p4bkg; if(etapi0flag != 1) p4bkg = new TF1("pm2",polff, xaxis->GetBinCenter(nminbord),xaxis->GetBinCenter(nmaxbord)); else p4bkg = new TF1("pm2",polff, 0.35,0.75); hbkg->Fit(p4bkg,"R0"); hbkg->DrawCopy("sep"); p4bkg->SetLineStyle(kDashed); p4bkg->Draw("same"); // break; Double_t par[20],parf[20],errparf[20]; g1->GetParameters(&par[0]); p4bkg->GetParameters(&par[3]); char *totff = new char[20]; sprintf(totff,"gaus(0)+pol%d(3)",npol); TF1 *total = new TF1("total",totff,fitl,fith); TF1 *p4bkgfin = new TF1("pm2",polff,fitl,fith); total->SetParameters(par); if(etapi0flag==0){ total->SetParLimits(1,0.10,0.15); total->SetParLimits(2,0.135*0.06,0.135*0.3); }else{ total->SetParLimits(1,0.35,0.65); } // total->FixParameter(1,1.21340e-01); // total->FixParameter(2,2.69780e-02); mh1->Fit(total,"R0"); cout<<" yield.. "<< total->GetParameter(0) <<"+/- " << total->GetParError(0)<<endl; total->GetParameters(parf); for( Int_t nn=0; nn < 3+npol+1; nn++) errparf[nn]=total->GetParError(nn); g1->SetParameters(&parf[0]); p4bkgfin->SetParameters(&parf[3]); cout <<" Piz Mass = "<<parf[1]*1000.<<" +- "<<errparf[1]*1000.<< " Sigma ="<<parf[2]*1000.<<" +- "<<errparf[2]*1000.<<endl; cout << " Sigma Rel. = "<< parf[2]/parf[1]<<" +- " << errparf[2]/parf[1] <<endl; Float_t int_min=parf[1]-3.*parf[2]; Float_t int_max=parf[1]+3.*parf[2]; Float_t sig_peak=g1->Integral(int_min,int_max)/binsiz; Float_t bkgd_peak=p4bkgfin->Integral(int_min,int_max)/binsiz; cout<<" In +-3. sigma window: Signal="<<sig_peak<<" Bkgd="<<bkgd_peak<<endl; Float_t SB=sig_peak/bkgd_peak; Float_t SBerr=SB*(sqrt(1./sig_peak+1./bkgd_peak)); cout<<" Signal/Bkgd "<<SB<<" +- "<<SBerr<<endl; int_min=parf[1]-2.*parf[2]; int_max=parf[1]+2.*parf[2]; sig_peak=g1->Integral(int_min,int_max)/binsiz; bkgd_peak=p4bkgfin->Integral(int_min,int_max)/binsiz; cout<<" In +-2.sigma window: Signal="<<sig_peak<<" Bkgd="<<bkgd_peak<<endl; SB=sig_peak/bkgd_peak; SBerr=SB*(sqrt(1./sig_peak+1./bkgd_peak)); cout<<" Signal/Bkgd "<<SB<<" +- "<<SBerr<<endl; float S = sig_peak; float B = bkgd_peak; int_min=parf[1]-20.*parf[2]; int_max=parf[1]+20.*parf[2]; float S_all = g1->Integral(int_min,int_max)/binsiz; float test_sall = parf[0] * parf[2] * sqrt(acos(-1)) / binsiz; cout<<"signal all: "<< S_all << " "<< test_sall <<endl; float Serr_all = errparf[0]/ parf[0] * S_all; res[0] = S_all; res[1] = Serr_all; res[2] = parf[1]; res[3] = errparf[1]; res[4] = parf[2]; res[5] = errparf[2]; res[6] = SB; res[7] = SBerr; total->SetLineWidth(3); total->SetLineColor(kBlue); p4bkgfin->SetLineWidth(3); p4bkgfin->SetLineColor(kRed); mh1->DrawCopy("sep"); // total->SetRange(0.07,0.185); // p4bkgfin->SetRange(0.07,0.185); total->Draw("same"); p4bkgfin->SetLineStyle(kDashed); p4bkgfin->Draw("same"); TLatex l; // l.SetTextSize(0.06); l.SetTextSize(0.05); l.SetTextColor(1); l.SetNDC(); float sigma = parf[2]/ parf[1]*100; float sigmaerr = errparf[2]/ parf[1]*100; char *sigma_name = new char[50]; if(sigmaerr>0.005) sprintf(sigma_name,"#sigma = %3.2f #pm %3.2f %% ",sigma,sigmaerr); else sprintf(sigma_name,"#sigma = %3.2f %% ",sigma); if(posFlag==1){ l.DrawLatex(0.54,0.75,sigma_name); }else if( posFlag==2){ l.DrawLatex(0.54,0.3,sigma_name); } // sprintf(sigma_name,"S/B = %3.2f #pm %3.2f ",SB,SBerr); // sprintf(sigma_name,"S = %2.1f #pm %2.1f",S_all,Serr_all); // // l.DrawLatex(0.5,0.5,sigma_name); sprintf(sigma_name,"M = %3.1f #pm %3.1f MeV",parf[1]*1000.,errparf[1]*1000); if(posFlag==1){ l.DrawLatex(0.54,0.82,sigma_name); }else if( posFlag==2){ l.DrawLatex(0.54,0.37,sigma_name); } ///l.DrawLatex(0.169,470.,"d)"); c2->Modified(); c2->Update(); // c2->SaveAs("nice_pi0.gif"); if( text_x >0 && text_y >0){ TLatex * tex = new TLatex(text_x, text_y, texName); tex->SetNDC(); tex->SetTextSize(0.06); tex->SetLineWidth(2); tex->Draw(); } char *filename = new char[1000]; sprintf(filename,"%s/%s.gif",dirName,histName); c2->Print(filename); sprintf(filename,"%s/%s.C",dirName,histName); c2->Print(filename); // .x pi0_mfitpeak.C ("pi0ana_508030.root","minv_spb",0) // .x pi0_mfitpeak.C ("pi0ana_npu.root","minv_bkg",0) // .x pi0_mfitpeak.C ("pi0ana_punormv2.root","minv_spb",0) }
int main() { float const conS =.3/2.35; ofstream fout("cal/backN.cal"); ofstream fwhm("cal/fwhmback.dat"); TFile f("sort.root"); TCanvas* canvas[14]; int Ntele = 14; int Nstrip = 32; ostringstream outstring; TH2I frame("frame","",10,4.5,9.5,10,0,130); frame.SetStats(kFALSE); double xx[14*32]; double yy[14*32]; TF1 *func = new TF1("fit",ThPeaks,3,9,4); double para[5]; ifstream file("cal/back.cal"); float intercept, slope; int i1,i2; string name; TH1F con("con","",500,0,10); for (int itele=0;itele<Ntele;itele++) { outstring.str(""); outstring << "B"<<itele; name = outstring.str(); canvas[itele] = new TCanvas(name.c_str()); canvas[itele]->Divide(6,6); for (int istrip =0;istrip<Nstrip;istrip++) { canvas[itele]->cd(istrip+1); file >> i1 >> i2 >> slope >> intercept; outstring.str(""); outstring << "back/cal/EBC"<<itele<<"_"<<istrip; string name = outstring.str(); cout << name << endl; TH1I * hist = (TH1I*) f.Get(name.c_str()); frame.Draw(); hist->SetStats(kFALSE); hist->GetXaxis()->SetRangeUser(4.5,9.5); con.GetXaxis()->SetRangeUser(4.5,9.5); for (int i=1;i<=500;i++) for (int j=1;j<500;j++) { float deltax = hist->GetBinCenter(i)-con.GetBinCenter(j); if (fabs(deltax) > 10.*conS)continue; float fact = gauss(deltax,0.,conS); float y = fact*hist->GetBinContent(i)*hist->GetBinWidth(i); con.SetBinContent(j,y+con.GetBinContent(j)); } for (int i=1;i<=500;i++) { hist->SetBinContent(i,con.GetBinContent(i)); con.SetBinContent(i,0.); } hist->Draw("same"); func->SetParameter(0,0); func->SetParameter(1,1.); func->FixParameter(2,conS); //func->SetParameter(2,0.1); func->SetParameter(3,8.); func->SetLineColor(2); //func->Draw("same"); hist->Fit(func); func->GetParameters(para); cout << "chisq=" << func->GetChisquare() << endl; if (fabs(para[1]-1.) < .2) { slope *= para[1]; intercept = intercept*para[1] + para[0]; } fout << itele << " " << istrip << " " << slope << " " << intercept << endl; fwhm << itele << " " << istrip << " " << para[2]*2.35 << endl; int ii = itele*32+istrip; xx[ii] = (float)ii; yy[ii] = para[2]*2.35; cout << para[0] << " " << para[1] << " " << para[2] << endl; } } TFile g("ThBack.root","RECREATE"); for (int itele=0;itele<Ntele;itele++) canvas[itele]->Write(); TCanvas fwhmCan("fwhm"); TH2I frame2("frame2","",10,0,448,10,0,0.12); frame2.SetStats(kFALSE); frame2.GetYaxis()->SetTitle("FWHM [MeV]"); frame2.GetXaxis()->SetTitle("back strip"); frame2.Draw(); TGraph graph(32*14,xx,yy); graph.Draw("*"); graph.Write(); fwhmCan.Write(); g.Write(); }
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 RPCChambersCluster::variousStudyExperimentalFunction(TFile * fileToSave,TH1F * histo[10],const int & eventNum){ // Save file is used to save all the reconstructed graphs with tracks in order to inspect them RPCChamber * currentChamberObj; RPCChamber * triggerObj; RPCLinkBoardChannel * currentChannelObj; int numberOfChambers = this->getNumberOfChambers(); triggerObj = this->getTriggerObjectNumber(1); TGraphErrors * graphToFit; //currentChamberObj = this->getChamberNumber(1); int numberOfReferenceChambers = 0; // change this value for the three cases - CERN, Ghent and BARC vector<int> tempCluster; TH1F * hist1,* hist2,* hist3,* hist4, * numberOfClustersHisto, * topMinusEachChamberAvg, * bottomMinusEachChamberAvg,*clsSize , * numberOfClustersInSamePartitions, * histClustersPartitionDistr, * SingleMultiHits; hist1 = histo[0]; hist2 = histo[1]; hist3 = histo[2]; hist4 = histo[3]; numberOfClustersHisto = histo[4]; topMinusEachChamberAvg = histo[5]; bottomMinusEachChamberAvg = histo[6]; clsSize = histo[7]; histClustersPartitionDistr = histo[8]; SingleMultiHits = histo[9]; int timeReference = 0; int timeWindow = 0; int firstScintilatorTime = 0 ; int secondScintilatorTime = 0; int difference_reference = 0; int coincidence_time = 0 ; if (triggerObj->getChannel(32)->hasHit()){ coincidence_time = triggerObj->getChannel(32)->getHits().at(0); } ESiteFileType siteType = kIsCERNrawFile; // later make the method to take file type argument and to use it in here //TH1F * firstTriggerEntries = new TH1F("ScintStats1","ScintStats1",0,500,500); //firstTriggerEntries->SetLineColor(kBlue); //firstTriggerEntries->SetFillColor(kBlue); switch (siteType) { case kIsCERNrawFile: timeWindow = 500; numberOfReferenceChambers = 3; int countTwoHits=0; for (int i = 0 ; i < 13 ; i++){ if(triggerObj->getChannel(i+1)->hasHit() ){ if ( difference_reference == 0 || ( coincidence_time - triggerObj->getChannel(i+1)->getHits().at(0) ) < difference_reference ) { difference_reference = coincidence_time - triggerObj->getChannel(i+1)->getHits().at(0); firstScintilatorTime = triggerObj->getChannel(i+1)->getHits().at(0); } } } difference_reference = 0; for (int i = 13 ; i < 31 ; i++) { if(triggerObj->getChannel(i+1)->hasHit() ){ if ( difference_reference == 0 || ( coincidence_time - triggerObj->getChannel(i+1)->getHits().at(0) ) < difference_reference ) { difference_reference = coincidence_time - triggerObj->getChannel(i+1)->getHits().at(0); secondScintilatorTime = triggerObj->getChannel(i+1)->getHits().at(0); } } } //timeReference = timeReference/2; /* case kIsGENTrawFile: timeWindow = 20; for(int i = 0 ; i < 32 ; i++){ if(triggerObj->getChannel(i+1)->hasHit()) { triggerObj->getChannel(i+1)->getHits().at(0); } break; } case kIsBARCrawFile: timeWindow = 0; timeReference = 0; */ } timeReference = (firstScintilatorTime+secondScintilatorTime)/2; //cout << " time reference : " << timeReference << endl; //cout << " trigger entries : "; for (int i=0; i < 32 ; i++){ if (triggerObj->getChannel(i+1)->hasHit()){ // cout << " trig channel : " << i+1 << " " << triggerObj->getChannel(i+1)->getHits().at(0) << " "; } } cout << endl; // cout << " most close trigger entries : top " << firstScintilatorTime << " bottom : " << secondScintilatorTime; // cout << endl; hist1->Fill(abs(firstScintilatorTime-secondScintilatorTime)); hist2->Fill(coincidence_time - firstScintilatorTime); hist3->Fill(coincidence_time - secondScintilatorTime); // cout << "difference : " << firstScintilatorTime-secondScintilatorTime << endl; for (int totalChambers = 0 ; totalChambers < numberOfChambers ; totalChambers++){ currentChamberObj = this->getChamberNumber(totalChambers+1); cout << "Chamber " << totalChambers+1 ; for (int j=0 ; j < 96 ;j++){ currentChamberObj = this->getChamberNumber(totalChambers+1); currentChannelObj = currentChamberObj->getChannel(j+1); if (currentChannelObj->hasHit()){ cout << " channel " << currentChannelObj->getOnlineNumber() << " time " << currentChannelObj->getHits().at(0); } } cout << endl; currentChamberObj->findAllClustersForTriggerTimeReferenceAndTimeWindow(timeReference,timeWindow); // now check the clusterization methods // fill number of cluster when there is at least one if(currentChamberObj->getNumberOfClusters()){ numberOfClustersHisto->Fill(currentChamberObj->getNumberOfClusters()); } } cout << "-------------------" << endl; // cout << "Check new cluster methods" << endl; for (int totalChambers = 0 ; totalChambers < numberOfChambers ; totalChambers++){ currentChamberObj = this->getChamberNumber(totalChambers+1); // cout << "Chamber " << totalChambers+1 ; for (int i = 0 ; i < currentChamberObj->getNumberOfClusters() ; i++){ // make the difference to get the tolerance within one cluster int smallestTime = 0; int biggestTime = 0; int currentValue = 0; int sizeOfCurrentCluster = currentChamberObj->getClusterNumber(i+1).size(); tempCluster = currentChamberObj->getClusterNumber(i+1); int numberOfHits = 0 ; for (int j = 0 ; j < sizeOfCurrentCluster; j++){ // Fill the size here SingleMultiHits->Fill(currentChamberObj->getStrip(tempCluster.at(j))->getHits().size()); } clsSize->Fill(sizeOfCurrentCluster); for (int j = 0 ; j < sizeOfCurrentCluster ; j++ ){ currentValue = currentChamberObj->getStripsHitsTimesForCluster(i+1).at(j); if ( j == 0 ) { // init the values smallestTime = currentChamberObj->getStripsHitsTimesForCluster(i+1).at(j); biggestTime = currentChamberObj->getStripsHitsTimesForCluster(i+1).at(j); } else{ if ( smallestTime >= currentValue ){ smallestTime = currentValue; } if( biggestTime <= currentValue){ biggestTime = currentValue; } } } if (biggestTime - smallestTime != 0){ hist4->Fill(biggestTime-smallestTime); } int avgTimeForCluster = currentChamberObj->getAverageTimeForCluster(i+1); topMinusEachChamberAvg->Fill(abs(firstScintilatorTime - avgTimeForCluster)); bottomMinusEachChamberAvg->Fill(abs(secondScintilatorTime - avgTimeForCluster)); // cout << endl << "Cluster " << i+1 << " toptime " << biggestTime << " leasttime " << smallestTime ; } // cout << endl; } // cout << "-------Second check done-----------" << endl; // try with single cluster per chamber vector<int> vectorOfReferenceChambers; for (int i=0; i < this->getNumberOfChambers() ; i ++){ currentChamberObj = this->getChamberNumber(i+1); if (currentChamberObj->isReferenceChamber() && !currentChamberObj->getNumberOfClusters()){ // the reference chamber does not have a hit (cluster), probably inefficient (or else) , skip the execution break; } } // remove the following when the configuration object is introduced // done, change the implementation vectorOfReferenceChambers.push_back(1); vectorOfReferenceChambers.push_back(4); vectorOfReferenceChambers.push_back(6); /** Determination of track starts here */ // Move this part in separated method //TFile * goodTracks = new TFile("GoodTracks.root","UPDATE"); //TFile * badTracks = new TFile("BadTracks.root","UPDATE"); int globalCount = 1; 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[2])->getNumberOfClusters() ; k++ ){ // check the multiplicity. use 5 as upper limit number // with the test run 2202 - CERN channel 33 is noisy so there is a condition only for it here TO DO - remove the channel 33 condition // old function /** Hits : first , use the time to distinguish useless crap - like noisy channels * * 2. Check the partition plane (YZ plane) for vertical tracks. If the track is vertical don't search for consecutiveness and don't fill the YZ histo * 3. Check the partitions plane for consecutiveness - one could not expect track that passes 3 -> 1 -> 3 partitions * */ if(this->getChamberNumber(vectorOfReferenceChambers[0])->getSizeOfCluster(i+1) > 5 || this->getChamberNumber(vectorOfReferenceChambers[1])->getSizeOfCluster(j+1) > 5 || this->getChamberNumber(vectorOfReferenceChambers[2])->getSizeOfCluster(k+1) > 5 ) continue; // 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 int RefChamberClusterPartition[3] ; int currentDifference = 0; bool positive = false; bool negative = false; int partitionPenetrated = 1; // the Y coordinate is the partition number ( 1 2 or 3 - A B or C) RefChamberClusterPartition[0] = this->getChamberNumber(vectorOfReferenceChambers[0])->getXYCoordinatesOfCluster(i+1).at(1); RefChamberClusterPartition[1] = this->getChamberNumber(vectorOfReferenceChambers[1])->getXYCoordinatesOfCluster(j+1).at(1); RefChamberClusterPartition[2] = this->getChamberNumber(vectorOfReferenceChambers[2])->getXYCoordinatesOfCluster(k+1).at(1); for ( int ii = 0; ii < 2 ; ii++ ){ direction = (RefChamberClusterPartition[ii] - RefChamberClusterPartition[ii+1]); if (direction != 0) { direction = direction/abs(direction); partitionPenetrated++; } // get only the sign ( +1 or -1) if (direction && direction == -1) positive = true; if (direction && direction == 1 ) negative = true; } // cannot have a track that goes in both direction // partition logic end here stringstream ss; ss << globalCount; string histoCounter = ss.str(); TH2F * histXZ = new TH2F(histoCounter.c_str(),"XZ plane",110,0,110,68,0,34); histXZ->SetMarkerColor(kBlue); histXZ->SetMarkerStyle(kOpenTriangleDown); // - open triangle down not found on noise server ? double * xc = new double[3]; double * yc = new double[3]; double * zc = new double[3]; vector<double> coordinates ; double xCoordinate = 0; int yCoordinate = 0; int zCoorinate = 0; coordinates = this->getChamberNumber(1)->getXYCoordinatesOfCluster(i+1); xCoordinate = coordinates.at(0); yCoordinate = coordinates.at(1); zCoorinate = 10*vectorOfReferenceChambers[0]; int prevPartition = yCoordinate; xc[0] = xCoordinate; yc[0] = yCoordinate; zc[0] = 1*10; histXZ->Fill(zc[0],xCoordinate); cout << xCoordinate << " " << yCoordinate << endl; coordinates = this->getChamberNumber(4)->getXYCoordinatesOfCluster(j+1); xCoordinate = coordinates.at(0); yCoordinate = coordinates.at(1); xc[1] = xCoordinate; yc[1] = yCoordinate; zc[1] = 4*10; histXZ->Fill(zc[1],xCoordinate); prevPartition = yCoordinate; cout << xCoordinate << " " << yCoordinate << endl; coordinates = this->getChamberNumber(6)->getXYCoordinatesOfCluster(k+1); xCoordinate = coordinates.at(0); yCoordinate = coordinates.at(1); xc[2] = xCoordinate; yc[2] = yCoordinate; zc[2] = 6*10; histXZ->Fill(zc[2],xCoordinate); cout << xCoordinate << " " << yCoordinate << endl; if ( positive && negative ) continue; TF1 * fitfunc = new TF1("FitTrack","[0]+x*[1]",0,100); Double_t * params = new Double_t[2]; histXZ->Fit(fitfunc); fitfunc->GetParameters(params); cout << "par1 " << params[0] << " par2 " << params[1] << " chi2 " << fitfunc->GetChisquare() << endl; double channelToSearchHitIn ; for (int jj = 0 ; jj < this->getNumberOfChambers() ; jj++){ if (jj+1 != vectorOfReferenceChambers[0] || jj+1 != vectorOfReferenceChambers[1] || jj+1 != vectorOfReferenceChambers[1]) // add additional rule that the chamber should exist in the calibration object { channelToSearchHitIn = fitfunc->Eval((jj+1)*10); cout << "Evaluated for chamber number " << jj+1 << " value : " << channelToSearchHitIn << endl; } } // now here - what to return, and how to get the hits in the chambers under test from the function if (fitfunc->GetChisquare() > 20) continue; // cut the execution if(fitfunc->GetChisquare() < 20){ //goodTracks->Write(trackHistoName.c_str()); histClustersPartitionDistr->Fill(partitionPenetrated); //histXZ->SaveAs((trackHistoName+".root").c_str()); // here search for hits in the chambers under test } /* else{ badTracks->Write(trackHistoName.c_str()); } */ //trackHistoName+=".root"; //histXZ->SaveAs(trackHistoName.c_str()); histXZ->Delete(); } } } // badTracks->Close("R"); // badTracks->Delete(); // goodTracks->Close("R"); // goodTracks->Delete(); }
bool FitPeak(Double_t *par, TH1 *h, Float_t &area, Float_t &darea){ Double_t binWidth = h->GetXaxis()->GetBinWidth(1000);//Need to find the bin widths so that the integral makes sense Int_t rw = binWidth*20; //This number may change depending on the source used //Set the number of iterations. The code is pretty quick, so having a lot isn't an issue TVirtualFitter::SetMaxIterations(4999); Int_t xp = par[1]; //Define the fit function and the range of the fit TF1 *pp = new TF1("photopeak",fitFunction,xp-rw,xp+rw,10); //Name the parameters so it is easy to see what the code is doing pp->SetParName(0,"Height"); pp->SetParName(1,"centroid"); pp->SetParName(2,"sigma"); pp->SetParName(3,"beta"); pp->SetParName(4,"R"); pp->SetParName(5,"step"); pp->SetParName(6,"A"); pp->SetParName(7,"B"); pp->SetParName(8,"C"); pp->SetParName(9,"bg offset"); //Set some physical limits for parameters pp->SetParLimits(1,xp-rw,xp+rw); pp->SetParLimits(3,0,30); pp->SetParLimits(4,0,10); pp->SetParLimits(5,0.000,1000000); pp->SetParLimits(9,xp-20,xp+20); //Actually set the parameters in the photopeak function pp->SetParameters(par); // pp->FixParameter(4,0); // pp->FixParameter(5,0); pp->SetNpx(1000); //Draws a nice smooth function on the graph TFitResultPtr fitres = h->Fit("photopeak","RFS"); pp->Draw("same"); pp->GetParameters(&par[0]); TF1 *photopeak = new TF1("photopeak",photo_peak,xp-rw,xp+rw,10); photopeak->SetParameters(par); Double_t integral = photopeak->Integral(xp-rw,xp+rw)/binWidth; std::cout << "FIT RESULT CHI2 " << fitres->Chi2() << std::endl; std::cout << "FWHM = " << 2.35482*fitres->Parameter(2)/binWidth <<"(" << fitres->ParError(2)/binWidth << ")" << std::endl; std::cout << "NDF: " << fitres->Ndf() << std::endl; std::cout << "X sq./v = " << fitres->Chi2()/fitres->Ndf() << std::endl; TVirtualFitter *fitter = TVirtualFitter::GetFitter(); assert(fitter != 0); //make sure something was actually fit Double_t * covMatrix = fitres->GetCovarianceMatrix(); //This allows us to find the uncertainty in the integral Double_t sigma_integral = photopeak->IntegralError(xp-rw,xp+rw)/binWidth; std::cout << "Integral = " << integral << " +/- " << sigma_integral << std::endl; area = integral; darea = sigma_integral; if(fitres->Chi2()/fitres->Ndf() > 5.0) return false; return true; // myFitResult.fIntegral = integral; // return photopeak; }
// Function for the computation of channeling efficiency at various incoming angle Int_t AnalyseChannelingEfficiency(TTree *fTree,Float_t fChannelingMinimum = 35., Float_t fChannelingMaximum = 70.){ //**//Channeling Gaussian Fit Function TF1 *vChanneling = new TF1("vChanneling","gaus",fChannelingMinimum,fChannelingMaximum); vChanneling->SetParNames("Const","Mean","Sigma"); vChanneling->SetLineColor(4); vChanneling->SetLineStyle(2); TH2D *hChannelingPlot = new TH2D("hChannelingPlot","Deflection Angle vs. Incoming Angle;Horizontal Incoming Angle [#murad];Horizontal Deflection Angle [#murad]",21,-10.5,10.5,256,-127.5,128.5); TH1F *hChannelingEfficiency = new TH1F("hChannelingEfficiency","G4Channeling;Horizontal Incoming Angle [#murad];Efficiency [%]",21,-10.5,10.5); fTree->Draw("-(angXout-angXin):-angXin>>hChannelingPlot"); Double_t vNormalizationToAmorphous = 0.965; // Normalization for channeling efficiency, see PRSTAB 11, 063501 (2008) for(int i=2;i<=21;i++){ TH1D* h1 = hChannelingPlot->ProjectionY("h1",i,i); h1->Fit(vChanneling,"QR"); Double_t *vChannelingParameters; vChannelingParameters = vChanneling->GetParameters(); hChannelingEfficiency->SetBinContent(i,ComputeEfficiency(h1,vChannelingParameters)/vNormalizationToAmorphous); h1->Delete(); } hChannelingEfficiency->SetLineColor(3); hChannelingEfficiency->SetLineStyle(4); hChannelingEfficiency->SetMarkerColor(3); hChannelingEfficiency->SetFillStyle(0); hChannelingEfficiency->SetMarkerStyle(20); hChannelingEfficiency->Draw("PL"); TGraph* gRoughExperimentalData = new TGraph(11); gRoughExperimentalData->SetPoint( 0 , -10 , 20 ); gRoughExperimentalData->SetPoint( 1 , -8 , 38 ); gRoughExperimentalData->SetPoint( 2 , -6 , 56 ); gRoughExperimentalData->SetPoint( 3 , -4 , 72 ); gRoughExperimentalData->SetPoint( 4 , -2 , 80 ); gRoughExperimentalData->SetPoint( 5 , 0 , 84 ); gRoughExperimentalData->SetPoint( 6 , 2 , 82 ); gRoughExperimentalData->SetPoint( 7 , 4 , 78 ); gRoughExperimentalData->SetPoint( 8 , 6 , 66 ); gRoughExperimentalData->SetPoint( 9 , 8 , 52 ); gRoughExperimentalData->SetPoint( 10 , 10 , 37 ); gRoughExperimentalData->SetLineColor(4); gRoughExperimentalData->SetLineStyle(3); gRoughExperimentalData->SetFillStyle(0); gRoughExperimentalData->SetFillColor(0); gRoughExperimentalData->SetMarkerColor(4); gRoughExperimentalData->SetMarkerStyle(21); gRoughExperimentalData->SetTitle("Phys. Lett. B 680, 129"); gRoughExperimentalData->Draw("sameCP"); TLegend *aLegend = new TLegend(0.30,0.15,0.55,0.3); aLegend->AddEntry(hChannelingEfficiency); aLegend->AddEntry(gRoughExperimentalData); aLegend->SetFillStyle(0); aLegend->SetLineColor(0); aLegend->Draw(); return 0; }
void UpsilonMassFit_All(int iSpec = 3, int PutWeight=1) { //See pT Cut double PtCut= 4.0; //minbias integrated, |y|<1.2 and |y|\in[1.2,2.4], centrality [0,10][10,20][20,100]%, pt [0,6.5], [6.5, 10] [10,20] gROOT->SetStyle("Plain"); gStyle->SetPalette(1); gStyle->SetFrameBorderMode(0); gStyle->SetFrameFillColor(0); gStyle->SetCanvasColor(0); gStyle->SetTitleFillColor(0); gStyle->SetStatColor(0); gStyle->SetPadBorderSize(0); gStyle->SetCanvasBorderSize(0); gStyle->SetOptTitle(1); // at least most of the time gStyle->SetOptStat(1); // most of the time, sometimes "nemriou" might be useful to display name, //number of entries, mean, rms, integral, overflow and underflow gStyle->SetOptFit(1); // set to 1 only if you want to display fit results //==================================== Define Histograms==================================================== ofstream dataFile(Form("Eff_Upsilon.txt")); TH1D *diMuonsInvMass_Gen = new TH1D("diMuonsInvMass_Gen","diMuonsInvMass_Gen", 100,8.0,12.0); TH1D *diMuonsPt_Gen = new TH1D("diMuonsPt_Gen","diMuonsPt_Gen", 100,0,30); //Rapidity Gen TH1D *diMuonsRap_Gen0 = new TH1D("diMuonsRap_Gen0","diMuonsRap_Gen0", 100,-5,5); TH1D *diMuonsRap_Gen1 = new TH1D("diMuonsRap_Gen1","diMuonsRap_Gen1", 100,-5,5); TH1D *diMuonsRap_Gen2 = new TH1D("diMuonsRap_Gen2","diMuonsRap_Gen2", 100,-5,5); TH1D *diMuonsRap_Gen3 = new TH1D("diMuonsRap_Gen3","diMuonsRap_Gen3", 100,-5,5); TH1D *diMuonsRap_Gen4 = new TH1D("diMuonsRap_Gen4","diMuonsRap_Gen4", 100,-5,5); TH1D *diMuonsRap_Gen5 = new TH1D("diMuonsRap_Gen5","diMuonsRap_Gen5", 100,-5,5); ////Rapidity Reco TH1D *diMuonsRap_Rec0 = new TH1D("diMuonsRap_Rec0","diMuonsRap_Rec0", 100,-5,5); diMuonsRap_Rec0->SetLineColor(2); TH1D *diMuonsRap_Rec1 = new TH1D("diMuonsRap_Rec1","diMuonsRap_Rec1", 100,-5,5); diMuonsRap_Rec1->SetLineColor(2); TH1D *diMuonsRap_Rec2 = new TH1D("diMuonsRap_Rec2","diMuonsRap_Rec2", 100,-5,5); diMuonsRap_Rec2->SetLineColor(2); TH1D *diMuonsRap_Rec3 = new TH1D("diMuonsRap_Rec3","diMuonsRap_Rec3", 100,-5,5); diMuonsRap_Rec3->SetLineColor(2); TH1D *diMuonsRap_Rec4 = new TH1D("diMuonsRap_Rec4","diMuonsRap_Rec4", 100,-5,5); diMuonsRap_Rec4->SetLineColor(2); TH1D *diMuonsRap_Rec5 = new TH1D("diMuonsRap_Rec5","diMuonsRap_Rec5", 100,-5,5); diMuonsRap_Rec5->SetLineColor(2); TH1D *Bin_Gen = new TH1D("Bin_Gen","Bin_Gen", 40,0,40); //==============================================Define AccEff Stuff here=========================================== // Pt bin sizes int Nptbin=1; double pt_bound[100] = {0}; if(iSpec == 1) { Nptbin = 8; //for plots pt_bound[0] = 0.0; pt_bound[1] = 2.0; pt_bound[2] = 4.0; pt_bound[3] = 6.0; pt_bound[4] = 8.0; pt_bound[5] = 10.0; pt_bound[6] = 14.0; pt_bound[7] = 20.0; pt_bound[8] = 30.0; //pt_bound[0] = 0; //pt_bound[1] = 20.0; //pt_bound[2] = 0.0; //pt_bound[3] = 6.5; //pt_bound[4] = 10.0; //pt_bound[5] = 20.0; } if(iSpec == 2) { Nptbin = 8; pt_bound[0] = -2.4; pt_bound[1] = -1.6; pt_bound[2] = -1.2; pt_bound[3] = -0.8; pt_bound[4] = 0.0; pt_bound[5] = 0.8; pt_bound[6] = 1.2; pt_bound[7] = 1.6; pt_bound[8] = 2.4; //pt_bound[0] = 0.0; //pt_bound[1] = 1.2; //pt_bound[2] = 2.4; } if(iSpec == 3) { Nptbin = 8; // pt_bound[0] = 0.0;//0 //pt_bound[1] = 8.0;//20 //pt_bound[2] = 24.0;//60 //pt_bound[3] = 40.0;//100 //for plots pt_bound[0] = 0.0;//0 pt_bound[1] = 4.0;//10 pt_bound[2] = 8.0;//20 pt_bound[3] = 12.0;//25 pt_bound[4] = 16.0;//50 pt_bound[5] = 20.0;//100 pt_bound[6] = 24.0; pt_bound[7] = 32.0; pt_bound[8] = 40.0; } //X Axis error on Eff graph double PT[100], DelPT[100], mom_err[100]; for (Int_t ih = 0; ih < Nptbin; ih++) { PT[ih] = (pt_bound[ih] + pt_bound[ih+1])/2.0; DelPT[ih] = pt_bound[ih+1] - pt_bound[ih]; mom_err[ih] = DelPT[ih]/2.0; } double genError, recError; double gen_pt[100]={0}, gen_ptError[100]={0}; double rec_pt[100]={0}, rec_ptError[100]={0}; double Eff_cat_1[100]={0},Err_Eff_cat_1[100]={0}; // Histogram arrays TH1D *diMuonsInvMass_GenA[10][1000]; TH1D *diMuonsInvMass_RecA[10][1000]; TH1D *diMuonsPt_GenA[10][1000]; TH1D *diMuonsPt_RecA[10][1000]; char nameGen[10][500], nameRec[10][500], nameGenPt[10][500], nameRecPt[10][500]; for (int ifile = 0; ifile <= 5; ifile++) { for (Int_t ih = 0; ih < Nptbin; ih++) { sprintf(nameGen[ifile],"DiMuonMassGen_pt_%d_%d",ih,ifile); sprintf(nameRec[ifile],"DiMuonMassRec_pt_%d_%d",ih,ifile); sprintf(nameGenPt[ifile],"DiMuonPtGen_pt_%d_%d",ih,ifile); sprintf(nameRecPt[ifile],"DiMuonPtRec_pt_%d_%d",ih,ifile); diMuonsInvMass_GenA[ifile][ih]= new TH1D(nameGen[ifile],nameGen[ifile], 100,8.0,12.0); //for eff Gen; diMuonsInvMass_GenA[ifile][ih]->Sumw2(); diMuonsInvMass_GenA[ifile][ih]->SetMarkerStyle(7); diMuonsInvMass_GenA[ifile][ih]->SetMarkerColor(4); diMuonsInvMass_GenA[ifile][ih]->SetLineColor(4); diMuonsInvMass_RecA[ifile][ih] = new TH1D(nameRec[ifile],nameRec[ifile], 100,8.0,12.0); //for eff Rec; diMuonsInvMass_RecA[ifile][ih]->Sumw2(); diMuonsInvMass_RecA[ifile][ih]->SetMarkerStyle(8); diMuonsInvMass_RecA[ifile][ih]->SetMarkerColor(4); diMuonsInvMass_RecA[ifile][ih]->SetLineColor(4); diMuonsPt_GenA[ifile][ih]= new TH1D(nameGenPt[ifile],nameGenPt[ifile], 100,0,40); //for eff Gen; diMuonsPt_RecA[ifile][ih]= new TH1D(nameRecPt[ifile],nameRecPt[ifile], 100,0,40); //for eff Rec; } } //===========================================Input Root File============================================================ char fileName[10][500]; //0.0380228 0.0480769 0.0293255 0.0125156 0.00336587 0.00276319*2/5 = 0.001105276 //Scales double scale[10]={0}; scale[0]=(6.8802); // pT [0-3] scale[1]=(8.6995); // pT [3-6] scale[2]=(5.3065); // pT [6-9] scale[3]=(2.2647); // pT [9-12] scale[4]=(3.0453); // pT [12-15] scale[5]=(1.0000); // pT [15-30] sprintf(fileName[0],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt03_N.root"); sprintf(fileName[1],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt36_N.root"); sprintf(fileName[2],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt69_N.root"); sprintf(fileName[3],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt912_N.root"); sprintf(fileName[4],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1215_N.root"); sprintf(fileName[5],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1530_N.root"); TFile *infile; TTree *tree; TTree *gentree; //===========File loop ====================== for(int ifile =0; ifile<=5; ifile++){ infile=new TFile(fileName[ifile],"R"); tree=(TTree*)infile->Get("SingleMuonTree"); gentree=(TTree*)infile->Get("SingleGenMuonTree"); //Event variables int eventNb,runNb,lumiBlock, gbin, rbin; //Jpsi Variables Double_t JpsiMass,JpsiPt,JpsiRap, JpsiCharge; Double_t JpsiVprob; //2.) muon variables RECO double muPosPx, muPosPy, muPosPz, muPosEta, muPosPt,muPosP; double muNegPx, muNegPy, muNegPz, muNegEta, muNegPt,muNegP; //(1).Positive Muon double muPos_nchi2In, muPos_dxy, muPos_dz, muPos_nchi2Gl; int muPos_found, muPos_pixeLayers, muPos_nValidMuHits,muPos_arbitrated; bool muPos_matches,muPos_tracker; //(2).Negative Muon double muNeg_nchi2In, muNeg_dxy, muNeg_dz, muNeg_nchi2Gl; int muNeg_found, muNeg_pixeLayers, muNeg_nValidMuHits,muNeg_arbitrated; bool muNeg_matches,muNeg_tracker; //Gen Level variables //Gen JPsi Variables double GenJpsiMass, GenJpsiPt, GenJpsiRap; double GenJpsiPx, GenJpsiPy, GenJpsiPz; //2.) Gen muon variables double GenmuPosPx, GenmuPosPy, GenmuPosPz, GenmuPosEta, GenmuPosPt; double GenmuNegPx, GenmuNegPy, GenmuNegPz, GenmuNegEta, GenmuNegPt; //Event variables tree->SetBranchAddress("eventNb",&eventNb); tree->SetBranchAddress("runNb",&runNb); tree->SetBranchAddress("lumiBlock",&lumiBlock); //Jpsi Variables tree->SetBranchAddress("JpsiCharge",&JpsiCharge); tree->SetBranchAddress("JpsiMass",&JpsiMass); tree->SetBranchAddress("JpsiPt",&JpsiPt); tree->SetBranchAddress("JpsiRap",&JpsiRap); tree->SetBranchAddress("JpsiVprob",&JpsiVprob); tree->SetBranchAddress("rbin",&rbin); //muon variable tree->SetBranchAddress("muPosPx",&muPosPx); tree->SetBranchAddress("muPosPy",&muPosPy); tree->SetBranchAddress("muPosPz",&muPosPz); tree->SetBranchAddress("muPosEta",&muPosEta); tree->SetBranchAddress("muNegPx", &muNegPx); tree->SetBranchAddress("muNegPy", &muNegPy); tree->SetBranchAddress("muNegPz", &muNegPz); tree->SetBranchAddress("muNegEta", &muNegEta); //1). Positive Muon tree->SetBranchAddress("muPos_nchi2In", &muPos_nchi2In); tree->SetBranchAddress("muPos_dxy", &muPos_dxy); tree->SetBranchAddress("muPos_dz", &muPos_dz); tree->SetBranchAddress("muPos_nchi2Gl", &muPos_nchi2Gl); tree->SetBranchAddress("muPos_found", &muPos_found); tree->SetBranchAddress("muPos_pixeLayers", &muPos_pixeLayers); tree->SetBranchAddress("muPos_nValidMuHits", &muPos_nValidMuHits); tree->SetBranchAddress("muPos_matches", &muPos_matches); tree->SetBranchAddress("muPos_tracker", &muPos_tracker); tree->SetBranchAddress("muPos_arbitrated", &muPos_arbitrated); //2). Negative Muon tree->SetBranchAddress("muNeg_nchi2In", &muNeg_nchi2In); tree->SetBranchAddress("muNeg_dxy", &muNeg_dxy); tree->SetBranchAddress("muNeg_dz", &muNeg_dz); tree->SetBranchAddress("muNeg_nchi2Gl", &muNeg_nchi2Gl); tree->SetBranchAddress("muNeg_found", &muNeg_found); tree->SetBranchAddress("muNeg_pixeLayers", &muNeg_pixeLayers); tree->SetBranchAddress("muNeg_nValidMuHits", &muNeg_nValidMuHits); tree->SetBranchAddress("muNeg_matches", &muNeg_matches); tree->SetBranchAddress("muNeg_tracker", &muNeg_tracker); tree->SetBranchAddress("muNeg_arbitrated", &muNeg_arbitrated); //====================================Gen Variables========================================================= //Gen Jpsi Variables gentree->SetBranchAddress("GenJpsiMass", &GenJpsiMass); gentree->SetBranchAddress("GenJpsiPt", &GenJpsiPt); gentree->SetBranchAddress("GenJpsiRap", &GenJpsiRap); gentree->SetBranchAddress("GenJpsiPx", &GenJpsiPx); gentree->SetBranchAddress("GenJpsiPy", &GenJpsiPy); gentree->SetBranchAddress("GenJpsiPz", &GenJpsiPz); gentree->SetBranchAddress("gbin",&gbin); //muon variable gentree->SetBranchAddress("GenmuPosPx", &GenmuPosPx); gentree->SetBranchAddress("GenmuPosPy", &GenmuPosPy); gentree->SetBranchAddress("GenmuPosPz", &GenmuPosPz); gentree->SetBranchAddress("GenmuPosEta", &GenmuPosEta); gentree->SetBranchAddress("GenmuNegPx", &GenmuNegPx); gentree->SetBranchAddress("GenmuNegPy", &GenmuNegPy); gentree->SetBranchAddress("GenmuNegPz", &GenmuNegPz); gentree->SetBranchAddress("GenmuNegEta", &GenmuNegEta); //====================================================== Gen tree loop ================================================ int NAccep=0; int nGenEntries=gentree->GetEntries(); cout<<" Total Entries in GenLevel Tree for pT range: "<<fileName[ifile]<<" "<< nGenEntries<< " ========="<<endl; //dataFile<<" Total Entries in GenLevel Tree for pT range: "<<fileName[ifile]<<" "<< nGenEntries<< " ====="<<endl; for(int i=0; i< nGenEntries; i++) { gentree->GetEntry(i); if(i%1000==0){ cout<<" processing record "<<i<<endl; cout<<" Mass "<< GenJpsiMass<< " pT "<< GenJpsiPt << " Y " <<GenJpsiRap<<endl; } bool GenPosIn=0, GenNegIn=0,GenPosPass=0,GenNegPass=0; GenmuPosPt= TMath::Sqrt(GenmuPosPx*GenmuPosPx + GenmuPosPy*GenmuPosPy); GenmuNegPt= TMath::Sqrt(GenmuNegPx*GenmuNegPx + GenmuNegPy*GenmuNegPy); diMuonsInvMass_Gen->Fill(GenJpsiMass); diMuonsPt_Gen->Fill(GenJpsiPt); if(IsAccept(GenmuPosPt, GenmuPosEta)) {GenPosIn=1;} if(IsAccept(GenmuNegPt, GenmuNegEta)) {GenNegIn=1;} if(GenPosIn && GenNegIn ) NAccep++; if(GenPosIn==1 && GenmuPosPt> PtCut) {GenPosPass=1;} if(GenNegIn==1 && GenmuNegPt> PtCut) {GenNegPass=1;} double GenCenWeight=0,GenWeight=0; GenCenWeight=FindCenWeight(gbin); Bin_Gen->Fill(gbin); GenWeight=GenCenWeight*scale[ifile]; if(PutWeight==0){GenWeight=1;} if(GenPosIn && GenNegIn){ if(ifile==0){diMuonsRap_Gen0->Fill(GenJpsiRap);} if(ifile==1){diMuonsRap_Gen1->Fill(GenJpsiRap);} if(ifile==2){diMuonsRap_Gen2->Fill(GenJpsiRap);} if(ifile==3){diMuonsRap_Gen3->Fill(GenJpsiRap);} if(ifile==4){diMuonsRap_Gen4->Fill(GenJpsiRap);} if(ifile==5){diMuonsRap_Gen5->Fill(GenJpsiRap);} } for (Int_t ih = 0; ih < Nptbin; ih++) { //adding pT of all pt bins to see diss is cont if(iSpec == 1) if( (GenPosPass==1 && GenNegPass==1) && (TMath::Abs(GenJpsiRap)<2.4 ) && (GenJpsiPt>pt_bound[ih] && GenJpsiPt<=pt_bound[ih+1])){diMuonsPt_GenA[ifile][ih]->Fill(GenJpsiPt,GenWeight);} if(iSpec == 1) if( (GenPosPass==1 && GenNegPass==1) && (TMath::Abs(GenJpsiRap)<2.4 )&&(GenJpsiPt>pt_bound[ih] && GenJpsiPt<=pt_bound[ih+1])){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight);} //if(iSpec == 2) if((GenPosPass==1 && GenNegPass==1) && (GenJpsiPt<20.0) && (TMath::Abs(GenJpsiRap) > pt_bound[ih] && TMath::Abs(GenJpsiRap) <=pt_bound[ih+1] )){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight);} //for non symetric plots if(iSpec == 2) if((GenPosPass==1 && GenNegPass==1) && (GenJpsiPt<20.0) && ((GenJpsiRap) > pt_bound[ih] && (GenJpsiRap) <=pt_bound[ih+1] )){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight);} if(iSpec == 3) if( (GenPosPass==1 && GenNegPass==1) && (GenJpsiPt < 20.0) && (TMath::Abs(GenJpsiRap)<2.4 ) && (gbin>=pt_bound[ih] && gbin<pt_bound[ih+1])){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight);} } }//gen loop end cout<<" accepted no "<< NAccep<<endl; //dataFile<<" accepted no "<< NAccep<<endl; // new TCanvas; //diMuonsInvMass_Gen->Draw(); //gPad->Print("plots/diMuonsInvMass_Gen.png"); //new TCanvas; //diMuonsPt_Gen->Draw(); //gPad->Print("plots/diMuonsPt_Gen.png"); //new TCanvas; //diMuonsRap_Gen0->Draw(); //sprintf(PlotName,"plots/diMuonsRap_Gen_%d.pdf",ifile); //gPad->Print(PlotName); //new TCanvas; //Bin_Gen->Draw(); //gPad->Print("plots/Bin_Gen.png"); //=============== Rec Tree Loop ============================================================================== int nRecEntries=tree->GetEntries(); cout<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<" "<<nRecEntries<< "====="<<endl; //dataFile<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<" "<<nRecEntries<<endl; for(int i=0; i<nRecEntries; i++) { tree->GetEntry(i); if(i%100000==0){ cout<<" processing record "<<i<<endl; cout<<" processing Run " <<runNb <<" event "<<eventNb<<" lum block "<<lumiBlock<<endl; cout<<" Mass "<< JpsiMass<< " pT "<< JpsiPt << " Y " <<JpsiRap<<" "<<JpsiVprob<<" charge "<<JpsiCharge<<endl; } bool PosPass=0, NegPass=0, AllCut=0 ,PosIn=0, NegIn=0; muPosPt= TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy); muPosP = TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy+ muPosPz*muPosPz); muNegPt= TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy); muNegP = TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy +muNegPz*muNegPz); if(IsAccept(muPosPt, muPosEta)){PosIn=1;} if(IsAccept(muNegPt, muNegEta)){NegIn=1;} if(muPos_found > 10 && muPos_pixeLayers > 0 && muPos_nchi2In < 4.0 && muPos_dxy < 3 && muPos_dz < 15 && muPos_nchi2Gl < 20 && muPos_arbitrated==1 && muPos_tracker==1 ){PosPass=1;} if((muNeg_found >10 && muNeg_pixeLayers >0 && muNeg_nchi2In <4.0 && muNeg_dxy < 3 && muNeg_dz < 15 && muNeg_nchi2Gl < 20 && muNeg_arbitrated==1 && muNeg_tracker==1)){NegPass=1;} // cout<<muPos_matches<<" "<<muNeg_matches<<endl; if((muPosPt > PtCut && muNegPt > PtCut) && (muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)){AllCut=1;} //without muon ID cuts //if((muPosPt > PtCut && muNegPt > PtCut) && (muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1)){AllCut=1;} //without trigger //if( (muPosPt > PtCut && muNegPt > PtCut) && (PosIn==1 && NegIn==1 ) && (PosPass==1 && NegPass==1)){AllCut=1;} double RecCenWeight=0,RecWeight=0; RecCenWeight=FindCenWeight(rbin); RecWeight=RecCenWeight*scale[ifile]; if(PutWeight==0){RecWeight=1;} if(i%100000==0){ cout<<" eff loop for reco "<<endl; } if(AllCut==1){ if(ifile==0){diMuonsRap_Rec0->Fill(JpsiRap);} if(ifile==1){diMuonsRap_Rec1->Fill(JpsiRap);} if(ifile==2){diMuonsRap_Rec2->Fill(JpsiRap);} if(ifile==3){diMuonsRap_Rec3->Fill(JpsiRap);} if(ifile==4){diMuonsRap_Rec4->Fill(JpsiRap);} if(ifile==5){diMuonsRap_Rec5->Fill(JpsiRap);} } //Eff loop for reco if((JpsiCharge == 0) && (JpsiVprob > 0.01)) { for (Int_t ih = 0; ih < Nptbin; ih++) { //to see cont reco pT if(iSpec == 1)if((AllCut==1) && (TMath::Abs(JpsiRap) < 2.4) && (JpsiPt>pt_bound[ih] && JpsiPt<=pt_bound[ih+1])) {diMuonsPt_RecA[ifile][ih]->Fill(JpsiPt,RecWeight);} if(iSpec == 1)if((AllCut==1) && (TMath::Abs(JpsiRap)<2.4 ) && (JpsiPt > pt_bound[ih] && JpsiPt <=pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass, RecWeight);} //if(iSpec == 2) if( (AllCut==1) && (JpsiPt<20.0) && (TMath::Abs(JpsiRap) > pt_bound[ih] && TMath::Abs(JpsiRap) <=pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass,RecWeight);} //for non symetric plots if(iSpec == 2) if( (AllCut==1) && (JpsiPt<20.0) && ((JpsiRap) > pt_bound[ih] && (JpsiRap) <=pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass,RecWeight);} if(iSpec == 3) if((AllCut==1) && (JpsiPt<20.0) && (TMath::Abs(JpsiRap) < 2.4) && (rbin>=pt_bound[ih] && rbin < pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass,RecWeight);} } } } /* new TCanvas; if(ifile==0){diMuonsRap_Gen0->Draw();new TCanvas; diMuonsRap_Rec0->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen0.png");} if(ifile==1){diMuonsRap_Gen1->Draw();new TCanvas; diMuonsRap_Rec1->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen1.png");} if(ifile==2){diMuonsRap_Gen2->Draw();new TCanvas; diMuonsRap_Rec2->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen2.png");} if(ifile==3){diMuonsRap_Gen3->Draw();new TCanvas; diMuonsRap_Rec3->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen3.png");} if(ifile==4){diMuonsRap_Gen4->Draw();new TCanvas; diMuonsRap_Rec4->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen4.png");} if(ifile==5){diMuonsRap_Gen5->Draw();new TCanvas; diMuonsRap_Rec5->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen5.png");} */ } // file loop ends /////////////////////////////////////////////////////////////////// cout<< " adding "<<endl; TH1D *diMuonsInvMass_RecA1[100]; TH1D *diMuonsInvMass_GenA1[100]; TH1D *diMuonsPt_GenA1[100]; TH1D *diMuonsPt_RecA1[100]; TF1 *backfun_1; char namePt_1B[500];//for bkg func for(Int_t ih = 0; ih < Nptbin; ih++){ diMuonsInvMass_RecA1[ih] = diMuonsInvMass_RecA[0][ih]; diMuonsInvMass_GenA1[ih] = diMuonsInvMass_GenA[0][ih]; diMuonsPt_GenA1[ih] = diMuonsPt_GenA[0][ih]; diMuonsPt_RecA1[ih] = diMuonsPt_RecA[0][ih]; for (int ifile = 1; ifile <= 5; ifile++) { diMuonsInvMass_RecA1[ih]->Add(diMuonsInvMass_RecA[ifile][ih]); diMuonsInvMass_GenA1[ih]->Add(diMuonsInvMass_GenA[ifile][ih]); diMuonsPt_GenA1[ih]->Add(diMuonsPt_GenA[ifile][ih]); diMuonsPt_RecA1[ih]->Add(diMuonsPt_RecA[ifile][ih]); } } //===========================Fitting===================================================================// // Fit ranges double mass_low, mass_high; double MassUpsilon, WeidthUpsilon; // Low mass range upsilon width 54 KeV MassUpsilon = 9.46; WeidthUpsilon = 0.060; mass_low = 8.8; mass_high = 10.0; // Fit ranges // Fit Function crystall ball // TF1 *GAUSPOL = new TF1("GAUSPOL",CrystalBall,8.0,12.0,5); //GAUSPOL->SetParNames("#alpha","n","Mean","#sigma","N"); //GAUSPOL->SetLineWidth(2.0); //GAUSPOL->SetLineColor(2); //GAUSPOL->SetParameter(0, 1.756); //GAUSPOL->SetParameter(1, 2.636); //GAUSPOL->SetParameter(2, MassUpsilon); //GAUSPOL->SetParameter(3, WeidthUpsilon); //GAUSPOL->SetParLimits(2, 0.1*MassUpsilon,2.0*MassUpsilon); //GAUSPOL->SetParLimits(3, 0.1*WeidthUpsilon,2.0*WeidthUpsilon); // Fit Function crystall ball TF1 *GAUSPOL = new TF1("GAUSPOL",CrystalBall,8.0,12.0,6); GAUSPOL->SetParNames("Yield (#Upsilon)","BinWidth","Mean","Sigma","#alpha","n"); GAUSPOL->SetParameter(2, MassUpsilon); GAUSPOL->SetParameter(3, WeidthUpsilon); GAUSPOL->SetParLimits(3, 0.1*WeidthUpsilon,2.0*WeidthUpsilon); GAUSPOL->SetParameter(4, 1.0); GAUSPOL->SetParameter(5, 20.0); GAUSPOL->SetLineWidth(2.0); GAUSPOL->SetLineColor(2); //=====================Loop for eff=========================================================== double GenNo[100]={0}; double Eff[100]={0}; double GenError[100]={0}; double RecError[100]={0}; double errEff_cat_S1[100]={0}; double errEff_cat_S2[100]={0}; double errEff_cat_S1_1[100]={0},errEff_cat_S1_2[100]={0}; double errEff_cat_S2_1[100]={0},errEff_cat_S2_2[100]={0}; char PlotName[500],PlotName1[500], PlotName2[500]; char GPlotName[500],GPlotName1[500], GPlotName2[500]; for (Int_t ih = 0; ih < Nptbin; ih++) { cout<<" no of gen dimuons from diMuons Pt histo "<<diMuonsPt_GenA1[ih]->Integral(1,100)<<endl; cout<<" no of gen dimuons from diMuons Mass histo "<<diMuonsInvMass_GenA1[ih]->Integral(1,100)<<endl; //from pT histogram //gen_pt[ih] =diMuonsPt_GenA1[ih]->IntegralAndError(1,100,genError); gen_pt[ih] = diMuonsInvMass_GenA1[ih]->IntegralAndError(1,100,genError); gen_ptError[ih]= genError; if(iSpec==1) sprintf(PlotName,"plots/DiMuonMass_PtBin_%d.png",ih); if(iSpec==2) sprintf(PlotName,"plots/DiMuonMass_RapBin_%d.png",ih); if(iSpec==3) sprintf(PlotName,"plots/DiMuonMass_CentBin_%d.png",ih); if(iSpec==1) sprintf(PlotName1,"plots/DiMuonMass_PtBin_%d.pdf",ih); if(iSpec==2) sprintf(PlotName1,"plots/DiMuonMass_RapBin_%d.pdf",ih); if(iSpec==3) sprintf(PlotName1,"plots/DiMuonMass_CentBin_%d.pdf",ih); if(iSpec==1) sprintf(PlotName2,"plots/DiMuonMass_PtBin_%d.eps",ih); if(iSpec==2) sprintf(PlotName2,"plots/DiMuonMass_RapBin_%d.eps",ih); if(iSpec==3) sprintf(PlotName2,"plots/DiMuonMass_CentBin_%d.eps",ih); //giving inetial value for crystall ball fourth parameter diMuonsInvMass_RecA1[ih]->Rebin(2); //GAUSPOL->SetParameter(0, diMuonsInvMass_RecA1[ih]->GetMaximum()); GAUSPOL->SetParameter(0, diMuonsInvMass_RecA1[ih]->Integral(0,50)); GAUSPOL->FixParameter(1, diMuonsInvMass_RecA1[ih]->GetBinWidth(1)); new TCanvas; diMuonsInvMass_RecA1[ih]->Fit("GAUSPOL","LLMERQ", "", mass_low, mass_high); double UpsilonMass = GAUSPOL->GetParameter(2); double UpsilonWidth = GAUSPOL->GetParameter(3); double UpsilonYield = GAUSPOL->GetParameter(0); double UpsilonYieldError = GAUSPOL->GetParError(0); double par[20]; GAUSPOL->GetParameters(par); sprintf(namePt_1B,"pt_1B_%d",ih); backfun_1 = new TF1(namePt_1B, Pol2, mass_low, mass_high, 3); backfun_1->SetParameters(&par[4]); double MassLow=(UpsilonMass-3*UpsilonWidth); double MassHigh=(UpsilonMass+3*UpsilonWidth); int binlow =diMuonsInvMass_RecA1[ih]->GetXaxis()->FindBin(MassLow); int binhi =diMuonsInvMass_RecA1[ih]->GetXaxis()->FindBin(MassHigh); double binwidth=diMuonsInvMass_RecA1[ih]->GetBinWidth(1); //yield by function //rec_pt[ih] = UpsilonYield; //rec_ptError[ih]=UpsilonYieldError; cout<<"Rec diMuons from Pt histo "<<diMuonsPt_RecA1[ih]->Integral(1,100)<<endl; cout<<"Rec dimuons from mass "<<diMuonsInvMass_RecA1[ih]->Integral(1,100)<<endl; //from pT histo //rec_pt[ih]=diMuonsPt_RecA1[ih]->IntegralAndError(1, 100,recError); //yield by histogram integral rec_pt[ih] = diMuonsInvMass_RecA1[ih]->IntegralAndError(binlow, binhi,recError); rec_ptError[ih]= recError; //Cal eff Eff_cat_1[ih] = rec_pt[ih]/gen_pt[ih]; //calculate error on eff GenNo[ih]=gen_pt[ih]; Eff[ih]= Eff_cat_1[ih]; GenError[ih]=gen_ptError[ih]; RecError[ih]=rec_ptError[ih]; //error errEff_cat_S1_1[ih]= ( (Eff[ih] * Eff[ih]) /(GenNo[ih] * GenNo[ih]) ); errEff_cat_S1_2[ih]= (RecError[ih] * RecError[ih]); errEff_cat_S1[ih]= (errEff_cat_S1_1[ih] * errEff_cat_S1_2[ih]); errEff_cat_S2_1[ih]= ( (1 - Eff[ih])* (1 - Eff[ih]) ) / ( GenNo[ih] * GenNo[ih]); errEff_cat_S2_2[ih]= (GenError[ih] * GenError[ih] ) - ( RecError[ih] * RecError[ih] ); errEff_cat_S2[ih]=errEff_cat_S2_1[ih]*errEff_cat_S2_2[ih]; Err_Eff_cat_1[ih]=sqrt(errEff_cat_S1[ih] + errEff_cat_S2[ih]); //error for no weights //Err_Eff_cat_1[ih]= Eff_cat_1[ih]*TMath::Sqrt(gen_ptError[ih]*gen_ptError[ih]/(gen_pt[ih]*gen_pt[ih]) + rec_ptError[ih]*rec_ptError[ih]/(rec_pt[ih]* rec_pt[ih])); cout<<"Upsilon Yield by integral of histo: "<< diMuonsInvMass_RecA1[ih]->IntegralAndError(binlow, binhi,recError) <<" error "<< rec_ptError[ih]<<endl; cout<<"UpsilonYield by CB yield det: "<< UpsilonYield << " UpsilonWidth "<< UpsilonWidth<<" UpsilonMass "<<UpsilonMass <<endl; cout<<"Upsilon Yield by Function integral: "<< GAUSPOL->Integral(MassLow,MassHigh)/binwidth <<endl; cout<<" rec_pt[ih] "<< rec_pt[ih] <<" gen_pt[ih] "<<gen_pt[ih]<<endl; //dataFile<<" rec_pt[ih] "<< rec_pt[ih] <<" gen_pt[ih] "<<gen_pt[ih]<<endl; cout<<" eff "<< Eff_cat_1[ih]<<" error "<<Err_Eff_cat_1[ih]<<endl; dataFile<<"ih " <<ih<<" eff "<< Eff_cat_1[ih]<<" error "<<Err_Eff_cat_1[ih]<<endl; if(iSpec==1) sprintf(GPlotName,"plots/GenDiMuonMass_PtBin_%d.png",ih); if(iSpec==2) sprintf(GPlotName,"plots/GenDiMuonMass_RapBin_%d.png",ih); if(iSpec==3) sprintf(GPlotName,"plots/GenDiMuonMass_CentBin_%d.png",ih); if(iSpec==1) sprintf(GPlotName1,"plots/GenDiMuonMass_PtBin_%d.pdf",ih); if(iSpec==2) sprintf(GPlotName1,"plots/GenDiMuonMass_RapBin_%d.pdf",ih); if(iSpec==3) sprintf(GPlotName1,"plots/GenDiMuonMass_CentBin_%d.pdf",ih); if(iSpec==1) sprintf(GPlotName2,"plots/GenDiMuonMass_PtBin_%d.eps",ih); if(iSpec==2) sprintf(GPlotName2,"plots/GenDiMuonMass_RapBin_%d.eps",ih); if(iSpec==3) sprintf(GPlotName2,"plots/GenDiMuonMass_CentBin_%d.eps",ih); backfun_1->SetLineColor(4); backfun_1->SetLineWidth(1); //backfun_1->Draw("same"); gPad->Print(PlotName); gPad->Print(PlotName1); gPad->Print(PlotName2); new TCanvas; diMuonsInvMass_GenA1[ih]->Draw(); gPad->Print(GPlotName); gPad->Print(GPlotName1); gPad->Print(GPlotName2); // new TCanvas; //diMuonsPt_GenA1[ih]->Draw(); //new TCanvas; //diMuonsPt_RecA1[ih]->Draw(); } dataFile.close(); TFile *outfile; if(iSpec==1)outfile =new TFile("EffUpsilon_Pt.root","Recreate"); if(iSpec==2)outfile =new TFile("EffUpsilon_Rap.root","Recreate"); if(iSpec==3)outfile =new TFile("EffUpsilon_Cent.root","Recreate"); TGraphErrors *Eff_Upsilon = new TGraphErrors(Nptbin, PT, Eff_cat_1, mom_err,Err_Eff_cat_1); Eff_Upsilon->SetMarkerStyle(21); Eff_Upsilon->SetMarkerColor(2); Eff_Upsilon->GetYaxis()->SetTitle("Reco Eff"); if(iSpec==1) Eff_Upsilon->GetXaxis()->SetTitle("#Upsilon pT (GeV/c^{2})"); if(iSpec==2) Eff_Upsilon->GetXaxis()->SetTitle("#Upsilon rapidity"); if(iSpec==3) Eff_Upsilon->GetXaxis()->SetTitle("bin"); Eff_Upsilon->GetYaxis()->SetRangeUser(0,1.0); TLegend *legend_GP = new TLegend( 0.50,0.79,0.80,0.89); legend_GP->SetBorderSize(0); legend_GP->SetFillStyle(0); legend_GP->SetFillColor(0); legend_GP->SetTextSize(0.032); legend_GP->AddEntry(Eff_Upsilon,"PythiaEvtGen + HydjetBass", "P"); new TCanvas; Eff_Upsilon->Draw("AP"); legend_GP->Draw("Same"); Eff_Upsilon->Write(); if(iSpec==1){ gPad->Print("plots/Eff_Upsilon_Pt.pdf");gPad->Print("plots/Eff_Upsilon_Pt.png");gPad->Print("plots/Eff_Upsilon_Pt.eps");} if(iSpec==2){ gPad->Print("plots/Eff_Upsilon_Rap.pdf");gPad->Print("plots/Eff_Upsilon_Rap.png"); gPad->Print("plots/Eff_Upsilon_Rap.eps");} if(iSpec==3){ gPad->Print("plots/Eff_Upsilon_Cent.pdf");gPad->Print("plots/Eff_Upsilon_Cent.png"); gPad->Print("plots/Eff_Upsilon_Cent.eps"); } outfile->Write(); outfile->Close(); }
void fitMKVoight(TH1 *h33 , Double_t low, Double_t high, Double_t p0, Double_t p1, Double_t p2, Double_t p3, Double_t initialPar, Double_t width, Double_t Gamma, Double_t factor, Int_t draw_opt){ //double nEnt = h33->GetEntries(); double nEnt = h33->GetMaximum(); double in_par[8] = {100, initialPar, width , Gamma, p0, p1, p2}; //{A,mean,sigma,Gamma} TF1 *fitter = new TF1("fitter",myFuncBWG,low,high,8); fitter->SetParameters(&in_par[0]); fitter->SetParLimits(0,10,nEnt); fitter->SetParLimits(1,initialPar-width,initialPar+width); fitter->SetLineColor(kBlue); h33->Fit("fitter","REM+","same"); //h33->Draw("E"); TF1 *backFcn = new TF1("backFcn", "pol2",low,high); TF1 *signalFcn = new TF1("signalFcn", myVoight,low,high,4); signalFcn->SetLineColor(kBlue); signalFcn->SetLineWidth(2); Double_t par[8]; fitter->GetParameters(par); backFcn->SetParameters(&par[4]); backFcn->SetLineStyle(2); backFcn->SetLineColor(6); backFcn->SetLineWidth(1); signalFcn->SetParameters(par); signalFcn->SetLineStyle(2); signalFcn->SetLineColor(4); signalFcn->SetLineWidth(1); // backFcn->Draw("same"); //signalFcn->Draw("same"); //Double_t Intg = abs(signalFcn->Integral(par[1]-factor*par[2],par[1]+factor*par[2])); ROOT::Math::GSLIntegrator ig(1.E-6,1.E-6,1000); ROOT::Math::WrappedTF1 wf(*fitter); ig.SetFunction(wf); double Intg = ig.Integral(par[1]-factor*par[2],par[1]+factor*par[2]); Double_t Intb = abs(backFcn->Integral(par[1]-factor*par[2],par[1]+factor*par[2])); Double_t binw = h33->GetBinWidth(1); Int_t yield = Intg/binw; Int_t bckgd = Intb/binw; //Double_t ratio = double(yield)/TMath::Sqrt(double(bckgd)); Double_t ratio = double(yield)/double(yield+bckgd); cout << yield << "\t" << ratio << endl; TAxis *x=h33->GetXaxis(); TAxis *y=h33->GetYaxis(); Double_t startx=x->GetXmin()+0.45*(x->GetXmax()-x->GetXmin()); /* Double_t starty0=0.5*h33->GetMaximum(); Double_t starty1=0.56*h33->GetMaximum(); Double_t starty2=0.62*h33->GetMaximum(); Double_t starty3=0.68*h33->GetMaximum(); Double_t starty4=0.74*h33->GetMaximum(); Double_t starty5=0.8*h33->GetMaximum(); */ Double_t starty0=0.35*h33->GetMaximum(); Double_t starty1=0.43*h33->GetMaximum(); Double_t starty2=0.49*h33->GetMaximum(); Double_t starty3=0.56*h33->GetMaximum(); Double_t starty4=0.63*h33->GetMaximum(); Double_t starty5=0.7*h33->GetMaximum(); double meanError = fitter->GetParError(1); double sigmaError = fitter->GetParError(2); if (draw_opt ==1) { TLatex *sum = new TLatex(startx*0.93, starty5,Form("Yield: %i",yield)); TLatex *sum12 = new TLatex(startx*0.93, starty4,Form("Background: %i",bckgd)); TLatex *sum0=new TLatex(startx*0.93, starty3,Form("Range: #pm %2.1f #sigma",factor)); TLatex *sum2=new TLatex(startx*0.93, starty2,Form("Mean: %4.4f #pm %.4f GeV",par[1], meanError)); TLatex *sum3=new TLatex(startx*0.93, starty1,Form("#sigma: %5.4f #pm %.4f GeV",par[2], sigmaError)); //TLatex *ra = new TLatex(startx*0.93, starty0,Form("#frac{S}{#sqrt{B}}= %.1f", ratio)); TLatex *ra = new TLatex(startx*0.93, starty0,Form("#frac{S}{S+B} = %1.4f", ratio)); sum->SetTextSize(0.04); sum->SetTextColor(kBlue);//2 sum->Draw("same"); sum12->SetTextSize(0.04); sum12->SetTextColor(kBlue);//6 sum12->Draw("same"); ra->SetTextSize(0.04); ra->SetTextColor(kBlue);//was black before; ra->Draw("same"); sum0->SetTextSize(0.04); sum0->SetTextColor(kBlue);//2 sum0->Draw("same"); sum2->SetTextSize(0.04); sum2->SetTextColor(kBlue);//4 sum2->Draw("same"); sum3->SetTextSize(0.04); sum3->SetTextColor(kBlue);//4 sum3->Draw("same"); } }
//________________________________________________________________________________ void peaks(TH1* h, Int_t np=10, Int_t ij=0) { if (! h) return; npeaks = TMath::Abs(np); if (! c1) c1 = new TCanvas(); else c1->Clear(); if (c2 && ij > 0) {c2->cd(ij); h->Draw(); c2->Update();} c1->Divide(1,2); c1->cd(1); 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,5,"",0.05); printf("Found %d candidate peaks to fit\n",nfound); if (! nfound) return; //Estimate background using TSpectrum::Background TH1 *hb = s->Background(h,20,"same"); hb->Draw("same"); c1->Update(); if (c2 && ij > 0) {c2->cd(ij); h->Draw(); c2->Update();} if (np <0) return; //estimate linear background using a fitting method c1->cd(2); TF1 *fline = new TF1("fline","pol1",0,1000); fline->FixParameter(1,0.); h->Fit("fline","qnlw"); if (c2 && ij > 0) {c2->cd(ij+1); h->Draw(); c2->Update(); c1->cd(2);} //Loop on all found peaks. Eliminate peaks at the background level Double_t par[3000]; par[0] = fline->GetParameter(0); par[1] = fline->GetParameter(1); npeaks = 0; Float_t *xpeaks = s->GetPositionX(); Float_t ymax = 0; for (Int_t p=0;p<nfound;p++) { Float_t xp = xpeaks[p]; Int_t bin = h->GetXaxis()->FindBin(xp); Float_t yp = h->GetBinContent(bin); if (yp-3*TMath::Sqrt(yp) < fline->Eval(xp)) continue; par[3*npeaks+2] = yp; if (yp > ymax) ymax = yp; par[3*npeaks+3] = xp; par[3*npeaks+4] = 3; npeaks++; } cout << "Found " << npeaks << " useful peaks to fit" << endl; Int_t NP = 0; Int_t nbad = 0; TString LineH(" {\""); LineH += h->GetName(); LineH += "\""; TString Line(""); struct ParErr_t {Double_t par, err;}; ParErr_t parErr[10]; TF1 *fit = 0; if (ymax > 2*par[0]) { cout << "Now fitting: Be patient" << endl; fit = new TF1("fit",fpeaks,0,1000,2+3*npeaks); TVirtualFitter::Fitter(h2,10+3*npeaks); //we may have more than the default 25 parameters fit->SetParameter(0,par[0]); fit->FixParameter(1,0.); for (Int_t p = 0; p < npeaks; p++) { fit->SetParName(3*p+2,Form("A%i",p)); fit->SetParLimits(3*p+2,0,1e6); fit->SetParameter(3*p+2,par[3*p+2]); fit->SetParName(3*p+3,Form("#mu%i",p)); fit->SetParLimits(3*p+3,TMath::Max(0.,par[3*p+3]-2), TMath::Min(240.,par[3*p+3]+2)); fit->SetParameter(3*p+3,par[3*p+3]); fit->SetParName(3*p+4,Form("#sigma%i",p)); fit->SetParLimits(3*p+4,0.01,20); fit->SetParameter(3*p+4,par[3*p+4]); } fit->SetNpx(1000); h2->SetStats(0); h2->Fit("fit","l"); if (c2 && ij > 0) {c2->cd(ij); h2->Draw("same"); c2->Update(); c1->cd(2);} fit->GetParameters(par); for (Int_t p = 0; p<np;p++) { if (p < npeaks && par[3*p+2] > 5*fit->GetParError(3*p+2) && par[3*p+2] > par[0]) { if (TMath::Abs(par[3*p+4]) > 5.0) nbad++; // Line += Form(",%f,%f,%7.2f,%5.2f",par[3*p+2],fit->GetParError(3*p+2),par[3*p+3],TMath::Abs(par[3*p+4])); parErr[NP].par = par[3*p+3]; parErr[NP].err = TMath::Abs(par[3*p+4]); for (Int_t i = 0; i < NP; i++) { if (parErr[i].par > parErr[NP].par) { ParErr_t temp = parErr[i]; parErr[i] = parErr[NP]; parErr[NP] = temp; } } NP++; } } } for (Int_t p = 0; p < np; p++) { if (p < NP) Line += Form(",%7.2f,%5.2f",parErr[p].par,parErr[p].err); else Line += ",0,0"; } Line += "},"; if (nbad > 1) NP = -NP; // reject whole hybrid LineH += Form(",%3i",NP); cout << LineH << Line << endl; out << LineH << Line << endl; c1->Update(); if (c2) c2->Update(); delete fit; delete s; }
void pc3fit(){ gStyle->SetErrorX(0); gStyle->SetOptStat(0); gStyle->SetOptFit(1); TFile *f = TFile::Open("merged_Anappmb.root"); TString charge; ofstream fout("Run15pppc3dphidzcalib.dat"); fout<<"double dphishift[2][2][50];"<<endl; fout<<"double dzshift[2][2][50];"<<endl; fout<<"double dphisigma[2][2][50];"<<endl; fout<<"double dzsigma[2][2][50];"<<endl; TCanvas *c1 = new TCanvas("c1","c1",500,500); TCanvas *c2 = new TCanvas("c2","c2",500,500); for(int ipt=0; ipt<50; ipt++){ for(int iarm=0; iarm<2; iarm++){ for(int ich=0; ich<2; ich++){ if(ich==0) charge = "pos"; else if(ich==1) charge = "neg"; //if(iarm!=0 || ich!=1 || ipt !=1) continue; TH2F *pc3dphidz = (TH2F*)f->Get(Form("pc3dphidz_arm%d_%s_%d",iarm,charge.Data(),ipt)); if(pc3dphidz->Integral()==0){ fout<<"dphishift["<<iarm<<"]["<<ich<<"]["<<ipt<<"] = "<<-0.0<<"; "; fout<<"dzshift["<<iarm<<"]["<<ich<<"]["<<ipt<<"] = "<<-0.0<<"; "; fout<<"dphisigma["<<iarm<<"]["<<ich<<"]["<<ipt<<"] = "<<-0.0<<"; "; fout<<"dzsigma["<<iarm<<"]["<<ich<<"]["<<ipt<<"] = "<<-0.0<<"; "; continue; } TH1F* pc3dphi = (TH1F*)pc3dphidz->ProjectionX(Form("pc3dphi_%d_%d_%d",iarm,ich,ipt),0,-1); TH1F* pc3dz = (TH1F*)pc3dphidz->ProjectionY(Form("pc3dz_%d_%d_%d",iarm,ich,ipt),0,-1); //pc3dphi->Rebin(4); pc3dz->Rebin(5); pc3dphi->Scale(1./pc3dphi->Integral()); pc3dz->Scale(1./pc3dz->Integral()); TF1 *fphi = new TF1("fphi","gaus(0)+gaus(3)",-0.1,0.1); fphi->SetNpx(10000); //TF1 *fphi = new TF1("fphi","[0]*([1]*exp(-(x-[2])**2/[3]/[3])+(1-[1])*exp(-(x-[4])**2/[5]/[5]))",-0.1,0.1); fphi->SetParameters(1e-1,0,1e-3,1e-3,0,1e-2); //fphi->SetParameters(4.79253e-02,9.25529e-01,-8.56488e-05,-7.46701e-03,-5.37828e-04,5.99178e-0); SetStyle(*pc3dphi,0.8,1,20,0,0); c1->cd(); c1->SetLogy(); pc3dphi->Draw("P"); pc3dphi->Fit("fphi","RQ"); pc3dphi->Fit("fphi","RQ"); double par[6]; fphi->GetParameters(par); TF1 *fphi1 = new TF1("fphi1","gaus",-0.1,0.1); fphi1->SetNpx(10000); fphi1->SetParameters(par); TF1 *fphi2 = new TF1("fphi2","gaus",-0.1,0.1); fphi2->SetNpx(10000); fphi2->SetParameters(&par[3]); fphi1->SetLineColor(4); fphi1->Draw("same"); fphi2->SetLineColor(6); fphi2->Draw("same"); fout<<"dphishift["<<iarm<<"]["<<ich<<"]["<<ipt<<"] = "<<par[1]<<"; "; fout<<"dphisigma["<<iarm<<"]["<<ich<<"]["<<ipt<<"] = "<<par[2]<<"; "; if(par[1]>1) cout<<"Problem!: dphi: "<<"iarm = "<<iarm<<" ich = "<<ich<<" ipt = "<<ipt<<endl; c1->Print(Form("fig/pc3matching/dphi_%d_%d_%d.png",iarm,ich,ipt)); TF1 *fz = new TF1("fz","gaus(0)+gaus(3)",-10,10); //fz->SetParameters(3.02349e+07,8.32462e-01,2.39187e+00,2.17631e+07,6.35460e-01,8.09821e+00); fz->SetParameters(1e-1,0,2,1e-3,0,8); SetStyle(*pc3dz,0.8,1,20,0,0); c2->cd(); pc3dz->Draw("P"); pc3dz->Fit("fz","RQ"); fz->GetParameters(par); TF1 *fz1 = new TF1("fz1","gaus",-10,10); fz1->SetNpx(10000); fz1->SetParameters(par); TF1 *fz2 = new TF1("fz2","gaus",-10,10); fz2->SetNpx(10000); fz2->SetParameters(&par[3]); fz1->SetLineColor(4); //fz1->Draw("same"); fz2->SetLineColor(6); //fz2->Draw("same"); fout<<"dzshift["<<iarm<<"]["<<ich<<"]["<<ipt<<"] = "<<par[1]<<"; "; fout<<"dzsigma["<<iarm<<"]["<<ich<<"]["<<ipt<<"] = "<<par[2]<<"; "; if(par[1]>10) cout<<"Problem! dz: "<<"iarm = "<<iarm<<" ich = "<<ich<<" ipt = "<<ipt<<endl; c2->Print(Form("fig/pc3matching/dz_%d_%d_%d.png",iarm,ich,ipt)); } } fout<<endl; } }
void fitMKGaus_wPOINTERS(TH1D *h33 , Double_t low, Double_t high, Double_t p0, Double_t p1, Double_t p2, Double_t p3, Double_t initialPar, Double_t width, Double_t factor, Int_t draw_opt, Int_t *fitted_yield, Int_t *fitted_bckgrd, Double_t *fitted_mean, Double_t *fitted_meanerror, Double_t *fitted_sigma, Double_t *fitted_sigmaerror, Double_t *fitted_ratio ){//Double_t *array[8] double nEnt = h33->GetEntries(); TF1 *fitter = new TF1("fitter","gaus + [3] + [4]*x + [5]*x*x + [6]*x*x*x",low,high); fitter->SetParameters(100, initialPar, width, p0, p1, p2, p3); fitter->SetParLimits(0,10,nEnt); fitter->SetParLimits(1,initialPar-width,initialPar+width); h33->Fit("fitter","REM","same"); //h33->Draw("E"); TF1 *backFcn = new TF1("backFcn", "pol3",low,high); TF1 *signalFcn = new TF1("signalFcn", "gaus",low,high); signalFcn->SetLineColor(2); signalFcn->SetLineWidth(2); Double_t par[7]; fitter->GetParameters(par); backFcn->SetParameters(&par[3]); backFcn->SetLineStyle(2); backFcn->SetLineColor(6); backFcn->SetLineWidth(1); signalFcn->SetParameters(par); signalFcn->SetLineStyle(2); signalFcn->SetLineColor(4); signalFcn->SetLineWidth(1); backFcn->Draw("same"); signalFcn->Draw("same"); Double_t Intg = signalFcn->Integral(par[1]-factor*par[2],par[1]+factor*par[2]); Double_t Intb = backFcn->Integral(par[1]-factor*par[2],par[1]+factor*par[2]); Double_t binw = h33->GetBinWidth(1); Int_t yield = Intg/binw; Int_t bckgd = Intb/binw; Double_t ratio = double(yield)/TMath::Sqrt(double(bckgd)); cout << yield << "\t" << ratio << endl; TAxis *x=h33->GetXaxis(); TAxis *y=h33->GetYaxis(); Double_t startx=x->GetXmin()+0.75*(x->GetXmax()-x->GetXmin()); Double_t starty0=0.35*h33->GetMaximum(); Double_t starty1=0.45*h33->GetMaximum(); Double_t starty2=0.55*h33->GetMaximum(); Double_t starty3=0.65*h33->GetMaximum(); Double_t starty4=0.75*h33->GetMaximum(); Double_t starty5=0.85*h33->GetMaximum(); double meanError = fitter->GetParError(1); double sigmaError = fitter->GetParError(2); if (draw_opt ==1) { TLatex *sum = new TLatex(startx*0.93, starty5,Form("Yield: %i",yield)); TLatex *sum12 = new TLatex(startx*0.93, starty4,Form("Background: %i",bckgd)); TLatex *sum0=new TLatex(startx*0.93, starty3,Form("Range: #pm %2.1f #sigma",factor)); TLatex *sum2=new TLatex(startx*0.93, starty2,Form("Mean:%4.4f #pm %.4f GeV",par[1], meanError)); TLatex *sum3=new TLatex(startx*0.93, starty1,Form("#sigma:%5.4f #pm %.4f GeV",par[2], sigmaError)); TLatex *ra = new TLatex(startx*0.93, starty0,Form("#frac{S}{#sqrt{B}}= %.1f", ratio)); sum->SetTextSize(0.04); sum->SetTextColor(2); sum->Draw("same"); sum12->SetTextSize(0.04); sum12->SetTextColor(6); sum12->Draw("same"); ra->SetTextSize(0.04); ra->Draw("same"); sum0->SetTextSize(0.04); sum0->SetTextColor(2); sum0->Draw("same"); sum2->SetTextSize(0.04); sum2->SetTextColor(4); sum2->Draw("same"); sum3->SetTextSize(0.04); sum3->SetTextColor(4); sum3->Draw("same"); } (*fitted_yield) = yield; (*fitted_bckgrd) = bckgd; (*fitted_mean) = par[1]; (*fitted_meanerror) = meanError; (*fitted_sigma) = par[2]; (*fitted_sigmaerror) = sigmaError; (*fitted_ratio) =ratio; // (*array[0]) = yield; (*array[1]) = bckgd); (*array[2]) = factor; (*array[3]) = par[1]; (*array[4]) = meanError; // (*array[5]) = par[2]; (*array[6]) = sigmaError; (*array[7]) = ratio; // // for (Int_t cnt = 0; cnt < 7; cnt++) { // cout<<array[cnt]<<endl; // } // h33->GetXaxis()->SetTitle("M(e^{+}e^{-}#gamma) [GeV]"); // h33->GetYaxis()->SetTitleOffset(1.2); // // h33->GetYaxis()->SetTitle("Entries / 6 MeV"); //can1->Print("/Volumes/Mac_Storage/Physics_Papers/Annual_Review_Paper/ODU_Group_Pres/PLOTS_for_Review/New_Mass_Plots/etaprime.pdf") }
void drawPrunedJM_noDiboson(){ gStyle->SetOptStat(0); gStyle->SetOptFit(11111111); TFile *f = TFile::Open("prunedJetMMu_noDiboson.root"); TH1D* h_MCWW = (TH1D*)(f->Get("prunedJetMMu_WW_pythia_filtered")); TH1D* h_MCWZ = (TH1D*)(f->Get("prunedJetMMu_WZ_pythia_filtered")); TH1D* h_MCZZ = (TH1D*)(f->Get("prunedJetMMu_ZZ_pythia_filtered")); TH1D* h_dataMu = (TH1D*)(f->Get("prunedJetMMu_data_DoubleMu")); Double_t lumi_MCWW = 9959752/56.0; Double_t lumi_MCWZ = 9910267/22.4; Double_t lumi_MCZZ = 9769891/7.6; Double_t lumi_dataMu = 19671.225; h_MCWW->Scale(lumi_dataMu/lumi_MCWW); h_MCWZ->Scale(lumi_dataMu/lumi_MCWZ); h_MCZZ->Scale(lumi_dataMu/lumi_MCZZ); TH1D* h_allDibosonMC = new TH1D("h_allDibosonMC", "", 100, 40, 240); h_allDibosonMC->Add(h_MCWW); h_allDibosonMC->Add(h_MCWZ); h_allDibosonMC->Add(h_MCZZ); TH1D* h_dataMu_noDiboson = new TH1D("h_dataMu_noDiboson", "", 100, 40, 240); h_dataMu_noDiboson->SetTitle("Pruned jet mass distribution (data)"); h_dataMu_noDiboson->GetXaxis()->SetTitle("Mass"); h_dataMu_noDiboson->GetYaxis()->SetTitle("Event numbers"); Int_t NBIN = h_allDibosonMC->GetNbinsX(); for(Int_t i = 1; i < NBIN; i++){ Int_t binCenter = h_dataMu_noDiboson->GetBinCenter(i); Int_t binContent = h_dataMu->GetBinContent(i) - h_allDibosonMC->GetBinContent(i); if( binCenter > 110 && binCenter < 140 ) continue; h_dataMu_noDiboson->SetBinContent(i, binContent); } TF1* fitCurve = new TF1("fitCurve", fitFunc, 40, 240, 4); h_dataMu_noDiboson->Fit(fitCurve, "", "", 40, 240); Double_t nBkgSig = fitCurve->Integral(110,140)/h_dataMu->GetBinWidth(1); vector<Double_t> par; vector<Double_t> posPar; vector<Double_t> negPar; for(Int_t i = 0; i < 4; i++){ par.push_back(fitCurve->GetParameters()[i]); posPar.push_back(par[i] + fitCurve->GetParErrors()[i]); negPar.push_back(par[i] - fitCurve->GetParErrors()[i]); } Double_t x; TF1* posFit[4]; posFit[0] = new TF1("posFit1", Form("%f*TMath::Exp(%f*x)*0.5*(1+TMath::Erf((x-(%f))/%f))",posPar[0],par[1],par[2],par[3]), 40, 240); posFit[1] = new TF1("posFit2", Form("%f*TMath::Exp(%f*x)*0.5*(1+TMath::Erf((x-(%f))/%f))",par[0],posPar[1],par[2],par[3]), 40, 240); posFit[2] = new TF1("posFit3", Form("%f*TMath::Exp(%f*x)*0.5*(1+TMath::Erf((x-(%f))/%f))",par[0],par[1],posPar[2],par[3]), 40, 240); posFit[3] = new TF1("posFit4", Form("%f*TMath::Exp(%f*x)*0.5*(1+TMath::Erf((x-(%f))/%f))",par[0],par[1],par[2],posPar[3]), 40, 240); TF1* negFit[4]; negFit[0] = new TF1("negFit1", Form("%f*TMath::Exp(%f*x)*0.5*(1+TMath::Erf((x-(%f))/%f))",negPar[0],par[1],par[2],par[3]), 40, 240); negFit[1] = new TF1("negFit2", Form("%f*TMath::Exp(%f*x)*0.5*(1+TMath::Erf((x-(%f))/%f))",par[0],negPar[1],par[2],par[3]), 40, 240); negFit[2] = new TF1("negFit3", Form("%f*TMath::Exp(%f*x)*0.5*(1+TMath::Erf((x-(%f))/%f))",par[0],par[1],negPar[2],par[3]), 40, 240); negFit[3] = new TF1("negFit4", Form("%f*TMath::Exp(%f*x)*0.5*(1+TMath::Erf((x-(%f))/%f))",par[0],par[1],par[2],negPar[3]), 40, 240); TMatrixD posColM(4,1); TMatrixD negColM(4,1); TMatrixD posRowM(1,4); TMatrixD negRowM(1,4); for(Int_t i = 0; i < 4; i++){ posColM(i,0) = fabs(nBkgSig - posFit[i]->Integral(110,140)/h_dataMu->GetBinWidth(1)); negColM(i,0) = fabs(nBkgSig - negFit[i]->Integral(110,140)/h_dataMu->GetBinWidth(1)); posRowM(0,i) = posColM(i,0); negRowM(0,i) = negColM(i,0); } gMinuit->mnmatu(1); TFitResultPtr fitptr = h_dataMu_noDiboson->Fit(fitCurve, "S"); TFitResult fitresult = (*fitptr); TMatrixD corrM = fitresult.GetCorrelationMatrix(); TMatrixD posTemp = posRowM*(corrM*posColM); TMatrixD negTemp = negRowM*(corrM*negColM); Double_t posSystUnc = TMath::Sqrt(posTemp(0,0)); Double_t negSystUnc = TMath::Sqrt(negTemp(0,0)); cout << "\nNumber of background events in signal region: " << nBkgSig << " +" << posSystUnc << " -" << negSystUnc << "\n" << endl; TCanvas* c = new TCanvas("c","",0,0,800,800); c->cd(); h_dataMu_noDiboson->SetFillColor(kCyan); h_dataMu_noDiboson->Draw(); c->Print("dataMu_noDiboson.pdf"); }
void fitGausExample() { int bins = 100; int min = 0; int max = 1600; sigMin = 500; sigMax = 800; double bgMin = 100; double bgMax = 1300; double xpos; TCanvas *testCanvas = new TCanvas("testCanvas","testCanvas",600,400); //x,y pad1 = new TPad("pad1","pad1",0.0000,0.0000,1.0000,1.0000,0,0,0); pad1->Draw(); pad1->cd(); TH1F *h1 = new TH1F("h1","Fitting Example",bins,min,max); TH1F *h2 = new TH1F("h2","h2",bins,min,max); TH1F *h3 = new TH1F("h3","Fitting Example",bins,min,max); TH1F *bg = new TH1F("bg","bg",bins,min,max); // The section below will fill h1 with a guassian // function with a mean of 670 and a sigma of 20 // and fill h2 with a "uniform" random background // from bgMin<x<bgMax for (int i=0; i<10000000; i++) { // h1->Fill(gRandom->Uniform(10,1400)); h1->Fill(gRandom->Uniform(0,1600)); h1->Fill(gRandom->Exp(1400)); } for (int i=0; i<100000; i++) { // h1->Fill(gRandom->Uniform(1400,1500)); } for (int i=0; i<50000; i++) { h1->Fill(gRandom->Gaus(670,20)); } for (int i=0; i<bins; i++) { // xpos = i*((max-min)/bins)+min; // cout << "xpos: " << xpos << endl; // h1->Fill(xpos,100*exp((-1)*xpos)); // h2->Fill(i*((max-min)/bins)+min,i*500); } // h1->Add(h2,-1); h1->SetMinimum(0); h1->SetMaximum(300000); h1->Draw(); TF1 *bgFit = new TF1("bgFit","[0]+[1]*x",bgMin,bgMax); // TF1 *bgFit = new TF1("bgFit","expo",bgMin,bgMax); // TF1 *bgFit = new TF1("bgFit","exp([1]*x+[0])+[2]",bgMin,bgMax); TF1 *bgFit = new TF1("bgFit",fline,bgMin,sigMin,3); bgFit->SetLineColor(kOrange); bgFit->SetParameter(0,1); bgFit->SetParameter(1,1/1600); bgFit->SetParameter(2,1); bgFit->SetParName(0,"Offset"); bgFit->SetParName(1,"Tau"); bgFit->SetParName(2,"Background"); reject = kTRUE; h1->Fit(bgFit,"R"); reject = kFALSE; TF1 *fleft = new TF1("fleft",fline,bgMin,sigMin,3); fleft->SetLineColor(kOrange); fleft->SetParameters(bgFit->GetParameters()); h1->GetListOfFunctions()->Add(fleft); gROOT->GetListOfFunctions()->Remove(fleft); TF1 *fright = new TF1("fright",fline,sigMax,bgMax,3); fright->SetLineColor(kOrange); fright->SetParameters(bgFit->GetParameters()); h1->GetListOfFunctions()->Add(fright); gROOT->GetListOfFunctions()->Remove(fright); // h1->SetMaximum(300000); h1->Draw(); double fitOffset = bgFit->GetParameter(0); double fitTau = bgFit->GetParameter(1); // double fitBackground = bgFit->GetParameter(2); double fitOffsetErr = bgFit->GetParError(0); double fitTauErr = bgFit->GetParError(1); // double fitBackgroundErr = bgFit->GetParError(2); cout << "Number of Bins: " << h1->GetSize()-2 << endl;; cout << "fitOffset: " << fitOffset << endl;; cout << "fitTau: " << fitTau << endl;; for (int i=0; i<(h1->GetSize()-2); i++) { xpos = i*((max-min)/bins)+min; // h2->Fill(xpos,i*500); bg->Fill(xpos,(fitOffset + fitTau*xpos)); // bg->Fill(xpos,(exp(fitTau*xpos + fitOffset) + fitBackground)); } bg->SetLineColor(kBlue); bg->Draw("same"); h3->Add(h1); h3->Add(bg,-1); h3->SetLineColor(kRed); h3->SetMinimum(0); h3->Draw("same"); cout << "sigMin: " << sigMin << ", sigMax: " << sigMax << endl; TF1 *sigFit = new TF1("sigFit","gaus",sigMin,sigMax); sigFit->SetLineColor(kBlue); sigFit->SetParameter(0,1000); sigFit->SetParameter(1,690); sigFit->SetParameter(2,20); sigFit->SetParameter(3,1); sigFit->SetParName(0,"Weight"); sigFit->SetParName(1,"Mean"); sigFit->SetParName(2,"Sigma"); // sigFit->SetParName(3,"Background"); h3->SetMaximum(300000); h3->Fit(sigFit,"R"); sigFit->Draw("same"); double fitWeight = sigFit->GetParameter(0); double fitMean = sigFit->GetParameter(1); double fitSigma = sigFit->GetParameter(2); double fitWeightErr = sigFit->GetParError(0); double fitMeanErr = sigFit->GetParError(1); double fitSigmaErr = sigFit->GetParError(2); fitResults = new TPaveText(0.11,0.70,0.4,0.89,"NDC"); TString WeightStr = "Weight = "; WeightStr += fitWeight; WeightStr += " ± "; WeightStr += fitWeightErr; TString MeanStr = "Mean = "; MeanStr += fitMean; MeanStr += " ± "; MeanStr += fitMeanErr; TString SigmaStr = "Sigma = "; SigmaStr += sqrt(fitSigma*fitSigma); SigmaStr += " ± "; SigmaStr += fitSigmaErr; TString OffsetStr = "Offset = "; OffsetStr += fitOffset; OffsetStr += " ± "; OffsetStr += fitOffsetErr; TString TauStr = "Tau = "; TauStr += fitTau; TauStr += " ± "; TauStr += fitTauErr; TString BackgroundStr = "BackgroundConst = "; BackgroundStr += fitBackground; BackgroundStr += " ± "; BackgroundStr += fitBackgroundErr; TText *t1 = fitResults->AddText(WeightStr); TText *t2 = fitResults->AddText(MeanStr); TText *t3 = fitResults->AddText(SigmaStr); TText *t4 = fitResults->AddText(BackgroundStr); TText *t5 = fitResults->AddText(TauStr); TText *t6 = fitResults->AddText(OffsetStr); h1->Draw("same"); TString theFitStr = "("; theFitStr += fitWeight; theFitStr += "*exp(-0.5*((x-"; theFitStr += fitMean; theFitStr += ")/"; theFitStr += fitSigma; theFitStr += ")^2))+"; theFitStr += fitBackground; theFitStr += "+exp("; theFitStr += fitTau; theFitStr += "*x+"; theFitStr += fitOffset; theFitStr += ")"; TF1 *theFit = new TF1("theFit",theFitStr,bgMin,bgMax); theFit->SetLineColor(kMagenta); theFit->Draw("same"); double integralOfPeak; integralOfPeak = sigFit->Integral((fitMean - 3*sqrt(fitSigma*fitSigma)),(fitMean + 3*sqrt(fitSigma*fitSigma))); TString peakInt = "Integral of Peak: "; peakInt += integralOfPeak; cout << peakInt << endl; TText *t7 = fitResults->AddText(peakInt); pad1->Update(); TString outputPlotsHere = "/home/ellie/physics/e05-102/analysis-scripts/devel/test_stuff/"; TString testOutTitle = outputPlotsHere; testOutTitle += "test_out_step_1"; testOutTitle += ".svg"; fitResults->Draw("same"); }
void linfitMKDoubleGaus(TH1 *h33 , Double_t low, Double_t high, Double_t p0, Double_t p1, Double_t initialPar, Double_t width, Double_t factor, Int_t draw_opt){ double nEnt = h33->GetEntries(); TF1 *fitter = new TF1("fitter","gaus(0) + gaus(3) + [6] + [7]*x",low,high); fitter->SetParameters(100, initialPar, width, 100, initialPar, width/2., p0, p1); fitter->SetParLimits(0,10,nEnt); fitter->SetParLimits(1,initialPar-width,initialPar+width); fitter->SetParLimits(3,10,nEnt); fitter->SetParLimits(4,initialPar-width/2.,initialPar+width/2.); h33->Fit("fitter","REM","same"); //h33->Draw("E"); TF1 *backFcn = new TF1("backFcn", "[0] + [1]*x",low,high); TF1 *signalFcn = new TF1("signalFcn", "gaus(0) + gaus(3)",low,high); signalFcn->SetLineColor(2); signalFcn->SetLineWidth(2); Double_t par[8]; fitter->GetParameters(par); signalFcn->SetParameters(par); signalFcn->SetLineStyle(2); signalFcn->SetLineColor(4); signalFcn->SetLineWidth(1); backFcn->SetParameters(&par[6]); backFcn->SetLineStyle(2); backFcn->SetLineColor(6); backFcn->SetLineWidth(1); backFcn->Draw("same"); signalFcn->Draw("same"); Double_t Intg = abs(signalFcn->Integral(par[1]-factor*fabs(par[2]),par[1]+factor*fabs(par[2]))); Double_t Intb = abs(backFcn->Integral(par[1]-factor*fabs(par[2]),par[1]+factor*fabs(par[2]))); Double_t binw = h33->GetBinWidth(1); Int_t yield = Intg/binw; Int_t bckgd = Intb/binw; Double_t ratio = double(yield)/(double(yield+bckgd)); //(double(yield+bckgd) cout << yield << "\t" <<bckgd<<"\t"<< ratio << endl; TAxis *x=h33->GetXaxis(); TAxis *y=h33->GetYaxis(); Double_t startx=x->GetXmin()+0.75*(x->GetXmax()-x->GetXmin()); Double_t starty=0.65*h33->GetMaximum(); Double_t starty1=0.55*h33->GetMaximum(); Double_t starty0=0.75*h33->GetMaximum(); Double_t starty2=0.95*h33->GetMaximum(); Double_t starty3=0.85*h33->GetMaximum(); double meanError = fitter->GetParError(4); double sigmaError = fitter->GetParError(5); if (draw_opt ==1) { TLatex *sum = new TLatex(startx*0.83, starty,Form("Yield: %i",yield)); TLatex *sum12 = new TLatex(startx*0.83, starty*0.84,Form("Background: %i",bckgd)); TLatex *sum0=new TLatex(startx*0.83, starty0,Form("Range: #pm %2.1f #sigma",factor)); TLatex *sum2=new TLatex(startx*0.83, starty2,Form("Mean:%3.3f #pm %.3f",par[4], meanError)); TLatex *sum3=new TLatex(startx*0.83, starty3,Form("#sigma:%5.4f #pm %.4f GeV",par[5], sigmaError)); TLatex *ra = new TLatex(startx*0.83, starty*0.6,Form("#frac{S}{S+B}= %.3f", ratio)); sum->SetTextSize(0.04); sum->SetTextColor(2); //sum->Draw("same"); sum12->SetTextSize(0.04); sum12->SetTextColor(6); //sum12->Draw("same"); //ra->Draw("same"); sum0->SetTextSize(0.04); sum0->SetTextColor(2); //sum0->Draw("same"); sum2->SetTextSize(0.04); sum2->SetTextColor(4); sum2->Draw("same"); sum3->SetTextSize(0.04); sum3->SetTextColor(4); //sum3->Draw("same"); } // h33->GetXaxis()->SetTitle("M(e^{+}e^{-}#gamma) [GeV]"); // h33->GetYaxis()->SetTitleOffset(1.2); // // h33->GetYaxis()->SetTitle("Entries / 6 MeV"); //can1->Print("/Volumes/Mac_Storage/Physics_Papers/Annual_Review_Paper/ODU_Group_Pres/PLOTS_for_Review/New_Mass_Plots/etaprime.pdf") }
//=============================== void FitSignalBG(Double_t nSigma, Int_t iRapBin, Int_t iPTBin){ gStyle->SetOptFit(kTRUE); gStyle->SetOptStat(kFALSE); Char_t name[100]; //1.) perform the fit to the continuum, using the sidebands sprintf(name, "c1_rap%d_pT%d", iRapBin, iPTBin); TCanvas *c1 = new TCanvas(name); sprintf(name, "Counts per %1.0f MeV", 1000.*binWidth); c1->SetFillColor(0); c1->SetLeftMargin(0.15); hMass->SetYTitle(name); hMass->SetXTitle("M_{#mu#mu} [GeV]"); hMass->SetTitleOffset(1.5, "y"); hMass->SetStats(0); hMass->Draw(); //starting values for fit: Double_t a = -2.0e6, b = 5.e5, c = -2.4e4; Double_t range_min = 8.6, range_max = 11.4; Double_t normY1S = hMass->GetMaximum() / binWidth; Double_t normY2S = 0.3*normY1S; Double_t normY3S = 0.15*normY1S; Double_t sigma1S = 0.1, mean1S = 9.45; Double_t alpha = 1.33, n = 6.6; //CB-tail parameters printf("will be fitting the continuum between %1.2f < M < %1.2f\n", range_min, range_max); sprintf(name, "fCont"); TF1* fCONT = new TF1(name, fitContinuum, range_min, range_max, 3); fCONT->SetParameters(a, b, c); hMass->Fit(fCONT, "0", "", range_min, range_max); fCONT = hMass->GetFunction(name); Double_t chisqrd = fCONT->GetChisquare(); Int_t NDF = fCONT->GetNDF(); Double_t redChi2 = chisqrd/NDF; printf("\nChisqrd = %1.3f, NDF = %d, Chisqrd/NDF = %1.3f, Prob = %1.3f\n\n", chisqrd, NDF, redChi2, TMath::Prob(chisqrd,NDF)); fCONT->GetParameters(fitParBG); for(int iPar = 0; iPar < 3; iPar++){ fitParBGerr[iPar]=fCONT->GetParError(iPar); } //2.) fit the peaks on the top of a fixed continuum sprintf(name,"fPeaks"); Int_t const npar = 10; fRECO = new TF1(name, fitPolyCrystal3, peak_min, peak_max, npar); fRECO->SetParNames("normY1S", "mass_Ups1S", "sigma_Ups1S", "normY2S", "normY3S", "n", "alpha", "a", "b", "c"); fRECO->SetParameters(normY1S, mean1S, sigma1S, normY2S, normY3S, n, alpha, a, b, c); fRECO->FixParameter(7,fitParBG[0]); fRECO->FixParameter(8,fitParBG[1]); fRECO->FixParameter(9,fitParBG[2]); //fix alpha and n from the fit to all bins if(iPTBin > 0 && iRapBin > 0){ Char_t fileName[100]; if(iRapBin == 0) sprintf(fileName, "tmpFiles/CBParameters.root"); else sprintf(fileName, "tmpFiles/CBParameters_rap%d.root", iRapBin); TFile *fIn = new TFile(fileName); TTree *treeIn = (TTree *) gDirectory->Get("CBPars"); Double_t alphaAll, nAll; TBranch *b_alphaAll, *b_nAll; treeIn->SetBranchAddress("alphaAll", &alphaAll, &b_alphaAll); treeIn->SetBranchAddress("nAll", &nAll, &b_nAll); Long64_t iEntry = treeIn->LoadTree(0); treeIn->GetEntry(0); printf("alpha and n from File: %1.3f, %1.3f\n", alphaAll, nAll); fRECO->FixParameter(5, nAll); fRECO->FixParameter(6, alphaAll); } hMass->Fit(fRECO, "0", "", peak_min, peak_max); fRECO = hMass->GetFunction(name); fRECO->SetLineWidth(1); Double_t fitParTot[npar]; fRECO->GetParameters(fitParTot); normY1S = fitParTot[0]; printf("normY1S = %1.3e\n", normY1S); mean1S = fitParTot[1]; sigma1S = fitParTot[2]; normY2S = fitParTot[3]; normY3S = fitParTot[4]; n = fitParTot[5]; printf("n = %1.3f\n", n); alpha = fitParTot[6]; printf("alpha = %1.3f\n", alpha); sigma1S_save[iRapBin][iPTBin]=sigma1S; chisqrd = fRECO->GetChisquare(); NDF = fRECO->GetNDF(); redChi2 = chisqrd/NDF; printf("\nChisqrd = %1.3f, NDF = %d, Chisqrd/NDF = %1.3f, Prob = %1.3e\n", chisqrd, NDF, redChi2, TMath::Prob(chisqrd,NDF)); //save alpha and n parameters if fit is //for integrated bins in y and pT: if(iPTBin == 0) SaveCBParameters(iRapBin, iPTBin, alpha, n, fRECO->GetParError(6), fRECO->GetParError(5)); Double_t mean2S = mean1S*(massPDG2S/massPDG1S); Double_t mean3S = mean1S*(massPDG3S/massPDG1S); Double_t sigma2S = sigma1S*(massPDG2S/massPDG1S); Double_t sigma3S = sigma1S*(massPDG3S/massPDG1S); printf("=========================================\n"); printf("Calculate the number of Y's in the sample\n"); printf("=========================================\n"); TF1 *CB[kNbSpecies]; Double_t intCBFit[kNbSpecies]; //integral values of a CB with N=Nfit and fixed alpha, n, sigma, width for(int iUps = 0; iUps < kNbSpecies; iUps++){ sprintf(name, "CB_%d", iUps); CB[iUps] = new TF1(name, CBFunction, range_min, range_max, 5); CB[iUps]->SetParameter(0, 1.); if(iUps == 0){ CB[iUps]->FixParameter(1, mean1S); CB[iUps]->FixParameter(2, sigma1S); } else if(iUps == 1){ CB[iUps]->FixParameter(1, mean2S); CB[iUps]->FixParameter(2, sigma2S); } else if(iUps == 2){ CB[iUps]->FixParameter(1, mean3S); CB[iUps]->FixParameter(2, sigma3S); } CB[iUps]->FixParameter(3, alpha); CB[iUps]->FixParameter(4, n); intCB[iUps] = CB[iUps]->Integral(range_min, range_max); } nY[UPS1S] = normY1S * intCB[UPS1S]; nY[UPS2S] = normY2S * intCB[UPS2S]; nY[UPS3S] = normY3S * intCB[UPS3S]; printf("rapidity bin %d, pT bin %d\n", iRapBin, iPTBin); printf("the integral of the fitted CB for the %s is: %1.3e --> #%s = %1.3e\n", specName[UPS1S], intCB[UPS1S], specName[UPS1S], nY[UPS1S]); printf("the integral of the fitted CB for the %s is: %1.3e --> #%s = %1.3e\n", specName[UPS2S], intCB[UPS2S], specName[UPS2S], nY[UPS2S]); printf("the integral of the fitted CB for the %s is: %1.3e --> #%s = %1.3e\n", specName[UPS3S], intCB[UPS3S], specName[UPS3S], nY[UPS3S]); //calculate the fraction of BG in a given mass interval massMin[UPS1S] = mean1S - nSigma*sigma1S; massMin[UPS2S] = mean2S - nSigma*sigma2S; massMin[UPS3S] = mean3S - nSigma*sigma3S; massMax[UPS1S] = mean1S + nSigma*sigma1S; massMax[UPS2S] = mean2S + nSigma*sigma2S; massMax[UPS3S] = mean3S + nSigma*sigma3S; for(int iSpecies = 0; iSpecies < kNbSpecies; iSpecies++){ printf("integrating histos between %1.3f and %1.3f GeV (+- %1.1f sigma window)\n", massMin[iSpecies], massMax[iSpecies], nSigma); } fUps1S = new TF1("fUps1S", CBFunction, range_min, range_max, 5); fUps1S->FixParameter(0, normY1S * binWidth); fUps1S->FixParameter(1, mean1S); fUps1S->FixParameter(2, sigma1S); fUps1S->FixParameter(3, alpha); fUps1S->FixParameter(4, n); fUps2S = new TF1("fUps2S", CBFunction, range_min, range_max, 5); fUps2S->FixParameter(0, normY2S * binWidth); fUps2S->FixParameter(1, mean2S); fUps2S->FixParameter(2, sigma2S); fUps2S->FixParameter(3, alpha); fUps2S->FixParameter(4, n); fUps3S = new TF1("fUps3S", CBFunction, range_min, range_max, 5); fUps3S->FixParameter(0, normY3S * binWidth); fUps3S->FixParameter(1, mean3S); fUps3S->FixParameter(2, sigma3S); fUps3S->FixParameter(3, alpha); fUps3S->FixParameter(4, n); Double_t nUps[kNbSpecies]; nUps[UPS1S] = fUps1S->Integral(massMin[UPS1S], massMax[UPS1S]); nUps[UPS2S] = fUps2S->Integral(massMin[UPS2S], massMax[UPS2S]); nUps[UPS3S] = fUps3S->Integral(massMin[UPS3S], massMax[UPS3S]); fBG = new TF1("fBG", DrawContinuum, range_min, range_max, 3); for(int iPar = 0; iPar < 3; iPar++){ fBG->FixParameter(iPar, fitParBG[iPar]); fBG->SetParError(iPar, fitParBGerr[iPar]); // printf("fBG par %f +- %f\n", fBG->GetParameter(iPar), fBG->GetParError(iPar)); } Double_t nBG[kNbSpecies]; nBG[UPS1S] = fBG->Integral(massMin[UPS1S], massMax[UPS1S]); nBG[UPS2S] = fBG->Integral(massMin[UPS2S], massMax[UPS2S]); nBG[UPS3S] = fBG->Integral(massMin[UPS3S], massMax[UPS3S]); /* intCB[UPS3S] = CB[UPS3S]->Integral(massMin[UPS3S], massMax[UPS3S]); intCB[UPS2S] = CB[UPS2S]->Integral(massMin[UPS3S], massMax[UPS3S]); intCB[UPS1S] = CB[UPS1S]->Integral(massMin[UPS3S], massMax[UPS3S]); nY[UPS3S] = normY3S * intCB[UPS3S]; nY[UPS2S] = normY2S * intCB[UPS2S]; nY[UPS1S] = normY1S * intCB[UPS1S]; printf("3S region:::1sigma integral CB3S = %1.3f, normY3S = %1.3f, nY3S = %1.3f\n",intCB[UPS3S] ,normY3S,nY[UPS3S]); printf("3S region:::1sigma integral CB2S = %1.3f, normY2S = %1.3f, nY2S = %1.3f\n",intCB[UPS2S] ,normY2S,nY[UPS2S]); printf("3S region:::1sigma integral CB1S = %1.3f, normY1S = %1.3f, nY1S = %1.3f\n",intCB[UPS1S] ,normY1S,nY[UPS1S]); printf("3S region:::1sigma integral BKG = %1.3f, normBkg = %1.3f, nBkg = %1.3f\n",fBG->Integral(massMin[UPS3S], massMax[UPS3S]) ,1/binWidth,fBG->Integral(massMin[UPS3S], massMax[UPS3S])/binWidth); printf("3S region:::1sigma CB3S background fraction = %1.3f\n",fBG->Integral(massMin[UPS3S], massMax[UPS3S])/binWidth/(fBG->Integral(massMin[UPS3S], massMax[UPS3S])/binWidth+nY[UPS1S]+nY[UPS2S]+nY[UPS3S])); printf("3S region:::1sigma NumEvents = %1.3f\n",fBG->Integral(massMin[UPS3S], massMax[UPS3S])/binWidth+nY[UPS1S]+nY[UPS2S]+nY[UPS3S]); intCB[UPS3S] = CB[UPS3S]->Integral( range_min, range_max); intCB[UPS2S] = CB[UPS2S]->Integral( range_min, range_max); intCB[UPS1S] = CB[UPS1S]->Integral( range_min, range_max); nY[UPS3S] = normY3S * intCB[UPS3S]; nY[UPS2S] = normY2S * intCB[UPS2S]; nY[UPS1S] = normY1S * intCB[UPS1S]; printf("3S region:::FullRegion integral CB3S = %1.3f, normY3S = %1.3f, nY3S = %1.3f\n",intCB[UPS3S] ,normY3S,nY[UPS3S]); printf("3S region:::FullRegion integral CB2S = %1.3f, normY2S = %1.3f, nY2S = %1.3f\n",intCB[UPS2S] ,normY2S,nY[UPS2S]); printf("3S region:::FullRegion integral CB1S = %1.3f, normY1S = %1.3f, nY1S = %1.3f\n",intCB[UPS1S] ,normY1S,nY[UPS1S]); printf("3S region:::FullRegion integral background = %1.3f\n",fBG->Integral(range_min, range_max)/binWidth); printf("3S region:::FullRegion NumEvents = %1.3f\n",fBG->Integral(range_min, range_max)/binWidth+nY[UPS1S]+nY[UPS2S]+nY[UPS3S]); double tempBfrac=fBG->Integral(massMin[UPS3S], massMax[UPS3S])/(fBG->Integral(massMin[UPS3S], massMax[UPS3S])+fUps1S->Integral(massMin[UPS3S], massMax[UPS3S])+fUps2S->Integral(massMin[UPS3S], massMax[UPS3S])+fUps3S->Integral(massMin[UPS3S], massMax[UPS3S])); printf("3S region:::1sigma fUps background fraction = %1.3f\n",tempBfrac); */ if(iRapBin == 0 || iPTBin == 0) printf("rapidity bin %d, pTBin %d\n", iRapBin, iPTBin); else{ printf("rapidity bin %d (%1.1f - %1.1f), pT bin %d (%1.0f - %1.0f GeV/c)\n", iRapBin, onia::rapForPTRange[iRapBin-1], onia::rapForPTRange[iRapBin], iPTBin, onia::pTRange[iRapBin][iPTBin-1], onia::pTRange[iRapBin][iPTBin]); } FILE *fInfo = fopen("tmpFiles/statistics.txt", "a"); if(iRapBin == 0 || iPTBin == 0) fprintf(fInfo, "rapidity bin %d, pTBin %d\n", iRapBin, iPTBin); else{ fprintf(fInfo, "rapidity bin %d (%1.1f - %1.1f), pT bin %d (%1.0f - %1.0f GeV/c)\n", iRapBin, onia::rapForPTRange[iRapBin-1], onia::rapForPTRange[iRapBin], iPTBin, onia::pTRange[iRapBin][iPTBin-1], onia::pTRange[iRapBin][iPTBin]); } for(int iSpecies = 0; iSpecies < kNbSpecies; iSpecies++){ fracBG[iSpecies] = nBG[iSpecies] / (nBG[iSpecies] + nUps[iSpecies]); // printf("nUps = %1.3f\n", nUps[iSpecies]); // printf("nBG = %1.3f\n", nBG[iSpecies]); printf("%s: fraction of BG in a +- %1.1f sigma window is %1.3f (not correct)\n",specName[iSpecies], nSigma, fracBG[iSpecies]); printf("%s: Number of BG events in a +- %1.1f sigma window is %1.3f, number of signal events is %1.3f\n",nSigma, nBG[iSpecies], nUps[iSpecies]); fprintf(fInfo, "integral of the fitted CB for the %s is (norm factor= %1.3e): %7.0f\n", specName[iSpecies], intCB[iSpecies], nY[iSpecies]); } fclose(fInfo); // if(iPTBin > 0 && iRapBin > 0) if(iPTBin > -1 && iRapBin > -1) SaveFitPars(iRapBin, iPTBin); }
void plot_uparaCorr_V_lumi_upara() { TFile *f = new TFile("data_wen_cell_noWPtCut_newDataSet.root"); gDirectory->cd("UE_Hist"); char name[50]; const Int_t n_Lumi_Bins = 10; double Lumi_Average[n_Lumi_Bins], Lumi_Average_Err[n_Lumi_Bins]; double UParaCorr_Lumi[n_Lumi_Bins], UParaCorr_Lumi_Err[n_Lumi_Bins]; const Int_t n_UPara_Bins = 13; double UPara_Average[n_UPara_Bins], UPara_Average_Err[n_UPara_Bins]; double UParaCorr_UPara[n_UPara_Bins], UParaCorr_UPara_Err[n_UPara_Bins]; for(int i=0; i<n_Lumi_Bins; i++) { sprintf(name, "%s%d", "InstLumi_", i); TH1F *hLumi = gROOT->FindObject(name); Lumi_Average[i] = hLumi->GetMean(); Lumi_Average_Err[i] = 0.; delete hLumi; // sum5towEt vs deltaPhi sprintf(name, "%s%d", "sum5towEt_Lumi_", i); TH1F *hLumi_Upara = gROOT->FindObject(name); TF1 *fitfunc = new TF1("fitf", fitf, 0.2, 0.4, 1); hLumi_Upara->Fit("fitf", "r"); double param, param_err; fitfunc->GetParameters(¶m); param_err = fitfunc->GetParError(0); UParaCorr_Lumi[i] = param; UParaCorr_Lumi_Err[i] = param_err; delete fitfunc; delete hLumi_Upara; } for(int i=0; i<n_UPara_Bins; i++) { sprintf(name, "%s%d", "UPara_", i); TH1F *hUPara = gROOT->FindObject(name); UPara_Average[i] = hUPara->GetMean(); UPara_Average_Err[i] = 0.; delete hUPara; // sum5towEt vs deltaPhi sprintf(name, "%s%d", "sum5towEt_UPara_", i); TH1F *hUPara_Upara = gROOT->FindObject(name); TF1 *fitfunc = new TF1("fitf", fitf, 0.2, 0.4, 1); hUPara_Upara->Fit("fitf", "r"); double param, param_err; fitfunc->GetParameters(¶m); param_err = fitfunc->GetParError(0); UParaCorr_UPara[i] = param; UParaCorr_UPara_Err[i] = param_err; delete fitfunc; delete hUPara_Upara; } // uparallel vs luminosity TCanvas *c1 = new TCanvas("c1", "canvas"); TGraphErrors *ge = new TGraphErrors(n_Lumi_Bins, Lumi_Average, UParaCorr_Lumi, Lumi_Average_Err, UParaCorr_Lumi_Err); c1->SetGridx(); c1->SetGridy(); ge->Draw("AP"); c1->Update(); // uparallel vs uparallel TCanvas *c2 = new TCanvas("c2", "canvas"); TGraphErrors *ge2 = new TGraphErrors(n_UPara_Bins, UPara_Average, UParaCorr_UPara, UPara_Average_Err, UParaCorr_UPara_Err); c2->SetGridx(); c2->SetGridy(); ge2->Draw("AP"); c2->Update(); }