void turn2Dinto1Ds(char* myf, char *myh, char* myfo) { TFile* mytfile = new TFile(myf); TH2* my2dh = (TH2*) mytfile->Get(myh); my2dh->SetDirectory(0); TFile* myoftile = new TFile(myfo,"RECREATE"); myoftile->cd(); //std::vector<TH1*> vechist; Int_t ybins = my2dh->GetNbinsX(); std::cout << " Full bins " << ybins << std::endl; std::cout << " Entries " << my2dh->GetEntries(); for (Int_t Ybin = 1; Ybin <= ybins; ++Ybin) { TH1* onehist = (TH1*) my2dh->ProjectionY(Form("rap%d",Ybin), Ybin,Ybin,""); std::cout << " Entries: " << onehist->GetEntries() << std::endl; onehist->Write(); } myoftile->Write(); myoftile->Close(); mytfile->Close(); }
void getPlotData() { TH1 * h = (TH1*) m_file->Get(m_direc.c_str()); for (int i=0; i<h->GetXaxis()->GetNbins(); i++) { m_xs.push_back(h->GetXaxis()->GetBinCenter(i)); m_ys.push_back(h->GetBinContent(i)); } m_plot->m_xAxisTitle = std::string(h->GetXaxis()->GetTitle()); m_plot->m_yAxisTitle = std::string(h->GetYaxis()->GetTitle()); m_plot->m_title = std::string(h->GetTitle()); std::stringstream ssN, ssMu, ssSig, ssUF, ssOF; ssN << std::setprecision(4) << h->GetEntries(); ssMu << std::setprecision(4) << h->GetMean(); ssSig << std::setprecision(4) << h->GetRMS(); ssUF << std::setprecision(4) << h->GetBinContent(0); ssOF << std::setprecision(4) << h->GetBinContent(h->GetNbinsX() + 1); m_statsTitles.push_back("N:"); m_statsTitles.push_back("mu:"); m_statsTitles.push_back("sig:"); m_statsTitles.push_back("UF:"); m_statsTitles.push_back("OF:"); m_statsValues.push_back(ssN.str()); m_statsValues.push_back(ssMu.str()); m_statsValues.push_back(ssSig.str()); m_statsValues.push_back(ssUF.str()); m_statsValues.push_back(ssOF.str()); }
TSeqCollection *GetCollection() { TObject *obj; #ifndef ClingWorkAroundMissingDynamicScope # define ClingWorkAroundMissingDynamicScope #endif #ifdef ClingWorkAroundMissingDynamicScope f = (TFile*)gROOT->ProcessLine("hsimple(1);"); #else f = hsimple(1); #endif gROOT->cd(); TList *l0 = new TList(); TList *l01 = new TList(); TH1 *hpx = (TH1*)f->Get("hpx"); printf("Adding hpx: %d entries\n", (int)hpx->GetEntries()); l01->Add(hpx); TH1 *hpxpy = (TH1*)f->Get("hpxpy"); l01->Add(hpxpy); TH1 *hprof = (TH1*)f->Get("hprof"); l0->Add(hprof); l0->Add(l01); return l0; }
void DrawStatBox(TObject** Histos, std::vector<char*> legend, bool Mean, double X, double Y, double W, double H) { int N = legend.size(); char buffer[255]; if(Mean)H*=3; for(int i=0;i<N;i++){ TPaveText* stat = new TPaveText(X,Y-(i*H), X+W, Y-(i+1)*H, "NDC"); TH1* Histo = (TH1*)Histos[i]; sprintf(buffer,"Entries : %i\n",(int)Histo->GetEntries()); stat->AddText(buffer); if(Mean){ sprintf(buffer,"Mean : %6.2f\n",Histo->GetMean()); stat->AddText(buffer); sprintf(buffer,"RMS : %6.2f\n",Histo->GetRMS()); stat->AddText(buffer); } stat->SetFillColor(0); stat->SetLineColor(Color[i]); stat->SetTextColor(Color[i]); stat->SetBorderSize(0); stat->SetMargin(0.05); stat->SetTextAlign(12); stat->Draw(); } }
// Extract and merge histograms in range [from, to) (to is not included) // TH1 *merge(const string &path, TFile **input, const int &from, const int &to, const bool &do_normalize = false) { TH1 *result = 0; for(int i = from; to > i; ++i) { TH1 *hist = get(path, input[i], i); if (!hist) { cerr << "failed to extract: " << path << endl; continue; } if (!result) result = dynamic_cast<TH1 *>(hist->Clone()); else result->Add(hist); } if (do_normalize && result && result->GetEntries()) { result->Scale(1. / result->Integral()); } return result; }
int PlotAndCheck(TTree *tree, TCanvas *c1, int index, const char *selection) { c1->cd(index); tree->Draw("fOffset*fX.fElements",selection); TH1 *href = (TH1*)gPad->GetListOfPrimitives()->FindObject("htemp"); c1->cd(index+1); tree->Draw("mult", selection); TH1 *halias = (TH1*)gPad->GetListOfPrimitives()->FindObject("htemp"); if ( href->GetEntries() != halias->GetEntries() || fabs(href->GetMean()-halias->GetMean()) > 0.000001 ){ fprintf(stdout, "For %s\n",selection); fprintf(stdout, "The direct histogram and the alias histogram are different!\n"); fprintf(stdout, "Entries: %f vs %f\n",href->GetEntries(),halias->GetEntries()); fprintf(stdout, "Mean : %f vs %f\n",href->GetMean(),halias->GetMean()); } return index+2; }
//________________________________________________________ Int_t GFOverlay::AddHistsAt(const TObjArray &hists, const TObjArray &legends, Int_t layer,Int_t pos) { // hists and legends must have same length, but might have gaps... // return number of hists found and added Int_t nHists = 0; for (Int_t iHist = 0; iHist < hists.GetEntriesFast(); ++iHist) { TH1 *hist = static_cast<TH1*>(hists[iHist]); if (!hist) continue; if (fNormalise && hist->GetEntries()) { hist->Scale(1./hist->GetEntries()); } fHistMan->AddHistSame(hist, layer, pos, (legends[iHist] ? legends[iHist]->GetName() : 0)); ++nHists; } return nHists; }
Double_t fitfulllang( char* hs ) { TH1 *h = (TH1*)gDirectory->Get(hs); if( h == NULL ){ cout << hs << " does not exist\n"; return 0; } double aa = h->GetEntries();//normalization // find peak: int ipk = h->GetMaximumBin(); double xpk = h->GetBinCenter(ipk); double sm = xpk / 9; // sigma double ns = sm; // noise // fit range: int ib0 = ipk/2; int ib9 = h->GetNbinsX() - 1; double x0 = h->GetBinLowEdge(ib0); double x9 = h->GetBinLowEdge(ib9) + h->GetBinWidth(ib9); // create a TF1 with the range from x0 to x9 and 4 parameters TF1 *fitFcn = new TF1( "fitFcn", fitLandauGauss, x0, x9, 4 ); fitFcn->SetParName( 0, "peak" ); fitFcn->SetParName( 1, "sigma" ); fitFcn->SetParName( 2, "area" ); fitFcn->SetParName( 3, "smear" ); fitFcn->SetNpx(500); fitFcn->SetLineWidth(4); fitFcn->SetLineColor(kMagenta); // set start values: fitFcn->SetParameter( 0, xpk ); // peak position, defined above fitFcn->SetParameter( 1, sm ); // width fitFcn->SetParameter( 2, aa ); // area fitFcn->SetParameter( 3, ns ); // noise h->Fit("fitFcn", "NQR", "ep" );// R = range from fitFcn return fitFcn->GetParameter(0); }
void HistoProofMan::Save(){ if(!fname[0])return; printf("HistoMan::Save ----> Saving %s\n",fname); TDirectory *dsave = gDirectory; TFile* pp=TFile::Open(fname,"RECREATE"); pp->cd(); hashtable<TH1*>::iterator it; for(it=hlist.begin();it!=hlist.end();it++) { TH1 *obj = it->second; if (obj && obj->GetEntries() > 0) obj->Write(); } pp->Write(); pp->Close(); printf(" ..... done\n"); if (dsave) dsave->cd(); // fdir->Purge(); return; }
void logStatisticsPar(std::ostream& out, RooDataSet *dataSet, RooRealVar *realVar, int nBins, double chi2, const RooArgList &variables) { TH1 *histogram = dataSet->createHistogram(Form("h%s", dataSet->GetName()), *realVar, RooFit::Binning(nBins)); // Create the TeX file out << "\\documentclass[10pt]{article}" << std::endl; out << "\\usepackage[usenames]{color} %used for font color" << std::endl; out << "\\usepackage{fontspec}" << std::endl; out << "\\usepackage{xunicode}" << std::endl; out << "\\usepackage{xltxtra}" << std::endl; out << "\\defaultfontfeatures{Scale=MatchLowercase}" << std::endl; out << "\\setromanfont[Mapping=tex-text]{Myriad Pro}" << std::endl; out << "\\setsansfont[Mapping=tex-text]{Myriad Pro}" << std::endl; out << "\\setmonofont{Monaco}" << std::endl; out << "\\begin{document}" << std::endl; out << "\\thispagestyle{empty}" << std::endl; out << "\\setlength{\\tabcolsep}{1ex}" << std::endl; out << "\\setlength{\\fboxsep}{0ex}" << std::endl; out << "{\\fontsize{7pt}{0.9em}\\selectfont" << std::endl; out << "\\framebox{\\begin{tabular*}{60pt}{l@{\\extracolsep{\\fill}}r}" << std::endl; // This is the particular info for the histogram out << "Entries & " ; formatNumber(histogram->GetEntries(), out) << " \\\\" << std::endl; out << "Mean & " ; formatNumber(histogram->GetMean(), out) << " \\\\" << std::endl; out << "RMS & " ; formatNumber(histogram->GetRMS(), out) << " \\\\" << std::endl; if (chi2 > 0.0) { out << "Fit $\\chi^{2}$ & " ; formatNumber(chi2, out) << " \\\\" << std::endl; } RooRealVar *theVariable; for (int index = 0; index < variables.getSize(); index++) { theVariable = dynamic_cast<RooRealVar*>(variables.find(variables[index].GetName())); out << theVariable->GetTitle() << " & $\\textrm{" ; formatNumber(theVariable->getValV(), out) << "} \\pm \\textrm{" ; formatNumber(theVariable->getError(), out) << "}$ \\\\" << std::endl; } out << "\\end{tabular*}}}" << std::endl; out << "\\end{document}" << std::endl; histogram->Delete(); }
void rescaleBoundaryHists(std::string infile, int numSamples=-1){ TFile* f = new TFile(infile.c_str(), "UPDATE"); TDirectory* dir = 0; TIter dir_it(f->GetListOfKeys()); TKey* dir_k; while ((dir_k = (TKey *)dir_it())) { if (TString(dir_k->GetClassName()) != "TDirectoryFile") continue; std::string dir_name = std::string(dir_k->GetTitle()); if(dir_name == "") continue; dir = (TDirectory*)dir_k->ReadObj(); if(dir == 0) continue; TIter hist_it(dir->GetListOfKeys(), kIterBackward); TKey* hist_k; while ((hist_k = (TKey *)hist_it())) { std::string hist_name = (hist_k->GetTitle()); if (hist_name.find("_HI") != std::string::npos || hist_name.find("_LOW") != std::string::npos || hist_name.find("h_n_mt2bins") != std::string::npos) { TH1* h = (TH1*)hist_k->ReadObj(); if(numSamples==-1) h->Scale(1.0/h->GetEntries()); else h->Scale(1.0/numSamples); dir->cd(); h->Write("",TObject::kOverwrite); } } } delete dir; gDirectory->GetList()->Delete(); f->Write("",TObject::kOverwrite); f->Close(); delete f; }
// Returns the RMS including 96% of the histogram entries, cutting the tails: Double_t getRMS96(char* hs, double truncation=96.) { bool debug = false; TH1 *h = (TH1*)gDirectory->Get(hs); if( h == NULL ){ cout << hs << " does not exist\n"; return 0; } // Total entries: double integral = h->GetEntries(); int maxbin = h->GetMaximumBin(); if(debug) cout << "entries=" << integral << " maxbin=" << maxbin << endl; double subrange_integral = h->GetBinContent(maxbin); int bin = 0; while(subrange_integral < truncation/100*integral) { bin++; // Add one bin to the left: subrange_integral += h->GetBinContent(maxbin-bin); // Add one bin to the right: subrange_integral += h->GetBinContent(maxbin+bin); if(debug) cout << "subrange " << (maxbin-bin) << "-" << (maxbin+bin) << ": entries=" << subrange_integral << endl; } if(debug) cout << "subrange " << (maxbin-bin) << "-" << (maxbin+bin) << " now has " << subrange_integral << " entries, this is " << (100.0*subrange_integral)/integral << "%" << endl; // Correct by overshoot bin: subrange_integral -= h->GetBinContent(maxbin+bin); subrange_integral -= h->GetBinContent(maxbin-bin); bin--; int binlow = maxbin-bin; int binhigh = maxbin+bin; if(debug) cout << "subrange " << (maxbin-bin) << "-" << (maxbin+bin) << " now has " << subrange_integral << " entries, this is " << (100.0*subrange_integral)/integral << "%" << endl; h->GetXaxis()->SetRange(binlow,binhigh); //to restrict range to bins binlow to binhigh double rms96 = h->GetRMS(); //will return the RMS within the axis range return rms96; }
void DoFit(TH2 *hist) { TChannel::DeleteAllChannels(); TChannel::ReadCalFile("GrifCal.cal"); printf("made %i channels.\n",TChannel::GetNumberOfChannels()); TNucleus nuc("152eu"); for(int x = 1; x <= 64; ++x) { printf(" x = %i\n",x); TH1 *p = GetProjectionY(hist,x); if(p->GetEntries() < 100) continue; TGraph* graph = autogain(p,&nuc); TChannel *chan = TChannel::GetChannelByNumber(x); if(!chan) continue; chan->DestroyCalibrations(); chan->AddENGCoefficient(graph->GetFunction("pol1")->GetParameter(0)); chan->AddENGCoefficient(graph->GetFunction("pol1")->GetParameter(1)); chan->SetIntegration(125); } TChannel::WriteCalFile("NewGrifCal.cal"); }
TCanvas* cumulative() { TH1* h = new TH1D("h", "h", 100, -5., 5.); gRandom->SetSeed(); h->FillRandom("gaus", 1u << 16); // get the cumulative of h TH1* hc = h->GetCumulative(); // check that c has the "right" contents Double_t* integral = h->GetIntegral(); for (Int_t i = 1; i <= hc->GetNbinsX(); ++i) { assert(std::abs(integral[i] * h->GetEntries() - hc->GetBinContent(i)) < 1e-7); } // draw histogram together with its cumulative distribution TCanvas* c = new TCanvas; c->Divide(1,2); c->cd(1); h->Draw(); c->cd(2); hc->Draw(); c->Update(); return c; }
//void MergeMetHists(const int Nfiles=0, // const std::string filenamebase="", // const std::string title="", const std::string name="", // const float LoX=-1, const float HiX=-1, const int rebin=1, // const std::string printfile="", bool debug=false) void MergeMetHists(const int Nfiles, const std::string filenamebase, const std::string title, const std::string name, const float LoX=-1, const float HiX=-1, const int rebin=1, const std::string printfile="", const int MetSig=4, bool debug=false, const bool logy=false) { assert (Nfiles>0 && "Number of files must be > 0"); assert (name.length()>0 && "Require hist name!"); assert (filenamebase.length()>0 && "Require base of the file name!"); std::cout << "MetSig=" << MetSig << std::endl; std::cout << "Searching for obj = " << name <<std::endl; std::string data_path, bg_path, def_path; std::string ue1_path, ue2_path, ue3_path, ue4_path, ue5_path, ue6_path; std::string ue7_path, ue8_path, ue9_path; std::string jer1_path, jer2_path, jer3_path, jer4_path, jer5_path; std::string jer6_path, jer7_path, jer8_path, jer9_path, jer10_path; data_path="/Ana/MyJetFilter/Hist/Ana_data/"; bg_path="/Ana/MyJetFilter/Hist/Ana_bckg/"; def_path="/Ana/MyJetFilter/Hist/Ana_def/"; ue1_path="/Ana/MyJetFilter/Hist/Ana_ue1/"; ue2_path="/Ana/MyJetFilter/Hist/Ana_ue2/"; ue3_path="/Ana/MyJetFilter/Hist/Ana_ue3/"; ue4_path="/Ana/MyJetFilter/Hist/Ana_ue4/"; ue5_path="/Ana/MyJetFilter/Hist/Ana_ue5/"; ue6_path="/Ana/MyJetFilter/Hist/Ana_ue6/"; ue7_path="/Ana/MyJetFilter/Hist/Ana_ue7/"; ue8_path="/Ana/MyJetFilter/Hist/Ana_ue8/"; ue9_path="/Ana/MyJetFilter/Hist/Ana_ue9/"; jer1_path="/Ana/MyJetFilter/Hist/Ana_jer1/"; jer2_path="/Ana/MyJetFilter/Hist/Ana_jer2/"; jer3_path="/Ana/MyJetFilter/Hist/Ana_jer3/"; jer4_path="/Ana/MyJetFilter/Hist/Ana_jer4/"; jer5_path="/Ana/MyJetFilter/Hist/Ana_jer5/"; jer6_path="/Ana/MyJetFilter/Hist/Ana_jer6/"; jer7_path="/Ana/MyJetFilter/Hist/Ana_jer7/"; jer8_path="/Ana/MyJetFilter/Hist/Ana_jer8/"; jer9_path="/Ana/MyJetFilter/Hist/Ana_jer9/"; jer10_path="/Ana/MyJetFilter/Hist/Ana_jer10/"; /* data_path="Ana_data"; bg_path="Ana_bckg"; def_path="Ana_def"; ue1_path="Ana_ue1"; ue2_path="Ana_ue2"; ue3_path="Ana_ue3"; ue4_path="Ana_ue4"; ue5_path="Ana_ue5"; ue6_path="Ana_ue6"; ue7_path="Ana_ue7"; ue8_path="Ana_ue8"; ue9_path="Ana_ue9"; jer1_path="Ana_jer1"; jer2_path="Ana_jer2"; jer3_path="Ana_jer3"; jer4_path="Ana_jer4"; jer5_path="Ana_jer5"; jer6_path="Ana_jer6"; jer7_path="Ana_jer7"; jer8_path="Ana_jer8"; jer9_path="Ana_jer9"; jer10_path="Ana_jer10"; */ std::vector<std::string> vPaths; vPaths.push_back(data_path); vPaths.push_back(bg_path); vPaths.push_back(def_path); vPaths.push_back(ue1_path); vPaths.push_back(ue2_path); vPaths.push_back(ue3_path); vPaths.push_back(ue4_path); vPaths.push_back(ue5_path); vPaths.push_back(ue6_path); vPaths.push_back(ue7_path); vPaths.push_back(ue8_path); vPaths.push_back(ue9_path); vPaths.push_back(jer1_path); vPaths.push_back(jer2_path); vPaths.push_back(jer3_path); vPaths.push_back(jer4_path); vPaths.push_back(jer5_path); vPaths.push_back(jer6_path); vPaths.push_back(jer7_path); vPaths.push_back(jer8_path); vPaths.push_back(jer9_path); vPaths.push_back(jer10_path); TFile *f = 0; TH1 *hist_data = 0, *hist_bg = 0; int iNHists = vPaths.size(); std::vector<TH1*> vHist; for (int n= 0; n < iNHists; ++n) { TH1 *temp=0; vHist.push_back(temp); } int NfilesOpened = 0; //for (int i=1; i<=1; ++i) for (int i=1; i<=Nfiles; ++i) { std::stringstream file; file << filenamebase << i; //file << "myhisto_PhoJetAna_Pyth_phojet22_1Njet15_test_040208.root"; f = new TFile (file.str().c_str()); if (f->IsZombie()) { std::cout << "ERROR::File " << file.str() << " did not open! Exiting." << std::endl; exit (1); } else { NfilesOpened++; if (debug) { std::cout << "File Added::"; f->Print(); } } gROOT->ls(); TFolder *fold = (TFolder*) gDirectory->FindObjectAny("Ana"); assert(fold != NULL && "folder null"); TFolder *dir = (TFolder*) fold->FindObjectAny("MyJetFilter"); assert(dir != NULL && "dir null"); TFolder *dir2 = (TFolder*) dir->FindObjectAny("Hist"); assert(dir2 != NULL && "Hist null"); //TH1 *h = dynamic_cast<TH1*> (dir3->FindObjectAny(name.c_str())); //assert (h!=NULL && "hist null"); //h->Draw(); //return; for (unsigned int iPath = 0; iPath < vPaths.size(); ++iPath) { //std::cout << "iPath = " << iPath << std::endl; TFolder *dir3 = (TFolder*) dir2->FindObjectAny(vPaths.at(iPath).c_str()); assert(dir3 != NULL && "data null"); //f->cd(); //gDirectory->pwd(); //f->cd(vPaths.at(iPath).c_str()); //gDirectory->pwd(); //if (iPath<2) f->ls(); //TH1 *hTemp = dynamic_cast<TH1*> (gDirectory->FindObjectAny(name.c_str())); std::stringstream histpath; histpath << vPaths.at(iPath) << name; //TFolder *ana = (TFolder*) gDirectory->FindObjectAny("Ana"); //assert(ana !=NULL && "Ana folder not found"); //std::cout << "histpath = " << histpath.str() << std::endl; TH1 *hTemp = dynamic_cast<TH1*> (dir3->FindObjectAny(name.c_str())); assert(hTemp != NULL && "object not found!"); if (hTemp->GetEntries()) // this has to be done to avoid crashes when adding hists which some how have 'sum=nan' instead of 'sum=0' when they do not have any entries. { if (! vHist.at(iPath)) { std::string name = hTemp->GetName() + std::string ("_Clone"); vHist.at(iPath) = dynamic_cast<TH1*>(hTemp->Clone (name.c_str())); assert(vHist.at(iPath) != NULL && "Data hist cast failed"); vHist.at(iPath)->SetDirectory(0); } else { vHist.at(iPath)->Add(hTemp); } } } delete f; } /* assert(vHist.size() == vPaths.size()); for (int k=0; k < vHist.size(); ++k) { vHist.at(k)->Print(); } */ DoSystematics(vHist); hist_data = vHist.at(0); hist_bg = vHist.at(1); /* std::cout << "NORMALIZING BG TO DATA " << std::endl; double data_int = hist_data->Integral(); double bg_int = hist_bg->Integral(); hist_bg->Scale(data_int/bg_int); std::cout << "SCALE = " << data_int/bg_int << std::endl; */ if (debug) { hist_data->Print("all"); hist_bg->Print("all"); } std::cout << "Total file added = " << NfilesOpened << std::endl; gStyle->SetOptStat(""); if (hist_data->GetEntries()) hist_data->Rebin(rebin); if (hist_bg->GetEntries()) hist_bg->Rebin(rebin); TH1 *hist_err_copy = NULL; std::string bgname = hist_bg->GetName() + std::string ("err_copy"); hist_err_copy = dynamic_cast<TH1*>(hist_bg->Clone (bgname.c_str())); hist_err_copy->SetDirectory(0); TH1 *hist_data_copy = NULL; std::string dataname = hist_data->GetName() + std::string ("data_copy"); hist_data_copy = dynamic_cast<TH1*>(hist_data->Clone (dataname.c_str())); hist_data_copy->SetDirectory(0); float x_loLim, x_hiLim; if (LoX >0) x_loLim = LoX; else x_loLim = hist_data->GetBinLowEdge(1); if (HiX >0) x_hiLim = HiX; else x_hiLim = max(FindUpLimit(hist_data), FindUpLimit(hist_bg)) + hist_data->GetBinWidth(1) * 2; if (debug) { std::cout << "min, max = " << x_loLim << ", " << x_hiLim << std::endl; } float y_hiLim = max(FindUpLimit(hist_data,"Y"), FindUpLimit(hist_bg,"Y")); if (logy) y_hiLim *= 10; else y_hiLim += y_hiLim * 0.1; gStyle->SetCanvasColor (10); gStyle->SetCanvasBorderSize (0); gStyle->SetCanvasBorderMode (0); gStyle->SetPadColor (10); gStyle->SetFillColor (10); gStyle->SetTitleFillColor (10); gStyle->SetTitleBorderSize (0); gStyle->SetStatColor (10); gStyle->SetStatBorderSize (1); gStyle->SetCanvasDefW(1200); gStyle->SetCanvasDefH(600); int labelfont = 10 * 4 + 2; //10 * font ID + precision (2 = scalable) int titlefont = 10 * 4 + 2; //10 * font ID + precision (2 = scalable) gStyle->SetLabelFont(labelfont,"X"); gStyle->SetLabelFont(labelfont,"Y"); gStyle->SetTitleFont(titlefont,"X"); gStyle->SetTitleFont(titlefont,"Y"); gStyle->SetLabelSize(0.04,"X"); gStyle->SetLabelSize(0.027,"Y"); //gStyle->SetLabelOffset(0.9); gStyle->SetTitleSize(0.03,"Y"); gStyle->SetTitleOffset(1.8,"Y"); //TGaxis::SetMaxDigits(3); hist_data->UseCurrentStyle(); hist_bg->UseCurrentStyle(); TCanvas *c1= new TCanvas; c1->Divide(2,1); c1->cd(1); if (logy) { if (hist_data->GetEntries() > 0 && hist_bg->GetEntries() > 0) gPad->SetLogy(); } gPad->SetTickx(); gPad->SetTicky(); gPad->SetGridx(); gPad->SetGridy(); TPaveText *tp = new TPaveText(0.02,0.92,0.98,0.99,"NDC"); tp->SetLineColor(10); tp->SetTextFont(titlefont); std::string tt(hist_data->GetTitle()); // hist_data->SetTitle(""); // hist_bg->SetTitle(""); if (title.length()>0) { //tt += " - "; tt += title; //tt = title; if (debug) { std::cout << tt << std::endl; } tp->AddText(tt.c_str()); } std::stringstream ytitle, xtitle; ytitle << "Events / " << setprecision(3) << hist_data->GetXaxis()->GetBinWidth(1) << " GeV"; if (debug) { std::cout << hist_data->GetBinWidth(1) <<std::endl; } if (name == "MetAll") xtitle << "#slash{E}_{T} (for all events) (GeV)"; else if (name == "Met") xtitle << "#slash{E}_{T} (after cuts) (GeV)"; else if (name == "MetSig") xtitle << "#slash{E}_{T} Significance (for all events)"; else if (name == "Njet15") xtitle << "Njets^{E_{T}>15GeV} (After #slash{E}_{T}-Sig cut)"; else if (name == "Njet20") xtitle << "Njets^{E_{T}>20GeV} (After #slash{E}_{T}-Sig cut)"; else if (name == "Njet25") xtitle << "Njets^{E_{T}>25GeV} (After #slash{E}_{T}-Sig cut)"; else if (name == "Njet30") xtitle << "Njets^{E_{T}>30GeV} (After #slash{E}_{T}-Sig cut)"; else if (name == "Njet35") xtitle << "Njets^{E_{T}>35GeV} (After #slash{E}_{T}-Sig cut)"; if (debug) { std::cout << "xtitle=" << xtitle.str() << std::endl; } if (debug) { hist_data->Print(); std::cout << "bin#\tLoEdge\tdata\tdata_err\tbg_cont\tbg_err"<<std::endl; for (unsigned bin = 0; bin <= (unsigned) hist_data_copy->GetNbinsX() + 1; ++ bin) { float val = hist_data->GetBinContent (bin); float err = hist_data->GetBinError(bin); float val2 = hist_bg->GetBinContent (bin); float err2 = hist_bg->GetBinError(bin); float loEdge = hist_data->GetBinLowEdge(bin); if (val>0 || err>0 || val2>0 || err2>0) std::cout << bin << "\t" << loEdge <<"\t" << val << "\t" << err << "\t\t" << val2 << "\t" << err2 << std::endl; } } hist_data->GetXaxis()->SetTitle(xtitle.str().c_str()); if (name.find("Njet") == std::string::npos) hist_data->GetYaxis()->SetTitle(ytitle.str().c_str()); hist_data->GetXaxis()->CenterTitle(true); hist_data->GetYaxis()->CenterTitle(true); hist_bg->GetXaxis()->SetTitle(xtitle.str().c_str()); if (name.find("Njet") == std::string::npos) hist_bg->GetYaxis()->SetTitle(ytitle.str().c_str()); hist_bg->GetXaxis()->CenterTitle(true); hist_bg->GetYaxis()->CenterTitle(true); //temp x_loLim = 0; x_hiLim = 200; hist_data->GetXaxis()->SetRangeUser(x_loLim, x_hiLim); hist_bg->GetXaxis()->SetRangeUser(x_loLim, x_hiLim); hist_data->SetMinimum(0.1); hist_bg->SetMinimum(0.1); hist_data->SetMaximum(y_hiLim); hist_bg->SetMaximum(y_hiLim); hist_data->SetMarkerStyle(8); hist_data->SetMarkerSize(1.0); hist_data->SetMarkerColor(kBlue); hist_data->SetLineColor(kBlue); hist_bg->SetMarkerColor(kRed); hist_bg->SetLineColor(kRed); hist_bg->SetFillColor(kRed); hist_data->SetTitleSize(0.04); hist_bg->SetTitleSize(0.04); TH1* hist_bg_copy = dynamic_cast<TH1*>(hist_bg->Clone ("hist_bg_BlkLine")); hist_bg_copy->SetLineColor(kBlack); hist_bg_copy->SetLineWidth(2); hist_bg_copy->SetFillColor(0); //hist_bg_copy->Draw("L"); //hist_bg->Draw("sameE2"); // hist_bg->SetFillColor(10); // hist_bg->SetLineColor(10); hist_bg->Draw("E2"); hist_bg_copy->Draw("SAME HIST"); hist_data->Draw("sameP"); //tp->Draw(); TLegend *leg = new TLegend (0.4,0.8,0.90,0.90); leg->SetTextFont(42); leg->SetTextSize(0.025); leg->SetBorderSize (1); leg->SetFillColor (10); //std::stringstream leg_data, leg_bg; //leg_data << "Data (E=" << hist_data->GetEntries() << " M=" << hist_data->GetMean() // << " R=" << hist_data->GetRMS() << ")"; //leg_bg << "Bkg (E=" << hist_bg->GetEntries() << " M=" << hist_bg->GetMean() // << " R=" << hist_bg->GetRMS() << ")"; //leg->AddEntry(hist_data,leg_data.str().c_str()); //leg->AddEntry(hist_bg,leg_bg.str().c_str()); //leg->AddEntry(hist_data,"Data (Measured) (DET Jets) "); //leg->AddEntry(hist_bg, "MC Prediction (HAD Jets, Norm to Data)"); leg->AddEntry(hist_data,"Data (Measured)"); leg->AddEntry(hist_bg, "MC Prediction"); leg->Draw(); // now to make the ratio plots for (unsigned bin = 0; bin <= (unsigned) hist_data_copy->GetNbinsX() + 1; ++ bin) { const float val = hist_err_copy->GetBinContent (bin); const float scale = val ? 1. / val : 0; hist_data_copy->SetBinContent (bin, (hist_data_copy->GetBinContent (bin) - val) * scale); hist_data_copy->SetBinError (bin, hist_data_copy->GetBinError (bin) * scale); }; for (unsigned bin = 0; bin <= (unsigned) hist_err_copy->GetNbinsX() + 1; ++ bin) { float value = hist_err_copy->GetBinContent (bin); float error = hist_err_copy->GetBinError (bin); hist_err_copy->SetBinError (bin, value ? error / value : 0); hist_err_copy->SetBinContent (bin, 0); }; /* TH1 *hist_ratio = NULL; std::string myname = hist_data->GetName() + std::string ("_copy"); hist_ratio = dynamic_cast<TH1*>(hist_data->Clone (myname.c_str())); hist_ratio->Divide(hist_bg); */ hist_data_copy->UseCurrentStyle(); hist_err_copy->UseCurrentStyle(); //new TCanvas(); c1->cd(2); gPad->SetTickx(); gPad->SetTicky(); gPad->SetGridx(); gPad->SetGridy(); hist_data_copy->SetTitle(""); hist_err_copy->SetTitle(""); //hist_data_copy->SetTitle(tt.c_str()); //hist_err_copy->SetTitle(tt.c_str()); hist_data_copy->GetXaxis()->SetTitle(xtitle.str().c_str()); hist_err_copy->GetXaxis()->SetTitle(xtitle.str().c_str()); hist_data_copy->GetXaxis()->SetRangeUser(x_loLim, x_hiLim); hist_err_copy->GetXaxis()->SetRangeUser(x_loLim, x_hiLim); float fRatioHist_ymax = 1.0; float fRatioHist_ymin = -1.0; hist_data_copy->SetMinimum(fRatioHist_ymin); hist_data_copy->SetMaximum(fRatioHist_ymax); hist_err_copy->SetMinimum(fRatioHist_ymin); hist_err_copy->SetMaximum(fRatioHist_ymax); std::stringstream ratio_ytitle; ratio_ytitle << "(Data Measured - MC Prediction) / MC Prediction"; hist_data_copy->GetYaxis()->SetTitle(ratio_ytitle.str().c_str()); hist_err_copy->GetYaxis()->SetTitle(ratio_ytitle.str().c_str()); //hist_data_copy->SetTitle(ratio_ytitle.str().c_str()); //hist_err_copy->SetTitle(ratio_ytitle.str().c_str()); hist_data_copy->GetXaxis()->CenterTitle(true); hist_data_copy->GetYaxis()->CenterTitle(true); hist_err_copy->GetXaxis()->CenterTitle(true); hist_err_copy->GetYaxis()->CenterTitle(true); // hist_data->GetYaxis()->SetRangeUser(; //// hist_bg->SetMinimum(0.1); hist_data_copy->SetLineColor(kBlue); hist_data_copy->SetMarkerColor(kBlue); hist_data_copy->SetMarkerStyle (8); hist_data_copy->SetMarkerSize(1.0); hist_err_copy->SetFillColor(kRed); hist_err_copy->SetFillStyle(3002); hist_data_copy->Draw("P"); hist_err_copy->Draw("same E2"); //tp->Draw(); c1->cd(); if (printfile.length()>0) { c1->Print(printfile.c_str()); } DebugSystError(hist_data,hist_bg, hist_data_copy, hist_err_copy); }
//------------------------------------------------------------------------------ void PlotAlignmentValidation::plotOutlierModules(const char *outputFileName, std::string plotVariable, float plotVariable_cut ,int unsigned minHits) { Int_t counter=0; setNiceStyle(); gStyle->SetOptStat(111111); gStyle->SetStatY(0.9); //TList treelist=getTreeList(); TCanvas *c1 = new TCanvas("canv", "canv", 800, 500); //setCanvasStyle( *c1 ); outputFile = outputDir +'/'+ outputFileName; c1->Print( (outputFile+'[').Data() ); c1->Divide(2,1); TTree *tree= (*sourceList.begin())->getTree(); TkOffTreeVariables *treeMem = 0; // ROOT will initilise tree->SetBranchAddress("TkOffTreeVariables", &treeMem); Long64_t nentries = tree->GetEntriesFast(); for (Long64_t i = 0; i < nentries; i++){ tree->GetEntry(i); float var = 0; if (plotVariable == "chi2PerDofX") var =treeMem->chi2PerDofX; else if(plotVariable == "chi2PerDofY") var =treeMem->chi2PerDofY; else if(plotVariable == "fitMeanX") var =treeMem->fitMeanX; else if(plotVariable == "fitMeanY") var =treeMem->fitMeanY; else if(plotVariable == "fitSigmaX") var =treeMem->fitSigmaX; else if(plotVariable == "fitSigmaY") var =treeMem->fitSigmaY; else { cout<<"There is no variable "<<plotVariable<<" included in the tree."<<endl; break; } // cout<<"treeMem->entries "<<treeMem->entries<<endl; // cout<<"var "<<var<<endl; // cout<<"plotVariable_cut "<<plotVariable_cut<<endl; if (var > plotVariable_cut && treeMem->entries > minHits) { TFile *f=(*sourceList.begin())->getFile();//(TFile*)sourcelist->First(); if(f->FindKeyAny(treeMem->histNameX.c_str())!=0){ TH1 *h = (TH1*) f->FindKeyAny(treeMem->histNameX.c_str())->ReadObj();//f->FindObjectAny(treeMem->histNameX.c_str()); gStyle->SetOptFit(0111); cout<<"hist name "<<h->GetName()<<endl; TString path =(char*)strstr( gDirectory->GetPath(), "TrackerOfflineValidation" ); //cout<<"hist path "<<path<<endl; //cout<<"wrote text "<<endl; if(h) cout<<h->GetEntries()<<endl; //modules' location as title c1->cd(0); TPaveText * text=new TPaveText(0,0.95,0.99,0.99); text->AddText(path); text->SetFillColor(0); text->SetShadowColor(0); text->SetBorderSize( 0 ); text->Draw(); //residual histogram c1->cd(1); TPad *subpad = (TPad*)c1->GetPad(1); subpad->SetPad(0,0,0.5,0.94); h->Draw(); //norm. residual histogram h = (TH1*) f->FindObjectAny(treeMem->histNameNormX.c_str()); if(h) cout<<h->GetEntries()<<endl; c1->cd(2); TPad *subpad2 = (TPad*)c1->GetPad(2); subpad2->SetPad(0.5,0,0.99,0.94); h->Draw(); c1->Print(outputFile); counter++; } else{ cout<<"There are no residual histograms on module level stored!"<<endl; cout<<"Please make sure that moduleLevelHistsTransient = cms.bool(False) in the validation job!"<<endl; break; } } } c1->Print( (outputFile+"]").Data() ); if (counter == 0) cout<<"no bad modules found"<<endl; //read the number of entries in the t3 //TTree* tree=0; //tree=(TTree*)treeList->At(0); //c1->Close(); }
void Fit(TString SIGNAL,TString HISTO,double scaleSGN) { gROOT->ForceStyle(); TFile *fDat = TFile::Open("Histo_flatTree_data_tmva"+SIGNAL+".root"); TFile *fBkg = TFile::Open("Histo_flatTree_qcd_weights_tmva"+SIGNAL+".root"); TFile *fSgn = TFile::Open("Histo_flatTree_"+SIGNAL+"_weights_tmva"+SIGNAL+".root"); TH1 *hDat = (TH1*)fDat->Get(HISTO); TH1 *hBkgRaw = (TH1*)fBkg->Get(HISTO); TH1 *hSgn = (TH1*)fSgn->Get(HISTO); TH1 *hDat_JESlo = (TH1*)fDat->Get(HISTO+"_JESlo"); TH1 *hBkgRaw_JESlo = (TH1*)fBkg->Get(HISTO+"_JESlo"); TH1 *hSgn_JESlo = (TH1*)fSgn->Get(HISTO+"_JESlo"); TH1 *hDat_JESup = (TH1*)fDat->Get(HISTO+"_JESup"); TH1 *hBkgRaw_JESup = (TH1*)fBkg->Get(HISTO+"_JESup"); TH1 *hSgn_JESup = (TH1*)fSgn->Get(HISTO+"_JESup"); TH1F *hBkg = (TH1F*)hBkgRaw->Clone("Bkg"); TH1F *hBkg_JESlo = (TH1F*)hBkgRaw_JESlo->Clone("Bkg_JESlo"); TH1F *hBkg_JESup = (TH1F*)hBkgRaw_JESup->Clone("Bkg_JESup"); hBkg->Smooth(2); hBkg_JESlo->Smooth(2); hBkg_JESup->Smooth(2); hSgn->Smooth(2); hSgn_JESlo->Smooth(2); hSgn_JESup->Smooth(2); double lumi = 4967; hBkg->Scale(lumi); hBkg_JESlo->Scale(lumi); hBkg_JESup->Scale(lumi); double k_factor = hDat->Integral()/hBkg->Integral(); double k_factor_JESlo = hDat->Integral()/hBkg_JESlo->Integral(); double k_factor_JESup = hDat->Integral()/hBkg_JESup->Integral(); hBkg->Scale(k_factor); cout<<"Signal entries = "<<hSgn->GetEntries()<<endl; hSgn->Scale(lumi/scaleSGN); hBkg_JESlo->Scale(k_factor_JESlo); hSgn_JESlo->Scale(lumi/scaleSGN); hBkg_JESup->Scale(k_factor_JESup); hSgn_JESup->Scale(lumi/scaleSGN); hSgn_JESlo->Scale(hSgn->Integral()/hSgn_JESlo->Integral()); hSgn_JESup->Scale(hSgn->Integral()/hSgn_JESup->Integral()); TH1 *hBkg_STATlo = (TH1*)hBkg->Clone(HISTO+"_STATlo"); TH1 *hSgn_STATlo = (TH1*)hSgn->Clone(HISTO+"_STATlo"); TH1 *hBkg_STATup = (TH1*)hBkg->Clone(HISTO+"_STATup"); TH1 *hSgn_STATup = (TH1*)hSgn->Clone(HISTO+"_STATup"); float y1,e1; for(int i=0;i<hBkg->GetNbinsX();i++) { y1 = hBkg->GetBinContent(i+1); e1 = hBkg->GetBinError(i+1); hBkg_STATlo->SetBinContent(i+1,y1-e1); hBkg_STATup->SetBinContent(i+1,y1+e1); y1 = hSgn->GetBinContent(i+1); e1 = hSgn->GetBinError(i+1); hSgn_STATlo->SetBinContent(i+1,y1-e1); hSgn_STATup->SetBinContent(i+1,y1+e1); } hBkg_STATlo->Scale(hBkg->Integral()/hBkg_STATlo->Integral()); hBkg_STATup->Scale(hBkg->Integral()/hBkg_STATup->Integral()); hSgn_STATlo->Scale(hSgn->Integral()/hSgn_STATlo->Integral()); hSgn_STATup->Scale(hSgn->Integral()/hSgn_STATup->Integral()); double xMIN = hBkg->GetBinLowEdge(1); double xMAX = hBkg->GetBinLowEdge(hBkg->GetNbinsX()+1); double xMIN2 = hDat->GetBinLowEdge(hDat->FindFirstBinAbove(0.5)); double xMAX2 = hDat->GetBinLowEdge(hDat->FindLastBinAbove(0.5)+1); RooRealVar x("x","x",xMIN2,xMAX2); RooDataHist data("data","dataset with x",x,hDat); RooDataHist bkg("qcd","bkg with x",x,hBkg); RooDataHist sgn("signal","sgn with x",x,hSgn); RooHistPdf bkgPDF("bkgPDF","bkgPDF",x,bkg,0); RooHistPdf sgnPDF("sgnPDF","sgnPDF",x,sgn,0); RooRealVar f("f","f",0,0.,1.); RooAddPdf model("model","model",RooArgList(sgnPDF,bkgPDF),RooArgList(f)); RooFitResult* r = model.fitTo(data,Save()); r->Print("v"); double N = hDat->Integral(); double B = hBkg->Integral(); double S = hSgn->Integral(); double m = f.getVal(); double e = f.getError(); cout<<"k-factor = "<<k_factor<<endl; cout<<N<<" "<<B<<" "<<S<<endl; cout<<"Total cross section = "<<N/lumi<<" pb"<<endl; cout<<"Model cross section = "<<S/lumi<<" pb"<<endl; cout<<"Fitted signal strength = "<<m*N/S<<endl; cout<<"Fitted signal error = "<<e*N/S<<endl; double p = 0.95; double xup = (N/S)*(m+sqrt(2.)*e*TMath::ErfInverse((1-p)*TMath::Erf(m/e)+p)); cout<<"Bayesian Upper limit = "<<xup<<endl; RooPlot* frame1 = x.frame(); data.plotOn(frame1); model.plotOn(frame1,Components("sgnPDF*"),LineStyle(1),LineWidth(2),LineColor(kGreen+1)); model.plotOn(frame1,Components("bkgPDF*"),LineStyle(1),LineWidth(2),LineColor(kRed)); model.plotOn(frame1,LineStyle(1),LineWidth(2),LineColor(kBlue)); //cout<<frame1->chiSquare()<<endl; RooHist* hresid = frame1->residHist(); RooHist* hpull = frame1->pullHist(); RooPlot* frame2 = x.frame(Title("Residual Distribution")); frame2->addPlotable(hresid,"P") ; // Create a new frame to draw the pull distribution and add the distribution to the frame RooPlot* frame3 = x.frame(Title("Pull Distribution")); frame3->addPlotable(hpull,"P"); TCanvas* cFit = new TCanvas("fitANN_"+SIGNAL,"fitANN_"+SIGNAL,900,600); gPad->SetLogy(); frame1->SetMaximum(1e+4); frame1->SetMinimum(0.5); frame1->GetXaxis()->SetTitle("ANN Output"); frame1->GetYaxis()->SetTitle("Events"); frame1->Draw(); cout<<frame1->nameOf(3)<<endl; TLegend *leg = new TLegend(0.7,0.65,0.9,0.9); leg->SetHeader(SIGNAL); leg->AddEntry(frame1->findObject("h_data"),"data","P"); leg->AddEntry(frame1->findObject("model_Norm[x]"),"QCD+Signal","L"); leg->AddEntry(frame1->findObject("model_Norm[x]_Comp[bkgPDF*]"),"QCD","L"); leg->AddEntry(frame1->findObject("model_Norm[x]_Comp[sgnPDF*]"),"Signal","L"); leg->SetFillColor(0); leg->SetBorderSize(0); leg->SetTextFont(42); leg->SetTextSize(0.04); leg->Draw(); TCanvas* cPull = new TCanvas("pullANN_"+SIGNAL,"pullANN_"+SIGNAL,900,400); frame3->GetXaxis()->SetTitle("ANN Output"); frame3->GetYaxis()->SetTitle("Pull"); frame3->Draw(); cout<<"Creating datacard"<<endl; ofstream datacard; datacard.open("datacard_"+SIGNAL+"_"+HISTO+".txt"); datacard.setf(ios::right); datacard<<"imax 1"<<"\n"; datacard<<"jmax 1"<<"\n"; datacard<<"kmax *"<<"\n"; datacard<<"----------------"<<"\n"; datacard<<"shapes * * "<<SIGNAL+"_"+HISTO+"_input.root $PROCESS $PROCESS_$SYSTEMATIC"<<"\n"; datacard<<"----------------"<<"\n"; datacard<<"bin 1"<<"\n"; datacard<<"observation "<<N<<"\n"; datacard<<"----------------"<<"\n"; datacard<<"bin 1 1"<<"\n"; datacard<<"process signal background "<<"\n"; datacard<<"process 0 1"<<"\n"; datacard<<"rate "<<S<<" "<<B<<"\n"; datacard<<"----------------"<<"\n"; datacard<<"lumi lnN 1.022 1.022"<<"\n"; datacard<<"jes shape 1 1"<<"\n"; datacard<<"mcstat shape 1 1"<<"\n"; datacard<<"jer shape 0 0"<<"\n"; datacard.close(); TFile *out = new TFile(SIGNAL+"_"+HISTO+"_input.root","RECREATE"); out->cd(); hDat->Write("data_obs"); hBkg->Write("background"); hSgn->Write("signal"); hDat_JESlo->Write("data_obs_jesDown"); hBkg_JESlo->Write("background_jesDown"); hBkg_STATlo->Write("background_mcstatDown"); hSgn_STATlo->Write("signal_mcstatDown"); hSgn_JESlo->Write("signal_jesDown"); hDat_JESup->Write("data_obs_jesUp"); hBkg_JESup->Write("background_jesUp"); hBkg_STATup->Write("background_mcstatUp"); hSgn_JESup->Write("signal_jesUp"); hSgn_STATup->Write("signal_mcstatUp"); //----- JER placeholder ---------------- hBkg_JESlo->Write("background_jerDown"); hSgn_JESlo->Write("signal_jerDown"); hBkg_JESup->Write("background_jerUp"); hSgn_JESup->Write("signal_jerUp"); }
void calculateTriggerRates( TString inFile0Name = "root://eoscms//eos/cms/store/caf/user/velicanu/PA2013_merged_HiForest/pPb_hiForest2_1_15_test.root", // TString inFile0Name = "/castor/cern.ch/user/m/miheejo/openHLT/cms442/r181530_reco_v1_2/HIExpressPhysics_hiexp-hirun2011-r181530-reco-v1_2.root", // "/castor/cern.ch/user/k/kimy/openHLT//openhlt_run181531.root", // "/castor/cern.ch/user/v/velicanu/HIHLT_Validation_Test_GRIF_v10.root", Int_t runNum = 202792, TString outdir = "output", char *projectTitle = "HIpARun2013", string source = "data" ) { char szBuf[256]; int scale = 23; // event selectoin //Form("&&Run==%d&&LumiBlock>%d",runNum,goodLumiStart) // trigger under investigation // const int ntrigs = 8; // const char* triggerPath[ntrigs] = {"","HLT_HIMinBiasHfOrBSC", // "L1_SingleMu3_BptxAND","HLT_HIL1SingleMu3","HLT_HIL2Mu3", // "L1_DoubleMuOpen_BptxAND","HLT_HIL1DoubleMuOpen","HLT_HIL2DoubleMu3"}; const int ntrigs = 9; const char* triggerPath[ntrigs] = { "", "HLT_PAL1SingleMuOpen_v1", "HLT_PAL1SingleMu3_v1", "HLT_PAL1SingleMu7_v1", "HLT_PAL1SingleMu12_v1", "HLT_PAL1DoubleMu0_v1", "HLT_PADimuon0_NoVertexing_v1", "HLT_PAMu5_v1", "HLT_PAMu8_v1" }; TString str; TH1D *ahTemp[ntrigs]; double ahTempRate[ntrigs]; //Rates (Integrated over lumisections) // Load input TChain * HltTree = new TChain("hltanalysis/HltTree","HI OpenHLT Tree"); HltTree->Add(inFile0Name); cout << inFile0Name << endl; cout << " # entries: " << HltTree->GetEntries() << endl; int nEvents = HltTree->GetEntries(); for(int it=1; it<ntrigs; it++) { TH1D *ph = new TH1D("ph","",1100,0,1100); HltTree->Draw("LumiBlock>>ph",str.Format("%s",triggerPath[it])); TH1D *phLumi = (TH1D*)gDirectory->Get("ph"); phLumi->SetDirectory(0); phLumi->Scale(1./(phLumi->GetBinWidth(1)*23));// 1lumi unit=23 sec ahTempRate[it] = phLumi->Integral()/phLumi->GetNbinsX(); ahTemp[it] = phLumi; cout<< triggerPath[it]<<"\t"<<phLumi->GetEntries()<< "\t" << ahTempRate[it] << endl; } //---------------------------- // drawing part // axis // TH1D * phLumiAxis = new TH1D("phLumiAxis",";Lumi Section;dEvt/dLumiSec",1100,0,1100); TH1D * phLumiAxis = new TH1D("phLumiAxis",";Lumi Section;Rate [Hz]",1,0,1200); phLumiAxis->SetMinimum(0.01); phLumiAxis->SetMaximum(1e+3); gStyle->SetOptStat(kFALSE); // legend TLegend *l0= new TLegend(0.2,0.4,0.8,0.9); l0->SetHeader(str.Format("HICorePhysics_L1DoubleMuOpen: %d",nEvents)); l0->SetMargin(0.1); l0->SetFillStyle(0); l0->SetLineColor(0); l0->SetLineWidth(5.0); l0->SetTextSize(0.03); // canvas TCanvas *pcLumi = new TCanvas("pcLumi","pcLumi"); pcLumi->cd(); phLumiAxis->Draw(); pcLumi->SetLogy(); for(int it=1; it<ntrigs; it++) { TH1 *phLocal = (TH1 *)(ahTemp[it]->Clone("phLocal")); phLocal->SetDirectory(0); phLocal->SetLineColor(it); if (it >= 10) phLocal->SetLineColor(it+20); if(it==5) phLocal->SetLineColor(kOrange+2); phLocal->Draw("same"); l0->AddEntry(phLocal,str.Format("%s: %.2f%, %.2f Hz",triggerPath[it],100*phLocal->GetEntries()/nEvents,ahTempRate[it]),"l");; pcLumi->Update(); } l0->Draw("same"); pcLumi->SaveAs("TrigRate.pdf"); }
void dataCutM(int cent0=20, int cent1=25, int from=0, int to=34){ char name[200]; int bad, centrality; float trk_Q [RDET][NHAR]; float trk_Psi [RDET][NHAR]; float cal_Q [CDET][NHAR]; float cal_Psi [CDET][NHAR]; TChain* tree = new TChain("tree"); char dfilelist[100]; sprintf(dfilelist,"outlist.txt"); ifstream lis(dfilelist); int cnt=0; int dnt=0; while(!lis.eof()) { string filename; lis >> filename; if(cnt>=from&&cnt<to) { cout << filename << endl; if(!filename.empty()) tree->Add(filename.c_str()); dnt++; } cnt++; } tree->SetBranchAddress("bad", &bad); tree->SetBranchAddress("centrality", ¢rality); tree->SetBranchAddress("trk_Q", trk_Q ); tree->SetBranchAddress("trk_Psi", trk_Psi ); tree->SetBranchAddress("cal_Q", cal_Q ); tree->SetBranchAddress("cal_Psi", cal_Psi ); float Trk_Q [RDET][NHAR]; float Trk_Psi[RDET][NHAR]; float Cal_Q [CDET][NHAR]; float Cal_Psi[CDET][NHAR]; Init(cent0, cent1); cout<<"Run Centrality "<<cent0<<" "<<cent1<<endl; int nevents = tree->GetEntries(); cout<<"nevents "<<nevents<<endl; // for(int iev=0; iev<2000000; iev++){ float maxqcut[CDET][NHAR] = {{0}}; for(int ihar=0; ihar<NHAR; ihar++){ for(int idet=0; idet<CDET; idet++){ maxqcut[idet][ihar] = 0; }} for(int iev=0; iev<nevents; iev++){ tree->GetEntry(iev); if(iev%1000000==0) cout<<iev<<endl; if(centrality>=cent1 || centrality<cent0) continue; hcent->Fill(centrality); for(int idet = 0; idet<RDET; idet++){ for(int ihar=0; ihar<NHAR; ihar++){ Trk_Q[idet][ihar] = trk_Q[idet][ihar]; Trk_Psi[idet][ihar] = trk_Psi[idet][ihar]; } } for(int idet = 0; idet<CDET; idet++){ for(int ihar=0; ihar<NHAR; ihar++){ Cal_Q[idet][ihar] = cal_Q[idet][ihar]; Cal_Psi[idet][ihar] = cal_Psi[idet][ihar]; } } double dQ[] = {0,0,0,0,0,0,0}; double dPsi[] = {0,0,0,0,0,0,0}; for(int ih=0; ih<NHAR;ih++){ dQ[ih] = Cal_Q[0][ih] - Cal_Q[1][ih]; dPsi[ih] = (Cal_Psi[0][ih] - Cal_Psi[1][ih]); dPsi[ih] = atan2(sin(dPsi[ih]), cos(dPsi[ih])); } for(int ihar=0; ihar<NHAR; ihar++){ for(int idet=0; idet<CDET; idet++){ if(Cal_Q[idet][ihar] >maxqcut[idet][ihar]) maxqcut[idet][ihar] = Cal_Q[idet][ihar]; hqFcal[idet][ihar] ->Fill(Cal_Q[idet][ihar]); } hQPsi[NA-1][ihar] ->Fill(dPsi[ihar],dQ[ihar]); } }//end of events TH1* htmp; float steps[] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.01}; float qcut[CDET][NHAR][NQ]; for(int idet=0; idet<CDET; idet++){ for(int ihar=0; ihar<NHAR; ihar++){ sprintf(name,"scale_%d_%d", idet, ihar); htmp = (TH1*)hqFcal[idet][ihar] ->Clone(name); htmp-> Scale(1.0/htmp->GetEntries()); htmp-> SetTitle(name); double sum = 0; int cnt = 0; for(int ib=1; ib<=htmp->GetNbinsX(); ib++){ sum+= htmp->GetBinContent(ib); if(sum>steps[cnt]) { qcut[idet][ihar][cnt] = htmp->GetBinCenter(ib); cnt++;} } qcut[idet][ihar][9] = maxqcut[idet][ihar] + 0.00001; cout<<idet<<" "<<ihar<<" "<<cnt<<" "<<sum<<endl; } } ofstream tout; sprintf(name,"cutInfo1_%d_%d.txt", cent0, cent1); tout.open(name); tout<<"cent "<<cent0<<"--"<<cent1<<endl; for(int idet=0; idet<CDET; idet++){ tout<<"IDET = "<<idet<<endl; for(int ihar=0; ihar<NHAR; ihar++){ for(int iq=0; iq<NQ; iq++){ if(iq==0) tout<<"{"<<qcut[idet][ihar][iq]<<", "; else if(iq<9) tout<<qcut[idet][ihar][iq]<<", "; else if(iq ==9) tout<<qcut[idet][ihar][iq]<<"}, "<<endl; } } } tout.close(); fileout->Write(); fileout->Close(); }
void LATcorr::Eval_LATcorr(int n){ if(effR->GetEntries()>0){ CalcLATcorr( ((TH2 *)beforeR),((TH2 *)afterR),LATcorrR,n); FitLATcorr(LATcorrR,LATcorrR_fit,n); } }
void printCalibStat(Int_t run, const char * fname, TTreeSRedirector * pcstream){ // // Dump the statistical information about all histograms in the calibration files // into the statistical tree, print on the screen (log files) as well // // // 1. Default dump for all histograms // Information to dump: // stat =Entries, Mean, MeanError, RMS, MaxBin // Branch naming convention: // <detName>_<hisName><statName> // // 2. Detector statistical information - to be implemented by expert // - First version implemented by MI // // TFile *fin = TFile::Open(fname); if (!fin) return; const Double_t kMaxHis=10000; TList * keyList = fin->GetListOfKeys(); Int_t nkeys=keyList->GetEntries(); Double_t *hisEntries = new Double_t[kMaxHis]; Double_t *hisMean = new Double_t[kMaxHis]; Double_t *hisMeanError = new Double_t[kMaxHis]; Double_t *hisRMS = new Double_t[kMaxHis]; Double_t *hisMaxBin = new Double_t[kMaxHis]; Int_t counter=0; if (pcstream) (*pcstream)<<"calibStatAll"<<"run="<<run; for (Int_t ikey=0; ikey<nkeys; ikey++){ TObject * object = fin->Get(keyList->At(ikey)->GetName()); if (!object) continue; if (object->InheritsFrom("TCollection")==0) continue; TSeqCollection *collection = (TSeqCollection*)object; Int_t nentries= collection->GetEntries(); for (Int_t ihis=0; ihis<nentries; ihis++){ TObject * ohis = collection->At(ihis); if (!ohis) continue; if (ohis->InheritsFrom("TH1")==0) continue; TH1* phis = (TH1*)ohis; hisEntries[counter]=phis->GetEntries(); Int_t idim=1; if (ohis->InheritsFrom("TH2")) idim=2; if (ohis->InheritsFrom("TH3")) idim=3; hisMean[counter]=phis->GetMean(idim); hisMeanError[counter]=phis->GetMeanError(idim); hisRMS[counter]=phis->GetRMS(idim); hisMaxBin[counter]=phis->GetBinCenter(phis->GetMaximumBin()); if (pcstream) (*pcstream)<<"calibStatAll"<< Form("%s_%sEntries=",keyList->At(ikey)->GetName(), phis->GetName())<<hisEntries[counter]<< Form("%s_%sMean=",keyList->At(ikey)->GetName(), phis->GetName())<<hisMean[counter]<< Form("%s_%sMeanError=",keyList->At(ikey)->GetName(), phis->GetName())<<hisMeanError[counter]<< Form("%s_%sRMS=",keyList->At(ikey)->GetName(), phis->GetName())<<hisRMS[counter]<< Form("%s_%sMaxBin=",keyList->At(ikey)->GetName(), phis->GetName())<<hisMaxBin[counter]; //printf("Histo:\t%s_%s\t%f\t%d\n",keyList->At(ikey)->GetName(), phis->GetName(), hisEntries[counter],idim); counter++; } delete object; } // // Expert dump example (MI first iteration): // // 0.) TOF dump // Int_t tofEvents=0; Int_t tofTracks=0; TList * TOFCalib = (TList*)fin->Get("TOFHistos"); if (TOFCalib) { TH1 *histoEvents = (TH1*)TOFCalib->FindObject("hHistoVertexTimestamp"); TH1 *histoTracks = (TH1*)TOFCalib->FindObject("hHistoDeltatTimestamp"); if (histoEvents && histoTracks){ tofEvents = TMath::Nint(histoEvents->GetEntries()); tofTracks = TMath::Nint(histoTracks->GetEntries()); } delete TOFCalib; } printf("Monalisa TOFevents\t%d\n",tofEvents); if (pcstream) (*pcstream)<<"calibStatAll"<<"TOFevents="<<tofEvents; printf("Monalisa TOFtracks\t%d\n",tofTracks); if (pcstream) (*pcstream)<<"calibStatAll"<<"TOFtracks="<<tofTracks; // // 1.) TPC dump - usefull events/tracks for the calibration // Int_t tpcEvents=0; Int_t tpcTracks=0; TObject* obj = dynamic_cast<TObject*>(fin->Get("TPCCalib")); TObjArray* array = dynamic_cast<TObjArray*>(obj); TDirectory* dir = dynamic_cast<TDirectory*>(obj); AliTPCcalibTime * calibTime = NULL; if (dir) { calibTime = dynamic_cast<AliTPCcalibTime*>(dir->Get("calibTime")); } else if (array){ calibTime = (AliTPCcalibTime *)array->FindObject("calibTime"); } if (calibTime) { tpcEvents = TMath::Nint(calibTime->GetTPCVertexHisto(0)->GetEntries()); tpcTracks = TMath::Nint(calibTime->GetResHistoTPCITS(0)->GetEntries()); } printf("Monalisa TPCevents\t%d\n",tpcEvents); if (pcstream) (*pcstream)<<"calibStatAll"<<"TPCevents="<<tpcEvents; printf("Monalisa TPCtracks\t%d\n",tpcTracks); if (pcstream) (*pcstream)<<"calibStatAll"<<"TPCtracks="<<tpcTracks; // // 2. TRD dump // Int_t trdEvents=0; Int_t trdTracks=0; TList * TRDCalib = (TList*)fin->Get("TRDCalib"); if (TRDCalib) { TH1 *histoEvents = (TH1*)TRDCalib->FindObject("NEventsInput_AliTRDCalibTask"); TH1 *histoTracks = (TH1*)TRDCalib->FindObject("AbsoluteGain_AliTRDCalibTask"); if (histoEvents && histoTracks){ trdEvents= TMath::Nint(histoEvents->GetEntries()); trdTracks= TMath::Nint(histoTracks->GetEntries()); } delete TRDCalib; } printf("Monalisa TRDevents\t%d\n",trdEvents); if (pcstream) (*pcstream)<<"calibStatAll"<<"TRDevents="<<trdEvents; printf("Monalisa TRDtracks\t%d\n",trdTracks); if (pcstream) (*pcstream)<<"calibStatAll"<<"TRDtracks="<<trdTracks; // // 3. T0 dump // Int_t T0Events=0; TList * T0Calib = (TList*)fin->Get("T0Calib"); if (T0Calib) { TH1 *histoEvents = (TH1*) T0Calib->FindObject("fTzeroORAplusORC"); if (histoEvents){ T0Events= TMath::Nint(histoEvents->GetEntries()); } delete T0Calib; } printf("Monalisa T0events\t%d\n",T0Events); if (pcstream) (*pcstream)<<"calibStatAll"<<"T0events="<<T0Events; // // 4. Mean vertex - dump // Not present in CPass1 /* Int_t meanVertexEvents=0; TList * meanVertexCalib = (TList*)fin->Get("MeanVertex"); if (meanVertexCalib) { TH1 *histoEvents = (TH1*) meanVertexCalib->FindObject("hTRKVertexX"); if (histoEvents){ meanVertexEvents = TMath::Nint(histoEvents->GetEntries()); } delete meanVertexCalib; } printf("Monalisa MeanVertexevents\t%d\n",meanVertexEvents); if (pcstream) (*pcstream)<<"calibStatAll"<<"MeanVertexevents="<<meanVertexEvents; */ // // 5. SDD dump // Int_t sddEvents=0; Int_t sddTracks=0; TList * SDDCalib = (TList*)fin->Get("clistSDDCalib"); if (SDDCalib) { TH1 *histoEvents = (TH1*) SDDCalib->FindObject("hNEvents"); if (histoEvents ){ sddEvents = TMath::Nint(histoEvents->GetBinContent(4)); sddTracks = TMath::Nint(histoEvents->GetBinContent(5)); } delete SDDCalib; } printf("Monalisa SDDevents\t%d\n",sddEvents); if (pcstream) (*pcstream)<<"calibStatAll"<<"SDDevents="<<sddEvents; printf("Monalisa SDDtracks\t%d\n",sddTracks); if (pcstream) (*pcstream)<<"calibStatAll"<<"SDDtracks="<<sddTracks; // // 6. AD dump // Int_t adEvents=0; TDirectory *adDir = (TDirectory*)fin->Get("ADCalib"); if (adDir) { TList *adList = (TList*) adDir->Get("ADCalibListHist"); if (adList) { TH2* adHistInt0 = (TH2*) adList->FindObject("hCh00_bc10_int0"); if (adHistInt0) adEvents += TMath::Nint(adHistInt0->GetEntries()); TH2* adHistInt1 = (TH2*) adList->FindObject("hCh00_bc10_int1"); if (adHistInt1) adEvents += TMath::Nint(adHistInt1->GetEntries()); delete adList; } } printf("Monalisa ADevents\t%d\n",adEvents); if (pcstream) (*pcstream)<<"calibStatAll"<<"ADevents="<<adEvents; // if (pcstream) (*pcstream)<<"calibStatAll"<<"\n"; delete fin; }
void correlation_plots2(bool rwt = true, TString catName = "e3je2t"){ int numhists = 0; // jet and tag cut for each category TString jettagcut = ""; if (catName == "ge4je2t"){ jettagcut = "numJets>3 && numTaggedJets==2"; numhists = 7; } else if(catName == "e3je2t"){ jettagcut = "numJets==3 && numTaggedJets==2"; numhists = 5; } else std::cout << "Error, wrong category name" << std::endl; //IN GLOBAL SCOPE // const int numhists = 5; // 5; const int numprofiles = pow(numhists,2); TProfile** profiles_Data = new TProfile * [numprofiles]; TProfile** profiles_MC = new TProfile * [numprofiles]; //IN MAIN FUNCTION char** histnames = new char * [numhists]; char** histXaxis = new char * [numhists]; int* histbins = new int[numhists]; double* histmin = new double[numhists]; double* histmax = new double[numhists]; if(catName == "e3je2t"){ histnames[0] = (char*) "sum_pt"; histXaxis[0] = (char*) "p_{T}(l, jets)"; histbins[0] = 13; histmin[0] = 150; histmax[0] = 930; histnames[1] = (char*) "min_dr_jets"; histXaxis[1] = (char*) "minimum #DeltaR(j, j)"; histbins[1] = 12; histmin[1] = 0.5; histmax[1] = 3.5; histnames[2] = (char*) "avg_btag_disc_non_btags"; histXaxis[2] = (char*) "#mu^{CSV}(non b-tags)"; histbins[2] = 10; histmin[2] = 0.0; histmax[2] = 0.68; histnames[3] = (char*) "avg_btag_disc_btags"; histXaxis[3] = (char*) "#mu^{CSV}"; histbins[3] = 10; histmin[3] = 0.7; histmax[3] = 1; histnames[4] = (char*) "BDTG_e3je2t"; histXaxis[4] = (char*) "BDT output"; histbins[4] = 10; histmin[4] = -1.; histmax[4] = 1.; } else if(catName == "ge4je2t"){ histnames[0] = (char*) "sum_pt"; histXaxis[0] = (char*) "p_{T}(l, jets)"; histbins[0] = 15; histmin[0] = 200; histmax[0] = 1400; histnames[1] = (char*) "min_dr_jets"; histXaxis[1] = (char*) "minimum #DeltaR(j, j)"; histbins[1] = 11; histmin[1] = 0.5; histmax[1] = 2.7; histnames[2] = (char*) "avg_btag_disc_non_btags"; histXaxis[2] = (char*) "#mu^{CSV}(non b-tags)"; histbins[2] = 11; histmin[2] = 0.0; histmax[2] = 0.605; histnames[3] = (char*) "higgsLike_dijet_mass"; histXaxis[3] = (char*) "higgsLike dijet mass"; histbins[3] = 17; histmin[3] = 34; histmax[3] = 255; histnames[4] = (char*) "higgsLike_dijet_mass2"; histXaxis[4] = (char*) "higgsLike dijet mass2"; histbins[4] = 17; histmin[4] = 30; histmax[4] = 370; histnames[5] = (char*) "numJets"; histXaxis[5] = (char*) "N_{jets}"; histbins[5] = 5; histmin[5] = 4; histmax[5] = 9; histnames[6] = (char*) "BDTG_ge4je2t"; histXaxis[6] = (char*) "BDT output"; histbins[6] = 12; histmin[6] = -0.95; histmax[6] = 0.85; } else std::cout << "Error2, wrong category name" << std::endl; //// TString cuts = "(oppositeLepCharge == 1) && (dR_leplep > 0.2) && (mass_leplep > 12) && isCleanEvent && PassZmask==1 && "; cuts += jettagcut; //// sample info TString htitle[21] = {"_singlet_s","_singlet_tW","_singlet_t","_singletbar_s","_singletbar_tW","_singletbar_t","_ttbarW","_ttbarZ","_ttbar_cc","_ttbar_bb","_ttbar_b","_ttbar","_wjets","_zjets","_zjets_lowmass","_ww","_wz","_zz","_MuEG","_DoubleElectron","_DoubleMu",}; // Float_t lumi = 19450; //////// //SKIPPING HISTOGRAM INITIALIZATION FOR OTHER 49 VARIABLES (USE ABOVE THREE EXAMPLES FOR YOUR USE) //////// TDirectory *currentDir = gDirectory; for (int i = 0; i < numhists; i++){ std::cout << "-->Figuring out binning for " << histnames[i] << std::endl; //Set the binning on the x-axis by looking at the data and combining bins (if necessary) to make sure there are no poorly populated bins //Define poorly populated arbitrarily as N < 100 currentDir->cd(); //This is because the "Draw" command only finds TString histName = Form("tempData_%s",histnames[i]); TH1 * tempHist = new TH1D(histName,"",histbins[i],histmin[i],histmax[i]); //Only look at data for (int isam=18; isam<21; isam++){ TString sample = htitle[isam]; TString fileName = "/afs/crc.nd.edu/user/w/wluo1/LHCP_2013/CMSSW_5_3_8_patch1/src/BEAN/DrawPlots/bin/treeFiles/dilSummaryTrees" +sample + "_2012_53x_July5th_all.root"; std::cout << " -->Including " << fileName << std::endl; TFile * tmpfile = new TFile(fileName); TTree * tmpTree = (TTree*)tmpfile->Get("summaryTree"); currentDir->cd(); //This is because the "Draw" command only finds TString selection = "(" + cuts + "&&"; if (isam == 18) selection+= "MuonEle && isMuEGTriggerPass"; else if (isam == 19) selection += "TwoEle && isDoubleElectronTriggerPass"; else if (isam == 20) selection += "TwoMuon && isDoubleMuTriggerPass"; selection += ")"; TString var = string(histnames[i])+">>+"+histName ; tmpTree->Draw(var, selection, "goff"); tmpfile->Close(); delete tmpfile; } std::cout << "tempHist name = " << tempHist->GetName() << std::endl; std::cout << "tempHist: Entries = " << tempHist->GetEntries() << ", Integral = " << tempHist->Integral() << std::endl; double threshold = (tempHist->Integral())/20; //Now, look through the bins of the histograms, combining when necessary int nBinsUsed = 0; double *xBins = new double[histbins[i]+1]; xBins[0] = histmin[i]; //First bin always starts at minimum double binSum = 0; for (int iBin = 1; iBin <= histbins[i]; ++iBin) { binSum += tempHist->GetBinContent(iBin); std::cout << "binSum = " << binSum << ", iBin = " << iBin << std::endl; if (binSum >= threshold) { std::cout << "Setting bin edge!" << std::endl; ++nBinsUsed; xBins[nBinsUsed] = tempHist->GetBinLowEdge(iBin+1); binSum = 0.; } } //Now check: if binSum > 0, that means the last bin was too small to be a bin //by itself. If so, we need to make sure it's combined with the bin on it's left by setting the bin edge to the histogram max if (binSum > 0) { xBins[nBinsUsed] = tempHist->GetBinLowEdge(histbins[i]+1); } std::cout << " -->Proposed binning: " << histbins[i] << ", " << histmin[i] << ", " << histmax[i] << std::endl; std::cout << " -->Using " << nBinsUsed << " bins: "; for (int iBin = 0; iBin < nBinsUsed; ++iBin) std::cout << xBins[iBin] << ", "; std::cout << xBins[nBinsUsed] << std::endl; for (int j = 0; j < numhists; j++) { currentDir->cd(); //This is because the "Draw" command only finds profiles_Data[numhists*i+j] = new TProfile(Form("profiles_Data_%s_%s",histnames[i],histnames[j]),"",nBinsUsed,xBins); profiles_Data[numhists*i+j]->Sumw2(); profiles_Data[numhists*i+j]->SetLineWidth(2); profiles_MC[numhists*i+j] = new TProfile(Form("profiles_MC_%s_%s",histnames[i],histnames[j]),"",nBinsUsed,xBins); profiles_MC[numhists*i+j]->Sumw2(); profiles_MC[numhists*i+j]->SetLineWidth(2); } delete[] xBins; } // loop over samples for (int isam=0; isam<21; isam++){ /// get the tree file for each sample TString sample = htitle[isam]; TString fileName = "/afs/crc.nd.edu/user/w/wluo1/LHCP_2013/CMSSW_5_3_8_patch1/src/BEAN/DrawPlots/bin/treeFiles/dilSummaryTrees" +sample + "_2012_53x_July5th_all.root"; std::cout << "-->start processing sample " << fileName << std::endl; TFile * tmpfile = new TFile(fileName); TTree * tmpTree = (TTree*)tmpfile->Get("summaryTree"); TString weight = "(19450*Xsec/nGen)*weight*topPtWgt*lepTotalSF*triggerSF*csvWgtlf*csvWgthf*"; ///// before rwt if (rwt) weight = "(19450*Xsec/nGen)*weight*topPtWgt*lepTotalSF*triggerSF*csvWgtlf*csvWgthf*"; ///// after rwt TString lepCut = "((MuonEle && isMuEGTriggerPass) || (TwoEle && isDoubleElectronTriggerPass) || (TwoMuon && isDoubleMuTriggerPass))"; if (isam==18) lepCut = "(MuonEle && isMuEGTriggerPass)"; if (isam==19) lepCut = "(TwoEle && isDoubleElectronTriggerPass)"; if (isam==20) lepCut = "(TwoMuon && isDoubleMuTriggerPass)"; /// selection cut TString selection = weight; // selection += Form("%f*",lumi); //Adjust for sample normalization; selection += ("(" + cuts + "&&" + lepCut + ")"); if (isam>17) selection = ("(" + cuts + "&&" + lepCut + ")"); // no weights for data // std::cout << " -->selection is: " << selection << std::endl; ///// loop through variables for (int i = 0; i < numhists; i++){ for (int j = 0; j < numhists; j++){ TString proName = profiles_MC[numhists*i+j]->GetName(); if (isam >= 18) proName = profiles_Data[numhists*i+j]->GetName(); TString var = string(histnames[j]) + ":" + string(histnames[i])+">>+"+proName ; currentDir->cd(); //This is because the "Draw" command only finds tmpTree->Draw(var, selection, "goff"); } } tmpfile->Close(); delete tmpfile; } // end sample loop //Format the plots the way Robin does for (int i = 0; i < numhists; i++) { for (int j = 0; j < numhists; j++) { profiles_MC[numhists*i+j]->SetFillColor(2); profiles_MC[numhists*i+j]->SetLineColor(0); profiles_MC[numhists*i+j]->SetMarkerSize(0); profiles_MC[numhists*i+j]->SetFillStyle(3013); profiles_MC[numhists*i+j]->GetXaxis()->SetTitle(histXaxis[i]); profiles_MC[numhists*i+j]->GetYaxis()->SetTitle(histXaxis[j]); profiles_MC[numhists*i+j]->GetYaxis()->SetTitleOffset(1.3); double minval = 9999999.0; double maxval = -9999999.0; for(int ibin = 0; ibin < profiles_Data[numhists*i+j]->GetNbinsX(); ibin++){ if(profiles_Data[numhists*i+j]->GetBinContent(ibin+1) != 0.0){ if(profiles_Data[numhists*i+j]->GetBinContent(ibin+1)-profiles_Data[numhists*i+j]->GetBinError(ibin+1) < minval) minval = profiles_Data[numhists*i+j]->GetBinContent(ibin+1)-profiles_Data[numhists*i+j]->GetBinError(ibin+1); if(profiles_Data[numhists*i+j]->GetBinContent(ibin+1)+profiles_Data[numhists*i+j]->GetBinError(ibin+1) > maxval) maxval = profiles_Data[numhists*i+j]->GetBinContent(ibin+1)+profiles_Data[numhists*i+j]->GetBinError(ibin+1); } if(profiles_MC[numhists*i+j]->GetBinContent(ibin+1) != 0.0){ if(profiles_MC[numhists*i+j]->GetBinContent(ibin+1)-profiles_MC[numhists*i+j]->GetBinError(ibin+1) < minval) minval = profiles_MC[numhists*i+j]->GetBinContent(ibin+1)-profiles_MC[numhists*i+j]->GetBinError(ibin+1); if(profiles_MC[numhists*i+j]->GetBinContent(ibin+1)+profiles_MC[numhists*i+j]->GetBinError(ibin+1) > maxval) maxval = profiles_MC[numhists*i+j]->GetBinContent(ibin+1)+profiles_MC[numhists*i+j]->GetBinError(ibin+1); } } if(minval < 0) { profiles_MC[numhists*i+j]->SetMaximum(maxval + 0.4*fabs(maxval-1.1*minval)); profiles_MC[numhists*i+j]->SetMinimum(1.1*minval); } else { profiles_MC[numhists*i+j]->SetMaximum(maxval + 0.4*fabs(maxval-0.9*minval)); profiles_MC[numhists*i+j]->SetMinimum(0.9*minval); } } //end loop j } //end loop i //Save plots in output file TString outFileName = "corrPlots"; if (rwt) outFileName += "_rwt_"; outFileName += catName; outFileName += ".root"; TFile *outputFile = TFile::Open(outFileName,"RECREATE"); outputFile->cd(); for (int i = 0; i < numhists*numhists; ++i) { profiles_MC[i]->Write(); profiles_Data[i]->Write(); } outputFile->Close(); }
/** * This function fits TH2F slices with a selected fitType function (gaussian, lorentz, ...). */ TGraphErrors* fit2DProj(TString name, TString path, int minEntries, int rebinX, int rebinY, int fitType, TFile * outputFile, const TString & resonanceType, const double & xDisplace, const TString & append) { //Read the TH2 from file TFile *inputFile = new TFile(path); TH2 * histo = (TH2*) inputFile->Get(name); if( rebinX > 0 ) histo->RebinX(rebinX); if( rebinY > 0 ) histo->RebinY(rebinY); //Declare some variables TH1 * histoY; TString nameY; std::vector<double> Ftop; std::vector<double> Fwidth; std::vector<double> Fmass; std::vector<double> Etop; std::vector<double> Ewidth; std::vector<double> Emass; std::vector<double> Fchi2; std::vector<double> Xcenter; std::vector<double> Ex; TString fileOutName("fitCompare2"+name); fileOutName += append; fileOutName += ".root"; TFile *fileOut=new TFile(fileOutName,"RECREATE"); for (int i=1; i<=(histo->GetXaxis()->GetNbins());i++) { //Project on Y (set name and title) std::stringstream number; number << i; TString numberString(number.str()); nameY = name + "_" + numberString; // std::cout << "nameY " << nameY << std::endl; histoY = histo->ProjectionY(nameY, i, i); double xBin = histo->GetXaxis()->GetBinCenter(i); std::stringstream xBinString; xBinString << xBin; TString title("Projection of x = "); title += xBinString.str(); histoY->SetName(title); if (histoY->GetEntries() > minEntries) { //Make the dirty work! TF1 *fit; std::cout << "fitType = " << fitType << std::endl; if(fitType == 1) fit = gaussianFit(histoY, resonanceType); else if(fitType == 2) fit = lorentzianFit(histoY, resonanceType); else if(fitType == 3) fit = linLorentzianFit(histoY); else { std::cout<<"Wrong fit type: 1=gaussian, 2=lorentzian, 3=lorentzian+linear."<<std::endl; abort(); } double *par = fit->GetParameters(); double *err = fit->GetParErrors(); // Check the histogram alone TCanvas *canvas = new TCanvas(nameY+"alone", nameY+" alone"); histoY->Draw(); canvas->Write(); // Only for check TCanvas *c = new TCanvas(nameY, nameY); histoY->Draw(); fit->Draw("same"); fileOut->cd(); c->Write(); if( par[0] == par[0] ) { //Store the fit results Ftop.push_back(par[0]); Fwidth.push_back(fabs(par[1]));//sometimes the gaussian has negative width (checked with Rene Brun) Fmass.push_back(par[2]); Etop.push_back(err[0]); Ewidth.push_back(err[1]); Emass.push_back(err[2]); Fchi2.push_back(fit->GetChisquare()/fit->GetNDF()); double xx= histo->GetXaxis()->GetBinCenter(i); Xcenter.push_back(xx); double ex = 0; Ex.push_back(ex); } else { // Skip nan std::cout << "Skipping nan" << std::endl; Ftop.push_back(0); Fwidth.push_back(0); Fmass.push_back(0); Etop.push_back(1); Ewidth.push_back(1); Emass.push_back(1); Fchi2.push_back(100000); Xcenter.push_back(0); Ex.push_back(1); } } } fileOut->Close(); //Plots the fit results in TGraphs const int nn= Ftop.size(); double x[nn],ym[nn],e[nn],eym[nn]; double yw[nn],eyw[nn],yc[nn]; // std::cout << "number of bins = " << nn << std::endl; // std::cout << "Values:" << std::endl; for (int j=0;j<nn;j++){ // std::cout << "xCenter["<<j<<"] = " << Xcenter[j] << std::endl; x[j]=Xcenter[j]+xDisplace; // std::cout << "Fmass["<<j<<"] = " << Fmass[j] << std::endl; ym[j]=Fmass[j]; // std::cout << "Emass["<<j<<"] = " << Emass[j] << std::endl; eym[j]=Emass[j]; // std::cout << "Fwidth["<<j<<"] = " << Fwidth[j] << std::endl; yw[j]=Fwidth[j]; // std::cout << "Ewidth["<<j<<"] = " << Ewidth[j] << std::endl; eyw[j]=Ewidth[j]; // std::cout << "Fchi2["<<j<<"] = " << Fchi2[j] << std::endl; yc[j]=Fchi2[j]; e[j]=0; } TGraphErrors *grM = new TGraphErrors(nn,x,ym,e,eym); grM->SetTitle(name+"_M"); grM->SetName(name+"_M"); TGraphErrors *grW = new TGraphErrors(nn,x,yw,e,eyw); grW->SetTitle(name+"_W"); grW->SetName(name+"_W"); TGraphErrors *grC = new TGraphErrors(nn,x,yc,e,e); grC->SetTitle(name+"_chi2"); grC->SetName(name+"_chi2"); grM->SetMarkerColor(4); grM->SetMarkerStyle(20); grW->SetMarkerColor(4); grW->SetMarkerStyle(20); grC->SetMarkerColor(4); grC->SetMarkerStyle(20); //Draw and save the graphs outputFile->cd(); TCanvas * c1 = new TCanvas(name+"_W",name+"_W"); c1->cd(); grW->Draw("AP"); c1->Write(); TCanvas * c2 = new TCanvas(name+"_M",name+"_M"); c2->cd(); grM->Draw("AP"); c2->Write(); TCanvas * c3 = new TCanvas(name+"_C",name+"_C"); c3->cd(); grC->Draw("AP"); c3->Write(); return grM; }
int main(int argc, char** argv) { WTempForCombination3D input7; WTempForCombination3D input8; WTempForCombination3D input7tmp; WTempForCombination3D input8tmp; TH1* bkginsignal7 = 0; //for t-processes other than munub TH1* bkg7 = 0; // for non-t processes TH1* bkginsignal8 = 0; //for t-processes other than munub TH1* bkg8 = 0; // for non-t processes bool singleMatrix = false; bool is2Drecgen = false; bool do3D = false; int muRebin = 1; int eRebin = 1; double f0mu = 0; double flmu = 0; double fmu = 1.; double nwmu = -1.; std::vector<std::string> namings7; //electron channel namings7.push_back(string("die")); namings7.push_back(string("ehad")); namings7.push_back(string("etau")); namings7.push_back("mue"); std::vector<std::string> namings8; namings8.push_back(string("dimu")); namings8.push_back(string("muhad")); namings8.push_back(string("mutau")); namings8.push_back("mue"); TFile * file = 0; int iRandom = 0; for (int f = 1; f < argc; f++) { std::string arg_fth(*(argv + f)); if (iRandom == 0) cout << f << " ---- " << arg_fth << endl; if (arg_fth == "fzRef") { f++; std::string out(*(argv + f)); f0mu = atof(out.c_str()); } else if (arg_fth == "flRef") { f++; std::string out(*(argv + f)); flmu = atof(out.c_str()); } else if (arg_fth == "fRef") { f++; std::string out(*(argv + f)); fmu = atof(out.c_str()); } else if (arg_fth == "nwRef") { f++; std::string out(*(argv + f)); nwmu = atof(out.c_str()); } else if (arg_fth == "signal7") { f++; std::string out(*(argv + f)); if (iRandom == 0) cout << "signal7" << endl; file = new TFile(out.c_str(), "read"); bool muonfile = false; for (unsigned int i = 0; i < namings7.size(); i++) { int pos = string(file->GetName()).find(namings7[i].c_str()); muonfile = (pos >= 0 && pos < string(file->GetName()).size()); if (muonfile) { if (iRandom == 0) { cout << "I am in signal7 (electron) channel and I accept "; cout << file->GetName() << " as signal" << endl; } break; } } if (!do3D || (do3D && !muonfile)) { input7tmp.rest.signalIID.push_back(((TH2*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta2D"))->RebinY(eRebin)); if (iRandom == 0) cout << input7tmp.rest.signalIID.at(input7tmp.rest.signalIID.size() - 1)->GetName() << endl; if (iRandom == 0) cout << "signal2D integral 7: " << input7tmp.rest.signalIID.at(input7tmp.rest.signalIID.size() - 1)->Integral() << endl; } if (do3D && muonfile) { if (iRandom == 0) cout << " in 3D :-)" << endl; input7tmp.rest.signalIIID.push_back(((TH3D*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta3D"))->Rebin3D(1, eRebin, 1, "newname")); if (iRandom == 0) cout << input7tmp.rest.signalIIID.at(input7tmp.rest.signalIIID.size() - 1) << endl; } if (iRandom == 0) if (input7tmp.rest.signalIID.size()) cout << input7tmp.rest.signalIID.at(input7tmp.rest.signalIID.size() - 1)->GetNbinsY() << endl; if (bkginsignal7 == 0) bkginsignal7 = (((TH1*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta"))->Rebin(eRebin)); else bkginsignal7->Add(((TH1*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta"))->Rebin(eRebin)); } else if (arg_fth == "signal8") { f++; std::string out(*(argv + f)); if (iRandom == 0) cout << "signal8" << endl; file = new TFile(out.c_str(), "read"); bool muonfile = false; for (unsigned int i = 0; i < namings8.size(); i++) { int pos = string(file->GetName()).find(namings8[i].c_str()); muonfile = (pos >= 0 && pos < string(file->GetName()).size()); if (muonfile) { if (iRandom == 0) cout << "I am in signal8 (muon) channel and I accept "; if (iRandom == 0) cout << file->GetName() << " as signal" << endl; break; } } if (!do3D || (do3D && !muonfile)) { input8tmp.rest.signalIID.push_back(((TH2*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta2D"))->RebinY(muRebin)); if (iRandom == 0) { cout << input8tmp.rest.signalIID.at(input8tmp.rest.signalIID.size() - 1)->GetName() << endl; cout << "signal2D integral 8: " << input8tmp.rest.signalIID.at(input8tmp.rest.signalIID.size() - 1)->Integral() << endl; } } if (do3D && muonfile) { if (iRandom == 0) cout << " in 3D :-)" << endl; input8tmp.rest.signalIIID.push_back(((TH3D*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta3D"))->Rebin3D(1, muRebin, 1, "newname")); if (iRandom == 0) cout << input8tmp.rest.signalIIID.at(input8tmp.rest.signalIIID.size() - 1) << endl; } if (input8tmp.rest.signalIID.size()) if (iRandom == 0) cout << input8tmp.rest.signalIID.at(input8tmp.rest.signalIID.size() - 1)->GetNbinsY() << endl; if (bkginsignal8 == 0) bkginsignal8 = (((TH1*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta"))->Rebin(muRebin)); else bkginsignal8->Add(((TH1*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta"))->Rebin(muRebin)); } else if (arg_fth == "data7") { f++; std::string out(*(argv + f)); if (iRandom == 0) cout << "data 7" << endl; file = new TFile(out.c_str(), "read"); input7tmp.rest.data = ((TH1*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta"))->Rebin(eRebin); } else if (arg_fth == "data8") { f++; std::string out(*(argv + f)); if (iRandom == 0) cout << "data 8" << endl; file = new TFile(out.c_str(), "read"); input8tmp.rest.data = ((TH1*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta"))->Rebin(muRebin); } else if (arg_fth == "bkg7") { f++; std::string out(*(argv + f)); if (iRandom == 0) cout << "bkg 7" << endl; file = new TFile(out.c_str(), "read"); // if (bkg7 == NULL) { // cout << "here .." << endl; // bkg7 = ((TH1*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta"))->Rebin(1); // } else { // bkg7->Add(((TH1*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta"))->Rebin(1)); // } bool myQCD = (out.find("_QCD.root") > 0 && fabs(out.find("_QCD.root")) < out.size()); if (iRandom == 0) cout << file->GetName() << "\tmyQCD: " << myQCD << endl; TH1 * tmpQCD = 0; if (myQCD) { tmpQCD = ((TH1*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta"))->Rebin(eRebin); if (iRandom == 0) cout << "tmpQCD: " << tmpQCD << endl; tmpQCD->Scale(107.5 / tmpQCD->Integral()); if (iRandom == 0) cout << out << "\thas " << tmpQCD->GetEntries() << " entries but " << tmpQCD->Integral() << " integral" << endl; } if (bkg7 == NULL) { if (iRandom == 0) cout << "here .." << endl; if (myQCD) bkg7 = tmpQCD; else bkg7 = ((TH1*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta"))->Rebin(eRebin); } else { if (myQCD) bkg7->Add(tmpQCD); else bkg7->Add(((TH1*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta"))->Rebin(eRebin)); } } else if (arg_fth == "bkg8") { f++; std::string out(*(argv + f)); if (iRandom == 0) cout << "bkg 8" << endl; file = new TFile(out.c_str(), "read"); if (bkg8 == NULL) { if (iRandom == 0) cout << "here .." << endl; bkg8 = ((TH1*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta"))->Rebin(muRebin); } else { bkg8->Add(((TH1*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta"))->Rebin(muRebin)); } } else if (arg_fth == "wtemplate7") { f++; std::string out(*(argv + f)); if (iRandom == 0) cout << "w template 7" << endl; file = new TFile(out.c_str(), "read"); // input7tmp.Wtemplate = ((TH1*) file->Get("btag10")); // input7tmp.Wtemplate = ((TH1*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta")); input7tmp.Wtemplate = ((TH1*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta")); input7tmp.Wtemplate->Rebin(eRebin); } else if (arg_fth == "wtemplate8") { f++; std::string out(*(argv + f)); if (iRandom == 0) cout << "w template 8" << endl; file = new TFile(out.c_str(), "read"); input8tmp.Wtemplate = ((TH1*) file->Get("DefaultTrue_allW/DefaultTrue_allWcosTheta")); input8tmp.Wtemplate->Rebin(muRebin); } else if (arg_fth == "singleMatrix") { f++; if (iRandom == 0) cout << "singleMatrix" << endl; std::string out(*(argv + f)); if (out == "true") singleMatrix = true; } else if (arg_fth == "is2Drecgen") { f++; if (iRandom == 0) cout << "is2Drecgen" << endl; std::string out(*(argv + f)); if (out == "yes" || out == "Yes" || out == "Y" || out == "y" || out == "YES") is2Drecgen = true; } else if (arg_fth == "do3D") { f++; if (iRandom == 0) cout << "do3D" << endl; std::string out(*(argv + f)); if (out == "yes" || out == "Yes" || out == "Y" || out == "y" || out == "YES") do3D = true; } else if (arg_fth == "nPE") { f++; if (iRandom == 0) cout << "nPE" << endl; std::string out(*(argv + f)); iRandom = (int) atof(out.c_str()); } } #ifndef Syst if (iRandom == 0) { cout << "7: " << bkg7 << "\t" << input7tmp.rest.data << "\t" << input7tmp.Wtemplate << endl; cout << "8: " << bkg8 << "\t" << input8tmp.rest.data << "\t" << input8tmp.Wtemplate << endl; } input7tmp.Wtemplate->Sumw2(); input7tmp.Wtemplate->Scale((double) 1. / (double) input7tmp.Wtemplate->Integral()); input8tmp.Wtemplate->Sumw2(); input8tmp.Wtemplate->Scale((double) 1. / (double) input8tmp.Wtemplate->Integral()); if (iRandom != 0) { if (iRandom == 1) { cout << "------------------------------" << endl; cout << "I will randomize the histogram" << endl; cout << "PE Number is " << iRandom << endl; cout << "------------------------------" << endl; } if (is2Drecgen && !singleMatrix && do3D) { for (unsigned int i = 0; i < input7tmp.rest.signalIID.size(); i++) { input7.rest.signalIID.push_back((TH2*) MakeRandomHistogram(input7tmp.rest.signalIID[i], iRandom, 2)); } for (unsigned int i = 0; i < input7tmp.rest.signalIIID.size(); i++) { input7.rest.signalIIID.push_back((TH3*) MakeRandomHistogram(input7tmp.rest.signalIIID[i], iRandom, 3)); } for (unsigned int i = 0; i < input8tmp.rest.signalIID.size(); i++) { input8.rest.signalIID.push_back((TH2*) MakeRandomHistogram(input8tmp.rest.signalIID[i], iRandom, 2)); } for (unsigned int i = 0; i < input8tmp.rest.signalIIID.size(); i++) { input8.rest.signalIIID.push_back((TH3*) MakeRandomHistogram(input8tmp.rest.signalIIID[i], iRandom, 3)); } } } else { input7.rest.signalIID = input7tmp.rest.signalIID; input7.rest.signalIIID = input7tmp.rest.signalIIID; input8.rest.signalIID = input8tmp.rest.signalIID; input8.rest.signalIIID = input8tmp.rest.signalIIID; } input7.rest.data = input7tmp.rest.data; input8.rest.data = input8tmp.rest.data; input7.Wtemplate = input7tmp.Wtemplate; input8.Wtemplate = input8tmp.Wtemplate; double x[8] = {0.722384, 0.308293, 0, 0, 1., 1., 1., 1.}; double xerr[8] = {-1., -1., -1., -1., -1., -1., -1., -1.}; double correlation; if (is2Drecgen && !singleMatrix && do3D) { if (iRandom == 0) { cout << "In Bias fit: \n\tsize of 2D signal at 7 TeV is " << input7.rest.signalIID.size() << "\n\tsize of 3D signal at 7 TeV is " << input7.rest.signalIIID.size() << endl; cout << "In Bias fit: \n\tsize of 2D signal at 8 TeV is " << input8.rest.signalIID.size() << "\n\tsize of 3D signal at 8 TeV is " << input8.rest.signalIIID.size() << endl; } if (bkg7 != NULL && bkginsignal7 != NULL) { bkg7->Add(bkginsignal7); } else if (bkg7 == NULL && bkginsignal7 != NULL) { bkg7 = (TH1*) bkginsignal7->Clone("myBkg7"); } input7.rest.nonRWs = bkg7; if (bkg8 != NULL && bkginsignal8 != NULL) { bkg8->Add(bkginsignal8); } else if (bkg8 == NULL && bkginsignal8 != NULL) { bkg8 = (TH1*) bkginsignal8->Clone("myBkg8"); } input8.rest.nonRWs = bkg8; if (iRandom == 0) cout << "Here" << endl; std::pair<ROOT::Math::Functor, LucaLikelihood*> myLL = LucaLikelihood::getLucaLikelihoodForBias("LL", input7, input8, false); if (iRandom == 0) { cout << "before get minimum simple: " << endl; cout << "bkg bins 7: " << input7.rest.nonRWs->GetNbinsX() << endl; cout << "bkg bins 8: " << input8.rest.nonRWs->GetNbinsX() << endl; cout << "w bins 7: " << input7.Wtemplate->GetNbinsX() << endl; cout << "w bins 8: " << input8.Wtemplate->GetNbinsX() << endl; cout << "data bins 7: " << input7.rest.data->GetNbinsX() << endl; cout << "data bins 8: " << input8.rest.data->GetNbinsX() << endl; } GetMinimumLuca(myLL.first, x, xerr, correlation, true, f0mu, flmu, fmu, nwmu); delete myLL.second; } else { cout << "Not implemented yet!" << endl; } #endif #ifdef Syst cout << "7: " << bkg7 << "\t" << input7.rest.data << "\t" << input7.Wtemplate << endl; cout << "8: " << bkg8 << "\t" << input8.rest.data << "\t" << input8.Wtemplate << endl; input7.Wtemplate->Sumw2(); input7.Wtemplate->Scale((double) 1. / (double) input7.Wtemplate->Integral()); double x[5] = {0.7, 0.3, 1., 1., 1.,}; double xerr[5] = {-1., -1., -1., -1., -1.,}; double correlation; cout << "In Syst fit: \n\tsize of 2D signal at 7 TeV is " << input7.rest.signalIID.size() << "\n\tsize of 3D signal at 7 TeV is " << input7.rest.signalIIID.size() << endl; cout << "In Syst fit: \n\tsize of 2D signal at 8 TeV is " << input8.rest.signalIID.size() << "\n\tsize of 3D signal at 8 TeV is " << input8.rest.signalIIID.size() << endl; cout << "nbin signal 7: " << input7.rest.signalIID[0]->GetYaxis()->GetNbins() << endl; cout << "nbin signal 8: " << input8.rest.signalIID[0]->GetYaxis()->GetNbins() << endl; TH1* Signal1D7 = 0; TH1* Signal1D8 = 0; stringstream s; for (unsigned int p = 0; p < input7.rest.signalIID.size(); p++) { s.str(""); s << p << "7_pY"; if (Signal1D7 == 0) Signal1D7 = (TH1*) input7.rest.signalIID.at(p)->ProjectionY(s.str().c_str()); else Signal1D7->Add((TH1*) input7.rest.signalIID.at(p)->ProjectionY(s.str().c_str())); } s.str(""); for (unsigned int p = 0; p < input8.rest.signalIID.size(); p++) { s.str(""); s << p << "8_pY"; if (Signal1D8 == 0) Signal1D8 = (TH1*) input8.rest.signalIID.at(p)->ProjectionY(s.str().c_str()); else Signal1D8->Add((TH1*) input8.rest.signalIID.at(p)->ProjectionY(s.str().c_str())); } cout << "signal done" << endl; #ifndef IJES cout << "-- " << bkginsignal8->Integral() << endl; cout << "-- " << bkg8->Integral() << endl; if (bkginsignal8 != NULL) { if (bkg8 != NULL) { bkg8->Add(bkginsignal8); } else { bkg8 = bkginsignal8; } } #endif #ifdef IJES if (bkginsignal8 != NULL) // bkg->Add(bkginsignal8); Signal1D8->Add(bkginsignal8); #endif if (bkginsignal7 != NULL) // bkg->Add(bkginsignal7); Signal1D7->Add(bkginsignal7); InputForCombination1D IDin8; IDin8.name = "IDin8"; IDin8.data = input8.rest.data; IDin8.nonRWs = bkg8; IDin8.signalID = Signal1D8; WTempForCombination1D IDin7; IDin7.rest.name = "IDin7"; IDin7.rest.data = input7.rest.data; IDin7.rest.nonRWs = bkg7; IDin7.rest.signalID = Signal1D7; IDin7.Wtemplate = input7.Wtemplate; cout << "8TeV Info: \n\tnData: " << IDin8.data->Integral() << "\n\tnSignal: " << IDin8.signalID->Integral() << "\n\tnBkg: " << IDin8.nonRWs->Integral() << endl; cout << "7TeV Info: \n\tnData: " << IDin7.rest.data->Integral() << "\n\tnSignal: " << IDin7.rest.signalID->Integral() << "\n\tnBkg: " << IDin7.rest.nonRWs->Integral() << endl; std::pair<ROOT::Math::Functor, LucaLikelihood*> myLL = LucaLikelihood::getLucaLikelihoodForSyst("LL", IDin7, IDin8, true); GetMinimumSystCombined(myLL.first, x, xerr, correlation, true); cout << "----- systematics: " << endl; double f00 = 0.713279; double fl0 = 0.293116; double f0n = 0.707345; double fln = 0.296289; cout << "\nDelF0 = " << x[0] - f0n << " +/- " << xerr[0]* 0.114023 / 0.0217699 << endl; cout << "\nDelFL = " << x[1] - fln << " +/- " << xerr[1]* 0.0687606 / 0.0207235 << endl; cout << "\nF0 = " << x[0] - f0n + f00 << " +/- " << xerr[0]* 0.114023 / 0.0217699 << endl; cout << "\nFL = " << x[1] - fln + fl0 << " +/- " << xerr[1]* 0.0687606 / 0.0207235 << endl; delete myLL.second; #endif return 0; }
//______________________________________________________________________________ void CheckTime(const Char_t* loc) { // Check time. Char_t t[256]; // number of runs Int_t nRuns = gFiles->GetSize(); // create arrays const Int_t nCh = 352; Double_t** pedPos = new Double_t*[nCh]; Double_t* runNumbersD = new Double_t[nRuns]; for (Int_t i = 0; i < nCh; i++) pedPos[i] = new Double_t[nRuns]; // open the output files TFile* fROOTout = new TFile("/tmp/tagger_time.root", "RECREATE"); // create directories for (Int_t i = 0; i < nCh; i++) { sprintf(t, "%03d", i); fROOTout->mkdir(t); } TF1* func = new TF1("func", "gaus(0)+pol1(3)", -1000 , 1000); // loop over runs for (Int_t i = 0; i < nRuns; i++) { // get the file TFile* f = (TFile*) gFiles->At(i); // extract run number Int_t runNumber; sprintf(t, "%s/ARHistograms_CB_%%d.root", loc); sscanf(f->GetName(), t, &runNumber); runNumbersD[i] = (Double_t)runNumber; printf("Processing run %d (%d/%d)\n", runNumber, i+1, nRuns); fROOTout->cd(); TH2* h2 = (TH2*) f->Get("CaLib_Tagger_Time"); // loop over channels for (Int_t j = 0; j < nCh; j++) { // load histogram sprintf(t, "%03d", j); fROOTout->cd(t); sprintf(t, "%d_%d", i, j); TH1* h = h2->ProjectionX(t, j+1, j+1); h->Rebin(2); sprintf(t, "Run_%d", runNumber); TCanvas* c = new TCanvas(t, t); TLine* tline = 0; // check entries if (h->GetEntries()) { // fit gaussian to peak Double_t maxPos = h->GetXaxis()->GetBinCenter(h->GetMaximumBin()); func->SetParameters(1, maxPos, 0.5, 1, 0.1); func->SetRange(maxPos - 2, maxPos + 2); func->SetParLimits(0, 0, 1000); for (Int_t k = 0; k < 10; k++) if (!h->Fit(func, "RBQ")) break; // save position in file and memory maxPos = func->GetParameter(1); pedPos[j][i] = maxPos; h->GetXaxis()->SetRangeUser(maxPos - 10, maxPos + 10); h->Draw(); tline = new TLine(maxPos, 0, maxPos, 10000); tline->SetLineColor(kRed); tline->SetLineWidth(2); tline->Draw(); } else { h->Draw(); } c->Write(c->GetName(), TObject::kOverwrite); delete h; delete c; if (tline) delete tline; } delete h2; } // create pedestal evolution graphs fROOTout->cd(); // loop over channels for (Int_t j = 0; j < nCh; j++) { printf("Creating time graph for channel %d\n", j); TGraph* g = new TGraph(nRuns, runNumbersD, pedPos[j]); sprintf(t, "Overview_%03d", j); g->SetName(t); g->SetTitle(t); //g->GetYaxis()->SetRangeUser(1200, 1300); g->Write(g->GetName(), TObject::kOverwrite); delete g; } printf("Saving output file\n"); delete fROOTout; // cleanup for (Int_t i = 0; i < nCh; i++) delete [] pedPos[i]; delete [] pedPos; delete [] runNumbersD; }
//______________________________________________________________________________ void CalibrateFit(Int_t nPar, Double_t time_limit, Double_t bad_frac) { // Calibrate using iterative fitting. const Double_t convergence_factor = 0.05; // iterate calibrations for (Int_t i = 0; i >= 0; i++) { // create new histogram TH2* h = CreateHisto("fit_histo", nPar, gOff); // user info printf("Calibration iteration %d\n", i+1); // loop over elements Int_t n = 0; Int_t outside_n = 0; for (Int_t j = 0; j < nPar; j++) { // create projection TH1* hProj = (TH1*) h->ProjectionX(TString::Format("Proj_%d", j).Data(), j+1, j+1, "e"); // check for filled histograms if (hProj->GetEntries()) { // create fitting function TF1* func = new TF1(TString::Format("Func_%d", j).Data(), "gaus", -5, 5); func->SetParameter(0, 1); func->SetParameter(1, hProj->GetXaxis()->GetBinCenter(hProj->GetMaximumBin())); func->SetParameter(2, 0.1); // fit histogram hProj->GetXaxis()->SetRangeUser(-5, 5); hProj->Fit(func, "0Q"); Double_t mean = func->GetParameter(1); // update offset gOff[j] = gOff[j] + convergence_factor * mean / gGain[j]; n++; if (TMath::Abs(mean) > time_limit) outside_n++; // clean-up delete func; } // clean-up delete hProj; } // clean-up delete h; // user info Double_t outside_frac = (Double_t)outside_n/(Double_t)n; printf("Element outside limits: %.1f%%\n", outside_frac*100.); if (outside_frac < bad_frac) break; } }
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 glauberCut(int from=0, int to=100){ char name[200]; TChain* t = new TChain("t"); char dfilelist[100]; sprintf(dfilelist,"filelist.txt"); ifstream lis(dfilelist); int cnt=0; int dnt=0; while(!lis.eof()) { string filename; lis >> filename; if(cnt>=from&&cnt<to) { cout << filename << endl; if(!filename.empty()) t->Add(filename.c_str()); dnt++; } cnt++; } double b; int ncoll; int npart,npartproj,nparttarg; int nHitBbc_n, nHitBbc_s, BBCTrig; int Centbin; double qBBC_n, qBBC_s, pTrigBBC; double vertex, ecc_std,ecc_rp, ecc_part,ecc_partr,r_ollitra,r_geo,r_arith,r_ollitrar,r_geor,r_arithr,e4; double e_gl[ETOT],ang_gl[ETOT]; double re_gl[ETOT],rang_gl[ETOT]; double pe_gl[ETOT],pang_gl[ETOT]; double pre_gl[ETOT],prang_gl[ETOT]; t->SetBranchAddress("b", &b ); t->SetBranchAddress("Centbin", &Centbin); t->SetBranchAddress("ncoll", &ncoll); t->SetBranchAddress("npart", &npart); t->SetBranchAddress("npartproj", &npartproj); t->SetBranchAddress("nparttarg", &nparttarg); /* t->SetBranchAddress("ecc_std", &ecc_std ); t->SetBranchAddress("ecc_rp", &ecc_rp ); t->SetBranchAddress("ecc_part", &ecc_part ); t->SetBranchAddress("e_gl", e_gl ); //r2 t->SetBranchAddress("ang_gl", ang_gl ); t->SetBranchAddress("pe_gl", pe_gl ); //no only Conside Npart t->SetBranchAddress("pang_gl", pang_gl); */ // t->SetBranchAddress("re_gl", re_gl ); //r3,2,3,4,5,6 // t->SetBranchAddress("rang_gl", rang_gl); t->SetBranchAddress("pre_gl", pre_gl); // t->SetBranchAddress("prang_gl", prang_gl); //t->SetBranchAddress("nux", &nux); //t->SetBranchAddress("nuy", &nuy); //t->SetBranchAddress("st_part", &st_part); int nevents = t->GetEntries(); cout<<"will run "<<nevents/1000000<<"M events"<<endl; TH1D* hecc [NCENT][NHAR]; TH1D* hcent[NCENT]; for(int icent=0; icent<NCENT; icent++){ sprintf(name,"hcent_%.2d", icent); hcent[icent] = new TH1D(name, name ,NCENT, 0-0.5, NCENT-0.5); } for(int icent=0; icent<NCENT; icent++){ for(int ihar=0; ihar<NHAR; ihar++){ sprintf(name, "hecc_ic%.2d_ih%d", icent, ihar); hecc[icent][ihar] = new TH1D(name, name, 100000, 0, 1); } } for(int iev=0; iev<nevents; iev++){ t->GetEntry(iev); if(iev%1000000==0) cout<<iev<<endl; if(Centbin!=0) continue; hcent[Centbin] ->Fill(Centbin); for(int ihar=0; ihar<NHAR; ihar++){ hecc[Centbin][ihar] ->Fill(pre_gl[ihar]); } } //end of events float steps[NSTEP] = {0}; float Ecut[NCENT][NHAR][NSTEP]; for(int is=0; is<NSTEP-1; is++){ steps[is] = (is+1)*1.0/NSTEP; } steps[NSTEP-1] = 1.01; for(int icent=0; icent<NCENT; icent++){ for(int ihar=0; ihar<NHAR; ihar++){ TH1* htmp; sprintf(name,"scale_%d_%d", icent, ihar); htmp = (TH1*)hecc[icent][ihar] ->Clone(name); htmp-> Scale(1.0/htmp->GetEntries()); double sum = 0; int cnt = 0; for(int ib=1; ib<=htmp->GetNbinsX(); ib++){ sum+= htmp->GetBinContent(ib); if(sum>steps[cnt]) { Ecut[icent][ihar][cnt] = htmp->GetBinCenter(ib); cnt++;} } Ecut[icent][ihar][NSTEP-1] = 1.01; cout<<icent<<" "<<ihar<<" "<<cnt<<" "<<sum<<endl; } } ofstream tout; sprintf(name,"ECut_cent0.txt"); tout.open(name); for(int cent=0; cent<NCENT; cent++){ tout<<"centb "<<cent<<endl; for(int ihar=0; ihar<NHAR; ihar++){ for(int iq=0; iq<NSTEP; iq++){ if(iq==0) tout<<"{"<<Ecut[cent][ihar][iq]<<", "; else if(iq<NSTEP-1) tout<<Ecut[cent][ihar][iq]<<", "; else if(iq ==NSTEP-1) tout<<Ecut[cent][ihar][iq]<<"}, "<<endl; } } } tout.close(); TFile* fout = new TFile("glauber_cut_cent0.root","recreate"); for(int icent=0; icent<NCENT; icent++){ for(int ihar=0; ihar<NHAR; ihar++){ hecc[icent][ihar] ->Write(); } } for(int icent=0; icent<NCENT; icent++){ hcent[icent] ->Write(); } fout->Close(); }