void PlotGain( Char_t *fname, Char_t *hname0, Char_t *option, UInt_t pCbc = 0, UInt_t color = 4 ){ TH1F *h0 = new TH1F( hname0, ";V_{CTH} middle point pedestal subtracted;count", 180, -80, 0 ); TFile *fin = new TFile( fname ); TFile *fped = new TFile( "/Users/kirika/Work/CMS_UPGRADE/eps_calib/VCthScanCalibrationResult.root" ); for( UInt_t i=0; i<254; i++ ){ TString hname = Form( "h_00_%02d_%03d", pCbc, i ); TH1F *h = (TH1F *) fin->Get( hname ); TF1 *func = h->GetFunction( Form("f_%s", hname.Data() ) ); h = (TH1F *) fped->Get( hname ); TF1 *func0 = h->GetFunction( Form("f_%s", hname.Data() ) ); h0->Fill( func->GetParameter(0) - func0->GetParameter(0) ); } h0->Draw( option ); }
vector<double> one_fit(bool do_fit) { TH1F* h = new TH1F("h","h", 20, -10, 10); h->FillRandom("gaus"); vector<double> ret; if (do_fit) { h->Fit("gaus",""); TF1* g = h->GetFunction("gaus"); h->Draw(); canvas->Modified(); canvas->Update(); for (int ind=0; ind < 3; ++ind) { ret.push_back(g->GetParameter(ind)); } } else { for (int ind=0; ind < 3; ++ind) { ret.push_back(0.0); } } ret.push_back(h->GetMean()); ret.push_back(h->GetRMS()); delete h; return ret; }
void PlotE( Char_t *fname, UInt_t pBeId = 0, UInt_t pFeId = 0, UInt_t pCbc = 0, UInt_t color = 4 ){ TH1F *h0 = new TH1F("Noise", ";% ;count", 100, 0, 0.2 ); TFile *fin = new TFile( fname ); TFile *fped = new TFile( "/Users/kirika/Work/CMS_UPGRADE/eps_calib/VCthScanCalibrationResult.root" ); for( UInt_t i=0; i<254; i++ ){ TString hname = Form( "h_%02d_%02d_%02d_%03d", pBeId, pFeId, pCbc, i ); TH1F *h = (TH1F *) fin->Get( hname ); TF1 *func = h->GetFunction( Form("f_%s", hname.Data() ) ); h = (TH1F *) fped->Get( hname ); TF1 *func0 = h->GetFunction( Form("f_%s", hname.Data() ) ); h0->Fill( func->GetParameter(1) / ( func0->GetParameter(0) - func->GetParameter(0) ) ); } h0->Draw(); }
void plotMuFromToys(std::string inputFile, std::string selectString="fit_status==0"){ // Some Global preferences gROOT->SetStyle("Plain"); gSystem->Load("$CMSSW_BASE/lib/$SCRAM_ARCH/libHiggsAnalysisCombinedLimit.so"); gStyle->SetOptFit(1111); gStyle->SetOptStat(1111); gStyle->SetPalette(1,0); TFile *fi_ = TFile::Open(inputFile.c_str()); TTree *tree_sb = (TTree*) fi_->Get("tree_fit_sb"); TH1F *mures = new TH1F("mures","",25,-2.,2.); mures->SetLineColor(kBlue+3); mures->SetMarkerStyle(kOpenCircle); mures->SetLineWidth(2); mures->GetXaxis()->SetTitle("#mu - 1"); mures->GetYaxis()->SetTitle(Form("no toys (%d total)",int(tree_sb->GetEntries()))); mures->GetYaxis()->SetTitleOffset(1.05); mures->GetXaxis()->SetTitleOffset(0.9); mures->GetYaxis()->SetTitleSize(0.05); mures->GetXaxis()->SetTitleSize(0.05); TCanvas *c = new TCanvas("c","",960,800); tree_sb->Draw("mu>>mures",selectString.c_str()); mures->Fit("gaus"); mures->GetFunction("gaus")->SetLineColor(kCyan+3); mures->Draw("pe1"); c->SaveAs("mlfit/mu_residual.pdf"); }
void PlotScurveGroup( Char_t *fname, UInt_t pBeId = 0, UInt_t pFeId = 0, UInt_t pCbc = 0, UInt_t pGroup = 0, UInt_t color = 4 ){ TFile *fin = new TFile( fname ); UInt_t cCh1(0); for( int i=0; i < 16; i++ ){ cCh1 = i * 16 + pGroup*2; for( int j = cCh1; j < cCh1 + 2; j++ ){ if( j < 254 ){ TString hname = Form( "h_%02d_%02d_%02d_%03d", pBeId, pFeId, pCbc, j ); TH1F *h = (TH1F *) fin->Get( hname ); h->GetXaxis()->SetRangeUser( 50, 170 ); h->SetLineColor(1); h->SetMarkerColor(1); h->SetTitle( Form( "FE(00),CBC(%02d); VCth; Rate", pCbc ) ); TF1 *func = h->GetFunction( Form("f_%s", hname.Data() ) ); if( i == 0 ) h->Draw(); else h->Draw("same"); } } } TString cPadName( fname ); cPadName.ReplaceAll( ".root", Form( "G%d.png", pGroup ) ); gPad->Print( cPadName ); }
double Alignment::Fit(TH1F &beta){ double xmin=beta.GetXaxis()->GetXmin(); double xmax=beta.GetXaxis()->GetXmax(); double prev_norma=-1; double norma,mean,sigma; for(int i=0;i<10;i++){ if(xmin>beta.GetXaxis()->GetXmax() || xmax<beta.GetXaxis()->GetXmin() || xmin>=xmax) return 0; // Fail // beta.Fit("gaus","0q","",xmin,xmax); beta.Fit("gaus","0q","",xmin,xmax); TF1 *func=beta.GetFunction("gaus"); norma=func->GetParameter(0); mean=func->GetParameter(1); sigma=fabs(func->GetParameter(2)); xmin=mean-1.0*sigma; xmax=mean+2.0*sigma; if(fabs(norma-prev_norma)<1e-3) break; prev_norma=norma; } return -norma; // This have to be minimized }
pair <float,float> find_interpolated_point(TH2F* histo, int xbin, bool mSUGRA=true) { int minaccept=4; TCanvas *flatcan = new TCanvas("flatcan","flatcan"); stringstream histoname; histoname << "exclusion shape for x bin " << xbin; TH1F *flathisto; if(mSUGRA) flathisto = new TH1F("flat",histoname.str().c_str(),histo->GetNbinsY(),histo->GetYaxis()->GetBinLowEdge(1),histo->GetYaxis()->GetBinLowEdge(histo->GetNbinsY())+histo->GetYaxis()->GetBinWidth(histo->GetNbinsY())); else flathisto = new TH1F("flat",histoname.str().c_str(),histo->GetNbinsX(),histo->GetXaxis()->GetBinLowEdge(1),histo->GetXaxis()->GetBinLowEdge(histo->GetNbinsX())+histo->GetXaxis()->GetBinWidth(histo->GetNbinsX())); int acceptedpoints=0; int nbins=histo->GetNbinsY(); if(!mSUGRA) histo->GetNbinsX(); for(int i=1;i<nbins;i++) { float value=0; if(i<=nbins-2) value=((1/3.0)*(histo->GetBinContent(xbin,i)+histo->GetBinContent(xbin+1,i)+histo->GetBinContent(xbin+2,i))); if(i==nbins-1) value=((1/2.0)*(histo->GetBinContent(xbin,i)+histo->GetBinContent(xbin,i+1))); if(i==nbins) value=(histo->GetBinContent(xbin,i)); if(value<20&&value>0) { flathisto->SetBinContent(i,value); flathisto->SetBinError(i,TMath::Sqrt(value)); acceptedpoints++; } } float pointone=-100; TLine *excluded; if(acceptedpoints>minaccept) { flathisto->Fit("expo","Q"); TF1 *fitfunc = (TF1*)flathisto->GetFunction("expo"); pointone=-(fitfunc->GetParameter(0)/fitfunc->GetParameter(1)); excluded=new TLine(pointone,0,pointone,10); } pair <float,float> anything; anything.first=histo->GetXaxis()->GetBinCenter(xbin); anything.second=pointone; stringstream flatname; flathisto->GetYaxis()->SetRangeUser(0,10); flathisto->Draw(); if(acceptedpoints>minaccept) excluded->SetLineColor(kGreen); if(acceptedpoints>minaccept) excluded->SetLineStyle(2); if(acceptedpoints>minaccept) excluded->SetLineWidth(2); if(acceptedpoints>minaccept) excluded->Draw("same"); flatname << "Limits/partials/partial_" << xbin << "___" << histo->GetName() << ".png"; if(draweachone) CompleteSave(flatcan,flatname.str()); delete flatcan; delete flathisto; return anything; }
// --------------------------------- // void ClosureTest() { setTDRStyle(); gROOT->ForceStyle(); // input files // TFile* mc_smeared_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final_ClosureSecondHalf_v2.root", "READ"); /* TFile* mc_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneEE3C_Flat_herwigpp_final_nominal_v2.root", "READ"); TFile* mc_smeared_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final_ClosureFirstHalf_v2.root", "READ");*/ /*TFile* mc_smeared_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneEE3C_Flat_herwigpp_final_nominal_v4.root", "READ"); TFile* mc_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final_nominal_v4.root", "READ");*/ //TFile* mc_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final.root", "READ"); TFile* mc_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final_ClosureFirstHalf_NotSmeared_v4.root", "READ"); TFile* mc_smeared_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final_ClosureSecondHalf_Smeared_v4.root", "READ"); TString suffix = "_PythiaSmearedVsPythia_v4"; // TString suffix = "_HerwigVsPythia"; // TString suffix = "_PythiaVsHerwig_v4"; // define helper histos TH1F *tmp_mcsmeared = new TH1F(); TH1F *tmp_mc = new TH1F(); TH1F *tmp_gensmeared = new TH1F(); TH1F *tmp_gen = new TH1F(); tmp_mcsmeared->Sumw2(); tmp_mc->Sumw2(); tmp_gensmeared->Sumw2(); tmp_gen->Sumw2(); std::vector<float> alpha; alpha.push_back(0.1); alpha.push_back(0.125); alpha.push_back(0.15); alpha.push_back(0.175); alpha.push_back(0.20); alpha.push_back(0.225); alpha.push_back(0.25); float pt_bins[14] = {62, 107, 175, 205, 242, 270, 310, 335, 379, 410, 467, 600, 1000, 2000}; // float eta_bins[6] = {0, 0.5, 1.1, 1.7, 2.3, 5.0}; float eta_bins[8] = {0, 0.5, 1.1, 1.7, 2.3, 2.8, 3.2, 5.0}; TH1F *extrapolated_mcsmeared = new TH1F("extrapolated_mcsmeared", "extrapolated_mcsmeared", 13, pt_bins); TH1F *extrapolated_mc = new TH1F("extrapolated_mc", "extrapolated_mc", 13, pt_bins); TH1F *extrapolated_gen = new TH1F("extrapolated_gen", "extrapolated_gen", 13, pt_bins); TH1F *extrapolated_mcsmeared_with_pli = new TH1F("extrapolated_mcsmeared_with_pli", "extrapolated_mcsmeared", 13, pt_bins); TH1F *extrapolated_mc_with_pli = new TH1F("extrapolated_mc_with_pli", "extrapolated_mc", 13, pt_bins); TH1F* RatioVsEta = new TH1F("RatioVsEta", "", 7, eta_bins); TH1F* RatioVsEta_with_pli = new TH1F("RatioVsEta_with_pli", "", 7, eta_bins); extrapolated_mcsmeared->Sumw2(); extrapolated_mc->Sumw2(); extrapolated_gen->Sumw2(); extrapolated_mcsmeared_with_pli->Sumw2(); extrapolated_mc_with_pli->Sumw2(); RatioVsEta->Sumw2(); RatioVsEta_with_pli->Sumw2(); // how much should be truncated? double yq_IQW[2],xq_IQW[2]; xq_IQW[0] = 0.0; xq_IQW[1] = 0.985; //// get asymmetry histos for(int ieta=0; ieta < 5; ++ieta){ // cout << "eta Bin: " << ieta << endl; extrapolated_mcsmeared->Reset(); extrapolated_mc->Reset(); extrapolated_gen->Reset(); extrapolated_mcsmeared_with_pli->Reset(); extrapolated_mc_with_pli->Reset(); for(int ipt=0; ipt < 13; ++ipt){ // cout << "pt Bin: " << ipt << endl; std::vector<double> x,x_e,MCy,MCy_e,Datay,Datay_e,Geny,Geny_e; for(int ialpha=0; ialpha < 7; ++ialpha){ //for(int ialpha=0; ialpha < 3; ++ialpha){ // cout << "alpha Bin: " << ialpha << endl; TString hname = Form("Pt%i_eta%i_alpha%i", ipt, ieta, ialpha); TString hname_gen = Form("GenAsymm_Pt%i_eta%i_alpha%i", ipt, ieta, ialpha); // cout << "hname: " << hname << endl; mc_file->cd(); tmp_mc = 0; tmp_gen = 0; tmp_mc = (TH1F*) gDirectory->FindObjectAny(hname); tmp_gen = (TH1F*) gDirectory->FindObjectAny(hname_gen); mc_smeared_file->cd(); tmp_mcsmeared = 0; tmp_gensmeared = 0; tmp_mcsmeared = (TH1F*) gDirectory->FindObjectAny(hname); tmp_gensmeared = (TH1F*) gDirectory->FindObjectAny(hname_gen); x.push_back(alpha.at(ialpha)); x_e.push_back(0.); double mc_width = GetAsymmWidth(tmp_mc, xq_IQW, yq_IQW); double mc_width_err = GetAsymmWidth(tmp_mc, xq_IQW, yq_IQW)/(TMath::Sqrt(2*tmp_mc->GetEffectiveEntries())); double data_width = GetAsymmWidth(tmp_mcsmeared, xq_IQW, yq_IQW); double data_width_err = GetAsymmWidth(tmp_mcsmeared, xq_IQW, yq_IQW)/(TMath::Sqrt(2*tmp_mcsmeared->GetEffectiveEntries())); double gen_width = GetAsymmWidth(tmp_gen, xq_IQW, yq_IQW); double gen_width_err = GetAsymmWidth(tmp_gen, xq_IQW, yq_IQW)/(TMath::Sqrt(2*tmp_gen->GetEffectiveEntries())); MCy.push_back( mc_width ); MCy_e.push_back( mc_width_err ); Datay.push_back( data_width ); Datay_e.push_back( data_width_err ); Geny.push_back( gen_width ); Geny_e.push_back( gen_width_err ); tmp_mc->Scale(tmp_mcsmeared->Integral()/tmp_mc->Integral()); tmp_gen->Scale(tmp_gensmeared->Integral()/tmp_gen->Integral()); // draw asymmetry histos TCanvas *c5 = new TCanvas("c5", "", 600, 600); c5->SetLogy(); // tmp_mc->GetYaxis()->SetRangeUser(0.1, 100.*tmp_mc->GetMaximum()); // tmp_mc->GetXaxis()->SetTitle("(p_{T,1} - p_{T,2})/(p_{T,1} + p_{T,2})"); tmp_mc->GetXaxis()->SetTitle("|A|"); tmp_mc->GetYaxis()->SetTitle("Events"); tmp_mc->SetLineColor(30); // tmp_mc->SetFillColor(30); tmp_mc->Rebin(10); tmp_mc->Draw("hist"); // gauss_mc->Draw("same"); tmp_mcsmeared->Rebin(10); tmp_mcsmeared->SetMarkerStyle(20); tmp_mcsmeared->Draw("histsame"); TPaveText *label = util::LabelFactory::createPaveTextWithOffset(3,0.8,0.01); label->AddText("Anti-k_{T} (R=0.5) PFCHS Jets"); label->AddText( Form("%0.1f #leq |#eta| #leq %0.1f, %3.0f #leq p_{T}^{ave} [GeV] #leq %3.0f", eta_bins[ieta], eta_bins[ieta+1], pt_bins[ipt], pt_bins[ipt+1]) ); label->AddText( Form("#alpha #leq %0.3f", alpha.at(ialpha)) ); label->Draw("same"); TLegend* leg1 = util::LabelFactory::createLegendColWithOffset(2,0.65,0.2); leg1->AddEntry(tmp_mcsmeared,"Herwig","L"); leg1->AddEntry(tmp_mc,"Pythia","L"); leg1->Draw(); if(ieta == 0 && ipt == 0 && ialpha == 0 ) c5->Print("ClosureTest/AsymmHistos" + suffix + ".eps("); else if(ieta == 4 && ipt == 12 && ialpha == 6) c5->Print("ClosureTest/AsymmHistos" + suffix + ".eps)"); else c5->Print("ClosureTest/AsymmHistos" + suffix + ".eps"); // draw gen-asymmetry histos TCanvas *c5b = new TCanvas("c5b", "", 600, 600); c5b->SetLogy(); // tmp_gen->GetYaxis()->SetRangeUser(0.1, 100.*tmp_gen->GetMaximum()); // tmp_gen->GetXaxis()->SetTitle("(p_{T,1} - p_{T,2})/(p_{T,1} + p_{T,2})"); tmp_gen->GetXaxis()->SetTitle("|A_{gen}|"); tmp_gen->GetYaxis()->SetTitle("Events"); tmp_gen->SetLineColor(30); // tmp_gen->SetFillColor(30); tmp_gen->Rebin(10); tmp_gen->Draw("hist"); // gauss_gen->Draw("same"); tmp_gensmeared->Rebin(10); tmp_gensmeared->SetMarkerStyle(20); tmp_gensmeared->Draw("histsame"); TPaveText *label2 = util::LabelFactory::createPaveTextWithOffset(3,0.8,0.01); label2->AddText("Anti-k_{T} (R=0.5) PFCHS Jets"); label2->AddText( Form("%0.1f #leq |#eta| #leq %0.1f, %3.0f #leq p_{T}^{ave} [GeV] #leq %3.0f", eta_bins[ieta], eta_bins[ieta+1], pt_bins[ipt], pt_bins[ipt+1]) ); label2->AddText( Form("#alpha #leq %0.3f", alpha.at(ialpha)) ); label2->Draw("same"); TLegend* leg2 = util::LabelFactory::createLegendColWithOffset(2,0.65,0.2); leg2->AddEntry(tmp_gensmeared,"Herwig","L"); leg2->AddEntry(tmp_gen,"Pythia","L"); leg2->Draw(); if(ieta == 0 && ipt == 0 && ialpha == 0 ) c5b->Print("ClosureTest/GenAsymmHistos" + suffix + ".eps("); else if(ieta == 4 && ipt == 12 && ialpha == 6) c5b->Print("ClosureTest/GenAsymmHistos" + suffix + ".eps)"); else c5b->Print("ClosureTest/GenAsymmHistos" + suffix + ".eps"); } // Covariance matrices needed for fitting TMatrixD y_cov_mc; TMatrixD y_cov_data; TMatrixD y_cov_gen; y_cov_mc.ResizeTo(alpha.size(), alpha.size()); y_cov_data.ResizeTo(alpha.size(), alpha.size()); y_cov_gen.ResizeTo(alpha.size(), alpha.size()); // fill covariance matrix for data and mc for(int ialpha=0; ialpha < alpha.size(); ++ialpha){ for (Int_t jalpha =0; jalpha < alpha.size(); jalpha++){ if( ialpha <= jalpha ) { double n1_mc = pow(MCy.at(ialpha),2)/(2*pow(MCy_e.at(ialpha),2)); double n2_mc = pow(MCy.at(jalpha),2)/(2*pow(MCy_e.at(jalpha),2)); double n1_data = pow(Datay.at(ialpha),2)/(2*pow(Datay_e.at(ialpha),2)); double n2_data = pow(Datay.at(jalpha),2)/(2*pow(Datay_e.at(jalpha),2)); double n1_gen = pow(Geny.at(ialpha),2)/(2*pow(Geny_e.at(ialpha),2)); double n2_gen = pow(Geny.at(jalpha),2)/(2*pow(Geny_e.at(jalpha),2)); y_cov_mc(ialpha, jalpha) = pow(MCy_e.at(ialpha),2) * pow((n1_mc/n2_mc),2)* (MCy.at(ialpha)/MCy.at(jalpha)); y_cov_data(ialpha, jalpha) = pow(Datay_e.at(ialpha),2) * pow((n1_data/n2_data),2)* (Datay.at(ialpha)/Datay.at(jalpha)); y_cov_gen(ialpha, jalpha) = pow(Geny_e.at(ialpha),2) * pow((n1_gen/n2_gen),2)* (Geny.at(ialpha)/Geny.at(jalpha)); } else { double n1_mc = pow(MCy.at(jalpha),2)/(2*pow(MCy_e.at(jalpha),2)); double n2_mc = pow(MCy.at(ialpha),2)/(2*pow(MCy_e.at(ialpha),2)); double n1_data = pow(Datay.at(jalpha),2)/(2*pow(Datay_e.at(jalpha),2)); double n2_data = pow(Datay.at(ialpha),2)/(2*pow(Datay_e.at(ialpha),2)); double n1_gen = pow(Geny.at(jalpha),2)/(2*pow(Geny_e.at(jalpha),2)); double n2_gen = pow(Geny.at(ialpha),2)/(2*pow(Geny_e.at(ialpha),2)); y_cov_mc(ialpha, jalpha) = pow(MCy_e.at(jalpha),2) * pow((n1_mc/n2_mc),2)* (MCy.at(jalpha)/MCy.at(ialpha)); y_cov_data(ialpha, jalpha) = pow(Datay_e.at(jalpha),2) * pow((n1_data/n2_data),2)* (Datay.at(jalpha)/Datay.at(ialpha)); y_cov_gen(ialpha, jalpha) = pow(Geny_e.at(jalpha),2) * pow((n1_gen/n2_gen),2)* (Geny.at(jalpha)/Geny.at(ialpha)); } } } //create TGraphErrors from previously defined vectors TGraphErrors *extrapol_MC = new TGraphErrors(alpha.size(),&x[0],&MCy[0],&x_e[0],&MCy_e[0]); TGraphErrors *extrapol_Data = new TGraphErrors(alpha.size(),&x[0],&Datay[0],&x_e[0],&Datay_e[0]); TGraphErrors *extrapol_Gen = new TGraphErrors(alpha.size(),&x[0],&Geny[0],&x_e[0],&Geny_e[0]); // fit linear extrapolation function TF1 *lin_extrapol_mc = new TF1("lin_extrapol_mc","[0]+[1]*x",0,alpha.back()+0.05); TF1 *lin_extrapol_data = new TF1("lin_extrapol_data","[0]+[1]*x",0,alpha.back()+0.05); TF1 *lin_extrapol_gen = new TF1("lin_extrapol_gen","[0]+[1]*x",0,alpha.back()+0.05); //fit extrapolation function to the TGraphErrors for data and MC // extrapol_MC->Fit("lin_extrapol_mc","Q","same",0,alpha.back()+0.05); // extrapol_Data->Fit("lin_extrapol_data","Q","same",0,alpha.back()+0.05); // fit mc data.reset(); data.x_val = x; data.y_val = MCy; data.y_cov.ResizeTo(alpha.size(), alpha.size()); data.y_cov = y_cov_mc; data.CheckPoints(); // choose start values for MC fit double slope = (MCy.at(MCy.size()-1) - MCy.at(MCy.size()-4))/(x.at(x.size()-1) - x.at(x.size()-4)); double d_slope = slope; double offset = MCy.at(MCy.size()-1) - (slope*x.at(x.size()-1)); double d_offset = offset; std::cout << "MC start values: " << "slope: " << slope << " offset: " << offset << std::endl; make_lin_fit(slope, d_slope, offset, d_offset); std::cout << "MC fit values: " << "slope: " << slope << " offset: " << offset << std::endl; lin_extrapol_mc->SetParameter(0, offset); lin_extrapol_mc->SetParError(0, d_offset); lin_extrapol_mc->SetParameter(1, slope); lin_extrapol_mc->SetParError(1, d_slope); extrapol_MC->GetListOfFunctions()->Add(lin_extrapol_mc); data.reset(); // fit data data.x_val = x; data.y_val = Datay; data.y_cov.ResizeTo(alpha.size(), alpha.size()); data.y_cov = y_cov_data; data.CheckPoints(); // choose start values for data fit slope = (Datay.at(Datay.size()-1) - Datay.at(Datay.size()-4))/(x.at(x.size()-1) - x.at(x.size()-4)); d_slope = slope; offset = Datay.at(Datay.size()-1) - (slope*x.at(x.size()-1)); d_offset = offset; std::cout << "Data start values: " << "slope: " << slope << " offset: " << offset << std::endl; make_lin_fit(slope, d_slope, offset, d_offset); std::cout << "Data fit values: " << "slope: " << slope << " offset: " << offset << std::endl; lin_extrapol_data->SetParameter(0, offset); lin_extrapol_data->SetParError(0, d_offset); lin_extrapol_data->SetParameter(1, slope); lin_extrapol_data->SetParError(1, d_slope); extrapol_Data->GetListOfFunctions()->Add(lin_extrapol_data); data.reset(); // fit gen data.x_val = x; data.y_val = Geny; data.y_cov.ResizeTo(alpha.size(), alpha.size()); data.y_cov = y_cov_gen; data.CheckPoints(); // choose start values for gen fit slope = (Geny.at(Geny.size()-1) - Geny.at(Geny.size()-4))/(x.at(x.size()-1) - x.at(x.size()-4)); d_slope = slope; offset = Geny.at(Geny.size()-1) - (slope*x.at(x.size()-1)); d_offset = offset; std::cout << "Gen start values: " << "slope: " << slope << " offset: " << offset << std::endl; make_lin_fit(slope, d_slope, offset, d_offset); std::cout << "Gen fit values: " << "slope: " << slope << " offset: " << offset << std::endl; lin_extrapol_gen->SetParameter(0, offset); lin_extrapol_gen->SetParError(0, d_offset); lin_extrapol_gen->SetParameter(1, slope); lin_extrapol_gen->SetParError(1, d_slope); extrapol_Gen->GetListOfFunctions()->Add(lin_extrapol_gen); data.reset(); // draw extrapolations data + mc TCanvas *c = new TCanvas("c","",600,600); std::pair <float,float> minMaxPair = determineMinMax(extrapol_Data); c->DrawFrame(0,minMaxPair.first*0.5-0.05,alpha.back()+0.05,minMaxPair.second*1.47,(";Threshold #alpha_{max};#sigma_{A}")); extrapol_MC->SetMarkerStyle(20); extrapol_MC->SetMarkerColor(kRed+1); extrapol_MC->SetLineColor(kRed+1); extrapol_MC->Draw("P"); extrapol_Data->SetMarkerStyle(20); extrapol_Data->SetMarkerColor(kBlack); extrapol_Data->SetLineColor(kBlack); extrapol_Data->Draw("Psame"); TF1* MCTemp = new TF1(); TF1* DataTemp = new TF1(); extrapol_MC->GetFunction("lin_extrapol_mc")->SetLineColor(kRed+1); extrapol_MC->GetFunction("lin_extrapol_mc")->SetLineStyle(2); extrapol_Data->GetFunction("lin_extrapol_data")->SetLineColor(kBlack); extrapol_Data->GetFunction("lin_extrapol_data")->SetLineStyle(2); MCTemp=(TF1*) extrapol_MC->GetFunction("lin_extrapol_mc")->Clone(); DataTemp=(TF1*) extrapol_Data->GetFunction("lin_extrapol_data")->Clone(); MCTemp->SetRange(0.1,1); MCTemp->SetLineStyle(1); MCTemp->Draw("same"); DataTemp->SetRange(0.1,1); DataTemp->SetLineStyle(1); DataTemp->Draw("same"); TPaveText *label = util::LabelFactory::createPaveTextWithOffset(2,1.0,0.5); label->AddText("Anti-k_{T} (R=0.5) PFchs Jets"); label->AddText( Form("%0.1f #leq |#eta| #leq %0.1f, %3.0f #leq #bar{ p}_{T} [GeV] #leq %3.0f", eta_bins[ieta], eta_bins[ieta+1], pt_bins[ipt], pt_bins[ipt+1]) ); label->Draw("same"); TLegend* leg1 = util::LabelFactory::createLegendWithOffset(2,0.6); leg1->AddEntry(extrapol_Data,"Extrapolation (MC smeared)","LP"); leg1->AddEntry(extrapol_MC,"Extrapolation (MC)","LP"); leg1->Draw(); cmsPrel(-1, false , 8); TString name; name = Form("ClosureTest/Extrapol_Eta%i_pt%i" + suffix + ".eps", ieta, ipt); c->Print(name); TCanvas *cb = new TCanvas("c","",600,600); std::pair <float,float> minMaxPair2 = determineMinMax(extrapol_Data); cb->DrawFrame(0,minMaxPair2.first*0.5-0.05,alpha.back()+0.05,minMaxPair2.second*1.47,(";Threshold #alpha_{max, gen};#sigma_{A, gen}")); extrapol_Gen->SetMarkerStyle(20); extrapol_Gen->SetMarkerColor(kBlue+1); extrapol_Gen->SetLineColor(kBlue+1); extrapol_Gen->Draw("P"); TF1* GenTemp = new TF1(); extrapol_Gen->GetFunction("lin_extrapol_gen")->SetLineColor(kBlue+1); extrapol_Gen->GetFunction("lin_extrapol_gen")->SetLineStyle(2); GenTemp=(TF1*) extrapol_Gen->GetFunction("lin_extrapol_gen")->Clone(); GenTemp->SetRange(0.1,1); GenTemp->SetLineStyle(1); GenTemp->Draw("same"); TPaveText *label2 = util::LabelFactory::createPaveTextWithOffset(2,1.0,0.05); label2->AddText("Anti-k_{T} (R=0.5) PFchs Jets"); label2->AddText( Form("%0.1f #leq |#eta| #leq %0.1f, %3.0f #leq #bar{ p}_{T} [GeV] #leq %3.0f", eta_bins[ieta], eta_bins[ieta+1], pt_bins[ipt], pt_bins[ipt+1]) ); label2->Draw("same"); TLegend* leg2 = util::LabelFactory::createLegendWithOffset(2,0.15); leg2->AddEntry(extrapol_Gen,"Extrapolation (PLI)","LP"); leg2->Draw(); cmsPrel(-1, false , 8); TString name2; name2 = Form("ClosureTest/Extrapol_Eta%i_pt%i_gen" + suffix + ".eps", ieta, ipt); cb->Print(name2); float par_data = lin_extrapol_data->GetParameter(0); float par_data_err = lin_extrapol_data->GetParError(0); float par_mc = lin_extrapol_mc->GetParameter(0); float par_mc_err = lin_extrapol_mc->GetParError(0); float par_gen = lin_extrapol_gen->GetParameter(0); float par_gen_err = lin_extrapol_gen->GetParError(0); cout << "ieta : " << ieta << " ipt : " << ipt << endl; cout << "Parameter data: " << par_data << endl; cout << "Parameter error data: " << par_data_err << endl; cout << "Parameter mc: " << par_mc << endl; cout << "Parameter error mc: " << par_mc_err << endl; cout << "Parameter gen: " << par_gen << endl; cout << "Parameter error gen: " << par_gen_err << endl; extrapolated_mcsmeared->SetBinContent(ipt+1, par_data); extrapolated_mcsmeared->SetBinError(ipt+1, par_data_err); extrapolated_mc->SetBinContent(ipt+1, par_mc); extrapolated_mc->SetBinError(ipt+1, par_mc_err); extrapolated_gen->SetBinContent(ipt+1, par_gen); extrapolated_gen->SetBinError(ipt+1, par_gen_err); float par_data_pli_corr = 0; float par_data_pli_corr_err = 0; float par_mc_pli_corr = 0; float par_mc_pli_corr_err = 0; if(par_gen > 0 && par_data > 0 && par_mc > 0 && par_data > par_gen && par_mc > par_gen) { par_data_pli_corr = TMath::Sqrt(pow(par_data,2) - pow(par_gen,2)); par_data_pli_corr_err = TMath::Sqrt( pow(par_data,2)/(pow(par_data,2) - pow(par_gen,2)) * pow(par_data_err,2) + pow(par_gen,2)/(pow(par_data,2) - pow(par_gen,2)) * pow(par_gen_err,2)); par_mc_pli_corr = TMath::Sqrt(pow(par_mc,2) - pow(par_gen,2)); par_mc_pli_corr_err = TMath::Sqrt( pow(par_mc,2)/(pow(par_mc,2) - pow(par_gen,2)) * pow(par_mc_err,2) + pow(par_gen,2)/(pow(par_mc,2) - pow(par_gen,2)) * pow(par_gen_err,2)); } extrapolated_mcsmeared_with_pli->SetBinContent(ipt+1, par_data_pli_corr); extrapolated_mcsmeared_with_pli->SetBinError(ipt+1, par_data_pli_corr_err); extrapolated_mc_with_pli->SetBinContent(ipt+1, par_mc_pli_corr); extrapolated_mc_with_pli->SetBinError(ipt+1, par_mc_pli_corr_err); cout << "Parameter data after pli: " << par_data_pli_corr << endl; cout << "Parameter error data after pli: " << par_data_pli_corr_err << endl; cout << "Parameter mc after pli: " << par_mc_pli_corr << endl; cout << "Parameter error mc after pli: " << par_mc_pli_corr_err << endl; } // --------------------------------------- // // calc data/mc ratio and fit with constant TH1F* ratio = new TH1F(*extrapolated_mc); TH1F* ratio_with_pli = new TH1F(*extrapolated_mc); ratio->Divide(extrapolated_mcsmeared, extrapolated_mc, 1, 1); ratio_with_pli->Divide(extrapolated_mcsmeared_with_pli, extrapolated_mc_with_pli, 1, 1); TF1 *fit_const = new TF1("fit_const", "[0]", ratio->GetXaxis()->GetXmin(), ratio->GetXaxis()->GetXmax()); fit_const->SetParameters(0, 1.1); fit_const->SetParName(0, "const"); ratio->Fit("fit_const", "", "same"); ratio->GetXaxis()->SetTitle("#bar{ p}_{T} [GeV]"); ratio->GetYaxis()->SetRangeUser(0.7, 1.4); ratio->GetYaxis()->SetTitle("MC_{smeared}/MC ratio (const fit)"); RatioVsEta->SetBinContent(ieta+1, ratio->GetFunction("fit_const")->GetParameter(0)); RatioVsEta->SetBinError(ieta+1, ratio->GetFunction("fit_const")->GetParError(0)); TCanvas *c3 = new TCanvas("c3","",600,600); c3->SetLogx(); ratio->Draw(); TString name3; name3 = Form("ClosureTest/ExtrapolRatio_Eta%i" + suffix + ".eps", ieta); c3->Print(name3); ratio_with_pli->Fit("fit_const", "", "same"); ratio_with_pli->GetXaxis()->SetTitle("#bar{ p}_{T} [GeV]"); ratio_with_pli->GetYaxis()->SetRangeUser(0.7, 1.4); ratio_with_pli->GetYaxis()->SetTitle("MC_{smeared}/MC ratio (const fit)"); TCanvas *c3b = new TCanvas("c3","",600,600); c3b->SetLogx(); ratio_with_pli->Draw(); TString name4; name4 = Form("ClosureTest/ExtrapolRatio_Eta%i_with_pli" + suffix + ".eps", ieta); c3b->Print(name4); RatioVsEta_with_pli->SetBinContent(ieta+1, ratio_with_pli->GetFunction("fit_const")->GetParameter(0)); RatioVsEta_with_pli->SetBinError(ieta+1, ratio_with_pli->GetFunction("fit_const")->GetParError(0)); } // draw data/mc scaling factors vs. eta TCanvas *c4 = new TCanvas(); RatioVsEta->GetYaxis()->SetRangeUser(0.7, 1.3); RatioVsEta->GetXaxis()->SetTitle("|#eta|"); RatioVsEta->GetYaxis()->SetTitle("MC_{smeared} /MC ratio (const fit)"); RatioVsEta->Draw(); c4->Print("ClosureTest/ScalingFactorsVsEta" + suffix + ".eps"); cout << "//----------------------------------------------//" << endl; cout << "Scaling factors without PLI: " << endl; cout << "Ratio eta1: " << RatioVsEta->GetBinContent(1) << " +- " << RatioVsEta->GetBinError(1) << endl; cout << "Ratio eta2: " << RatioVsEta->GetBinContent(2) << " +- " << RatioVsEta->GetBinError(2) << endl; cout << "Ratio eta3: " << RatioVsEta->GetBinContent(3) << " +- " << RatioVsEta->GetBinError(3) << endl; cout << "Ratio eta4: " << RatioVsEta->GetBinContent(4) << " +- " << RatioVsEta->GetBinError(4) << endl; cout << "Ratio eta5: " << RatioVsEta->GetBinContent(5) << " +- " << RatioVsEta->GetBinError(5) << endl; cout << "Ratio eta6: " << RatioVsEta->GetBinContent(6) << " +- " << RatioVsEta->GetBinError(6) << endl; cout << "Ratio eta7: " << RatioVsEta->GetBinContent(7) << " +- " << RatioVsEta->GetBinError(7) << endl; cout << "//----------------------------------------------//" << endl; TCanvas *c4b = new TCanvas(); RatioVsEta_with_pli->GetYaxis()->SetRangeUser(0.7, 1.4); RatioVsEta_with_pli->GetXaxis()->SetTitle("|#eta|"); RatioVsEta_with_pli->GetYaxis()->SetTitle("MC_{smeared} /MC ratio (const fit)"); RatioVsEta_with_pli->Draw(); c4b->Print("ClosureTest/ScalingFactorsVsEta_with_pli" + suffix + ".eps"); cout << "//----------------------------------------------//" << endl; cout << "Scaling factors with PLI: " << endl; cout << "Ratio eta1: " << RatioVsEta_with_pli->GetBinContent(1) << " +- " << RatioVsEta_with_pli->GetBinError(1) << endl; cout << "Ratio eta2: " << RatioVsEta_with_pli->GetBinContent(2) << " +- " << RatioVsEta_with_pli->GetBinError(2) << endl; cout << "Ratio eta3: " << RatioVsEta_with_pli->GetBinContent(3) << " +- " << RatioVsEta_with_pli->GetBinError(3) << endl; cout << "Ratio eta4: " << RatioVsEta_with_pli->GetBinContent(4) << " +- " << RatioVsEta_with_pli->GetBinError(4) << endl; cout << "Ratio eta5: " << RatioVsEta_with_pli->GetBinContent(5) << " +- " << RatioVsEta_with_pli->GetBinError(5) << endl; cout << "Ratio eta6: " << RatioVsEta_with_pli->GetBinContent(6) << " +- " << RatioVsEta_with_pli->GetBinError(6) << endl; cout << "Ratio eta7: " << RatioVsEta_with_pli->GetBinContent(7) << " +- " << RatioVsEta_with_pli->GetBinError(7) << endl; cout << "//----------------------------------------------//" << endl; }
void plot1d(int hid) { gStyle->SetOptStat(0); char c[50]; c1->Clear(); if(m1dHist[hid]==0){ c1->Divide(2,2); for(int quad=0; quad<kFgtNumQuads; quad++){ TVirtualPad* pad1 = c1->cd(quad+1); pad1->SetLogy(l1dHist[hid]); double xmin, xmax, ymin=0.0, ymax=0.0; if(l1dHist[hid]==1) ymin=0.1; for(int disc=0; disc<kFgtNumDiscs; disc++){ sprintf(c,"%1d%1s-%s",disc+1,cquad[quad],c1dHist[hid]); //printf("Getting %s\n",c); TH1F *h = hist1[disc][quad][hid] = (TH1F*)file->Get(c); xmin=h->GetXaxis()->GetXmin(); xmax=h->GetXaxis()->GetXmax(); double m=h->GetMaximum(); if(ymax<m) ymax=m; printf("disc=%d max=%6.1f ymax=%6.1f xmin=%6.1f xmax=%6.1f\n",disc+1,m,ymax,xmin,xmax); } sprintf(c,"Quad%1s-%s",cquad[quad],c1dHist[hid]); TH2F *frame = new TH2F(c,c,1,xmin,xmax,1,ymin,ymax*1.2); frame->SetStats(0); frame->Draw(); for(int disc=0; disc<kFgtNumDiscs; disc++){ TH1F *h=hist1[disc][quad][hid]; h->SetLineColor(color[disc]); h->SetLineWidth(3); h->Draw("SAME"); if(f1dHist[hid]==0){ float mean=h->GetMean(); sprintf(c,"%1d%s mean=%6.2f",disc+1,cquad[quad],mean); }else if(f1dHist[hid]==1){ int res = h->Fit("gaus","0Q"); TF1 *f = h->GetFunction("gaus"); float sig = f->GetParameter(2); if(res==0 && sig>0.0001 && h->GetEntries()>5){ f->SetLineColor(color[disc]); f->SetLineWidth(2); f->Draw("SAME"); sprintf(c,"%1d%s sig=%6.3f",disc+1,cquad[quad],sig); }else{ sprintf(c,"%1d%s",disc+1,cquad[quad]); } }else if(f1dHist[hid]==2){ int res = h->Fit("landau","0Q"); TF1 *f = h->GetFunction("landau"); float peak = f->GetParameter(1); if(res==0 && peak>0 && h->GetEntries()>5){ f->SetLineColor(color[disc]); f->SetLineWidth(2); f->Draw("SAME"); sprintf(c,"%1d%s mpv=%6.0f",disc+1,cquad[quad],peak); }else{ sprintf(c,"%1d%s",disc+1,cquad[quad]); } } TText *t1; float x1= 0.2, x2= 0.55; float y1=0.8 - 0.07*disc; float y2=0.8 - 0.07*(disc-3); if(disc<3) { t1 = new TText(x1,y1,c); } else { t1 = new TText(x2,y2,c); } t1->SetNDC(); t1->SetTextSize(0.04); t1->SetTextColor(color[disc]); t1->Draw(); } } }else{ c1->Divide(4,6); gStyle->SetOptStat(0); gStyle->SetOptTitle(0); gStyle->SetOptFit(0); for(int disc=0; disc<kFgtNumDiscs; disc++){ for(int quad=0; quad<kFgtNumQuads; quad++){ TPad* pad = c1->cd(disc*4+quad+1); pad->SetRightMargin(0.01); pad->SetLeftMargin(0.1); pad->SetTopMargin(0.01); pad->SetBottomMargin(0.1); pad->SetLogy(l1dHist[hid]); sprintf(c,"%1d%1s-%s",disc+1,cquad[quad],c1dHist[hid]); TH1F *h = hist1[disc][quad][hid] = (TH1F*)file->Get(c); h->SetFillColor(color[disc]); h->GetXaxis()->SetLabelSize(0.1); h->GetYaxis()->SetLabelSize(0.1); h->GetXaxis()->SetNdivisions(205); h->Draw(); if(f1dHist[hid]==0){ float mean=h->GetMean(); sprintf(c,"%1d%s mean=%6.2f",disc+1,cquad[quad],mean); }else if(f1dHist[hid]==1){ int res = h->Fit("gaus","0Q"); TF1 *f = h->GetFunction("gaus"); float sig = f->GetParameter(2); if(res==0 && sig>0.0001 && h->GetEntries()>5){ f->SetLineColor(color[disc]); f->SetLineWidth(2); f->Draw("SAME"); sprintf(c,"%1d%s sig=%6.3f",disc+1,cquad[quad],sig); }else{ sprintf(c,"%1d%s",disc+1,cquad[quad]); } }else if(f1dHist[hid]==2){ int res = h->Fit("landau","0Q"); TF1 *f = h->GetFunction("landau"); float peak = f->GetParameter(1); if(res==0 && peak>0 && h->GetEntries()>5){ f->SetLineColor(1); f->SetLineWidth(2); f->Draw("SAME"); sprintf(c,"%1d%s mpv=%6.0f",disc+1,cquad[quad],peak); }else{ sprintf(c,"%1d%s",disc+1,cquad[quad]); } if(hid==8) {mPeakC[disc][quad]=peak;} if(hid==9) { mPeakA[disc][quad]=peak; int n=h->GetEntries(); if(n>0){ float cut=2800; int bin=h->FindBin(cut); int nbin=h->GetNbinsX(); float sat=h->Integral(bin,nbin+1); //printf("bin=%d nbin=%d sat=%f\n",bin,nbin,sat); mFracA[disc][quad]=sat/float(n); } } if(hid==11) {mPeakL[disc][quad]=peak;} // printf("LandauPeak=%f\n",peak);} } TText *t1 = new TText(0.3,0.85,c); t1->SetNDC(); t1->SetTextSize(0.15); t1->SetTextColor(color[disc]); t1->Draw(); } } } c1->Update(); save(c1dHist[hid]); }
void fullCalib7_14(){ const int numRuns = 6; const char* files[numRuns] = { "../crunchedFiles/run_00393_crunched.root", "../crunchedFiles/run_00394_crunched.root", "../crunchedFiles/run_00395_crunched.root", "../crunchedFiles/run_00398_crunched.root", "../crunchedFiles/run_00399_crunched.root", "../crunchedFiles/run_00400_crunched.root" }; gStyle->SetOptFit(1); cout << "Which? " << endl; int which; cin >> which; vector<double> means; vector<double> sigs; vector<double> meanErrs; vector<double> sigErrs; for (int i = 0; i < numRuns; ++i){ TFile* f = new TFile(files[i]); TTree* t = (TTree*) f->Get("t"); cout << "got tree" << endl; t->Draw(Form("sipm%i.energy>>histo%i", which,i),Form("sipm%i.valid",which)); cout << "drew" << endl; cout << "finding obj" << endl; TH1F* h = (TH1F*) gROOT->FindObject(Form("histo%i",i)); h->Fit("gaus","0"); means.push_back(h->GetFunction("gaus")->GetParameter(1)); sigs.push_back(h->GetFunction("gaus")->GetParameter(2)); meanErrs.push_back(h->GetFunction("gaus")->GetParError(1)); sigErrs.push_back(h->GetFunction("gaus")->GetParError(2)); cout << "end itr" << endl; } vector<double> variances; vector<double> varianceErrors; for(int i = 0; i < means.size(); ++i){ variances.push_back(sigs[i]*sigs[i]); varianceErrors.push_back(2*sigs[i]*sigErrs[i]); } TGraphErrors* linGraph = new TGraphErrors(means.size(), &means[0], &variances[0], &meanErrs[0], &varianceErrors[0]); TGraphErrors* quadGraph = new TGraphErrors(means.size(), &means[0], &variances[0], &meanErrs[0], &varianceErrors[0]); linGraph->SetMarkerStyle(20); linGraph->Fit("pol1"); linGraph->SetTitle(Form("SiPM %i", which)); linGraph->GetFunction("pol1")->SetLineColor(kBlue); linGraph->GetXaxis()->SetTitle("Mean"); linGraph->GetYaxis()->SetTitle("#sigma^{2}"); quadGraph->SetMarkerStyle(20); quadGraph->Fit("pol2"); quadGraph->GetFunction("pol2")->SetLineColor(kRed); linGraph->Draw("ap"); quadGraph->Draw("psame"); }
void display(){ gROOT->ProcessLine(".x lhcbStyle.C"); gStyle->SetPalette(1); string filename = "../analysed/SET9THL914.root"; TFile* file = new TFile(filename.c_str(),"OPEN"); int nBinsX=32; int nBinsY=32; int nPixelsX=64; int nPixelsY=64; std::cout<<"Making global intercept tot map"<<std::endl; // Global intercept map (not per pixel) TH2F* hToTMap = new TH2F("hToTMap","hToTMap",nBinsX,0,nPixelsX,nBinsY,0,nPixelsY); for(int x=0;x<nBinsX;x++){ for(int y=0;y<nBinsY;y++){ int id = x + y*nBinsX; // Get the ToT distribution for this location string histoname = "/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixMap"+makestring(id); TH1F* totMapHisto = 0; totMapHisto = (TH1F*)gDirectory->Get(histoname.c_str()); if(totMapHisto == 0) continue; if(totMapHisto->GetEntries() < 20) continue; // Fit the tot distribution and enter the value in the ToT map totMapHisto->Fit("gaus","0q"); TF1* fit = totMapHisto->GetFunction("gaus"); hToTMap->Fill(x*floor(nPixelsX/nBinsX),y*floor(nPixelsY/nBinsY),fit->GetParameter(1)); delete fit; delete totMapHisto; } } // Plot the map of ToT TCanvas* canv = new TCanvas(); hToTMap->GetXaxis()->SetTitle("Column"); hToTMap->GetYaxis()->SetTitle("Row"); hToTMap->GetZaxis()->SetTitle("Mean charge (ToT)"); hToTMap->SetMaximum(9); hToTMap->SetMinimum(5); hToTMap->DrawCopy("colz"); std::cout<<"Making per pixel tot map"<<std::endl; // Per pixel map TH2F* hToTMapPerPixel = new TH2F("hToTMapPerPixel","hToTMapPerPixel",nPixelsX,0,nPixelsX,nPixelsY,0,nPixelsY); for(int x=0;x<nPixelsX;x++){ for(int y=0;y<nPixelsY;y++){ int id = x + y*nPixelsX; // Get the ToT distribution for this location string histoname = "/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixPixel"+makestring(id); TH1F* totMapHisto = 0; totMapHisto = (TH1F*)gDirectory->Get(histoname.c_str()); if(totMapHisto == 0) continue; if(totMapHisto->GetEntries() < 10) continue; // Fit the tot distribution and enter the value in the ToT map totMapHisto->Fit("gaus","0q"); TF1* fit = totMapHisto->GetFunction("gaus"); hToTMapPerPixel->Fill(x,y,fit->GetParameter(1)); delete fit; delete totMapHisto; } } // Plot the map of ToT TCanvas* canv2 = new TCanvas(); hToTMapPerPixel->GetXaxis()->SetTitle("Column"); hToTMapPerPixel->GetYaxis()->SetTitle("Row"); hToTMapPerPixel->GetZaxis()->SetTitle("Mean charge (ToT)"); hToTMapPerPixel->SetMaximum(10); hToTMapPerPixel->SetMinimum(0); hToTMapPerPixel->DrawCopy("colz"); std::cout<<"Making pixel response tot maps"<<std::endl; // Pixel response maps int responseBins=100; double responseWidth=0.05; TH2F* hToTMapPixelResponseX = new TH2F("hToTMapPixelResponseX","hToTMapPixelResponseX",responseBins+1,-responseWidth,responseWidth,15,0,15); for(double rID=0;rID<responseBins;rID++){ // Get the ToT distribution for this location string histoname = "/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixResponseX"+makestringD(rID); TH1F* totMapHisto = 0; totMapHisto = (TH1F*)gDirectory->Get(histoname.c_str()); if(totMapHisto == 0) continue; if(totMapHisto->GetEntries() < 1) continue; // loop over all tot bins for(int i=0;i<45;i++){ hToTMapPixelResponseX->Fill(2.*responseWidth*(rID/100.)-responseWidth,i,totMapHisto->GetBinContent(totMapHisto->FindBin(i))); } delete totMapHisto; } // Plot the map of ToT TCanvas* canv3 = new TCanvas(); hToTMapPixelResponseX->GetXaxis()->SetTitle("Track distance x (mm)"); hToTMapPixelResponseX->GetYaxis()->SetTitle("ToT"); hToTMapPixelResponseX->DrawCopy("colz"); TH1F* hToTProfilePixelResponseY = new TH1F("hToTProfilePixelResponseY","hToTProfilePixelResponseY",responseBins+1,-responseWidth,responseWidth); TH2F* hToTMapPixelResponseY = new TH2F("hToTMapPixelResponseY","hToTMapPixelResponseY",responseBins+1,-responseWidth,responseWidth,16,0,16); for(double rID=0;rID<responseBins;rID++){ // Get the ToT distribution for this location string histoname = "/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixResponseY"+makestringD(rID); TH1F* totMapHisto = 0; totMapHisto = (TH1F*)gDirectory->Get(histoname.c_str()); if(totMapHisto == 0) continue; if(totMapHisto->GetEntries() < 1) continue; // loop over all tot bins for(int i=0;i<45;i++){ hToTMapPixelResponseY->Fill(2.*responseWidth*(rID/100.)-responseWidth,i,totMapHisto->GetBinContent(totMapHisto->FindBin(i))); } hToTProfilePixelResponseY->Fill(2.*responseWidth*(rID/100.)-responseWidth+0.001,totMapHisto->GetXaxis()->GetBinCenter(totMapHisto->GetMaximumBin())); delete totMapHisto; } // Plot the map of ToT TCanvas* canv4 = new TCanvas(); hToTMapPixelResponseY->GetXaxis()->SetTitle("Track distance y (mm)"); hToTMapPixelResponseY->GetYaxis()->SetTitle("ToT"); hToTMapPixelResponseY->GetZaxis()->SetTitle("Number of events"); hToTMapPixelResponseY->DrawCopy("colz"); // drawline(-0.03,1,7); // drawline(0.03,1,7); TCanvas* canv6 = new TCanvas(); hToTProfilePixelResponseY->GetXaxis()->SetTitle("Track distance y (mm)"); hToTProfilePixelResponseY->GetYaxis()->SetTitle("Most probable ToT"); hToTProfilePixelResponseY->DrawCopy(""); TCanvas* canv5 = new TCanvas(); TH1F* sidebandLow = (TH1F*)gDirectory->Get("/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixResponseY20"); TH1F* sidebandHigh = (TH1F*)gDirectory->Get("/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixResponseY80"); sidebandHigh->GetXaxis()->SetTitle("ToT (single pixel)"); sidebandHigh->GetXaxis()->SetRangeUser(0,20); sidebandHigh->DrawCopy(""); sidebandLow->SetLineColor(2); sidebandLow->DrawCopy("same"); }
void data_to_tree() { Double_t pedtime; Double_t pedTr; Double_t pedTl; Double_t rped; Double_t lped; //ptfactor = point to time factor //const Double_t ptfactor = 0.050; const Double_t ptfactor = 0.0407; TFile* f = new TFile("data_to_tree.root", "RECREATE"); ifstream in; ofstream out; //bring data files and give name to use in this code. //data file name is in order type_ch0highvoltage_ch2highvoltage_#ofevent_position_3.dat const Int_t nFile = 10; // including long file for TWC const Char_t* file[nFile] = {"./Cobalt_data/Co_2090v_2160v_10k_10cm_3.dat", "./Cobalt_data/Co_2090v_2160v_10k_20cm_3.dat", "./Cobalt_data/Co_2090v_2160v_10k_30cm_3.dat", "./Cobalt_data/Co_2090v_2160v_10k_40cm_3.dat", "./Cobalt_data/Co_2090v_2160v_10k_50cm_3.dat", "./Cobalt_data/Co_2090v_2160v_10k_60cm_3.dat", "./Cobalt_data/Co_2090v_2160v_10k_70cm_3.dat", "./Cobalt_data/Co_2090v_2160v_10k_80cm_3.dat", "./Cobalt_data/Co_2090v_2160v_10k_90cm_3.dat", "./Cobalt_data/Co_2090v_2160v_100k_50cm_3.dat"}; const Char_t* distance[nFile] = {"10cm", "20cm", "30cm", "40cm", "50cm", "60cm", "70cm", "80cm", "90cm", "50cm100k"}; TCanvas* c1 = new TCanvas("c1", "pedl", 200, 0, 600, 600); TH1F* pedlhist = new TH1F("pedlhist", "left", 200, 0, 200); TCanvas* c2 = new TCanvas("c2", "pedr", 210, 10, 610, 610); TH1F* pedrhist = new TH1F("pedrhist", "right", 200, 0, 200); //bring the pedestal file in.open("./Cobalt_data/pedestal_2090v_2160v_10k_4.dat"); if(in.is_open()) { while(1) { in >> pedtime >> pedTl >> pedTr >> lped >> rped; if(!in.good()) break; pedlhist->Fill(lped); pedrhist->Fill(rped); } } in.close(); c1->cd(); pedlhist->Draw(); pedlhist->Fit("gaus", "", "", 150, 160); Double_t pedlmean = pedlhist->GetFunction("gaus")->GetParameter(1); c1->SaveAs("CFDpedl.png"); c2->cd(); pedrhist->Draw(); pedrhist->Fit("gaus", "", "", 105, 125); Double_t pedrmean = pedrhist->GetFunction("gaus")->GetParameter(1); c2->SaveAs("CFDpedr.png"); //pr: position resolution TTree* pr[nFile]; for(Int_t i = 0; i < nFile; i++) { in.open(file[i]); Double_t time = 0; Double_t Tl = 0; Double_t Tr = 0; Double_t Al = 0; Double_t Ar = 0; pr[i] = new TTree(distance[i], "position resolution data"); pr[i]->Branch("Tl", &Tl, "Tl/D"); pr[i]->Branch("Tr", &Tr, "Tr/D"); pr[i]->Branch("Al", &Al, "Al/D"); pr[i]->Branch("Ar", &Ar, "Ar/D"); //correction // 1. TDCchannel * ptfactor // 2. ADC - pedestal mean if(in.is_open()) { while(1) { in >> time >> Tl >> Tr >> Al >> Ar; if(!in.good()) break; Tl = Tl*ptfactor; Tr = Tr*ptfactor; Al = Al-pedlmean; Ar = Ar-pedrmean; pr[i]->Fill(); } } in.close(); } f->Write(); }
void plotTreeNorms(TTree *tree_, std::string selectString, bool do7TeV){ // Create a map for plotting the pullsummaries: std::map < const char*, std::pair <double,double> > pullSummaryMap; int nPulls=0; TObjArray *l_branches = tree_->GetListOfBranches(); int nBranches = l_branches->GetEntries(); gStyle->SetPadTopMargin(0.01); TCanvas *c = new TCanvas("c","",960,800); std::string treename = tree_->GetName(); c->SaveAs(Form("%s_normresiduals.pdf[",treename.c_str())); // File to store plots in TFile *fOut = new TFile(Form("%s_normresiduals.root",treename.c_str()),"RECREATE"); TH1F *bHd = new TH1F("bHd","",50,-1.0,1.0); TH1F *bHfd = new TH1F("bHfd","",50,-1.0,1.0); for (int iobj=0;iobj<nBranches;iobj++){ TBranch *br =(TBranch*) l_branches->At(iobj); // Draw the normal histogram const char* name = br->GetName(); // select only the normalizations string namestr(name); if(namestr.find("n_exp")==string::npos) continue; bool fitPull=true; bool fitPullf=true; double p_mean =0; int nToysInTree = tree_->GetEntries(); // Find out if paramter is fitted value or constraint term. bool isFitted = true; p_mean = prenorms_[name].first; // toy initial parameters from the datacards std::cout << "******* "<< name << " *******"<<std::endl; std::cout << p_mean << std::endl; std::cout << "******************************" <<std::endl; TH1F* bH = (TH1F*)bHd->Clone(Form("%s",name)); TH1F* bHf = (TH1F*)bHfd->Clone(Form("%s_fail",name)); const char* drawInput = Form("(%s-%f)/%f",name,p_mean,p_mean); tree_->Draw(Form("%s>>%s",drawInput,name),""); tree_->Draw(Form("%s>>%s_fail",drawInput,name),selectString.c_str(),"same"); fitPull = true; fitPullf = true; bHf->SetLineColor(2); bH->GetXaxis()->SetTitle(bH->GetTitle()); bH->GetYaxis()->SetTitle(Form("no toys (%d total)",nToysInTree)); bH->GetYaxis()->SetTitleOffset(1.05); bH->GetXaxis()->SetTitleOffset(0.9); bH->GetYaxis()->SetTitleSize(0.05); bH->GetXaxis()->SetTitleSize(0.05); bH->GetXaxis()->SetTitle(Form("%s",name)); bH->SetTitle(""); if ( bH->Integral() <=0 ) fitPull = false; if (fitPull) {bH->Fit("gaus"); bH->GetFunction("gaus")->SetLineColor(4);} if ( bHf->Integral() <=0 ) fitPullf = false; if (fitPullf) {bHf->Fit("gaus"); bHf->GetFunction("gaus")->SetLineColor(2);} c->Clear(); TPad pad1("t1","",0.01,0.01,0.66,0.95); TPad pad2("t2","",0.70,0.20,0.98,0.80); pad1.SetNumber(1); pad2.SetNumber(2); if ( isFitted ) {pad2.Draw();} pad1.Draw(); pad1.SetGrid(true); TLatex *titletext = new TLatex();titletext->SetNDC(); c->cd(1); bH->Draw(); bHf->Draw("same"); TLegend *legend = new TLegend(0.6,0.8,0.9,0.89); legend->SetFillColor(0); legend->AddEntry(bH,"All Toys","L"); legend->AddEntry(bHf,selectString.c_str(),"L"); legend->Draw(); if (fitPull){ c->cd(2); double gap; TLatex *tlatex = new TLatex(); tlatex->SetNDC(); if (fitPullf) {tlatex->SetTextSize(0.09); gap=0.12;} else {tlatex->SetTextSize(0.11);gap=0.14;} tlatex->SetTextColor(4); tlatex->DrawLatex(0.11,0.80,Form("Mean : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParError(1))); tlatex->DrawLatex(0.11,0.80-gap,Form("Sigma : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(2),bH->GetFunction("gaus")->GetParError(2))); if (fitPullf){ tlatex->SetTextColor(2); tlatex->DrawLatex(0.11,0.60,Form("Mean : %.3f #pm %.3f",bHf->GetFunction("gaus")->GetParameter(1),bHf->GetFunction("gaus")->GetParError(1))); tlatex->DrawLatex(0.11,0.60-gap,Form("Sigma : %.3f #pm %.3f",bHf->GetFunction("gaus")->GetParameter(2),bHf->GetFunction("gaus")->GetParError(2))); } tlatex->SetTextSize(0.10); tlatex->SetTextColor(1); tlatex->DrawLatex(0.11,0.33,Form("Pre-fit: %.3f",p_mean)); pullSummaryMap[name]=std::make_pair<double,double>(bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParameter(2)); nPulls++; } // double titleSize = isFitted ? 0.1 : 0.028; //titletext->SetTextSize(titleSize);titletext->SetTextAlign(21); titletext->DrawLatex(0.55,0.92,name); c->SaveAs(Form("%s_normresiduals_%s.pdf",treename.c_str(),(do7TeV ? "7TeV": "8TeV"))); c->SaveAs(Form("mlfit/%s_residual_%s_%s.pdf",name,treename.c_str(),(do7TeV ? "7TeV": "8TeV"))); fOut->WriteObject(c,Form("%s_%s",treename.c_str(),name)); } if (nPulls>0){ std::cout << "Generating Pull Summaries" <<std::endl; int nRemainingPulls = nPulls; TCanvas *hc = new TCanvas("hc","",3000,2000); hc->SetGrid(0); std::map < const char*, std::pair <double,double> >::iterator pull_it = pullSummaryMap.begin(); std::map < const char*, std::pair <double,double> >::iterator pull_end = pullSummaryMap.end(); int pullPlots = 1; while (nRemainingPulls > 0){ int nThisPulls = min(maxPullsPerPlot,nRemainingPulls); TH1F pullSummaryHist("pullSummary","",nThisPulls,0,nThisPulls); for (int pi=1;pull_it!=pull_end && pi<=nThisPulls ;pull_it++,pi++){ pullSummaryHist.GetXaxis()->SetBinLabel(pi,(*pull_it).first); pullSummaryHist.SetBinContent(pi,((*pull_it).second).first); pullSummaryHist.SetBinError(pi,((*pull_it).second).second); nRemainingPulls--; } pullSummaryHist.SetMarkerStyle(21);pullSummaryHist.SetMarkerSize(1.5);pullSummaryHist.SetMarkerColor(2);pullSummaryHist.SetLabelSize(pullLabelSize); pullSummaryHist.GetYaxis()->SetRangeUser(-1,1);pullSummaryHist.GetYaxis()->SetTitle("residual summary (relative)");pullSummaryHist.Draw("E1"); hc->SaveAs(Form("%s_normresiduals_%s.pdf",treename.c_str(),(do7TeV ? "7TeV": "8TeV"))); hc->SaveAs(Form("mlfit/residual_summary_%d_%s_%s.pdf",pullPlots,treename.c_str(),(do7TeV ? "7TeV": "8TeV"))); fOut->WriteObject(hc,Form("comb_pulls_%s_%d",treename.c_str(),pullPlots)); // hc->SaveAs(Form("comb_pulls_%s_%d.pdf",treename.c_str(),pullPlots)); pullPlots++; } delete hc; } c->SaveAs(Form("%s_normresiduals_%s.pdf]",treename.c_str(),(do7TeV ? "7TeV": "8TeV"))); fOut->Close(); delete c; return; }
void TrigWeightFit1D(){ TFile *f = new TFile("../data/scale_factors/HLTEffParkedABCD_1D.root"); TFile *out = new TFile("HLTEffParkedABCD_1DFit.root","RECREATE"); unsigned nVars=4; std::vector<std::string> histstofit[4]; std::vector<std::string> mjjhists; mjjhists.push_back("hData_MJJ_1D_A"); mjjhists.push_back("hData_MJJ_1D_BC"); mjjhists.push_back("hData_MJJ_1D_D"); std::vector<std::string> metl1hists; metl1hists.push_back("hData_MET_L1_A"); metl1hists.push_back("hData_MET_L1_BC"); metl1hists.push_back("hData_MET_L1_D"); std::vector<std::string> methists; methists.push_back("hData_MET_1D_A"); methists.push_back("hData_MET_1D_BC"); methists.push_back("hData_MET_1D_D"); std::vector<std::string> jet2hists; jet2hists.push_back("hData_JET2_1D_A"); jet2hists.push_back("hData_JET2_1D_BC"); jet2hists.push_back("hData_JET2_1D_D"); histstofit[0]=mjjhists; histstofit[1]=metl1hists; histstofit[2]=methists; histstofit[3]=jet2hists; //create a function with 3 parameters in the range [-3,3] for(unsigned iVar=0;iVar<nVars;iVar++){ for(unsigned iTurnon=0;iTurnon<histstofit[iVar].size();iTurnon++){ TH1F *hpx = (TH1F*)f->Get(histstofit[iVar][iTurnon].c_str()); //LOOP OVER THE TRIG TURN ONS double rangelow,rangehigh; if(iVar==0){ rangelow=600; rangehigh=2200; } else if(iVar==1){ rangelow=60; rangehigh=400; } else if(iVar==2){ rangelow=0; rangehigh=400; } else if(iVar==3){ rangelow=0; rangehigh=100; } TF1 *func = new TF1("erf","0.5*(1+TMath::Erf((x-[0])/(sqrt([1]))))",rangelow,rangehigh); func->SetParameters(100,10000); func->SetParNames("Turn On","Sigma"); func->SetParLimits(0,-10000,10000); func->SetParLimits(1,0,100000); hpx->Fit("erf","R"); TCanvas *c1=new TCanvas(); hpx->Draw(); c1->SaveAs((histstofit[iVar][iTurnon]+".pdf").c_str()); TF1 *fitresult=hpx->GetFunction("erf"); //Get name to save as std::string outname=histstofit[iVar][iTurnon].substr(1); out->WriteObject(fitresult,("f"+outname).c_str()); } } }
void plotTree(TTree *tree_, std::string whichfit, std::string selectString){ // Create a map for plotting the pullsummaries: std::map < const char*, std::pair <double,double> > pullSummaryMap; int nPulls=0; TObjArray *l_branches = tree_->GetListOfBranches(); int nBranches = l_branches->GetEntries(); TCanvas *c = new TCanvas("c","",960,800); std::string treename = tree_->GetName(); c->SaveAs(Form("%s.pdf[",treename.c_str())); for (int iobj=0;iobj<nBranches;iobj++){ TBranch *br =(TBranch*) l_branches->At(iobj); // Draw the normal histogram const char* name = br->GetName(); bool fitPull=false; bool plotLH=false; TGraph *gr=0; double p_mean =0; double p_err =0; int nToysInTree = tree_->GetEntries(); if (doPull && findNuisancePre(name)){ p_mean = bfvals_[name].first; // toy constrainits thrown about best fit to data p_err = prevals_[name].second; // uncertainties taken from card const char* drawInput = Form("(%s-%f)/%f",name,p_mean,p_err); tree_->Draw(Form("%s>>%s",drawInput,name),""); tree_->Draw(Form("%s>>%s_fail",drawInput,name),selectString.c_str(),"same"); fitPull = true; if (doLH) { gr = graphLH(name,p_err,whichfit); plotLH=true; } } else{ tree_->Draw(Form("%s>>%s",name,name),""); tree_->Draw(Form("%s>>%s_fail",name,name),"mu<0","same"); } TH1F* bH = (TH1F*) gROOT->FindObject(Form("%s",name))->Clone(); TH1F* bHf = (TH1F*) gROOT->FindObject(Form("%s_fail",name))->Clone(); bHf->SetLineColor(2); bH->GetXaxis()->SetTitle(bH->GetTitle()); bH->GetYaxis()->SetTitle(Form("no toys (%d total)",nToysInTree)); bH->GetYaxis()->SetTitleOffset(1.32); bH->SetTitle(""); if (fitPull) bH->Fit("gaus"); c->Clear(); TPad pad1("t1","",0.01,0.02,0.59,0.98); TPad pad2("t2","",0.59,0.04,0.98,0.62); TPad pad3("t3","",0.59,0.64,0.98,0.90); pad1.SetNumber(1); pad2.SetNumber(2); pad3.SetNumber(3); pad1.Draw(); pad2.Draw();pad3.Draw(); pad2.SetGrid(true); c->cd(1); bH->Draw(); bHf->Draw("same"); TLatex *titletext = new TLatex();titletext->SetNDC();titletext->SetTextSize(0.04); titletext->DrawLatex(0.1,0.95,name); TLegend *legend = new TLegend(0.6,0.8,0.9,0.89); legend->SetFillColor(0); legend->AddEntry(bH,"All Toys","L"); legend->AddEntry(bHf,selectString.c_str(),"L"); legend->Draw(); if (doPull && plotLH) { c->cd(2); gr->Draw("ALP"); } if (fitPull){ c->cd(3); TLatex *tlatex = new TLatex(); tlatex->SetNDC(); tlatex->SetTextSize(0.12); tlatex->DrawLatex(0.15,0.75,Form("Mean : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParError(1))); tlatex->DrawLatex(0.15,0.60,Form("Sigma : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(2),bH->GetFunction("gaus")->GetParError(2))); tlatex->DrawLatex(0.15,0.35,Form("Pre-fit : %.3f ",prevals_[name].first)); tlatex->DrawLatex(0.15,0.2,Form("Best-fit (B) : %.3f ",p_mean)); tlatex->DrawLatex(0.15,0.05,Form("Best-fit (S+B): %.3f ",bfvals_sb_[name].first)); pullSummaryMap[name]=std::make_pair<double,double>(bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParameter(2)); nPulls++; } c->SaveAs(Form("%s.pdf",treename.c_str())); } if (doPull && nPulls>0){ int nRemainingPulls = nPulls; TCanvas *hc = new TCanvas("hc","",3000,2000); hc->SetGrid(0); std::map < const char*, std::pair <double,double> >::iterator pull_it = pullSummaryMap.begin(); std::map < const char*, std::pair <double,double> >::iterator pull_end = pullSummaryMap.end(); while (nRemainingPulls > 0){ int nThisPulls = min(15,nRemainingPulls); TH1F pullSummaryHist("pullSummary","",nThisPulls,0,nThisPulls); for (int pi=1;pull_it!=pull_end && pi<=nThisPulls ;pull_it++,pi++){ pullSummaryHist.GetXaxis()->SetBinLabel(pi,(*pull_it).first); pullSummaryHist.SetBinContent(pi,((*pull_it).second).first); pullSummaryHist.SetBinError(pi,((*pull_it).second).second); nRemainingPulls--; } pullSummaryHist.SetMarkerStyle(21);pullSummaryHist.SetMarkerSize(1.5);pullSummaryHist.SetMarkerColor(2);pullSummaryHist.SetLabelSize(0.018); pullSummaryHist.GetYaxis()->SetRangeUser(-3,3);pullSummaryHist.GetYaxis()->SetTitle("pull summary");pullSummaryHist.Draw("E1"); hc->SaveAs(Form("%s.pdf",treename.c_str())); } delete hc; } c->SaveAs(Form("%s.pdf]",treename.c_str())); delete c; return; }
void pmt_testing(char* input_file) { Double_t width = 1000; Double_t height = 1000; TCanvas * canvas = new TCanvas("canvas", "PMT Testing", 0, 0, width, height); canvas->SetWindowSize(width + (width - canvas->GetWw()), height + (height - canvas->GetWh())); //Parameters Int_t nbins = 40; Double_t min = 550000; //hist min/max values Double_t max = 600000; //Must be better way to get these! //Initialized variables Int_t num_data_points = 0; Int_t pulse; Int_t channel; Int_t total_channels; const Int_t pedestal = 2020; //how to determine this? TFile *file = new TFile("adc_data.root", "recreate"); //Style settings gROOT->SetStyle("Plain"); gStyle->SetPalette(53); gStyle->SetOptStat(111111); gStyle->SetOptFit(1111); gStyle->SetStatBorderSize(0); gStyle->SetOptTitle(1); //Prepare Data //Create nTuple TTree *t1 = new TTree("t1", "ADC Data"); t1->Branch("pulse", &pulse, "pulse/I"); t1->Branch("channel", &channel, "channel/I"); ifstream in; in.open(input_file); //Fill TTree while ( in >> channel) { if (num_data_points % 2520 == 0) pulse++; t1->Fill(); num_data_points++; } in.close(); TH1F * spectrum = new TH1F("spectrum", "ADC Spectrum; Accumulated Channels; Counts", nbins, min, max); //spectrum->SetBit(TH1::kCanRebin); spectrum->Sumw2(); for(Int_t i = 0; i < t1->GetEntries(); i++) { t1->GetEntry(i); if (i % 2520 == 0) { cout << "total_channels = " << total_channels << endl; spectrum->Fill(total_channels); total_channels = 0; } total_channels += TMath::Abs(channel - pedestal); } spectrum->SetLineWidth(2); spectrum->SetMarkerColor(kBlack); spectrum->SetLineColor(kBlack); // Fit Gaussian to curve and Draw spectrum->Fit("gaus"); spectrum->GetFunction("gaus")->SetLineColor(kRed); spectrum->Draw("Same"); t1->Write(); spectrum->Write(); }
void howManyPESinglePt(){ const int numRuns = 6; const char* file = "../crunchedFiles/run_00462_crunched.root"; gStyle->SetOptFit(1); gStyle->SetOptStat(0); double pes[16]; double peErrors[16]; double gains[16]; double gainErrors[16]; TCanvas* c1 = new TCanvas(); cout << "starting loop " << endl; for(int row = 2; row < 6; ++row){ for(int col = 2; col < 6; ++col){ double mean; double sig; double meanErr; double sigErr; TFile* f = new TFile(file); TTree* t = (TTree*) f->Get("t"); t->Draw(Form("sipm%i%i.energy>>histo%i%i", row,col,row,col),Form("sipm%i%i.valid",row,col)); TH1F* h = (TH1F*) gROOT->FindObject(Form("histo%i%i",row,col)); h->Fit("gaus","0q"); mean = (h->GetFunction("gaus")->GetParameter(1)); sig = (h->GetFunction("gaus")->GetParameter(2)); meanErr = (h->GetFunction("gaus")->GetParError(1)); sigErr = (h->GetFunction("gaus")->GetParError(2)); double variance = sig*sig; double varianceError = 2*sig*sigErr; UInt_t index = (row-2)*4 + (col-2); pes[index] = mean*mean/sig/sig; gains[index] = mean/pes[index]; gainErrors[index] = TMath::Sqrt((2*sig/mean*sigErr)*(2*sig/mean*sigErr)+(sig*sig/mean/mean*meanErr)*(sig*sig/mean/mean*meanErr)); peErrors[index] = TMath::Sqrt((2*mean/sig/sig*sigErr)*(2*mean/sig/sig*sigErr)+(2*mean*mean/sig/sig/sig*sigErr)*(2*mean*mean/sig/sig/sig*sigErr)); /* pes[drs] = 1.0/quadGraph->GetFunction("pol2")->GetParameter(1)*means[0]; gains[drs] = quadGraph->GetFunction("pol2")->GetParameter(1); gainErrors[drs] = quadGraph->GetFunction("pol2")->GetParError(1); peErrors[drs] = TMath::Sqrt((1/gains[drs]*meanErrs[0])*(1/gains[drs]*meanErrs[0])+ (means[0]/(gains[drs]*gains[drs])*gainErrors[drs])*(means[0]/(gains[drs]*gains[drs])*gainErrors[drs])); */ } } for(int i = 0; i <16; ++i){ cout << "SiPM " << 2+i/4 << 2+i%4 << " --- " << "p1 : " << gains[i] << ", " << pes[i] << " photoelectrons at open filter." << endl; } TGraphErrors* peGainGraph = new TGraphErrors(16, gains, pes, gainErrors, peErrors); peGainGraph->SetMarkerStyle(20); peGainGraph->GetXaxis()->SetTitle("gain"); peGainGraph->GetYaxis()->SetTitle("PE at open filter"); c1->SetGridx(); c1->SetGridy(); peGainGraph->Draw("ap"); cout << "drew graph " << endl; TCanvas* c2 = new TCanvas(); TH2F* peMap = new TH2F("pes","PE Map", 4,0,4,4,0,4); for(int i = 0; i < 16; ++i){ peMap->Fill(.5+i%4, 3.5-i/4, pes[i]); } peMap->GetXaxis()->SetLabelOffset(99); peMap->GetYaxis()->SetLabelOffset(99); c2->SetTickx(0); c2->SetTicky(0); peMap->Draw("TEXT"); TCanvas* c3 = new TCanvas(); TH2F* gainMap = new TH2F("gains","Gain Map", 4,0,4,4,0,4); for(int i = 0; i < 16; ++i){ gainMap->Fill(.5+i%4, 3.5-i/4, gains[i]); } gainMap->GetXaxis()->SetLabelOffset(99); gainMap->GetYaxis()->SetLabelOffset(99); gainMap->Draw("TEXT"); }
int rdEztFeePed( int nEve=3000, Int_t nFiles = 20, char* file="R5135068ezB.lis", char* inDir = "../oldPanitkin/muDst/", TString outPath="feePed4/" ){ // file="st_physics_6008023_raw_1030001.MuDst.root";// pedestal, 1987eve file="st_physics_6008016_raw_1020001.MuDst.root";// commisCu, ~20Keve // inDir = "./"; gROOT->LoadMacro("$STAR/StRoot/StMuDSTMaker/COMMON/macros/loadSharedLibraries.C"); loadSharedLibraries(); cout << " loading done " << endl; assert( !gSystem->Load("StEEmcPoolmuEztFeePed")); // assert( !gSystem->Load("StEEmcUtil")); // create chain chain = new StChain("StChain"); printf("adding muDst from '%s' ....\n",file); // Now we add Makers to the chain... muMk = new StMuDstMaker(0,0,inDir,file,"MuDst.root",nFiles); TChain* tree=muMk->chain(); assert(tree); int nEntries=tree->GetEntries(); printf("total eve in chain =%d\n",nEntries); printf("in=%s%s=\n",inDir,file); //return; HList=new TObjArray; myMk3=new StFeePedMaker("eeFeePed","MuDst"); myMk3->SetHList(HList); gMessMgr->SwitchOff("D"); gMessMgr->SwitchOn("I"); muMk->SetStatus("*",0); muMk->SetStatus("EztAll",1); chain->Init(); chain->ls(3); // muMk->printArrays(); printf("All Ezt-branches set\n"); int eventCounter=0; int stat=0; int t1=time(0); StMuTimer timer; timer.start(); //--------------------------------------------------- while ( 1) {// loop over events if(eventCounter>=nEve) break; eventCounter++; chain->Clear(); stat = chain->Make(); if(stat) break; if(eventCounter%1000!=0)continue; printf("\n\n ====================%d processing ==============\n", eventCounter); } printf("sorting done, nEve=%d of %d\n",nEve, nEntries); int t2=time(0); if(t1==t2) t2++; float rate=1.*eventCounter/(t2-t1); float nMnts=(t2-t1)/60.; printf("sorting done %d of nEve=%d, elapsed rate=%.1f Hz, tot %.1f minutes\n",eventCounter,nEntries,rate,nMnts); if (eventCounter) { cout << "CPU time/event= " << timer.elapsedTime()/eventCounter << " sec " << " rate= " << eventCounter/timer.elapsedTime() << " Hz" << endl; } //-------------------- calculate FEE peds & produce output files ------ printf("name Nentries chi2 gaus_ampl gaus_mean gaus_sig err_ampl err_mean err_sig \n"); TIterator* iter = HList->MakeIterator(); TH1F* h; char oName[100]; FILE *fo; oName[0]=0; int nPed=0; TString fName=outPath+"eemcPed4.dat"; FILE *fo2=fopen(fName.Data(),"w"); while((h=(TH1F*)iter->Next())) { char *txt=h->GetName(); int cr=atoi(txt+2); int chan=atoi(txt+6); int ped4=0; if(chan%32==0) { if(oName[0]) fclose(fo); sprintf(oName,"%scrate%dboard%d.ped4",outPath.Data(),cr, 1+chan/32); FILE *fo=fopen(oName,"w"); if(fo==0) { printf("\n\nDid you created dir=%s ??? ,JB\n\n",outPath.Data()); printf("ABORT macro\n"); assert(fo); } printf(" write to '%s'\n",oName); } int ret=-1; // Fit range max -low, max+high, default: max-5, max+4 if(cr==4 && chan==127) ret=myMk3->fitPed(h,20); // just example else ret=myMk3->fitPed(h); if (ret) { printf("%s empty\n",h->GetName()); fprintf(fo2," %d %3d 5000 %d\n",cr,chan,ped4); fprintf(fo," %d\n",ped4); continue; } TF1* fit= h->GetFunction("pedFun"); assert(fit); nPed++; // fit->Print(); return; float ped=fit->GetParameter(1); int ped4=(25-ped)/4; if(ped>24) ped4=(22-ped)/4; fprintf(fo2,"%d %d %.1f %d\n",cr,chan,ped,ped4); fprintf(fo,"%d\n",ped4); printf("%s %8.0f %8.3f %9.3f %8.2f %7.2f %6.2f %7.2f %6.2f\n", h->GetName(), h->GetEntries(), fit->GetChisquare(), fit->GetParameter(0), fit->GetParameter(1), // pedestal centroid fit->GetParameter(2), // sigma of gaussian fit->GetParError(0), fit->GetParError(1), fit->GetParError(2)); // break; } myMk3->saveHisto(outPath+"feePed"); fclose(fo2); fclose(fo); printf("Fit found %d pedestals\n",nPed); // h=(TH1F*)HList->FindObject("cr5_ch095"); // this is 'stuck bit' channel h=(TH1F*)HList->FindObject("cr5_ch094"); // a regular channel h->Draw(); gPad->SetLogy(); }
void AnalyzeData(char *DataFile = "drs4_peds_5buffers.dat", Int_t nevt, Int_t startEv = 1, char *PedFile, Int_t DrawExtraGraphs = 0) { // Redefine DOMINO Depth in ADC counts const Float_t DominoDepthADC = pow(2, DOMINO_DEPTH); // open file FILE *fdata = OpenDataFile(DataFile); struct channel_struct *p; struct channel_struct *dep; // create histograms // create list of histograms for channels and distribution TList *DistChList = new TList(); TH1F *distch; // histo with distribution of cell-charge, for each channel TList *DistChSubList = new TList(); TH1F *distchsub; // histo with distribution of cell-charge, pedestals subtracted, for each channel TList *DistCh0SubList = new TList(); TH1F *distch0sub; // histo with distribution of cell-charge, pedestals subtracted, // channel 0 subtracted for each channel TList *grPedList = new TList(); TGraphErrors *grPed; // for each channel, pedestal value and RMS for each cell is plotted TList *hCellList = new TList(); TH1F *hCell; // charge distribution for each cell (DOMINO_NCELL x DOMINO_NCH histos) TList *hCellSubList = new TList(); TH1F *hCellSub; // charge distribution for each cell (DOMINO_NCELL x DOMINO_NCH histos), pedestal subtracted TList *hRMSList = new TList(); TH1F *hRMSdist; // histo with RMS distribution (statistical RMS of distribution) TList *hRMSFitList = new TList(); TH1F *hRMSFitdist; // histo with RMS distribution (RMS of Gaussian fit) TList *grDataList = new TList(); TGraphErrors *grData; // charge-cell and RMS for each cell is plotted TList *grDataSubList = new TList(); TGraphErrors *grDataSub; // pedestal subtracted charge-cell and RMS for each cell is plotted for (int h = 0; h < DOMINO_NCH; h++) { // TString title = "Data Dist channel"; title += h; distch = new TH1F(title, title, DominoDepthADC, 0., DominoDepthADC); DistChList->Add(distch); // TString title = "Data Dist Ped Sub channel"; title += h; distchsub = new TH1F(title, title, DominoDepthADC, -DominoDepthADC/2, DominoDepthADC/2); DistChSubList->Add(distchsub); // TString title = "Data Dist Ped Ch0 Sub channel"; title += h; distch0sub = new TH1F(title, title, DominoDepthADC, -DominoDepthADC/2, DominoDepthADC/2); DistCh0SubList->Add(distch0sub); // TString title = "Pedestal ch"; title += h; grPed = new TGraphErrors(DOMINO_NCELL); grPed->SetTitle(title); grPedList->Add(grPed); // TString title = "Data ch"; title += h; grData = new TGraphErrors(DOMINO_NCELL); grData->SetTitle(title); grDataList->Add(grData); // // Mean data and RMS for each channel and cell TString title = "Data PedSubtracted ch"; title += h; grDataSub = new TGraphErrors(DOMINO_NCELL); grDataSub->SetTitle(title); grDataSubList->Add(grDataSub); // for (int ch = 0; ch < DOMINO_NCELL; ch++) { // data distribution histos TString title = "Data ch"; title += h; title += " cell"; title += ch; hCell = new TH1F(title, title, DominoDepthADC, 0., DominoDepthADC); hCellList->Add(hCell); // data (ped subtracted) distribution histos TString title = "Data PedSub ch"; title += h; title += " cell "; title += ch; hCellSub = new TH1F(title, title, 2 * DominoDepthADC, -1 * DominoDepthADC, DominoDepthADC); hCellSubList->Add(hCellSub); } // Data-RMS distribution histos TString title = "RMSDist channel"; title += h; hRMSdist = new TH1F(title, title, 100, 0, 20.); hRMSList->Add(hRMSdist); // Data-RMS (calculated through a fit) distribution histos TString title = "RMSFitDist channel"; title += h; hRMSFitdist = new TH1F(title, title, 100, 0, 20.); hRMSFitList->Add(hRMSFitdist); } //-------------- // // calculate or read pedestals from file grPedList = OpenPedestals(PedFile); // return; // // ====== Read data file and subtract the pedestals // // Count number of events in data file int nevtDataMax = 0; while (!feof(fdata)) { fread((void *) &event_data, 1, sizeof(event_data), fdata); nevtDataMax++; } printf("nevtDataMax: %d\n", nevtDataMax); if (nevt > (nevtDataMax - startEv) || nevt == 0) nevt = nevtDataMax - startEv; cout << endl << "==>> Processing " << nevt << " events from file " << DataFile << endl; rewind(fdata); Int_t ievt = 1; // go to first event (startEv) while (ievt < startEv) { fread((void *) &event_data, 1, sizeof(event_data), fdata); if (feof(fdata)) break; ievt++; } // filling ievt = 1; Int_t flagEnd = 0; Double_t chtmp; Double_t PedVal, itmp, Ch0Val; // loop on events cout << endl << " --- read DATA file:" << fdata << endl; while (ievt <= nevt && !flagEnd) { fread((void *) &event_data, 1, sizeof(event_data), fdata); if (feof(fdata)) flagEnd = 1; if (ievt % (nevt / 10 + 1) == 0) cout << "*" << endl; p = (struct channel_struct *) &event_data.ch[0]; // read bunch of data dep = (struct channel_struct *) &event_data.ch[1]; // read bunch of data TGraphErrors *grCh0 = new TGraphErrors(DOMINO_NCELL); // loop on channels for (int h = 0; h < DOMINO_NCH; h++) { // loop on cells distch = (TH1F *) DistChList->At(h); distchsub = (TH1F *) DistChSubList->At(h); grPed = (TGraphErrors *) grPedList->At(h); distch0sub = (TH1F *) DistCh0SubList->At(h); if(h==0) { for(i = 0; i < DOMINO_NCELL;i++) { grPed->GetPoint(i, itmp, PedVal); chtmp = (Double_t)(p->data[i]); chtmp = chtmp - PedVal; grCh0->SetPoint(i,itmp, chtmp); } } for (int i = 0; i < DOMINO_NCELL; i++) { // Read pedestal value for this cell grPed->GetPoint(i, itmp, PedVal); grCh0->GetPoint(i, itmp, Ch0Val); // cout << itmp << ", " << PedVal << endl; // Read calibration correction for this cell // CalFact = //charge distribution for each cell, pedestal subtracted chtmp = (Double_t)(p->data[i]); // data value // cout << "tcell, tcell, depth: " << chtmp << "," << p->data[i] << "," << deptmp << endl; distch->Fill(chtmp); // Check data value: must be within DOMINO Depth // if(chtmp > DominoDepthADC) // cout << " === WARNING!!! Channel " << h << " Cell " << i << " has value " << chtmp << endl; // cout << "Charge: " << p->data[i] << endl; ((TH1 *) hCellList->At(h * DOMINO_NCELL + i))->Fill(chtmp); // Now the pedestal is subtracted chtmp = chtmp - PedVal; distchsub->Fill(chtmp); ((TH1 *) hCellSubList->At(h * DOMINO_NCELL + i))->Fill(chtmp); chtmp = chtmp - Ch0Val; distch0sub->Fill(chtmp); } p++; // next channel } ievt++; // next event } cout << endl; // now mean and RMS for each cell are computed and save in histos and graphs cout << " --- filling data histos and grphs " << endl; TF1 *fgauss = new TF1("fgauss", Gauss, -10., 10., 3); fgauss->SetParLimits(0, 0.1, 10000.); fgauss->SetParLimits(1, 0., 4096.); fgauss->SetParLimits(2, 0.1, 20.); Float_t mean, rms, meansub, rmssub; for (int h = 0; h < DOMINO_NCH; h++) { // for (int h=5; h<6; h++){ cout << " Channel:" << h << endl; hRMSdist = (TH1F *) hRMSList->At(h); hRMSFitdist = (TH1F *) hRMSFitList->At(h); grData = (TGraphErrors *) grDataList->At(h); grDataSub = (TGraphErrors *) grDataSubList->At(h); for (int ch = 0; ch < DOMINO_NCELL; ch++) { // data distribution histos // cout << "cell:" << ch << " index:" << h*DOMINO_NCELL+ch << " Mean,RMS:"<<hCell->GetMean()<< "," << hCell->GetRMS()<<endl; hCell = (TH1F *) hCellList->At(h * DOMINO_NCELL + ch); mean = hCell->GetMean(); rms = hCell->GetRMS(); hCellSub = (TH1F *) hCellSubList->At(h * DOMINO_NCELL + ch); meansub = hCellSub->GetMean(); rmssub = hCellSub->GetRMS(); fgauss->SetParameter(0, (Double_t) nevt / 4.); fgauss->SetParameter(1, mean); fgauss->SetParameter(2, rms); // hCell->Fit("fgauss","QN0"); grData->SetPoint(ch, ch, mean); grData->SetPointError(ch, 0, rms); grDataSub->SetPoint(ch, ch, meansub); // grDataSub->SetPointError(ch,0.5,rmssub); grDataSub->SetPointError(ch, 0.5, 2.1); hRMSdist->Fill(rms); hRMSFitdist->Fill(fgauss->GetParameter(2)); // cout << "cell:" << ch << " index:" << h*DOMINO_NCELL+ch << " Mean,RMS:"<< mean << "," << rms<<endl; } } Double_t x, y, chtmp, x1, x2, y1, y2; /*TList *grCellCalibList = OpenCalibFile("CalibrationData1000events.root"); TGraphErrors *grCellCalib; TGraphErrors *grDataSubCalib = new TGraphErrors(DOMINO_NCELL); grDataSubCalib->SetTitle("Data after calibration correction"); grDataSub = (TGraphErrors *) grDataSubList->At(anaChannel); for(ch = 0; ch < DOMINO_NCELL; ch++) { grCellCalib = ((TGraphErrors *) grCellCalibList->At(ch)); grCellCalib->Fit("pol3", "Q"); TF1 *pol3fit = ((TF1 *) grCellCalib->GetFunction("pol3")); grDataSub->GetPoint(ch, x, y); chtmp = y - (Double_t)(pol3fit->Eval(y/3.25)); grDataSubCalib->SetPoint(ch, x, chtmp); } TCanvas *cGrTest = new TCanvas("grTest", "test per vedere i dati", 1000,1000); grDataSubCalib->Draw("APEL");*/ TString Title = "Charge Distribution per channel"; gStyle->SetOptFit(111); TCanvas *cdistch = new TCanvas("cdistch", Title, 1000, 1000); cdistch->Divide(3, 3); for (int i = 0; i < DOMINO_NCH; i++) { cdistch->cd(i + 1); TH1 *dhist = (TH1 *) DistChList->At(i); dhist->DrawCopy(); dhist->SetLineWidth(1); dhist->Fit("gaus", "Q"); dhist->GetFunction("gaus")->SetLineColor(4); dhist->GetFunction("gaus")->SetLineWidth(2); } TString Title = "Charge Distribution Pedestals Subtracted per channel"; TCanvas *cdistchsub = new TCanvas("cdistchsub", Title, 1000, 1000); cdistchsub->Divide(3, 3); for (int i = 0; i < DOMINO_NCH; i++) { cdistchsub->cd(i + 1); TH1 *dsubhist = (TH1 *) DistChSubList->At(i); dsubhist->DrawCopy(); dsubhist->SetLineWidth(1); dsubhist->Fit("gaus", "Q"); dsubhist->GetFunction("gaus")->SetLineColor(4); dsubhist->GetFunction("gaus")->SetLineWidth(2); } TString Title = "Charge Distribution Pedestals and Ch0 Subtracted per channel"; TCanvas *cdistch0sub = new TCanvas("cdistch0sub", Title, 1000, 1000); cdistch0sub->Divide(3, 3); for (int i = 0; i < DOMINO_NCH; i++) { cdistch0sub->cd(i + 1); TH1 *dch0subhist = (TH1 *) DistCh0SubList->At(i); dch0subhist->DrawCopy(); dch0subhist->SetLineWidth(1); dch0subhist->Fit("gaus", "Q"); dch0subhist->GetFunction("gaus")->SetLineColor(4); dch0subhist->GetFunction("gaus")->SetLineWidth(2); } TCanvas *cDataSubTest = new TCanvas("cDataSubTest", "Data after pedestal subtraction", 1000, 1000); cDataSubTest->Divide(1,8); for (h = 0; h< DOMINO_NCH; h++) { grDataSub = (TGraphErrors *) grDataSubList->At(h); cDataSubTest->cd(h+1); grDataSub->GetYaxis()->SetLabelSize(0.06); grDataSub->GetXaxis()->SetLabelSize(0.06); grDataSub->Draw("APE"); } TCanvas *cDataSubTestCh5 = new TCanvas("cDataSubTestCh5", "Data after pedestal subtraction Ch5", 1200, 800); grDataSub = (TGraphErrors *) grDataSubList->At(anaChannel); grDataSub->GetYaxis()->SetLabelSize(0.06); grDataSub->GetYaxis()->SetTitle("ADC Counts"); grDataSub->GetXaxis()->SetTitle("Cell"); grDataSub->GetXaxis()->SetLabelSize(0.06); TLine *refval = new TLine(0,350,1024,350); refval->SetLineWidth(3); refval->SetLineStyle(2); refval->SetLineColor(2); TLine *i1 = new TLine(121,-50,121,800); i1->SetLineStyle(2); TLine *i2 = new TLine(291,-50,291,800); i2->SetLineStyle(2); TLine *i3 = new TLine(461,-50,461,800); i3->SetLineStyle(2); TLine *i4 = new TLine(632,-50,632,800); i4->SetLineStyle(2); TLine *i5 = new TLine(803,-50,803,800); i5->SetLineStyle(2); TLine *i6 = new TLine(975,-50,975,800); i6->SetLineStyle(2); TLine *ireal1 = new TLine(121+20,600,121+20,800); ireal1->SetLineWidth(3); ireal1->SetLineColor(4); TLine *ireal2 = new TLine(291-20,600,291-20,800); ireal2->SetLineWidth(3); ireal2->SetLineColor(4); TLine *ireal3 = new TLine(461+20,600,461+20,800); ireal3->SetLineWidth(3); ireal3->SetLineColor(4); TLine *ireal4 = new TLine(632-20,600,632-20,800); ireal4->SetLineWidth(3); ireal4->SetLineColor(4); TLine *ireal5 = new TLine(803+20,600,803+20,800); ireal5->SetLineWidth(3); ireal5->SetLineColor(4); TLine *ireal6 = new TLine(975-20,600,975-20,800); ireal6->SetLineWidth(3); ireal6->SetLineColor(4); grDataSub->Draw("APE"); refval->Draw("SAME"); i1->Draw("SAME"); i2->Draw("SAME"); i3->Draw("SAME"); i4->Draw("SAME"); i5->Draw("SAME"); i6->Draw("SAME"); ireal1->Draw("SAME"); ireal2->Draw("SAME"); ireal3->Draw("SAME"); ireal4->Draw("SAME"); ireal5->Draw("SAME"); ireal6->Draw("SAME"); TCanvas *cDataTest = new TCanvas("cDataTest", "Raw Data", 1000,1000); cDataTest->Divide(1,8); for(h = 0; h < DOMINO_NCH; h++) { cDataTest->cd(h+1); grData = (TGraphErrors *) grDataList->At(h); grData->SetMarkerStyle(20); grData->SetMarkerSize(0.5); grData->Draw("APE"); } // save root file with graph containing channel 5 data after pedestals subtraction. /* cout << "test" << endl; TString OutFile = DataSubFile; TFile *f = new TFile(OutFile,"RECREATE"); int h = anaChannel; TString key="DataSubGraph"; key += h; ((TGraphErrors*)grDataSubList->At(h))->Write(key); f->Close(); cout << " ---- Write data on file " << endl; */ // =======================================================// // =====================Matteo's Code=====================// // =======================================================// /* Int_t cht, incCht, decCht, xflag, nPeriods, iMax, iMin; Double_t xdiff, incDiff, decDiff, incDiffTemp, decDiffTemp, incXDiff, decXDiff; Double_t fitMax, fitMin, fitPeriod, chisquare; Double_t DominoXval[DOMINO_NCELL]; Double_t DominoYval[DOMINO_NCELL]; Double_t FitXval[DOMINO_NCELL]; Double_t FitYval[DOMINO_NCELL]; // opens grDataSub.root TString FileName = DataSubFile; TGraphErrors *grDataSub; int h = anaChannel; TFile *f = new TFile(FileName); TString key = "DataSubGraph"; key += h; grDataSub = (TGraphErrors *) f->Get(key); f->Close(); // Create a new graph with channel 5 data TGraphErrors *grDataSubAnaCh; int h = anaChannel; grDataSubAnaCh = (TGraphErrors *) grDataSubList->At(h); TGraphErrors *grDataSubFix = grDataSubAnaCh->Clone(); TGraphErrors *grRes = new TGraphErrors(DOMINO_NCELL); TList *grResPeriodList = new TList(); Double_t xtemp, ytemp, DominoMax, DominoMin; for (int ch = 0; ch < DOMINO_NCELL; ch++){ // get domino-output point and save in array grDataSubAnaCh->GetPoint(ch, DominoXval[ch], DominoYval[ch]); } // find the domino point with max y-value iMax = 0; for(int ch = 0; ch < DOMINO_NCELL; ch++) { if(DominoYval[ch] > DominoYval[iMax]) { DominoMax = DominoYval[ch]; iMax = ch; } } cout << "DominoMax e': " << DominoMax << endl; // find the domino point with min y-value iMin = 0; for (int ch = 0; ch < DOMINO_NCELL; ch++) { if(DominoYval[ch] < DominoYval[iMin]) { DominoMin = DominoYval[ch]; iMin = ch; } } cout << "DominoMin e': " << DominoMin << endl; // remove points from the graph that will be used for fit for (int ch = 0; ch < DOMINO_NCELL; ch++){ grDataSubFix->GetPoint(ch, xtemp, ytemp); if(ytemp > 0.8*DominoMax || ytemp < 0.2*DominoMin) grDataSubFix->RemovePoint(ch); } TF1 *fsin = new TF1("fsin", sigSin, 0., 1024., 4); fsin->SetParameters(600., DOMINO_NCELL / 4., 150., 150.); fsin->SetParNames("amplitude", "Period", "Phase", "DC-Offset"); grDataSubFix->Fit("fsin"); TF1 *fsinFit = grDataSubFix->GetFunction("fsin"); fsinFit->SetParNames("amplitude", "Period", "Phase", "DC-Offset"); chisquare = grDataSub->Chisquare(fsinFit); cout << "il chi quadro della funzione di fit e' : " << chisquare << endl; for (int ch = 0; ch < DOMINO_NCELL; ch++) { // get Fit-value and save in array FitXval[ch] = DominoXval[ch]; FitYval[ch] = fsinFit->Eval(FitXval[ch]); } fitPeriod = fsinFit->GetParameter("Period"); cout << "il periodo della funzione e': " << fitPeriod << endl; nPeriods = (Int_t) (DOMINO_NCELL/fitPeriod); cout << "il numero di periodi della funzione e': " << nPeriods << endl; fitMax = fsinFit->GetMaximum(); cout << "il massimo della funzione e': " << fitMax << endl; fitMin = fsinFit->GetMinimum(); cout << "il minimo della funzione e': " << fitMin << endl; // computes the y difference between the ch-domino point and the i-fit point // and stops when the difference changes sign // // first and last points are not included in the cicle // // if the fit point y-value is bigger or smaller than the fit function max*0.8 or min*0.2 // the point is removed for (int ch = 1; ch < DOMINO_NCELL - 1; ch++) { if(FitYval[ch] > 0.8*fitMax || FitYval[ch] < 0.2*fitMin) { grRes->RemovePoint(ch); continue; } incDiff = DominoYval[ch] - FitYval[ch]; incDiffTemp = DominoYval[ch] - FitYval[ch + 1]; decDiff = DominoYval[ch] - FitYval[ch]; decDiffTemp = DominoYval[ch] - FitYval[ch - 1]; if(abs(incDiffTemp) < abs(incDiff) || (sign(incDiff) != sign(incDiffTemp) && abs(decDiffTemp) > abs(decDiff))) { for (int i = ch; i < DOMINO_NCELL; i++, incDiff = incDiffTemp) { incDiffTemp = DominoYval[ch] - FitYval[i]; if (sign(incDiff) != sign(incDiffTemp)) { if(abs(incDiffTemp) < abs(incDiff)) incCht = i; else incCht = i - 1; break; } } xflag = 1; } else if(abs(decDiffTemp) < abs(decDiff) || (sign(decDiff) != sign(decDiffTemp) && abs(incDiffTemp) > abs(incDiff))) { for (int j = ch; j >= 0 ; j--, decDiff = decDiffTemp) { decDiffTemp = DominoYval[ch] - FitYval[j]; if (sign(decDiff) != sign(decDiffTemp)) { if(abs(decDiffTemp) < abs(decDiff)) decCht = j; else decCht = j + 1; break; } } xflag = -1; } if(xflag == 1) xdiff = FitXval[incCht] - DominoXval[ch]; else xdiff = FitXval[decCht] - DominoXval[ch]; grRes->SetPoint(ch, (Double_t) ch, xdiff); } cout << "Draw Time Residuals" << endl; TString Title = "Time Residuals"; TCanvas *timeres = new TCanvas("timeres", Title, 1200, 780); grRes->SetMarkerStyle(20); grRes->SetMarkerSize(0.3); grRes->GetYaxis()->SetLabelSize(0.12); grRes->GetXaxis()->SetLabelSize(0.12); grRes->Draw("APE"); // The previous graph is now split in N graphs, where N is the number of fit periods // this will be needed to set the function phase // // iMax = 0; // // for(ch = 0; ch < fitPeriod - 1; ch++) { // if(FitYval[ch] > FitYval[iMax]) iMax = ch; // } cout << "il primo massimo ha l'indice : " << iMax << endl; for (i = 0; i < nPeriods; i++) { TGraphErrors *grResPeriod = new TGraphErrors((Int_t) fitPeriod); grResPeriodList->Add(grResPeriod); for(ch = i*fitPeriod + 1; ch < fitPeriod + (i*fitPeriod); ch++) { if(FitYval[ch] > 0.8*fitMax || FitYval[ch] < 0.2*fitMin) { grResPeriod->RemovePoint(ch); continue; } incDiff = DominoYval[ch] - FitYval[ch]; incDiffTemp = DominoYval[ch] - FitYval[ch + 1]; decDiff = DominoYval[ch] - FitYval[ch]; decDiffTemp = DominoYval[ch] - FitYval[ch - 1]; if(abs(incDiffTemp) < abs(incDiff) || (sign(incDiff) != sign(incDiffTemp) && abs(decDiffTemp) > abs(decDiff))) { for (int k = ch; k < k*fitPeriod + fitPeriod; k++, incDiff = incDiffTemp) { incDiffTemp = DominoYval[ch] - FitYval[k]; if (sign(incDiff) != sign(incDiffTemp)) { if(abs(incDiffTemp) < abs(incDiff)) incCht = k; else incCht = k - 1; break; } } xflag = 1; } else if(abs(decDiffTemp) < abs(decDiff) || (sign(decDiff) != sign(decDiffTemp) && abs(incDiffTemp) > abs(incDiff))) { for (int j = ch; j > i*fitPeriod; j--, decDiff = decDiffTemp) { decDiffTemp = DominoYval[ch] - FitYval[j]; if (sign(decDiff) != sign(decDiffTemp)) { if(abs(decDiffTemp) < abs(decDiff)) decCht = j; else decCht = j + 1; break; } } xflag = -1; } if(xflag == 1) xdiff = FitXval[incCht] - DominoXval[ch]; else xdiff = FitXval[decCht] - DominoXval[ch]; grResPeriod->SetPoint(ch - i*fitPeriod, (Double_t) (ch - i*fitPeriod), xdiff); } } TCanvas *timeresperiod = new TCanvas("timeresperiod", "Time Residuals Period", 1200, 780); for(i = 0; i < nPeriods; i++) { grResPeriod = ((TGraphErrors *) grResPeriodList->At(i)); grResPeriod->SetMarkerStyle(20); grResPeriod->SetMarkerSize(0.3); grResPeriod->GetYaxis()->SetLabelSize(0.12); grResPeriod->GetXaxis()->SetLabelSize(0.12); grResPeriod->Draw("APEsame"); } cout << "Draw Data - Pedestals Subtracted" << endl; TString Title = "Average Charge - Pedestal subtracted"; TCanvas *csubdata = new TCanvas("csubdata", Title, 1200, 780); grDataSubAnaCh->SetMarkerStyle(20); grDataSubAnaCh->SetMarkerSize(0.3); grDataSubAnaCh->GetYaxis()->SetLabelSize(0.12); grDataSubAnaCh->GetXaxis()->SetLabelSize(0.12); grDataSubAnaCh->Draw("APE"); fsinFit->Draw("same"); */ // draw extra graphs if (DrawExtraGraphs == 1) { cout << " ----- DRAW Results ------" << endl; //================ DRAW Results ================== TCanvas *c = new TCanvas("ctmp", "test", 800, 800); c->Divide(3, 3); for (int pad = 1; pad < 10; pad++) { c->cd(pad); ((TH1 *) hCellList->At(pad * 512 + 219))->DrawCopy(); hCellSub = (TH1F *) hCellSubList->At(pad * 512 + 219); hCellSub->SetLineColor(2); hCellSub->DrawCopy("same"); } cout << "Draw RMS distributions" << endl; TString Title = "RMS distributions per channel"; TCanvas *c4 = new TCanvas("c4", Title, 700, 700); c4->Divide(3, 3); for (int i = 0; i < DOMINO_NCH; i++) { c4->cd(i + 2); hRMSdist = (TH1F *) hRMSList->At(i); hRMSFitdist = (TH1F *) hRMSFitList->At(i); hRMSFitdist->SetLineColor(2); hRMSFitdist->DrawCopy(); hRMSdist->DrawCopy("same"); } TList *grDataCh0SubList = new TList(); TGraphErrors *grDataCh0Sub; for(h = 0; h< DOMINO_NCELL; h++) { grDataCh0Sub = new TGraphErrors(DOMINO_NCELL); grDataCh0SubList->Add(grDataCh0Sub); } TGraphErrors *grDataSubCh0 = (TGraphErrors *) grDataSubList->At(6); for(h = 0; h < DOMINO_NCH; h++) { grDataSub = (TGraphErrors *) grDataSubList->At(h); grDataCh0Sub = (TGraphErrors *) grDataCh0SubList->At(h); for(ch = 0; ch < DOMINO_NCELL; ch++) { grDataSubCh0->GetPoint(ch, x1, y1); grDataSub->GetPoint(ch, x2, y2); grDataCh0Sub->SetPoint(ch, x1 , y2 - y1); } } TCanvas *cDataCH0Sub = new TCanvas("cDataCH0Sub","cDataCH0Sub", 1000,1000); cDataCH0Sub->Divide(1,8); for(h = 0; h < DOMINO_NCH; h++) { cDataCH0Sub->cd(h+1); grDataCh0Sub = (TGraphErrors *) grDataCh0SubList->At(h); grDataCh0Sub->GetYaxis()->SetLabelSize(0.12); grDataCh0Sub->GetXaxis()->SetLabelSize(0.12); grDataCh0Sub->Draw("APEL"); } cout << "Draw Data - Pedestals Subtracted" << endl; TString Title = "Average Charge - Pedestal subtracted"; TCanvas *csubdata = new TCanvas("csubdata", Title, 1000, 1000); csubdata->Divide(3,3); for(h = 0; h < DOMINO_NCH; h++) { csubdata->cd(h+1); TString title = "DataSub channel "; title += h; TH1F *hCellDataSub = new TH1F(title, title, 100, -20, 20); grDataSub = (TGraphErrors *) grDataSubList->At(h); for(ch = 0; ch < DOMINO_NCELL; ch++) { grDataSub->GetPoint(ch, x, y); hCellDataSub->Fill(y); } hCellDataSub->Fit("gaus", "Q"); hCellDataSub->GetXaxis()->SetTitle("ADC Counts"); hCellDataSub->GetFunction("gaus")->SetLineColor(4); hCellDataSub->DrawCopy(); } cout << "breakpoint" << endl; TCanvas *csubdata2 = new TCanvas("csubdata2", "DataSub for every channel", 1000, 1000); TString title = "DataSub every channel "; TH1F *hCellChDataSubTot = new TH1F(title, title, 100, -20, 20); for(h = 0; h < DOMINO_NCH; h++) { grDataSub = (TGraphErrors *) grDataSubList->At(h); for(ch = 0; ch < DOMINO_NCELL; ch++) { grDataSub->GetPoint(ch, x, y); hCellChDataSubTot->Fill(y); } hCellChDataSubTot->Fit("gaus", "Q"); hCellChDataSubTot->GetXaxis()->SetTitle("ADC Counts"); hCellChDataSubTot->GetFunction("gaus")->SetLineColor(4); hCellChDataSubTot->Draw(); } cout << "Draw Pedestals" << endl; TString Title = "Pedestals"; TCanvas *c2 = new TCanvas("c2", Title, 1050, 780); c2->SetBorderMode(0); c2->SetBorderSize(0.); c2->Divide(1, 8); // gStyle->SetCanvasBorderMode(0.); // gStyle->SetCanvasBorderSize(0.); Double_t x, y; for (int h = 0; h < DOMINO_NCH; h++) { c2->cd(h + 1); grPed = ((TGraphErrors *) grPedList->At(h)); grPed->SetMarkerStyle(20); grPed->SetMarkerSize(0.5); grPed->GetYaxis()->SetLabelSize(0.12); grPed->GetXaxis()->SetLabelSize(0.12); // cout << " err:" << grPed->GetErrorY(102) << " " ; // cout << x << "--" << y << endl; grPed->Draw("APE"); } cout << "Draw Data - Average charge" << endl; TString Title = "Average_Charge"; TCanvas *cdata = new TCanvas("cdata", Title, 1050, 780); cdata->Divide(1, 8); Double_t x, y; for (int h = 0; h < DOMINO_NCH; h++) { cdata->cd(h + 1); grData = ((TGraphErrors *) grDataList->At(h)); grData->SetMarkerStyle(20); grData->SetMarkerSize(0.3); grData->GetYaxis()->SetLabelSize(0.12); grData->GetXaxis()->SetLabelSize(0.12); grData->GetPoint(10, x, y); // cout << x << "-" << y << endl; grData->Draw("APE"); } cout << "Draw Data - Pedestals Subtracted" << endl; TString Title = "Average Charge - Pedestal subtracted"; TCanvas *csubdata = new TCanvas("csubdata", Title, 1200, 780); csubdata->Divide(1, 8); TF1 *fsin = new TF1("fsin", sigSin, 0., 1024., 4); TH1D *resDist = new TH1D("resDist", "Residuals Signal", 100, -100., 100.); cout << "Draw Data - Pedestals Subtracted" << endl; TString Title = "Residuals"; TCanvas *residuals = new TCanvas("residuals", Title, 1200, 780); resDist->DrawCopy(); } fclose(fdata); hCellList->Delete(); hCellSubList->Delete(); hRMSList->Delete(); hRMSFitList->Delete(); }
int main(int argc, char** argv) { setTDRStyle(); gStyle -> SetOptFit(0000); int nFib = 64; int nCryst = 9; std::string inFileName(argv[1]); //---------- // open file TFile* inFile = TFile::Open(Form("ntuples/tot_capture_%s.root",inFileName.c_str())); TTree* tree = (TTree*)( inFile->Get("tree") ); //--------------------- // set branch addresses std::map<int,std::vector<int>*> t_waveform; std::map<int,std::vector<int>*> t_crystWaveform; for(int fibIt = 0; fibIt < nFib; ++fibIt) { t_waveform[fibIt] = new std::vector<int>; tree -> SetBranchAddress(Form("fib%02d_waveform",fibIt),&t_waveform[fibIt]); } for(int crystIt = 0; crystIt < nCryst; ++crystIt) { t_crystWaveform[crystIt] = new std::vector<int>; tree -> SetBranchAddress(Form("cryst%01d_waveform",crystIt),&t_crystWaveform[crystIt]); } //------------- // define plots std::map<int,int> n_waveform_fib; TGraph** g_waveform_fib = new TGraph*[nFib]; std::map<int,int> n_waveform_cut_fib; TGraph** g_waveform_cut_fib = new TGraph*[nFib]; TH1F** h_ped_fib = new TH1F*[nFib]; TH1F* h_ped_fib_all = new TH1F("h_ped_fib_all","",100,80.,120.); TH1F** h_maximum_fib = new TH1F*[nFib]; TH1F* h_maximum_fib_all = new TH1F("h_maximum_fib_all","",1000,0.,2500.); for(int fibIt = 0; fibIt < nFib; ++fibIt) { g_waveform_fib[fibIt] = new TGraph(); g_waveform_cut_fib[fibIt] = new TGraph(); h_ped_fib[fibIt] = new TH1F(Form("h_ped_fib%02d",fibIt),"",100,80.,120.); h_maximum_fib[fibIt] = new TH1F(Form("h_maximum_fib%02d",fibIt),"",1000,0.,2500.); } TProfile2D* p_fibAveInt = new TProfile2D("p_fibAveInt","",17,-0.5,16.5,18,-0.5,17.5); TProfile2D* p_fibAveMax = new TProfile2D("p_fibAveMax","",17,-0.5,16.5,18,-0.5,17.5); TProfile2D* p_crystAveMax = new TProfile2D("p_crystAveMax","",3,-0.5,2.5,3,-0.5,2.5); TH1F* h_tot_integral = new TH1F("h_tot_integral","",1000,0.,100000.); TH1F* h_tot_maximum = new TH1F("h_tot_maximum", "",1000,0.,1000.); //------------------ // loop over entries for(int entry = 0; entry < tree->GetEntries(); ++entry) { std::cout << ">>> reading entry " << entry << " / " << tree->GetEntries() << "\r" << std::flush; tree -> GetEntry(entry); float tot_integral = 0.; float tot_maximum = 0.; for(int fibIt = 0; fibIt < nFib; ++fibIt) { ++n_waveform_fib[fibIt]; AddWaveform(g_waveform_fib[fibIt],t_waveform[fibIt]); float ped, integral, maximum; CalculateAmplitude(t_waveform[fibIt],ped,integral,maximum); h_ped_fib[fibIt] -> Fill(ped); h_ped_fib_all -> Fill(ped); h_maximum_fib[fibIt] -> Fill(maximum); h_maximum_fib_all -> Fill(maximum); int x = 16-2*int(fibIt/8); int y = (x/2)%2 == 0 ? 16-2*(fibIt%8) : 16-2*(fibIt%8)-1; p_fibAveInt -> Fill(x,y,integral); p_fibAveMax -> Fill(x,y,maximum); if( maximum+ped > 120. ) { tot_integral += integral; tot_maximum += maximum; ++n_waveform_cut_fib[fibIt]; AddWaveform(g_waveform_cut_fib[fibIt],t_waveform[fibIt]); } } for(int crystIt = 0; crystIt < nCryst; ++crystIt) { float ped, integral, maximum; CalculateAmplitude(t_waveform[crystIt],ped,integral,maximum); p_crystAveMax -> Fill(crystIt%3,2-crystIt/3,maximum); } h_tot_integral -> Fill(tot_integral); h_tot_maximum -> Fill(tot_maximum); } TCanvas* c_waveform_fib_all = new TCanvas(); int plotIt = 0; float min = +999999.; float max = -999999.; for(int fibIt = 0; fibIt < nFib; ++fibIt) { TGraph* g = g_waveform_fib[fibIt]; if( g->GetN() == 0 ) continue; NormalizeGraph(g,n_waveform_fib[fibIt]); if( GetMinimum(g) < min ) min = GetMinimum(g); if( GetMaximum(g) > max ) max = GetMaximum(g); } for(int fibIt = 0; fibIt < nFib; ++fibIt) { TGraph* g = g_waveform_fib[fibIt]; if( g->GetN() == 0 ) continue; TCanvas* c_waveform_fib = new TCanvas(); g -> SetMinimum(min-0.05*fabs(max-min)); g -> SetMaximum(max+0.05*fabs(max-min)); g -> SetLineWidth(2); g -> SetLineColor(fibIt+1); g -> SetMarkerSize(0.2); g -> GetXaxis() -> SetTitle("sample time (ns)"); g -> Draw("APL"); c_waveform_fib -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/plotsPerFib/waveform_fib%02d.png",inFileName.c_str(),fibIt),"png"); c_waveform_fib_all -> cd(); if( plotIt == 0 ) g -> Draw("APL"); else g -> Draw("PL,same"); ++plotIt; } c_waveform_fib_all -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/waveform_fib_all.png",inFileName.c_str()),"png"); TCanvas* c_waveform_cut_fib_all = new TCanvas(); plotIt = 0; min = +999999.; max = -999999.; for(int fibIt = 0; fibIt < nFib; ++fibIt) { TGraph* g = g_waveform_cut_fib[fibIt]; if( g->GetN() == 0 ) continue; NormalizeGraph(g,n_waveform_cut_fib[fibIt]); if( GetMinimum(g) < min ) min = GetMinimum(g); if( GetMaximum(g) > max ) max = GetMaximum(g); } for(int fibIt = 0; fibIt < nFib; ++fibIt) { TGraph* g = g_waveform_cut_fib[fibIt]; if( g->GetN() == 0 ) continue; //g -> SetMinimum(min-0.05*fabs(max-min)); //g -> SetMaximum(max+0.05*fabs(max-min)); g -> SetLineWidth(2); g -> SetLineColor(fibIt+1); g -> SetMarkerSize(0.2); g -> GetXaxis() -> SetTitle("sample time (ns)"); g -> Draw("APL"); c_waveform_cut_fib_all -> cd(); if( plotIt == 0 ) g -> Draw("APL"); else g -> Draw("PL,same"); ++plotIt; } c_waveform_cut_fib_all -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/waveform_cut_fib_all.png",inFileName.c_str()),"png"); for(int fibIt = 0; fibIt < nFib; ++fibIt) { TH1F* h = h_ped_fib[fibIt]; TCanvas* c_ped_fib = new TCanvas(); c_ped_fib -> SetLogy(); h -> SetLineWidth(2); h -> GetXaxis() -> SetTitle("max sample"); h -> Draw(); h -> Fit("gaus","Q"); TLatex* latex1 = new TLatex(0.60,0.90,Form("RMS = %.1f",h->GetRMS())); latex1 -> SetNDC(); latex1 -> SetTextFont(42); latex1 -> SetTextSize(0.04); latex1 -> Draw("same"); TLatex* latex2 = new TLatex(0.60,0.85,Form("#sigma = %.1f",h->GetFunction("gaus")->GetParameter(2))); latex2 -> SetNDC(); latex2 -> SetTextFont(42); latex2 -> SetTextSize(0.04); latex2 -> Draw("same"); c_ped_fib -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/plotsPerFib/ped_fib%02d.png",inFileName.c_str(),fibIt),"png"); h = h_maximum_fib[fibIt]; TCanvas* c_maximum_fib = new TCanvas(); c_maximum_fib -> SetLogy(); h -> SetLineWidth(2); h -> GetXaxis() -> SetTitle("max sample"); h -> Draw(); c_maximum_fib -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/plotsPerFib/maximum_fib%02d.png",inFileName.c_str(),fibIt),"png"); } TCanvas* c_ped_fib_all = new TCanvas(); c_ped_fib_all -> SetLogy(); h_ped_fib_all -> SetLineWidth(2); h_ped_fib_all -> GetXaxis() -> SetTitle("pedestal"); h_ped_fib_all -> Draw(); h_ped_fib_all -> Fit("gaus","Q"); TLatex* latex1 = new TLatex(0.60,0.90,Form("RMS = %.1f",h_ped_fib_all->GetRMS())); latex1 -> SetNDC(); latex1 -> SetTextFont(42); latex1 -> SetTextSize(0.04); latex1 -> Draw("same"); TLatex* latex2 = new TLatex(0.60,0.85,Form("#sigma = %.1f",h_ped_fib_all->GetFunction("gaus")->GetParameter(2))); latex2 -> SetNDC(); latex2 -> SetTextFont(42); latex2 -> SetTextSize(0.04); latex2 -> Draw("same"); c_ped_fib_all -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/ped_fib_all.png",inFileName.c_str()),"png"); TCanvas* c_maximum_fib_all = new TCanvas(); c_maximum_fib_all -> SetLogy(); h_maximum_fib_all -> SetLineWidth(2); h_maximum_fib_all -> GetXaxis() -> SetTitle("max sample"); h_maximum_fib_all -> Draw(); c_maximum_fib_all -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/maximum_fib_all.png",inFileName.c_str()),"png"); TCanvas* c_fibAveInt = new TCanvas(); p_fibAveInt -> Draw("COLZ"); c_fibAveInt -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/fibAveInt.png",inFileName.c_str()),"png"); TCanvas* c_fibAveMax = new TCanvas(); p_fibAveMax -> Draw("COLZ"); c_fibAveMax -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/fibAveMax.png",inFileName.c_str()),"png"); TCanvas* c_crystAveMax = new TCanvas(); p_crystAveMax -> Draw("COLZ"); c_crystAveMax -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/crystAveMax.png",inFileName.c_str()),"png"); TCanvas* c_tot_integral = new TCanvas(); c_tot_integral -> SetLogy(); h_tot_integral -> Draw(); c_tot_integral -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/tot_integral.png",inFileName.c_str()),"png"); TCanvas* c_tot_maximum = new TCanvas(); c_tot_maximum -> SetLogy(); h_tot_maximum -> Draw(); c_tot_maximum -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/tot_maximum.png",inFileName.c_str()),"png"); }
void howManyPe7_17_evening(){ cout << "Starting" << endl; const int numRuns = 6; const char* files[numRuns] = { "../../crunchedFiles/run_00480_crunched.root", "../../crunchedFiles/run_00481_crunched.root", "../../crunchedFiles/run_00482_crunched.root", "../../crunchedFiles/run_00483_crunched.root", "../../crunchedFiles/run_00484_crunched.root", "../../crunchedFiles/run_00485_crunched.root", }; gStyle->SetOptFit(1); gStyle->SetOptStat(0); double pes[16]; double peErrors[16]; double gains[16]; double gainErrors[16]; TCanvas* c1 = new TCanvas(); cout << "starting loop " << endl; for(int row = 2; row < 6; ++row){ for(int col = 2; col < 6; ++col){ vector<double> means; vector<double> sigs; vector<double> meanErrs; vector<double> sigErrs; for (int i = 0; i < numRuns; ++i){ TFile* f = new TFile(files[i]); TTree* t = (TTree*) f->Get("t"); t->Draw(Form("sipm%i%i.energy>>histo%i%i", row,col,row,col),Form("sipm%i%i.valid",row,col)); TH1F* h = (TH1F*) gROOT->FindObject(Form("histo%i%i",row,col)); h->Fit("gaus","0q"); if(h->GetFunction("gaus")->GetParameter(1)>250){ means.push_back(h->GetFunction("gaus")->GetParameter(1)); sigs.push_back(h->GetFunction("gaus")->GetParameter(2)); meanErrs.push_back(h->GetFunction("gaus")->GetParError(1)); sigErrs.push_back(h->GetFunction("gaus")->GetParError(2)); } } vector<double> variances; vector<double> varianceErrors; for(int i = 0; i < means.size(); ++i){ variances.push_back(sigs[i]*sigs[i]); varianceErrors.push_back(2*sigs[i]*sigErrs[i]); } if(means.size() > 1){ TGraphErrors* linGraph = new TGraphErrors(means.size(), &means[0], &variances[0], &meanErrs[0], &varianceErrors[0]); TGraphErrors* quadGraph = new TGraphErrors(means.size(), &means[0], &variances[0], &meanErrs[0], &varianceErrors[0]); linGraph->SetMarkerStyle(20); linGraph->Fit("pol1","q"); linGraph->SetTitle(Form("SiPM %i%i", row, col)); linGraph->GetFunction("pol1")->SetLineColor(kBlue); linGraph->GetXaxis()->SetTitle("Mean"); linGraph->GetYaxis()->SetTitle("#sigma^{2}"); quadGraph->SetMarkerStyle(20); quadGraph->Fit("pol2","q"); quadGraph->GetFunction("pol2")->SetLineColor(kRed); linGraph->Draw("ap"); quadGraph->Draw("psame"); UInt_t index = (row-2)*4 + (col-2); pes[index] = 1.0/linGraph->GetFunction("pol1")->GetParameter(1)*means[0]; gains[index] = linGraph->GetFunction("pol1")->GetParameter(1); gainErrors[index] = linGraph->GetFunction("pol1")->GetParError(1); peErrors[index] = TMath::Sqrt((1/gains[index]*meanErrs[0])*(1/gains[index]*meanErrs[0])+ (means[0]/(gains[index]*gains[index])*gainErrors[index])*(means[0]/(gains[index]*gains[index])*gainErrors[index])); /* pes[drs] = 1.0/quadGraph->GetFunction("pol2")->GetParameter(1)*means[0]; gains[drs] = quadGraph->GetFunction("pol2")->GetParameter(1); gainErrors[drs] = quadGraph->GetFunction("pol2")->GetParError(1); peErrors[drs] = TMath::Sqrt((1/gains[drs]*meanErrs[0])*(1/gains[drs]*meanErrs[0])+ (means[0]/(gains[drs]*gains[drs])*gainErrors[drs])*(means[0]/(gains[drs]*gains[drs])*gainErrors[drs])); */ delete linGraph; delete quadGraph; } else if (means.size()==1){ UInt_t index = (row-2)*4 + (col-2); UInt_t mean = means[0]; UInt_t sig = sigs[0]; UInt_t meanErr = meanErrs[0]; UInt_t sigErr = sigErrs[0]; pes[index] = mean*mean/sig/sig; gains[index] = mean/pes[index]; gainErrors[index] = TMath::Sqrt((2*sig/mean*sigErr)*(2*sig/mean*sigErr)+(sig*sig/mean/mean*meanErr)*(sig*sig/mean/mean*meanErr)); peErrors[index] = TMath::Sqrt((2*mean/sig/sig*sigErr)*(2*mean/sig/sig*sigErr)+(2*mean*mean/sig/sig/sig*sigErr)*(2*mean*mean/sig/sig/sig*sigErr)); } else{ UInt_t index = (row-2)*4 + (col-2); pes[index] = -1; gains[index] = -1; peErrors[index] = -1; gainErrors[index] = -1; } } } for(int i = 0; i <16; ++i){ cout << "SiPM " << 2+i/4 << 2+i%4 << " --- " << "p1 : " << gains[i] << ", " << pes[i] << " photoelectrons at open filter, " << gains[i]*pes[i] << "calibration constant." << endl; } TGraphErrors* peGainGraph = new TGraphErrors(16, gains, pes, gainErrors, peErrors); peGainGraph->SetMarkerStyle(20); peGainGraph->GetXaxis()->SetTitle("gain"); peGainGraph->GetYaxis()->SetTitle("PE at open filter"); c1->SetGridx(); c1->SetGridy(); peGainGraph->Draw("ap"); cout << "drew graph " << endl; TCanvas* c2 = new TCanvas(); TH2F* peMap = new TH2F("pes","PE Map", 4,0,4,4,0,4); for(int i = 0; i < 16; ++i){ peMap->Fill(.5+i%4, 3.5-i/4, pes[i]); } peMap->GetXaxis()->SetLabelOffset(99); peMap->GetYaxis()->SetLabelOffset(99); c2->SetTickx(0); c2->SetTicky(0); peMap->Draw("TEXT"); TCanvas* c3 = new TCanvas(); TH2F* gainMap = new TH2F("gains","Gain Map", 4,0,4,4,0,4); for(int i = 0; i < 16; ++i){ gainMap->Fill(.5+i%4, 3.5-i/4, gains[i]); } gainMap->GetXaxis()->SetLabelOffset(99); gainMap->GetYaxis()->SetLabelOffset(99); gainMap->Draw("TEXT"); }
void plotTree(TTree *tree_, std::string whichfit, std::string selectString){ // Create a map for plotting the pullsummaries: std::map < const char*, std::pair <double,double> > pullSummaryMap; int nPulls=0; TObjArray *l_branches = tree_->GetListOfBranches(); int nBranches = l_branches->GetEntries(); gStyle->SetPadTopMargin(0.01); TCanvas *c = new TCanvas("c","",960,800); std::string treename = tree_->GetName(); c->SaveAs(Form("%s.pdf[",treename.c_str())); // File to store plots in TFile *fOut = new TFile(Form("%s.root",treename.c_str()),"RECREATE"); for (int iobj=0;iobj<nBranches;iobj++){ TBranch *br =(TBranch*) l_branches->At(iobj); // Draw the normal histogram const char* name = br->GetName(); // names with - are not allowed string namestr(name); if(namestr.find("-")!=string::npos) { std::cout << "Variable " << name << " contains a bad character: -. Skipping. " << std::endl; continue; } bool fitPull=false; bool fitPullf=false; bool plotLH=false; TGraph *gr=NULL; double p_mean =0; double p_err =0; int nToysInTree = tree_->GetEntries(); // Find out if paramter is fitted value or constraint term bool isFitted = findNuisancePre(name); if (doPull && isFitted){ p_mean = bfvals_[name].first; // toy constrainits thrown about best fit to data if(namestr.find("n_exp")==string::npos) p_err = prevals_[name].second; // uncertainties taken from card std::cout << "******* "<< name << " *******"<<std::endl; std::cout << p_mean << " " << p_err << std::endl; std::cout << "******************************" <<std::endl; const char* drawInput; // if the parameter is a normalization, the error is not available. Do the residual instead of the pull if(namestr.find("n_exp")!=string::npos) drawInput = Form("(%s-%f)/%f",name,p_mean,p_mean); else drawInput = Form("(%s-%f)/%f",name,p_mean,p_err); tree_->Draw(Form("%s>>%s",drawInput,name),""); tree_->Draw(Form("%s>>%s_fail",drawInput,name),selectString.c_str(),"same"); fitPull = true; fitPullf = true; if (doLH) { gr = graphLH(name,p_err,whichfit); if (gr) plotLH=true; } } else{ tree_->Draw(Form("%s>>%s",name,name),""); tree_->Draw(Form("%s>>%s_fail",name,name),selectString.c_str(),"same"); } TH1F* bH = (TH1F*) gROOT->FindObject(Form("%s",name))->Clone(); TH1F* bHf = (TH1F*) gROOT->FindObject(Form("%s_fail",name))->Clone(); bHf->SetLineColor(2); bH->GetXaxis()->SetTitle(bH->GetTitle()); bH->GetYaxis()->SetTitle(Form("no toys (%d total)",nToysInTree)); bH->GetYaxis()->SetTitleOffset(1.05); bH->GetXaxis()->SetTitleOffset(0.9); bH->GetYaxis()->SetTitleSize(0.05); bH->GetXaxis()->SetTitleSize(0.05); if (isFitted) {bH->GetXaxis()->SetTitle(Form("(%s-#theta_{B})/#sigma_{#theta}",name));} else {bH->GetXaxis()->SetTitle(Form("%s",name));} bH->SetTitle(""); if ( bH->Integral() <=0 ) fitPull = false; if (fitPull) {bH->Fit("gaus"); bH->GetFunction("gaus")->SetLineColor(4);} if ( bHf->Integral() <=0 ) fitPullf = false; if (fitPullf) {bHf->Fit("gaus"); bHf->GetFunction("gaus")->SetLineColor(2);} c->Clear(); //TPad pad1("t1","",0.01,0.02,0.59,0.98); // Pad 1 sizes depend on the parameter type ... double pad1_x1,pad1_x2,pad1_y1,pad1_y2; if ( !isFitted ) { pad1_x1 = 0.01; pad1_x2 = 0.98; pad1_y1 = 0.045; pad1_y2 = 0.98; } else { pad1_x1 = 0.01; pad1_x2 = 0.59; pad1_y1 = 0.56; pad1_y2 = 0.98; } TPad pad1("t1","",pad1_x1,pad1_y1,pad1_x2,pad1_y2); TPad pad1a("t1a","",0.01,0.045,0.59,0.522); TPad pad2("t2","",0.59,0.04,0.98,0.62); TPad pad3("t3","",0.55,0.64,0.96,0.95); pad1.SetNumber(1); pad2.SetNumber(2); pad3.SetNumber(3); pad1a.SetNumber(4); if ( isFitted ) {pad1a.Draw();pad2.Draw();pad3.Draw();} pad1.Draw(); pad2.SetGrid(true); TLatex *titletext = new TLatex();titletext->SetNDC(); if ( isFitted ){ c->cd(4); tree_->Draw(Form("%s:%s_In>>%s_%s_2d",name,name,name,tree_->GetName()),""); //TH2D *h2d_corr = (TH2D*)gROOT->FindObject(Form("%s_2d",name)); //h2d_corr->SetMarkerColor(4); //h2d_corr->SetTitle(""); //h2d_corr->GetXaxis()->SetTitle(Form("%s_In",name)); //h2d_corr->GetYaxis()->SetTitle(Form("%s",name)); titletext->SetTextAlign(11); titletext->SetTextSize(0.05); titletext->DrawLatex(0.05,0.02,Form("%s_In",name)); titletext->SetTextAngle(90); titletext->DrawLatex(0.04,0.06,Form("%s",name)); titletext->SetTextAngle(0); } c->cd(1); bH->Draw(); bHf->Draw("same"); TLegend *legend = new TLegend(0.6,0.8,0.9,0.89); legend->SetFillColor(0); legend->AddEntry(bH,"All Toys","L"); legend->AddEntry(bHf,selectString.c_str(),"L"); legend->Draw(); if (doPull && plotLH) { c->cd(2); gr->Draw("ALP"); } if (fitPull){ c->cd(3); double gap; TLatex *tlatex = new TLatex(); tlatex->SetNDC(); if (fitPullf) {tlatex->SetTextSize(0.09); gap=0.12;} else {tlatex->SetTextSize(0.11);gap=0.14;} tlatex->SetTextColor(4); tlatex->DrawLatex(0.11,0.80,Form("Mean : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParError(1))); tlatex->DrawLatex(0.11,0.80-gap,Form("Sigma : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(2),bH->GetFunction("gaus")->GetParError(2))); if (fitPullf){ tlatex->SetTextColor(2); tlatex->DrawLatex(0.11,0.60,Form("Mean : %.3f #pm %.3f",bHf->GetFunction("gaus")->GetParameter(1),bHf->GetFunction("gaus")->GetParError(1))); tlatex->DrawLatex(0.11,0.60-gap,Form("Sigma : %.3f #pm %.3f",bHf->GetFunction("gaus")->GetParameter(2),bHf->GetFunction("gaus")->GetParError(2))); } tlatex->SetTextSize(0.10); tlatex->SetTextColor(1); if(namestr.find("n_exp")!=string::npos) tlatex->DrawLatex(0.11,0.33,Form("Pre-fit: %.3f",prevals_[name].first)); else tlatex->DrawLatex(0.11,0.33,Form("Pre-fit #pm #sigma_{#theta}: %.3f #pm %.3f",prevals_[name].first, p_err)); tlatex->DrawLatex(0.11,0.18,Form("Best-fit (#theta_{B}) : %.3f ",p_mean)); tlatex->DrawLatex(0.11,0.03,Form("Best-fit (#theta_{S+B}): %.3f ",bfvals_sb_[name].first)); pullSummaryMap[name]=std::make_pair<double,double>(bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParameter(2)); nPulls++; } double titleSize = isFitted ? 0.1 : 0.028; titletext->SetTextSize(titleSize);titletext->SetTextAlign(21); titletext->DrawLatex(0.55,0.92,name); c->SaveAs(Form("%s.pdf",treename.c_str())); fOut->WriteObject(c,Form("%s_%s",treename.c_str(),name)); //c->SaveAs(Form("%s_%s.pdf",treename.c_str(),name)); } if (doPull && nPulls>0){ std::cout << "Generating Pull Summaries" <<std::endl; int nRemainingPulls = nPulls; TCanvas *hc = new TCanvas("hc","",3000,2000); hc->SetGrid(0); std::map < const char*, std::pair <double,double> >::iterator pull_it = pullSummaryMap.begin(); std::map < const char*, std::pair <double,double> >::iterator pull_end = pullSummaryMap.end(); int pullPlots = 1; while (nRemainingPulls > 0){ int nThisPulls = min(maxPullsPerPlot,nRemainingPulls); TH1F pullSummaryHist("pullSummary","",nThisPulls,0,nThisPulls); for (int pi=1;pull_it!=pull_end && pi<=nThisPulls ;pull_it++,pi++){ pullSummaryHist.GetXaxis()->SetBinLabel(pi,(*pull_it).first); pullSummaryHist.SetBinContent(pi,((*pull_it).second).first); pullSummaryHist.SetBinError(pi,((*pull_it).second).second); nRemainingPulls--; } pullSummaryHist.SetMarkerStyle(21);pullSummaryHist.SetMarkerSize(1.5);pullSummaryHist.SetMarkerColor(2);pullSummaryHist.SetLabelSize(pullLabelSize); pullSummaryHist.GetYaxis()->SetRangeUser(-3,3);pullSummaryHist.GetYaxis()->SetTitle("pull summary (n#sigma)");pullSummaryHist.Draw("E1"); hc->SaveAs(Form("%s.pdf",treename.c_str())); fOut->WriteObject(hc,Form("comb_pulls_%s_%d",treename.c_str(),pullPlots)); // hc->SaveAs(Form("comb_pulls_%s_%d.pdf",treename.c_str(),pullPlots)); pullPlots++; } delete hc; } c->SaveAs(Form("%s.pdf]",treename.c_str())); fOut->Close(); delete c; return; }
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(); }
uwLowLightCalib(){ const int numRuns = 18; const char* files[numRuns] = { "../crunchedFiles/run_00262_crunched.root", "../crunchedFiles/run_00263_crunched.root", "../crunchedFiles/run_00264_crunched.root", "../crunchedFiles/run_00265_crunched.root", "../crunchedFiles/run_00266_crunched.root", "../crunchedFiles/run_00267_crunched.root", "../crunchedFiles/run_00268_crunched.root", "../crunchedFiles/run_00269_crunched.root", "../crunchedFiles/run_00270_crunched.root", "../crunchedFiles/run_00274_crunched.root", "../crunchedFiles/run_00275_crunched.root", "../crunchedFiles/run_00278_crunched.root", "../crunchedFiles/run_00279_crunched.root", "../crunchedFiles/run_00280_crunched.root", "../crunchedFiles/run_00281_crunched.root", "../crunchedFiles/run_00282_crunched.root", "../crunchedFiles/run_00284_crunched.root", "../crunchedFiles/run_00285_crunched.root"}; gStyle->SetOptFit(1); vector<double> means[4]; vector<double> sigs[4]; vector<double> meanErrs[4]; vector<double> sigErrs[4]; for (int i = 0; i < numRuns; ++i){ TFile* f = new TFile(files[i]); TTree* t = (TTree*) f->Get("t"); for (int j = 0; j < 4; ++j){ t->Draw(Form("sipm%i.energy>>h%i",j+1,j),Form("sipm%i.valid",j+1)); TH1F* h = (TH1F*) gROOT->FindObject(Form("h%i",j)); h->Fit("gaus","0"); means[j].push_back(h->GetFunction("gaus")->GetParameter(1)); sigs[j].push_back(h->GetFunction("gaus")->GetParameter(2)); meanErrs[j].push_back(h->GetFunction("gaus")->GetParError(1)); sigErrs[j].push_back(h->GetFunction("gaus")->GetParError(2)); } } vector<double> variances[4]; vector<double> varianceErrors[4]; for(int i = 0; i < means.size(); ++i){ for(int j = 0; j < 4; ++j){ variances[j].push_back(sigs[j][i]*sigs[j][i]); varianceErrors[j].push_back(2*sigs[j][i]*sigErrs[j][i]); } } TCanvas* c1 = new TCanvas(); c1->Divide(2,2); for(int j = 0; j < 4; ++j){ c1->cd(j+1); TGraphErrors* linGraph = new TGraphErrors(means[j].size(), &means[j][0], &variances[j][0], &meanErrs[j][0], &varianceErrors[j][0]); TGraphErrors* quadGraph = new TGraphErrors(means.size(), &means[j][0], &variances[j][0], &meanErrs[j][0], &varianceErrors[j][0]); linGraph->SetMarkerStyle(20); linGraph->Fit("pol1"); linGraph->SetTitle(Form("SiPM %i", j+1)); linGraph->GetFunction("pol1")->SetLineColor(kBlue); linGraph->GetXaxis()->SetTitle("Mean"); linGraph->GetYaxis()->SetTitle("#sigma^{2}"); quadGraph->SetMarkerStyle(20); quadGraph->Fit("pol2"); quadGraph->GetFunction("pol2")->SetLineColor(kRed); linGraph->Draw("ap"); quadGraph->Draw("psame"); } for( int i = 0; i < 4; ++ i){ for (int j = 0; j<i; ++j){ new TCanvas(); TGraphErrors* corrGraph = new TGraphErrors(means[i].size(), &means[i][0], &means[j][0], &meanErrs[i][0], &meanErrs[j][0]); corrGraph->GetXaxis()->SetTitle(Form("SiPM %i Mean", i+1)); corrGraph->GetYaxis()->SetTitle(Form("SiPM %i Mean", j+1)); corrGraph->SetTitle(Form("SiPM %i vs SiPM %i",j+1, i+1)); corrGraph->Fit("pol1"); corrGraph->SetMarkerStyle(20); corrGraph->Draw("ap"); } } }
void ootpu_fit(TString files, TString comments="") { TChain* chain = new TChain("reduced_tree"); chain->Add(files); TH1::SetDefaultSumw2(); TH1F* hrelIso = new TH1F("hrelIso","", 30, 0, 0.5); TH1F* hOOTPU = new TH1F("hOOTPU","", 75, 0, 75); TH1F* hOOTPUvsIso = new TH1F("hOOTPUvsIso",";Out-of-time ints.;Isolation cut efficiency", 15, 0, 75); hrelIso->StatOverflows(true); int n1(0), n2(0); if (files.Contains("20bx25")) { n1=15; n2=75; } else if (files.Contains("S14")) { n1=0; n2=120; } else { // default: 8 TeV scenario n1=0; n2=70; } TString mu("num_gen_muons==1&&muon_reco_match>=0"); int low = 15; for (int bin(1); bin<hOOTPUvsIso->GetNbinsX()+1; bin++) { if (bin<4) continue; if (bin>4) low=low+5; if (low>hOOTPUvsIso->GetBinLowEdge(hOOTPUvsIso->GetNbinsX())) break; TString cuts = Form("(%s)&&(oot_pu>=%d&&oot_pu<%d)",mu.Data(),low,low+4); cout << "Cuts: " << cuts.Data() << endl; chain->Project(hrelIso->GetName(), "muon_relIso", cuts); chain->Project(hOOTPU->GetName(), "oot_pu", cuts); hrelIso->Scale(1/hrelIso->GetEntries()); Double_t left(0.), lerror(0.), right(0.), rerror(0.); left = hrelIso->IntegralAndError(1,12,lerror); right = hrelIso->IntegralAndError(13,31,rerror); float rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right))); printf("bin1: %3.2f +/- %3.3f\n", left/(left+right),rat_error); hOOTPUvsIso->SetBinContent(bin,left/(left+right)); hOOTPUvsIso->SetBinError(bin,rat_error); } hOOTPUvsIso->SetLineColor(1); hOOTPUvsIso->SetMarkerColor(1); hOOTPUvsIso->SetMarkerStyle(20); TCanvas* c1 = new TCanvas(); hOOTPUvsIso->Draw("e1"); // do a linear fit TF1 *flin = new TF1("flin", "1 ++ x", 15, 75); hOOTPUvsIso->Fit(flin); flin=hOOTPUvsIso->GetFunction("flin"); flin->SetLineColor(kBlue); flin->SetLineWidth(2); TString plotTitle ="OOTPU_fit"+comments+".pdf"; c1->Print(plotTitle); // cout << "Rejection rates" << endl; // Double_t left(0.), lerror(0.), right(0.), rerror(0.); // left = hA->IntegralAndError(1,12,lerror); // right = hA->IntegralAndError(13,31,rerror); // float rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right))); // printf("bin1: %3.2f +/- %3.3f\n", left/(left+right),rat_error); // left = hB->IntegralAndError(1,12,lerror); // right = hB->IntegralAndError(13,31,rerror); // rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right))); // printf("bin2: %3.2f +/- %3.3f\n", left/(left+right),rat_error); // left = hC->IntegralAndError(1,12,lerror); // right = hC->IntegralAndError(13,31,rerror); // rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right))); // printf("bin3: %3.2f +/- %3.3f\n", left/(left+right),rat_error); // left = hD->IntegralAndError(1,12,lerror); // right = hD->IntegralAndError(13,31,rerror); // rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right))); // printf("bin4: %3.2f +/- %3.3f\n", left/(left+right),rat_error); }
void data_to_tree() { Double_t pedtime; Double_t pedTr; Double_t pedTl; Double_t rped; Double_t lped; //ptfactor = point to time factor //const Double_t ptfactor = 0.050; const Double_t ptfactor = 0.0407; TFile* f = new TFile("data_to_tree_t4.root", "RECREATE"); ifstream in; ofstream out; //bring data files and give name to use in this code. //data file name is in order type_ch0threshold(left)_ch2threshold(right)_ch0highvoltage_ch2highvoltage_#ofevent const Char_t* file[9] = {"VTD_Co_10cm_t4.dat", "VTD_Co_20cm_t4.dat", "VTD_Co_30cm_t4.dat", "VTD_Co_40cm_t4.dat", "VTD_Co_50cm_t4.dat", "VTD_Co_60cm_t4.dat", "VTD_Co_70cm_t4.dat", "VTD_Co_80cm_t4.dat", "VTD_Co_90cm_t4.dat"}; const Char_t* distance[9] = {"10cm", "20cm", "30cm", "40cm", "50cm", "60cm", "70cm", "80cm", "90cm"}; TCanvas* c1 = new TCanvas("c1", "pedl", 200, 0, 600, 600); TH1F* pedlhist = new TH1F("pedlhist", "left", 200, 0, 200); TCanvas* c2 = new TCanvas("c2", "pedr", 210, 10, 610, 610); TH1F* pedrhist = new TH1F("pedrhist", "right", 200, 0, 200); in.open("VTD_pedestal.dat"); if(in.is_open()) { while(1) { in >> pedtime >> pedTl >> pedTr >> lped >> rped; if(!in.good()) break; pedlhist->Fill(lped); pedrhist->Fill(rped); } } in.close(); c1->cd(); pedlhist->Draw(); pedlhist->Fit("gaus", "", "", 122, 126); Double_t pedlmean = pedlhist->GetFunction("gaus")->GetParameter(1); c1->SaveAs("VTDpedl.png"); c2->cd(); pedrhist->Draw(); pedrhist->Fit("gaus", "", "", 92, 107); Double_t pedrmean = pedrhist->GetFunction("gaus")->GetParameter(1); c2->SaveAs("VTDpedr.png"); //pr: position resolution TTree* pr[9]; for(Int_t i = 0; i < 9; i++) { in.open(file[i]); Double_t time = 0; Double_t Tl = 0; Double_t Tr = 0; Double_t Al = 0; Double_t Ar = 0; pr[i] = new TTree(distance[i], "position resolution data"); pr[i]->Branch("Tl", &Tl, "Tl/D"); pr[i]->Branch("Tr", &Tr, "Tr/D"); pr[i]->Branch("Al", &Al, "Al/D"); pr[i]->Branch("Ar", &Ar, "Ar/D"); if(in.is_open()) { while(1) { in >> time >> Tl >> Tr >> Al >> Ar; if(!in.good()) break; Tl = Tl*ptfactor; Tr = Tr*ptfactor; Al = Al-pedlmean; Ar = Ar-pedrmean; pr[i]->Fill(); } } in.close(); } f->Write(); }