// ----------------------------------------------------------------------------- // TH1* getHisto( TString path, TString nameHist, TString nameFile, TString Dirname, int rebin ) { TString name = path + nameFile; TFile* file = new TFile(name); // file->ls(); TDirectory* dir = (TDirectory*)file->Get(Dirname); // dir->ls(); if( !dir) { std::cout << " dir " << Dirname << std::endl; } TH1* hist = (TH1*)dir->Get(nameHist); if (!hist) { std::cout << " name: " << nameHist << " file: " << nameFile << " dir: " << Dirname << std::endl; abort(); } hist->SetLineWidth(1); if ( rebin > 0 ) { hist->Rebin(rebin); } hist->GetXaxis()->SetTitleSize(0.055); hist->GetYaxis()->SetTitleSize(0.055); hist->GetXaxis()->SetLabelSize(0.05); hist->GetYaxis()->SetLabelSize(0.05); hist->SetStats(kFALSE); return hist; }
void showGraph(double canvasSizeX, double canvasSizeY, TGraph* graph, bool useLogScaleX, double xMin, double xMax, const std::string& xAxisTitle, double xAxisOffset, bool useLogScaleY, double yMin, double yMax, const std::string& yAxisTitle, double yAxisOffset, const std::string& outputFileName) { TCanvas* canvas = new TCanvas("canvas", "canvas", canvasSizeX, canvasSizeY); canvas->SetFillColor(10); canvas->SetBorderSize(2); canvas->SetTopMargin(0.05); canvas->SetLeftMargin(0.19); canvas->SetBottomMargin(0.19); canvas->SetRightMargin(0.05); canvas->SetLogx(useLogScaleX); canvas->SetLogy(useLogScaleY); TH1* dummyHistogram = new TH1D("dummyHistogram", "dummyHistogram", 10, xMin, xMax); dummyHistogram->SetTitle(""); dummyHistogram->SetStats(false); dummyHistogram->SetMinimum(yMin); dummyHistogram->SetMaximum(yMax); dummyHistogram->Draw("axis"); TAxis* xAxis = dummyHistogram->GetXaxis(); xAxis->SetTitle(xAxisTitle.data()); xAxis->SetTitleOffset(xAxisOffset); xAxis->SetTitleSize(0.065); xAxis->SetLabelSize(0.055); xAxis->SetLabelOffset(0.01); xAxis->SetTickLength(0.055); xAxis->SetNdivisions(505); TAxis* yAxis = dummyHistogram->GetYaxis(); yAxis->SetTitle(yAxisTitle.data()); yAxis->SetTitleOffset(yAxisOffset); yAxis->SetTitleSize(0.070); yAxis->SetLabelSize(0.055); yAxis->SetLabelOffset(0.01); yAxis->SetTickLength(0.055); yAxis->SetNdivisions(505); graph->SetMarkerColor(1); graph->SetLineColor(1); graph->Draw("p"); canvas->Update(); size_t idx = outputFileName.find_last_of('.'); std::string outputFileName_plot = std::string(outputFileName, 0, idx); if ( useLogScaleY ) outputFileName_plot.append("_log"); else outputFileName_plot.append("_linear"); if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName, idx)).data()); canvas->Print(std::string(outputFileName_plot).append(".png").data()); //canvas->Print(std::string(outputFileName_plot).append(".pdf").data()); //canvas->Print(std::string(outputFileName_plot).append(".root").data()); delete dummyHistogram; delete canvas; }
void evtime() { vector<int> runs; vector<int> marks; vector<int> mcols; runs.push_back(13893); marks.push_back(2); mcols.push_back(2); runs.push_back(14009); marks.push_back(24); mcols.push_back(4); runs.push_back(14085); marks.push_back(25); mcols.push_back(3); runs.push_back(14234); marks.push_back(5); mcols.push_back(3); runs.push_back(14434); marks.push_back(28); mcols.push_back(3); string pre = "run"; string suf = "evt.root"; double tmax = 160; double emax = 180; new TCanvas; TH1* ph = new TH2F("hevtime", "Event vs. time; Time [sec]; Event", tmax, 0, tmax, emax, 0, emax); ph->SetStats(0); ph->Draw("axis"); TLegend* pleg = new TLegend(0.65,0.15,0.85,0.37); pleg->SetBorderSize(0); for ( unsigned int isam=0; isam<runs.size(); ++isam ) { int run = runs[isam]; int icol = dsindex(run); int col = colormap(icol); ostringstream ssrun; ssrun << run; string srun = ssrun.str(); ostringstream sst0; sst0 << t0map(run); string fname = pre + srun + suf; TFile* pfile = TFile::Open(fname.c_str(), "READ"); TTree* ptree = dynamic_cast<TTree*>(pfile->Get("DXDisplay/EventTree")); ptree->SetMarkerStyle(marks[isam]); ptree->SetMarkerColor(col); cout << run << " " << col << " " << sst0.str() << endl; if ( ptree == 0 ) { cout << "Tree not found" << endl; pfile->ls(); return; } string sarg = "event:tlo-"; sarg += sst0.str(); sarg += ">>hevtime"; ptree->Draw(sarg.c_str(), "", "same"); pleg->AddEntry(ptree, srun.c_str(), "p"); } pleg->Draw(); }
// ----------------------------------------------------------------------------- // TH1* getHisto( std::string nameFile, std::string nameHist, std::string Dirname, int rebin ) { std::string name = nameFile; TFile* file = new TFile(name.c_str()); if (file) { std::cout << "Opened file: " << file->GetName() << std::endl; } else { std::cout << "Could not find file: " << name << std::endl; return 0; } TDirectory* dir = (TDirectory*)file->Get(Dirname.c_str()); if (dir) { std::cout << "Opened dir: " << dir->GetName() << std::endl; } else { std::cout << "Could not find dir: " << Dirname << std::endl; return 0; } int low = 375; TH1* hist = 0; if ( false || nameHist.find("HtMultiplicity_HT375") == std::string::npos ) { hist = (TH1*)dir->Get(nameHist.c_str()); } else { for ( uint ii = low; ii <= 975; ii+=100 ) { std::stringstream tmp; tmp << "HtMultiplicity_HT" << ii << nameHist.substr(20); if ( !hist ) { dir->cd(); TH1D* temp = (TH1D*)dir->Get( "HtMultiplicity_HT375_aT0" ); //TH1D* temp = (TH1D*)file->Get( tmp.str().c_str() ); if (temp) { hist = (TH1D*)temp->Clone(); } else { std::cout << "1 Unable to retrieve histo with name " << tmp.str() << std::endl; } } else { dir->cd(); TH1D* temp = (TH1D*)dir->Get( tmp.str().c_str() ); if (temp) { hist->Add( (TH1D*)temp ); } else { std::cout << "2 Unable to retrieve histo with name " << tmp.str() << std::endl; } } } } if (hist) { std::cout << "Opened histo: " << hist->GetName() << std::endl; } else { std::cout << "Could not find histo: " << nameHist << std::endl; return 0; } hist->SetLineWidth(3); if ( rebin > 0 ) { hist->Rebin(rebin); } hist->GetXaxis()->SetTitleSize(0.055); hist->GetYaxis()->SetTitleSize(0.055); hist->GetXaxis()->SetLabelSize(0.05); hist->GetYaxis()->SetLabelSize(0.05); hist->SetStats(kFALSE); return hist; }
Double_t fitgp0( char* hs ) { TH1 *h = (TH1*)gDirectory->Get(hs); if( h == NULL ){ cout << hs << " does not exist\n"; return 0; } h->SetMarkerStyle(21); h->SetMarkerSize(0.8); h->SetStats(1); gStyle->SetOptFit(101); gROOT->ForceStyle(); double dx = h->GetBinWidth(1); double nmax = h->GetBinContent(h->GetMaximumBin()); double xmax = h->GetBinCenter(h->GetMaximumBin()); double nn = 7*nmax; int nb = h->GetNbinsX(); double n1 = h->GetBinContent(1); double n9 = h->GetBinContent(nb); double bg = 0.5*(n1+n9); double x1 = h->GetBinCenter(1); double x9 = h->GetBinCenter(nb); // create a TF1 with the range from x1 to x9 and 4 parameters TF1 *gp0Fcn = new TF1( "gp0Fcn", gp0Fit, x1, x9, 4 ); gp0Fcn->SetParName( 0, "mean" ); gp0Fcn->SetParName( 1, "sigma" ); gp0Fcn->SetParName( 2, "area" ); gp0Fcn->SetParName( 3, "BG" ); gp0Fcn->SetNpx(500); gp0Fcn->SetLineWidth(4); gp0Fcn->SetLineColor(kMagenta); gp0Fcn->SetLineColor(kGreen); // set start values for some parameters: gp0Fcn->SetParameter( 0, xmax ); // peak position gp0Fcn->SetParameter( 1, 4*dx ); // width gp0Fcn->SetParameter( 2, nn ); // N gp0Fcn->SetParameter( 3, bg ); // N: not drawing // Q: quiet // R: use specified range h->Fit( "gp0Fcn", "NQR", "ep" ); return gp0Fcn->GetParameter(1); }
void DrawHijing2GeV() { TCanvas *c1 = new TCanvas(); TFile *fin = TFile::Open("Gamma_Neutron_Hijing_Energy_Graphs.root"); gROOT->cd(); TH1 *h1lim = new TH1F("h1lim","",1,0,0.1); TH1 *hjbkg = (TH1 *) fin->Get("hjbkg")->Clone(); TGraph *anti_neutron2GeV = (TGraph *) fin->Get("anti_neutron2GeV")->Clone(); TGraph *neutron2GeV = (TGraph *) fin->Get("neutron2GeV")->Clone(); h1lim->SetStats(0); h1lim->SetMaximum(0.3); h1lim->SetTitle("2 GeV Hadronic Showers with HIJING background"); h1lim->GetYaxis()->SetTitle("Deposited Energey [GeV]"); h1lim->GetYaxis()->SetTitleOffset(1.2); h1lim->GetXaxis()->SetTitle("cone size (#sqrt{#Delta#Phi^{2}+#Delta#Theta^{2}})"); h1lim->GetXaxis()->SetTitleOffset(1.2); h1lim->Draw(); hjbkg->SetStats(0); hjbkg->SetLineColor(6); hjbkg->SetMaximum(5.5); hjbkg->SetLineWidth(2); hjbkg->Draw("same"); anti_neutron2GeV->SetLineColor(4); anti_neutron2GeV->SetLineWidth(2); anti_neutron2GeV->Draw("same"); neutron2GeV->SetLineColor(2); neutron2GeV->SetLineWidth(2); neutron2GeV->Draw("same"); TLine *tl = new TLine(); tl->SetLineStyle(2); tl->DrawLine(0.024,0,0.024,0.3); TLegend *legrda = new TLegend(0.67,0.34,0.87,0.54,NULL,"brNDC"); legrda->SetLineColor(1); legrda->SetLineStyle(1); legrda->SetLineWidth(1); legrda->SetFillColor(10); legrda->SetFillStyle(1001); legrda->SetBorderSize(0); // legrda->SetTextSize(labelsize); legrda->AddEntry(hjbkg,"HIJING bkg"); legrda->AddEntry(anti_neutron2GeV,"2 GeV Anti Neutron","l"); legrda->AddEntry(neutron2GeV,"2 GeV Neutron", "l"); legrda->AddEntry(tl,"EMCal tower size","l"); legrda->Draw(); fin->Close(); c1->Print("Hijing2GeV.png"); }
void histogramStyle(TH1& hist, int color, int lineStyle, int markerStyle, float markersize, int filled) { hist.SetLineWidth(3); hist.SetStats(kFALSE); hist.SetLineColor (color); hist.SetMarkerColor(color); hist.SetMarkerStyle(markerStyle); hist.SetMarkerSize(markersize); hist.SetLineStyle(lineStyle); if(filled==1){ hist.SetFillStyle(1001); hist.SetFillColor(color); } else{ hist.SetFillStyle(0); } }
void TestShaping(int max=4) { TArrayI adcs(10); TGraph* orig = new TGraph(adcs.fN); orig->SetName("Original"); orig->SetTitle("Original"); orig->SetMarkerStyle(25); orig->SetMarkerColor(1); orig->SetMarkerSize(2); orig->SetLineColor(1); for (Int_t i = 0; i < adcs.fN; i++) { adcs.fArray[i] = Int_t(gRandom->Uniform(0, 1023)); orig->SetPoint(i, i, adcs.fArray[i]); } TCanvas* c = new TCanvas("c", "c"); c->SetFillColor(0); c->SetTopMargin(.02); c->SetRightMargin(.02); TH1* h = new TH1F("frame","frame", adcs.fN+1, -2, adcs.fN); h->SetMinimum(0); h->SetMaximum(1300); h->SetStats(0); h->Draw(""); orig->Draw("pl same"); TLegend* l = new TLegend(adcs.fN*3./4, 1023, adcs.fN, 1300, "", ""); l->SetFillColor(0); l->SetBorderSize(1); l->AddEntry(orig, orig->GetTitle(), "lp"); for (int i = 1; i <= max; i++) { TGraph* g = makeGraph(adcs, i); g->Draw("pl same"); l->AddEntry(g, g->GetTitle(), "lp"); } l->Draw(); c->Modified(); c->Update(); c->cd(); }
TH1* getMonitorElement(TFile* inputFile, const TString& dqmDirectory, const char* dqmSubDirectory, const TString& meName) { TString meName_full = TString("DQMData").Append("/"); if ( dqmDirectory != "") meName_full.Append(dqmDirectory).Append("/"); meName_full.Append(dqmSubDirectory).Append("/").Append(meName); std::cout << "meName_full = " << meName_full << std::endl; TH1* me = (TH1*)inputFile->Get(meName_full); std::cout << "me = " << me << std::endl; //if ( !me->GetSumw2() ) me->Sumw2(); me->Sumw2(); me->Rebin(2); me->Scale(1./me->Integral()); me->SetMaximum(1.); me->SetStats(false); return me; }
Int_t VisualizeSurface() { std::string gfname; std::cout << "\nFor the graph "; ListAllFilesInDirOfType (".",".root"); std::cout << "\nEnter filename : "; std::getline(std::cin, gfname); TGraphErrors* mygr = GetGraph(gfname); mygr->SetMarkerColor(kRed); mygr->SetLineColor(kRed); mygr->SetMarkerStyle(20); std::string parfname = GetParamFile(); std::ifstream pfile(parfname.data()); Parameters params(pfile); if (! params.KeysAreSensible()) return -1; AngDistC W(params, 1, ELECTRIC); std::cout << params << std::endl; TGraph* gr = new TGraph(mygr->GetN()); gr->SetMarkerColor(kBlue); gr->SetLineColor(kBlue); gr->SetMarkerStyle(20); Double_t num, denom; Double_t ratio; Double_t x[2]; for (UInt_t i=0; i<mygr->GetN(); i++) { x[0] = mygr->GetX()[i]; x[1] = 0; num = W(x); x[1] = TMath::Pi()/2.; denom = W(x); ratio = num/denom; gr->SetPoint(i, mygr->GetX()[i], TMath::Abs(ratio)); } std::cout << "\n Phase2ChiSqC setup completed " << std::endl; TPaveText* pt = new TPaveText(0.5, 0.75, 0.8, 0.95); std::ostringstream os("", std::ios::out|std::ios::app); os << "a = " << params[0]->GetValue(); pt->AddText(os.str().data()); os.str("b = "); os << params[1]->GetValue(); pt->AddText(os.str().data()); os.str("c = "); os << params[2]->GetValue(); pt->AddText(os.str().data()); os.str("d = "); os << params[3]->GetValue(); pt->AddText(os.str().data()); TH1* h = new TH2D("Ratio Comparison", "", 10, -1,1, 500, 0,100); h->SetStats(0); TCanvas* c = new TCanvas("c"); h->Draw(); gr->Draw("LP"); mygr->Draw("LP"); gPad->Modified(); c->Update(); TLegend *leg = new TLegend(0.5, 0.75, 0.8, 0.95); leg->AddEntry(gr, "Fit", "PL"); leg->AddEntry(mygr, "Data", "PL"); leg->Draw(); return 0; }
void makePlot(TCanvas* canvas, const std::string& outputFileName, TTree* testTree, const std::string& varName, unsigned numBinsX, double xMin, double xMax) { std::cout << "creating histogramTauIdPassed..." << std::endl; TString histogramTauIdPassedName = TString("histogramTauIdPassed").Append("_").Append(varName.data()); TH1* histogramTauIdPassed = fillHistogram(testTree, varName, "type==1", "", histogramTauIdPassedName.Data(), numBinsX, xMin, xMax); std::cout << "--> histogramTauIdPassed = " << histogramTauIdPassed << ":" << " integral = " << histogramTauIdPassed->Integral() << std::endl; std::cout << "creating histogramTauIdFailed..." << std::endl; TString histogramTauIdFailedName = TString("histogramTauIdFailed").Append("_").Append(varName.data()); TH1* histogramTauIdFailed = fillHistogram(testTree, varName, "type==0", "", histogramTauIdFailedName.Data(), numBinsX, xMin, xMax); std::cout << "--> histogramTauIdFailed = " << histogramTauIdFailed << " integral = " << histogramTauIdFailed->Integral() << std::endl; std::cout << "creating histogramTauIdDenominator..." << std::endl; TString histogramTauIdDenominatorName = TString("histogramTauIdDenominator").Append("_").Append(varName.data()); TH1* histogramTauIdDenominator = new TH1F(histogramTauIdDenominatorName.Data(), histogramTauIdDenominatorName.Data(), numBinsX, xMin, xMax); histogramTauIdDenominator->Add(histogramTauIdPassed); histogramTauIdDenominator->Add(histogramTauIdFailed); std::cout << "--> histogramTauIdDenominator = " << histogramTauIdDenominator << " integral = " << histogramTauIdDenominator->Integral() << std::endl; std::cout << "creating histogramFakeRate..." << std::endl; TString histogramFakeRateName = TString("histogramFakeRate").Append("_").Append(varName.data()); TH1* histogramFakeRate = new TH1F(histogramFakeRateName.Data(), histogramFakeRateName.Data(), numBinsX, xMin, xMax); histogramFakeRate->Add(histogramTauIdPassed); histogramFakeRate->Divide(histogramTauIdDenominator); std::cout << "--> histogramFakeRate = " << histogramFakeRate << " integral = " << histogramFakeRate->Integral() << std::endl; std::cout << "creating histogramFakeRateWeighted..." << std::endl; TString histogramFakeRateWeightedName = TString("histogramFakeRateWeighted").Append("_").Append(varName.data()); TH1* histogramFakeRateWeighted = fillHistogram(testTree, varName, "", "MVA_KNN", histogramFakeRateWeightedName.Data(), numBinsX, xMin, xMax); histogramFakeRateWeighted->Divide(histogramTauIdDenominator); std::cout << "--> histogramFakeRateWeighted = " << histogramFakeRateWeighted << " entries = " << histogramFakeRateWeighted->GetEntries() << "," << " integral = " << histogramFakeRateWeighted->Integral() << std::endl; // Scale the weighted fake rate histogram histogramFakeRate->SetTitle(varName.data()); histogramFakeRate->SetStats(false); histogramFakeRate->SetMinimum(1.e-4); histogramFakeRate->SetMaximum(1.e+1); histogramFakeRate->SetLineColor(2); histogramFakeRate->SetLineWidth(2); histogramFakeRate->SetMarkerStyle(20); histogramFakeRate->SetMarkerColor(2); histogramFakeRate->SetMarkerSize(1); histogramFakeRate->Draw("e1p"); histogramFakeRateWeighted->SetLineColor(4); histogramFakeRateWeighted->SetLineWidth(2); histogramFakeRateWeighted->SetMarkerStyle(24); histogramFakeRateWeighted->SetMarkerColor(4); histogramFakeRateWeighted->SetMarkerSize(1); histogramFakeRateWeighted->Draw("e1psame"); TLegend legend(0.11, 0.73, 0.31, 0.89); legend.SetBorderSize(0); legend.SetFillColor(0); legend.AddEntry(histogramFakeRate, "Tau id. discr.", "p"); legend.AddEntry(histogramFakeRateWeighted, "Fake-Rate weight", "p"); legend.Draw(); canvas->Update(); canvas->Print(outputFileName.data()); }
void showGraphs(const TString& title, double canvasSizeX, double canvasSizeY, TGraph* graph1, const std::string& legendEntry1, TGraph* graph2, const std::string& legendEntry2, TGraph* graph3, const std::string& legendEntry3, TGraph* graph4, const std::string& legendEntry4, TGraph* graph5, const std::string& legendEntry5, TGraph* graph6, const std::string& legendEntry6, double xMin, double xMax, unsigned numBinsX, const std::string& xAxisTitle, double xAxisOffset, double yMin, double yMax, const std::string& yAxisTitle, double yAxisOffset, double legendX0, double legendY0, const std::string& outputFileName) { TCanvas* canvas = new TCanvas("canvas", "canvas", canvasSizeX, canvasSizeY); canvas->SetFillColor(10); canvas->SetBorderSize(2); canvas->SetLeftMargin(0.12); canvas->SetBottomMargin(0.12); int colors[6] = { 1, 2, 3, 4, 6, 7 }; int markerStyles[6] = { 22, 32, 20, 24, 21, 25 }; TLegend* legend = new TLegend(legendX0, legendY0, legendX0 + 0.44, legendY0 + 0.20, "", "brNDC"); legend->SetBorderSize(0); legend->SetFillColor(0); TH1* dummyHistogram = new TH1D("dummyHistogram", "dummyHistogram", numBinsX, xMin, xMax); dummyHistogram->SetTitle(""); dummyHistogram->SetStats(false); dummyHistogram->SetMinimum(yMin); dummyHistogram->SetMaximum(yMax); TAxis* xAxis = dummyHistogram->GetXaxis(); xAxis->SetTitle(xAxisTitle.data()); xAxis->SetTitleOffset(xAxisOffset); TAxis* yAxis = dummyHistogram->GetYaxis(); yAxis->SetTitle(yAxisTitle.data()); yAxis->SetTitleOffset(yAxisOffset); dummyHistogram->Draw("axis"); graph1->SetLineColor(colors[0]); graph1->SetLineWidth(2); graph1->Draw("L"); legend->AddEntry(graph1, legendEntry1.data(), "l"); if ( graph2 ) { graph2->SetLineColor(colors[1]); graph2->SetLineWidth(2); graph2->Draw("L"); legend->AddEntry(graph2, legendEntry2.data(), "l"); } if ( graph3 ) { graph3->SetLineColor(colors[2]); graph3->SetLineWidth(2); graph3->Draw("L"); legend->AddEntry(graph3, legendEntry3.data(), "l"); } if ( graph4 ) { graph4->SetLineColor(colors[3]); graph4->SetLineWidth(2); graph4->Draw("L"); legend->AddEntry(graph4, legendEntry4.data(), "l"); } if ( graph5 ) { graph5->SetLineColor(colors[4]); graph5->SetLineWidth(2); graph5->Draw("L"); legend->AddEntry(graph5, legendEntry5.data(), "l"); } if ( graph6 ) { graph6->SetLineColor(colors[5]); graph6->SetLineWidth(2); graph6->Draw("L"); legend->AddEntry(graph6, legendEntry6.data(), "l"); } legend->Draw(); TPaveText* label = 0; if ( title.Length() > 0 ) { label = new TPaveText(0.175, 0.925, 0.48, 0.98, "NDC"); label->AddText(title.Data()); label->SetTextAlign(13); label->SetTextSize(0.045); label->SetFillStyle(0); label->SetBorderSize(0); label->Draw(); } canvas->Update(); size_t idx = outputFileName.find_last_of('.'); std::string outputFileName_plot = std::string(outputFileName, 0, idx); if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName, idx)).data()); canvas->Print(std::string(outputFileName_plot).append(".png").data()); canvas->Print(std::string(outputFileName_plot).append(".pdf").data()); delete legend; delete label; delete dummyHistogram; delete canvas; }
void showEfficiency(const TString& title, double canvasSizeX, double canvasSizeY, const TH1* histogram1_numerator, const TH1* histogram1_denominator, const std::string& legendEntry1, const TH1* histogram2_numerator, const TH1* histogram2_denominator, const std::string& legendEntry2, const TH1* histogram3_numerator, const TH1* histogram3_denominator, const std::string& legendEntry3, const TH1* histogram4_numerator, const TH1* histogram4_denominator, const std::string& legendEntry4, const TH1* histogram5_numerator, const TH1* histogram5_denominator, const std::string& legendEntry5, const TH1* histogram6_numerator, const TH1* histogram6_denominator, const std::string& legendEntry6, const std::string& xAxisTitle, double xAxisOffset, bool useLogScale, double yMin, double yMax, const std::string& yAxisTitle, double yAxisOffset, double legendX0, double legendY0, const std::string& outputFileName) { TCanvas* canvas = new TCanvas("canvas", "canvas", canvasSizeX, canvasSizeY); canvas->SetFillColor(10); canvas->SetBorderSize(2); canvas->SetLeftMargin(0.12); canvas->SetBottomMargin(0.12); canvas->SetLogy(useLogScale); canvas->SetGridx(); canvas->SetGridy(); TH1* dummyHistogram = new TH1D("dummyHistogram_top", "dummyHistogram_top", 10, histogram1_numerator->GetXaxis()->GetXmin(), histogram1_numerator->GetXaxis()->GetXmax()); dummyHistogram->SetTitle(""); dummyHistogram->SetStats(false); dummyHistogram->SetMaximum(yMax); dummyHistogram->SetMinimum(yMin); TAxis* xAxis = dummyHistogram->GetXaxis(); xAxis->SetTitle(xAxisTitle.data()); xAxis->SetTitleOffset(xAxisOffset); TAxis* yAxis = dummyHistogram->GetYaxis(); yAxis->SetTitle(yAxisTitle.data()); yAxis->SetTitleOffset(yAxisOffset); dummyHistogram->Draw(); int colors[6] = { 1, 2, 3, 4, 6, 7 }; int markerStyles[6] = { 22, 32, 20, 24, 21, 25 }; int numGraphs = 1; if ( histogram2_numerator && histogram2_denominator ) ++numGraphs; if ( histogram3_numerator && histogram3_denominator ) ++numGraphs; if ( histogram4_numerator && histogram4_denominator ) ++numGraphs; if ( histogram5_numerator && histogram5_denominator ) ++numGraphs; if ( histogram6_numerator && histogram6_denominator ) ++numGraphs; TLegend* legend = new TLegend(legendX0, legendY0, legendX0 + 0.18, legendY0 + 0.05*numGraphs, "", "brNDC"); legend->SetBorderSize(0); legend->SetFillColor(0); TGraphAsymmErrors* graph1 = getEfficiency(histogram1_numerator, histogram1_denominator); graph1->SetLineColor(colors[0]); graph1->SetMarkerColor(colors[0]); graph1->SetMarkerStyle(markerStyles[0]); graph1->Draw("p"); legend->AddEntry(graph1, legendEntry1.data(), "p"); TGraphAsymmErrors* graph2 = 0; if ( histogram2_numerator && histogram2_denominator ) { graph2 = getEfficiency(histogram2_numerator, histogram2_denominator); graph2->SetLineColor(colors[1]); graph2->SetMarkerColor(colors[1]); graph2->SetMarkerStyle(markerStyles[1]); graph2->Draw("p"); legend->AddEntry(graph2, legendEntry2.data(), "p"); } TGraphAsymmErrors* graph3 = 0; if ( histogram3_numerator && histogram3_denominator ) { graph3 = getEfficiency(histogram3_numerator, histogram3_denominator); graph3->SetLineColor(colors[2]); graph3->SetMarkerColor(colors[2]); graph3->SetMarkerStyle(markerStyles[2]); graph3->Draw("p"); legend->AddEntry(graph3, legendEntry3.data(), "p"); } TGraphAsymmErrors* graph4 = 0; if ( histogram4_numerator && histogram4_denominator ) { graph4 = getEfficiency(histogram4_numerator, histogram4_denominator); graph4->SetLineColor(colors[3]); graph4->SetMarkerColor(colors[3]); graph4->SetMarkerStyle(markerStyles[3]); graph4->Draw("p"); legend->AddEntry(graph4, legendEntry4.data(), "p"); } TGraphAsymmErrors* graph5 = 0; if ( histogram5_numerator && histogram5_denominator ) { graph5 = getEfficiency(histogram5_numerator, histogram5_denominator); graph5->SetLineColor(colors[4]); graph5->SetMarkerColor(colors[4]); graph5->SetMarkerStyle(markerStyles[4]); graph5->Draw("p"); legend->AddEntry(graph5, legendEntry5.data(), "p"); } TGraphAsymmErrors* graph6 = 0; if ( histogram6_numerator && histogram6_denominator ) { graph6 = getEfficiency(histogram6_numerator, histogram6_denominator); graph6->SetLineColor(colors[5]); graph6->SetMarkerColor(colors[5]); graph6->SetMarkerStyle(markerStyles[5]); graph6->Draw("p"); legend->AddEntry(graph6, legendEntry6.data(), "p"); } legend->Draw(); TPaveText* label = 0; if ( title.Length() > 0 ) { label = new TPaveText(0.175, 0.925, 0.48, 0.98, "NDC"); label->AddText(title.Data()); label->SetTextAlign(13); label->SetTextSize(0.045); label->SetFillStyle(0); label->SetBorderSize(0); label->Draw(); } canvas->Update(); size_t idx = outputFileName.find_last_of('.'); std::string outputFileName_plot = std::string(outputFileName, 0, idx); if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName, idx)).data()); canvas->Print(std::string(outputFileName_plot).append(".png").data()); canvas->Print(std::string(outputFileName_plot).append(".pdf").data()); delete legend; delete label; delete dummyHistogram; delete canvas; }
void makePlot(double canvasSizeX, double canvasSizeY, TH1* histogramTTH, TH1* histogramData, TH1* histogramTT, TH1* histogramTTV, TH1* histogramEWK, TH1* histogramRares, TH1* histogramBgrSum, TH1* histogramBgrUncertainty, const std::string& xAxisTitle, double xAxisOffset, bool useLogScale, double yMin, double yMax, const std::string& yAxisTitle, double yAxisOffset, const std::string& outputFileName) { TH1* histogramTTH_density = 0; if ( histogramTTH ) { if ( histogramData ) checkCompatibleBinning(histogramTTH, histogramData); histogramTTH_density = divideHistogramByBinWidth(histogramTTH); } TH1* histogramData_density = 0; if ( histogramData ) { histogramData_density = divideHistogramByBinWidth(histogramData); } TH1* histogramTT_density = 0; if ( histogramTT ) { if ( histogramData ) checkCompatibleBinning(histogramTT, histogramData); histogramTT_density = divideHistogramByBinWidth(histogramTT); } TH1* histogramTTV_density = 0; if ( histogramTTV ) { if ( histogramData ) checkCompatibleBinning(histogramTTV, histogramData); histogramTTV_density = divideHistogramByBinWidth(histogramTTV); } TH1* histogramEWK_density = 0; if ( histogramEWK ) { if ( histogramData ) checkCompatibleBinning(histogramEWK, histogramData); histogramEWK_density = divideHistogramByBinWidth(histogramEWK); } TH1* histogramRares_density = 0; if ( histogramRares ) { if ( histogramData ) checkCompatibleBinning(histogramRares, histogramData); histogramRares_density = divideHistogramByBinWidth(histogramRares); } TH1* histogramBgrSum_density = 0; if ( histogramBgrSum ) { if ( histogramData ) checkCompatibleBinning(histogramBgrSum, histogramData); histogramBgrSum_density = divideHistogramByBinWidth(histogramBgrSum); } TH1* histogramBgrUncertainty_density = 0; if ( histogramBgrUncertainty ) { if ( histogramData ) checkCompatibleBinning(histogramBgrUncertainty, histogramData); histogramBgrUncertainty_density = divideHistogramByBinWidth(histogramBgrUncertainty); } TCanvas* canvas = new TCanvas("canvas", "", canvasSizeX, canvasSizeY); canvas->SetFillColor(10); canvas->SetFillStyle(4000); canvas->SetFillColor(10); canvas->SetTicky(); canvas->SetBorderSize(2); canvas->SetLeftMargin(0.12); canvas->SetBottomMargin(0.12); TPad* topPad = new TPad("topPad", "topPad", 0.00, 0.35, 1.00, 1.00); topPad->SetFillColor(10); topPad->SetTopMargin(0.065); topPad->SetLeftMargin(0.15); topPad->SetBottomMargin(0.03); topPad->SetRightMargin(0.05); topPad->SetLogy(useLogScale); TPad* bottomPad = new TPad("bottomPad", "bottomPad", 0.00, 0.00, 1.00, 0.35); bottomPad->SetFillColor(10); bottomPad->SetTopMargin(0.02); bottomPad->SetLeftMargin(0.15); bottomPad->SetBottomMargin(0.31); bottomPad->SetRightMargin(0.05); bottomPad->SetLogy(false); canvas->cd(); topPad->Draw(); topPad->cd(); TAxis* xAxis_top = histogramData_density->GetXaxis(); xAxis_top->SetTitle(xAxisTitle.data()); xAxis_top->SetTitleOffset(xAxisOffset); xAxis_top->SetLabelColor(10); xAxis_top->SetTitleColor(10); TAxis* yAxis_top = histogramData_density->GetYaxis(); yAxis_top->SetTitle(yAxisTitle.data()); yAxis_top->SetTitleOffset(yAxisOffset); yAxis_top->SetTitleSize(0.085); yAxis_top->SetLabelSize(0.05); yAxis_top->SetTickLength(0.04); TLegend* legend = new TLegend(0.66, 0.45, 0.94, 0.92, NULL, "brNDC"); legend->SetFillStyle(0); legend->SetBorderSize(0); legend->SetFillColor(10); legend->SetTextSize(0.055); histogramData_density->SetTitle(""); histogramData_density->SetStats(false); histogramData_density->SetMaximum(yMax); histogramData_density->SetMinimum(yMin); histogramData_density->SetMarkerStyle(20); histogramData_density->SetMarkerSize(2); histogramData_density->SetMarkerColor(kBlack); histogramData_density->SetLineColor(kBlack); legend->AddEntry(histogramData_density, "Observed", "p"); histogramData_density->Draw("ep"); legend->AddEntry(histogramTTH_density, "t#bar{t}H", "l"); histogramTT_density->SetTitle(""); histogramTT_density->SetStats(false); histogramTT_density->SetMaximum(yMax); histogramTT_density->SetMinimum(yMin); histogramTT_density->SetFillColor(kMagenta - 10); legend->AddEntry(histogramTT_density, "t#bar{t}+jets", "f"); histogramTTV_density->SetFillColor(kOrange - 4); legend->AddEntry(histogramTTV_density, "t#bar{t}+V", "f"); histogramEWK_density->SetFillColor(kRed + 2); legend->AddEntry(histogramEWK_density, "EWK", "f"); histogramRares_density->SetFillColor(kBlue - 8); legend->AddEntry(histogramRares_density, "Rares", "f"); THStack* histogramStack_density = new THStack("stack", ""); histogramStack_density->Add(histogramRares_density); histogramStack_density->Add(histogramEWK_density); histogramStack_density->Add(histogramTTV_density); histogramStack_density->Add(histogramTT_density); histogramStack_density->Draw("histsame"); histogramBgrUncertainty_density->SetFillColor(kBlack); histogramBgrUncertainty_density->SetFillStyle(3344); histogramBgrUncertainty_density->Draw("e2same"); legend->AddEntry(histogramBgrUncertainty_density, "Uncertainty", "f"); histogramTTH_density->SetLineWidth(2); histogramTTH_density->SetLineStyle(1); histogramTTH_density->SetLineColor(kBlue); histogramTTH_density->Draw("histsame"); histogramData_density->Draw("epsame"); histogramData_density->Draw("axissame"); legend->Draw(); addLabel_CMS_luminosity(0.2050, 0.9225, 0.6850); canvas->cd(); bottomPad->Draw(); bottomPad->cd(); TH1* histogramRatio = (TH1*)histogramData->Clone("histogramRatio"); histogramRatio->Reset(); if ( !histogramRatio->GetSumw2N() ) histogramRatio->Sumw2(); checkCompatibleBinning(histogramRatio, histogramBgrSum); histogramRatio->Divide(histogramData, histogramBgrSum); int numBins_bottom = histogramRatio->GetNbinsX(); for ( int iBin = 1; iBin <= numBins_bottom; ++iBin ) { double binContent = histogramRatio->GetBinContent(iBin); if ( histogramData && histogramData->GetBinContent(iBin) >= 0. ) histogramRatio->SetBinContent(iBin, binContent - 1.0); else histogramRatio->SetBinContent(iBin, -10.); } histogramRatio->SetTitle(""); histogramRatio->SetStats(false); histogramRatio->SetMinimum(-0.50); histogramRatio->SetMaximum(+0.50); histogramRatio->SetMarkerStyle(histogramData_density->GetMarkerStyle()); histogramRatio->SetMarkerSize(histogramData_density->GetMarkerSize()); histogramRatio->SetMarkerColor(histogramData_density->GetMarkerColor()); histogramRatio->SetLineColor(histogramData_density->GetLineColor()); histogramRatio->Draw("ep"); TAxis* xAxis_bottom = histogramRatio->GetXaxis(); xAxis_bottom->SetTitle(xAxis_top->GetTitle()); xAxis_bottom->SetLabelColor(1); xAxis_bottom->SetTitleColor(1); xAxis_bottom->SetTitleOffset(1.20); xAxis_bottom->SetTitleSize(0.13); xAxis_bottom->SetLabelOffset(0.02); xAxis_bottom->SetLabelSize(0.10); xAxis_bottom->SetTickLength(0.055); TAxis* yAxis_bottom = histogramRatio->GetYaxis(); yAxis_bottom->SetTitle("#frac{Data - Simulation}{Simulation}"); yAxis_bottom->SetTitleOffset(0.80); yAxis_bottom->SetNdivisions(505); yAxis_bottom->CenterTitle(); yAxis_bottom->SetTitleSize(0.09); yAxis_bottom->SetLabelSize(0.10); yAxis_bottom->SetTickLength(0.04); TH1* histogramRatioUncertainty = (TH1*)histogramBgrUncertainty->Clone("histogramRatioUncertainty"); if ( !histogramRatioUncertainty->GetSumw2N() ) histogramRatioUncertainty->Sumw2(); checkCompatibleBinning(histogramRatioUncertainty, histogramBgrUncertainty); histogramRatioUncertainty->Divide(histogramBgrSum); int numBins = histogramRatioUncertainty->GetNbinsX(); for ( int iBin = 1; iBin <= numBins; ++iBin ) { double binContent = histogramRatioUncertainty->GetBinContent(iBin); histogramRatioUncertainty->SetBinContent(iBin, binContent - 1.0); } histogramRatioUncertainty->SetFillColor(histogramBgrUncertainty_density->GetFillColor()); //histogramRatioUncertainty->SetFillStyle(histogramBgrUncertainty_density->GetFillStyle()); histogramRatioUncertainty->SetFillStyle(3644); TF1* line = new TF1("line","0", xAxis_bottom->GetXmin(), xAxis_bottom->GetXmax()); line->SetLineStyle(3); line->SetLineWidth(1); line->SetLineColor(kBlack); line->Draw("same"); histogramRatioUncertainty->Draw("e2same"); histogramRatio->Draw("epsame"); canvas->Update(); size_t idx = outputFileName.find("."); std::string outputFileName_plot(outputFileName, 0, idx); if ( useLogScale ) outputFileName_plot.append("_log"); else outputFileName_plot.append("_linear"); if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName, idx)).data()); canvas->Print(std::string(outputFileName_plot).append(".png").data()); canvas->Print(std::string(outputFileName_plot).append(".pdf").data()); canvas->Print(std::string(outputFileName_plot).append(".root").data()); delete histogramTTH_density; delete histogramData_density; delete histogramTT_density; delete histogramTTV_density; delete histogramEWK_density; delete histogramRares_density; delete histogramBgrSum_density; //delete histogramBgrUncertainty_density; delete histogramStack_density; delete legend; delete topPad; delete histogramRatio; delete histogramRatioUncertainty; delete line; delete bottomPad; delete canvas; }
void makePlot(const std::string& inputFilePath, const std::string& canvasName, const std::string& sample, int massPoint, const std::string& channel, double k, const std::string& inputFileName, const std::string& outputFilePath, const std::string& outputFileName) { std::string inputFileName_full = Form("%s%s", inputFilePath.data(), inputFileName.data()); TFile* inputFile = new TFile(inputFileName_full.data()); if ( !inputFile ) { std::cerr << "Failed to open input file = " << inputFileName_full << " !!" << std::endl; assert(0); } inputFile->ls(); TCanvas* canvas = dynamic_cast<TCanvas*>(inputFile->Get(canvasName.data())); if ( !canvas ) { std::cerr << "Failed to load canvas = " << canvasName << " !!" << std::endl; assert(0); } int idxPad = -1; if ( massPoint == 90 ) idxPad = 1; if ( massPoint == 125 ) idxPad = 2; if ( massPoint == 200 ) idxPad = 3; if ( massPoint == 300 ) idxPad = 4; if ( massPoint == 500 ) idxPad = 5; if ( massPoint == 800 ) idxPad = 6; if ( !(idxPad >= 1 && idxPad <= 6) ) { std::cerr << "Invalid sample = " << sample << " !!" << std::endl; assert(0); } TVirtualPad* pad = canvas->GetPad(idxPad); std::cout << "pad = " << pad << ": ClassName = " << pad->ClassName() << std::endl; TCanvas* canvas_new = new TCanvas("canvas_new", "canvas_new", 900, 800); canvas_new->SetFillColor(10); canvas_new->SetBorderSize(2); canvas_new->SetTopMargin(0.065); canvas_new->SetLeftMargin(0.17); canvas_new->SetBottomMargin(0.165); canvas_new->SetRightMargin(0.015); canvas_new->SetLogx(true); canvas_new->SetLogy(true); canvas_new->Draw(); canvas_new->cd(); //TList* pad_primitives = canvas->GetListOfPrimitives(); TList* pad_primitives = pad->GetListOfPrimitives(); TH1* histogramCA = 0; TH1* histogramSVfit = 0; TH1* histogramSVfitMEMkEq0 = 0; TH1* histogramSVfitMEMkNeq0 = 0; TIter pad_nextObj(pad_primitives); while ( TObject* obj = pad_nextObj() ) { std::string objName = ""; if ( dynamic_cast<TNamed*>(obj) ) objName = (dynamic_cast<TNamed*>(obj))->GetName(); std::cout << "obj = " << obj << ": name = " << objName << ", type = " << obj->ClassName() << std::endl; TH1* tmpHistogram = dynamic_cast<TH1*>(obj); if ( tmpHistogram ) { std::cout << "tmpHistogram:" << " fillColor = " << tmpHistogram->GetFillColor() << ", fillStyle = " << tmpHistogram->GetFillStyle() << "," << " lineColor = " << tmpHistogram->GetLineColor() << ", lineStyle = " << tmpHistogram->GetLineStyle() << ", lineWidth = " << tmpHistogram->GetLineWidth() << "," << " markerColor = " << tmpHistogram->GetMarkerColor() << ", markerStyle = " << tmpHistogram->GetMarkerStyle() << ", markerSize = " << tmpHistogram->GetMarkerSize() << "," << " integral = " << tmpHistogram->Integral() << std::endl; std::cout << "(mean = " << tmpHistogram->GetMean() << ", rms = " << tmpHistogram->GetRMS() << ": rms/mean = " << (tmpHistogram->GetRMS()/tmpHistogram->GetMean()) << ")" << std::endl; if ( tmpHistogram->GetLineColor() == 416 ) histogramCA = tmpHistogram; if ( tmpHistogram->GetLineColor() == 600 ) histogramSVfit = tmpHistogram; if ( tmpHistogram->GetLineColor() == 616 ) histogramSVfitMEMkEq0 = tmpHistogram; if ( tmpHistogram->GetLineColor() == 632 ) histogramSVfitMEMkNeq0 = tmpHistogram; } } if ( !(histogramCA && histogramSVfit && histogramSVfitMEMkEq0 && histogramSVfitMEMkNeq0) ) { std::cerr << "Failed to load histograms !!" << std::endl; assert(0); } //gStyle->SetLineStyleString(2,"40 10 10 10 10 10 10 10"); //gStyle->SetLineStyleString(3,"25 15"); //gStyle->SetLineStyleString(4,"60 25"); //int colors[4] = { kBlack, kGreen - 6, kBlue - 7, kMagenta - 7 }; int colors[4] = { 28, kGreen - 6, kBlue - 7, kBlack }; //int lineStyles[4] = { 2, 3, 4, 1 }; int lineStyles[4] = { 7, 1, 1, 1 }; //int lineWidths[4] = { 3, 3, 4, 3 }; int lineWidths[4] = { 3, 3, 1, 1 }; int markerStyles[4] = { 20, 25, 21, 24 }; int markerSizes[4] = { 2, 2, 2, 2 }; histogramCA->SetFillColor(0); histogramCA->SetFillStyle(0); histogramCA->SetLineColor(colors[0]); histogramCA->SetLineStyle(lineStyles[0]); histogramCA->SetLineWidth(lineWidths[0]); histogramCA->SetMarkerColor(colors[0]); histogramCA->SetMarkerStyle(markerStyles[0]); histogramCA->SetMarkerSize(markerSizes[0]); histogramSVfit->SetFillColor(0); histogramSVfit->SetFillStyle(0); histogramSVfit->SetLineColor(colors[1]); histogramSVfit->SetLineStyle(lineStyles[1]); histogramSVfit->SetLineWidth(lineWidths[1]); histogramSVfit->SetMarkerColor(colors[1]); histogramSVfit->SetMarkerStyle(markerStyles[1]); histogramSVfit->SetMarkerSize(markerSizes[1]); histogramSVfitMEMkEq0->SetFillColor(0); histogramSVfitMEMkEq0->SetFillStyle(0); histogramSVfitMEMkEq0->SetLineColor(colors[2]); histogramSVfitMEMkEq0->SetLineStyle(lineStyles[2]); histogramSVfitMEMkEq0->SetLineWidth(lineWidths[2]); histogramSVfitMEMkEq0->SetMarkerColor(colors[2]); histogramSVfitMEMkEq0->SetMarkerStyle(markerStyles[2]); histogramSVfitMEMkEq0->SetMarkerSize(markerSizes[2]); // CV: fix pathological bins at high mass for which dN/dm increases int numBins = histogramSVfitMEMkEq0->GetNbinsX(); for ( int idxBin = 1; idxBin <= numBins; ++idxBin ) { double binCenter = histogramSVfitMEMkEq0->GetBinCenter(idxBin); if ( (channel == "#tau_{h}#tau_{h}" && massPoint == 500 && binCenter > 1500.) || (channel == "#tau_{h}#tau_{h}" && massPoint == 800 && binCenter > 2000.) || (channel == "#mu#tau_{h}" && massPoint == 500 && binCenter > 1500.) || (channel == "#mu#tau_{h}" && massPoint == 800 && binCenter > 2500.) ) { histogramSVfitMEMkEq0->SetBinContent(idxBin, 0.); } } histogramSVfitMEMkNeq0->SetFillColor(0); histogramSVfitMEMkNeq0->SetFillStyle(0); histogramSVfitMEMkNeq0->SetLineColor(colors[3]); histogramSVfitMEMkNeq0->SetLineStyle(lineStyles[3]); histogramSVfitMEMkNeq0->SetLineWidth(lineWidths[3]); histogramSVfitMEMkNeq0->SetMarkerColor(colors[3]); histogramSVfitMEMkNeq0->SetMarkerStyle(markerStyles[3]); histogramSVfitMEMkNeq0->SetMarkerSize(markerSizes[3]); TAxis* xAxis = histogramCA->GetXaxis(); xAxis->SetTitle("m_{#tau#tau} [GeV]"); xAxis->SetTitleOffset(1.15); xAxis->SetTitleSize(0.070); xAxis->SetTitleFont(42); xAxis->SetLabelOffset(0.010); xAxis->SetLabelSize(0.055); xAxis->SetLabelFont(42); xAxis->SetTickLength(0.040); xAxis->SetNdivisions(510); //double xMin = 20.; //double xMax = xAxis->GetXmax(); //xAxis->SetRangeUser(xMin, xMax); TAxis* yAxis = histogramCA->GetYaxis(); yAxis->SetTitle("dN/dm_{#tau#tau} [1/GeV]"); yAxis->SetTitleOffset(1.20); yAxis->SetTitleSize(0.070); yAxis->SetTitleFont(42); yAxis->SetLabelOffset(0.010); yAxis->SetLabelSize(0.055); yAxis->SetLabelFont(42); yAxis->SetTickLength(0.040); yAxis->SetNdivisions(505); double massPoint_double = 0.; if ( massPoint == 90 ) massPoint_double = 91.2; else massPoint_double = massPoint; double dLog = (TMath::Log(5.*massPoint_double) - TMath::Log(50.))/25.; // xMin = 50, xMax = 5*massPoint, numBins = 25 double binWidth = TMath::Exp(TMath::Log(massPoint_double) + 0.5*dLog) - TMath::Exp(TMath::Log(massPoint_double) - 0.5*dLog); double sf_binWidth = 1./binWidth; std::cout << "massPoint = " << massPoint << ": sf_binWidth = " << sf_binWidth << std::endl; histogramCA->SetTitle(""); histogramCA->SetStats(false); histogramCA->SetMaximum(sf_binWidth*0.79); histogramCA->SetMinimum(sf_binWidth*1.1e-4); histogramCA->Draw("hist"); histogramSVfit->Draw("histsame"); //histogramSVfitMEMkEq0->Draw("histsame"); histogramSVfitMEMkEq0->Draw("epsame"); //histogramSVfitMEMkNeq0->Draw("histsame"); histogramSVfitMEMkNeq0->Draw("epsame"); histogramCA->Draw("axissame"); //TPaveText* label_sample = new TPaveText(0.21, 0.86, 0.46, 0.94, "NDC"); TPaveText* label_sample = new TPaveText(0.1700, 0.9475, 0.4600, 1.0375, "NDC"); label_sample->SetFillStyle(0); label_sample->SetBorderSize(0); label_sample->AddText(sample.data()); label_sample->SetTextFont(42); label_sample->SetTextSize(0.055); label_sample->SetTextColor(1); label_sample->SetTextAlign(13); label_sample->Draw(); //TLegend* legend_new = new TLegend(0.225, 0.52, 0.41, 0.82, NULL, "brNDC"); TLegend* legend_new = new TLegend(0.30, 0.30, 0.80, 0.80, NULL, "brNDC"); legend_new->SetFillColor(10); legend_new->SetFillStyle(0); legend_new->SetBorderSize(0); legend_new->SetTextFont(42); legend_new->SetTextSize(0.055); legend_new->SetTextColor(1); legend_new->SetMargin(0.20); legend_new->AddEntry(histogramCA, "CA", "l"); legend_new->AddEntry(histogramSVfit, "SVfit", "l"); //legend_new->AddEntry(histogramSVfitMEMkEq0, "SVfitMEM (k=0)", "l"); legend_new->AddEntry(histogramSVfitMEMkEq0, "SVfitMEM (k=0)", "p"); //legend_new->AddEntry(histogramSVfitMEMkNeq0, Form("SVfitMEM(k=%1.0f)", k), "l"); legend_new->AddEntry(histogramSVfitMEMkNeq0, Form("SVfitMEM (k=%1.0f)", k), "p"); //legend_new->Draw(); double label_channel_y0; if ( channel == "e#mu" ) label_channel_y0 = 0.9275; else if ( channel == "#mu#tau_{h}" ) label_channel_y0 = 0.9400; else if ( channel == "#tau_{h}#tau_{h}" ) label_channel_y0 = 0.9350; else { std::cerr << "Invalid channel = " << channel << " !!" << std::endl; assert(0); } TPaveText* label_channel = new TPaveText(0.895, label_channel_y0, 0.975, label_channel_y0 + 0.055, "NDC"); label_channel->SetFillStyle(0); label_channel->SetBorderSize(0); label_channel->AddText(channel.data()); label_channel->SetTextFont(62); label_channel->SetTextSize(0.055); label_channel->SetTextColor(1); label_channel->SetTextAlign(31); label_channel->Draw(); canvas_new->Update(); std::string outputFileName_full = Form("%s%s", outputFilePath.data(), outputFileName.data()); size_t idx = outputFileName_full.find_last_of('.'); std::string outputFileName_plot = std::string(outputFileName_full, 0, idx); canvas_new->Print(std::string(outputFileName_plot).append(".pdf").data()); canvas_new->Print(std::string(outputFileName_plot).append(".root").data()); std::string channel_string; if ( channel == "e#mu" ) channel_string = "emu"; else if ( channel == "#mu#tau_{h}" ) channel_string = "muhad"; else if ( channel == "#tau_{h}#tau_{h}" ) channel_string = "hadhad"; else { std::cerr << "Invalid channel = " << channel << " !!" << std::endl; assert(0); } std::string outputFileName_legend = Form("makeSVfitMEM_PerformancePlots_legend_%s.pdf", channel_string.data()); makePlot_legend(legend_new, outputFilePath, outputFileName_legend); delete label_sample; delete legend_new; delete label_channel; delete canvas_new; delete inputFile; }
void plotVariable(string variable = "Elec_Fbrem", const TString& category = "TauNoGammas", const TString& xAxisTitle = "Fbrem", const TString& yAxisTitle = "a.u.", float xMin = -0.2, float xMax = 1, int nBins = 100, int numPVMin = 0, int numPVMax = 50, float PtMin = 10, float PtMax = 60, const TString& Region = "Endcap" ) { string discriminator = ""; // string discriminator = "-AntiEMed"; float AbsEtaMin = 0; float AbsEtaMax = 3.0; if(Region == "Barrel"){ AbsEtaMin = 0; AbsEtaMax = 1.479; } if(Region == "Endcap"){ AbsEtaMin = 1.479; AbsEtaMax = 3.0; } TCanvas *c1 = new TCanvas("c1","",5,30,650,600); c1->SetGrid(0,0); c1->SetFillStyle(4000); c1->SetFillColor(10); c1->SetTicky(); c1->SetObjectStat(0); gStyle->SetOptStat(0); gStyle->SetTitleFillColor(0); gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(0); gStyle->SetPadBorderMode(0); gStyle->SetPadColor(0); gStyle->SetTitleFillColor(0); gStyle->SetTitleBorderSize(0); gStyle->SetTitleH(0.07); gStyle->SetTitleFontSize(0.1); gStyle->SetTitleStyle(0); gStyle->SetTitleOffset(1.3,"y"); TLegend* leg = new TLegend(0.6,0.75,0.8,0.88,NULL,"brNDC"); leg->SetFillStyle(0); leg->SetBorderSize(0); leg->SetFillColor(10); leg->SetTextSize(0.03); //leg->SetHeader("#splitline{CMS Preliminary}{ #sqrt{s}=7 TeV}"); // std::string inputFileName = "/data_CMS/cms/ivo/AntiEMVA/Trees/AntiEMVA_Fall11DYJetsToLL-iter4.root"; // std::string inputFileName = "/data_CMS/cms/ivo/AntiEMVA/Trees/Trees_ForV4/AntiEMVA_AntiEMVATrees-DYJetsToLL-madgraph-PUS6.root"; std::string inputFileName = "/data_CMS/cms/ivo/AntiEMVA/Trees/Trees_ForV4/AntiEMVA_V4.root"; TFile* inputFile = new TFile (inputFileName.data(),"READ"); if(inputFile->IsZombie()){ cout << "No such file!" << endl; return; } TTree* inputTree = (TTree*)inputFile->Get("AntiEMVAAnalyzer2/tree"); // TTree* inputTree = (TTree*)inputFile->Get("AntiEMVAAnalyzer/tree"); std::vector<TH1*> histograms; std::vector<std::string> matchings ; matchings.push_back("GenHadMatch"); matchings.push_back("GenEleMatch"); for ( std::vector<std::string>::const_iterator matching = matchings.begin(); matching != matchings.end(); ++matching ) { TCut PUSelection(Form("NumPV>%i && NumPV<%i",numPVMin,numPVMax)); TCut ElecPtSelection (Form("Elec_Pt>%0f && Elec_Pt<%0f",PtMin,PtMax)); TCut TauPtSelection (Form("Tau_Pt>%0f && Tau_Pt<%0f",PtMin,PtMax)); TCut ElecAbsEtaSelection (Form("Elec_AbsEta>%0f && Elec_AbsEta<%0f",AbsEtaMin,AbsEtaMax)); TCut TauAbsEtaSelection = ""; if(Region == "Barrel"){ TauAbsEtaSelection = "Tau_Eta>-1.479 && Tau_Eta<1.479"; } if(Region == "Endcap"){ TauAbsEtaSelection = "(Tau_Eta>1.479 && Tau_Eta<3.0) || (Tau_Eta>-3.0 && Tau_Eta<-1.479)"; } // TCut TauAbsEtaSelection (Form("Tau_AbsEta>%0f && Tau_AbsEta<%0f",AbsEtaMin,AbsEtaMax)); TCut ElecMatchSelection (Form("Elec_%s == 1",matching->data())); // TCut ElecMatchSelection (Form("Elec_PFTauMatch && Elec_%s",matching->data())); TCut TauMatchSelection (Form("Tau_%s",matching->data())); TCut CategorySelection = ""; if(discriminator == ""){ if (category == "NoEleMatch") CategorySelection = "Tau_GsfEleMatch<0.5"; if (category == "woG") CategorySelection = "Tau_NumGammaCands<0.5"; if (category == "wGwoGSF") CategorySelection = "Tau_NumGammaCands>0.5 && Tau_HasGsf<0.5"; if (category == "wGwGSFwoPFMVA")CategorySelection = "Tau_NumGammaCands>0.5 && Tau_HasGsf>0.5 && Elec_PFMvaOutput<-0.1"; if (category == "wGwGSFwPFMVA")CategorySelection = "Tau_NumGammaCands>0.5 && Tau_HasGsf>0.5 && Elec_PFMvaOutput>-0.1"; } if(discriminator == "-AntiEMed"){ if (category == "NoEleMatch") CategorySelection = "Tau_GsfEleMatch<0.5"; if (category == "woG") CategorySelection = "Tau_NumGammaCands<0.5"; if (category == "wGwoGSF") CategorySelection = "Tau_NumGammaCands>0.5 && (Tau_HasGsf<0.5 || (Tau_HasGsf>0.5 && Elec_PFMvaOutput>-0.1))"; if (category == "wGwGSFwoPFMVA")CategorySelection = "Tau_NumGammaCands>0.5 && Tau_HasGsf>0.5 && Elec_PFMvaOutput<-0.1"; } TCut ElecSelection = CategorySelection && PUSelection && ElecPtSelection && ElecAbsEtaSelection && ElecMatchSelection ; TCut TauSelection = CategorySelection && PUSelection && TauPtSelection && TauAbsEtaSelection && TauMatchSelection ; TCut Selection; if (variable.find("Elec")!=std::string::npos)Selection = ElecSelection; if (variable.find("Tau")!=std::string::npos)Selection = TauSelection; TH1F* hVariable = new TH1F( "hVariable" ,"" , nBins ,xMin, xMax); hVariable->SetXTitle(Form("%s",variable.data())); if (matching->find("EleMatch")!=std::string::npos){ // hVariable->SetFillColor(kRed); // hVariable->SetFillStyle(3345); hVariable->SetLineColor(kRed); hVariable->SetLineWidth(2); } if (matching->find("HadMatch")!=std::string::npos){ // hVariable->SetFillColor(kBlue); // hVariable->SetFillStyle(3354); hVariable->SetLineColor(kBlue); hVariable->SetLineWidth(2); } inputTree->Draw(Form("%s>>hVariable",variable.data())); cout<<"Variable plotted : "<<variable<<endl; cout<<"Matching applied : "<<matching->data()<<endl; cout<<" Total number of Candidates : "<<hVariable->GetEntries()<<endl; inputTree->Draw(Form("%s>>hVariable",variable.data()),Selection); cout<<" Number of Cantidates after selection: "<<hVariable->GetEntries()<<endl; hVariable->Scale(1./hVariable->Integral()); leg->AddEntry(hVariable,Form("%s",matching->data())); histograms.push_back(hVariable); c1->Clear(); } // double yMin = +1.e+6; // double yMax = -1.e+6; TH1* refHistogram = histograms.front(); refHistogram->SetStats(false); refHistogram->SetTitle(""); // refHistogram->SetMinimum(yMin); // refHistogram->SetMaximum(yMax); if (xAxisTitle == "HoHplusE" ) { refHistogram->SetMaximum(1.0); refHistogram->SetMinimum(0.01); c1->SetLogy(); } if(xAxisTitle == "E_{#gamma}/(P_{in}-P_{out})" ){ refHistogram->SetMaximum(0.03); refHistogram->SetMinimum(0.0); } if(xAxisTitle == "HadrMva(#tau)" ){ refHistogram->SetMaximum(0.25); refHistogram->SetMinimum(0.0); } TAxis* xAxis = refHistogram->GetXaxis(); xAxis->SetTitle(xAxisTitle.Data()); xAxis->SetTitleOffset(1.15); //if(variable.find("AbsEta")!=std::string::npos)xAxis->SetLimits(AbsEtaMin, AbsEtaMax); TAxis* yAxis = refHistogram->GetYaxis(); yAxis->SetTitle(yAxisTitle.Data()); yAxis->SetTitleOffset(1.30); int numHistograms = histograms.size(); float YMax = 0; for ( int iHistogram = 0; iHistogram < numHistograms; ++iHistogram ) { TH1* histogram = histograms[iHistogram]; if(histogram->GetMaximum()>YMax) YMax = histogram->GetMaximum(); } for ( int iHistogram = 0; iHistogram < numHistograms; ++iHistogram ) { TH1* histogram = histograms[iHistogram]; yAxis->SetRangeUser(0.,YMax+0.10*YMax); std::string drawOption = "hist"; if ( iHistogram > 0 ) drawOption.append("same"); histogram->Draw(drawOption.data()); leg->Draw(); }//loop matchings string outputName = Form("plots/plotVariablesAntiEMVA/%s/plotVariablesAntiEMVA_v4_%s_%s_%s",category.Data(),category.Data(),variable.data(),Region.Data()); c1->Print(std::string(outputName).append(".png").data()); c1->Print(std::string(outputName).append(".pdf").data()); }
//void LeptonEnergy(const char *inputFile = "sourceFiles/LO/ttbar_LO_total.root") void LeptonEnergy(const TString & file) { //const char *inputFile = Form("/home/tjkim/work/pheno/topmass/sourceFiles/LO/fromSayaka/ttbar_%s.root",file.Data()); //gSystem->Load("/export/apps/delphes//libDelphes"); const char *inputFile = Form("/data/users/seohyun/analysis/ttbar_%s.root",file.Data()); gSystem->Load("/home/seohyun/delphes/libDelphes.so"); /* TFile *f2 = TFile::Open("weightfunc2.root"); TFile *f3 = TFile::Open("weightfunc3.root"); TFile *f5 = TFile::Open("weightfunc5.root"); TFile *f15 = TFile::Open("weightfunc15.root"); const int nmass = 151; float mymass[ nmass ]; float integral2[ nmass ]; float integral3[ nmass ]; float integral5[ nmass ]; float integral15[ nmass ]; for(int i=0; i < nmass ; i++){ integral2[i] = 0.0; integral3[i] = 0.0; integral5[i] = 0.0; integral15[i] = 0.0; } TGraph * g2[nmass]; TGraph * g3[nmass]; TGraph * g5[nmass]; TGraph * g15[nmass]; TIter next(f2->GetListOfKeys()); TKey *key; int i = 0; while( (key = (TKey*) next())) { TClass *cl = gROOT->GetClass( key->GetClassName()); if( !cl->InheritsFrom("TGraph")) continue; g2[i] = (TGraph*) key->ReadObj(); string mass = g2[i]->GetName(); float temp = atof(mass.c_str()); mymass[i] = temp; i++; } TIter next(f3->GetListOfKeys()); i = 0; while( (key = (TKey*) next())) { TClass *cl = gROOT->GetClass( key->GetClassName()); if( !cl->InheritsFrom("TGraph")) continue; g3[i] = (TGraph*) key->ReadObj(); i++; } TIter next(f5->GetListOfKeys()); i = 0; while( (key = (TKey*) next())) { TClass *cl = gROOT->GetClass( key->GetClassName()); if( !cl->InheritsFrom("TGraph")) continue; g5[i] = (TGraph*) key->ReadObj(); i++; } TIter next(f15->GetListOfKeys()); i = 0; while( (key = (TKey*) next())) { TClass *cl = gROOT->GetClass( key->GetClassName()); if( !cl->InheritsFrom("TGraph")) continue; g15[i] = (TGraph*) key->ReadObj(); i++; } TFile * res = TFile::Open("hist_LO_res_v3.root"); TH1F * h_acc = (TH1F*) res->Get("h_totalacc_lepton"); */ //TFile* f = TFile::Open("hist_LO_res_60.root", "recreate"); TFile* f = TFile::Open(Form("170717/hist_%s.root",file.Data()), "recreate"); // Create chain of root trees TChain chain("Delphes"); chain.Add(inputFile); // Create object of class ExRootTreeReader ExRootTreeReader *treeReader = new ExRootTreeReader(&chain); Long64_t numberOfEntries = treeReader->GetEntries(); // Get pointers to branches used in this analysis TClonesArray *branchParticle = treeReader->UseBranch("Particle"); TClonesArray *branchMuon = treeReader->UseBranch("Muon"); TClonesArray *branchElectron = treeReader->UseBranch("Electron"); TClonesArray *branchJet = treeReader->UseBranch("Jet"); TClonesArray *branchEvent = treeReader->UseBranch("Event"); GenParticle *particle; GenParticle *daughter1; GenParticle *daughter2; GenParticle *granddaughter1_1; GenParticle *granddaughter1_2; GenParticle *granddaughter2_1; GenParticle *granddaughter2_2; GenParticle *genelectron; GenParticle *genmuon; LHEFEvent * event; // Create TTree //Float_t Muon_E; //Float_t Electron_E; //Float_t Lepton_E; //Float_t Lepton_E_reco; //TTree * tree = new TTree("tree","lepton energy"); //tree->Branch("Lepton_E",&Lepton_E,"Lepton_E/F"); //tree->Branch("Lepton_E_reco",&Lepton_E_reco,"Lepton_E_reco/F"); //tree->Branch("Muon_E",&Muon_E,"Muon_E/F"); //tree->Branch("Electron_E",&Electron_E,"Electron_E/F"); // Book histograms TH1 * channel = new TH1F("channel", "ttbar event categorization", 7, 0.0, 7.0); TH1 * h_muon_energy = new TH1F("h_muon_energy", "muon energy distribution", 5000, 0, 500); TH1 * h_electron_energy = new TH1F("h_electron_energy", "electron energy distribution", 5000, 0, 500); TH1 * h_lepton_energy = new TH1F("h_lepton_energy", "lepton energy distribution", 5000, 0, 500); //TH1 * h_muon_energy_acc = new TH1F("h_muon_energy_acc", "muon energy distribution", 5000, 0, 500); //TH1 * h_electron_energy_acc = new TH1F("h_electron_energy_acc", "electron energy distribution", 5000, 0, 500); TH1 * h_lepton_energy_acc = new TH1F("h_lepton_energy_acc", "lepton energy distribution", 5000, 0, 500); //TH1 * h_muon_energy_reco = new TH1F("h_muon_energy_reco", "muon energy distribution at RECO", 5000, 0, 500); //TH1 * h_electron_energy_reco = new TH1F("h_electron_energy_reco", "electron energy distribution at RECO", 5000, 0, 500); TH1 * h_lepton_energy_reco = new TH1F("h_lepton_energy_reco", "lepton energy distribution at RECO", 5000, 0, 500); TH2 * h2_lepton_energy_response = new TH2F("h2_lepton_energy_response", "lepton energy response", 5000, 0, 500,5000,0,500); //TH1 * h_muon_energy_reco_S2 = new TH1F("h_muon_energy_reco_S2", "muon energy distribution at RECO", 5000, 0, 500); //TH1 * h_electron_energy_reco_S2 = new TH1F("h_electron_energy_reco_S2", "electron energy distribution at RECO", 5000, 0, 500); //TH1 * h_lepton_energy_reco_S2 = new TH1F("h_lepton_energy_reco_S2", "lepton energy distribution at RECO", 5000, 0, 500); //TH1 * h_lepton_nbjets_reco_S2 = new TH1F("h_lepton_nbjets_reco_S2","number of b jets",5,0,5); //TH1 * h_muon_energy_reco_final = new TH1F("h_muon_energy_reco_final", "muon energy distribution at RECO", 5000, 0, 500); //TH1 * h_electron_energy_reco_final = new TH1F("h_electron_energy_reco_final", "electron energy distribution at RECO", 5000, 0, 500); TH1 * h_lepton_energy_reco_final = new TH1F("h_lepton_energy_reco_final", "lepton energy distribution at RECO", 5000, 0, 500); TH2 * h2_lepton_energy_final_response = new TH2F("h2_lepton_energy_final_response", "lepton energy response", 5000, 0, 500,5000,0,500); //std::vector<float> lepton_E; //std::vector<float> lepton_E_final; int ndileptonic = 0; //ee, mm, tautau int ndileptonic2 = 0; //ee, mm, tau->ee, mm int ndileptonic3 = 0; //ee, mm int nsemileptonic = 0; int nsemileptonic2 = 0; int nsemileptonic3 = 0; int nhadronic = 0; // Loop over all events for(Int_t entry = 0; entry < numberOfEntries; ++entry) { //if( entry == 100000) break; if( entry%1000 == 0) cout << "starting with " << entry << endl; // Load selected branches with data from specified event treeReader->ReadEntry(entry); int nmuons = 0; int nelectrons= 0; int ntaumuons = 0; int ntauelectrons= 0; int ntaus = 0 ; int nhadrons = 0 ; // If event contains at least 1 particle int ntop = 0; double genweight = 1.0; if(branchEvent->GetEntries() > 0) { event = (LHEFEvent * ) branchEvent->At(0); genweight = event->Weight; //cout << "event number = " << event->Number << endl; //cout << "event weight = " << event->Weight << endl; } //Lepton_E = -1.0; if(branchParticle->GetEntries() > 0) { for(int i = 0; i < branchParticle->GetEntriesFast() ; i++){ if(ntop == 2) break; particle = (GenParticle *) branchParticle->At(i); int status = particle->Status; bool LO = true; //if( LO ) cout << "THIS IS LO..." << endl; if( status != 3) continue; int id = particle->PID; double gen_pt = particle->PT; double gen_eta = particle->Eta; //Leading order if( LO) { if( abs(id) == 11 ){ genelectron = particle; double energy = genelectron->E; h_electron_energy->Fill( energy, genweight ); h_lepton_energy->Fill( energy, genweight ); //Lepton_E = energy; //for(int i=0; i < nmass; i++){ // float w = g2[i]->Eval( energy ); // integral2[i] = integral2[i] + w ; //} //lepton_E.push_back( energy ); if( energy > 20 && fabs(gen_eta) < 2.4) { //h_electron_energy_acc->Fill( energy, genweight ); h_lepton_energy_acc->Fill( energy, genweight ); nmuons++; } //daughter1 = (GenParticle*) branchParticle->At( particle->D1); //daughter2 = (GenParticle*) branchParticle->At( particle->D2); //int d1_id = abs(daughter1->PID); //int d2_id = abs(daughter2->PID); //cout << "electron daughter " << d1_id << " , " << d2_id << endl; }else if( abs(id) == 13 ){ genmuon = particle; double energy = genmuon->E; h_muon_energy->Fill( energy, genweight ); h_lepton_energy->Fill( energy, genweight ); //Lepton_E = energy; //for(int i=0; i < nmass; i++){ // float w = g2[i]->Eval( energy ); // integral2[i] = integral2[i] + w ; //} //lepton_E.push_back( energy ); if( energy > 20 && fabs(gen_eta) < 2.4) { //h_muon_energy_acc->Fill( energy, genweight ); h_lepton_energy_acc->Fill( energy, genweight ); nelectrons++; } //int d1_id = -1; //int d2_id = -1; //if( particle->D1 >= branchParticle->GetEntries()){ // daughter1 = (GenParticle*) branchParticle->At( particle->D1); // int d1_id = abs(daughter1->PID); //} //if( particle->D1 >= branchParticle->GetEntries()){ // daughter1 = (GenParticle*) branchParticle->At( particle->D1); // int d1_id = abs(daughter1->PID); //} //cout << "muon daughter " << d1_id << " , " << d2_id << endl; } //NLO }else if( abs(id) == 6 ) { ntop++; particle = (GenParticle*) branchParticle->At( i ) ; if( particle->D1 >= branchParticle->GetEntries() ) continue; bool lasttop = false ; while( !lasttop ){ if( particle->D1 >= branchParticle->GetEntries() ) break; GenParticle * d = (GenParticle *) branchParticle->At( particle->D1 ); if( abs(d->PID) != 6 ) { lasttop = true; } else { particle = d ; } } if( particle->D1 >= branchParticle->GetEntries() || particle->D2 >= branchParticle->GetEntries() ){ continue; } daughter1 = (GenParticle*) branchParticle->At( particle->D1) ; daughter2 = (GenParticle*) branchParticle->At( particle->D2) ; bool lastW = false; int d1_id = abs(daughter1->PID); int d2_id = abs(daughter2->PID); //cout << "top daughter " << d1_id << " , " << d2_id << endl; while( !lastW) { if( daughter1->D1 >= branchParticle->GetEntries() ) break; GenParticle * d = (GenParticle *) branchParticle->At( daughter1->D1 ); if( abs(d->PID) != 24 ) { lastW = true; } else { daughter1 = d ; } } if( daughter1->D1 >= branchParticle->GetEntries() || daughter1->D2 >= branchParticle->GetEntries() ){ continue; } granddaughter1_1 = (GenParticle*) branchParticle->At( daughter1->D1) ; granddaughter1_2 = (GenParticle*) branchParticle->At( daughter1->D2) ; granddaughter2_1 = (GenParticle*) branchParticle->At( daughter2->D1) ; granddaughter2_2 = (GenParticle*) branchParticle->At( daughter2->D2) ; int gd1_1_id = abs(granddaughter1_1->PID); int gd1_2_id = abs(granddaughter1_2->PID); int gd2_1_id = abs(granddaughter2_1->PID); int gd2_2_id = abs(granddaughter2_2->PID); //cout << "W daughters = " << gd1_1_id << " , " << gd1_2_id << " , " << gd2_1_id << " , " << gd2_2_id << endl; int W_dau_status = granddaughter1_1->Status ; //if( gd1_1_id > gd1_2_id ) cout << "Something is WRONG ! " << endl; GenParticle * le = (GenParticle * ) branchParticle->At( granddaughter1_1->D1 ); //GenParticle * leda = (GenParticle * ) branchParticle->At( le->D1); if( gd1_1_id == 11 || gd1_1_id == 13 ){ cout << le->D1 << " , " << le->D2 << endl; // cout << " original id and status = " << gd1_1_id << " , " << W_dau_status << " le id and status = " << le->PID << " , " << le->Status << " leda id and status = " << leda->PID << " , " << leda->Status << endl; } if( gd1_1_id == 11 ) { nelectrons++; //genelectron = granddaughter1_2; genelectron = le; } else if( gd1_1_id == 13 ) { nmuons++; //genmuon = granddaughter1_2; genmuon = le; } else if( gd1_1_id == 15 ) { ntaus++; /* if( granddaughter1_2->D1 >= branchParticle->GetEntries() || granddaughter1_2->D2 >= branchParticle->GetEntries() ){ continue; } GenParticle * taudaughter1 = (GenParticle*) branchParticle->At( granddaughter1_2->D1) ; GenParticle * taudaughter2 = (GenParticle*) branchParticle->At( granddaughter1_2->D2) ; int taud1_id = abs(taudaughter1->PID); int taud2_id = abs(taudaughter2->PID); //cout << "tau daughter = " << taud1_id << " " << taud2_id << endl; if( taud1_id == 11 || taud1_id == 12 ) ntauelectrons++; else if( taud1_id == 13 || taud1_id == 14 ) ntaumuons++; else if( taud1_id == 15 || taud1_id == 16 ) { if( taudaughter1->D1 >= branchParticle->GetEntries() || taudaughter1->D2 >= branchParticle->GetEntries() ){ continue; } GenParticle * taugranddaughter1 = (GenParticle*) branchParticle->At( taudaughter1->D1) ; GenParticle * taugranddaughter2 = (GenParticle*) branchParticle->At( taudaughter1->D2) ; int taugd1_id = abs(taugranddaughter1->PID); int taugd2_id = abs(taugranddaughter2->PID); //cout << "tau grand daughter = " << taugd1_id << " " << taugd2_id << endl; if( taugd1_id == 11 || taugd1_id == 12 ) ntauelectrons++; else if( taugd1_id == 13 || taugd1_id == 14 ) ntaumuons++; ㅜㅜ else { continue; } } else { continue; } */ }else{ nhadrons++; } //cout << "nelectrons = " << nelectrons << " nmuons = " << nmuons << " ntaus = " << ntaus << " nhadrons = " << nhadrons << endl; } } } if( LO ){ }else{ int remaining = 0 ; int nleptons = nelectrons + nmuons + ntaus; if( nleptons == 2 && nhadrons == 0){ //cout << "dilepton" << endl; ndileptonic++; if( ntaus ==0 || ( ntaus == 1 && (ntauelectrons+ntaumuons) == 1) || (ntaus == 2 && (ntauelectrons+ntaumuons) == 2) ) { ndileptonic2++; } if( ntaus == 0) ndileptonic3++; }else if( nleptons == 1 && nhadrons == 1){ //cout << "lepton+jets" << endl; nsemileptonic++; if( ntaus ==0 || ( ntaus == 1 && (ntauelectrons+ntaumuons) == 1) ) nsemileptonic2++; if( ntaus == 0 ) { nsemileptonic3++; if( nmuons ) { h_muon_energy->Fill(genmuon->E, genweight); h_lepton_energy->Fill(genmuon->E, genweight); } if( nelectrons ) { h_electron_energy->Fill(genelectron->E, genweight); h_lepton_energy->Fill(genelectron->E, genweight); } } }else if ( nleptons == 0 && nhadrons == 2 ){ //cout << "hadronic" << endl; nhadronic++; }else{ //cout << "remaining" << endl; remaining++; } } Muon * mymuon; Electron * myelectron; bool passmuon = false; bool passelectron = false; if(branchMuon->GetEntries() > 0) { bool mymuonpass = false; for(int i = 0; i < branchMuon->GetEntriesFast() ; i++){ Muon * muon = (Muon *) branchMuon->At(i); if( muon->P4().E() > 20 && fabs( muon->P4().Eta() < 2.4) ){ mymuon = muon; mymuonpass = true; } break; } if( mymuonpass && ( nmuons > 0 || nelectrons > 0 ) ){ //h_muon_energy_reco->Fill(mymuon->P4().E(), genweight); h_lepton_energy_reco->Fill(mymuon->P4().E(), genweight); h2_lepton_energy_response->Fill(mymuon->P4().E(), genmuon->E, genweight); passmuon = true; } } if(branchElectron->GetEntries() > 0) { bool myelectronpass = false; for(int i = 0; i < branchElectron->GetEntriesFast() ; i++){ Electron * electron = (Electron *) branchElectron->At(i); if( electron->P4().E() > 20 && fabs( electron->P4().Eta() < 2.4) ){ myelectron = electron; myelectronpass = true; } break; } if( myelectronpass && ( nmuons > 0 || nelectrons > 0 ) ){ //h_electron_energy_reco->Fill(myelectron->P4().E(), genweight); h_lepton_energy_reco->Fill(myelectron->P4().E(), genweight); h2_lepton_energy_response->Fill(myelectron->P4().E(), genelectron->E, genweight); passelectron = true; } } if(branchJet->GetEntries() > 0 ) { int njets = 0; int nbjets = 0; for(int i = 0; i < branchJet->GetEntriesFast() ; i++){ Jet * jet = (Jet *) branchJet->At(i); if( jet->P4().Pt() > 30 && fabs( jet->P4().Eta() < 2.5) ){ njets++; if( jet->BTag ) nbjets++; } } } //Muon_E = -9.0; //Electron_E = -9.0; //Lepton_E_reco = -1.0; float Energy = 9.0; if( passelectron && !passmuon && njets >= 4){ float myele_energy = myelectron->P4().E(); //h_electron_energy_reco_S2->Fill(myele_energy, genweight); //h_lepton_energy_reco_S2->Fill(myele_energy, genweight); //h_lepton_nbjets_reco_S2->Fill(nbjets); if( nbjets >= 2 ){ //h_electron_energy_reco_final->Fill(myele_energy, genweight); h_lepton_energy_reco_final->Fill(myele_energy, genweight); h2_lepton_energy_final_response->Fill(myele_energy, genelectron->E, genweight); } //lepton_E_final.push_back( myelectron->P4().E() ); //for(int i=0; i < nmass; i++){ // float corr = 1.0/ h_acc->Interpolate( myelectron->P4().E() ); // float w = g2[i]->Eval( myelectron->P4().E() ); //integral2[i] = integral2[i] + w*corr ; //} //Electron_E = myele_energy; //Lepton_E_reco = myele_energy; } if( passmuon && !passelectron && njets >= 4){ float mymuon_energy = mymuon->P4().E(); //h_muon_energy_reco_S2->Fill(mymuon_energy, genweight); //h_lepton_energy_reco_S2->Fill(mymuon_energy, genweight); //h_lepton_nbjets_reco_S2->Fill(nbjets); if( nbjets >= 2 ){ // h_muon_energy_reco_final->Fill(mymuon_energy, genweight); h_lepton_energy_reco_final->Fill(mymuon_energy, genweight); h2_lepton_energy_final_response->Fill(mymuon_energy, genmuon->E, genweight); } //lepton_E_final.push_back( mymuon->P4().E() ); //for(int i=0; i < nmass; i++){ // float corr = 1.0/ h_acc->Interpolate( mymuon->P4().E() ); // float w = g2[i]->Eval( mymuon->P4().E() ); //integral2[i] = integral2[i] + w*corr ; //} //Muon_E = mymuon_energy; //Lepton_E_reco = mymuon_energy; } /* for(int i=0; i < nmass; i++){ //for(int i=0; i < 0; i++){ float lenergy = -9; if( Muon_E > 0 && Electron_E < 0 ) lenergy = Muon_E; if( Muon_E < 0 && Electron_E > 0 ) lenergy = Electron_E; float acc = h_acc->Interpolate( lenergy ); integral2[i] = integral2[i] + g2[i]->Eval( lenergy ) /acc ; integral3[i] = integral3[i] + g3[i]->Eval( lenergy ) /acc ; integral5[i] = integral5[i] + g5[i]->Eval( lenergy ) /acc ; integral15[i] = integral15[i] + g15[i]->Eval( lenergy ) /acc ; } */ //if( passmuon && passelectron) cout << "Lepton E = " << Lepton_E << endl; //tree->Fill(); } //tree->Print(); // for(int m=0; m < nmass; m++){ // for(int i=0; i < 400;i++){ // float bincenter = h_lepton_energy->GetBinCenter(i+1); // float binconten = h_lepton_energy->GetBinContent(i+1); // float weight_value = g2[m]->Eval( bincenter ); // integral2[m] = integral2[m] + weight_value*binconten; // } // } /* for(int m=0; m < nmass; m++){ for(int i=0; i < lepton_E_final.size() ;i++){ float energy = lepton_E_final[i]; float corr = 1.0/ h_acc->Interpolate( energy ); float weight_value2 = g2[m]->Eval( bincenter ); float weight_value3 = g3[m]->Eval( bincenter ); float weight_value5 = g5[m]->Eval( bincenter ); float weight_value15 = g15[m]->Eval( bincenter ); integral2[m] = integral2[m] + weight_value2*corr; integral3[m] = integral3[m] + weight_value3*corr; integral5[m] = integral5[m] + weight_value5*corr; integral15[m] = integral15[m] + weight_value15*corr; } } TGraph * final2 = new TGraph(); TGraph * final3 = new TGraph(); TGraph * final5 = new TGraph(); TGraph * final15 = new TGraph(); for (Int_t i=0;i<nmass;i++) { final2->SetPoint(i, mymass[i], integral2[i]); final3->SetPoint(i, mymass[i], integral3[i]); final5->SetPoint(i, mymass[i], integral5[i]); final15->SetPoint(i, mymass[i], integral15[i]); } final2->SetName("n2"); final3->SetName("n3"); final5->SetName("n5"); final15->SetName("n15"); final2->Write(); final3->Write(); final5->Write(); final15->Write(); */ if( remaining != 0 ) cout << "Someting is wrong" << endl; //TCanvas * c = new TCanvas("c","c",1000,600); channel->SetBinContent(1,ndileptonic); channel->SetBinContent(2,ndileptonic2); channel->SetBinContent(3,ndileptonic3); channel->SetBinContent(4,nsemileptonic); channel->SetBinContent(5,nsemileptonic2); channel->SetBinContent(6,nsemileptonic3); channel->SetBinContent(7,nhadronic); channel->GetXaxis()->SetBinLabel(1,"Dileptonic"); channel->GetXaxis()->SetBinLabel(2,"DileptonicTau"); channel->GetXaxis()->SetBinLabel(3,"DileptonicNoTau"); channel->GetXaxis()->SetBinLabel(4,"Semileptonic"); channel->GetXaxis()->SetBinLabel(5,"SemileptonicTau"); channel->GetXaxis()->SetBinLabel(6,"SemileptonicNoTau"); channel->GetXaxis()->SetBinLabel(7,"Hadronic"); //int nBins = 400; //h_lepton_energy->AddBinContent(nBins, h_lepton_energy->GetBinContent(nBins+1)); //h_lepton_energy_reco_final->AddBinContent(nBins, h_lepton_energy_reco_final->GetBinContent(nBins+1)); // Show resulting histograms channel->SetStats(0000); double scale = 1.0/numberOfEntries; channel->Scale( scale ); //channel->Draw("HText0"); /* channel->Write(); h_muon_energy->Write(); h_electron_energy->Write(); h_lepton_energy->Write(); h_muon_energy_acc->Write(); h_electron_energy_acc->Write(); h_lepton_energy_acc->Write(); h_muon_energy_reco->Write(); h_electron_energy_reco->Write(); h_lepton_energy_reco->Write(); h_muon_energy_reco_final->Write(); h_electron_energy_reco_final->Write(); h_lepton_energy_reco_final->Write(); */ f->Write(); f->Close(); }
void makeNeuralMtautauPerformancePlots() { std::string inputFileName = "../test/testNeuralMtautau.root"; TFile* inputFile = TFile::Open(inputFileName.data()); std::string histogramName = "histogramRecVsGenMass"; TH2* histogram2d = dynamic_cast<TH2*>(getHistogram(inputFile, "", histogramName.data())); const int numGenMassBins = 17; double genMassBins[] = { 0., 50., 60., 70., 80., 90., 100., 110., 120., 130., 140., 160., 200., 250., 300., 350., 400., 500. }; int genMassBin_index = 0; TH1* histogram1dTruncatedSum = 0; TGraphErrors* graph_mean = new TGraphErrors(numGenMassBins); TGraphErrors* graph_rms = new TGraphErrors(numGenMassBins); int numBins2dX = histogram2d->GetNbinsX(); for ( int iBin2dX = 1; iBin2dX <= numBins2dX; ++iBin2dX ) { std::string histogram1dName = std::string(histogram2d->GetName()).append(Form("BinX%i", iBin2dX)); TH1* histogram1d = histogram2d->ProjectionX(histogram1dName.data(), iBin2dX, iBin2dX); std::string histogram1dTruncatedName = std::string(histogram2d->GetName()).append(Form("BinX%i_truncated", iBin2dX)); TH1* histogram1dTruncated = new TH1D(histogram1dTruncatedName.data(), histogram1dTruncatedName.data(), 200, 0., 2.); double mTauTau_gen = histogram2d->GetXaxis()->GetBinCenter(iBin2dX); //if ( mTauTau_gen > 100. ) continue; //std::cout << "iBin2dX = " << iBin2dX << ": mTauTau(gen) = " << mTauTau_gen << std::endl; //std::cout << "histogram1d: mean = " << histogram1d->GetMean() << "," // << " rms = " << histogram1d->GetRMS() << std::endl; int numBins1d = histogram1d->GetNbinsX(); for ( int iBin1d = 1; iBin1d <= numBins1d; ++iBin1d ) { double mTauTau_rec = histogram1d->GetBinCenter(iBin1d); //std::cout << "iBin1d = " << iBin1d << ": mTauTau(rec) = " << mTauTau_rec << std::endl; double ratio = mTauTau_rec/mTauTau_gen; //std::cout << "ratio = " << ratio << std::endl; double binContent = histogram1d->GetBinContent(iBin1d); if ( binContent > 1.e-2 ) histogram1dTruncated->Fill(ratio, binContent); } //std::cout << "histogram1dTruncated: mean = " << histogram1dTruncated->GetMean() << "," // << " rms = " << histogram1dTruncated->GetRMS() << std::endl; delete histogram1d; if ( mTauTau_gen > genMassBins[genMassBin_index + 1] && mTauTau_gen < genMassBins[numGenMassBins - 1] ) { double x = 0.5*(genMassBins[genMassBin_index] + genMassBins[genMassBin_index + 1]); double xErr = 0.5*(genMassBins[genMassBin_index + 1] - genMassBins[genMassBin_index]); double y_mean = histogram1dTruncatedSum->GetMean(); double yErr_mean = histogram1dTruncatedSum->GetMeanError(); double y_rms = histogram1dTruncatedSum->GetRMS(); double yErr_rms = histogram1dTruncatedSum->GetRMSError(); //std::cout << "mTauTau(gen) = " << x << ": mean = " << y_mean << " +/- " << yErr_mean << "," // << " rms = " << y_rms << " +/- " << yErr_rms << std::endl; graph_mean->SetPoint(genMassBin_index, x, y_mean); graph_mean->SetPointError(genMassBin_index, xErr, yErr_mean); graph_rms->SetPoint(genMassBin_index, x, y_rms); graph_rms->SetPointError(genMassBin_index, xErr, yErr_rms); delete histogram1dTruncatedSum; histogram1dTruncatedSum = 0; ++genMassBin_index; } if ( !histogram1dTruncatedSum ) { histogram1dTruncatedSum = histogram1dTruncated; } else { histogram1dTruncatedSum->Add(histogram1dTruncated); delete histogram1dTruncated; } } delete histogram1dTruncatedSum; TCanvas* canvas = new TCanvas("canvas", "canvas", 800, 600); canvas->SetFillColor(10); canvas->SetBorderSize(2); canvas->SetLeftMargin(0.12); canvas->SetBottomMargin(0.12); canvas->SetLogy(); TH1* dummyHistogram = new TH1F("dummyHistogram", "dummyHistogram", 50, 0., 500.); dummyHistogram->SetStats(false); dummyHistogram->SetTitle(""); dummyHistogram->SetMinimum(1.e-2); dummyHistogram->SetMaximum(1.e+1); TAxis* xAxis = dummyHistogram->GetXaxis(); xAxis->SetTitle("M_{#tau#tau}^{gen} / GeV"); xAxis->SetTitleOffset(1.15); TAxis* yAxis = dummyHistogram->GetYaxis(); yAxis->SetTitle("M_{#tau#tau}^{rec} / GeV"); yAxis->SetTitleOffset(1.30); dummyHistogram->Draw("axis"); graph_mean->SetMarkerStyle(20); graph_mean->SetMarkerColor(1); graph_mean->Draw("P"); graph_rms->SetMarkerStyle(20); graph_rms->SetMarkerColor(2); graph_rms->Draw("P"); TLegend* legend = new TLegend(0.64, 0.69, 0.88, 0.87, "", "brNDC"); legend->SetBorderSize(0); legend->SetFillColor(0); legend->AddEntry(graph_mean, "<M_{#tau#tau}^{rec}/M_{#tau#tau}^{gen}>", "p"); legend->AddEntry(graph_rms, "#sigma(M_{#tau#tau}^{rec}/M_{#tau#tau}^{gen})", "p"); legend->Draw(); canvas->Update(); std::string outputFileName = "neuralMtautauPerformancePlot.eps"; size_t idx = outputFileName.find_last_of('.'); std::string outputFileName_plot = std::string(outputFileName, 0, idx); if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName, idx)).data()); canvas->Print(std::string(outputFileName_plot).append(".png").data()); canvas->Print(std::string(outputFileName_plot).append(".pdf").data()); delete graph_mean; delete graph_rms; delete dummyHistogram; delete legend; delete canvas; }
// //---------------------------------------------------------------------- // int fittp0( char* hs ) { TH1 *h = (TH1*)gDirectory->Get(hs); if( h == NULL ){ cout << hs << " does not exist\n"; } else{ h->SetMarkerStyle(21); h->SetMarkerSize(0.8); h->SetStats(1); gStyle->SetOptFit(101); gROOT->ForceStyle(); double dx = h->GetBinWidth(1); double nmax = h->GetBinContent(h->GetMaximumBin()); double xmax = h->GetBinCenter(h->GetMaximumBin()); double nn = 7*nmax; int nb = h->GetNbinsX(); double n1 = h->GetBinContent(1); double n9 = h->GetBinContent(nb); double bg = 0.5*(n1+n9); double x1 = h->GetBinCenter(1); double x9 = h->GetBinCenter(nb); cout << hs << ": " << x1 << " - " << x9 << endl; // create a TF1 with the range from x1 to x9 and 5 parameters TF1 *tp0Fcn = new TF1( "tp0Fcn", tp0Fit, x1, x9, 5 ); tp0Fcn->SetParName( 0, "mean" ); tp0Fcn->SetParName( 1, "sigma" ); tp0Fcn->SetParName( 2, "nu" ); tp0Fcn->SetParName( 3, "area" ); tp0Fcn->SetParName( 4, "BG" ); tp0Fcn->SetNpx(500); tp0Fcn->SetLineWidth(4); tp0Fcn->SetLineColor(kMagenta); tp0Fcn->SetLineColor(kGreen); // set start values for some parameters: cout << hs << " " << dx << ", " << nn << ", " << xmax << endl; tp0Fcn->SetParameter( 0, xmax ); // peak position tp0Fcn->SetParameter( 1, 4*dx ); // width tp0Fcn->SetParameter( 2, 2.2 ); // nu tp0Fcn->SetParameter( 3, nn ); // N tp0Fcn->SetParameter( 4, bg ); h->Fit( "tp0Fcn", "R", "ep" ); // h->Fit("tp0Fcn","V+","ep"); h->Draw("histepsame"); // data again on top } }
void makeSplitQCDhist_PythiaBinned(vector<string> folders, const string histname, const string htrange, const string htbinlabel, const hist_t histinfo) { const float scaleTo = fDATA_LUMI; // pb TLegend *leg = new TLegend(0.6,0.65,0.9,0.9); leg->SetTextFont(42); vector<TH1*> hists; new TCanvas(); gPad->SetLogy(); gPad->SetTickx(); gPad->SetTicky(); stringstream title; title << htrange << " [" << histinfo.name << "];" << histinfo.title; cout << title.str() << endl; TH1* Hist = GetHist(histname); Hist->SetTitle(title.str().c_str()); Hist->SetMarkerStyle(20); Hist->SetStats(0); Hist->Rebin(histinfo.rebin); Hist->Draw("P"); /* for (unsigned i = 0; i < folders.size(); ++i) { string njet(""); if (i==0) njet += "[2-3]"; else if (i==1) njet += "[4-5]"; else if (i==2) njet += "[6-7]"; else if (i==3) njet += "#geq 8"; */ /*if (i==0) njet += "3"; else if (i==1) njet += "4"; else if (i==2) njet += "5"; else if (i==3) njet += "6"; else if (i==4) njet += "7"; else if (i==5) njet += "8";*/ /* stringstream title, histName; title << htrange << ";" << histinfo.title; cout << title.str() << endl; histName << folders.at(i) << "/" << histname;; hists.push_back(GetHist(histName.str())); hists.at(i)->SetTitle(title.str().c_str()); hists.at(i)->SetMarkerStyle(20+i); hists.at(i)->SetMarkerColor(1+i*2); hists.at(i)->SetStats(0); hists.at(i)->Rebin(histinfo.rebin); if (histinfo.normalizeByBinWidth) NormByBinWidth(hists.at(i)); stringstream legname; legname << "Njets " << njet; leg->AddEntry(hists.at(i), legname.str().c_str()); if (i==0) hists.at(i)->Draw("P"); else hists.at(i)->Draw("same P"); } leg->Draw(); */ }
void recurseOverKeys(TDirectory *target, TString imageType) { // TString path( (char*)strstr( target->GetPath(), ":" ) ); // path.Remove( 0, 2 ); // cout << path << endl; // sourceFile->cd( path ); target->cd(); TDirectory *current_sourcedir = gDirectory; TKey *key; TIter nextkey(current_sourcedir->GetListOfKeys()); TCanvas *canvasDefault = new TCanvas(); while ( (key = (TKey*)nextkey() ) ) { TObject* obj = key->ReadObj(); if (obj->IsA()->InheritsFrom("TH1") ) { // ************************** // Plot & Save this Histogram TH1* h = (TH1*)obj; h->SetStats(displayStatsBox); TString histName = h->GetName(); // Now to label the X-axis! // if (autoLabelXaxis) { // if ( histName.Contains("Phi") ) { // h->GetXaxis()->SetTitle("#phi"); // } else if ( histName.Contains("Eta") ) { // h->GetXaxis()->SetTitle("#eta"); // } else if ( histName.Contains("Pt") ) { // h->GetXaxis()->SetTitle("p_{T} (GeV)"); // } else if ( histName.Contains("Et") ) { // h->GetXaxis()->SetTitle("E_{T} (GeV)"); // } // } // h->SetLineColor(lineColor); // h->SetLineWidth(lineWidth); // ******************************** // A trick to decide whether to have log or no-log y axis // get hist max y value if (autoLogYaxis) { Double_t testYvalue = h->GetMaximum(); //cout << testYvalue << endl; if (testYvalue > 1.0) { Double_t maxy = log10(testYvalue); // get hist min y value Double_t miny = log10(h->GetMinimum(1.0)); // log scale if more than 3 powers of 10 between low and high bins if ( (maxy-miny) > 3.0 ) { canvasDefault->SetLogy(1); } } } // End of log or no-log y axis decision // ******************************** h->Draw(drawOptions1D); canvasDefault->Modified(); canvasDefault->Update(); // gPad->Print(outputFolder+path+"/"+histName+outputType); TString outputFolder = "images/"; gPad->Print(outputFolder+histName+"."+imageType); // To store the root file name in image file name: //canvasDefault->Print(outputFolder+histFileName+histName+outputType); // if (printOutput) cout << outputFolder+path+"/"+histName+outputType << endl; canvasDefault->SetLogy(0); // reset to no-log - prevents errors // ************************** } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) { // it's a subdirectory cout << "Found subdirectory " << obj->GetName() << endl; // gSystem->MakeDirectory(outputFolder+path+"/"+obj->GetName()); // obj is now the starting point of another round of merging // obj still knows its depth within the target file via // GetPath(), so we can still figure out where we are in the recursion recurseOverKeys((TDirectory*)obj, imageType); } // end of IF a TDriectory } // end of LOOP over keys }
void FitOmegaPeak(const bool fixOmegaMass=false, const double r_min=650.0, const double r_max=900.0) { const char* hist_name = "ggg_IM"; const int npx = 500; const double omega_mass = 782.0; const double expected_width = 15.0; TH1* h = NULL; gDirectory->GetObject(hist_name, h); if(!h) { cerr << "Can't find histogram" << endl; return; } TF1* sig = new TF1("sig", "gaus", r_min, r_max); sig->SetLineColor(kGreen); sig->SetNpx(npx); // height sig->SetParameter(0, 0.5 * h->GetMaximum()); // position if(fixOmegaMass) sig->FixParameter(1, omega_mass); else sig->SetParameter(1, omega_mass); // width sig->SetParameter(2, expected_width); TF1* bg = new TF1("bg", "pol2", r_min, r_max); bg->SetLineColor(kBlue); bg->SetParameter(0,0); bg->SetParName(0, "BG p_{0}"); bg->SetParameter(1,0); bg->SetParName(1, "BG p_{1}"); bg->SetParameter(2,0); bg->SetParName(2, "BG p_{2}"); TFSum::FitRanged(h, bg, 650, 730, 830, 900); //bg->FixParameter(0, bg->GetParameter(0)); //bg->FixParameter(1, bg->GetParameter(1)); //bg->FixParameter(2, bg->GetParameter(2)); TFSum* sum = new TFSum("sum", sig, bg, r_min, r_max); sum->SetNpx(npx); TCanvas* c = new TCanvas(); c->SetTitle(Form("Fit to %s", hist_name)); h->SetStats(true); gStyle->SetOptFit(1); h->Draw(); h->Fit(sum->Function(), "REM0NB"); sum->SyncToFcts(); sum->Draw(); const double total_area = sum->Function()->Integral(r_min, r_max); const double bg_area = bg->Integral(r_min, r_max); const double sig_area = total_area - bg_area; const double sig_to_bg = sig_area / bg_area; const double peak_pos = sig->GetParameter(1); cout << "Mass offset = " << peak_pos - omega_mass << " MeV\n"; cout << "Sig/BG = " << sig_to_bg << "\n"; cout << "Sig = " << sig_area << endl; // TODO: choose a position. Positions for TLatex are histogram coordinates. TLatex* label = new TLatex(r_min, h->GetMaximum(),Form("Signal content = %lf", sig_area)); label->Draw(); }
void FFT() { // Histograms // ========= //prepare the canvas for drawing TCanvas *myc = new TCanvas("myc", "Fast Fourier Transform", 800, 600); myc->SetFillColor(45); TPad *c1_1 = new TPad("c1_1", "c1_1",0.01,0.67,0.49,0.99); TPad *c1_2 = new TPad("c1_2", "c1_2",0.51,0.67,0.99,0.99); TPad *c1_3 = new TPad("c1_3", "c1_3",0.01,0.34,0.49,0.65); TPad *c1_4 = new TPad("c1_4", "c1_4",0.51,0.34,0.99,0.65); TPad *c1_5 = new TPad("c1_5", "c1_5",0.01,0.01,0.49,0.32); TPad *c1_6 = new TPad("c1_6", "c1_6",0.51,0.01,0.99,0.32); c1_1->Draw(); c1_2->Draw(); c1_3->Draw(); c1_4->Draw(); c1_5->Draw(); c1_6->Draw(); c1_1->SetFillColor(30); c1_1->SetFrameFillColor(42); c1_2->SetFillColor(30); c1_2->SetFrameFillColor(42); c1_3->SetFillColor(30); c1_3->SetFrameFillColor(42); c1_4->SetFillColor(30); c1_4->SetFrameFillColor(42); c1_5->SetFillColor(30); c1_5->SetFrameFillColor(42); c1_6->SetFillColor(30); c1_6->SetFrameFillColor(42); c1_1->cd(); TH1::AddDirectory(kFALSE); //A function to sample TF1 *fsin = new TF1("fsin", "sin(x)+sin(2*x)+sin(0.5*x)+1", 0, 4*TMath::Pi()); fsin->Draw(); Int_t n=25; TH1D *hsin = new TH1D("hsin", "hsin", n+1, 0, 4*TMath::Pi()); Double_t x; //Fill the histogram with function values for (Int_t i=0; i<=n; i++){ x = (Double_t(i)/n)*(4*TMath::Pi()); hsin->SetBinContent(i+1, fsin->Eval(x)); } hsin->Draw("same"); fsin->GetXaxis()->SetLabelSize(0.05); fsin->GetYaxis()->SetLabelSize(0.05); c1_2->cd(); //Compute the transform and look at the magnitude of the output TH1 *hm =0; TVirtualFFT::SetTransform(0); hm = hsin->FFT(hm, "MAG"); hm->SetTitle("Magnitude of the 1st transform"); hm->Draw(); //NOTE: for "real" frequencies you have to divide the x-axes range with the range of your function //(in this case 4*Pi); y-axes has to be rescaled by a factor of 1/SQRT(n) to be right: this is not done automatically! hm->SetStats(kFALSE); hm->GetXaxis()->SetLabelSize(0.05); hm->GetYaxis()->SetLabelSize(0.05); c1_3->cd(); //Look at the phase of the output TH1 *hp = 0; hp = hsin->FFT(hp, "PH"); hp->SetTitle("Phase of the 1st transform"); hp->Draw(); hp->SetStats(kFALSE); hp->GetXaxis()->SetLabelSize(0.05); hp->GetYaxis()->SetLabelSize(0.05); //Look at the DC component and the Nyquist harmonic: Double_t re, im; //That's the way to get the current transform object: TVirtualFFT *fft = TVirtualFFT::GetCurrentTransform(); c1_4->cd(); //Use the following method to get just one point of the output fft->GetPointComplex(0, re, im); printf("1st transform: DC component: %f\n", re); fft->GetPointComplex(n/2+1, re, im); printf("1st transform: Nyquist harmonic: %f\n", re); //Use the following method to get the full output: Double_t *re_full = new Double_t[n]; Double_t *im_full = new Double_t[n]; fft->GetPointsComplex(re_full,im_full); //Now let's make a backward transform: TVirtualFFT *fft_back = TVirtualFFT::FFT(1, &n, "C2R M K"); fft_back->SetPointsComplex(re_full,im_full); fft_back->Transform(); TH1 *hb = 0; //Let's look at the output hb = TH1::TransformHisto(fft_back,hb,"Re"); hb->SetTitle("The backward transform result"); hb->Draw(); //NOTE: here you get at the x-axes number of bins and not real values //(in this case 25 bins has to be rescaled to a range between 0 and 4*Pi; //also here the y-axes has to be rescaled (factor 1/bins) hb->SetStats(kFALSE); hb->GetXaxis()->SetLabelSize(0.05); hb->GetYaxis()->SetLabelSize(0.05); delete fft_back; fft_back=0; // Data array - same transform // =========================== //Allocate an array big enough to hold the transform output //Transform output in 1d contains, for a transform of size N, //N/2+1 complex numbers, i.e. 2*(N/2+1) real numbers //our transform is of size n+1, because the histogram has n+1 bins Double_t *in = new Double_t[2*((n+1)/2+1)]; Double_t re_2,im_2; for (Int_t i=0; i<=n; i++){ x = (Double_t(i)/n)*(4*TMath::Pi()); in[i] = fsin->Eval(x); } //Make our own TVirtualFFT object (using option "K") //Third parameter (option) consists of 3 parts: //- transform type: // real input/complex output in our case //- transform flag: // the amount of time spent in planning // the transform (see TVirtualFFT class description) //- to create a new TVirtualFFT object (option "K") or use the global (default) Int_t n_size = n+1; TVirtualFFT *fft_own = TVirtualFFT::FFT(1, &n_size, "R2C ES K"); if (!fft_own) return; fft_own->SetPoints(in); fft_own->Transform(); //Copy all the output points: fft_own->GetPoints(in); //Draw the real part of the output c1_5->cd(); TH1 *hr = 0; hr = TH1::TransformHisto(fft_own, hr, "RE"); hr->SetTitle("Real part of the 3rd (array) tranfsorm"); hr->Draw(); hr->SetStats(kFALSE); hr->GetXaxis()->SetLabelSize(0.05); hr->GetYaxis()->SetLabelSize(0.05); c1_6->cd(); TH1 *him = 0; him = TH1::TransformHisto(fft_own, him, "IM"); him->SetTitle("Im. part of the 3rd (array) transform"); him->Draw(); him->SetStats(kFALSE); him->GetXaxis()->SetLabelSize(0.05); him->GetYaxis()->SetLabelSize(0.05); myc->cd(); //Now let's make another transform of the same size //The same transform object can be used, as the size and the type of the transform //haven't changed TF1 *fcos = new TF1("fcos", "cos(x)+cos(0.5*x)+cos(2*x)+1", 0, 4*TMath::Pi()); for (Int_t i=0; i<=n; i++){ x = (Double_t(i)/n)*(4*TMath::Pi()); in[i] = fcos->Eval(x); } fft_own->SetPoints(in); fft_own->Transform(); fft_own->GetPointComplex(0, re_2, im_2); printf("2nd transform: DC component: %f\n", re_2); fft_own->GetPointComplex(n/2+1, re_2, im_2); printf("2nd transform: Nyquist harmonic: %f\n", re_2); delete fft_own; delete [] in; delete [] re_full; delete [] im_full; }
void FFT() { //This tutorial illustrates the Fast Fourier Transforms interface in ROOT. //FFT transform types provided in ROOT: // - "C2CFORWARD" - a complex input/output discrete Fourier transform (DFT) // in one or more dimensions, -1 in the exponent // - "C2CBACKWARD"- a complex input/output discrete Fourier transform (DFT) // in one or more dimensions, +1 in the exponent // - "R2C" - a real-input/complex-output discrete Fourier transform (DFT) // in one or more dimensions, // - "C2R" - inverse transforms to "R2C", taking complex input // (storing the non-redundant half of a logically Hermitian array) // to real output // - "R2HC" - a real-input DFT with output in ¡Èhalfcomplex¡É format, // i.e. real and imaginary parts for a transform of size n stored as // r0, r1, r2, ..., rn/2, i(n+1)/2-1, ..., i2, i1 // - "HC2R" - computes the reverse of FFTW_R2HC, above // - "DHT" - computes a discrete Hartley transform // Sine/cosine transforms: // DCT-I (REDFT00 in FFTW3 notation) // DCT-II (REDFT10 in FFTW3 notation) // DCT-III(REDFT01 in FFTW3 notation) // DCT-IV (REDFT11 in FFTW3 notation) // DST-I (RODFT00 in FFTW3 notation) // DST-II (RODFT10 in FFTW3 notation) // DST-III(RODFT01 in FFTW3 notation) // DST-IV (RODFT11 in FFTW3 notation) //First part of the tutorial shows how to transform the histograms //Second part shows how to transform the data arrays directly //Authors: Anna Kreshuk and Jens Hoffmann //********* Histograms ********// //prepare the canvas for drawing TCanvas *myc = new TCanvas("myc", "Fast Fourier Transform", 800, 600); myc->SetFillColor(45); TPad *c1_1 = new TPad("c1_1", "c1_1",0.01,0.67,0.49,0.99); TPad *c1_2 = new TPad("c1_2", "c1_2",0.51,0.67,0.99,0.99); TPad *c1_3 = new TPad("c1_3", "c1_3",0.01,0.34,0.49,0.65); TPad *c1_4 = new TPad("c1_4", "c1_4",0.51,0.34,0.99,0.65); TPad *c1_5 = new TPad("c1_5", "c1_5",0.01,0.01,0.49,0.32); TPad *c1_6 = new TPad("c1_6", "c1_6",0.51,0.01,0.99,0.32); c1_1->Draw(); c1_2->Draw(); c1_3->Draw(); c1_4->Draw(); c1_5->Draw(); c1_6->Draw(); c1_1->SetFillColor(30); c1_1->SetFrameFillColor(42); c1_2->SetFillColor(30); c1_2->SetFrameFillColor(42); c1_3->SetFillColor(30); c1_3->SetFrameFillColor(42); c1_4->SetFillColor(30); c1_4->SetFrameFillColor(42); c1_5->SetFillColor(30); c1_5->SetFrameFillColor(42); c1_6->SetFillColor(30); c1_6->SetFrameFillColor(42); c1_1->cd(); TH1::AddDirectory(kFALSE); //A function to sample TF1 *fsin = new TF1("fsin", "exp(-(x-679.)/40.0)*TMath::Erfc(-(1/sqrt(2))*((x-679.)/2.0 + 0.05))", 0, 1023); TF1 *model = new TF1("model", "[0]*exp(-(x-[1])/[2])*TMath::Erfc(-(1/sqrt(2))*((x-[1])/[3] + [3]/[2]))", 0, 1023); model->SetParameter( 0, 1. ); model->SetParameter( 1, 679. ); model->SetParameter( 2, 40. ); model->SetParameter( 3, 2. ); model->SetLineColor( kViolet ); TF1 *model2 = new TF1("model2", "[0]*exp(-(x-[1])/[2])*TMath::Erfc(-(1/sqrt(2))*((x-[1])/[3] + [3]/[2])) + [4]*sin(2*TMath::Pi()*[5]*x)", 0, 1023); model2->SetParameter( 0, 1. ); model2->SetParameter( 1, 679. ); model2->SetParameter( 2, 40. ); model2->SetParameter( 3, 2. ); model2->SetParameter( 4, 0.05 ); model2->SetParameter( 5, 2. ); model2->SetLineColor( kViolet ); //fsin->Draw(); Int_t n=1024; TH1D *hsin = new TH1D("hsin", "hsin", n+1, 0, 1023); Double_t x; //hsin->Fit( model,"MLR" ); //Fill the histogram with function values for (Int_t i=0; i<=n; i++){ /* if( i >= n/2 ) { x = (Double_t(i-(n/2+1))/n)*(160*TMath::Pi()); } else { x = -80*TMath::Pi()+(Double_t(i)/n)*(160*TMath::Pi()); } */ x = (Double_t(i)/n)*(1024); //std::cout << "n: " << i << " x: " << x << std::endl; hsin->SetBinContent(i+1, fsin->Eval(x)); } hsin->Fit( model2,"MLR" ); //TFile* fn = new TFile("/Users/cmorgoth/Software/git/TimingAna_New/CIT_Laser_022015_69_ana.root", "READ"); TFile* fn = new TFile("/Users/cmorgoth/Work/data/LaserDataAtCaltech/02282015/CIT_Laser_022015_69_ana.root", "READ"); TH1F* pulse = (TH1F*)fn->Get("CH2pulse"); //hsin->Draw("same"); hsin->SetLineColor(kGreen-4); hsin->Draw(); model->Draw("same"); //pulse->SetAxisRange(650, 780, "X"); pulse->Scale(22.0); pulse->Draw("same"); fsin->GetXaxis()->SetLabelSize(0.05); fsin->GetYaxis()->SetLabelSize(0.05); c1_2->cd(); //Compute the transform and look at the magnitude of the output TH1 *hm =0; TVirtualFFT::SetTransform(0); //hm = hsin->FFT(hm, "MAG"); hm = pulse->FFT(hm, "MAG"); hm->SetTitle("Magnitude of the 1st transform"); //hm->Draw(); double sf = 5e3;//to go from sample to picosecons and also from Hz to MHz double range = sf*(double)n/(1023.); int n_bin_fft = hm->GetNbinsX(); TH1F* hmr = new TH1F( "hmr" ,"Magnitude of the 1st transform Rescaled", n_bin_fft, 0, range); for( int i = 1; i <= n_bin_fft; i++) { double bc = hm->GetBinContent( i )/sqrt( n ); hmr->SetBinContent( i, bc ); } hmr->SetXTitle("f (MHz)"); hmr->Draw(); //Transfor to the theoretical function TH1 *hm2 =0; TVirtualFFT::SetTransform(0); hm2 = hsin->FFT(hm2, "MAG"); hm2->SetLineColor(2); //hm2->Draw("same"); TH1F* hmr2 = new TH1F( "hmr2" ,"Magnitude of the 1st transform Rescaled", n_bin_fft, 0, range); for( int i = 1; i <= n_bin_fft; i++) { double bc = hm2->GetBinContent( i )/sqrt( n ); hmr2->SetBinContent( i, bc ); } hmr2->SetLineColor( kRed ); hmr2->Draw("same"); //NOTE: for "real" frequencies you have to divide the x-axes range with the range of your function //(in this case 4*Pi); y-axes has to be rescaled by a factor of 1/SQRT(n) to be right: this is not done automatically! hm->SetStats(kFALSE); hm->GetXaxis()->SetLabelSize(0.05); hm->GetYaxis()->SetLabelSize(0.05); c1_3->cd(); //Look at the phase of the output TH1 *hp = 0; hp = hsin->FFT(hp, "PH"); hp->SetTitle("Phase of the 1st transform"); hp->Draw(); hp->SetStats(kFALSE); hp->GetXaxis()->SetLabelSize(0.05); hp->GetYaxis()->SetLabelSize(0.05); //Look at the DC component and the Nyquist harmonic: Double_t re, im; //That's the way to get the current transform object: TVirtualFFT *fft = TVirtualFFT::GetCurrentTransform(); c1_4->cd(); //Use the following method to get just one point of the output fft->GetPointComplex(0, re, im); printf("1st transform: DC component: %f\n", re); fft->GetPointComplex(n/2+1, re, im); printf("1st transform: Nyquist harmonic: %f\n", re); //Use the following method to get the full output: Double_t *re_full = new Double_t[n]; Double_t *im_full = new Double_t[n]; fft->GetPointsComplex(re_full,im_full); //Now let's make a backward transform: TVirtualFFT *fft_back = TVirtualFFT::FFT(1, &n, "C2R M K"); fft_back->SetPointsComplex(re_full,im_full); fft_back->Transform(); TH1 *hb = 0; //Let's look at the output hb = TH1::TransformHisto(fft_back,hb,"Re"); hb->SetTitle("The backward transform result"); hb->Draw(); //NOTE: here you get at the x-axes number of bins and not real values //(in this case 25 bins has to be rescaled to a range between 0 and 4*Pi; //also here the y-axes has to be rescaled (factor 1/bins) hb->SetStats(kFALSE); hb->GetXaxis()->SetLabelSize(0.05); hb->GetYaxis()->SetLabelSize(0.05); delete fft_back; fft_back=0; //********* Data array - same transform ********// //Allocate an array big enough to hold the transform output //Transform output in 1d contains, for a transform of size N, //N/2+1 complex numbers, i.e. 2*(N/2+1) real numbers //our transform is of size n+1, because the histogram has n+1 bins Double_t *in = new Double_t[2*((n+1)/2+1)]; Double_t re_2,im_2; for (Int_t i=0; i<=n; i++){ x = (Double_t(i)/n)*(4*TMath::Pi()); in[i] = fsin->Eval(x); } //Make our own TVirtualFFT object (using option "K") //Third parameter (option) consists of 3 parts: //-transform type: // real input/complex output in our case //-transform flag: // the amount of time spent in planning // the transform (see TVirtualFFT class description) //-to create a new TVirtualFFT object (option "K") or use the global (default) Int_t n_size = n+1; TVirtualFFT *fft_own = TVirtualFFT::FFT(1, &n_size, "R2C ES K"); if (!fft_own) return; fft_own->SetPoints(in); fft_own->Transform(); //Copy all the output points: fft_own->GetPoints(in); //Draw the real part of the output c1_5->cd(); TH1 *hr = 0; hr = TH1::TransformHisto(fft_own, hr, "RE"); hr->SetTitle("Real part of the 3rd (array) tranfsorm"); hr->Draw(); hr->SetStats(kFALSE); hr->GetXaxis()->SetLabelSize(0.05); hr->GetYaxis()->SetLabelSize(0.05); c1_6->cd(); TH1 *him = 0; him = TH1::TransformHisto(fft_own, him, "IM"); him->SetTitle("Im. part of the 3rd (array) transform"); him->Draw(); him->SetStats(kFALSE); him->GetXaxis()->SetLabelSize(0.05); him->GetYaxis()->SetLabelSize(0.05); myc->cd(); //Now let's make another transform of the same size //The same transform object can be used, as the size and the type of the transform //haven't changed TF1 *fcos = new TF1("fcos", "cos(x)+cos(0.5*x)+cos(2*x)+1", 0, 4*TMath::Pi()); for (Int_t i=0; i<=n; i++){ x = (Double_t(i)/n)*(4*TMath::Pi()); in[i] = fcos->Eval(x); } fft_own->SetPoints(in); fft_own->Transform(); fft_own->GetPointComplex(0, re_2, im_2); printf("2nd transform: DC component: %f\n", re_2); fft_own->GetPointComplex(n/2+1, re_2, im_2); printf("2nd transform: Nyquist harmonic: %f\n", re_2); delete fft_own; delete [] in; delete [] re_full; delete [] im_full; }
void blinding_study() { gSystem->CompileMacro("MitGPTree.h"); // First we define MIT Style for the plots. TStyle *MitStyle = gStyle; //gStyle = MitStyle; // Canvas MitStyle->SetCanvasColor (0); MitStyle->SetCanvasBorderSize(10); MitStyle->SetCanvasBorderMode(0); MitStyle->SetCanvasDefH (700); MitStyle->SetCanvasDefW (700); MitStyle->SetCanvasDefX (100); MitStyle->SetCanvasDefY (100); // Pads MitStyle->SetPadColor (0); MitStyle->SetPadBorderSize (10); MitStyle->SetPadBorderMode (0); MitStyle->SetPadBottomMargin(0.13); MitStyle->SetPadTopMargin (0.04); MitStyle->SetPadLeftMargin (0.18); MitStyle->SetPadRightMargin (0.04); MitStyle->SetPadGridX (0); MitStyle->SetPadGridY (0); MitStyle->SetPadTickX (0); MitStyle->SetPadTickY (0); // Frames MitStyle->SetFrameFillStyle ( 0); MitStyle->SetFrameFillColor ( 0); MitStyle->SetFrameLineColor ( 1); MitStyle->SetFrameLineStyle ( 0); MitStyle->SetFrameLineWidth ( 1); MitStyle->SetFrameBorderSize(10); MitStyle->SetFrameBorderMode( 0); // Histograms MitStyle->SetHistFillColor(2); MitStyle->SetHistFillStyle(0); MitStyle->SetHistLineColor(1); MitStyle->SetHistLineStyle(0); MitStyle->SetHistLineWidth(2); MitStyle->SetNdivisions(505); // Functions MitStyle->SetFuncColor(1); MitStyle->SetFuncStyle(0); MitStyle->SetFuncWidth(2); // Various MitStyle->SetMarkerStyle(20); MitStyle->SetMarkerColor(kBlack); MitStyle->SetMarkerSize (1.2); MitStyle->SetTitleSize (0.055,"X"); MitStyle->SetTitleOffset(1.200,"X"); MitStyle->SetLabelOffset(0.005,"X"); MitStyle->SetLabelSize (0.050,"X"); MitStyle->SetLabelFont (42 ,"X"); MitStyle->SetTickLength (-0.03,"X"); MitStyle->SetStripDecimals(kFALSE); MitStyle->SetTitleSize (0.055,"Y"); MitStyle->SetTitleOffset(1.800,"Y"); MitStyle->SetLabelOffset(0.010,"Y"); MitStyle->SetLabelSize (0.050,"Y"); MitStyle->SetLabelFont (42 ,"Y"); MitStyle->SetTickLength (-0.03,"Y"); MitStyle->SetTextSize (0.055); MitStyle->SetTextFont (42); MitStyle->SetStatFont (42); MitStyle->SetTitleFont (42); MitStyle->SetTitleFont (42,"X"); MitStyle->SetTitleFont (42,"Y"); MitStyle->SetOptStat (0); // Here the style section ends and the macro begins. string sig_samples[] = { "s12-dmmpho-v_m1-v7a", "s12-dmmpho-av_m1-v7a", "s12-dmmpho-v_m10-v7a", "s12-dmmpho-av_m10-v7a", "s12-dmmpho-v_m100-v7a", "s12-dmmpho-av_m100-v7a", "s12-dmmpho-v_m200-v7a", "s12-dmmpho-av_m200-v7a", "s12-dmmpho-av_m300-v7a", "s12-dmmpho-v_m500-v7a", "s12-dmmpho-av_m500-v7a", "s12-dmmpho-v_m1000-v7a", "s12-dmmpho-av_m1000-v7a", "s12-addmpho-md1_d2-v7a", "s12-addmpho-md1_d3-v7a", "s12-addmpho-md1_d4-v7a", "s12-addmpho-md1_d5-v7a", "s12-addmpho-md1_d6-v7a", "s12-addmpho-md2_d2-v7a", "s12-addmpho-md2_d3-v7a", "s12-addmpho-md2_d5-v7a", "s12-addmpho-md2_d6-v7a", "s12-addmpho-md3_d2-v7a", "s12-addmpho-md3_d3-v7a", "s12-addmpho-md3_d4-v7a", "s12-addmpho-md3_d5-v7a", "s12-addmpho-md3_d6-v7a" } Int_t signal_num=0; // This macro considers only one signal sample at a time, so the variable signal_num defines // which signal sample to work on (it is the index of the sample in sig_samples). double sig_weights[] = { 4.81E-07, 4.79E-07, 4.80E-07, 4.81E-07, 4.77E-07, 4.26E-07, 4.23E-07, 3.18E-07, 2.19E-07, 2.01E-07, 9.52E-08, 3.00E-08, 8.22E-09, 6.48E-02, 1.73E-01, 6.93E-02, 9.17E-02, 9.63E-01, 5.87E-03, 4.91E-03, 4.37E-03, 4.26E-03, 1.45E-03, 7.93E-04, 5.53E-04, 4.26E-04, 3.24E-04 }; // The signal weights are given by (sigma_MC * lumi)/(N_processed). Background weights are defined similarly below. string bg_samples[] = {"s12-zgptg130-v7c", "s12-wjets-ptw100-v7a", "s12-wgptg130-v7a", "s12-qcdht100-250-v7a", "s12-qcdht250-500-v7a", "s12-qcdht500-1000-v7a", "s12-qcdht1000-v7a", "s12-2pibo10_25-v7a", "s12-2pibo25_250-v7a", "s12-2pibo250-v7a", "s12-2pibx10_25-v7a", "s12-2pibx25_250-v7a", "s12-2pibx250-v7a", "s12-pj50_80-v7a", "s12-pj80_120-v7a", "s12-pj120_170-v7a", "s12-pj170_300-v7a", "s12-pj300_470-v7a", "s12-pj470_800-v7a", "s12-pj800_1400-v7a", "s12-pj1400_1800-v7a", "s12-pj1800-v7a", "s12-zgllgptg130-v7a", "s12-zgllg-v7a"}; double bg_weights[]= { 5.28E-03, 1.14E-01, 1.38E-02, 5.63E+03, 2.34E+02, 9.71E+00, 3.09E-01, 9.21E+00, 9.90E-01, 4.21E-04, 1.66E+01, 6.43E-01, 4.91E-05, 3.30E+01, 5.49E+00, 1.09E+00, 3.01E-01, 2.15E-02, 2.10E-03, 7.11E-05, 4.45E-07, 1.88E-08, 3.18E-03, 5.10E-01 }; string sigLine = sig_samples[signal_num]; Double_t sigWeight = sig_weights[signal_num]; TH1* sig_hist = new TH1F("sig_hist", TString("Phi Between Met and Photon for Signal Events [") + TString(sigLine) + TString("]"), 70, 0, 3.5); TH1* bg_hist = new TH1F("bg_hist", TString("Phi Between Met and Photon for Background Events [") + TString(sigLine) + TString("]"), 70, 0, 3.5); TH1* signifhist = new TH1F("signifhist", TString(" "), 24, 2, 3.2); cout<<"The selected signal sample is: "<<TString(sigLine)<<" "<<endl; TString sigFilename = TString("monoph-2013-July9_") + TString(sigLine) + TString("_noskim.root"); MitGPTree sigEvent; sigEvent.LoadTree(TString("/scratch/cferko/hist/monoph-2013-July9/merged/")+sigFilename, 0); sigEvent.InitTree(0); int nDataSig=sigEvent.tree_->GetEntries(); for (int evt=0; evt<nDataSig; ++evt) { sigEvent.tree_->GetEntry(evt); Double_t pho1Pt = sigEvent.pho1_.Pt(); Double_t jet1Pt = sigEvent.jet1_.Pt(); Double_t met = sigEvent.met_; Double_t metPhi = sigEvent.metPhi_; Double_t nphotons = sigEvent.nphotons_; Double_t ncosmics = sigEvent.ncosmics_; Double_t phoPassEleVeto = sigEvent.phoPassEleVeto_a1_; Double_t jet1Pt = sigEvent.jet1_.Pt(); Double_t nlep = sigEvent.nlep_; Double_t pho1Eta = sigEvent.pho1_.Eta(); Double_t pho1Phi = sigEvent.pho1_.Phi(); Double_t phoIsTrigger = sigEvent.phoIsTrigger_a1_; Double_t phoLeadTimeSpan = sigEvent.phoLeadTimeSpan_a1_; Double_t phoCoviEtaiEta = sigEvent.phoCoviEtaiEta_a1_; Double_t phoCoviPhiiPhi = sigEvent.phoCoviPhiiPhi_a1_; Double_t phoMipIsHalo = sigEvent.phoMipIsHalo_a1_; Double_t phoSeedTime = sigEvent.phoSeedTime_a1_; Double_t deltaPhi = TMath::ACos(TMath::Cos(pho1Phi - metPhi)); if (TMath::Abs(pho1Eta)<1.479 && met>140 && pho1Pt>160 && nphotons>0 && phoPassEleVeto>0 && phoIsTrigger==1 && TMath::Abs(phoLeadTimeSpan) < 8. && phoCoviEtaiEta > 0.001 && phoCoviPhiiPhi > 0.001 && phoMipIsHalo == 0 && phoSeedTime > -1.5 && nlep==0 && ncosmics==0 && jet1Pt<100) sig_hist->Fill(deltaPhi, sigWeight); } for (int i=0; i<24; i++) { string bgLine = bg_samples[i]; Double_t bgWeight = bg_weights[i]; TString bgFilename = TString("monoph-2013-July9_") + TString(bgLine) + TString("_noskim.root"); MitGPTree bgEvent; bgEvent.LoadTree(TString("/scratch/cferko/hist/monoph-2013-July9/merged/") + bgFilename, 0); bgEvent.InitTree(0); int nDataBg=bgEvent.tree_->GetEntries(); for (int evt=0; evt<nDataBg; ++evt) { bgEvent.tree_->GetEntry(evt); Double_t pho1Pt = bgEvent.pho1_.Pt(); Double_t jet1Pt = bgEvent.jet1_.Pt(); Double_t met = bgEvent.met_; Double_t metPhi = bgEvent.metPhi_; Double_t nphotons = bgEvent.nphotons_; Double_t ncosmics = bgEvent.ncosmics_; Double_t phoPassEleVeto = bgEvent.phoPassEleVeto_a1_; Double_t jet1Pt = bgEvent.jet1_.Pt(); Double_t nlep = bgEvent.nlep_; Double_t pho1Eta = bgEvent.pho1_.Eta(); Double_t pho1Phi = bgEvent.pho1_.Phi(); Double_t phoIsTrigger = bgEvent.phoIsTrigger_a1_; Double_t phoLeadTimeSpan = bgEvent.phoLeadTimeSpan_a1_; Double_t phoCoviEtaiEta = bgEvent.phoCoviEtaiEta_a1_; Double_t phoCoviPhiiPhi = bgEvent.phoCoviPhiiPhi_a1_; Double_t phoMipIsHalo = bgEvent.phoMipIsHalo_a1_; Double_t phoSeedTime = bgEvent.phoSeedTime_a1_; Double_t deltaPhi = TMath::ACos(TMath::Cos(pho1Phi - metPhi)); if (TMath::Abs(pho1Eta)<1.479 && met>140 && pho1Pt>160 && nphotons>0 && phoPassEleVeto>0 && phoIsTrigger==1 && TMath::Abs(phoLeadTimeSpan) < 8. && phoCoviEtaiEta > 0.001 && phoCoviPhiiPhi > 0.001 && phoMipIsHalo == 0 && phoSeedTime > -1.5 && nlep==0 && ncosmics==0 && jet1Pt<100) bg_hist->Fill(deltaPhi, bgWeight); } } Double_t sigTot = sig_hist->Integral(); Double_t bgTot = bg_hist->Integral(); Double_t signifTot = sigTot/TMath::Sqrt(bgTot); Double_t signifTarget = 0.25*signifTot; Int_t reduced=0; // The strange limits in the for loop are a messy hack to get the integral to work out. Since hist->Integral(a,b) // integrates from BIN a to BIN b (bin numbers instead of values of the x-axis), I choose to work from bin 64 // (an angle cut of 3.2) to bin 40 (an angle cut of 2). for (int i=64; i>=40; i--) { Double_t sigcount = sig_hist->Integral(0, i); Double_t bgcount = bg_hist->Integral(0, i); if (bgcount>0) { Double_t significance = sigcount/TMath::Sqrt(bgcount); // cout<<"At a phi cut of "<<sig_hist->GetBinCenter(i)+0.025<<" the significance is "<<significance<<", which is a fraction "<<significance/signifTot<<" of max."<<endl; if (significance<signifTarget && reduced==0) { cout<<"The signal significance is reduced to one-fourth of its uncut value at a phi cut of "<<sig_hist->GetBinCenter(i)+0.025<<endl; reduced=1; } signifhist->Fill(sig_hist->GetBinCenter(i), significance); } } signifhist->SetStats(kFALSE); signifhist->GetXaxis()->SetTitle("Maximum #Delta#phi"); signifhist->GetYaxis()->SetTitle("Signal Significance"); signifhist->Draw(); c1->Print(TString("Blinding_") + TString(sigLine) + TString(".pdf")); }
void showGraph(TGraph* graph, const std::string& xAxisTitle, Float_t* genX, double yMin, double yMax, const std::string& yAxisTitle, const std::string& outputFileName) { TCanvas* canvas = new TCanvas("canvas", "canvas", 800, 600); canvas->SetFillColor(10); canvas->SetBorderSize(2); canvas->SetTopMargin(0.10); canvas->SetLeftMargin(0.16); canvas->SetRightMargin(0.14); canvas->SetBottomMargin(0.12); int numPoints = graph->GetN(); double xMin, xMax, yDummy; graph->GetPoint(0, xMin, yDummy); graph->GetPoint(numPoints - 1, xMax, yDummy); TH1* dummyHistogram = new TH1D("dummyHistogram", "dummyHistogram", numPoints/100, xMin, xMax); dummyHistogram->SetStats(false); dummyHistogram->SetMinimum(yMin); dummyHistogram->SetMaximum(yMax); TAxis* xAxis = dummyHistogram->GetXaxis(); xAxis->SetTitle(xAxisTitle.data()); xAxis->SetTitleOffset(1.15); TAxis* yAxis = dummyHistogram->GetYaxis(); yAxis->SetTitle(yAxisTitle.data()); yAxis->SetTitleOffset(1.15); dummyHistogram->Draw("axis"); TGraph* genMarker = 0; if ( genX ) { genMarker = new TGraph(2); genMarker->SetPoint(0, xMin, *genX); genMarker->SetPoint(1, xMax, *genX); genMarker->SetLineColor(8); genMarker->SetLineWidth(1); genMarker->SetMarkerColor(8); genMarker->SetMarkerStyle(20); genMarker->SetMarkerSize(1); genMarker->Draw("L"); } graph->SetLineColor(1); graph->SetLineWidth(2); graph->SetMarkerColor(1); graph->SetMarkerStyle(20); graph->SetMarkerSize(1); graph->Draw("L"); canvas->Update(); size_t idx = outputFileName.find_last_of('.'); std::string outputFileName_plot = std::string(outputFileName, 0, idx); if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName, idx)).data()); canvas->Print(std::string(outputFileName_plot).append(".png").data()); canvas->Print(std::string(outputFileName_plot).append(".pdf").data()); canvas->Print(std::string(outputFileName_plot).append(".root").data()); delete dummyHistogram; delete genMarker; delete canvas; }
void check1SLimits( const char* workDir, // workDir: usual tag where to look for files in Output const char* lFileName="cLimits_683_NominalABCD_Asym_2SPL_woSyst.csv", // file name to save limits results bool dosyst = false, int mode = 1, // mode=0 -> pass, mode=1 -> prompt, mode=2 -> nonprompt const char* workDirFail="" ) { TString slFileName(lFileName); if ( dosyst && !slFileName.Contains("wSys") ) { cout << "Comparison requires systematics but limits file does not contain them" << endl; return; } // list of files set<anabin> thebins = allbins(); const char* ppp = "../Fitter"; // systematic uncertainties for fit map<anabin, syst> syst_All; if ( dosyst ) { if (mode==0) syst_All = readSyst_all_pass("",ppp,workDir); if (mode==1) syst_All = readSyst_all_prompt("",ppp,workDir,workDirFail); if (mode==2) syst_All = readSyst_all_nonprompt("",ppp,workDir,workDirFail); } // bin edges float ptmin, ptmax, ymin, ymax, centmin, centmax; // histo for 1sigma limits checks TH1* hCL = new TH1D("hOneSigmaCLComparison","",thebins.size(),0,thebins.size()); hCL->GetYaxis()->SetTitle("CL_{1#sigma}/#sigma"); hCL->GetYaxis()->SetTitleOffset(1.15); hCL->SetStats(0); hCL->SetDirectory(0); hCL->SetMarkerColor(1); hCL->SetMarkerStyle(20); hCL->SetMarkerSize(1); hCL->SetLineColor(1); TLine* l1 = new TLine(0.,1.,hCL->GetXaxis()->GetXmax(),1.); l1->SetLineWidth(3); hCL->GetListOfFunctions()->Add(l1); map<anabin,limits> maplim = readLimits(Form("csv/%s",slFileName.Data())); int cnt=1; for (set<anabin>::const_iterator it=thebins.begin(); it!=thebins.end(); it++) { cout << "Checking 1 sigma limits for analysis bin " << cnt << endl; anabin thebin = *it; ptmin = thebin.ptbin().low(); ptmax = thebin.ptbin().high(); ymin = thebin.rapbin().low(); ymax = thebin.rapbin().high(); centmin = thebin.centbin().low(); centmax = thebin.centbin().high(); double sigmaDoubleR = 0; double doubleR = 0; if (mode==0) { doubleR = doubleratio_pass_nominal(workDir,thebin,ppp); sigmaDoubleR = doubleratio_pass_stat(workDir,thebin,ppp); } if (mode==1) { doubleR = doubleratio_prompt_nominal(workDir,workDirFail,thebin,ppp); sigmaDoubleR = doubleratio_prompt_stat(workDir,workDirFail,thebin,ppp); } if (mode==2) { doubleR = doubleratio_nonprompt_nominal(workDir,workDirFail,thebin,ppp); sigmaDoubleR = doubleratio_nonprompt_stat(workDir,workDirFail,thebin,ppp); } double systAll=0; if ( dosyst ) { systAll = syst_All[thebin].value_dR; sigmaDoubleR = sqrt(pow(sigmaDoubleR,2)+pow(systAll,2)); } limits lim = maplim[thebin]; TString binName(Form("Pt[%.1f,%.1f]-Y[%.1f,%.1f]-C[%.1f,%.1f]",ptmin,ptmax,ymin,ymax,centmin,centmax)); double comp = -1.; if ( sigmaDoubleR != 0 ) comp = (lim.val.second-lim.val.first)/(2.*sigmaDoubleR); hCL->SetBinContent(cnt,comp); hCL->GetXaxis()->SetBinLabel(cnt,binName.Data()); cnt++; } // loop on the files TFile* fSave = new TFile("oneSigmaCLComparison.root","RECREATE"); TCanvas* c = new TCanvas("cOneSigmaCLComparison","",90,116,1265,535); c->Range(-3.690909,-0.01066472,33.30606,0.01252061); c->SetFillColor(0); c->SetBorderMode(0); c->SetBorderSize(2); c->SetRightMargin(0.1163896); c->SetTopMargin(0.03732809); c->SetBottomMargin(0.1630648); c->SetFrameBorderMode(0); c->SetFrameBorderMode(0); gPad->SetGridx(); gPad->SetGridy(); hCL->Draw("p"); c->Write("cOneSigmaCLComparison", TObject::kOverwrite | TObject::kSingleKey); fSave->Close(); delete fSave; }
void PerformanceSpectrumUncorr(const Char_t *fname = "HFEtask.root"){ gROOT->SetStyle("Plain"); gStyle->SetTitleFillColor(0); gStyle->SetTitleBorderSize(0); gStyle->SetTitleX(0.1); gStyle->SetTitleY(0.96); TFile *in = TFile::Open(fname); TList *res = (TList *)in->Get("HFE_Results"); TList *qa = (TList *)in->Get("HFE_QA"); gROOT->cd(); AliHFEcontainer *tcont = dynamic_cast<AliHFEcontainer *>(res->FindObject("trackContainer")); AliCFContainer *c = tcont->GetCFContainer("recTrackContReco"); AliCFContainer *cb = tcont->GetCFContainer("hadronicBackground"); TH1 *spec = c->Project(c->GetNStep() - 1, 0); spec->GetXaxis()->SetTitle("p_{T} / GeV/c"); spec->GetYaxis()->SetTitle("#frac{dN}{dp_{T}} / (GeV/c)^{-1}"); spec->GetXaxis()->SetRangeUser(ptmin, ptmax); spec->GetYaxis()->SetTitleOffset(1.1); spec->SetTitle(); spec->SetStats(kFALSE); spec->SetLineColor(kBlue); spec->SetLineWidth(1); spec->SetMarkerColor(kBlue); spec->SetMarkerStyle(22); // Produce background subtracted spectrum AliCFDataGrid tracks("tracks", "track grid", *c, c->GetNStep() - 1); AliCFDataGrid background("background", "background grid", *cb, 1); tracks.ApplyBGCorrection(background); TH1 *spec_subtracted = tracks.Project(0); spec_subtracted->GetXaxis()->SetTitle("p_{T} / GeV/c"); spec_subtracted->GetYaxis()->SetTitle("#frac{dN}{dp_{T}} / (GeV/c)^{-1}"); spec_subtracted->GetXaxis()->SetRangeUser(ptmin, ptmax); spec_subtracted->GetYaxis()->SetTitleOffset(1.1); spec_subtracted->SetTitle(); spec_subtracted->SetStats(kFALSE); spec_subtracted->SetLineColor(kRed); spec_subtracted->SetLineWidth(1); spec_subtracted->SetMarkerColor(kRed); spec_subtracted->SetMarkerStyle(22); TLegend *leg = new TLegend(0.2, 0.25, 0.4, 0.35); leg->SetBorderSize(0); leg->SetFillStyle(0); leg->AddEntry(spec, "Raw Spectrum", "p"); leg->AddEntry(spec_subtracted, "Spectrum after background subtraction", "p"); TCanvas *c1 = new TCanvas("cspec", "Single-inclusive electron spectrum", 1200, 750); c1->cd(); c1->SetLogy(); c1->SetGridx(kFALSE); c1->SetGridy(kFALSE); spec->Draw("ep"); spec_subtracted->Draw("epsame"); leg->Draw(); ALICEWorkInProgress(c1, "today"); // PID TList *pidqa = (TList *)qa->FindObject("HFEpidQA"); AliHFEtpcPIDqa *tpcqa = (AliHFEtpcPIDqa *)pidqa->FindObject("TPCQA"); AliHFEtofPIDqa *tofqa = (AliHFEtofPIDqa *)pidqa->FindObject("TOFQA"); // Make Plots for TPC // Create histograms by projecting the THnSparse TH2 *hTPCall = tpcqa->MakeSpectrumdEdx(AliHFEdetPIDqa::kBeforePID); TH2 *hTPCselected = tpcqa->MakeSpectrumdEdx(AliHFEdetPIDqa::kAfterPID); TH2 *hTPCsigmaAll = tpcqa->MakeSpectrumNSigma(AliHFEdetPIDqa::kBeforePID); TH2* hTPCsigmaSelected = tpcqa->MakeSpectrumNSigma(AliHFEdetPIDqa::kAfterPID); // Make Plots for TOF TH2 *hTOFsigmaAll = tofqa->MakeSpectrumNSigma(AliHFEdetPIDqa::kBeforePID); TH2 *hTOFsigmaSelected = tofqa->MakeSpectrumNSigma(AliHFEdetPIDqa::kAfterPID); hTPCsigmaAll->SetTitle("TPC n#sigma around the electron line"); hTPCsigmaSelected->SetTitle("TPC n#sigma around the electron line for selected tracks"); hTOFsigmaAll->SetTitle("TOF n#sigma around the electron line"); hTOFsigmaSelected->SetTitle("TOF n#sigma around the electron line for selected tracks"); DefineTPChisto(hTPCall, "TPC Signal / a.u"); DefineTPChisto(hTPCselected, "TPC Signal / a.u."); DefineTPChisto(hTPCsigmaAll, "TPC Sigma"); DefineTPChisto(hTPCsigmaSelected, "TPC Sigma"); // Also make nice histograms for TOF DefineTPChisto(hTOFsigmaAll, "TOF Sigma"); DefineTPChisto(hTOFsigmaSelected, "TOF Sigma"); // Plot them TCanvas *c2 = new TCanvas("cTPCall", "TPC Signal for all tracks", 640, 480); c2->cd(); c2->SetGridx(kFALSE); c2->SetGridy(kFALSE); c2->SetLogx(); c2->SetLogz(); hTPCall->GetYaxis()->SetRangeUser(40., 100.); hTPCall->Draw("colz"); ALICEWorkInProgress(c2, "today"); TCanvas *c3 = new TCanvas("cTPCsel", "TPC Signal for selected tracks", 640, 480); c3->cd(); c3->SetGridx(kFALSE); c3->SetGridy(kFALSE); c3->SetLogx(); c3->SetLogz(); hTPCselected->GetYaxis()->SetRangeUser(40., 100.); hTPCselected->Draw("colz"); ALICEWorkInProgress(c3, "today"); TCanvas *c4 = new TCanvas("cTPCsigAll", "TPC Sigma for all tracks", 640, 480); c4->cd(); c4->SetGridx(kFALSE); c4->SetGridy(kFALSE); c4->SetLogx(); c4->SetLogz(); //hTPCsigmaAll->GetYaxis()->SetRangeUser(-3.5, 5.); hTPCsigmaAll->Draw("colz"); ALICEWorkInProgress(c4, "today"); TCanvas *c5 = new TCanvas("cTPCsigSel", "TPC Sigma for selected tracks", 640, 480); c5->cd(); c5->SetGridx(kFALSE); c5->SetGridy(kFALSE); c5->SetLogx(); c5->SetLogz(); hTPCsigmaSelected->GetYaxis()->SetRangeUser(-3.5, 5.); hTPCsigmaSelected->Draw("colz"); ALICEWorkInProgress(c5, "today"); TCanvas *c6 = new TCanvas("cTOFsigAll", "TOF Sigma for all tracks", 640, 480); c6->cd(); c6->SetGridx(kFALSE); c6->SetGridy(kFALSE); c6->SetLogx(); c6->SetLogz(); hTOFsigmaAll->Draw("colz"); ALICEWorkInProgress(c6, "today"); TCanvas *c7 = new TCanvas("cTOFsigSel", "TOF Sigma for selected tracks", 640, 480); c7->cd(); c7->SetGridx(kFALSE); c7->SetGridy(kFALSE); c7->SetLogx(); c7->SetLogz(); //hTOFsigmaSelected->GetYaxis()->SetRangeUser(-3, 3); hTOFsigmaSelected->Draw("colz"); ALICEWorkInProgress(c7, "today"); TFile *output = new TFile("Performance.root", "RECREATE"); output->cd(); spec->Write(); hTPCall->Write(); hTPCselected->Write(); hTPCsigmaAll->Write(); hTPCsigmaSelected->Write(); c1->Write(); c2->Write(); c3->Write(); c4->Write(); c5->Write(); c6->Write(); c7->Write(); output->Close(); delete output; }
void FFT() { //This tutorial illustrates the Fast Fourier Transforms interface in ROOT. //FFT transform types provided in ROOT: // - "C2CFORWARD" - a complex input/output discrete Fourier transform (DFT) // in one or more dimensions, -1 in the exponent // - "C2CBACKWARD"- a complex input/output discrete Fourier transform (DFT) // in one or more dimensions, +1 in the exponent // - "R2C" - a real-input/complex-output discrete Fourier transform (DFT) // in one or more dimensions, // - "C2R" - inverse transforms to "R2C", taking complex input // (storing the non-redundant half of a logically Hermitian array) // to real output // - "R2HC" - a real-input DFT with output in ¡Èhalfcomplex¡É format, // i.e. real and imaginary parts for a transform of size n stored as // r0, r1, r2, ..., rn/2, i(n+1)/2-1, ..., i2, i1 // - "HC2R" - computes the reverse of FFTW_R2HC, above // - "DHT" - computes a discrete Hartley transform // Sine/cosine transforms: // DCT-I (REDFT00 in FFTW3 notation) // DCT-II (REDFT10 in FFTW3 notation) // DCT-III(REDFT01 in FFTW3 notation) // DCT-IV (REDFT11 in FFTW3 notation) // DST-I (RODFT00 in FFTW3 notation) // DST-II (RODFT10 in FFTW3 notation) // DST-III(RODFT01 in FFTW3 notation) // DST-IV (RODFT11 in FFTW3 notation) //First part of the tutorial shows how to transform the histograms //Second part shows how to transform the data arrays directly //Authors: Anna Kreshuk and Jens Hoffmann //********* Histograms ********// //prepare the canvas for drawing TCanvas *myc = new TCanvas("myc", "Fast Fourier Transform", 800, 600); myc->SetFillColor(45); TPad *c1_1 = new TPad("c1_1", "c1_1",0.01,0.67,0.49,0.99); TPad *c1_2 = new TPad("c1_2", "c1_2",0.51,0.67,0.99,0.99); TPad *c1_3 = new TPad("c1_3", "c1_3",0.01,0.34,0.49,0.65); TPad *c1_4 = new TPad("c1_4", "c1_4",0.51,0.34,0.99,0.65); TPad *c1_5 = new TPad("c1_5", "c1_5",0.01,0.01,0.49,0.32); TPad *c1_6 = new TPad("c1_6", "c1_6",0.51,0.01,0.99,0.32); c1_1->Draw(); c1_2->Draw(); c1_3->Draw(); c1_4->Draw(); c1_5->Draw(); c1_6->Draw(); c1_1->SetFillColor(30); c1_1->SetFrameFillColor(42); c1_2->SetFillColor(30); c1_2->SetFrameFillColor(42); c1_3->SetFillColor(30); c1_3->SetFrameFillColor(42); c1_4->SetFillColor(30); c1_4->SetFrameFillColor(42); c1_5->SetFillColor(30); c1_5->SetFrameFillColor(42); c1_6->SetFillColor(30); c1_6->SetFrameFillColor(42); c1_1->cd(); TH1::AddDirectory(kFALSE); //A function to sample TF1 *fsin = new TF1("fsin", "sin(x)*sin(x)/(x*x)", 0, 4*TMath::Pi()); fsin->Draw(); Int_t n=25; TH1D *hsin = new TH1D("hsin", "hsin", n+1, 0, 4*TMath::Pi()); Double_t x; //Fill the histogram with function values for (Int_t i=0; i<=n; i++){ x = (Double_t(i)/n)*(4*TMath::Pi()); hsin->SetBinContent(i+1, fsin->Eval(x)); } hsin->Draw("same"); fsin->GetXaxis()->SetLabelSize(0.05); fsin->GetYaxis()->SetLabelSize(0.05); c1_2->cd(); //Compute the transform and look at the magnitude of the output TH1 *hm =0; TVirtualFFT::SetTransform(0); hm = hsin->FFT(hm, "MAG"); hm->SetTitle("Magnitude of the 1st transform"); hm->Draw(); //NOTE: for "real" frequencies you have to divide the x-axes range with the range of your function //(in this case 4*Pi); y-axes has to be rescaled by a factor of 1/SQRT(n) to be right: this is not done automatically! hm->SetStats(kFALSE); hm->GetXaxis()->SetLabelSize(0.05); hm->GetYaxis()->SetLabelSize(0.05); c1_3->cd(); //Look at the phase of the output TH1 *hp = 0; hp = hsin->FFT(hp, "PH"); hp->SetTitle("Phase of the 1st transform"); hp->Draw(); hp->SetStats(kFALSE); hp->GetXaxis()->SetLabelSize(0.05); hp->GetYaxis()->SetLabelSize(0.05); //Look at the DC component and the Nyquist harmonic: Double_t re, im; //That's the way to get the current transform object: TVirtualFFT *fft = TVirtualFFT::GetCurrentTransform(); c1_4->cd(); //Use the following method to get just one point of the output fft->GetPointComplex(0, re, im); printf("1st transform: DC component: %f\n", re); fft->GetPointComplex(n/2+1, re, im); printf("1st transform: Nyquist harmonic: %f\n", re); //Use the following method to get the full output: Double_t *re_full = new Double_t[n]; Double_t *im_full = new Double_t[n]; fft->GetPointsComplex(re_full,im_full); //Now let's make a backward transform: TVirtualFFT *fft_back = TVirtualFFT::FFT(1, &n, "C2R M K"); fft_back->SetPointsComplex(re_full,im_full); fft_back->Transform(); TH1 *hb = 0; //Let's look at the output hb = TH1::TransformHisto(fft_back,hb,"Re"); hb->SetTitle("The backward transform result"); hb->Draw(); //NOTE: here you get at the x-axes number of bins and not real values //(in this case 25 bins has to be rescaled to a range between 0 and 4*Pi; //also here the y-axes has to be rescaled (factor 1/bins) hb->SetStats(kFALSE); hb->GetXaxis()->SetLabelSize(0.05); hb->GetYaxis()->SetLabelSize(0.05); delete fft_back; fft_back=0; //********* Data array - same transform ********// //Allocate an array big enough to hold the transform output //Transform output in 1d contains, for a transform of size N, //N/2+1 complex numbers, i.e. 2*(N/2+1) real numbers //our transform is of size n+1, because the histogram has n+1 bins Double_t *in = new Double_t[2*((n+1)/2+1)]; Double_t re_2,im_2; for (Int_t i=0; i<=n; i++){ x = (Double_t(i)/n)*(4*TMath::Pi()); in[i] = fsin->Eval(x); } //Make our own TVirtualFFT object (using option "K") //Third parameter (option) consists of 3 parts: //-transform type: // real input/complex output in our case //-transform flag: // the amount of time spent in planning // the transform (see TVirtualFFT class description) //-to create a new TVirtualFFT object (option "K") or use the global (default) Int_t n_size = n+1; TVirtualFFT *fft_own = TVirtualFFT::FFT(1, &n_size, "R2C ES K"); if (!fft_own) return; fft_own->SetPoints(in); fft_own->Transform(); //Copy all the output points: fft_own->GetPoints(in); //Draw the real part of the output c1_5->cd(); TH1 *hr = 0; hr = TH1::TransformHisto(fft_own, hr, "RE"); hr->SetTitle("Real part of the 3rd (array) tranfsorm"); hr->Draw(); hr->SetStats(kFALSE); hr->GetXaxis()->SetLabelSize(0.05); hr->GetYaxis()->SetLabelSize(0.05); c1_6->cd(); TH1 *him = 0; him = TH1::TransformHisto(fft_own, him, "IM"); him->SetTitle("Im. part of the 3rd (array) transform"); him->Draw(); him->SetStats(kFALSE); him->GetXaxis()->SetLabelSize(0.05); him->GetYaxis()->SetLabelSize(0.05); myc->cd(); //Now let's make another transform of the same size //The same transform object can be used, as the size and the type of the transform //haven't changed TF1 *fcos = new TF1("fcos", "cos(x)+cos(0.5*x)+cos(2*x)+1", 0, 4*TMath::Pi()); for (Int_t i=0; i<=n; i++){ x = (Double_t(i)/n)*(4*TMath::Pi()); in[i] = fcos->Eval(x); } fft_own->SetPoints(in); fft_own->Transform(); fft_own->GetPointComplex(0, re_2, im_2); printf("2nd transform: DC component: %f\n", re_2); fft_own->GetPointComplex(n/2+1, re_2, im_2); printf("2nd transform: Nyquist harmonic: %f\n", re_2); delete fft_own; delete [] in; delete [] re_full; delete [] im_full; }
void showGraphs(double canvasSizeX, double canvasSizeY, TGraph* graph1, const std::string& legendEntry1, TGraph* graph2, const std::string& legendEntry2, TGraph* graph3, const std::string& legendEntry3, TGraph* graph4, const std::string& legendEntry4, TGraph* graph5, const std::string& legendEntry5, TGraph* graph6, const std::string& legendEntry6, int colors[], int markerStyles[], double legendTextSize, double legendPosX, double legendPosY, double legendSizeX, double legendSizeY, std::vector<std::string>& labelTextLines, double labelTextSize, double labelPosX, double labelPosY, double labelSizeX, double labelSizeY, double xMin, double xMax, const std::string& xAxisTitle, double xAxisOffset, double yMin, double yMax, const std::string& yAxisTitle, double yAxisOffset, const std::string& outputFileName) { TCanvas* canvas = new TCanvas("canvas", "canvas", canvasSizeX, canvasSizeY); canvas->SetFillColor(10); canvas->SetBorderSize(2); canvas->SetLeftMargin(0.14); canvas->SetBottomMargin(0.12); TH1* dummyHistogram = new TH1D("dummyHistogram", "dummyHistogram", 100, xMin, xMax); dummyHistogram->SetTitle(""); dummyHistogram->SetStats(false); dummyHistogram->SetMinimum(yMin); dummyHistogram->SetMaximum(yMax); TAxis* xAxis = dummyHistogram->GetXaxis(); xAxis->SetTitle(xAxisTitle.data()); xAxis->SetTitleSize(0.045); xAxis->SetTitleOffset(xAxisOffset); TAxis* yAxis = dummyHistogram->GetYaxis(); yAxis->SetTitle(yAxisTitle.data()); yAxis->SetTitleSize(0.045); yAxis->SetTitleOffset(yAxisOffset); dummyHistogram->Draw("axis"); graph1->SetLineColor(colors[0]); graph1->SetLineWidth(2); graph1->SetMarkerColor(colors[0]); graph1->SetMarkerStyle(markerStyles[0]); graph1->SetMarkerSize(2); graph1->Draw("p"); if ( graph2 ) { graph2->SetLineColor(colors[1]); graph2->SetLineWidth(2); graph2->SetMarkerColor(colors[1]); graph2->SetMarkerStyle(markerStyles[1]); graph2->SetMarkerSize(2); graph2->Draw("p"); } if ( graph3 ) { graph3->SetLineColor(colors[2]); graph3->SetLineWidth(2); graph3->SetMarkerColor(colors[2]); graph3->SetMarkerStyle(markerStyles[2]); graph3->SetMarkerSize(2); graph3->Draw("p"); } if ( graph4 ) { graph4->SetLineColor(colors[3]); graph4->SetLineWidth(2); graph4->SetMarkerColor(colors[3]); graph4->SetMarkerStyle(markerStyles[3]); graph4->SetMarkerSize(2); graph4->Draw("p"); } if ( graph5 ) { graph5->SetLineColor(colors[4]); graph5->SetLineWidth(2); graph5->SetMarkerColor(colors[4]); graph5->SetMarkerStyle(markerStyles[4]); graph5->SetMarkerSize(2); graph5->Draw("p"); } if ( graph6 ) { graph6->SetLineColor(colors[5]); graph6->SetLineWidth(2); graph6->SetMarkerColor(colors[5]); graph6->SetMarkerStyle(markerStyles[5]); graph6->SetMarkerSize(2); graph6->Draw("p"); } TLegend* legend = new TLegend(legendPosX, legendPosY, legendPosX + legendSizeX, legendPosY + legendSizeY, "", "brNDC"); legend->SetBorderSize(0); legend->SetFillColor(0); legend->SetTextSize(legendTextSize); legend->AddEntry(graph1, legendEntry1.data(), "p"); if ( graph2 ) legend->AddEntry(graph2, legendEntry2.data(), "p"); if ( graph3 ) legend->AddEntry(graph3, legendEntry3.data(), "p"); if ( graph4 ) legend->AddEntry(graph4, legendEntry4.data(), "p"); if ( graph5 ) legend->AddEntry(graph5, legendEntry5.data(), "p"); if ( graph6 ) legend->AddEntry(graph6, legendEntry6.data(), "p"); legend->Draw(); TPaveText* label = 0; if ( labelTextLines.size() > 0 ) { label = new TPaveText(labelPosX, labelPosY, labelPosX + labelSizeX, labelPosY + labelSizeY, "brNDC"); for ( std::vector<std::string>::const_iterator labelTextLine = labelTextLines.begin(); labelTextLine != labelTextLines.end(); ++labelTextLine ) { label->AddText(labelTextLine->data()); } label->SetFillColor(10); label->SetBorderSize(0); label->SetTextColor(1); label->SetTextAlign(12); label->SetTextSize(labelTextSize); label->Draw(); } canvas->Update(); std::string outputFileName_plot = "plots/"; size_t idx = outputFileName.find_last_of('.'); outputFileName_plot.append(std::string(outputFileName, 0, idx)); if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName, idx)).data()); canvas->Print(std::string(outputFileName_plot).append(".png").data()); canvas->Print(std::string(outputFileName_plot).append(".pdf").data()); delete dummyHistogram; delete label; delete legend; delete canvas; }