Beispiel #1
0
void mc2ibd_NE(TChain *tMC, TFile *fBgnd, TCanvas *cv)
{
	char str[1024];
	TLatex *txt = new TLatex();

	TH1D *hExp = (TH1D *) fBgnd->Get("hNEA-diff");
	if (!hExp) {
		printf("Histogram hNEA-diff not found in %s\n", fBgnd->GetName());
		return;
	}
	hExp->SetTitle("Delayed event energy;MeV;Events/200 keV");
	hExp->SetLineColor(kBlack);
	hExp->SetLineWidth(3);

	gROOT->cd();
	TH1D *hMC = new TH1D("hNEMC", "Delayed event energy (MC);MeV;Events/200 keV", 45, 3, 12);
	hMC->SetLineColor(kBlue);
	tMC->Project(hMC->GetName(), "NeutronEnergy", cX && cY && cZ && cR && c20 && cGamma && cGammaMax && cPe);
	hMC->Sumw2();
	hMC->Scale(hExp->Integral(15, 45) / hMC->Integral(15,45));
	
	cv->Clear();
	hMC->Draw("hist");
	hExp->DrawCopy("same");
	TLegend *lg = new TLegend(0.65, 0.8, 0.89, 0.89);
	lg->AddEntry(hExp, "IBD", "LE");
	lg->AddEntry(hMC, "MC", "L");
	lg->Draw();
}
Beispiel #2
0
double  Getmean(TString sys1, TString sys2, float cent1, float cent2){

  gROOT->SetStyle("Plain");
  TFile *infile = TFile::Open(Form("glau_%s%s_ntuple_1M.root",sys1.Data(),sys2.Data()));
  infile->cd();
  TH2F *pEcc2B = new TH2F("pEcc2B","#epsilon_{2} vs impact paramter in 200 GeV Collisions from Glauber MC;B;#epsilon_{n}",25200,-0.5,251.5,100,0,1);
  if(sys2.Contains("smeared")){
  TNtuple *nt = (TNtuple*)infile->Get("nt");
  nt->Project("pEcc2B","Ecc3G:B");
  }
  else{
  TNtuple *nt = (TNtuple*)infile->Get(Form("nt_%s_%s",sys1.Data(),sys2.Data()));
  nt->Project("pEcc2B","Ecc2:B");
  }
  TH1D* hB = (TH1D*)pEcc2B->ProjectionX("hB",0,-1);
  for(int ibin=0;ibin<hB->GetNbinsX();ibin++){
      if(hB->Integral(0,ibin) >= cent1 /100. * hB->Integral()){ int bin1 = ibin; break;}
  }
  for(int ibin=0;ibin<hB->GetNbinsX();ibin++){
      if(hB->Integral(0,ibin) >= cent2 /100. * hB->Integral()){ int bin2 = ibin; break;}
  }
  cout<< bin1 << "\t" << bin2 << endl;
  TH1D* hEcc2 = (TH1D*)pEcc2B->ProjectionY("hEcc2",bin1,bin2);
//  hEcc2->Draw();
  cout << hEcc2 -> GetEntries() << endl;
  double mean = hEcc2->GetMean();
  return mean;
}
Beispiel #3
0
void mc2ibd_R2(TChain *tMC, TFile *fBgnd, TCanvas *cv)
{
	char str[1024];
	TLatex *txt = new TLatex();

	TH1D *hExp = (TH1D *) fBgnd->Get("hR2A-diff");
	if (!hExp) {
		printf("Histogram hR2A-diff not found in %s\n", fBgnd->GetName());
		return;
	}
	hExp->SetTitle("Distance between positron and neutron, 3D case;cm;Events/4cm");
	hExp->SetLineColor(kBlack);
	hExp->SetLineWidth(3);

	gROOT->cd();
	TH1D *hMC = new TH1D("hR2MC", "Distance between positron and neutron, 3D case (MC);cm;Events/4cm", 40, 0, 160);
	hMC->SetLineColor(kBlue);
	tMC->Project(hMC->GetName(), "Distance", cX && cY && cZ && cRXY && c20 && cGamma && cGammaMax && cPe && cN);
	hMC->Sumw2();
	hMC->Scale(hExp->Integral() / hMC->Integral());
	
	cv->Clear();
	hExp->DrawCopy();
	hMC->Draw("hist,same");
	TLegend *lg = new TLegend(0.65, 0.8, 0.89, 0.89);
	lg->AddEntry(hExp, "IBD", "LE");
	lg->AddEntry(hMC, "MC", "L");
	lg->Draw();
}
Beispiel #4
0
void loglikdistrib(Int_t ntrials = 10000, Bool_t print = kFALSE)
{
  // compute distribution of log likelihood value
  TH1D * hmc   = gStack[gPadNr][gOrder[gPadNr][0]];
  TH1D * hdata = gStack[gPadNr][gMaxProcess-1];
  Int_t nbins = hmc->GetNbinsX();
  Double_t loglik = loglikelihood(hmc, hdata, 1, nbins);
  TH1D * htest = new TH1D(*hdata);
  TH1D * lldistrib = new TH1D("lldistrib", "log(Likelihood) distribution", 
			      1000, loglik-200, loglik+200);
  setopt(lldistrib);
  for (Int_t n = 0; n < ntrials; n++) {
    // generate poisson around theorie
    for (Int_t i = 1; i <= nbins; i++) {
      htest->SetBinContent(i, gRandom->Poisson(hmc->GetBinContent(i)));
    }
    lldistrib->Fill(loglikelihood(hmc, htest, 1, nbins));
  }
  TCanvas * llcanvas = new TCanvas("llcanvas", "Log(Likelihood) distribution", 
				   40, 40, 800, 600);
  setopt(llcanvas);
  lldistrib->SetFillColor(kYellow);
  lldistrib->Draw();
  lldistrib->GetYaxis()->SetTitle("Anzahl Ereignisse");
  lldistrib->GetXaxis()->SetTitle("-ln L");
  // autozoom
  Int_t lowbin = 1;
  while (lldistrib->GetBinContent(lowbin) == 0)
    lowbin++;
  Int_t highbin = lldistrib->GetNbinsX();
  while (lldistrib->GetBinContent(highbin) == 0)
    highbin--;
  lldistrib->SetAxisRange(lldistrib->GetBinLowEdge(lowbin), 
			  lldistrib->GetBinLowEdge(highbin));
  TH1D * hworse = (TH1D *) lldistrib->Clone();
  for (Int_t nbin = 1; nbin < 501; nbin++) {
    hworse->SetBinContent(nbin, 0);
  }
  hworse->SetFillColor(95);
  hworse->Draw("same");
  Double_t pvalue = lldistrib->Integral(501,1000) / lldistrib->Integral();
  TLatex * tex = new TLatex(0.18, 0.96, Form("-ln L_{obs} = %5.2f", loglik));
  tex->SetNDC();
  tex->SetTextAlign(13);
  tex->Draw();
  tex = new TLatex(0.18, 0.86, Form("CL_{obs} = %.3f", pvalue));
  tex->SetNDC();
  tex->SetTextAlign(13);
  tex->Draw();
  TLine * l = new TLine(loglik, 0, loglik, lldistrib->GetMaximum());
  l->SetLineWidth(3);
  l->SetLineColor(kBlue);
  l->Draw();
  llcanvas->Modified();
  llcanvas->Update();
  if (print)
    llcanvas->Print("lldistrib.pdf");
  cd(gPadNr+1);
}
Beispiel #5
0
// Called just after the main event loop
// Can be used to write things out, dump a summary etc
// Return non-zero to indicate a problem
int TemplateCreator::AfterLastEntry(TGlobalData* gData, const TSetupData* setup){

  // Print extra info if we're debugging this module:
  if(Debug()){
     cout<<"-----I'm debugging TemplateCreator::AfterLastEntry()"<<endl;
  }

  // Print to stdout the percentage of successful fit for each channel
  StringPulseIslandMap::const_iterator it;
  for(it = gData->fPulseIslandToChannelMap.begin(); it != gData->fPulseIslandToChannelMap.end(); ++it){
    std::string bankname = it->first;
    std::string detname = setup->GetDetectorName(bankname);

    TH1D* hTemplate = fTemplates[detname];
    
    if (!hTemplate) { // if there's no template been created for this channel
      continue;
    }
    
    int& n_fit_attempts = fNFitAttempts[detname]; // number of pulses we try to fit to
    int& n_successful_fits = fNSuccessfulFits[detname];
    std::cout << "TemplateCreator: " << detname << ": " << n_fit_attempts << " fits attempted with " << n_successful_fits << " successful (" << ((double)n_successful_fits/(double)n_fit_attempts)*100 << "%)" << std::endl;

    // Normalise the template so that it has pedestal=0 and amplitude=1
    // Work out the pedestal of the template from the first 5 bins
    int n_bins_for_template_pedestal = 5;
    double total = 0;
    for (int iBin = 1; iBin <= n_bins_for_template_pedestal; ++iBin) {
      total += hTemplate->GetBinContent(iBin);
    }
    double template_pedestal = total / n_bins_for_template_pedestal;
    //    std::cout << detname << ": Template Pedestal = " << template_pedestal << std::endl;
   
    // Subtract off the pedesal
    for (int iBin = 1; iBin <= hTemplate->GetNbinsX(); ++iBin) {
      double old_value = hTemplate->GetBinContent(iBin);
      double new_value = old_value - template_pedestal;

      hTemplate->SetBinContent(iBin, new_value);
    }

    // Integrate over the histogram and scale to give an area of 1
    double integral = std::fabs(hTemplate->Integral()); // want the absolute value for the integral because of the negative polarity pulses
    hTemplate->Scale(1.0/integral);
    integral = std::fabs(hTemplate->Integral());

    // Save the template to the file
    fTemplateArchive->SaveTemplate(hTemplate);
  }

  // Clean up the template archive
  delete fTemplateArchive;

  return 0;
}
Beispiel #6
0
// Takes as input a given process with corresponding luminosity, as well as sample CME, cuts, directory location, and output file name - saves corresponding histogram in root file.
void processtree(TString sample, Double_t weight, TLorentzVector CME, TString filename, TString directory, TString param, TString cut, std::clock_t start, Int_t all){

    //Open File
    TFile *f = new TFile(directory);
    TTree *ttree = (TTree*)f->Get(sample);

    TString recohistname, paramhistname;
    if (all==0){
        recohistname = "_recoilmassHIST";
        paramhistname = "_parameterHIST";
    }
    if (all==1){
        recohistname = "_recoilmassHIST_all";
        paramhistname = "_parameterHIST_all";
    }

    TString histname = sample + recohistname;
    TH1D *recoilmassHIST   = new TH1D(histname,histname,CME.M()/2,0,CME.M());
    //recoilmassHIST->SetCanExtend(kAllAxes);
    ttree->Project(histname, "recoilmass", cut);

    histname = sample + paramhistname;
    TH1D *parameterHIST   = new TH1D(histname,histname,CME.M()/2,1,-1);
    //parameterHIST->SetCanExtend(kAllAxes);
    ttree->Project(histname, param, cut);

    //Normalize Hist
    recoilmassHIST->Scale(1/recoilmassHIST->GetMaximum());
    parameterHIST->Scale(1/parameterHIST->GetMaximum()) ;

    //Normalize Hist
//    recoilmassHIST->Scale(weight);
//    parameterHIST->Scale(weight) ;

    // Writes yield of each histogram for each cut to text file
    ofstream myfile;
    Double_t yield = recoilmassHIST->Integral(); 
    myfile.open ("yield.txt", ios::app);
        cout << "Yield for " << sample << " for Cut " << param << " is " << yield << endl;
        myfile << param << " " << all << " " << sample << " " << yield << "\n"; //write to file
    myfile.close();

    if (recoilmassHIST->Integral() == 0){
        recoilmassHIST->Fill(0);
    }
    if (parameterHIST->Integral() == 0){
        parameterHIST->Fill(0);
    }

    TFile g(filename, "update");
    recoilmassHIST->Write();
    parameterHIST->Write();
    g.Close();
}
Beispiel #7
0
void plotTurnOn(TTree* inttree, TString triggerpass, TString variable, TString varname, TString varlatex)
{
  if(varname=="vtxprob")
    {
      BIN_MIN = 0;
      BIN_MAX = 1;
    }
  else if(varname=="ffls3d")
    {
      BIN_MIN = 0;
      BIN_MAX = 50;
    }
  else if(varname=="cosalpha")
    {
      BIN_MIN = 0.9;
      BIN_MAX = 1;
    }
  TH1D* hAll = new TH1D(Form("h%s_%s_All",triggerpass.Data(),varname.Data()),Form(";%s;Probability",varlatex.Data()),BIN_NUM,BIN_MIN,BIN_MAX);
  inttree->Project(Form("h%s_%s_All",triggerpass.Data(),varname.Data()),variable,prefilter);
  TH1D* hMBseed = new TH1D(Form("h%s_%s_MBseed",triggerpass.Data(),varname.Data()),Form(";%s;Probability",varlatex.Data()),BIN_NUM,BIN_MIN,BIN_MAX);
  inttree->Project(Form("h%s_%s_MBseed",triggerpass.Data(),varname.Data()),variable,Form("%s&&%s",prefilter.Data(),triggerpass.Data()));
  //cout<<hAll->Integral()<<endl;
  hAll->Scale(1./hAll->Integral());
  hMBseed->Scale(1./hMBseed->Integral());
  hAll->SetStats(0);
  hMBseed->SetStats(0);
  hAll->SetMaximum(hMBseed->GetMaximum()*1.3);
  hAll->SetLineWidth(2);
  hAll->SetLineColor(kBlue-7);
  hAll->SetFillColor(kBlue-7);
  hAll->SetFillStyle(3001);
  hMBseed->SetLineWidth(2);
  hMBseed->SetLineColor(kRed);
  hMBseed->SetFillColor(kRed);
  hMBseed->SetFillStyle(3004);
  TCanvas* c = new TCanvas(Form("c%s_%s",triggerpass.Data(),varname.Data()),"",500,500);
  hAll->Draw();
  hMBseed->Draw("same");
  TLatex* tex = new TLatex(0.18,0.96,triggerpass);
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->Draw();
  TLegend* leg = new TLegend(0.60,0.82,0.92,0.93);
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);
  leg->AddEntry(hAll,"all","f");
  leg->AddEntry(hMBseed,"pass trigger","f");
  leg->Draw();
  c->SaveAs(Form("triggerturnonPlots/pthat%.0f/c%s_%s.pdf",pthat,triggerpass.Data(),varname.Data()));

}
void GaussianProfile::getTruncatedMeanRMS(TH1* hist, float& mean, float& mean_error, float& rms, float& rms_error) {
  int nBins = hist->GetNbinsX();
  double xMin = hist->GetXaxis()->GetXmin();
  double xMax = hist->GetXaxis()->GetXmax();
  //double binWidth = (xMax - xMin) / (double) nBins; //WARNING: this works only if bins are of the same size
  double integral = hist->Integral();

  int maxBin = 0;
  TF1* gaussian = new TF1("gaussian", "gaus");
  fitProjection(hist, gaussian, 1.5, "RQN");
  //maxBin = (int) ceil((gaussian->GetParameter(1) - xMin) / binWidth);
  maxBin = hist->FindBin(gaussian->GetParameter(1));
  delete gaussian;

  TH1D* newHisto = new TH1D("newHisto", "", nBins, xMin, xMax);
  newHisto->SetBinContent(maxBin, hist->GetBinContent(maxBin));
  newHisto->SetBinError(maxBin, hist->GetBinError(maxBin));
  int iBin = maxBin;
  int delta_iBin = 1;
  int sign  = 1;

  while (newHisto->Integral() < 0.99 * integral) {
    iBin += sign * delta_iBin;

    newHisto->SetBinContent(iBin, hist->GetBinContent(iBin));
    newHisto->SetBinError(iBin, hist->GetBinError(iBin));

    delta_iBin += 1;
    sign *= -1;
  }

  rms = newHisto->GetRMS();
  rms_error = newHisto->GetRMSError();

  while (newHisto->Integral() < 0.99 * integral) {
    iBin += sign * delta_iBin;

    newHisto->SetBinContent(iBin, hist->GetBinContent(iBin));
    newHisto->SetBinError(iBin, hist->GetBinError(iBin));

    delta_iBin += 1;
    sign *= -1;
  }

  mean = newHisto->GetMean();
  mean_error = newHisto->GetMeanError();

  delete newHisto;
}
void CalcQCDNormFactor() {
  //TFile *f = TFile::Open("results/Plotter_out_2016_05_29_22h19m32.root"); // 76X Silver JSON
  TFile *f = TFile::Open("results/Plotter_out_2016_06_21_15h27m59.root"); // 76X Golden JSON
  TCanvas *c = (TCanvas*)f->Get("NJet/PlotSamples_Pass5Cuts_PassHLT");
  THStack *s = (THStack*)c->GetListOfPrimitives()->At(1);
  TH1D *data = (TH1D*)c->GetListOfPrimitives()->At(3);
  double MC_integral = 0;
  double QCD_count = 0;
  for (int i=s->GetHists()->GetEntries()-1; i>=0; --i) {
    TH1D* h = (TH1D*)s->GetHists()->At(i);
    if (i==s->GetHists()->GetEntries()-1) QCD_count = h->Integral();
    std::cout<<h->GetName()<<" "<<h->Integral()<<std::endl;
    MC_integral += h->Integral();
  }
  double data_QCD_estimate = data->Integral()- (MC_integral-QCD_count);
  double QCD_scale = data_QCD_estimate/QCD_count;
  std::cout<<"MC:                  "<<MC_integral<<std::endl;
  std::cout<<"Data:                "<<data->Integral()<<std::endl;
  std::cout<<"MC   (QCD only):     "<<QCD_count<<std::endl;
  std::cout<<"Data (QCD only est): "<<data_QCD_estimate<<std::endl;
  std::cout<<"QCD Scale: "<<QCD_scale<<std::endl;

  TH1D* qcd = (TH1D*)s->GetHists()->At(s->GetHists()->GetEntries()-1);
  qcd->Scale(QCD_scale);
  c->Draw();
  
  //TCanvas *c = (TCanvas*)f->Get("NJet/PlotSamples_Pass5Cuts_PassHLT_Ratio");
  //
  //TH1D* ratio = (TH1D*)((TVirtualPad*)c->cd(2))->GetListOfPrimitives()->At(0);
  //TF1* fit = new TF1("fit","pol1", 400, 2000);
  //ratio->Fit("fit","RBQ0");
  //fit->SetLineColor(2);
  //fit->SetLineWidth(1);
  //TF1* fit_up   = (TF1*)fit->Clone("fit_up");
  //TF1* fit_down = (TF1*)fit->Clone("fit_down");
  //fit_up  ->SetParameter(0,fit->GetParameter(0)+fit->GetParError(0)*1);
  //fit_down->SetParameter(0,fit->GetParameter(0)-fit->GetParError(0)*1);
  //fit_up  ->SetParameter(1,fit->GetParameter(1)+fit->GetParError(1)*1);
  //fit_down->SetParameter(1,fit->GetParameter(1)-fit->GetParError(1)*1);
  //fit_up  ->SetLineColor(4); fit_up  ->Draw("SAME");
  //fit_down->SetLineColor(4); fit_down->Draw("SAME");
  //fit->Draw("SAME");
  //
  //std::cout<<"Fit result:"<<std::endl;
  //std::cout<<"p0: "<<fit->GetParameter(0)<<" +- "<<fit->GetParError(0)*1<<std::endl;
  //std::cout<<"p1: "<<fit->GetParameter(1)<<" +- "<<fit->GetParError(1)*1<<std::endl;
  //f->Close();  
}
void PlotWriteErrors(TFile* input, TFile* output, TString output_folder, TString canvas, TString Hist, TString Opt="")
{

  // Setup the canvas
  TCanvas *c1= new TCanvas(canvas,canvas,800,700);

  // Get the histograms from the files
  TH1D *Data = (TH1D*)input->Get(Hist);

  //check to make sure there are some events before setting the log scale
  if(Data->Integral() == 0 ) c1->SetLogy(0);
  else  c1->SetLogy(1);

  // Fill for histogram
  Data->SetFillColor(kBlue);
  Data->GetXaxis()->SetTitleSize(0.06);
  Data->GetXaxis()->SetTitleOffset(0.75);
  Data->GetYaxis()->SetTitleSize(0.05);
  Data->GetYaxis()->SetTitleOffset(1.00);

  // plot them
  Data->DrawCopy("hist");

  gPad->RedrawAxis();

  //write canvas as png
  c1->Print(TString(output_folder+canvas+".png"));  

  //write canvas to output file
  output->cd();
  c1->Write();
  return;
}
Beispiel #11
0
TH1D* getQCD(int rebinFact){
	TString dir = "rootFiles/";
	
	TFile* file = new TFile(dir +"qcdest.root");		
	TH1D* plot = (TH1D*) file->Get("muon_AbsEta_0btag");

// 	for(int i = 1; i <= plot->GetNbinsX(); i++){
// 	plot->SetBinError(i, 0.0);
// 	}

	plot->SetFillColor(kYellow);
	plot->SetLineColor(kYellow);
	plot->SetMarkerStyle(1);
		
	TH1D* copyplot = new TH1D("qcd plot", "qcd plot", 30, 0.0, 3.0);
	
	for(int i = 1; i <= plot->GetNbinsX(); i++){
	copyplot->SetBinContent(i, plot->GetBinContent(i));
	//copyplot->SetBinError(i, plot->GetBinError(i));
	}
	copyplot->SetFillColor(kYellow);
	copyplot->SetLineColor(kYellow);
	copyplot->SetMarkerStyle(1);
	copyplot->Scale(1./copyplot->Integral());	
	copyplot->Rebin(rebinFact);
	
	//file->Close("R");
	return copyplot;
	//file->Close();
}
void  makeGaussianSignals(SigData_t& m_sigdata)
{
  //std::vector<TH1D *> vgsh(NUMCHAN);
  std::vector<TH1D *> vcdfh(NUMCHAN);

  if( m_sigdata.find("gs") == m_sigdata.end() ) {
    cerr << "Gaussian signal data not found, not making CDF signal!" << endl;
    return;
  }

  for (int ichan=0; ichan<NUMCHAN; ichan++) {
    TH1D *cdfh;

    TString channame(channames[ichan]);
    TString name;

    TH1D * gsh = m_sigdata["gs"].at(ichan);

    assert(gsh) ;

#if 0
    name = "Signalgs_"+channame;
    gsh = (TH1D *)tch->Clone(name.Data());

    assert(gsh);

    gsh->SetTitle("Gaussian signal");
    
    gsh->Reset();

    TF1 *g = (TF1 *)gROOT->GetFunction("gaus");
    g->SetParameters(1,gaussian_mean_mass_gev,gaussian_mass_sigma_gev);
    gsh->FillRandom("gaus",100000);

    // norm to 1pb signal with 1/fb integrated luminosity
    double norm = 1000 * gseffxacc[ichan]/gsh->Integral(0,gsh->GetNbinsX()+1,"width");

    //gsh->Scale(norm/eff_fudgefactor); // kludge: pre-undo the fudge in the next module
    gsh->Scale(norm);

    vgsh[ichan] = gsh;
#endif

    // New CDF bump, same as Gauss but set to CDF (obs/theor)*(LHC theor) = 3.43pb
    cdfh = (TH1D *)gsh->Clone("CDFbump");

    cdfh->Scale(3.43);

    vcdfh[ichan] = cdfh;

    cdfh->Draw();

    gsh->Draw("same");

  } // channel loop

  //m_sigdata["gs"]  = vgsh;
  m_sigdata["cdf"] = vcdfh;
}                                                           // makeGaussianSignals
Beispiel #13
0
void Normalize(TH1D &h, double normalization, bool norm_per_avg_width) {
    int nbins = h.GetNbinsX();
    double low = h.GetBinLowEdge(1);
    double high = h.GetBinLowEdge(nbins+1);
    double width = (high-low)/nbins;
    if(norm_per_avg_width) normalization *= width;
    double integral = h.Integral("width");
    h.Scale(normalization/integral);
}
Beispiel #14
0
void CompareBranch(string MCfilename, string CDfilename, string MCbranchname, string CDbranchname, string xtitle, string unit, string plotname, string MCcuts, string CDcuts, string MCweight, string CDweight, double xlow, double xup, int nbins)
{
  TH1D*  MChist = MakeBranchPlot(MCfilename,MCbranchname,MCcuts,MCweight,xlow,xup,nbins);
  TH1D*  CDhist = MakeBranchPlot(CDfilename,CDbranchname,CDcuts,CDweight,xlow,xup,nbins);
  MChist->Scale(1./MChist->Integral());
  CDhist->Scale(1./CDhist->Integral());
  MChist->SetDrawOption("B");
  MChist->SetFillColor(kOrange);
  MChist->SetLineColor(kOrange);
  MChist->SetMaximum(MChist->GetMaximum()*1.3);
  MChist->SetMinimum(0);
  // Draw everything
  plotmaker plotter(MChist);
  plotter.SetTitle(xtitle, unit);
  TCanvas* plot = plotter.Draw();
  CDhist->Draw("sameE1");
  plot->SaveAs((plotname+".pdf").c_str());
}
Beispiel #15
0
// Draw 1D histos
TH1D *plot1Dhisto(double intLumi,TFile *fileName,TString folderName,TString histoName,int color,int rebin,float xMin,float xMax,TString xName, TString yName,TString sampleName,bool mc) {  
  
  TH1D *hTemp = (TH1D*)fileName->Get(folderName+"/"+histoName);
  hTemp->SetName(histoName+"_"+sampleName);
  if (mc){ 
    hTemp->Scale(intLumi/100.);
  }
  hTemp->Rebin(rebin);
  hTemp->SetLineColor(color);
  hTemp->SetLineWidth(5);
  hTemp->GetXaxis()->SetRangeUser(xMin,xMax);
  hTemp->GetXaxis()->SetTitle(xName);
  hTemp->GetXaxis()->SetTitleSize(0.06);
  hTemp->GetXaxis()->SetLabelSize(0.06);
  hTemp->GetYaxis()->SetTitle(yName);
  hTemp->GetYaxis()->SetTitleSize(0.06);
  hTemp->GetYaxis()->SetLabelSize(0.06);
  hTemp->SetTitleOffset(1.5, "Y");
  // last/first bin: put over/underflow
  hTemp->SetBinContent(hTemp->FindBin(xMax),hTemp->Integral(hTemp->FindBin(xMax),hTemp->GetNbinsX()+1));
  hTemp->SetBinContent(hTemp->FindBin(xMin),hTemp->Integral(-1,hTemp->FindBin(xMin)));  

  hTemp->SetBinError(hTemp->FindBin(xMax),sqrt(hTemp->Integral(hTemp->FindBin(xMax),hTemp->GetNbinsX()+1)));
  hTemp->SetBinError(hTemp->FindBin(xMin),sqrt(hTemp->Integral(-1,hTemp->FindBin(xMin))));
  //fileName->Close();

  /*
  if (histoName != "LP_tot") {
    if (histoName != "SumLepPt_tot") {
      if ((folderName == "ANplots150_NOLP")) { hTemp->GetXaxis()->SetRangeUser(0.,300.); } 
      if ((folderName == "ANplots250_NOLP")) { hTemp->GetXaxis()->SetRangeUser(0.,400.); }
      if ((folderName == "ANplots350_NOLP")) { hTemp->GetXaxis()->SetRangeUser(0.,500.); }
      if ((folderName == "ANplots450_NOLP")) { hTemp->GetXaxis()->SetRangeUser(0.,1000.); }
    }
    else {
      if ((folderName == "ANplots150_NOLP")) { hTemp->GetXaxis()->SetRangeUser(100.,300.); } 
      if ((folderName == "ANplots250_NOLP")) { hTemp->GetXaxis()->SetRangeUser(200.,400.); }
      if ((folderName == "ANplots350_NOLP")) { hTemp->GetXaxis()->SetRangeUser(300.,500.); }
      if ((folderName == "ANplots450_NOLP")) { hTemp->GetXaxis()->SetRangeUser(400.,1000.); }
    }
  } 
  */ 
  return hTemp;
} // ~ end of plot1Dhisto function
//--------------------------------------------------------------------------------------------------
// Get Total Number of Events in the sample
//--------------------------------------------------------------------------------------------------
Double_t getNormalizationWeight(TString filename, TString datasetName) {
  // Get Normalization Weight Factor

  //Get Number of Events in the Sample
  TFile *file = new TFile(filename.Data(),"READ");
  if (!file) {
    cout << "Could not open file " << filename << endl;
    return 0;
  }

  //TDirectory *dir = (TDirectory*)file->FindObjectAny("AnaFwkMod");
  //if (!dir) {
  //  cout << "Could not find directory AnaFwkMod"
  //       << " in file " << filename << endl;
  //  delete file;
  //  return 0;
  //}

  TH1D *hist = (TH1D*) gROOT->FindObject("hDAllEvents");
  if (!hist) {
    cout << "Could not find histogram hDAllEvents in directory AnaFwkMod"
         << " in file " << filename << endl;
    //delete dir;
    delete file;
    return 0;
  }
  Double_t NEvents = hist->Integral();
  cout << "Original events in the sample: " << NEvents << endl;

  //Get CrossSection
  mithep::SimpleTable xstab("$CMSSW_BASE/src/MitPhysics/data/xs.dat");
  Double_t CrossSection = xstab.Get(datasetName.Data());
  Double_t Weight = CrossSection / NEvents;
  // weight for data is always 1 (-1 to make a trick for fakes)
  if(CrossSection < 0) Weight = -1.0;

  // Only gg->H and qqH samples
  if(datasetName.Contains("-gf-") ||
     datasetName.Contains("-vbf-")){
    // Only high mass samples
    if(datasetName.Contains("h250") || datasetName.Contains("h300") || datasetName.Contains("h350") || datasetName.Contains("h400") || 
       datasetName.Contains("h450") || datasetName.Contains("h500") || datasetName.Contains("h550") || datasetName.Contains("h600") ||
       datasetName.Contains("h700") || datasetName.Contains("h800") || datasetName.Contains("h900") || datasetName.Contains("h1000")){
      TH1D *histBeforeWeight = (TH1D*) gROOT->FindObject("hDHKFactor_1");
      TH1D *histAfterWeight  = (TH1D*) gROOT->FindObject("hDHKFactor_2");
      cout << "Nevents before/after reweighting: " << histBeforeWeight->GetSumOfWeights() << " " << 
                                                      histAfterWeight->GetSumOfWeights() << endl;
      Weight = Weight * histBeforeWeight->GetSumOfWeights() / histAfterWeight->GetSumOfWeights();
    }
  }

  //delete dir;
  delete file;
  return Weight;

}
Beispiel #17
0
int main(){
	TFile * data = TFile::Open("TreesMu_Data_plots.root");
	TH1D * dataMtop = (TH1D*)data->Get("antiEtaFwDTrue_allW/antiEtaFwDTrue_allWcosTheta");
	
	TFile * tt = TFile::Open("TreesMu_TTBar_RW.root");
	
	TH1D * ttMtop = (TH1D*)tt->Get("MtopOutWindowTrue_allW/MtopOutWindowTrue_allWcosTheta");
	
	TH2D * ttMtop2D = (TH2D*)tt->Get("MtopOutWindowTrue_allW/MtopOutWindowTrue_allWcosTheta2D");
	
  std::pair<TF1, WeightFunctionCreator*> WeightFuncUD(WeightFunctionCreator::getWeightFunction("WeightFuncUDF", F0, FL));
  std::pair<TF1, WeightFunctionCreator*> WeightFuncDU(WeightFunctionCreator::getWeightFunction("WeightFuncDUF", F0, FL));
  cout<<F0 + F0Sys<<"\t"<<FL - FLSys<<endl;
	WeightFuncUD.first.SetParameters(F0 + F0Sys, FL - FLSys);
	WeightFuncDU.first.SetParameters(F0 - F0Sys, FL + FLSys);
	
	TH1D * ttUD = myReweightor(ttMtop2D,WeightFuncUD,"WeightFuncUD_");
	cout<<"ratio: "<<ttMtop2D->Integral()/ttUD->Integral()<<endl;
	ttUD->Scale(ttMtop2D->Integral()/ttUD->Integral());
	ttUD->Add(ttMtop);
	TH1D * wUD = (TH1D*)ttUD->Clone("wUD");
	wUD->Scale(-1.);
	wUD->Add(dataMtop);
	
	TH1D * ttDU = myReweightor(ttMtop2D,WeightFuncDU,"WeightFuncDU_");
	cout<<"ratio: "<<ttMtop2D->Integral()/ttDU->Integral()<<endl;
	ttDU->Scale(ttMtop2D->Integral()/ttDU->Integral());
	ttDU->Add(ttMtop);
	TH1D * wDU = (TH1D*)ttDU->Clone("wDU");
	wDU->Scale(-1.);
	wDU->Add(dataMtop);
	
	TFile * out = new TFile("file.root","recreate");
	out->cd();
	WeightFuncUD.first.Write();
	WeightFuncDU.first.Write();
	ttUD->Write();
	ttDU->Write();	
	wUD->Write();
	wDU->Write();	
	out->Close();
	return 1;
}
Beispiel #18
0
TFile* getFile(std::string infiles, Double_t crossSection, Double_t* scale){

  TFile* f = TFile::Open(infiles.data());
  TH1D* h = (TH1D*)(f->Get("totalEvents"));
  Double_t dataLumi = 2080; //pb-1 
  *scale = dataLumi/(h->Integral()/crossSection);

  return f;

}
Beispiel #19
0
void mc2ibd_PPX(char X, TChain *tMC, TFile *fBgnd, TCanvas *cv)
{
	char str[1024];
	TH1D *hExp;
	TH1D *hMC;
	TCut cut;

	sprintf(str, "hP%cA-diff", X);
	hExp = (TH1D *) fBgnd->Get(str);
	if (!hExp) {
		printf("Histogram hP%cA-diff not found in %s\n", X, fBgnd->GetName());
		return;
	}
	gROOT->cd();
	sprintf(str, "hMCPP%c", X);
	hMC = new TH1D(str, "MC XYZ", hExp->GetNbinsX(), 0, 100);
	sprintf(str, "PositronX[%d]+%4.1f", X - 'X', (X=='Z') ? 0.5 : 2.0);
	switch (X) {
	case 'X':
		cut = cY && "PositronX[0]>=0" && cZ && cR && c20 && cGamma && cGammaMax && cPe && cN;
		break;
	case 'Y':
		cut = cX && "PositronX[1]>=0" && cZ && cR && c20 && cGamma && cGammaMax && cPe && cN;
		break;
	default:
		cut = cX && cY && cR && c20 && cGamma && cGammaMax && cPe && cN;
	}
	tMC->Project(hMC->GetName(), str, cut);
	hMC->Sumw2();
	cv->Clear();
	hExp->SetLineColor(kBlack);
	hExp->SetLineWidth(3);
	hMC->SetLineColor(kBlue);
	hMC->SetLineWidth(1);
	hMC->Scale(hExp->Integral() / hMC->Integral());
	hExp->Draw();
	hMC->Draw("hist,same");
	TLegend *lg = new TLegend(0.5, 0.2, 0.65, 0.35);
	lg->AddEntry(hExp, "IBD", "LE");
	lg->AddEntry(hMC,  "MC",  "L");
	lg->Draw();
	cv->Update();
}
Beispiel #20
0
void testIntegration(){
	
	
	
	TFile* infile = new TFile("/Users/keithlandry/Desktop/testPtHist.root");

	TH1D * h = infile->Get("Pt");
	
	
	int bmin = 751;
	int bmax = bmin+1;
	
  double binval = 0;
	int numberOfPairs = 0;
	
	cout << "starting at bmin = " << bmin << "  bmax = " << bmax << endl;
	
	cout << (double)h->GetEntries()/9.0 << endl;
	
	for (int i=0; i < h->GetNbinsX()-bmin; i++)
	{
		bmax++;

		cout << " i = " << i << " bmax = " << bmax << endl;
		
		int integ = h->Integral(bmin,bmax);
		
		cout << bmax << "   " << integ << endl;
		
		binval += h->GetBinContent(bmax)*h->GetBinCenter(bmax);
		numberOfPairs += h->GetBinContent(bmax);

		if (integ > (double)h->GetEntries()/9.0)
		{
			cout << bmax << "   " << integ << endl;
			lastI = i;
			break;
		}
		
		if (bmax == 1000)
		{
			break;
		}
		
		
	}
	
	
	cout << "avg val of bin " << (double)binval/numberOfPairs << endl;
	
	cout << " Pt = " << h->GetBinCenter(bmax) << endl;
	
	
	
}
Beispiel #21
0
void makeWeightDistribution(TH1D *mcScenario, vector<double> & dataPileupDistribution, vector<double> & result) {
   std::cout<<"does it even start?"<<std::endl;
  Int_t nbins = mcScenario->GetNbinsX();
  std::cout<<"splitter"<<std::endl;
  Int_t ndatabins = dataPileupDistribution.size();
  std::cout<<"two more lines"<<std::endl;
  TH1D *hweights = new TH1D("hweights", "hweights", nbins, mcScenario->GetXaxis()->GetXmin(), mcScenario->GetXaxis()->GetXmax());
  //std::cout<<" ******************************************  1"<<std::endl;
  for(int ibin=0; ibin<nbins; ++ibin) {
	    //std::cout<<" ******************************************  2"<<std::endl;

    if(ibin<ndatabins)
      hweights->SetBinContent(ibin+1, dataPileupDistribution[ibin]);
    else
      hweights->SetBinContent(ibin+1, 0.);
  }

  // Check integrals, make sure things are normalized
  float deltaH = hweights->Integral();
  if( fabs(1.0 - deltaH)>0.02 ) { // *OOPS*...
    hweights->Scale( 1.0/hweights->Integral() );
  }
  float deltaMC = mcScenario->Integral();
  if( fabs(1.0 - deltaMC)>0.02 ) {
    mcScenario->Scale( 1.0/mcScenario->Integral() );
  }
  //std::cout<<" ******************************************  3"<<std::endl;

  hweights->Divide( mcScenario );  // so now the average weight should be 1.0    

  for(int ibin=0; ibin<nbins; ++ibin) {
  //std::cout<<" ******************************************  4"<<std::endl;
	  
    result.push_back(hweights->GetBinContent(ibin+1));
  }
  //std::cout<<" ******************************************  5"<<std::endl;

  delete hweights;
  //std::cout<<" ******************************************  6"<<std::endl;

  return;
}
//################################################################################################################################
 // Get the 68% confindence interval of mu1/mu2
void getPoissonIntervalls(double mu1, double mu2){

  double result = mu1/mu2;
  TH1D *expHist = new TH1D("mu1/mu2","mu1/mu2",1000,0,1);
  TRandom3 rand1(0);
  TRandom3 rand2(0);

  cout<<"mu1 = "<<mu1<<endl;
  cout<<"mu2 = "<<mu2<<endl;
  cout<<"ratio = "<<result<<endl;

  for(int i=0; i<10000000; i++){

    expHist->Fill(1.*rand1.Poisson(mu1)/rand2.Poisson(mu2));
  }

  // Get now the 68% upper and lower interval
  double errUp  = 0;
  double errLow = 0;
  for(int i=1; i<=expHist->GetNbinsX();i++){

    double upperIntegral = expHist->Integral(i,expHist->GetNbinsX());
    double lowerIntegral = expHist->Integral(1,i);

    if(abs(upperIntegral/expHist->Integral()-0.32)<0.02){
      cout<<"upper bound = "<<expHist->GetBinCenter(i)<<endl;
      errUp = expHist->GetBinCenter(i)-result;
    }
    if(abs(lowerIntegral/expHist->Integral()-0.32)<0.02){
      cout<<"lower bound = "<<expHist->GetBinCenter(i)<<endl;
      errLow = result - expHist->GetBinCenter(i);
    }
  }


  cout<<"error Up = "<<errUp<<endl;
  cout<<"error Low = "<<errLow<<endl;

  TCanvas *c = new TCanvas("cExp","cExp",0,0,500,500);
  c->cd();
  expHist->Draw();
}    
Beispiel #23
0
void DrawNcollNpartdis(){
        int Gth=0;
	TFile *fGlauber = TFile::Open(stdGlaulist[Gth]);
	TTree *t = (TTree*)fGlauber->Get("nt_Pb_Pb");
        Float_t Ncoll, Npart, B;	Long_t Nevent;
	t->SetBranchAddress("Ncoll",&Ncoll);
	t->SetBranchAddress("Npart",&Npart);
	t->SetBranchAddress("B",&B);
        Nevent = (Long_t) t->GetEntries();
    	Long_t Ev;	Int_t Bino;	Double_t Para, Bi_Para;
        TH1D* hNcoll = new TH1D("","",4000,0,4000);
        TH1D* hNpart = new TH1D("","",4000,0,4000);
	for (Ev=0; Ev<Nevent; Ev++){
	//if(Ev%100000==0)	cout<<"\t"<<"Have run "<<Ev<<" events"<<endl;
        	t->GetEntry(Ev);
                hNcoll->Fill(Ncoll);
                hNpart->Fill(Npart);
        }
	TString name;
        if(Gth==0)
                name = "G0";
        else if(Gth<nGlau)
                name = Form("Glau_%d",Gth);
        else
                name = Form("bin_%d",Gth-nGlau+1);
        TCanvas *c1 = new TCanvas();
        c1->SetLogy();
        hNcoll->Scale(1./hNcoll->Integral());
        hNcoll->GetXaxis()->SetRangeUser(0,3000);
        hNcoll->GetXaxis()->SetTitle("Ncoll");
        hNcoll->GetYaxis()->SetTitle("Event Fraction");
        hNcoll->Draw();
        c1->Print(Form("%s_Ncoll.png",name.Data()));
        TCanvas *c2 = new TCanvas();
        c2->SetLogy();
        hNpart->Scale(1./hNpart->Integral());
        hNpart->GetXaxis()->SetRangeUser(0,500);
        hNpart->GetXaxis()->SetTitle("Npart");
        hNpart->GetYaxis()->SetTitle("Event Fraction");
        hNpart->Draw();
        c2->Print(Form("%s_Npart.png",name.Data()));
}
TH1D * getNiceHistogram(int nbins, std::vector<Double_t> binning, TFile * file, TString hist) {
  TH1D *sample = (TH1D*)(file->Get(hist)->Clone());
  TH1D *binned = dynamic_cast<TH1D*>(sample->Rebin(nbins,"madgraph",&binning.front()));
  for (Int_t bin=0; bin < nbins; bin++) {
    // Divide rebinned histogram's bin content by bin width factor (new/old):
    binned->SetBinError(bin+1,sqrt(binned->GetBinContent(bin+1))/((binning.at(bin+1)-binning.at(bin))/sample->GetBinWidth(1)));
    binned->SetBinContent(bin+1,binned->GetBinContent(bin+1)/((binning.at(bin+1)-binning.at(bin))/sample->GetBinWidth(1)));
  }
  binned->Scale(1/binned->Integral("width"));
  return binned;
}
Beispiel #25
0
void combineHists( TFile* fSig, TFile* fBg, std::string histName, std::string plotOpt, std::string outputName, std::string label=""){
    TH1::SetDefaultSumw2();

    TCanvas c1;
    TH1D* hSig = fSig->Get(histName.c_str());
    TH1D* hBg  = fBg->Get(histName.c_str());
    cout << "signal: " << hSig->Integral()  << " bg: " << hBg->Integral() << endl;
    hSig->SetMarkerSize(0);
    doSignalHist(hSig);
    hBg->SetMarkerSize(0);
    doAltBGHist(hBg);
    
    THStack st("h","");
    st.Add(hSig);
    st.Add(hBg);
    st.Draw((plotOpt+"NOSTACK").c_str());
    st.GetXaxis()->SetTitle(hSig->GetXaxis()->GetTitle());
    st.GetYaxis()->SetTitle(hSig->GetYaxis()->GetTitle());
    setAltTitleLabelSizes(&st.GetHistogram());

    st.SetTitle("");
    st.Draw((plotOpt+"NOSTACK").c_str());
    TLegend leg(0.65,0.6, 0.85,0.85);
    doStandardLegend(&leg);
    leg.AddEntry(hSig,"#splitline{Signal MC}{m_{#phi} = 8 GeV}","l");
    leg.AddEntry(hBg,"QCD b#bar{b} MC","l");
    leg.Draw();

    TPaveText t(0.15, 0.7, 0.5, 0.8, "NDC");
    t.AddText(label.c_str());
    doStandardText(&t);
    if (label != "") {
        t.Draw();
    }
    c1.SaveAs(outputName.c_str());

    if (!hSig) delete hSig;
    if (!hBg) delete hBg;
}
double countTotal(process &process)
{
  // Create temporary histogram
  TH1D* tmp = new TH1D("tmp", "tmp", 30, 0, 1000);

  double Total = 0;
  process.GetChain()->Draw("Njet>>tmp", "XS*5000/Nevt", "goff");
  Total = int(tmp->Integral());

  delete tmp;
  process.SetNevt_nosel(Total);
  return Total;
}
double countDataEvt(TChain* chain, TCut Cut)
{
  // Create temporary histogram
  TH1D* tmp = new TH1D("tmp", "tmp", 30, 0, 1000);

  // Get number of events after a cut
  double Evt = 0;
  chain->Draw("Njet>>tmp",Cut, "goff");
  Evt = tmp->Integral();

  delete tmp;
  return Evt;
}
double countDataTotal(TChain* chain)
{
  // Create temporary histogram
  TH1D* tmp = new TH1D("tmp", "tmp", 30, 0, 1000);

  // Get number of events after a cut
  double Total = 0;
  chain->Draw("Njet>>tmp","", "goff");
  Total = tmp->Integral();

  delete tmp;
  return Total;
}
Beispiel #29
0
double getQCD(TString Variable, TString Obj, int rebinFact, double *errorRef) {
    TString dir = "rootFilesV4/central/";
    TFile* file = new TFile(dir + "SingleMu_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");

    TFile* tt_file = new TFile(dir + "TTJet_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
    TFile* vjets_file = new TFile(dir + "VJets_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
    TFile* stop_file = new TFile(dir + "SingleTop_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");

    cout << "TTbar_plus_X_analysis/MuPlusJets/QCD non iso mu+jets ge3j/"+Obj+"0btag" << endl;

    TString IsoFolder;
    if(Variable == "HT") {
        IsoFolder = "QCD mu+jets PFRelIso";
    } else {
        IsoFolder = "QCD non iso mu+jets ge3j";
    }


    TH1D* plot = (TH1D*) file->Get("TTbar_plus_X_analysis/MuPlusJets/"+IsoFolder+"/"+Obj+"0btag");
    plot->Sumw2();

    TH1D* tt_plot = (TH1D*) tt_file->Get("TTbar_plus_X_analysis/MuPlusJets/"+IsoFolder+"/"+Obj+"0btag");
    TH1D* vjets_plot = (TH1D*) vjets_file->Get("TTbar_plus_X_analysis/MuPlusJets/"+IsoFolder+"/"+Obj+"0btag");
    TH1D* stop_plot = (TH1D*) stop_file->Get("TTbar_plus_X_analysis/MuPlusJets/"+IsoFolder+"/"+Obj+"0btag");

    TH1D* allMC = (TH1D*)tt_plot->Clone("allMC");

    allMC->Add(vjets_plot);
    allMC->Add(stop_plot);

    plot->Add(allMC, -1);

    *errorRef = sqrt(plot->Integral() + pow(0.5*allMC->Integral(),2));

    return plot->Integral();

}
Beispiel #30
0
/* Get a fake estimate from the given histogram, i.e. return Data - MC.
 *
 * Subtract all background MCs from data but the one specified with
 * "notremove". Under- and overflows are ignored in computation.
 *
 * @param hname     Histogram name from which to compute estimate
 * @return          Histogram of fakes
 */
TH1D * get_fakes_1d(const char * hname)
{
  // get number of single fakes from data histogram
  plot(hname);
  legend();
  TH1D * hData = dataHisto();
  if (hData == 0) {
    THROW("get_fakes() needs a data histogram");
  }
  // data
  double N = hData->Integral();
  INFO("Data events: " << N);

  TH1D * hBack = 0;
  for (unsigned int i = 0; i < sizeof(removeNames)/sizeof(void *); i++) {
    TH1D * hSub = backgroundHisto(removeNames[i]);
    if (hSub == 0) {
      THROW(string("get_fakes() problem getting background ")+removeNames[i]);
    }
    // add backgrounds together
    if (hBack == 0) {
      hBack = hSub;
    }
    else {
      hBack->Add(hSub);
      delete hSub;
    }
  }
  N = hBack->Integral();
  INFO("Background events : " << N);

  // subtract
  hData->Add(hBack, -1.);
  // temporarily needed for function call
  delete hBack;
  return hData;
}