TH1F * getpdgs(std::string const & dr, std::string const & we) { TCanvas * canvas_temp = new TCanvas("temp"); tree->Draw((dr+">>h").c_str(), we.c_str()); TH1F * hist = (TH1F*)gDirectory->Get("h"); int const min = hist->GetBinLowEdge(hist->FindFirstBinAbove(0)); int const max = hist->GetBinLowEdge(hist->FindLastBinAbove(0)) + hist->GetBinWidth(hist->FindLastBinAbove(0)) + 1; int const binno = max - min; delete canvas_temp; delete hist; canvas_temp = new TCanvas("temp"); tree->Draw(Form((dr+">>h(%d,%d,%d)").c_str(), binno, min, max), we.c_str()); ofile->cd(); delete canvas_temp; TH1F * histb = (TH1F*)gDirectory->Get("h"); if(histb->GetEntries() == 0) { delete histb; return nullptr; } return histb; }
void performClosure(RooRealVar *mass, RooAbsPdf *pdf, RooDataSet *data, string closurename, double wmin=110., double wmax=130., double slow=110., double shigh=130., double step=0.002) { // plot to perform closure test cout << "Performing closure test..." << endl; double nbins = (wmax-wmin)/step; TH1F *h = new TH1F("h","h",int(floor(nbins+0.5)),wmin,wmax); if (data){ pdf->fillHistogram(h,RooArgList(*mass),data->sumEntries()); h->Scale(2*h->GetNbinsX()/double(binning_)); } else { pdf->fillHistogram(h,RooArgList(*mass)); } int binLow = h->FindBin(slow); int binHigh = h->FindBin(shigh)-1; TH1F *copy = new TH1F("copy","c",binHigh-binLow,h->GetBinLowEdge(binLow),h->GetBinLowEdge(binHigh+1)); for (int b=0; b<copy->GetNbinsX(); b++) copy->SetBinContent(b+1,h->GetBinContent(b+1+binLow)); double areaCov = 100*h->Integral(binLow,binHigh)/h->Integral(); // style h->SetLineColor(kBlue); h->SetLineWidth(3); h->SetLineStyle(7); copy->SetLineWidth(3); copy->SetFillColor(kGray); TCanvas *c = new TCanvas(); if (data){ RooPlot *plot = mass->frame(Bins(binning_),Range("higgsRange")); plot->addTH1(h,"hist"); plot->addTH1(copy,"same f"); if (data) data->plotOn(plot); pdf->plotOn(plot,Normalization(h->Integral(),RooAbsReal::NumEvent),NormRange("higgsRange"),Range("higgsRange"),LineWidth(1),LineColor(kRed),LineStyle(kDashed)); plot->Draw(); c->Print(closurename.c_str()); } else { RooPlot *plot = mass->frame(Bins(binning_),Range("higgsRange")); h->Scale(plot->getFitRangeBinW()/h->GetBinWidth(1)); copy->Scale(plot->getFitRangeBinW()/h->GetBinWidth(1)); pdf->plotOn(plot,LineColor(kRed),LineWidth(3)); plot->Draw(); h->Draw("hist same"); copy->Draw("same f"); c->Print(closurename.c_str()); } cout << "IntH: [" << h->GetBinLowEdge(binLow) << "-" << h->GetBinLowEdge(binHigh+1) << "] Area = " << areaCov << endl; delete c; delete copy; delete h; }
int main(int argc, char* argv[]){ ic::Plot::SetTdrStyle(); TH1F data = GetFromTFile<TH1F>("datacard_m_vis_inclusive_et_2011.root", "/eleTau_inclusive", "data_obs"); TH1F zee = GetFromTFile<TH1F>("datacard_m_vis_inclusive_et_2011.root", "/eleTau_inclusive", "ZL"); double data_rate = data.Integral(); double zee_init_rate = zee.Integral(); RooRealVar x("x","mvis",data.GetBinLowEdge(1),data.GetBinLowEdge(data.GetNbinsX()+1)); RooRealVar c1("c1","c1",-10,10); RooRealVar c2("c2","c2",-1,1); RooRealVar c3("c3","c3",-1,1); RooGenericPdf bkg("bkg","exp(c1*x+c2*x*x+c3*x*x*x)",RooArgSet(x,c1,c2,c3)); RooDataHist zee_hist("zee_hist","zee_hist",RooArgSet(x),&zee); RooHistPdf zee_pdf("zee_pdf","zee_pdf",RooArgSet(x),zee_hist); ///Fit Data TCanvas C("canvas", "canvas", 800,800); RooRealVar yield("yield","yield",0.01,.9); RooAddPdf full_pdf("full_pdf","full_pdf",RooArgList(zee_pdf,bkg),RooArgList(yield)); RooDataHist data_hist("data_hist","data_hist",RooArgSet(x),&data); RooChi2Var chi("chi","chi",full_pdf,data_hist,RooFit::DataError(RooAbsData::SumW2)); RooMinuit minuit(chi); minuit.migrad(); RooPlot* plot=x.frame(); data_hist.plotOn(plot); full_pdf.plotOn(plot); full_pdf.plotOn(plot,RooFit::Components(zee_pdf),RooFit::LineColor(2)); C.Clear(); plot->SetTitle("Title"); plot->GetYaxis()->SetTitle(""); plot->GetXaxis()->SetTitle("m(e#tau)"); plot->Draw(); C.Print("plotZEE.pdf"); double fit_frac = yield.getVal(); double fit_frac_err = yield.getError(); double zee_fit_rate = data_rate * fit_frac; double err = (data_rate * fit_frac_err) / zee_init_rate; std::cout << "Scale factor: " << zee_fit_rate / zee_init_rate << " +/- " << err << std::endl; return 0; }
void PoissonianMagic() { TFile file_PUnum("/nfs/dust/cms/user/rathjd/VBF-LS-tau/PU/DataPUFile_22Jan2013ReReco_Run2012.root", "read"); TFile file_PUden("/nfs/dust/cms/user/rathjd/VBF-LS-tau/PU/S10MC_PUFile.root", "read"); TH1F *data = (TH1F*)file_PUnum.Get("analyzeHiMassTau/NVertices_0"); data->Scale(1/data->Integral(0,-1)); TH1F *MC = (TH1F*)file_PUden.Get("analyzeHiMassTau/NVertices_0"); MC->Scale(1/MC->Integral(0,-1)); //define empty histograms for the smeared versions TH1F *num = (TH1F*)data->Clone("ratio"); for(int i=0; i<num->GetNbinsX(); i++) num->SetBinContent(i+1,0); TH1F *den = (TH1F*)data->Clone("MC"); for(int i=0; i<den->GetNbinsX(); i++) den->SetBinContent(i+1,0); //generate the poissonian distributions for(unsigned int i=0; i<data->GetNbinsX(); i++){ TF1 *Pd = new TF1("Pd", "TMath::PoissonI(x,[0])",0,100); Pd->SetParameter(0,data->GetBinLowEdge(i+1)); std::cout<<data->GetBinLowEdge(i+1)<<std::endl; TF1 *Pm = new TF1("Pm", "TMath::PoissonI(x,[0])",0,100); Pm->SetParameter(0,MC->GetBinLowEdge(i+1)); //add up the poissonians for(unsigned int j=0; j<data->GetNbinsX(); j++){ num->SetBinContent(j+1,num->GetBinContent(j+1)+Pd->Eval(j)/Pd->Integral(0,100)*data->GetBinContent(i+1)); den->SetBinContent(j+1,den->GetBinContent(j+1)+Pm->Eval(j)/Pm->Integral(0,100)*MC->GetBinContent(i+1)); } } //make the ratio and save the result num->Divide(den); TFile *f=new TFile("PUreweightHistogram.root","RECREATE"); num->Write(); den->Write(); f->Close(); file_PUnum.Close(); file_PUden.Close(); }
void rediscover_the_top(string mcjzb, string datajzb) { dout << "Hi! today we are going to (try to) rediscover the top!" << endl; TCanvas *c3 = new TCanvas("c3","c3"); c3->SetLogy(1); vector<float> binning; //binning=allsamples.get_optimal_binsize(mcjzb,cutmass&&cutOSSF&&cutnJets,20,50,800); /* binning.push_back(50); binning.push_back(100); binning.push_back(150); binning.push_back(200); binning.push_back(500); TH1F *dataprediction = allsamples.Draw("dataprediction", "-"+datajzb, binning, "JZB [GeV]", "events", cutmass&&cutOSSF&&cutnJets,data, luminosity); TH1F *puresignal = allsamples.Draw("puresignal", datajzb, binning, "JZB [GeV]", "events", cutmass&&cutOSOF&&cutnJets,data, luminosity); // TH1F *puresignal = allsamples.Draw("puresignal", mcjzb, binning, "JZB [GeV]", "events", cutmass&&cutOSSF&&cutnJets,mc, luminosity,allsamples.FindSample("TTJets")); TH1F *observed = allsamples.Draw("observed", datajzb,binning, "JZB [GeV]", "events", cutmass&&cutOSSF&&cutnJets,data,luminosity); ofstream myfile; TH1F *ratio = (TH1F*)observed->Clone(); ratio->Divide(dataprediction); ratio->GetYaxis()->SetTitle("Ratio obs/pred"); ratio->Draw(); c3->SaveAs("testratio.png"); myfile.open ("ShapeFit_log.txt"); establish_upper_limits(observed,dataprediction,puresignal,"LM4",myfile); myfile.close(); */ int nbins=100; float low=0; float hi=500; TCanvas *c4 = new TCanvas("c4","c4",900,900); c4->Divide(2,2); c4->cd(1); c4->cd(1)->SetLogy(1); TH1F *datapredictiont = allsamples.Draw("datapredictiont", "-"+datajzb, nbins,low,hi, "JZB [GeV]", "events", cutmass&&cutOSSF&&cutnJets,data, luminosity); TH1F *datapredictiono = allsamples.Draw("datapredictiono", "-"+datajzb, nbins,low,hi, "JZB [GeV]", "events", cutmass&&cutOSOF&&cutnJets,data, luminosity); datapredictiont->Add(datapredictiono,-1); dout << "Second way of doing this !!!! Analytical shape to the left :-D" << endl; vector<TF1*> functions = do_cb_fit_to_plot(datapredictiont,10); datapredictiont->SetMarkerColor(kRed); datapredictiont->SetLineColor(kRed); datapredictiont->Draw(); functions[1]->Draw("same"); TText *title1 = write_title("Top Background Prediction (JZB<0, with osof subtr)"); title1->Draw(); c4->cd(2); c4->cd(2)->SetLogy(1); TH1F *observedt = allsamples.Draw("observedt", datajzb, nbins,low,hi, "JZB [GeV]", "events", cutmass&&cutOSSF&&cutnJets,data, luminosity); observedt->Draw(); datapredictiont->Draw("histo,same"); functions[1]->Draw("same"); TText *title2 = write_title("Observed and predicted background"); title2->Draw(); c4->cd(3); c4->cd(3)->SetLogy(1); // TH1F *ratio = (TH1F*)observedt->Clone(); TH1F *analytical_background_prediction= new TH1F("analytical_background_prediction","",nbins,low,hi); for(int i=0;i<=nbins;i++) { analytical_background_prediction->SetBinContent(i+1,functions[1]->Eval(((hi-low)/((float)nbins))*(i+0.5))); analytical_background_prediction->SetBinError(i+1,TMath::Sqrt(functions[1]->Eval(((hi-low)/((float)nbins))*(i+0.5)))); } analytical_background_prediction->GetYaxis()->SetTitle("JZB [GeV]"); analytical_background_prediction->GetYaxis()->CenterTitle(); TH1F *analyticaldrawonly = (TH1F*)analytical_background_prediction->Clone(); analytical_background_prediction->SetFillColor(TColor::GetColor("#3399FF")); analytical_background_prediction->SetMarkerSize(0); analytical_background_prediction->Draw("e5"); analyticaldrawonly->Draw("histo,same"); functions[1]->Draw("same"); TText *title3 = write_title("Analytical bg pred histo"); title3->Draw(); c4->cd(4); // c4->cd(4)->SetLogy(1); vector<float> ratio_binning; ratio_binning.push_back(0); ratio_binning.push_back(5); ratio_binning.push_back(10); ratio_binning.push_back(20); ratio_binning.push_back(50); // ratio_binning.push_back(60); /* ratio_binning.push_back(51); ratio_binning.push_back(52); ratio_binning.push_back(53); ratio_binning.push_back(54); ratio_binning.push_back(55); ratio_binning.push_back(56); ratio_binning.push_back(57); ratio_binning.push_back(58); ratio_binning.push_back(59); ratio_binning.push_back(60); // ratio_binning.push_back(70);*/ // ratio_binning.push_back(80); // ratio_binning.push_back(90); ratio_binning.push_back(80); // ratio_binning.push_back(110); ratio_binning.push_back(500); TH1F *observedtb = allsamples.Draw("observedtb", datajzb, ratio_binning, "JZB [GeV]", "events", cutmass&&cutOSSF&&cutnJets,data, luminosity); TH1F *datapredictiontb = allsamples.Draw("datapredictiontb", "-"+datajzb, ratio_binning, "JZB [GeV]", "events", cutmass&&cutOSSF&&cutnJets,data, luminosity); TH1F *datapredictiontbo = allsamples.Draw("datapredictiontbo", "-"+datajzb, ratio_binning, "JZB [GeV]", "events", cutmass&&cutOSOF&&cutnJets,data, luminosity); datapredictiontb->Add(datapredictiontbo,-1); TH1F *analytical_background_predictionb = allsamples.Draw("analytical_background_predictionb",datajzb, ratio_binning, "JZB [GeV]", "events", cutmass&&cutOSSF&&cutnJets&&"mll<2",data, luminosity); for(int i=0;i<=(int)ratio_binning.size();i++) { analytical_background_predictionb->SetBinContent(i+1,functions[1]->Eval(analytical_background_predictionb->GetBinCenter(i))); analytical_background_predictionb->SetBinError(i+1,TMath::Sqrt(functions[1]->Eval(analytical_background_predictionb->GetBinCenter(i)))); } TH1F *ratio = (TH1F*) observedtb->Clone(); ratio->Divide(datapredictiontb); for (int i=0;i<=(int)ratio_binning.size();i++) { dout << observedtb->GetBinLowEdge(i+1) << ";"<<observedtb->GetBinContent(i+1) << ";" << datapredictiontb->GetBinContent(i+1) << " --> " << ratio->GetBinContent(i+1) << "+/-" << ratio->GetBinError(i+1) << endl; } // ratio->Divide(datapredictiontb); // ratio->Divide(analytical_background_predictionb); // TGraphAsymmErrors *JZBratio= histRatio(observedtb,analytical_background_predictionb,data,ratio_binning); // ratio->Divide(analytical_background_prediction); // ratio->Divide(datapredictiont); // ratio->GetYaxis()->SetTitle("obs/pred"); // JZBratio->Draw("AP"); ratio->GetYaxis()->SetRangeUser(0,10); ratio->Draw(); //analytical_background_predictionb->Draw(); // JZBratio->SetTitle(""); TText *title4 = write_title("Ratio of observed to predicted"); title4->Draw(); // CompleteSave(c4,"test/ttbar_discovery_dataprediction___analytical_function"); CompleteSave(c4,"test/ttbar_discovery_dataprediction__analytical__new_binning_one_huge_bin_from_80"); }
void AnalysisBase::findDeadRegions(){ cout << "=================================================" << endl; cout << "findDeadRegions(): Looking for dead strip regions " << endl; cout << "=================================================" << endl; TH1F* hf = new TH1F("hf","X position of matched cluster",200,-10.0,10.0); TH1F* hnf = new TH1F("hnf","X position of matched cluster",200,-10.0,10.0); double nomStrip = 0, detStrip = 0; Long64_t nbytes = 0, nb = 0; Int_t nentries = fChain->GetEntriesFast(); for (Long64_t jentry=0; jentry<nentries;jentry++) { Long64_t ientry = LoadTree(jentry); if (ientry < 0) break; nb = fChain->GetEntry(jentry); nbytes += nb; if(n_tp3_tracks > 1) continue; // Loop over TPIX tracks in event for(int k=0; k<n_tp3_tracks; k++){ double x_trk = vec_trk_tx->at(k)*z_DUT+vec_trk_x->at(k); double y_trk = vec_trk_ty->at(k)*z_DUT+vec_trk_y->at(k); transformTrackToDUTFrame(k, x_trk, y_trk, nomStrip, detStrip ); bool goodTrack = false; bool inFiducial = false; if(x_trk>xMin && x_trk<xMax && y_trk>yMin && y_trk<yMax) inFiducial = true; inFiducial = inFiducial && (x_trk<xLeftHole || x_trk>xRightHole); double tx = 1000*vec_trk_tx->at(k); double ty = 1000*vec_trk_ty->at(k); if(tx>txMin && tx<txMax && ty>tyMin && ty<tyMax) goodTrack = true; bool goodTime = (clustersTDC >= tdcLo && clustersTDC <= tdcHi); bool foundHit = false; // Loop over clusters for(int j=0; j<min(clusterNumberPerEvent,10); j++){ if(clustersPosition[j] < 0.1) continue; if(polarity*clustersCharge[j] < kClusterChargeMin) continue; //bool goodHit = (clustersPosition[j]>iLo || clustersPosition[j]<iHi); double x_dut = getDUTHitPosition(j); double dx = x_dut - x_trk; if(goodTrack && inFiducial && goodTime && fabs(dx)<dxWin) { foundHit = true; } } if(inFiducial && goodTrack && goodTime) { hf->Fill(x_trk); if(!foundHit) hnf->Fill(x_trk); } } } TH1F *hineff = (TH1F*)hnf->Clone("hineff"); hineff->Divide(hf); // Only for debugging /* TCanvas *cc = new TCanvas("cc","Hits",800,800); cc->Divide(2,2); cc->cd(1); hnf->Draw(); cc->cd(2); hf->Draw(); cc->cd(3); hineff->Draw(); */ for(int k = 0; k<hineff->GetNbinsX()-1; k++){ if(nDeadRegion > 20){ cout << "WARNING: Exceeded 20 dead regions, exiting from loop" << endl; break; } double v1 = hineff->GetBinContent(k); if(v1 > k_DeadStrip){ deadRegionLo[nDeadRegion] = hf->GetBinLowEdge(k); for(int j = k; j<hineff->GetNbinsX(); j++){ double v2 = hineff->GetBinContent(j); if(v2 < k_DeadStrip){ deadRegionHi[nDeadRegion] = hf->GetBinLowEdge(j); cout << "====> Found inefficiency strip region from x : " << deadRegionLo[nDeadRegion] << " <===> " << deadRegionHi[nDeadRegion] << " mm" << endl; k = j + 1; nDeadRegion++; break; } } } } delete hf; delete hnf; delete hineff; return; }
void plotHitEnergy(string inputDir, float radius=0.4){ setNCUStyle(true); TH1F* hecal; TH1F* hhcal; TString energy=gSystem->GetFromPipe(Form("file=%s; test=${file##*/}; test2=${test%%mumu*}; echo \"${test2##*tev}\"",inputDir.data())); cout << "energy = " << energy.Data() << endl; string inputFile = inputDir + "/radius" + Form("%0.1f",radius)+ "_rawhit.root"; cout << "opening " << inputFile.data() << endl; TFile *f = TFile::Open(inputFile.data()); hecal = (TH1F*)f->FindObjectAny("hecalhit_energy"); hecal->SetLineWidth(3); hecal->SetFillStyle(1001); hecal->SetFillColor(4); hecal->SetLineColor(4); hecal->SetXTitle("EM_BARREL hit energy [GeV]"); hecal->SetYTitle(Form("Number of hits per %d GeV",(int)hecal->GetBinWidth(1))); hecal->SetTitleOffset(1.2,"X"); hecal->SetTitleOffset(1.4,"Y"); hhcal = (TH1F*)f->FindObjectAny("hhcalhit_energy"); hhcal->SetLineWidth(3); hhcal->SetFillStyle(1001); hhcal->SetFillColor(2); hhcal->SetLineColor(2); hhcal->SetXTitle("HAD_BARREL hit energy [GeV]"); hhcal->SetYTitle(Form("Number of hits per %d GeV",(int)hhcal->GetBinWidth(1))); hhcal->SetTitleOffset(1.2,"X"); hhcal->SetTitleOffset(1.4,"Y"); TLegend* leg = new TLegend(0.444,0.690,0.990,0.903); leg->SetFillColor(0); leg->SetFillStyle(0); TCanvas* c1 = new TCanvas("c1","",500,500); int lastbin=hecal->FindLastBinAbove(0)+50; float xmax=hecal->GetBinLowEdge(lastbin); hecal->GetXaxis()->SetRangeUser(0,xmax); hecal->Draw("hist"); c1->SetLogy(1); leg->SetHeader("rfull012"); leg->AddEntry(hecal,Form("%s-TeV Z'#rightarrow qq",energy.Data()),"f"); leg->Draw("same"); c1->Print(Form("rfull012/rfull012_EM_BARREL_hit_energy_%sTeVZp.pdf",energy.Data())); c1->Print(Form("rfull012/rfull012_EM_BARREL_hit_energy_%sTeVZp.eps",energy.Data())); leg->Clear(); lastbin=hhcal->FindLastBinAbove(0)+50; xmax=hhcal->GetBinLowEdge(lastbin); hhcal->GetXaxis()->SetRangeUser(0,xmax); hhcal->Draw("hist"); c1->SetLogy(1); leg->SetHeader("rfull012"); leg->AddEntry(hhcal,Form("%s-TeV Z'#rightarrow qq",energy.Data()),"f"); leg->Draw("same"); c1->Print(Form("rfull012/rfull012_HAD_BARREL_hit_energy_%sTeVZp.pdf",energy.Data())); c1->Print(Form("rfull012/rfull012_HAD_BARREL_hit_energy_%sTeVZp.eps",energy.Data())); }
void plotHitEnergy(string inputDir, int hittype=1, float radius=0.4) { setNCUStyle(true); string decversion; if(inputDir.find("rfull009")!=std::string::npos)decversion="rfull009"; else if(inputDir.find("rfull012")!=std::string::npos)decversion="rfull012"; TH1F* hecal; TH1F* hhcal; std::string ecalhitname = hittype==1? "EM_BARREL":"EcalBarrelHits"; std::string hcalhitname = hittype==1? "HAD_BARREL":"HcalBarrelHits"; TString energy=gSystem->GetFromPipe(Form("file=%s; test=${file##*/}; test2=${test%%mumu*}; echo \"${test2##*tev}\"",inputDir.data())); cout << "energy = " << energy.Data() << endl; string inputFile = inputDir + "/radius" + Form("%0.1f",radius)+ (hittype==1? "_rawhit.root": "_rawhit_new.root"); cout << "opening " << inputFile.data() << endl; TFile *f = TFile::Open(inputFile.data()); hecal = (TH1F*)f->FindObjectAny("hecalhit_energy"); hecal->SetLineWidth(3); hecal->SetFillStyle(1001); hecal->SetFillColor(4); hecal->SetLineColor(4); hecal->SetXTitle(Form("%s hit energy [GeV]",ecalhitname.data())); hecal->SetYTitle(Form("Number of hits per %.1f GeV",hecal->GetBinWidth(1))); hecal->SetTitleOffset(1.2,"X"); hecal->SetTitleOffset(1.4,"Y"); hhcal = (TH1F*)f->FindObjectAny("hhcalhit_energy"); hhcal->SetLineWidth(3); hhcal->SetFillStyle(1001); hhcal->SetFillColor(2); hhcal->SetLineColor(2); hhcal->SetXTitle(Form("%s hit energy [GeV]",hcalhitname.data())); hhcal->SetYTitle(Form("Number of hits per %.1f GeV",hhcal->GetBinWidth(1))); hhcal->SetTitleOffset(1.2,"X"); hhcal->SetTitleOffset(1.4,"Y"); TLegend* leg = new TLegend(0.444,0.690,0.990,0.903); leg->SetFillColor(0); leg->SetFillStyle(0); TCanvas* c1 = new TCanvas("c1","",500,500); int lastbin=hecal->FindLastBinAbove(0)+20; float xmax=hecal->GetBinLowEdge(lastbin); hecal->GetXaxis()->SetRangeUser(0,xmax); hecal->Draw("hist"); c1->SetLogy(1); leg->SetHeader(decversion.data()); leg->AddEntry(hecal,Form("%s-TeV Z'#rightarrow qq",energy.Data()),"f"); leg->Draw("same"); std::string outputname = decversion + "/" + decversion + "_" + ecalhitname + "hit_energy_" + Form("%s",energy.Data()) + "TeVZp"; c1->Print(Form("%s.pdf",outputname.data())); c1->Print(Form("%s.eps",outputname.data())); leg->Clear(); lastbin=hhcal->FindLastBinAbove(0)+20; xmax=hhcal->GetBinLowEdge(lastbin); hhcal->GetXaxis()->SetRangeUser(0,xmax); hhcal->Draw("hist"); c1->SetLogy(1); leg->SetHeader(decversion.data()); leg->AddEntry(hhcal,Form("%s-TeV Z'#rightarrow qq",energy.Data()),"f"); leg->Draw("same"); outputname = decversion + "/" + decversion + "_" + hcalhitname + "hit_energy_" + Form("%s",energy.Data()) + "TeVZp"; c1->Print(Form("%s.pdf",outputname.data())); c1->Print(Form("%s.eps",outputname.data())); }
void Fit(TString SIGNAL,TString HISTO,double scaleSGN) { gROOT->ForceStyle(); TFile *fDat = TFile::Open("Histo_flatTree_data_tmva"+SIGNAL+".root"); TFile *fBkg = TFile::Open("Histo_flatTree_qcd_weights_tmva"+SIGNAL+".root"); TFile *fSgn = TFile::Open("Histo_flatTree_"+SIGNAL+"_weights_tmva"+SIGNAL+".root"); TH1 *hDat = (TH1*)fDat->Get(HISTO); TH1 *hBkgRaw = (TH1*)fBkg->Get(HISTO); TH1 *hSgn = (TH1*)fSgn->Get(HISTO); TH1 *hDat_JESlo = (TH1*)fDat->Get(HISTO+"_JESlo"); TH1 *hBkgRaw_JESlo = (TH1*)fBkg->Get(HISTO+"_JESlo"); TH1 *hSgn_JESlo = (TH1*)fSgn->Get(HISTO+"_JESlo"); TH1 *hDat_JESup = (TH1*)fDat->Get(HISTO+"_JESup"); TH1 *hBkgRaw_JESup = (TH1*)fBkg->Get(HISTO+"_JESup"); TH1 *hSgn_JESup = (TH1*)fSgn->Get(HISTO+"_JESup"); TH1F *hBkg = (TH1F*)hBkgRaw->Clone("Bkg"); TH1F *hBkg_JESlo = (TH1F*)hBkgRaw_JESlo->Clone("Bkg_JESlo"); TH1F *hBkg_JESup = (TH1F*)hBkgRaw_JESup->Clone("Bkg_JESup"); hBkg->Smooth(2); hBkg_JESlo->Smooth(2); hBkg_JESup->Smooth(2); hSgn->Smooth(2); hSgn_JESlo->Smooth(2); hSgn_JESup->Smooth(2); double lumi = 4967; hBkg->Scale(lumi); hBkg_JESlo->Scale(lumi); hBkg_JESup->Scale(lumi); double k_factor = hDat->Integral()/hBkg->Integral(); double k_factor_JESlo = hDat->Integral()/hBkg_JESlo->Integral(); double k_factor_JESup = hDat->Integral()/hBkg_JESup->Integral(); hBkg->Scale(k_factor); cout<<"Signal entries = "<<hSgn->GetEntries()<<endl; hSgn->Scale(lumi/scaleSGN); hBkg_JESlo->Scale(k_factor_JESlo); hSgn_JESlo->Scale(lumi/scaleSGN); hBkg_JESup->Scale(k_factor_JESup); hSgn_JESup->Scale(lumi/scaleSGN); hSgn_JESlo->Scale(hSgn->Integral()/hSgn_JESlo->Integral()); hSgn_JESup->Scale(hSgn->Integral()/hSgn_JESup->Integral()); TH1 *hBkg_STATlo = (TH1*)hBkg->Clone(HISTO+"_STATlo"); TH1 *hSgn_STATlo = (TH1*)hSgn->Clone(HISTO+"_STATlo"); TH1 *hBkg_STATup = (TH1*)hBkg->Clone(HISTO+"_STATup"); TH1 *hSgn_STATup = (TH1*)hSgn->Clone(HISTO+"_STATup"); float y1,e1; for(int i=0;i<hBkg->GetNbinsX();i++) { y1 = hBkg->GetBinContent(i+1); e1 = hBkg->GetBinError(i+1); hBkg_STATlo->SetBinContent(i+1,y1-e1); hBkg_STATup->SetBinContent(i+1,y1+e1); y1 = hSgn->GetBinContent(i+1); e1 = hSgn->GetBinError(i+1); hSgn_STATlo->SetBinContent(i+1,y1-e1); hSgn_STATup->SetBinContent(i+1,y1+e1); } hBkg_STATlo->Scale(hBkg->Integral()/hBkg_STATlo->Integral()); hBkg_STATup->Scale(hBkg->Integral()/hBkg_STATup->Integral()); hSgn_STATlo->Scale(hSgn->Integral()/hSgn_STATlo->Integral()); hSgn_STATup->Scale(hSgn->Integral()/hSgn_STATup->Integral()); double xMIN = hBkg->GetBinLowEdge(1); double xMAX = hBkg->GetBinLowEdge(hBkg->GetNbinsX()+1); double xMIN2 = hDat->GetBinLowEdge(hDat->FindFirstBinAbove(0.5)); double xMAX2 = hDat->GetBinLowEdge(hDat->FindLastBinAbove(0.5)+1); RooRealVar x("x","x",xMIN2,xMAX2); RooDataHist data("data","dataset with x",x,hDat); RooDataHist bkg("qcd","bkg with x",x,hBkg); RooDataHist sgn("signal","sgn with x",x,hSgn); RooHistPdf bkgPDF("bkgPDF","bkgPDF",x,bkg,0); RooHistPdf sgnPDF("sgnPDF","sgnPDF",x,sgn,0); RooRealVar f("f","f",0,0.,1.); RooAddPdf model("model","model",RooArgList(sgnPDF,bkgPDF),RooArgList(f)); RooFitResult* r = model.fitTo(data,Save()); r->Print("v"); double N = hDat->Integral(); double B = hBkg->Integral(); double S = hSgn->Integral(); double m = f.getVal(); double e = f.getError(); cout<<"k-factor = "<<k_factor<<endl; cout<<N<<" "<<B<<" "<<S<<endl; cout<<"Total cross section = "<<N/lumi<<" pb"<<endl; cout<<"Model cross section = "<<S/lumi<<" pb"<<endl; cout<<"Fitted signal strength = "<<m*N/S<<endl; cout<<"Fitted signal error = "<<e*N/S<<endl; double p = 0.95; double xup = (N/S)*(m+sqrt(2.)*e*TMath::ErfInverse((1-p)*TMath::Erf(m/e)+p)); cout<<"Bayesian Upper limit = "<<xup<<endl; RooPlot* frame1 = x.frame(); data.plotOn(frame1); model.plotOn(frame1,Components("sgnPDF*"),LineStyle(1),LineWidth(2),LineColor(kGreen+1)); model.plotOn(frame1,Components("bkgPDF*"),LineStyle(1),LineWidth(2),LineColor(kRed)); model.plotOn(frame1,LineStyle(1),LineWidth(2),LineColor(kBlue)); //cout<<frame1->chiSquare()<<endl; RooHist* hresid = frame1->residHist(); RooHist* hpull = frame1->pullHist(); RooPlot* frame2 = x.frame(Title("Residual Distribution")); frame2->addPlotable(hresid,"P") ; // Create a new frame to draw the pull distribution and add the distribution to the frame RooPlot* frame3 = x.frame(Title("Pull Distribution")); frame3->addPlotable(hpull,"P"); TCanvas* cFit = new TCanvas("fitANN_"+SIGNAL,"fitANN_"+SIGNAL,900,600); gPad->SetLogy(); frame1->SetMaximum(1e+4); frame1->SetMinimum(0.5); frame1->GetXaxis()->SetTitle("ANN Output"); frame1->GetYaxis()->SetTitle("Events"); frame1->Draw(); cout<<frame1->nameOf(3)<<endl; TLegend *leg = new TLegend(0.7,0.65,0.9,0.9); leg->SetHeader(SIGNAL); leg->AddEntry(frame1->findObject("h_data"),"data","P"); leg->AddEntry(frame1->findObject("model_Norm[x]"),"QCD+Signal","L"); leg->AddEntry(frame1->findObject("model_Norm[x]_Comp[bkgPDF*]"),"QCD","L"); leg->AddEntry(frame1->findObject("model_Norm[x]_Comp[sgnPDF*]"),"Signal","L"); leg->SetFillColor(0); leg->SetBorderSize(0); leg->SetTextFont(42); leg->SetTextSize(0.04); leg->Draw(); TCanvas* cPull = new TCanvas("pullANN_"+SIGNAL,"pullANN_"+SIGNAL,900,400); frame3->GetXaxis()->SetTitle("ANN Output"); frame3->GetYaxis()->SetTitle("Pull"); frame3->Draw(); cout<<"Creating datacard"<<endl; ofstream datacard; datacard.open("datacard_"+SIGNAL+"_"+HISTO+".txt"); datacard.setf(ios::right); datacard<<"imax 1"<<"\n"; datacard<<"jmax 1"<<"\n"; datacard<<"kmax *"<<"\n"; datacard<<"----------------"<<"\n"; datacard<<"shapes * * "<<SIGNAL+"_"+HISTO+"_input.root $PROCESS $PROCESS_$SYSTEMATIC"<<"\n"; datacard<<"----------------"<<"\n"; datacard<<"bin 1"<<"\n"; datacard<<"observation "<<N<<"\n"; datacard<<"----------------"<<"\n"; datacard<<"bin 1 1"<<"\n"; datacard<<"process signal background "<<"\n"; datacard<<"process 0 1"<<"\n"; datacard<<"rate "<<S<<" "<<B<<"\n"; datacard<<"----------------"<<"\n"; datacard<<"lumi lnN 1.022 1.022"<<"\n"; datacard<<"jes shape 1 1"<<"\n"; datacard<<"mcstat shape 1 1"<<"\n"; datacard<<"jer shape 0 0"<<"\n"; datacard.close(); TFile *out = new TFile(SIGNAL+"_"+HISTO+"_input.root","RECREATE"); out->cd(); hDat->Write("data_obs"); hBkg->Write("background"); hSgn->Write("signal"); hDat_JESlo->Write("data_obs_jesDown"); hBkg_JESlo->Write("background_jesDown"); hBkg_STATlo->Write("background_mcstatDown"); hSgn_STATlo->Write("signal_mcstatDown"); hSgn_JESlo->Write("signal_jesDown"); hDat_JESup->Write("data_obs_jesUp"); hBkg_JESup->Write("background_jesUp"); hBkg_STATup->Write("background_mcstatUp"); hSgn_JESup->Write("signal_jesUp"); hSgn_STATup->Write("signal_mcstatUp"); //----- JER placeholder ---------------- hBkg_JESlo->Write("background_jerDown"); hSgn_JESlo->Write("signal_jerDown"); hBkg_JESup->Write("background_jerUp"); hSgn_JESup->Write("signal_jerUp"); }
void calCrystalDepo(TTree *t1041, int ThisModule = -99, bool IsBatch =0){ if(IsBatch) gROOT->SetBatch(); TString ThisModuleString = TString::Itoa(ThisModule,10); int UpOrDown = ThisModule/abs(ThisModule); float Scale = 1.; if(UpOrDown == -1) Scale = 0.5; cout << "Creating energy distributions of events with maximum deposition in module: " << ThisModuleString << endl; //Define Histograms //This histogram is a tool TH1F* MatrixDepo = new TH1F("MatrixDepo", "Deposition on Matrix", 68, -17, 17); TH1F* fracDep = new TH1F("fracDep", "Highest Amplitude Crystal/Total Deposition", 100, 0, 1.2); TH1F* MaxBin = new TH1F("MaxBin", "Deposition of Highest Amplitude Crystal", 100,400*Scale,7000*Scale); TH1F* Integral = new TH1F("Integral", "Integral", 100,4000*Scale,13000*Scale); TH1F* SigNoise = new TH1F("SigNoise", "Signa/Pedestal", 100, 0, 2.); // gStyle->SetOptStat(0); Mapper *mapper=Mapper::Instance(); TBEvent *event = new TBEvent(); t1041->SetBranchAddress("tbevent", &event); bool haverechits=false; vector<TBRecHit> *rechits=0; if(t1041->GetListOfBranches()->FindObject("tbrechits")) { cout <<"found rechits"<<endl; t1041->SetBranchAddress("tbrechits",&rechits); haverechits=true; } Int_t start=0; Int_t end=t1041->GetEntries(); int nEntries=0; // end = 10; for (Int_t i=start; i<end; i++) { t1041->GetEntry(i); if (i==0) mapper->SetEpoch(event->GetTimeStamp()); if(haverechits && rechits->size() < 1) continue; MatrixDepo->Reset(); float maxDepoModuleID = -99; float maxDepo = 0; float secondMaxDepo = 0; float secondMaxDepoModuleID = -99; float totdep = 0; float totalnoise = 0; float sumrms = 0; for (Int_t j = 0; j < event->NPadeChan(); j++){ if (haverechits && j>=(int)rechits->size()) break; double ped,sig, max, maxTime; int channelID; if (haverechits){ TBRecHit &hit=rechits->at(j); ped=hit.Pedestal(); sig=hit.NoiseRMS(); max=hit.AMax(); maxTime=hit.TRise(); channelID=hit.GetChannelID(); } double x,y; int moduleID,fiberID; mapper->ChannelID2ModuleFiber(channelID,moduleID,fiberID); mapper->ModuleXY(moduleID,x,y); MatrixDepo->Fill(moduleID, max); if(UpOrDown > 0 && moduleID > 0) totalnoise+=ped; if(UpOrDown < 0 && moduleID < 0) totalnoise+=ped; } int minx = 0; int maxx = 0; if(UpOrDown > 0){ minx = MatrixDepo->GetXaxis()->FindBin(0.); maxx = MatrixDepo->GetXaxis()->FindBin(17.); MatrixDepo->GetXaxis()->SetRange(minx, maxx); } if(UpOrDown < 0){ minx = MatrixDepo->GetXaxis()->FindBin(-17.); maxx = MatrixDepo->GetXaxis()->FindBin(0.); MatrixDepo->GetXaxis()->SetRange(minx, maxx); } // cout << "TOTAL NOISE: " << totalnoise << endl; float maxbin = MatrixDepo->GetBinContent(MatrixDepo->GetMaximumBin()); float integral = MatrixDepo->Integral(minx,maxx); maxDepoModuleID = MatrixDepo->GetBinLowEdge(MatrixDepo->GetMaximumBin()); if( abs(ThisModule) != 99 && maxDepoModuleID != ThisModule ) continue; if( abs(ThisModule) == 100 ){ if( abs(maxDepoModuleID) != 6 && abs(maxDepoModuleID) != 7 && abs(maxDepoModuleID) != 10 && abs(maxDepoModuleID) != 11) continue; } // if(sumrms/totdep > 0.3) continue; // if( maxDepo/totdep < 0.2 || maxDepo/totdep > 0.5) continue; if( maxbin/integral < .55) continue; // if( totdep/totalnoise < 1.) continue; // if( totdep < 950) continue; // if(sumrms/totdep < 0.3) cout << totdep << endl; MaxBin->Fill(maxbin); Integral->Fill(integral); fracDep->Fill(maxbin/integral); // cout << maxbin/integral; // SigNoise->Fill(integral/totalnoise); // cout << maxbin << endl; nEntries++; } TString FileFig; TCanvas *c5=new TCanvas("c5","Average Peak Height",800,800); c5->SetGrid(); fracDep->Draw(); FileFig = "energy/R9_Module_"+ThisModuleString+".png"; c5->SaveAs(FileFig); TCanvas *c7=new TCanvas("c7","MAXBIN",800,800); c7->SetGrid(); // MaxBin->Fit("gaus", "","", 4100, 6000); MaxBin->Draw(); FileFig = "energy/eMaxCrystal_Module_"+ThisModuleString+".png"; c7->SaveAs(FileFig); TCanvas *c8=new TCanvas("c8","Integral",800,800); c8->SetGrid(); // TF1* fit = new TF1("fit","p0*exp(-(0.5)*((x-760)/p1)^2)",0, 3000); // fit->SetParameters(500, 50); Integral->Fit("gaus");//, "", "", 3000, 4000); gStyle->SetOptFit(); Integral->Draw(); FileFig = "energy/eMatrix_Module_"+ThisModuleString+".png"; c8->SaveAs(FileFig); TCanvas *c9=new TCanvas("c9","Integral",800,800); c9->SetGrid(); SigNoise->Draw(); FileFig = "energy/SignalToNoise_Module"+ThisModuleString+".png"; c9->SaveAs(FileFig); }
void plotFrac(TList* HistList, TH1F* compT, std::string name, bool fracAll){ gROOT->SetBatch(); system("mkdir -p plots/ada/fracs"); system("mkdir -p plots/grad/fracs"); std::string bdt; TString str = compT->GetName(); if (str.Contains("ada")) bdt="ada"; if (str.Contains("grad")) bdt="grad"; int nHists=HistList->GetEntries(); TH1F *comp = linearBin(compT); TH1F *uandd[nHists]; gROOT->SetStyle("Plain"); gROOT->ForceStyle(); gStyle->SetOptStat(0); TCanvas *canv = new TCanvas("","",700,700); canv->Divide(1,2,0.1,0.1); canv->cd(1); gPad->SetPad(0.01,0.3,0.99,0.99); gPad->SetBottomMargin(0.0); gPad->SetLeftMargin(0.1); comp->SetLineColor(1); comp->SetFillColor(kGray); comp->Draw("hist"); comp->SetTitle(("Up, down and interpolated templates for "+bdt+" "+name).c_str()); comp->GetYaxis()->SetRangeUser(0.0,((TH1F*)HistList->At(0))->GetMaximum()+0.5); comp->GetYaxis()->SetTitle("Events / bin"); comp->GetXaxis()->SetTitle("Category"); int mass; if (name=="syst120") mass=120; if (name=="syst135") mass=135; TLegend *leg = new TLegend(0.6,0.5,0.88,0.88); leg->SetLineColor(0); leg->SetFillColor(0); if (name=="syst120" || name=="syst135"){ leg->AddEntry(comp,Form("True %d signal binned at %d",mass,mass),"f"); } canv->cd(2); gPad->SetPad(0.01,0.01,0.99,0.3); gPad->SetTopMargin(0.0); gPad->SetBottomMargin(0.2); gPad->SetLeftMargin(0.1); TF1 *line = new TF1("line","0.0",0.,comp->GetBinLowEdge(comp->GetNbinsX()+1)); line->SetLineColor(kBlack); for (int i=0; i<nHists; i++){ TH1F *temp = linearBin((TH1F*)HistList->At(i)); temp->SetLineColor((i+1)*2); if (!fracAll && i==nHists-1) temp->SetLineColor(kBlack); canv->cd(1); temp->DrawCopy("same e"); uandd[i]= (TH1F*)temp->Clone(); uandd[i]->Add(comp,-1); uandd[i]->Divide(temp); uandd[i]->Scale(-100.); //uandd[i]->Divide(comp); if (name=="syst120" || name=="syst135") { if (i==0) leg->AddEntry(uandd[i],Form("True %d signal binned at %d",mass+5,mass),"lep"); if (i==1) leg->AddEntry(uandd[i],Form("True %d signal binned at %d",mass-5,mass),"lep"); if (i==nHists-1) leg->AddEntry(uandd[i],Form("Interpolated %d signal",mass),"lep"); } //uandd[i]->Scale(100.0); canv->cd(2); if (fracAll){ if (i==0) uandd[i]->Draw("e"); else { uandd[i]->Draw("same e"); line->Draw("same"); } } else { if (i==nHists-1) { uandd[i]->Draw("e"); line->Draw("same"); } } uandd[i]->SetTitle(""); uandd[i]->GetYaxis()->SetLabelSize(0.08); uandd[i]->GetYaxis()->SetRangeUser(-50.,50.); uandd[i]->GetYaxis()->SetTitle("#frac{#Delta_{int}}{int} %"); uandd[i]->GetYaxis()->SetTitleOffset(0.4); uandd[i]->GetYaxis()->SetTitleSize(0.08); uandd[i]->GetXaxis()->SetLabelSize(0.08); uandd[i]->GetXaxis()->SetTitle("BDT output"); uandd[i]->GetXaxis()->SetTitleSize(0.08); canv->cd(1); if (name=="syst120" || name=="syst135") leg->Draw("same"); } canv->Print(("plots/"+bdt+"/fracs/"+name+".png").c_str(),"png"); delete canv; fracCalls++; }
void createNNLOplot(TString theory="ahrens") { // theory="ahrens", "kidonakis" TString outputRootFile="test.root"; // NB: add new datset name here if(theory.Contains("ahrens") ){ outputRootFile="AhrensNLONNLL"; //if(theory.Contains("mtt") ) outputRootFile+="mttbar" ; //else if(theory.Contains("pt")) outputRootFile+="pTttbar"; outputRootFile+=".root"; } else if(theory=="kidonakis") outputRootFile="KidonakisAproxNNLO.root"; // general options gStyle->SetOptStat(0); bool usequad=true; bool divideByBinwidth=true; // list of variables std::vector<TString> xSecVariables_, xSecLabel_; // NB: add variables for new datset name here TString xSecVariablesUsedAhrens[] ={"ttbarMass", "ttbarPt"}; TString xSecVariablesUsedKidonakis[] ={"topPt" , "topY" }; if( theory.Contains("ahrens") ) xSecVariables_ .insert( xSecVariables_.begin(), xSecVariablesUsedAhrens , xSecVariablesUsedAhrens + sizeof(xSecVariablesUsedAhrens )/sizeof(TString) ); else if(theory=="kidonakis") xSecVariables_ .insert( xSecVariables_.begin(), xSecVariablesUsedKidonakis, xSecVariablesUsedKidonakis + sizeof(xSecVariablesUsedKidonakis)/sizeof(TString) ); // get variable binning used for final cross sections std::map<TString, std::vector<double> > bins_=makeVariableBinning(); //std::vector<double> tempbins_; //double ttbarMassBins[]={345,445,545,745, 1045}; //tempbins_.insert( tempbins_.begin(), ttbarMassBins, ttbarMassBins + sizeof(ttbarMassBins)/sizeof(double) ); //bins_["ttbarMass"]=tempbins_; // loop all variables for(unsigned var=0; var<xSecVariables_.size(); ++var){ TString variable=xSecVariables_[var]; std::cout << "----------" << std::endl; std::cout << theory << ": " << variable << std::endl; // get bin boundaries double low =bins_[variable][0]; double high=bins_[variable][bins_[variable].size()-1]; // -------------------------- // get raw nnlo theory points // -------------------------- // NB: add new datset file names here TGraph * rawHist; TString predictionfolder="/afs/naf.desy.de/group/cms/scratch/tophh/CommonFiles/"; if(theory=="ahrens" ){ if(variable.Contains("ttbarMass")) rawHist= new TGraph(predictionfolder+"AhrensTheory_Mttbar_8000_172.5_NLONNLL_norm.dat");//AhrensTheory_Mtt_7000_172.5_Mtt_fin.dat if(variable.Contains("ttbarPt" )) rawHist= new TGraph(predictionfolder+"AhrensTheory_pTttbar_8000_172.5_NLONNLL_abs.dat");//AhrensTheory_pTttbar_7000_172.5_NLONNLL_abs.dat } else if(theory=="kidonakis"){ if(variable.Contains("topPt")) rawHist= new TGraph(predictionfolder+"pttopnnloapprox8lhc173m.dat");//"ptnormalNNLO7lhc173m.dat" //"pttopnnloapprox8lhc173m.dat" if(variable.Contains("topY" )) rawHist= new TGraph(predictionfolder+"ytopnnloapprox8lhc173m.dat" );//"ynormalNNLO7lhc173m.dat" //"ytopnnloapprox8lhc173m.dat" } // NB: say if points should be interpreted as single points with // nothing in between or as integrated value over the range bool points=true; if(theory.Contains("ahrens")) points=false; else if(theory=="kidonakis") points=true; std::cout << "input: " << rawHist->GetTitle() << std::endl; std::cout << "interprete values as points?: " << points << std::endl; // -------------------- // convertion to TH1F* // -------------------- double *Xvalues = rawHist->GetX(); int Nbins=rawHist->GetN(); //double *Yvalues = rawHist->GetY(); // not working double xmax=-1; double xmin=-1; double binwidth=-1; // TH1F* hist; // NB: add additional binning for new theory here // NB: if loaded data should be interpreted as points with // nothing in between (like kidonakis), make suree you // choose a binning that is fine enough for the // data points loaded if(theory=="ahrens"){ if(variable.Contains("ttbarMass")){ xmin= 345.; xmax=2720.; binwidth=25.;// 5 for 8TeV, 25 for 7TeV if(TString(rawHist->GetTitle()).Contains("8000")) binwidth=5.; } else if(variable.Contains("ttbarPt")){ xmin= 0.; xmax=1300.; binwidth=5.; } } else if(theory=="kidonakis"){ if(variable.Contains("topPt")){ xmin= 0.; xmax=1500.; binwidth=1.; } else if(variable.Contains("topY")){ xmin=-3.8; xmax= 3.8; binwidth=0.01; } } // fill data in binned TH1F hist= new TH1F ( variable, variable, (int)((xmax-xmin)/binwidth), xmin, xmax); TH1F* ori=(TH1F*)hist->Clone("original points"); std::cout << "fine binned theory prediction has " << hist->GetNbinsX() << " bins" << std::endl; std::cout << "loaded values from .dat file: " << std::endl; // list all data values loaded and the corresponding bin for(int bin=1; bin<=Nbins; ++bin){ double x=-999; double y=-999; // NB: choose if loaded data is interpreted as points with nothing // between (like kidonakis) or as integrated over the bin range (like ahrens) if(points){ // check if you are still inside the array //std::cout << "data point " << bin-1 << "/" << sizeof(Xvalues)/sizeof(double) << std::endl; if(rawHist->GetPoint(bin-1, x, y)!=-1){ //x=Xvalues[bin-1]; // get value from data points x+=0.5*binwidth; // add half the binwidth to get the center of the bin } } else{ x=hist->GetBinCenter(bin); // get bin center y=rawHist->GetY()[bin-1]; } if(x!=-999){ std::cout << "data point: " << bin; std::cout << "(<x>=" << x << ")-> bin"; // get bin in target (fine binned) plot int bin2=bin; if(points) bin2=hist->FindBin(x); //double y=Yvalues[bin2-1]; std::cout << bin2 << " ("; std::cout << hist->GetBinLowEdge(bin2) << ".." << hist->GetBinLowEdge(bin2+1); std::cout << "): " << y << std::endl; // fill target (fine binned) plot if(!points) hist->SetBinContent(bin2, y); // mark bins coming from the original prediction ori->SetBinContent(bin2, 1.); // ------------------------------- // fit range without data entries // ------------------------------- // NB: needed if loaded data is interpreted as points with nothing // between (like kidonakis) if(points){ // perform a linear fit wrt previous point // get the two points (this bin and the previous one) int binPrev= (bin==1&&variable=="topPt") ? 0 : hist->FindBin(Xvalues[bin-2]+0.5*binwidth); double x2=-1; double x1= 0; double y2=-1; double y1= 0.; rawHist->GetPoint(bin-1, x2, y2); x2+=0.5*binwidth; if(bin==1&&variable=="topPt"){ y1=0; x1=0; } else{ rawHist->GetPoint(bin-2, x1, y1); x1+=0.5*binwidth; } // calculate linear funtion double a=(y2-y1)/(x2-x1); double b=y1-a*x1; TF1* linInterpol=new TF1("linInterpol"+getTStringFromInt(bin), "[0]*x+[1]", x1, x2); linInterpol->SetParameter(0,a); linInterpol->SetParameter(1,b); double xlow = (bin==1&&variable=="topPt") ? 0. : hist->GetBinLowEdge(binPrev+1); double xhigh = hist->GetBinLowEdge(bin2+1); std::cout << " lin. interpolation [ (" << x1 << "," << y1 << ") .. (" << x2 << "," << y2 << ") ]: " << a << "*x+" << b << std::endl; linInterpol->SetRange(xlow, xhigh); hist->Add(linInterpol); } } } // check theory curve std::cout << std::endl << "analyze theory curve:" << std::endl; double integralRawTheory=hist->Integral(0.,hist->GetNbinsX()+1); std::cout << "Integral: " << integralRawTheory << std::endl; if(integralRawTheory==0.){ std::cout << "ERROR: Integral can not be 0!" << std::endl; exit(0); } std::cout << "binwidth: " << binwidth << std::endl; std::cout << "Integral*binwidth: " << integralRawTheory*binwidth << std::endl; std::cout << "binRange: " << xmin << ".." << xmax << std::endl; std::cout << " -> reco range: " << low << ".." << high << std::endl; std::vector<double> recoBins_=bins_[variable]; for(unsigned int i=0; i<recoBins_.size(); ++i){ i==0 ? std::cout << "(" : std::cout << ", "; std::cout << recoBins_[i]; if(i==recoBins_.size()-1) std::cout << ")" << std::endl; } // check if you need to divide by binwidth if(std::abs(1.-integralRawTheory)<0.03){ std::cout << "Integral is approx. 1 -> need to divide by binwidth!" << std::endl; hist->Scale(1./binwidth); } else if(std::abs(1-integralRawTheory*binwidth)<0.03){ std::cout << "Integral*binwidth is approx. 1 -> no scaling needed!" << std::endl; } else{ std::cout << "need to normalize and divide by binwidth"; hist->Scale(1./(binwidth*integralRawTheory)); } // styling hist->GetXaxis()->SetRangeUser(low,high); hist->SetMarkerColor(kMagenta); hist->SetLineColor( kMagenta); hist->SetMarkerStyle(24); // create canvas std::cout << std::endl << "create canvas " << std::endl; TCanvas *canv = new TCanvas(variable,variable,800,600); canv->cd(); std::cout << "draw original theory curve " << std::endl; //temp->Draw("axis"); hist->Draw("p"); //hist->Draw("hist same"); // draw original points if(points){ for(int bin=1; bin<ori->GetNbinsX(); ++bin){ // create copy of original data points with the normalized values if(ori->GetBinContent(bin)!=0) ori->SetBinContent(bin, hist->GetBinContent(bin)); ori->SetMarkerColor(kBlack); ori->SetMarkerStyle(29); ori->SetMarkerSize(1); ori->Draw("p same"); } } // -------------------- // create rebinned plot // -------------------- std::cout << std::endl << "create rebinned curve:" << std::endl; TString name=""; // NB: add name for dataset here name=variable; if( theory=="kidonakis") name+="approxnnlo"; else if(theory=="ahrens" ) name+="nlonnll" ; TH1F* binnedPlot=new TH1F(name, name, bins_[variable].size()-1, &bins_[variable][0]); for(int bin=1; bin<=hist->GetNbinsX(); ++bin){ double y=hist->GetBinContent(bin)*hist->GetBinWidth(bin); double xlow =hist->GetBinLowEdge(bin); double xhigh=hist->GetBinLowEdge(bin+1); // search corresponding bin in rebinned curve bool found=false; //std::cout << "xlow: " << xlow << ", xhigh: " << xhigh << std::endl; // FIXME for(int binRebinned=0; binRebinned<=binnedPlot->GetNbinsX()+1; ++binRebinned){ if(binnedPlot->GetBinLowEdge(binRebinned)<=xlow&&binnedPlot->GetBinLowEdge(binRebinned+1)>=xhigh){ found=true; binnedPlot->SetBinContent(binRebinned, binnedPlot->GetBinContent(binRebinned)+y); break; } //else{ // std::cout << "not in: " << binnedPlot->GetBinLowEdge(binRebinned) << ".." << binnedPlot->GetBinLowEdge(binRebinned+1)<< std::endl; //} } // -------------------- // use linear interpolation for edge bins // -------------------- if(hist->GetBinCenter(bin)<high&&!found){ std::cout << "need interpolation for bin" << bin << "(<x>=" << hist->GetBinCenter(bin) << ")!"<< std::endl; // search for the two bins involved double binLow=0; double binHigh=0; for(int binRebinned=1; binRebinned<=binnedPlot->GetNbinsX(); ++binRebinned){ // search for bin in binned histo where upper border of is close to lower border of unbinned histo if(std::abs(binnedPlot->GetBinLowEdge(binRebinned+1)-xlow)<binwidth){ binLow =binRebinned; binHigh=binRebinned+1; break; } } std::cout << "theory bin " << xlow << ".." << xhigh << "-> reco bins "; std::cout << binnedPlot->GetBinLowEdge(binLow) << ".." << binnedPlot->GetBinLowEdge(binLow+1) << " & "; std::cout << binnedPlot->GetBinLowEdge(binHigh) << ".." << binnedPlot->GetBinLowEdge(binHigh+1) << std::endl; // get the two points (this bin and the previous one) double x2=hist->GetBinCenter (bin ); double x1=hist->GetBinCenter (bin-1); double x3=hist->GetBinCenter (bin+1); double y2=hist->GetBinContent(bin ); double y1=hist->GetBinContent(bin-1); double y3=hist->GetBinContent(bin+1); // calculate linear funtion double a=(y2-y1)/(x2-x1); double b=y1-a*x1; TF1* linInterpol=new TF1("linInterpol"+getTStringFromInt(bin), "[0]*x+[1]", x1, x2); linInterpol->SetParameter(0,a); linInterpol->SetParameter(1,b); // calculate the corresponding area of linear function to binned curve double contributionLowerBin=linInterpol->Integral(xlow,binnedPlot->GetBinLowEdge(binHigh)); double contributionUpperBin=linInterpol->Integral(binnedPlot->GetBinLowEdge(binHigh),xhigh); // draw interpolation function for checking linInterpol->SetRange(xlow,xhigh); linInterpol->SetLineColor(kMagenta); linInterpol->DrawClone("same"); // eventually use quadratic interpolation for the first harens m(ttbar) bin if(theory=="ahrens"&&variable.Contains("ttbarMass")&&usequad&&x2<450){ // calculate quadratic funtion double a2=(y2-((y3-y1))*(x2-x1)/(x3-x1))/(x2*x2-x1*x1-(x2-x1)*(x3*x3+x1*x1)/(x3-x1)); double b2=((y3-y1)-a2*(x3*x3-x1*x1))/(x3-x1); double c2=y1-a2*x1*x1-b*x1; TF1* quadInterpol=new TF1("quadInterpol"+getTStringFromInt(bin), "[0]*x*x+[1]*x+[2]", x1, x2); quadInterpol->SetParameter(0,a2); quadInterpol->SetParameter(1,b2); quadInterpol->SetParameter(2,c2); // draw quad interpolation function for checking quadInterpol->SetRange(xlow,xhigh); quadInterpol->SetLineColor(kGreen); quadInterpol->SetLineStyle(2); hist->Fit(quadInterpol, "", "same", x1, x3); // calculate the corresponding area of linear function to binned curve quadInterpol->DrawClone("same"); double areaLow =quadInterpol->Integral(xlow,binnedPlot->GetBinLowEdge(binHigh) ); double areaHigh=quadInterpol->Integral(binnedPlot->GetBinLowEdge(binHigh),xhigh); std::cout << "ratio(high/low) linear/quadratic: " << contributionUpperBin/contributionLowerBin << "/"<< areaHigh/areaLow << std::endl; contributionLowerBin=y2*binwidth*areaLow /(areaLow+areaHigh); contributionUpperBin=y2*binwidth*areaHigh/(areaLow+areaHigh); } // add fitted result binnedPlot->SetBinContent(binLow , binnedPlot->GetBinContent(binLow )+contributionLowerBin); binnedPlot->SetBinContent(binHigh, binnedPlot->GetBinContent(binHigh)+contributionUpperBin); } } // ensure over/underflow is 0 binnedPlot->SetBinContent(0, 0.); binnedPlot->SetBinContent(binnedPlot->GetNbinsX()+1, 0.); // ensure normalization binnedPlot->Scale(1./(binnedPlot->Integral(0.,binnedPlot->GetNbinsX()+1))); // divide by binwidth if(divideByBinwidth){ for(int bin=1; bin<=binnedPlot->GetNbinsX(); ++bin){ binnedPlot->SetBinContent(bin, binnedPlot->GetBinContent(bin)/binnedPlot->GetBinWidth(bin)); } } std::cout << "-------------------------------------------" << std::endl; std::cout << "result: binned output histo" << std::endl; for(int bin=1; bin<=binnedPlot->GetNbinsX(); ++bin){ std::cout << "content bin " << bin << " (" << binnedPlot->GetBinLowEdge(bin) << ".." << binnedPlot->GetBinLowEdge(bin+1) << ")= " << binnedPlot->GetBinContent(bin) << std::endl; } // styling binnedPlot->SetLineColor(kBlue); binnedPlot->SetLineWidth(2); std::cout << "draw rebinned theory curve " << std::endl; binnedPlot->Draw("hist same"); // draw bin boundaries std::cout << "draw bin boundaries " << std::endl; int binColor=kRed; int binWidth=2; int binStyle=6; for(int bin=0; bin<(int)bins_.size(); ++bin){ if(!variable.Contains("ttbarMass")||bins_[variable][bin]>=345.) drawLine(bins_[variable][bin], 0, bins_[variable][bin], hist->GetMaximum(), binColor, binWidth, binStyle); } TH1F* line=(TH1F*)hist->Clone("line"); line->SetLineColor(binColor); line->SetLineWidth(binWidth); line->SetLineStyle(binStyle); // legend TLegend *leg = new TLegend(0.7, 0.6, 0.95, 0.9); legendStyle(*leg,theory); if(points) leg ->AddEntry(ori, "original data points","P"); leg ->AddEntry(hist , "theory prediction" ,"P"); leg ->AddEntry(line , "reco binning" ,"L"); leg ->AddEntry(hist , "linear interpolation" ,"L"); leg ->AddEntry(binnedPlot, "rebinned curve" ,"L"); leg->Draw("same"); std::cout << "done" << std::endl; // save in png and rootfile std::cout << std::endl << "do saving..." << std::endl; canv->SaveAs(variable+"Norm_Theory.png"); TH1F* out=(TH1F*)binnedPlot->Clone(); out->SetTitle(variable); out->SetName (variable); out->GetXaxis()->SetTitle(xSecLabelName(variable)); TString yTile="#frac{1}{#sigma} #frac{d#sigma}{d"; if(variable=="ttbarMass") yTile+="m^{t#bar{t}}} [GeV^{-1}]"; if(variable=="ttbarPt") yTile+="p_{T}^{t#bar{t}}} [GeV^{-1}]"; if(variable=="topPt") yTile+="p_{T}^{t}} [GeV^{-1}]"; if(variable=="topY" ) yTile+="y^{t}}"; out->GetYaxis()->SetTitle(yTile); out->SetLineColor(kOrange+2); out->SetLineStyle(2); std::cout << std::endl << "draw final result " << std::endl; TCanvas *canv2 = new TCanvas(variable+"Rebinned",variable+"Rebinned",800,600); canv2->cd(); out->Draw(); saveToRootFile(outputRootFile, out , true, 0,"" ); saveToRootFile(outputRootFile, rawHist, true, 0,"graph" ); saveToRootFile(outputRootFile, canv , true, 0,"detail"); std::cout << "done!" << std::endl; } }
void SPEFit(char * fname, int run, int LED_amp, double cutmax = 250.0) { //set plotting styles gStyle->SetCanvasColor(0); gStyle->SetPadColor(0); gStyle->SetCanvasBorderMode(0); gStyle->SetFrameBorderMode(0); gStyle->SetStatColor(0); gStyle->SetPadTickX(1); gStyle->SetPadTickY(1); //set file names stringstream out_fname; stringstream out_fname1; out_fname<<"SPEconstants_Run_"<<run<<".txt"; out_fname1<<"SPEspec_Run_"<<run<<".txt"; ofstream constants_file(out_fname.str().c_str(),ios_base::trunc); ofstream constants_file1(out_fname1.str().c_str(),ios_base::trunc); constants_file<<"Run "<<run<<endl; constants_file<<"type SPE"<<endl; constants_file<<"LED_amplitude "<<LED_amp<<endl<<endl; //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl; constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag Polya_shape Polya_shape_err Polya_mode"<<endl; out_fname.str(""); out_fname<<"SPEdistributions_Run_"<<run<<".txt"; out_fname.str(""); out_fname<<"SPEextra_Run_"<<run<<".txt"; //ofstream extra_file(out_fname.str().c_str(),ios_base::trunc); //extra_file<<endl<<"LED_amplitude HV Spigot Channel PedSubtracted_mean Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl; double scale = 1.0; scale = 2.6; //Need to scale up HF charge double fC2electrons = 6240.; //convert fC to #electrons char spename[128], pedname[128], spehistname[128]; bool drawflag; TFile *tf = new TFile(fname); TCanvas *c1 = new TCanvas("c1","c1",1200,700); c1->Divide(6,4); c1->SetBorderMode(0); c1->SetBorderSize(0); TCanvas *c2 = new TCanvas("c2","c2",1200,700); c2->Divide(6,4); c2->SetBorderMode(0); c2->SetBorderSize(0); TCanvas *c3 = new TCanvas("c3","c3",1200,700); c3->Divide(6,4); c3->SetBorderMode(0); c3->SetBorderSize(0); const int NnewBins = 106; double binsX[NnewBins] = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500}; TH1F* hspe = new TH1F("hspe","hspe",NnewBins-1,binsX); int Npoints; TH2D *tmp; for(Npoints=0;Npoints<10;Npoints++){ sprintf(spename,"spetest/spigot_%d/bb_%d/LED_HVset_%d_sp_%d_BB_%d",0,1,Npoints,0,1); tmp=(TH2D *)tf->Get(spename); if(tmp==0) break; } TH2D *LED[3][3][20]; TH2D *PED[3][3]; for(int iSpig = 0; iSpig < 3; iSpig++)for(int bb = 1; bb < 4; bb++){ for(int ii=0; ii<Npoints; ii++){ sprintf(spename,"spetest/spigot_%d/bb_%d/LED_HVset_%d_sp_%d_BB_%d",iSpig,bb,ii,iSpig,bb); LED[iSpig][bb-1][ii]=(TH2D *)tf->Get(spename); } sprintf(spename,"spetest/spigot_%d/bb_%d/PED_sp_%d_BB_%d",iSpig,bb,iSpig,bb); PED[iSpig][bb-1]=(TH2D *)tf->Get(spename); } for(int ii=0; ii<Npoints; ii++) { drawflag=false; int HV=0; for (int iSpig = 0; iSpig < 3; iSpig++) { for(int i = 0; i < 24; i++) { int bb=BB_MAP[i]; int pmt=PMT_MAP[i]; sprintf(spehistname,"led %d %d %d",ii,iSpig,i); TH1D *hspe_temp = (TH1D *)LED[iSpig][bb-1][ii]->ProjectionX(spehistname,pmt,pmt,"")->Clone(); sprintf(spehistname,"ped %d %d %d",ii,iSpig,i); TH1D *hped = (TH1D *)PED[iSpig][bb-1]->ProjectionX(spehistname,pmt,pmt,"")->Clone(); sscanf(&hspe_temp->GetTitle()[7],"%d",&HV); hspe->Reset(); sprintf (spehistname, "SumLED%d_sp_%d_ch_%d", HV, iSpig, i); hspe->SetTitle(spehistname); //combine bins of original SPE histogram for(int ib=1; ib<=hspe_temp->GetNbinsX(); ib++) { double bin_center = hspe_temp->GetBinCenter(ib); if(bin_center>hspe->GetXaxis()->GetXmax()) continue; int newbin = hspe->FindBin(bin_center); double new_content = hspe->GetBinContent(newbin) + hspe_temp->GetBinContent(ib); double new_error = sqrt(pow(hspe->GetBinError(newbin),2)+pow(hspe_temp->GetBinError(ib),2)); hspe->SetBinContent(newbin,new_content); hspe->SetBinError(newbin,new_error); } TH1F* hspe_unscaled = (TH1F*)hspe->Clone("hspe_unscaled"); //renormalize bins of new SPE histogram for(int ib=1; ib<=hspe->GetNbinsX(); ib++) { double new_content = hspe->GetBinContent(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1); double new_error = hspe->GetBinError(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1); hspe->SetBinContent(ib,new_content); hspe->SetBinError(ib,new_error); } if(hspe_temp->Integral()==0) continue; else drawflag=true; Nev = hspe_temp->Integral()*hspe_temp->GetXaxis()->GetBinWidth(1); TF1 *fped = new TF1("fped","gaus",0, 80); hped->Fit(fped,"NQR"); double pploc = fped->GetParameter(1), ppwidth = fped->GetParameter(2); //cout<<"Ped only: ped mean "<<fped->GetParameter(1)<<", ped width "<<fped->GetParameter(2)<<" normalization "<<fped->GetParameter(0)<<endl; hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + ppwidth); //cout<<"SPE distribution: ped mean "<<fped->GetParameter(1)<<", ped width "<<fped->GetParameter(2)<<" normalization "<<fped->GetParameter(0)<<endl; //estimate SPE peak location int max_SPE_bin, maxbin, Nbins; double max_SPE_height=0, minheight, max_SPE_location; bool minflag = false; maxbin=hspe->FindBin(fped->GetParameter(1)); //location of pedestal peak minheight=hspe->GetBinContent(maxbin); //initialize minheight /* int maxped_bin = hspe->GetMaximumBin(); int maxped_binheight = hspe->GetBinContent(maxped_bin); minheight = maxped_binheight; */ Nbins = hspe->GetNbinsX(); for(int j=/*maxped_bin*/maxbin+1; j<Nbins-1; j++) { //start from pedestal peak and loop through bins if(hspe->GetBinContent(j) > minheight && !minflag) minflag=true; //only look for SPE peak when minflag=true if(hspe->GetBinContent(j) < minheight ) minheight = hspe->GetBinContent(j); if(minflag && hspe->GetBinContent(j) > max_SPE_height){ max_SPE_bin = j; max_SPE_location = hspe->GetBinCenter(max_SPE_bin); max_SPE_height = hspe->GetBinContent(j); } } //start from pedestal peak and loop through bins //find minimum bin between pedestal and SPE peaks hspe->GetXaxis()->SetRange(maxbin,max_SPE_bin); int minbin = hspe->GetMinimumBin(); double minbin_location = hspe->GetBinCenter(minbin); hspe->GetXaxis()->SetRange(1,Nbins); TF1 *fit = new TF1("fit", FitFun, 0, 500, 5); double mu = - log(fped->Integral(0,100)/Nev); if(mu<0) mu=0.01; double gain_est = max_SPE_location-1.0*fped->GetParameter(1); if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, 20, 1, gain_est, 3.0); else fit->SetParameters(mu, 20, 1, 2.1*fped->GetParameter(2), 3.0); //case of no clear minimum; start looking for SPE peak at 2sigma away from pedestal peak fit->SetParLimits(0, 0, 10); fit->FixParameter(1, fped->GetParameter(1)); fit->FixParameter(2, fped->GetParameter(2)); fit->SetParLimits(3, fped->GetParameter(2)*2, 350); fit->SetParLimits(4, 1.01, 100.); double maxfitrange = 500.; double minfitrange = 0.; hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange); double rms_estimate = fit->GetParameter(3)/sqrt(fit->GetParameter(4)); maxfitrange = fped->GetParameter(1)+4*fit->GetParameter(3)+rms_estimate; // cout<<"estimate of gain "<<gain_est<<", fit "<<fit->GetParameter(3)<<endl; // cout<<"Shape Parameter "<<fit->GetParameter(4)<<endl; // cout<<"SPE width "<<rms_estimate<<endl; // cout<<"maxfitrange "<<maxfitrange<<endl; if(500<maxfitrange) maxfitrange = 500; hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange); //calculate NDOF of fit excluding bins with 0 entries int myNDOF=-3; //three free parameters for(int j=hspe->FindBin(minfitrange); j<=hspe->FindBin(maxfitrange); j++) { //loop through fitted spe bins if(hspe->GetBinContent(j)) myNDOF++; } //loop through fitted spe bins // cout<<"estimate of gain "<<gain_est<<", fit "<<fit->GetParameter(3)<<endl; // cout<<"Shape Parameter "<<fit->GetParameter(4)<<endl; // double SPE_rms = fit->GetParameter(3)/sqrt(fit->GetParameter(4)); // cout<<"SPE width "<<SPE_rms<<endl; //cout<<"SPE width "<<fit->GetParameter(4)<<endl; //cout<<"Fit normalization constant: estimate "<<mu<<" fit "<<fit->GetParameter(0)<<endl; //cout<<spename<<endl; //calculate means and integrals of the fit and data double fint, fint_error, hint, favg, havg; int temp_lowbin, temp_highbin; temp_lowbin = hspe->FindBin(minfitrange); temp_highbin = hspe->FindBin(maxfitrange); hspe_unscaled->GetXaxis()->SetRangeUser(minfitrange, maxfitrange); havg = hspe_unscaled->GetMean(); hint = hspe->Integral(temp_lowbin,temp_highbin,"width"); double min_frange = hspe->GetBinLowEdge(temp_lowbin); favg = fit->Mean(min_frange, maxfitrange); fint = fit->Integral(min_frange, maxfitrange); //fint_error = fit->IntegralError(min_frange, maxfitrange); double PE5int = 0; //integral of events with >=5 PE double PE5loc = fped->GetParameter(1)+ 5*fit->GetParameter(3); if(PE5loc>500) PE5int = 0; else { int PE5bin = hspe_temp->FindBin(PE5loc); temp_highbin = hspe_temp->FindBin(maxfitrange)-1; PE5int = hspe_temp->Integral(PE5bin,temp_highbin,"width"); } int PE5flag = 0; if(PE5int/hint>0.05) PE5flag = 1; //set flag if more than 5% of events in the fit correspond to >=5PE //========================================= for(int i1=1;i1<hspe->GetNbinsX();i1++){ constants_file1<<HV<<"\t"<<iSpig<<"\t"<<i<<"\t"<<2.6*hspe->GetBinCenter(i1)<<"\t"<<hspe->GetBinContent(i1)<<"\t"<<fit->Eval(hspe->GetBinCenter(i1))<<"\n"; } //========================================= //output calibrations constants //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag Polya_shape Polya_shape_err Polya_mode"<<endl; constants_file<<LED_amp<<" "<<HV<<" "<<iSpig<<" "<<(bb-1)*8+pmt<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(3)/sqrt(fit->GetParameter(4))<<" "<<0<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<" "<<fit->GetParameter(4)<<" "<<fit->GetParError(4)<<" "<<scale*(fit->GetParameter(4)-1.0)/fit->GetParameter(4)*fit->GetParameter(3)*fC2electrons<<endl; // cout<<LED_amp<<" "<<HV<<" "<<iSpig<<" "<<QIECh[i]<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/fit->GetNDF()<<" "<<fit->GetChisquare()<<" "<<fit->GetNDF()<<" "<<myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<endl; //extra_file<<endl<<"LED_amplitude HV Spigot Channel SignalAvg_inFitRange FitAvg_inFitRange SignalInt_inFitRange FitInt_inFitRange PEge5Int Gain(fC) Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl; //extra_file<<LED_amp<<" "<<HV<<" "<<iSpig<<" "<<QIECh[i]<<" "<<scale*havg<<" "<<scale*favg<<" "<<hint<<" "<<fint<<" "<<PE5int<<" "<<scale*fit->GetParameter(3)<<" "<<scale*fit->GetParError(3)<<" "<<fit->GetChisquare()/myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl; //cout<<"# Spigot Channel Ped_mean Ped_RMS SPE_PeakRMS Gain Normalized_Chi2 Avg_PE"<<endl; //cout<<iSpig<<" "<<i<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<fit->GetChisquare()/fit->GetNDF()<<" "<<fit->GetParameter(0)<<endl<<endl; if(iSpig==0) c1->cd(i+1); else if(iSpig==1) c2->cd(i+1); else if(iSpig==2) c3->cd(i+1); gPad->SetBorderMode(0); gPad->SetBorderSize(0); gPad->SetRightMargin(0.01); gPad->SetBottomMargin(0.1); gPad->SetLogy(true); hspe->GetXaxis()->SetRangeUser(0, /*300*/508); hspe->SetLineColor(kBlue); hspe->DrawClone("hist"); fit->SetLineWidth(2); fit->Draw("same"); } } if(drawflag) { //draw plots of fit if data for the HV is present stringstream plot_name; //plot_name<<"Plots/SPEFits_Spigot0_Run_"<<run<<"_HV"<<HV<<".pdf"; plot_name<<"Plots/SPEFits_Spigot0_Run_"<<run<<"_HV"<<HV<<"_config"<<ii<<".pdf"; c1->SaveAs(plot_name.str().c_str()); plot_name.str( std::string() ); //plot_name<<"Plots/SPEFits_Spigot1_Run_"<<run<<"_HV"<<HV<<".pdf"; plot_name<<"Plots/SPEFits_Spigot1_Run_"<<run<<"_HV"<<HV<<"_config"<<ii<<".pdf"; c2->SaveAs(plot_name.str().c_str()); plot_name.str( std::string() ); //plot_name<<"Plots/SPEFits_Spigot2_Run_"<<run<<"_HV"<<HV<<".pdf"; plot_name<<"Plots/SPEFits_Spigot2_Run_"<<run<<"_HV"<<HV<<"_config"<<ii<<".pdf"; c3->SaveAs(plot_name.str().c_str()); } } //HV loop constants_file.close(); constants_file1.close(); }
void DoEvolutions( const TString &sim, Int_t time, Int_t Nbins=1, const TString &options="") { #ifdef __CINT__ gSystem->Load("libptools.so"); #endif PGlobals::Initialize(); // Palettes! gROOT->Macro("PPalettes.C"); TString opt = options; // cout << "options = " << opt << endl; // Load PData PData *pData = PData::Get(sim.Data()); pData->LoadFileNames(time); if(!pData->IsInit()) return; Bool_t CYL = kFALSE; if(sim.Contains("cyl")) { CYL = kTRUE; opt += "cyl"; } Bool_t ThreeD = kFALSE; if(sim.Contains("3D")) ThreeD = kTRUE; // Some plasma constants Double_t n0 = pData->GetPlasmaDensity(); Double_t kp = pData->GetPlasmaK(); Double_t skindepth = 1.0; if(kp!=0.0) skindepth = 1/kp; Double_t E0 = pData->GetPlasmaE0(); // Some initial beam properties: Float_t Ebeam = pData->GetBeamEnergy() * PUnits::MeV; Float_t gamma = pData->GetBeamGamma(); Float_t vbeam = pData->GetBeamVelocity(); Double_t rms0 = pData->GetBeamRmsY() * kp; if(CYL) rms0 = pData->GetBeamRmsR() * kp; // Time in OU Float_t Time = pData->GetRealTime(); // z start of the plasma in normalized units. Float_t zStartPlasma = pData->GetPlasmaStart() * kp; // z start of the beam in normalized units. Float_t zStartBeam = pData->GetBeamStart() * kp; if(opt.Contains("center")) { Time -= zStartPlasma; if(opt.Contains("comov")) // Centers on the head of the beam. Time += zStartBeam; } // Beam charge 2D and 1D histogram (on-axis) // ------------------------------------------------------------------ TH2F *hDen2D = NULL; if(pData->GetChargeFileName(1)) { char hName[24]; sprintf(hName,"hDen2D"); hDen2D = (TH2F*) gROOT->FindObject(hName); if(hDen2D) { delete hDen2D; hDen2D = NULL; } if(!ThreeD) hDen2D = pData->GetCharge(1,opt); else hDen2D = pData->GetCharge2DSliceZY(1,-1,1,opt+"avg"); hDen2D->SetName(hName); hDen2D->GetXaxis()->CenterTitle(); hDen2D->GetYaxis()->CenterTitle(); hDen2D->GetZaxis()->CenterTitle(); if(opt.Contains("comov")) hDen2D->GetXaxis()->SetTitle("k_{p}#zeta"); else hDen2D->GetXaxis()->SetTitle("k_{p}z"); if(CYL) hDen2D->GetYaxis()->SetTitle("k_{p}r"); else hDen2D->GetYaxis()->SetTitle("k_{p}y"); hDen2D->GetZaxis()->SetTitle("n_{b}/n_{0}"); } // Define ranges from the charge 2D histogram: // Binning for 2D histograms: // We get this values from the 2D density histogram. Int_t x1Nbin = hDen2D->GetNbinsX(); Float_t x1Range = (hDen2D->GetXaxis()->GetXmax() - hDen2D->GetXaxis()->GetXmin()); Float_t x1Mid = (hDen2D->GetXaxis()->GetXmax() + hDen2D->GetXaxis()->GetXmin())/2.; Float_t x1Min = hDen2D->GetXaxis()->GetXmin(); Float_t x1Max = hDen2D->GetXaxis()->GetXmax(); Int_t x2Nbin = hDen2D->GetNbinsY(); Float_t x2Range = (hDen2D->GetYaxis()->GetXmax() - hDen2D->GetYaxis()->GetXmin()); Float_t x2Mid = (hDen2D->GetYaxis()->GetXmax() + hDen2D->GetYaxis()->GetXmin())/2.; Float_t x2Min = x2Mid - x2Range/2; Float_t x2Max = x2Mid + x2Range/2; if(Nbins==0) { Nbins = TMath::Nint(rms0 / hDen2D->GetYaxis()->GetBinWidth(1)) ; // cout << Form(" Rms0 = %6.2f Dx = %6.2f Nbins = %4i .", // rms0, hDen2D->GetYaxis()->GetBinWidth(1), Nbins) << endl; } // Slice width limits. Int_t FirstyBin = 0; Int_t LastyBin = 0; if(!CYL) { FirstyBin = hDen2D->GetNbinsY()/2 + 1 - Nbins; LastyBin = hDen2D->GetNbinsY()/2 + Nbins; } else { FirstyBin = 1; LastyBin = Nbins; } // OUTPUT ROOT FILE WITH THE PLOTS: TString filename = Form("./%s/Plots/Evolutions/Evolutions-%s.root",sim.Data(),sim.Data()); TFile * ifile = (TFile*) gROOT->GetListOfFiles()->FindObject(filename); // if doesn't exist the directory should be created if (!ifile) { TString f = filename; TString dir2 = f.Remove( f.Last( '/' ), f.Length() - f.Last( '/' ) ); TString dir1 = f.Remove( f.Last( '/' ), f.Length() - f.Last( '/' ) ); gSystem->mkdir( dir1 ); gSystem->mkdir( dir2 ); ifile = new TFile(filename,"UPDATE"); } // Charge 1D histogram on axis TH1F *hDen1D = NULL; if(pData->GetChargeFileName(1)) { TString opth1 = opt; opth1 += "avg"; char hName[24]; sprintf(hName,"hDen1D"); hDen1D = (TH1F*) gROOT->FindObject(hName); if(hDen1D) delete hDen1D; if(ThreeD) { hDen1D = pData->GetH1SliceZ3D(pData->GetChargeFileName(1)->c_str(),"charge",-1,Nbins,-1,Nbins,opth1.Data()); } else if(CYL) { // Cylindrical: The first bin with r>0 is actually the number 1 (not the 0). hDen1D = pData->GetH1SliceZ(pData->GetChargeFileName(1)->c_str(),"charge",1,Nbins,opth1.Data()); } else { // 2D cartesian hDen1D = pData->GetH1SliceZ(pData->GetChargeFileName(1)->c_str(),"charge",-1,Nbins,opth1.Data()); } hDen1D->SetName(hName); if(opt.Contains("comov")) hDen1D->GetXaxis()->SetTitle("k_{p}#zeta"); else hDen1D->GetXaxis()->SetTitle("k_{p}z"); hDen1D->GetYaxis()->SetTitle("n_{b}/n_{0}"); } // On-axis beam density vs \zeta vs time! _________________________________ TH2F *hDen1DvsTime = NULL; if(hDen1D) { char hName[24]; sprintf(hName,"hDen1DvsTime"); TH2F *hDen1DvsTimeOld = (TH2F*) ifile->Get(hName); Int_t nBins = 1; Float_t edge0 = Time-0.5; Float_t edge1 = Time+0.5; if(hDen1DvsTimeOld!=NULL) { nBins = hDen1DvsTimeOld->GetNbinsX()+1; Float_t binwidth = (Time - hDen1DvsTimeOld->GetXaxis()->GetBinCenter(1))/(nBins-1); edge0 = hDen1DvsTimeOld->GetXaxis()->GetBinCenter(1) - binwidth/2.; edge1 = Time + binwidth/2.; } hDen1DvsTime = new TH2F("temp","",nBins,edge0,edge1, hDen1D->GetNbinsX(), hDen1D->GetBinLowEdge(1), hDen1D->GetBinLowEdge(hDen1D->GetNbinsX()+1)); for(Int_t ix=1;ix<hDen1DvsTime->GetNbinsX();ix++) { for(Int_t iy=1;iy<hDen1DvsTime->GetNbinsY();iy++) { hDen1DvsTime->SetBinContent(ix,iy,hDen1DvsTimeOld->GetBinContent(ix,iy)); } } delete hDen1DvsTimeOld; // Fill last bin with the newest values. for(Int_t iy=1;iy<=hDen1D->GetNbinsX();iy++) { hDen1DvsTime->SetBinContent(nBins,iy,hDen1D->GetBinContent(iy)); } hDen1DvsTime->GetZaxis()->SetTitle("n_{b}/n_{0}"); hDen1DvsTime->GetYaxis()->SetTitle("k_{p}#zeta"); hDen1DvsTime->GetXaxis()->SetTitle("k_{p}z"); hDen1DvsTime->GetZaxis()->CenterTitle(); hDen1DvsTime->GetYaxis()->CenterTitle(); hDen1DvsTime->GetXaxis()->CenterTitle(); hDen1DvsTime->SetName(hName); // Change the range of z axis Float_t Denmax = hDen1DvsTime->GetMaximum(); hDen1DvsTime->GetZaxis()->SetRangeUser(0,Denmax); hDen1DvsTime->Write(hName,TObject::kOverwrite); } // RMS (vs z) of the beam's charge distribution: TProfile *hDen2Dprof = NULL; TH1F *hRms = NULL; Double_t axisPos = x2Mid; if(hDen2D) { TString pname = hDen2D->GetName(); pname += "_pfx"; hDen2Dprof = (TProfile*) gROOT->FindObject(pname.Data()); if(hDen2Dprof) { delete hDen2Dprof; hDen2Dprof = NULL; } hDen2Dprof = hDen2D->ProfileX("_pfx",1,-1,"s"); hRms = (TH1F*) gROOT->FindObject("hRms"); if(hRms) delete hRms; hRms = new TH1F("hRms","",x1Nbin,x1Min,x1Max); if(CYL) axisPos = 0.0; for(Int_t j=0;j<hRms->GetNbinsX();j++) { Double_t rms = 0; Double_t total = 0; for(Int_t k=1;k<=x2Nbin;k++) { Double_t value = hDen2D->GetBinContent(j,k); Double_t radius = hDen2D->GetYaxis()->GetBinCenter(k) - axisPos; if(CYL) { rms += radius*radius*radius*value; total += radius*value; } else { rms += radius*radius*value; total += value; } // cout << Form(" (%i,%i) -> radius = %7.4f , density = %7.4f",j,k,radius,value) << endl; } rms /= total; rms = sqrt(rms); hRms->SetBinContent(j,rms); } hRms->GetXaxis()->SetTitle("k_{p}z"); if(opt.Contains("comov")) hRms->GetXaxis()->SetTitle("k_{p}#zeta"); hRms->GetYaxis()->SetTitle("k_{p}#LTr#GT_{rms}"); } // Transverse charge RMS vs \zeta vs time! _________________________________ TH2F *hRmsvsTime = NULL; if(hRms) { char hName[24]; sprintf(hName,"hRmsvsTime"); TH2F *hRmsvsTimeOld = (TH2F*) ifile->Get(hName); Int_t nBins = 1; Float_t edge0 = Time-0.5; Float_t edge1 = Time+0.5; if(hRmsvsTimeOld!=NULL) { nBins = hRmsvsTimeOld->GetNbinsX()+1; Float_t binwidth = (Time - hRmsvsTimeOld->GetXaxis()->GetBinCenter(1))/(nBins-1); edge0 = hRmsvsTimeOld->GetXaxis()->GetBinCenter(1) - binwidth/2.; edge1 = Time + binwidth/2.; } hRmsvsTime = new TH2F("temp","",nBins,edge0,edge1, hRms->GetNbinsX(), hRms->GetBinLowEdge(1), hRms->GetBinLowEdge(hRms->GetNbinsX()+1)); for(Int_t ix=1;ix<hRmsvsTime->GetNbinsX();ix++) { for(Int_t iy=1;iy<hRmsvsTime->GetNbinsY();iy++) { hRmsvsTime->SetBinContent(ix,iy,hRmsvsTimeOld->GetBinContent(ix,iy)); } } delete hRmsvsTimeOld; // Fill last bin with the newest values. for(Int_t iy=1;iy<=hRms->GetNbinsX();iy++) { hRmsvsTime->SetBinContent(nBins,iy,hRms->GetBinContent(iy)); } hRmsvsTime->GetZaxis()->SetTitle("#LTr#GT_{rms}"); hRmsvsTime->GetYaxis()->SetTitle("k_{p}#zeta"); hRmsvsTime->GetXaxis()->SetTitle("k_{p}z"); hRmsvsTime->GetZaxis()->CenterTitle(); hRmsvsTime->GetYaxis()->CenterTitle(); hRmsvsTime->GetXaxis()->CenterTitle(); hRmsvsTime->SetName(hName); // Change the range of z axis Float_t Rmsmax = hRmsvsTime->GetMaximum(); hRmsvsTime->GetZaxis()->SetRangeUser(0,Rmsmax); hRmsvsTime->Write(hName,TObject::kOverwrite); } // INTEGRATED Beam's Charge: // Total charge vs time : TGraph *gQvsTime = NULL; if(hDen2D) { Double_t Q = 0; for(Int_t i=1;i<=x1Nbin;i++) { for(Int_t j=1;j<=x2Nbin;j++) { Double_t value = hDen2D->GetBinContent(i,j); if(CYL) { Double_t radius = hDen2D->GetYaxis()->GetBinCenter(j); Q += radius * value; // cout << Form(" (%i,%i) -> radius = %7.4f , value = %7.4f",i,j,radius,value) << endl; } else { Q += value; } } } Double_t xbinsize = hDen2D->GetXaxis()->GetBinWidth(1); Double_t ybinsize = hDen2D->GetYaxis()->GetBinWidth(1); Q *= xbinsize * ybinsize; if(!CYL && !ThreeD) { Q *= TMath::Sqrt(2*TMath::Pi()) * rms0; } else if(CYL) { Q *= 2*TMath::Pi(); } if(opt.Contains("units")) { Double_t dV = skindepth * skindepth * skindepth; Q *= n0 * dV; Q *= (PConst::ElectronCharge/PUnits::picocoulomb); cout << Form(" Integrated charge = %8i pC", TMath::Nint(Q)) << endl; } else { cout << Form(" Integrated charge = %8.4f n0 * kp^-3",Q) << endl; } Int_t nPoints = 0; char gName[32]; sprintf(gName,"gQvsTime"); gQvsTime = (TGraph*) ifile->Get(gName); if(gQvsTime==NULL) { gQvsTime = new TGraph(); gQvsTime->SetName(gName); nPoints = 0; // Some cosmetics at creation time: gQvsTime->SetLineWidth(3); gQvsTime->SetLineColor(PGlobals::fieldLine); gQvsTime->SetMarkerStyle(20); gQvsTime->SetMarkerSize(0.4); gQvsTime->SetMarkerColor(PGlobals::fieldLine); gQvsTime->GetYaxis()->SetTitle("charge [n_{0}/k_{p}^{3}]"); gQvsTime->GetXaxis()->SetTitle("k_{p}z"); } else { nPoints = gQvsTime->GetN(); } gQvsTime->Set(nPoints+1); gQvsTime->SetPoint(nPoints,Time,Q); gQvsTime->Write(gName,TObject::kOverwrite); } // ------------------------------------------------------------------------------------ // Longitudinal phasespace Int_t gNbin = 100; // Float_t gMin = 80; // Float_t gMax = 120; Float_t gMin = 43.07 - 1.2; Float_t gMax = 43.07 + 1.2; TH2F *hGvsZ = NULL; if(pData->GetRawFileName(1)) { char hName[24]; sprintf(hName,"hGvsZ"); hGvsZ = (TH2F*) gROOT->FindObject(hName); if(hGvsZ) { delete hGvsZ; hGvsZ = NULL; } hGvsZ = new TH2F(hName,"",x1Nbin,x1Min,x1Max,gNbin,gMin,gMax); pData->GetH2Raw(pData->GetRawFileName(1)->c_str(),"x1","gamma",hGvsZ,opt); hGvsZ->GetXaxis()->CenterTitle(); hGvsZ->GetYaxis()->CenterTitle(); hGvsZ->GetZaxis()->CenterTitle(); hGvsZ->GetYaxis()->SetTitle("#gamma"); if(opt.Contains("comov")) { hGvsZ->GetXaxis()->SetTitle("k_{p}#zeta"); hGvsZ->GetZaxis()->SetTitle("dN/d#zetad#gamma [a.u.]"); } else { hGvsZ->GetXaxis()->SetTitle("k_{p}z"); hGvsZ->GetZaxis()->SetTitle("dN/dzd#gamma [a.u.]"); } } else { cout << Form("--> No RAW data file is present for species 1") << endl; } TH2F *hGvsTime = NULL; TProfile *hGvsZprof = NULL; TGraphErrors *gGvsZ = NULL; if(hGvsZ) { TString pname = hGvsZ->GetName(); pname += "_pfx"; hGvsZprof = (TProfile*) gROOT->FindObject(pname.Data()); if(hGvsZprof) delete hGvsZprof; hGvsZprof = hGvsZ->ProfileX("_pfx",1,-1,"s"); gGvsZ = (TGraphErrors*) gROOT->FindObject("gGvsZ"); if(gGvsZ) delete gGvsZ; Int_t Npoints = hGvsZprof->GetNbinsX(); Double_t *x = new Double_t[Npoints]; Double_t *y = new Double_t[Npoints]; Double_t *ex = new Double_t[Npoints]; Double_t *ey = new Double_t[Npoints]; for(Int_t j=0;j<Npoints;j++) { x[j] = hGvsZprof->GetBinCenter(j); y[j] = hGvsZprof->GetBinContent(j); ex[j] = 0; ey[j] = hGvsZprof->GetBinError(j); } gGvsZ = new TGraphErrors(Npoints,x,y,ex,ey); gGvsZ->SetName("gGvsZ"); // PGlobals::SetH1Style((TH1*)gGvsZ,1); PGlobals::SetGraphStyle(gGvsZ,1); if(opt.Contains("comov")) gGvsZ->GetXaxis()->SetTitle("k_{p}#zeta"); else gGvsZ->GetXaxis()->SetTitle("k_{p}z"); gGvsZ->GetYaxis()->SetTitle("#LT#gamma#GT [MeV]"); char hName[24]; sprintf(hName,"hGvsTime"); TH2F *hGvsTimeOld = (TH2F*) ifile->Get(hName); Int_t nBins = 1; Float_t edge0 = Time-0.5; Float_t edge1 = Time+0.5; if(hGvsTimeOld!=NULL) { nBins = hGvsTimeOld->GetNbinsX()+1; Float_t binwidth = (Time - hGvsTimeOld->GetXaxis()->GetBinCenter(1))/(nBins-1); edge0 = hGvsTimeOld->GetXaxis()->GetBinCenter(1) - binwidth/2.; edge1 = Time + binwidth/2.; } hGvsTime = new TH2F("temp","",nBins,edge0,edge1, hGvsZprof->GetNbinsX(), hGvsZprof->GetBinLowEdge(1), hGvsZprof->GetBinLowEdge(hGvsZprof->GetNbinsX()+1)); for(Int_t ix=1;ix<hGvsTime->GetNbinsX();ix++) { for(Int_t iy=1;iy<hGvsTime->GetNbinsY();iy++) { hGvsTime->SetBinContent(ix,iy,hGvsTimeOld->GetBinContent(ix,iy)); } } delete hGvsTimeOld; // Fill last bin with the newest values. for(Int_t iy=1;iy<=hGvsZprof->GetNbinsX();iy++) { hGvsTime->SetBinContent(nBins,iy,hGvsZprof->GetBinContent(iy)); } hGvsTime->GetZaxis()->SetTitle("#LT#gamma#GT"); hGvsTime->GetYaxis()->SetTitle("k_{p}#zeta"); hGvsTime->GetXaxis()->SetTitle("k_{p}z"); hGvsTime->GetZaxis()->CenterTitle(); hGvsTime->GetYaxis()->CenterTitle(); hGvsTime->GetXaxis()->CenterTitle(); hGvsTime->SetName(hName); // Change the range of z axis Float_t Gmax = hGvsTime->GetMaximum(); Float_t Gmin = hGvsTime->GetMinimum(); hGvsTime->GetZaxis()->SetRangeUser(Gmin,Gmax); hGvsTime->Write(hName,TObject::kOverwrite); } // --------------------------------------------------------------------------------- // EM fields on - axis : TString opth1 = opt; opth1 += "avg"; // Get electric fields const Int_t Nfields = 2; TH1F **hE1D = new TH1F*[Nfields]; for(Int_t i=0;i<Nfields;i++) { hE1D[i] = NULL; if(!pData->GetEfieldFileName(i)) continue; char nam[3]; sprintf(nam,"e%i",i+1); if(ThreeD) { if(i==0) hE1D[i] = pData->GetH1SliceZ3D(pData->GetEfieldFileName(i)->c_str(),nam,-1,Nbins,-1,Nbins,opth1.Data()); else hE1D[i] = pData->GetH1SliceZ3D(pData->GetEfieldFileName(i)->c_str(),nam,-Nbins,Nbins,-Nbins,Nbins,opth1.Data()); } else if(CYL) { // Cylindrical: The first bin with r>0 is actually the number 1 (not the 0). if(i==0) hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,1,Nbins,opth1.Data()); else hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,1,Nbins,opth1.Data()); } else { // 2D cartesian if(i==0) hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,-1,Nbins,opth1.Data()); else hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,-Nbins,Nbins,opth1.Data()); } char hName[24]; sprintf(hName,"hE_%i_%i",i,time); hE1D[i]->SetName(hName); if(opt.Contains("comov")) hE1D[i]->GetXaxis()->SetTitle("k_{p}#zeta"); else hE1D[i]->GetXaxis()->SetTitle("k_{p}z"); if(i==0) hE1D[i]->GetYaxis()->SetTitle("E_{z}/E_{0}"); else if(i==1) hE1D[i]->GetYaxis()->SetTitle("E_{y}/E_{0}"); else if(i==2) hE1D[i]->GetYaxis()->SetTitle("E_{x}/E_{0}"); hE1D[i]->GetYaxis()->CenterTitle(); hE1D[i]->GetXaxis()->CenterTitle(); } // Calculate wave positions: // ---------------------------------------------------------------- // Calculate the crossings and the extremes of the Electric fields Float_t Ecross[Nfields][100] = {{0.0}}; Float_t Eextr[Nfields][100] = {{0.0}}; Int_t Ncross[Nfields] = {0}; for(Int_t i=0;i<Nfields;i++) { Ncross[i] = 0; if(!hE1D[i]) continue; // Only smooths the focusing if flag activated.. if(i>0 && opt.Contains("smooth")) { // cout << " Smoothing fields on axis..." << endl; hE1D[i]->Smooth(10); } Float_t maxZeta = zStartBeam; if(opt.Contains("center")) maxZeta -= zStartBeam; for(Int_t ip=hE1D[i]->GetNbinsX();ip>1;ip--) { Float_t Z2 = hE1D[i]->GetBinCenter(ip-1); if(Z2 > maxZeta) continue; Float_t E1 = hE1D[i]->GetBinContent(ip); Float_t E2 = hE1D[i]->GetBinContent(ip-1); Float_t Z1 = hE1D[i]->GetBinCenter(ip); // cout << Form("Z1 = %6.4f Z2 = %6.4f E1 = %6.4f E2 = %6.4f", Z1, Z2, E1, E2) << endl; if(E1*E2 >= 0) { // No change of sign means we are in a side of the zero axis. if(fabs(E2)>fabs(Eextr[i][Ncross[i]])) { Eextr[i][Ncross[i]] = E2; } } if(E1*E2 < 0) { // change of sign means a crossing! // The next crossing has to be far enough from the previous one: Float_t zcross = -E1 * ( (Z2-Z1)/(E2-E1) ) + Z1; if(Ncross[i]>0 && fabs(Ecross[i][Ncross[i]-1]-zcross)<TMath::PiOver2() ) continue; // cout << " CROSS! " << endl; // add the point Ecross[i][Ncross[i]] = zcross; Ncross[i]++; } } cout << " -> Number of crossings for field " << i << " : " << Ncross[i] << endl; for(Int_t ic=0;ic<Ncross[i];ic++) { // cout << Form(" %2i: zeta = %6.4f E = %6.4f", ic, Ecross[i][ic], Eextr[i][ic]) << endl; } hE1D[i]->SetLineColor(kRed); hE1D[i]->Write(hE1D[i]->GetName(),TObject::kOverwrite); } // Get the Graphs and histos from file Int_t nPoints = 0; TGraph ***gEcross = new TGraph**[Nfields]; TGraph ***gEextr = new TGraph**[Nfields]; TH2F **hEvsTime = new TH2F*[Nfields]; for(Int_t i=0;i<Nfields;i++) { char hName[24]; sprintf(hName,"hEvsTime_%i",i); TH2F *hEvsTimeOld = (TH2F*) ifile->Get(hName); Int_t nBins = 1; Float_t edge0 = Time-0.5; Float_t edge1 = Time+0.5; if(hEvsTimeOld!=NULL) { nBins = hEvsTimeOld->GetNbinsX()+1; Float_t binwidth = (Time - hEvsTimeOld->GetXaxis()->GetBinCenter(1))/(nBins-1); edge0 = hEvsTimeOld->GetXaxis()->GetBinCenter(1) - binwidth/2.; edge1 = Time + binwidth/2.; } hEvsTime[i] = new TH2F("temp","",nBins,edge0,edge1, hE1D[i]->GetNbinsX(), hE1D[i]->GetBinLowEdge(1), hE1D[i]->GetBinLowEdge(hE1D[i]->GetNbinsX()+1)); for(Int_t ix=1;ix<hEvsTime[i]->GetNbinsX();ix++) { for(Int_t iy=1;iy<hEvsTime[i]->GetNbinsY();iy++) { hEvsTime[i]->SetBinContent(ix,iy,hEvsTimeOld->GetBinContent(ix,iy)); } } delete hEvsTimeOld; // Fill last bin with the newest values. for(Int_t iy=1;iy<=hE1D[i]->GetNbinsX();iy++) { hEvsTime[i]->SetBinContent(nBins,iy,hE1D[i]->GetBinContent(iy)); } if(i==0) hEvsTime[i]->GetZaxis()->SetTitle("E_{z}/E_{0}"); else if(i==1) hEvsTime[i]->GetZaxis()->SetTitle("E_{y}/E_{0}"); else if(i==2) hEvsTime[i]->GetZaxis()->SetTitle("E_{x}/E_{0}"); hEvsTime[i]->GetYaxis()->SetTitle("k_{p}#zeta"); hEvsTime[i]->GetXaxis()->SetTitle("k_{p}z"); hEvsTime[i]->GetZaxis()->CenterTitle(); hEvsTime[i]->GetYaxis()->CenterTitle(); hEvsTime[i]->GetXaxis()->CenterTitle(); hEvsTime[i]->SetName(hName); // Change the range of z axis for the fields to be symmetric. Float_t Emax = hEvsTime[i]->GetMaximum(); Float_t Emin = hEvsTime[i]->GetMinimum(); if(Emax > TMath::Abs(Emin)) Emin = -Emax; else Emax = -Emin; hEvsTime[i]->GetZaxis()->SetRangeUser(Emin,Emax); hEvsTime[i]->Write(hName,TObject::kOverwrite); // --- gEcross[i] = new TGraph*[Ncross[i]]; gEextr[i] = new TGraph*[Ncross[i]]; char gName[24]; Int_t ifail = 0; for(Int_t ic=0;ic<Ncross[i];ic++) { sprintf(gName,"gEcross_%i_%i",i,ic); gEcross[i][ic] = (TGraph*) ifile->Get(gName); if(gEcross[i][ic]==NULL) { gEcross[i][ic] = new TGraph(); gEcross[i][ic]->SetName(gName); nPoints = 0; // Some cosmetics at creation time: if(i==1) gEcross[i][ic]->SetLineStyle(2); else gEcross[i][ic]->SetLineStyle(1); gEcross[i][ic]->SetLineWidth(1); gEcross[i][ic]->SetLineColor(kGray+1); gEcross[i][ic]->SetMarkerStyle(20); gEcross[i][ic]->SetMarkerSize(0.4); gEcross[i][ic]->SetMarkerColor(kGray+1); gEcross[i][ic]->GetYaxis()->SetTitle("k_{p}#zeta]"); gEcross[i][ic]->GetXaxis()->SetTitle("k_{p}z"); } else { nPoints = gEcross[i][ic]->GetN(); } // Check the new crossings respect the previous ones: // Double_t t,zeta; // if(nPoints>0) { // gEcross[i][ic]->GetPoint(nPoints-1,t,zeta); // if(fabs(zeta-Ecross[i][ic+ifail])>TMath::Pi()) { // ic--; // ifail++; // continue; // } // } gEcross[i][ic]->Set(nPoints+1); gEcross[i][ic]->SetPoint(nPoints,Time,Ecross[i][ic+ifail]); gEcross[i][ic]->Write(gName,TObject::kOverwrite); // if(ic==Ncross[i]-1) continue; sprintf(gName,"gEextr_%i_%i",i,ic); gEextr[i][ic] = (TGraph*) ifile->Get(gName); if(gEextr[i][ic]==NULL) { gEextr[i][ic] = new TGraph(); gEextr[i][ic]->SetName(gName); nPoints = 0; // Some cosmetics at creation time: if(i==0) { gEextr[i][ic]->SetLineWidth(3); gEextr[i][ic]->SetLineColor(PGlobals::fieldLine); gEextr[i][ic]->SetMarkerStyle(20); gEextr[i][ic]->SetMarkerSize(0.4); gEextr[i][ic]->SetMarkerColor(PGlobals::fieldLine); gEextr[i][ic]->GetYaxis()->SetTitle("E_{z}/E_{0}"); gEextr[i][ic]->GetXaxis()->SetTitle("k_{p}z"); } else if(i==1) { gEextr[i][ic]->SetLineWidth(1); gEextr[i][ic]->SetLineColor(kGray+2); gEextr[i][ic]->SetMarkerStyle(20); gEextr[i][ic]->SetMarkerSize(0.4); gEextr[i][ic]->SetMarkerColor(kGray+2); gEextr[i][ic]->GetYaxis()->SetTitle("E_{y}/E_{0}"); gEextr[i][ic]->GetXaxis()->SetTitle("k_{p}z"); } } else { nPoints = gEextr[i][ic]->GetN(); } gEextr[i][ic]->Set(nPoints+1); gEextr[i][ic]->SetPoint(nPoints,Time,Eextr[i][ic]); gEextr[i][ic]->Write(gName,TObject::kOverwrite); } } ifile->Close(); }
void makeFitPlotSFJVF() { gROOT->SetBatch(); gROOT->SetStyle("Plain"); gStyle->SetOptStat(0); gROOT->ProcessLine(".x def.C"); gROOT->ProcessLine(".x common.C"); bool doSubPlot = 0; std::string sel = "MV160"; std::string var = "Sd0t1"; const int nf = 2; std::string fv[nf] = {"","_JVF0"}; double sf[100][100]; double sferr[100][100]; double sfX[100]; double sfXerr[100]; TCanvas *c1 = new TCanvas("c1","c1",0,0,600,500); c1->Draw(); c1->cd(); TPad *c1_1; if( doSubPlot ) { c1->Range(0,0,1,1); c1_1 = new TPad("c1_1","main",0.01,0.30,0.99,0.99); c1_1->Draw(); c1_1->cd(); } gStyle->SetHistTopMargin(0); TLegend *leg = new TLegend(0.70,0.90,0.90,0.70); leg->SetFillColor(253); leg->SetBorderSize(0); int nbins = 0; int im = 0; TH1F *hc; TH1F *hsf[nf]; for(int f=0;f<nf;f++) { std::string fname = "results/sfoverlay/fit_EFF_beauty_"+var+"_"+sel+fv[f]+".root"; TFile *file = new TFile(fname.c_str()); TH1F *h = (TH1F*)file->Get("h1c"); nbins = h->GetXaxis()->GetNbins(); for(int ib=1;ib<nbins+1;ib++) { double cont = h->GetBinContent(ib); double err = h->GetBinError(ib); sfXerr[ib-1] = h->GetBinWidth(ib)/2.0; sfX[ib-1] = h->GetBinLowEdge(ib) + sfXerr[ib-1]; sf[ib-1][im] = cont; sferr[ib-1][im] = err; } if( f == 0 ) {h->SetMarkerStyle(20);h->SetMarkerColor(kRed);h->SetLineColor(kRed);} if( f == 1 ) {h->SetMarkerStyle(25);h->SetMarkerColor(kBlack);h->SetLineColor(kBlack);} if( f == 2 ) {h->SetMarkerStyle(22);h->SetMarkerColor(kBlue);h->SetLineColor(kBlue);} if( f == 3 ) {h->SetMarkerStyle(23);h->SetMarkerColor(kMagenta);h->SetLineColor(kMagenta);} std::string tit = ""; if( f == 0 ) tit = "JVF > 0.5"; if( f == 1 ) tit = "JVF > 0"; if( f == 2 ) tit = "S_{d_{0}}(t_{3})"; if( f == 3 ) tit = "S_{d_{0}}(#mu)"; leg->AddEntry(h,tit.c_str(),"lep"); if( f == 0 ) h->Draw("e1"); else h->Draw("e1 same"); ATLASLabel(0.20,0.85,"Internal",1); h->GetYaxis()->SetRangeUser(0.3,1.6); h->GetXaxis()->SetRangeUser(0.0,0.04); im++; std::string hname = "hsf"+std::string(Form("%d",f)); hsf[f] = (TH1F*)h->Clone(hname.c_str()); } leg->Draw(); gPad->RedrawAxis("g"); /* if( doSubPlot ) { std::string foutStr = "results/fit_EFF_beauty_SFOVERLAY_"+sel+".root"; TFile *fout = new TFile(foutStr.c_str(),"RECREATE"); int inb = hsf[0]->GetXaxis()->GetNbins(); const int nb = inb; double av[nb]; double errSum[nb]; double absv[nb]; for(int ib=1;ib<=nb;ib++) { av[ib-1] = 0.; absv[ib-1] = 0.; errSum[ib-1] = 0.; } for(int ih=0;ih<nf;ih++) { for(int ib=1;ib<=nb;ib++) { double err = hsf[ih]->GetBinError(ib); // av[ib-1] += (err > 0) ? hsf[ih]->GetBinContent(ib)/pow(err,2) : 0.; av[ib-1] += hsf[ih]->GetBinContent(ib)/float(nf); errSum[ib-1] += (err > 0) ? 1./pow(err,2) : 0.; } } for(int ih=0;ih<nf;ih++) { for(int ib=1;ib<=nb;ib++) { double err = hsf[ih]->GetBinError(ib); absv[ib-1] += pow(err,2); } } for(int ib=1;ib<=nb;ib++) { // av[ib-1] /= errSum[ib-1]; } for(int ib=1;ib<=nb;ib++) { absv[ib-1] = sqrt(absv[ib-1])/float(nf); // absv[ib-1] = 1./sqrt(errSum[ib-1]); std::cout << av[ib-1] << " +- " << absv[ib-1] << std::endl; } c1->cd(); TPad *c1_2 = new TPad("c1_2", "ratio",0.01,0.01,0.99,0.37); c1_2->Draw(); c1_2->cd(); c1_2->SetBottomMargin(0.37); c1_2->SetGrid(0,1); TH1F *h1c = (TH1F*)hsf[0]->Clone("h1c"); for(int ib=1;ib<=nb;ib++) { h1c->SetBinContent(ib,av[ib-1]); h1c->SetBinError(ib,absv[ib-1]); } h1c->SetMarkerStyle(20); h1c->SetMarkerSize(0.8); h1c->GetYaxis()->SetNdivisions(5); h1c->GetYaxis()->SetTitle("Data/MC"); h1c->GetYaxis()->SetTitleSize((h1c->GetYaxis()->GetTitleSize())*2); h1c->GetYaxis()->SetTitleOffset(h1c->GetYaxis()->GetTitleOffset()/2); h1c->GetXaxis()->SetTitleSize((h1c->GetXaxis()->GetTitleSize())*2); h1c->GetXaxis()->SetTitleOffset(h1c->GetXaxis()->GetTitleOffset()+0.2); h1c->GetYaxis()->SetLabelSize((h1c->GetYaxis()->GetLabelSize())*2); h1c->GetXaxis()->SetLabelSize((h1c->GetXaxis()->GetLabelSize())*2); h1c->GetXaxis()->SetTitle(h1c->GetXaxis()->GetTitle()); h1c->SetLineColor(kBlack); h1c->SetMarkerColor(kBlack); h1c->Draw("e1"); h1c->GetYaxis()->SetRangeUser(0.5,1.5); c1->Update(); for(int ih=0;ih<nf;ih++) { hsf[ih]->Write(); } fout->Write(); fout->Close(); }*/ std::string fsave = "pics/fit_SFJVF_"+sel+".eps"; c1->Print(fsave.c_str()); gApplication->Terminate(); }
void Draw(TCanvas *c1, const int &rebin=1, const bool &showErr=true) { gStyle->SetOptStat(0); c1->cd(); c1->Clear(); TPad *pad1; pad1 = new TPad("pad1","pad1",0,1-0.614609572,1,1); pad1->SetTopMargin(0.0983606557); pad1->SetBottomMargin(0.025); pad1->Draw(); pad1->cd(); RebinHists(rebin); THStack *hstack = GetStack(c1->GetLogy()); TH1F *signal = GetSignalHist(); TH1F *data = GetDataHist(); if(c1->GetLogy()) gPad->SetLogy(); hstack->GetHistogram()->SetLabelSize(0.00,"X"); hstack->GetHistogram()->SetLabelSize(0.06,"Y"); hstack->GetHistogram()->SetTitleSize(0.06,"XY"); hstack->Draw("hist"); if(signal && ! _stackSignal) signal->Draw("hist,same"); if(data) data->Draw("ep,same"); DrawLabels(); pad1->GetFrame()->DrawClone(); TH1F *summed = GetSummedMCHist(); TH1F *rdat = (TH1F*)data->Clone("rdat"); if(gROOT->FindObject("rref")) gROOT->FindObject("rref")->Delete(); TH1F *rref = new TH1F("rref","rref", summed->GetNbinsX(), summed->GetBinLowEdge(1), summed->GetBinLowEdge(summed->GetNbinsX()+1) ); for (int i = 1, n = rref->GetNbinsX(); i <= n+1; ++i) { rref->SetBinContent(i,summed->GetBinContent(i)); rref->SetBinError(i,summed->GetBinError(i)); } rref->SetTitle(""); rref->SetLineWidth(0); rref->SetFillColor(kGray+1); rref->SetFillStyle(1001); double absmax = 0; for (int i = 0, n = rdat->GetNbinsX(); i <= n+1; ++i) { double scale = rref->GetBinContent(i); if (scale == 0) { rdat->SetBinContent(i, 0); rref->SetBinContent(i, 10000); rdat->SetBinError(i, 0); rref->SetBinError(i, 0); } else { rdat->SetBinContent(i, rdat->GetBinContent(i)/scale); rref->SetBinContent(i, rref->GetBinContent(i)/scale); rdat->SetBinError(i, rdat->GetBinError(i)/scale); rref->SetBinError(i, rref->GetBinError(i)/scale); double mymax = TMath::Max(1.2*fabs(rdat->GetBinContent(i)-1)+1.4*rdat->GetBinError(i), 2.0*rref->GetBinError(i)); absmax = TMath::Max(mymax, absmax); } } c1->cd(); TPad *pad2 = new TPad("pad2","pad2",0,0,1,1-0.614609572); pad2->SetTopMargin(0.0261437908); pad2->SetBottomMargin(0.392156863); pad2->Draw(); pad2->cd(); TLine *line = new TLine(rref->GetXaxis()->GetXmin(), 1.0, rref->GetXaxis()->GetXmax(), 1.0); line->SetLineColor(kBlack); line->SetLineWidth(1); line->SetLineStyle(1); if(showErr) { rref->GetYaxis()->SetRangeUser(TMath::Max(-1.,1.-absmax), TMath::Min(3.,absmax+1.)); AxisFonts(rref->GetXaxis(), "x", hstack->GetXaxis()->GetTitle()); rref->GetYaxis()->SetTitle("data/mc"); rref->GetYaxis()->SetLabelSize(0.10); rref->GetYaxis()->SetTitleSize(0.10); rref->GetYaxis()->SetTitleOffset(0.85); rref->GetXaxis()->SetLabelSize(0.10); rref->GetXaxis()->SetTitleSize(0.10); rref->GetXaxis()->SetTitleOffset(1.5); rref->Draw("E2"); rdat->SetMarkerStyle(20); rdat->Draw("E SAME p"); line->Draw("SAME"); c1->Update(); pad2->GetFrame()->DrawClone(); } else { rdat->GetYaxis()->SetRangeUser(TMath::Max(-1.,1.-absmax), TMath::Min(3.,absmax+1.)); rdat->GetYaxis()->SetTitle("data/mc"); rdat->GetYaxis()->SetLabelSize(0.10); rdat->GetYaxis()->SetTitleSize(0.10); rdat->GetYaxis()->SetTitleOffset(0.85); AxisFonts(rdat->GetXaxis(), "x", hstack->GetXaxis()->GetTitle()); rdat->GetXaxis()->SetLabelSize(0.10); rdat->GetXaxis()->SetTitleSize(0.10); rdat->GetXaxis()->SetTitleOffset(1.5); rdat->SetTitle(""); rdat->SetMarkerStyle(20); rdat->Draw("E p"); line->Draw("SAME"); c1->Update(); pad2->GetFrame()->DrawClone(); } }
void fitPtOverMCJLST(int mass = 125, int LHCsqrts = 7, int whichtype = 1, bool correctErrors = false, /* string changeParName = "", */ bool showErrorPDFs = false, string systString = "Default") // whichtype // 0 - gg Signal // 1 - VBF Signal // 2 - ZZ // 3 - ZX // 4 - ggZZ // 5 - WH // 6 - ZH // 7 - ttH { string changeParName = ""; if (systString == "Default") changeParName = "up"; string nameSample[8] = {"gg","vbf","zz","zx","ggzz","wh","zh","tth"}; float maxType[8] = {2.4,3.2,1.6,1.6,1.6,3.2,3.2,3.2}; float rebinType[8] = {1,2,1,1,4,10,10,40}; for (int t = 0; t < 8; t++) { if (mass > 150) maxType[t] = int(117.90*maxType[t]/sqrt(mass-10.91))/10.; } char fileToOpen[200]; sprintf(fileToOpen,"selRootFiles/PToverM_%s%d_SEL_%dTeV.root",nameSample[whichtype].c_str(),mass,LHCsqrts); // if (whichtype == 3) sprintf(fileToOpen,"PTOVERM_%s_SEL_allTeV.root",nameSample[whichtype].c_str()); RooRealVar* ptoverm = new RooRealVar("ptoverm","p_{T}/M^{4l}",0.,maxType[whichtype],"GeV/c"); TFile input(fileToOpen); // if (systString == "Mass" || systString == "Mela") { // sprintf(fileToOpen,"ptovermH_%sUp",systString.c_str()); // } else { sprintf(fileToOpen,"ptovermH_%s",systString.c_str()); //} TH1F* ptovermH = (TH1F*)input.Get(fileToOpen); if (rebinType[whichtype] > 1) ptovermH->Rebin(rebinType[whichtype]); if (maxType[whichtype] < ptovermH->GetBinLowEdge(ptovermH->GetNbinsX() + 1) - ptovermH->GetBinWidth(1)) { int theBin = ptovermH->FindBin(maxType[whichtype]); ptovermH->GetXaxis()->SetRange(1,theBin-1); } gROOT->ProcessLine(".L mytdrstyle.C"); gROOT->ProcessLine("setTDRStyle()"); // cout << endl << "Signal " << endl; ptoverm->setBins(ptovermH->GetNbinsX()); RooDataHist* rdh = new RooDataHist("rdh","Some dataset",RooArgList(*ptoverm),Import(*ptovermH,kFALSE)); // fit definitions // RooWorkspace *ws = new RooWorkspace("ws"); RooRealVar m("m","emme", 1.,0.01, 40.); RooRealVar n("n","enne", 0.93, 0.05, 15.); RooRealVar n2("n2","enne2", 0.75, 0.5, 15.); RooRealVar bb("bb","bibi",0.02, 0.000005, 20.0); RooRealVar T("T","tti",0.2,0.00000005,1.); RooRealVar bb2("bb2","bibi2",0.02, 0.0005, 10.0); RooRealVar fexp("fexp","f_exp",0.02, 0.0, 1.0); if (whichtype == 0) { if (LHCsqrts == 8) { m.setVal(3.319); // m.setConstant(kTRUE); n.setVal(0.7606); if (systString != "Default" || mass != 125) n.setConstant(kTRUE); n2.setVal(0.8061); n2.setConstant(kTRUE); bb.setVal(3.728); // bb.setConstant(kTRUE); T.setVal(0.00333); // T.setConstant(kTRUE); bb2.setVal(1.7172); // bb2.setConstant(kTRUE); fexp.setVal(0.002144); if (systString != "Default" || mass != 125) fexp.setConstant(kTRUE); } else { m.setVal(0.061); // m.setConstant(kTRUE); n.setVal(1.6141); if (systString == "Resummation" || systString == "TopMass") n.setConstant(kTRUE); n2.setVal(1.3294); n2.setConstant(kTRUE); bb.setVal(4.2761); // bb.setConstant(kTRUE); T.setVal(0.0361); // T.setConstant(kTRUE); bb2.setVal(1.6643); bb2.setConstant(kTRUE); fexp.setVal(0.0004); // fexp.setConstant(kTRUE); } } else if (whichtype == 1) { m.setVal(1.006); // m.setConstant(kTRUE); n.setVal(10.939); n.setConstant(kTRUE); n2.setVal(1.1448); n2.setConstant(kTRUE); bb.setVal(0.02048); bb.setConstant(kTRUE); T.setVal(0.16115); if (systString.find("Mela") != string::npos) T.setConstant(kTRUE); // T.setConstant(kTRUE); bb2.setVal(1.0024); bb2.setConstant(kTRUE); fexp.setVal(0.005); fexp.setConstant(kTRUE); if (mass > 300) { fexp.setVal(0.0); fexp.setConstant(kFALSE); } if (mass > 500) { bb2.setVal(5.0); // bb2.setConstant(kFALSE); } if (mass > 500) { bb.setVal(15.0); // bb.setConstant(kFALSE); } } else if (whichtype == 2) { if (LHCsqrts == 8) { m.setVal(1.0476); // m.setConstant(kTRUE); bb.setVal(3.3088); // if (mass != 140) bb.setConstant(kTRUE); n2.setVal(0.7146); n2.setConstant(kTRUE); n.setVal(0.9518); n.setConstant(kTRUE); bb2.setVal(100000.); bb2.setConstant(kTRUE); T.setVal(0.0021889); if (systString.find("Mela") != string::npos || mass != 140) T.setConstant(kTRUE); fexp.setVal(0.0); fexp.setConstant(kTRUE); } else { m.setVal(1.028); // m.setConstant(kTRUE); bb.setVal(2.91); // bb.setConstant(kTRUE); n2.setVal(0.7146); n2.setConstant(kTRUE); n.setVal(0.9518); n.setConstant(kTRUE); bb2.setVal(100000.); bb2.setConstant(kTRUE); T.setVal(0.002248); if (systString.find("Mela") != string::npos) T.setConstant(kTRUE); fexp.setVal(0.0); fexp.setConstant(kTRUE); } } else if (whichtype == 3) { m.setVal(1.411); // m.setConstant(kTRUE); n.setVal(3.4523); n.setConstant(kTRUE); n2.setVal(0.6910); n2.setConstant(kTRUE); bb.setVal(0.00039); // bb.setConstant(kTRUE); T.setVal(0.118); // T.setConstant(kTRUE); bb2.setVal(0.0224); bb2.setConstant(kTRUE); fexp.setVal(0.0); fexp.setConstant(kTRUE); } else if (whichtype == 4) { m.setVal(1.411); // m.setConstant(kTRUE); n.setVal(5.756); // n.setConstant(kTRUE); n2.setVal(0.8738); // n2.setConstant(kTRUE); bb.setVal(0.00039); // bb.setConstant(kTRUE); T.setVal(0.118); // T.setConstant(kTRUE); bb2.setVal(0.0224); bb2.setConstant(kTRUE); fexp.setVal(0.0); fexp.setConstant(kTRUE); } else if (whichtype == 5 && LHCsqrts == 8) { m.setVal(1.006); // m.setConstant(kTRUE); n.setVal(10.939); n.setConstant(kTRUE); n2.setVal(1.1448); n2.setConstant(kTRUE); bb.setVal(3.897); bb.setConstant(kTRUE); T.setVal(0.1009); // T.setConstant(kTRUE); bb2.setVal(1.0224); bb2.setConstant(kTRUE); fexp.setVal(0.01); fexp.setConstant(kTRUE); } else { // cout << "Entro qui" << endl; m.setVal(1.006); // m.setConstant(kTRUE); n.setVal(10.939); n.setConstant(kTRUE); n2.setVal(1.1448); n2.setConstant(kTRUE); bb.setVal(0.0129); bb.setConstant(kTRUE); T.setVal(0.1009); // T.setConstant(kTRUE); bb2.setVal(1.0224); bb2.setConstant(kTRUE); fexp.setVal(0.01); fexp.setConstant(kTRUE); } RooModifTsallis* rt3 = new RooModifTsallis("rt3","rt3",*ptoverm,m,n,n2,bb,bb2,T,fexp); // ws->import(*rt3); // fit RooFitResult* fit = rt3->fitTo(*rdh,Minos(0),Save(1),SumW2Error(kTRUE),NumCPU(1)); float mVal = m.getVal(); float nVal = n.getVal(); float n2Val = n2.getVal(); float bbVal = bb.getVal(); float bb2Val = bb2.getVal(); float fexpVal = fexp.getVal(); float TVal = T.getVal(); if (correctErrors) { // Tsallis errors not reliable, use toy MC TH1F* mHist = new TH1F("mHist","m",21,-0.5*mVal,0.5*mVal); TH1F* nHist = new TH1F("nHist","n",21,-0.2*nVal,0.2*nVal); TH1F* n2Hist = new TH1F("n2Hist","n2",21,-0.2*n2Val,0.2*n2Val); TH1F* bbHist = new TH1F("bbHist","bb",21,-0.2*bbVal,0.2*bbVal); TH1F* bb2Hist = new TH1F("bb2Hist","bb2",21,-0.2*bb2Val,0.2*bb2Val); TH1F* fexpHist = new TH1F("fexpHist","fexp",21,-0.2*fexpVal-0.000001,0.2*fexpVal+0.000001); TH1F* THist = new TH1F("THist","T",21,-0.5*TVal,0.5*TVal); mHist->GetXaxis()->SetTitle("m-m_{gen}"); nHist->GetXaxis()->SetTitle("n-n_{gen}"); n2Hist->GetXaxis()->SetTitle("n2-n2_{gen}"); bbHist->GetXaxis()->SetTitle("bb-bb_{gen}"); bb2Hist->GetXaxis()->SetTitle("bb2-bb2_{gen}"); THist->GetXaxis()->SetTitle("T-T_{gen}"); fexpHist->GetXaxis()->SetTitle("fexp-fexp_{gen}"); for (unsigned int iToy = 0; iToy < 200; iToy++) { cout << endl << "####" << endl; cout << "Generating toy experiment n. " << iToy+1 << endl; m.setVal(mVal); n.setVal(nVal); n2.setVal(n2Val); bb.setVal(bbVal); bb2.setVal(bb2Val); fexp.setVal(fexpVal); T.setVal(TVal); TDatime *now = new TDatime(); Int_t seed = now->GetDate() + now->GetTime(); cout << "RooFit Generation Seed = " << seed+iToy << endl; RooRandom::randomGenerator()->SetSeed(seed+iToy); cout << "####" << endl << endl; RooDataSet *dataToy = rt3->generate(RooArgSet(*ptoverm),ptovermH->GetEntries()); RooDataHist *dataToyH = new RooDataHist("dataToyH","toy",RooArgSet(*ptoverm),*dataToy); rt3->fitTo(*dataToyH,Minos(0),SumW2Error(kTRUE),NumCPU(1)); if (fit->floatParsFinal().find("m")) mHist->Fill(m.getVal()-mVal); if (fit->floatParsFinal().find("n")) nHist->Fill(n.getVal()-nVal); if (fit->floatParsFinal().find("n2")) n2Hist->Fill(n2.getVal()-n2Val); if (fit->floatParsFinal().find("bb")) bbHist->Fill(bb.getVal()-bbVal); if (fit->floatParsFinal().find("bb2")) bb2Hist->Fill(bb2.getVal()-bb2Val); if (fit->floatParsFinal().find("fexp")) fexpHist->Fill(fexp.getVal()-fexpVal); if (fit->floatParsFinal().find("T")) THist->Fill(T.getVal()-TVal); } TCanvas cant("cant","Test canvas",5.,5.,900.,500.); cant.Divide(4,2); cant.cd(1); mHist->Draw(); cant.cd(2); nHist->Draw(); cant.cd(3); n2Hist->Draw(); cant.cd(4); bbHist->Draw(); cant.cd(5); bb2Hist->Draw(); cant.cd(6); fexpHist->Draw(); cant.cd(7); THist->Draw(); // cant.SaveAs("figs/testToys.pdf"); cant.SaveAs("newfigs/testToys.pdf"); if (fit->floatParsFinal().find("m")) m.setError(mHist->GetRMS()); if (fit->floatParsFinal().find("n")) n.setError(nHist->GetRMS()); if (fit->floatParsFinal().find("n2")) n2.setError(n2Hist->GetRMS()); if (fit->floatParsFinal().find("bb")) bb.setError(bbHist->GetRMS()); if (fit->floatParsFinal().find("bb2")) bb2.setError(bb2Hist->GetRMS()); if (fit->floatParsFinal().find("fexp")) fexp.setError(fexpHist->GetRMS()); if (fit->floatParsFinal().find("T")) T.setError(THist->GetRMS()); } m.setVal(mVal); n.setVal(nVal); n2.setVal(n2Val); bb.setVal(bbVal); bb2.setVal(bb2Val); fexp.setVal(fexpVal); T.setVal(TVal); char fileToSave[200]; // if (changeParName != "") // sprintf(fileToSave,"text/paramsPTOverMCJLST_%s_%dTeV_%s_%s.txt",nameSample[whichtype].c_str(),LHCsqrts,systString.c_str(),changeParName.c_str()); // else sprintf(fileToSave,"text/paramsPTOverMCJLST_%s%d_%dTeV_%s.txt",nameSample[whichtype].c_str(),mass,LHCsqrts,systString.c_str()); ofstream os1(fileToSave); if (changeParName != "") { sprintf(fileToSave,"m%s",changeParName.c_str()); m.SetName(fileToSave); sprintf(fileToSave,"n%s",changeParName.c_str()); n.SetName(fileToSave); sprintf(fileToSave,"n2%s",changeParName.c_str()); n2.SetName(fileToSave); sprintf(fileToSave,"bb%s",changeParName.c_str()); bb.SetName(fileToSave); sprintf(fileToSave,"bb2%s",changeParName.c_str()); bb2.SetName(fileToSave); sprintf(fileToSave,"fexp%s",changeParName.c_str()); fexp.SetName(fileToSave); sprintf(fileToSave,"T%s",changeParName.c_str()); T.SetName(fileToSave); } (RooArgSet(m,n,n2,bb,bb2,fexp,T)).writeToStream(os1,false); os1.close(); RooRealVar mup("mup","emme", 1.,0.01, 30.); RooRealVar nup("nup","enne", 0.93, 0.5, 15.); RooRealVar n2up("n2up","enne2", 0.75, 0.5, 15.); RooRealVar bbup("bbup","bibi",0.02, 0.00005, 20.0); RooRealVar Tup("Tup","tti",0.2,0.00000005,1.); RooRealVar bb2up("bb2up","bibi2",0.02, 0.0005, 10.0); RooRealVar fexpup("fexpup","f_exp",0.02, 0.0, 1.0); RooModifTsallis* rt3up = new RooModifTsallis("rt3up","rt3up",*ptoverm,mup,nup,n2up,bbup,bb2up,Tup,fexpup); // ws->import(*rt3up); RooRealVar mdown("mdown","emme", 1.,0.01, 30.); RooRealVar ndown("ndown","enne", 0.93, 0.5, 15.); RooRealVar n2down("n2down","enne2", 0.75, 0.5, 15.); RooRealVar bbdown("bbdown","bibi",0.02, 0.00005, 20.0); RooRealVar Tdown("Tdown","tti",0.2,0.00000005,1.); RooRealVar bb2down("bb2down","bibi2",0.02, 0.0005, 10.0); RooRealVar fexpdown("fexpdown","f_exp",0.02, 0.0, 1.0); RooModifTsallis* rt3down = new RooModifTsallis("rt3down","rt3down",*ptoverm,mdown,ndown,n2down,bbdown,bb2down,Tdown,fexpdown); // ws->import(*rt3down); RooPlot *frame = ptoverm->frame(); char reducestr[300]; sprintf(reducestr,"ptoverm > %f && ptoverm < %f",ptoverm->getMin(),ptoverm->getMax()); rdh->plotOn(frame,DataError(RooAbsData::SumW2),Cut(reducestr)); static RooHist *hpull; float chi2 = 0.; if (changeParName == "") { sprintf(fileToSave,"text/paramsPTOverMCJLST_%s%d_%dTeV_Default.txt",nameSample[whichtype].c_str(),mass,LHCsqrts); ifstream is1(fileToSave); (RooArgSet(mup,nup,n2up,bbup,bb2up,fexpup,Tup)).readFromStream(is1,false); mdown.setVal(fabs(3*mup.getVal() - 2*m.getVal())); ndown.setVal(fabs(3*nup.getVal() - 2*n.getVal())); n2down.setVal(fabs(3*n2up.getVal() - 2*n2.getVal())); bbdown.setVal(fabs(3*bbup.getVal() - 2*bb.getVal())); Tdown.setVal(fabs(3*Tup.getVal() - 2*T.getVal())); bb2down.setVal(fabs(3*bb2up.getVal() - 2*bb2.getVal())); fexpdown.setVal(fabs(3*fexpup.getVal() - 2*fexp.getVal())); if (showErrorPDFs) { rt3->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent)); hpull = frame->pullHist(); rt3up->plotOn(frame,LineColor(kBlue),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent)); if (systString.find("Mela") == string::npos) rt3down->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent)); } else { rt3->plotOn(frame,LineColor(kBlue),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent)); hpull = frame->pullHist(); } } else { mup.setVal(m.getVal() + m.getError()); cout << "mup = " << mup.getVal() << endl; nup.setVal(n.getVal() + n.getError()); n2up.setVal(n2.getVal() + n2.getError()); bbup.setVal(bb.getVal() + bb.getError()); Tup.setVal(T.getVal() + T.getError()); bb2up.setVal(bb2.getVal() + bb2.getError()); fexpup.setVal(fexp.getVal() + fexp.getError()); mdown.setVal(m.getVal() - m.getError()); cout << "mdown = " << mdown.getVal() << endl; ndown.setVal(n.getVal() - n.getError()); n2down.setVal(n2.getVal() - n2.getError()); bbdown.setVal(bb.getVal() - bb.getError()); Tdown.setVal(T.getVal() - T.getError()); bb2down.setVal(bb2.getVal() - bb2.getError()); fexpdown.setVal(fexp.getVal() - fexp.getError()); rt3->plotOn(frame,LineColor(kBlue),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent)); hpull = frame->pullHist(); if (showErrorPDFs) { rt3up->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent)); rt3down->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent)); } } double *ypulls = hpull->GetY(); unsigned int nBins = rdh->numEntries(); unsigned int nFullBins = 0; for (unsigned int i = 0; i < nBins; i++) { cout << "Pull of bin " << i << " = " << ypulls[i] << endl; if (fabs(ypulls[i]) < 5.0) chi2 += ypulls[i]*ypulls[i]; cout << "Partial chi2 = " << chi2 << endl; if (fabs(ypulls[i]) > 0.0001 && fabs(ypulls[i]) < 5.0) nFullBins++; } for (unsigned int i = 0; i < nBins; i++) { if (fabs(ypulls[i]) < 0.0001) ypulls[i] = 999.; hpull->SetPointError(i,0.,0.,0.,0.); } int nFitPar = fit->floatParsFinal().getSize() - 1; TCanvas can("can","The canvas",5.,5.,500.,900.); can.Divide(1,3); TLatex *t = new TLatex(); t->SetNDC(); t->SetTextAlign(22); t->SetTextSize(0.06); can.cd(1); gPad->SetBottomMargin(0.0); frame->Draw(); // gPad->SetLogy(); // Htest->Draw(); sprintf(fileToSave,"%s %d GeV at %d TeV",nameSample[whichtype].c_str(),mass,LHCsqrts); t->DrawLatex(0.6,0.8,fileToSave); can.cd(2); gPad->SetLogy(); gPad->SetTopMargin(0.0); frame->Draw(); RooPlot* pull = ptoverm->frame(Title("Pull Distribution")) ; pull->GetYaxis()->SetTitle("Pull"); /* pull->SetLabelSize(0.08,"XYZ"); pull->SetTitleSize(0.08,"XYZ"); pull->SetTitleOffset(0.6,"Y"); pull->SetTitleOffset(1.0,"X"); */ pull->addPlotable(hpull,"P") ; pull->SetMinimum(-6.); pull->SetMaximum(6.); can.cd(3); gPad->SetGridy(); pull->Draw(); sprintf(fileToSave,"#chi^{2}/n_{DoF} = %4.1f/%d",chi2,nFullBins - nFitPar); if (chi2 < 1000.) t->DrawLatex(0.80,0.86,fileToSave); // sprintf(fileToSave,"figs/fitPTOverMCJLST_%s%d_%dTeV_%s.pdf",nameSample[whichtype].c_str(),mass,LHCsqrts,systString.c_str()); sprintf(fileToSave,"newfigs/fitPTOverMCJLST_%s%d_%dTeV_%s.pdf",nameSample[whichtype].c_str(),mass,LHCsqrts,systString.c_str()); can.SaveAs(fileToSave); }
void AlignTopAndBottomTOFs(string ArrayPart="NV",Float_t Start=-5,Float_t End=25){ for (int bar=1;bar<13;bar++){ stringstream nameTop; stringstream nameBottom; nameTop<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"_TopCutTOFPr"; TH1F * CurrentTop = (TH1F*)gDirectory->Get(nameTop.str().c_str()); nameBottom<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"_BottomCutTOFPr"; TH1F * CurrentBottom = (TH1F*)gDirectory->Get(nameBottom.str().c_str()); // TCanvas *c=new TCanvas("c"); // c->cd(1); // CurrentTop->Draw(); // CurrentBottom->Draw("same"); int binsTop = CurrentTop->GetNbinsX(); int binsBottom= CurrentBottom->GetNbinsX(); if ( binsTop !=binsBottom){ cout<<"Nubmer of bins for the top channel not the same as for the bottom channel"<<endl; cout<<"This was for "<<CurrentTop->GetName()<<" and "<<CurrentBottom->GetName()<<endl; return; } int bins=binsTop; double topLow = CurrentTop->GetBinLowEdge(1);//ROOT histograms start at bin 1. bin 0 is underflow double topHigh= CurrentBottom->GetBinLowEdge(binsTop) +CurrentBottom->GetBinWidth(binsTop);//ROOT histograms end at bin N. N+1 is overflow bin. double NanoSecsPerBin = ((topHigh-topLow)*4)/binsTop; // cout<<topLow<<" "<<topHigh<<endl; // cout<<"NanoSecsPerBin "<<NanoSecsPerBin<<endl; int ForthOfBins = TMath::Floor(0.25* bins); int EighthOfBins = TMath::Floor( (1.0/8)* bins); int NumberOfShifts = 2*EighthOfBins; // 1/8 of the number of bins *2 for left/right shifts int TopZeroBin = CurrentTop->GetMaximumBin(); int StartBin = CurrentTop->FindBin(Start); int EndBin = CurrentTop->FindBin(End); //Find shift That moves Bottom -> Top vector <double> TheChi2s; vector <int> TheShifts; for (int i=0;i<NumberOfShifts;i++){ double binShift = (i - NumberOfShifts/2); double chi2=0; // cout<<"Looking in bin range "<<TopZeroBin-EighthOfBins<<" "<<TopZeroBin+EighthOfBins<<endl; // cout<<"That is from "<<CurrentTop->GetBinCenter(TopZeroBin-EighthOfBins)<<" "<<CurrentTop->GetBinCenter(TopZeroBin+EighthOfBins)<<endl; for (int bin=StartBin ;bin<EndBin;bin++){ double b = CurrentBottom->GetBinContent(bin + binShift); double t = CurrentTop->GetBinContent(bin); if (b !=0 && t!=0){ double temp =((b-t)*(b-t))/( TMath::Sqrt(t) ); chi2+=temp; } } TheChi2s.push_back(chi2); TheShifts.push_back(binShift); } ///Find miminum by linear search double min = 9999999999.0; int MinSpot=-1; for (int i=0;i<NumberOfShifts;i++){ if ( TheChi2s[i] < min){ min=TheChi2s[i]; MinSpot=i; } } cout<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"B "<<"1 0 "<<fixed<<setw(6)<<setprecision(4)<<TheShifts[MinSpot]/4.0*NanoSecsPerBin<<endl; cout<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"T "<<"1 0 0"<<endl; } cout<<"There were "<<NanoSecsPerBin<<" nano secs per bin"<<endl; // TGraph * graph = new TGraph(); // cout<<"Size of Chi2s "<<TheChi2s.size()<<endl; // cout<<"Num "<<NumberOfShifts<<endl; // for (int i=0;i<NumberOfShifts;i++){ // graph->SetPoint(i,TheShifts[i],TheChi2s[i]); // } // TCanvas *c2 = new TCanvas("c2"); // c2->cd(1); // graph->Draw("A*"); }
//............................................ // Constructor for accpetance from a ROOT Tfile SlicedAcceptance::SlicedAcceptance( string type, string fileName,string histName, bool fluctuate, bool quiet ) : slices(), nullSlice(new AcceptanceSlice(0.,0.,0.)), tlow(), thigh(), beta(), _sortedSlices(false), maxminset(false), t_min(0.), t_max(0.), _hasChecked(false), _storedDecision(false) { if(!quiet) cout << "Root file being used for acceptance" << endl; (void)type; if( type != "RootFile" ) { }//do nothing for now string fullFileName = StringProcessing::FindFileName( fileName, quiet ); if( !quiet ) cout << "Opening: " << fullFileName << endl; TFile* file = TFile::Open(TString(fullFileName)); if(!quiet) cout << "File " << fullFileName << " opened!" << endl; TH1F* histo = (TH1F*)file->Get(TString(histName)); if(!quiet) cout << "Histo " << histName << " opened!" << endl; histo->Draw(); if(!quiet) cout << "Histo " << histName << " drawn!" << endl; // histo->Sumw2(); if(fluctuate){ cout << "WARNING! You have fluctuated the acceptance." << endl; cout << "WARNING! This is for systematic studies only. " << endl; cout << "WARNING! Projections and pull fits will have a different fluctuated acceptance to the PDF you fit with." << endl; cout << "WARNING! ONLY USE FluctuateAcceptance:True FOR SYSTEMATIC STUDIES" << endl; TRandom3 * rng = new TRandom3(0); //Randomly fluctuate bin contents within error: for (int l = 1; l <= histo->GetNbinsX(); ++l){ if(!quiet) cout << "Bin content and error before: " << histo->GetBinContent(l) << "+/-" << histo->GetBinError(l); histo->SetBinContent(l,rng->Gaus(histo->GetBinContent(l),histo->GetBinError(l))); if(!quiet) cout << " and after: " << histo->GetBinContent(l) << "+/-" << histo->GetBinError(l) << endl; } delete rng; } histo->Scale(1./(histo->GetBinContent(histo->GetMaximumBin()))); histo->SetMinimum(0); double maxend = histo->GetBinLowEdge(histo->GetNbinsX()) + histo->GetBinWidth(histo->GetNbinsX()); double height; double start; double end = histo->GetBinLowEdge(histo->GetNbinsX()) + histo->GetBinWidth(histo->GetNbinsX()); double dheight; for (int l = 1; l <= histo->GetNbinsX(); ++l){ height = histo->GetBinContent(l); dheight = height; for (int n = l; n>0; n--){ if(histo->GetBinContent(n)<height){ dheight = height - histo->GetBinContent(n); cout << l << " " << n << " " << dheight << endl; break; } } start = histo->GetBinLowEdge(l); end = maxend; for (int m = l; m <= histo->GetNbinsX(); ++m){ double thisbinheight = histo->GetBinContent(m); if(thisbinheight<height){ end = histo->GetBinLowEdge(m); break; } } slices.push_back( new AcceptanceSlice( start, end, dheight ) ); if(!quiet) cout << start << " " << end << " " << dheight << endl; } histo->Delete(); // delete histo; file->Close(); delete file; if( !quiet ) cout << "Time Acc Slices: " << slices.size() << endl; if( slices.size() == 1 ) { cout << "SlicedAcceptance: SERIOUS ERROR" << endl; exit(0); } //....done..... _sortedSlices = this->isSorted(); if( _sortedSlices ) { if( !quiet ) cout << "Sliced Acceptance is using sorted horizontal slices" << endl; } else { if( !quiet ) cout << "Sliced Acceptance is NOT using sorted horizontal slices" << endl; } }
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- int main (int argc, char ** argv) { // check number of inpt parameters if(argc < 2){ cerr<<"Forgot to parse the cfg file --> exit "<<endl; return -1; } // Set Root style from global enviroment path string ROOTStyle; if(getenv ("ROOTStyle")!=NULL){ ROOTStyle = getenv ("ROOTStyle"); gROOT->ProcessLine((".x "+ROOTStyle+"/setTDRStyle.C").c_str()); } gStyle->SetOptStat(0); gStyle->SetPadTopMargin(0.09); gStyle->SetPadLeftMargin(0.13); gStyle->SetErrorX(0.5); // parse config file parameter if (gConfigParser) return 1 ; gConfigParser = new ConfigParser(); TString config ; config.Form("%s",argv[1]); if(!(gConfigParser->init(config))){ cout << ">>> parseConfigFile::Could not open configuration file " << config << endl; return -1; } // import base directory where samples are located and txt file with the directory name + other info string InputBaseDirectory = gConfigParser -> readStringOption("Input::InputBaseDirectory"); // import from cfg file the cross section value for this sample float CrossSection = gConfigParser -> readFloatOption("Input::CrossSection"); // total number of events int maxEventNumber = gConfigParser -> readFloatOption("Input::EventsNumber"); // treeName string treeName = gConfigParser -> readStringOption("Input::TreeName"); // take the cut list string InputCutList = gConfigParser -> readStringOption("Input::InputCutList"); // Read the cut file vector <cutContainer> CutList; if(ReadInputCutFile(InputCutList,CutList) <= 0){ cerr<<" Empty Cut List File or not Exisisting --> Exit "<<endl; return -1;} // take the variable list to be plotted string InputVariableList = gConfigParser -> readStringOption("Input::InputVariableList"); vector<variableContainer> variableList; if(ReadInputVariableFile(InputVariableList,variableList) <= 0 ){ cerr<<" Empty Variable List File or not Exisisting --> Exit "<<endl; return -1;} // take lumi and other parameters float lumi = gConfigParser -> readFloatOption("Option::Lumi"); // fb^(-1) lumi *= 1000. ; // transform into pb^(-1) finalStateString = gConfigParser -> readStringOption("Option::finalStateString"); matchingCone = gConfigParser -> readFloatOption("Option::matchingCone"); minLeptonCleaningPt = gConfigParser -> readFloatOption("Option::minLeptonCleaningPt"); minLeptonCutPt = gConfigParser -> readFloatOption("Option::minLeptonCutPt"); minJetCutPt = gConfigParser -> readFloatOption("Option::minJetCutPt"); usePuppiAsDefault = gConfigParser -> readBoolOption("Option::usePuppiAsDefault"); leptonIsoCut_mu = gConfigParser -> readFloatOption("Option::leptonIsoCutMu"); leptonIsoCut_el = gConfigParser -> readFloatOption("Option::leptonIsoCutEl"); leptonIsoCutLoose = gConfigParser -> readFloatOption("Option::leptonIsoCutLoose"); // output directory string outputPlotDirectory = gConfigParser -> readStringOption("Output::outputPlotDirectory"); system(("mkdir -p output/"+outputPlotDirectory).c_str()); system(("rm -r output/"+outputPlotDirectory+"/*").c_str()); system(("mkdir -p output/"+outputPlotDirectory+"/xs").c_str()); system(("mkdir -p output/"+outputPlotDirectory+"/norm").c_str()); ///// Start the analysis map<string,TH1F*> histoCutEff ; TChain* chain = new TChain (treeName.c_str()) ; chain->Add ((InputBaseDirectory+"/*.root").c_str()) ; int totEvent = chain->GetEntries(); readTree* reader = new readTree((TTree*)(chain)); cout<<"Lumi (fb-1) "<<lumi/1000<<" entries before "<<totEvent<<" cross section "<<CrossSection<<" Nevents before selections "<<lumi*CrossSection<<" weight "<<lumi*CrossSection/float(totEvent)<<endl; float weight = 1.0*lumi*CrossSection/float(totEvent) ; // make the plot container vector<histoContainer> plotVector; for(size_t iCut = 0; iCut < CutList.size(); iCut++){ histoCutEff["WW_EWK_pos_"+to_string(iCut)+"_"+CutList.at(iCut).cutLayerName] = new TH1F(("WW_EWK_pos_"+to_string(iCut)+"_"+CutList.at(iCut).cutLayerName).c_str(),"",15,0,15); for(size_t iVar = 0; iVar < variableList.size(); iVar++){ plotVector.push_back(histoContainer(CutList.at(iCut).cutLayerName,variableList.at(iVar))); } } int passingLHEFilter = 0 ; int maximumEvents = chain->GetEntries () ; if (maxEventNumber > 0 && maxEventNumber < maximumEvents) maximumEvents = maxEventNumber ; // Loop on the events for(int iEvent = 0; iEvent < maximumEvents ; iEvent++){ reader->fChain->GetEntry(iEvent) ; if (iEvent % 100000 == 0) cout << "reading event " << iEvent << "\n" ; // filter LHE level leptons if(TString(finalStateString).Contains("UU")){ if(fabs(reader->leptonLHEpid1) != 13 or fabs(reader->leptonLHEpid2) != 13) continue; } else if(TString(finalStateString).Contains("EE")){ if(fabs(reader->leptonLHEpid1) != 11 or fabs(reader->leptonLHEpid2) != 11) continue; } else if(TString(finalStateString).Contains("EU")){ if(fabs(reader->leptonLHEpid1) != 11 or fabs(reader->leptonLHEpid2) !=13) continue ; } else if(TString(finalStateString).Contains("UE")){ if(fabs(reader->leptonLHEpid1) != 13 or fabs(reader->leptonLHEpid2) !=11) continue ; } else{ cerr<<"problem with lhe level filter definition --> skip event"<<endl; continue; } passingLHEFilter++; // if an event pass the cut, fill the associated map leptonContainer lepton1,lepton2,parton1,parton2,neutrino1,neutrino2,vboson1,vboson2; lepton1.lepton4V_.SetPtEtaPhiM(reader->leptonLHEpt1,reader->leptonLHEeta1,reader->leptonLHEphi1,reader->leptonLHEm1); lepton1.charge_ = reader->leptonLHEch1; lepton1.flavour_ = reader->leptonLHEpid1; lepton2.lepton4V_.SetPtEtaPhiM(reader->leptonLHEpt2,reader->leptonLHEeta2,reader->leptonLHEphi2,reader->leptonLHEm2); lepton2.charge_ = reader->leptonLHEch2; lepton2.flavour_ = reader->leptonLHEpid2; parton1.lepton4V_.SetPtEtaPhiM(reader->jetLHEPartonpt1,reader->jetLHEPartoneta1,reader->jetLHEPartonphi1,0.); parton2.lepton4V_.SetPtEtaPhiM(reader->jetLHEPartonpt2,reader->jetLHEPartoneta2,reader->jetLHEPartonphi2,0.); neutrino1.lepton4V_.SetPtEtaPhiM(reader->neutrinoLHEpt1,reader->neutrinoLHEeta1,reader->neutrinoLHEphi1,0.); neutrino1.charge_ = 0.; neutrino1.flavour_ = reader->neutrinoLHEpid1; neutrino2.lepton4V_.SetPtEtaPhiM(reader->neutrinoLHEpt2,reader->neutrinoLHEeta2,reader->neutrinoLHEphi2,0.); neutrino2.charge_ = 0.; neutrino2.flavour_ = reader->neutrinoLHEpid2; vboson1.lepton4V_.SetPtEtaPhiM(reader->vbosonLHEpt1,reader->vbosonLHEeta1,reader->vbosonLHEphi1,reader->vbosonLHEm1); vboson1.charge_ = reader->vbosonLHEch1; vboson1.flavour_ = reader->vbosonLHEpid1; vboson2.lepton4V_.SetPtEtaPhiM(reader->vbosonLHEpt2,reader->vbosonLHEeta2,reader->vbosonLHEphi2,reader->vbosonLHEm2); vboson2.charge_ = reader->vbosonLHEch2; vboson2.flavour_ = reader->vbosonLHEpid2; float minDR_1 = 999; float minDR_2 = 999; vector<leptonContainer> lepton, neutrino; lepton.push_back(lepton1); lepton.push_back(lepton2); neutrino.push_back(neutrino1); neutrino.push_back(neutrino2); leptonContainer leptFromV1, leptFromV2, neuFromV1, neuFromV2; for(size_t iLep= 0; iLep < lepton.size(); iLep++){ for(size_t iNeu = 0; iNeu < neutrino.size(); iNeu++){ if((lepton.at(iLep).lepton4V_+neutrino.at(iNeu).lepton4V_).DeltaR(vboson1.lepton4V_) < minDR_1 ){ minDR_1 = (lepton.at(iLep).lepton4V_+neutrino.at(iNeu).lepton4V_).DeltaR(vboson1.lepton4V_); leptFromV1 = lepton.at(iLep); neuFromV1 = neutrino.at(iNeu); } if((lepton.at(iLep).lepton4V_+neutrino.at(iNeu).lepton4V_).DeltaR(vboson2.lepton4V_) < minDR_2){ minDR_2 = (lepton.at(iLep).lepton4V_+neutrino.at(iNeu).lepton4V_).DeltaR(vboson2.lepton4V_); leptFromV2 = lepton.at(iLep); neuFromV2 = neutrino.at(iNeu); } } } if(leptFromV1.lepton4V_ == leptFromV2.lepton4V_ or neuFromV1.lepton4V_ == neuFromV2.lepton4V_){ cerr<<" bad matching with gen W "<<endl; continue; } double costheta1 = 0; double costheta2 = 0; double Phi = 0; double costhetastar = 0; double Phi1 = 0; double costheta1_vbf = 0; double costheta2_vbf = 0; double Phi_vbf = 0; double costhetastar_vbf = 0; double Phi1_vbf = 0; TLorentzVector VV = vboson1.lepton4V_ + vboson2.lepton4V_; if(leptFromV1.charge_ > 0 and leptFromV2.charge_ > 0){ computeAnglesResonance(VV,vboson1.lepton4V_,neuFromV1.lepton4V_,leptFromV1.lepton4V_,vboson2.lepton4V_,neuFromV2.lepton4V_,leptFromV2.lepton4V_, costheta1,costheta2,Phi,costhetastar,Phi1); computeAnglesVBF(VV,vboson1.lepton4V_,neuFromV1.lepton4V_,leptFromV1.lepton4V_,vboson2.lepton4V_,neuFromV2.lepton4V_,leptFromV2.lepton4V_,parton1.lepton4V_, parton2.lepton4V_,costheta1_vbf,costheta2_vbf,Phi_vbf,costhetastar_vbf,Phi1_vbf); } else if(leptFromV1.charge_ < 0 and leptFromV2.charge_ < 0){ computeAnglesResonance(VV,vboson1.lepton4V_,leptFromV1.lepton4V_,neuFromV1.lepton4V_,vboson2.lepton4V_,leptFromV2.lepton4V_,neuFromV2.lepton4V_, costheta1,costheta2,Phi,costhetastar,Phi1); computeAnglesVBF(VV,vboson1.lepton4V_,leptFromV1.lepton4V_,neuFromV1.lepton4V_,vboson2.lepton4V_,leptFromV2.lepton4V_,neuFromV2.lepton4V_,parton1.lepton4V_, parton2.lepton4V_,costheta1_vbf,costheta2_vbf,Phi_vbf,costhetastar_vbf,Phi1_vbf); } else if(leptFromV1.charge_ < 0 and leptFromV2.charge_ > 0){ computeAnglesResonance(VV,vboson1.lepton4V_,leptFromV1.lepton4V_,neuFromV1.lepton4V_,vboson2.lepton4V_,neuFromV2.lepton4V_,leptFromV2.lepton4V_, costheta1,costheta2,Phi,costhetastar,Phi1); computeAnglesVBF(VV,vboson1.lepton4V_,leptFromV1.lepton4V_,neuFromV1.lepton4V_,vboson2.lepton4V_,neuFromV2.lepton4V_,leptFromV2.lepton4V_,parton1.lepton4V_, parton2.lepton4V_,costheta1_vbf,costheta2_vbf,Phi_vbf,costhetastar_vbf,Phi1_vbf); } else if(leptFromV1.charge_ > 0 and leptFromV2.charge_ < 0){ computeAnglesResonance(VV,vboson1.lepton4V_,neuFromV1.lepton4V_,leptFromV1.lepton4V_,vboson2.lepton4V_,leptFromV2.lepton4V_,neuFromV2.lepton4V_, costheta1,costheta2,Phi,costhetastar,Phi1); computeAnglesVBF(VV,vboson1.lepton4V_,neuFromV1.lepton4V_,leptFromV1.lepton4V_,vboson2.lepton4V_,leptFromV2.lepton4V_,neuFromV2.lepton4V_,parton1.lepton4V_, parton2.lepton4V_,costheta1_vbf,costheta2_vbf,Phi_vbf,costhetastar_vbf,Phi1_vbf); } else{ cerr<<" wrong charge composition "<<endl; continue; } float mTR = 0; float mR = 0; TLorentzVector L_met ,L_dijet, L_dilepton, L_LLmet; L_met = neutrino1.lepton4V_ + neutrino2.lepton4V_; L_dijet = parton1.lepton4V_ + parton2.lepton4V_; L_dilepton = lepton1.lepton4V_ + lepton2.lepton4V_; L_LLmet = L_dilepton + L_met ; computeRazor(lepton1.lepton4V_,lepton2.lepton4V_,L_met,mTR,mR); if(lepton1.lepton4V_.Pt() < minLeptonCutPt or lepton2.lepton4V_.Pt() < minLeptonCutPt) continue; // Loop on the cut list --> one cut for each polarization for(size_t iCut = 0; iCut < CutList.size(); iCut++){ // cut the events string name = "WW_EWK"; if(!passCutContainerSelection(reader, CutList.at(iCut), name, int(iCut), usePuppiAsDefault, minLeptonCutPt, minLeptonCleaningPt, leptonIsoCut_mu, leptonIsoCut_el, leptonIsoCutLoose, matchingCone, minJetCutPt, histoCutEff, finalStateString)) continue; float asimL = (lepton1.lepton4V_.Pt()-lepton2.lepton4V_.Pt())/(lepton1.lepton4V_.Pt()+lepton2.lepton4V_.Pt()) ; float asimJ = (parton1.lepton4V_.Pt()-parton2.lepton4V_.Pt())/(parton1.lepton4V_.Pt()+parton2.lepton4V_.Pt()) ; float Rvar = (lepton1.lepton4V_.Pt()*lepton2.lepton4V_.Pt())/(parton1.lepton4V_.Pt()*parton2.lepton4V_.Pt()) ; // loop on variables for(size_t iVar = 0; iVar < variableList.size(); iVar++){ histoContainer tmpPlot; tmpPlot.cutName = CutList.at(iCut).cutLayerName; tmpPlot.varName = variableList.at(iVar).variableName; vector<histoContainer>::iterator itVec ; itVec = find(plotVector.begin(),plotVector.end(),tmpPlot); if(itVec == plotVector.end()){ cerr<<"Problem -->plot not found for "<<CutList.at(iCut).cutLayerName<<" "<<variableList.at(iVar).variableName<<endl; continue ; } // vector boson info if(variableList.at(iVar).variableName == "ptV1"){ itVec->histogram->Fill(vboson1.lepton4V_.Pt(),1.*weight) ; } else if(variableList.at(iVar).variableName == "ptV2"){ itVec->histogram->Fill(vboson2.lepton4V_.Pt(),weight) ; } else if(variableList.at(iVar).variableName == "etaV1"){ itVec->histogram->Fill(vboson1.lepton4V_.Eta(),weight) ; } else if(variableList.at(iVar).variableName == "etaV2"){ itVec->histogram->Fill(vboson2.lepton4V_.Eta(),weight) ; } else if(variableList.at(iVar).variableName == "ptVV"){ itVec->histogram->Fill(L_dijet.Pt(),weight) ; } else if(variableList.at(iVar).variableName == "mVV"){ itVec->histogram->Fill(L_dijet.M(),weight) ; } // decay information if(variableList.at(iVar).variableName == "costheta1"){ itVec->histogram->Fill(fabs(costheta1),1.*weight) ; } else if(variableList.at(iVar).variableName == "costheta2"){ itVec->histogram->Fill(fabs(costheta2),weight) ; } if(variableList.at(iVar).variableName == "costheta1_vbf"){ itVec->histogram->Fill(fabs(costheta1_vbf),1.*weight) ; } else if(variableList.at(iVar).variableName == "costheta2_vbf"){ itVec->histogram->Fill(fabs(costheta2_vbf),weight) ; } if(variableList.at(iVar).variableName == "Phi"){ itVec->histogram->Fill(fabs(Phi),1.*weight) ; } else if(variableList.at(iVar).variableName == "Phi1"){ itVec->histogram->Fill(fabs(Phi1),weight) ; } if(variableList.at(iVar).variableName == "Phi_vbf"){ itVec->histogram->Fill(fabs(Phi_vbf),1.*weight) ; } else if(variableList.at(iVar).variableName == "Phi1_vbf"){ itVec->histogram->Fill(fabs(Phi1_vbf),weight) ; } else if(variableList.at(iVar).variableName == "costhetastar"){ itVec->histogram->Fill(fabs(costhetastar),weight) ; } else if(variableList.at(iVar).variableName == "costhetastar_vbf"){ itVec->histogram->Fill(fabs(costhetastar_vbf),weight) ; } else if(variableList.at(iVar).variableName == "mTR"){ itVec->histogram->Fill(mTR,weight) ; } else if(variableList.at(iVar).variableName == "mR"){ itVec->histogram->Fill(mR,weight) ; } // jet info if(variableList.at(iVar).variableName == "ptj1"){ itVec->histogram->Fill(parton1.lepton4V_.Pt(),1.*weight) ; } else if(variableList.at(iVar).variableName == "ptj2"){ itVec->histogram->Fill(parton2.lepton4V_.Pt(),weight) ; } else if(variableList.at(iVar).variableName == "etaj1"){ itVec->histogram->Fill(parton1.lepton4V_.Eta(),weight) ; } else if(variableList.at(iVar).variableName == "etaj2"){ itVec->histogram->Fill(parton2.lepton4V_.Eta(),weight) ; } else if(variableList.at(iVar).variableName == "detajj"){ itVec->histogram->Fill(fabs(parton1.lepton4V_.Eta()-parton2.lepton4V_.Eta()),weight) ; } else if(variableList.at(iVar).variableName == "ptjj"){ itVec->histogram->Fill(L_dijet.Pt(),weight) ; } else if(variableList.at(iVar).variableName == "mjj"){ itVec->histogram->Fill(L_dijet.M(),weight) ; } else if(variableList.at(iVar).variableName == "Asim_j"){ itVec->histogram->Fill(asimJ,weight) ; } else if(variableList.at(iVar).variableName == "DeltaPhi_JJ"){ itVec->histogram->Fill(fabs(parton1.lepton4V_.DeltaPhi(parton2.lepton4V_)),weight) ; } else if(variableList.at(iVar).variableName == "ptl1"){ itVec->histogram->Fill(lepton1.lepton4V_.Pt(),weight) ; } else if(variableList.at(iVar).variableName == "ptl2"){ itVec->histogram->Fill(lepton2.lepton4V_.Pt(),weight) ; } else if(variableList.at(iVar).variableName == "etal1"){ itVec->histogram->Fill(lepton1.lepton4V_.Eta(),weight) ; } else if(variableList.at(iVar).variableName == "etal2"){ itVec->histogram->Fill(lepton2.lepton4V_.Eta(),weight) ; } else if(variableList.at(iVar).variableName == "mll"){ itVec->histogram->Fill(L_dilepton.M(),weight) ; } else if(variableList.at(iVar).variableName == "ptll"){ itVec->histogram->Fill(L_dilepton.Pt(),weight) ; } else if(variableList.at(iVar).variableName == "DeltaPhi_LL"){ itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(lepton2.lepton4V_)),weight) ; } else if(variableList.at(iVar).variableName == "Asim_l"){ itVec->histogram->Fill(asimL,weight) ; } else if(variableList.at(iVar).variableName == "met"){ itVec->histogram->Fill(L_met.Pt(),weight) ; } else if(variableList.at(iVar).variableName == "R"){ itVec->histogram->Fill(Rvar,weight) ; } else if(variableList.at(iVar).variableName == "DeltaPhi_LMet"){ itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(L_met)),weight) ; } else if(variableList.at(iVar).variableName == "ptLMet"){ itVec->histogram->Fill((lepton1.lepton4V_ + L_met).Pt(),weight) ; } else if(variableList.at(iVar).variableName == "DeltaPhi_TLMet"){ itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(L_met)),weight) ; } else if(variableList.at(iVar).variableName == "ptTLMet"){ itVec->histogram->Fill((lepton2.lepton4V_ + L_met).Pt(),weight) ; } else if(variableList.at(iVar).variableName == "DeltaPhi_LLMet"){ itVec->histogram->Fill(fabs(L_dilepton.DeltaPhi(L_met)),weight) ; } else if(variableList.at(iVar).variableName == "ptLLMet"){ itVec->histogram->Fill((L_dilepton + L_met).Pt(),weight) ; } /// else if(variableList.at(iVar).variableName == "DeltaPhi_LJL"){ itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(parton1.lepton4V_)),weight) ; } else if(variableList.at(iVar).variableName == "ptLJL"){ itVec->histogram->Fill((lepton1.lepton4V_+parton1.lepton4V_).Pt(),weight) ; } else if(variableList.at(iVar).variableName == "DeltaPhi_TJL"){ itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(parton2.lepton4V_)),weight) ; } else if(variableList.at(iVar).variableName == "ptTJL"){ itVec->histogram->Fill((lepton1.lepton4V_+parton2.lepton4V_).Pt(),weight) ; } else if(variableList.at(iVar).variableName == "DeltaPhi_JJL"){ itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(L_dijet)),weight) ; } else if(variableList.at(iVar).variableName == "ptJJL"){ itVec->histogram->Fill((lepton1.lepton4V_+L_dijet).Pt(),weight) ; } else if(variableList.at(iVar).variableName == "DeltaPhi_LJTL"){ itVec->histogram->Fill(fabs(lepton2.lepton4V_.DeltaPhi(parton1.lepton4V_)),weight) ; } else if(variableList.at(iVar).variableName == "DeltaPhi_TJTL"){ itVec->histogram->Fill(fabs(lepton2.lepton4V_.DeltaPhi(parton2.lepton4V_)),weight) ; } else if(variableList.at(iVar).variableName == "DeltaPhi_JJTL"){ itVec->histogram->Fill(fabs(lepton2.lepton4V_.DeltaPhi(L_dijet)),weight) ; } else if(variableList.at(iVar).variableName == "ptLJTL"){ itVec->histogram->Fill((lepton2.lepton4V_+parton1.lepton4V_).Pt(),weight) ; } else if(variableList.at(iVar).variableName == "ptTJTL"){ itVec->histogram->Fill((lepton2.lepton4V_+parton2.lepton4V_).Pt(),weight) ; } else if(variableList.at(iVar).variableName == "ptJJTL"){ itVec->histogram->Fill((lepton2.lepton4V_+L_dijet).Pt(),weight) ; } else if(variableList.at(iVar).variableName == "DeltaPhi_LJLL"){ itVec->histogram->Fill(fabs(L_dilepton.DeltaPhi(parton1.lepton4V_)),weight) ; } else if(variableList.at(iVar).variableName == "DeltaPhi_TJLL"){ itVec->histogram->Fill(fabs(L_dilepton.DeltaPhi(parton2.lepton4V_)),weight) ; } else if(variableList.at(iVar).variableName == "DeltaPhi_JJLL"){ itVec->histogram->Fill(fabs(L_dilepton.DeltaPhi(L_dijet)),weight) ; } else if(variableList.at(iVar).variableName == "ptLJLL"){ itVec->histogram->Fill((L_dilepton+parton1.lepton4V_).Pt(),weight) ; } else if(variableList.at(iVar).variableName == "ptTJLL"){ itVec->histogram->Fill((L_dilepton+parton2.lepton4V_).Pt(),weight) ; } else if(variableList.at(iVar).variableName == "ptJJLL"){ itVec->histogram->Fill((L_dilepton+L_dijet).Pt(),weight) ; } /// else if(variableList.at(iVar).variableName == "DeltaPhi_JJMet"){ itVec->histogram->Fill(fabs(L_dijet.DeltaPhi(L_met)),weight) ; } else if(variableList.at(iVar).variableName == "ptJJMet"){ itVec->histogram->Fill((L_dijet+L_met).Pt(),weight) ; } else if(variableList.at(iVar).variableName == "DeltaPhi_LJMet"){ itVec->histogram->Fill(fabs(parton1.lepton4V_.DeltaPhi(L_met)),weight) ; } else if(variableList.at(iVar).variableName == "ptLJMet"){ itVec->histogram->Fill((parton1.lepton4V_+L_met).Pt(),weight) ; } else if(variableList.at(iVar).variableName == "DeltaPhi_TJMet"){ itVec->histogram->Fill(fabs(parton2.lepton4V_.DeltaPhi(L_met)),weight) ; } else if(variableList.at(iVar).variableName == "ptTJMet"){ itVec->histogram->Fill((parton2.lepton4V_+L_met).Pt(),weight) ; } else if(variableList.at(iVar).variableName == "mlljj"){ itVec->histogram->Fill((L_dilepton+L_dijet).M(),weight) ; } else if(variableList.at(iVar).variableName == "mlljjmet"){ itVec->histogram->Fill((L_dilepton+L_dijet+L_met).M(),weight) ; } else if(variableList.at(iVar).variableName == "mTH"){ itVec->histogram->Fill(sqrt(2*L_dilepton.Pt()*L_met.Pt()*(1-TMath::Cos(L_dilepton.DeltaPhi(L_met)))),weight) ; } } // loop on variables } // Loop on the cut list } // Loop on the events TFile* outputEfficiency = new TFile(("output/"+outputPlotDirectory+"/outputEfficiency.root").c_str(),"RECREATE"); for(map<string,TH1F*>::const_iterator itMap = histoCutEff.begin(); itMap != histoCutEff.end(); itMap++){ itMap->second->Scale(1./itMap->second->GetBinContent(1)); itMap->second->Write(); } outputEfficiency->Close(); // make the canvas and basic banners TCanvas *cCanvas = new TCanvas("cCanvas","",1,52,550,550); cCanvas->SetTicks(); cCanvas->SetFillColor(0); cCanvas->SetBorderMode(0); cCanvas->SetBorderSize(2); cCanvas->SetTickx(1); cCanvas->SetTicky(1); cCanvas->SetRightMargin(0.05); cCanvas->SetBottomMargin(0.12); cCanvas->SetFrameBorderMode(0); cCanvas->cd(); TPad* upperPad = new TPad("upperPad", "upperPad", .005, .180, .995, .980); TPad* lowerPad = new TPad("lowerPad", "lowerPad", .005, .005, .995, .18); lowerPad->SetGridx(); lowerPad->SetGridy(); upperPad->SetLeftMargin(0.12); upperPad->SetRightMargin(0.1); lowerPad->SetLeftMargin(0.12); lowerPad->SetRightMargin(0.1); lowerPad->SetTopMargin(0.002); lowerPad->Draw(); upperPad->Draw(); TCanvas *cCanvasNorm = new TCanvas("cCanvasNorm","",1,52,550,550); cCanvasNorm->SetTicks(); cCanvasNorm->SetFillColor(0); cCanvasNorm->SetBorderMode(0); cCanvasNorm->SetBorderSize(2); cCanvasNorm->SetTickx(1); cCanvasNorm->SetTicky(1); cCanvasNorm->SetRightMargin(0.05); cCanvasNorm->SetBottomMargin(0.12); cCanvasNorm->SetFrameBorderMode(0); TLatex * tex = new TLatex(0.88,0.92," 14 TeV"); tex->SetNDC(); tex->SetTextAlign(31); tex->SetTextFont(42); tex->SetTextSize(0.045); tex->SetLineWidth(2); TLatex * tex2 = new TLatex(0.14,0.92,"Delphes"); tex2->SetNDC(); tex2->SetTextFont(61); tex2->SetTextSize(0.045); tex2->SetLineWidth(2); TLatex * tex3 = new TLatex(0.295,0.92,"Simulation Preliminary"); tex3->SetNDC(); tex3->SetTextFont(52); tex3->SetTextSize(0.04); tex3->SetLineWidth(2); TLegend* legend = new TLegend(0.55,0.75,0.85,0.89); legend->SetBorderSize(0); legend->SetFillColor(0); legend->SetFillStyle(0); legend->SetTextSize(0.04); legend->SetTextFont(42); legend->SetNColumns (3) ; // make the plot on the same canvas for each variable (legend entry is the cut layer name) vector<TH1F*> numerator ; vector<TH1F*> denominator ; for(size_t iVar = 0; iVar < variableList.size(); iVar++){ // loop on var numerator.clear(); denominator.clear(); for(size_t iCut = 0; iCut < CutList.size(); iCut++){ // loop on cuts histoContainer tmpPlot; tmpPlot.cutName = CutList.at(iCut).cutLayerName; tmpPlot.varName = variableList.at(iVar).variableName; vector<histoContainer>::iterator itVec ; itVec = find(plotVector.begin(),plotVector.end(),tmpPlot); if(itVec == plotVector.end()){ cerr<<"Problem -->plot not found for "<<CutList.at(iCut).cutLayerName<<" "<<variableList.at(iVar).variableName<<endl; } itVec->histogram->GetXaxis()->SetTitleSize(0.04); itVec->histogram->GetXaxis()->SetTitleOffset(1.16); itVec->histogram->GetXaxis()->SetLabelSize(0.04); itVec->histogram->GetYaxis()->SetRangeUser(0.001,itVec->histogram->GetMaximum()*1.25); itVec->histogram->GetYaxis()->SetTitleSize(0.05); itVec->histogram->GetYaxis()->SetTitleOffset(1.20); itVec->histogram->GetYaxis()->SetLabelSize(0.04); itVec->histogram->SetLineColor(iCut+1); if(iCut %2 == 0) itVec->histogram->SetLineStyle(1); else itVec->histogram->SetLineStyle(2); itVec->histogram->SetLineWidth(2); itVec->histogram->GetYaxis()->SetTitle("#sigma x lumi"); upperPad->cd(); if(iCut == 0) itVec->histogram->Draw("hist"); else itVec->histogram->Draw("hist same"); legend->AddEntry(itVec->histogram,CutList.at(iCut).cutLayerName.c_str(),"l"); if(itVec->findCutByLabel("LL")) numerator.push_back(itVec->histogram); denominator.push_back(itVec->histogram); cCanvasNorm->cd(); TH1F* htempNorm = (TH1F*) itVec->histogram->Clone((string(itVec->histogram->GetName())+"_norm").c_str()); htempNorm->Scale(1./itVec->histogram->Integral()); htempNorm->GetYaxis()->SetRangeUser(0.,htempNorm->GetMaximum()*1.5); if(iCut == 0) htempNorm->Draw("hist"); else htempNorm->Draw("hist same"); } // make ratio plot lowerPad->cd(); TH1F* numTotal = 0; TH1F* denTotal = 0; TH1F* ratio = 0; TH1F* ratioW = 0; for(size_t itNum = 0; itNum < numerator.size(); itNum ++){ if(itNum == 0 and ratio == 0) numTotal = (TH1F*) numerator.at(itNum)->Clone(("Num_"+string(numerator.at(itNum)->GetName())).c_str()); else if(ratio !=0) numTotal->Add(numerator.at(itNum)); } for(size_t itDen = 0; itDen < denominator.size(); itDen ++){ if(itDen == 0 and denTotal == 0 ) { denTotal = (TH1F*) denominator.at(itDen)->Clone(("Den_"+string(denominator.at(itDen)->GetName())).c_str()); } else if(denTotal !=0){ denTotal->Add(denominator.at(itDen)); } } ratio = new TH1F(("Ratio_"+string(denominator.at(0)->GetName())).c_str(),"",numTotal->GetNbinsX(),numTotal->GetBinLowEdge(1),numTotal->GetBinLowEdge(numTotal->GetNbinsX()+1)); ratio->GetYaxis()->SetTitle("S/(#sqrt{S+B})"); ratio->SetMarkerSize(1.1); ratioW = new TH1F(("ratioW_"+string(denominator.at(0)->GetName())).c_str(),"",numTotal->GetNbinsX(),numTotal->GetBinLowEdge(1),numTotal->GetBinLowEdge(numTotal->GetNbinsX()+1)); ratioW->GetYaxis()->SetTitle("weighted S/(#sqrt{S+B})"); ratioW->SetMarkerSize(1.1); TString name = "norm_" ; name += denTotal->GetName () ; TH1F * norm_denTotal = (TH1F *) denTotal->Clone (name) ; norm_denTotal->Scale (1. / norm_denTotal->GetMaximum ()) ; // weight the S/sqrt (B) by the shape of the total, // so that only bins with a lot of stats become visibly significant for(int iBin = 0; iBin < ratio->GetNbinsX()+1; iBin++){ if(denTotal->GetBinContent(iBin) !=0){ ratioW->SetBinContent(iBin, norm_denTotal->GetBinContent (iBin) * numTotal->GetBinContent(iBin) / sqrt(denTotal->GetBinContent(iBin))); ratio->SetBinContent(iBin, numTotal->GetBinContent(iBin) / sqrt(denTotal->GetBinContent(iBin))); } else ratio->SetBinContent(iBin,0.); } ratio->GetXaxis()->SetTitle(""); ratio->SetLineColor(kBlue); ratio->SetLineStyle(2); ratio->SetLineWidth(2); ratio->GetXaxis()->SetLabelOffset(999); ratio->GetXaxis()->SetLabelSize(0); ratio->GetYaxis()->SetLabelSize(0.15); ratio->GetYaxis()->SetTitleSize(0.15); ratio->GetYaxis()->SetTitleOffset(0.30); ratio->GetYaxis()->SetNdivisions(504); ratioW->GetXaxis()->SetTitle(""); ratioW->SetLineColor(kBlack); ratioW->SetLineWidth(2); ratioW->GetXaxis()->SetLabelOffset(999); ratioW->GetXaxis()->SetLabelSize(0); ratioW->GetYaxis()->SetLabelSize(0.15); ratioW->GetYaxis()->SetTitleSize(0.15); ratioW->GetYaxis()->SetTitleOffset(0.30); ratioW->GetYaxis()->SetNdivisions(504); ratio->GetYaxis()->SetRange(min(ratio->GetMinimum(),ratioW->GetMinimum())*0.9,max(ratio->GetMaximum(),ratioW->GetMaximum())*1.1); TH1F * frame = lowerPad->DrawFrame (ratio->GetXaxis ()->GetXmin (), 0., ratio->GetXaxis ()->GetXmax (), 2.) ; frame->GetXaxis()->SetTitle (ratio->GetXaxis ()->GetTitle ()) ; frame->GetYaxis()->SetTitle (ratio->GetYaxis ()->GetTitle ()) ; frame->GetXaxis()->SetLabelOffset(999); frame->GetXaxis()->SetLabelSize(0); frame->GetYaxis()->SetLabelSize(0.15); frame->GetYaxis()->SetTitleSize(0.15); frame->GetYaxis()->SetTitleOffset(0.30); frame->GetYaxis()->SetNdivisions(504); ratio->Draw("P"); ratioW->Draw("Lsame"); upperPad->cd(); tex->Draw("same"); tex2->Draw("same"); tex3->Draw("same"); legend->Draw("same"); cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/xs/"+variableList.at(iVar).variableName+".pdf").c_str(),"pdf"); cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/xs/"+variableList.at(iVar).variableName+".png").c_str(),"png"); cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/xs/"+variableList.at(iVar).variableName+".root").c_str(),"root"); cCanvasNorm->cd(); tex->Draw("same"); tex2->Draw("same"); tex3->Draw("same"); legend->Draw("same"); cCanvasNorm->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+".pdf").c_str(),"pdf"); cCanvasNorm->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+".png").c_str(),"png"); cCanvasNorm->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+".root").c_str(),"root"); legend->Clear(); } // loop on var cout<<"LHE filter efficiency : "<<passingLHEFilter<<" totEvent "<<totEvent<<" efficiency "<<float(passingLHEFilter)/float(totEvent)*100<<" % "<<endl; //Normalize histograms for(size_t ihisto = 0; ihisto < plotVector.size(); ihisto++){ if(plotVector.at(ihisto).varName == "DeltaPhi_LL") cout<<"Events Histo "<<plotVector.at(ihisto).histogram->GetName()<<" unweighted "<<plotVector.at(ihisto).histogram->GetEntries()<<" weighted "<<plotVector.at(ihisto).histogram->Integral(0,plotVector.at(ihisto).histogram->GetNbinsX()+1)<<endl; } return 0 ; }
void plotSystFracs(TList* HistList, TH1F* compT, std::string name){ gROOT->SetBatch(); system("mkdir -p plots/ada/systs"); system("mkdir -p plots/grad/systs"); std::string bdt; TString str = compT->GetName(); if (str.Contains("ada")) bdt="ada"; if (str.Contains("grad")) bdt="grad"; int nHists=HistList->GetEntries(); TH1F *comp = linearBin(compT); gROOT->SetStyle("Plain"); gROOT->ForceStyle(); gStyle->SetOptStat(0); TCanvas *canv = new TCanvas("","",700,700); TLegend *leg = new TLegend(0.6,0.6,0.88,0.88); leg->SetLineColor(0); leg->SetFillColor(0); TF1 *line = new TF1("line","0.0",0.,comp->GetBinLowEdge(comp->GetNbinsX()+1)); line->SetLineColor(kBlack); TF1 *line1 = new TF1("line","10.0",0.,comp->GetBinLowEdge(comp->GetNbinsX()+1)); line1->SetLineColor(kGray+2); line1->SetLineStyle(2); TF1 *line2 = new TF1("line","-10.0",0.,comp->GetBinLowEdge(comp->GetNbinsX()+1)); line2->SetLineColor(kGray+2); line2->SetLineStyle(2); int colors[10] = {kBlue,kMagenta,kGreen,kCyan,kRed,kBlue+3,kOrange+1,kSpring-1,kMagenta+3,kGreen+3}; int color=0; for (int i=0; i<nHists; i++){ TH1F *systHist = linearBin((TH1F*)HistList->At(i)); systHist->Add(comp,-1); systHist->Divide(comp); systHist->Scale(100.); std::string systStr = systHist->GetName(); int ind = systStr.rfind("cat0"); std::string systName = systStr.substr(ind+5,systStr.size()); systHist->SetLineColor(colors[color]); systHist->SetTitle(Form("%s",name.c_str())); systHist->GetYaxis()->SetTitle("Difference over nominal %"); systHist->GetYaxis()->SetTitleOffset(1.4); systHist->GetXaxis()->SetTitle("BDT output"); systHist->GetYaxis()->SetRangeUser(-100.,250); if (int(systName.find("Up"))>0){ systHist->SetLineStyle(1); systName = systName.substr(0,systName.rfind("Up")); leg->AddEntry(systHist,systName.c_str(),"l"); color++; } else if (int(systName.find("Down"))>0){ systHist->SetLineStyle(2); systName = systName.substr(0,systName.rfind("Down")); } if (i==0) systHist->DrawCopy("hist"); else systHist->DrawCopy("same hist"); } leg->Draw("same"); line->Draw("same"); line1->Draw("same"); line2->Draw("same"); canv->Print(("plots/"+bdt+"/systs/"+name+".png").c_str(),"png"); delete canv; systCalls++; }
void compareSherpaMadgraph(std::string sherpafile, std::string madgraphfile, std::string var, float xmin=-9999.0, float xmax=-9999.0, bool logScale=false, std::string output="test") { setTDRStyle(); gStyle->SetOptStat(0); TH1F* hsherpa; TH1F* hmadgraph; char tempName[300]; // first get the histogram files TFile *fsherpa = TFile::Open(sherpafile.data()); TFile *fmadgraph = TFile::Open(madgraphfile.data()); hsherpa = (TH1F*)(fsherpa->Get(var.data())); hmadgraph = (TH1F*)(fmadgraph->Get(var.data())); TH1D* hscale =(TH1D*) hsherpa->Clone("hscale"); hscale->SetYTitle("SHERPA/MADGRAPH"); int nREBIN=2; if(var.find("pt")!= std::string::npos) nREBIN=4; hsherpa->GetXaxis()->SetNdivisions(5); hsherpa->GetYaxis()->SetDecimals(); hsherpa->Rebin(nREBIN); hmadgraph->GetXaxis()->SetNdivisions(5); hmadgraph->GetYaxis()->SetDecimals(); hmadgraph->Rebin(nREBIN); hscale->GetXaxis()->SetNdivisions(5); hscale->GetYaxis()->SetDecimals(); hscale->Rebin(nREBIN); hsherpa->SetLineColor(2); hsherpa->SetMarkerColor(2); hsherpa->SetMarkerSize(1); hsherpa->SetMarkerStyle(24); hmadgraph->SetLineColor(4); hmadgraph->SetMarkerColor(4); hmadgraph->SetMarkerSize(1); hmadgraph->SetMarkerStyle(21); // if normalizing to the same area, set the scale int binLo = -1; int binHi = -1; int nbins = hsherpa->GetNbinsX(); if(xmin>-9999.0 && xmax>-9999.0) { binLo = hsherpa->FindBin(xmin); binHi = hsherpa->FindBin(xmax)-1; } else { binLo = 1; binHi = nbins; xmin = hsherpa->GetBinLowEdge(1); xmax = hsherpa->GetBinLowEdge(nbins+1); } // float scale_mc = (float)hsherpa->Integral(binLo,binHi)/(float)hmadgraph->Integral(binLo,binHi); // cout << "binLo = " << binLo << ", binHi = " << binHi << endl; // cout << "xmin = " << xmin << "xmax = " << xmax << endl; // hmadgraph->Sumw2(); // hmadgraph->Scale(scale_mc); float scale_sherpa = 1000.0*4.890*3048.0/4.71644910071102437e+06; float scale_madgraph = 1000.0*4.890*3048.0/3.59644320000000000e+07; hsherpa->Sumw2(); hsherpa->Scale(scale_sherpa); hmadgraph->Sumw2(); hmadgraph->Scale(scale_madgraph); cout << "hmadgraph integral = " << hmadgraph->Integral() << endl; cout << "hsherpa integral = " << hsherpa->Integral() << endl;; // get the ratio double chi2 = 0; int realbin = 0; for(int i=1; i<= nbins; i++) { double nmc=hmadgraph->GetBinContent(i); double ndata=hsherpa->GetBinContent(i); double nmcerr=hmadgraph->GetBinError(i); double ndataerr=hsherpa->GetBinError(i); if(nmc<0 || ndata<0)continue; if(nmcerr==0 && ndataerr==0)continue; if(nmc==0 && ndata==0)continue; double chi2ndef = (nmc-ndata)*(nmc-ndata)/ ( nmcerr*nmcerr+ ndataerr*ndataerr); chi2 += chi2ndef; realbin++; cout << "Bin " << i << " : " << ndata << ", " << nmc; cout << " " << chi2ndef << endl; // now calculate the ratio if(nmc==0 || nmcerr==0 || ndata==0 || ndataerr==0)continue; cout << "Bin " << i << " ratio = " << ndata/nmc << endl; hscale->SetBinContent(i,ndata/nmc); double err = 0; err= (ndata/nmc)*sqrt(pow(nmcerr/nmc,2)+pow(ndataerr/ndata,2)); hscale->SetBinError(i,err); } hsherpa->GetXaxis()->SetRangeUser(xmin,xmax); hmadgraph->GetXaxis()->SetRangeUser(xmin,xmax); hscale->GetXaxis()->SetRangeUser(xmin,xmax); TCanvas* c1 = new TCanvas("c1","",700,1000); c1->Divide(1,2,0.01,0); c1->cd(1); if(logScale) gPad->SetLogy(1); gPad->SetTopMargin(0.01); gPad->SetBottomMargin(0); gPad->SetRightMargin(0.04); float max_data = hsherpa->GetBinError(hsherpa->GetMaximumBin()) + hsherpa->GetMaximum(); float max_mc = hmadgraph->GetBinError(hmadgraph->GetMaximumBin()) + hmadgraph->GetMaximum(); if(max_data > max_mc) { hsherpa->Draw("e"); hmadgraph->Draw("hesame"); } else { hmadgraph->Draw("he"); hsherpa->Draw("esame"); } float x1NDC = 0.691; float y1NDC = 0.757; float x2NDC = 0.894; float y2NDC = 0.973; TLegend* leg = new TLegend(x1NDC,y1NDC,x2NDC,y2NDC); leg->SetFillColor(0); leg->SetFillStyle(0); leg->SetTextSize(0.04); leg->SetBorderSize(0); leg->AddEntry(hsherpa, "SHERPA"); leg->AddEntry(hmadgraph, "MADGRAPH"); leg->Draw("same"); c1->cd(2); gStyle->SetStatW (0.3); gStyle->SetStatH (0.3); gStyle->SetStatX (0.879447); gStyle->SetStatY (0.939033); gStyle->SetStatFontSize(0.05); gStyle->SetStatBorderSize(0); gPad->SetRightMargin(0.04); gPad->SetTopMargin(0); gPad->SetBottomMargin(0.2); gPad->SetTickx(); gStyle->SetOptFit(1); hscale->SetTitle(""); hscale->SetMaximum(3.0); hscale->SetMinimum(-0.5); hscale->SetTitleOffset(1.2,"Y"); hscale->Draw("e1"); TF1* fline = new TF1("fline","pol1"); TLine* l2 = new TLine(xmin,1.,xmax,1.); l2->SetLineColor(4); l2->SetLineStyle(3); fline->SetLineWidth(3); fline->SetLineColor(6); fline->SetNpx(2500); hscale->Fit("fline","",""); l2->Draw("same"); string dirName = "compareSherpaMadgraph"; gSystem->mkdir(dirName.data()); std::string filename; std::string psname = dirName + "/" + var; if(output !="test") psname = dirName+ "/" + output; else psname = dirName+ "/" + var; filename = psname + ".eps"; c1->Print(filename.data()); filename = psname + ".gif"; c1->Print(filename.data()); filename = psname + ".pdf"; c1->Print(filename.data()); // c1->Close(); }
pair <float,float> find_point(TH2F* histo, int xbin, bool mSUGRA=true) { TH1F *flathisto; if(mSUGRA) flathisto = new TH1F("flat","flat",histo->GetNbinsY(),histo->GetYaxis()->GetBinLowEdge(1),histo->GetYaxis()->GetBinLowEdge(histo->GetNbinsY())+histo->GetYaxis()->GetBinWidth(histo->GetNbinsY())); else flathisto = new TH1F("flat","flat",histo->GetNbinsX(),histo->GetXaxis()->GetBinLowEdge(1),histo->GetXaxis()->GetBinLowEdge(histo->GetNbinsX())+histo->GetXaxis()->GetBinWidth(histo->GetNbinsX())); int nbins=histo->GetNbinsY(); if(!mSUGRA) nbins=histo->GetNbinsX(); for(int i=1;i<nbins;i++) { float value=(histo->GetBinContent(xbin,i)); if(value<20&&value>0) flathisto->SetBinContent(i,value); } float pointone=-100; nbins=flathisto->GetNbinsX(); if(!mSUGRA) nbins=flathisto->GetNbinsY(); for(int i=nbins;i>=1;i--) { if(pointone<0&&flathisto->GetBinContent(i)<1&&flathisto->GetBinContent(i)>0) pointone=flathisto->GetBinLowEdge(i)+flathisto->GetBinWidth(i); } pair <float,float> anything; if(mSUGRA) anything.first=histo->GetXaxis()->GetBinCenter(xbin); else anything.first=histo->GetYaxis()->GetBinCenter(xbin); anything.second=pointone; delete flathisto; return anything; }
// This is the Efrac plot for a CALSum range void Efrac_all_energies::Loop2() { if (fChain == 0) return; TH1F * hPi = new TH1F("hPi","",500,-0.2,3); TH1F * hE = new TH1F("hE","",500,-0.2,3); Int_t NE75 = 0; Int_t NE100 = 0; Int_t NE125 = 0; Int_t NE150 = 0; Int_t NE175 = 0; Int_t NPi250 = 0; Int_t NPi300 = 0; Int_t NPi350 = 0; Double_t gainA[12] = {4.23,4.23,3.92,3.09,5.81,5.03,3.17,5.30,4.31,3.90,4.04,3.68}; Double_t myfCHA[12]; Double_t myBSDLatePE = 0; fChain->SetBranchStatus("*",1); Long64_t nentries = fChain->GetEntriesFast(); Long64_t nbytes = 0, nb = 0; for (Long64_t jentry=0; jentry<nentries;jentry++) { Long64_t ientry = LoadTree(jentry); if (ientry < 0) break; nb = fChain->GetEntry(jentry); nbytes += nb; ///////////////////////////////////////////////////////////////////////// // These are just cuts for valid BSD/CAL data values // Need a BSD event which also includes the CAL //////////////////////////////////////////////////////////////////////// if( !IsWithCal ) continue; myBSDLatePE = 0; for( int i = 0; i < 12; i++ ) myfCHA[i] = -1; for( int i = 1; i <= 10; i++ ) { if( fCHA[i] <= 0 ) { myfCHA[i] = 2048; } else { myfCHA[i] = fCHA[i]; } } // Simulate CAL trigger by requiring 6 consecutive layers with > 40 MeV Int_t Ntrig_layers = 0; for( int i = 0; i < 20; i++ ) { if( CALProfile[i]/9 > 40 ) Ntrig_layers++; else Ntrig_layers = 0; if( Ntrig_layers >= 6 ) break; } if( Ntrig_layers < 6 ) continue; // New cut to look at a range of CALSum // if( CALSum < 6000 || CALSum > 7500 ) continue; if( CALSum < 6000 || CALSum > 9000 ) continue; for( int i = 1; i <= 10; i++ ) myBSDLatePE += myfCHA[i]*0.25E-12/(gainA[i]*1.E6*1.6E-19); // Check if we've got enough of that particular flavor, i.e. all electrons // need to be weighted equally relative to pions if( ptype == 2 && penergy == 250 && NPi250 > 6617) continue; if( ptype == 2 && penergy == 300 && NPi300 > 6617) continue; if( ptype == 2 && penergy == 350 && NPi350 > 6617) continue; if( ptype == 1 && penergy == 75 && NE75 > 2442 ) continue; if( ptype == 1 && penergy == 100 && NE100 > 2442 ) continue; if( ptype == 1 && penergy == 125 && NE125 > 2442 ) continue; if( ptype == 1 && penergy == 150 && NE150 > 2442 ) continue; if( ptype == 1 && penergy == 175 && NE175 > 2442 ) continue; // Fill Efrac for electrons if( ptype == 1 && (penergy >=75 || penergy <= 175) ) hE->Fill(myBSDLatePE/CALSum); // Fill Efrac for pions if( ptype == 2 && (penergy >= 250 || penergy <= 350) ) hPi->Fill(myBSDLatePE/CALSum); // Increment counts, since everything has to be equally weighted if( ptype == 2 && penergy == 250 ) NPi250++; if( ptype == 2 && penergy == 300 ) NPi300++; if( ptype == 2 && penergy == 350 ) NPi350++; if( ptype == 1 && penergy == 75 ) NE75++; if( ptype == 1 && penergy == 100 ) NE100++; if( ptype == 1 && penergy == 125 ) NE125++; if( ptype == 1 && penergy == 150 ) NE150++; if( ptype == 1 && penergy == 175 ) NE175++; } hE->SetLineColor(kRed); hE->SetTitle("Efrac for 250-350 GeV Pions (Blue) and 75-175 GeV Electrons (Red) and CALSum Between 6000 and 9000"); hE->GetXaxis()->SetTitle("Efrac (\"detector\" units)"); hE->GetXaxis()->CenterTitle(); hE->Scale(1./hE->GetEntries()); hE->Draw(); hPi->Scale(1./hPi->GetEntries()); hPi->Draw("sames"); Double_t reg_power[1000]; Double_t e_accept[1000]; Double_t pi_accept[1000]; Double_t endbin[1000]; Int_t Npts = 0; Int_t Nskip = 0; Int_t start = hE->FindBin(0); Int_t nbins = 40; // ToDo: Add error bars cout << "Start = " << start << endl; Double_t x_err[1000]; Double_t y_err[1000]; Double_t num = 0; Double_t den = 0; Double_t num_err = 0; Double_t den_err = 0; Double_t Ne = 0; Double_t Ne_total = 0; Double_t Npi = 0; Double_t Npi_total = 0; Double_t Ne_entries = hE->GetEntries(); Double_t Npi_entries = hPi->GetEntries(); for( int i = 0; i < nbins; i++ ) { cout << "Efrac = " << hE->GetBinLowEdge(start+i) << endl; if( hPi->Integral(start,start+i) > 10./Ne_entries && hE->Integral(start,start+i) > 10./Npi_entries ) { num_err = 0; den_err = 0; Ne = 0; Npi = 0; num = 0; den = 0; Npi_total = 0; Ne_total = 0; Ne = hE->Integral(start,start+i); Ne_total = hE->Integral(); Npi = hPi->Integral(start,start+i); Npi_total = hPi->Integral(); num = (Ne/Ne_total); den = (Npi/Npi_total); reg_power[i-Nskip] = num/den; e_accept[i-Nskip] = num; pi_accept[i-Nskip] = den; endbin[i-Nskip] = start+i; num = (Ne/Ne_total); den = (Npi/Npi_total); num_err = (num) * sqrt(1/(Ne*Ne_entries) + 1/(Ne_total*Ne_entries)); den_err = (den) * sqrt(1/(Npi*Npi_entries) + 1/(Npi_total*Npi_entries)); y_err[i-Nskip] = (num/den) * sqrt( (num_err*num_err)/(num*num) + (den_err*den_err)/(den*den) ); x_err[i-Nskip] = num_err; cout << i-Nskip << " " << e_accept[i-Nskip] << " " << pi_accept[i-Nskip] << " " << reg_power[i-Nskip] << " " << hPi->Integral(start,start+i) << " " << hE->Integral(start,start+i) << " " << num_err << " " << den_err << endl; Npts++; } else Nskip++; } /* // For quick and easy copy/paste graphing cout << "rej[" << Npts << "] = {"; for(int i = 0; i < Npts; i++ ) cout << reg_power[i] << ", " << endl; cout << endl; // For quick and easy copy/paste graphing cout << "e_accept[" << Npts << "] = {"; for(int i = 0; i < Npts; i++ ) cout << e_accept[i] << ", " << endl; cout << endl; cout << "x_err[" << Npts << "] = {"; for( int i = 0; i < Npts; i++ ) cout << x_err[i] << endl; cout << endl; cout << "y_err[" << Npts << "] = {"; for( int i = 0; i < Npts; i++ ) cout << y_err[i] << endl; cout << endl; */ TCanvas * cv2 = new TCanvas("cv2"); TGraphErrors * gr = new TGraphErrors(Npts,e_accept,reg_power,x_err,y_err); gr->SetTitle(""); gr->GetXaxis()->SetTitle("Electron acceptance"); gr->GetXaxis()->CenterTitle(); gr->GetYaxis()->SetTitle("Rejection Power"); gr->GetYaxis()->CenterTitle(); gr->SetMarkerStyle(20); gr->Draw("APL"); }
void makePlotTriggers3(){ bool DCSonly = false;//always false string whichdata = "SingleMuon"; //string whichdata = "DoubleMuon"; //string whichdata = "MuonEG"; //string whichdata = "SingleElectron"; // vector<char*> bgnames, signames; vector<string> bgstrings, sigstrings; vector<Color_t> colors; const unsigned int datasetsize = 4;//12 const unsigned int bgsetsize = 4;//8 const unsigned int sigsetsize = datasetsize-bgsetsize; string datasets[datasetsize]={"TTbar_amcnlo_50ns","WJets_50ns","DY_M50_50ns","DY_M10_50ns"}; //char* dataset[datasetsize]={"TTbar1l","TTbar2l","SingleT","VJets","Rare","Stop_425_325","Stop_500_325","Stop_650_325","Stop_850_100"}; const Color_t mccolor[datasetsize]={kBlue+1,kGreen+1,kMagenta+1,kMagenta-2};// string outputdir = "../plots/first_20150727/"; string inputdir = "../rootfiles/first_20150727/"; if(DCSonly) outputdir = "../plots/first_20150727/DCSonly/"; for(unsigned int n=0; n<bgsetsize; ++n) { //bgnames.push_back(dataset[n]); bgstrings.push_back(datasets[n]); colors.push_back(mccolor[n]); } for(unsigned int n=bgsetsize; n<datasetsize; ++n) { //signames.push_back(dataset[n]); sigstrings.push_back(datasets[n]); colors.push_back(mccolor[n]); } TFile *fbg[bgsetsize]; vector<string> histonames; vector<string> histonames1; vector<string> histonames2; vector<float> fithisto; vector<string> xt; vector<string> yt; //histonames.push_back("TriggerEff__Mu50_Pt"); fithisto.push_back(52); //histonames1.push_back("Trigger__Mu50Tag_Pt"); //histonames2.push_back("Trigger__Mu50Probe_Pt"); histonames.push_back("TriggerEff_IsoMu27_Pt"); fithisto.push_back(29); xt.push_back("muon p_{T} [GeV]"); yt.push_back("Efficiency(IsoMu27||IsoTkMu27)"); histonames1.push_back("Trigger_IsoMu27Tag_Pt"); histonames2.push_back("Trigger_IsoMu27Probe_Pt"); histonames.push_back("TriggerEff_IsoMu27_Eta"); fithisto.push_back(-1); xt.push_back("muon #eta"); yt.push_back("Efficiency(IsoMu27||IsoTkMu27)"); histonames1.push_back("Trigger_IsoMu27Tag_Eta"); histonames2.push_back("Trigger_IsoMu27Probe_Eta"); histonames.push_back("TriggerEff_IsoMu27_RelIso03"); fithisto.push_back(-1); xt.push_back("muon rel.iso"); yt.push_back("Efficiency(IsoMu27||IsoTkMu27)"); histonames1.push_back("Trigger_IsoMu27Tag_RelIso03"); histonames2.push_back("Trigger_IsoMu27Probe_RelIso03"); histonames.push_back("TriggerEff_IsoMu27_RelIso03EA"); fithisto.push_back(-1); xt.push_back("muon rel.iso-EA"); yt.push_back("Efficiency(IsoMu27||IsoTkMu27)"); histonames1.push_back("Trigger_IsoMu27Tag_RelIso03EA"); histonames2.push_back("Trigger_IsoMu27Probe_RelIso03EA"); histonames.push_back("TriggerEff_IsoMu27_RelIso03DB"); fithisto.push_back(-1); xt.push_back("muon rel.iso-DB"); yt.push_back("Efficiency(IsoMu27||IsoTkMu27)"); histonames1.push_back("Trigger_IsoMu27Tag_RelIso03DB"); histonames2.push_back("Trigger_IsoMu27Probe_RelIso03DB"); histonames.push_back("TriggerEff_IsoMu27_miniiso"); fithisto.push_back(-1); xt.push_back("muon rel.miniiso"); yt.push_back("Efficiency(IsoMu27||IsoTkMu27)"); histonames1.push_back("Trigger_IsoMu27Tag_miniiso"); histonames2.push_back("Trigger_IsoMu27Probe_miniiso"); histonames.push_back("TriggerEff_IsoMu27_miniisoDB"); fithisto.push_back(-1); xt.push_back("muon rel.miniiso-DB"); yt.push_back("Efficiency(IsoMu27||IsoTkMu27)"); histonames1.push_back("Trigger_IsoMu27Tag_miniisoDB"); histonames2.push_back("Trigger_IsoMu27Probe_miniisoDB"); histonames.push_back("TriggerEff_IsoMu20_Pt"); fithisto.push_back(22); xt.push_back("muon p_{T} [GeV]"); yt.push_back("Efficiency(IsoMu20||IsoTkMu20)"); histonames1.push_back("Trigger_IsoMu20Tag_Pt"); histonames2.push_back("Trigger_IsoMu20Probe_Pt"); histonames.push_back("TriggerEff_IsoMu20_Eta"); fithisto.push_back(-1); xt.push_back("muon #eta"); yt.push_back("Efficiency(IsoMu20||IsoTkMu20)"); histonames1.push_back("Trigger_IsoMu20Tag_Eta"); histonames2.push_back("Trigger_IsoMu20Probe_Eta"); histonames.push_back("TriggerEff_IsoMu20_RelIso03"); fithisto.push_back(-1); xt.push_back("muon rel.iso"); yt.push_back("Efficiency(IsoMu20||IsoTkMu20)"); histonames1.push_back("Trigger_IsoMu20Tag_RelIso03"); histonames2.push_back("Trigger_IsoMu20Probe_RelIso03"); histonames.push_back("TriggerEff_IsoMu20_RelIso03EA"); fithisto.push_back(-1); xt.push_back("muon rel.iso-EA"); yt.push_back("Efficiency(IsoMu20||IsoTkMu20)"); histonames1.push_back("Trigger_IsoMu20Tag_RelIso03EA"); histonames2.push_back("Trigger_IsoMu20Probe_RelIso03EA"); histonames.push_back("TriggerEff_IsoMu20_RelIso03DB"); fithisto.push_back(-1); xt.push_back("muon rel.iso-DB"); yt.push_back("Efficiency(IsoMu20||IsoTkMu20)"); histonames1.push_back("Trigger_IsoMu20Tag_RelIso03DB"); histonames2.push_back("Trigger_IsoMu20Probe_RelIso03DB"); histonames.push_back("TriggerEff_IsoMu20_miniiso"); fithisto.push_back(-1); xt.push_back("muon rel.miniiso"); yt.push_back("Efficiency(IsoMu20||IsoTkMu20)"); histonames1.push_back("Trigger_IsoMu20Tag_miniiso"); histonames2.push_back("Trigger_IsoMu20Probe_miniiso"); histonames.push_back("TriggerEff_IsoMu20_miniisoDB"); fithisto.push_back(-1); xt.push_back("muon rel.miniiso-DB"); yt.push_back("Efficiency(IsoMu20||IsoTkMu20)"); histonames1.push_back("Trigger_IsoMu20Tag_miniisoDB"); histonames2.push_back("Trigger_IsoMu20Probe_miniisoDB"); //histonames.push_back("TriggerEff__Mu45eta2p1_Pt"); fithisto.push_back(47); //histonames1.push_back("Trigger__Mu45eta2p1Tag_Pt"); //histonames2.push_back("Trigger__Mu45eta2p1Probe_Pt"); histonames.push_back("TriggerEff_IsoMu24eta2p1_Pt"); fithisto.push_back(26); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoMu24eta2p1Tag_Pt"); histonames2.push_back("Trigger_IsoMu24eta2p1Probe_Pt"); histonames.push_back("TriggerEff_IsoMu24eta2p1_Eta"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoMu24eta2p1Tag_Eta"); histonames2.push_back("Trigger_IsoMu24eta2p1Probe_Eta"); histonames.push_back("TriggerEff_IsoMu24eta2p1_RelIso03"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoMu24eta2p1Tag_RelIso03"); histonames2.push_back("Trigger_IsoMu24eta2p1Probe_RelIso03"); histonames.push_back("TriggerEff_IsoMu24eta2p1_RelIso03EA"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoMu24eta2p1Tag_RelIso03EA"); histonames2.push_back("Trigger_IsoMu24eta2p1Probe_RelIso03EA"); histonames.push_back("TriggerEff_IsoMu24eta2p1_RelIso03DB"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoMu24eta2p1Tag_RelIso03DB"); histonames2.push_back("Trigger_IsoMu24eta2p1Probe_RelIso03DB"); histonames.push_back("TriggerEff_IsoMu24eta2p1_miniiso"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoMu24eta2p1Tag_miniiso"); histonames2.push_back("Trigger_IsoMu24eta2p1Probe_miniiso"); histonames.push_back("TriggerEff_IsoMu24eta2p1_miniisoDB"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoMu24eta2p1Tag_miniisoDB"); histonames2.push_back("Trigger_IsoMu24eta2p1Probe_miniisoDB"); histonames.push_back("TriggerEff_DiMu_LeadPt"); fithisto.push_back(20); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_DiMuTag_LeadPt"); histonames2.push_back("Trigger_DiMuProbe_LeadPt"); histonames.push_back("TriggerEff_DiMu_TrailPt"); fithisto.push_back(10); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_DiMuTag_TrailPt"); histonames2.push_back("Trigger_DiMuProbe_TrailPt"); histonames.push_back("TriggerEff_PureIsoMu20_Pt"); fithisto.push_back(22); xt.push_back("muon p_{T} [GeV]"); yt.push_back("Efficiency(IsoMu20)"); histonames1.push_back("Trigger_PureIsoMu20Tag_Pt"); histonames2.push_back("Trigger_PureIsoMu20Probe_Pt"); histonames.push_back("TriggerEff_PureIsoMu20_Eta"); fithisto.push_back(-1); xt.push_back("muon #eta"); yt.push_back("Efficiency(IsoMu20)"); histonames1.push_back("Trigger_PureIsoMu20Tag_Eta"); histonames2.push_back("Trigger_PureIsoMu20Probe_Eta"); histonames.push_back("TriggerEff_PureIsoMu20_Phi"); fithisto.push_back(-1); xt.push_back("muon #phi"); yt.push_back("Efficiency(IsoMu20)"); histonames1.push_back("Trigger_PureIsoMu20Tag_Phi"); histonames2.push_back("Trigger_PureIsoMu20Probe_Phi"); histonames.push_back("TriggerEff_PureIsoMu20_RelIso03"); fithisto.push_back(-1); xt.push_back("muon rel.iso"); yt.push_back("Efficiency(IsoMu20)"); histonames1.push_back("Trigger_PureIsoMu20Tag_RelIso03"); histonames2.push_back("Trigger_PureIsoMu20Probe_RelIso03"); histonames.push_back("TriggerEff_PureIsoMu20_RelIso03DB"); fithisto.push_back(-1); xt.push_back("muon rel.iso-DB"); yt.push_back("Efficiency(IsoMu20)"); histonames1.push_back("Trigger_PureIsoMu20Tag_RelIso03DB"); histonames2.push_back("Trigger_PureIsoMu20Probe_RelIso03DB"); histonames.push_back("TriggerEff_IsoTkMu20_Pt"); fithisto.push_back(22); xt.push_back("muon p_{T} [GeV]"); yt.push_back("Efficiency(IsoTkMu20)"); histonames1.push_back("Trigger_IsoTkMu20Tag_Pt"); histonames2.push_back("Trigger_IsoTkMu20Probe_Pt"); histonames.push_back("TriggerEff_IsoTkMu20_Eta"); fithisto.push_back(-1); xt.push_back("muon #eta"); yt.push_back("Efficiency(IsoTkMu20)"); histonames1.push_back("Trigger_IsoTkMu20Tag_Eta"); histonames2.push_back("Trigger_IsoTkMu20Probe_Eta"); histonames.push_back("TriggerEff_IsoTkMu20_Phi"); fithisto.push_back(-1); xt.push_back("muon #phi"); yt.push_back("Efficiency(IsoTkMu20)"); histonames1.push_back("Trigger_IsoTkMu20Tag_Phi"); histonames2.push_back("Trigger_IsoTkMu20Probe_Phi"); histonames.push_back("TriggerEff_IsoTkMu20_RelIso03"); fithisto.push_back(-1); xt.push_back("muon rel.iso"); yt.push_back("Efficiency(IsoTkMu20)"); histonames1.push_back("Trigger_IsoTkMu20Tag_RelIso03"); histonames2.push_back("Trigger_IsoTkMu20Probe_RelIso03"); histonames.push_back("TriggerEff_IsoTkMu20_RelIso03DB"); fithisto.push_back(-1); xt.push_back("muon rel.iso-DB"); yt.push_back("Efficiency(IsoTkMu20)"); histonames1.push_back("Trigger_IsoTkMu20Tag_RelIso03DB"); histonames2.push_back("Trigger_IsoTkMu20Probe_RelIso03DB"); histonames.push_back("TriggerEff_PureIsoMu20_Pt_etarestrict"); fithisto.push_back(22); xt.push_back("muon p_{T} [GeV]"); yt.push_back("Efficiency(IsoMu20)"); histonames1.push_back("Trigger_PureIsoMu20Tag_Pt_etarestrict"); histonames2.push_back("Trigger_PureIsoMu20Probe_Pt_etarestrict"); histonames.push_back("TriggerEff_PureIsoMu20_Phi_etarestrict"); fithisto.push_back(-1); xt.push_back("muon #phi"); yt.push_back("Efficiency(IsoMu20)"); histonames1.push_back("Trigger_PureIsoMu20Tag_Phi_etarestrict"); histonames2.push_back("Trigger_PureIsoMu20Probe_Phi_etarestrict"); histonames.push_back("TriggerEff_IsoTkMu20_Pt_etarestrict"); fithisto.push_back(22); xt.push_back("muon p_{T} [GeV]"); yt.push_back("Efficiency(IsoTkMu20)"); histonames1.push_back("Trigger_IsoTkMu20Tag_Pt_etarestrict"); histonames2.push_back("Trigger_IsoTkMu20Probe_Pt_etarestrict"); histonames.push_back("TriggerEff_IsoTkMu20_Phi_etarestrict"); fithisto.push_back(-1); xt.push_back("muon #phi"); yt.push_back("Efficiency(IsoTkMu20)"); histonames1.push_back("Trigger_IsoTkMu20Tag_Phi_etarestrict"); histonames2.push_back("Trigger_IsoTkMu20Probe_Phi_etarestrict"); histonames.push_back("TriggerEff_PureIsoMu20_RelIso03_etarestrict"); fithisto.push_back(-1); xt.push_back("muon rel.iso"); yt.push_back("Efficiency(IsoMu20)"); histonames1.push_back("Trigger_PureIsoMu20Tag_RelIso03_etarestrict"); histonames2.push_back("Trigger_PureIsoMu20Probe_RelIso03_etarestrict"); histonames.push_back("TriggerEff_PureIsoMu20_RelIso03DB_etarestrict"); fithisto.push_back(-1); xt.push_back("muon rel.iso-DB"); yt.push_back("Efficiency(IsoMu20)"); histonames1.push_back("Trigger_PureIsoMu20Tag_RelIso03DB_etarestrict"); histonames2.push_back("Trigger_PureIsoMu20Probe_RelIso03DB_etarestrict"); histonames.push_back("TriggerEff_IsoTkMu20_RelIso03_etarestrict"); fithisto.push_back(-1); xt.push_back("muon rel.iso"); yt.push_back("Efficiency(IsoTkMu20)"); histonames1.push_back("Trigger_IsoTkMu20Tag_RelIso03_etarestrict"); histonames2.push_back("Trigger_IsoTkMu20Probe_RelIso03_etarestrict"); histonames.push_back("TriggerEff_IsoTkMu20_RelIso03DB_etarestrict"); fithisto.push_back(-1); xt.push_back("muon rel.iso-DB"); yt.push_back("Efficiency(IsoTkMu20)"); histonames1.push_back("Trigger_IsoTkMu20Tag_RelIso03DB_etarestrict"); histonames2.push_back("Trigger_IsoTkMu20Probe_RelIso03DB_etarestrict"); histonames.push_back("TriggerEff_PureIsoMu27_Pt"); fithisto.push_back(29); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_PureIsoMu27Tag_Pt"); histonames2.push_back("Trigger_PureIsoMu27Probe_Pt"); histonames.push_back("TriggerEff_PureIsoMu27_Eta"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_PureIsoMu27Tag_Eta"); histonames2.push_back("Trigger_PureIsoMu27Probe_Eta"); histonames.push_back("TriggerEff_PureIsoMu27_Phi"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_PureIsoMu27Tag_Phi"); histonames2.push_back("Trigger_PureIsoMu27Probe_Phi"); histonames.push_back("TriggerEff_PureIsoMu27_RelIso03"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_PureIsoMu27Tag_RelIso03"); histonames2.push_back("Trigger_PureIsoMu27Probe_RelIso03"); histonames.push_back("TriggerEff_PureIsoMu27_RelIso03DB"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_PureIsoMu27Tag_RelIso03DB"); histonames2.push_back("Trigger_PureIsoMu27Probe_RelIso03DB"); histonames.push_back("TriggerEff_IsoTkMu27_Pt"); fithisto.push_back(29); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoTkMu27Tag_Pt"); histonames2.push_back("Trigger_IsoTkMu27Probe_Pt"); histonames.push_back("TriggerEff_IsoTkMu27_Eta"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoTkMu27Tag_Eta"); histonames2.push_back("Trigger_IsoTkMu27Probe_Eta"); histonames.push_back("TriggerEff_IsoTkMu27_Phi"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoTkMu27Tag_Phi"); histonames2.push_back("Trigger_IsoTkMu27Probe_Phi"); histonames.push_back("TriggerEff_IsoTkMu27_RelIso03"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoTkMu27Tag_RelIso03"); histonames2.push_back("Trigger_IsoTkMu27Probe_RelIso03"); histonames.push_back("TriggerEff_IsoTkMu27_RelIso03DB"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoTkMu27Tag_RelIso03DB"); histonames2.push_back("Trigger_IsoTkMu27Probe_RelIso03DB"); histonames.push_back("TriggerEff_PureIsoMu24eta2p1_Pt"); fithisto.push_back(26); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_PureIsoMu24eta2p1Tag_Pt"); histonames2.push_back("Trigger_PureIsoMu24eta2p1Probe_Pt"); histonames.push_back("TriggerEff_PureIsoMu24eta2p1_Eta"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_PureIsoMu24eta2p1Tag_Eta"); histonames2.push_back("Trigger_PureIsoMu24eta2p1Probe_Eta"); histonames.push_back("TriggerEff_PureIsoMu24eta2p1_Phi"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_PureIsoMu24eta2p1Tag_Phi"); histonames2.push_back("Trigger_PureIsoMu24eta2p1Probe_Phi"); histonames.push_back("TriggerEff_PureIsoMu24eta2p1_RelIso03"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_PureIsoMu24eta2p1Tag_RelIso03"); histonames2.push_back("Trigger_PureIsoMu24eta2p1Probe_RelIso03"); histonames.push_back("TriggerEff_PureIsoMu24eta2p1_RelIso03DB"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_PureIsoMu24eta2p1Tag_RelIso03DB"); histonames2.push_back("Trigger_PureIsoMu24eta2p1Probe_RelIso03DB"); histonames.push_back("TriggerEff_IsoTkMu24eta2p1_Pt"); fithisto.push_back(25); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoTkMu24eta2p1Tag_Pt"); histonames2.push_back("Trigger_IsoTkMu24eta2p1Probe_Pt"); histonames.push_back("TriggerEff_IsoTkMu24eta2p1_Eta"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoTkMu24eta2p1Tag_Eta"); histonames2.push_back("Trigger_IsoTkMu24eta2p1Probe_Eta"); histonames.push_back("TriggerEff_IsoTkMu24eta2p1_Phi"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoTkMu24eta2p1Tag_Phi"); histonames2.push_back("Trigger_IsoTkMu24eta2p1Probe_Phi"); histonames.push_back("TriggerEff_IsoTkMu24eta2p1_RelIso03"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoTkMu24eta2p1Tag_RelIso03"); histonames2.push_back("Trigger_IsoTkMu24eta2p1Probe_RelIso03"); histonames.push_back("TriggerEff_IsoTkMu24eta2p1_RelIso03DB"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_IsoTkMu24eta2p1Tag_RelIso03DB"); histonames2.push_back("Trigger_IsoTkMu24eta2p1Probe_RelIso03DB"); histonames.push_back("TriggerEff_Mu50_Pt"); fithisto.push_back(52); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_Mu50Tag_Pt"); histonames2.push_back("Trigger_Mu50Probe_Pt"); histonames.push_back("TriggerEff_Mu50_Eta"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_Mu50Tag_Eta"); histonames2.push_back("Trigger_Mu50Probe_Eta"); histonames.push_back("TriggerEff_Mu50_Phi"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_Mu50Tag_Phi"); histonames2.push_back("Trigger_Mu50Probe_Phi"); histonames.push_back("TriggerEff_Mu50_RelIso03"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_Mu50Tag_RelIso03"); histonames2.push_back("Trigger_Mu50Probe_RelIso03"); histonames.push_back("TriggerEff_Mu50_RelIso03DB"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_Mu50Tag_RelIso03DB"); histonames2.push_back("Trigger_Mu50Probe_RelIso03DB"); histonames.push_back("TriggerEff_Mu45eta2p1_Pt"); fithisto.push_back(47); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_Mu45eta2p1Tag_Pt"); histonames2.push_back("Trigger_Mu45eta2p1Probe_Pt"); histonames.push_back("TriggerEff_Mu45eta2p1_Eta"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_Mu45eta2p1Tag_Eta"); histonames2.push_back("Trigger_Mu45eta2p1Probe_Eta"); histonames.push_back("TriggerEff_Mu45eta2p1_Phi"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_Mu45eta2p1Tag_Phi"); histonames2.push_back("Trigger_Mu45eta2p1Probe_Phi"); histonames.push_back("TriggerEff_Mu45eta2p1_RelIso03"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_Mu45eta2p1Tag_RelIso03"); histonames2.push_back("Trigger_Mu45eta2p1Probe_RelIso03"); histonames.push_back("TriggerEff_Mu45eta2p1_RelIso03DB"); fithisto.push_back(-1); xt.push_back(histonames.back()); yt.push_back("Efficiency"); histonames1.push_back("Trigger_Mu45eta2p1Tag_RelIso03DB"); histonames2.push_back("Trigger_Mu45eta2p1Probe_RelIso03DB"); TString fdataname = (inputdir+"Histos3Trigger_"+whichdata+".root"); if(DCSonly) fdataname = (inputdir+"Histos3TriggerDCS_"+whichdata+".root"); TFile *fdata = TFile::Open(fdataname.Data()); TCanvas *c1 = new TCanvas("c1", "",477,41,750,500); gStyle->SetOptFit(1); gStyle->SetOptStat(0); gStyle->SetOptTitle(0); c1->SetFillColor(0); c1->SetBorderMode(0); c1->SetBorderSize(2); c1->SetTickx(1); c1->SetTicky(1); c1->SetLeftMargin(0.18); c1->SetRightMargin(0.05); c1->SetTopMargin(0.07); c1->SetBottomMargin(0.15); c1->SetFrameFillStyle(0); c1->SetFrameBorderMode(0); c1->SetFrameFillStyle(0); c1->SetFrameBorderMode(0); float scale; for(unsigned int i = 0; i<histonames1.size();++i){ for(unsigned int j = 0; j<7;++j){ string prefix = ""; if(j==1) prefix = "Run251244_"; else if(j==2) prefix = "Run251251_"; else if(j==3) prefix = "Run251252_"; else if(j==4) prefix = "RunPre251561_"; else if(j==5) prefix = "RunAllPre251561_"; else if(j>=6) prefix = "RunAfter251561_"; //if(j==5 && !(histonames1[i]=="TriggerEff_PureIsoMu20_Pt"||histonames1[i]=="TriggerEff_PureIsoMu20_Phi"||histonames1[i]=="TriggerEff_PureIsoMu20_Eta"|| // histonames1[i]=="TriggerEff_IsoTkMu20_Pt" ||histonames1[i]=="TriggerEff_IsoTkMu20_Phi" ||histonames1[i]=="TriggerEff_IsoTkMu20_Eta")) continue; //if(j!=5) continue; string name = prefix + histonames1[i]+"_"+whichdata; TH1F *hdatatag = (TH1F*)fdata->Get(name.c_str()); name = prefix + histonames2[i]+"_"+whichdata; TH1F *hdataprobe = (TH1F*)fdata->Get(name.c_str()); name = prefix + histonames[i]+"_"+whichdata; float xup = hdatatag->GetBinLowEdge(hdatatag->GetNbinsX())+hdatatag->GetBinWidth(hdatatag->GetNbinsX()); TH1F *ht = (TH1F*)hdatatag->Clone("ht"); TH1F *hp = (TH1F*)hdataprobe->Clone("hp"); if(ht->Integral()<=0) continue; TEfficiency *tdataeff = new TEfficiency((*hp),(*ht)); TH1F *hdataeff = new TH1F(name.c_str(),"",hdatatag->GetNbinsX(), hdatatag->GetBinLowEdge(1), xup); //hdataeff->Divide(hdataprobe,hdatatag); //hdataeff->GetYaxis()->SetTitle("Efficiency"); //hdataeff->GetXaxis()->SetTitle(histonames[i].c_str()); hdataeff->GetYaxis()->SetTitle(yt[i].c_str()); hdataeff->GetXaxis()->SetTitle(xt[i].c_str()); hdataeff->Draw(); hdataeff->GetYaxis()->SetRangeUser(0.,1.2); hdataeff->SetMinimum(0.); hdataeff->SetMaximum(1.2); c1->Clear(); c1->cd(); hdataeff->Draw("axis"); tdataeff->Draw("same"); //TGraphAsymmErrors *gdataeff = new TGraphAsymmErrors(); //for(unsigned int i = ) TGraphAsymmErrors *gdataeff = (TGraphAsymmErrors*)tdataeff->CreateGraph(); hdataeff->Draw("axis"); gdataeff->Draw("P"); c1->Update(); string outname = outputdir +whichdata + "/" + prefix+ histonames[i] + ".pdf"; c1->SaveAs(outname.c_str()); if(fithisto[i]>0){ name = name + "_fit"; TF1 *fitfunc = new TF1(name.c_str(),"[0]",fithisto[i],xup); //hdataeff->Fit(fitfunc,"R"); //gdataeff->Fit(fitfunc,"WR"); gdataeff->Fit(fitfunc,"R"); c1->Update(); fitfunc->Draw("same"); outname = outputdir +whichdata + "/" + prefix + histonames[i] + "_fitted.pdf"; c1->SaveAs(outname.c_str()); //std::ostringstream Stream; //Stream << "Fit = " << fitfunc->GetParameter(0); //TString fitnumber = Stream.str().c_str(); //TLatex * tex = new TLatex(0.328859,0.95,fitnumber.Data()); //tex->SetNDC(); //tex->SetTextFont(42); //tex->SetTextSize(0.04181185); //tex->SetLineWidth(2); //tex->Draw(); } } } }
void ootpu_fit(TString files, TString comments="") { TChain* chain = new TChain("reduced_tree"); chain->Add(files); TH1::SetDefaultSumw2(); TH1F* hrelIso = new TH1F("hrelIso","", 30, 0, 0.5); TH1F* hOOTPU = new TH1F("hOOTPU","", 75, 0, 75); TH1F* hOOTPUvsIso = new TH1F("hOOTPUvsIso",";Out-of-time ints.;Isolation cut efficiency", 15, 0, 75); hrelIso->StatOverflows(true); int n1(0), n2(0); if (files.Contains("20bx25")) { n1=15; n2=75; } else if (files.Contains("S14")) { n1=0; n2=120; } else { // default: 8 TeV scenario n1=0; n2=70; } TString mu("num_gen_muons==1&&muon_reco_match>=0"); int low = 15; for (int bin(1); bin<hOOTPUvsIso->GetNbinsX()+1; bin++) { if (bin<4) continue; if (bin>4) low=low+5; if (low>hOOTPUvsIso->GetBinLowEdge(hOOTPUvsIso->GetNbinsX())) break; TString cuts = Form("(%s)&&(oot_pu>=%d&&oot_pu<%d)",mu.Data(),low,low+4); cout << "Cuts: " << cuts.Data() << endl; chain->Project(hrelIso->GetName(), "muon_relIso", cuts); chain->Project(hOOTPU->GetName(), "oot_pu", cuts); hrelIso->Scale(1/hrelIso->GetEntries()); Double_t left(0.), lerror(0.), right(0.), rerror(0.); left = hrelIso->IntegralAndError(1,12,lerror); right = hrelIso->IntegralAndError(13,31,rerror); float rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right))); printf("bin1: %3.2f +/- %3.3f\n", left/(left+right),rat_error); hOOTPUvsIso->SetBinContent(bin,left/(left+right)); hOOTPUvsIso->SetBinError(bin,rat_error); } hOOTPUvsIso->SetLineColor(1); hOOTPUvsIso->SetMarkerColor(1); hOOTPUvsIso->SetMarkerStyle(20); TCanvas* c1 = new TCanvas(); hOOTPUvsIso->Draw("e1"); // do a linear fit TF1 *flin = new TF1("flin", "1 ++ x", 15, 75); hOOTPUvsIso->Fit(flin); flin=hOOTPUvsIso->GetFunction("flin"); flin->SetLineColor(kBlue); flin->SetLineWidth(2); TString plotTitle ="OOTPU_fit"+comments+".pdf"; c1->Print(plotTitle); // cout << "Rejection rates" << endl; // Double_t left(0.), lerror(0.), right(0.), rerror(0.); // left = hA->IntegralAndError(1,12,lerror); // right = hA->IntegralAndError(13,31,rerror); // float rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right))); // printf("bin1: %3.2f +/- %3.3f\n", left/(left+right),rat_error); // left = hB->IntegralAndError(1,12,lerror); // right = hB->IntegralAndError(13,31,rerror); // rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right))); // printf("bin2: %3.2f +/- %3.3f\n", left/(left+right),rat_error); // left = hC->IntegralAndError(1,12,lerror); // right = hC->IntegralAndError(13,31,rerror); // rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right))); // printf("bin3: %3.2f +/- %3.3f\n", left/(left+right),rat_error); // left = hD->IntegralAndError(1,12,lerror); // right = hD->IntegralAndError(13,31,rerror); // rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right))); // printf("bin4: %3.2f +/- %3.3f\n", left/(left+right),rat_error); }
void makeResultTables(std::string decayChannel = "combined", bool extrapolate=true, bool hadron=false, bool addCrossCheckVariables=false, bool useBCC=false, int verbose=1){ // ============================ // Set Root Style // ============================ TStyle myStyle("HHStyle","HHStyle"); setHHStyle(myStyle); TGaxis::SetMaxDigits(2); myStyle.cd(); gROOT->SetStyle("HHStyle"); // ============================ // Open file // ============================ if(extrapolate==true) hadron=false; TString filename="diffXSecTopSemi"; if(decayChannel=="combined") filename+="Lep"; else if(decayChannel=="electron") filename+="Elec"; else if(decayChannel=="muon" ) filename+="Mu"; if(extrapolate) filename+="Parton"; else{ if(hadron) filename+="Hadron"; else filename+="Parton"; filename+="PhaseSpace"; } filename+=".root"; if(verbose>0) std::cout << "opening file " << filename << std::endl; TFile* file = TFile::Open(filename, "READ"); if(!file){ std::cout << "ERROR: can not open file " << filename << std::endl; exit(0); } // dont associate new objects with file to be able to close it in the end gROOT->cd(); // ============================ // Get plots // ============================ // variables to be processed std::vector<TString> xSecVariables_; // a) top and ttbar quantities if(!hadron){ xSecVariables_.insert(xSecVariables_.end(), xSecVariablesKinFit, xSecVariablesKinFit + sizeof(xSecVariablesKinFit)/sizeof(TString)); } // b) lepton and b-jet quantities if(hadron||!extrapolate){ xSecVariables_.insert(xSecVariables_.end(), xSecVariablesFinalState , xSecVariablesFinalState + sizeof(xSecVariablesFinalState )/sizeof(TString)); } // c) cross check variables presently only available for parton level cross-sections if (addCrossCheckVariables && !hadron){ xSecVariables_.insert( xSecVariables_.end(), xSecVariablesCCVar, xSecVariablesCCVar + sizeof(xSecVariablesCCVar )/sizeof(TString) ); xSecVariables_.insert( xSecVariables_.end(), xSecVariablesCCVarNorm, xSecVariablesCCVarNorm + sizeof(xSecVariablesCCVarNorm)/sizeof(TString)); } for(unsigned int i=0; i<xSecVariables_.size(); ++i){ TString plotName=xSecVariables_[i]; if(verbose>0) std::cout << std::endl << "variable: " << plotName << std::endl; // get canvas for chosen cross section TCanvas* canvas = (TCanvas*)(file->Get("finalXSec/"+plotName+"Norm")->Clone()); if(!canvas){ std::cout << "ERROR: can not load canvas finalXSec/"+plotName+"Norm" << std::endl; exit(0); } // GET DATA: with final errors from canvas TGraphAsymmErrors* dataTot = (TGraphAsymmErrors*)canvas->GetPrimitive("dataTotalError"); TGraphAsymmErrors* dataStat = (TGraphAsymmErrors*)canvas->GetPrimitive("dataStatError" ); TH1F* binned = (TH1F*)canvas->GetPrimitive(plotName); TH1F* binnedMCatNLO = (TH1F*)canvas->GetPrimitive(plotName+"MC@NLO"); TH1F* binnedPowheg = (TH1F*)canvas->GetPrimitive(plotName+"POWHEG"); TH1F* binnedPowhegHerwig = (TH1F*)canvas->GetPrimitive(plotName+"POWHEGHERWIG"); TH1F* binnedNNLO = (TH1F*)canvas->GetPrimitive(plotName+"nnlo"); if(!dataTot){ std::cout << "ERROR: can not load TGraphAsymmErrors dataTotalError in canvas finalXSec/"+plotName+"Norm" << std::endl; exit(0); } if(!dataStat){ std::cout << "ERROR: can not load TGraphAsymmErrors dataStatError in canvas finalXSec/"+plotName+"Norm" << std::endl; exit(0); } if(!binned){ std::cout << "ERROR: can not load TH1F topPt in canvas finalXSec/"+plotName << std::endl; exit(0); } // define range of relevant plots // INFO: keep this consistent with the range as defined in setXAxisRange // and makevariableBinning in basicFunctions.h double xMin=-999999999; double xMax= 999999999; if(plotName.Contains ("topPt" )){ xMin=0. ; xMax=401. ;} else if(plotName.Contains("topY" )){ xMin=-2.51; xMax=2.51 ;} else if(plotName.Contains("ttbarY" )){ xMin=-2.51; xMax=2.51 ;} else if(plotName.Contains("ttbarMass")){ xMin=344. ; xMax=1601.;} else if(plotName.Contains("ttbarPt" )){ xMin=0. ; xMax=301. ;} else if(plotName.Contains("lepPt" )){ xMin=29 ; xMax=201. ;} else if(plotName.Contains("lepEta" )){ xMin=-2.11; xMax=2.11 ;} else if(plotName.Contains("bqPt" )){ xMin=29. ; xMax=401. ;} else if(plotName.Contains("bqEta" )){ xMin=-2.41; xMax=2.41 ;} else if(plotName.Contains("bbbarPt" )){ xMin=0. ; xMax=800. ;} else if(plotName.Contains("bbbarMass")){ xMin=0. ; xMax=1200.;} else if(plotName.Contains("ttbarDelPhi" )){ xMin=0. ; xMax=3.16;} else if(plotName.Contains("ttbarPhiStar")){ xMin=0. ; xMax=2.01;} else if(plotName.Contains("lbMass" )){ xMin=0. ; xMax=501.;} else if(plotName.Contains("Njets" )){ xMin=3. ; xMax=10. ;} else if(plotName.Contains("rhos" )){ xMin=0. ; xMax=1.1 ;} // initialize ndof counter int ndof=0; // initialize global chi2 double chi2=0; double chi2Mc=0; double chi2Po=0; double chi2PoHer=0; double chi2NN=0; // loop all bins for(int bin=1; bin<=binned->GetNbinsX(); ++bin){ if(verbose>1) std::cout << "bin #" << bin; // collect information double MCxSec =binned ->GetBinContent(bin); double MCxSecMc=binnedMCatNLO ? binnedMCatNLO->GetBinContent(bin) : 0; double MCxSecPo=binnedPowheg ? binnedPowheg ->GetBinContent(bin) : 0; double MCxSecPoHer=binnedPowhegHerwig ? binnedPowhegHerwig ->GetBinContent(bin) : 0; double MCxSecNN=binnedNNLO ? binnedNNLO ->GetBinContent(bin) : 0; // FIXME: current topY NNLO prediction is shifted by one! make sure this is still the case if you update the new prediction if(plotName.Contains("topY")) MCxSecNN=binnedNNLO ? binnedNNLO->GetBinContent(bin+1) : 0; double xSec=dataTot->GetY()[bin]; double totError=dataTot->GetErrorYhigh(bin); double statError=dataStat->GetErrorYhigh(bin); double sysError=sqrt(totError*totError-statError*statError); double BCCxValue=dataTot->GetX()[bin]; double xValueUp=binned->GetBinLowEdge(bin+1); double xValueDn=binned->GetBinLowEdge(bin); if(verbose>1) std::cout << std::setprecision(2) << std::fixed << ", xvalue: " << BCCxValue << " (" << xValueDn << ".." << xValueUp << ")" << std::endl; // combine information in Latex line style in one TString int precXSec=6; int precErr=1; int precXBCC=2; int precX=1; if(plotName.Contains("Pt")){ precXBCC=1; if(plotName.Contains("Lep" )) precXBCC=2; if(plotName.Contains("ttbar")) precXBCC=0; precX=0; } if(plotName.Contains("Eta")||plotName.Contains("Y")){ precXBCC=3; precX=1; } if(plotName.Contains("Mass")){ precXBCC=1; precX=0; } // if(plotName.Contains("ttbarY")){ // std::cout << std::endl << "xValueDn=" << xValueDn << std::endl; // std::cout << "precX=" << precX << std::endl; // std::cout << "xValueDn +5./(pow(10,precX+1))=" << xValueDn +5./(pow(10,precX +1)) << std::endl; // TString help=getTStringFromDouble(xValueDn +5./(pow(10,precX+1)), precX, true); // std::cout << "rounded number=" << help << std::endl; // } TString out= ""; if(useBCC){ out+=getTStringFromDouble(BCCxValue, precXBCC); out+=" & "; } out+=fillspace(xValueDn, getBigitFromDouble(binned->GetBinLowEdge(binned->GetNbinsX()+1))); out+=getTStringFromDouble(xValueDn, precX); out+=" to "; out+=fillspace(xValueUp, getBigitFromDouble(binned->GetBinLowEdge(binned->GetNbinsX()+1))); out+=getTStringFromDouble(xValueUp, precX); out+=" & "; out+=getTStringFromDouble(MCxSec, precXSec); out+=" & "; out+=getTStringFromDouble(xSec , precXSec); out+=" & "; out+=fillspace(100*(statError/xSec), 2); out+=getTStringFromDouble(100*(statError/xSec), precErr); out+=" & "; out+=fillspace(100*(sysError/xSec), 2); out+=getTStringFromDouble(100*(sysError/xSec ), precErr); out+=" & "; out+=fillspace(100*(totError/xSec), 2); out+=getTStringFromDouble(100*(totError/xSec ), precErr); out+=" \\\\ "; bool append= (bin==1 ? false : true); TString txtfile="./diffXSecFromSignal/plots/"+TString(decayChannel)+"/2012/"+filename; txtfile.ReplaceAll(".root",plotName+".txt"); writeToFile(out, txtfile, append); // chi2 for this distribution if(xValueDn>=xMin&&xValueUp<=xMax){ ++ndof; chi2+= ((std::abs(MCxSec -xSec)/totError)*(std::abs(MCxSec -xSec)/totError)); if(MCxSecMc!=0)chi2Mc+=((std::abs(MCxSecMc-xSec)/totError)*(std::abs(MCxSecMc-xSec)/totError)); if(MCxSecPo!=0)chi2Po+=((std::abs(MCxSecPo-xSec)/totError)*(std::abs(MCxSecPo-xSec)/totError)); if(MCxSecPoHer!=0)chi2PoHer+=((std::abs(MCxSecPoHer-xSec)/totError)*(std::abs(MCxSecPoHer-xSec)/totError)); if(MCxSecNN!=0)chi2NN+=((std::abs(MCxSecNN-xSec)/totError)*(std::abs(MCxSecNN-xSec)/totError)); if(verbose>1) std::cout << "-> considered for chi2" << std::endl; } //std::cout << out << std::endl; //std::cout << BCCxValue << " & " << xValueDn << " to " << xValueUp << " & " << MCxSec << " & " << xSec << " & " << statError/xSec << " & " << sysError/xSec << " & " << totError/xSec << " \\\\ " << std::endl; if(verbose>1){ std::cout << std::setprecision(7) << std::fixed << "data: " << xSec << "+/-" << statError << "+/-" << sysError << std::endl; std::cout << std::setprecision(7) << std::fixed << "MadGraph+Pythia: " << MCxSec; std::cout << std::setprecision(2) << std::fixed << " (" << std::abs(MCxSec -xSec)/totError << " std variations)" << std::endl; if(MCxSecMc!=0){ std::cout << std::setprecision(7) << std::fixed << "MC@NLO+Herwig: " << MCxSecMc; std::cout << std::setprecision(2) << std::fixed << " (" << std::abs(MCxSecMc-xSec)/totError << " std variations)" << std::endl; } if(MCxSecPo!=0){ std::cout << std::setprecision(7) << std::fixed << "Powheg+Pythia: " << MCxSecPo; std::cout << std::setprecision(2) << std::fixed << " (" << std::abs(MCxSecPo-xSec)/totError << " std variations)" << std::endl; } if(MCxSecPoHer!=0){ std::cout << std::setprecision(7) << std::fixed << "Powheg+Herwig: " << MCxSecPoHer; std::cout << std::setprecision(2) << std::fixed << " (" << std::abs(MCxSecPoHer-xSec)/totError << " std variations)" << std::endl; } if(MCxSecNN!=0){ std::cout << std::setprecision(7) << std::fixed << "NNLO: " << MCxSecNN; std::cout << std::setprecision(2) << std::fixed << " (" << std::abs(MCxSecNN-xSec)/totError << " std variations)" << std::endl; } } if(bin==binned->GetNbinsX()&&ndof!=0){ chi2 /=ndof; chi2Mc/=ndof; chi2Po/=ndof; chi2PoHer/=ndof; chi2NN/=ndof; if(verbose>1) std::cout << std::endl; if(chi2 !=0 ){writeToFile("%chi2(MadGraph+Pythia): "+getTStringFromDouble(chi2 ), txtfile, true); if(verbose>0){std::cout << "chi2(MadGraph+Pythia): " << chi2 << std::endl;}} if(chi2Mc!=0 ){writeToFile("%chi2(MC@NLO+Herwig ): "+getTStringFromDouble(chi2Mc ), txtfile, true); if(verbose>0){std::cout << "chi2(MC@NLO+Herwig ): " << chi2Mc << std::endl;}} if(chi2Po!=0 ){writeToFile("%chi2(Powheg+Pythia ): "+getTStringFromDouble(chi2Po ), txtfile, true); if(verbose>0){std::cout << "chi2(Powheg+Pythia ): " << chi2Po << std::endl;}} if(chi2PoHer!=0){writeToFile("%chi2(Powheg+Herwig ): "+getTStringFromDouble(chi2PoHer), txtfile, true); if(verbose>0){std::cout << "chi2(Powheg+Herwig ): " << chi2PoHer << std::endl;}} if(chi2NN!=0 ){writeToFile("%chi2(NNLO/NLO+NNLL ): "+getTStringFromDouble(chi2NN ), txtfile, true); if(verbose>0){std::cout << "chi2(NNLO/NLO+NNLL ): " << chi2NN << std::endl;}} } } } }
void checkFitCBBW(float mass,float width,string channel, string modelName,double Ymax,bool testGeneratedKinematics=0,bool testKinematicsWithoutSelection =0) { float gamma = width*mass; std::ostringstream s; s<< mass; std::string Mass(s.str()); std::ostringstream ss; int temp_width = width*10; ss<<temp_width; std::string swidth(ss.str()); string sMCname = "MC sample, m_{VV}="+Mass+", width=0."+swidth; string suffix ="#"+channel; if(channel.find("mu")==string::npos) { suffix = "e"; } string name= modelName+" #rightarrow "+suffix+", m_{WW} = "+Mass; string soutput_pdf_name = "/usr/users/dschaefer/root/results/testFit/M"+Mass+"/"+modelName+"_M"+Mass+"_"+"width0p"+swidth+"_"+channel+"_matchedJet.pdf"; if(testGeneratedKinematics) { soutput_pdf_name = "/usr/users/dschaefer/root/results/testFit/M"+Mass+"/"+modelName+"_M"+Mass+"_"+"width0p"+swidth+"_"+channel+"_matchedJet_gen.pdf"; } if(testKinematicsWithoutSelection) { soutput_pdf_name = "/usr/users/dschaefer/root/results/testFit/M"+Mass+"/"+modelName+"_M"+Mass+"_"+"width0p"+swidth+"_"+channel+"_withoutSelections.pdf"; } string sfile_narrow; if(mass == 800 or mass ==1600) { sfile_narrow ="/usr/users/dschaefer/root/results/BulkGrav/BulkGrav_M"+Mass+"_width0p0_mWW_"+channel+".root"; if(testKinematicsWithoutSelection) { sfile_narrow ="/usr/users/dschaefer/root/results/BulkGrav/BulkGrav_M"+Mass+"_width0p0_mWW_"+channel+"_withoutSelection.root"; } } else { sfile_narrow ="/usr/users/dschaefer/root/results/Wprime/Wprime_M"+Mass+"_width0p0_mWW_"+channel+".root"; } string sfile_width ="/usr/users/dschaefer/root/results/"+modelName+"/"+modelName+"_M"+Mass+"_width0p"+swidth+"_mWW_"+channel+".root"; if(testGeneratedKinematics) { sfile_width ="/usr/users/dschaefer/root/results/"+modelName+"/"+modelName+"_M"+Mass+"_width0p"+swidth+"_mWW_"+channel+"_gen.root"; } if(testKinematicsWithoutSelection) { sfile_width ="/usr/users/dschaefer/root/results/"+modelName+"/"+modelName+"_M"+Mass+"_width0p"+swidth+"_mWW_"+channel+"_withoutSelection.root"; } const char* file_width = sfile_width.c_str(); const char* file_narrow = sfile_narrow.c_str(); const char* MCname= sMCname.c_str(); const char* title = name.c_str(); const char* output_pdf_name = soutput_pdf_name.c_str(); TFile *f = new TFile(file_width,"READ"); TFile *f_narrow = new TFile(file_narrow,"READ"); TH1F* h = (TH1F*) f->Get("hmWW"); TH1F* h_narrow = (TH1F*) f_narrow->Get("hmWW"); int tmp = h_narrow->GetSize()-2; double massMax_narrow = h_narrow->GetBinLowEdge(h_narrow->GetBin(tmp)); double massMin_narrow = h_narrow->GetBinLowEdge(0); tmp = h->GetSize()-2; double massMax_width = h->GetBinLowEdge(h->GetBin(tmp)); double massMin_width = h->GetBinLowEdge(0); RooRealVar m_narrow("m","m",massMin_narrow, massMax_narrow); RooRealVar m_width("m_w","m_w",massMin_width,massMax_width); float mCBMin; float mCBMax; float sCB; float sCBMin; float sCBMax; float n1; float n1Max; float n1Min; float n2Max; float n2Min; float n2; float alpha1; float alpha11Min; float alpha1Max; float alpha1Min; float alpha2Max; float alpha2Min; float alpha2; if(mass == 800) { sCB =50; sCBMin =40; sCBMax=70; n1 = 15.; n1Min=5.;n1Max =25.; n2 = 15.; n2Min=5.;n2Max =25.; alpha1 =1.5;alpha1Min=1.;alpha1Max=1.9; alpha2 =1.64;alpha2Min=1.;alpha2Max=1.9; } if(mass == 1200) { sCB =50; sCBMin =40; sCBMax=70; n1 = 15.; n1Min=5.;n1Max =25.; n2 = 15.; n2Min=5.;n2Max =25.; alpha1 =1.5;alpha1Min=1.;alpha1Max=1.9; alpha2 =1.64;alpha2Min=1.;alpha2Max=1.9; } if(mass == 2000) { sCB =150; sCBMin =110; sCBMax=175; n1 = 10.; n1Min=0.01;n1Max =35.; n2 = 20; n2Min=0.01;n2Max =35.; alpha1 =1.5;alpha1Min=0.5;alpha1Max=3.; alpha2 =1.5;alpha2Min=0.5;alpha2Max=3.0; } if(mass == 3000) { sCB =150; sCBMin =110; sCBMax=175; n1 = 10.; n1Min=0.01;n1Max =35.; n2 = 20; n2Min=0.01;n2Max =35.; alpha1 =1.5;alpha1Min=0.5;alpha1Max=3.; alpha2 =1.5;alpha2Min=0.5;alpha2Max=3.0; } if(mass==4000) { sCB =200; sCBMin =140; sCBMax=230; n1 = 10.; n1Min=0.01;n1Max =35.; n2 = 20; n2Min=0.01;n2Max =35.; alpha1 =1.5;alpha1Min=0.5;alpha1Max=3.; alpha2 =1.5;alpha2Min=0.5;alpha2Max=3.0; } RooRealVar m_new = m_width; m_new.setBins(1000,"cache"); RooRealVar mean_CB("mean_CB","mean_CB",mass+90,mass-20,mass+100); RooRealVar sigma_CB("sigma_CB","sigma_CB",sCB,sCBMin,sCBMax); RooRealVar n1_CB("n1_CB","n1_CB",n1,n1Min,n1Max); RooRealVar alpha2_CB("alpha2_CB","alpha2_CB",alpha2,alpha2Min,alpha2Max); RooRealVar n2_CB("n2_CB","n2_CB",n2,n2Min,n2Max); RooRealVar alpha1_CB("alpha1_CB","alpha1_CB",alpha1,alpha1Min,alpha1Max); RooRealVar mean_conv("mean_conv","mean_conv",0); RooRealVar width_BW("width_BW","width_BW",gamma); RooDoubleCrystalBall CB("CB","CB",m_narrow,mean_CB,sigma_CB,alpha1_CB,n1_CB,alpha2_CB,n2_CB); RooDataHist dh_narrow("dh_narrow","dh_narrow",m_narrow,Import(*h_narrow)); CB.fitTo(dh_narrow); mean_CB.getVal(); sigma_CB.getVal(); n1_CB.getVal(); n2_CB.getVal(); alpha1_CB.getVal(); alpha2_CB.getVal(); RooBWRunPdf BW("BW","BW",m_new,mean_CB,width_BW); RooDoubleCrystalBall CB_fitted("CB_fitted","CB_fitted",m_new,mean_conv,sigma_CB,alpha1_CB,n1_CB,alpha2_CB,n2_CB); RooDataHist dh("dh","dh",m_width,Import(*h)); RooPlot* frame = m_width.frame(); frame->GetXaxis()->SetTitle("m_{VV} [GeV]"); frame->SetTitle(title); frame->GetYaxis()->SetTitleOffset(1.4); frame->setPadFactor(1); dh.plotOn(frame,"name_dh"); if(testKinematicsWithoutSelection) { RooBWRunPdf BW_withoutSelection("BW_wS","BW_wS",m_width,mean_CB,width_BW); BW_withoutSelection.plotOn(frame,"name_model_pdf"); } else { RooFFTConvPdf model_pdf("conv","conv",m_new,BW,CB_fitted); model_pdf.setBufferFraction(5.0); model_pdf.plotOn(frame,"name_model_pdf"); } //BW.plotOn(frame,MarkerColor(kRed),LineColor(kRed)); //CB.plotOn(frame,MarkerColor(kGreen),LineColor(kGreen)); //model_pdf.fitTo(dh); RooPlot* frame_narrow_fit = m_narrow.frame(); frame_narrow_fit->GetXaxis()->SetTitle("m_{VV} [GeV]"); frame_narrow_fit->SetTitle("Double Crystall Ball"); dh_narrow.plotOn(frame_narrow_fit); CB.plotOn(frame_narrow_fit); TCanvas* canvas1 = new TCanvas("canvas1","canvas1",400,600); gPad->SetLeftMargin(0.15); TPad* pad1 = new TPad("pad1","pad1",0.,0.2,1.,1.0); TPad* pad2 = new TPad("pad2","pad2",0.,0.,1.0,0.2); pad1->SetLeftMargin(0.15); pad2->SetLeftMargin(0.15); pad1->Draw(); pad2->Draw(); pad1->cd(); frame->GetYaxis()->SetTitleOffset(2.0); //double Ymax = 400; frame->SetMaximum(Ymax); frame->Draw(); TString dh_name = frame->nameOf(0); TString model_pdf_name = frame->nameOf(1); TLegend* leg = new TLegend(0.48,0.89,0.89,0.8);//0.48,0.89,0.9,0.8) leg->SetBorderSize(0); leg->SetFillColor(0); leg->AddEntry(frame->findObject(dh_name),MCname,"lep"); if(testKinematicsWithoutSelection) { leg->AddEntry(frame->findObject(model_pdf_name),"Breit-Wigner ","L"); } else { leg->AddEntry(frame->findObject(model_pdf_name),"(CB*BW)(m) ","L"); } leg->Draw(); double chi2 = frame->chiSquare(); string schi2 = "X^{2} ="+std::to_string(chi2); const char* textChi2 = schi2.c_str(); TLatex text; text.SetTextFont(43); text.SetTextSize(16); text.DrawLatex(massMin_width+(massMax_width-massMin_width)/10.,Ymax-Ymax/10.,textChi2); RooPlot* frame2 = m_width.frame(); frame2->addObject(frame->pullHist()); frame2->SetMinimum(-25); frame2->SetMaximum(15); frame2->SetTitle("pulls"); pad2->cd(); frame2->Draw(); canvas1->SaveAs(output_pdf_name); TCanvas* canvas2 = new TCanvas("canvas2","canvas2",400,400); canvas2->cd(); frame_narrow_fit->Draw(); }
void SPEFit(char * fLEDname, char * fPEDname, int run, int LED_amp, double cutmax = 250.0) { //set plotting styles gStyle->SetCanvasColor(0); gStyle->SetPadColor(0); gStyle->SetCanvasBorderMode(0); gStyle->SetFrameBorderMode(0); gStyle->SetStatColor(0); gStyle->SetPadTickX(1); gStyle->SetPadTickY(1); //set file names stringstream out_fname; stringstream out_fname1; out_fname<<"SPEconstants_Run_"<<run<<".txt"; out_fname1<<"SPEspec_Run_"<<run<<".txt"; ofstream constants_file(out_fname.str().c_str(),ios_base::trunc); //ofstream constants_file1(out_fname1.str().c_str(),ios_base::trunc); constants_file<<"Run "<<run<<endl; constants_file<<"type SPE"<<endl; constants_file<<"LED_amplitude "<<LED_amp<<endl<<endl; constants_file<<endl<<"LED_amplitude Depth Phi Eta Ped_mean Ped_mean_err Ped_RMS Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl; out_fname.str(""); out_fname<<"SPEdistributions_Run_"<<run<<".txt"; out_fname.str(""); out_fname<<"SPEextra_Run_"<<run<<".txt"; //ofstream extra_file(out_fname.str().c_str(),ios_base::trunc); double scale = 1.0; scale = 2.6; //Need to scale up HF charge double fC2electrons = 6240.; //convert fC to #electrons char spename[128], pedname[128], spehistname[128]; TFile *tfLED = new TFile(fLEDname); TFile *tfPED = new TFile(fPEDname); //const int NnewBins = 106; //double binsX[NnewBins] = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500}; const int NnewBins = 80; double binsX[NnewBins] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,114,117,120,123,126,129,132,135,138,141,144,147,150,153,156,159,162,165,168,171,174,177,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500}; TH1F* hspe = new TH1F("hspe","hspe",NnewBins-1,binsX); int NDepth = 2; //number of depths int MinDepth = 1; int MaxDepth = 2; int MinEta = 29; int MaxEta = 41; int MinPhi = 41; int MaxPhi = 53; TCanvas *Carray[NDepth+1][MaxPhi+1]; bool drawflag[NDepth+1][MaxPhi+1]; TH1F *LED[NDepth+1][MaxEta+1][MaxPhi+1]; TH1F *PED[NDepth+1][MaxEta+1][MaxPhi+1]; for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){ for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){ bool nonNull = false; for(int iEta = MinEta; iEta <= MaxEta; iEta++){ sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi); LED[iDepth][iEta][iPhi]=(TH1F *)tfLED->Get(spename); if(LED[iDepth][iEta][iPhi]) nonNull = true; sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi); PED[iDepth][iEta][iPhi]=(TH1F *)tfPED->Get(spename); } drawflag[iDepth][iPhi] = false; char canvname[16]; sprintf(canvname, "c_%d_%d", iDepth,iPhi); if(nonNull){ //only create canvas if distributions exist Carray[iDepth][iPhi] = new TCanvas(canvname,canvname,1200,700); Carray[iDepth][iPhi]->Divide(5,3); } } } int HV=0; for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){ for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){ for(int iEta = MinEta; iEta <= MaxEta; iEta++){ //cout<<iDepth<<" "<<iPhi<<" "<<iEta<<endl; if(!LED[iDepth][iEta][iPhi]) continue; sprintf(spehistname,"led %d %d %d",iDepth,iEta,iPhi); TH1F *hspe_temp = (TH1F *)LED[iDepth][iEta][iPhi]->Clone(spehistname); sprintf(spehistname,"ped %d %d %d",iDepth,iEta,iPhi); TH1F *hped = (TH1F *)PED[iDepth][iEta][iPhi]->Clone(spehistname); hspe->Reset(); sprintf (spehistname, "SumLED_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi); hspe->SetTitle(spehistname); //combine bins of original SPE histogram for(int ib=1; ib<=hspe_temp->GetNbinsX(); ib++) { double bin_center = hspe_temp->GetBinCenter(ib); if(bin_center>hspe->GetXaxis()->GetXmax()) continue; int newbin = hspe->FindBin(bin_center); double new_content = hspe->GetBinContent(newbin) + hspe_temp->GetBinContent(ib); double new_error = sqrt(pow(hspe->GetBinError(newbin),2)+pow(hspe_temp->GetBinError(ib),2)); hspe->SetBinContent(newbin,new_content); hspe->SetBinError(newbin,new_error); } TH1F* hspe_unscaled = (TH1F*)hspe->Clone("hspe_unscaled"); //renormalize bins of new SPE histogram for(int ib=1; ib<=hspe->GetNbinsX(); ib++) { double new_content = hspe->GetBinContent(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1); double new_error = hspe->GetBinError(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1); hspe->SetBinContent(ib,new_content); hspe->SetBinError(ib,new_error); } if(hspe_temp->Integral()==0) continue; else drawflag[iDepth][iPhi] = true; Nev = hspe_temp->Integral()*hspe_temp->GetXaxis()->GetBinWidth(1); TF1 *fped = new TF1("fped","gaus",0, 80); hped->Fit(fped,"NQR"); double pploc = fped->GetParameter(1), ppwidth = fped->GetParameter(2); hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + ppwidth); //estimate SPE peak location int max_SPE_bin, maxbin, Nbins; double max_SPE_height=0, minheight, max_SPE_location; bool minflag = false; maxbin=hspe->FindBin(fped->GetParameter(1)); //location of pedestal peak minheight=hspe->GetBinContent(maxbin); //initialize minheight Nbins = hspe->GetNbinsX(); for(int j=maxbin+1; j<Nbins-1; j++) { //start from pedestal peak and loop through bins if(hspe->GetBinContent(j) > minheight && !minflag) minflag=true; //only look for SPE peak when minflag=true if(hspe->GetBinContent(j) < minheight ) minheight = hspe->GetBinContent(j); if(minflag && hspe->GetBinContent(j) > max_SPE_height){ max_SPE_bin = j; max_SPE_location = hspe->GetBinCenter(max_SPE_bin); max_SPE_height = hspe->GetBinContent(j); } } //start from pedestal peak and loop through bins //find minimum bin between pedestal and SPE peaks hspe->GetXaxis()->SetRange(maxbin,max_SPE_bin); int minbin = hspe->GetMinimumBin(); double minbin_location = hspe->GetBinCenter(minbin); hspe->GetXaxis()->SetRange(1,Nbins); TF1 *fit = new TF1("fit", FitFun, 0, 500, 5); double mu = - log(fped->Integral(0,100)/Nev); if(mu<0) mu=0.01; double gain_est = max_SPE_location-1.0*fped->GetParameter(1); if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, 20, 1, gain_est, gain_est*0.5); else fit->SetParameters(mu, 20, 1, 2.1*fped->GetParameter(2), 10); //case of no clear minimum; start looking for SPE peak at 2sigma away from pedestal peak fit->SetParLimits(0, 0, 10); fit->FixParameter(1, fped->GetParameter(1)); fit->FixParameter(2, fped->GetParameter(2)); fit->SetParLimits(3, fped->GetParameter(2)*2, 350); fit->SetParLimits(4, fped->GetParameter(2)*1.01, 250); double maxfitrange = 500.; double minfitrange = 0.; hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange); maxfitrange = fped->GetParameter(1)+4*fit->GetParameter(3)+fit->GetParameter(4); if(500<maxfitrange) maxfitrange = 500; hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange); //calculate NDOF of fit excluding bins with 0 entries int myNDOF=-3; //three free parameters for(int j=hspe->FindBin(minfitrange); j<=hspe->FindBin(maxfitrange); j++) { //loop through fitted spe bins if(hspe->GetBinContent(j)) myNDOF++; } //loop through fitted spe bins //calculate means and integrals of the fit and data double fint, fint_error, hint, favg, havg; int temp_lowbin, temp_highbin; temp_lowbin = hspe->FindBin(minfitrange); temp_highbin = hspe->FindBin(maxfitrange); hspe_unscaled->GetXaxis()->SetRangeUser(minfitrange, maxfitrange); havg = hspe_unscaled->GetMean(); hint = hspe->Integral(temp_lowbin,temp_highbin,"width"); double min_frange = hspe->GetBinLowEdge(temp_lowbin); favg = fit->Mean(min_frange, maxfitrange); fint = fit->Integral(min_frange, maxfitrange); //fint_error = fit->IntegralError(min_frange, maxfitrange); double PE5int = 0; //integral of events with >=5 PE double PE5loc = fped->GetParameter(1)+ 5*fit->GetParameter(3); if(PE5loc>500) PE5int = 0; else { int PE5bin = hspe_temp->FindBin(PE5loc); temp_highbin = hspe_temp->FindBin(maxfitrange)-1; PE5int = hspe_temp->Integral(PE5bin,temp_highbin,"width"); } int PE5flag = 0; if(PE5int/hint>0.05) PE5flag = 1; //set flag if more than 5% of events in the fit correspond to >=5PE //========================================= //for(int i1=1;i1<hspe->GetNbinsX();i1++){ //constants_file1<<HV<<"\t"<<iDepth<<"\t"<<iEta<<"\t"<<iPhi<<"\t"<<2.6*hspe->GetBinCenter(i1)<<"\t"<<hspe->GetBinContent(i1)<<"\t"<<fit->Eval(hspe->GetBinCenter(i1))<<"\n"; //} //========================================= //printf("%d\n",myNDOF); //output calibrations constants //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl; constants_file<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl; /* if(iDepth==2 && iPhi==53 && iEta==36){ cout<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<gain_est<<" "<<fit->GetParameter(3)<<endl; cout<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl; } */ Carray[iDepth][iPhi]->cd(iEta-MinEta+1); gPad->SetBorderMode(0); gPad->SetBorderSize(0); gPad->SetRightMargin(0.01); gPad->SetBottomMargin(0.1); gPad->SetLogy(true); hspe->GetXaxis()->SetRangeUser(0, 200 /*300*//*508*/); hspe->SetLineColor(kBlue); hspe->DrawClone("hist"); fit->SetLineWidth(2); fit->Draw("same"); } if(drawflag[iDepth][iPhi]) { //draw plots of fit if data for the HV is present stringstream plot_name; plot_name<<"Plots/SPEFits_Run_"<<run<<"_Depth"<<iDepth<<"_Phi"<<iPhi<<".pdf"; Carray[iDepth][iPhi]->SaveAs(plot_name.str().c_str()); plot_name.str( std::string() ); } } } constants_file.close(); //constants_file1.close(); }
void drawpdgstack(std::string const & which_pdg, std::string const & cname, std::string const & dr, std::string const & binning, std::string const & we = "", std::string const & op = "", std::string const & title = "", std::string const & xtitle = "", std::string const & ytitle = "", bool const pdg_sign = true) { ofile->cd(); TH1F * hist = getpdgs(which_pdg.c_str(), we); if(!hist) { std::cout << "drawpdgstack: Empty pdg hist for \"" << which_pdg << "\" with selection \"" << we << "\"\n"; return; } THStack * stack = new THStack("stack", ""); TLegend * legend = new TLegend(0.6, 0.9, 0.9, 0.6); double sig_evtsppot = 0; if(tree2) { TString draw_str = ""; draw_str += dr; draw_str += ">>h_sig"; draw_str += binning; TCanvas * canvas_pdg_temp = new TCanvas("temp"); tree2->Draw(draw_str.Data(), we.c_str(), op.c_str()); delete canvas_pdg_temp; TH1F * hist_sig = (TH1F*)gDirectory->Get("h_sig"); hist_sig->SetLineColor(1); hist_sig->SetFillColor(kRed+3); hist_sig->Scale(1. / signal_pot * run_pot); stack->Add(hist_sig); legend->AddEntry(hist_sig, ("Signal: "+to_string_with_precision(hist_sig->Integral())).c_str()); sig_evtsppot = hist_sig->Integral(); } legend->SetHeader(("Total: "+to_string_with_precision((hist->Integral()/background_pot*run_pot + sig_evtsppot))).c_str()); ((TLegendEntry*)legend->GetListOfPrimitives()->First())->SetTextAlign(22); std::vector<int> pdg_vec; for(int i = 1; i <= hist->GetNbinsX(); ++i) { if(hist->GetBinContent(i) == 0) continue; int const pdg = i+hist->GetBinLowEdge(0); if(!pdg_sign) { if(std::find(pdg_vec.begin(), pdg_vec.end(), abs(pdg)) != pdg_vec.end()) continue; pdg_vec.push_back(abs(pdg)); } TString hname = ""; hname += "h_"; hname += pdg; TString draw_str = ""; draw_str += dr; draw_str += ">>h_"; draw_str += pdg; draw_str += binning; TString weight_str = ""; weight_str += we; weight_str += "&&("; weight_str += which_pdg; weight_str += "=="; weight_str += pdg; if(!pdg_sign && pdg < 0) { weight_str += "||"; weight_str += which_pdg; weight_str += "=="; weight_str += abs(pdg); } weight_str += ")"; TCanvas * canvas_pdg_temp = new TCanvas("temp"); tree->Draw(draw_str.Data(), weight_str.Data(), op.c_str()); delete canvas_pdg_temp; int pdg_temp = pdg; if(!pdg_sign) pdg_temp = abs(pdg); pdg_stuff const & pdg_s = get_pdg_stuff(pdg_temp, pdg_sign); TH1F * hist_pdg = (TH1F*)gDirectory->Get(hname.Data()); hist_pdg->SetLineColor(1); hist_pdg->SetFillColor(pdg_s._color); hist_pdg->Scale(1. / background_pot * run_pot); stack->Add(hist_pdg); legend->AddEntry(hist_pdg, (pdg_s._particle_name+": "+to_string_with_precision(hist_pdg->Integral())).c_str()); } TCanvas * canvas = new TCanvas(cname.c_str()); stack->Draw(); stack->SetTitle(title.c_str()); stack->GetXaxis()->SetTitle(xtitle.c_str()); stack->GetXaxis()->CenterTitle(); stack->GetYaxis()->SetTitle(ytitle.c_str()); stack->GetYaxis()->CenterTitle(); legend->Draw(); canvas->Write(); delete stack; delete legend; delete canvas; delete hist; }