Example #1
2
void annconvergencetest( TDirectory *lhdir )
{
   TCanvas* c = new TCanvas( "MLPConvergenceTest", "MLP Convergence Test", 150, 0, 600, 580*0.8 ); 
  
   TH1* estimatorHistTrain = (TH1*)lhdir->Get( "estimatorHistTrain" );
   TH1* estimatorHistTest  = (TH1*)lhdir->Get( "estimatorHistTest"  );

   Double_t m1  = estimatorHistTrain->GetMaximum();
   Double_t m2  = estimatorHistTest ->GetMaximum();
   Double_t max = TMath::Max( m1, m2 );
   m1  = estimatorHistTrain->GetMinimum();
   m2  = estimatorHistTest ->GetMinimum();
   Double_t min = TMath::Min( m1, m2 );
   estimatorHistTrain->SetMaximum( max + 0.1*(max - min) );
   estimatorHistTrain->SetMinimum( min - 0.1*(max - min) );
   estimatorHistTrain->SetLineColor( 2 );
   estimatorHistTrain->SetLineWidth( 2 );
   estimatorHistTrain->SetTitle( TString("MLP Convergence Test") );
  
   estimatorHistTest->SetLineColor( 4 );
   estimatorHistTest->SetLineWidth( 2 );

   estimatorHistTrain->GetXaxis()->SetTitle( "Epochs" );
   estimatorHistTrain->GetYaxis()->SetTitle( "Estimator" );
   estimatorHistTrain->GetXaxis()->SetTitleOffset( 1.20 );
   estimatorHistTrain->GetYaxis()->SetTitleOffset( 1.65 );

   estimatorHistTrain->Draw();
   estimatorHistTest ->Draw("same");

   // need a legend
   TLegend *legend= new TLegend( 1 - c->GetRightMargin() - 0.45, 1-c->GetTopMargin() - 0.20, 
                                 1 - c->GetRightMargin() - 0.05, 1-c->GetTopMargin() - 0.05 );

   legend->AddEntry(estimatorHistTrain,"Training Sample","l");
   legend->AddEntry(estimatorHistTest,"Test sample","l");
   legend->Draw("same");
   legend->SetMargin( 0.3 );

   c->cd();
   TMVAGlob::plot_logo(); // don't understand why this doesn't work ... :-(
   c->Update();

   TString fname = "plots/annconvergencetest";
   TMVAGlob::imgconv( c, fname );
}
Example #2
1
void ratioPlots( TCanvas* c1, TH1* h_r, TH1* h_i, 
		 string xTitle, string yTitle, 	string savePath, 
		 double fitMin=-100000, double fitMax=100000, bool doubleColFit=0 ){

	double xMaximum = h_r->GetXaxis()->GetBinUpEdge(h_r->GetXaxis()->GetLast());
	double xMinimum = h_r->GetXaxis()->GetBinLowEdge(h_r->GetXaxis()->GetFirst());
	double yMaximum;
	double yMinimum;

	h_i->Sumw2();
	h_r->Sumw2();

	TLine* line1 = new TLine(xMinimum,1,xMaximum,1);
	line1->SetLineColor(1);
	line1->SetLineWidth(2);
	line1->SetLineStyle(7);
	
	TF1* fpol1  = new TF1("fpol1", "pol1", fitMin, fitMax);	
	fpol1->SetLineColor(2);
	fpol1->SetLineWidth(3);
	fpol1->SetLineStyle(7);
	
	TH1* hRatio = (TH1*)h_r->Clone("clone_record");
	hRatio->Divide(h_i);
	yMaximum = hRatio->GetMaximum();
	yMinimum = hRatio->GetMinimum(0);
	hRatio->GetYaxis()->SetRangeUser(yMinimum/2.5,yMaximum+yMaximum/5);
	hRatio->SetXTitle(xTitle.c_str());
	hRatio->SetYTitle(yTitle.c_str());
	hRatio->SetLineColor(9); 
	hRatio->SetLineWidth(2); 
	hRatio->SetMarkerStyle(8); 
	hRatio->Draw("e");
	hRatio->Fit("fpol1", "L");
	line1->Draw("SAME");
	
	if(doubleColFit){
		double p0=fpol1->GetParameter(0);
		double p1=fpol1->GetParameter(1);
		double endPoint=double(fitMax*p1)+p0;
		double p1new=(endPoint-1)/(fitMax-fitMin);
		char fun[100], text[100];
		sprintf(fun,"x*(%f)+1",p1new);	
		sprintf(text,"Tangent: %f",p1new);	
		TF1* fnew = new TF1("fnew", fun, fitMin, fitMax);
		fnew->SetLineColor(2);
		fnew->SetLineWidth(3);
		fnew->Draw("SAME");
	
			
		TText* Title = new TText( fitMax/12, yMinimum, text);
		Title->SetTextColor(2);
		Title->SetTextSize(0.035);
		Title->Draw("SAME");
	}

	c1->SaveAs(savePath.c_str());
	c1->cd();
}
Example #3
0
// -----------------------------------------------------------------------------
//
TH1* getHisto( std::string nameFile,
	       std::string nameHist,
	       std::string Dirname, 
	       int rebin ) {
  std::string name = nameFile;
  TFile* file =  new TFile(name.c_str());
  if (file) { std::cout << "Opened file: " << file->GetName() << std::endl; }
  else { 
    std::cout << "Could not find file: " << name << std::endl; 
    return 0; 
  }
  
  TDirectory* dir = (TDirectory*)file->Get(Dirname.c_str());
  if (dir) { std::cout << "Opened dir: " << dir->GetName() << std::endl; }
  else { 
    std::cout << "Could not find dir: " << Dirname << std::endl; 
    return 0; 
  }
  
  int low = 375;
  TH1* hist = 0;
  if ( false || nameHist.find("HtMultiplicity_HT375") == std::string::npos ) { 
    hist = (TH1*)dir->Get(nameHist.c_str());
  } else {
    
    for ( uint ii = low; ii <= 975; ii+=100 ) {
      std::stringstream tmp; tmp << "HtMultiplicity_HT" << ii << nameHist.substr(20);
      if ( !hist ) { 
	dir->cd();
	TH1D* temp = (TH1D*)dir->Get( "HtMultiplicity_HT375_aT0" );
	//TH1D* temp = (TH1D*)file->Get( tmp.str().c_str() );
	if (temp) { hist = (TH1D*)temp->Clone(); } 
	else { std::cout << "1 Unable to retrieve histo with name " << tmp.str() << std::endl; }
      } else { 
	dir->cd();
	TH1D* temp = (TH1D*)dir->Get( tmp.str().c_str() );
	if (temp) { hist->Add( (TH1D*)temp ); } 
	else { std::cout << "2 Unable to retrieve histo with name " << tmp.str() << std::endl; }
      }
    }

  }
  if (hist) { std::cout << "Opened histo: " << hist->GetName() << std::endl; }
  else { 
    std::cout << "Could not find histo: " << nameHist << std::endl; 
    return 0; 
  }

  hist->SetLineWidth(3);
  if ( rebin > 0 ) { hist->Rebin(rebin); }
  hist->GetXaxis()->SetTitleSize(0.055);
  hist->GetYaxis()->SetTitleSize(0.055);
  hist->GetXaxis()->SetLabelSize(0.05);
  hist->GetYaxis()->SetLabelSize(0.05);
  hist->SetStats(kFALSE);
  return hist;
}
Example #4
0
/**
SetColor/Style Histo
*/
void SetColorAndStyleHisto(TH1 & histo , EColor color){
 histo.SetFillStyle (3001) ;
 histo.SetFillColor (color) ;
 histo.SetLineColor (color) ;
 histo.SetLineWidth (1) ;
 histo.SetMarkerColor (color) ;
 histo.SetMarkerSize (1) ;
 histo.SetMarkerStyle (20) ;
}
TH1* GetHist(const string histname)
{
	//hists are already scaled to 10fb-1
	TH1* h = dynamic_cast<TH1*> (files[0]->Get(histname.c_str()));
	if (h == NULL)
	{
		cout << "hist " << histname << " not found in " <<  "!" << endl;
		assert (false);
	}
	TH1* hist = dynamic_cast<TH1*> (h->Clone());
	hist->Sumw2();
	hist->SetLineWidth(2);

	return hist;
}
void DrawHijing2GeV()
{
  TCanvas *c1 = new TCanvas();
TFile *fin = TFile::Open("Gamma_Neutron_Hijing_Energy_Graphs.root");
gROOT->cd();
TH1 *h1lim = new TH1F("h1lim","",1,0,0.1);
TH1 *hjbkg = (TH1 *) fin->Get("hjbkg")->Clone();
TGraph *anti_neutron2GeV = (TGraph *) fin->Get("anti_neutron2GeV")->Clone();
TGraph *neutron2GeV = (TGraph *) fin->Get("neutron2GeV")->Clone();
h1lim->SetStats(0);
h1lim->SetMaximum(0.3);
h1lim->SetTitle("2 GeV Hadronic Showers with HIJING background");
h1lim->GetYaxis()->SetTitle("Deposited Energey [GeV]");
h1lim->GetYaxis()->SetTitleOffset(1.2);
h1lim->GetXaxis()->SetTitle("cone size (#sqrt{#Delta#Phi^{2}+#Delta#Theta^{2}})");
h1lim->GetXaxis()->SetTitleOffset(1.2);
h1lim->Draw();
hjbkg->SetStats(0);
hjbkg->SetLineColor(6);
hjbkg->SetMaximum(5.5);
hjbkg->SetLineWidth(2);
hjbkg->Draw("same");
anti_neutron2GeV->SetLineColor(4);
anti_neutron2GeV->SetLineWidth(2);
anti_neutron2GeV->Draw("same");
neutron2GeV->SetLineColor(2);
neutron2GeV->SetLineWidth(2);
neutron2GeV->Draw("same");
TLine *tl = new TLine();
tl->SetLineStyle(2);
tl->DrawLine(0.024,0,0.024,0.3);
TLegend *legrda = new TLegend(0.67,0.34,0.87,0.54,NULL,"brNDC");
  legrda->SetLineColor(1);
  legrda->SetLineStyle(1);
  legrda->SetLineWidth(1);
  legrda->SetFillColor(10);
  legrda->SetFillStyle(1001);
  legrda->SetBorderSize(0);
//  legrda->SetTextSize(labelsize);
  legrda->AddEntry(hjbkg,"HIJING bkg"); 
  legrda->AddEntry(anti_neutron2GeV,"2 GeV Anti Neutron","l"); 
  legrda->AddEntry(neutron2GeV,"2 GeV Neutron", "l"); 
  legrda->AddEntry(tl,"EMCal tower size","l"); 
  legrda->Draw();
 
fin->Close();
c1->Print("Hijing2GeV.png");
}
void histogramStyle(TH1& hist, int color, int lineStyle, int markerStyle, float markersize, int filled) 
{
  hist.SetLineWidth(3);
  hist.SetStats(kFALSE);
  hist.SetLineColor  (color);
  hist.SetMarkerColor(color);  
  hist.SetMarkerStyle(markerStyle);
  hist.SetMarkerSize(markersize);
  hist.SetLineStyle(lineStyle);
  if(filled==1){
  hist.SetFillStyle(1001);
  hist.SetFillColor(color);
  }
  else{
    hist.SetFillStyle(0);
  }
}
void makePlot_legend(TLegend* legend, const std::string& outputFilePath, const std::string& outputFileName)
{
  TCanvas* canvas_legend = new TCanvas("canvas_legend", "canvas_legend", 900, 800);
  canvas_legend->SetFillColor(10);
  canvas_legend->SetBorderSize(2);
  canvas_legend->Draw();
  canvas_legend->cd();

  legend->SetX1NDC(0.30);
  legend->SetY1NDC(0.30);
  legend->SetX2NDC(0.80);
  legend->SetY2NDC(0.80);
  legend->SetTextSize(0.070);
  legend->SetMargin(0.20);
  TList* legend_primitives = legend->GetListOfPrimitives();
  TIter legend_nextObj(legend_primitives);
  while ( TObject* obj = legend_nextObj() ) {
    std::string objName = "";
    if ( dynamic_cast<TNamed*>(obj) ) objName = (dynamic_cast<TNamed*>(obj))->GetName();    
    //std::cout << "obj = " << obj << ": name = " << objName << ", type = " << obj->ClassName() << std::endl;

    TLegendEntry* legendEntry = dynamic_cast<TLegendEntry*>(obj);
    if ( legendEntry ) {
      TH1* histogram = dynamic_cast<TH1*>(legendEntry->GetObject());
      if ( histogram ) {
	histogram->SetLineWidth(2*histogram->GetLineWidth());
	histogram->SetMarkerSize(3);
      }
    }
  }
  legend->Draw();

  canvas_legend->Update();

  std::string outputFileName_full = Form("%s%s", outputFilePath.data(), outputFileName.data());
  size_t idx = outputFileName_full.find_last_of('.');
  std::string outputFileName_plot = std::string(outputFileName_full, 0, idx);
  canvas_legend->Print(std::string(outputFileName_plot).append(".pdf").data());
  canvas_legend->Print(std::string(outputFileName_plot).append(".root").data());

  delete canvas_legend;
}
vector<TH1*> GetHist(const string histname)
{
	//hists are already scaled to 10fb-1
	vector<TH1*> hists;
	for (int i=0; i< nBins; ++i)
	{
		TH1* h = dynamic_cast<TH1*> (files[i]->Get(histname.c_str()));
		if (h == NULL)
		{
			cout << "hist " << histname << " not found in file # " << i <<  " !" << endl;
			assert (false);
		}
		TH1* hist = dynamic_cast<TH1*> (h->Clone());
		hist->Sumw2();
		hist->SetLineWidth(2);
		hists.push_back(hist);
	}

	return hists;
}
void boostcontrolplots( TDirectory *boostdir ) {

   const Int_t nPlots = 4;

   Int_t width  = 900;
   Int_t height = 600;
   char cn[100];
   const TString titName = boostdir->GetName();
   sprintf( cn, "cv_%s", titName.Data() );
   TCanvas *c = new TCanvas( cn,  Form( "%s Control Plots", titName.Data() ),
                             width, height ); 
   c->Divide(2,2);


   const TString titName = boostdir->GetName();

   TString hname[nPlots]={"Booster_BoostWeight","Booster_MethodWeight","Booster_ErrFraction","Booster_OrigErrFraction"};

   for (Int_t i=0; i<nPlots; i++){
      Int_t color = 4; 
      TPad * cPad = (TPad*)c->cd(i+1);
      TH1 *h = (TH1*) boostdir->Get(hname[i]);
      TString plotname = h->GetName();
      h->SetMaximum(h->GetMaximum()*1.3);
      h->SetMinimum( 0 );
      h->SetMarkerColor(color);
      h->SetMarkerSize( 0.7 );
      h->SetMarkerStyle( 24 );
      h->SetLineWidth(1);
      h->SetLineColor(color);
      h->Draw();
      c->Update();
   }

   // write to file
   TString fname = Form( "plots/%s_ControlPlots", titName.Data() );
   TMVAGlob::imgconv( c, fname );
   
}
Example #11
0
void SetAxisLabels(TH1& hist, char* xtitle, char* ytitle="",
		   double xoffset=1.1, double yoffset=1.4) {

  TAxis* x = hist.GetXaxis();
  TAxis* y = hist.GetYaxis();
  x->SetTitle(xtitle);
  x->SetTitleSize(0.06);
  x->SetLabelSize(0.05);
  x->SetTitleOffset(xoffset);
  x->SetNdivisions(505);
  y->SetTitle(ytitle);
  y->SetTitleSize(0.06);
  y->SetLabelSize(0.05);
  y->SetTitleOffset(yoffset);
  y->SetNoExponent();
  hist.SetLineWidth(2);
  hist.SetMarkerStyle(20);

  std::stringstream str;
  str << "Events / " << (int) lumi << " pb^{-1}   ";
  std::string  defYtitle = str.str();
  if(ytitle=="") y->SetTitle( defYtitle.c_str() );
}
Example #12
0
TH1* compRatioHistogram(const std::string& ratioHistogramName, const TH1* numerator, const TH1* denominator)
{
  TH1* histogramRatio = 0;
  
  if ( numerator->GetDimension() == denominator->GetDimension() &&
       numerator->GetNbinsX() == denominator->GetNbinsX() ) {
    histogramRatio = (TH1*)numerator->Clone(ratioHistogramName.data());
    histogramRatio->Divide(denominator);
    
    int nBins = histogramRatio->GetNbinsX();
    for ( int iBin = 1; iBin <= nBins; ++iBin ){
      double binContent = histogramRatio->GetBinContent(iBin);
      histogramRatio->SetBinContent(iBin, binContent - 1.);
    }
    
    histogramRatio->SetLineColor(numerator->GetLineColor());
    histogramRatio->SetLineWidth(numerator->GetLineWidth());
    histogramRatio->SetMarkerColor(numerator->GetMarkerColor());
    histogramRatio->SetMarkerStyle(numerator->GetMarkerStyle());
    histogramRatio->SetMarkerSize(numerator->GetMarkerSize());
  }

  return histogramRatio;
}
Example #13
0
// input: - Input file (result from TMVA)
//        - use of TMVA plotting TStyle
void mvas( TString fin = "TMVA.root", HistType htype = MVAType, Bool_t useTMVAStyle = kTRUE )
{
   // set style and remove existing canvas'
   TMVAGlob::Initialize( useTMVAStyle );

   // switches
   const Bool_t Save_Images     = kTRUE;

   // checks if file with name "fin" is already open, and if not opens one
   TFile* file = TMVAGlob::OpenFile( fin );  

   // define Canvas layout here!
   Int_t xPad = 1; // no of plots in x
   Int_t yPad = 1; // no of plots in y
   Int_t noPad = xPad * yPad ; 
   const Int_t width = 600;   // size of canvas

   // this defines how many canvases we need
   TCanvas *c = 0;

   // counter variables
   Int_t countCanvas = 0;

   // search for the right histograms in full list of keys
   TIter next(file->GetListOfKeys());
   TKey *key(0);   
   while ((key = (TKey*)next())) {

      if (!TString(key->GetName()).BeginsWith("Method_")) continue;
      if( ! gROOT->GetClass(key->GetClassName())->InheritsFrom("TDirectory") ) continue;

      TString methodName;
      TMVAGlob::GetMethodName(methodName,key);

      TDirectory* mDir = (TDirectory*)key->ReadObj();

      TIter keyIt(mDir->GetListOfKeys());
      TKey *titkey;
      while ((titkey = (TKey*)keyIt())) {
         if (!gROOT->GetClass(titkey->GetClassName())->InheritsFrom("TDirectory")) continue;

         TDirectory *titDir = (TDirectory *)titkey->ReadObj();
         TString methodTitle;
         TMVAGlob::GetMethodTitle(methodTitle,titDir);

         cout << "--- Found directory for method: " << methodName << "::" << methodTitle << flush;
         TString hname = "MVA_" + methodTitle;
         if      (htype == ProbaType  ) hname += "_Proba";
         else if (htype == RarityType ) hname += "_Rarity";
         TH1* sig = dynamic_cast<TH1*>(titDir->Get( hname + "_S" ));
         TH1* bgd = dynamic_cast<TH1*>(titDir->Get( hname + "_B" ));

         if (sig==0 || bgd==0) {
            if     (htype == MVAType)     
               cout << "mva distribution not available (this is normal for Cut classifier)" << endl;
            else if(htype == ProbaType)   
               cout << "probability distribution not available (this is normal for Cut classifier)" << endl;
            else if(htype == RarityType)  
               cout << "rarity distribution not available (this is normal for Cut classifier)" << endl;
            else if(htype == CompareType) 
               cout << "overtraining check not available (this is normal for Cut classifier)" << endl;
            else cout << endl;
         } 
         else {
            cout << endl;
            // chop off useless stuff
            sig->SetTitle( Form("TMVA response for classifier: %s", methodTitle.Data()) );
            if      (htype == ProbaType) 
               sig->SetTitle( Form("TMVA probability for classifier: %s", methodTitle.Data()) );
            else if (htype == RarityType) 
               sig->SetTitle( Form("TMVA Rarity for classifier: %s", methodTitle.Data()) );
            else if (htype == CompareType) 
               sig->SetTitle( Form("TMVA overtraining check for classifier: %s", methodTitle.Data()) );
         
            // create new canvas
            TString ctitle = ((htype == MVAType) ? 
                              Form("TMVA response %s",methodTitle.Data()) : 
                              (htype == ProbaType) ? 
                              Form("TMVA probability %s",methodTitle.Data()) :
                              (htype == CompareType) ? 
                              Form("TMVA comparison %s",methodTitle.Data()) :
                              Form("TMVA Rarity %s",methodTitle.Data()));
         
            TString cname = ((htype == MVAType) ? 
                             Form("output_%s",methodTitle.Data()) : 
                             (htype == ProbaType) ? 
                             Form("probability_%s",methodTitle.Data()) :
                             (htype == CompareType) ? 
                             Form("comparison_%s",methodTitle.Data()) :
                             Form("rarity_%s",methodTitle.Data()));

            c = new TCanvas( Form("canvas%d", countCanvas+1), ctitle, 
                             countCanvas*50+200, countCanvas*20, width, (Int_t)width*0.78 ); 
    
            // set the histogram style
            TMVAGlob::SetSignalAndBackgroundStyle( sig, bgd );
   
            // normalise both signal and background
            TMVAGlob::NormalizeHists( sig, bgd );
   
            // frame limits (choose judicuous x range)
            Float_t nrms = 4;
            cout << "--- Mean and RMS (S): " << sig->GetMean() << ", " << sig->GetRMS() << endl;
            cout << "--- Mean and RMS (B): " << bgd->GetMean() << ", " << bgd->GetRMS() << endl;
            Float_t xmin = TMath::Max( TMath::Min(sig->GetMean() - nrms*sig->GetRMS(), 
                                                  bgd->GetMean() - nrms*bgd->GetRMS() ),
                                       sig->GetXaxis()->GetXmin() );
            Float_t xmax = TMath::Min( TMath::Max(sig->GetMean() + nrms*sig->GetRMS(), 
                                                  bgd->GetMean() + nrms*bgd->GetRMS() ),
                                       sig->GetXaxis()->GetXmax() );
            Float_t ymin = 0;
            Float_t maxMult = (htype == CompareType) ? 1.3 : 1.2;
            Float_t ymax = TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*maxMult;
   
            // build a frame
            Int_t nb = 500;
            TString hFrameName(TString("frame") + methodTitle);
            TObject *o = gROOT->FindObject(hFrameName);
            if(o) delete o;
            TH2F* frame = new TH2F( hFrameName, sig->GetTitle(), 
                                    nb, xmin, xmax, nb, ymin, ymax );
            frame->GetXaxis()->SetTitle( methodTitle + ((htype == MVAType || htype == CompareType) ? " response" : "") );
            if      (htype == ProbaType  ) frame->GetXaxis()->SetTitle( "Signal probability" );
            else if (htype == RarityType ) frame->GetXaxis()->SetTitle( "Signal rarity" );
            frame->GetYaxis()->SetTitle("Normalized");
            TMVAGlob::SetFrameStyle( frame );
   
            // eventually: draw the frame
            frame->Draw();  
    
            c->GetPad(0)->SetLeftMargin( 0.105 );
            frame->GetYaxis()->SetTitleOffset( 1.2 );

            // Draw legend               
            TLegend *legend= new TLegend( c->GetLeftMargin(), 1 - c->GetTopMargin() - 0.12, 
                                          c->GetLeftMargin() + (htype == CompareType ? 0.40 : 0.3), 1 - c->GetTopMargin() );
            legend->SetFillStyle( 1 );
            legend->AddEntry(sig,TString("Signal")     + ((htype == CompareType) ? " (test sample)" : ""), "F");
            legend->AddEntry(bgd,TString("Background") + ((htype == CompareType) ? " (test sample)" : ""), "F");
            legend->SetBorderSize(1);
            legend->SetMargin( (htype == CompareType ? 0.2 : 0.3) );
            legend->Draw("same");

            // overlay signal and background histograms
            sig->Draw("samehist");
            bgd->Draw("samehist");
   
            if (htype == CompareType) {
               // if overtraining check, load additional histograms
               TH1* sigOv = 0;
               TH1* bgdOv = 0;

               TString ovname = hname += "_Train";
               sigOv = dynamic_cast<TH1*>(titDir->Get( ovname + "_S" ));
               bgdOv = dynamic_cast<TH1*>(titDir->Get( ovname + "_B" ));
      
               if (sigOv == 0 || bgdOv == 0) {
                  cout << "+++ Problem in \"mvas.C\": overtraining check histograms do not exist" << endl;
               }
               else {
                  cout << "--- Found comparison histograms for overtraining check" << endl;

                  TLegend *legend2= new TLegend( 1 - c->GetRightMargin() - 0.42, 1 - c->GetTopMargin() - 0.12,
                                                 1 - c->GetRightMargin(), 1 - c->GetTopMargin() );
                  legend2->SetFillStyle( 1 );
                  legend2->SetBorderSize(1);
                  legend2->AddEntry(sigOv,"Signal (training sample)","P");
                  legend2->AddEntry(bgdOv,"Background (training sample)","P");
                  legend2->SetMargin( 0.1 );
                  legend2->Draw("same");
               }
               Int_t col = sig->GetLineColor();
               sigOv->SetMarkerColor( col );
               sigOv->SetMarkerSize( 0.7 );
               sigOv->SetMarkerStyle( 20 );
               sigOv->SetLineWidth( 1 );
               sigOv->SetLineColor( col );
               sigOv->Draw("e1same");
      
               col = bgd->GetLineColor();
               bgdOv->SetMarkerColor( col );
               bgdOv->SetMarkerSize( 0.7 );
               bgdOv->SetMarkerStyle( 20 );
               bgdOv->SetLineWidth( 1 );
               bgdOv->SetLineColor( col );
               bgdOv->Draw("e1same");

               ymax = TMath::Max( ymax, TMath::Max( sigOv->GetMaximum(), bgdOv->GetMaximum() )*maxMult );
               frame->GetYaxis()->SetLimits( 0, ymax );
      
               // for better visibility, plot thinner lines
               sig->SetLineWidth( 1 );
               bgd->SetLineWidth( 1 );

               // perform K-S test
               cout << "--- Perform Kolmogorov-Smirnov tests" << endl;
               Double_t kolS = sig->KolmogorovTest( sigOv );
               Double_t kolB = bgd->KolmogorovTest( bgdOv );
               cout << "--- Goodness of signal (background) consistency: " << kolS << " (" << kolB << ")" << endl;

               TString probatext = Form( "Kolmogorov-Smirnov test: signal (background) probability = %5.3g (%5.3g)", kolS, kolB );
               TText* tt = new TText( 0.12, 0.74, probatext );
               tt->SetNDC(); tt->SetTextSize( 0.032 ); tt->AppendPad(); 
            }

            // redraw axes
            frame->Draw("sameaxis");

            // text for overflows
            Int_t    nbin = sig->GetNbinsX();
            Double_t dxu  = sig->GetBinWidth(0);
            Double_t dxo  = sig->GetBinWidth(nbin+1);
            TString uoflow = Form( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", 
                                   sig->GetBinContent(0)*dxu*100, bgd->GetBinContent(0)*dxu*100,
                                   sig->GetBinContent(nbin+1)*dxo*100, bgd->GetBinContent(nbin+1)*dxo*100 );
            TText* t = new TText( 0.975, 0.115, uoflow );
            t->SetNDC();
            t->SetTextSize( 0.030 );
            t->SetTextAngle( 90 );
            t->AppendPad();    
   
            // update canvas
            c->Update();

            // save canvas to file

            TMVAGlob::plot_logo(1.058);
            if (Save_Images) {
               if      (htype == MVAType)     TMVAGlob::imgconv( c, Form("plots/mva_%s",     methodTitle.Data()) );
               else if (htype == ProbaType)   TMVAGlob::imgconv( c, Form("plots/proba_%s",   methodTitle.Data()) ); 
               else if (htype == CompareType) TMVAGlob::imgconv( c, Form("plots/overtrain_%s", methodTitle.Data()) ); 
               else                           TMVAGlob::imgconv( c, Form("plots/rarity_%s",  methodTitle.Data()) ); 
            }
            countCanvas++;
         }
      }
   }
}
Example #14
0
void makeStack(TString myVar, TString myCut, TString myName, TString myAxisNameX, TString myAxisNameY, 
               vector<const Sample*>& listOfSignals, vector<const Sample*>& listOfSamples, vector<const Sample*> listOfDatasets, 
               TString inFileName,
               bool isBlind, bool isLog, bool drawSignal, bool drawLegend,
               int nBins, float xLow, float xHigh,
               float* xlowVec)
{
  // prepare the input file
  TFile* infile = new TFile(inFileName, "READ"); 
  infile -> cd();
  
  // prepare the stack
  THStack *hs = new THStack("hs","");
  // prepare the histos pointers
  TH1F*   hist[20];
  // prepare the tree pointers
  TTree*  tree[20];
  // prepare the legend
  TLegend* leg = new TLegend(.7485,.7225,.9597,.9604);
  leg->SetFillColor(0);
  // prepare the colors
  Int_t col[20] = {46,2,12,5,3,4,9,7,47,49,49,50,51,52,53,54,55,56,57,58};
  // prepare the cut
  if (isBlind) myCut += "*(phoMetDeltaPhi < 2.9)";        
  // prepare the Y axis lable
  if (xlowVec != 0) myAxisNameY = "Events/" + myAxisNameY;
  else {
    float binWidth = (xHigh-xLow)/nBins;
    TString tempString;
    tempString.Form("%.2f ",binWidth); 
    myAxisNameY = "Events/" + tempString + myAxisNameY;
  }
  // prepare the legend strings
  vector<TString> theLegends;
  
  // loop through the datasets and produce the plots
  TH1F* hdata;
  TH1F* hsignal;
  //prepare data and signal histos
  if (xlowVec != 0) hdata   = new TH1F("hdata","",nBins,xlowVec);
  else hdata = new TH1F("hdata","",nBins,xLow,xHigh);
  if (xlowVec != 0) hsignal = new TH1F("hsignal","",nBins,xlowVec);
  else hsignal = new TH1F("hsignal","",nBins,xLow,xHigh);

  TTree*  treedata[20];
  for (UInt_t iDatas=0; iDatas < listOfDatasets.size(); iDatas++) {
    //get the tree
    treedata[iDatas] = (TTree*) infile -> Get(listOfDatasets.at(iDatas)->Name()->Data());

    //fill the histogram
    if ( iDatas == 0 ) treedata[iDatas] -> Draw(myVar + " >> hdata","evt_weight*kf_weight*pu_weight" + myCut);
    else treedata[iDatas] -> Draw(myVar + " >>+ hdata","evt_weight*kf_weight*pu_weight" + myCut);
    
    if ( isBlind && iDatas == 0 ) leg -> AddEntry(hdata, "DATA (19.8 fb^{-1})", "pl");    
    
  }//end loop on datasets
  if (xlowVec != 0) {
    for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinError  (iBin,hdata->GetBinError(iBin)/hdata->GetBinWidth(iBin));
    for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinContent(iBin,hdata->GetBinContent(iBin)/hdata->GetBinWidth(iBin));
  }

  TTree*  treesignal[20];
  for (UInt_t iSignal=0; iSignal < listOfSignals.size(); iSignal++) {
    //get the tree
    treesignal[iSignal] = (TTree*) infile -> Get(listOfSignals.at(iSignal)->Name()->Data());

    //fill the histogram
    TString thisScale = Form("%f *", *(listOfSignals.at(iSignal)->Scale()));
    if ( iSignal == 0 ) treesignal[iSignal] -> Draw(myVar + " >> hsignal",thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    else treesignal[iSignal] -> Draw(myVar + " >>+ hsignal",thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    
    if ( drawSignal && iSignal == 0 ) leg -> AddEntry(hsignal, "Signal", "l");    
    
  }//end loop on signals
  if (xlowVec != 0) {
    for (int iBin = 1; iBin <= nBins; iBin++) hsignal->SetBinError  (iBin,hsignal->GetBinError(iBin)/hsignal->GetBinWidth(iBin));
    for (int iBin = 1; iBin <= nBins; iBin++) hsignal->SetBinContent(iBin,hsignal->GetBinContent(iBin)/hsignal->GetBinWidth(iBin));
  }
  hsignal -> SetLineColor(49);
  hsignal -> SetLineWidth(4.0);
       
  int theHistCounter = 0;
  // loop through the samples and produce the plots
  for (UInt_t iSample=0; iSample < listOfSamples.size(); iSample++) {

    //determine if the histo is first of the series
    bool isFirstOfSerie = (*listOfSamples.at(iSample)->Legend()).CompareTo(" ");
    bool isLastOfSerie = false;
    if (iSample == listOfSamples.size() - 1) isLastOfSerie = true;
    if (iSample < listOfSamples.size() - 1 && (*listOfSamples.at(iSample+1)->Legend()).CompareTo(" ") != 0) isLastOfSerie = true;
    
    //get the tree
    tree[iSample] = (TTree*) infile -> Get(listOfSamples.at(iSample)->Name()->Data());
    //if sample first of the list create a new histogram
    if (isFirstOfSerie) {
       TString thisHistName = "h_" + *(listOfSamples.at(iSample)->Name());
       //variable bin histo
       if (xlowVec != 0) hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xlowVec);
       //fixed bin histo
       else hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xLow,xHigh);
       hist[theHistCounter] -> Sumw2();
       hist[theHistCounter] -> SetFillColor(col[theHistCounter]);
       hist[theHistCounter] -> SetFillStyle(1001);
       theLegends.push_back(*listOfSamples.at(iSample)->Legend());
    }

    //fill the histogram
    TString thisScale = Form("%f *", *(listOfSamples.at(iSample)->Scale()));
    if (isFirstOfSerie) tree[iSample] -> Draw(myVar + " >> " + TString(hist[theHistCounter] -> GetName()),thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    else tree[iSample] -> Draw(myVar + " >>+ " + TString(hist[theHistCounter] -> GetName()),thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    
    //add the histogram to the stack if the last of the series:
    //either last sample or ~ sample followed by non ~ sample
    if (isLastOfSerie) {
       if (xlowVec != 0) {
         for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinError  (iBin,hist[theHistCounter]->GetBinError(iBin)/hist[theHistCounter]->GetBinWidth(iBin));
         for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinContent(iBin,hist[theHistCounter]->GetBinContent(iBin)/hist[theHistCounter]->GetBinWidth(iBin));
       }
       hs -> Add(hist[theHistCounter]);
       theHistCounter++;
    }
    
  }//end loop on samples

  //Fix the legend
  for (int iHisto = theHistCounter-1; iHisto >= 0; iHisto--) {
    leg -> AddEntry(hist[iHisto], theLegends[iHisto], "f");   
  }
  
  //get the maximum to properly set the frame
  float theMax = hdata -> GetBinContent(hdata -> GetMaximumBin()) + hdata -> GetBinError(hdata -> GetMaximumBin());
  TH1* theMCSum = (TH1*) hs->GetStack()->Last();
  float theMaxMC = theMCSum->GetBinContent(theMCSum->GetMaximumBin()) + theMCSum->GetBinError(theMCSum->GetMaximumBin());
  if (theMaxMC > theMax) theMax = theMaxMC;
  
  //prepare the ratio band and plot
  TH1* theMCRatioBand = makeRatioBand(theMCSum);
  TH1* theRatioPlot = makeRatioPlot(hdata,theMCSum);
    
  TCanvas* can = new TCanvas();
  can -> SetLogy(isLog);
  
  TPad *pad1 = new TPad("pad1","top pad",0,0.30,1,1);
  pad1->SetBottomMargin(0.02);
  pad1->SetLeftMargin(0.13);
  pad1->Draw();
  TPad *pad2 = new TPad("pad2","bottom pad",0,0.0,1,0.30);
  pad2->SetTopMargin(0.02);
  pad2->SetLeftMargin(0.13);
  pad2->SetBottomMargin(0.4);
  pad2->SetGridy();
  pad2->Draw();
  
  pad1->cd();
  hs->Draw("hist");
  hdata->Draw("same,pe");
  if (drawSignal) hsignal->Draw("same,hist");
  if (drawLegend) leg->Draw("same");
  //hs->GetXaxis()->SetTitle(myAxisNameX);
  hs->GetYaxis()->SetTitle(myAxisNameY);
  hs->GetXaxis()->SetLabelSize(0.04);
  hs->GetYaxis()->SetLabelSize(0.04);
  hs->GetXaxis()->SetLabelOffset(0.025);
  hs->GetYaxis()->SetLabelOffset(0.035);
  //hs->GetXaxis()->SetTitleOffset(1.1);
  hs->GetYaxis()->SetTitleOffset(1.1);
  hs->SetMaximum(theMax);
  if (isLog) hs->SetMinimum(0.01);
  
  pad2->cd();
  theMCRatioBand->GetXaxis()->SetTitle(myAxisNameX);
  theMCRatioBand->GetXaxis()->SetTitleSize(0.16);
  theMCRatioBand->GetXaxis()->SetTitleOffset(1.1);
  theMCRatioBand->GetXaxis()->SetLabelSize(0.12);
  theMCRatioBand->GetXaxis()->SetLabelOffset(0.07);
  theMCRatioBand->GetYaxis()->SetTitle("Data/MC");
  theMCRatioBand->GetYaxis()->SetTitleSize(0.10);
  theMCRatioBand->GetYaxis()->SetTitleOffset(0.6);
  theMCRatioBand->GetYaxis()->SetLabelSize(0.06);
  theMCRatioBand->GetYaxis()->SetLabelOffset(0.03);
  theMCRatioBand->SetFillStyle(3001);
  theMCRatioBand->SetFillColor(kBlue);
  theMCRatioBand->SetLineWidth(1);
  theMCRatioBand->SetLineColor(kBlack);
  theMCRatioBand->SetMarkerSize(0.1);
  theMCRatioBand->SetMaximum(4.);
  theMCRatioBand->SetMinimum(0.);
  theMCRatioBand->Draw("E2");
  TLine *line = new TLine(xLow,1,xHigh,1);
  line->SetLineColor(kBlack);
  line->Draw("same");
  theRatioPlot->Draw("same,pe");
  
  can->cd();
  can->Modified();
  can -> SaveAs(myName + ".pdf","pdf");
  
  //cleanup the memory allocation
  delete theMCSum;
  delete hs;
  delete leg;
  delete hdata;
  delete pad1;
  delete pad2;
  delete can;
  delete theMCRatioBand;
  delete theRatioPlot;
  infile -> Close();
  delete infile;
  
  return;
}
void EMCDistribution_ADC(bool log_scale = true)
{
  TString gain = "RAW";

  TText *t;
  TCanvas *c1 = new TCanvas(
      "EMCDistribution_ADC_" + gain + TString(log_scale ? "_Log" : "") + cuts,
      "EMCDistribution_ADC_" + gain + TString(log_scale ? "_Log" : "") + cuts,
      1800, 1000);
  c1->Divide(8, 8, 0., 0.01);
  int idx = 1;
  TPad *p;

  for (int iphi = 8 - 1; iphi >= 0; iphi--)
  {
    for (int ieta = 0; ieta < 8; ieta++)
    {
      p = (TPad *) c1->cd(idx++);
      c1->Update();

      if (log_scale)
      {
        p->SetLogz();
      }
      p->SetGridx(0);
      p->SetGridy(0);

      TString hname = Form("hEnergy_ieta%d_iphi%d", ieta, iphi) + TString(log_scale ? "_Log" : "");

      TH1 *h = NULL;

      if (log_scale)
        h = new TH2F(hname,
                     Form(";Calibrated Tower Energy Sum (GeV);Count / bin"), 24, -.5,
                     23.5,
                     //                128+64, 0, 3096);
                     4098, -1, 4097);
      //          else
      //            h = new TH2F(hname,
      //                Form(";Calibrated Tower Energy Sum (GeV);Count / bin"), 100,
      //                -.050, .5,128,0,2048);

      h->SetLineWidth(0);
      h->SetLineColor(kBlue + 3);
      h->SetFillColor(kBlue + 3);
      h->GetXaxis()->SetTitleSize(.09);
      h->GetXaxis()->SetLabelSize(.08);
      h->GetYaxis()->SetLabelSize(.08);
      h->GetYaxis()->SetRangeUser(0, 4096);

      //          if (log_scale)
      //            QAHistManagerDef::useLogBins(h->GetYaxis());

      TString sdraw = "TOWER_" + gain + "_CEMC[].signal_samples[]:fmod(Iteration$,24)>>" + hname;
      TString scut =
          Form(
              "TOWER_%s_CEMC[].get_bineta()==%d && TOWER_%s_CEMC[].get_binphi()==%d",
              gain.Data(), ieta, gain.Data(), iphi);

      cout << "T->Draw(\"" << sdraw << "\",\"" << scut << "\");" << endl;

      T->Draw(sdraw, scut, "colz");

      TText *t = new TText(.9, .9, Form("Col%d Row%d", ieta, iphi));
      t->SetTextAlign(33);
      t->SetTextSize(.15);
      t->SetNDC();
      t->Draw();

      //          return;
    }
  }

  SaveCanvas(c1,
             TString(_file0->GetName()) + TString("_DrawPrototype3EMCalTower_") + TString(c1->GetName()), false);
}
void makePlot(TCanvas* canvas, const std::string& outputFileName, TTree* testTree, const std::string& varName, 
	      unsigned numBinsX, double xMin, double xMax)
{
  std::cout << "creating histogramTauIdPassed..." << std::endl;
  TString histogramTauIdPassedName = TString("histogramTauIdPassed").Append("_").Append(varName.data());
  TH1* histogramTauIdPassed = fillHistogram(testTree, varName, "type==1", "",
					    histogramTauIdPassedName.Data(), numBinsX, xMin, xMax);
  std::cout << "--> histogramTauIdPassed = " << histogramTauIdPassed << ":" 
	    << " integral = " << histogramTauIdPassed->Integral() << std::endl;

  std::cout << "creating histogramTauIdFailed..." << std::endl;
  TString histogramTauIdFailedName = TString("histogramTauIdFailed").Append("_").Append(varName.data());
  TH1* histogramTauIdFailed = fillHistogram(testTree, varName, "type==0", "",
					    histogramTauIdFailedName.Data(), numBinsX, xMin, xMax);
  std::cout << "--> histogramTauIdFailed = " << histogramTauIdFailed 
	    << " integral = " << histogramTauIdFailed->Integral() << std::endl;

  std::cout << "creating histogramTauIdDenominator..." << std::endl;
  TString histogramTauIdDenominatorName = TString("histogramTauIdDenominator").Append("_").Append(varName.data());
  TH1* histogramTauIdDenominator = new TH1F(histogramTauIdDenominatorName.Data(), 
					    histogramTauIdDenominatorName.Data(), numBinsX, xMin, xMax);
  histogramTauIdDenominator->Add(histogramTauIdPassed);
  histogramTauIdDenominator->Add(histogramTauIdFailed);
  std::cout << "--> histogramTauIdDenominator = " << histogramTauIdDenominator 
	    << " integral = " << histogramTauIdDenominator->Integral() << std::endl;

  std::cout << "creating histogramFakeRate..." << std::endl;
  TString histogramFakeRateName = TString("histogramFakeRate").Append("_").Append(varName.data());
  TH1* histogramFakeRate = new TH1F(histogramFakeRateName.Data(), 
				    histogramFakeRateName.Data(), numBinsX, xMin, xMax);
  histogramFakeRate->Add(histogramTauIdPassed);
  histogramFakeRate->Divide(histogramTauIdDenominator);
  std::cout << "--> histogramFakeRate = " << histogramFakeRate 
	    << " integral = " << histogramFakeRate->Integral() << std::endl;

  std::cout << "creating histogramFakeRateWeighted..." << std::endl;
  TString histogramFakeRateWeightedName = TString("histogramFakeRateWeighted").Append("_").Append(varName.data());
  TH1* histogramFakeRateWeighted = fillHistogram(testTree, varName, "", "MVA_KNN", 
						 histogramFakeRateWeightedName.Data(), numBinsX, xMin, xMax);
  histogramFakeRateWeighted->Divide(histogramTauIdDenominator);
  std::cout << "--> histogramFakeRateWeighted = " << histogramFakeRateWeighted 
	    << " entries = " << histogramFakeRateWeighted->GetEntries() << ","
	    << " integral = " << histogramFakeRateWeighted->Integral() << std::endl;
  // Scale the weighted fake rate histogram

  histogramFakeRate->SetTitle(varName.data());
  histogramFakeRate->SetStats(false);
  histogramFakeRate->SetMinimum(1.e-4);
  histogramFakeRate->SetMaximum(1.e+1);
  histogramFakeRate->SetLineColor(2);
  histogramFakeRate->SetLineWidth(2);
  histogramFakeRate->SetMarkerStyle(20);
  histogramFakeRate->SetMarkerColor(2);
  histogramFakeRate->SetMarkerSize(1);
  histogramFakeRate->Draw("e1p");

  histogramFakeRateWeighted->SetLineColor(4);
  histogramFakeRateWeighted->SetLineWidth(2);
  histogramFakeRateWeighted->SetMarkerStyle(24);
  histogramFakeRateWeighted->SetMarkerColor(4);
  histogramFakeRateWeighted->SetMarkerSize(1);
  histogramFakeRateWeighted->Draw("e1psame");

  TLegend legend(0.11, 0.73, 0.31, 0.89);
  legend.SetBorderSize(0);
  legend.SetFillColor(0);
  legend.AddEntry(histogramFakeRate, "Tau id. discr.", "p");
  legend.AddEntry(histogramFakeRateWeighted, "Fake-Rate weight", "p");
  legend.Draw();

  canvas->Update();
  canvas->Print(outputFileName.data());
}
void EMCDistribution_SUM_RawADC(TString sTOWER = "Energy_Sum_col1_row2_5x5",
                                TString CherenkovSignal = "C2_Inner")
{
  TH1 *EnergySum_LG_full = new TH1F("EnergySum_LG_full",
                                    ";Tower Energy Sum (ADC);Count / bin", 260, -100, 2500);
  TH1 *EnergySum_LG = new TH1F("EnergySum_LG",
                               ";Tower Energy Sum (ADC);Count / bin", 260, -100, 2500);
  //  TH1 * EnergySum_HG = new TH1F("EnergySum_HG",
  //      ";Low range Tower Energy Sum (ADC);Count / bin", 50, 0, 500);

  TH1 *C2_Inner_full = new TH1F("C2_Inner_full",
                                CherenkovSignal + ";Cherenkov Signal (ADC);Count / bin", 1000, 0, 2000);
  TH1 *C2_Inner = new TH1F("C2_Inner",
                           CherenkovSignal + ";Cherenkov Inner Signal (ADC);Count / bin", 1000, 0, 2000);

  EnergySum_LG_full->SetLineColor(kBlue + 3);
  EnergySum_LG_full->SetLineWidth(2);

  EnergySum_LG->SetLineColor(kGreen + 3);
  EnergySum_LG->SetLineWidth(3);
  EnergySum_LG->SetMarkerColor(kGreen + 3);

  C2_Inner_full->SetLineColor(kBlue + 3);
  C2_Inner_full->SetLineWidth(2);

  C2_Inner->SetLineColor(kGreen + 3);
  C2_Inner->SetLineWidth(3);
  C2_Inner->SetMarkerColor(kGreen + 3);

  TCut c2 = CherenkovSignal + ">240";

  T->Draw(sTOWER + ">>EnergySum_LG_full", "", "goff");
  T->Draw(sTOWER + ">>EnergySum_LG", c2, "goff");
  T->Draw(CherenkovSignal + ">>C2_Inner_full", "", "goff");
  T->Draw(CherenkovSignal + ">>C2_Inner", c2, "goff");

  TText *t;
  TCanvas *c1 = new TCanvas(
      "EMCDistribution_SUM_RawADC_" + sTOWER + "_" + CherenkovSignal + cuts,
      "EMCDistribution_SUM_RawADC_" + sTOWER + "_" + CherenkovSignal + cuts, 1800,
      600);
  c1->Divide(3, 1);
  int idx = 1;
  TPad *p;

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  p->SetLogy();
  p->SetGridx(0);
  p->SetGridy(0);

  C2_Inner_full->DrawClone();
  C2_Inner->DrawClone("same");

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  p->SetLogy();
  p->SetGridx(0);
  p->SetGridy(0);

  TH1 *h = (TH1 *) EnergySum_LG_full->DrawClone();
  //  h->GetXaxis()->SetRangeUser(0, h->GetMean() + 5 * h->GetRMS());
  (TH1 *) EnergySum_LG->DrawClone("same");

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  //  p->SetLogy();
  p->SetGridx(0);
  p->SetGridy(0);

  TH1 *h_full = (TH1 *) EnergySum_LG_full->DrawClone();
  TH1 *h = (TH1 *) EnergySum_LG->DrawClone("same");

  TF1 *fgaus_g = new TF1("fgaus_LG_g", "gaus", h->GetMean() - 1 * h->GetRMS(),
                         h->GetMean() + 4 * h->GetRMS());
  fgaus_g->SetParameters(1, h->GetMean() - 2 * h->GetRMS(),
                         h->GetMean() + 2 * h->GetRMS());
  h->Fit(fgaus_g, "MR0N");

  TF1 *fgaus = new TF1("fgaus_LG", "gaus",
                       fgaus_g->GetParameter(1) - 1 * fgaus_g->GetParameter(2),
                       fgaus_g->GetParameter(1) + 4 * fgaus_g->GetParameter(2));
  fgaus->SetParameters(fgaus_g->GetParameter(0), fgaus_g->GetParameter(1),
                       fgaus_g->GetParameter(2));
  h->Fit(fgaus, "MR");

  h->Sumw2();
  h_full->Sumw2();
  h_full->GetXaxis()->SetRangeUser(h->GetMean() - 4 * h->GetRMS(),
                                   h->GetMean() + 4 * h->GetRMS());

  h->SetLineWidth(2);
  h->SetMarkerStyle(kFullCircle);

  h_full->SetTitle(
      Form("#DeltaE/<E> = %.1f%%",
           100 * fgaus->GetParameter(2) / fgaus->GetParameter(1)));

  //  p = (TPad *) c1->cd(idx++);
  //  c1->Update();
  //  p->SetLogy();
  //  p->SetGridx(0);
  //  p->SetGridy(0);
  //
  //  TH1 * h = (TH1 *) EnergySum_LG->DrawClone();
  //  h->GetXaxis()->SetRangeUser(0,500);
  //  h->SetLineWidth(2);
  //  h->SetLineColor(kBlue + 3);
  ////  h->Sumw2();
  //  h->GetXaxis()->SetRangeUser(0, h->GetMean() + 5 * h->GetRMS());
  //
  //  p = (TPad *) c1->cd(idx++);
  //  c1->Update();
  ////  p->SetLogy();
  //  p->SetGridx(0);
  //  p->SetGridy(0);
  //
  //  TH1 * h = (TH1 *) EnergySum_LG->DrawClone();
  //  h->GetXaxis()->SetRangeUser(0,500);
  //
  //  TF1 * fgaus = new TF1("fgaus_HG", "gaus", 0, 100);
  //  fgaus->SetParameters(1, h->GetMean() - 2 * h->GetRMS(),
  //      h->GetMean() + 2 * h->GetRMS());
  //  h->Fit(fgaus, "M");
  //
  //  h->Sumw2();
  //  h->GetXaxis()->SetRangeUser(h->GetMean() - 4 * h->GetRMS(),
  //      h->GetMean() + 4 * h->GetRMS());
  //
  //  h->SetLineWidth(2);
  //  h->SetMarkerStyle(kFullCircle);
  //
  //  h->SetTitle(
  //      Form("#DeltaE/<E> = %.1f%%",
  //          100 * fgaus->GetParameter(2) / fgaus->GetParameter(1)));

  SaveCanvas(c1,
             TString(_file0->GetName()) + TString("_DrawPrototype3EMCalTower_") + TString(c1->GetName()), false);
}
Example #18
0
histoBook* histoBook::set( string opt, vector<string> params ){

	//cout  << "Setting : " << opt << endl;
	//for ( int i = 0; i < params.size(); i++ ){
	//	cout << params[ i ] << " ";
	//}
	//cout << endl;
	// force the param name to lowercase
	transform(opt.begin(), opt.end(), opt.begin(), ::tolower);

    TH1* h = get( styling );
    if ( h ){

	    if ( "title" == opt ){
	    	h->SetTitle( cParam(params, 0) );
	    } else if ( "x" == opt ){
	    	h->GetXaxis()->SetTitle( cParam(params, 0) );
	    } else if ( "y" == opt ){
	    	h->GetYaxis()->SetTitle( cParam(params, 0) );
	    } else if ( "legend" == opt ){
	    	legend->AddEntry( h, cParam(params, 0), cParam(params, 1, "lpf") );
			legend->Draw();
	    } else if ( "draw" == opt ){
	    	drawOption = cParam(params, 0);
	    } else if ( "linecolor" == opt ){
	    	int c = color( cParam( params, 0) );
	    	if ( c  < 0 )
	    		c = (int) dParam( params, 0);
	    	h->SetLineColor( c );
	    } else if ( "fillcolor" == opt ){
	    	int c = color( cParam( params, 0) );
	    	if ( c  < 0 )
	    		c = (int) dParam( params, 0);
	    	h->SetFillColor( c );
	    } else if ( "linewidth" == opt ){
	    	h->SetLineWidth( dParam( params, 0) );
	    } else if ( "domain" == opt ){
	    	double min = dParam( params, 0);
	    	double max = dParam( params, 1);
		    h->GetXaxis()->SetRangeUser( min, max );
	    } else if ( "dynamicdomain" == opt ){
	    	double thresh = dParam( params, 0);
	    	int min = (int)dParam( params, 1);
	    	int max = (int)dParam( params, 2);
	    	int axis = (int)dParam( params, 3);		// 1 = x, 2 = y

	    	if ( 1 != axis && 2 != axis )
	    		axis = 1;
	    	
	    	if ( thresh >= 0) {
	    		if ( -1 >= min )
	    			min = h->FindFirstBinAbove( thresh, axis );
	    		if ( -1 >= max )
	    			max = h->FindLastBinAbove( thresh, axis );
	    	}
	    	
	    	if ( 1 == axis )
		  	  h->GetXaxis()->SetRange( min, max );
		  	else if ( 2 == axis )
		  		h->GetYaxis()->SetRange( min, max );

	    }  else if ( "range" == opt ){

	    	double min = dParam( params, 0);
	    	double max = dParam( params, 1);
	    	
	    	h->GetYaxis()->SetRangeUser( min, max );
	    } else if ( "markercolor" == opt ) {
	    	int c = color( cParam( params, 0) );
	    	if ( c  < 0 )
	    		c = (int) dParam( params, 0);
	    	h->SetMarkerColor( c );
	    } else if ( "markerstyle" == opt ) {
	    	h->SetMarkerStyle( (int)dParam( params, 0) );
	    } else if ( "legend" == opt ){
	    	// p1 - alignmentX
	    	// p2 - alignmentY
	    	// p3 - width
	    	// p4 - height

	    	// make sure option is valid
	    	double p1 = dParam( params, 0);
	    	double p2 = dParam( params, 1);
	    	if ( !(legendAlignment::center == p1 || legendAlignment::left == p1 || legendAlignment::right == p1) )
	    		p1 = legendAlignment::best;
	    	if ( !(legendAlignment::center == p2 || legendAlignment::top == p2 || legendAlignment::bottom == p2) )
	    		p2 = legendAlignment::best;
	    	placeLegend( p1, p2, dParam( params, 3), dParam( params, 3) );
	    } else if ( "numberofticks" == opt ){
	    	// p1 - # of primary divisions
	    	// p2 - # of secondary divisions
	    	// p3 - axis : 0 or 1 = x, 2 = y
	    	double p1 = dParam( params, 0);
	    	double p2 = dParam( params, 1);
	    	double p3 = dParam( params, 2);

	    	if ( p2 == -1 )
	    		p2 = 0;

		    if ( 2 == (int)p3 )
		    	h->GetYaxis()->SetNdivisions( (int) p1, (int) p2, 0, true );
		    else 
		    	h->GetXaxis()->SetNdivisions( (int) p1, (int) p2, 0, true );
	    } else if ( "logy" == opt ){
	    	gPad->SetLogy( (int)dParam( params, 0 ) );
	    } else if ( "logx" == opt ){
	    	gPad->SetLogx( (int)dParam( params, 0 ) );
	    } else if ( "logz" == opt ){
	    	gPad->SetLogz( (int)dParam( params, 0 ) );
	    }




	}

	return this;



}
void EMCDistribution_PeakSample_Fast(bool full_gain = false)
{
  const TString gain = "RAW";

  TString hname = "EMCDistribution_" + gain + TString(full_gain ? "_FullGain" : "") + cuts;

  TH2 *h2 = NULL;
  {
    if (full_gain)
    {
      h2 = new TH2F(hname,
                    Form(";Calibrated Tower Energy Sum (ADC);Count / bin"), 100,
                    .05 * 100, 25 * 100, 64, -.5, 63.5);
      QAHistManagerDef::useLogBins(h2->GetXaxis());
    }
    else
    {
      h2 = new TH2F(hname,
                    Form(";Calibrated Tower Energy Sum (ADC);Count / bin"), 260,
                    -.2 * 100, 5 * 100, 64, -.5, 63.5);
    }
    T->Draw(
        "TOWER_" + gain + "_CEMC[].get_bineta() + 8* TOWER_" + gain + "_CEMC[].get_binphi():(TOWER_RAW_CEMC[].signal_samples[10] - TOWER_RAW_CEMC[].signal_samples[0])*(-1)>>" + hname, "", "goff");
  }

  TText *t;
  TCanvas *c1 = new TCanvas(
      "EMCDistribution_PeakSample_Fast_" + TString(full_gain ? "_FullGain" : "") + cuts,
      "EMCDistribution_PeakSample_Fast_" + TString(full_gain ? "_FullGain" : "") + cuts, 1800, 950);
  c1->Divide(8, 8, 0., 0.01);
  int idx = 1;
  TPad *p;

  for (int iphi = 8 - 1; iphi >= 0; iphi--)
  {
    for (int ieta = 0; ieta < 8; ieta++)
    {
      p = (TPad *) c1->cd(idx++);
      c1->Update();

      p->SetLogy();
      if (full_gain)
      {
        p->SetLogx();
      }
      p->SetGridx(0);
      p->SetGridy(0);

      TString hname = Form("hEnergy_ieta%d_iphi%d", ieta, iphi) + TString(full_gain ? "_FullGain" : "");

      TH1 *h = h2->ProjectionX(hname, ieta + 8 * iphi + 1,
                               ieta + 8 * iphi + 1);  // axis bin number is encoded as ieta+8*iphi+1

      h->SetLineWidth(0);
      h->SetLineColor(kBlue + 3);
      h->SetFillColor(kBlue + 3);

      h->GetXaxis()->SetTitleSize(.09);
      h->GetXaxis()->SetLabelSize(.08);
      h->GetYaxis()->SetLabelSize(.08);

      h->Draw();

      if (full_gain)
        h->Fit("x*gaus", "M");
      else
        h->Fit("landau", "M");

      double peak = -1;

      TF1 *fit = ((TF1 *) (h->GetListOfFunctions()->At(0)));
      if (fit)
      {
        fit->SetLineColor(kRed);
        peak = fit->GetParameter(1);
      }

      cout << Form("Finished <Col%d Row%d> = %.1f", ieta, iphi, peak)
           << endl;

      TText *t = new TText(.9, .9,
                           Form("<Col%d Row%d> = %.1f", ieta, iphi, peak));
      t->SetTextAlign(33);
      t->SetTextSize(.15);
      t->SetNDC();
      t->Draw();
    }
  }

  SaveCanvas(c1,
             TString(_file0->GetName()) + TString("_DrawPrototype3EMCalTower_") + TString(c1->GetName()), false);
}
Example #20
0
//void makeHist(const int sample, const int dataset=1)
void makeHist(const string title="")
{
	vector<Hist> hist2print;
	TPaveText *tx = new TPaveText(.05,.1,.95,.8);
//	tx->AddText("Using Deafult JERs for all jets");
//	tx->AddText("Using b-Jet JERs");

/*	string title("QCD MG:");

	//if (sample==1) title += "NJet(70/50/30>=2/4/5), #slash{E}_{T}>175, Triplet>1, 80<TopMass<270, TOP+0.5*BJET>500, MT2>300, #Delta#Phi(.5,.5,.3), BJets>=1";
	if (sample==1)      title += "All Stop cuts applied (use default JERs for all jets)";
	else if (sample==2) title += "All Stop cuts applied + Inverted #Delta#Phi (use default JERs for all jets)";
	else if (sample==3) title += "All Stop cuts applied (use b-Jet JERs)";
	else if (sample==4) title += "All Stop cuts applied + Inverted #Delta#Phi (use b-Jet JERs)";
	else if (sample==5) title += "No cuts applied";
*/
	unsigned bitMaskArray[] = {0,1,2,3,129,130,131,195,257,258,269,323};
	vector<unsigned> vBitMaskArray(bitMaskArray, bitMaskArray + sizeof(bitMaskArray) / sizeof(unsigned));



	stringstream unclmet_title;
	unclmet_title << title << "Unclutered MET";
	hist2print.push_back(Hist("met",title,2,0.0, 400.0,1));
	hist2print.push_back(Hist("unclmet",unclmet_title.str().c_str(),2,0.0, 100.0,1));
	hist2print.push_back(Hist("mht",title,2,0.0, 400.0,1));
	hist2print.push_back(Hist("ht",title,2,0,2000,1));
	hist2print.push_back(Hist("njet30eta5p0",title,1,0,15,1));
	hist2print.push_back(Hist("nbjets",title,1,0,10,1));
//	hist2print.push_back(Hist("bjetPt",title,2));
	hist2print.push_back(Hist("M123",title,2));
//	hist2print.push_back(Hist("M23overM123",title));
	hist2print.push_back(Hist("MT2",title,2));
	hist2print.push_back(Hist("MTb",title,4));
	hist2print.push_back(Hist("MTt",title,4));
	hist2print.push_back(Hist("MTb_p_MTt",title,2,400,1000,1));
	//hist2print.push_back(Hist("jet1_pt",title,2));
	//hist2print.push_back("bjetPt");
//	hist2print.push_back(Hist("bjetMass",title,2,0,200));
//	hist2print.push_back(Hist("dphimin",title,4));


	TFile *outRootFile = new TFile("Merged.root");

	/*TPad *c1=0, *c2=0;
	TCanvas *c = GetCanvas(c1, c2);
	if (c ==NULL|| c1 == 0 ||c2 == 0)
	{
		cout << " A drawing pad is null !"<< endl;
		cout << "c = " << c << endl;
		cout << "c1 = " << c1 << endl;
		cout << "c2 = " << c2 << endl;
		assert(false);
	}*/
   TCanvas *c = new TCanvas("c1");
   c->Range(0,0,1,1);
   c->SetBorderSize(2);
   c->SetFrameFillColor(0);
  
// ------------>Primitives in pad: c1_1
   TPad *c1_1 = new TPad("c1_1", "c1_1",0.01,0.30,0.99,0.99);
   c1_1->Draw();
   c1_1->cd();
   c1_1->SetBorderSize(2);
   c1_1->SetTickx(1);
   c1_1->SetTicky(1);
   c1_1->SetTopMargin(0.1);
   c1_1->SetBottomMargin(0.0);
   //c1_1->SetFrameFillColor(3);
	//c1_1->SetLogy();
  
  c->cd();
// ------------>Primitives in pad: c1_2
   TPad *c1_2 = new TPad("c1_2", "c1_2",0.01,0.01,0.99,0.30);
   c1_2->Draw();
   c1_2->cd();
   c1_2->SetBorderSize(2);
   c1_2->SetTickx(1);
   c1_2->SetTicky(1);
   c1_2->SetTopMargin(0.0);
   c1_2->SetBottomMargin(0.24);
   c1_2->SetFrameFillColor(0);
	c1_2->SetGridx();
	c1_2->SetGridy();
	c->cd();
	gStyle->SetOptStat(0);
	gPad->Print("samples.eps[");

	for (unsigned i=0;i<vBitMaskArray.size(); ++i)
	{
		unsigned mask = vBitMaskArray.at(i);
		for (unsigned ihist=0; ihist < hist2print.size(); ++ihist)
		{
			stringstream path, reco_hist_name, gen_hist_name, smear_hist_name;
			stringstream reco_hist, gen_hist, smear_hist;
			stringstream folder;
			folder << "Hist/Mask"<< mask << "HT0to8000MHT0to8000/";
			//cout << "folder = " << folder.str() << endl;

			/*	if ((hist2print.at(ihist).Name()).find("Jet"))
				{
				reco_hist_name << folder.str() << "reco" << hist2print.at(ihist).Name() << "_copy";
				reco_hist << folder.str() << "reco" << hist2print.at(ihist).Name();
				smear_hist_name << folder.str() << "smeared" << hist2print.at(ihist).Name() << "_copy";
				smear_hist << folder.str() << "smeared" << hist2print.at(ihist).Name();
				gen_hist_name << folder.str() << "gen" << hist2print.at(ihist).Name() << "_copy";
				gen_hist << folder.str() << "gen" << hist2print.at(ihist).Name();
				} else
				*/	{
					reco_hist_name << folder.str() << "reco_" << hist2print.at(ihist).Name() << "_copy";
					reco_hist << folder.str() << "reco_" << hist2print.at(ihist).Name();
					smear_hist_name << folder.str() << "smeared_" << hist2print.at(ihist).Name() << "_copy";
					smear_hist << folder.str() << "smeared_" << hist2print.at(ihist).Name();
					gen_hist_name << folder.str() << "gen_" << hist2print.at(ihist).Name() << "_copy";
					gen_hist << folder.str() << "gen_" << hist2print.at(ihist).Name();
				}

				TH1* hreco = (TH1*) (outRootFile->Get(reco_hist.str().c_str()));
				if (hreco == NULL) { cout << "hreco = " << reco_hist.str() << " was not found!" << endl; assert(false); } 
				hreco->SetDirectory(0);
				TH1* hsmear = (TH1*) (outRootFile->Get(smear_hist.str().c_str()));
				if (hsmear == NULL) { cout << "hsmear = " << smear_hist.str() << " was not found!" << endl; assert(false); } 
				hsmear->SetDirectory(0);
				TH1* hgen = (TH1*) (outRootFile->Get(gen_hist.str().c_str()));
				//->Clone(gen_hist_name.str().c_str()));
				if (hgen == NULL) { cout << "hgen = " << gen_hist.str() << " was not found!" << endl; assert(false); } 
				hgen->SetDirectory(0);

				hreco->Sumw2();
				hsmear->Sumw2();
				hgen->Sumw2();

				const int rebin = hist2print.at(ihist).Rebin();
				const string title = hist2print.at(ihist).Title();
				const double xmin = hist2print.at(ihist).Xmin();
				const double xmax = hist2print.at(ihist).Xmax();

				if (rebin>1)
				{
					hreco->Rebin(rebin);
					hsmear->Rebin(rebin);
					hgen->Rebin(rebin);
				}
				if (title.length()>0)
				{
					hreco->SetTitle(title.c_str());
					hsmear->SetTitle(title.c_str());
					hgen->SetTitle(title.c_str());
				}
				if (xmin != LargeNegNum || xmax != LargeNegNum)
				{
					hreco->GetXaxis()->SetRangeUser(xmin,xmax);
					hsmear->GetXaxis()->SetRangeUser(xmin,xmax);
					hgen->GetXaxis()->SetRangeUser(xmin,xmax);
				}

				const double reco_max_y  = hreco->GetBinContent(hreco->GetMaximumBin());
				const double smear_max_y = hsmear->GetBinContent(hsmear->GetMaximumBin());
				const double y_max = max(reco_max_y, smear_max_y);
				double y_min = 9999.0;
				for (unsigned bin=1; bin<hreco->GetNbinsX(); ++bin)
				{
					const double v1 = hreco->GetBinContent(bin);
					const double v2 = hsmear->GetBinContent(bin);
					const double minv = min(v1,v2);
					if (minv != 0 && minv < y_min) y_min = minv;
					
				}

				cout << hreco->GetName() << "->ymin/max = " << y_min << "(" << y_min/2.0 << ")/" << y_max << "(" << y_max*2.0 << ")" << endl;
				hreco->GetYaxis()->SetRangeUser(y_min/2.0, y_max*2.0);
				hsmear->GetYaxis()->SetRangeUser(y_min/2.0, y_max*2.0);


				hgen->SetLineColor(kBlue);
				hgen->SetMarkerColor(kBlue);
				hgen->SetMarkerStyle(24);
				hgen->SetLineWidth(2);
				hsmear->SetLineColor(kRed);
				hsmear->SetMarkerColor(kRed);
				hsmear->SetMarkerStyle(24);
				hsmear->SetLineWidth(2);
				hreco->SetLineWidth(2);
				hreco->SetMarkerStyle(kDot);
				hreco->SetLineColor(kBlack);
				hreco->SetMarkerColor(kBlack);
				//hreco->GetXaxis()->SetRangeUser(0,300);
				//hsmear->GetXaxis()->SetRangeUser(0,300);


				hreco->GetYaxis()->CenterTitle(1);
				hreco->SetLabelFont(42,"XYZ");
				hreco->SetTitleFont(42,"XYZ");
				hreco->GetYaxis()->SetTitleOffset(0.8);
				hreco->SetLabelSize(0.05,"XYZ");
				hreco->SetTitleSize(0.06,"XYZ");


				TH1 *hsmeartoreco_ratio = (TH1*) (hsmear->Clone("hsmear_copy"));
				hsmeartoreco_ratio->Divide(hreco);
				hsmeartoreco_ratio->SetTitle("");
				hsmeartoreco_ratio->GetYaxis()->SetTitle("Smear/Reco");
				hsmeartoreco_ratio->GetYaxis()->SetRangeUser(0,2.);

				hsmeartoreco_ratio->GetYaxis()->SetTitleOffset(0.4);
				hsmeartoreco_ratio->GetXaxis()->SetTitleOffset(0.9);
				hsmeartoreco_ratio->GetYaxis()->CenterTitle(1);
				hsmeartoreco_ratio->GetXaxis()->CenterTitle(1);
				hsmeartoreco_ratio->SetLabelSize(0.125,"XYZ");
				hsmeartoreco_ratio->SetTitleSize(0.125,"XYZ");
				//	hsmeartoreco_ratio->SetLabelFont(labelfont,"XYZ");
				//	hsmeartoreco_ratio->SetTitleFont(titlefont,"XYZ");
				hsmeartoreco_ratio->GetXaxis()->SetTickLength(0.07);



				stringstream recoleg,smearleg, genleg;
				const double sum_reco  = hreco->Integral(1, hreco->GetNbinsX()+1);
				const double sum_smear = hsmear->Integral(1, hsmear->GetNbinsX()+1);
				const double sum_gen   = hgen->Integral(1, hgen->GetNbinsX()+1);
				const double err_reco  = StatErr(hreco);
				const double err_smear = StatErr(hsmear);


				cout << setprecision(1) << fixed;

				recoleg << "Reco (" << sum_reco << "#pm" << err_reco << ")";
				smearleg << "Smear (" << sum_smear << "#pm" << err_smear << ")";
				genleg << "Gen (" << sum_gen << ")";
				cout <<  smear_hist_name.str() << "::reco/smear = " << sum_reco << "/" << sum_smear << endl;

				TLegend *l2 = new TLegend(0.6,0.6,0.9,0.9);
				l2->AddEntry(hreco, recoleg.str().c_str());
				//l2->AddEntry(hgen, genleg.str().c_str());
				l2->AddEntry(hsmear, smearleg.str().c_str());

				c1_1->cd();
				gPad->SetLogy(hist2print.at(ihist).LogY());

				hreco->DrawCopy();
				//hgen->DrawCopy("same");
				hsmear->DrawCopy("same");
				l2->Draw();
				//tx->Draw();
				c1_2->cd();
				hsmeartoreco_ratio->DrawCopy();
				c->cd();
				gPad->Print("samples.eps");

		}
	}

	gPad->Print("samples.eps]");
}
void EMCDistribution(TString gain = "CALIB", bool log_scale = false)
{
  TText *t;
  TCanvas *c1 = new TCanvas(
      "EMCDistribution_" + gain + TString(log_scale ? "_Log" : "") + cuts,
      "EMCDistribution_" + gain + TString(log_scale ? "_Log" : "") + cuts, 1800,
      1000);
  c1->Divide(8, 8, 0., 0.01);
  int idx = 1;
  TPad *p;

  for (int iphi = 8 - 1; iphi >= 0; iphi--)
  {
    for (int ieta = 0; ieta < 8; ieta++)
    {
      p = (TPad *) c1->cd(idx++);
      c1->Update();

      p->SetLogy();
      p->SetGridx(0);
      p->SetGridy(0);

      TString hname = Form("hEnergy_ieta%d_iphi%d", ieta, iphi) + TString(log_scale ? "_Log" : "");

      TH1 *h = NULL;

      if (log_scale)
        h = new TH1F(hname,
                     Form(";Calibrated Tower Energy Sum (GeV);Count / bin"), 300,
                     5e-3, 3096);
      else
        //            h = new TH1F(hname,
        //                Form(";Calibrated Tower Energy Sum (GeV);Count / bin"), 196,
        //                1900, 2096);
        h = new TH1F(hname,
                     Form(";Calibrated Tower Energy Sum (GeV);Count / bin"), 596,
                     -96, 500);

      h->SetLineWidth(0);
      h->SetLineColor(kBlue + 3);
      h->SetFillColor(kBlue + 3);
      h->GetXaxis()->SetTitleSize(.09);
      h->GetXaxis()->SetLabelSize(.08);
      h->GetYaxis()->SetLabelSize(.08);

      if (log_scale)
        QAHistManagerDef::useLogBins(h->GetXaxis());

      T->Draw(
          "TOWER_" + gain + "_CEMC[].get_energy_power_law_exp()>>" + hname,
          Form(
              "TOWER_%s_CEMC[].get_bineta()==%d && TOWER_%s_CEMC[].get_binphi()==%d",
              gain.Data(), ieta, gain.Data(), iphi),
          "");

      TText *t = new TText(.9, .9, Form("Col%d Row%d", ieta, iphi));
      t->SetTextAlign(33);
      t->SetTextSize(.15);
      t->SetNDC();
      t->Draw();

      //          return;
    }
  }

  SaveCanvas(c1,
             TString(_file0->GetName()) + TString("_DrawPrototype3EMCalTower_") + TString(c1->GetName()), false);
}
Example #22
0
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();
}
Example #23
0
CompareSpectra(Int_t part, Int_t charge, Int_t cent = -1, Int_t ratio = kFALSE, Int_t fitfunc = -1, Bool_t cutSpectra = kTRUE) 
{

  gROOT->LoadMacro("HistoUtils.C");

  gStyle->SetOptStat(0);
  gStyle->SetOptFit();

  LoadLibraries();
  AliBWFunc bwf;
  bwf.SetVarType(AliBWFunc::kdNdpt);
  TF1 *fFitFunc = NULL;

  switch (fitfunc) {
  case 0:
    gROOT->LoadMacro("SpectraAnalysis.C");
    fFitFunc = STAR_BlastWave("fBW", AliPID::ParticleMass(part), 0.9, 0.1, 1.);
    fBW->SetParLimits(3, 0.5, 1.5);
    //    fBW->FixParameter(3, 1.);
    break;
  case 1:
    fFitFunc = bwf.GetLevi(AliPID::ParticleMass(part), AliPID::ParticleMass(part), 5., 1000.);
    break;
  case 2:
    fFitFunc = bwf.GetBoltzmann(AliPID::ParticleMass(part), AliPID::ParticleMass(part), 100.);
    break;
  case 3:
    fFitFunc = bwf.GetMTExp(AliPID::ParticleMass(part),AliPID::ParticleMass(part) , 100.);
    break;
  case 4:
    fFitFunc = bwf.GetPTExp(AliPID::ParticleMass(part), 100.);
    break;
  case 5:
    fFitFunc = bwf.GetBGBW(AliPID::ParticleMass(part), 0.5, 0.1, 1.e6);
    break;
  case 6:
    fFitFunc = new TF1("fpol9", "pol9", 0., 5.0);
    break;
  }
  if (fFitFunc) fFitFunc->SetLineWidth(2);

  TFile *itssafile = TFile::Open(ratio ? itssaratiofilename : itssafilename);
  //  TFile *itstpcfile = TFile::Open(itstpcfilename);
  if (part / 3 == charge / 3)
    Char_t *tpctofratiofilename = tpctofratiofilenameA;
  else
    Char_t *tpctofratiofilename = tpctofratiofilenameB;
  TFile *tpctoffile = TFile::Open(ratio ? tpctofratiofilename : tpctoffilename);
  TFile *toffile = TFile::Open(ratio ? tofratiofilename : toffilename);
  //  TFile *hydrofile = TFile::Open(hydrofilename);

  TCanvas *cCanvas = new TCanvas("cCanvas");
  if (cent == -1) cCanvas->Divide(5, 2);
  TCanvas *cCanvasCombined = new TCanvas("cCanvasCombined");
  TCanvas *cCanvasRatio = new TCanvas("cCanvasRatio");
  if (cent == -1) cCanvasRatio->Divide(5, 2);
  TCanvas *cCanvasRatioComb = new TCanvas("cCanvasRatioComb");
  if (cent == -1) cCanvasRatioComb->Divide(5, 2);
  TCanvas *cCanvasRatioFit = new TCanvas("cCanvasRatioFit");
  if (cent == -1) cCanvasRatioFit->Divide(5, 2);
  TPad *curpad = NULL;
  TH1D *hITSsa, *hITSTPC, *hTPCTOF, *hTOF;
  TGraph *hHydro;
  TGraphErrors *gCombined[10];
  TProfile *pCombined[10];
  TH1D *hCombined[10];
  TH1D *hRatio_ITSsa_ITSTPC[10];
  TH1D *hRatio_ITSsa_TPCTOF[10];
  TH1D *hRatio_ITSTPC_TPCTOF[10];
  TH1D *hRatio_ITSTPC_TOF[10];
  TH1D *hRatio_TPCTOF_TOF[10];
  TH1D *hRatio_ITSsa_TOF[10];
  for (Int_t icent = 0; icent < 10; icent++) {
    if (cent != -1 && icent != cent) continue;
    gCombined[icent] = new TGraphErrors();
    pCombined[icent] = new TProfile(Form("pCombined_cent%d", icent), "", NptBins, ptBin);
    hCombined[icent] = new TH1D(Form("hCombined_cent%d", icent), "", NptBins, ptBin);
    TObjArray spectraArray;
    hITSsa = ratio ? GetITSsaRatio(itssafile, part, charge, icent, cutSpectra): GetITSsaSpectrum(itssafile, part, charge, icent, cutSpectra);
    //    hITSTPC = GetITSTPCSpectrum(itstpcfile, part, charge, icent, cutSpectra);
    hTPCTOF = ratio ? GetTPCTOFRatio(tpctoffile, part, charge, icent, cutSpectra) : GetTPCTOFSpectrum(tpctoffile, part, charge, icent, cutSpectra);
    hTOF = ratio ? GetTOFRatio(toffile, part, charge, icent, cutSpectra) : GetTOFSpectrum(toffile, part, charge, icent, cutSpectra);
    //    hHydro = GetHydroSpectrum(hydrofile, part, charge, icent);
    if (cent == -1)
      curpad = (TPad *)cCanvas->cd(icent + 1);
    else
      curpad = (TPad *)cCanvas->cd();
    if (!ratio)
      TH1D *hArea = new TH1D(Form("hArea_%d", icent), Form("%s (%s);p_{T} (GeV/c);#frac{d^{2}N}{dy dp_{t}};", partChargeName[part][charge], centName[icent]), 100, 0., 5.);
    else
      TH1D *hArea = new TH1D(Form("hArea_%d", icent), Form("%s (%s);p_{T} (GeV/c);#frac{d^{2}N}{dy dp_{t}};", "generic ratio", centName[icent]), 100, 0., 5.);
    hArea->Draw();
    Double_t minimum = 0.001;
    Double_t maximum = 1000.;
    if (hITSsa) {
      AddPointsToGraph(hITSsa, gCombined[icent]);
      AddPointsToProfile(hITSsa, pCombined[icent]);
      spectraArray.Add(hITSsa);
      hITSsa->DrawCopy("same");
      if (hITSsa->GetMaximum() > maximum) maximum = hITSsa->GetMaximum();
      if (hITSsa->GetMinimum() < minimum) minimum = hITSsa->GetMinimum();
    }
    if (hITSTPC) {
      AddPointsToGraph(hITSTPC, gCombined[icent]);
      AddPointsToProfile(hITSTPC, pCombined[icent]);
      spectraArray.Add(hITSTPC);
      hITSTPC->DrawCopy("same");
      if (hITSTPC->GetMaximum() > maximum) maximum = hITSTPC->GetMaximum();
      if (hITSTPC->GetMinimum() < minimum) minimum = hITSTPC->GetMinimum();
    }
    if (hTPCTOF) {
      AddPointsToGraph(hTPCTOF, gCombined[icent]);
      AddPointsToProfile(hTPCTOF, pCombined[icent]);
      spectraArray.Add(hTPCTOF);
      hTPCTOF->DrawCopy("same");
      if (hTPCTOF->GetMaximum() > maximum) maximum = hTPCTOF->GetMaximum();
      if (hTPCTOF->GetMinimum() < minimum) minimum = hTPCTOF->GetMinimum();
    }
    if (hTOF) {
      AddPointsToGraph(hTOF, gCombined[icent]);
      AddPointsToProfile(hTOF, pCombined[icent]);
      spectraArray.Add(hTOF);
      hTOF->DrawCopy("same");
      if (hTOF->GetMaximum() > maximum) maximum = hTOF->GetMaximum();
      if (hTOF->GetMinimum() < minimum) minimum = hTOF->GetMinimum();
    }
    if (hHydro) {
      ;//hHydro->Draw("c,same");
    }
    TLegend *legend = curpad->BuildLegend();
    legend->SetFillStyle(0);
    legend->SetFillColor(0);
    legend->DeleteEntry();

    hArea->SetMaximum(maximum * 1.1);
    hArea->SetMinimum(0.01);
    //    gPad->SetLogy();

    /*** RATIOS ***/

    /* switch canvas */
    if (cent == -1)
      curpad = (TPad *)cCanvasRatio->cd(icent + 1);
    else
      curpad = (TPad *)cCanvasRatio->cd();

   
    /* area histo */
    if (!ratio)
      TH1D *hAreaRatio = new TH1D(Form("hAreaRatio_%d", icent), Form("%s (%s);p_{T} (GeV/c);ratio;", partChargeName[part][charge], centName[icent]), 100, 0., 5.);
    else
      TH1D *hAreaRatio = new TH1D(Form("hAreaRatio_%d", icent), Form("%s (%s);p_{T} (GeV/c);ratio;", "generic ratio", centName[icent]), 100, 0., 5.);

    hAreaRatio->SetMaximum(1.5);
    hAreaRatio->SetMinimum(0.5);
    hAreaRatio->Draw();

    /* do ratios */
    if (hITSsa && hITSTPC) {
      hRatio_ITSsa_ITSTPC[icent] = new TH1D(*hITSsa);
      hRatio_ITSsa_ITSTPC[icent]->Divide(hITSTPC);
      hRatio_ITSsa_ITSTPC[icent]->SetNameTitle(Form("hRatio_ITSsa_ITSTPC_cent%d", icent), "ITSsa / ITSTPC");
      hRatio_ITSsa_ITSTPC[icent]->Draw("same");
    }
    if (hITSsa && hTPCTOF) {
      hRatio_ITSsa_TPCTOF[icent] = new TH1D(*hITSsa);
      hRatio_ITSsa_TPCTOF[icent]->Divide(hTPCTOF);
      hRatio_ITSsa_TPCTOF[icent]->SetNameTitle(Form("hRatio_ITSsa_TPCTOF_cent%d", icent), "ITSsa / TPCTOF");
      hRatio_ITSsa_TPCTOF[icent]->SetMarkerStyle(23);
      hRatio_ITSsa_TPCTOF[icent]->SetMarkerColor(4);
      hRatio_ITSsa_TPCTOF[icent]->Draw("same");
    }
    if (hITSTPC && hTPCTOF) {
      hRatio_ITSTPC_TPCTOF[icent] = new TH1D(*hITSTPC);
      hRatio_ITSTPC_TPCTOF[icent]->Divide(hTPCTOF);
      hRatio_ITSTPC_TPCTOF[icent]->SetNameTitle(Form("hRatio_ITSTPC_TPCTOF_cent%d", icent), "ITSTPC / TPCTOF");
      hRatio_ITSTPC_TPCTOF[icent]->Draw("same");
    }
    if (hTPCTOF && hTOF) {
      hRatio_TPCTOF_TOF[icent] = new TH1D(*hTPCTOF);
      hRatio_TPCTOF_TOF[icent]->Divide(hTOF);
      hRatio_TPCTOF_TOF[icent]->SetNameTitle(Form("hRatio_TPCTOF_TOF_cent%d", icent), "TPCTOF / TOF");
      hRatio_TPCTOF_TOF[icent]->Draw("same");
    }
    if (hITSsa && hTOF) {
      hRatio_ITSsa_TOF[icent] = new TH1D(*hITSsa);
      hRatio_ITSsa_TOF[icent]->Divide(hTOF);
      hRatio_ITSsa_TOF[icent]->SetNameTitle(Form("hRatio_ITSsa_TOF_cent%d", icent), "ITSsa / TOF");
      //      hRatio_ITSsa_TOF[icent]->SetMarkerStyle(25);
      //      hRatio_ITSsa_TOF[icent]->SetMarkerColor(2);
      hRatio_ITSsa_TOF[icent]->Draw("same");
    }

    /* legend */
    TLegend *legendRatio = curpad->BuildLegend();
    legendRatio->SetFillStyle(0);
    legendRatio->SetFillColor(0);
    legendRatio->DeleteEntry();

    CombineSpectra(hCombined[icent], &spectraArray);
    hCombined[icent]->SetFillStyle(0);
    hCombined[icent]->SetFillColor(kOrange + 1);
    hCombined[icent]->SetMarkerColor(kOrange+1);
    hCombined[icent]->SetMarkerStyle(24);
    hCombined[icent]->SetLineColor(kOrange+1);
    hCombined[icent]->SetLineWidth(2);
    hCombined[icent]->SetMarkerSize(0);
    
    //    hCombined[icent]->DrawCopy("same,E2");
    //    pCombined[icent]->DrawCopy("same");

    if (cent == -1)
      cCanvas->cd(icent + 1);
    else
      cCanvas->cd();
    //    hCombined[icent]->Draw("same, E2");

    cCanvasCombined->cd();
    if (cent == -1 && icent != 0)
      hCombined[icent]->Draw("E2,same");
    else
      hCombined[icent]->Draw("E2");

    //    cCanvasCombined->DrawClonePad();
    if (hITSsa) {
      hITSsa->DrawCopy("same");
    }
    if (hITSTPC) {
      hITSTPC->DrawCopy("same");
    }
    if (hTPCTOF) {
      hTPCTOF->DrawCopy("same");
    }
    if (hTOF) {
      hTOF->DrawCopy("same");
    }
    if (hHydro) {
      ;//hHydro->Draw("c,same");
    }

    if (cent == -1)
      cCanvasRatioComb->cd(icent + 1);
    else
      cCanvasRatioComb->cd();
    //    hCombined[icent]->Draw("same, E2");

    TH1 *hhr = HistoUtils_smartratio(hCombined[icent], hCombined[icent]);
    hhr->SetMaximum(1.25);
    hhr->SetMinimum(0.75);
    hhr->SetFillStyle(3001);
    hhr->SetTitle("combined error;p_{T} (GeV/c);ratio wrt. combined");
    hhr->Draw("e2");
    if (hITSsa) {
      hhr = HistoUtils_smartratio(hITSsa, hCombined[icent]);
      hhr->SetLineColor(1);
      hhr->SetLineWidth(2);
      hhr->Draw("e2,same");
    }
    if (hITSTPC) {
      hhr = HistoUtils_smartratio(hITSTPC, hCombined[icent]);
      hhr->SetLineColor(1);
      hhr->SetLineWidth(2);
      hhr->Draw("e2,same");
    }
    if (hTPCTOF) {
      hhr = HistoUtils_smartratio(hTPCTOF, hCombined[icent]);
      hhr->SetLineColor(8);
      hhr->SetLineWidth(2);
      hhr->Draw("e2,same");
    }
    if (hTOF) {
      hhr = HistoUtils_smartratio(hTOF, hCombined[icent]);
      hhr->SetLineColor(4);
      hhr->SetLineWidth(2);
      hhr->Draw("e2,same");
    }
    if (hHydro) {
      ;//hHydro->Draw("c,same");
    }


    if (!fFitFunc)
      continue;
    
    //    gCombined[icent]->Draw("p*");
    //    gCombined[icent]->Fit(fFitFunc, "0q", "", 0.5, 1.0);
    //    gCombined[icent]->Fit(fFitFunc, "0q", "", 0.2, 1.5);
    hCombined[icent]->Fit(fFitFunc, "0q", "", 0., 5.);
    fFitFunc->DrawCopy("same");
    printf("cent = %d, dNdy = %f +- %f\n", icent, fFitFunc->GetParameter(0), fFitFunc->GetParError(0));

    if (cent == -1)
      cCanvas->cd(icent + 1);
    else
      cCanvas->cd();
    fFitFunc->DrawCopy("same");

    if (cent == -1)
      cCanvasRatioFit->cd(icent + 1);
    else
      cCanvasRatioFit->cd();
    if (!ratio)
      TH1D *hAreaRatioFit = new TH1D(Form("hAreaRatioFit_%d", icent), Form("%s (%s);p_{T} (GeV/c);ratio wrt. fit;", partChargeName[part][charge], centName[icent]), 100, 0., 5.);
    else
      TH1D *hAreaRatioFit = new TH1D(Form("hAreaRatioFit_%d", icent), Form("%s (%s);p_{T} (GeV/c);ratio wrt. fit;", "generic ratio", centName[icent]), 100, 0., 5.);
    hAreaRatioFit->SetMaximum(1.5);
    hAreaRatioFit->SetMinimum(0.5);
    hAreaRatioFit->Draw();
    legend->Draw("same");

    if (hITSsa) {
      hITSsa->Divide(fFitFunc);
      hITSsa->DrawCopy("same");
    }
    if (hITSTPC) {
      hITSTPC->Divide(fFitFunc);
      hITSTPC->DrawCopy("same");
    }
    if (hTPCTOF) {
      hTPCTOF->Divide(fFitFunc);
      hTPCTOF->DrawCopy("same");
    }
    if (hTOF) {
      hTOF->Divide(fFitFunc);
      hTOF->DrawCopy("same");
    }

  }

}
void makePlot(const std::string& inputFilePath, const std::string& canvasName, const std::string& sample, int massPoint, const std::string& channel, double k, 
	      const std::string& inputFileName, const std::string& outputFilePath, const std::string& outputFileName)
{
  std::string inputFileName_full = Form("%s%s", inputFilePath.data(), inputFileName.data());
  TFile* inputFile = new TFile(inputFileName_full.data());
  if ( !inputFile ) {
    std::cerr << "Failed to open input file = " << inputFileName_full << " !!" << std::endl;
    assert(0);
  }

  inputFile->ls();

  TCanvas* canvas = dynamic_cast<TCanvas*>(inputFile->Get(canvasName.data()));
  if ( !canvas ) {
    std::cerr << "Failed to load canvas = " << canvasName << " !!" << std::endl;
    assert(0);
  }

  int idxPad = -1;
  if ( massPoint ==  90 ) idxPad = 1;
  if ( massPoint == 125 ) idxPad = 2;
  if ( massPoint == 200 ) idxPad = 3;
  if ( massPoint == 300 ) idxPad = 4;
  if ( massPoint == 500 ) idxPad = 5;
  if ( massPoint == 800 ) idxPad = 6;  
  if ( !(idxPad >= 1 && idxPad <= 6) ) {
    std::cerr << "Invalid sample = " << sample << " !!" << std::endl;
    assert(0);
  }
  TVirtualPad* pad = canvas->GetPad(idxPad);
  std::cout << "pad = " << pad << ": ClassName = " << pad->ClassName() << std::endl;

  TCanvas* canvas_new = new TCanvas("canvas_new", "canvas_new", 900, 800);
  canvas_new->SetFillColor(10);
  canvas_new->SetBorderSize(2);
  canvas_new->SetTopMargin(0.065);
  canvas_new->SetLeftMargin(0.17);
  canvas_new->SetBottomMargin(0.165);
  canvas_new->SetRightMargin(0.015);
  canvas_new->SetLogx(true);
  canvas_new->SetLogy(true);
  canvas_new->Draw();
  canvas_new->cd();

  //TList* pad_primitives = canvas->GetListOfPrimitives();
  TList* pad_primitives = pad->GetListOfPrimitives();

  TH1* histogramCA            = 0;
  TH1* histogramSVfit         = 0;
  TH1* histogramSVfitMEMkEq0  = 0;
  TH1* histogramSVfitMEMkNeq0 = 0;

  TIter pad_nextObj(pad_primitives);
  while ( TObject* obj = pad_nextObj() ) {
    std::string objName = "";
    if ( dynamic_cast<TNamed*>(obj) ) objName = (dynamic_cast<TNamed*>(obj))->GetName();    
    std::cout << "obj = " << obj << ": name = " << objName << ", type = " << obj->ClassName() << std::endl;

    TH1* tmpHistogram = dynamic_cast<TH1*>(obj);
    if ( tmpHistogram ) {
      std::cout << "tmpHistogram:" 
		<< " fillColor = " << tmpHistogram->GetFillColor() << ", fillStyle = " << tmpHistogram->GetFillStyle() << ","
		<< " lineColor = " << tmpHistogram->GetLineColor() << ", lineStyle = " << tmpHistogram->GetLineStyle() << ", lineWidth = " << tmpHistogram->GetLineWidth() << ","
		<< " markerColor = " << tmpHistogram->GetMarkerColor() << ", markerStyle = " << tmpHistogram->GetMarkerStyle() << ", markerSize = " << tmpHistogram->GetMarkerSize() << ","
		<< " integral = " << tmpHistogram->Integral() << std::endl;
      std::cout << "(mean = " << tmpHistogram->GetMean() << ", rms = " << tmpHistogram->GetRMS() << ": rms/mean = " << (tmpHistogram->GetRMS()/tmpHistogram->GetMean()) << ")" << std::endl;
      if ( tmpHistogram->GetLineColor() == 416 ) histogramCA            = tmpHistogram;
      if ( tmpHistogram->GetLineColor() == 600 ) histogramSVfit         = tmpHistogram;
      if ( tmpHistogram->GetLineColor() == 616 ) histogramSVfitMEMkEq0  = tmpHistogram;
      if ( tmpHistogram->GetLineColor() == 632 ) histogramSVfitMEMkNeq0 = tmpHistogram;
    }
  }

  if ( !(histogramCA && histogramSVfit && histogramSVfitMEMkEq0 && histogramSVfitMEMkNeq0) ) {
    std::cerr << "Failed to load histograms !!" << std::endl;
    assert(0);
  }

  //gStyle->SetLineStyleString(2,"40 10 10 10 10 10 10 10");
  //gStyle->SetLineStyleString(3,"25 15");
  //gStyle->SetLineStyleString(4,"60 25");

  //int colors[4] = { kBlack, kGreen - 6, kBlue - 7, kMagenta - 7  };
  int colors[4] = { 28, kGreen - 6, kBlue - 7, kBlack };
  //int lineStyles[4] = { 2, 3, 4, 1 };
  int lineStyles[4] = { 7, 1, 1, 1 };
  //int lineWidths[4] = { 3, 3, 4, 3 };
  int lineWidths[4] = { 3, 3, 1, 1 };
  int markerStyles[4] = { 20, 25, 21, 24 };
  int markerSizes[4] = { 2, 2, 2, 2 };

  histogramCA->SetFillColor(0);
  histogramCA->SetFillStyle(0);
  histogramCA->SetLineColor(colors[0]);
  histogramCA->SetLineStyle(lineStyles[0]);
  histogramCA->SetLineWidth(lineWidths[0]);
  histogramCA->SetMarkerColor(colors[0]);
  histogramCA->SetMarkerStyle(markerStyles[0]);
  histogramCA->SetMarkerSize(markerSizes[0]);

  histogramSVfit->SetFillColor(0);
  histogramSVfit->SetFillStyle(0);
  histogramSVfit->SetLineColor(colors[1]);
  histogramSVfit->SetLineStyle(lineStyles[1]);
  histogramSVfit->SetLineWidth(lineWidths[1]);
  histogramSVfit->SetMarkerColor(colors[1]);
  histogramSVfit->SetMarkerStyle(markerStyles[1]);
  histogramSVfit->SetMarkerSize(markerSizes[1]);

  histogramSVfitMEMkEq0->SetFillColor(0);
  histogramSVfitMEMkEq0->SetFillStyle(0);
  histogramSVfitMEMkEq0->SetLineColor(colors[2]);
  histogramSVfitMEMkEq0->SetLineStyle(lineStyles[2]);
  histogramSVfitMEMkEq0->SetLineWidth(lineWidths[2]);
  histogramSVfitMEMkEq0->SetMarkerColor(colors[2]);
  histogramSVfitMEMkEq0->SetMarkerStyle(markerStyles[2]);
  histogramSVfitMEMkEq0->SetMarkerSize(markerSizes[2]);
  // CV: fix pathological bins at high mass for which dN/dm increases
  int numBins = histogramSVfitMEMkEq0->GetNbinsX();
  for ( int idxBin = 1; idxBin <= numBins; ++idxBin ) {
    double binCenter = histogramSVfitMEMkEq0->GetBinCenter(idxBin);
    if ( (channel == "#tau_{h}#tau_{h}" && massPoint == 500 && binCenter > 1500.) ||
	 (channel == "#tau_{h}#tau_{h}" && massPoint == 800 && binCenter > 2000.) ||
	 (channel == "#mu#tau_{h}"      && massPoint == 500 && binCenter > 1500.) ||
	 (channel == "#mu#tau_{h}"      && massPoint == 800 && binCenter > 2500.) ) {
      histogramSVfitMEMkEq0->SetBinContent(idxBin, 0.);
    }
  }

  histogramSVfitMEMkNeq0->SetFillColor(0);
  histogramSVfitMEMkNeq0->SetFillStyle(0);
  histogramSVfitMEMkNeq0->SetLineColor(colors[3]);
  histogramSVfitMEMkNeq0->SetLineStyle(lineStyles[3]);
  histogramSVfitMEMkNeq0->SetLineWidth(lineWidths[3]);
  histogramSVfitMEMkNeq0->SetMarkerColor(colors[3]);
  histogramSVfitMEMkNeq0->SetMarkerStyle(markerStyles[3]);
  histogramSVfitMEMkNeq0->SetMarkerSize(markerSizes[3]);

  TAxis* xAxis = histogramCA->GetXaxis();
  xAxis->SetTitle("m_{#tau#tau} [GeV]");
  xAxis->SetTitleOffset(1.15);
  xAxis->SetTitleSize(0.070);
  xAxis->SetTitleFont(42);
  xAxis->SetLabelOffset(0.010);
  xAxis->SetLabelSize(0.055);
  xAxis->SetLabelFont(42);
  xAxis->SetTickLength(0.040);
  xAxis->SetNdivisions(510);

  //double xMin = 20.;
  //double xMax = xAxis->GetXmax();
  //xAxis->SetRangeUser(xMin, xMax);

  TAxis* yAxis = histogramCA->GetYaxis();
  yAxis->SetTitle("dN/dm_{#tau#tau} [1/GeV]");
  yAxis->SetTitleOffset(1.20);
  yAxis->SetTitleSize(0.070);
  yAxis->SetTitleFont(42);
  yAxis->SetLabelOffset(0.010);
  yAxis->SetLabelSize(0.055);
  yAxis->SetLabelFont(42);
  yAxis->SetTickLength(0.040);  
  yAxis->SetNdivisions(505);

  double massPoint_double = 0.;
  if ( massPoint == 90 ) massPoint_double = 91.2;
  else massPoint_double = massPoint;
  double dLog = (TMath::Log(5.*massPoint_double) - TMath::Log(50.))/25.; // xMin = 50, xMax = 5*massPoint, numBins = 25
  double binWidth = TMath::Exp(TMath::Log(massPoint_double) + 0.5*dLog) - TMath::Exp(TMath::Log(massPoint_double) - 0.5*dLog);
  double sf_binWidth = 1./binWidth;
  std::cout << "massPoint = " << massPoint << ": sf_binWidth = " << sf_binWidth << std::endl;

  histogramCA->SetTitle("");
  histogramCA->SetStats(false);
  histogramCA->SetMaximum(sf_binWidth*0.79);
  histogramCA->SetMinimum(sf_binWidth*1.1e-4);
  histogramCA->Draw("hist");
  histogramSVfit->Draw("histsame");
  //histogramSVfitMEMkEq0->Draw("histsame");
  histogramSVfitMEMkEq0->Draw("epsame");
  //histogramSVfitMEMkNeq0->Draw("histsame");
  histogramSVfitMEMkNeq0->Draw("epsame");
  histogramCA->Draw("axissame");

  //TPaveText* label_sample = new TPaveText(0.21, 0.86, 0.46, 0.94, "NDC");
  TPaveText* label_sample = new TPaveText(0.1700, 0.9475, 0.4600, 1.0375, "NDC");
  label_sample->SetFillStyle(0);
  label_sample->SetBorderSize(0);
  label_sample->AddText(sample.data());
  label_sample->SetTextFont(42);
  label_sample->SetTextSize(0.055);
  label_sample->SetTextColor(1);
  label_sample->SetTextAlign(13);
  label_sample->Draw();

  //TLegend* legend_new = new TLegend(0.225, 0.52, 0.41, 0.82, NULL, "brNDC");
  TLegend* legend_new = new TLegend(0.30, 0.30, 0.80, 0.80, NULL, "brNDC");
  legend_new->SetFillColor(10);
  legend_new->SetFillStyle(0);
  legend_new->SetBorderSize(0);
  legend_new->SetTextFont(42);
  legend_new->SetTextSize(0.055);
  legend_new->SetTextColor(1);
  legend_new->SetMargin(0.20);
  legend_new->AddEntry(histogramCA, "CA", "l");
  legend_new->AddEntry(histogramSVfit, "SVfit", "l");
  //legend_new->AddEntry(histogramSVfitMEMkEq0, "SVfitMEM (k=0)", "l");
  legend_new->AddEntry(histogramSVfitMEMkEq0, "SVfitMEM (k=0)", "p");
  //legend_new->AddEntry(histogramSVfitMEMkNeq0, Form("SVfitMEM(k=%1.0f)", k), "l");
  legend_new->AddEntry(histogramSVfitMEMkNeq0, Form("SVfitMEM (k=%1.0f)", k), "p");
  //legend_new->Draw();

  double label_channel_y0;
  if      ( channel == "e#mu"             ) label_channel_y0 = 0.9275;
  else if ( channel == "#mu#tau_{h}"      ) label_channel_y0 = 0.9400;
  else if ( channel == "#tau_{h}#tau_{h}" ) label_channel_y0 = 0.9350;
  else {
    std::cerr << "Invalid channel = " << channel << " !!" << std::endl;
    assert(0);
  }
  TPaveText* label_channel = new TPaveText(0.895, label_channel_y0, 0.975, label_channel_y0 + 0.055, "NDC");
  label_channel->SetFillStyle(0);
  label_channel->SetBorderSize(0);
  label_channel->AddText(channel.data());
  label_channel->SetTextFont(62);
  label_channel->SetTextSize(0.055);
  label_channel->SetTextColor(1);
  label_channel->SetTextAlign(31);
  label_channel->Draw();

  canvas_new->Update();

  std::string outputFileName_full = Form("%s%s", outputFilePath.data(), outputFileName.data());
  size_t idx = outputFileName_full.find_last_of('.');
  std::string outputFileName_plot = std::string(outputFileName_full, 0, idx);
  canvas_new->Print(std::string(outputFileName_plot).append(".pdf").data());
  canvas_new->Print(std::string(outputFileName_plot).append(".root").data());

  std::string channel_string;
  if      ( channel == "e#mu"             ) channel_string = "emu";
  else if ( channel == "#mu#tau_{h}"      ) channel_string = "muhad";
  else if ( channel == "#tau_{h}#tau_{h}" ) channel_string = "hadhad";
  else {
    std::cerr << "Invalid channel = " << channel << " !!" << std::endl;
    assert(0);
  }
  std::string outputFileName_legend = Form("makeSVfitMEM_PerformancePlots_legend_%s.pdf", channel_string.data());
  makePlot_legend(legend_new, outputFilePath, outputFileName_legend);

  delete label_sample;
  delete legend_new;
  delete label_channel;
  delete canvas_new;

  delete inputFile;
}
Example #25
0
void makeSystPlot( TFile * f, TString oldFolder, RooWorkspace *WS,  string channel, string syst, int toMassNo, int fromMassNo) //massNo 0-51, see xSec7TeV.h 
{

  RooArgList  * hobs = new RooArgList("hobs");
  RooRealVar BDT("CMS_vhbb_BDT_Zll", "CMS_vhbb_BDT_Zll", -1, 1);///OLD VARIABLE NAME HERE
  hobs->add(*WS->var("CMS_vhbb_BDT_Zll"));  ///NEW VARIABLE NAME HERE
  RooWorkspace *tempWS =  (RooWorkspace*) f->Get(oldFolder.Data());
  TString systT(syst);
  TString chanT(channel);
  bool writeIt = 1;
 
  if(chanT.Contains("QCD") || chanT.Contains("Wj"))
  if(!(systT.Contains("stat"))) writeIt = 0;
 

  if((kount < 3) && (channel=="data_obs"))
  {
    kount++;
    std::string namen  = channel;
    
    std::cout << "reading WS "<< oldFolder.Data() << std::endl;
    std::cout << namen << std::endl;
    RooDataHist* tempRooDataHistNom = (RooDataHist*)  tempWS->data(namen.c_str());
    TH1 *tempHistNom = tempRooDataHistNom->createHistogram(namen.c_str(),BDT,Binning(bins));
    std::cout << namen << std::endl;

    RooDataHist *DHnom = new RooDataHist(channel.c_str(),"",*hobs,tempHistNom);  
    WS->import(*(new RooHistPdf(channel.c_str(),"",*hobs,*DHnom)));
 
 }

 if (channel!="data_obs")
 {
  std::string nameUp; 
  std::string namen; 
  std::string nameDown;


  if((syst == "stat"))
  {
    if(IFILE.Contains("7TeV"))
    {
      nameUp  = channel + "CMS_vhbb_stats_" + channel + "_" + oldFolder.Data() + "Up";
      namen  = channel;
      nameDown  = channel + "CMS_vhbb_stats_" + channel + "_" + oldFolder.Data() + "Down";
    }
    if(IFILE.Contains("8TeV"))
    { 
      nameUp  = channel + "CMS_vhbb_stats_" + channel + "_" + oldFolder.Data() + "Up";
      namen  = channel;
      nameDown  = channel + "CMS_vhbb_stats_" + channel + "_" + oldFolder.Data() + "Down";
    }

  }
  else
  {
  nameUp  = channel + "CMS_" + syst + "Up";
  namen  = channel;
  nameDown = channel + "CMS_" + syst + "Down";
  }
  if((syst == "ZJModel"))
  {
    if(IFILE.Contains("7TeV"))
    { 
      nameUp  = channel + "CMS_vhbb_ZJModel_" + oldFolder.Data() + "_7TeVUp";
      namen  = channel;
      nameDown  = channel + "CMS_vhbb_ZJModel_" + oldFolder.Data() + "_7TeVDown";
    }
    if(IFILE.Contains("8TeV"))
    { 
      nameUp  = channel + "CMS_vhbb_ZJModel_" + oldFolder.Data() + "_8TeVUp";
      namen  = channel;
      nameDown  = channel + "CMS_vhbb_ZJModel_" + oldFolder.Data() + "_8TeVDown";
    }

  }
  
  if(writeIt)
   {
    RooDataHist* tempRooDataHistUp = (RooDataHist*)  tempWS->data(nameUp.c_str());
    RooDataHist* tempRooDataHistDown = (RooDataHist*)  tempWS->data(nameDown.c_str());
    RooDataHist* tempRooDataHistNom = (RooDataHist*)  tempWS->data(namen.c_str());


   
    std::cout << oldFolder.Data() << std::endl; 
    std::cout << nameUp.c_str() << std::endl; 
 	 
    TH1 *tempHistUp = tempRooDataHistUp->createHistogram(nameUp.c_str(),BDT,Binning(bins));
    TH1 *tempHistDown = tempRooDataHistDown->createHistogram(nameDown.c_str(),BDT,Binning(bins));
    std::cout << namen.c_str() << std::endl;
    TH1 *tempHistNom = tempRooDataHistNom->createHistogram(namen.c_str(),BDT,Binning(bins));

    if(chanT.Contains("VH") && IFILE.Contains("7TeV"))
    {
     tempHistUp->Scale(xSec7ZH[toMassNo]/xSec7ZH[fromMassNo]);
     tempHistDown->Scale(xSec7ZH[toMassNo]/xSec7ZH[fromMassNo]);
     tempHistNom->Scale(xSec7ZH[toMassNo]/xSec7ZH[fromMassNo]);
    }  
 
   if(chanT.Contains("VH") && IFILE.Contains("8TeV"))
   {
     tempHistUp->Scale(xSec8ZH[toMassNo]/xSec8ZH[fromMassNo]);
     tempHistDown->Scale(xSec8ZH[toMassNo]/xSec8ZH[fromMassNo]);
     tempHistNom->Scale(xSec8ZH[toMassNo]/xSec8ZH[fromMassNo]);
   }  
   
   std::cout<< "channel--> " << channel << std::endl;


   tempHistUp->SetLineColor(kRed);
   tempHistUp->SetLineWidth(3);
   tempHistUp->SetFillColor(0);
  
   tempHistDown->SetLineColor(kBlue);
   tempHistDown->SetFillColor(0);
   tempHistDown->SetLineWidth(3);
  
   tempHistNom->SetFillColor(0);
   tempHistNom->SetMarkerStyle(20);
   tempHistUp->SetTitle((channel + syst).c_str());
 
 
   RooDataHist *DHnom;
   RooDataHist *DHup = new RooDataHist(nameUp.c_str(),"",*hobs,tempHistUp);  
   if(kount2 < 3) DHnom = new RooDataHist(namen.c_str(),"",*hobs,tempHistNom);
   RooDataHist *DHdown = new RooDataHist(nameDown.c_str(),"",*hobs,tempHistDown);  

   WS->import(*(new RooHistPdf(nameUp.c_str(),"",*hobs,*DHup)));
   WS->import(*(new RooHistPdf(nameDown.c_str(),"",*hobs,*DHdown)));
   if(kount2 < 3){ WS->import(*(new RooHistPdf(namen.c_str(),"",*hobs,*DHnom))); kount2++;}
   }
 }


}
Example #26
0
void plot_efficiencies( TFile* file, Int_t type = 2, TDirectory* BinDir)
{
   // input:   - Input file (result from TMVA),
   //          - type = 1 --> plot efficiency(B) versus eff(S)
   //                 = 2 --> plot rejection (B) versus efficiency (S)

   Bool_t __PLOT_LOGO__  = kTRUE;
   Bool_t __SAVE_IMAGE__ = kTRUE;

   // the coordinates
   Float_t x1 = 0;
   Float_t x2 = 1;
   Float_t y1 = 0;
   Float_t y2 = 0.8;

   // reverse order if "rejection"
   if (type == 2) {
      Float_t z = y1;
      y1 = 1 - y2;
      y2 = 1 - z;    
      //      cout << "--- type==2: plot background rejection versus signal efficiency" << endl;
   }
   else {
      //  cout << "--- type==1: plot background efficiency versus signal efficiency" << endl;
   }
   // create canvas
   TCanvas* c = new TCanvas( "c", "the canvas", 200, 0, 650, 500 );

   // global style settings
   c->SetGrid();
   c->SetTicks();

   // legend
   Float_t x0L = 0.107,     y0H = 0.899;
   Float_t dxL = 0.457-x0L, dyH = 0.22;
   if (type == 2) {
      x0L = 0.15;
      y0H = 1 - y0H + dyH + 0.07;
   }
   TLegend *legend = new TLegend( x0L, y0H-dyH, x0L+dxL, y0H );
   legend->SetTextSize( 0.05 );
   legend->SetHeader( "MVA Method:" );
   legend->SetMargin( 0.4 );

   TString xtit = "Signal efficiency";
   TString ytit = "Background efficiency";  
   if (type == 2) ytit = "Background rejection";
   TString ftit = ytit + " versus " + xtit;

   if (TString(BinDir->GetName()).Contains("multicut")){
      ftit += "  Bin: ";
      ftit += (BinDir->GetTitle());
   }

   // draw empty frame
   if(gROOT->FindObject("frame")!=0) gROOT->FindObject("frame")->Delete();
   TH2F* frame = new TH2F( "frame", ftit, 500, x1, x2, 500, y1, y2 );
   frame->GetXaxis()->SetTitle( xtit );
   frame->GetYaxis()->SetTitle( ytit );
   TMVAGlob::SetFrameStyle( frame, 1.0 );

   frame->Draw();  

   Int_t color = 1;
   Int_t nmva  = 0;
   TKey *key, *hkey;

   TString hNameRef = "effBvsS";
   if (type == 2) hNameRef = "rejBvsS";

   TList hists;
   TList methods;
   UInt_t nm = TMVAGlob::GetListOfMethods( methods );
   //   TIter next(file->GetListOfKeys());
   TIter next(&methods);

   // loop over all methods
   while (key = (TKey*)next()) {
      TDirectory * mDir = (TDirectory*)key->ReadObj();
      TList titles;
      UInt_t ninst = TMVAGlob::GetListOfTitles(mDir,titles);
      TIter nextTitle(&titles);
      TKey *titkey;
      TDirectory *titDir;
      while ((titkey = TMVAGlob::NextKey(nextTitle,"TDirectory"))) {
         titDir = (TDirectory *)titkey->ReadObj();
         TString methodTitle;
         TMVAGlob::GetMethodTitle(methodTitle,titDir);
         TIter nextKey( titDir->GetListOfKeys() );
         while ((hkey = TMVAGlob::NextKey(nextKey,"TH1"))) {
            TH1 *h = (TH1*)hkey->ReadObj();    
            TString hname = h->GetName();
            if (hname.Contains( hNameRef ) && hname.BeginsWith( "MVA_" )) {
               h->SetLineWidth(3);
               h->SetLineColor(color);
               color++; if (color == 5 || color == 10 || color == 11) color++; 
               h->Draw("csame");
               hists.Add(h);
               nmva++;
            }
         }
      }
   }

   while (hists.GetSize()) {
      TListIter hIt(&hists);
      TH1* hist(0);
      Double_t largestInt=-1;
      TH1* histWithLargestInt(0);
      while ((hist = (TH1*)hIt())!=0) {
         Double_t integral = hist->Integral(1,hist->FindBin(0.9999));
         if (integral>largestInt) {
            largestInt = integral;
            histWithLargestInt = hist;
         }
      }
      if (histWithLargestInt == 0) {
         cout << "ERROR - unknown hist \"histWithLargestInt\" --> serious problem in ROOT file" << endl;
         break;
      }
      legend->AddEntry(histWithLargestInt,TString(histWithLargestInt->GetTitle()).ReplaceAll("MVA_",""),"l");
      hists.Remove(histWithLargestInt);
   }   
   
   // rescale legend box size
   // current box size has been tuned for 3 MVAs + 1 title
   if (type == 1) {
      dyH *= (1.0 + Float_t(nmva - 3.0)/4.0);
      legend->SetY1( y0H - dyH );
   }
   else {
      dyH *= (Float_t(nmva - 3.0)/4.0);
      legend->SetY2( y0H + dyH);
   }

   // redraw axes
   frame->Draw("sameaxis");  
   legend->Draw("same");

   // ============================================================

   if (__PLOT_LOGO__) TMVAGlob::plot_logo();

   // ============================================================

   c->Update();

   TString fname = "plots/" + hNameRef;
   if (TString(BinDir->GetName()).Contains("multicut")){
      TString fprepend(BinDir->GetName());
      fprepend.ReplaceAll("multicutMVA_","");
      fname = "plots/" + fprepend + "_" + hNameRef;
   }
   if (__SAVE_IMAGE__) TMVAGlob::imgconv( c, fname );

   return;
}
void PerformanceSpectrumUncorr(const Char_t *fname = "HFEtask.root"){

  gROOT->SetStyle("Plain");
  gStyle->SetTitleFillColor(0);
  gStyle->SetTitleBorderSize(0);
  gStyle->SetTitleX(0.1);
  gStyle->SetTitleY(0.96);

  TFile *in = TFile::Open(fname);
  TList *res = (TList *)in->Get("HFE_Results");
  TList *qa = (TList *)in->Get("HFE_QA");
  gROOT->cd();
  AliHFEcontainer *tcont = dynamic_cast<AliHFEcontainer *>(res->FindObject("trackContainer"));
  AliCFContainer *c = tcont->GetCFContainer("recTrackContReco");
  AliCFContainer *cb = tcont->GetCFContainer("hadronicBackground");

  TH1 *spec = c->Project(c->GetNStep() - 1, 0);
  spec->GetXaxis()->SetTitle("p_{T} / GeV/c");
  spec->GetYaxis()->SetTitle("#frac{dN}{dp_{T}} / (GeV/c)^{-1}");
  spec->GetXaxis()->SetRangeUser(ptmin, ptmax);
  spec->GetYaxis()->SetTitleOffset(1.1);
  spec->SetTitle();
  spec->SetStats(kFALSE);

  spec->SetLineColor(kBlue);
  spec->SetLineWidth(1);
  spec->SetMarkerColor(kBlue);
  spec->SetMarkerStyle(22);

  // Produce background subtracted spectrum
  AliCFDataGrid tracks("tracks", "track grid", *c, c->GetNStep() - 1);
  AliCFDataGrid background("background", "background grid", *cb, 1);
  tracks.ApplyBGCorrection(background);
  TH1 *spec_subtracted = tracks.Project(0);
  spec_subtracted->GetXaxis()->SetTitle("p_{T} / GeV/c");
  spec_subtracted->GetYaxis()->SetTitle("#frac{dN}{dp_{T}} / (GeV/c)^{-1}");
  spec_subtracted->GetXaxis()->SetRangeUser(ptmin, ptmax);
  spec_subtracted->GetYaxis()->SetTitleOffset(1.1);
  spec_subtracted->SetTitle();
  spec_subtracted->SetStats(kFALSE);
  spec_subtracted->SetLineColor(kRed);
  spec_subtracted->SetLineWidth(1);
  spec_subtracted->SetMarkerColor(kRed);
  spec_subtracted->SetMarkerStyle(22);

  TLegend *leg = new TLegend(0.2, 0.25, 0.4, 0.35);
  leg->SetBorderSize(0);
  leg->SetFillStyle(0);
  leg->AddEntry(spec, "Raw Spectrum", "p");
  leg->AddEntry(spec_subtracted, "Spectrum after background subtraction", "p");
 
  TCanvas *c1 = new TCanvas("cspec", "Single-inclusive electron spectrum", 1200, 750);
  c1->cd();
  c1->SetLogy();
  c1->SetGridx(kFALSE);
  c1->SetGridy(kFALSE);
  spec->Draw("ep");
  spec_subtracted->Draw("epsame");
  leg->Draw();
  ALICEWorkInProgress(c1, "today");

  // PID
  TList *pidqa = (TList *)qa->FindObject("HFEpidQA");
  AliHFEtpcPIDqa *tpcqa = (AliHFEtpcPIDqa *)pidqa->FindObject("TPCQA");
  AliHFEtofPIDqa *tofqa = (AliHFEtofPIDqa *)pidqa->FindObject("TOFQA");

  // Make Plots for TPC
  // Create histograms by projecting the THnSparse
  TH2 *hTPCall = tpcqa->MakeSpectrumdEdx(AliHFEdetPIDqa::kBeforePID);
  TH2 *hTPCselected = tpcqa->MakeSpectrumdEdx(AliHFEdetPIDqa::kAfterPID);
  TH2 *hTPCsigmaAll = tpcqa->MakeSpectrumNSigma(AliHFEdetPIDqa::kBeforePID);
  TH2* hTPCsigmaSelected = tpcqa->MakeSpectrumNSigma(AliHFEdetPIDqa::kAfterPID);
  // Make Plots for TOF
  TH2 *hTOFsigmaAll = tofqa->MakeSpectrumNSigma(AliHFEdetPIDqa::kBeforePID);
  TH2 *hTOFsigmaSelected = tofqa->MakeSpectrumNSigma(AliHFEdetPIDqa::kAfterPID);

  hTPCsigmaAll->SetTitle("TPC n#sigma around the electron line");
  hTPCsigmaSelected->SetTitle("TPC n#sigma around the electron line for selected tracks");
  hTOFsigmaAll->SetTitle("TOF n#sigma around the electron line");
  hTOFsigmaSelected->SetTitle("TOF n#sigma around the electron line for selected tracks");
  DefineTPChisto(hTPCall, "TPC Signal / a.u");
  DefineTPChisto(hTPCselected, "TPC Signal / a.u.");
  DefineTPChisto(hTPCsigmaAll, "TPC Sigma");
  DefineTPChisto(hTPCsigmaSelected, "TPC Sigma");

  // Also make nice histograms for TOF
  DefineTPChisto(hTOFsigmaAll, "TOF Sigma");
  DefineTPChisto(hTOFsigmaSelected, "TOF Sigma");

  // Plot them
  TCanvas *c2 = new TCanvas("cTPCall", "TPC Signal for all tracks", 640, 480);
  c2->cd();
  c2->SetGridx(kFALSE);
  c2->SetGridy(kFALSE);
  c2->SetLogx();
  c2->SetLogz();
  hTPCall->GetYaxis()->SetRangeUser(40., 100.);
  hTPCall->Draw("colz");
  ALICEWorkInProgress(c2, "today");

  TCanvas *c3 = new TCanvas("cTPCsel", "TPC Signal for selected tracks", 640, 480);
  c3->cd();
  c3->SetGridx(kFALSE);
  c3->SetGridy(kFALSE);
  c3->SetLogx();
  c3->SetLogz();
  hTPCselected->GetYaxis()->SetRangeUser(40., 100.);
  hTPCselected->Draw("colz");
  ALICEWorkInProgress(c3, "today");

  TCanvas *c4 = new TCanvas("cTPCsigAll", "TPC Sigma for all tracks", 640, 480);
  c4->cd();
  c4->SetGridx(kFALSE);
  c4->SetGridy(kFALSE);
  c4->SetLogx();
  c4->SetLogz();
  //hTPCsigmaAll->GetYaxis()->SetRangeUser(-3.5, 5.);
  hTPCsigmaAll->Draw("colz");
  ALICEWorkInProgress(c4, "today");

  TCanvas *c5 = new TCanvas("cTPCsigSel", "TPC Sigma for selected tracks", 640, 480);
  c5->cd();
  c5->SetGridx(kFALSE);
  c5->SetGridy(kFALSE);
  c5->SetLogx();
  c5->SetLogz();
  hTPCsigmaSelected->GetYaxis()->SetRangeUser(-3.5, 5.);
  hTPCsigmaSelected->Draw("colz");
  ALICEWorkInProgress(c5, "today");

  TCanvas *c6 = new TCanvas("cTOFsigAll", "TOF Sigma for all tracks", 640, 480);
  c6->cd();
  c6->SetGridx(kFALSE);
  c6->SetGridy(kFALSE);
  c6->SetLogx();
  c6->SetLogz();
  hTOFsigmaAll->Draw("colz");
  ALICEWorkInProgress(c6, "today");

  TCanvas *c7 = new TCanvas("cTOFsigSel", "TOF Sigma for selected tracks", 640, 480);
  c7->cd();
  c7->SetGridx(kFALSE);
  c7->SetGridy(kFALSE);
  c7->SetLogx();
  c7->SetLogz();
  //hTOFsigmaSelected->GetYaxis()->SetRangeUser(-3, 3);
  hTOFsigmaSelected->Draw("colz");
  ALICEWorkInProgress(c7, "today");

  TFile *output = new TFile("Performance.root", "RECREATE");
  output->cd();
  spec->Write();
  hTPCall->Write();
  hTPCselected->Write();
  hTPCsigmaAll->Write();
  hTPCsigmaSelected->Write();
  c1->Write();
  c2->Write();
  c3->Write();
  c4->Write();
  c5->Write();
  c6->Write();
  c7->Write();
  output->Close();
  delete output;
}
Example #28
0
TCanvas* plotting36GS( bool logScale=false ) 
{

  std::cout << "plotting mu + standalone " << std::endl;
  TGaxis::SetMaxDigits(3);

  // channels, ordered as in the legend
  vector<TString> channels;  
  vector<TString> hnames; 
  vector<TString> type;

  map<TString,int> fillColor_;
  map<TString,int> lineColor_;
  int lineWidth1(2);
  int lineWidth2(1);

  bool salamanderStyle=true;
  if( salamanderStyle )
    {
      fillColor_["Signal"] = kOrange-2;
      lineColor_["Signal"] = kOrange+3;
      
      fillColor_["EWK"] = kOrange+7;
      lineColor_["EWK"] = kOrange+3;
      
      fillColor_["QCD"] = kViolet-5;
      lineColor_["QCD"] = kViolet+3;
      
      fillColor_["ttbar"] = kRed+2;
      lineColor_["ttbar"] = kRed+4;
      
      fillColor_["gamma+jet"] = kMagenta+4;
      lineColor_["gamma+jet"] = kViolet+3;
    }
  else
    {
      lineWidth1 = 2;
      lineWidth2 = 2;

      fillColor_["Signal"] = kPink+6;
      lineColor_["Signal"] = kMagenta+3;
      
      fillColor_["EWK"] = kAzure+8;
      lineColor_["EWK"] = kAzure+4;
      
      fillColor_["QCD"] = kYellow-7;
      lineColor_["QCD"] = kYellow+4;
      
      fillColor_["ttbar"] = kGreen;
      lineColor_["ttbar"] = kGreen+2;
      
      fillColor_["gamma+jet"] = kOrange;
      lineColor_["gamma+jet"] = kOrange+2;
    }

  // root file, where the data is
  TString fname("root/");

  // histogram limits, in linear and logarithmic
  int nbin_(100);
  float xmin_(0.), xmax_(0.); 
  float ymin_(0.), ymax_(0.); 
  float yminl_(0.), ymaxl_(0.); 

  // titles and axis, marker size
  TString xtitle;
  TString ytitle;
  int ndivx(510);
  int ndivy(510);
  float markerSize(0.);
  float titleOffset(1.);

  float r0_ = 1.;
  float dr_ = 0.3;
  if( use_chi )
    {
      r0_ = 0.;
      dr_ = 7.5;
      //dr_ = 3.0;
    }

  // canvas name
  TString cname("");
  TString ctitle;

  // legend position and scale;
  float xl_  = 0.;
  float yl_  = 0.; 	   
  float scalel_ = 0.0;

  {
    if( logScale )
      //      fname += "Zmumu_40-200_36pb";
      fname += "Zmusta_36pb";
    else
      fname += "Zmusta_36pb";

    if( logScale )
      {
	lineWidth1 = 1;
	lineWidth2 = 1;
      }
    
    channels.push_back("Zmumu"); 
    hnames.push_back("   Z #rightarrow #mu^{+}#mu^{-}"); 
    type.push_back("Signal"); 
    
    bool revert(false);
    if( logScale )
      {
 	if( revert )
 	  {
 	    channels.push_back("EWK");          
 	    hnames.push_back("   EWK");                
	    type.push_back("EWK"); 
	    
 	    channels.push_back("tt");              
 	    hnames.push_back("   t#bar{t}");         
	    type.push_back("ttbar"); 

	     	    channels.push_back("QCD");              
	     	    hnames.push_back("   QCD");              
	    	    type.push_back("QCD"); 
 	  }
 	else
 	  {
 	    channels.push_back("EWK");          
 	    hnames.push_back("   EWK");                
	    type.push_back("EWK"); 
	    
 	    channels.push_back("tt");              
 	    hnames.push_back("   t#bar{t}");         
	    type.push_back("ttbar"); 
	    
	    channels.push_back("QCD");              
	     	    hnames.push_back("   QCD");              
	    	    type.push_back("QCD"); 	  
	      
 	  }
       }
    
    if( !logScale )
      {
	// lin scale
	xmin_ = 60;
	xmax_ = 120;
	ymin_ = 0.01;
	ymax_ = 2100;

  }
    else
      {	
	// log scale
	xmin_ = 40;
	xmax_ = 200;
	yminl_ = 0.08;
	ymaxl_ = 3000;

      }

    xtitle = "M(#mu^{+}#mu^{-})    [GeV]";
    ytitle = "number of events /";    


    ndivx = 504;
    if( logScale )
      {
	ytitle += "5 GeV";
	ndivy = 510;
      }
    else
      {
	ytitle += " GeV";
	ndivy = 506;
      }
    
    if( logScale )
      {
	markerSize = 0.48;
      }
    else
      {	
	markerSize = 0.75;
      }
    
    cname += "Zmusta";
    ctitle = "Z to mu sta analysis";
    
    if( logScale )
      {
	xl_ = 0.60;
	yl_ = 0.50;
	scalel_ = 0.065;
      }
    else
      {
	xl_ = 0.22;
	yl_ = 0.50;
	scalel_ = 0.072;
      }
  }

  if( logScale ) cname += "MuSta_log";
  else           cname += "MuStaNotInThePAPER_lin";

  //Open the root file containing histograms and graphs
  fname += ".root";
  TFile* f_ = TFile::Open(fname,"READ");

  TCanvas* c_ = new TCanvas(cname,ctitle,300,300,479,510);
  c_->SetLeftMargin(  87./479 );
  c_->SetRightMargin( 42./479 );
  c_->SetTopMargin(  30./510 );
  c_->SetBottomMargin( 80./510 ); 
  c_->SetFillColor(0);
  c_->SetTickx(1);
  c_->SetTicky(1);
  c_->SetFrameFillStyle(0);
  c_->SetFrameLineWidth(2);
  c_->SetFrameBorderMode(0);
  Double_t scale = 4;
  Double_t wbin = 42*scale;
  Double_t left  = 8*scale;
  Double_t right = 5*scale;
  Double_t h1 = 135*scale;
  Double_t h2 = 45*scale;
  Double_t top1 = 15*scale;
  Double_t bot1 = 3*scale;
  Double_t top2 = 3*scale;
  //  Double_t bot1 = 0*scale;
  //  Double_t top2 = 0*scale;
  Double_t bot2 = 80*scale;
  Double_t W = left + wbin + right;
  Double_t H = h1 + h2;
  Double_t s[2] = {1, h1/h2 };

  TPad* pad[2];
  pad[0] = new TPad( "top", "top", 
		     0, h2/H, 1, 1,
		     kWhite,0,0);
  pad[0]->SetLeftMargin(  left/W );
  pad[0]->SetRightMargin( right/W );
  pad[0]->SetTopMargin(  top1/H );
  pad[0]->SetBottomMargin( bot1/H );

  pad[1] = new TPad( "bottom", "bottom", 
		     0, 0, 1, h2/H,
		     kWhite,0,0);
  pad[1]->SetLeftMargin(  left/W );
  pad[1]->SetRightMargin( right/W );
  pad[1]->SetTopMargin(  top2/H );
  pad[1]->SetBottomMargin( bot2/H );
  pad[1]->SetGridy();

  for( int ii=0; ii<2; ii++ )
    {
      pad[ii]->SetFillColor(0);
      pad[ii]->SetTickx(1);
      pad[ii]->SetTicky(1);
      pad[ii]->SetFrameFillStyle(0);
      pad[ii]->SetFrameLineWidth(2);
      pad[ii]->SetFrameBorderMode(0);
      pad[ii]->SetFrameFillStyle(0);
      pad[ii]->SetFrameLineWidth(2);
      pad[ii]->SetFrameBorderMode(0);
    }

  // a dummy histogram with the correct x axis
  // Warning: setTDRstyle() must be called before
  TH1F* h_= new TH1F( "bidon", "bidon", nbin_, xmin_, xmax_ );
  TAxis* ax_ = h_->GetXaxis();
  TAxis* ay_ = h_->GetYaxis();

  ax_->SetTitle(xtitle);
  ax_->CenterTitle();
  ax_->SetTitleOffset(1.0);
  ax_->SetNdivisions(ndivx);

  ay_->SetTitle(ytitle);
  ay_->CenterTitle();
  ay_->SetNdivisions(ndivy);
  ay_->SetTitleOffset(titleOffset);
  ay_->SetLabelOffset(0.015);

  // fetch histograms and dress them
  vector<TH1F*> histos;

  size_t nChan=channels.size();   
  for( size_t ii=0;ii<nChan;ii++)
    {
      TH1F* tmp = (TH1F*)f_->Get(channels[ii]);      
      tmp->SetFillColor( fillColor_[type[ii]] );
      tmp->SetLineColor( lineColor_[type[ii]] );
      tmp->SetLineWidth( lineWidth2 );
      histos.push_back(tmp);
    }

  //
  // stack histograms
  //
  TH1* h_stack = (TH1*) histos[nChan-1]->Clone();
  h_stack -> Reset();

  TString stackName_ = TString("Mll");
  vector<TH1*> listOfStackedHists;
  for( size_t ii=0; ii<nChan; ii++ )
    {
      TH1* hh_ = (TH1*) histos[nChan-ii-1]->Clone();

      stackName_ += "_";
      stackName_ += hh_->GetName();	  	  

      TAxis* xaxis = h_stack->GetXaxis();
      for( int iBin=1; iBin<=xaxis->GetNbins(); iBin++ )
	{
	  hh_ -> AddBinContent( iBin, h_stack->GetBinContent( iBin ) );
	}        

      hh_->SetName( stackName_ );
      delete h_stack;
      h_stack = hh_;
      listOfStackedHists.push_back( (TH1*)hh_->Clone() );
    }
  delete h_stack;
  
  TH1* totalHisto = listOfStackedHists[nChan-1];

  // colors the stacked histogram
  totalHisto->SetLineColor( lineColor_["Signal"] );
  totalHisto->SetLineWidth( lineWidth1 );
  
  // The data points are presented as a TGraph 
  // - error bars indicate the Poisson confidence interval at 68%
  // - bins with zero entry are removed
  TH1* hdata = (TH1*) f_->Get("hdata");
  // hdata->Sumw2();
  //hdata->Rebin(2);
  RooHist* roohist;
  TGraphAsymmErrors* dataGraph;

  roohist = new RooHist((*hdata));

  int Nn0=0;
  vector<double> vY;
  vector<double> vX;
  vector<double > veY;
  vector<double > veX;
  vector<double> tmp(0,2);

  for(int ip=0;ip<roohist->GetN();ip++) 
    {
      double Y,X;
      roohist->GetPoint(ip,X,Y);
      
      if(Y!=0) 
	{
	  Nn0++;
	  
	  vY.push_back(Y);
	  vX.push_back(X);
	  veX.push_back( roohist->GetErrorXlow(ip) );
	  veX.push_back( roohist->GetErrorXhigh(ip) );
	  veY.push_back( roohist->GetErrorYlow(ip) );
	  veY.push_back( roohist->GetErrorYhigh(ip) );
	}
    }
  dataGraph=new TGraphAsymmErrors(Nn0);
  for(int ip=0;ip<Nn0;ip++) 
    {
      dataGraph->SetPoint(ip,vX[ip],vY[ip]);      
      dataGraph->SetPointError(ip,veX[ip*2],veX[ip*2+1],veY[ip*2],veY[ip*2+1]);
    }
  dataGraph->SetName("data");

  dataGraph->SetMarkerStyle(kFullCircle);
  dataGraph->SetMarkerColor(kBlack);
  dataGraph->SetMarkerSize(markerSize);

  TGraph* dummyGraph = (TGraph*) dataGraph->Clone("dummyGraph");
  dummyGraph->SetLineColor(0);
  dummyGraph->SetMarkerSize(1.5*markerSize);

  // Remove the horizontal bars (at Michael's request)
  double x_(0), y_(0);
  for( int ii=0; ii<dataGraph->GetN(); ii++ )
    {
      dataGraph->SetPointEXlow(ii,0);
      dataGraph->SetPointEXhigh(ii,0);
      dataGraph->GetPoint(ii,x_,y_ );
      if( y_==0 )
	{
	  dataGraph->RemovePoint( ii );
	  ii--;
	}	  
    }

  // get the ratio data/fit
  TGraphAsymmErrors* ratioGraph = (TGraphAsymmErrors*) dataGraph->Clone("ratio");
  TH1* hfit = totalHisto;
  for( int ii=0; ii<dataGraph->GetN(); ii++ )
    {
      dataGraph->GetPoint(ii,x_,y_ );
      ratioGraph->SetPointEYlow(ii,0);
      ratioGraph->SetPointEYhigh(ii,0);
      ratioGraph->SetPoint(ii,x_,0 );
      double eyl_ = dataGraph->GetErrorYlow(ii);
      double eyh_ = dataGraph->GetErrorYhigh(ii);
      int jj = hfit->FindBin(x_);
      float fit_ = hfit->GetBinContent( jj );
      if( fit_>0 )
	{
	  if( use_chi )
	    {
	      ratioGraph->SetPointEYlow(ii,eyl_/sqrt(fit_));
	      ratioGraph->SetPointEYhigh(ii,eyh_/sqrt(fit_));
	      ratioGraph->SetPoint(ii,x_,(y_-fit_)/sqrt(fit_) );
	    }
	  else
	    {
	      ratioGraph->SetPointEYlow(ii,eyl_/fit_);
	      ratioGraph->SetPointEYhigh(ii,eyh_/fit_);
	      ratioGraph->SetPoint(ii,x_,y_/fit_ );
	    }
	}
      //      cout << ii << " ratio=" << ratioGraph->GetY()[ii] 
      //       	   << "+" << ratioGraph->GetEYhigh()[ii] 
      //	   << "-" << ratioGraph->GetEYlow()[ii] << endl;
    }

  TH1* hratio_ = (TH1*) h_->Clone("hratio");
  ax_->SetLabelOffset(99);
  ax_->SetTitleOffset(99);

  //
  // now plotting
  //  
  c_->Draw();
  c_->cd();

  TPad* p_ = pad[0];
  p_->Draw();
  p_->cd();

  if( logScale )
    {
      p_->SetLogy(true);
    }
  else
    {
      p_->SetLogy(false);
    }

  if( !logScale )
    {
      h_->GetYaxis()->SetRangeUser(ymin_+0.001*(ymax_-ymin_),ymax_);
    }
  else
    {
      h_->GetYaxis()->SetRangeUser(yminl_,ymaxl_);
    }

  h_->Draw();

  float dxl_ = scalel_*3.5;
  float dyl_ = scalel_*1.8;
  if( logScale )
    {
      dxl_ = scalel_*4;
      dyl_ = scalel_*3.4;
    }
  TLegend* legend=new TLegend(xl_,yl_,xl_+dxl_,yl_+dyl_);
  legend->SetLineColor(0);
  legend->SetFillColor(0);
  legend->SetTextFont(42);
  legend->SetTextSize(0.048);
  
  legend->AddEntry(dummyGraph,"   data","pl");      
  if( logScale )
    {
      legend->AddEntry(dummyGraph,"       ","0");
    }
  for(size_t ii=0;ii<nChan;ii++) 
    {
      legend->AddEntry(histos[ii],hnames[ii],"f");
    }
  legend->Draw("same");

  totalHisto->Draw("same");

  for( size_t ii=0; ii<nChan; ii++ )
    {
      //  listOfStackedHists[nChan-ii-1]->Sumw2();   
      listOfStackedHists[nChan-ii-1]->Rebin(1.);
      listOfStackedHists[nChan-ii-1]->Scale(1.);
      listOfStackedHists[nChan-ii-1]->Draw("Same");
    }

  // draw the data points
  dataGraph->Draw("PE");

  // redraw axis
  p_->RedrawAxis();

  //lumi pad, cms prelim pad etc..
  {
    int txtFont = 42;  // bold is 62
    float txtSize1 = 0.055;
    float txtX1 = 0.91;
    float txtY1 = 0.935;

    float txtSize2 = 0.05;
    float txtX2 = 0.85;
    float txtY2 = 0.83;
    
    // TEST FOR THE NAME ZMT, ZMMNONISO, ZMS
    float txtSize3 = 0.055;
    float txtX3 = 0.3;
    float txtY3 = 0.935;

    TLatex latex;
    latex.SetNDC();
    latex.SetTextFont(txtFont);
    
    latex.SetTextSize(txtSize1);    
    latex.SetTextAlign(31); // align right
    latex.DrawLatex(txtX1,txtY1,"CMS");

    latex.SetTextAlign(31); // align right
    latex.SetTextSize(txtSize2);
    latex.DrawLatex(txtX2,txtY2,"36 pb^{-1}  at  #sqrt{s} = 7 TeV");

    latex.SetTextAlign(21); // align left???
    latex.SetTextSize(txtSize3);
    latex.DrawLatex(txtX3,txtY3,"global plus standalone muon");
  }

  c_->cd();
  
  p_ = pad[1];

  p_->Draw();

  p_->cd();

  TAxis* xratio_ = hratio_->GetXaxis();
  TAxis* yratio_ = hratio_->GetYaxis();

  yratio_->SetRangeUser(r0_-0.9999*dr_,r0_+0.9999*dr_);
  yratio_->SetLabelSize( s[1]*yratio_->GetLabelSize() );
  yratio_->SetTitleSize( s[1]*yratio_->GetTitleSize() );
  yratio_->SetLabelOffset( yratio_->GetLabelOffset() );
  yratio_->SetTitleOffset( yratio_->GetTitleOffset()/s[1] );
  if( use_chi )
    {
      yratio_->SetTitle("#chi");
      yratio_->SetNdivisions(4);
    }
  else
    {
      yratio_->SetTitle("data/fit");
      yratio_->SetNdivisions(3);
    }

  xratio_->SetLabelSize( s[1]*xratio_->GetLabelSize() );
  xratio_->SetTitleSize( s[1]*xratio_->GetTitleSize() );
  xratio_->SetTitleOffset( 1.0 );
  xratio_->CenterTitle();
  xratio_->SetLabelOffset( xratio_->GetLabelOffset()*s[1] );
  xratio_->SetTickLength( xratio_->GetTickLength()*s[1] );

  hratio_->Draw();
  ratioGraph->SetMarkerSize( ratioGraph->GetMarkerSize()*1. );
  ratioGraph->SetLineColor( kBlack );

  ratioGraph->SetMarkerColor( kGray+2 );
  ratioGraph->SetMarkerStyle( kFullCircle );
  ratioGraph->DrawClone("PE");
  ratioGraph->SetMarkerColor( kBlack );
  ratioGraph->SetMarkerStyle( kOpenCircle );
  ratioGraph->DrawClone("PE");

  p_->RedrawAxis();

  c_->cd();

  return c_;
}
Example #29
0
void plotter::draw_delta_comparison( TH1* total_, TH1* stat_, std::vector<TH1*> MODEL_DELTA, std::vector<TString> UncertNames, TString category, TString file_name){
  TH1* total = (TH1*) total_->Clone();
  TH1* stat = (TH1*) stat_->Clone();
  std::vector<TH1*> delta;
  for(unsigned int i=0; i<MODEL_DELTA.size(); i++){
    delta.push_back( (TH1*) MODEL_DELTA[i]->Clone() );
  }

  TCanvas *c= new TCanvas("c","",600,600);
  gPad->SetLeftMargin(0.15);
  total->SetTitle("");
  total->GetXaxis()->SetTitle("Leading-jet mass [GeV]");
  total->GetYaxis()->SetTitle("relative uncertainty [%]");
  total->GetYaxis()->SetTitleOffset(1.5);
  total->GetYaxis()->SetNdivisions(505);
  total->GetYaxis()->SetRangeUser(0, 100);
  total->SetFillColor(13);
  total->SetFillStyle(3144);
  total->SetLineColor(13);
  total->SetMarkerStyle(-1);
  total->Draw("HIST");
  stat->SetLineColor(kBlack);
  stat->SetLineWidth(4);
  stat->SetMarkerStyle(0);
  stat->Draw("B SAME");

  Color_t col[] = {kRed-4, kAzure+7, kGreen, 798, kBlue, kOrange-3, kMagenta, kYellow, kAzure, 14, kRed+5, kGreen-8};
  int i=0;
  for(auto hist: delta){
    gPad->SetLeftMargin(0.15);
    hist->SetLineColor(col[i]);
    hist->SetLineWidth(4);
    hist->SetMarkerStyle(0);
    hist->Draw("B SAME");
    i++;
  }

  // LEGEND
  TLegend *leg = new TLegend(0.4,0.6,0.88,0.88);
  leg->SetFillStyle(0);
  leg->SetNColumns(2);
  if(category == "exp")        leg->AddEntry(total, "stat #oplus exp. sys", "f");
  else if(category == "model") leg->AddEntry(total, "stat #oplus model sys", "f");
  leg->AddEntry(stat, "stat", "l");
  for(unsigned int i=0; i<delta.size(); i++){
    if      (UncertNames[i] == "mass")      leg->AddEntry(delta[i],"choice of m_{t}","l");
    else if (UncertNames[i] == "stat")      leg->AddEntry(delta[i],"statistics","l");
    else if (UncertNames[i] == "b-tagging") leg->AddEntry(delta[i],"b tagging","l");
    else if (UncertNames[i] == "pile-up")   leg->AddEntry(delta[i],"pileup","l");
    else if (UncertNames[i] == "jec")       leg->AddEntry(delta[i],"jet energy scale","l");
    else if (UncertNames[i] == "jer")       leg->AddEntry(delta[i],"jet energy resolution","l");
    else if (UncertNames[i] == "cor")       leg->AddEntry(delta[i],"XCone jet correction","l");
    else if (UncertNames[i] == "MuTrigger") leg->AddEntry(delta[i],"muon trigger","l");
    else if (UncertNames[i] == "MuID")      leg->AddEntry(delta[i],"muon ID","l");
    else if (UncertNames[i] == "ElTrigger") leg->AddEntry(delta[i],"electron trigger","l");
    else if (UncertNames[i] == "ElID")      leg->AddEntry(delta[i],"electron ID","l");
    else if (UncertNames[i] == "ElReco")    leg->AddEntry(delta[i],"electron reconstruction","l");
    else if (UncertNames[i] == "hdamp")     leg->AddEntry(delta[i],"h_{damp}","l");
    else                                    leg->AddEntry(delta[i],UncertNames[i],"l");
  }
  leg->Draw();

  gPad->RedrawAxis();
  c->SaveAs(directory + file_name + ".pdf");
  delete c;
}
Example #30
-1
// -----------------------------------------------------------------------------
//
TH1* getHisto( TString path,
         TString nameHist,
         TString nameFile,
         TString Dirname,
         int rebin ) {
  TString name = path + nameFile;
  TFile* file =  new TFile(name);
  TDirectory* dir = (TDirectory*)file->Get(Dirname);
  TH1* hist = (TH1*)file->Get(nameHist);
  if (!hist) {
    std::cout << " name: " << nameHist
        << " file: " << nameFile
        << " dir: " <<  Dirname
        << std::endl;
    abort();

  }
  hist->SetLineWidth(1);
  if ( rebin > 0 ) { hist->Rebin(rebin); }
  hist->GetXaxis()->SetTitleSize(0.055);
  hist->GetYaxis()->SetTitleSize(0.055);
  hist->GetXaxis()->SetLabelSize(0.05);
  hist->GetYaxis()->SetLabelSize(0.05);
  hist->SetStats(kFALSE);
  return hist;
}