void plot_mc(string name="g", double q2=1.9, Int_t n=0) { // SetAtlasStyle(); TGraphErrors *p; TString nn; nn.Form("ave_%s_vs_x_for_Q2=%g",name.c_str(),q2); gDirectory->GetObject(nn,p); // p->Print(); Double_t ratsize = 0.0; TCanvas *c = new TCanvas("PDF","pdf",600,600); TPad *pad1 = new TPad("pad1","pad1",0.,ratsize,1.,1.); pad1->SetLogx(); pad1->Draw(); pad1->cd(); p->GetXaxis()->Set(101,0.0001,1.); p->SetFillColor(kRed-2); p->SetFillStyle(3001); p->SetLineWidth(1); p->SetLineColor(kRed); p->GetYaxis()->SetTitle(name.c_str()); p->GetYaxis()->SetTitleSize(0.06); p->GetYaxis()->SetTitleOffset(1.); p->GetXaxis()->Set(101,0.0001,1.); p->Draw("ALE3"); Double_t av = 0; Double_t av2 = 0; for (Int_t i = 1; i<n+1 ; i++) { nn.Form("%s_vs_x_for_Q^{2}=%g_%i",name.c_str(),q2,i); TGraph *pp = NULL; gDirectory->GetObject(nn,pp); if (pp != NULL) { pp->SetLineColor(kGreen); pp->Draw("L"); av += pp->GetY()[0]; av2 += pp->GetY()[0]*pp->GetY()[0]; cout << i << " "<<pp->GetY()[0] << endl; } } av /= n; av2 = sqrt(av2/n - av*av); // cout << n << " "<<av << " "<< av2<<endl; p->Draw("E3C"); }
void plotTanb(const char* filename, const char* channel, bool draw_injected_=false, double min_=0., double max_=60., bool log_=false, std::string dataset_="CMS Preliminary, H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV, 19.8 fb^{-1} at 8 TeV", std::string xaxis_="m_{A} [GeV]", std::string yaxis_="#bf{tan#beta}") { TFile* file = TFile::Open(filename); // retrieve TGraphs from file TGraph* expected = (TGraph*)file->Get(std::string(channel).append("/expected").c_str()); TGraph* expected_low = (TGraph*)file->Get(std::string(channel).append("/expected_low").c_str()); TGraph* observed = (TGraph*)file->Get(std::string(channel).append("/observed").c_str()); TGraph* observed_low = (TGraph*)file->Get(std::string(channel).append("/observed_low").c_str()); TGraph* upperLEP = (TGraph*)file->Get(std::string(channel).append("/upperLEP").c_str()); TGraph* lowerLEP = (TGraph*)file->Get(std::string(channel).append("/lowerLEP").c_str()); TGraphAsymmErrors* innerBand = (TGraphAsymmErrors*)file->Get(std::string(channel).append("/innerBand").c_str()); TGraphAsymmErrors* innerBand_low = (TGraphAsymmErrors*)file->Get(std::string(channel).append("/innerBand_low").c_str()); TGraphAsymmErrors* outerBand = (TGraphAsymmErrors*)file->Get(std::string(channel).append("/outerBand").c_str()); TGraphAsymmErrors* outerBand_low = (TGraphAsymmErrors*)file->Get(std::string(channel).append("/outerBand_low").c_str()); TGraphAsymmErrors* plain = (TGraphAsymmErrors*)file->Get(std::string(channel).append("/plain").c_str()); TGraphAsymmErrors* plain_low = (TGraphAsymmErrors*)file->Get(std::string(channel).append("/plain_low").c_str()); // this is new for injected plot TGraph* injected = 0;; if(draw_injected_) {injected = (TGraph*)file->Get("injected/observed");} if(draw_injected_){ for( int i=0; i<expected->GetN(); i++){ double shift = injected->GetY()[i]-expected->GetY()[i]; innerBand->SetPoint(i, innerBand->GetX()[i], innerBand->GetY()[i]+shift); outerBand->SetPoint(i, outerBand->GetX()[i], outerBand->GetY()[i]+shift); } } // this functionality is not yet supported std::map<double, TGraphAsymmErrors*> higgsBands; // this functionality is not yet supported std::map<std::string, TGraph*> comparisons; // set up styles SetStyle(); // do the plotting TCanvas canv = TCanvas("canv", "Limits", 600, 600); // do the plotting plottingTanb(canv, plain, plain_low, innerBand, innerBand_low, outerBand, outerBand_low, expected, expected_low, observed, observed_low, lowerLEP, upperLEP, higgsBands, comparisons, xaxis_, yaxis_, injected, min_, max_, log_); /// setup the CMS Preliminary CMSPrelim(dataset_.c_str(), "", 0.145, 0.835); // write results to files canv.Print(std::string(channel).append("_tanb").append(".png").c_str()); canv.Print(std::string(channel).append("_tanb").append(".pdf").c_str()); canv.Print(std::string(channel).append("_tanb").append(".eps").c_str()); return; }
void BoundaryFinder::StoreDataFromGraph(const TGraph &gr) { Double_t *x = gr.GetX(); Double_t *y = gr.GetY(); ComputeCenter(gr); Double_t xr=0, yr=0; for (UInt_t i=0; i<gr.GetN(); i++) { xr = x[i]-fCenter.first; yr = y[i]-fCenter.second; point_t p = {::sqrt(xr*xr + yr*yr), i}; fSortedVals.insert(std::make_pair(::atan2(yr,xr),p)); } }
void BoundaryFinder::ComputeCenter(const TGraph& gr) { Double_t *x = gr.GetX(); Double_t *y = gr.GetY(); UInt_t n = gr.GetN(); Double_t sum_x = 0; Double_t sum_y = 0; for (UInt_t i=0; i<n; i++) { sum_x += x[i]; sum_y += y[i]; } fCenter.first = sum_x/n; fCenter.second = sum_y/n; }
//______________________________________________________________________________ void Draw(TFile* f, const char* gname, TLegend* l, Bool_t normalized) { if (!f) return; TGraph* g = static_cast<TGraph*>(f->Get(gname)); if (!g) return; if ( normalized ) { g = static_cast<TGraph*>(g->Clone()); for ( Int_t i = 0; i < g->GetN(); ++i ) { Double_t y = g->GetY()[i]; g->SetPoint(i,g->GetX()[i],y/NTOTALNUMBEROFPADS); } } g->Draw("lp"); g->GetXaxis()->SetNdivisions(505); g->GetXaxis()->SetNoExponent(); if (l) l->AddEntry(g,gname,"LP"); }
void oindree_min_signal(int start_run, int end_run) { const int num_ant = 48; const int num_phi = 16; //double pkpk[num_ant]; double pkpk[num_phi]; int max_index; int min_index; double max; double min; AnitaVersion::set(4); AnitaPol::AnitaPol_t pol = AnitaPol::kHorizontal; AnitaRing::AnitaRing_t ring = AnitaRing::kBottomRing; //for (int i = 0; i < num_ant; i++) //{ //pkpk[i] = 0.0; //} for (int i = 0; i < num_phi; i++) { pkpk[i] = 0.0; } TChain headChain("headTree"); for (int run_number = start_run; run_number <= end_run; run_number++) { headChain.Add(TString::Format("$ANITA_ROOT_DATA/run%d/timedHeadFile%d.root",run_number,run_number)); } TimedAnitaHeader *header = NULL; headChain.SetBranchAddress("header",&header); int header_num_entries = headChain.GetEntries(); cout << "number of entries in header anita-4 is " << header_num_entries << endl; TChain eventChain("eventTree"); for (int run_number = start_run; run_number <= end_run; run_number++) { eventChain.Add(TString::Format("$ANITA_ROOT_DATA/run%d/eventFile%d.root",run_number,run_number)); } RawAnitaEvent *event = NULL; eventChain.SetBranchAddress("event",&event); int event_num_entries = eventChain.GetEntries(); cout << "number of entries in event anita-4 is " << event_num_entries << endl; TChain prettyChain("prettyHkTree"); for (int run_number = start_run; run_number <= end_run; run_number++) { prettyChain.Add(TString::Format("$ANITA_ROOT_DATA/run%d/prettyHkFile%d.root",run_number,run_number)); } PrettyAnitaHk *hk = NULL; prettyChain.SetBranchAddress("hk",&hk); int hk_num_entries = prettyChain.GetEntries(); cout << "number of entries in prettyHk anita-4 is " << hk_num_entries << endl; UInt_t count=0; TH1D *hmin_signal = new TH1D("hmin_signal",";MinOverPhiSectors(pk-pk voltage in mV);Number of Events",100,0,1000); for(int ientry=0; ientry < header_num_entries; ientry=ientry+1000) { eventChain.GetEntry(ientry); headChain.GetEntry(ientry); prettyChain.GetEntry(ientry); //cout << "realTime is " << header->realTime << endl; //cout << " here " << endl; //This step produces a calibrated UsefulAnitaEvent UsefulAnitaEvent realEvent(event,WaveCalType::kDefault,hk); //cout << " after useful " << endl; //cout << realEvent.eventNumber << " " << header->eventNumber << endl; // cout << realEvent.gotCalibTemp << " " << realEvent.calibTemp << endl; count++; //initialize double min_pkpk = 0.0; //for (int j = 0; j < num_ant; j++) //{ //pkpk[j] = 0.0; //} for (int j = 0; j < num_phi; j++) { pkpk[j] = 0.0; } //for (int iant = 0; iant < num_ant; iant++) //{ //TGraph *gr = new TGraph(0); // gr = realEvent.getGraph(iant,pol); //pkpk[iant] = (gr->GetY()[TMath::LocMax(gr->GetN(),gr->GetY())]) - (gr->GetY()[TMath::LocMin(gr->GetN(),gr->GetY())]); //cout << pkpk[iant] << endl; //delete gr; //} //loop over antennas max_index = 0; min_index = 0; max = 0.0; min = 0.0; for (int iphi = 0; iphi < num_phi; iphi++) { max_index = 0; min_index = 0; max = 0.0; min = 0.0; TGraph *gr = new TGraph(0); gr = realEvent.getGraph(ring,iphi,pol); max_index = TMath::LocMax(gr->GetN(),gr->GetY()); min_index = TMath::LocMin(gr->GetN(),gr->GetY()); max = gr->GetY()[max_index]; min = gr->GetY()[min_index]; pkpk[iphi] = max - min; //cout << pkpk[iphi] << endl; //cout << max << " " << min << endl; //cout << max_index << " " << min_index << endl; delete gr; } // loop over phi sectors //min_pkpk = pkpk[TMath::LocMin(num_ant,pkpk)]; min_pkpk = pkpk[TMath::LocMin(num_phi,pkpk)]; //cout << "min pkpk is " << min_pkpk << endl; hmin_signal->Fill(min_pkpk); if (min_pkpk < 50) { cout << "min pkpk is " << min_pkpk << "run is " << header->run << "event number is " << header->eventNumber << endl; } } //loop over events ends cerr << endl; cout << "Processed " << count << " events.\n"; //just to check how a graph looks //TCanvas *c = new TCanvas("c","c",1000,800); //gr->Draw("alp"); //gr->GetXaxis()->SetTitle("Time (ns)"); //gr->GetYaxis()->SetTitle("Voltage (mV)"); //gr->SetTitle("Voltage-time waveform using UsefulAnitaEvent"); //c->SaveAs("gr.png"); //delete c; TCanvas *h = new TCanvas("h","h",1000,800); h->SetLogy(); hmin_signal->SetStats(0); hmin_signal->Draw(""); hmin_signal->SaveAs(Form("hmin_signal_pol%iring%i.root",pol,ring)); h->SaveAs(Form("min_signal_pol%iring%i.png",pol,ring)); h->SaveAs(Form("min_signal_pol%iring%i.root",pol,ring)); }//end of macro
// This must run with AnitaAnalysisFramework loaded void ALFASpectrum(int eventNumber) { int run = AnitaDataset::getRunContainingEventNumber(eventNumber); AnitaDataset * d = new AnitaDataset(run); d->getEvent(eventNumber); d->useful()->setAlfaFilterFlag(false); TGraph * alfaGraph = d->useful()->getGraph(AnitaRing::kTopRing, 4, AnitaPol::kHorizontal); // printf("%p\n", alfaGraph); AnalysisWaveform *wf_akima = new AnalysisWaveform( alfaGraph->GetN(), alfaGraph->GetX(), alfaGraph->GetY(), 1./2.6, AnalysisWaveform::AKIMA); // AnalysisWaveform *wf_sparse = new AnalysisWaveform( alfaGraph->GetN(), alfaGraph->GetX(), alfaGraph->GetY(), 1./2.6, AnalysisWaveform::REGULARIZED_SPARSE_YEN); const TGraphAligned * uneven = wf_akima->uneven(); TString fname; fname.Form("alfa_%d_uneven.csv",eventNumber); FILE * ff = fopen(fname.Data(),"w"); for (int i = 0; i < uneven->GetN(); i++) fprintf(ff,"%g,%g\n", uneven->GetX()[i], uneven->GetY()[i]); fclose(ff); fname.Form("alfa_%d_akima.csv",eventNumber); const TGraphAligned * even = wf_akima->even(); ff = fopen(fname.Data(),"w"); for (int i = 0; i < even->GetN(); i++) fprintf(ff,"%g,%g\n", even->GetX()[i], even->GetY()[i]); fclose(ff); /* new TCanvas; alfaGraph->Draw("al"); wf_akima->setTitle("akima"); wf_sparse->setTitle("sparse"); wf_akima->setColor(2); wf_sparse->setColor(3); // wf_akima->padFreq(3); // wf_sparse->padFreq(3); wf_akima->drawEven("lsame"); wf_sparse->drawEven("lsame"); */ TCanvas * c = new TCanvas; wf_akima->padEven(10); //wf_sparse->padEven(9); // wf_sparse->setFreqDisplayRange(0.7,0.9); wf_akima->drawPower("al"); wf_akima->setFreqDisplayRange(0.7,0.9); wf_akima->setTitle(TString::Format("%d",eventNumber)); TGraph *g = new TGraph(2); g->GetX()[0] = 0.792; g->GetX()[1] = 0.792; g->GetY()[1] = 1; g->GetY()[0] = 0; // wf_sparse->drawPower("lsame"); g->Draw("lsame"); c->SaveAs(TString::Format("alfa_%d.png", eventNumber)); }
void PlotRakeEvolutions(const TString &sim, const TString &options="png") { #ifdef __CINT__ gSystem->Load("libplasma.so"); #endif PlasmaGlob::Initialize(); // Palettes! gROOT->Macro("PlasmaPalettes.C"); TString opt = options; // More makeup Float_t margins[4] = {0.15,0.15,0.20,0.10}; gStyle->SetPadLeftMargin(margins[0]); // Margin left axis gStyle->SetPadRightMargin(margins[2]); gStyle->SetPadTopMargin(margins[3]); // Margin left axis gStyle->SetPadBottomMargin(margins[1]); gStyle->SetPadTickX(1); gStyle->SetPadTickY(1); if(opt.Contains("grid")) { gStyle->SetPadGridX(1); gStyle->SetPadGridY(1); } const Int_t Nspaces = 4; TString phaname[Nspaces] = {"p1x1","p2x2","p3x3","x2x1"}; TGraph *gXmean[Nspaces]; TGraph *gYmean[Nspaces]; TGraph *gXrms[Nspaces]; TGraph *gYrms[Nspaces]; TGraph *gEmit[Nspaces]; TGraph *gCharge = NULL; // Special graph with an Energy spread band: TGraphErrors *gEneRms = NULL; Float_t maxEmit[Nspaces] = { -999., -999., -999., -999.}; Float_t minEmit[Nspaces] = { 999., 999.,999., 999.}; Float_t maxXmean[Nspaces] = { -999., -999., -999., -999.}; Float_t minXmean[Nspaces] = { 999., 999., 999., 999.}; Float_t maxXrms[Nspaces] = { -999., -999., -999., -999.}; Float_t minXrms[Nspaces] = { 999., 999., 999., 999.}; Float_t maxYmean[Nspaces] = { -999., -999., -999., -999.}; Float_t minYmean[Nspaces] = { 999., 999., 999.}; Float_t maxYrms[Nspaces] = { -999., -999., -999., -999.}; Float_t minYrms[Nspaces] = { 999., 999., 999., 999.}; Float_t maxCharge =-999.; Float_t minCharge = 999.; // Resolution: Int_t sizex = 600; Int_t sizey = 800; if(opt.Contains("hres")) { Int_t sizex = 1024; Int_t sizey = 768; } for(Int_t i=0;i<Nspaces;i++) { TString filename; filename = Form("./%s/Plots/EmittanceEvolution/Evolutions-%s-%s.root",sim.Data(),sim.Data(),phaname[i].Data()); TFile *ifile = (TFile*) gROOT->GetListOfFiles()->FindObject(filename.Data()); if (!ifile) ifile = new TFile(filename,"READ"); gEmit[i] = (TGraph*) ifile->Get("gEmitvsTime"); gXmean[i] = (TGraph*) ifile->Get("gXmeanvsTime"); gXrms[i] = (TGraph*) ifile->Get("gXrmsvsTime"); gYmean[i] = (TGraph*) ifile->Get("gYmeanvsTime"); gYrms[i] = (TGraph*) ifile->Get("gYrmsvsTime"); // Energy spread if(i==0) { gCharge = (TGraph*) ifile->Get("gChargevsTime"); Int_t Npoints = gCharge->GetN(); Double_t *yCharge = gCharge->GetY(); for(Int_t j=0;j<Npoints;j++) { if(yCharge[j]>maxCharge) maxCharge = yCharge[j]; if(yCharge[j]<minCharge) minCharge = yCharge[j]; } Double_t *xValues = gYmean[i]->GetX(); Double_t *yMean = gYmean[i]->GetY(); Double_t *yRms = gYrms[i]->GetY(); Npoints = gYmean[i]->GetN(); gEneRms = new TGraphErrors(Npoints,xValues,yMean,0,yRms); // cout << "NPOints = " << gEneRms->GetN() << endl; // for(Int_t j=0;j<gEneRms->GetN();j++) { // gEneRms->SetPointError(j,0.0,yRms[j]); // cout << "eoooo" << endl; // } } // Calculate the max and min of every set of graphs: Int_t Npoints = gEmit[i]->GetN(); Double_t *yEmit = gEmit[i]->GetY(); for(Int_t j=0;j<Npoints;j++) { if(yEmit[j]>maxEmit[i]) maxEmit[i] = yEmit[j]; if(yEmit[j]<minEmit[i]) minEmit[i] = yEmit[j]; } Npoints = gXmean[i]->GetN(); Double_t *yXmean = gXmean[i]->GetY(); for(Int_t j=0;j<Npoints;j++) { if(yXmean[j]>maxXmean[i]) maxXmean[i] = yXmean[j]; if(yXmean[j]<minXmean[i]) minXmean[i] = yXmean[j]; } Npoints = gXrms[i]->GetN(); Double_t *yXrms = gXrms[i]->GetY(); for(Int_t j=0;j<Npoints;j++) { if(yXrms[j]>maxXrms[i]) maxXrms[i] = yXrms[j]; if(yXrms[j]<minXrms[i]) minXrms[i] = yXrms[j]; } Npoints = gYmean[i]->GetN(); Double_t *yYmean = gYmean[i]->GetY(); for(Int_t j=0;j<Npoints;j++) { if(yYmean[j]>maxYmean[i]) maxYmean[i] = yYmean[j]; if(yYmean[j]<minYmean[i]) minYmean[i] = yYmean[j]; } Npoints = gYrms[i]->GetN(); Double_t *yYrms = gYrms[i]->GetY(); for(Int_t j=0;j<Npoints;j++) { if(yYrms[j]>maxYrms[i]) maxYrms[i] = yYrms[j]; if(yYrms[j]<minYrms[i]) minYrms[i] = yYrms[j]; } } // -------------------- // Canvas setup TCanvas *C1 = new TCanvas("C1","Evolution of Emittance",sizex,sizey); C1->cd(); // C1->Divide(1,Nspaces); // PlasmaGlob::CanvasPartition(C1,pad,Nspaces); const Int_t Npads = 3; TH1F *hFrame[Npads]; TPad **pad = new TPad*[Npads]; // Setup Pad layout: Double_t lMargin = 0.15; Double_t rMargin = 0.15; Double_t bMargin = 0.08; Double_t tMargin = 0.08; Double_t vSpacing = 0.01; Double_t hStep = (1.-lMargin-rMargin); Double_t vStep = (1.- bMargin - tMargin - (Npads-1) * vSpacing) / Npads; Float_t *vposd = new Float_t[Npads]; Float_t *vposu = new Float_t[Npads]; Float_t *vmard = new Float_t[Npads]; Float_t *vmaru = new Float_t[Npads]; Float_t *vfactor = new Float_t[Npads]; Float_t *hposl = new Float_t[Npads]; Float_t *hposr = new Float_t[Npads]; Float_t *hmarl = new Float_t[Npads]; Float_t *hmarr = new Float_t[Npads]; Float_t *hfactor = new Float_t[Npads]; for(Int_t i=0;i<Npads;i++) { hposl[i] = 0.0; hposr[i] = 1.0; hmarl[i] = lMargin; hmarr[i] = rMargin; if(i==0) { vposd[i] = 0.0; vposu[i] = bMargin + vStep; vfactor[i] = vposu[i]-vposd[i]; vmard[i] = bMargin / vfactor[i]; vmaru[i] = 0.0; } else if(i == Npads-1) { vposd[i] = vposu[i-1] + vSpacing; vposu[i] = vposd[i] + vStep + tMargin; vfactor[i] = vposu[i]-vposd[i]; vmard[i] = 0.0; vmaru[i] = tMargin / (vposu[i]-vposd[i]); } else { vposd[i] = vposu[i-1] + vSpacing; vposu[i] = vposd[i] + vStep; vfactor[i] = vposu[i]-vposd[i]; vmard[i] = 0.0; vmaru[i] = 0.0; } hfactor[i] = hposl[i]-hposr[i]; C1->cd(); char name[16]; sprintf(name,"pad_%i",i); cout << endl << Form("%s : %4.2f %4.2f %4.2f %4.2f",name,hposl[i],vposd[i],hposr[i],vposu[i]) << endl; pad[i] = new TPad(name,"",hposl[i],vposd[i],hposr[i],vposu[i]); pad[i]->SetLeftMargin(hmarl[i]); pad[i]->SetRightMargin(hmarr[i]); pad[i]->SetBottomMargin(vmard[i]); pad[i]->SetTopMargin(vmaru[i]); pad[i]->Draw(); pad[i]->cd(); sprintf(name,"hFrame_%i",i); hFrame[i] = new TH1F(name,"",100,0,20); hFrame[i]->GetYaxis()->SetLabelSize(0.02/vfactor[i]); hFrame[i]->GetYaxis()->SetLabelOffset(0.01/vfactor[i]); hFrame[i]->GetYaxis()->SetTitleSize(0.02/vfactor[i]); hFrame[i]->GetYaxis()->SetTitleOffset(1.0-vfactor[i]);///vfactor[i]); hFrame[i]->GetXaxis()->SetLabelSize(0.07); hFrame[i]->GetXaxis()->SetLabelOffset(0.01/vfactor[i]); hFrame[i]->GetXaxis()->SetTitleSize(0.07); hFrame[i]->GetXaxis()->SetTitleOffset(1.1);///vfactor[i]); hFrame[i]->Draw("axis"); if(i==2) { Float_t yMin = 0.0001; // minYmean[0] - (maxYmean[0]-minYmean[0])*0.1; Float_t yMax = maxYmean[0] + (maxYmean[0]-minYmean[0])*0.1; hFrame[i]->GetYaxis()->SetRangeUser(yMin,yMax); hFrame[i]->GetXaxis()->SetTitle("propagation length [mm]"); hFrame[i]->GetYaxis()->SetTitle("p_{z} [GeV/c]"); // PlasmaGlob::SetH1LabelSize(hFrame[i]); gEneRms->SetFillColor(kGray); gEneRms->Draw("3"); gYmean[0]->Draw("L"); // Charge on right axis: Float_t yrMin = 0.00001; // minCharge - (maxCharge-minCharge)*0.1; Float_t yrMax = maxCharge + (maxCharge-minCharge)*0.1; Float_t slope = (yMax-yMin)/(yrMax-yrMin); Double_t *x = gCharge->GetX(); Double_t *y = gCharge->GetY(); for(Int_t j=0;j<gCharge->GetN();j++) { gCharge->SetPoint(j,x[j],slope*(y[j]-yrMin)+yMin); } //hFrame[i]->GetYaxis()->SetRangeUser(yrMin,yrMax); gCharge->SetLineStyle(2); gCharge->SetLineWidth(3); gCharge->SetLineColor(kAzure-8); gCharge->Draw("L"); pad[i]->Update(); } else if(i==1) { Float_t yMin,yMax; if(minXrms[1]<minXrms[0]) yMin = minXrms[1]; else yMin = minXrms[0]; if(maxXrms[1]>maxXrms[0]) yMax = maxXrms[1]; else yMax = maxXrms[0]; Float_t yDist = yMax - yMin; yMin -= 0.1*yDist; yMax += 0.1*yDist; hFrame[i]->GetYaxis()->SetRangeUser(yMin,yMax); hFrame[i]->GetXaxis()->SetTitle("propagation length [mm]"); hFrame[i]->GetYaxis()->SetTitle("rms size [#mum]"); // PlasmaGlob::SetH1LabelSize(hFrame[i]); gXrms[0]->SetLineStyle(1); gXrms[0]->SetLineWidth(3); gXrms[0]->SetLineColor(kOrange+10); gXrms[0]->Draw("L"); gXrms[1]->SetLineStyle(2); gXrms[1]->SetLineWidth(3); gXrms[1]->SetLineColor(kAzure-8); gXrms[1]->Draw("L"); pad[i]->Update(); } else if(i==0) { Float_t yMin,yMax; if(minEmit[1]<minEmit[0]) yMin = minEmit[1]; else yMin = minEmit[0]; if(maxEmit[1]>maxEmit[0]) yMax = maxEmit[1]; else yMax = maxEmit[0]; Float_t yDist = yMax - yMin; yMin -= 0.1*yDist; yMax += 0.1*yDist; hFrame[i]->GetYaxis()->SetRangeUser(yMin,yMax); hFrame[i]->GetXaxis()->SetTitle("propagation length [mm]"); hFrame[i]->GetYaxis()->SetTitle("trans. emittance [(MeV/c) #mum]"); // PlasmaGlob::SetH1LabelSize(hFrame[i]); gEmit[0]->SetLineStyle(1); gEmit[0]->SetLineWidth(3); gEmit[0]->SetLineColor(kOrange+10); gEmit[0]->Draw("L"); gEmit[1]->SetLineStyle(2); gEmit[1]->SetLineWidth(3); gEmit[1]->SetLineColor(kAzure-8); gEmit[1]->Draw("L"); pad[i]->Update(); } } C1->cd(); // Print to a file // Output file TString fOutName = Form("./%s/Plots/RakeEvolution/RakeEvolution-%s",sim.Data(),sim.Data()); PlasmaGlob::imgconv(C1,fOutName,opt); }
void laserCalibration( char* filename = "frascatirun", //input file int filenum = 1081, //file number int channel = 3, //trace channel int flagChannel = 5, //laser flag channel Double_t entriesN = 10, //number of entries for prcessing int sleep = 10, //sleep time between 2 processed entries, helpful for viewing traces bool gui = true //enable or disable trace visualization ) { caen_5742 caen; Int_t nbins = 1024; Double_t entries = entriesN; Int_t bin; TCanvas *c1 = new TCanvas("c1","frascatirun",900,700); c1->Divide(1,2); c1->cd(1); TGraph* g = new TGraph(); TH1F* lmPeaks = new TH1F("lm","Peaks Ratio", 1000, 0, 5000); TH1F* d = new TH1F("d","",nbins,0,nbins); TH1F* back = new TH1F("Back","",nbins,0,nbins); // input file char fname[100]=0; sprintf(fname,"%s_0%i.root",filename,filenum); TFile* infile = new TFile(fname); TTree *t = (TTree*) infile->Get("t"); t->SetBranchAddress("caen_5742", &caen.system_clock); t->Print(); if(entriesN<=0) entries = t->GetEntries(); //out file char foutname[100]=0; int lm=0; if (channel ==3)lm=1; if (channel ==4)lm=2; sprintf(foutname,"./calibration/LM%i_out_0%i.root",lm,filenum); outfile = new TFile(foutname,"RECREATE"); outTree = new TTree("LM","frascatirun output"); calibTree = new TTree("LM_cal","frascatirun output"); outTree->Branch("LM_PX1",&fPositionX1,"PX1/D"); outTree->Branch("LM_PX2",&fPositionX2,"PX2/D"); outTree->Branch("LM_PY1",&fPositionY1,"PY1/D"); outTree->Branch("LM_PY2",&fPositionY2,"PY2/D"); //outTree->Branch("baseline",baseline,"baseline[1024]/F"); outTree->Branch("time",&timeline,"time/D"); outTree->Branch("LM_P2_Integral",&integralP2,"IP2/D"); calibTree->Branch("LM_P2_Integral_mean",&integralP2_mean,"IP2_mean/D"); calibTree->Branch("LM_P2_Integral_mean_error",&integralP2_mean_error,"IP2_mean_error/D"); calibTree->Branch("LM_P2_Integral_sigma",&integralP2_sigma,"IP2_sigma/D"); calibTree->Branch("LM_P2_Integral_sigma_error",&integralP2_sigma_error,"IP2_sigma_error/D"); /************************************** * read entries ************************************** */ for (int j = 0; j < entries; ++j){ gSystem->Sleep (sleep); t->GetEntry(j); //TRIGGER SELECTION if(caen.trace[flagChannel][400]>1000 && caen.trace[flagChannel][800]<3000){ timeline = caen.system_clock; /************************************** * Peaks estimation ************************************** */ for (int i = 0; i < nbins; ++i){ g->SetPoint(i, i, caen.trace[channel][i]); } Double_t y_max = TMath::MaxElement(g->GetN(),g->GetY()); Float_t * source = new Float_t[nbins]; Float_t * dest = new Float_t[nbins]; for (int i = 0; i < nbins; ++i){ source[i]=y_max-caen.trace[channel][i]; g->SetPoint(i, i, source[i]); } //Use TSpectrum to find the peak candidates TSpectrum *s = new TSpectrum(); Int_t nfound = s->SearchHighRes(source, dest, nbins, 3, 2, kTRUE, 2, kFALSE, 5); /************************************** * Background estimation ************************************** */ Int_t ssize = nbins; Int_t numberIterations = 20; Int_t direction = s->kBackIncreasingWindow; Int_t filterOrder = s->kBackOrder2; bool smoothing = kFALSE; Int_t smoothWindow = s->kBackSmoothing3; bool compton = kFALSE; for (int i = 0; i < nbins; ++i) baseline[i] = source[i]; s->Background(baseline, ssize, numberIterations, direction, filterOrder, smoothing, smoothWindow, compton); /************************************** * Peaks and integral estimation ************************************** */ Double_t px[2], py[2]; for (int i = 0; i < nbins; ++i) dest[i] = source[i]-baseline[i]; if(nfound==2){ bin = s->GetPositionX()[0]; fPositionX1 = bin; fPositionY1 = dest[bin]; px[0] = bin; py[0] = dest[bin]; bin = s->GetPositionX()[1]; fPositionX2 = bin; fPositionY2 = dest[bin]; px[1] = bin; py[1] = dest[bin]; } int posxa=6; int posxb=9; switch (filenum){ case 1081: posxa=6; posxb=9; break; case 1082: posxa=5; posxb=7; break; case 1083: posxa=5; posxb=8; break; case 1084: posxa=5; posxb=7; break; case 1085: posxa=5; posxb=7; break; case 1086: posxa=5; posxb=5; break; case 1087: posxa=4; posxb=4; break; case 1088: posxa=3; posxb=4; break; case 1089: posxa=3; posxb=3; break; default: posxa=6; posxb=9; } integralP2 = g->Integral (fPositionX2-posxa,fPositionX2+posxb); /************************************** * print and update the canvas ************************************** */ if(gui==true){ TH1F* gh = g->GetHistogram(); gh->FillN(nbins,g->GetX(),g->GetY()); g->Draw(); TPolyMarker* pm = (TPolyMarker*)gh->GetListOfFunctions()->FindObject("TPolyMarker"); if (pm) { gh->GetListOfFunctions()->Remove(pm); delete pm; } pm = new TPolyMarker(nfound, px, py); gh->GetListOfFunctions()->Add(pm); pm->SetMarkerStyle(23); pm->SetMarkerColor(kBlue); pm->SetMarkerSize(1.3); for (i = 0; i < nbins; i++) d->SetBinContent(i,dest[i]); d->SetLineColor(kRed); d->Draw("SAME"); for (i = 0; i < nbins; i++) back->SetBinContent(i,baseline[i]); back->SetLineColor(kGreen); back->Draw("SAME"); c1->Update(); } /************************************** * Fill tree and peaks data Histogram ************************************** */ if(nfound==2) { lmPeaks->Fill(integralP2); outTree->Fill(); } //printf("time= %d, posx1= %d, posy1= %d\n",time, fPositionX1, fPositionY1); //printf("time= %d, posx2= %d, posy2= %d\n",time, fPositionX2, fPositionY2); //for (int i=0;i<nbins;i++) printf("time = %d\n",baseline[i]); } } /************************************** * switch to the bottom pan and Draw Histogram ************************************** */ c1->cd(2); //lmPeaks->SetAxisRange(TMath::MinElement(entries,binmin),TMath::MaxElement(entries,binmax)+100); //lmPeaks->SetAxisRange(0,3000); lmPeaks->Fit("gaus"); integralP2_mean = lmPeaks->GetFunction("gaus")->GetParameter(1); integralP2_sigma = lmPeaks->GetFunction("gaus")->GetParameter(2); integralP2_mean_error = lmPeaks->GetFunction("gaus")->GetParError(1); integralP2_sigma_error = lmPeaks->GetFunction("gaus")->GetParError(2); //printf("mean = %f\n",integralP2_mean); //printf("sigma = %f\n",integralP2_sigma); calibTree->Fill(); lmPeaks->Draw(); c1->Update(); outfile->cd(); gROOT->GetList()->Write(); outTree->Write(); calibTree->Write(); outfile->Close(); }
void plotLimit(string outputDir="./", TString inputs="", TString inputs_blinded="", TString inputXSec="", bool strengthLimit=true, bool blind=false, double energy=7, double luminosity=5.035, TString legendName="ee and #mu#mu channels") { setTDRStyle(); gStyle->SetPadTopMargin (0.05); gStyle->SetPadBottomMargin(0.12); gStyle->SetPadRightMargin (0.16); gStyle->SetPadLeftMargin (0.14); gStyle->SetTitleSize(0.04, "XYZ"); gStyle->SetTitleXOffset(1.1); gStyle->SetTitleYOffset(1.45); gStyle->SetPalette(1); gStyle->SetNdivisions(505); //get the limits from the tree TFile* file = TFile::Open(inputs); printf("Looping on %s\n",inputs.Data()); if(!file) return; if(file->IsZombie()) return; TFile* file_blinded = TFile::Open(inputs_blinded); printf("Looping on %s\n",inputs_blinded.Data()); if(!file_blinded) return; if(file_blinded->IsZombie()) return; TTree* tree_blinded = (TTree*)file_blinded->Get("limit"); tree_blinded->GetBranch("mh" )->SetAddress(&Tmh ); tree_blinded->GetBranch("limit" )->SetAddress(&Tlimit ); tree_blinded->GetBranch("limitErr" )->SetAddress(&TlimitErr); tree_blinded->GetBranch("quantileExpected")->SetAddress(&TquantExp); TGraph* ExpLimitm2 = getLimitGraph(tree_blinded,0.025); TGraph* ExpLimitm1 = getLimitGraph(tree_blinded,0.160); TGraph* ExpLimit = getLimitGraph(tree_blinded,0.500); TGraph* ExpLimitp1 = getLimitGraph(tree_blinded,0.840); TGraph* ExpLimitp2 = getLimitGraph(tree_blinded,0.975); file_blinded->Close(); TTree* tree = (TTree*)file->Get("limit"); tree->GetBranch("mh" )->SetAddress(&Tmh ); tree->GetBranch("limit" )->SetAddress(&Tlimit ); tree->GetBranch("limitErr" )->SetAddress(&TlimitErr); tree->GetBranch("quantileExpected")->SetAddress(&TquantExp); TGraph* ObsLimit = getLimitGraph(tree,-1 ); file->Close(); FILE* pFileSStrenght = fopen((outputDir+"SignalStrenght").c_str(),"w"); std::cout << "Printing Signal Strenght" << std::endl; for(int i=0;i<ExpLimit->GetN();i++){ double M = ExpLimit->GetX()[i]; std::cout << "Mass: " << M << "; ExpLimit: " << ExpLimit->Eval(M) << std::endl; printf("$%8.6E$ & $%8.6E$ & $[%8.6E,%8.6E]$ & $[%8.6E,%8.6E]$ \\\\\\hline\n",M, ExpLimit->Eval(M), ExpLimitm1->Eval(M), ExpLimitp1->Eval(M), ExpLimitm2->Eval(M), ExpLimitp2->Eval(M)); fprintf(pFileSStrenght, "$%8.6E$ & $%8.6E$ & $[%8.6E,%8.6E]$ & $[%8.6E,%8.6E]$ & $%8.6E$ \\\\\\hline\n",M, ExpLimit->Eval(M), ExpLimitm1->Eval(M), ExpLimitp1->Eval(M), ExpLimitm2->Eval(M), ExpLimitp2->Eval(M), ObsLimit->Eval(M)); if(int(ExpLimit->GetX()[i])%50!=0)continue; //printf("%f ",ObsLimit->Eval(M)); }printf("\n"); fclose(pFileSStrenght); //get the pValue inputs = inputs.ReplaceAll("/LimitTree", "/PValueTree"); file = TFile::Open(inputs); printf("Looping on %s\n",inputs.Data()); if(!file) return; if(file->IsZombie()) return; tree = (TTree*)file->Get("limit"); tree->GetBranch("limit" )->SetAddress(&Tlimit ); TGraph* pValue = getLimitGraph(tree,-1); file->Close(); //make TH Cross-sections string suffix = outputDir; TGraph* THXSec = Hxswg::utils::getXSec(outputDir); scaleGraph(THXSec, 1000); //convert cross-section to fb double cprime=1.0; double brnew=0.0; double XSecScaleFactor = 1.0; if(suffix.find("_cp")!=string::npos){ sscanf(suffix.c_str()+suffix.find("_cp"), "_cp%lf_brn%lf", &cprime, &brnew); XSecScaleFactor = pow(cprime,2) * (1-brnew); } //XSecScaleFactor = 0.001; //pb to fb scaleGraph(THXSec, XSecScaleFactor); string prod = "pp_SM"; if(outputDir.find("ggH")!=std::string::npos)prod="gg"; if(outputDir.find("qqH")!=std::string::npos)prod="qq"; if(outputDir.find("ppH")!=std::string::npos)prod="pp"; strengthLimit = false; if(prod=="pp_SM")strengthLimit=true; //TGraph *XSecMELA = Hxswg::utils::getXSecMELA(cprime); //Hxswg::utils::multiplyGraph( ObsLimit, XSecMELA); //Hxswg::utils::multiplyGraph( ExpLimitm2, XSecMELA); //Hxswg::utils::multiplyGraph( ExpLimitm1, XSecMELA); //Hxswg::utils::multiplyGraph( ExpLimit, XSecMELA); //Hxswg::utils::multiplyGraph( ExpLimitp1, XSecMELA); //Hxswg::utils::multiplyGraph( ExpLimitp2, XSecMELA); //Scale exclusion XSec in fb scaleGraph(ObsLimit , 0.001); //pb to fb scaleGraph(ExpLimitm2, 0.001); //pb to fb scaleGraph(ExpLimitm1, 0.001); //pb to fb scaleGraph(ExpLimit , 0.001); //pb to fb scaleGraph(ExpLimitp1, 0.001); //pb to fb scaleGraph(ExpLimitp2, 0.001); //pb to fb //scal eTH cross-section and limits according to scale factor //this only apply to NarrowResonnance case if(strengthLimit){ Hxswg::utils::divideGraph(ObsLimit , THXSec); Hxswg::utils::divideGraph(ExpLimitm2 , THXSec); Hxswg::utils::divideGraph(ExpLimitm1 , THXSec); Hxswg::utils::divideGraph(ExpLimit , THXSec); Hxswg::utils::divideGraph(ExpLimitp1 , THXSec); Hxswg::utils::divideGraph(ExpLimitp2 , THXSec); Hxswg::utils::divideGraph(THXSec , THXSec); } //limits in terms of signal strength TCanvas* c = new TCanvas("c", "c",800,800); c->SetGridx(); c->SetGridy(); TH1F* framework = new TH1F("Graph","Graph",1,strengthLimit?199:199,2500); //3000); framework->SetStats(false); framework->SetTitle(""); framework->GetXaxis()->SetTitle("M_{H} [GeV]"); framework->GetYaxis()->SetTitleOffset(1.70); if(strengthLimit){ framework->GetYaxis()->SetTitle("#mu = #sigma_{95%} / #sigma_{th}"); framework->GetYaxis()->SetRangeUser(1E-4,1E3); c->SetLogy(true); }else{ framework->GetYaxis()->SetTitle((string("#sigma_{95%} (") + prod +" #rightarrow H #rightarrow ZZ) (pb)").c_str()); framework->GetYaxis()->SetRangeUser(1E-3,1E3); c->SetLogy(true); } framework->GetXaxis()->SetLabelOffset(0.007); framework->GetXaxis()->SetLabelSize(0.03); framework->GetXaxis()->SetTitleOffset(1.0); framework->GetXaxis()->SetTitleFont(42); framework->GetXaxis()->SetTitleSize(0.035); framework->GetYaxis()->SetLabelFont(42); framework->GetYaxis()->SetLabelOffset(0.007); framework->GetYaxis()->SetLabelSize(0.03); framework->GetYaxis()->SetTitleOffset(1.3); framework->GetYaxis()->SetTitleFont(42); framework->GetYaxis()->SetTitleSize(0.035); framework->Draw(); TGraph* TGObsLimit = ObsLimit; TGObsLimit->SetLineWidth(2); TGraph* TGExpLimit = ExpLimit; TGExpLimit->SetLineWidth(2); TGExpLimit->SetLineStyle(2); TCutG* TGExpLimit1S = GetErrorBand("1S", ExpLimitm1, ExpLimitp1); TCutG* TGExpLimit2S = GetErrorBand("2S", ExpLimitm2, ExpLimitp2); TGExpLimit2S->SetFillColor(5); THXSec->SetLineWidth(2); THXSec->SetLineStyle(1); THXSec->SetLineColor(4); TGExpLimit->SetLineColor(1); TGExpLimit->SetLineStyle(2); TGObsLimit->SetLineWidth(2); TGObsLimit->SetMarkerStyle(20); TGExpLimit2S->Draw("fc same"); TGExpLimit1S->Draw("fc same"); if(!blind) TGObsLimit->Draw("same P"); TGExpLimit->Draw("same c"); /*if(strengthLimit){ TLine* SMLine = new TLine(framework->GetXaxis()->GetXmin(),1.0,framework->GetXaxis()->GetXmax(),1.0); SMLine->SetLineWidth(2); SMLine->SetLineStyle(1); SMLine->SetLineColor(4); SMLine->Draw("same C"); }else{ THXSec->Draw("same C"); }*/ utils::root::DrawPreliminary(luminosity, energy, c); TLegend* LEG = new TLegend(0.55,0.75,0.85,0.95); LEG->SetHeader(""); LEG->SetFillColor(0); LEG->SetFillStyle(0); LEG->SetTextFont(42); LEG->SetBorderSize(0); //LEG->AddEntry(THXSec , "Th prediction" ,"L"); LEG->AddEntry(TGExpLimit , "median expected" ,"L"); LEG->AddEntry(TGExpLimit1S , "expected #pm 1#sigma" ,"F"); LEG->AddEntry(TGExpLimit2S , "expected #pm 2#sigma" ,"F"); if(!blind) LEG->AddEntry(TGObsLimit , "observed" ,"LP"); LEG->Draw(); c->RedrawAxis(); c->SaveAs((outputDir+"Limit.png").c_str()); c->SaveAs((outputDir+"Limit.C").c_str()); c->SaveAs((outputDir+"Limit.pdf").c_str()); //save a summary of the limits FILE* pFileSum = fopen((outputDir+"LimitSummary").c_str(),"w"); for(int i=0;i<TGExpLimit->GetN();i++){ double M = ExpLimit->GetX()[i]; fprintf(pFileSum, "$%8.6E$ & $%8.6E$ & $[%8.6E,%8.6E]$ & $[%8.6E,%8.6E]$ & $%8.6E$ & Th=$%8.6E$ & pValue=$%8.6E$\\\\\\hline\n",M, ExpLimit->Eval(M), ExpLimitm1->Eval(M), ExpLimitp1->Eval(M), ExpLimitm2->Eval(M), ExpLimitp2->Eval(M), ObsLimit->Eval(M), (THXSec!=NULL)?THXSec->Eval(M):-1, pValue->Eval(M)); if(int(ExpLimit->GetX()[i])%50!=0)continue; printf("%f ",ObsLimit->Eval(M)); }printf("\n"); fclose(pFileSum); pFileSum = fopen((outputDir+"LimitRange").c_str(),"w"); fprintf(pFileSum, "EXPECTED LIMIT --> "); printLimits(pFileSum,TGExpLimit, TGExpLimit->GetX()[0], TGExpLimit->GetX()[TGExpLimit->GetN()-1]); if(!blind) fprintf(pFileSum, "OBSERVED LIMIT --> "); printLimits(pFileSum,TGObsLimit, TGObsLimit->GetX()[0], TGObsLimit->GetX()[TGObsLimit->GetN()-1]); fprintf(pFileSum, "Exp Limits for Model are: "); for(int i=0;i<TGExpLimit->GetN();i++){if(int(TGExpLimit->GetX()[i])%50==0) fprintf(pFileSum, "%f+-%f ",TGExpLimit->GetY()[i], (ExpLimitp1->GetY()[i]-ExpLimitm1->GetY()[i])/2.0);}fprintf(pFileSum,"\n"); if(!blind) { fprintf(pFileSum, "Obs Limits for Model are: "); for(int i=0;i<TGObsLimit->GetN();i++){if(int(TGObsLimit->GetX()[i])%50==0) fprintf(pFileSum, "%f ",TGObsLimit->GetY()[i]);}fprintf(pFileSum,"\n"); } fclose(pFileSum); }
int main(int argc, char** argv){ // because root is a piece of shit gSystem->Load("libTree"); if (argc != 2){ printf("Usage: ./pulse_shape <gain_meas root file>\n\te.g. ./pulse_shape test.root\n"); return -1; } char* file_name = argv[1]; // float t_min = -70e-9, t_max = 130e-9, u_min = -1., u_max = 2.; int sample_len; float baseline; // open root file and extract tree printf("[Pulse Shape] - Opening file '%s'..\n", file_name); TFile* in_file = TFile::Open(file_name, "READ"); TTree* in_tree = (TTree*)in_file->Get("outtree"); in_tree->SetBranchAddress("len", &sample_len); in_tree->SetBranchAddress("baseline", &baseline); in_tree->GetEntry(0); double* u = new double[sample_len]; double* t = new double[sample_len]; in_tree->SetBranchAddress("amplitude", u); in_tree->SetBranchAddress("time", t); const int nEvents = in_tree->GetEntries(); printf("[Pulse Shape] - Found tree with %i events, %i samples per event.\n", nEvents, sample_len); TFile* out_file = new TFile("out.root", "RECREATE"); TTree* out_tree = new TTree("out_tree", "outtree"); double riseTime, fallTime, pulseDuration; out_tree->Branch("risetime", &riseTime); out_tree->Branch("falltime", &fallTime); out_tree->Branch("pulseduration", &pulseDuration); TCanvas* c1 = new TCanvas(); TGraph* pulse = new TGraph(); pulse->SetTitle("Output pulse;t [s];U [V]"); pulse->SetMarkerStyle(7); TGraph* rf = new TGraph(); // drawing rise and fall time points rf->SetMarkerStyle(8); rf->SetMarkerColor(46); TF1* bl = new TF1("baseline", "[0]", -100, 100); // baseline bl->SetLineColor(38); // loop over data float uMax, lPos, hPos, lTime, hTime, rTime, buf; int maxEntry; for (int iEvent = 0; iEvent < nEvents; iEvent++){ uMax = -1.; in_tree->GetEntry(iEvent); for (int i = 0; i < sample_len; i++){ u[i] *= -1; pulse->SetPoint(i, t[i], u[i]); // find Maximum by Hand because root apparently isnt able to do so if (u[i] > uMax){ uMax = u[i]; maxEntry = i; } } // get 10% and 90% amplitude lPos = 0.1*(uMax - baseline) + baseline; hPos = 0.9*(uMax - baseline) + baseline; // get rise time -> start at maximum and go left lTime = -1; hTime = -1; for (int i = maxEntry; (buf = pulse->GetY()[i]) > 0.9*lPos; i--){ if ( buf > hPos ) hTime = pulse->GetX()[i]; if ( buf > lPos ){ lTime = pulse->GetX()[i]; } } riseTime = hTime - lTime; rf->SetPoint(0, lTime, lPos); rf->SetPoint(1, hTime, hPos); // get fall time -> start at maximum and go right rTime = -1; hTime = -1; for (int i = maxEntry; (buf = pulse->GetY()[i]) > 0.9*lPos; i++){ if ( buf > hPos ) hTime = pulse->GetX()[i]; if ( buf > lPos ){ rTime = pulse->GetX()[i]; } } fallTime = rTime - hTime; pulseDuration = rTime - lTime; rf->SetPoint(2, rTime, lPos); rf->SetPoint(3, hTime, hPos); out_tree->Fill(); // draw & save every 500th event if (iEvent%100 == 0) { printf("[Pulse Shape] - Risetime = %e s\n", riseTime); printf("[Pulse Shape] - Falltime = %e s\n", pulseDuration); printf("[Pulse Shape] - Pulse duration = %e s\n", fallTime); bl->SetParameter(0, baseline); pulse->Draw("A*"); bl->Draw("SAME"); rf->Draw("SAME*"); c1->Write(); } } // cleanup out_tree->Write(); out_file->Close(); in_file->Close(); return 0; }
int main(int argc, char* argv[]) { // initialize globalArgs globalArgs.data_folder = " "; globalArgs.arg_pathToSetupFile = " "; globalArgs.results_folder = " "; globalArgs.save_all = 0; // Get paremeter from the command int opt =0; opt = getopt(argc, argv, optString); if(opt == -1){ std::cerr << "There is no opption in the command! Type \"output -h\" for help." << std::endl; exit(EXIT_FAILURE); } while(opt != -1){ switch(opt){ case 'd': globalArgs.data_folder= optarg; //std::cout<<"-p option path= "<<globalArgs.arg_pathToData<<std::endl; break; case 'S': globalArgs.arg_pathToSetupFile = optarg; break; case 'o': globalArgs.results_folder = optarg; break; case 'a': globalArgs.save_all = 1; break; case 'h': case '?': std::cerr << "Usage: output -d pathToData -S pathToSetupFile -o pathToResultsFolder [-a]" << std::endl; std::cerr << "----------------------------------------------------------------------------------------------------"<<std::endl; std::cerr << " '-d'+'-S'+'-o' options are necessary!"<<std::endl; std::cerr << "-----------------------------------------------------------------------------------------------------"<<std::endl; std::cerr << " use '-a' option afterwards to save all the plots of the analysis to further check."<<std::endl; std::cerr << "-----------------------------------------------------------------------------------------------------"<<std::endl; std::cerr << "Example: ./output -d /Users/Analysis_waveforms/ov_scan_pde_H2014/ -S /Users/Analysis_waveforms/config_file.txt -o /Users/Analysis_waveforms/Plots/ [-a]"<<std::endl; exit(EXIT_FAILURE); break; default: break; } opt = getopt(argc, argv, optString); } if((strncmp(globalArgs.data_folder," ",1) == 0|| strncmp(globalArgs.arg_pathToSetupFile," ",1) == 0)){ std::cerr << "ERROR: -d or -S option is not set! Both of them has to be set correctly!"<<std::endl; exit(EXIT_FAILURE); } if(strncmp(globalArgs.results_folder," ",1) == 0){ std::cerr << "ERROR: -o option is not set! It has to be set up correctly!"<<std::endl; exit(EXIT_FAILURE); } ifstream setupFile(globalArgs.arg_pathToSetupFile); if(!setupFile){ std::cerr << "Failure: could not open file: \"" << globalArgs.arg_pathToSetupFile << "\"." << std::endl; std::cerr << "Please check if the path is correct or not!" << std::endl; exit(EXIT_FAILURE); } //////////////// //Define thresholds //////////////// //in nanoseconds const double reject_time = 4; vector <Double_t> reject_time_v; //used for AP, delayed x-talk and long tau fit //in percentage of pe const double after_pulse_th = 0.38; vector <Double_t> after_pulse_th_v; const double direct_xtalk_th = 1.17; vector <Double_t> direct_xtalk_th_v; const double xtalk_th = 0.85; vector <Double_t> xtalk_th_v; const double time_dist_th = 0.4; vector <Double_t> time_dist_th_v; //////////////// //////////////// //Read setup file: string s; vector <TString> vol_folders; Int_t data_size; while (true) { Double_t rt; Double_t ap; Double_t delay; Double_t imme; getline(setupFile, s); if (setupFile.eof()) break; const char* searchString = s.c_str(); char volt [20]; Int_t numfiles; if (s.find("#") == 0 || s=="") { continue; // Skip commented or empty lines } //Find the voltages if(sscanf(searchString, "V || %s ||", volt)==1){ vol_folders.push_back(volt); reject_time_v.push_back(reject_time); after_pulse_th_v.push_back(after_pulse_th); direct_xtalk_th_v.push_back(direct_xtalk_th); xtalk_th_v.push_back(xtalk_th); time_dist_th_v.push_back(time_dist_th); } if(sscanf(searchString, "V/th || %s ||", volt)==1){ vol_folders.push_back(volt); getline(setupFile, s); const char* thresholds_string = s.c_str(); sscanf(thresholds_string, "Rej_t: %lf, AP_th: %lf, Delay_th: %lf, Imm_th: %lf", &rt,&ap,&delay,&imme); reject_time_v.push_back(rt); after_pulse_th_v.push_back(ap); direct_xtalk_th_v.push_back(imme); xtalk_th_v.push_back(delay); time_dist_th_v.push_back(time_dist_th); } //Find data size if(sscanf(searchString, "Files at each voltage || %d ||", &numfiles)==1){ data_size = numfiles; } } //Initialize variables const Int_t vol_size = vol_folders.size(); int singleplot=0; Int_t Event=0; Char_t Category[15]; TGraph* waveform = 0; Double_t Amp; Double_t V_meas; double pe = 0.07; int row = 0; int full_n_file = 0; int ap_n_file = 0; int xtalk_n_file = 0; int dxtalk_n_file = 0; int time_dist_n_file = 0; int direct_xtalk_pulse; Double_t direct_xtalk_pulse_cnt=0; int xtalk_pulse; Double_t xtalk_pulse_cnt = 0; int after_pulse; Double_t after_pulse_cnt=0; Double_t event_cnt = 0; double sig_max = 0; double time_of_max = 0; double sig_max_first = 0; double time_of_max_first = 0; int max_cnt = 0; int max_noise_cnt = 0; int max_found = 0; /*const char * Voltage="56.5V"; int event=0; if (singleplot) { single_plot(Voltage,event); }*/ //Create a root tree with the graph of the waveform of each event and //classify them TString filename = globalArgs.results_folder; filename.Append("noiseanalysis.root"); TFile *hfile = 0; hfile = TFile::Open(filename,"RECREATE"); TTree *tree = new TTree("T","Noise Analysis"); tree->Branch("Event",&Event,"Event/I"); tree->Branch("Category",Category,"Category/C"); //Uncomment if every single waveform is desired to be saved by its own on the root file //tree->Branch("waveform","TGraph",&waveform); tree->Branch("V_meas",&V_meas,"V_meas/D"); //OV of the measurement TGraph* Correl_noise[4]; Correl_noise[0] = new TGraph(); Correl_noise[1] = new TGraph(); Correl_noise[2] = new TGraph(); Correl_noise[3] = new TGraph(); TGraph *Expfit_longtau[vol_size]; TGraph *Expfit_AP[vol_size]; //Fiting functions of long tau and AP recharge TF1 *exp_longtau= new TF1("exptau","[0]*exp(-x/[1])",0,180 * ns); TF1 *exp= new TF1("exp","[0]*(1-exp(-x/[1]))+[2]*exp(-x/[3])",0,180 * ns); TCanvas* c1[vol_size]; TCanvas* c2[vol_size]; TCanvas* c3[vol_size]; TCanvas* c4[vol_size]; TMultiGraph *Cleanwaves[vol_size]; TCanvas* expfit_longtau_c[vol_size]; TCanvas* expfit_AP_c[vol_size]; cout<<"////////////"<< endl; cout<<"****----->Voltage Breakdown calculation ***"<< endl; vector <Double_t> pe_volt; TGraph *Vbias_ver= new TGraph(); //Change to not recalculate the pe //pe_volt.push_back(6.87435e-02); /*pe_volt.push_back( 1.20426e-01); pe_volt.push_back(1.75262e-01); pe_volt.push_back(2.30936e-01); pe_volt.push_back(2.87958e-01);*/ //pe_volt.push_back( 3.44156e-01); //Double_t VBD=55.9006; //Calculate Voltage breakdown and value of pe for (int i=0; i<vol_size; i++) { pe_volt.push_back(Amplitude_calc(vol_folders.at(i).Data(), data_size)); V_meas = vol_folders.at(i).Atof(); Vbias_ver->SetPoint(i, pe_volt.at(i), V_meas); } TCanvas* ca= new TCanvas("Voltage Breakdown calculation","Voltage Breakdown calculation",100,100,900,700); Vbias_ver->SetTitle("Voltage Breakdown calculation"); Vbias_ver->GetYaxis()->SetTitle("Bias Volatge [V]"); Vbias_ver->GetYaxis()->SetTitleOffset(1.2); Vbias_ver->GetXaxis()->SetTitle("Mean peak amplitude [V]"); Vbias_ver->Draw("AP*"); ca->SetGrid(); TPaveText * pv = new TPaveText(0.2,0.65,0.35,0.74,"brNDC"); cout<<"////////////"<< endl; cout<<"****----->Voltage Breakdown fit ***"<< endl; TFitResultPtr fit = Vbias_ver->Fit("pol1","S"); Double_t VBD= fit->Value(0); Char_t VBD_text[20]; sprintf(VBD_text,"V_{BD} = %2.2f",VBD); pv->AddText(VBD_text); pv->Draw(); if (globalArgs.save_all==1) ca->Write(); cout<<"////////////"<< endl; cout<<"****----->Noise analysis ***"<< endl; cout<<"////////////"<< endl; ///////////////// // Loop over all Voltages measured ///////////////// for (int i=0; i<vol_size; i++) { //Important to reinitialize, the value color* = kOrange-11 is used to plot axis of TGraph() int color1 = kOrange-11; int color2 = kOrange-11; int color3 = kOrange-11; int color4 = kOrange-11; direct_xtalk_pulse_cnt = 0; xtalk_pulse_cnt = 0; after_pulse_cnt = 0; event_cnt = 0; //Events on the Voltage measured cout<<"****----->Voltage analyzed: "<< vol_folders.at(i) << endl; //Define amplitude measured at which OV Double_t pe = pe_volt.at(i); V_meas = vol_folders.at(i).Atof()-VBD; //Define canvases to save and check results Char_t canvas_title[40]; sprintf(canvas_title,"Direct CrossTalk OV = %2.2f V",V_meas); c1[i] = new TCanvas(canvas_title,canvas_title,100,100,900,700); sprintf(canvas_title,"Delayed CrossTalk OV = %2.2f V",V_meas); c2[i] = new TCanvas(canvas_title,canvas_title,100,100,900,700); sprintf(canvas_title,"After Pulse OV = %2.2f V",V_meas); c3[i] = new TCanvas(canvas_title,canvas_title,100,100,900,700); sprintf(canvas_title,"Clean OV = %2.2f V",V_meas); c4[i] = new TCanvas(canvas_title,canvas_title,100,100,900,700); Cleanwaves[i]=new TMultiGraph(); sprintf(canvas_title,"Exponential fit, #tau_l OV = %2.2f V",V_meas); expfit_longtau_c[i] = new TCanvas(canvas_title,canvas_title,300,100,900,500); sprintf(canvas_title,"Exponential fit OV = %2.2f V",V_meas); expfit_AP_c[i] = new TCanvas(canvas_title,canvas_title,300,100,900,500); Expfit_longtau[i]= new TGraph(); Expfit_AP[i]= new TGraph(); //loop over every measurement on a folder for (int j=0; j<data_size; j++) { Char_t datafilename[200]; Char_t datashortfilename[100]; sprintf(datafilename,"%s%s/C1H%05i.csv",globalArgs.data_folder,vol_folders.at(i).Data(),j); sprintf(datashortfilename,"%s_C1H%05i",vol_folders.at(i).Data(),j); //Get the data of a single file: waveform = new TGraph(datafilename,"%lg %lg","/t;,"); if (waveform->IsZombie()) continue; waveform->SetName(datashortfilename); waveform->SetTitle(""); Int_t ROWS_DATA = waveform->GetN(); Double_t *time = waveform->GetX(); Double_t *volts = waveform->GetY(); Amp = waveform->GetY()[0]; ///////////////////////////////////////////////////// // Data filtering into the different type of events // direct x-talk AP delayed x-talk ///////////////////////////////////////////////////// after_pulse = 0; xtalk_pulse = 0; direct_xtalk_pulse = 0; sig_max = 0; max_cnt = 0; max_found = 0; ///////////////////////////////////////////////////// // direct x-talk for (row = 0; row < ROWS_DATA; row++) { if ((time[row]>0 * ns)&(volts[row] > direct_xtalk_th_v.at(i) * pe)) {// time larger 0ns direct_xtalk_pulse++; } } ///////////////////////////////////////////////////// // after-pulse threshold for (row = 0; row < ROWS_DATA; row++) { if ((time[row]>reject_time_v.at(i)*ns)&(volts[row] > after_pulse_th_v.at(i) * pe)) {// time larger 4ns and ap_th after_pulse++; } } ///////////////////////////////////////////////////// // delayed x-talk for (row = 0; row < ROWS_DATA; row++) { if ((time[row]>reject_time_v.at(i)*ns)&(volts[row] > xtalk_th_v.at(i) * pe)) {// time larger 4ns and larger xtalk_th xtalk_pulse++; } } ///////////////////////////////////////////////////////////////////// // Detect peaks in data after 4ns, count the number of maxima and // measure the time of arrival of first maxima, used later for AP exp fit ///////////////////////////////////////////////////////////////////// max_noise_cnt = 0; for (row = 0; row < ROWS_DATA; row++) { if (time[row] > reject_time_v.at(i)*ns) {// time larger 4ns if (volts[row] > sig_max) { sig_max = volts[row]; // set the max time_of_max = time[row]; // time max max_noise_cnt++; // set the histeresis cnt }else if (max_noise_cnt > 0) max_noise_cnt--; // count down if no new max is reached // decide if real max or only noise, threshold has to be reached in case of a real max if (max_noise_cnt>2 && sig_max > time_dist_th_v.at(i) * pe) { max_cnt++; if (max_cnt == 1) { sig_max_first = sig_max; // sig max time_of_max_first = time_of_max; // time max max_found = 1; //printf("First max found: sig=%f time=%f ns max_noise_cnt=%d\n", sig_max, time_of_max / ns, max_noise_cnt); } //printf("Max number is: %d cnt=%d\n", max_cnt, max_noise_cnt); } } // 4ns } //loop over time bool clean = true; //The pulse is clean until the contrary can be demonstrated char graph_title[50]; //Check for imm x-talk and plot if (direct_xtalk_pulse > 0){ direct_xtalk_pulse_cnt++; sprintf(Category,"ImmCrosstalk"); c1[i]->cd(); //Set graph color, and counting to draw axis and title color1=color1+2; if (color1>kOrange+110) { color1=kOrange-8; }else if (color1>kOrange+109){ color1=kOrange-7; } waveform->SetLineColor(color1); waveform->SetMarkerColor(color1); //Format the graph sprintf(graph_title,"Direct CrossTalk OV = %2.2f V",V_meas); waveform = format_graph(waveform,graph_title,2.5*pe); if (color1>kOrange-8) { waveform->Draw("SAME"); }else{ waveform->Draw("AL"); c1[i]->SetGrid(); } clean = false; } // only delayed x-talk if (xtalk_pulse > 0 && direct_xtalk_pulse == 0){ xtalk_pulse_cnt++; sprintf(Category,"DelCrosstalk"); c2[i]->cd(); //Set graph color, and counting to draw axis and title color2=color2+2; if (color2>kOrange+110) { color2=kOrange-8; }else if (color2>kOrange+109){ color2=kOrange-7; } waveform->SetLineColor(color2); waveform->SetMarkerColor(color2); //Format the graph sprintf(graph_title,"Delayed cross-talk OV = %2.2f V",V_meas); waveform = format_graph(waveform,graph_title,1.2*pe); if (color2>kOrange-8) { waveform->Draw("SAME"); }else{ waveform->Draw("AL"); c2[i]->SetGrid(); } clean = false; } // Only after pulse if (after_pulse > 0 && xtalk_pulse == 0 && direct_xtalk_pulse == 0){ after_pulse_cnt++; sprintf(Category,"AfterPulse"); c3[i]->cd(); //Set graph color, and counting to draw axis and title color3=color3+2; if (color3>kOrange+110) { color3=kOrange-8; }else if (color3>kOrange+109){ color3=kOrange-7; } waveform->SetLineColor(color3); waveform->SetMarkerColor(color3); //Format the graph sprintf(graph_title,"After pulse OV = %2.2f V",V_meas); waveform = format_graph(waveform,graph_title,1.2*pe); if (color3>kOrange-8) { waveform->Draw("SAME"); }else{ waveform->Draw("AL"); c3[i]->SetGrid(); } clean = false; //Fill for the exponential fit Expfit_AP[i]->SetPoint(after_pulse_cnt-1,time_of_max,sig_max); } // Only clean graphs for the sample if (clean){ sprintf(Category,"Clean"); if (color4 < 860 && j <100) { //Max 100 clean graphs on the plot Cleanwaves[i]->Add(waveform); c4[i]->cd(); //Set graph color, and counting to draw axis and title color4=color4+2; if (color4>kOrange+110) { color4=kOrange-8; }else if (color4>kOrange+109){ color4=kOrange-7; } waveform->SetLineColor(color4); waveform->SetMarkerColor(color4); //Format the graph sprintf(graph_title,"Clean pulse OV = %2.2f V",V_meas); waveform = format_graph(waveform,graph_title,1.2*pe); if (color4>kOrange-8) { waveform->Draw("SAME"); }else{ waveform->Draw("AL"); c4[i]->SetGrid(); } } } tree->Fill(); Event ++;//Total number of events analyzed on the run if (Event%500==0) { cout<<"****----->Events analyzed:"<< Event << endl; } event_cnt++; } cout<<"////////////"<< endl; cout<<"****----->Long tau fit ***"<< endl; expfit_longtau_c[i]->cd(); Cleanwaves[i]->Draw("AP*"); // Fit parameters and limits to calculate slow component of the pulse exp_longtau->SetParameter(0,pe*0.2); exp_longtau->SetParLimits(0,0.05*pe,0.5*pe); exp_longtau->SetParameter(1,80*ns); exp_longtau->SetParLimits(1,4*ns,200*ns); Cleanwaves[i]->Fit("exptau","","",reject_time_v.at(i)*ns,60*ns); // Fit boundaries for the slow component of the pulse Double_t amp0 = exp_longtau->GetParameter(0); Double_t tau = exp_longtau->GetParameter(1); if (globalArgs.save_all==1) expfit_longtau_c[i]->Write(); c4[i]->cd(); TF1* exp_tau_plot =(TF1*) exp_longtau->Clone(); exp_tau_plot->Draw("SAME");//Draw fit-line over clean waveforms cout<<"////////////"<< endl; cout<<"****----->After pulse fit ***"<< endl; expfit_AP_c[i]->cd(); Expfit_AP[i]->Draw("AP*"); // Fit parameters and limits to calculate AP recharge exp->SetParameter(0,pe); exp->SetParLimits(0,0.5*pe,1.5*pe); exp->SetParameter(1,30*ns); exp->SetParLimits(1,4*ns,500*ns); exp->SetParameter(2,amp0); exp->FixParameter(2,amp0); exp->SetParameter(3,tau); exp->FixParameter(3,tau); Expfit_AP[i]->Fit("exp"); if (globalArgs.save_all==1) expfit_AP_c[i]->Write(); c3[i]->cd(); TF1* exp_plot =(TF1*) exp->Clone(); exp_plot->Draw("SAME"); //Draw fit-line over AP waveforms //Final result: Correlated noise Correl_noise[0]->SetPoint(i,V_meas,direct_xtalk_pulse_cnt/event_cnt*100); Correl_noise[1]->SetPoint(i,V_meas,after_pulse_cnt/event_cnt*100); Correl_noise[2]->SetPoint(i,V_meas,xtalk_pulse_cnt/event_cnt*100); Correl_noise[3]->SetPoint(i,V_meas, Correl_noise[0]->GetY()[i]+Correl_noise[1]->GetY()[i]+Correl_noise[2]->GetY()[i]); //Save/print reults: if (globalArgs.save_all==1){ c1[i]->Write(); c2[i]->Write(); c3[i]->Write(); c4[i]->Write(); } sprintf(canvas_title,"%sImmcrosstalk_%s.pdf",globalArgs.results_folder,vol_folders.at(i).Data()); c1[i]->Print(canvas_title,"pdf"); sprintf(canvas_title,"%sDelcrosstalk_%s.pdf",globalArgs.results_folder,vol_folders.at(i).Data()); c2[i]->Print(canvas_title,"pdf"); sprintf(canvas_title,"%sAfterpulse_%s.pdf",globalArgs.results_folder,vol_folders.at(i).Data()); c3[i]->Print(canvas_title,"pdf"); sprintf(canvas_title,"%sClean_%s.pdf",globalArgs.results_folder,vol_folders.at(i).Data()); c4[i]->Print(canvas_title,"pdf"); } //Save TTree with hist of noise //Save each event with its OV and the noise classification tree->Write(); //Create final plot of total correlated noise TCanvas* c5 = new TCanvas("Correlated Noise","Correlated Noise",100,100,900,700); Double_t tot_max_noise = TMath::MaxElement(Correl_noise[3]->GetN(),Correl_noise[3]->GetY()); Correl_noise[3]->SetTitle("Correlated Noise"); Correl_noise[3]->SetMarkerColor(kRed); Correl_noise[3]->SetLineColor(kRed); Correl_noise[3]->GetYaxis()->SetRangeUser(0,tot_max_noise+2); Correl_noise[3]->GetYaxis()->SetTitle("Noise [%]"); Correl_noise[3]->GetXaxis()->SetTitle("OverVoltage [V]"); Correl_noise[3]->Draw("ALP*"); Correl_noise[0]->SetTitle("Direct Cross-Talk"); Correl_noise[1]->SetTitle("After Pulse"); Correl_noise[2]->SetTitle("Delayed Cross-Talk"); Correl_noise[0]->SetLineColor(kBlue); Correl_noise[1]->SetLineColor(kOrange+7); Correl_noise[2]->SetLineColor(kGreen+2); Correl_noise[0]->SetMarkerColor(kBlue); Correl_noise[1]->SetMarkerColor(kOrange+7); Correl_noise[2]->SetMarkerColor(kGreen+2); Correl_noise[0]->Draw("LP*"); Correl_noise[1]->Draw("LP*"); Correl_noise[2]->Draw("LP*"); TLegend* leg = new TLegend(0.15,0.65,0.47,0.87); leg->AddEntry(Correl_noise[3],"Total","lp"); leg->AddEntry(Correl_noise[0],"Direct Cross-Talk","lp"); leg->AddEntry(Correl_noise[1],"After Pulse","lp"); leg->AddEntry(Correl_noise[2],"Delayed Cross-Talk","lp"); leg->Draw(); c5->SetGrid(); TString final_plot_name = globalArgs.results_folder; final_plot_name.Append("Correlated Noise.pdf"); c5->Print(final_plot_name,"pdf"); c5->Write(); delete hfile; return 0; }
void plot() { TGraph * FWHM = new TGraph( "plot.txt" , "%lg %lg %*lg %*lg" ); TGraph * FWTM = new TGraph( "plot.txt" , "%lg %*lg %lg %*lg" ); TGraph * FWFM = new TGraph( "plot.txt" , "%lg %*lg %*lg %lg" ); TGraph * ratioTH = new TGraph(); TGraph * ratioFH = new TGraph(); ratioTH->SetName("ratioTH"); ratioFH->SetName("ratioFH"); double * x = FWHM->GetX(); double * yH = FWHM->GetY(); double * yT = FWTM->GetY(); double * yF = FWFM->GetY(); for ( int i = 0 ; i < FWHM->GetN() ; i++ ) { ratioTH->SetPoint( i , x[i] , yT[i]/yH[i] ); ratioFH->SetPoint( i , x[i] , yF[i]/yH[i] ); } ratioTH->SetTitle("Gaussianity"); ratioTH->GetXaxis()->SetTitle("Energy Width [us]"); ratioTH->SetMarkerStyle(20); ratioTH->SetMarkerColor(kViolet+2); ratioTH->SetMarkerSize(1.5); ratioTH->SetLineColor(kViolet+2); ratioFH->SetMarkerStyle(29); ratioFH->SetMarkerColor(kYellow+2); ratioFH->SetMarkerSize(1.5); ratioFH->SetLineColor(kYellow+2); ratioTH->GetYaxis()->SetRangeUser(1,6); FWHM->SetTitle("Resolution"); FWHM->GetYaxis()->SetRangeUser(0,17); FWHM->GetYaxis()->SetTitle("[keV]"); FWHM->GetXaxis()->SetTitle("Energy Width [us]"); FWHM->SetMarkerStyle(33); FWHM->SetMarkerColor(kGreen+3); FWHM->SetMarkerSize(1.5); FWHM->SetLineColor(kGreen+3); FWTM->SetMarkerStyle(22); FWTM->SetMarkerColor(kBlue); FWTM->SetMarkerSize(1.5); FWTM->SetLineColor(kBlue); FWFM->SetMarkerStyle(23); FWFM->SetMarkerColor(kRed); FWFM->SetMarkerSize(1.5); FWFM->SetLineColor(kRed); TCanvas * can = new TCanvas("can","can",1); can->Divide(2,1); can->cd(1); gPad->SetGrid(); FWHM->Draw("AP"); FWTM->Draw("PSAME"); FWFM->Draw("PSAME"); TLegend * leg = new TLegend(0.24,0.77,0.42,0.88); leg->SetTextAlign(22); leg->SetTextSize(0.037); leg->AddEntry(FWHM,"FWHM","p"); leg->AddEntry(FWTM,"FWTM","p"); leg->AddEntry(FWFM,"FWFM","p"); leg->Draw(); can->cd(2); gPad->SetGrid(); ratioTH->Draw("AP"); ratioFH->Draw("PSAME"); TLine * lineTH = new TLine( ratioTH->GetXaxis()->GetXmin() , 1.82 , ratioTH->GetXaxis()->GetXmax() , 1.82 ); TLine * lineFH = new TLine( ratioTH->GetXaxis()->GetXmin() , 2.38 , ratioTH->GetXaxis()->GetXmax() , 2.38 ); lineTH->SetLineWidth(2); lineTH->SetLineStyle(9); lineTH->SetLineColor(kViolet+2); lineFH->SetLineWidth(2); lineFH->SetLineStyle(9); lineFH->SetLineColor(kYellow+2); lineTH->Draw(); lineFH->Draw(); TLegend * leg2 = new TLegend(0.14,0.77,0.45,0.88); leg2->SetTextAlign(22); leg2->SetTextSize(0.037); leg2->AddEntry(ratioTH,"FWTM/FWHM","p"); leg2->AddEntry(ratioFH,"FWFM/FWHM","p"); leg2->Draw(); return; }
void createNNLOplot(TString theory="ahrens") { // theory="ahrens", "kidonakis" TString outputRootFile="test.root"; // NB: add new datset name here if(theory.Contains("ahrens") ){ outputRootFile="AhrensNLONNLL"; //if(theory.Contains("mtt") ) outputRootFile+="mttbar" ; //else if(theory.Contains("pt")) outputRootFile+="pTttbar"; outputRootFile+=".root"; } else if(theory=="kidonakis") outputRootFile="KidonakisAproxNNLO.root"; // general options gStyle->SetOptStat(0); bool usequad=true; bool divideByBinwidth=true; // list of variables std::vector<TString> xSecVariables_, xSecLabel_; // NB: add variables for new datset name here TString xSecVariablesUsedAhrens[] ={"ttbarMass", "ttbarPt"}; TString xSecVariablesUsedKidonakis[] ={"topPt" , "topY" }; if( theory.Contains("ahrens") ) xSecVariables_ .insert( xSecVariables_.begin(), xSecVariablesUsedAhrens , xSecVariablesUsedAhrens + sizeof(xSecVariablesUsedAhrens )/sizeof(TString) ); else if(theory=="kidonakis") xSecVariables_ .insert( xSecVariables_.begin(), xSecVariablesUsedKidonakis, xSecVariablesUsedKidonakis + sizeof(xSecVariablesUsedKidonakis)/sizeof(TString) ); // get variable binning used for final cross sections std::map<TString, std::vector<double> > bins_=makeVariableBinning(); //std::vector<double> tempbins_; //double ttbarMassBins[]={345,445,545,745, 1045}; //tempbins_.insert( tempbins_.begin(), ttbarMassBins, ttbarMassBins + sizeof(ttbarMassBins)/sizeof(double) ); //bins_["ttbarMass"]=tempbins_; // loop all variables for(unsigned var=0; var<xSecVariables_.size(); ++var){ TString variable=xSecVariables_[var]; std::cout << "----------" << std::endl; std::cout << theory << ": " << variable << std::endl; // get bin boundaries double low =bins_[variable][0]; double high=bins_[variable][bins_[variable].size()-1]; // -------------------------- // get raw nnlo theory points // -------------------------- // NB: add new datset file names here TGraph * rawHist; TString predictionfolder="/afs/naf.desy.de/group/cms/scratch/tophh/CommonFiles/"; if(theory=="ahrens" ){ if(variable.Contains("ttbarMass")) rawHist= new TGraph(predictionfolder+"AhrensTheory_Mttbar_8000_172.5_NLONNLL_norm.dat");//AhrensTheory_Mtt_7000_172.5_Mtt_fin.dat if(variable.Contains("ttbarPt" )) rawHist= new TGraph(predictionfolder+"AhrensTheory_pTttbar_8000_172.5_NLONNLL_abs.dat");//AhrensTheory_pTttbar_7000_172.5_NLONNLL_abs.dat } else if(theory=="kidonakis"){ if(variable.Contains("topPt")) rawHist= new TGraph(predictionfolder+"pttopnnloapprox8lhc173m.dat");//"ptnormalNNLO7lhc173m.dat" //"pttopnnloapprox8lhc173m.dat" if(variable.Contains("topY" )) rawHist= new TGraph(predictionfolder+"ytopnnloapprox8lhc173m.dat" );//"ynormalNNLO7lhc173m.dat" //"ytopnnloapprox8lhc173m.dat" } // NB: say if points should be interpreted as single points with // nothing in between or as integrated value over the range bool points=true; if(theory.Contains("ahrens")) points=false; else if(theory=="kidonakis") points=true; std::cout << "input: " << rawHist->GetTitle() << std::endl; std::cout << "interprete values as points?: " << points << std::endl; // -------------------- // convertion to TH1F* // -------------------- double *Xvalues = rawHist->GetX(); int Nbins=rawHist->GetN(); //double *Yvalues = rawHist->GetY(); // not working double xmax=-1; double xmin=-1; double binwidth=-1; // TH1F* hist; // NB: add additional binning for new theory here // NB: if loaded data should be interpreted as points with // nothing in between (like kidonakis), make suree you // choose a binning that is fine enough for the // data points loaded if(theory=="ahrens"){ if(variable.Contains("ttbarMass")){ xmin= 345.; xmax=2720.; binwidth=25.;// 5 for 8TeV, 25 for 7TeV if(TString(rawHist->GetTitle()).Contains("8000")) binwidth=5.; } else if(variable.Contains("ttbarPt")){ xmin= 0.; xmax=1300.; binwidth=5.; } } else if(theory=="kidonakis"){ if(variable.Contains("topPt")){ xmin= 0.; xmax=1500.; binwidth=1.; } else if(variable.Contains("topY")){ xmin=-3.8; xmax= 3.8; binwidth=0.01; } } // fill data in binned TH1F hist= new TH1F ( variable, variable, (int)((xmax-xmin)/binwidth), xmin, xmax); TH1F* ori=(TH1F*)hist->Clone("original points"); std::cout << "fine binned theory prediction has " << hist->GetNbinsX() << " bins" << std::endl; std::cout << "loaded values from .dat file: " << std::endl; // list all data values loaded and the corresponding bin for(int bin=1; bin<=Nbins; ++bin){ double x=-999; double y=-999; // NB: choose if loaded data is interpreted as points with nothing // between (like kidonakis) or as integrated over the bin range (like ahrens) if(points){ // check if you are still inside the array //std::cout << "data point " << bin-1 << "/" << sizeof(Xvalues)/sizeof(double) << std::endl; if(rawHist->GetPoint(bin-1, x, y)!=-1){ //x=Xvalues[bin-1]; // get value from data points x+=0.5*binwidth; // add half the binwidth to get the center of the bin } } else{ x=hist->GetBinCenter(bin); // get bin center y=rawHist->GetY()[bin-1]; } if(x!=-999){ std::cout << "data point: " << bin; std::cout << "(<x>=" << x << ")-> bin"; // get bin in target (fine binned) plot int bin2=bin; if(points) bin2=hist->FindBin(x); //double y=Yvalues[bin2-1]; std::cout << bin2 << " ("; std::cout << hist->GetBinLowEdge(bin2) << ".." << hist->GetBinLowEdge(bin2+1); std::cout << "): " << y << std::endl; // fill target (fine binned) plot if(!points) hist->SetBinContent(bin2, y); // mark bins coming from the original prediction ori->SetBinContent(bin2, 1.); // ------------------------------- // fit range without data entries // ------------------------------- // NB: needed if loaded data is interpreted as points with nothing // between (like kidonakis) if(points){ // perform a linear fit wrt previous point // get the two points (this bin and the previous one) int binPrev= (bin==1&&variable=="topPt") ? 0 : hist->FindBin(Xvalues[bin-2]+0.5*binwidth); double x2=-1; double x1= 0; double y2=-1; double y1= 0.; rawHist->GetPoint(bin-1, x2, y2); x2+=0.5*binwidth; if(bin==1&&variable=="topPt"){ y1=0; x1=0; } else{ rawHist->GetPoint(bin-2, x1, y1); x1+=0.5*binwidth; } // calculate linear funtion double a=(y2-y1)/(x2-x1); double b=y1-a*x1; TF1* linInterpol=new TF1("linInterpol"+getTStringFromInt(bin), "[0]*x+[1]", x1, x2); linInterpol->SetParameter(0,a); linInterpol->SetParameter(1,b); double xlow = (bin==1&&variable=="topPt") ? 0. : hist->GetBinLowEdge(binPrev+1); double xhigh = hist->GetBinLowEdge(bin2+1); std::cout << " lin. interpolation [ (" << x1 << "," << y1 << ") .. (" << x2 << "," << y2 << ") ]: " << a << "*x+" << b << std::endl; linInterpol->SetRange(xlow, xhigh); hist->Add(linInterpol); } } } // check theory curve std::cout << std::endl << "analyze theory curve:" << std::endl; double integralRawTheory=hist->Integral(0.,hist->GetNbinsX()+1); std::cout << "Integral: " << integralRawTheory << std::endl; if(integralRawTheory==0.){ std::cout << "ERROR: Integral can not be 0!" << std::endl; exit(0); } std::cout << "binwidth: " << binwidth << std::endl; std::cout << "Integral*binwidth: " << integralRawTheory*binwidth << std::endl; std::cout << "binRange: " << xmin << ".." << xmax << std::endl; std::cout << " -> reco range: " << low << ".." << high << std::endl; std::vector<double> recoBins_=bins_[variable]; for(unsigned int i=0; i<recoBins_.size(); ++i){ i==0 ? std::cout << "(" : std::cout << ", "; std::cout << recoBins_[i]; if(i==recoBins_.size()-1) std::cout << ")" << std::endl; } // check if you need to divide by binwidth if(std::abs(1.-integralRawTheory)<0.03){ std::cout << "Integral is approx. 1 -> need to divide by binwidth!" << std::endl; hist->Scale(1./binwidth); } else if(std::abs(1-integralRawTheory*binwidth)<0.03){ std::cout << "Integral*binwidth is approx. 1 -> no scaling needed!" << std::endl; } else{ std::cout << "need to normalize and divide by binwidth"; hist->Scale(1./(binwidth*integralRawTheory)); } // styling hist->GetXaxis()->SetRangeUser(low,high); hist->SetMarkerColor(kMagenta); hist->SetLineColor( kMagenta); hist->SetMarkerStyle(24); // create canvas std::cout << std::endl << "create canvas " << std::endl; TCanvas *canv = new TCanvas(variable,variable,800,600); canv->cd(); std::cout << "draw original theory curve " << std::endl; //temp->Draw("axis"); hist->Draw("p"); //hist->Draw("hist same"); // draw original points if(points){ for(int bin=1; bin<ori->GetNbinsX(); ++bin){ // create copy of original data points with the normalized values if(ori->GetBinContent(bin)!=0) ori->SetBinContent(bin, hist->GetBinContent(bin)); ori->SetMarkerColor(kBlack); ori->SetMarkerStyle(29); ori->SetMarkerSize(1); ori->Draw("p same"); } } // -------------------- // create rebinned plot // -------------------- std::cout << std::endl << "create rebinned curve:" << std::endl; TString name=""; // NB: add name for dataset here name=variable; if( theory=="kidonakis") name+="approxnnlo"; else if(theory=="ahrens" ) name+="nlonnll" ; TH1F* binnedPlot=new TH1F(name, name, bins_[variable].size()-1, &bins_[variable][0]); for(int bin=1; bin<=hist->GetNbinsX(); ++bin){ double y=hist->GetBinContent(bin)*hist->GetBinWidth(bin); double xlow =hist->GetBinLowEdge(bin); double xhigh=hist->GetBinLowEdge(bin+1); // search corresponding bin in rebinned curve bool found=false; //std::cout << "xlow: " << xlow << ", xhigh: " << xhigh << std::endl; // FIXME for(int binRebinned=0; binRebinned<=binnedPlot->GetNbinsX()+1; ++binRebinned){ if(binnedPlot->GetBinLowEdge(binRebinned)<=xlow&&binnedPlot->GetBinLowEdge(binRebinned+1)>=xhigh){ found=true; binnedPlot->SetBinContent(binRebinned, binnedPlot->GetBinContent(binRebinned)+y); break; } //else{ // std::cout << "not in: " << binnedPlot->GetBinLowEdge(binRebinned) << ".." << binnedPlot->GetBinLowEdge(binRebinned+1)<< std::endl; //} } // -------------------- // use linear interpolation for edge bins // -------------------- if(hist->GetBinCenter(bin)<high&&!found){ std::cout << "need interpolation for bin" << bin << "(<x>=" << hist->GetBinCenter(bin) << ")!"<< std::endl; // search for the two bins involved double binLow=0; double binHigh=0; for(int binRebinned=1; binRebinned<=binnedPlot->GetNbinsX(); ++binRebinned){ // search for bin in binned histo where upper border of is close to lower border of unbinned histo if(std::abs(binnedPlot->GetBinLowEdge(binRebinned+1)-xlow)<binwidth){ binLow =binRebinned; binHigh=binRebinned+1; break; } } std::cout << "theory bin " << xlow << ".." << xhigh << "-> reco bins "; std::cout << binnedPlot->GetBinLowEdge(binLow) << ".." << binnedPlot->GetBinLowEdge(binLow+1) << " & "; std::cout << binnedPlot->GetBinLowEdge(binHigh) << ".." << binnedPlot->GetBinLowEdge(binHigh+1) << std::endl; // get the two points (this bin and the previous one) double x2=hist->GetBinCenter (bin ); double x1=hist->GetBinCenter (bin-1); double x3=hist->GetBinCenter (bin+1); double y2=hist->GetBinContent(bin ); double y1=hist->GetBinContent(bin-1); double y3=hist->GetBinContent(bin+1); // calculate linear funtion double a=(y2-y1)/(x2-x1); double b=y1-a*x1; TF1* linInterpol=new TF1("linInterpol"+getTStringFromInt(bin), "[0]*x+[1]", x1, x2); linInterpol->SetParameter(0,a); linInterpol->SetParameter(1,b); // calculate the corresponding area of linear function to binned curve double contributionLowerBin=linInterpol->Integral(xlow,binnedPlot->GetBinLowEdge(binHigh)); double contributionUpperBin=linInterpol->Integral(binnedPlot->GetBinLowEdge(binHigh),xhigh); // draw interpolation function for checking linInterpol->SetRange(xlow,xhigh); linInterpol->SetLineColor(kMagenta); linInterpol->DrawClone("same"); // eventually use quadratic interpolation for the first harens m(ttbar) bin if(theory=="ahrens"&&variable.Contains("ttbarMass")&&usequad&&x2<450){ // calculate quadratic funtion double a2=(y2-((y3-y1))*(x2-x1)/(x3-x1))/(x2*x2-x1*x1-(x2-x1)*(x3*x3+x1*x1)/(x3-x1)); double b2=((y3-y1)-a2*(x3*x3-x1*x1))/(x3-x1); double c2=y1-a2*x1*x1-b*x1; TF1* quadInterpol=new TF1("quadInterpol"+getTStringFromInt(bin), "[0]*x*x+[1]*x+[2]", x1, x2); quadInterpol->SetParameter(0,a2); quadInterpol->SetParameter(1,b2); quadInterpol->SetParameter(2,c2); // draw quad interpolation function for checking quadInterpol->SetRange(xlow,xhigh); quadInterpol->SetLineColor(kGreen); quadInterpol->SetLineStyle(2); hist->Fit(quadInterpol, "", "same", x1, x3); // calculate the corresponding area of linear function to binned curve quadInterpol->DrawClone("same"); double areaLow =quadInterpol->Integral(xlow,binnedPlot->GetBinLowEdge(binHigh) ); double areaHigh=quadInterpol->Integral(binnedPlot->GetBinLowEdge(binHigh),xhigh); std::cout << "ratio(high/low) linear/quadratic: " << contributionUpperBin/contributionLowerBin << "/"<< areaHigh/areaLow << std::endl; contributionLowerBin=y2*binwidth*areaLow /(areaLow+areaHigh); contributionUpperBin=y2*binwidth*areaHigh/(areaLow+areaHigh); } // add fitted result binnedPlot->SetBinContent(binLow , binnedPlot->GetBinContent(binLow )+contributionLowerBin); binnedPlot->SetBinContent(binHigh, binnedPlot->GetBinContent(binHigh)+contributionUpperBin); } } // ensure over/underflow is 0 binnedPlot->SetBinContent(0, 0.); binnedPlot->SetBinContent(binnedPlot->GetNbinsX()+1, 0.); // ensure normalization binnedPlot->Scale(1./(binnedPlot->Integral(0.,binnedPlot->GetNbinsX()+1))); // divide by binwidth if(divideByBinwidth){ for(int bin=1; bin<=binnedPlot->GetNbinsX(); ++bin){ binnedPlot->SetBinContent(bin, binnedPlot->GetBinContent(bin)/binnedPlot->GetBinWidth(bin)); } } std::cout << "-------------------------------------------" << std::endl; std::cout << "result: binned output histo" << std::endl; for(int bin=1; bin<=binnedPlot->GetNbinsX(); ++bin){ std::cout << "content bin " << bin << " (" << binnedPlot->GetBinLowEdge(bin) << ".." << binnedPlot->GetBinLowEdge(bin+1) << ")= " << binnedPlot->GetBinContent(bin) << std::endl; } // styling binnedPlot->SetLineColor(kBlue); binnedPlot->SetLineWidth(2); std::cout << "draw rebinned theory curve " << std::endl; binnedPlot->Draw("hist same"); // draw bin boundaries std::cout << "draw bin boundaries " << std::endl; int binColor=kRed; int binWidth=2; int binStyle=6; for(int bin=0; bin<(int)bins_.size(); ++bin){ if(!variable.Contains("ttbarMass")||bins_[variable][bin]>=345.) drawLine(bins_[variable][bin], 0, bins_[variable][bin], hist->GetMaximum(), binColor, binWidth, binStyle); } TH1F* line=(TH1F*)hist->Clone("line"); line->SetLineColor(binColor); line->SetLineWidth(binWidth); line->SetLineStyle(binStyle); // legend TLegend *leg = new TLegend(0.7, 0.6, 0.95, 0.9); legendStyle(*leg,theory); if(points) leg ->AddEntry(ori, "original data points","P"); leg ->AddEntry(hist , "theory prediction" ,"P"); leg ->AddEntry(line , "reco binning" ,"L"); leg ->AddEntry(hist , "linear interpolation" ,"L"); leg ->AddEntry(binnedPlot, "rebinned curve" ,"L"); leg->Draw("same"); std::cout << "done" << std::endl; // save in png and rootfile std::cout << std::endl << "do saving..." << std::endl; canv->SaveAs(variable+"Norm_Theory.png"); TH1F* out=(TH1F*)binnedPlot->Clone(); out->SetTitle(variable); out->SetName (variable); out->GetXaxis()->SetTitle(xSecLabelName(variable)); TString yTile="#frac{1}{#sigma} #frac{d#sigma}{d"; if(variable=="ttbarMass") yTile+="m^{t#bar{t}}} [GeV^{-1}]"; if(variable=="ttbarPt") yTile+="p_{T}^{t#bar{t}}} [GeV^{-1}]"; if(variable=="topPt") yTile+="p_{T}^{t}} [GeV^{-1}]"; if(variable=="topY" ) yTile+="y^{t}}"; out->GetYaxis()->SetTitle(yTile); out->SetLineColor(kOrange+2); out->SetLineStyle(2); std::cout << std::endl << "draw final result " << std::endl; TCanvas *canv2 = new TCanvas(variable+"Rebinned",variable+"Rebinned",800,600); canv2->cd(); out->Draw(); saveToRootFile(outputRootFile, out , true, 0,"" ); saveToRootFile(outputRootFile, rawHist, true, 0,"graph" ); saveToRootFile(outputRootFile, canv , true, 0,"detail"); std::cout << "done!" << std::endl; } }
/* root -l 'sigmapeak.C+(0.025)' // Processing sigmapeak.C+(0.025)... background only: bkg_nsigma_0_99 = -0.352803 sig_nsigma_0_59 = -0.608621 sig_nsigma_0_99 = 2.1472 sig_nsigma_60_99 = 4.14042 sig_nsigma_70_90 = 5.57689 sig_nsigma_75_85 = 8.056 */ void sigmapeak(Double_t signal_area=0.025) { Double_t bkg_mean = 0; Double_t bkg_sigma = 0.001; Double_t x[100]; Double_t y[100]; Int_t np = 100; TRandom3 rand; for (int i=0; i<np; ++i) { x[i] = i; y[i] = rand.Gaus(bkg_mean,bkg_sigma); } TGraph* gr = new TGraph(np,x,y); gr->SetNameTitle("gr",Form("#sigma = %0.1f",bkg_sigma)); gr->SetMarkerStyle(7); gr->SetMarkerColor(46); new TCanvas(); gr->Draw("ap"); Double_t bkg_nsigma_0_99 = Nsigma(gr->GetY(), 0,99, bkg_sigma); cout<< "background only: bkg_nsigma_0_99 = " << bkg_nsigma_0_99 <<endl; // add signal Double_t signal_mean = 80; Double_t signal_sigma = 3; for (int i=0; i<gr->GetN(); ++i) { Double_t xx = (gr->GetX()[i] - signal_mean)/signal_sigma; Double_t arg = 0.5*xx*xx; Double_t exp = arg < 50? TMath::Exp(-arg): 0; Double_t signal = signal_area/(TMath::Sqrt(TMath::TwoPi())*signal_sigma) * exp; gr->SetPoint(i, gr->GetX()[i], gr->GetY()[i] + signal); } gr->SetTitle(Form("#sigma_{bkg} = %0.3f signal: area = %0.3f mean = %0.0f sigma = %0.1f", bkg_sigma,signal_area,signal_mean,signal_sigma)); gr->Draw("apl"); gr->Fit("gaus", "R", "", signal_mean - 5*signal_sigma, signal_mean+5*signal_sigma); Double_t fit_area = 2.5 * gr->GetFunction("gaus")->GetParameter("Constant") * gr->GetFunction("gaus")->GetParameter("Sigma"); cout<< "Area under fitted gaussian = " << fit_area <<endl; // titmax(); gPad->Modified(); // to create box (NB: the pad was not drawn yet at this point!) gPad->Update(); TPaveText* tit = (TPaveText*)gPad->GetPrimitive("title"); tit->SetX1NDC(0.); tit->SetX2NDC(1.); tit->SetY1NDC(0.9); tit->SetY2NDC(1.); gPad->Modified(); // to update the pad gPad->Update(); Double_t sig_nsigma_0_59 = Nsigma(gr->GetY(), 0,59, bkg_sigma); cout<< "sig_nsigma_0_59 = " << sig_nsigma_0_59 <<endl; Double_t sig_nsigma_0_99 = Nsigma(gr->GetY(), 0,99, bkg_sigma); cout<< "sig_nsigma_0_99 = " << sig_nsigma_0_99 <<endl; Double_t sig_nsigma_60_99 = Nsigma(gr->GetY(), 60,99, bkg_sigma); cout<< "sig_nsigma_60_99 = " << sig_nsigma_60_99 <<endl; Double_t sig_nsigma_70_90 = Nsigma(gr->GetY(), 70,90, bkg_sigma); cout<< "sig_nsigma_70_90 = " << sig_nsigma_70_90 <<endl; Double_t sig_nsigma_75_85 = Nsigma(gr->GetY(), 75,85, bkg_sigma); cout<< "sig_nsigma_75_85 = " << sig_nsigma_75_85 <<endl; Double_t ys5[100]; smooth5(np, gr->GetY(), ys5); TGraph* gr5 = new TGraph(np, x, ys5); gr5->SetNameTitle("gr5","smoothed on 5 points"); gr5->SetMarkerStyle(7); gr5->SetMarkerColor(2); gr5->SetLineColor(2); new TCanvas; gr5->Draw("apl"); Double_t ys7[100]; smooth7(np, gr->GetY(), ys7); TGraph* gr7 = new TGraph(np, x, ys7); gr7->SetNameTitle("gr7","smoothed on 7 points"); gr7->SetMarkerStyle(7); gr7->SetMarkerColor(8); gr7->SetLineColor(8); new TCanvas; gr7->Draw("apl"); Double_t ys7a[100]; smooth7a(np, gr->GetY(), ys7a); TGraph* gr7a = new TGraph(np, x, ys7a); gr7a->SetNameTitle("gr7a","smoothed on 7a points"); gr7a->SetMarkerStyle(7); gr7a->SetMarkerColor(3); gr7a->SetLineColor(3); new TCanvas; gr7a->Draw("apl"); Double_t ys5g[100]; smooth5g(np, gr->GetY(), ys5g); TGraph* gr5g = new TGraph(np, x, ys5g); gr5g->SetNameTitle("gr5g","smoothed on 5g points"); gr5g->SetMarkerStyle(7); gr5g->SetMarkerColor(4); gr5g->SetLineColor(4); new TCanvas; gr5g->Draw("apl"); Double_t ys5a[100]; smooth5a(np, gr->GetY(), ys5a); TGraph* gr5a = new TGraph(np, x, ys5a); gr5a->SetNameTitle("gr5a","smoothed on 5a points"); gr5a->SetMarkerStyle(7); gr5a->SetMarkerColor(6); gr5a->SetLineColor(6); new TCanvas; gr5a->Draw("apl"); }
void makeMuVMassPlot(bool iUseWWType = false) { SetStyle(); TCanvas *lCan = new TCanvas("A","A",600,600); // lCan->SetGridx(1); //lCan->SetGridy(1); lCan->SetRightMargin(0.14); double *lTX1 = new double[2]; double *lTX2 = new double[2]; double lMinNLL = 1000; double lVMin = 0; double *lMin = new double[36]; if(!iUseWWType) for(int i0 = 0; i0 < 36; i0++) { lMin[i0] = getMinNLL(110+i0*1.); if(lMin[i0] < lVMin) {lVMin = lMin[i0]; lTX1[0] = 110+i0*1.;}} //lMin[17] = (lMin[16]+lMin[18])/2.; //lMin[21] = (lMin[20]+lMin[22])/2.; //lMin[29] = (lMin[28]+lMin[30])/2.; //lMin[34] = (lMin[33]+lMin[35])/2.; TFile *lFile = new TFile("/afs/cern.ch/user/p/pharris/public/massscan/cmb+.root"); TTree *lTree = lFile->FindObjectAny("limit"); TH2F *lH = new TH2F("2D","2D",36,109.5,145.5,50,-2.,3.); float lNLL = 0; lTree->SetBranchAddress("nll" ,&lNLL); float lMNLL = 0; lTree->SetBranchAddress("deltaNLL",&lMNLL); double lMH = 0; lTree->SetBranchAddress("mh" ,&lMH); float lR = 0; lTree->SetBranchAddress("r" ,&lR); if(iUseWWType) { for(int i0 = 0; i0 < lTree->GetEntries(); i0++) { lTree->GetEntry(i0); if(lR < 0.1 && lR > 0) lMin[int(lMH-110)] = -lMNLL; } lVMin = 10000; for(int i0 = 0; i0 < lTree->GetEntries(); i0++) { lTree->GetEntry(i0); double pMin = lMin[int(lMH-110)] + lMNLL; if(pMin < lVMin) lVMin = pMin; } } for(int i0 = 0; i0 < lTree->GetEntries(); i0++) { lTree->GetEntry(i0); //if(lMH == 125) continue; lNLL = 0.; //lMin = 0.; lH->SetBinContent(lH->GetXaxis()->FindBin(lMH),lH->GetYaxis()->FindBin(lR),(lMNLL+lMin[lH->GetXaxis()->FindBin(lMH)-1]-lVMin)); if(lMH == lTX1[0] && lMNLL < lMinNLL) {lMinNLL = lMNLL; lTX2[0] = lR;} } TH2F* lHC = lH->Clone("2D_v2"); double lCont[3]; lCont[0] = 1.17; lCont[1] = 3.0; lCont[2] = 9.0; lHC->SetContour(2,lCont); //lCan->SetLogz(); lHC->Draw("cont z list"); lCan->Update(); lHC->Draw("colz"); TObjArray *lContours = (TObjArray*)gROOT->GetListOfSpecials()->FindObject("contours"); int lTotalConts = lContours->GetSize(); double *lTX = new double[2]; lTX[0] = 110; lTX[1] = 145; double *lTY = new double[2]; lTY[0] = -0.5; lTY[1] = 2.5; TGraph *lFirst = new TGraph(2,lTX,lTY); lFirst->SetLineColor(kWhite); lFirst->GetXaxis()->SetRangeUser(110,148); lFirst->Draw("al"); lFirst->SetTitle(""); lH->GetYaxis()->SetRangeUser(-0.5,2.5); lFirst->GetXaxis()->SetTitle("m_{H}[GeV]"); lFirst->GetXaxis()->SetTitleOffset(1.0); lFirst->GetYaxis()->SetTitle("#mu_{best-fit}"); lFirst->GetYaxis()->SetTitleOffset(1.2); lH->GetXaxis()->SetTitle("m_{H}[GeV]"); lH->GetXaxis()->SetTitleOffset(1.0); lH->GetYaxis()->SetTitle("#mu_{best-fit}"); lH->GetYaxis()->SetTitleOffset(1.2); lTX1[1] = lTX1[0]; lTX2[1] = lTX2[1]+0.001; TGraph *lSecond = new TGraph(1,lTX1,lTX2); lSecond->SetMarkerStyle(34); lSecond->SetMarkerSize(3.5); //lSecond->Draw("p"); TLegend *lL = new TLegend(0.65,0.15,0.85,0.35); lL->SetBorderSize(0); lL->SetFillColor(0); lL->SetFillStyle(0); for(i0 = 0; i0 < lTotalConts; i0++){ pContLevel = (TList*)lContours->At(lTotalConts-1.-i0); // Get first graph from list on curves on this level std::vector<double> lX; std::vector<double> lY; pCurv = (TGraph*)pContLevel->First(); for(int i1 = 0; i1 < pContLevel->GetSize(); i1++){ for(int i2 = 0; i2 < pCurv->GetN(); i2++) {lX.push_back(pCurv->GetX()[i2]); lY.push_back(pCurv->GetY()[i2]);} //pCurv->GetPoint(0, x0, y0); pCurv->SetLineColor(kBlack);//kGreen+i0); pCCurv = (TGraph*)pCurv->Clone(); if(i0 == 0) pCCurv->SetFillColor(0); if(i0 == 1) pCCurv->SetFillColor(0); //if(i0 == 1) pCCurv->SetLineStyle(kDashed); pCCurv->SetLineWidth(3); pCCurv->GetXaxis()->SetRangeUser(0,3.0); //if(i0 == 0) pCCurv->Draw("AL"); //if(i0 != -10) pCCurv->Draw("LC"); //l.DrawLatex(x0,y0,val); pCurv = (TGraph*)pContLevel->After(pCurv); // Get Next graph } TGraph *lTotal = new TGraph(lX.size(),&lX[0],&lY[0]); lTotal->SetLineWidth(3); lTotal->SetFillColor(kGreen+i0*2); lTotal->SetFillStyle(3001); //lTotal->Draw("lf"); //if(i0 == 0) lTotal->Draw("alf"); //if(i0 == 0) lTotal->Draw("alf"); //for(int iX = 0; iX < lTotal->GetN(); iX++) cout << "===> " << lTotal->GetX()[iX] << " -- " << lTotal->GetY()[iX] << endl; //if(i0 != -10) lTotal->Draw("lfC"); bool pSwitch = false; int pSign = -1.; if(lTotal->GetX()[0] > lTotal->GetX()[1]) pSign = 1; double pXOld = lTotal->GetX()[lTotal->GetN()-1]; std::vector<double> pXLeft; std::vector<double> pXRight; std::vector<double> pYLeft; std::vector<double> pYRight; for(int iX = 0; iX < lTotal->GetN(); iX++) { double pX = lTotal->GetX()[iX]; if(pSign*pX > pSign*pXOld ) {pSwitch = !pSwitch; pSign *= -1;} if(!pSwitch) {pXLeft.push_back(lTotal->GetX()[iX]); pYLeft.push_back(lTotal->GetY()[iX]); } if(pSwitch) {pXRight.push_back(lTotal->GetX()[iX]); pYRight.push_back(lTotal->GetY()[iX]); } pXOld = pX; } TGraph *lLeftTotal = new TGraph(pXLeft.size() ,&pXLeft[0],&pYLeft[0]); TGraph *lRightTotal = new TGraph(pXRight.size(),&pXRight[0],&pYRight[0]); lLeftTotal->SetLineColor(kRed); lRightTotal->SetLineColor(kBlue); lLeftTotal->SetLineStyle(kDashed); lRightTotal->SetLineStyle(kDashed); //lLeftTotal->Draw("l"); //lRightTotal->Draw("l"); TGraphSmooth *lGS0 = new TGraphSmooth("normal"); TGraphSmooth *lGS1 = new TGraphSmooth("normal"); TGraph *lSmooth0 = lGS0->SmoothSuper(lRightTotal,"",0.,0.); TGraph *lSmooth1 = lGS1->SmoothSuper(lLeftTotal,"",0.,0.) ; lSmooth0->Draw("l"); lSmooth1->Draw("l"); std::vector<double> pXSmooth; std::vector<double> pYSmooth; std::vector<double> pXSmooth1; std::vector<double> pYSmooth1; cout << "==" << lSmooth0->GetN() << " -- " <<lSmooth1->GetN() << endl; for(int iX = 0; iX < lSmooth0->GetN(); iX++) {pXSmooth.push_back(lSmooth0->GetX()[iX]); pYSmooth.push_back(lSmooth0->GetY()[iX]);} for(int iX = 0; iX < lSmooth1->GetN(); iX++) {pXSmooth.push_back(lSmooth1->GetX()[lSmooth1->GetN()-iX-1]); pYSmooth.push_back(lSmooth1->GetY()[lSmooth1->GetN()-iX-1]);} for(int iX = 0; iX < lSmooth0->GetN(); iX++) {pXSmooth1.push_back(lSmooth0->GetX()[iX]); pYSmooth1.push_back(lSmooth0->GetY()[iX]);} for(int iX = 0; iX < lSmooth1->GetN(); iX++) {pXSmooth1.push_back(lSmooth1->GetX()[lSmooth1->GetN()-iX-1]); pYSmooth1.push_back(lSmooth1->GetY()[lSmooth1->GetN()-iX-1]);} //if(i0 == 1) {pXSmooth1.push_back(lSmooth1->GetX()[0]); pYSmooth1.push_back(lSmooth1->GetY()[0]);} TGraph *pSmoothShape = new TGraph(pXSmooth.size() ,&pXSmooth [0],&pYSmooth [0]); TGraph *pSmoothShape1 = new TGraph(pXSmooth1.size(),&pXSmooth1[0],&pYSmooth1[0]); if(i0 == 1) {TLine *lLine = new TLine(pXSmooth1[0],pYSmooth1[0],pXSmooth1[pXSmooth1.size()-1],pYSmooth1[pYSmooth1.size()-1]); lLine->Draw();} pSmoothShape1->SetLineColor(kBlack); pSmoothShape1->SetLineWidth(2); pSmoothShape->SetFillColor(kGreen+i0*2); pSmoothShape->SetFillStyle(3001); pSmoothShape->Draw("lf"); pSmoothShape1->Draw("l"); if(i0 == 0) lL->AddEntry(lTotal,"95% CL","lf"); if(i0 == 1) lL->AddEntry(lTotal,"68% CL","lf"); } lL->AddEntry(lSecond,"BestFit","p"); lSecond->Draw("lp"); lL->Draw(); std::string masslabel = "m_{H}"; double mass = 125; TString label = TString::Format("%s = 135 GeV", masslabel.c_str());//, 125.); TPaveText* textlabel = new TPaveText(0.18, 0.81, 0.50, 0.90, "NDC"); textlabel->SetBorderSize( 0 ); textlabel->SetFillStyle ( 0 ); textlabel->SetTextAlign ( 12 ); textlabel->SetTextSize (0.04 ); textlabel->SetTextColor ( 1 ); textlabel->SetTextFont ( 62 ); textlabel->AddText(label); //textlabel->Draw(); CMSPrelim("Preliminary, H#rightarrow#tau#tau,L = 24.3 fb^{-1}", "", 0.145, 0.835); gPad->RedrawAxis(); lCan->Update(); lCan->SaveAs("cmb+_muvmass.png"); lCan->SaveAs("cmb+_muvmass.pdf"); lCan->SaveAs("cmb+_muvmass.eps"); }
void buildFakeAngTree(const Char_t* outtag, const Float_t timereso, // ns const UInt_t simevts=1, const Float_t thetaOpt=400, // deg const Float_t phiOpt=400, // deg const Float_t coneOpt=400, // deg const UInt_t rseed=23192, const Float_t norm=100.0, // mV const Float_t noise=20.0, // mV const Char_t* outdir="/data/users/cjreed/work/simEvts", const Char_t* infn="/w2/arianna/jtatar/nt.sigtemps.root", const Char_t* geofn="/data/users/cjreed/work/" "BounceStudy/Stn10/" "CampSiteGeometry.root") { // if any of the angles (thetaOpt, phiOpt, coneOpt) > 360, a random // value will be used instead // // expect angles in the Templates tree to be in degrees // // expect the waveforms in the Templates tree to have amplitude 1 TRandom3 rnd(rseed); geof = TFile::Open(geofn); gg = dynamic_cast<TGeoManager*>(geof->Get("CampSite2013")); site = dynamic_cast<const TSnGeoStnSite*>(gg->GetTopVolume()); TVector3 pos[NSnConstants::kNchans], nvec[NSnConstants::kNchans]; for (UChar_t ch=0; ch<NSnConstants::kNchans; ++ch) { site->SetLPDAPosition(ch, pos[ch]); site->SetLPDANormalVec(ch, nvec[ch]); Printf("pos ch%d:",ch); pos[ch].Print(); Printf("normal ch%d:",ch); nvec[ch].Print(); } TArrayD zeros(6); inf = TFile::Open(infn); nnt = dynamic_cast<TTree*>(inf->Get("Templates")); TString infns(infn); TString indir; Int_t fl(0); if (infns.Contains('/')) { fl = infns.Last('/') + 1; indir = infns(0, fl-1); } TString plaininfn = infns(fl, infns.Length()-fl); TString outfn = Form("%s/FakeEvts.%s.%s", outdir, outtag, plaininfn.Data()); outf = TFile::Open(outfn.Data(),"recreate"); outf->cd(); TParameter<Float_t> trp("TimeResolution", timereso); trp.Write(); TParameter<Float_t> nmp("Normalization", norm); nmp.Write(); TParameter<Float_t> nop("NoiseRMS", noise); nop.Write(); TParameter<UInt_t> rsp("RandomSeed", rseed); rsp.Write(); TSnCalWvData* wave = new TSnCalWvData; Float_t eang(0), hang(0), hpf(0), limiter(0), coneang(0); Bool_t bice(kFALSE); nnt->SetBranchAddress("wave.",&wave); nnt->SetBranchAddress("EAng",&eang); nnt->SetBranchAddress("HAng",&hang); nnt->SetBranchAddress("hpf",&hpf); nnt->SetBranchAddress("limiter",&limiter); nnt->SetBranchAddress("coneAng",&coneang); nnt->SetBranchAddress("bIce",&bice); // to look up waveform for EAng, HAng nnt->BuildIndex("EAng + (1000*HAng)","coneAng"); // find the max angles Printf("finding allowed angles..."); std::set<Float_t> Eangs, Hangs, Cangs; const Long64_t nnents = nnt->GetEntries(); for (Long64_t i=0; i<nnents; ++i) { nnt->GetEntry(i); Eangs.insert(eang); Hangs.insert(hang); Cangs.insert(coneang); } #ifdef DEBUG std::set<Float_t>::const_iterator ang, end = Eangs.end(); Printf("EAngs:"); for (ang=Eangs.begin(); ang!=end; ++ang) { Printf("%g",*ang); } Printf("HAngs:"); for (ang=Hangs.begin(), end=Hangs.end(); ang!=end; ++ang) { Printf("%g",*ang); } Printf("ConeAngs:"); for (ang=Cangs.begin(), end=Cangs.end(); ang!=end; ++ang) { Printf("%g",*ang); } #endif Float_t theta(0), phi(0), cone(0); Float_t EAng[NSnConstants::kNchans], HAng[NSnConstants::kNchans]; Float_t CAng(0); TSnCalWvData* evdat = new TSnCalWvData; TSnEventMetadata* meta = new TSnEventMetadata; TSnEventHeader* hdr = new TSnEventHeader; //ot = nnt->CloneTree(0); //ot->SetName("SimTemplEvts"); ot = new TTree("SimTemplEvts","simulated events from templates",1); ot->SetDirectory(outf); ot->Branch("EventMetadata.",&meta); ot->Branch("EventHeader.",&hdr); ot->Branch("EAng",&(EAng[0]),Form("EAng[%hhu]/F",NSnConstants::kNchans)); ot->Branch("HAng",&(HAng[0]),Form("HAng[%hhu]/F",NSnConstants::kNchans)); ot->Branch("CAng",&CAng,"CAng/F"); ot->Branch("theta",&theta,"theta/F"); ot->Branch("phi",&phi,"phi/F"); ot->Branch("NuData.",&evdat); // some useful aliases TString an; for (UChar_t ch=0; ch<NSnConstants::kNchans; ++ch) { // to use as a cut for a particular channel: an = Form("Ch%d",ch); ot->SetAlias(an.Data(), Form("(Iteration$>=(%hhu*%hhu)) && (Iteration$<(%hhu*%hhu))", NSnConstants::kNsamps, ch, NSnConstants::kNsamps, static_cast<UChar_t>(ch+1))); // to use as a variable showing the sample number [0,127] for any chan an = Form("SmpCh%d",ch); ot->SetAlias(an.Data(), Form("Iteration$-%u", static_cast<UInt_t>(ch) *static_cast<UInt_t>(NSnConstants::kNsamps))); // e.g. Draw("RawData.fData:SmpCh2","EventHeader.fNum==21 && Ch2","l") } Printf("generating events..."); TStopwatch timer; timer.Start(); for (UInt_t i=0; i<simevts; ++i) { if ( (i%1000)==0 ) { fprintf(stderr,"Processing %u/%u ... \r",i,simevts); } // choose angles theta = (thetaOpt>360.) ? TMath::ACos( rnd.Uniform(-1.0, 0.0) ) : thetaOpt * TMath::DegToRad(); phi = (phiOpt>360.) ? rnd.Uniform(0.0, TMath::TwoPi()) : phiOpt * TMath::DegToRad(); cone = (coneOpt>360.) ? rnd.Uniform(*(Cangs.begin()), *(Cangs.rbegin())) : coneOpt; // leave this one in degrees (as in the tree) CAng = findNearestAllowedAngle(Cangs, cone); #ifdef DEBUG Printf("--- theta=%g, phi=%g, cone=%g", theta*TMath::RadToDeg(), phi*TMath::RadToDeg(), cone); #endif // calculate channel shifts TArrayD pwdt = NSnChanCorl::GetPlaneWaveOffsets(theta, phi, zeros, pos, kNgTopFirn); TVector3 dir; dir.SetMagThetaPhi(1.0, theta, phi); #ifdef DEBUG TObjArray graphs; graphs.SetOwner(kTRUE); TCanvas* c1 = new TCanvas("c1","c1",800,700); c1->Divide(2,2); #endif for (UChar_t ch=0; ch<NSnConstants::kNchans; ++ch) { // look up the EAng, fhang for this antenna Float_t feang(0), fhang(0); findEangHang(nvec[ch], dir, feang, fhang); feang = TMath::Abs(TVector2::Phi_mpi_pi(feang)); fhang = TMath::Abs(TVector2::Phi_mpi_pi(fhang)); feang *= TMath::RadToDeg(); fhang *= TMath::RadToDeg(); // find closest allowed angle EAng[ch] = findNearestAllowedAngle(Eangs, feang); HAng[ch] = findNearestAllowedAngle(Hangs, fhang); const Long64_t ni = nnt->GetEntryNumberWithIndex(EAng[ch] + (1000*HAng[ch]), CAng); #ifdef DEBUG Printf("EAng=%g (%g), HAng=%g (%g), CAng=%g, ni=%lld", EAng[ch],feang,HAng[ch],fhang,CAng,ni); #endif if (ni>-1) { nnt->GetEntry(ni); #ifdef DEBUG c1->cd(ch+1); TGraph* och = wave->NewGraphForChan(0, kTRUE); const Int_t ochnp = och->GetN(); Double_t* ochy = och->GetY(); for (Int_t k=0; k<ochnp; ++k, ++ochy) { *ochy *= norm; } graphs.Add(och); och->SetLineColor(kBlack); och->SetMarkerColor(kBlack); och->SetMarkerStyle(7); och->Draw("apl"); #endif // first calculate the shift between chans due to the angle // ch0 is always unshifted; other chans shifted w.r.t. ch0 // jitter the shift by the specified timing resolution const Double_t shift = rnd.Gaus( (ch==0) ? 0.0 : -pwdt.At( TSnRecoChanOffsets::IndexFor(ch, 0) ), timereso); // get a graph of the waveform // data only in channel 0 of the template TGraph* gch = wave->NewGraphForChan(0, kTRUE); // "fit" the graph with an spline interpolation TSpline3* gsp = new TSpline3("stmp", gch); // evaluate the spline at the new sample positions // (shifted, but NOT wrapped) // and save that into the event data waveform Float_t* d = evdat->GetData(ch); const Float_t tstep = 1.0 / NSnConstants::kSampRate; const Float_t tlast = static_cast<Float_t>(NSnConstants::kNsamps-1) / NSnConstants::kSampRate; Float_t xloc = shift; for (UChar_t s=0; s<NSnConstants::kNsamps; ++s, ++d, xloc+=tstep) { if ( (xloc<0.0) || (xloc>=tlast) ) { *d = 0.0; } else { *d = gsp->Eval( xloc ); } } #ifdef DEBUG Printf("ch%hhu: shift=%g, dt=%g", ch, shift, (ch==0) ? 0.0 : pwdt.At( TSnRecoChanOffsets::IndexFor(ch, 0) )); TGraph* fch = evdat->NewGraphForChan(ch, kTRUE); Double_t* y = gch->GetY(); Double_t* fy = fch->GetY(); for (UChar_t s=0; s<NSnConstants::kNsamps; ++s, ++y, ++fy) { *y *= norm; *fy *= norm; } gch->SetLineColor(kRed+1); gch->SetMarkerColor(kRed+1); gch->SetMarkerStyle(7); gch->Draw("pl"); delete gsp; gsp = new TSpline3("stmp",gch); gsp->SetLineColor(kAzure-6); gsp->SetMarkerColor(kAzure-6); gsp->SetMarkerStyle(7); gsp->Draw("pl same"); graphs.Add(fch); fch->SetLineColor(kOrange+7); fch->SetMarkerColor(kOrange+7); fch->SetMarkerStyle(7); fch->Draw("pl"); #endif d = evdat->GetData(ch); // finally add noise to the waveform for (UChar_t s=0; s<NSnConstants::kNsamps; ++s, ++d) { *d = rnd.Gaus( (*d) * norm, noise ); } #ifdef DEBUG TGraph* nch = evdat->NewGraphForChan(ch, kTRUE); graphs.Add(nch); nch->SetLineColor(kGreen+2); nch->SetMarkerColor(kGreen+2); nch->SetMarkerStyle(7); nch->Draw("pl"); #endif // cleanup #ifdef DEBUG graphs.Add(gch); graphs.Add(gsp); #else delete gch; delete gsp; #endif } } // end channel loop #ifdef DEBUG TObject* o(0); while ( (o=c1->WaitPrimitive())!=0 ) { gSystem->ProcessEvents(); } delete c1; #endif // save this event ot->Fill(); } // end event loop fprintf(stderr,"\n"); timer.Stop(); Printf("Finished generating events in:"); timer.Print(); outf->Write(); Printf("Wrote [%s]",outf->GetName()); delete outf; outf=0; // close file }
void disceff(TString filename) { gROOT->SetStyle("Plain"); TString cmssw; // 167 cmssw = "$3.1.0_pre9$"; TFile *f = TFile::Open(filename); std::vector< TString > taggers; taggers.push_back( "TC2" ); taggers.push_back( "TC3" ); taggers.push_back( "TP" ); taggers.push_back( "BTP" ); taggers.push_back( "SSV" ); taggers.push_back( "CSV" ); taggers.push_back( "MSV" ); taggers.push_back( "SMT" ); taggers.push_back( "SETbyIP3d" ); taggers.push_back( "SETbyPt" ); taggers.push_back( "SMTbyIP3d" ); taggers.push_back( "SMTbyPt" ); std::vector< TString > discriminators; for ( size_t itagger = 0; itagger < taggers.size(); ++itagger ) { discriminators.push_back( "disc"+taggers[itagger]+"_udsg" ); } // discriminators.push_back( "discTC3_udsg" ); // discriminators.push_back( "discTP_udsg" ); const int dim=taggers.size(); TCanvas *cv[dim]; TMultiGraph* mg[dim]; for ( size_t itagger = 0; itagger < taggers.size(); ++itagger ) { TString tag = "g"+taggers[itagger]+"_udsg"; TString tagb = "g"+taggers[itagger]+"_b"; TString tagc = "g"+taggers[itagger]+"_c"; cv[itagger] = new TCanvas("cv_"+taggers[itagger],"cv_"+taggers[itagger],700,700); TLegend *legend0 = new TLegend(0.68,0.70,0.88,0.90); TGraphErrors *agraph = (TGraphErrors*) gDirectory->Get("BTagPATAnalyzer"+taggers[itagger]+"/"+taggers[itagger]+"/"+tag); TGraphErrors *bgraph = (TGraphErrors*) gDirectory->Get("BTagPATAnalyzer"+taggers[itagger]+"/"+taggers[itagger]+"/"+tagb); TGraphErrors *cgraph = (TGraphErrors*) gDirectory->Get("BTagPATAnalyzer"+taggers[itagger]+"/"+taggers[itagger]+"/"+tagc); TGraph *dgraph = (TGraph*) gDirectory->Get("BTagPATAnalyzer"+taggers[itagger]+"/"+taggers[itagger]+"/"+discriminators[itagger]); TGraph *bvsdgraph = new TGraph(dgraph->GetN(),dgraph->GetY(),bgraph->GetY()); TGraph *cvsdgraph = new TGraph(dgraph->GetN(),dgraph->GetY(),cgraph->GetY()); TGraph *lvsdgraph = new TGraph(dgraph->GetN(),dgraph->GetY(),agraph->GetY()); TGraph *udsgvsdgraph = new TGraph(dgraph->GetN(),dgraph->GetY(),dgraph->GetX()); dgraph->Sort(); // udsgvsdgraph->Sort(); // udsgvsdgraph->SetLineColor(1); // legend0 -> AddEntry(udsgvsdgraph,"control","l"); lvsdgraph->Sort(); lvsdgraph->SetLineColor(2); legend0 -> AddEntry(lvsdgraph,tag,"l"); cvsdgraph->Sort(); cvsdgraph->SetLineColor(3); legend0 -> AddEntry(cvsdgraph,tagc,"l"); bvsdgraph->Sort(); bvsdgraph->SetLineColor(4); legend0 -> AddEntry(bvsdgraph,tagb,"l"); mg[itagger]= new TMultiGraph(); // mg[itagger]->Add(udsgvsdgraph); mg[itagger]->Add(lvsdgraph); mg[itagger]->Add(cvsdgraph); mg[itagger]->Add(bvsdgraph); // mg[itagger]->Add(dgraph); cv[itagger]->cd(1); mg[itagger]->Draw("ALP"); mg[itagger]->GetYaxis()->SetTitle("eff"); mg[itagger]->GetXaxis()->SetTitle("discriminant"); legend0 -> Draw(); cv[itagger]->Update(); cv[itagger]->cd(0); cv[itagger]-> Print ("BTagPATeff_vs_disc"+taggers[itagger]+".eps"); cv[itagger]-> Print ("BTagPATeff_vs_disc"+taggers[itagger]+".ps"); TGraphErrors *g = new TGraphErrors(agraph->GetN(),agraph->GetY(),agraph->GetX(),agraph->GetEY(),agraph->GetEX()); g->Sort(); g->SetLineColor(itagger+1); std::cout << " Tagger: " << tag << std::endl; std::cout << " Loose(10%): " << " cut > " << std::setprecision(4) << dgraph->Eval(0.1) << " b-eff = " << g->Eval(0.1) << std::endl; std::cout << " Medium(1%): " << " cut > " << std::setprecision(4) << dgraph->Eval(0.01) << " b-eff = " << g->Eval(0.01) << std::endl; std::cout << " Tight(0.1%) = " << " cut > " << std::setprecision(4) << dgraph->Eval(0.001) << " b-eff = " << g->Eval(0.001) << std::endl; }//end for }
void integrated_lumi(Bool_t goodOnly=0){ nGoodRuns+= nGoodRuns15f; nGoodRuns+= nGoodRuns15h; nGoodRuns+= nGoodRuns15i; nGoodRuns+= nGoodRuns15j; nGoodRuns+= nGoodRuns15l; Int_t j=0; for (Int_t i=0;i<nGoodRuns15f;i++) goodRuns[j++]=goodRuns15f[i]; for (Int_t i=0;i<nGoodRuns15h;i++) goodRuns[j++]=goodRuns15h[i]; // for (Int_t i=0;i<nGoodRuns15i_badIR;i++) goodRuns[j++]=goodRuns15i_badIR[i]; // for (Int_t i=0;i<nGoodRuns15i_badSPD;i++) goodRuns[j++]=goodRuns15i_badSPD[i]; for (Int_t i=0;i<nGoodRuns15i;i++) goodRuns[j++]=goodRuns15i[i]; for (Int_t i=0;i<nGoodRuns15j;i++) goodRuns[j++]=goodRuns15j[i]; for (Int_t i=0;i<nGoodRuns15l;i++) goodRuns[j++]=goodRuns15l[i]; gStyle->SetPadTopMargin(0.01); gStyle->SetPadRightMargin(0.01); gStyle->SetPadBottomMargin(0.06); gStyle->SetPadLeftMargin(0.13); TGaxis::SetMaxDigits(3); gStyle->SetOptTitle(1); gStyle->SetTitleOffset(1.6,"Y"); gStyle->SetOptStat(0); TLatex* latex = new TLatex(); latex->SetTextSize(0.05); latex->SetTextFont(42); latex->SetTextAlign(11); latex->SetNDC(); t = new TChain("trending"); t->AddFile("trending.root"); classes = new TObjArray(); partition = new TObjString(); lhcState = new TObjString(); lhcPeriod = new TObjString(); activeDetectors = new TObjString(); t->SetBranchAddress("run",&run); t->SetBranchAddress("fill",&fill); t->SetBranchAddress("classes",&classes); t->SetBranchAddress("class_l2a",&class_l2a); t->SetBranchAddress("class_lumi",&class_lumi); t->SetBranchAddress("timeStart",&timeStart); t->SetBranchAddress("timeEnd",&timeEnd); t->SetBranchAddress("partition",&partition); t->SetBranchAddress("lhcState",&lhcState); t->SetBranchAddress("lhcPeriod",&lhcPeriod); t->SetBranchAddress("activeDetectors",&activeDetectors); TGraph* gINT = GetStat("CINT7-B-NOPF-CENT",1,goodOnly); TGraph* gMUL = GetStat("CMUL7-B-NOPF-MUFAST",1,goodOnly); TGraph* gV0M = GetStat("CVHMV0M-B-NOPF-CENTNOTRD",1,goodOnly); TGraph* gSH2 = GetStat("CVHMSH2-B-NOPF-CENTNOTRD",1,goodOnly); TGraph* gStatINT = GetStat("CINT7-B-NOPF-CENT",0,goodOnly); TGraph* gStatV0M = GetStat("CVHMV0M-B-NOPF-CENTNOTRD",0,goodOnly); TGraph* gStatSH2 = GetStat("CVHMSH2-B-NOPF-CENTNOTRD",0,goodOnly); TGraph* gStatEMC = GetStat("CEMC7-B-NOPF-CENTNOTRD",0,goodOnly,"PHYSICS_2"); TGraph* gStatDMC = GetStat("CDMC7-B-NOPF-CENTNOTRD",0,goodOnly,"PHYSICS_2"); gMUL->SetLineColor(kBlack); gINT->SetLineColor(kBlue); gV0M->SetLineColor(kMagenta); gSH2->SetLineColor(kRed); gStatV0M->SetLineColor(kMagenta); gStatSH2->SetLineColor(kRed); gStatEMC->SetLineColor(kGray); gStatDMC->SetLineColor(kGreen-2); TCanvas* c1 = new TCanvas("c1","",800,700); Double_t xminLumi = gMUL->GetXaxis()->GetXmin(); Double_t xmaxLumi = gMUL->GetXaxis()->GetXmax(); Double_t ymaxLumi = gMUL->GetYaxis()->GetXmax()*1.1; TH1F* f1 = gPad->DrawFrame(xminLumi,0,xmaxLumi,ymaxLumi); SetFrame(f1); f1->GetYaxis()->SetTitle("Integrated luminosity, pb^{-1}"); f1->GetXaxis()->SetTimeDisplay(1); f1->GetXaxis()->SetTimeFormat("%d %b"); Double_t y = 0.94; latex->DrawLatex(0.18,0.94,"ALICE Performance, pp #sqrt{s} = 13 TeV"); latex->SetTextColor(gINT->GetLineColor()); latex->DrawLatex(0.18,y-=0.07,Form("MB triggers: L = %.3f pb^{-1}",gINT->GetY()[gINT->GetN()-1])); latex->SetTextColor(gV0M->GetLineColor()); latex->DrawLatex(0.18,y-=0.07,Form("V0 HM triggers: L = %.3f pb^{-1}",gV0M->GetY()[gV0M->GetN()-1])); latex->SetTextColor(gSH2->GetLineColor()); latex->DrawLatex(0.18,y-=0.07,Form("SPD HM triggers: L = %.3f pb^{-1}",gSH2->GetY()[gSH2->GetN()-1])); latex->SetTextColor(gMUL->GetLineColor()); latex->DrawLatex(0.18,y-=0.07,Form("Dimuon triggers: L = %.3f pb^{-1}",gMUL->GetY()[gMUL->GetN()-1])); gMUL->Draw(); gINT->Draw(); gV0M->Draw(); gSH2->Draw(); gPad->Print("lumi_dimuon_triggers.png"); TCanvas* c2 = new TCanvas("c2","",800,700); Double_t xminEvents = gStatINT->GetXaxis()->GetXmin(); Double_t xmaxEvents = gStatINT->GetXaxis()->GetXmax(); Double_t ymaxEvents = gStatINT->GetYaxis()->GetXmax()*1.1; TH1F* f2 = gPad->DrawFrame(xminEvents,0,xmaxEvents,ymaxEvents); SetFrame(f2); f2->GetYaxis()->SetTitle("Recorded triggers, 10^{6}"); f2->GetXaxis()->SetTimeDisplay(1); f2->GetXaxis()->SetTimeFormat("%d %b"); gStatINT->Draw(); gStatV0M->Draw(); gStatSH2->Draw(); // gStatDMC->Draw(); // gStatEMC->Draw(); latex->SetTextColor(1); latex->DrawLatex(0.18,0.94,"ALICE Performance, pp #sqrt{s} = 13 TeV"); y = 0.94; latex->SetTextColor(gStatINT->GetLineColor()); latex->DrawLatex(0.18,y-=0.07,Form("MB triggers: %.0fM",gStatINT->GetY()[gStatINT->GetN()-1])); latex->SetTextColor(gStatV0M->GetLineColor()); latex->DrawLatex(0.18,y-=0.07,Form("V0 HM triggers: %.0fM",gStatV0M->GetY()[gStatV0M->GetN()-1])); latex->SetTextColor(gStatSH2->GetLineColor()); latex->DrawLatex(0.18,y-=0.07,Form("SPD HM triggers: %.0fM",gStatSH2->GetY()[gStatSH2->GetN()-1])); // latex->SetTextColor(gStatEMC->GetLineColor()); // latex->DrawLatex(0.18,y-=0.07,Form("EMCAL triggers: %.0fM",gStatEMC->GetY()[gStatDMC->GetN()-1])); // latex->SetTextColor(gStatDMC->GetLineColor()); // latex->DrawLatex(0.18,y-=0.07,Form("DCAL triggers: %.0fM",gStatDMC->GetY()[gStatDMC->GetN()-1])); gPad->Print("stat_mb_triggers.png"); }
void msugraThExcl(TString msugrafile = "msugra_status.txt", TGraph* staulsp=0, TGraph* negmasssq=0, TGraph* noRGE=0, TGraph* noEWSB=0, TGraph* tachyons=0) { TTree msugra; msugra.ReadFile(msugrafile); float m0, m12; int status; msugra.SetBranchAddress("m0",&m0); msugra.SetBranchAddress("m12",&m12); msugra.SetBranchAddress("status",&status); TH2D *stat1hist = new TH2D("stat1hist","stat1hist",250,0,5000,100,0,1000); TH2D *stat2hist = new TH2D("stat2hist","stat2hist",250,0,5000,100,0,1000); TH2D *stat3hist = new TH2D("stat3hist","stat3hist",250,0,5000,100,0,1000); TH2D *stat4hist = new TH2D("stat4hist","stat4hist",250,0,5000,100,0,1000); TH2D *stat5hist = new TH2D("stat5hist","stat5hist",250,0,5000,100,0,1000); for(int i=0; i<msugra.GetEntries(); i++) { msugra.GetEntry(i); switch(status) { case 5: stat5hist->Fill(m0-1,m12-1,1); case 3: stat3hist->Fill(m0-1,m12-1,1); case 4: stat4hist->Fill(m0-1,m12-1,1); case 2: stat2hist->Fill(m0-1,m12-1,1); break; case 1: stat1hist->Fill(m0-1,m12-1,1); default: break; } } smoothHisto(stat1hist,3); smoothHisto(stat2hist,3); smoothHisto(stat3hist,3); smoothHisto(stat4hist,3); smoothHisto(stat5hist,3); stat1hist->SetContour(1); stat1hist->SetContourLevel(0,0.5); stat2hist->SetContour(1); stat2hist->SetContourLevel(0,0.5); stat3hist->SetContour(1); stat3hist->SetContourLevel(0,0.5); stat4hist->SetContour(1); stat4hist->SetContourLevel(0,0.5); stat5hist->SetContour(1); stat5hist->SetContourLevel(0,0.5); TCanvas* c = new TCanvas; /// DRAW STAU LSP stat1hist->Draw("contlist"); c->Update(); if (!staulsp) staulsp = new TGraph; TObjArray* conts_1 = (TObjArray*) gROOT->GetListOfSpecials()->FindObject("contours"); TList* cont_1 = (TList*) conts_1->At(0); TGraph* mystaulsp = (TGraph*) cont_1->At(1); for(int pt=0; pt<mystaulsp->GetN(); pt++) { staulsp->SetPoint(pt,mystaulsp->GetX()[pt],mystaulsp->GetY()[pt]); } staulsp->SetPoint(staulsp->GetN(),200,1010); staulsp->SetPoint(staulsp->GetN(),-10,1010); staulsp->SetPoint(staulsp->GetN(),-10,-10); //staulsp->SetFillColor(kBlue); staulsp->SetFillColor(kMagenta-10); staulsp->SetLineColor(kGray+2); staulsp->SetLineWidth(2); /// DRAW -VE MASS SQUARED stat2hist->Draw("contlist"); c->Update(); if (!negmasssq) negmasssq = new TGraph; TObjArray* conts_2 = (TObjArray*) gROOT->GetListOfSpecials()->FindObject("contours"); TList* cont_2 = (TList*) conts_2->At(0); TGraph* mynegmasssq = (TGraph*) cont_2->At(0); for(int pt=0; pt<mynegmasssq->GetN(); pt++) { negmasssq->SetPoint(pt,mynegmasssq->GetX()[pt],mynegmasssq->GetY()[pt]); } negmasssq->SetPoint(negmasssq->GetN(),5010,1010); negmasssq->SetPoint(negmasssq->GetN(),5010,-10); negmasssq->SetPoint(negmasssq->GetN(),-10,-10); negmasssq->SetFillColor(kAzure+1); negmasssq->SetLineColor(kGray+2); negmasssq->SetLineWidth(2); /// DRAW NO RGE stat4hist->Draw("contlist"); c->Update(); if(!noRGE) noRGE = new TGraph; TObjArray* conts_4 = (TObjArray*) gROOT->GetListOfSpecials()->FindObject("contours"); TList* cont_4 = (TList*) conts_4->At(0); TGraph* mynoRGE = (TGraph*) cont_4->At(1); mynoRGE->SetPoint(mynoRGE->GetN(),5010,875); mynoRGE->SetPoint(mynoRGE->GetN(),5010,-10); for(int pt=0; pt<mynoRGE->GetN(); pt++) { noRGE->SetPoint(pt,mynoRGE->GetX()[pt],mynoRGE->GetY()[pt]); } noRGE->SetFillColor(kGreen-6); noRGE->SetLineColor(kGray+2); noRGE->SetLineWidth(1); stat3hist->Draw("contlist"); c->Update(); /// DRAW NO EWSB if(!noEWSB) noEWSB = new TGraph; TObjArray* conts_3 = (TObjArray*) gROOT->GetListOfSpecials()->FindObject("contours"); TList* cont_3 = (TList*) conts_3->At(0); TGraph* mynoEWSB = (TGraph*) cont_3->At(1); mynoEWSB->SetPoint(mynoEWSB->GetN(),5010,810); mynoEWSB->SetPoint(mynoEWSB->GetN(),5010,-10); mynoEWSB->SetPoint(mynoEWSB->GetN(),500,-10); for(int pt=0; pt<mynoEWSB->GetN(); pt++) { noEWSB->SetPoint(pt,mynoEWSB->GetX()[pt],mynoEWSB->GetY()[pt]); } noEWSB->SetFillColor(kMagenta-10); //noEWSB->SetFillColor(kGreen+2); noEWSB->SetLineColor(kGray+2); noEWSB->SetLineWidth(1); stat5hist->Draw("contlist"); c->Update(); /// DRAW TACHYONS if(!tachyons) tachyons = new TGraph; TObjArray* conts_5 = (TObjArray*) gROOT->GetListOfSpecials()->FindObject("contours"); TList* cont_5 = (TList*) conts_5->At(0); TGraph* mytachyons = (TGraph*) cont_5->At(0); mytachyons->SetPoint(mytachyons->GetN(),350,-10); mytachyons->SetPoint(mytachyons->GetN(),-10,-10); mytachyons->SetPoint(mytachyons->GetN(),-10,80); for(int pt=0; pt<mytachyons->GetN(); pt++) { tachyons->SetPoint(pt,mytachyons->GetX()[pt],mytachyons->GetY()[pt]); } tachyons->SetFillColor(kRed); tachyons->SetLineColor(kGray+2); tachyons->SetLineWidth(1); TH2D frame("frame","frame",10,0,5010,10,0,1000); frame.Draw(); staulsp->Draw("f"); negmasssq->Draw("f"); noRGE->Draw("f"); noRGE->Draw("l"); noEWSB->Draw("f"); noEWSB->Draw("l"); tachyons->Draw("f"); tachyons->Draw("l"); negmasssq->Draw("l"); staulsp->Draw("l"); c->RedrawAxis(); }