Beispiel #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 );
}
Beispiel #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();
}
Beispiel #3
0
// Draw pT balance plots
void PlotOnCanvas(TH1& genHist, TH1& recoHist, TString plotname) {


  TLine* line1 = new TLine(1.0, genHist.GetMinimum(), 
			   1.0, genHist.GetMaximum());
  line1->SetLineColor(4);
  line1->SetLineWidth(2);

  TCanvas canvas("canvas", "", 880, 600);
  gStyle->SetOptStat(0);
  genHist.Draw("hist");
  line1->Draw();
  recoHist.Draw("same");
  recoHist.Draw("HIST same");
  leg_hist = new TLegend(0.6,0.65,0.85,0.85);
  leg_hist->AddEntry(&genHist,"Generator level","l");
  leg_hist->AddEntry(&recoHist,"Calorimeter level","l");
  leg_hist->SetFillColor(0);
  leg_hist->Draw();
  canvas.SaveAs(plotname+TString(".eps"));
  canvas.SaveAs(plotname+TString(".gif"));
  canvas.SaveAs(plotname+TString(".root"));

  delete line1;
  delete leg_hist;
}
Beispiel #4
0
void Test(TH1* h, TH1* s, const char* test)
{
   // Check that hist and sparse are equal, print the test result
   cout << test << ": ";
   
   // What exactly is "equal"?
   // Define it as  the max of 1/1000 of the "amplitude" of the 
   // original hist, or 1E-4, whatever is larger.
   Double_t epsilon = 1E-4;
   Double_t diffH = h->GetMaximum() - h->GetMinimum();
   if (diffH < 0.) diffH = -diffH;
   if (diffH / 1000. > epsilon)
      epsilon = diffH / 1000.;

   TH1* diff = (TH1*)s->Clone("diff");
   diff->Add(h, -1);
   Double_t max = diff->GetMaximum();
   Double_t min = diff->GetMinimum();
   if (max < -min) max = -min;
   if (max < epsilon) cout << "SUCCESS";
   else {
      cout << "FAIL: delta=" << max;
      TCanvas* c = new TCanvas(test, test);
      c->Divide(1,3);
      c->cd(1); h->Draw();
      c->cd(2); s->Draw();
      c->cd(3); diff->Draw();
      TFile f("runsparse.root", "UPDATE");
      c->Write();
      delete c;
   }
   cout <<endl;
   delete diff;
}
Beispiel #5
0
TH1F *stabilityHist(TGraphErrors *g_data, double& y_err_mean){
  //------------------------------
  Double_t *Y=g_data->GetY();
  Double_t *EY = g_data->GetEY();

  TH1 *obj = (TH1*) g_data->GetYaxis()->GetParent();
  TH1F *hist_corr = new TH1F("hist_"+TString(g_data->GetName()),"",
			     g_data->GetN(), obj->GetMinimum(), obj->GetMaximum());
  hist_corr->GetXaxis()->SetLabelSize(0);
  hist_corr->GetYaxis()->SetLabelSize(0);
  for(int i =0; i < g_data->GetN(); i++){
    hist_corr -> Fill(Y[i]);
    y_err_mean+=EY[i];
  }
  y_err_mean/=g_data->GetN();
  return hist_corr;
}
Beispiel #6
0
  //____________________________________________________________________
  TH1* One(TDirectory* newDir, TDirectory* oldDir, Double_t c1, Double_t c2)
  {
    TString name;
    name.Form("cent%03dd%02d_%03dd%02d",
	      Int_t(c1), Int_t(c1*100)%100,
	      Int_t(c2), Int_t(c2*100)%100);
    TDirectory* newSubDir = GetD(newDir, name);
    TDirectory* oldSubDir = GetD(oldDir, name);
    if (!newSubDir || !oldSubDir) return 0;
    Int_t newDim = 0;
    if      (TString(newDir->GetName()).Contains("etaipz")) newDim = 3;
    else if (TString(newDir->GetName()).Contains("eta"))    newDim = 2;
    else if (TString(newDir->GetName()).Contains("const"))  newDim = 1;
    Int_t oldDim = 0;
    if      (TString(oldDir->GetName()).Contains("etaipz")) oldDim = 3;
    else if (TString(oldDir->GetName()).Contains("eta"))    oldDim = 2;
    else if (TString(oldDir->GetName()).Contains("const"))  oldDim = 1;

    TDirectory* newSubSubDir = GetD(newSubDir, Form("results%dd",newDim));
    TDirectory* oldSubSubDir = GetD(oldSubDir, Form("results%dd",oldDim));
    if (!newSubSubDir || !oldSubSubDir) return 0;

    TH1* newRes = GetH1(newSubSubDir, "result");
    TH1* oldRes = GetH1(oldSubSubDir, "result");
    if (!newRes || !oldRes) return 0;

    TH1* ratio = static_cast<TH1*>(newRes->Clone(name));
    ratio->SetDirectory(0);
    ratio->SetTitle(Form("%5.1f - %5.1f%%", c1, c2));
    ratio->SetYTitle("New / Old");
    ratio->Divide(oldRes);
    fMin = TMath::Min(fMin, ratio->GetMinimum());
    fMax = TMath::Max(fMax, ratio->GetMaximum());

    Printf("Calculated %s/%s", newDir->GetName(), oldDir->GetName());
    if (!fLegend) return ratio;

    
    TLegendEntry* e =
      fLegend->AddEntry("", Form("%3.0f - %3.0f%%", c1, c2), "f");
    e->SetFillStyle(1001);
    e->SetFillColor(ratio->GetMarkerColor());
  
    return ratio;
  }
Beispiel #7
0
void pidHistogramMaker::distributionReport( string pType ){

	uint nBinsPt = ptBins.size() - 1;
	string rName = speciesName( pType, 0 );

	taskProgress tp( pType + " distribution report", nBinsPt );

	book->cd( "tof" );
	for ( uint i = 0; i < nBinsPt; i ++ ){

		tp.showProgress( i );

		// momentum value used for finding nice range
		double p = ptBins[ i ];
		double p2 = ptBins[ i + 1 ];
		double avgP = 0.2;
		avgP = (ptBins[ i ] + ptBins[ i + 1])/2.0;
		

		string name = speciesName( pType, 0, i, 0 );

		book->cd( "dedx_tof" );
		TH2 * pTof = book->get2D( name );
		book->cd( "scratch" );
		TH2 * pDedx = (TH2*)pTof->Clone( "pDedx__" );

		// start a new page on the report file
		pReport[ rName ]->newPage( 2, 2 );


		// get information on plot ranges
		double tofLow, tofHigh, dedxLow, dedxHigh;
		autoViewport( pType, p, &tofLow, &tofHigh, &dedxLow, &dedxHigh, tofPadding, dedxPadding, tofScalePadding, dedxScalePadding );
		
		if ( true ) {	// show the tof proj

			string title = "#beta^{-1} : " + ts(ptBins[ i ], 4) + " < pT < " + ts(ptBins[i+1], 4);
			vector<string> others = otherSpecies( pType );
			vector< double > tofMean = enhanceTof( pType, others, avgP );
			vector< double > dedxMean = enhanceDedx( pType, others, avgP );
			pReport[ rName ]->cd( 1, 1 );
			//hdt->GetXaxis()->SetRangeUser( -.06, .06 );
			// Make the all tof tracks histogram
			string hName = sTofName( pType, 0, i );
			book->cd( "scratch" );
			TH1* hTof = (TH1D*)pTof->ProjectionY( "_py" );
			book->cd( "tof" );
			book->add( hName, (TH1*)hTof->Clone( hName.c_str() )  );
			book->style( hName )->set( "style.tof" )
			 	->set( "title", title )->draw();

			TLine * l1 = new TLine( tofMean[ 0 ], hTof->GetMinimum(), tofMean[ 0 ], hTof->GetMaximum() );
			l1->Draw();
			TLine * l2 = new TLine( tofMean[ 1 ], hTof->GetMinimum(), tofMean[ 1 ], hTof->GetMaximum() );
			l2->Draw();

			pReport[ rName ]->cd( 2, 1 );
			pTof->GetXaxis()->SetRangeUser( -.06, .06 );
			// Make the all tof tracks histogram
			hName = sTofName( pType, 0, i, 0, pType );
			book->cd( "scratch" );
			hTof = (TH1D*)pTof->ProjectionY( "_py" );
			book->cd( "tof" );
			book->add( hName, (TH1*)hTof->Clone( hName.c_str() )  );
			book->style( hName )->set( "style.tof" )
			 	->set( "title", title + " " + pType + " enhanced" )->draw();

			for ( int j = 0; j < dedxMean.size(); j++ ){

				pReport[ rName ]->cd( j+1, 2 );
				pTof->GetXaxis()->SetRangeUser( dedxMean[j]-0.06, dedxMean[j]+0.06 );
				// Make the all tof tracks histogram
				hName = sTofName( pType, 0, i, 0, others[ j ] );
				book->cd( "scratch" );
				hTof = (TH1D*)pTof->ProjectionY( "_py" );
				book->cd( "tof" ); 
				book->add( hName, (TH1*)hTof->Clone( hName.c_str() )  );
				book->style( hName )->set( "style.tof" )
				 	->set( "title", title + " " + others[ j ] + " enhanced" )->draw();
			}

		}

		pReport[ rName ]->savePage();
		pReport[ rName ]->newPage( 2, 2 );


		if ( true ) {	// show the dedx proj

			string title = "dEdx : " + ts(ptBins[ i ], 4) + " < pT < " + ts(ptBins[i+1], 4);
			pTof->GetXaxis()->SetRange( 1, pTof->GetXaxis()->GetNbins() );
			pTof->GetYaxis()->SetRange( 1, pTof->GetYaxis()->GetNbins() );

			vector<string> others = otherSpecies( pType );
			vector< double > tofMean = enhanceTof( pType, others, avgP );
			vector< double > dedxMean = enhanceDedx( pType, others, avgP );
			pReport[ rName ]->cd( 1, 1 );
			
			// Make the all dedx tracks histogram
			string hName = sDedxName( pType, 0, i );
			book->cd( "scratch" );
			TH1* hDedx = (TH1D*)pTof->ProjectionX( "_px" );
			book->cd( "dedx" );
			book->add( hName, (TH1*)hDedx->Clone( hName.c_str() )  );
			book->style( hName )->set( "style.dedx" )
			 	->set( "title", title )->draw();

			TLine * l1 = new TLine( dedxMean[ 0 ], hDedx->GetMinimum(), dedxMean[ 0 ], hDedx->GetMaximum() );
			l1->Draw();
			TLine * l2 = new TLine( dedxMean[ 1 ], hDedx->GetMinimum(), dedxMean[ 1 ], hDedx->GetMaximum() );
			l2->Draw();

			pReport[ rName ]->cd( 2, 1 );
			pTof->GetYaxis()->SetRangeUser( -.012, .012 );
			// Make the all tof tracks histogram
			hName = sDedxName( pType, 0, i, 0, pType );
			book->cd( "scratch" );
			hDedx = (TH1D*)pTof->ProjectionX( "_px" );
			book->cd( "dedx" );
			book->add( hName, (TH1*)hDedx->Clone( hName.c_str() )  );
			book->style( hName )->set( "style.dedx" )
			 	->set( "title", title + " " + pType + " enhanced" )->draw();
			
			for ( int j = 0; j < dedxMean.size(); j++ ){

				pReport[ rName ]->cd( j+1, 2 );
				pTof->GetYaxis()->SetRangeUser( tofMean[j]-0.012, tofMean[j]+0.012 );
				// Make the all tof tracks histogram
				hName = sDedxName( pType, 0, i, 0, others[ j ] );
				book->cd( "scratch" );
				hDedx = (TH1D*)pTof->ProjectionX( "_px" );
				book->cd( "dedx" ); 
				book->add( hName, (TH1*)hDedx->Clone( hName.c_str() )  );
				book->style( hName )->set( "style.dedx" )
				 	->set( "title", title + " " + others[ j ] + " enhanced" )->draw();
			}

		}

		pReport[ rName ]->savePage();
		
	}



}
Beispiel #8
0
void proc_pileup(const AliVdMMetaData& vdmMetaData,
                 AliVdMScanData& allData,
                 const char* classAC,
                 const char* classAnotC,
                 const char* classCnotA,
                 const std::vector<Double_t>& par0)
{
  typedef std::map<Short_t, TGraphErrors> map_t; // BCID -> TGraphErrors
  map_t gAnotC, gCnotA;  // one-arm/two-arm ratios

  // (1) fill one-arm/two-arm ratio graphs for all BCIDs
  for (Int_t iScan=0; iScan<4; ++iScan) {
    AliVdMTree& vtAND   = allData.GetMap(iScan)[classAC];
    AliVdMTree& vtAnotC = allData.GetMap(iScan)[classAnotC];
    AliVdMTree& vtCnotA = allData.GetMap(iScan)[classCnotA];
    vtAND.Zip3([&gAnotC,&gCnotA](const AliVdMTree::DefaultBranchData& d,
                                 AliVdMTree::branchMap_t& mapAC,
                                 AliVdMTree::branchMap_t& mapAnotC,
                                 AliVdMTree::branchMap_t& mapCnotA)
               {
                 AliVdMTree::ValErr v1 = mapAnotC["rate"];
                 v1 /= mapAC["rate"];
                 // v1 /= mapAC["relBkgd"];
                 v1 *= mapAnotC["relBkgd"];
                 if (!v1.isInf() && v1.val()) {
                   const Int_t m1 = gAnotC[d.BCID()].GetN();
                   gAnotC[d.BCID()].SetPoint     (m1, mapAC["mu"].val(), v1.val());
                   gAnotC[d.BCID()].SetPointError(m1, mapAC["mu"].err(), v1.err());
                 }
                 AliVdMTree::ValErr v2 = mapCnotA["rate"];
                 v2 /= mapAC["rate"];
                 // v2 /= mapAC["relBkgd"];
                 v2 *= mapCnotA["relBkgd"];
                 if (!v2.isInf() && v2.val()) {
                   const Int_t m2 = gCnotA[d.BCID()].GetN();
                   gCnotA[d.BCID()].SetPoint     (m2, mapAC["mu"].val(), v2.val());
                   gCnotA[d.BCID()].SetPointError(m2, mapAC["mu"].err(), v2.err());
                 }
               },
               vtAnotC, vtCnotA);
  }

  // (2) fit model
  AliVdMPileup pileupModel;

  TString pn = TString::Format("pileup_%s.pdf", classAC);
  TCanvas *c1 = new TCanvas;
  c1->SaveAs(pn+"[");

  const AliTriggerBCMask& bcMask = vdmMetaData.GetTriggerBCMask();
  const Int_t             nBCs   = bcMask.GetNUnmaskedBCs();

  TH1 *hPar[5] = {
    SetAttr(new TH1D("hrA",      ";BCID;r_{A}",           nBCs,0,nBCs), kRed),
    SetAttr(new TH1D("hrC",      ";BCID;r_{C}",           nBCs,0,nBCs), kBlue),
    SetAttr(new TH1D("hbkgdA",   ";BCID;bkgd_{A}",        nBCs,0,nBCs), kRed),
    SetAttr(new TH1D("hbkgdC",   ";BCID;bkgd_{C}",        nBCs,0,nBCs), kBlue),
    SetAttr(new TH1D("hChi2NDF", ";BCID;#chi^{2}/n.d.f.", nBCs,0,nBCs), kBlue)
  };

  for (Int_t bc=0, counter=0; bc<3564; ++bc) {
    if (bcMask.GetMask(bc))
      continue;

    const TString binLabel = TString::Format("%d", bc);
    for (Int_t i=0; i<5; ++i)
      hPar[i]->GetXaxis()->SetBinLabel(1+counter, binLabel);

    c1->Clear();
    c1->SetLogx();
    c1->SetLogy();
    TH1 *hf = c1->DrawFrame(1e-6, 0.01, 0.5, 20);
    hf->SetTitle(TString::Format("BCID=%d %s;two-arm #mu;one-arm/two-arm", bc, classAC));
    pileupModel.DoFit(&gAnotC[bc], &gCnotA[bc], &par0[0]);

    SetAttr(&gAnotC[bc], kBlue);
    SetAttr(&gCnotA[bc], kRed);
    gAnotC[bc].Draw("PE");
    gCnotA[bc].Draw("PE");

    TF1 *fAnotC = SetAttr(new TF1("fAnotC", &pileupModel, &AliVdMPileup::fcnAnotC, 1e-6, 0.5, 5), kBlue);
    fAnotC->SetParameters(pileupModel.GetPar());
    fAnotC->SetNpx(1000);
    fAnotC->Draw("same");

    TF1 *fCnotA = SetAttr(new TF1("fCnotA", &pileupModel, &AliVdMPileup::fcnCnotA, 1e-6, 0.5, 5), kRed);
    fCnotA->SetParameters(pileupModel.GetPar());
    fCnotA->SetNpx(1000);
    fCnotA->Draw("same");

    TLegend *leg = new TLegend(0.6, 0.75, 0.9, 0.9);
    leg->AddEntry(&gCnotA[bc], "AnotC/AandC", "PEL");
    leg->AddEntry(&gAnotC[bc], "CnotA/AandC", "PEL");
    leg->Draw();

    TPaveText *pt = new TPaveText(0.6, 0.4, 0.9, 0.7, "NDC NB");
    pt->SetFillStyle(0);
    pt->AddText(TString::Format("#chi^{2}/n.d.f = %.0f/%.0f = %.2f", pileupModel.GetChi2(), pileupModel.GetNDF(), pileupModel.GetChi2()/pileupModel.GetNDF()));
    {
      double curval,err, lowlim, uplim;
      int iuint;
      TString name;
      for (Int_t ivar=0; ivar<4; ++ivar) {
        gMinuit->mnpout(ivar, name, curval, err, lowlim, uplim,iuint);
        hPar[ivar]->SetBinContent(1+counter, curval);
        hPar[ivar]->SetBinError(1+counter, err);
        if (ivar==0) {
          hf->SetMinimum(0.5*curval);
        }
        if (ivar==1) {
          hf->SetMinimum(TMath::Min(hf->GetMinimum(), 0.5*curval));
        }
        if (ivar < 2)
          pt->AddText(TString::Format("%s = %.4f#pm%.4f", name.Data(), curval, err));
        else
          pt->AddText(TString::Format("%s = %.1e#pm%.1e", name.Data(), curval, err));
        pt->GetLine(1+ivar)->SetTextColor(ivar%2 ? kRed : kBlue);
      }
      hPar[4]->SetBinContent(1+counter, pileupModel.GetChi2()/pileupModel.GetNDF());
    }
    pt->Draw();
    c1->SaveAs(pn);
    Printf("%f / %f", pileupModel.GetChi2(), pileupModel.GetNDF());
    ++counter;
  }
  gStyle->SetOptStat("n");
  gStyle->SetOptFit(111);
  TCanvas *c2 = new TCanvas;
  for (Int_t i=0; i<4; ++i) {
    FitPol0(hPar[i])->Draw();
    c2->SaveAs(pn);
  }
  hPar[4]->SetMinimum(0);
  hPar[4]->Draw();
  c2->SaveAs(pn+")");
}
Beispiel #9
0
void  drawPlots(canvasSet_t& cs,bool savePlots2file)
{
  wCanvas_t *wc0 = cs.canvases[0];
  unsigned npads = wc0->npadsx*wc0->npadsy;
  unsigned npadsall = cs.ncanvases*npads;

  if (!npads) {
    if (gl_verbose) cout << "Nothing to draw, guess I'm done." << endl;
    return; // no pads to draw on.

  } else if (!wc0->pads.size()) {

    /********************************************************
     * CHECK MULTIPAD OPTION, ASSIGN HISTOS TO PADS/CANVASES
     ********************************************************/

    if (wc0->multipads.size()) {
      npadsall = assignHistos2Multipad(cs);
    } else {
      cerr << "npads>0, but no pad specs supplied, exiting." << endl;
      return; // no pads to draw on.
    }
  } else if (cs.ncanvases>1) {
    npadsall = assignPads2Canvases(cs);
  } else {
    npadsall = std::min(npadsall,(unsigned)wc0->pads.size());
  }

  wc0->c1->cd();

  if (gl_verbose)
    cout << "Drawing on " << npadsall << " pad(s)" << endl;

  wLegend_t *wleg = NULL;

  /***************************************************
   * LOOP OVER PADS...
   ***************************************************/

  //vector<vector<string> >::const_iterator it;
  for (unsigned ipad = 0; ipad< npadsall; ipad++) {

    if (gl_verbose) cout << "Drawing pad# " << ipad+1 << endl;

    unsigned ipadc =  ipad % npads;
    unsigned cnum  = (ipad / npads) + 1;

    wCanvas_t *wc = cs.canvases[cnum-1];

    if (!ipadc) {
      if (cnum-1) { // first canvas already created
	wc->c1 = new TCanvas(wc->title.c_str(),wc->title.c_str(),
			     wc->padxdim*wc->npadsx,
			     wc->padydim*wc->npadsy);
	float left = wc->leftmargin;
	float bot  = wc->bottommargin;
	float rhgt = 1-wc->rightmargin;
	float top  = 1-wc->topmargin;
	wc->motherpad = new TPad("mother","",left,bot,rhgt,top);
	wc->c1->SetFillColor(wc->fillcolor);
	wc->motherpad->SetFillColor(wc->fillcolor);
	wc->motherpad->Draw();
	wc->motherpad->cd();
	wc->motherpad->Divide(wc->npadsx,wc->npadsy); // , wc->padxmargin,wc->padymargin);
      }

      /***************************************************
       * CHECK FOR LATEX OBJECTS ON THE CANVAS
       ***************************************************/
      
      wc->c1->cd();
      for (unsigned j=0; j<wc->latex_ids.size(); j++) {
	string& lid = wc->latex_ids[j];
	map<string,TLatex *>::const_iterator it = glmap_id2latex.find(lid);
	if (it == glmap_id2latex.end()) {
	  cerr << "ERROR: latex id " << lid << " never defined in layout" << endl;
	  exit (-1);
	}
	TLatex *ltx = it->second;
	ltx->Draw();
	wc->c1->Update();
      }
    }

    wPad_t *& wp = wc->pads[ipadc];
    wp->vp = wc->motherpad->cd(ipadc+1);

    if (!wp->histo_ids.size() &&
	!wp->stack_ids.size() &&
	!wp->graph_ids.size() &&
	!wp->macro_ids.size()) {
      cerr << "ERROR: pad #" << ipadc+1 << " has no ids defined for it";
      cerr << ", continuing to the next" << endl;
      continue;
    }


#if 0
    /***************************************************
     * Draw the frame first:
     * (Fix up frame since it can't be auto-scaled:)
     ***************************************************/
    string& hid0 = wp->histo_ids[0];
    map<string,wTH1 *>::const_iterator it = glmap_id2histo.find(hid0);
    if (it == glmap_id2histo.end()) {
      cerr << "ERROR: id0 " << hid0 << " never defined in layout" << endl;
      return;
    }
    wTH1 *myHisto = it->second;
    TH1  *h = myHisto->histo();

    if (wp->hframe->histo()->GetXaxis()->GetXmin() <=
	wp->hframe->histo()->GetXaxis()->GetXmax())
      wp->hframe->histo()->GetXaxis()->SetRangeUser(h->GetXaxis()->GetXmin(),
						    h->GetXaxis()->GetXmax());
    if (wp->hframe->histo()->GetYaxis()->GetXmin() <= 
	wp->hframe->histo()->GetYaxis()->GetXmax())
      wp->hframe->histo()->GetYaxis()->SetRangeUser(h->GetYaxis()->GetXmin(),
						    h->GetYaxis()->GetXmax());

    wp->hframe->SetStats(0);
    //wp->hframe->Draw("AXIS");
#endif

    /***************************************************
     * Check for external macros to run on the pad
     ***************************************************/
    for (size_t i=0; i<wp->macro_ids.size(); i++) {
      map<string,string>::const_iterator it = glmap_objpath2id.find(wp->macro_ids[i]);
      if (it != glmap_objpath2id.end()) {
	string path = it->second;
	int error;
	gROOT->Macro(path.c_str(), &error, kTRUE); // update current pad
	if (error) {
	  static const char *errorstr[] = {
	    "kNoError","kRecoverable","kDangerous","kFatal","kProcessing" };
	  cerr << "ERROR: error returned from macro: " << errorstr[error] << endl;
	}
      } else {
	cerr << "ERROR: macro id " << wp->macro_ids[i];
	cerr << " never defined in layout" << endl;
      }
    }
    /***************************************************
     * Check for existence of a legend, create it
     ***************************************************/
    bool drawlegend = false;

    if (wp->legid.size()) {
      map<string,wLegend_t *>::const_iterator it=glmap_id2legend.find(wp->legid);
      if (it != glmap_id2legend.end()) {
	drawlegend = true;
	wleg = it->second;
      } else {
	cerr << "ERROR: legend id " << wp->legid;
	cerr << " never defined in layout" << endl;
      }
    } else {
      // Maybe gPad already *has* a legend from macros...
      TPave *testing = (TPave *)gPad->GetPrimitive("TPave");
      if (testing &&
	  !strcmp(testing->IsA()->GetName(),"TLegend")) {
	TLegend *pullTheOtherOne = (TLegend *)testing;
	if (gl_verbose) cout << "Found legend from macro" << endl;
	wleg = new wLegend_t();
	wleg->leg = pullTheOtherOne;
	drawlegend = true;
      }
    }

    /***************************************************
     * LOOP OVER STACKS DEFINED FOR PAD...
     ***************************************************/

    if (wp->stack_ids.size()) {
      wStack_t *ws=NULL;
      for (unsigned j = 0; j < wp->stack_ids.size(); j++) {
	string& sid = wp->stack_ids[j];
	map<string,wStack_t *>::const_iterator it = glmap_id2stack.find(sid);
	if (it == glmap_id2stack.end()) {
	  cerr << "ERROR: stack id " << sid << " never defined in layout" << endl;
	  exit (-1);
	}

	bool firstInPad = !j;

	ws = it->second;
	if (!ws) { cerr<< "find returned NULL stack pointer for " << sid << endl; continue; }

	// Add the histos in the stack to any legend that exists

	//
	if (drawlegend) {
	  for (size_t i=0; i<ws->v_histos.size(); i++) {
	    wTH1 *wh = ws->v_histos[i];
	    wh->ApplySavedStyle();
	    if(wh->GetLegendEntry().size())
	      wh->Add2Legend(wleg->leg);
	  }
	}

	string drawopt("");
	if (ws->sum->GetDrawOption().size()) {
	  drawopt = ws->sum->GetDrawOption();
	  cout << "drawopt stored with histo = " << drawopt << endl;
	}

	drawInPad(wp, ws, firstInPad, drawopt);

	wp->vp->Update();
      }
    } // stack loop

    /***************************************************
     * LOOP OVER HISTOS DEFINED FOR PAD...
     ***************************************************/

    for (unsigned j = 0; j < wp->histo_ids.size(); j++) {
      string& hid = wp->histo_ids[j];
      map<string,wTH1 *>::const_iterator it = glmap_id2histo.find(hid);
      if (it == glmap_id2histo.end()) {
	cerr << "ERROR: histo id " << hid << " never defined in layout" << endl;
	exit (-1);
      }

      wTH1 *myHisto = it->second;
      
      if (myHisto) {
	bool firstInPad = !j && !wp->stack_ids.size();
	if (gl_verbose) {
	  cout << "Drawing " << hid << " => ";
	  cout << myHisto->histo()->GetName() << endl;
	  cout << "firstInPad = " << firstInPad << endl;
	}
	drawInPad(wp,*myHisto,firstInPad);

	myHisto->DrawFits("same");
	if (drawlegend && myHisto->GetLegendEntry().size()) {
	  if (wleg->drawoption.size()) myHisto->SetDrawOption(wleg->drawoption);
	  myHisto->Add2Legend(wleg->leg);
	}
	if (myHisto->statsAreOn()) {
	  myHisto->DrawStats();
	  wp->vp->Update();
	}

	myHisto->ApplySavedStyle();
	wp->vp->Update();
      }
    } // histos loop

    /***************************************************
     * LOOP OVER HISTOS DEFINED FOR ALTERNATE Y-AXIS
     ***************************************************/

    Float_t rightmax=0.0,rightmin=0.0;
    Float_t scale=0.0;
    for (unsigned j = 0; j < wp->altyh_ids.size(); j++) {
      string& hid = wp->altyh_ids[j];
      map<string,wTH1 *>::const_iterator it = glmap_id2histo.find(hid);
      if (it == glmap_id2histo.end()) {
	cerr << "ERROR: histo id " << hid << " never defined in layout" << endl;
	exit (-1);
      }

      wTH1 *myHisto = it->second;
      TH1 *h = myHisto->histo();

      if (!j) {
	//scale second set of histos to the pad coordinates
	rightmin = h->GetMinimum();
	rightmax = 1.1*h->GetMaximum();
	scale    = gPad->GetUymax()/rightmax;
      }
      TH1 *scaled=(TH1 *)h->Clone(Form("%s_%d",h->GetName(),ipad));

      scaled->Scale(scale);
      scaled->Draw("same");
   
      //draw an axis on the right side
      TGaxis *axis = new TGaxis(gPad->GetUxmax(), gPad->GetUymin(),
				gPad->GetUxmax(), gPad->GetUymax(),
				rightmin,rightmax,505,"+L");
      axis->Draw();
      gPad->Update();
      if (drawlegend && myHisto->GetLegendEntry().size()) {
	if (wleg->drawoption.size()) myHisto->SetDrawOption(wleg->drawoption);
	myHisto->Add2Legend(wleg->leg);
      }
    }

    /***************************************************
     * LOOP OVER GRAPHS DEFINED FOR PAD...
     ***************************************************/
#if 0
    TMultiGraph *mg;
    if (graph_ids.size())
      mg = new TMultiGraph();
#endif
    for( unsigned j = 0; j < wp->graph_ids.size(); j++ ) {
      string& gid = wp->graph_ids[j];
      
      wGraph_t *wg   = findGraph(gid);

      bool firstInPad = !j && !wp->histo_ids.size() && !wp->macro_ids.size();
      if( firstInPad && wg->gr && wg->gr->IsA()==TGraph::Class() )
	wg->drawopt += string("A"); // no histos drawn, need to draw the frame ourselves.

      if( wg && wg->gr ) {
	// "pre-draw" in order to define the plot elements
	wg->gr->Draw(wg->drawopt.c_str());

	if (firstInPad) {
	  // Now we can set the axis attributes and range:
	  wg->gr->GetXaxis()->ImportAttributes(wg->xax);
	  wg->gr->GetYaxis()->ImportAttributes(wg->yax);

	  cout << wg->xax->GetXmin() << " " << wg->xax->GetXmax() << endl;
	  if( wg->xax->GetXmax()>wg->xax->GetXmin() )
	    wg->gr->GetXaxis()->SetLimits(wg->xax->GetXmin(),wg->xax->GetXmax());
	  if( wg->yax->GetXmax()>wg->yax->GetXmin() )
	    wg->gr->GetYaxis()->SetRangeUser(wg->yax->GetXmin(),wg->yax->GetXmax());
	}
	// draw for good
	drawInPad<TGraph>(wp,wg->gr,wg->drawopt.c_str(),firstInPad);

	wp->vp->Update();
	if( wg->fitfn ) 
	  wg->gr->Fit(wg->fitfn);
	if( drawlegend && wg->leglabel.size() )
	  wleg->leg->AddEntry(wg->gr,wg->leglabel.c_str(),wg->legdrawopt.c_str());
      }
      if( wg && wg->gr2d ) {
	drawInPad<TGraph2D>(wp,wg->gr2d,wg->drawopt.c_str(),firstInPad);

	if (firstInPad) {
	  // Now we can set the axis attributes and range:
	  wg->gr2d->GetXaxis()->ImportAttributes(wg->xax);
	  wg->gr2d->GetYaxis()->ImportAttributes(wg->yax);

	  cout << wg->xax->GetXmin() << " " << wg->xax->GetXmax() << endl;
	  if( wg->xax->GetXmax()>wg->xax->GetXmin() )
	    wg->gr2d->GetXaxis()->SetLimits(wg->xax->GetXmin(),wg->xax->GetXmax());
	  if( wg->yax->GetXmax()>wg->yax->GetXmin() )
	    wg->gr2d->GetYaxis()->SetRangeUser(wg->yax->GetXmin(),wg->yax->GetXmax());
	}

	if (wg->contours) {
	  //cout << "setting contours "; wg->contours->Print();
	  wg->gr2d->GetHistogram()->SetContour(wg->contours->GetNoElements(),
					       wg->contours->GetMatrixArray());
	  wg->gr2d->SetLineStyle   (wg->lstyle);
	  wg->gr2d->SetLineColor   (wg->lcolor);
	  wg->gr2d->SetLineWidth   (wg->lwidth);
	}
	wp->vp->Modified();
	wp->vp->Update();
	if( drawlegend && wg->leglabel.size() )
	  wleg->leg->AddEntry(wg->gr2d,wg->leglabel.c_str(),wg->legdrawopt.c_str());
      }
    } // graph loop

    /***************************************************
     * LOOP OVER LINES DEFINED FOR PAD...
     ***************************************************/

    for( unsigned j = 0; j < wp->line_ids.size(); j++ ) {
      string drawopt("L");
      string& lid = wp->line_ids[j];
      map<string,TLine *>::const_iterator it2 = glmap_id2line.find(lid);
      if (it2 == glmap_id2line.end()) {
	cerr << "ERROR: line id " << lid << " never defined in layout" << endl;
	exit (-1);
      }

      TLine *line = it2->second;

      if (!j && !wp->histo_ids.size() && !wp->macro_ids.size())
	drawopt += string("A"); // no histos drawn, need to draw the frame ourselves.

      if (line) {
	drawInPad<TLine>(wp,line,drawopt.c_str());
	//if (drawlegend)
	//wleg->leg->AddEntry(line,lid.c_str(),"L");
      }
    }

    /***************************************************
     * LOOP OVER BOXES DEFINED FOR PAD...
     ***************************************************/

    for (unsigned j = 0; j < wp->box_ids.size(); j++) {
      string drawopt("L");
      string& bid = wp->box_ids[j];
      map<string,TBox *>::const_iterator it2 = glmap_id2box.find(bid);
      if (it2 == glmap_id2box.end()) {
	cerr << "ERROR: box id " << bid << " never defined in layout" << endl;
	exit (-1);
      }

      TBox *box = it2->second;

      if (box) {
	drawInPad<TBox>(wp,box,drawopt.c_str());
      }
    }

    /***************************************************
     * Draw the legend
     ***************************************************/

    if (drawlegend) {
      wleg->leg->Draw("same");
      wp->vp->Update();
    }

    /***************************************************
     * Draw each latex/label object
     ***************************************************/
    
    for (unsigned j=0; j<wp->latex_ids.size(); j++) {
      string& lid = wp->latex_ids[j];
      map<string,TLatex *>::const_iterator it2 = glmap_id2latex.find(lid);
      if (it2 == glmap_id2latex.end()) {
	cerr << "ERROR: latex id " << lid << " never defined in layout" << endl;
	exit (-1);
      }
      if (gl_verbose) cout << "Drawing latex object " << lid << endl;
      TLatex *ltx = it2->second;
      ltx->Draw();
      wp->vp->Update();
    }

    for (unsigned j = 0; j < wp->label_ids.size(); j++) {
      string& lid = wp->label_ids[j];
      map<string,wLabel_t *>::const_iterator it2 = glmap_id2label.find(lid);
      if (it2 == glmap_id2label.end()) {
	cerr << "ERROR: label id " << lid << " never defined in layout" << endl;
	exit (-1);
      }
      if (gl_verbose) cout << "Drawing label object " << lid << endl;
      wLabel_t *wlab = it2->second;
      drawStandardText(wlab->text, wlab->x1ndc, wlab->y1ndc,-1,-1,wlab->textsize);

      wp->vp->Update();
    }
    wc->c1->Update();

  } // pad loop

  //prdFixOverlay();

  if (savePlots2file) {
    wc0 = cs.canvases[0];
    if (!wc0->savenamefmts.size())  // define a default
      wc0->savenamefmts.push_back("%F_%C.png");
    for (size_t i=0; i<cs.canvases.size(); i++) {
      wCanvas_t *wc = cs.canvases[i];
      wc->c1->cd();
      for (size_t j=0; j<wc0->savenamefmts.size(); j++)
	saveCanvas2File(wc,wc0->savenamefmts[j]);
    }
  }
}                                                           // drawPlots
Beispiel #10
0
void recurseOverKeys(TDirectory *target, TString imageType) {

//  TString path( (char*)strstr( target->GetPath(), ":" ) );
//  path.Remove( 0, 2 );

//  cout << path << endl;

//  sourceFile->cd( path );
    target->cd();
    TDirectory *current_sourcedir = gDirectory;

    TKey *key;
    TIter nextkey(current_sourcedir->GetListOfKeys());
    TCanvas *canvasDefault = new TCanvas();

    while ( (key = (TKey*)nextkey() ) ) {

        TObject* obj = key->ReadObj();

        if (obj->IsA()->InheritsFrom("TH1") ) {

            // **************************
            // Plot & Save this Histogram
            TH1* h = (TH1*)obj;
            h->SetStats(displayStatsBox);

            TString histName = h->GetName();

            // Now to label the X-axis!
//      if (autoLabelXaxis) {
//	if ( histName.Contains("Phi") ) {
//	  h->GetXaxis()->SetTitle("#phi");
//	} else if ( histName.Contains("Eta") ) {
//	  h->GetXaxis()->SetTitle("#eta");
//	} else if ( histName.Contains("Pt") ) {
//	  h->GetXaxis()->SetTitle("p_{T} (GeV)");
//	} else if ( histName.Contains("Et") ) {
//	  h->GetXaxis()->SetTitle("E_{T} (GeV)");
//	}
//      }

//      h->SetLineColor(lineColor);
//      h->SetLineWidth(lineWidth);


            // ********************************
            // A trick to decide whether to have log or no-log y axis
            // get hist max y value
            if (autoLogYaxis) {
                Double_t testYvalue = h->GetMaximum();
                //cout << testYvalue << endl;

                if (testYvalue > 1.0) {
                    Double_t maxy = log10(testYvalue);

                    // get hist min y value
                    Double_t miny = log10(h->GetMinimum(1.0));

                    // log scale if more than 3 powers of 10 between low and high bins
                    if ( (maxy-miny) > 3.0 ) {
                        canvasDefault->SetLogy(1);
                    }
                }
            }
            // End of log or no-log y axis decision
            // ********************************

            h->Draw(drawOptions1D);
            canvasDefault->Modified();
            canvasDefault->Update();

//      gPad->Print(outputFolder+path+"/"+histName+outputType);
            TString outputFolder = "images/";
            gPad->Print(outputFolder+histName+"."+imageType);
            // To store the root file name in image file name:
            //canvasDefault->Print(outputFolder+histFileName+histName+outputType);
//      if (printOutput) cout << outputFolder+path+"/"+histName+outputType << endl;

            canvasDefault->SetLogy(0); // reset to no-log - prevents errors
            // **************************

        } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) {
            // it's a subdirectory

            cout << "Found subdirectory " << obj->GetName() << endl;
//      gSystem->MakeDirectory(outputFolder+path+"/"+obj->GetName());

            // obj is now the starting point of another round of merging
            // obj still knows its depth within the target file via
            // GetPath(), so we can still figure out where we are in the recursion
            recurseOverKeys((TDirectory*)obj, imageType);

        } // end of IF a TDriectory
    } // end of LOOP over keys
}
Beispiel #11
0
//________________________________________________________
void GFHistManager::DrawReally(Int_t layer)
{
  if(layer < 0 || layer > fDepth-1) {
    this->Warning("DrawReally","Layer %d does not exist, possible are 0 to %d.", 
		  layer, fDepth-1);
    return;
  }

  this->MakeCanvases(layer);

  TIter canIter(static_cast<TObjArray*>(fCanArrays->At(layer)));
  TIter histIter(static_cast<TObjArray*>(fHistArrays->At(layer)));

  Int_t histNo = 0; // becomes number of histograms in layer
  while(TCanvas* can = static_cast<TCanvas*>(canIter.Next())){
    Int_t nPads = this->NumberOfSubPadsOf(can);
    if (fNoX[layer] * fNoY[layer] != nPads && 
	!(nPads == 0 && fNoX[layer] * fNoY[layer] == 1)) {
      this->Warning("Update", "inconsistent number of pads %d, expect %d*%d",
		    nPads, fNoX[layer], fNoY[layer]);
    }
    for(Int_t i = 0; i <= nPads; ++i){
      if (i == 0 && nPads != 0) i = 1;
      can->cd(i);
      if(GFHistArray* histsOfPad = static_cast<GFHistArray*>(histIter.Next())){
	TIter hists(histsOfPad);
	TH1* firstHist = static_cast<TH1*>(hists.Next());
	firstHist->Draw();
	this->DrawFuncs(firstHist);
	while(TH1* h = static_cast<TH1*>(hists.Next())){
	  h->Draw(Form("SAME%s%s", (fSameWithStats ? "S" : ""), h->GetOption()));
	  this->DrawFuncs(h);
	}
	if(histsOfPad->GetEntriesFast() > 1){
	  const Double_t max = this->MaxOfHists(histsOfPad);
	  if(//firstHist->GetMaximumStored() != -1111. &&  ????
	     max > firstHist->GetMaximumStored()){
	    firstHist->SetMaximum((fLogY[layer] ? 1.1 : 1.05) * max);
	  }
	  const Double_t min = this->MinOfHists(histsOfPad);
	  if(!(gStyle->GetHistMinimumZero() && min > 0.)) {
	    firstHist->SetMinimum(min * 1.05);
	  }
	}
	if(fLogY[layer] 
	   && (firstHist->GetMinimum() > 0. 
	      || (firstHist->GetMinimum() == 0. 
		  && firstHist->GetMinimumStored() == -1111.)))gPad->SetLogy();
	// draw other objects:
	this->DrawObjects(layer, histNo);
	// make hist style differ
	if(fDrawDiffStyle) GFHistManager::MakeDifferentStyle(histsOfPad);
	// draw legends on top of all
	if(fLegendArrays && layer <= fLegendArrays->GetLast() && fLegendArrays->At(layer)){
	  this->DrawLegend(layer, histNo);
	}
	gPad->Modified();
	this->ColourFuncs(histsOfPad);
	if (fSameWithStats) {
	  gPad->Update(); // not nice to need this here, makes use over network impossible...
	  this->ColourStatsBoxes(histsOfPad);
	}
	histNo++;
      }
    } // loop over pads
  } // loop over canvases
}
Beispiel #12
0
int ratio5() {

  // Constants and arrays

  Int_t multi = 2;

  const Int_t n_at = 3;
  Int_t at[n_at] = { 500, 510, 550 };
  //for ( int ii = 0; ii < n_at; ++ii ) { at[ii] = 500 + ii * 10; }

  TString eq = "Gt";

  const Int_t n = 4;
  float pt[n]     = { 50., 40., 30., 20. };
  Int_t colour[n] = { 1, 2, 3, 4 };

  const Int_t m = 2;
  Int_t style[m]  = { kOpenSquare, kFullSquare };
  
  const Int_t ngr = 1000;
  double x3[ngr];
  double r[ngr];

  int count = 0;

  // General style

  gStyle->SetOptStat(0);
  
//   // Canvas for RECO curves 
//   TCanvas* reco_canvas = new TCanvas("Reco");
//   reco_canvas->SetFillColor(0);
//   reco_canvas->SetLineColor(0); 
//   reco_canvas->SetLogy();
//   TLegend* reco_legend = new TLegend( 0.5, 0.7, 0.88, 0.88, NULL, "brNDC" );
//   reco_legend->SetFillColor(0);
//   reco_legend->SetLineColor(0); 
//   bool empty = true;
//   double reco_max = 1.e-15.;
//   double reco_min = 1.e15;
  
  // Loop through pt bins

  for ( Int_t i = 0; i < 1; ++i ) {

    std::stringstream pt_can;
    pt_can << "PtBin" << pt[i];
    
    // Canvas for Pt bin
    TCanvas* pt_canvas = new TCanvas(TString(pt_can.str()),"");
    pt_canvas->SetFillColor(0);
    pt_canvas->SetLineColor(0); 
    pt_canvas->SetLogy();
    TLegend* pt_legend = new TLegend( 0.82, 0.5, 0.98, 0.9, NULL, "brNDC" );

    pt_legend->SetFillColor(0);
    pt_legend->SetLineColor(0); 
    bool empty = true;
    double pt_max = 1.e-15.;
    double pt_min = 1.e15;
    std::vector<TH1*> pt_ratio;

    pt_canvas->SetRightMargin(0.2);

    // Open files
    std::stringstream ss;
    ss << "results/4/Reco" << pt[i] << "_QCDPythia6.root";
    TString name(ss.str());
    TFile* file = new TFile(name);
    if ( file->IsZombie() || !(file->IsOpen()) ) { continue; }
    file->cd();
    
    // Loop through AlphaT thresolds
    for ( Int_t iat = 0; iat < n_at; ++iat ) {
    
      // Loop through RECO and GEN
      for ( Int_t j = 0; j < m; ++j ) {
	
	// Define names of histos to open 
	std::stringstream pre;
	std::stringstream post;
	if ( j == 0 ) {
	  pre << "Ratio" << at[iat] << "/GenHt" << eq << "PreAlphaT" << at[iat] << "_" << multi;
	  post << "Ratio" << at[iat] << "/GenHt" << eq << "PostAlphaT" << at[iat] << "_" << multi;
	  std::cout << pre.str() << std::endl;
	  std::cout << post.str() << std::endl;
	} else if ( j == 1 ) {
	  pre << "Ratio" << at[iat] << "/Ht" << eq << "PreAlphaT" << at[iat] << "_" << multi;
	  post << "Ratio" << at[iat] << "/Ht" << eq << "PostAlphaT" << at[iat] << "_" << multi;
	  std::cout << pre.str() << std::endl;
	  std::cout << post.str() << std::endl;
	}
	
	// Create ratio histo
	TH1* denominator = his( (TH1*)file->Get(TString(pre.str())), 45, 200., 650. );
	TH1* numerator = his( (TH1*)file->Get(TString(post.str())), 45, 200., 650. );
	int rebin = 5;
	numerator->Rebin(rebin);
	denominator->Rebin(rebin);
	TH1* ratio = (TH1*)numerator->Clone();
	ratio->Divide(denominator);
	//ratio->Divide(numerator,denominator,1.,1.,"b"); //@@ poisson errors
	ratio->SetMarkerStyle(style[j]);
	ratio->SetMarkerSize(1.2);
	ratio->SetMarkerColor(iat+1);//colour[iat]);
	ratio->SetBarOffset(0.1*i);
	//ratio->GetXaxis()->SetRangeUser(100.,550.);
	ratio->GetYaxis()->SetRangeUser(1.e-7,1.e-1);

	ratio->GetXaxis()->SetTitle("HT_{reco} [GeV]");
	ratio->GetYaxis()->SetTitle("R(#alpha_{T})");
	
 	if ( ratio->GetMaximum() > 0. &&
 	     ratio->GetMaximum() > pt_max ) {
 	  pt_max = ratio->GetMaximum();
 	}
 	if ( ratio->GetMinimum() > 0. && 
 	     ratio->GetMinimum() < pt_min ) {
 	  pt_min = ratio->GetMinimum();
 	}

	pt_ratio.push_back(ratio);

	if ( empty ) { ratio->Draw(""); empty = false; }
        else { ratio->Draw("same"); }

	//ratio->GetYaxis()->SetRangeUser(pt_min/1.1,pt_max*1.1);


	// Text for legend
	std::stringstream pt_leg;
	if ( j == 0 ) { pt_leg << "#alpha_{T} = " << at[iat]/1000. << ", GEN"; }
	else if ( j == 1 ) { pt_leg << "#alpha_{T} = " << at[iat]/1000. << ", RECO"; }
	pt_legend->AddEntry( ratio, TString(pt_leg.str()), "lep" );
	
// 	// Draw histos on canvas for RECO only
// 	if ( j == 1 ) {
// 	  reco_canvas->cd();
// 	  if ( i == 0 ) ratio->Draw("");
// 	  else ratio->Draw("same");
// 	  std::stringstream reco_leg;
// 	  reco_leg << "p_{T}^{min} = " << pt[i];
// 	reco_legend->AddEntry( ratio, TString(reco_leg.str()), "lep" );
// 	}
	
      }
    }

//       if (0) {

// 	int nbins = ratio->GetNbinsX();
// 	int bin_width = ratio->GetBinWidth(1);
      
// 	double lower = 0.;
// 	double upper = 1400.;
      
// 	int bin_lower = int( ( lower - ratio->GetBinLowEdge(1) ) / bin_width );
// 	for ( Int_t ii = bin_lower; ii < ratio->GetNbinsX()-1; ++ii ) {
// 	  if ( ratio->GetBinContent(ii) > 0. ) { 
// 	    lower = ratio->GetBinCenter(ii);
// 	    break;
// 	  }
// 	}
// 	int bin_upper = int( ( upper - ratio->GetBinLowEdge(1) ) / bin_width );
// 	for ( Int_t ii = bin_upper; ii > 0; --ii ) {
// 	  if ( ratio->GetBinContent(ii) > 0. ) { 
// 	    upper = ratio->GetBinCenter(ii);
// 	    break;
// 	  }
// 	}
// 	if (0) {
// 	  std::cout << " bin_width: " << bin_width
// 		    << " bin_lower: " << bin_lower
// 		    << " bin_upper: " << bin_upper
// 		    << " lower: " << lower
// 		    << " upper: " << upper
// 		    << std::endl;
// 	}

// 	TF1* fit = new TF1(sample[i],"expo",lower,upper); 
// 	fit->SetLineColor(colour[i]);
// 	fit->SetLineWidth(1);
// 	ratio->Fit(sample[i],"QR","same");

//       }
      
     pt_canvas->cd();
//      for ( Int_t iii = 0; iii < pt_ratio.size(); ++iii ) {
//        TH1* ratio = pt_ratio[iii];
//        if ( !ratio ) { continue; }
//        if ( ii == 0 ) { ratio->Draw(""); }
//        else { ratio->Draw("same"); }
//        ratio->GetYaxis()->SetRangeUser(pt_min/1.1,pt_max*1.1);
//      }
     pt_legend->Draw("same");
     pt_canvas->Update();
     pt_canvas->SaveAs(TString(pt_can.str()+".png"));
//       pt_canvas->SaveAs(TString(pt_can.str()+".C"));
      
    }

//   reco_canvas->cd();
//   reco_legend->Draw("same");
//   reco_canvas->Update();
//   reco_canvas->SaveAs(TString("Reco.png"));
//   reco_canvas->SaveAs(TString("Reco.C"));
  
//   TCanvas* c2 = new TCanvas("C2");
//   c2->SetLogy();
//   c2->SetFillColor(0);
//   gStyle->SetOptStat(0);
//   if ( count > 0 ) {
//     TGraph* graph = new TGraph(count,x3,r); 
//     graph->Draw("a*");
//   }

  
}
Beispiel #13
0
////////////////////////////////////////////////////////////
//
// Plot a page with several histograms
//
void PlotNHistograms(const TString& pdfFile,
		     TDirectory* rdir, TDirectory* sdir,
		     const TString& rcollname, const TString& scollname,
		     const char* canvasName, const char* canvasTitle,
		     const TString& refLabel, const TString& newLabel,
 		     unsigned int nhistos, const TString* hnames,
		     const TString* htitles, const char** drawopt,
 		     bool* logy = 0,  bool* logx = 0, bool* doKolmo = 0, Double_t* norm = 0,
		     Double_t* minx = 0, Double_t* maxx = 0,
		     Double_t* miny = 0, Double_t* maxy = 0) {

  if (DEBUGP) {
    cout << "   + Plotting histograms for " << canvasTitle << endl;
    cerr << "   + Plotting histograms for " << canvasTitle << endl;
  }

  TH1* rh_raw   = 0;
  TH1* rh       = 0;
  TH1* sh_raw   = 0;
  TH1* sh       = 0;

  TCanvas* canvas =  0;
  if (nhistos >4)
    canvas = new TCanvas(canvasName, canvasTitle, 1000, 1400);
  else
    canvas = new TCanvas(canvasName, canvasTitle, 1000, 1050);

  canvas->Draw();
  canvas->Divide(2,(nhistos+1)/2); //This way we print in 2 columns

  for (unsigned int i = 0; i < nhistos; i++) {

    if (DEBUGP) cout << " [" << i << "] histogram name: " << flush << hnames[i] << endl;

    //draw option for the new histogram
    TString drawoption = drawopt[i]; 

    // Skip histogram if no name is provided
    if (hnames[i] == "") continue;
    
    // Get Histograms
    // + Reference release
    rdir->cd(rcollname);
    
    if (DEBUGP) cout << " Getting object for reference sample " << (rcollname + "/" + hnames[i]) << endl;

    rdir->GetObject(rcollname + "/" + hnames[i], rh_raw);
    if (! rh_raw) {
      cout << "WARNING: Could not find a reference histogram or profile named " << hnames[i]
	   << " in " << rdir->GetName() << endl;
      cout << "         Skipping" << endl;
      continue;
    }

    //If it is a 2D project it in Y... is this what we always want?
    if (TString(rh_raw->IsA()->GetName()) == "TH2F") {

      if (DEBUGP) cout << " It is a TH2F object... project in Y!" << endl;

      TH1* proj = ((TH2F*) rh_raw)->ProjectionY();
      rh_raw = proj;
    }

    // + New release    
    sdir->cd(scollname);

    if (DEBUGP) cout << " Getting object for target sample " << (scollname + "/" + hnames[i]) << endl;

    sdir->GetObject(scollname + "/" + hnames[i], sh_raw);
    if (! sh_raw) {
      cout << "WARNING: Could not find a signal histogram or profile named " << hnames[i] 
	   << " in " << sdir->GetName() << endl;
      cout << "         Skipping" << endl;
      continue;
    }

    //If it is a 2D project it in Y... is this what we always want?
    if (TString(sh_raw->IsA()->GetName()) == "TH2F") {

      if (DEBUGP) cout << hnames[i] << " is a TH2F object... project in Y!" << endl;

      TH1* proj = ((TH2F*) sh_raw)->ProjectionY();
      sh_raw = proj;
    }

    rh = AddOverflow(rh_raw);
    sh = AddOverflow(sh_raw);

    // Set styles

    if (DEBUGP) cout << " Setting style..." << endl;

    SetHistogramStyle(rh, 21, 4);
    SetHistogramStyle(sh, 20, 2);

    //Change titles
    if (htitles) {
      rh->SetTitle(htitles[i]);
      sh->SetTitle(htitles[i]);
      rh->GetYaxis()->SetTitle(htitles[i]);
      sh->GetYaxis()->SetTitle(htitles[i]);
    }

    // SET X AXIS RANGE in plots
    Bool_t ChangeXRange = false ;
    Double_t Xleft = rh->GetXaxis()->GetXmin();
    Double_t Xright = rh->GetXaxis()->GetXmax(); 

    if (DEBUGP) cout << "ref histo Xleft, Xright = "<< Xleft << ", "<< Xright  << endl;
   
    if (sh->GetXaxis()->GetXmin() < rh->GetXaxis()->GetXmin()) {
      Xleft = sh->GetXaxis()->GetXmin();
      ChangeXRange = true;
      if (DEBUGP) cout << "automatic reset MIN (new < ref) Xleft = "<< Xleft << endl;
    }
    if (sh->GetXaxis()->GetXmax() > rh->GetXaxis()->GetXmax()) {
      Xright = sh->GetXaxis()->GetXmax();
      ChangeXRange = true;
      if (DEBUGP) cout << "automatic reset MAX (new > ref) Xright = "<< Xright << endl;
    }

    if (minx[i]!=0) {
      ChangeXRange = true ;
      Xleft = minx[i];
      if (DEBUGP) cout << "user reset Xleft = "<< Xleft << endl;
    }
    
    if (maxx[i]!=0) {
      ChangeXRange = true ;
      Xright = maxx[i];
      if (DEBUGP) cout << "user reset Xright = "<< Xleft << endl;
    }
        
    if (ChangeXRange) {
      if (DEBUGP) {
	cout << "Ref histo Xmin, Xmax = "<< rh->GetXaxis()->GetXmin()  << ", " << rh->GetXaxis()->GetXmax() <<endl;
	cout << "New histo Xmin, Xmax = "<< sh->GetXaxis()->GetXmin()  << ", " << sh->GetXaxis()->GetXmax() <<endl;
      }
      
      rh->GetXaxis()->SetRangeUser(Xleft,Xright);
      sh->GetXaxis()->SetRangeUser(Xleft,Xright);      

      if (DEBUGP) {
	cout << "reset Ref histo Xmin, Xmax = "<< rh->GetXaxis()->GetXmin()  << ", " << rh->GetXaxis()->GetXmax() <<endl;
	cout << "reset New histo Xmin, Xmax = "<< sh->GetXaxis()->GetXmin()  << ", " << sh->GetXaxis()->GetXmax() <<endl;
	cout << "resetting Ref and New histo Xleft, Xright = "<< Xleft << ", " << Xright <<endl;
      }
    }

    // ===============================================================================================
    // Normalize
    if (norm[i] < 0.) ; 
      // Default: do not normalize at all !
    else if (norm[i] == 0.)
      NormalizeHistogramsToFirst(rh,sh);
    else if (norm[i] == 1.)
      NormalizeHistogramsToOne(rh,sh);
    else if (norm[i] == 2.)
      NormalizeHistogramsAsDensity(rh,sh);
    // ===============================================================================================

    // ===============================================================================================
    // SET Y AXIS RANGE in plots
    //
    // MINIMUM
    //
    Double_t Ybottom;

    // if user-defined range force it !
    if (miny[i]!=0) {
      Ybottom = miny[i];
      if (DEBUGP) cout << "setting Minimum Y to user defined value: "<< miny[i] << endl;
    }
    else if (logy[i]) {
      // automatic setting for log scale
      Double_t yminr = rh->GetMinimum(0.); // min value larger than zero
      Double_t ymins = sh->GetMinimum(0.);
      Ybottom = yminr < ymins ? yminr*0.5 : ymins*0.5;
      if (DEBUGP) cout << "LOG scale, yminr, ymins: "<<yminr<<", "<<ymins <<"  ==>> Ybottom = "<<Ybottom<< endl;
    }
    else {
      // automatic setting for linear scale
      Double_t yminr = rh->GetMinimum(); // min value larger than zero
      Double_t ymins = sh->GetMinimum();
      Ybottom = yminr < ymins ? yminr-0.1*abs(yminr) : ymins-0.1*abs(ymins) ;
      // limit the scale to -1,+1 for relative pt bias to avoid failing fits
      if ((hnames[i] == "ptres_vs_eta_Mean") && (Ybottom <-1.)) Ybottom = -1.;
      if ((hnames[i] == "ptres_vs_pt_Mean") && (Ybottom <-1.)) Ybottom = -1.;
      if (DEBUGP) cout << "LIN scale, yminr, ymins: "<<yminr<<", "<<ymins <<"  ==>> Ybottom = "<<Ybottom<< endl;    
    }

    ///////////////////
    // MAXIMUM
    //
    Double_t Ytop;

    // if user-defined range force it !
    if (maxy[i]!=0) {
      Ytop = maxy[i];
      if (DEBUGP) cout << "setting Maximum Y to user defined value: "<< maxy[i] << endl;
    }
    else {
      Double_t ymaxr = rh->GetMaximum(); // max value
      Double_t ymaxs = sh->GetMaximum();
      Ytop = ymaxr > ymaxs ? ymaxr : ymaxs ;
      // automatic setting for log scale
      if (logy[i]) {
	Ytop = Ytop*2;
	if (DEBUGP) cout << "LOG scale, ymaxr, ymaxs: "<<ymaxr<<", "<<ymaxs <<"  ==>> Ytop = "<<Ytop<< endl;
      }
      else {
	Ytop = Ytop+0.1*abs(Ytop);
	// limit the scale to -1,+1 for relative pt bias to avoid failing fits
	if ((hnames[i] == "ptres_vs_eta_Mean") && (Ytop >1.)) Ytop = 1.;
	if ((hnames[i] == "ptres_vs_pt_Mean") && (Ytop >1.)) Ytop = 1.;
	if (DEBUGP) cout << "LIN scale, ymaxr, ymaxs: "<<ymaxr<<", "<<ymaxs <<"  ==>> Ytop = "<<Ytop<< endl;     
      }
    }

    // +++++++++++++++++++++++++++++++++++++++++
    rh->GetYaxis()->SetRangeUser(Ybottom,Ytop);
    sh->GetYaxis()->SetRangeUser(Ybottom,Ytop); 
    // +++++++++++++++++++++++++++++++++++++++++     

    // Move to subpad
    canvas->cd(i+1);
    
    TPad* pad1 = NULL;
    TPad* pad2 = NULL;

    pad1 = new TPad("pad1", "pad1", 0, 0.3, 1, 1.0);
    pad2 = new TPad("pad2", "pad2", 0, 0.0, 1, 0.3);

    pad1->SetTopMargin   (0.08);
    pad1->SetBottomMargin(0.01);
    pad1->Draw();

    pad2->SetTopMargin   (0.05);
    pad2->SetBottomMargin(0.45);
    pad2->Draw();// Set stat boxes                                                                      
    pad1->cd();

    // Check Logy                                                                                       
    if (logy[i]) gPad->SetLogy();
    if (logx[i]) {gPad->SetLogx(); pad2->SetLogx();}

    // Set stat boxes

    if (DEBUGP) cout << " Setting statistics..." << endl;
    setStats(sh, rh, -1, 0, false);
   
    // /////////// DRAW  histograms //////////////////////////////////////
    //
    // FIRST plot: reference (blue)   SECOND plot: new (red)
    if (DEBUGP) cout << " Drawing histograms..." << endl;

    if (ChangeXRange) {
      sh->Draw(drawoption);
      rh->Draw("same"+drawoption);
      sh->Draw("same"+drawoption);
    }
    else {
      rh->Draw(drawoption);
      sh->Draw("same"+drawoption);
    }

    // Perform Kolmogorov test if needed
    if (doKolmo) {
      if (doKolmo[i]) {
	if (DEBUGP) cout << " Performing Kolmogorov test..." << endl;
	//	TPad* c1_1 = canvas->GetPad(i+1);
	double kstest = KolmogorovTest(sh,rh);
	if(kstest<0.7)
	  gPad->SetFillColor(kBlue-10);
      }
    }
 
    pad2->cd();

    TH1* ratioplot = PlotRatiosHistograms(rh, sh);
    SetHistogramStyle(ratioplot, 21, 4);
    ratioplot->Draw("ep");
 } // End loop
  
   // Draw Legend

  if (DEBUGP) cout << " Drawing legend..." << endl;

  canvas->cd();
  
  TLegend* l = 0;
  if (nhistos > 4)
    l = new TLegend(0.20,0.665,0.80,0.685);
  else
    l = new TLegend(0.20,0.50,0.80,0.53);

  l->SetTextSize(0.011);
  l->SetLineColor(1);
  l->SetLineWidth(1);
  l->SetLineStyle(1);
  l->SetFillColor(0);
  l->SetBorderSize(2);
  l->AddEntry(rh,refLabel,"LPF");
  l->AddEntry(sh,newLabel,"LPF");
  l->Draw();
  
  // Print Canvas
  canvas->SaveAs(pdfFile+".pdf");
  canvas->SaveAs(pdfFile+".png");

  // Clean memory
  // delete l;
  delete canvas;
  if (DEBUGP) cout << "     ... plotted histograms for " << canvasTitle << endl;
}
Beispiel #14
0
void DrawTwoInPad(TVirtualPad* p,
                  Int_t        sub,
                  TH1*         h1,
                  TH1*         h2,
		  Bool_t       ratio,
		  Bool_t       logy=false,
		  Bool_t       legend=false)
{
  TVirtualPad* pp = p->cd(sub);
  pp->SetRightMargin(0.02);
  pp->SetLeftMargin(0.10);
  TVirtualPad* ppp = pp;
  if (ratio) {
    pp->Divide(1,2,0,0);
    ppp = pp->cd(1);				
    ppp->SetRightMargin(0.02);
  }
  if (logy) ppp->SetLogy();
  TH1* hs[] = { h1, h2, 0 };
  if (h1->GetMaximum() < h2->GetMaximum()) {
    hs[0] = h2;
    hs[1] = h1;
  }
  TH1** ph = hs;
  Double_t size = (ratio ? 0.1 : 0.05);
  Double_t off  = (ratio ? 0.6 : 0.5);
  h1->SetFillStyle(3004);
  h2->SetFillStyle(3005);
  while (*ph) {
    TString opt("hist");
    if (ph != hs) opt.Append(" same");

    TH1* copy = (*ph)->DrawCopy(opt);
    copy->GetXaxis()->SetLabelSize(2*size);
    copy->GetYaxis()->SetLabelSize(size);
    copy->GetYaxis()->SetTitleSize(size);
    copy->GetYaxis()->SetTitleOffset(off);
    copy->SetYTitle(copy->GetTitle());
    copy->SetTitle("");
    copy->SetDirectory(0);
    ph++;
  }
  TString s1 = h1->GetYaxis()->GetTitle();
  TString s2 = h2->GetYaxis()->GetTitle();
  
  if (legend) { 
    TLegend* l = new TLegend(0.6, 0.1, 0.9, 0.9);
    l->SetBorderSize(0);
    TLegendEntry* e = l->AddEntry("dummy", s1, "lf");
    l->SetFillColor(kWhite);
    e->SetFillColor(kBlack);
    e->SetFillStyle(h1->GetFillStyle());
    e = l->AddEntry("dummy", s2, "lf");
    e->SetFillColor(kBlack);
    e->SetFillStyle(h2->GetFillStyle());
    l->Draw();
  }
  if (!ratio) return;
  ppp = pp->cd(2);
  ppp->SetRightMargin(0.02);
  TH1* r = static_cast<TH1*>(h1->Clone(Form("ratio%s", h1->GetName())));
  r->SetDirectory(0);
  r->SetTitle("");
  r->GetXaxis()->SetLabelSize(size);
  r->GetYaxis()->SetLabelSize(size);
  r->GetYaxis()->SetTitleSize(0.9*size);
  r->GetYaxis()->SetTitleOffset(0.9*off);
  r->SetMarkerStyle(20);
  r->SetMarkerColor(h1->GetFillColor()+1);
  r->SetFillStyle(3007);
  r->SetYTitle(Form("#frac{%s}{%s}", s1.Data(), s2.Data()));

  // r->Add(h2, -1);
  // r->Divide(h1);
  if (!r->IsA()->InheritsFrom(TProfile::Class())) {
    r->GetSumw2()->Set(0); // r->Sumw2(false);
    h2->GetSumw2()->Set(0); // h2->Sumw2(false);
  }
  r->Divide(h2);
  Printf("%s", r->GetName());
  for (UShort_t bin = 1; bin <= r->GetNbinsX(); bin++) {
    Printf("  bin # %2d: Diff=%g+/-%g", bin, r->GetBinContent(bin),
	   r->GetBinError(bin));
    r->SetBinError(bin, 0);
  }
  r->GetSumw2()->Set(0); //r->Sumw2(false);
  r->SetMarkerSize(4);
  r->SetMaximum(r->GetMaximum()*1.2);
  r->SetMinimum(r->GetMinimum()*0.8);
  r->Draw("hist text30");  
  p->Modified();
  p->Update();
  p->cd();
}