void DrawCell( TMVA::PDEFoamCell *cell, TMVA::PDEFoam *foam,
	       Double_t x, Double_t y,
	       Double_t xscale,  Double_t yscale )
{
   // recursively draw cell and it's daughters

   Float_t xsize = xscale*1.5;
   Float_t ysize = yscale/3;
   if (xsize > 0.15) xsize=0.1; //xscale/2;
   if (cell->GetDau0() != NULL) {
      TLine *a1 = new TLine(x-xscale/4, y-ysize, x-xscale, y-ysize*2);
      a1->SetLineWidth(2);
      a1->Draw();
      DrawCell(cell->GetDau0(), foam, x-xscale, y-yscale, xscale/2, yscale);
   }
   if (cell->GetDau1() != NULL){
      TLine *a1 = new TLine(x+xscale/4, y-ysize, x+xscale, y-ysize*2);
      a1->SetLineWidth(2);
      a1->Draw();
      DrawCell(cell->GetDau1(), foam, x+xscale, y-yscale, xscale/2, yscale);
   }

   TPaveText *t = new TPaveText(x-xsize, y-ysize, x+xsize, y+ysize, "NDC");

   t->SetBorderSize(1);
   t->SetFillStyle(1);

   // draw all cell elements
   t->AddText( Form("Intg=%.5f", cell->GetIntg()) );
   t->AddText( Form("Var=%.5f", cell->GetDriv()) );
   TVectorD *vec = (TVectorD*) cell->GetElement();
   if (vec != NULL){
      for (Int_t i = 0; i < vec->GetNrows(); ++i) {
	 t->AddText( Form("E[%i]=%.5f", i, vec(i)) );
      }
   }

   if (cell->GetStat() != 1) {
      // cell is inactive --> draw split point
      t->SetFillColor( TColor::GetColor("#BBBBBB") );
      t->SetTextColor( TColor::GetColor("#000000") );

      // cell position and size
      TMVA::PDEFoamVect cellPosi(foam->GetTotDim()), cellSize(foam->GetTotDim());
      cell->GetHcub(cellPosi, cellSize);
      Int_t    kBest = cell->GetBest(); // best division variable
      Double_t xBest = cell->GetXdiv(); // best division point
      t->AddText( Form("dim=%i", kBest) );
      t->AddText( Form("cut=%.5g", foam->VarTransformInvers(kBest,cellPosi[kBest] + xBest*cellSize[kBest])) );
   } else {
      t->SetFillColor( TColor::GetColor("#DD0033") );
      t->SetTextColor( TColor::GetColor("#FFFFFF") );
   }

   t->Draw();

   return;
}
示例#2
0
文件: gldemos.C 项目: digideskio/root
void help()
{
   new TCanvas("chelp","Help on gldemos",200,10,700,600);

   TPaveLabel *title = new TPaveLabel(0.04, 0.86, 0.96, 0.98, "These demos show different gl painters.");
   title->SetFillColor(32);
   title->Draw();

   TPaveText *hdemo = new TPaveText(0.04, 0.04, 0.96, 0.8);
   hdemo->SetTextAlign(12);
   hdemo->SetTextFont(52);
   hdemo->SetTextColor(kBlue);
   hdemo->AddText("1. Glsurfaces demo shows glsurf4, glsurf1, glsurf3, glsurf1cyl, glsurfpol, gltf3 options.");
   hdemo->AddText("2. Glrose demontrates \"glsurf2pol\" drawing option and user-defined palette.");
   hdemo->AddText("3. Gltf3 demo shows \"gltf3\" option.");
   hdemo->AddText("4. Glbox demo shows \"glbox\" and \"glbox1\" options for TH3.");
   hdemo->AddText("5. Glparametric demo shows how to define and display parametric surfaces.");
   hdemo->AddText("You can zoom any plot: press 'J', 'K', 'j', 'k' keys, or use mouse wheel.");
   hdemo->AddText("Rotate any plot:");
   hdemo->AddText("  ---select plot with mouse cursor,");
   hdemo->AddText("  ---move mouse cursor, pressing and holding left mouse button ");
   hdemo->AddText("Pan plot:");
   hdemo->AddText("  ---select with mouse cursor a part of a plot, other than back box planes ,");
   hdemo->AddText("  ---move mouse cursor, pressing and holding middle mouse button ");
   hdemo->AddText("Selected part of a plot is higlighted (TF3 higlighting is not implemented yet.)");
   hdemo->AddText("You can select one of back box planes, press middle mouse button and move cursor-");
   hdemo->AddText("this will create \"slice\" (TF does not support yet).");
   hdemo->AddText("After the slice was created, you can project it on a back box");
   hdemo->AddText("  ---press key 'p' (now implemented only for surf options ).");
   hdemo->AddText("Left double click removes all slices/projections.");

   hdemo->Draw();

}
示例#3
0
void DrawStatBox(TObject** Histos, std::vector<char*> legend, bool Mean, double X, double Y, double W, double H)
{
   int    N             = legend.size();
   char   buffer[255];

   if(Mean)H*=3;
   for(int i=0;i<N;i++){
           TPaveText* stat = new TPaveText(X,Y-(i*H), X+W, Y-(i+1)*H, "NDC");
	   TH1* Histo = (TH1*)Histos[i];
           sprintf(buffer,"Entries : %i\n",(int)Histo->GetEntries());
           stat->AddText(buffer);

           if(Mean){
           sprintf(buffer,"Mean    : %6.2f\n",Histo->GetMean());
           stat->AddText(buffer);

           sprintf(buffer,"RMS     : %6.2f\n",Histo->GetRMS());
           stat->AddText(buffer);
           }

           stat->SetFillColor(0);
           stat->SetLineColor(Color[i]);
           stat->SetTextColor(Color[i]);
           stat->SetBorderSize(0);
           stat->SetMargin(0.05);
           stat->SetTextAlign(12);
           stat->Draw();
   }
}
示例#4
0
/************************************************************
*  Fit ADC spectrum
************************************************************/
int FitAdcHist(TH1F *h, float data[NDATA], const int print ) {
  TF1 *fadc;
  TPaveText *adcPT;

  // Protect for null histograms
  if( h == 0 || h->GetEntries()<1000. ) return -1;
  printf("Fitting %s\n",h->GetName());

  gStyle->SetOptStat("emr"); 
  adcPT = new TPaveText(0.58,0.315,0.98,0.635,"NDC");

//  Refit ADC
  Double_t n    = h->GetEntries();
  Double_t rms  = h->GetRMS();
  Double_t mean = h->GetMean();
  Double_t ymin = mean-2*rms;
  if( ymin < 60. ) ymin=60.;
  Double_t ymax = mean+1.5*rms;
  fadc = new TF1("adc_fun",skewnormal,ymin,ymax,4);
  fadc->SetParameters(n,mean,rms,1.5);
  fadc->SetParLimits(1,mean-rms,mean+0.5*rms);
  fadc->SetParLimits(2,rms*0.5,rms*1.5);
  fadc->SetParLimits(3,1.,4.);
  h->Fit("adc_fun","r"); 
//  If skew is too high refit with fixed skew
  if( fadc->GetParameter(3) > 2.5 ) {
    printf("REFIT %s\n",h->GetName());
    fadc->SetParameter(3,1.6);
    fadc->SetParLimits(3,1.6,1.6);
    h->Fit("adc_fun","r") ;
  }
// if have enough hits use fit results  
  if( n > MINHITS ) {
    data[13] = fadc->GetParameter(1);
    data[14] = fadc->GetParError(1);
    data[15] = fadc->GetParameter(2);
    data[16] = fadc->GetParError(2);
    data[17] = fadc->GetParameter(3);
    data[18] = fadc->GetParError(3);
    double dof = fadc->GetNDF();
    if( dof > 0. ) data[19] = fadc->GetChisquare()/dof;
    adcPT->AddText(Form("Peak %.1lf #pm %.1lf",data[13],data[14]));
    adcPT->AddText(Form("Width %.1lf #pm %.1lf",data[15],data[16]));
    adcPT->AddText(Form("Skew %.2lf #pm %.2lf",	data[17],data[18]));
    if( dof > 0. ) adcPT->AddText(Form("#Chi^{2}/DoF     %.2lf",data[19]));
    adcPT->SetTextColor(2);
    adcPT->Draw();
// if have too few hits use fit stats instead of fit results  
  } else {
    data[12] = mean;
    data[13] = h->GetMeanError();
    data[14] = rms;
    data[15] = h->GetRMSError();
    data[16] = h->GetSkewness();
  }
  if( print ) c1->Print(Form("%s_%s.png",fname,h->GetName()));
  return 0;
}    //end FitAdcHist
示例#5
0
void OverlayAnalysis::PostDrawMultiGraph(GraphName graphName, TMultiGraph *pMultiGraph) const
{
    if(NULL == pMultiGraph)
        return;

    // base customize
    pMultiGraph->GetXaxis()->SetTitle("Distance between showers [cm]");
    pMultiGraph->GetXaxis()->SetLabelFont(42);
    pMultiGraph->GetXaxis()->SetTitleSize(0.05);
    pMultiGraph->GetXaxis()->SetTitleOffset(1.);
    pMultiGraph->GetXaxis()->SetTitleFont(42);
    pMultiGraph->GetXaxis()->SetRangeUser(std::max(static_cast<int>(m_startDistance) - 5, 0), m_endDistance + 5);

    pMultiGraph->GetYaxis()->SetTitle("");
    pMultiGraph->GetYaxis()->SetLabelFont(42);
    pMultiGraph->GetYaxis()->SetTitleSize(0.045);
    pMultiGraph->GetYaxis()->SetTitleOffset(1.3);
    pMultiGraph->GetYaxis()->SetTitleFont(42);
    pMultiGraph->GetYaxis()->SetLabelSize(0.035);

    TPaveText *pt = new TPaveText(0.3, 0.2, 0.93, 0.3, "tbNDC");
    pt->SetTextSize(0.05);
    pt->SetTextColor(kGray+2);
    pt->SetFillColor(0);
    pt->SetLineWidth(0);
    pt->SetBorderSize(0);
    pt->AddText("CALICE SDHCAL");
    pt->SetTextFont(62);
    pt->Draw();

    // plot per plot customize
    switch(graphName)
    {
    case N_PFOS:
        pMultiGraph->GetYaxis()->SetTitle("<N_{pfos}>");
        pMultiGraph->GetYaxis()->SetRangeUser(1, 3);
        break;
    case NEUTRAL_PURITY:
        pMultiGraph->GetYaxis()->SetTitle("#rho_{neutral}");
        pMultiGraph->GetYaxis()->SetRangeUser(0, 1);
        break;
    case NEUTRAL_EFFICIENCY:
        pMultiGraph->GetYaxis()->SetTitle("#varepsilon_{neutral}");
        pMultiGraph->GetYaxis()->SetRangeUser(0, 1);
        break;
    case NEUTRAL_RECOVER_PROBA:
        pMultiGraph->GetYaxis()->SetTitle("P_{n>0}");
        pMultiGraph->GetYaxis()->SetRangeUser(0, 1);
        break;
    case NEUTRAL_ENERGY_DIFFERENCE_EFFICIENT:
        pMultiGraph->GetYaxis()->SetTitle("<E_{n,rec} - E_{n,meas}>, n>0");
        pMultiGraph->GetYaxis()->SetRangeUser(-5, 5);
        break;
    }
}
void 
CMSPrelim(const char* dataset, const char* channel,const char* cat)
{
  double lowX=0.16;
  double lowY=0.835;

  int color=1; int font = 62;
  
  TPaveText* cmsprel  = new TPaveText(lowX, lowY+0.06, lowX+0.30, lowY+0.16, "NDC");
  cmsprel->SetBorderSize(   0 );
  cmsprel->SetFillStyle(    0 );
  cmsprel->SetTextAlign(   12 );
  cmsprel->SetTextColor( color );
  cmsprel->SetTextFont ( font );
  //cmsprel->SetTextSize ( 0.035 );
  //cmsprel->SetTextSize ( 0.027 );
  cmsprel->SetTextSize ( 0.030 );
  cmsprel->AddText(dataset);
  cmsprel->Draw();

  TPaveText* chan     = new TPaveText(lowX+0.05, lowY-0.002, lowX+0.45, lowY+0.028, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.035 );
  chan->SetTextColor( color );
  chan->SetTextFont ( font );
  chan->AddText(channel);
  chan->Draw();

  TPaveText* category     = new TPaveText(lowX+0.05, lowY-0.002-0.06, lowX+0.45, lowY+0.028-0.06, "NDC");
  category->SetBorderSize(   0 );
  category->SetFillStyle(    0 );
  category->SetTextAlign(   12 );
  category->SetTextSize ( 0.035 );
  category->SetTextColor( color );
  category->SetTextFont ( font );
  category->AddText(cat);
  category->Draw();
}
示例#7
0
文件: online.C 项目: cipriangal/pan
void OnlineGUI::BadDraw(TString errMessage) {
  // Routine to display (in Pad) why a particular draw method has
  // failed.
  TPaveText *pt = new TPaveText(0.1,0.1,0.9,0.9,"brNDC");
  pt->SetBorderSize(3);
  pt->SetFillColor(10);
  pt->SetTextAlign(22);
  pt->SetTextFont(72);
  pt->SetTextColor(2);
  pt->AddText(errMessage.Data());
  pt->Draw();
//   cout << errMessage << endl;

}
示例#8
0
void CMSPrelim()
{
  
  
  TPaveText* cmsprel  = new TPaveText(0.19, 0.895 , 0.19 + 0.30, 0.895 + 0.10, "NDC");
  cmsprel->SetBorderSize(   0 );
  cmsprel->SetFillStyle(    0 );
  cmsprel->SetTextAlign(   12 );
  cmsprel->SetTextColor( 1 );
  cmsprel->SetTextFont ( 62 );

  //cmsprel->SetTextSize ( 0.035 );
  //cmsprel->AddText("CMS Preliminary,  #sqrt{s}=7-8 TeV,  L=24.3 fb^{-1},  H#rightarrow#tau#tau");

  //cmsprel->SetTextSize ( 0.027 );
  //cmsprel->AddText("CMS Preliminary, L=4.9 fb^{-1}@#sqrt{s}=7 TeV, L=19.3 fb^{-1}@#sqrt{s}=8 TeV, H#rightarrow#tau#tau");
  //cmsprel->AddText("CMS Preliminary,  #sqrt{s}=7 TeV, L=4.9 fb^{-1}; #sqrt{s}=8 TeV, L=19.3 fb^{-1}; H#rightarrow#tau#tau");

  cmsprel->SetTextSize ( 0.030 );
  cmsprel->AddText("CMS Preliminary,  H#rightarrow#tau#tau,  4.9 fb^{-1} at 7 TeV, 19.4 fb^{-1} at 8 TeV");

  cmsprel->Draw();

}
//*************************************************************
void FillTrendPlot(TH1F* trendPlot, TH1F* residualsPlot[100], TString fitPar_, TString var_,Int_t nBins_)
//*************************************************************
{

  std::cout<<"trendPlot name: "<<trendPlot->GetName()<<std::endl;

  // float phiInterval = (360.)/nBins_;
  float phiInterval = (2*TMath::Pi()/nBins_);
  float etaInterval = 5./nBins_;
 
  for ( int i=0; i<nBins_; ++i ) {
    
    int binn = i+1;

    char phipositionString[129];
    // float phiposition = (-180+i*phiInterval)+(phiInterval/2);
    float phiposition = (-TMath::Pi()+i*phiInterval)+(phiInterval/2);
    sprintf(phipositionString,"%.1f",phiposition);
    
    char etapositionString[129];
    float etaposition = (-2.5+i*etaInterval)+(etaInterval/2);
    sprintf(etapositionString,"%.1f",etaposition);

    std::pair<std::pair<Double_t,Double_t>, std::pair<Double_t,Double_t> > myFit = std::make_pair(std::make_pair(0.,0.),std::make_pair(0.,0.));

    if ( ((TString)trendPlot->GetName()).Contains("Norm") ) {
      //std::pair<std::pair<Double_t,Double_t>, std::pair<Double_t,Double_t>  > myFit = fitResiduals(residualsPlot[i]);
      myFit = fitResiduals(residualsPlot[i]);
    } else {
      //std::pair<std::pair<Double_t,Double_t>, std::pair<Double_t,Double_t>  > myFit = fitStudentTResiduals(residualsPlot[i]);
      myFit = fitResiduals(residualsPlot[i]);
    }

    if(fitPar_=="mean"){
      float mean_      = myFit.first.first;
      float meanErr_   = myFit.first.second;
      trendPlot->SetBinContent(i+1,mean_);
      trendPlot->SetBinError(i+1,meanErr_);
    } else if (fitPar_=="width"){
      float width_     = myFit.second.first;
      float widthErr_  = myFit.second.second;
      trendPlot->SetBinContent(i+1,width_);
      trendPlot->SetBinError(i+1,widthErr_);
    } else if (fitPar_=="median"){
      float median_    = getMedian(residualsPlot[i]).first;
      float medianErr_ = getMedian(residualsPlot[i]).second;
      trendPlot->SetBinContent(i+1,median_);
      trendPlot->SetBinError(i+1,medianErr_);
    } else if (fitPar_=="mad"){
      float mad_       = getMAD(residualsPlot[i]).first; 
      float madErr_    = getMAD(residualsPlot[i]).second;
      trendPlot->SetBinContent(i+1,mad_);
      trendPlot->SetBinError(i+1,madErr_);
    } else {
      std::cout<<"PrimaryVertexValidation::FillTrendPlot() "<<fitPar_<<" unknown estimator!"<<std::endl;
    }

    if(var_=="phi"){
      //  if( ((binn%2==0)&&(binn<=12)) || ((binn%2==1)&&(binn>12)) ) 
      // if( ((binn%3==1)&&(binn<=12)) || ((binn%3==0)&&(binn>12)) ) 
      //if((binn%3==0))
      //  trendPlot->GetXaxis()->SetBinLabel(binn,phipositionString); 
    } else if(var_=="eta"){
      // if( ((binn%2==0)&&(binn<=12)) || ((binn%2==1)&&(binn>12)) ) 
      // if( ((binn%3==1)&&(binn<=12)) || ((binn%3==0)&&(binn>12)) ) 
      //if((binn%3==0))
      //trendPlot->GetXaxis()->SetBinLabel(binn,etapositionString); 
    } else {
      //std::cout<<"PrimaryVertexValidation::FillTrendPlot() "<<var_<<" unknown track parameter!"<<std::endl;
    }
  }

  //trendPlot->GetXaxis()->LabelsOption("h");

  if(fitPar_=="mean" || fitPar_=="median"){

    TString res;
    if(TString(residualsPlot[0]->GetName()).Contains("dxy")) res="dxy";
    else if(TString(residualsPlot[0]->GetName()).Contains("dz")) res="dz";
    else if(TString(residualsPlot[0]->GetName()).Contains("IP2D")) res="IP2D";
    else if(TString(residualsPlot[0]->GetName()).Contains("resz")) res="resz";
    
    TCanvas *fitOutput = new TCanvas(Form("fitOutput_%s_%s_%s",res.Data(),var_.Data(),trendPlot->GetName()),Form("fitOutput_%s_%s",res.Data(),var_.Data()),1200,1200);
    fitOutput->Divide(5,5);
    
    TCanvas *fitPulls = new TCanvas(Form("fitPulls_%s_%s_%s",res.Data(),var_.Data(),trendPlot->GetName()),Form("fitPulls_%s_%s",res.Data(),var_.Data()),1200,1200);
    fitPulls->Divide(5,5);

    TH1F* residualsPull[nBins_];

    for(Int_t i=0;i<nBins_;i++){
      
      TF1 *tmp1 = (TF1*)residualsPlot[i]->GetListOfFunctions()->FindObject("tmp");
      fitOutput->cd(i+1)->SetLogy();
      fitOutput->cd(i+1)->SetBottomMargin(0.16);
      //fitOutput->cd(i+1)->SetTopMargin(0.05);
      //residualsPlot[i]->Sumw2();
      MakeNicePlotStyle(residualsPlot[i]);
      residualsPlot[i]->SetMarkerStyle(20);
      residualsPlot[i]->SetMarkerSize(1.);
      residualsPlot[i]->SetStats(0);
      //residualsPlot[i]->GetXaxis()->SetRangeUser(-3*(tmp1->GetParameter(1)),3*(tmp1->GetParameter(1)));
      residualsPlot[i]->Draw("e1");
      residualsPlot[i]->GetYaxis()->UnZoom();

      //std::cout<<"*********************"<<std::endl;
      //std::cout<<"fitOutput->cd("<<i+1<<")"<<std::endl;
      //std::cout<<"residualsPlot["<<i<<"]->GetTitle() = "<<residualsPlot[i]->GetTitle()<<std::endl;
      
      // -- for chi2 ----
      TPaveText *pt = new TPaveText(0.13,0.78,0.33,0.88,"NDC");
      pt->SetFillColor(10);
      pt->SetTextColor(1);
      pt->SetTextSize(0.07);
      pt->SetTextFont(42);
      pt->SetTextAlign(11);

      //TF1 *tmp1 = (TF1*)residualsPlot[i]->GetListOfFunctions()->FindObject("tmp");
      TString COUT = Form("#chi^{2}/ndf=%.1f",tmp1->GetChisquare()/tmp1->GetNDF());
      
      TText *text1 = pt->AddText(COUT);
      text1->SetTextFont(72);
      text1->SetTextColor(kBlue);
      pt->Draw("same");
    
      // -- for bins --
     
      TPaveText *title = new TPaveText(0.1,0.93,0.8,0.95,"NDC");
      title->SetFillColor(10);
      title->SetTextColor(1);
      title->SetTextSize(0.07);
      title->SetTextFont(42);
      title->SetTextAlign(11);
 
      //TText *text2 = title->AddText(residualsPlot[i]->GetTitle());
      //text2->SetTextFont(72);
      //text2->SetTextColor(kBlue);

      title->Draw("same");

      fitPulls->cd(i+1);
      fitPulls->cd(i+1)->SetBottomMargin(0.15);
      fitPulls->cd(i+1)->SetLeftMargin(0.15); 
      fitPulls->cd(i+1)->SetRightMargin(0.05); 
 
      residualsPull[i]=(TH1F*)residualsPlot[i]->Clone(Form("pull_%s",residualsPlot[i]->GetName()));
      for(Int_t nbin=1;nbin<=residualsPull[i]->GetNbinsX(); nbin++){
      	if(residualsPlot[i]->GetBinContent(nbin)!=0){ 
	  residualsPull[i]->SetBinContent(nbin,(residualsPlot[i]->GetBinContent(nbin) - tmp1->Eval(residualsPlot[i]->GetBinCenter(nbin)))/residualsPlot[i]->GetBinContent(nbin));
	  residualsPull[i]->SetBinError(nbin,0.1);
	}
      }

      TF1* toDel = (TF1*)residualsPull[i]->FindObject("tmp");
      if(toDel) residualsPull[i]->GetListOfFunctions()->Remove(toDel); 
      residualsPull[i]->SetMarkerStyle(20);
      residualsPull[i]->SetMarkerSize(1.);
      residualsPull[i]->SetStats(0);
			
      residualsPull[i]->GetYaxis()->SetTitle("(res-fit)/res");
      // residualsPull[i]->SetOptTitle(1);
      residualsPull[i]->GetXaxis()->SetLabelFont(42);
      residualsPull[i]->GetYaxis()->SetLabelFont(42);
      residualsPull[i]->GetYaxis()->SetLabelSize(.07);
      residualsPull[i]->GetXaxis()->SetLabelSize(.07);
      residualsPull[i]->GetYaxis()->SetTitleSize(.07);
      residualsPull[i]->GetXaxis()->SetTitleSize(.07);
      residualsPull[i]->GetXaxis()->SetTitleOffset(0.9);
      residualsPull[i]->GetYaxis()->SetTitleOffset(1.2);
      residualsPull[i]->GetXaxis()->SetTitleFont(42);
      residualsPull[i]->GetYaxis()->SetTitleFont(42);
      
      residualsPull[i]->Draw("e1");
      residualsPull[i]->GetYaxis()->UnZoom();
    }
    
    
    TString tpName =trendPlot->GetName();

    TString FitNameToSame  = Form("fitOutput_%s",(tpName.ReplaceAll("means_","").Data()));
    //fitOutput->SaveAs(FitNameToSame+".pdf");
    //fitOutput->SaveAs(FitNameToSame+".png");
    TString PullNameToSave = Form("fitPulls_%s",(tpName.ReplaceAll("means_","").Data()));
    //fitPulls->SaveAs(PullNameToSave+".pdf");
    //fitPulls->SaveAs(PullNameToSave+".png");
    
    //fitOutput->SaveAs(Form("fitOutput_%s_%s_%s.pdf",res.Data(),var_.Data(),trendPlot->GetName()));
    fitOutput->SaveAs(Form("fitOutput_%s.pdf",(((TString)trendPlot->GetName()).ReplaceAll("means_","")).Data()));
    fitPulls->SaveAs(Form("fitPulls_%s.pdf",(((TString)trendPlot->GetName()).ReplaceAll("means_","")).Data()));
    //fitOutput->SaveAs(Form("fitOutput_%s.png",(((TString)trendPlot->GetName()).ReplaceAll("means_","")).Data()));

  }
}
void 
HBB_HAD_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="bb_$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  const char* category_extra = "";
  if(std::string(directory) == std::string("bb_had0"  )){ category_extra = "all-had_{0}";  }
  if(std::string(directory) == std::string("bb_had1"  )){ category_extra = "all-had_{1}";  }
  if(std::string(directory) == std::string("bb_had2"  )){ category_extra = "all-had_{2}";  }
  if(std::string(directory) == std::string("bb_had3"  )){ category_extra = "all-had_{3}";  }
  if(std::string(directory) == std::string("bb_had4"  )){ category_extra = "all-had_{4}";  }
  if(std::string(directory) == std::string("bb_had5"  )){ category_extra = "all-had_{5}";  }
  if(std::string(directory) == std::string("bb_lep"   )){ category_extra = "semi-lep";  }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "Preliminary, #sqrt{s} = 7 TeV, L = 2.7 fb^{-1}";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "Preliminary, #sqrt{s} = 8 TeV, L = 19.4 fb^{-1}";}
  
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* Bbb  = refill((TH1F*)input->Get(TString::Format("%s/Bbb"   , directory)), "Bbb"); InitHist(Bbb, "", "", kMagenta-10, 1001);
  TH1F* Cbb  = refill((TH1F*)input->Get(TString::Format("%s/Cbb"   , directory)), "Cbb"); InitHist(Cbb, "", "", kRed    + 2, 1001);
  TH1F* Qbb  = refill((TH1F*)input->Get(TString::Format("%s/Qbb"   , directory)), "Qbb"); InitHist(Qbb, "", "", kBlue   - 8, 1001);
  TH1F* bbB  = refill((TH1F*)input->Get(TString::Format("%s/bbB"   , directory)), "bbB"); InitHist(bbB, "", "", kOrange - 4, 1001);
  TH1F* bbX  = refill((TH1F*)input->Get(TString::Format("%s/bbX"   , directory)), "bbX"); InitHist(bbX, "", "", kViolet - 0, 1001);
#ifdef MSSM
  //float bbHScale = 1.;
  //ggHScale = ($MSSM_SIGNAL_ggH_xseff_A + $MSSM_SIGNAL_ggH_xseff_hH);
  //bbHScale = ($MSSM_SIGNAL_bbH_xseff_A + $MSSM_SIGNAL_bbH_xseff_hH);
  TH1F* bbH  = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA"  , directory)), "bbH"  ); InitSignal(bbH); bbH->Scale($TANB); //bbH->Scale(bbHScale);
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
  InitHist(data, "#bf{m_{b#bar{b}} [GeV]}", "#bf{dN/dm_{b#bar{b}} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Qbb->Clone("ref");
  ref->Add(bbX);
  ref->Add(Cbb);
  ref->Add(bbB);
  ref->Add(Bbb);

  double unscaled[7];
  unscaled[0] = Qbb ->Integral();
  unscaled[1] = bbX ->Integral();
  unscaled[2] = Cbb ->Integral();
  unscaled[3] = bbB ->Integral();
  unscaled[4] = Bbb ->Integral();
#ifdef MSSM
  unscaled[5] = bbH ->Integral();
  unscaled[6] = 0;
#endif

  if(scaled){
    rescale(Bbb,   1); 
    rescale(bbB,   4); 
    rescale(Cbb,   2); 
    rescale(bbX,   5);
    rescale(Qbb,   3);
#ifdef MSSM 
    rescale(bbH,   6);
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-Qbb", "", 7, 0, 7);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Qbb  ->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-bbX"  , "", 7, 0, 7);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (bbX  ->Integral()/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-Cbb", "", 7, 0, 7);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (Cbb  ->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-bbB"  , "", 7, 0, 7);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (bbB  ->Integral()/unscaled[3]-1.) : 0.);
  scales[4] = new TH1F("scales-Bbb"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (Bbb  ->Integral()/unscaled[4]-1.) : 0.);
#ifdef MSSM
  scales[5] = new TH1F("scales-bbH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", 7, 0, 7);
  scales[6]->SetBinContent(7, 0.);
#endif

  bbX  ->Add(Qbb);
  Cbb  ->Add(bbX);
  bbB  ->Add(Cbb);
  Bbb  ->Add(bbB);
  if(!log){
#ifdef MSSM
    bbH  ->Add(Bbb);
#endif
  }

  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(350)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(1000)); };
#endif

  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Bbb, log)));
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Bbb ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);

  if(log){
    Bbb  ->Draw("histsame");
    bbB  ->Draw("histsame");
    Cbb  ->Draw("histsame");
    bbX  ->Draw("histsame");
    Qbb  ->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    bbH  ->Draw("histsame");
#endif
  }
  else{   
#ifndef DROP_SIGNAL
    bbH  ->Draw("histsame");
#endif 
    Bbb  ->Draw("histsame");
    bbB  ->Draw("histsame");
    Cbb  ->Draw("histsame");
    bbX  ->Draw("histsame");
    Qbb  ->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "b#bar{b}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.17, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText("b#bar{b}");
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m_{A}=$MA GeV");
  massA->Draw();

  TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
  tanb->SetBorderSize(   0 );
  tanb->SetFillStyle(    0 );
  tanb->SetTextAlign(   12 );
  tanb->SetTextSize ( 0.03 );
  tanb->SetTextColor(    1 );
  tanb->SetTextFont (   62 );
  tanb->AddText("tan#beta=$TANB");
  tanb->Draw();

  TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
  scen->SetBorderSize(   0 );
  scen->SetFillStyle(    0 );
  scen->SetTextAlign(   12 );
  scen->SetTextSize ( 0.03 );
  scen->SetTextColor(    1 );
  scen->SetTextFont (   62 );
  scen->AddText("m^{h}_{max}");
  scen->Draw();
#endif

#ifdef MSSM  
  TLegend* leg = new TLegend(0.55, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(bbH  , "#phi#rightarrowb#bar{b}" , "L" );
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + SM125 GeV signal"    , "LP");
#else
  leg->AddEntry(data , "observed"                       , "LP");
#endif
  leg->AddEntry(Bbb, "Bbb"                            , "F" );
  leg->AddEntry(bbB, "bbB"                            , "F" );
  leg->AddEntry(Cbb, "Cbb"                            , "F" );
  leg->AddEntry(bbX, "bbX"                            , "F" );
  leg->AddEntry(Qbb, "Qbb"                            , "F" );
  $ERROR_LEGEND
  leg->Draw();

//#ifdef MSSM
//  TPaveText* mssm  = new TPaveText(0.69, 0.85, 0.90, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("(m_{A}=250, tan#beta=5)");
//  mssm->Draw();
//#else
//  TPaveText* mssm  = new TPaveText(0.83, 0.85, 0.95, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("m_{H}=125");
//  mssm->Draw();
//#endif

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
  rat1->Divide(Bbb);
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
    zero->SetBinContent(ibin+1, 0.);
  }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+1.5);
  rat1->SetMinimum(-1.5);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{b#bar{b}} [GeV]}");
  rat1->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv0->RedrawAxis();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* rat2 = (TH1F*) Bbb->Clone("rat2");
  rat2->Divide(ref);
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  rat2->SetLineColor(kRed+ 3);
  rat2->SetFillColor(kRed-10);
  rat2->SetMaximum(+0.3);
  rat2->SetMinimum(-0.3);
  rat2->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{b#bar{b}} [GeV]}");
  rat2->GetXaxis()->SetRange(0, 28);
  rat2->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[4], "", "", kMagenta-10, 1001);
  InitHist  (scales[2], "", "", kRed    + 2, 1001);
  InitHist  (scales[0], "", "", kBlue   - 8, 1001);
  InitHist  (scales[3], "", "", kOrange - 4, 1001);
  InitHist  (scales[1], "", "", kViolet - 0, 1001);
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Qbb}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{bbX}");
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{Cbb}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{bbB}");
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{Bbb}");
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{NONE}" );
#endif
  scales[0]->SetMaximum(+1.0);
  scales[0]->SetMinimum(-1.0);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
  scales[4]->Draw("same");
  zero->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""), "update");
  output->cd();
  data ->Write("data_obs");
  Qbb  ->Write("Qbb"     );
  bbX  ->Write("bbX"     );
  Cbb  ->Write("Cbb"     );
  bbB  ->Write("bbB"     );
  Bbb  ->Write("Bbb"     );
#ifdef MSSM
  bbH  ->Write("bbH"     );
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
}
void makeMuVMassPlot(bool iUseWWType = false) { 
  SetStyle();
  TCanvas *lCan = new TCanvas("A","A",600,600);
  // lCan->SetGridx(1);
  //lCan->SetGridy(1);
  lCan->SetRightMargin(0.14);

  double *lTX1 = new double[2];
  double *lTX2 = new double[2];
  double lMinNLL = 1000;
  double lVMin = 0;
  double *lMin = new double[36];     
  if(!iUseWWType) for(int i0 = 0; i0 < 36; i0++) { lMin[i0] = getMinNLL(110+i0*1.); if(lMin[i0] < lVMin) {lVMin = lMin[i0]; lTX1[0] = 110+i0*1.;}}
  //lMin[17] = (lMin[16]+lMin[18])/2.;
  //lMin[21] = (lMin[20]+lMin[22])/2.;
  //lMin[29] = (lMin[28]+lMin[30])/2.;
  //lMin[34] = (lMin[33]+lMin[35])/2.;

  TFile *lFile = new TFile("/afs/cern.ch/user/p/pharris/public/massscan/cmb+.root");
  TTree *lTree = lFile->FindObjectAny("limit");
  TH2F *lH = new TH2F("2D","2D",36,109.5,145.5,50,-2.,3.);
  float  lNLL  = 0; lTree->SetBranchAddress("nll"     ,&lNLL);
  float  lMNLL = 0; lTree->SetBranchAddress("deltaNLL",&lMNLL);
  double lMH   = 0; lTree->SetBranchAddress("mh"      ,&lMH);
  float  lR    = 0; lTree->SetBranchAddress("r"       ,&lR);
  
  if(iUseWWType) { 
    for(int i0 = 0; i0 < lTree->GetEntries(); i0++) { 
      lTree->GetEntry(i0);
      if(lR < 0.1 && lR > 0)  lMin[int(lMH-110)] = -lMNLL;
    }
    lVMin = 10000;
    for(int i0 = 0; i0 < lTree->GetEntries(); i0++) { 
      lTree->GetEntry(i0);
      double pMin =  lMin[int(lMH-110)] + lMNLL;
      if(pMin < lVMin) lVMin = pMin;
    }
  }
  for(int i0 = 0; i0 < lTree->GetEntries(); i0++) { 
    lTree->GetEntry(i0);
    //if(lMH == 125) continue;
    lNLL = 0.; //lMin  = 0.;
    lH->SetBinContent(lH->GetXaxis()->FindBin(lMH),lH->GetYaxis()->FindBin(lR),(lMNLL+lMin[lH->GetXaxis()->FindBin(lMH)-1]-lVMin)); 
    if(lMH == lTX1[0] && lMNLL < lMinNLL) {lMinNLL = lMNLL; lTX2[0] = lR;}
  }
  TH2F* lHC = lH->Clone("2D_v2");
  double lCont[3];
  lCont[0] = 1.17; 
  lCont[1] = 3.0;
  lCont[2] = 9.0;
  lHC->SetContour(2,lCont);
  //lCan->SetLogz();
  lHC->Draw("cont z list");
  lCan->Update();
  lHC->Draw("colz");

  TObjArray *lContours = (TObjArray*)gROOT->GetListOfSpecials()->FindObject("contours");
  int lTotalConts = lContours->GetSize();
  double *lTX = new double[2]; lTX[0] = 110;  lTX[1] = 145; 
  double *lTY = new double[2]; lTY[0] = -0.5; lTY[1] = 2.5;
  TGraph *lFirst = new TGraph(2,lTX,lTY); lFirst->SetLineColor(kWhite);
  lFirst->GetXaxis()->SetRangeUser(110,148);
  lFirst->Draw("al"); lFirst->SetTitle("");
  lH->GetYaxis()->SetRangeUser(-0.5,2.5);
  lFirst->GetXaxis()->SetTitle("m_{H}[GeV]");
  lFirst->GetXaxis()->SetTitleOffset(1.0);
  lFirst->GetYaxis()->SetTitle("#mu_{best-fit}");
  lFirst->GetYaxis()->SetTitleOffset(1.2);

  lH->GetXaxis()->SetTitle("m_{H}[GeV]");
  lH->GetXaxis()->SetTitleOffset(1.0);
  lH->GetYaxis()->SetTitle("#mu_{best-fit}");
  lH->GetYaxis()->SetTitleOffset(1.2);

  lTX1[1] = lTX1[0]; lTX2[1] = lTX2[1]+0.001;
  TGraph *lSecond = new TGraph(1,lTX1,lTX2); lSecond->SetMarkerStyle(34); lSecond->SetMarkerSize(3.5);
  //lSecond->Draw("p");
  
  TLegend *lL = new TLegend(0.65,0.15,0.85,0.35); lL->SetBorderSize(0); lL->SetFillColor(0); lL->SetFillStyle(0); 
  for(i0 = 0; i0 < lTotalConts; i0++){
    pContLevel = (TList*)lContours->At(lTotalConts-1.-i0);
    // Get first graph from list on curves on this level
    std::vector<double> lX; 
    std::vector<double> lY; 
    pCurv = (TGraph*)pContLevel->First();
    for(int i1 = 0; i1 < pContLevel->GetSize(); i1++){
      for(int i2  = 0; i2 < pCurv->GetN(); i2++) {lX.push_back(pCurv->GetX()[i2]); lY.push_back(pCurv->GetY()[i2]);}
      //pCurv->GetPoint(0, x0, y0);
      pCurv->SetLineColor(kBlack);//kGreen+i0);
      pCCurv = (TGraph*)pCurv->Clone();
      if(i0 == 0) pCCurv->SetFillColor(0);
      if(i0 == 1) pCCurv->SetFillColor(0);
      //if(i0 == 1) pCCurv->SetLineStyle(kDashed);
      pCCurv->SetLineWidth(3);
      pCCurv->GetXaxis()->SetRangeUser(0,3.0);
      //if(i0 == 0) pCCurv->Draw("AL");
      //if(i0 != -10) pCCurv->Draw("LC");
      //l.DrawLatex(x0,y0,val);
      pCurv = (TGraph*)pContLevel->After(pCurv); // Get Next graph
    }
    TGraph *lTotal = new TGraph(lX.size(),&lX[0],&lY[0]);
    lTotal->SetLineWidth(3);
    lTotal->SetFillColor(kGreen+i0*2);
    lTotal->SetFillStyle(3001);
    //lTotal->Draw("lf");
    
    //if(i0 == 0) lTotal->Draw("alf");
    //if(i0 == 0) lTotal->Draw("alf");
    //for(int iX = 0; iX < lTotal->GetN(); iX++) cout << "===> " << lTotal->GetX()[iX] << " -- " << lTotal->GetY()[iX] << endl;
    //if(i0 != -10) lTotal->Draw("lfC");
    bool pSwitch = false;
    int  pSign   = -1.;   if(lTotal->GetX()[0] > lTotal->GetX()[1]) pSign = 1;
    double pXOld = lTotal->GetX()[lTotal->GetN()-1];
    std::vector<double> pXLeft;
    std::vector<double> pXRight;
    std::vector<double> pYLeft;
    std::vector<double> pYRight;
    for(int iX = 0; iX < lTotal->GetN(); iX++) { 
      double pX = lTotal->GetX()[iX];
      if(pSign*pX > pSign*pXOld ) {pSwitch = !pSwitch; pSign *= -1;}
      if(!pSwitch) {pXLeft.push_back(lTotal->GetX()[iX]); pYLeft.push_back(lTotal->GetY()[iX]); }
      if(pSwitch) {pXRight.push_back(lTotal->GetX()[iX]); pYRight.push_back(lTotal->GetY()[iX]); }
      pXOld = pX;
    }
    TGraph *lLeftTotal  = new TGraph(pXLeft.size() ,&pXLeft[0],&pYLeft[0]);
    TGraph *lRightTotal = new TGraph(pXRight.size(),&pXRight[0],&pYRight[0]);
    lLeftTotal->SetLineColor(kRed);
    lRightTotal->SetLineColor(kBlue);
    lLeftTotal->SetLineStyle(kDashed);
    lRightTotal->SetLineStyle(kDashed);
    //lLeftTotal->Draw("l");
    //lRightTotal->Draw("l");
    
    TGraphSmooth *lGS0 = new TGraphSmooth("normal");
    TGraphSmooth *lGS1 = new TGraphSmooth("normal");
    TGraph *lSmooth0 = lGS0->SmoothSuper(lRightTotal,"",0.,0.);
    TGraph *lSmooth1 = lGS1->SmoothSuper(lLeftTotal,"",0.,0.) ;
    lSmooth0->Draw("l");
    lSmooth1->Draw("l");
    std::vector<double> pXSmooth;
    std::vector<double> pYSmooth;
    std::vector<double> pXSmooth1;
    std::vector<double> pYSmooth1;
    cout << "==" << lSmooth0->GetN() << " -- " <<lSmooth1->GetN() << endl;
    for(int iX = 0; iX < lSmooth0->GetN(); iX++) {pXSmooth.push_back(lSmooth0->GetX()[iX]);                    pYSmooth.push_back(lSmooth0->GetY()[iX]);}
    for(int iX = 0; iX < lSmooth1->GetN(); iX++) {pXSmooth.push_back(lSmooth1->GetX()[lSmooth1->GetN()-iX-1]); pYSmooth.push_back(lSmooth1->GetY()[lSmooth1->GetN()-iX-1]);}

    for(int iX = 0; iX < lSmooth0->GetN(); iX++) {pXSmooth1.push_back(lSmooth0->GetX()[iX]);                    pYSmooth1.push_back(lSmooth0->GetY()[iX]);}
    for(int iX = 0; iX < lSmooth1->GetN(); iX++) {pXSmooth1.push_back(lSmooth1->GetX()[lSmooth1->GetN()-iX-1]); pYSmooth1.push_back(lSmooth1->GetY()[lSmooth1->GetN()-iX-1]);}
    //if(i0 == 1) {pXSmooth1.push_back(lSmooth1->GetX()[0]); pYSmooth1.push_back(lSmooth1->GetY()[0]);}
    TGraph *pSmoothShape  = new TGraph(pXSmooth.size() ,&pXSmooth [0],&pYSmooth [0]);
    TGraph *pSmoothShape1 = new TGraph(pXSmooth1.size(),&pXSmooth1[0],&pYSmooth1[0]);
    if(i0 == 1) {TLine  *lLine = new TLine(pXSmooth1[0],pYSmooth1[0],pXSmooth1[pXSmooth1.size()-1],pYSmooth1[pYSmooth1.size()-1]); lLine->Draw();}
    pSmoothShape1->SetLineColor(kBlack);
    pSmoothShape1->SetLineWidth(2);
    pSmoothShape->SetFillColor(kGreen+i0*2);
    pSmoothShape->SetFillStyle(3001);
    pSmoothShape->Draw("lf");
    pSmoothShape1->Draw("l");
    if(i0 == 0) lL->AddEntry(lTotal,"95% CL","lf");
    if(i0 == 1) lL->AddEntry(lTotal,"68% CL","lf");
  }
  lL->AddEntry(lSecond,"BestFit","p");
  lSecond->Draw("lp");
  lL->Draw();
  
  std::string masslabel = "m_{H}"; double mass = 125;
  TString label = TString::Format("%s = 135 GeV", masslabel.c_str());//, 125.);
  TPaveText* textlabel = new TPaveText(0.18, 0.81, 0.50, 0.90, "NDC");
  textlabel->SetBorderSize(   0 );
  textlabel->SetFillStyle (   0 );
  textlabel->SetTextAlign (  12 );
  textlabel->SetTextSize  (0.04 );
  textlabel->SetTextColor (   1 );
  textlabel->SetTextFont  (  62 );
  textlabel->AddText(label);
  //textlabel->Draw();
  CMSPrelim("Preliminary, H#rightarrow#tau#tau,L = 24.3 fb^{-1}", "", 0.145, 0.835);
  gPad->RedrawAxis();
  lCan->Update();

  lCan->SaveAs("cmb+_muvmass.png");
  lCan->SaveAs("cmb+_muvmass.pdf");
  lCan->SaveAs("cmb+_muvmass.eps");
}
示例#12
0
int fgtRawSpectraQA( const Char_t *filenameIn = "testfile.daq",
                     const Char_t *filebaseOut = "testfile.rawQA",
                     Int_t date = 20120115,
                     Int_t time = 0,
                     Float_t pedRelThres = 0,    // 0 = no cut, otherwise: # of sigma above pedestal for cut
                     Int_t nevents = 2000,
                     Int_t timebin = 2,
                     UInt_t statusMask,
                     Bool_t cutShortEvents = 1 ){

   LoadLibs();
   Int_t ierr = 0;

   //
   // START CONSTRUCTING THE CHAIN
   //

   cout << "Constructing the chain" << endl;
   analysisChain = new StChain("eemcAnalysisChain");

   //
   // THE DATABASE
   //

   // note: DB is used to convert elec coords into geoIds in
   // StEvent/StFgtStrip, and do determine the disc and quad given
   // an rdo/arm/apv combination.

   cout << "Constructing St_db_Maker" << endl;

   TString dir0 = "MySQL:StarDb";
   TString dir1 = "$STAR/StarDb";
   St_db_Maker *dbMkr = new St_db_Maker( "dbMkr", dir0, dir1 );
   dbMkr->SetDateTime(date,time);

   cout << "Constructing StFgtDbMaker" << endl;
   fgtDbMkr = new StFgtDbMaker( "fgtDbMkr" );

   //
   // NOW THE OTHER READERS AND MAKERS
   //

   cout << "Constructing the daq reader" << endl;
   daqRdr = new StFgtRawDaqReader( "daqReader", filenameIn, "" );
   daqRdr->setIsCosmic( 0 );
   daqRdr->cutShortEvents( cutShortEvents );

//    a2cMkr = new StFgtA2CMaker( "a2cMkr" );
//    a2cMkr->setStatusMask( statusMask );
//    a2cMkr->setAbsThres( -10000 );  // set to below -4096 to skip cut
//    a2cMkr->setRelThres( pedRelThres );  // set to zero to skip cut

   cout << "Constructing the QA Makers" << endl;
   qaMkr = new StFgtQaRawOctAdc( "qaMkr", 2 );
   qaMkr->setTimeBin( 2 );

   // debug
   analysisChain->ls(4);

   cout << "Initializing" << endl;
   ierr = analysisChain->Init();

   if( ierr ){
      cout << "Error initializing" << endl;
      return;
   };

   if( nevents < 0 )
      nevents = 1<<30; // a big number

   cout << "max nevents = " << nevents << endl;
   for( int i=0; i<nevents && !ierr; ++i ){

      if( i+1 % 100 == 0 )
         cout << "\ton event number " << i << endl;

      //cout << "clear" << endl;
      analysisChain->Clear();

      //cout << "make" << endl;
      ierr = analysisChain->Make();

   };

   //
   // Calls the ::Finish() method on all makers
   //
   cout << "finish" << endl;
   analysisChain->Finish();

   cout << "Making plots" << endl;

   gROOT->SetStyle("Plain");
   gStyle->SetOptStat(0);
   gStyle->SetPalette(1);

   can = new TCanvas( "fgtRawQA", "fgtRawQA", 850, 1100);
   can->Divide( 1, 4 );

   // open output file
   can->Print( (std::string(filebaseOut) + ".ps[").data() );

   //std::vector< TH2F* >& hist = qaMkr->getHistVec();

   cout << "First hist at " << qaMkr->getHist(0) << endl;

   cout << "Finding max" << endl;

   // get max
   Float_t max = 0;
   for( Int_t idx = 0; idx < 48; ++idx ){
      if( qaMkr->getHist(idx) )
         if( qaMkr->getHist(idx)->GetMaximum() > max )
            max = qaMkr->getHist(idx)->GetMaximum();
   };
   max = 0.9*max;

   cout << "Max is " << max << endl;

   TH2F *dummy[4];
   const Char_t dummyNames[4][20] = { "dummy1", "dummy2", "dummy3", "dummy4" };

   Float_t xMin = qaMkr->getHist(0)->GetXaxis()->GetXmin();
   Float_t xMax = qaMkr->getHist(0)->GetXaxis()->GetXmax();
   Float_t yMin = qaMkr->getHist(0)->GetYaxis()->GetXmin();
   Float_t yMax = qaMkr->getHist(0)->GetYaxis()->GetXmax();

   for( Int_t i=0; i<4; ++i )
      dummy[i] = new TH2F( dummyNames[i], "", 5, xMin, xMax, 1, yMin, yMax );

   std::stringstream ss;

   Int_t subpad = 1;
   idx = 0;
   for( Int_t rdo = 1; rdo < 3; ++rdo ){
      for( Int_t arm = 0; arm < 6; ++arm ){
         for( Int_t startIdx = 0; startIdx < 4; ++startIdx, ++idx ){
            for( Int_t oct = 0; oct < 1; ++oct ){

               cout << "rdo/arm/disc/oct = " << rdo << '/' << arm << '/' << startIdx << '/' << oct << endl;
               if( qaMkr->getHist(idx)->GetEntries() > 0 ){
                  can->cd(subpad);
                  gPad->SetLeftMargin( 0.06 );
                  gPad->SetRightMargin( 0.05 );
                  gPad->SetBottomMargin( 0.11 );

                  qaMkr->getHist(idx)->SetMaximum( max );
                  dummy[subpad-1]->GetXaxis()->SetTitleOffset(0.9);
                  dummy[subpad-1]->GetXaxis()->SetTitleSize(0.06);
                  dummy[subpad-1]->GetXaxis()->SetLabelSize(0.06);
                  dummy[subpad-1]->GetYaxis()->SetTitleOffset(0.55);
                  dummy[subpad-1]->GetYaxis()->SetTitleSize(0.06);
                  dummy[subpad-1]->GetYaxis()->SetLabelSize(0.06);

                  gPad->SetGridx(0);
                  gPad->SetGridy(0);

                  for( Int_t i = 0; i<5; ++i ){
                     ss.str("");
                     ss.clear();
                     ss << "channels in APV "; // startArray[startIdx]+i;
                     dummy[subpad-1]->GetXaxis()->SetBinLabel( i+1, ss.str().data() );
                  };
                  dummy[subpad-1]->GetXaxis()->SetNdivisions(222,0);
                  dummy[subpad-1]->SetMinimum( 0 );
                  dummy[subpad-1]->SetMaximum( max );
                  dummy[subpad-1]->SetTitle( qaMkr->getHist(idx)->GetTitle() );
                  qaMkr->getHist(idx)->SetTitle("");

                  dummy[subpad-1]->GetYaxis()->SetTitle( qaMkr->getHist(idx)->GetYaxis()->GetTitle() );
                  qaMkr->getHist(idx)->GetYaxis()->SetTitle("");
                  dummy[subpad-1]->Draw("COLZ");

                  qaMkr->getHist(idx)->Draw("COLZ SAME");

                  gPad->Update();
                  gPad->Modified();

                  TPaveText *title = (TPaveText*)(gPad->GetPrimitive("title"));
                  if( title ){
                     title->SetX1NDC( 0.045 );
                     title->SetX2NDC( 0.55 );
                     title->SetY1NDC( 0.91 ) ;
                     title->SetY2NDC( 0.999 );
                     title->SetBorderSize(0);
                     title->SetTextAlign( 12 );
                     title->SetTextColor(kBlue);
                     title->Draw();
                  };

                  TPave *palette = (TPave*)(gPad->GetPrimitive("palette"));
                  if( palette ){
                     palette->SetX1NDC( 0.955 );
                     palette->SetX2NDC( 0.985 );
                     palette->Draw();
                  };

                  ++subpad;
                  if( subpad == 5 ){
                     subpad = 1;
                     can->Print( (std::string(filebaseOut) + ".ps").data() );
                  };
               };
            };
         };
      };
   };

   if( subpad != 1 )
      can->Print( (std::string(filebaseOut) + ".ps").data() );
   can->Print( (std::string(filebaseOut) + ".ps]").data() );

   gSystem->Exec(( std::string("ps2pdf -dAutoRotatePages=/None ") + filebaseOut + ".ps" ).data());


   cerr << "\tall done" << endl;
   return;
};
void 
HTT_TT_X(bool scaled=true, bool log=false, float min=0., float max=-1., const char* inputfile="root/$HISTFILE", const char* directory="$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category_extra = "";
  if(std::string(directory) == std::string("emu_0jet_low"  )){ category_extra = "0 jet, low p_{T}";  }
  if(std::string(directory) == std::string("emu_0jet_high" )){ category_extra = "0 jet, high p_{T}"; }
  if(std::string(directory) == std::string("emu_boost_low" )){ category_extra = "1 jet, low p_{T}";  }
  if(std::string(directory) == std::string("emu_boost_high")){ category_extra = "1 jet, high p_{T}"; }
  if(std::string(directory) == std::string("emu_vbf"       )){ category_extra = "2 jet (VBF)";       }
  if(std::string(directory) == std::string("emu_nobtag"    )){ category_extra = "No B-Tag";          }
  if(std::string(directory) == std::string("emu_btag"      )){ category_extra = "B-Tag";             }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS Preliminary,  ZH#rightarrow#lltau#tau, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  ZH#rightarrowll#tau#tau, 19.4 fb^{-1} at 8 TeV";}
#ifdef MSSM
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 19.4 fb^{-1} at 8 TeV";}
#endif
  
  TFile* input = new TFile(inputfile);
  TH1F* ZZ  = refill((TH1F*)input->Get(TString::Format("%s/ZZ"   , directory)), "ZZ"); InitHist(ZZ, "", "", kMagenta-10, 1001);
  TH1F* GGToZZ2L2L  = refill((TH1F*)input->Get(TString::Format("%s/GGToZZ2L2L"   , directory)), "GGToZZ2L2L"); InitHist(GGToZZ2L2L, "", "", kMagenta-10, 1001);
  TH1F* Zjets    = refill((TH1F*)input->Get(TString::Format("%s/Zjets"     , directory)), "Zjets"  ); InitHist(Zjets  , "", "", kRed    + 2, 1001);
#ifndef DROP_SIGNAL
  TH1F* ZH_htt    = refill((TH1F*)input->Get(TString::Format("%s/ZH_htt"  , directory)+"125"), "ZH_htt"  ); InitSignal(ZH_htt); ZH_htt->Scale(SIGNAL_SCALE);
  TH1F* ZH_hww    = refill((TH1F*)input->Get(TString::Format("%s/ZH_hww"  , directory)+"125"), "ZH_hww"  ); InitSignal(ZH_hww); ZH_hww->Scale(SIGNAL_SCALE);
#endif
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)ZZ->Clone("ref");
  ref->Add(GGToZZ2L2L);
  ref->Add(Zjets  );

  double unscaled[5];
  unscaled[0] = ZZ->Integral();
  unscaled[1] = GGToZZ2L2L->Integral();
  unscaled[2] = Zjets  ->Integral();
#ifndef DROP_SIGNAL
  unscaled[3] = ZH_htt  ->Integral();
  unscaled[4] = ZH_hww  ->Integral();
#endif

  if(scaled){
    rescale(ZZ, 1);
    rescale(GGToZZ2L2L, 2);
    rescale(Zjets,   3);
#ifndef DROP_SIGNAL
    rescale(ZH_htt,   4);
    rescale(ZH_hww,   5);
#endif
  }

  TH1F* scales[5];
  scales[0] = new TH1F("scales-ZZ", "", 5, 0, 5);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (ZZ->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-GGToZZ2L2L", "", 5, 0, 5);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (GGToZZ2L2L->Integral()/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-Zjets"  , "", 5, 0, 5);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (Zjets  ->Integral()/unscaled[2]-1.) : 0.);
#ifndef DROP_SIGNAL
  scales[3] = new TH1F("scales-ZH_htt"  , "", 5, 0, 5);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (ZH_htt  ->Integral()/unscaled[3]-1.) : 0.);
  scales[4] = new TH1F("scales-ZH_hww"  , "", 5, 0, 5);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ZH_hww  ->Integral()/unscaled[4]-1.) : 0.);
#endif

  GGToZZ2L2L->Add(Zjets);
  ZZ  ->Add(GGToZZ2L2L);
  if(log){
#ifndef DROP_SIGNAL
    ZH_htt  ->Add(ZH_hww );
#endif
  }
  else{
#ifndef DROP_SIGNAL
    ZH_htt   ->Add(ZH_hww);
#endif
  }

  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(350)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(1000)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(350));
#endif

  data->SetNdivisions(505);
  data->SetMinimum(min);
  float maxZZ=ZZ->GetBinContent(ZZ->GetMaximumBin()); float maxdata=data->GetBinContent(data->GetMaximumBin());
  if (maxdata>maxZZ)
     data->SetMaximum(1.8*maxdata);
  else
     data->SetMaximum(1.8*maxZZ);
  data->Draw("e");

//  TH1F* errorBand = (TH1F*)ZZ ->Clone();
  TH1F* errorBand = (TH1F*)Zjets ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  errorBand  ->Scale(0.15);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  //if(log){
    ZZ  ->Draw("histsame");
    Zjets->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ZH_htt  ->Draw("histsame");
#endif
  //}
  //else{
//#ifndef DROP_SIGNAL
//    ggH  ->Draw("histsame");
//#endif
//    Ztt  ->Draw("histsame");
//    ttbar->Draw("histsame");
//    EWK  ->Draw("histsame");
//    Fakes->Draw("histsame");
//    $DRAW_ERROR
//  }
  data->Draw("esame");
  canv->RedrawAxis();

//  //CMSPrelim(dataset, "#tau_{e}#tau_{#mu}", 0.17, 0.835);  
  CMSPrelim(dataset, "", 0.16, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  if (directory=="eett_zh") 
    chan->AddText("#tau#tau");
  else
    chan->AddText("#mu#mu#tau#tau");
  chan->Draw();
//
//  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
//  cat->SetBorderSize(   0 );
//  cat->SetFillStyle(    0 );
//  cat->SetTextAlign(   12 );
//  cat->SetTextSize ( 0.05 );
//  cat->SetTextColor(    1 );
//  cat->SetTextFont (   62 );
//  cat->AddText(category_extra);
//  cat->Draw();
//
//#ifdef MSSM
//  TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
//  massA->SetBorderSize(   0 );
//  massA->SetFillStyle(    0 );
//  massA->SetTextAlign(   12 );
//  massA->SetTextSize ( 0.03 );
//  massA->SetTextColor(    1 );
//  massA->SetTextFont (   62 );
//  massA->AddText("m_{A}=$MAGeV");
//  massA->Draw();
//
//  TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
//  tanb->SetBorderSize(   0 );
//  tanb->SetFillStyle(    0 );
//  tanb->SetTextAlign(   12 );
//  tanb->SetTextSize ( 0.03 );
//  tanb->SetTextColor(    1 );
//  tanb->SetTextFont (   62 );
//  tanb->AddText("tan#beta=$TANB");
//  tanb->Draw();
// 
//  TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
//  scen->SetBorderSize(   0 );
//  scen->SetFillStyle(    0 );
//  scen->SetTextAlign(   12 );
//  scen->SetTextSize ( 0.03 );
//  scen->SetTextColor(    1 );
//  scen->SetTextFont (   62 );
//  scen->AddText("mhmax");
//  scen->Draw();
//#endif
//
//#ifdef MSSM  
//  TLegend* leg = new TLegend(0.45, 0.65, 0.95, 0.90);
//  SetLegendStyle(leg);
//  leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau" , "L" );
//#else
  TLegend* leg = new TLegend(0.50, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
//#ifndef DROP_SIGNAL
//  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ZH_htt  , TString::Format("%.0f#timesZH(125 GeV)#rightarrowll#tau#tau", SIGNAL_SCALE) , "L" );
//  }
//  else{
//    leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
//  }
//#endif
//#endif
  leg->AddEntry(data , "observed"                       , "LP");
  leg->AddEntry(ZZ  , "ZZ"           , "F" );
  leg->AddEntry(Zjets, "Reducible"                       , "F" );
//  leg->AddEntry(EWK  , "electroweak"                    , "F" );
//  leg->AddEntry(Fakes, "QCD"                            , "F" );
  $ERROR_LEGEND
  leg->Draw();
//
////#ifdef MSSM
////  TPaveText* mssm  = new TPaveText(0.69, 0.85, 0.90, 0.90, "NDC");
////  mssm->SetBorderSize(   0 );
////  mssm->SetFillStyle(    0 );
////  mssm->SetTextAlign(   12 );
////  mssm->SetTextSize ( 0.03 );
////  mssm->SetTextColor(    1 );
////  mssm->SetTextFont (   62 );
////  mssm->AddText("(m_{A}=250, tan#beta=5)");
////  mssm->Draw();
////#else
////  TPaveText* mssm  = new TPaveText(0.83, 0.85, 0.95, 0.90, "NDC");
////  mssm->SetBorderSize(   0 );
////  mssm->SetFillStyle(    0 );
////  mssm->SetTextAlign(   12 );
////  mssm->SetTextSize ( 0.03 );
////  mssm->SetTextColor(    1 );
////  mssm->SetTextFont (   62 );
////  mssm->AddText("m_{H}=125");
////  mssm->Draw();
////#endif
//
//  /*
//    Ratio Data over MC
//  */
//  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
//  canv0->SetGridx();
//  canv0->SetGridy();
//  canv0->cd();
//
//  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
//  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
//  rat1->Divide(Ztt);
//  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
//    if(rat1->GetBinContent(ibin+1)>0){
//      // catch cases of 0 bins, which would lead to 0-alpha*0-1
//      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
//    }
//    zero->SetBinContent(ibin+1, 0.);
//  }
//  rat1->SetLineColor(kBlack);
//  rat1->SetFillColor(kGray );
//  rat1->SetMaximum(+0.5);
//  rat1->SetMinimum(-0.5);
//  rat1->GetYaxis()->CenterTitle();
//  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
//  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
//  rat1->Draw();
//  zero->SetLineColor(kBlack);
//  zero->Draw("same");
//  canv0->RedrawAxis();
//
//  /*
//    Ratio After fit over Prefit
//  */
//  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
//  canv1->SetGridx();
//  canv1->SetGridy();
//  canv1->cd();
//
//  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
//  rat2->Divide(ref);
//  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
//    if(rat2->GetBinContent(ibin+1)>0){
//      // catch cases of 0 bins, which would lead to 0-alpha*0-1
//      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
//    }
//  }
//  rat2->SetLineColor(kRed+ 3);
//  rat2->SetFillColor(kRed-10);
//  rat2->SetMaximum(+0.3);
//  rat2->SetMinimum(-0.3);
//  rat2->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
//  rat2->GetYaxis()->CenterTitle();
//  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
//  rat2->GetXaxis()->SetRange(0, 28);
//  rat2->Draw();
//  zero->SetLineColor(kBlack);
//  zero->Draw("same");
//  canv1->RedrawAxis();
//
//  /*
//    Relative shift per sample
//  */
//  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
//  canv2->SetGridx();
//  canv2->SetGridy();
//  canv2->cd();
//
//  InitHist  (scales[0], "", "", kMagenta-10, 1001);
//  InitHist  (scales[1], "", "", kRed    + 2, 1001);
//  InitHist  (scales[2], "", "", kBlue   - 8, 1001);
//  InitHist  (scales[3], "", "", kOrange - 4, 1001);
//#ifndef DROP_SIGNAL
//  InitSignal(scales[4]);
//  InitSignal(scales[5]);
//  InitSignal(scales[6]);
//#endif
//  scales[0]->Draw();
//  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
//  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
//  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
//  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
//#ifdef MSSM
//  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
//  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
//  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{NONE}" );
//#else
//  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
//  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH}"  );
//  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{VH}"   );
//#endif
//  scales[0]->SetMaximum(+1.0);
//  scales[0]->SetMinimum(-1.0);
//  scales[0]->GetYaxis()->CenterTitle();
//  scales[0]->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
//  scales[1]->Draw("same");
//  scales[2]->Draw("same");
//  scales[3]->Draw("same");
//#ifndef DROP_SIGNAL
//  scales[4]->Draw("same");
//  scales[5]->Draw("same");
//  scales[6]->Draw("same");
//#endif
//  zero->Draw("same");
//  canv2->RedrawAxis();
//
//  /*
//    prepare output
//  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.png"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.pdf"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.eps"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
//  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
//  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
//  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
//  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
//  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
//  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
//  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
//  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
//  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  TFile* output = new TFile(TString::Format("%s_%sscaled_%s_%s.root", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""), "update");
  output->cd(); 
  data ->Write("data_obs");
  ZZ->Write("ZZ"   );
  Zjets  ->Write("Zjets"     );
  ZH_htt->Write("ZH_htt"   );
  ZH_hww  ->Write("ZH_hww"     );
//#ifdef MSSM
//  ggH  ->Write("ggH"     );
//  bbH  ->Write("bbH"     );
//#else
//#ifndef DROP_SIGNAL
//  ggH  ->Write("ggH"     );
//  qqH  ->Write("qqH"     );
//  VH   ->Write("VH"      );
//#endif
//#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
}
void PlotChargeFieldFocus2D( const TString &sim, Int_t time, Int_t zoom=2, Int_t Nbins=2, const TString &options="") {
  
#ifdef __CINT__  
  gSystem->Load("libplasma.so");
#endif

  PlasmaGlob::Initialize();

  // Palettes!
  gROOT->Macro("PlasmaPalettes.C");

  // Init Units table
  PUnits::UnitsTable::Get();
  
  // Load PData
  PData *pData = PData::Get(sim.Data());
  pData->LoadFileNames(time);
  if(!pData->IsInit()) return;

  TString opt = options;
 
  // More makeup
  if(opt.Contains("grid")) {
    gStyle->SetPadGridX(1);
    gStyle->SetPadGridY(1);
  }
 
  gStyle->SetTitleFont(42);
  gStyle->SetStatFont(42);
  gStyle->SetTextFont(42);
  gStyle->SetTitleFont(42,"xyz");
  gStyle->SetLabelFont(42,"xyz");

  // Some plasma constants
  Double_t n0 = pData->GetPlasmaDensity();
  Double_t kp = pData->GetPlasmaK();
  Double_t skindepth = 1.;
  if(kp!=0.0) skindepth = 1/kp;
  Double_t E0 = pData->GetPlasmaE0();

  // Some beam properties:
  Float_t Ebeam = pData->GetBeamEnergy() * PUnits::MeV;
  Float_t gamma = Ebeam / PConst::ElectronMassE;
  Float_t vbeam = TMath::Sqrt(1 - 1/(gamma*gamma));
  // cout << Form(" - Bunch gamma      = %8.4f", gamma ) << endl;
  // cout << Form(" - Bunch velocity   = %8.4f c", vbeam ) << endl;
  Float_t nb = pData->GetBeamDensity();
  
  // Time in OU
  Float_t Time = pData->GetRealTime();
  // z start of the plasma in normalized units.
  Float_t zStartPlasma = pData->GetPlasmaStart()*kp;
  // z start of the beam in normalized units.
  Float_t zStartBeam = pData->GetBeamStart()*kp;
  // z start of the neutral in normalized units.
  Float_t zStartNeutral = pData->GetNeutralStart()*kp;
  // z end of the neutral in normalized units.
  Float_t zEndNeutral = pData->GetNeutralEnd()*kp;
  
  if(opt.Contains("center")) {
    Time -= zStartPlasma;
    if(opt.Contains("comov"))      // Centers on the head of the beam.
      Time += zStartBeam;
  }
  Float_t shiftz = pData->Shift(opt);
  //  cout << "Shift = " << shiftz << endl;
  
  // Calculate the "axis range" in number of bins. If Nbins==0 a RMS width is taken.
  Double_t rms0 = pData->GetBeamRmsY() * kp;
  if(pData->IsCyl())  rms0  = pData->GetBeamRmsR() * kp;
  
  Int_t FirstyBin = 0;
  Int_t LastyBin = 0;
  if(Nbins==0) { 
    Nbins =  TMath::Nint(rms0 / pData->GetDX(1));
  }
  
  // Slice width limits.
  if(!pData->IsCyl()) {
    FirstyBin = pData->GetNX(1)/2 + 1 - Nbins;
    LastyBin =  pData->GetNX(1)/2 + Nbins;
  } else {
    FirstyBin = 1; 
    LastyBin  = Nbins;
  }
  // -------------------------------------------------------------------------------

  // Get charge density histos
  Int_t Nspecies = pData->NSpecies();
  TH2F **hDen2D = new TH2F*[Nspecies];
  TH1F **hDen1D = new TH1F*[Nspecies];
  for(Int_t i=0;i<Nspecies;i++) {

    hDen2D[i] = NULL;
    hDen1D[i] = NULL;
    
    if(!pData->GetChargeFileName(i)) 
      continue;

    cout << Form(" Getting charge density of specie: ") << i << endl;

    
    char hName[24];
    sprintf(hName,"hDen2D_%i",i);
    hDen2D[i] = (TH2F*) gROOT->FindObject(hName);
    if(hDen2D[i]) delete hDen2D[i];

    if(!pData->Is3D())
      hDen2D[i] = pData->GetCharge(i,opt);
    else
      hDen2D[i] = pData->GetCharge2DSliceZY(i,-1,Nbins,opt+"avg");

    //  cout << Form(" Charge density of specie '%s' loaded into histogram '%s'",pData->GetSpeciesName(i).c_str(),hName) << endl;
    
    hDen2D[i]->SetName(hName);
    hDen2D[i]->GetXaxis()->CenterTitle();
    hDen2D[i]->GetYaxis()->CenterTitle();
    hDen2D[i]->GetZaxis()->CenterTitle();
    
    if(opt.Contains("comov"))
      hDen2D[i]->GetXaxis()->SetTitle("#zeta [c/#omega_{p}]");
    else
      hDen2D[i]->GetXaxis()->SetTitle("z [c/#omega_{p}]");
    
    if(pData->IsCyl()) 
      hDen2D[i]->GetYaxis()->SetTitle("r [c/#omega_{p}]");
    else
      hDen2D[i]->GetYaxis()->SetTitle("y [c/#omega_{p}]");

    hDen2D[i]->GetZaxis()->SetTitle("n [n_{0}]");
    
    if(!opt.Contains("1dline")) continue;
    
    sprintf(hName,"hDen1D_%i",i);
    hDen1D[i] = (TH1F*) gROOT->FindObject(hName);
    if(hDen1D[i]) delete hDen1D[i];
    
    if(pData->Is3D()) {
      hDen1D[i] = pData->GetH1SliceZ3D(pData->GetChargeFileName(i)->c_str(),"charge",-1,Nbins,-1,Nbins,opt+"avg");
    } else if(pData->IsCyl()) { // Cylindrical: The first bin with r>0 is actually the number 1 (not the 0).
      hDen1D[i] = pData->GetH1SliceZ(pData->GetChargeFileName(i)->c_str(),"charge",1,Nbins,opt+"avg");
    } else { // 2D cartesian
      hDen1D[i] = pData->GetH1SliceZ(pData->GetChargeFileName(i)->c_str(),"charge",-1,Nbins,opt+"avg");
    }
    
    //  cout << Form(" Charge density of specie '%s' loaded into histogram '%s'",pData->GetSpeciesName(i).c_str(),hName) << endl;
    
    hDen1D[i]->SetName(hName);
    hDen1D[i]->GetXaxis()->CenterTitle();
    hDen1D[i]->GetYaxis()->CenterTitle();
       
    if(opt.Contains("comov"))
      hDen1D[i]->GetXaxis()->SetTitle("#zeta [c/#omega_{p}]");
    else
      hDen1D[i]->GetXaxis()->SetTitle("z [c/#omega_{p}]");
    
    hDen1D[i]->GetYaxis()->SetTitle("n [n_{0}]");


  }
  
  // Get electric fields
  const Int_t Nfields = 3;
  TH2F **hE2D = new TH2F*[Nfields];
  TH1F **hE1D = new TH1F*[Nfields];
  for(Int_t i=0;i<Nfields;i++) {
    hE2D[i] = NULL;
    hE1D[i] = NULL;

    if(!pData->GetEfieldFileName(i))
      continue;

    cout << Form(" Getting electric field number ") << i+1 << endl;


    char hName[24];
    sprintf(hName,"hE2D_%i",i);
    hE2D[i] = (TH2F*) gROOT->FindObject(hName);
    if(hE2D[i]) delete hE2D[i];

    if(!pData->Is3D())
      hE2D[i] = pData->GetEField(i,opt);
    else
      hE2D[i] = pData->GetEField2DSliceZY(i,-1,Nbins,opt+"avg");
    
   
    hE2D[i]->SetName(hName);   
    hE2D[i]->GetXaxis()->CenterTitle();
    hE2D[i]->GetYaxis()->CenterTitle();
    hE2D[i]->GetZaxis()->CenterTitle();
    if(opt.Contains("comov"))
      hE2D[i]->GetXaxis()->SetTitle("#zeta [c/#omega_{p}]");
    else
      hE2D[i]->GetXaxis()->SetTitle("z [c/#omega_{p}]");
    
    if(pData->IsCyl()) 
      hE2D[i]->GetYaxis()->SetTitle("r [c/#omega_{p}]");
    else
      hE2D[i]->GetYaxis()->SetTitle("y [c/#omega_{p}]");
    
    if(i==0)
      hE2D[i]->GetZaxis()->SetTitle("E_{z} [E_{0}]");
    else if(i==1)
      hE2D[i]->GetZaxis()->SetTitle("E_{y} [E_{0}]");
    else if(i==2)
      hE2D[i]->GetZaxis()->SetTitle("E_{x} [E_{0}]");

    if(!opt.Contains("1dline")) continue;
     
    sprintf(hName,"hE1D_%i",i);
    hE1D[i] = (TH1F*) gROOT->FindObject(hName);
    if(hE1D[i]) delete hE1D[i];
    
    // 1D histograms
    char nam[3]; sprintf(nam,"e%i",i+1);
    if(pData->Is3D()) {
      
      if(i==0) 
	hE1D[i] = pData->GetH1SliceZ3D(pData->GetEfieldFileName(i)->c_str(),nam,-1,Nbins,-1,Nbins,opt+"avg");
      else  
	hE1D[i] = pData->GetH1SliceZ3D(pData->GetEfieldFileName(i)->c_str(),nam,-Nbins,Nbins,-Nbins,Nbins,opt+"avg");
      
    } else if(pData->IsCyl()) { // Cylindrical: The first bin with r>0 is actually the number 1 (not the 0).
      
      hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,1,Nbins,opt+"avg");
      
    } else { // 2D cartesian
      
      if(i==0) 
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,-1,Nbins,opt+"avg");
      else 
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,-Nbins,Nbins,opt+"avg");    
      
    }
    
    hE1D[i]->SetName(hName);
    if(opt.Contains("comov"))
      hE1D[i]->GetXaxis()->SetTitle("#zeta [c/#omega_{p}]");
    else
      hE1D[i]->GetXaxis()->SetTitle("z [c/#omega_{p}]");
    
    if(i==0)
      hE1D[i]->GetYaxis()->SetTitle("E_{z} [E_{0}]");
    else if(i==1)
      hE1D[i]->GetYaxis()->SetTitle("E_{y} [E_{0}]");
    else if(i==2)
      hE1D[i]->GetYaxis()->SetTitle("E_{x} [E_{0}]");
    
  }
  
  // Now, combine the electric field components into the total |E|
  // and calculate ionization probability for He:
  // Outter Helium electron
  Double_t Eion0 = 24.59 * PUnits::eV;
  Double_t Z     = 1;
  Double_t l     = 0;
  Double_t m     = 0;
  
  TH1F *hIonProb1D = NULL;
  if(opt.Contains("ionprob")) {
    hIonProb1D = (TH1F*) hE1D[0]->Clone("hIonProb1D");
    hIonProb1D->Reset();
    Int_t NbinsX = hE1D[0]->GetNbinsX();
    for(Int_t j=1;j<=NbinsX;j++) {
      Double_t E1 = hE1D[0]->GetBinContent(j);
      Double_t E2 = hE1D[1]->GetBinContent(j);
      Double_t E3 = hE1D[2]->GetBinContent(j);
      Double_t E  = TMath::Sqrt(E1*E1+E2*E2+E3*E3);
      
      E *= E0;
      
      Double_t IonProb = (PFunc::ADK(E,Eion0,Z,l,m)/PUnits::atomictime)*PUnits::femtosecond;
      hIonProb1D->SetBinContent(j,IonProb);
    }
    hIonProb1D->GetYaxis()->SetTitle("W_{ADK} [fs^{-1}]");
  }
  
  // Tunning the Histograms
  // ---------------------
  
  // Chaning to user units: 
  // --------------------------
  
  if(opt.Contains("units") && n0) {
    
    for(Int_t i=0;i<Nspecies;i++) {

      if(!hDen2D[i]) continue;

      Int_t NbinsX = hDen2D[i]->GetNbinsX();
      Float_t xMin = skindepth * hDen2D[i]->GetXaxis()->GetXmin() / PUnits::um;
      Float_t xMax = skindepth * hDen2D[i]->GetXaxis()->GetXmax() / PUnits::um;
      Int_t NbinsY = hDen2D[i]->GetNbinsY();
      Float_t yMin = skindepth * hDen2D[i]->GetYaxis()->GetXmin() / PUnits::um;
      Float_t yMax = skindepth * hDen2D[i]->GetYaxis()->GetXmax() / PUnits::um;
      hDen2D[i]->SetBins(NbinsX,xMin,xMax,NbinsY,yMin,yMax);
      // for(Int_t j=0;j<hDen2D[i]->GetNbinsX();j++) {
      // 	for(Int_t k=0;k<hDen2D[i]->GetNbinsY();k++) {
      // 	  hDen2D[i]->SetBinContent(j,k, hDen2D[i]->GetBinContent(j,k) * n0 / (1e15/PUnits::cm3) );
      // 	}
      // }

      if(pData->IsCyl())
	hDen2D[i]->GetYaxis()->SetTitle("r [#mum]");      
      else
	hDen2D[i]->GetYaxis()->SetTitle("y [#mum]");      

      if(opt.Contains("comov"))
	hDen2D[i]->GetXaxis()->SetTitle("#zeta [#mum]");
      else
	hDen2D[i]->GetXaxis()->SetTitle("z [#mum]");
      
      //      hDen2D[i]->GetZaxis()->SetTitle("n [10^{15}/cm^{3}]");
      
      if(!hDen1D[i]) continue;
      
      hDen1D[i]->SetBins(NbinsX,xMin,xMax);
      
      if(opt.Contains("comov"))
    	hDen1D[i]->GetXaxis()->SetTitle("#zeta [#mum]");
      else
    	hDen1D[i]->GetXaxis()->SetTitle("z [#mum]");
      
    }

    for(Int_t i=0;i<Nfields;i++) {
      Int_t NbinsX = hE2D[i]->GetNbinsX();
      Float_t xMin = skindepth * hE2D[i]->GetXaxis()->GetXmin() / PUnits::um;
      Float_t xMax = skindepth * hE2D[i]->GetXaxis()->GetXmax() / PUnits::um;
      Int_t NbinsY = hE2D[i]->GetNbinsY();
      Float_t yMin = skindepth * hE2D[i]->GetYaxis()->GetXmin() / PUnits::um;
      Float_t yMax = skindepth * hE2D[i]->GetYaxis()->GetXmax() / PUnits::um;
      hE2D[i]->SetBins(NbinsX,xMin,xMax,NbinsY,yMin,yMax);
      if(hE1D[i]) 
	hE1D[i]->SetBins(NbinsX,xMin,xMax);
	

      for(Int_t j=0;j<hE2D[i]->GetNbinsX();j++) {	
	for(Int_t k=0;k<hE2D[i]->GetNbinsY();k++) {
	  hE2D[i]->SetBinContent(j,k, hE2D[i]->GetBinContent(j,k) * ( E0 / (PUnits::GV/PUnits::m) ) );
	}
	
	if(!hE1D[i]) continue;
	hE1D[i]->SetBinContent(j, hE1D[i]->GetBinContent(j) * ( E0 / (PUnits::GV) ) );
	
      }
      
      if(pData->IsCyl())
	hE2D[i]->GetYaxis()->SetTitle("r [#mum]");      
      else
	hE2D[i]->GetYaxis()->SetTitle("y [#mum]");      
 
      if(opt.Contains("comov"))
	hE2D[i]->GetXaxis()->SetTitle("#zeta [#mum]");
      else
	hE2D[i]->GetXaxis()->SetTitle("z [#mum]");
      
      if(i==0)
	hE2D[i]->GetZaxis()->SetTitle("E_{z} [GV/m]");
      else if(i==1)
	hE2D[i]->GetZaxis()->SetTitle("E_{y} [GV/m]");
      else if(i==2)
	hE2D[i]->GetZaxis()->SetTitle("E_{x} [GV/m]");


      if(!hE1D[i]) continue;
      if(opt.Contains("comov"))
	hE1D[i]->GetXaxis()->SetTitle("#zeta [mm]");
      else
	hE1D[i]->GetXaxis()->SetTitle("z [mm]");
      
      if(i==0)
	hE1D[i]->GetYaxis()->SetTitle("E_{z} [GV/m]");
      else if(i==1)
	hE1D[i]->GetYaxis()->SetTitle("E_{y} [GV/m]");
      else if(i==2)
	hE1D[i]->GetYaxis()->SetTitle("E_{x} [GV/m]");
      
      
    }
    if(hIonProb1D) {
      Int_t NbinsX = hIonProb1D->GetNbinsX();
      Float_t xMin = skindepth * hIonProb1D->GetXaxis()->GetXmin() / PUnits::um;
      Float_t xMax = skindepth * hIonProb1D->GetXaxis()->GetXmax() / PUnits::um;
      hIonProb1D->SetBins(NbinsX,xMin,xMax);
    }
  }
  
  // --------------------------------------------------- Vertical Zoom ------------

  Float_t range    = (hDen2D[0]->GetYaxis()->GetXmax() - hDen2D[0]->GetYaxis()->GetXmin())/zoom;
  Float_t midPoint = (hDen2D[0]->GetYaxis()->GetXmax() + hDen2D[0]->GetYaxis()->GetXmin())/2.;
  Double_t ymin = midPoint-range/2;
  Double_t ymax = midPoint+range/2;
  if(pData->IsCyl()) {
    ymin = hDen2D[0]->GetYaxis()->GetXmin();
    ymax = range;
  }
  hDen2D[0]->GetYaxis()->SetRangeUser(ymin,ymax);
  hE2D[0]->GetYaxis()->SetRangeUser(ymin,ymax);
  hE2D[1]->GetYaxis()->SetRangeUser(ymin,ymax);
  
  // ------------- z Zoom --------------------------------- Plasma palette -----------
  // Set the range of the plasma charge density histogram for maximum constrast 
  // using a dynamic palette wich adjust the nominal value to a certain color.
  

  Float_t density = 1;
  // if(opt.Contains("units") && n0)
  //   density = n0 / (1e17/PUnits::cm3);
  Float_t Base  = density;
  Float_t BaseB =  TMath::Nint(100*(nb/n0))/100.0;

  Float_t gMax  = hDen2D[0]->GetMaximum();
  Float_t gMin  = (0.1001) * Base;
  if(BaseB<Base) gMin  = (0.1001) * BaseB;

  if(gMax<Base) gMax = 1.1*Base;

  Float_t *Max = new Float_t[Nspecies];
  Float_t *Min = new Float_t[Nspecies];

  for(Int_t i=0;i<Nspecies;i++) {
    if(!hDen2D[i]) continue;
   
    Max[i] = hDen2D[i]->GetMaximum();
    Min[i] = 0.01*Max[i];
    //   if(i==1) = Min[i] = 1.001E-4;
    if(i==2) Min[i] = 1.001E-3;
    if(Max[i]>gMax) gMax = Max[i];
    
    hDen2D[i]->GetZaxis()->SetRangeUser(Min[i],Max[i]);
  }
  
  hDen2D[0]->GetZaxis()->SetRangeUser(gMin,gMax); 
  
  // if(hDen2D[1]) {
  //   hDen2D[1]->GetZaxis()->SetRangeUser(gMin,Max[1]);
  // } 

  // if(Nspecies>=3) {
  //   if(hDen2D[2]) {
  //     hDen2D[2]->GetZaxis()->SetRangeUser(gMin,Max[2]);
  //   } 
  // }
  
  // Dynamic plasma palette
  const Int_t plasmaDNRGBs = 3;
  const Int_t plasmaDNCont = 128;
  Double_t basePos = 0.5;
  if(gMax!=gMin) {
    if(opt.Contains("logz")) {
      Float_t a = 1.0/(TMath::Log10(gMax)-TMath::Log10(gMin));
      Float_t b = TMath::Log10(gMin);
      basePos = a*(TMath::Log10(Base) - b);
      
    } else {
      basePos = (1.0/(gMax-gMin))*(Base - gMin);
    }
  }

  Double_t plasmaDStops[plasmaDNRGBs] = { 0.00, basePos, 1.00 };
  Double_t plasmaDRed[plasmaDNRGBs]   = { 0.99, 0.90, 0.00 };
  Double_t plasmaDGreen[plasmaDNRGBs] = { 0.99, 0.90, 0.00 };
  Double_t plasmaDBlue[plasmaDNRGBs]  = { 0.99, 0.90, 0.00 };
   
  PPalette * plasmaPalette = (PPalette*) gROOT->FindObject("plasma");
  plasmaPalette->CreateGradientColorTable(plasmaDNRGBs, plasmaDStops, 
					  plasmaDRed, plasmaDGreen, plasmaDBlue, plasmaDNCont);
  
  // Change the range of z axis for the fields to be symmetric.
  Float_t Emax = hE2D[0]->GetMaximum();
  Float_t Emin = hE2D[0]->GetMinimum();
  if(Emax > TMath::Abs(Emin))
    Emin = -Emax;
  else
    Emax = -Emin;
  hE2D[0]->GetZaxis()->SetRangeUser(Emin,Emax); 

  Emax = hE2D[1]->GetMaximum();
  Emin = hE2D[1]->GetMinimum();
  if(Emax > TMath::Abs(Emin))
    Emin = -Emax;
  else
    Emax = -Emin;
  hE2D[1]->GetZaxis()->SetRangeUser(Emin,Emax); 
    

  
  // "Axis range" in Osiris units:
  Double_t ylow  = hDen2D[1]->GetYaxis()->GetBinLowEdge(FirstyBin);
  Double_t yup = hDen2D[1]->GetYaxis()->GetBinUpEdge(LastyBin);
  Double_t xmin = hDen2D[1]->GetXaxis()->GetXmin();
  Double_t xmax = hDen2D[1]->GetXaxis()->GetXmax();

  TLine *lineYzero = new TLine(xmin,0.0,xmax,0.0);
  lineYzero->SetLineColor(kGray+2);
  lineYzero->SetLineStyle(2);

  TLine *lineYup = new TLine(xmin,yup,xmax,yup);
  lineYup->SetLineColor(kGray+1);
  lineYup->SetLineStyle(2);
 
  TLine *lineYdown = new TLine(xmin,ylow,xmax,ylow);
  lineYdown->SetLineColor(kGray+1);
  lineYdown->SetLineStyle(2);

  zStartPlasma -= shiftz; 
  zStartNeutral -= shiftz; 
  zEndNeutral -= shiftz; 
  
  if(opt.Contains("units")) {
    zStartPlasma *= skindepth / PUnits::um;
    zStartNeutral *= skindepth / PUnits::um;
    zEndNeutral *= skindepth / PUnits::um;
  }

  //  cout << "Start plasma = " << zStartPlasma << endl;
  TLine *lineStartPlasma = new TLine(zStartPlasma,ymin,zStartPlasma,ymax);
  lineStartPlasma->SetLineColor(kRed);
  lineStartPlasma->SetLineStyle(1);
  lineStartPlasma->SetLineWidth(2);

  //  cout << "Start plasma = " << zStartNeutral << endl;
  TLine *lineStartNeutral = new TLine(zStartNeutral,ymin,zStartNeutral,ymax);
  lineStartNeutral->SetLineColor(kGray+1);
  lineStartNeutral->SetLineStyle(1);
  lineStartNeutral->SetLineWidth(2);

  //  cout << "End plasma = " << zEndNeutral << endl;
  TLine *lineEndNeutral = new TLine(zEndNeutral,ymin,zEndNeutral,ymax);
  lineEndNeutral->SetLineColor(kGray+1);
  lineEndNeutral->SetLineStyle(2);
  lineEndNeutral->SetLineWidth(2);
  
  // Plotting
  // -----------------------------------------------

  // Canvas setup
  TCanvas *C;
  if(opt.Contains("hres") && !opt.Contains("pdf")) // high resolution for plain grahics output.
    C = new TCanvas("C","2D Charge density, Accelerating and focusing fields",1500,2000);
  else
    C = new TCanvas("C","2D Charge density, Accelerating and focusing fields",750,1000);
 
  // Palettes setup
  TExec *exPlasma = new TExec("exPlasma","plasmaPalette->cd();");
  TExec *exHot    = new TExec("exHot","hotPalette->cd();");
  TExec *exElec   = new TExec("exElec","electronPalette->cd();");
  TExec *exField  = new TExec("exField","rbow2Palette->cd();");
  
  // Text objects
  TPaveText *textTime = new TPaveText(0.7,0.83,0.85,0.90,"NDC");
  PlasmaGlob::SetPaveTextStyle(textTime,32); 
  char ctext[128];
  if(opt.Contains("units") && n0) 
    sprintf(ctext,"z = %5.1f #mum", Time * skindepth / PUnits::um);
  else
    sprintf(ctext,"t = %5.1f #omega_{p}^{-1}",Time);
  textTime->AddText(ctext);
  
  TPaveText *textDen = new TPaveText(0.13,0.83,0.38,0.90,"NDC");
  PlasmaGlob::SetPaveTextStyle(textDen,12); 
  textDen->SetTextColor(kOrange+10);
  if(opt.Contains("units") && n0)
    sprintf(ctext,"n_{0} = %5.2f x 10^{15} / cm^{3}", 1e-15 * n0 * PUnits::cm3);
  else if(pData->GetBeamDensity() && n0)
    sprintf(ctext,"n_{b}/n_{0} = %5.2f", pData->GetBeamDensity()/n0);
  textDen->AddText(ctext);
  
  TPaveText *textWav = new TPaveText(0.13,0.75,0.38,0.82,"NDC");
  PlasmaGlob::SetPaveTextStyle(textWav,12); 
  textWav->SetTextColor(kGray+2);
  sprintf(ctext,"#lambda_{p} = %5.3f mm", skindepth * TMath::TwoPi() / PUnits::um);
  textWav->AddText(ctext);
  
  
  // Actual Plotting!
  // ------------------------------------------------------------

  // Output file
  TString fOutName = Form("./%s/Plots/ChargeFieldFocus2D/ChargeFieldFocus2D",pData->GetPath().c_str());
  fOutName += Form("-%s_%i",pData->GetName(),time);


  // Setup Pad layout:
  Double_t lMargin = 0.10;
  Double_t rMargin = 0.12;
  Double_t bMargin = 0.10;
  Double_t tMargin = 0.02;
  Double_t vSpacing = 0.01; 
  Double_t hStep = (1.-lMargin-rMargin);
  Double_t vStep = (1.-bMargin-tMargin)/3.;
 
  TPad *pad[3];

  // top plots
  pad[0] = new TPad("padt", "padt",0.00, bMargin + 2.*vStep + vSpacing,
		    lMargin+hStep+rMargin, 1.00);
  pad[0]->SetLeftMargin(1./(lMargin+hStep)*lMargin);
  pad[0]->SetRightMargin(1./(rMargin+hStep)*rMargin);  
  pad[0]->SetBottomMargin(0.0);                                   
  pad[0]->SetTopMargin(1./(tMargin+vStep)*tMargin);
  pad[0]->Draw();

  // middle plots
  pad[1] = new TPad("padm", "padm",0.00, bMargin + vStep + vSpacing,
		    lMargin + hStep + rMargin, bMargin + 2.*vStep );
  pad[1]->SetLeftMargin(1./(lMargin+hStep)*lMargin);
  pad[1]->SetRightMargin((1./(rMargin+hStep)*rMargin));
  pad[1]->SetBottomMargin(0.0);                                   
  pad[1]->SetTopMargin(0.);
  pad[1]->Draw();          

  // bottom plots
  pad[2] = new TPad("padb", "padb",0.00, 0.,lMargin+hStep+rMargin,bMargin+vStep);
  pad[2]->SetLeftMargin(1./(lMargin+hStep)*lMargin);
  pad[2]->SetRightMargin((1./(rMargin+hStep)*rMargin));
  pad[2]->SetBottomMargin(1./(bMargin+vStep)*bMargin);
  pad[2]->SetTopMargin(0.);
  pad[2]->Draw();       
  
  // Draw!
  pad[0]->cd(); // <---------------------------------------------- Top Plot ---------
  if(opt.Contains("logz")) {
    pad[0]->SetLogz(1);
  } else {
    pad[0]->SetLogz(0);
  }
  pad[0]->SetFrameLineWidth(3);  

  TH2F *hFrame = (TH2F*) gROOT->FindObject("hFrame1");
  if(hFrame) delete hFrame;
  hFrame = (TH2F*) hDen2D[0]->Clone("hFrame1");
  hFrame->Reset();

  hFrame->GetXaxis()->SetLabelOffset(999);

  hFrame->GetYaxis()->SetTitleSize(0.075);
  hFrame->GetYaxis()->SetTitleOffset(0.65);
  hFrame->GetYaxis()->SetLabelSize(0.065);
  hFrame->GetYaxis()->SetLabelOffset(0.02);
  hFrame->GetYaxis()->SetTickLength(0.02);
 
  hFrame->GetZaxis()->SetTitleSize(0.06);                        
  hFrame->GetZaxis()->SetTitleOffset(0.45);
  hFrame->GetZaxis()->SetLabelSize(0.06);  
  hFrame->GetZaxis()->SetTickLength(0.02);
  //  hFrame->GetZaxis()->SetNdivisions(505);

  hFrame->Draw("col");            

  if(Nspecies>=3) {
    if(hDen2D[2]) {
      exHot->Draw();
      hDen2D[2]->Draw("colz same");
    }
  }

  exPlasma->Draw();
  hDen2D[0]->Draw("colz same");
  
  if(hDen2D[1]) {
    exElec->Draw();
    hDen2D[1]->Draw("colz same");
  }
  
  if(opt.Contains("1dline")) {
    lineYzero->Draw();
    lineYdown->Draw();
    lineYup->Draw();
  }

  if(zStartPlasma>xmin && zStartPlasma<xmax)
    lineStartPlasma->Draw();
  if(zStartNeutral>xmin && zStartNeutral<xmax)
    lineStartNeutral->Draw();
  if(zEndNeutral>xmin && zEndNeutral<xmax)
    lineEndNeutral->Draw();
  
  pad[0]->Update();
  TPaletteAxis *palette = NULL;
  for(Int_t i=0;i<Nspecies;i++) {
    
    if(!hDen2D[i]) continue;
    palette = (TPaletteAxis*) hDen2D[i]->GetListOfFunctions()->FindObject("palette");
    if(!palette) continue;

    Float_t y1 = gPad->GetBottomMargin();
    Float_t y2 = 1 - gPad->GetTopMargin();
    Float_t x1 = gPad->GetLeftMargin();
    Float_t x2 = 1 - gPad->GetRightMargin();
    palette->SetY2NDC( (i+1)*(y2-y1)/Nspecies + y1);
    palette->SetY1NDC( i*(y2-y1)/Nspecies + y1);
    palette->SetX1NDC(x2 + 0.005);
    palette->SetX2NDC(x2 + 0.03);
    palette->SetTitleOffset(0.65);
    palette->SetTitleSize(0.07);
    palette->SetLabelSize(0.065);
    palette->SetBorderSize(2);
    palette->SetLineColor(1);
  
  }


  // 1D charge density plots:
  Float_t yaxismin  =  pad[0]->GetUymin();
  Float_t yaxismax  =  pad[0]->GetUymin() + 0.33*(pad[0]->GetUymax() - pad[0]->GetUymin()) - 0.00;
  
  //  Float_t denmin = (0.1001) * density;
  Float_t denmin = gMin;
  Float_t denmax = gMax;
  if(opt.Contains("logz")) {
    denmin = TMath::Log10(denmin);
    denmax = TMath::Log10(denmax);
  }
  
  for(Int_t i=0;i<Nspecies;i++) {
    if(!hDen1D[i]) continue;
    
    Float_t slope = (yaxismax - yaxismin)/(denmax - denmin);
    
    for(Int_t j=0;j<hDen1D[i]->GetNbinsX();j++) {
      Float_t content = hDen1D[i]->GetBinContent(j+1);
      if(opt.Contains("logz")) content = TMath::Log10(content); 
      
      if(content<denmin) 
	hDen1D[i]->SetBinContent(j+1,yaxismin);
      else 
	hDen1D[i]->SetBinContent(j+1,(content - denmin) * slope + yaxismin);
    }    

    hDen1D[i]->SetLineWidth(2);
    if(i==1) {
      hDen1D[i]->SetLineColor(PlasmaGlob::elecLine);
      hDen1D[i]->Draw("same C");
    } else if (i==2) {
      hDen1D[i]->SetLineColor(kOrange+8);
      hDen1D[i]->Draw("same C");
    }
  }
    
  textTime->Draw();
  //  textDen->Draw();
  //  textWav->Draw();
  
  pad[0]->RedrawAxis(); 

 
  pad[1]->cd(); // <--------------------------------------------- Mid Plot
  pad[1]->SetFrameLineWidth(3);  
    
  TH2F *hFrame2 = (TH2F*) gROOT->FindObject("hFrame2");
  if(hFrame2) delete hFrame2;
  hFrame2 = (TH2F*) hE2D[0]->Clone("hFrame2");
  hFrame2->Reset();

  Float_t yFactor = pad[0]->GetAbsHNDC()/pad[1]->GetAbsHNDC(); 

  hFrame2->GetXaxis()->SetLabelOffset(999);

  hFrame2->GetYaxis()->SetTitleSize(0.075*yFactor);
  hFrame2->GetYaxis()->SetTitleOffset(0.65/yFactor);
  hFrame2->GetYaxis()->SetLabelSize(0.0650*yFactor);
  hFrame2->GetYaxis()->SetLabelOffset(0.02/yFactor);
  hFrame2->GetYaxis()->SetTickLength(0.02/yFactor);
  
  hE2D[0]->GetZaxis()->SetTitleSize(0.06*yFactor);                        
  hE2D[0]->GetZaxis()->SetTitleOffset(0.45/yFactor);
  hE2D[0]->GetZaxis()->SetLabelSize(0.06*yFactor);  
  hE2D[0]->GetZaxis()->SetTickLength(0.02/yFactor);
  // hFrame2->GetZaxis()->SetNdivisions(505);
  
  hFrame2->Draw("col");

  exField->Draw();
  hE2D[0]->Draw("colz same");

  if(opt.Contains("1dline")) {
    lineYzero->Draw();
    lineYdown->Draw();
    lineYup->Draw();
  }
  if(zStartPlasma>xmin && zStartPlasma<xmax)
    lineStartPlasma->Draw();
  if(zStartNeutral>xmin && zStartNeutral<xmax)
    lineStartNeutral->Draw();
  if(zEndNeutral>xmin && zEndNeutral<xmax)
    lineEndNeutral->Draw();
  
  pad[1]->Update();
  
  palette = (TPaletteAxis*) hE2D[0]->GetListOfFunctions()->FindObject("palette");
  
  Float_t y1 = pad[1]->GetBottomMargin();
  Float_t y2 = 1 - pad[1]->GetTopMargin();
  Float_t x2 = 1 - pad[1]->GetRightMargin();
  palette->SetY2NDC(y2 - 0.01);
  palette->SetY1NDC(y1 + 0.01);
  palette->SetX1NDC(x2 + 0.005);
  palette->SetX2NDC(x2 + 0.03);
  palette->SetTitleSize(0.07*yFactor);
  palette->SetTitleOffset(0.65/yFactor);
  palette->SetLabelSize(0.065*yFactor);
  palette->SetBorderSize(2);
  palette->SetLineColor(1);
  
  
  // 1D electric field plots:
  if(hE1D[0]) {
    // yaxismin  =  pad[1]->GetUymin() + 0.16666*(pad[1]->GetUymax() - pad[1]->GetUymin());
    // yaxismax  =  pad[1]->GetUymax() - 0.16666*(pad[1]->GetUymax() - pad[1]->GetUymin());
    Float_t yaxismin  =  pad[1]->GetUymin();
    Float_t yaxismax  =  pad[1]->GetUymax();
    
    Float_t emin = hE1D[0]->GetMinimum();
    Float_t emax = hE1D[0]->GetMaximum();
    
    //Float_t slope = (yaxismax - yaxismin)/(emax - emin);
    Float_t slope = yaxismin/emin;
    
    for(Int_t j=0;j<hE1D[0]->GetNbinsX();j++) {
      Float_t content = hE1D[0]->GetBinContent(j+1);
      hE1D[0]->SetBinContent(j+1,(content - emin) * slope + yaxismin);
  }    
    
    hE1D[0]->SetLineWidth(2);
    hE1D[0]->SetLineColor(PlasmaGlob::elecLine);
    // hE1D[0]->SetLineColor(kGray+2);
    hE1D[0]->Draw("same C");
  }

  // Plot ionization probability:
  if(hIonProb1D) {
    Float_t ionmin = 0;
    Float_t ionmax = hIonProb1D->GetMaximum();
    
    Float_t slope = yaxismax/ionmax;
    
    for(Int_t j=0;j<hIonProb1D->GetNbinsX();j++) {
      Float_t content = hIonProb1D->GetBinContent(j+1);
      hIonProb1D->SetBinContent(j+1,content * slope);
    }    
    
    hIonProb1D->SetLineWidth(2);
    hIonProb1D->SetLineColor(kGray+2);
    hIonProb1D->Draw("same C");
  }
  

  pad[1]->RedrawAxis(); 

  pad[2]->cd();  // <--------------------------------------------- Bottom Plot
  pad[2]->SetFrameLineWidth(3);  
  
  TH2F *hFrame3 = (TH2F*) gROOT->FindObject("hFrame3");
  if(hFrame3) delete hFrame3;
  hFrame3 = (TH2F*) hE2D[1]->Clone("hFrame3");
  hFrame3->Reset();

  yFactor = pad[0]->GetAbsHNDC()/pad[2]->GetAbsHNDC();
  
  hFrame3->GetXaxis()->SetTitleSize(0.075);
  hFrame3->GetXaxis()->SetLabelSize(0.070);

  hFrame3->GetYaxis()->SetTitleSize(0.075*yFactor);
  hFrame3->GetYaxis()->SetTitleOffset(0.65/yFactor);
  hFrame3->GetYaxis()->SetLabelSize(0.0650*yFactor);
  hFrame3->GetYaxis()->SetLabelOffset(0.02/yFactor);
  hFrame3->GetYaxis()->SetTickLength(0.02/yFactor);

  hE2D[1]->GetZaxis()->SetTitleSize(0.06*yFactor);                        
  hE2D[1]->GetZaxis()->SetTitleOffset(0.45/yFactor);
  hE2D[1]->GetZaxis()->SetLabelSize(0.06*yFactor);  
  hE2D[1]->GetZaxis()->SetTickLength(0.02/yFactor);
  // hE2D[1]->GetZaxis()->SetNdivisions(505);
  
  hFrame3->Draw("col");

  exField->Draw();
  hE2D[1]->Draw("colz same");

  if(opt.Contains("1dline")) {
    lineYzero->Draw();
    lineYup->Draw();
  }

  if(zStartPlasma>xmin && zStartPlasma<xmax)
    lineStartPlasma->Draw();
  if(zStartNeutral>xmin && zStartNeutral<xmax)
    lineStartNeutral->Draw();
  if(zEndNeutral>xmin && zEndNeutral<xmax)
    lineEndNeutral->Draw();

  pad[2]->Update();
  palette = (TPaletteAxis*)hE2D[1]->GetListOfFunctions()->FindObject("palette");
  
  y1 = pad[2]->GetBottomMargin();
  y2 = 1 - pad[2]->GetTopMargin();
  x2 = 1 - pad[2]->GetRightMargin();
  palette->SetY2NDC(y2 - 0.01);
  palette->SetY1NDC(y1 + 0.01);
  palette->SetX1NDC(x2 + 0.005);
  palette->SetX2NDC(x2 + 0.03);
  palette->SetTitleSize(0.07*yFactor);
  palette->SetTitleOffset(0.65/yFactor);
  palette->SetLabelSize(0.065*yFactor);
  palette->SetBorderSize(2);
  palette->SetLineColor(1);

  // 1D electric field plots:
  if(hE1D[1]) {
    // yaxismin  =  pad[2]->GetUymin() + 0.16666*(pad[2]->GetUymax() - pad[2]->GetUymin());
    // yaxismax  =  pad[2]->GetUymax() - 0.16666*(pad[2]->GetUymax() - pad[2]->GetUymin());
    Float_t yaxismin  =  pad[2]->GetUymin();
    Float_t yaxismax  =  pad[2]->GetUymax();
    
    Float_t emin = hE1D[1]->GetMinimum();
    Float_t emax = hE1D[1]->GetMaximum();
    
    Float_t slope = yaxismin/emin;
    
    for(Int_t j=0;j<hE1D[1]->GetNbinsX();j++) {
      Float_t content = hE1D[1]->GetBinContent(j+1);
      hE1D[1]->SetBinContent(j+1,(content - emin) * slope + yaxismin);
    }    
    
    hE1D[1]->SetLineWidth(2);
    //hE1D[1]->SetLineStyle(2);
    // hE1D[1]->SetLineColor(kGray+2);
    hE1D[1]->SetLineColor(PlasmaGlob::elecLine);
    hE1D[1]->Draw("same C");
  }

  // Plot ionization probability:
  if(hIonProb1D) {
    Float_t ionmin = 0;
    Float_t ionmax = hIonProb1D->GetMaximum();
    
    Float_t slope = yaxismax/ionmax;
    
    for(Int_t j=0;j<hIonProb1D->GetNbinsX();j++) {
      Float_t content = hIonProb1D->GetBinContent(j+1);
      hIonProb1D->SetBinContent(j+1,content * slope);
    }    
    
    hIonProb1D->SetLineWidth(2);
    hIonProb1D->SetLineColor(kGray+2);
    hIonProb1D->Draw("same C");
  }

   
  pad[2]->RedrawAxis(); 

  C->cd();

  // Print to a file
  PlasmaGlob::imgconv(C,fOutName,opt);
  // ---------------------------------------------------------

}
示例#15
0
void plotRegrVsNoRegr(int channel, int massBin) {
  stringstream filenom, filenoregr;
  filenom << "m4lplots/nominal/fitM" << massBin << "_channel" << channel << ".root";
  filenoregr << "m4lplots/noregr/fitM" << massBin << "_channel" << channel << ".root";

  int col;
  if(channel==0) col=kOrange+7;
  if(channel==1) col=kAzure+2;
  if(channel==2) col=kGreen+3;

  TCanvas *c1 = new TCanvas("c1","c1",750,750);

  TFile *tfilenom = TFile::Open(filenom.str().c_str());
  RooPlot *plotnom = (RooPlot*)tfilenom->Get("m4lplot");
  plotnom->SetMarkerStyle(kOpenSquare);
  plotnom->Draw();
  TPaveText *pavenom = (TPaveText*)tfilenom->Get("TPave");
  pavenom->SetTextColor(col);
  pavenom->Draw("same");

  TFile *tfilenoregr = TFile::Open(filenoregr.str().c_str());
  RooPlot *plotnoregr = (RooPlot*)tfilenoregr->Get("m4lplot");
  plotnoregr->Draw("same");
  TPaveText *pavenoregr = (TPaveText*)tfilenoregr->Get("TPave");
  pavenoregr->Draw("same");

  // cosmetics
  TLegend *legend = new TLegend(0.20,0.45,0.45,0.60,NULL,"brNDC");
  legend->SetBorderSize(     0);
  legend->SetFillColor (     0);
  legend->SetTextAlign (    12);
  legend->SetTextFont  (    42);
  legend->SetTextSize  (0.03);

  TH1F *dummyPointsNom = new TH1F("dummyPNom","dummyPNom",1,0,1);
  TH1F *dummyPointsNoRegr = new TH1F("dummyPNoregr","dummyPNoregr",1,0,1);
  TH1F *dummyLine = new TH1F("dummyL","dummyL",1,0,1);
  dummyPointsNoRegr->SetMarkerStyle(kFullCircle);
  dummyPointsNoRegr->SetMarkerSize(1.1);
  dummyPointsNom->SetMarkerStyle(kFullSquare);
  dummyPointsNom->SetMarkerColor(col);
  dummyPointsNom->SetLineColor(col);
  dummyPointsNom->SetMarkerSize(1.1);
  dummyLine->SetLineColor(col);
  
  legend->AddEntry(dummyPointsNoRegr, "Simulation (E_{std}-p comb.)", "pel");
  legend->AddEntry(dummyPointsNom, "Simulation (E_{regr}-p comb.)", "pel");

  legend->Draw();

  TPaveText *text = new TPaveText(0.15,0.90,0.77,0.98,"brNDC");
  text->AddText("CMS Simulation");
  text->SetBorderSize(0);
  text->SetFillStyle(0);
  text->SetTextAlign(12);
  text->SetTextFont(42);
  text->SetTextSize(0.03);

  text->Draw();

  stringstream frameTitle;
  if(channel==0){frameTitle << "4#mu, m_{H} = ";}
  if(channel==1){frameTitle << "4e, m_{H} = ";}
  if(channel==2){frameTitle << "2e2#mu, m_{H} = ";}
  frameTitle << massBin << " GeV";

  TPaveText *titlet = new TPaveText(0.15,0.80,0.60,0.85,"brNDC");
  titlet->AddText(frameTitle.str().c_str());
  titlet->SetBorderSize(0);
  titlet->SetFillStyle(0);
  titlet->SetTextAlign(12);
  titlet->SetTextFont(132);
  titlet->SetTextSize(0.045);

  titlet->Draw();

  c1->SaveAs("comp.pdf");

}
void PlotPhaseVelocityFunctions( const TString &opt="")
{
#ifdef __CINT__
  gSystem->Load("libplasma.so");
#endif

  PlasmaGlob::Initialize();

  // Palettes!
  gROOT->Macro("PlasmaPalettes.C");
  
  gStyle->SetPadTopMargin(0.06); 
  gStyle->SetPadGridY(0);
  gStyle->SetPadGridX(0);
  gStyle->SetFrameLineWidth(2);
  gStyle->SetLabelSize(0.04, "xyz");
  gStyle->SetTitleOffset(1.2,"y");
  gStyle->SetTitleOffset(1.2,"z");
  gStyle->SetNdivisions(505,"xyz");

  PUnits::UnitsTable::Get();
  
  // // SPS parameters from Pukhov, Kumar et al. PRL107,145003(2011)
  // Double_t n0 = 7.76e14 / PUnits::cm3;
  // Double_t nb = 1.5e12 / PUnits::cm3;
  // Double_t lambda = PFunc::PlasmaWavelength(n0);
  // Double_t kp = PFunc::PlasmaWavenumber(n0);
  // Double_t skindepth =  PFunc::PlasmaSkindepth(n0);
  // Double_t r0 = 0.19 * PUnits::mm;
  // Double_t z  = 2.5 * PUnits::m;
  // Double_t zg = -28.6 * PUnits::mm;
  // Double_t E  = 450 * PUnits::GeV;
  // Double_t gamma = E / PConst::ProtonMassE ;

  // SPS parameters from Schroeder et al. PRL107,145002(2011)
  // Double_t n0 = 1.0;
  // Double_t nb = 0.002;
  // Double_t lambda = TMath::TwoPi();
  // Double_t kp = 1.0;
  // Double_t r0 = 1.0;
  // Double_t z  = 13105;
  // Double_t E  = 450 * PUnits::GeV;
  // Double_t gamma = E / PConst::ProtonMassE ;

  // PITZ parameters
  Double_t n0 = 1.0e15 / PUnits::cm3;
  Double_t nb = 1.05e13 / PUnits::cm3;
  Double_t lambda = PFunc::PlasmaWavelength(n0);
  Double_t kp = PFunc::PlasmaWavenumber(n0);
  Double_t skindepth =  PFunc::PlasmaSkindepth(n0);
  Double_t r0 = 34.259 * PUnits::um;
  Double_t z  = 150. * PUnits::mm;
  Double_t zg = -5. * PUnits::mm;
  Double_t E  = 25 * PUnits::MeV;
  Double_t gamma = (E / PConst::ElectronMassE) + 1.0;
  Double_t vb = TMath::Sqrt(1. - (1./(gamma*gamma)));

  cout << " n0 = " << n0 * PUnits::cm3 << "  e/cc" << endl;
  cout << " Wavelength = " << PUnits::BestUnit(lambda, "Length") << endl;
  cout << " Skindepth = " << PUnits::BestUnit(skindepth, "Length") << endl;
  cout << " Wavenumber = " << kp * PUnits::mm << "  mm^-1" << endl;

  // Normalized variables
  if(!opt.Contains("units")){
    r0 *= kp;
    nb /= n0;
    n0 = 1.0;
    z *= kp;
    zg *= kp;
  }
  

  Double_t N = PFunc::Nefoldings(z,zg,r0,gamma,nb,n0);
  Double_t r1 = (TMath::Power(3.,1./4.)/TMath::Power(8.*TMath::Pi()*N,1./2.)) * TMath::Exp(N) ;
  Double_t Gamma = PFunc::PhaseGamma(z,zg,r0,gamma,nb,n0);
  Double_t vph = PFunc::PhaseVelocity(z,zg,r0,gamma,nb,n0);
  Double_t vph2 = PFunc::PhaseVelocity2(z,zg,gamma,nb,n0);

  cout << " gamma beam = " << gamma << endl;
  cout << " zeta = " << z << endl;
  cout << " zeta comov. = " << zg << endl;
  cout << " r0 = " << r0 << endl;
  cout << " n_b0/n_0 = " << nb/n0 << endl;
  cout << " nu constant = " << PFunc::Nu(r0,n0) << endl;
  cout << " Number e-foldings = " << N << endl; 
  cout << " r1 = " << r1 << endl;
  cout << " Gamma wake = " << Gamma << endl;
  cout << " Wake Phase velocity  = " << vph << endl;
  cout << " Wake Phase velocity2 = " << vph2 << endl;
  cout << " Beam phase velocity  = " << vb << endl;

  const Int_t NPAR = 5;
  Double_t par[NPAR] = {zg,r0,gamma,nb,n0};
  TF1 *fPhaseVsZ2 = new TF1("fPhaseVsZ2",PhaseVelocityVsZ2,0,z,NPAR);
  fPhaseVsZ2->SetParameters(par);  
  TF1 *fPhaseVsZ = new TF1("fPhaseVsZ",PhaseVelocityVsZ,0,z,NPAR);
  fPhaseVsZ->SetParameters(par);

  Double_t par2[NPAR] = {z,r0,gamma,nb,n0};
  TF1 *fPhaseVsZg2 = new TF1("fPhaseVsZg2",PhaseVelocityVsZg2,zg,0.,NPAR);
  fPhaseVsZg2->SetParameters(par2);
  TF1 *fPhaseVsZg = new TF1("fPhaseVsZg",PhaseVelocityVsZg,zg,0.,NPAR);
  fPhaseVsZg->SetParameters(par2);
  
  const Int_t NPAR2D = 4;
  Double_t par3[NPAR2D] = {r0,gamma,nb,n0};
  TF2 *fPhaseVsZVsZg2 = new TF2("fPhaseVsZVsZg2",PhaseVelocityVsZVsZg2,0.,z,zg,0.,NPAR2D);
  fPhaseVsZVsZg2->SetParameters(par3);
  TF2 *fPhaseVsZVsZg = new TF2("fPhaseVsZVsZg",PhaseVelocityVsZVsZg,0.,z,zg,0.,NPAR2D);
  fPhaseVsZVsZg->SetParameters(par3);
  
  char ctext[64];
  TPaveText *textZetag = new TPaveText(0.13,0.85,0.38,0.92,"NDC");
  PlasmaGlob::SetPaveTextStyle(textZetag,12); 
  textZetag->SetTextColor(kGray+3);
  if(opt.Contains("units"))
    sprintf(ctext,"#zeta_{0} = %6.2f mm", zg / PUnits::mm);
  else
    sprintf(ctext,"#zeta_{0} = %6.2f c/#omega_{p}", zg);
  textZetag->AddText(ctext);
  
  TPaveText *textZeta = new TPaveText(0.13,0.85,0.38,0.92,"NDC");
  PlasmaGlob::SetPaveTextStyle(textZeta,12); 
  textZeta->SetTextColor(kGray+3);
  if(opt.Contains("units"))
    sprintf(ctext,"z_{0} = %6.2f mm", z / PUnits::mm);
  else
    sprintf(ctext,"z_{0} = %6.2f c/#omega_{p}", z);
  textZeta->AddText(ctext);

  // Graph for de-phasing:
  const Int_t NP = 100;
  TGraph *gPhase = new TGraph(NP);
  TGraph *gPhase2 = new TGraph(NP);
  Float_t phase  = zg;
  Float_t phase2 = zg;
  Float_t Dz = z / NP;
  for(Int_t i=0;i<NP;i++) {
    Float_t zp = (i+1)*Dz;
    Float_t v = PFunc::PhaseVelocity(zp,phase,r0,gamma,nb,n0);
    phase += (v - vb) * Dz;
    // cout << " z = " << zp << "  phase = " << phase << endl;
    if(opt.Contains("units"))
      gPhase->SetPoint(i,zp,(phase-zg)*kp);
    else
      gPhase->SetPoint(i,zp,(phase-zg));

    v = PFunc::PhaseVelocity2(zp,phase2,gamma,nb,n0);
    phase2 += (v - 1) * Dz;
    // cout << " z = " << zp << "  phase = " << phase << endl;
    if(opt.Contains("units"))
      gPhase2->SetPoint(i,zp,(phase2-zg)*kp);
    else
      gPhase2->SetPoint(i,zp,(phase2-zg));
  }
  
  TCanvas *C = new TCanvas("C","Wake phase velocity",1000,750);
  C->Divide(2,2);

  TLegend *Leg = new TLegend(0.6,0.20,0.85,0.35);
  PlasmaGlob::SetPaveStyle(Leg);
  Leg->SetTextAlign(22);
  Leg->SetTextColor(kGray+3);
  Leg->SetLineColor(1);
  Leg->SetBorderSize(1);
  Leg->SetFillColor(0);
  Leg->SetFillStyle(1001);
  //Leg-> SetNColumns(2);
  Leg->AddEntry(fPhaseVsZ,"PRL 107,145002","L");
  Leg->AddEntry(fPhaseVsZ2,"PRL 107,145003","L");
  Leg->SetTextColor(kGray+3);
  

  C->cd(1);
  fPhaseVsZ->GetYaxis()->SetTitle("(v_{p} - c)/c");
  if(opt.Contains("units")) 
    fPhaseVsZ->GetXaxis()->SetTitle("z [m]"); 
  else
    fPhaseVsZ->GetXaxis()->SetTitle("z [c/#omega_{p}]"); 
  fPhaseVsZ->GetYaxis()->SetRangeUser(-3e-4,0.);
  fPhaseVsZ->GetXaxis()->CenterTitle();
  fPhaseVsZ->GetYaxis()->CenterTitle();
  fPhaseVsZ->SetLineWidth(2);
  fPhaseVsZ->Draw("C");
  fPhaseVsZ2->SetLineWidth(2);
  fPhaseVsZ2->SetLineStyle(2);
  fPhaseVsZ2->Draw("C same");
  textZetag->Draw();
  Leg->Draw();

  C->cd(2);
  fPhaseVsZg->GetYaxis()->SetTitle("(v_{p} - c)/c");
  if(opt.Contains("units"))
    fPhaseVsZg->GetXaxis()->SetTitle("#zeta [m]"); 
  else
    fPhaseVsZg->GetXaxis()->SetTitle("#zeta [c/#omega_{p}]"); 
  fPhaseVsZg->GetYaxis()->SetRangeUser(-3e-4,0.);
  fPhaseVsZg->GetYaxis()->SetNdivisions(505);
  fPhaseVsZg->GetXaxis()->CenterTitle();
  fPhaseVsZg->SetLineWidth(2);
  fPhaseVsZg->GetYaxis()->CenterTitle();
  fPhaseVsZg->Draw("C");
  fPhaseVsZg2->SetLineWidth(2);
  fPhaseVsZg2->SetLineStyle(2);
  fPhaseVsZg2->Draw("C same");
  textZeta->Draw();
  
  C->cd(3);
  gPhase->GetYaxis()->SetTitle("#Delta#zeta [c/#omega_{p}]");
  
  if(opt.Contains("units")) {
    gPhase->GetXaxis()->SetTitle("z [m]"); 
    gPhase->GetXaxis()->SetNdivisions(510);
  } else
    gPhase->GetXaxis()->SetTitle("z [c/#omega_{p}]"); 
 
  
  // gPhase->GetXaxis()->SetNdivisions(510);
  gPhase->GetXaxis()->CenterTitle();
  gPhase->GetYaxis()->CenterTitle();
  gPhase->GetXaxis()->SetRangeUser(0.,z);
  gPhase->GetYaxis()->SetNdivisions(505);  
  gPhase->SetLineWidth(2);
  gPhase->Draw("AC");
  gPhase2->SetLineStyle(2);
  gPhase2->SetLineWidth(2);
  gPhase2->Draw("C");
  textZetag->Draw();

  C->cd(4);
  gPad->SetLeftMargin(0.18);

  if(opt.Contains("units")) {
    fPhaseVsZVsZg->GetYaxis()->SetTitle("#zeta [m]"); 
  } else
    fPhaseVsZVsZg->GetYaxis()->SetTitle("#zeta [c/#omega_{p}]"); 
  
  if(opt.Contains("units")) {
    fPhaseVsZVsZg->GetXaxis()->SetTitle("z [m]"); 
  } else
    fPhaseVsZVsZg->GetXaxis()->SetTitle("z [c/#omega_{p}]"); 
  
  fPhaseVsZVsZg->GetZaxis()->SetTitle("(v_{p} - c)/c"); 

  fPhaseVsZVsZg->GetYaxis()->SetNdivisions(505);
  // fPhaseVsZVsZg->GetXaxis()->SetNdivisions(510);
  fPhaseVsZVsZg->GetXaxis()->CenterTitle();
  fPhaseVsZVsZg->GetXaxis()->SetTitleOffset(1.6);
  fPhaseVsZVsZg->GetYaxis()->CenterTitle();
  fPhaseVsZVsZg->GetYaxis()->SetTitleOffset(2.0); 
  fPhaseVsZVsZg->GetZaxis()->CenterTitle();
  fPhaseVsZVsZg->GetZaxis()->SetTitleOffset(1.4); 
  
  fPhaseVsZVsZg->Draw("surf2");

  C->cd();

  // Print to a file
  PlasmaGlob::imgconv(C,"./WakePhaseVelocity",opt);
  // ---------------------------------------------------------

}
示例#17
0
void bbtt_upg_em(std::string var,int nbins, double xmin, double xmax,std::string xtitle, std::string ytitle, double sigscale=1)
{

  TFile *outDC = new TFile("hh_em_inputs.root","RECREATE");

  SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  TH1::SetDefaultSumw2(1);
 
  //std::string dir = "/data/blue/Bacon/029a/Upgrade/merged_talk_jun30/";
  std::string dir = "/afs/cern.ch/work/j/jlawhorn/public/ntuples/";
  
  std::stringstream scale; scale << sigscale;
  
  //Cut definitions
  double luminosity = 3000;
  std::stringstream lumi; lumi << luminosity;
  std::string objcut = "(tauCat1==3 && tauCat2==2 && ptTau1>20 && ptTau2>20 && tauIso2<0.4 && tauIso1<0.4 && (bTag1==2||bTag1==3||bTag1==6||bTag1==7) && (bTag2==1||bTag2==3||bTag2==6||bTag2==7) && ptB1>20 && ptB2>20 && sqrt( (etaTau1-etaTau2)**2 + (phiTau1-phiTau2)**2 )>0.4)";
  std::string jetcut = objcut+"*(mTT>20 && mTT<90)*(mBB1>70 && mBB1<140)*(mt2pileup>100)*(bdtVal>-0.05)";
  //signal region
  std::string mccut = jetcut+"*eventWeight*"+lumi.str();
  std::string sigcut = jetcut+"*eventWeight*"+lumi.str();
  std::string zjetcut = jetcut+"*eventWeight*(eventType==4)*"+lumi.str();
  std::string wjetcut = jetcut+"*eventWeight*(eventType==3)*"+lumi.str();
  std::string ewkcut = jetcut+"*eventWeight*(eventType!=1)*"+lumi.str();
  //--------------------------------------------------------------------------
  
  //Get the trees
  TTree *hhtree = load(dir+"HHToTTBB_14TeV.root"); 
  TTree *tttree = load(dir+"tt.root"); 
  //TTree *vbfhtree = load(dir+"VBFToTT_14TeV_phase2.root");
  //TTree *gfhtree = load(dir+"H.root");
  //TTree *vjettree = load(dir+"Vjets.root");
  //TTree *ewktree = load(dir+"diboson.root");
  
  //-------------------------------------------------------------------------
  
  //Get histograms
  TCanvas *canv0 = MakeCanvas("canv", "histograms", 600, 600);
  canv0->cd();
  std::string vardraw;
  /*  TH1F *Ztt = new TH1F("DY","",nbins,xmin,xmax);
  vardraw = var+">>"+"DY";
  vjettree->Draw(vardraw.c_str(),zjetcut.c_str());
  InitHist(Ztt  , xtitle.c_str(), ytitle.c_str(), TColor::GetColor(248,206,104), 1001);*/
  TH1F *ttbar = new TH1F("TTbar","",nbins,xmin,xmax);
  vardraw = var+">>"+"TTbar";
  tttree->Draw(vardraw.c_str(),mccut.c_str());
  InitHist(ttbar, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(155,152,204), 1001);
  /*  TH1F *wjets = new TH1F("Wjets","",nbins,xmin,xmax);
  vardraw = var+">>"+"Wjets";
  vjettree->Draw(vardraw.c_str(),wjetcut.c_str());
  InitHist(wjets, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(222,90,106), 1001);
  TH1F *ewk = new TH1F("Ewk","",nbins,xmin,xmax);
  vardraw = var+">>"+"Ewk";
  ewktree->Draw(vardraw.c_str(),ewkcut.c_str());
  InitHist(ewk, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(222,90,106), 1001);
  TH1F *vbfh = new TH1F("VBFH","",nbins,xmin,xmax);
  vardraw = var+">>"+"VBFH";
  vbfhtree->Draw(vardraw.c_str(),mccut.c_str());
  InitHist(vbfh, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(250,202,255), 1001);
  TH1F *ggh = new TH1F("GGH","",nbins,xmin,xmax);
  vardraw = var+">>"+"GGH";
  gfhtree->Draw(vardraw.c_str(),mccut.c_str());
  InitHist(ggh, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(250,202,255), 1001);*/
  TH1F *smhh = new TH1F("SMhh","",nbins,xmin,xmax);
  vardraw = var+">>"+"SMhh";
  hhtree->Draw(vardraw.c_str(),sigcut.c_str());
  InitSignal(smhh);
  smhh->SetLineColor(kBlack);
  delete canv0;
  //---------------------------------------------------------------------------
  //Print out the yields
  Double_t error=999;
  //ofstream outfile;
  //outfile.open("yields.txt");
  //outfile << "Yields for the signal region." << std::endl;
  cout << "SM hh   "  << smhh->IntegralAndError(0,smhh->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  /*  outfile << "SM h   "  << smhh->IntegralAndError(0,smhh->GetNbinsX(),error) << "+/-" << error << endl;
      outfile << "Ztt    "  << Ztt->IntegralAndError(0,Ztt->GetNbinsX(),error) << "+/-" << error << endl;*/
  cout << "ttbar    "  << ttbar->IntegralAndError(0,ttbar->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  /*  outfile << "ewk    "  << ewk->IntegralAndError(0,ewk->GetNbinsX(),error) << "+/-" << error << endl;
      outfile << "wjets    "  << wjets->IntegralAndError(0,wjets->GetNbinsX(),error) << "+/-" << error << endl;*/
  //--------------------------------------------------------------------------
  //outfile.close();
  outDC->cd();
  TDirectory* lTD = outDC->mkdir("emu");
  outDC->cd(lTD->GetPath());
  ttbar->SetName("data_obs");
  ttbar->SetTitle("data_obs");
  ttbar->Write();
  /*Ztt->SetName("ZTT");
  Ztt->SetTitle("ZTT");
  Ztt->Write();*/
  ttbar->SetName("TT");
  ttbar->SetTitle("TT");
  ttbar->Write();
  /*wjets->SetName("W");
  wjets->SetTitle("W");
  wjets->Write();
  ewk->SetName("VV");
  ewk->SetTitle("VV");
  ewk->Write();
  vbfh->SetName("qqH");
  vbfh->SetTitle("qqH");
  vbfh->Write();
  ggh->SetName("ggH");
  ggh->SetTitle("ggH");
  ggh->Write();*/
  smhh->SetName("ggHH");
  smhh->SetTitle("ggHH");
  smhh->Write();
  outDC->Close();
  //stack some  histtograms together
  //vbfh->Add(ggh); 
  //wjets->Add(ewk); 
  //-----------------------------------------------------------------------
  smhh->Scale(sigscale);
  //Draw the histograms
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  //wjets->Add(ttbar);  //Ztt->Add(wjets); 
  //vbfh->Add(Ztt);
  //Error band stat
  //TH1F* errorBand = (TH1F*)vbfh ->Clone("errorBand");
  TH1F* errorBand = (TH1F*)ttbar ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  //  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
  //     if(errorBand->GetBinContent(idx)>0){
  //       std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
  //       break;
  //     }
  //}
  ttbar->SetMaximum(1.1*std::max(maximum(ttbar, 0), maximum(smhh, 0)));
  //blind(data,75,150);
  //data->Draw("e");
  //vbfh->Draw("hist");
  //Ztt->Draw("histsame");
  //wjets->Draw("histsame");
  //ttbar->Draw("histsame");
  ttbar->SetTitle("");
  ttbar->Draw("hist"); 
  //data->Draw("esame");
  errorBand->Draw("e2same");
  smhh->Draw("histsame");
  canv->RedrawAxis();
  //canv->SetLogy(1);
  //---------------------------------------------------------------------------
  //Adding a legend
  TLegend* leg = new TLegend(0.53, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(smhh  , TString::Format("%.0f#timeshh#rightarrow#tau#tau bb", sigscale) , "L" );
  //leg->AddEntry(smhh , TString::Format("%.0f#timeshh#rightarrow#tau#tau bb", sigscale1) , "L" );
  //leg->AddEntry(data , "Observed"                       , "LP");
  //leg->AddEntry(vbfh  , "SM H#rightarrow#tau#tau"   , "F" );
  //leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  //leg->AddEntry(wjets  , "Electroweak"                    , "F" );
  leg->AddEntry(errorBand,"bkg. uncertainty","F");
  leg->Draw();
  //---------------------------------------------------------------------------
   
  //CMS preliminary 
  const char* dataset = "CMS Simulation, 3000 fb^{-1} at 14 TeV";
  const char* category = "";
  CMSPrelim(dataset, "#tau_{e}#tau_{#mu}", 0.17, 0.835);
  //CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->Draw();
  //-------------------------------------------------------------------------
  //Save histograms
  canv->Print((var+"_em.png").c_str());
  
  /*
    Ratio Data over MC
  */
  /*
  TCanvas *canv1 = MakeCanvas("canv0", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* model = (TH1F*)Ztt ->Clone("model");
  TH1F* test1 = (TH1F*)vbfh->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    //model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    model->SetBinError  (ibin+1, 0);
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ttbar->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)vbfh->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? vbfh->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? vbfh->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  //stat1->Draw();
  canv1->Print((var+"_ratio.png").c_str());
  */
}
示例#18
0
// examples macro
void 
etauAfterFit_novbf(bool scaled = true, bool log = true)
{
  // defining the common canvas, axes pad styles
  SetStyle();

  // open example histogram file
  TFile* exampleFile = new TFile("eleTau_sm.root");

  //load example histograms
  TH1F* data = (TH1F*)exampleFile->Get("eleTau_SM0/data_obs");
  if(data) {InitHist(data, "#bf{m_{vis} [GeV]}", "#bf{Events}"); InitData(data);} else{std::cout << "can't find hitogram " << "eleTau_SM0/data_obs" << std::endl;}

  TH1F* Fakes =  refill((TH1F*)exampleFile->Get("eleTau_SM0/QCD"))              ; InitHist(Fakes, "", "", kMagenta-10, 1001);                   
  TH1F* EWK1  =  refill((TH1F*)exampleFile->Get("eleTau_SM0/W"  ))              ; InitHist(EWK1 , "", "", kRed    + 2, 1001);
  TH1F* EWK2  =  refill((TH1F*)exampleFile->Get("eleTau_SM0/ZJ" ))              ; InitHist(EWK2 , "", "", kRed    + 2, 1001);
  TH1F* EWK3  =  refill((TH1F*)exampleFile->Get("eleTau_SM0/ZL" ))              ; InitHist(EWK3 , "", "", kRed    + 2, 1001);
  TH1F* EWK   =  refill((TH1F*)exampleFile->Get("eleTau_SM0/VV" ))              ; InitHist(EWK  , "", "", kRed    + 2, 1001);
  TH1F* ttbar =  refill((TH1F*)exampleFile->Get("eleTau_SM0/TT" ))              ; InitHist(ttbar, "", "", kBlue   - 8, 1001);
  TH1F* Ztt   =  refill((TH1F*)exampleFile->Get("eleTau_SM0/ZTT"))              ; InitHist(Ztt  , "", "", kOrange - 4, 1001);
  TH1F* ggH   =  refill((TH1F*)exampleFile->Get("eleTau_SM0/SM120" ))           ; InitSignal(ggH); ggH ->Scale(10*16.63*0.071*16.083/ggH ->Integral());
  TH1F* qqH   =  refill((TH1F*)exampleFile->Get("eleTau_SM0/VBF120"))           ; InitSignal(qqH); qqH ->Scale(10*1.269*0.071* 1.105/qqH ->Integral());
 
  if(scaled){
    rescale(Fakes, 2); 
    rescale(EWK1 , 3); 
    rescale(EWK2 , 4); 
    rescale(EWK3 , 5); 
    rescale(EWK  , 7); 
    rescale(ttbar, 6); 
    rescale(Ztt  , 1);
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
  }
  if(log){
    qqH  ->Add(ggH  );
    Fakes->Add(qqH  );
    EWK1 ->Add(Fakes);
    EWK2 ->Add(EWK1 );
    EWK3 ->Add(EWK2 );
    EWK  ->Add(EWK3 );
    ttbar->Add(EWK  );
    Ztt  ->Add(ttbar);
  }
  else{
    EWK1 ->Add(Fakes);
    EWK2 ->Add(EWK1 );
    EWK3 ->Add(EWK2 );
    EWK  ->Add(EWK3 );
    ttbar->Add(EWK  );
    Ztt  ->Add(ttbar);
    ggH  ->Add(Ztt  );
    qqH  ->Add(ggH  );
  }
  // define canvas
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){
    canv->SetLogy(1);
    data->SetMinimum(5.0);
    data->SetMaximum(500000.);
  }
  else{
    data->SetMaximum(4000.);
  }
  data->SetNdivisions(505);
  data->Draw("e");

  if(log){
    Ztt->Draw("same");
    ttbar->Draw("same");
    EWK->Draw("same");
    Fakes->Draw("same");
    qqH->Draw("same");
  }
  else{
    qqH->Draw("same");
    Ztt->Draw("same");
    ttbar->Draw("same");
    EWK->Draw("same");
    Fakes->Draw("same");
  }
  data->Draw("esame");
  canv->RedrawAxis();

  CMSPrelim("#tau_{e}#tau_{h}", 0.45, 0.75);
  
  TLegend* leg = new TLegend(0.45, 0.45, 0.9, 0.75);
  SetLegendStyle(leg);
  leg->AddEntry(qqH  , "(10x) H#rightarrow#tau#tau" , "L" );
  leg->AddEntry(data , "Observed"                , "LP");
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"    , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                , "F" );
  leg->AddEntry(EWK  , "Electroweak"             , "F" );
  leg->AddEntry(Fakes, "QCD"                     , "F" );
  leg->Draw();

  TPaveText* mssm  = new TPaveText(0.78, 0.70, 0.90, 0.74, "NDC");
  mssm->SetBorderSize(   0 );
  mssm->SetFillStyle(    0 );
  mssm->SetTextAlign(   12 );
  mssm->SetTextSize ( 0.04 );
  mssm->SetTextColor(    1 );
  mssm->SetTextFont (   62 );
  mssm->AddText("m_{H}=120");
  mssm->Draw();

  if(log){
    if(scaled) canv->Print("etau_rescaled_novbf_LOG.pdf"); else canv->Print("etau_unscaled_novbf_LOG.pdf");
    if(scaled) canv->Print("etau_rescaled_novbf_LOG.png"); else canv->Print("etau_unscaled_novbf_LOG.png");
  }
  else{
    if(scaled) canv->Print("etau_rescaled_novbf.pdf"); else canv->Print("etau_unscaled_novbf.pdf");
    if(scaled) canv->Print("etau_rescaled_novbf.png"); else canv->Print("etau_unscaled_novbf.png");
  }
}
示例#19
0
// main method
void LEDRef_evtdis(const int runno = 615,
		   const int gainv = 0,  /*0=low, 1=high*/
		   const int evtnum= -10,
		   int ymax=1023, // set the scale of plots
		   const int delay = 1)  // -1=no delay, wait for input, X>=0 => sleep aprox. X sec. after making plot
{
  // set ranges to plot
  const int strip_f = 0; // first
  const int strip_l = NSTRIPS - 1;
  
  const int nsamples = 65; // number of ADC time samples per channel and event
  
  const int saveplot = 0;
  const int numbering      = 1; // 0: no numbering, 1: nubering on each plot
  const int dofit = 0; // 0: no fit, 1: try to fit the spectra 
  const int debug    = 0;
  const float gammaN = 2;
  // end of setup    
  
  // Assume we are just interested in the 1st segment, _0.root below for fname*
  Char_t fname[256];
  sprintf(fname, "/local/data/Run_%09d.Seq_1A.Stream_0.root",runno);
  cout << "TOTCHAN " << TOTCHAN << endl;

  // set up a raw reader of the data
  AliRawReader *rawReader = NULL;
  rawReader = new AliRawReaderRoot(fname);
  AliCaloRawStream *in = NULL; 
  in = new AliCaloRawStream(rawReader,"EMCAL");

  // set up histograms
  TH1F *hfit[TOTCHAN];
  TF1 *f1[TOTCHAN];
  char ch_label[TOTCHAN][100];
  char buff1[100];
  char name[80];
  for(int i=0; i<TOTCHAN; i++) {
    sprintf(buff1,"hfit_%d",i);
    hfit[i] = new TH1F(buff1,"hfit", nsamples , -0.5, nsamples - 0.5);
    hfit[i]->SetDirectory(0);
    sprintf(name,"f1_%d",i);
    f1[i] = new TF1(name,fitfun,0,70,5);
    f1[i]->SetLineWidth(2);
    f1[i]->SetLineColor(2);

    //	int idx = istrip + NSTRIPS * gain; // encoding used later
    int gain = i / (NSTRIPS);
    int istrip = i % NSTRIPS;
    sprintf(ch_label[i], "Strip%02d", istrip);
  }
  
  TCanvas *cc1 = new TCanvas("cc1","3 columns of 8 strips each",600,800);
  int numcol = NSETS;
  int numrow = NSTRIPS_IN_SET;
  cc1->Divide(numcol, numrow);
  
  TText *t = new TText;
  t->SetTextSize(0.17);
  int clr[2] = {4,2}; // colors
  
  // figure out which events we should look at
  int firstevent = evtnum;
  int lastevent = evtnum;
  if (evtnum < 0) { // get a bunch of events
    firstevent = 0;
    lastevent = - evtnum;
  }
  if (evtnum == 0) { // get all events
    firstevent = 0;
    lastevent = 1000000;
  }
  
  Int_t iev =0;
  AliRawEventHeaderBase *aliHeader=NULL;    
  while ( rawReader->NextEvent() && iev < firstevent) {
    aliHeader = (AliRawEventHeaderBase*) rawReader->GetEventHeader();
    iev++;
  }
  
  // loop over selected events
  while ( rawReader->NextEvent() && iev <= lastevent) {
    aliHeader = (AliRawEventHeaderBase*) rawReader->GetEventHeader();
    int runNumber = aliHeader->Get("RunNb"); 
    
    cout << "Found run number " << runNumber << endl;
    
    // reset histograms
    for(int i=0; i<TOTCHAN; i++) {
      hfit[i]->Reset();
    }
    
    // get events (the "1" ensures that we actually select all events for now)
    if ( 1 || aliHeader->Get("Type") == AliRawEventHeaderBase::kPhysicsEvent ) {
      const UInt_t * evtId = aliHeader->GetP("Id");
      int evno_raw = (int) evtId[0];
      int timestamp = aliHeader->Get("Timestamp");
      
      cout << " evno " << evno_raw
	   << " size " << aliHeader->GetEventSize()
	   << " type " << aliHeader->Get("Type")
	   << " type name " << aliHeader->GetTypeName()
	   << " timestamp " << timestamp
	   << endl;
      
      /// process_event stream
      while ( in->Next() ) {
	
	int strip = in->GetColumn();
	int gain = in->GetRow();
	
	if (in->IsLEDMonData()) {
	  
	  int idx = strip + NSTRIPS*gain;
	  //cout << "hist idx " << idx << endl;
	  
	  if (idx < 0 || idx > TOTCHAN) { 
	    cout << "Hist idx out of range: " << idx << endl;
	  }
	  else { // reasonable range of idx
	    hfit[idx]->SetBinContent(in->GetTime(), in->GetSignal());
	  }

	} // LED Ref data only

      } // Raw data read
    
      // Next: let's actually plot the data..
      for (Int_t strip = strip_f; strip <= strip_l; strip++) {
	
	int idx = strip + NSTRIPS*gainv;
	
	// which set/column does the strip belong in
	int iset = strip / NSTRIPS_IN_SET; 	  
	int within_set = strip % NSTRIPS_IN_SET; 	  
	// on which pad should we plot it?
	int pad_id = (NSTRIPS_IN_SET-1-within_set)*NSETS + iset + 1;
	
	cout << "strip " << strip 
	     << ". set="<< iset << ", within_set=" << within_set
	     << ", pad=" << pad_id << endl;
	cc1->cd(pad_id);
	hfit[idx]->SetTitle("");
	hfit[idx]->SetFillColor(5);
	hfit[idx]->SetMaximum(ymax);
	hfit[idx]->SetMinimum(0);
	// we may or may not decide to fit the data
	if (dofit) {
	  f1[i]->SetParameter(0, 0); // initial guess; zero amplitude :=)
	  hfit[idx]->Fit(f1[i]);
	}
	hfit[idx]->Draw();
	if( numbering ) {
	  t->SetTextColor(clr[gainv]);
	  t->DrawTextNDC(0.65,0.65,ch_label[idx]);
	}
      }

      // add some extra text on the canvas
      // print a box showing run #, evt #, and timestamp
      cc1->cd();
      // first draw transparent pad
      TPad *trans = new TPad("trans","",0,0,1,1);
      trans->SetFillStyle(4000);
      trans->Draw();
      trans->cd();
      // then draw text
      TPaveText *label = new TPaveText(.2,.11,.8,.14,"NDC"); 
      //  label->Clear();
      label->SetBorderSize(1);
      label->SetFillColor(0);
      label->SetLineColor(clr[gainv]);
      label->SetTextColor(clr[gainv]);
      //label->SetFillStyle(0);
      TDatime d;
      d.Set(timestamp);
      sprintf(name,"Run %d, Event %d, Hist Max %d, %s",runno,iev,ymax,d.AsString());
      label->AddText(name);
      label->Draw();
      cc1->Update();
      cout << "Done" << endl;
      
      // some shenanigans to hold the plotting, if requested
      if (firstevent != lastevent) {
	if (delay == -1) {
	  // wait for character input before proceeding
	  cout << " enter y to proceed " << endl;
	  char dummy[2];
	  cin >> dummy;
	  cout << " read " << dummy << endl;
	  if (strcmp(dummy, "y")==0) {
	    cout << " ok, continuing with event " << iev+1 << endl;
	  }
	  else {
	    cout << " ok, exiting " << endl;
	    //exit(1);
	  }
	}
	else {
	  cout << "Sleeping for " << delay * 500 << endl;
	  gSystem->Sleep(delay * 500);
	}
      }

      // save plot, if setup/requested to do so
      char plotname[100];
      if (saveplot==1) {
	sprintf(plotname,"Run_%d_LEDRef_Ev%d_Gain%d_MaxHist%d.gif",
		runno,iev,gainv,ymax);  
	cout <<"SAVING plot:"<< plotname << endl;
	cc1->SaveAs(plotname);
      }

    } // event selection
示例#20
0
void 
HBB_LEP_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., const char* inputfile="root/$HISTFILE", const char* directory="bb_$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category_extra = "";
  if(std::string(directory) == std::string("bb_had0"  )){ category_extra = "all-had_{0}";  }
  if(std::string(directory) == std::string("bb_had1"  )){ category_extra = "all-had_{1}";  }
  if(std::string(directory) == std::string("bb_had2"  )){ category_extra = "all-had_{2}";  }
  if(std::string(directory) == std::string("bb_had3"  )){ category_extra = "all-had_{3}";  }
  if(std::string(directory) == std::string("bb_had4"  )){ category_extra = "all-had_{4}";  }
  if(std::string(directory) == std::string("bb_had5"  )){ category_extra = "all-had_{5}";  }
  if(std::string(directory) == std::string("bb_lep"   )){ category_extra = "semi-lep";  }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "Preliminary, #sqrt{s} = 7 TeV, L = 4.8 fb^{-1}";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "Preliminary, #sqrt{s} = 8 TeV, L = 19.4 fb^{-1}";}
  
  TFile* input = new TFile(inputfile);
  TH1F* bkgBBB  = refill((TH1F*)input->Get(TString::Format("%s/bkgBBB"   , directory)), "bkgBBB"); InitHist(bkgBBB, "", "", kMagenta-10, 1001);;
#ifdef MSSM
  float bbHScale = 1.; // scenario for MSSM, mhmax, mA=160, tanb=20, A+H for the time being
  if(std::string(inputfile).find("7TeV")!=std::string::npos){ bbHScale = (23314.3*0.879 + 21999.3*0.877)/1000.; }
  if(std::string(inputfile).find("8TeV")!=std::string::npos){ bbHScale = (31087.9*0.879 + 29317.8*0.877)/1000.; }
 //  float bbHScale = 1.; // scenario for MSSM, mhmax, mA=160, tanb=10, A+H for the time being
//   if(std::string(inputfile).find("7TeV")!=std::string::npos){ bbHScale = (6211.6*0.89 + 5145.0*0.85)/1000.; }
//   if(std::string(inputfile).find("8TeV")!=std::string::npos){ bbHScale = (8282.7*0.89 + 6867.8*0.85)/1000.; }
  TH1F* bbH  = refill((TH1F*)input->Get(TString::Format("%s/bbH160"  , directory)), "bbH"  ); InitSignal(bbH); bbH->Scale(bbHScale);
#endif
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
  InitHist(data, "#bf{m_{b#bar{b}} [GeV]}", "#bf{dN/dm_{b#bar{b}} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)bkgBBB->Clone("ref");

  double unscaled[7];
  unscaled[0] = bkgBBB ->Integral();
#ifdef MSSM
  unscaled[1] = bbH ->Integral();
  unscaled[2] = 0;
#endif

  if(scaled){
    rescale(bkgBBB,   1);
#ifdef MSSM 
    rescale(bbH,   2);
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-bkgBBB", "", 3, 0, 3);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (bkgBBB  ->Integral()/unscaled[0]-1.) : 0.);
#ifdef MSSM
  scales[1] = new TH1F("scales-bbH"  , "", 3, 0, 3);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (bbH  ->Integral()/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-NONE" , "", 3, 0, 3);
  scales[2]->SetBinContent(3, 0.);
#endif

  if(!log){
#ifdef MSSM
    bbH  ->Add(bkgBBB);
#endif
  }

  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(350)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(1000)); };
#endif

  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(bkgBBB, log)));
  data->Draw("e");

  TH1F* errorBand = (TH1F*)bkgBBB ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);

  if(log){
    bkgBBB  ->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    bbH     ->Draw("histsame");
#endif
  }
  else{  
#ifndef DROP_SIGNAL
    bbH     ->Draw("histsame");
#endif  
    bkgBBB  ->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "b#bar{b}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.17, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText("b#bar{b}");
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();
 
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m_{A}=160GeV");
  massA->Draw();

  TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
  tanb->SetBorderSize(   0 );
  tanb->SetFillStyle(    0 );
  tanb->SetTextAlign(   12 );
  tanb->SetTextSize ( 0.03 );
  tanb->SetTextColor(    1 );
  tanb->SetTextFont (   62 );
  tanb->AddText("tan#beta=20");
  tanb->Draw();

  TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
  scen->SetBorderSize(   0 );
  scen->SetFillStyle(    0 );
  scen->SetTextAlign(   12 );
  scen->SetTextSize ( 0.03 );
  scen->SetTextColor(    1 );
  scen->SetTextFont (   62 );
  scen->AddText("mhmax");
  scen->Draw();
#endif


#ifdef MSSM  
  TLegend* leg = new TLegend(0.55, 0.65, 0.94, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(bbH  , "#phi#rightarrowb#bar{b}" , "L" );
#endif
  leg->AddEntry(data,   "observed"                       , "LP");
  leg->AddEntry(bkgBBB, "bkgBBB"                      , "F" );
  $ERROR_LEGEND
  leg->Draw();

//#ifdef MSSM
//  TPaveText* mssm  = new TPaveText(0.69, 0.85, 0.90, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("(m_{A}=250, tan#beta=5)");
//  mssm->Draw();
//#else
//  TPaveText* mssm  = new TPaveText(0.83, 0.85, 0.95, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("m_{H}=125");
//  mssm->Draw();
//#endif

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
  rat1->Divide(bkgBBB);
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
    zero->SetBinContent(ibin+1, 0.);
  }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+1.5);
  rat1->SetMinimum(-1.5);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{b#bar{b}} [GeV]}");
  rat1->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv0->RedrawAxis();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* rat2 = (TH1F*) bkgBBB->Clone("rat2");
  rat2->Divide(ref);
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  rat2->SetLineColor(kRed+ 3);
  rat2->SetFillColor(kRed-10);
  rat2->SetMaximum(+0.3);
  rat2->SetMinimum(-0.3);
  rat2->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{b#bar{b}} [GeV]}");
  rat2->GetXaxis()->SetRange(0, 28);
  rat2->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kMagenta-10, 1001);
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{bkgBBB}");
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{NONE}" );
#endif
  scales[0]->SetMaximum(+1.0);
  scales[0]->SetMinimum(-1.0);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  zero->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.png"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.pdf"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.eps"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  TFile* output = new TFile(TString::Format("%s_%sscaled_%s_%s.root", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""), "update");
  output->cd();
  data ->Write("data_obs");
  bkgBBB  ->Write("bkgBBB"  );
#ifdef MSSM
  bbH  ->Write("bbH"     );
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
}
void compareLimits(const char* filename, const char* channelstr, bool expected, bool observed, const char* type, double minimum=0., double maximum=20., bool log=false, const char* label="#scale[1.5]{CMS}   h,H,A#rightarrow#tau#tau                     19.7 fb^{-1} (8 TeV) + 4.9 fb^{-1} (7 TeV)", bool legendOnRight=true, bool legendOnTop=true, bool ggH=true)
{
  SetStyle();

  std::map<std::string, unsigned int> colors;
  colors["0jet"       ] = kBlue;
  colors["1jet"       ] = kRed;
  colors["2jet"       ] = kMagenta;
  colors["vbf"        ] = kMagenta;
  colors["boost"      ] = kGreen;
  colors["btag"       ] = kRed; 
  colors["nobtag"     ] = kBlue; 
  colors["em"         ] = kBlue;
  colors["et"         ] = kRed;
  colors["mt"         ] = kGreen;
  colors["mm"         ] = kMagenta;
  colors["ee"         ] = kCyan;
  colors["tt"         ] = kMagenta+3;
  colors["vhtt"       ] = kCyan-6;
  colors["cmb"        ] = kBlack;
  colors["htt"        ] = kBlack;
  colors["ggH"        ] = kRed;
  colors["bbH"        ] = kBlue;
  colors["HIG-11-020" ] = kBlue+2;
  colors["HIG-11-029" ] = kRed+2;
  colors["HIG-12-018" ] = kBlue;
  colors["HIG-12-032" ] = kRed+2;
  colors["HIG-12-043" ] = kRed;
  colors["HIG-12-050" ] = kRed;

  std::cout << " *******************************************************************************************************\n"
	    << " * Usage     : root -l                                                                                  \n"
	    << " *             .x MitLimits/Higgs2Tau/macros/compareLimits.C+(file, chn, exp, obs, type, min, max, log) \n"
	    << " *                                                                                                      \n"
	    << " * Arguments :  + file     const char*      full path to the input file                                 \n"
	    << " *              + chn      const char*      list of channels; choose between: 'cmb', 'htt', 'emu',      \n"
	    << " *                                          'etau', 'mutau', 'mumu', 'vhtt', 'hgg', 'hww', 'ggH',       \n"
	    << " *                                          'bbH', 'nomix[-200, +200]', 'mhmax[-400, -200, +200]'       \n"
	    << " *                                          'mhmax[+400, +600, +800]', 'test-0...5', 'saeff', 'gluph'   \n"
	    << " *                                          The list should be comma separated and may contain          \n"
	    << " *                                          whitespaces                                                 \n"
	    << " *              + exp       bool            compare expected limits                                     \n"
	    << " *              + obs       bool            compare observed limits                                     \n"
	    << " *              + type      const char*     type of plot; choose between 'sm-xsec', 'mssm-xsec' and     \n"
	    << " *                                          'mssm-tanb'                                                 \n"
	    << " *              + max       double          maximum of the plot (default is 20.)                        \n"
	    << " *                                                                                                      \n"
	    << " *              + min       double          minimum of the plot (default is  0.)                        \n"
	    << " *                                                                                                      \n"
	    << " *              + log       bool            set log scale yes or no (default is false)                  \n"
	    << " *                                                                                                      \n"
	    << " *******************************************************************************************************\n";

  /// open input file  
  TFile* inputFile = new TFile(filename); if(inputFile->IsZombie()){ std::cout << "ERROR:: file: " << filename << " does not exist.\n"; }
  
  /// prepare input parameters
  std::vector<std::string> channels;
  string2Vector(cleanupWhitespaces(channelstr), channels);

  /// prepare histograms
  std::vector<TGraph*> hobs, hexp;
  for(unsigned i=0; i<channels.size(); ++i){
    if(observed) hobs.push_back(get<TGraph>(inputFile, std::string(channels[i]).append("/observed").c_str()));
    if(expected) hexp.push_back(get<TGraph>(inputFile, std::string(channels[i]).append("/expected").c_str()));
  }

  /// do the drawing
  TCanvas* canv1 = new TCanvas("canv1", "Limit Comparison", 600, 600);
  canv1->cd();
  canv1->SetGridx(1);
  canv1->SetGridy(1);
  if((std::string(type) == std::string("mssm-xsec") || std::string(type) == std::string("mssm-tanb")) && log) canv1->SetLogx(1); 

  bool firstPlot=true;
  for(unsigned int i=0; i<hexp.size(); ++i){
    if(firstPlot){
	if(log){ canv1->SetLogy(1); }
	hexp[i]->SetMaximum(maximum);
	hexp[i]->SetMinimum(minimum);
      
      // format x-axis
      std::string x_title;
      if(std::string(type) == std::string("mssm-tanb")){
	x_title = std::string("m_{A} [GeV]");
      }
      else if(std::string(type) == std::string("mssm-xsec")){
	x_title = std::string("m_{#phi} [GeV]");
      }
      else{
	x_title = std::string("m_{H} [GeV]");
      }
      hexp[i]->GetXaxis()->SetTitle(x_title.c_str());
      hexp[i]->GetXaxis()->SetLabelFont(62);
      hexp[i]->GetXaxis()->SetTitleFont(62);
      hexp[i]->GetXaxis()->SetTitleColor(1);
      hexp[i]->GetXaxis()->SetTitleOffset(1.05);
      if((std::string(type) == std::string("mssm-xsec") || std::string(type) == std::string("mssm-tanb")) && log){
	hexp[i]->GetXaxis()->SetNdivisions(50005, "X");
	hexp[i]->GetXaxis()->SetMoreLogLabels();
	hexp[i]->GetXaxis()->SetNoExponent();
	hexp[i]->GetXaxis()->SetLabelSize(0.040);
      }
      hexp[i]->GetXaxis()->SetLimits(hexp[i]->GetX()[0]-.1, hexp[i]->GetX()[hexp[i]->GetN()-1]+.1);
      if(std::string(type) == std::string("mssm-xsec") || std::string(type) == std::string("mssm-tanb")){
	if(log){
	  hexp[i]->GetXaxis()->SetLimits(hexp[i]->GetX()[0], hexp[i]->GetX()[hexp[i]->GetN()-1]+.1);
	}
	else{
	  hexp[i]->GetXaxis()->SetLimits(hexp[i]->GetX()[0]-.1, hexp[i]->GetX()[hexp[i]->GetN()-1]+.1);
	}      
      }

      // format y-axis
      std::string y_title;
      if( std::string(type) == std::string("mssm-xsec") ){
	if(ggH) y_title = std::string("95% CL limit on #sigma(gg#rightarrow#phi)#timesBR [pb]");
	else y_title = std::string("95% CL limit on #sigma(gg#rightarrowbb#phi)#timesBR [pb]");
      }
      else if(  std::string(type) == std::string("mssm-tanb")  ){
	y_title = std::string("#bf{tan#beta}");
      }
      else{
	y_title = std::string("95% CL limit on #sigma/#sigma_{SM}");
      }
      hexp[i]->GetYaxis()->SetTitle(y_title.c_str());
      hexp[i]->GetYaxis()->SetLabelFont(62);
      hexp[i]->GetYaxis()->SetTitleFont(62);
      hexp[i]->GetYaxis()->SetTitleOffset(1.05);
      hexp[i]->GetYaxis()->SetLabelSize(0.03);
    }
    hexp[i]->SetLineStyle(11.);
    hexp[i]->SetLineWidth( 3.); 
    hexp[i]->SetLineColor(colors.find(channels[i])->second);
    hexp[i]->SetMarkerStyle(20);
    hexp[i]->SetMarkerSize(MARKER_SIZE);
    hexp[i]->SetMarkerColor(colors.find(channels[i])->second);
    hexp[i]->Draw(firstPlot ? "APL" : "PLsame");
    //hexp[i]->Draw(firstPlot ? "AL" : "Lsame");
    firstPlot=false;
  }
  for(unsigned int i=0; i<hobs.size(); ++i){
    if(firstPlot){
      if(log){ canv1->SetLogy(1); }
      hobs[i]->SetMaximum(maximum);
      hobs[i]->SetMinimum(minimum);
      
      // format x-axis
      std::string x_title;
      if(std::string(type) == std::string("mssm-tanb")){
	x_title = std::string("m_{A} [GeV]");
      }
      else if(std::string(type) == std::string("mssm-xsec")){
	x_title = std::string("m_{#phi} [GeV]");
      }
      else{
	x_title = std::string("m_{H} [GeV]");
      }
      hobs[i]->GetXaxis()->SetTitle(x_title.c_str());
      hobs[i]->GetXaxis()->SetLabelFont(62);
      hobs[i]->GetXaxis()->SetTitleFont(62);
      hobs[i]->GetXaxis()->SetTitleColor(1);
      hobs[i]->GetXaxis()->SetTitleOffset(1.05);
      if((std::string(type) == std::string("mssm-xsec") || std::string(type) == std::string("mssm-tanb")) && log){
	hobs[i]->GetXaxis()->SetNdivisions(50005, "X");
	hobs[i]->GetXaxis()->SetMoreLogLabels();
	hobs[i]->GetXaxis()->SetNoExponent();
	hobs[i]->GetXaxis()->SetLabelSize(0.040);
      }
      hobs[i]->GetXaxis()->SetLimits(hobs[i]->GetX()[0]-.1, hobs[i]->GetX()[hobs[i]->GetN()-1]+.1);
      if(std::string(type) == std::string("mssm-xsec") || std::string(type) == std::string("mssm-tanb")){
	if(log){
	  hobs[i]->GetXaxis()->SetLimits(hobs[i]->GetX()[0], hobs[i]->GetX()[hobs[i]->GetN()-1]+.1);
	}
	else{
	  hobs[i]->GetXaxis()->SetLimits(hobs[i]->GetX()[0]-.1, hobs[i]->GetX()[hobs[i]->GetN()-1]+.1);
	}      
      }
      
      // format y-axis
      std::string y_title;
      if( std::string(type) == std::string("mssm-xsec") ){
	if(ggH) y_title = std::string("95% CL limit on #sigma#font[42]{(gg#phi)}#upoint#font[52]{B}#font[42]{(#phi#rightarrow#tau#tau)} [pb]");
	else y_title = std::string("95% CL limit on #sigma#font[42]{(bb#phi)}#upoint#font[52]{B}#font[42]{(#phi#rightarrow#tau#tau)} [pb]");
      }
      else if(  std::string(type) == std::string("mssm-tanb")  ){
	y_title = std::string("#bf{tan#beta}");
      }
      else{
	y_title = std::string("95% CL limit on #sigma/#sigma_{SM}");
      }
      hobs[i]->GetYaxis()->SetTitle(y_title.c_str());
      hobs[i]->GetYaxis()->SetLabelFont(62);
      hobs[i]->GetYaxis()->SetTitleOffset(1.05);
      hobs[i]->GetYaxis()->SetLabelSize(0.03);
    }
    hobs[i]->SetLineStyle(11.);
    hobs[i]->SetLineWidth( 3.); 
    hobs[i]->SetLineColor(colors.find(channels[i])->second);
    hobs[i]->SetMarkerStyle(20);
    hobs[i]->SetMarkerSize(MARKER_SIZE);
    hobs[i]->SetMarkerColor(colors.find(channels[i])->second);
    hobs[i]->Draw(firstPlot ? "APL" : "PLsame");
    //hobs[i]->Draw(firstPlot ? "AL" : "Lsame");
    firstPlot=false;
  }
  canv1->RedrawAxis();

  TPaveText* extra;
  if( std::string(type) == std::string("mssm-xsec") ){
    extra = new TPaveText(legendOnRight ? 0.6 : 0.18, 0.50, legendOnRight ? 0.95 : 0.605, 0.60, "NDC");
    extra->SetBorderSize(   0 );
    extra->SetFillStyle (   0 );
    extra->SetTextAlign (  12 );
    extra->SetTextSize  (0.04 );
    extra->SetTextColor (   1 );
    extra->SetTextFont  (  62 );
    if(ggH) extra->AddText("gg#phi");
    else extra->AddText("bb#phi");
    extra->Draw();
  }

  bool firstLeg=true;
  if(observed){
    TLegend* leg1;
    if(expected && observed){
      /// setup the CMS Preliminary
       if(std::string(type) == std::string("mssm-tanb")){
	  if (firstLeg) CMSPrelim(label, "", 0.15, 0.835);
	  leg1 = new TLegend(firstLeg ? 0.60 : 0.20, hobs.size()<5 ? 0.20-0.06*hobs.size() : 0.4, firstLeg ? 0.93 : 0.60, 0.20);
       }
       else{
	  if (firstLeg) CMSPrelim(label, "", 0.135, 0.835);
	  leg1 = new TLegend(firstLeg ? 0.20 : 0.20, hobs.size()<5 ? 0.90-0.08*hobs.size() : 0.6, firstLeg ? 0.63 : 0.60, 0.90);
       }
    }
    else{
      /// setup the CMS Preliminary
      if(std::string(type) == std::string("mssm-tanb")){
	CMSPrelim(label, "", 0.15, 0.835);
	leg1 = new TLegend(legendOnRight?0.60:0.20, hobs.size()<5 ? (legendOnTop?0.90:0.40)-0.04*hobs.size() : (legendOnTop?0.6:0.2), legendOnRight?0.94:0.45, (legendOnTop?0.90:0.40));
	   }
      else{
	CMSPrelim(label, "", 0.135, 0.835);
	leg1 = new TLegend(legendOnRight ? 0.50 : 0.20, hobs.size()<5 ? 0.90-0.08*hobs.size() : 0.6, legendOnRight ? 0.94 : 0.64, 0.90);
      }
    }
    if(std::string(type) == std::string("mssm-tanb")) {leg1->SetTextSize(0.03);}
    //leg1->SetTextSize(0.02);
    leg1->SetBorderSize( 0 );
    leg1->SetFillStyle ( 1001 );
    //leg1->SetFillColor ( 0 );
    leg1->SetFillColor (kWhite);
    leg1->SetHeader( "#bf{observed}" );
    for(unsigned int i=0; i<hobs.size(); ++i){
      leg1->AddEntry( hobs[i] , channel(channels[i]) ? legendEntry(channels[i]).c_str() : legendEntry(channels[i]).append("-Channel").c_str(),  "PL" );
    }
    leg1->Draw("same");
    firstLeg=false;
  }
  if(expected){
    TLegend* leg0;
    if(expected && observed){
      /// setup the CMS Preliminary
      if(std::string(type) == std::string("mssm-tanb")){
	CMSPrelim(label, "", 0.15, 0.835);
	leg0 = new TLegend(legendOnRight ? 0.60 : 0.20, hexp.size()<5 ? 0.20-0.06*hexp.size() : 0.4, legendOnRight ? 0.94 : 0.63, 0.20);
      }
      else{
	CMSPrelim(label, "", 0.135, 0.835);
	leg0 = new TLegend(legendOnRight ? 0.20 : 0.20, hexp.size()<5 ? 0.75-0.08*hexp.size() : 0.6, legendOnRight ? 0.94 : 0.63, 0.75);
      }
    }
    else{
      /// setup the CMS Preliminary
      if(std::string(type) == std::string("mssm-tanb")){
	CMSPrelim(label, "", 0.15, 0.835);
	leg0 = new TLegend(legendOnRight?0.60:0.20, hexp.size()<5 ? (legendOnTop?0.90:0.40)-0.04*hexp.size() : (legendOnTop?0.6:0.2), legendOnRight?0.94:0.45, (legendOnTop?0.90:0.40));
	   }
      else{
	CMSPrelim(label, "", 0.135, 0.835);
	leg0 = new TLegend(legendOnRight ? 0.50 : 0.20, hexp.size()<5 ? 0.90-0.06*hexp.size() : 0.6, legendOnRight ? 0.74 : 0.63, 0.90);
	//leg0 = new TLegend(legendOnRight ? 0.50 : 0.20, hexp.size()<5 ? 0.90-0.08*hexp.size() : 0.6, legendOnRight ? 0.94 : 0.80, 0.90);
      }
    }
    if(std::string(type) == std::string("mssm-tanb")) {leg0->SetTextSize(0.03);}
    leg0->SetBorderSize( 0 );
    leg0->SetFillStyle ( 1001 );
    leg0->SetFillColor (kWhite);
    leg0->SetHeader( "#bf{expected}" );
    for(unsigned int i=0; i<hexp.size(); ++i){
      leg0->AddEntry( hexp[i] , channel(channels[i]) ? legendEntry(channels[i]).c_str() : legendEntry(channels[i]).append("-Channel").c_str(),  "PL" );
    }
    leg0->Draw("same");
    firstLeg=false;
  }
  canv1->Print(std::string("singleLimits").append(expected ? "_expected" : "").append(observed ? "_observed" : "").append(std::string(type).find("mssm")!=std::string::npos ? "_mssm.png" : "_sm.png").c_str());
  canv1->Print(std::string("singleLimits").append(expected ? "_expected" : "").append(observed ? "_observed" : "").append(std::string(type).find("mssm")!=std::string::npos ? "_mssm.pdf" : "_sm.pdf").c_str());
  canv1->Print(std::string("singleLimits").append(expected ? "_expected" : "").append(observed ? "_observed" : "").append(std::string(type).find("mssm")!=std::string::npos ? "_mssm.pdf" : "_sm.eps").c_str());
  return;
}
//*************************************************************
void arrangeBiasCanvas(TCanvas *canv,TH1F* dxyPhiMeanTrend[100],TH1F* dzPhiMeanTrend[100],TH1F* dxyEtaMeanTrend[100],TH1F* dzEtaMeanTrend[100],Int_t nFiles, TString LegLabels[10]){
//*************************************************************

  TLegend *lego = new TLegend(0.19,0.70,0.79,0.92);
  lego-> SetNColumns(2);
  lego->SetFillColor(10);
  lego->SetTextSize(0.042);
  lego->SetTextFont(42);
  lego->SetFillColor(10);
  lego->SetLineColor(10);
  lego->SetShadowColor(10);

  TPaveText *pt = new TPaveText(0.13,0.95,0.89,0.97,"NDC");
  pt->SetFillColor(10);
  pt->SetTextColor(1);
  pt->SetTextFont(42);
  pt->SetTextAlign(11);
  TText *text1 = pt->AddText("CMS Preliminary 2015 - 3.8T collision data");
  text1->SetTextSize(0.05);
 
  TPaveText *pt2 = new TPaveText(0.70,0.75,0.89,0.92,"NDC");
  pt2->SetFillColor(10);
  pt2->SetTextColor(kBlue);
  pt2->SetTextFont(62);
  pt2->SetTextAlign(11);
  TText *text2 = pt2->AddText("run 247078");
  text2->SetTextSize(0.05);

  canv->SetFillColor(10);  
  canv->Divide(2,2);
 
  canv->cd(1)->SetBottomMargin(0.14);
  canv->cd(1)->SetLeftMargin(0.18);
  canv->cd(1)->SetRightMargin(0.01);
  canv->cd(1)->SetTopMargin(0.06);  

  canv->cd(2)->SetBottomMargin(0.14);
  canv->cd(2)->SetLeftMargin(0.18);
  canv->cd(2)->SetRightMargin(0.01);
  canv->cd(2)->SetTopMargin(0.06);  
  
  canv->cd(3)->SetBottomMargin(0.14);
  canv->cd(3)->SetLeftMargin(0.18);
  canv->cd(3)->SetRightMargin(0.01);
  canv->cd(3)->SetTopMargin(0.06);  

  canv->cd(4)->SetBottomMargin(0.14);
  canv->cd(4)->SetLeftMargin(0.18);
  canv->cd(4)->SetRightMargin(0.01);
  canv->cd(4)->SetTopMargin(0.06); 

  TH1F *dBiasTrend[4][nFiles]; 
  
  for(Int_t i=0;i<nFiles;i++){
    dBiasTrend[0][i] = dxyPhiMeanTrend[i];
    dBiasTrend[1][i] = dzPhiMeanTrend[i];
    dBiasTrend[2][i] = dxyEtaMeanTrend[i];
    dBiasTrend[3][i] = dzEtaMeanTrend[i];
  }

  Double_t absmin[4]={999.,999.,999.,999.};
  Double_t absmax[4]={-999.,-999.-999.,-999.};

  for(Int_t k=0; k<4; k++){

    canv->cd(k+1);
    
    for(Int_t i=0; i<nFiles; i++){
      if(dBiasTrend[k][i]->GetMaximum()>absmax[k]) absmax[k] = dBiasTrend[k][i]->GetMaximum();
      if(dBiasTrend[k][i]->GetMinimum()<absmin[k]) absmin[k] = dBiasTrend[k][i]->GetMinimum();
    }

   
    Double_t safeDelta=(absmax[k]-absmin[k])/8.;
    Double_t theExtreme=std::max(absmax[k],TMath::Abs(absmin[k]));

    for(Int_t i=0; i<nFiles; i++){
      if(i==0){
	//dBiasTrend[i]->GetYaxis()->SetRangeUser(absmin-safeDelta/2.,absmax+safeDelta);
	//std::cout<<"name is: "<< dBiasTrend[k][i]->GetName() <<std::endl;
	TString theTitle = dBiasTrend[k][i]->GetName();
	if( theTitle.Contains("Norm")){
	  dBiasTrend[k][i]->GetYaxis()->SetRangeUser(std::min(-0.48,absmin[k]-safeDelta/2.),std::max(0.48,absmax[k]+safeDelta/2.));
	} else {
	  //dBiasTrend[k][i]->GetYaxis()->SetRangeUser(std::min(-8.8,absmin[k]-safeDelta/2.),std::max(8.8,absmax[k]+safeDelta/2.));
	  dBiasTrend[k][i]->GetYaxis()->SetRangeUser(-theExtreme-(safeDelta/2.),theExtreme+(safeDelta/2.));
	  //dBiasTrend[k][i]->GetYaxis()->SetRangeUser(-theExtreme,theExtreme);
	} 
	dBiasTrend[k][i]->Draw("Le1");
      }
      else dBiasTrend[k][i]->Draw("Le1sames");
      if(k==0){
	lego->AddEntry(dBiasTrend[k][i],LegLabels[i]);
      } 
    }  
  
    lego->Draw();
    pt->Draw("same");
  }
  
}
//*************************************************************
void arrangeCanvas(TCanvas *canv,TH1F* meanplots[100],TH1F* widthplots[100],Int_t nFiles, TString LegLabels[10], bool onlyBias){
//*************************************************************

  TPaveText *ali = new TPaveText(0.18,0.87,0.50,0.93,"NDC");  
  ali->SetFillColor(10);
  ali->SetTextColor(1);
  ali->SetTextFont(42);
  ali->SetMargin(0.);
  ali->SetLineColor(10);
  ali->SetShadowColor(10);
  // pt->SetTextAlign(11);
  TText *alitext = ali->AddText("Alignment: PCL"); //"Preliminary 2015 - 0T collision data");
  alitext->SetTextSize(0.04);

  TLegend *lego = new TLegend(0.18,0.80,0.78,0.92);
  lego-> SetNColumns(2);
  //TLegend *lego = new TLegend(0.18,0.77,0.50,0.86);
  lego->SetFillColor(10);
  lego->SetTextSize(0.04);
  lego->SetTextFont(42);
  lego->SetFillColor(10);
  lego->SetLineColor(10);
  lego->SetShadowColor(10);

  TPaveText *pt  = NULL;
  TPaveText *pt2 = NULL;
  TPaveText *pt3 = NULL;

  if(!onlyBias){ 
    pt =new TPaveText(0.179,0.955,0.260,0.985,"NDC");
  } else {
    pt =new TPaveText(0.179,0.955,0.260,0.985,"NDC");
  }

  pt->SetFillColor(10);
  pt->SetTextColor(1);
  pt->SetTextFont(61);
  // pt->SetTextAlign(11);
  TText *text1 = pt->AddText("CMS"); //"Preliminary 2015 - 0T collision data");
  text1->SetTextSize(0.05);
 
  float extraOverCmsTextSize  = 0.76;

  if(!onlyBias){ 
    pt2 =new TPaveText(0.3,0.95,0.503,0.98,"NDC");
  } else {
    pt2 =new TPaveText(0.3,0.95,0.503,0.98,"NDC");
  }

  pt2->SetFillColor(10);
  pt2->SetTextColor(1);
  pt2->SetTextFont(52);
  pt2->SetTextAlign(22);
  TText *text2 = pt2->AddText("work in progress");
  text2->SetTextSize(0.05*extraOverCmsTextSize);

  if(!onlyBias){ 
    pt3 =new TPaveText(0.6,0.95,0.98,0.98,"NDC");
  } else {
    pt3 =new TPaveText(0.6,0.95,0.98,0.98,"NDC");
  }

  pt3->SetFillColor(10);
  pt3->SetTextColor(1);
  pt3->SetTextFont(42);
  // pt2->SetTextAlign(11);
  TText *text3 = pt3->AddText("3.8T collision data 2015");
  text3->SetTextSize(0.05*extraOverCmsTextSize);

  canv->SetFillColor(10);  
  if(!onlyBias) {
    canv->Divide(2,1);
    
    canv->cd(1)->SetBottomMargin(0.12);
    canv->cd(1)->SetLeftMargin(0.17);
    canv->cd(1)->SetRightMargin(0.02);
    canv->cd(1)->SetTopMargin(0.06);  
    
    canv->cd(2)->SetBottomMargin(0.12);
    canv->cd(2)->SetLeftMargin(0.17);
    canv->cd(2)->SetRightMargin(0.02);
    canv->cd(2)->SetTopMargin(0.06);  
  
    canv->cd(1);
  } else {
    
    canv->cd()->SetBottomMargin(0.14);
    canv->cd()->SetLeftMargin(0.17);
    canv->cd()->SetRightMargin(0.02);
    canv->cd()->SetTopMargin(0.06);  
    canv->cd();

  }

  Double_t absmin(999.);
  Double_t absmax(-999.);

  for(Int_t i=0; i<nFiles; i++){
    if(meanplots[i]->GetMaximum()>absmax) absmax = meanplots[i]->GetMaximum();
    if(meanplots[i]->GetMinimum()<absmin) absmin = meanplots[i]->GetMinimum();
  }

  Double_t safeDelta=(absmax-absmin)/2.;
  Double_t theExtreme=std::max(absmax,TMath::Abs(absmin));

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

    TString myTitle = meanplots[i]->GetName();
    float axmin = -999;
    float axmax = 999.;
    int ndiv = 510;
    if(myTitle.Contains("eta")){
      axmin = -2.5;
      axmax = 2.5;
      ndiv = 505;
    } else if (myTitle.Contains("phi")){
      axmin = -TMath::Pi();
      axmax = TMath::Pi();
      ndiv = 510;
    } else  {
      std::cout<<"unrecongnized variable";
    }

    meanplots[i]->GetXaxis()->SetLabelOffset(999);
    meanplots[i]->GetXaxis()->SetTickLength(0);
    
    // Redraw the new axis 
    gPad->Update();
    TGaxis *newaxis =  new TGaxis(gPad->GetUxmin(),gPad->GetUymin(),
				  gPad->GetUxmax(),gPad->GetUymin(),
				  axmin,
				  axmax,
				  //meanplots[i]->GetXaxis()->GetXmin(),
				  //meanplots[i]->GetXaxis()->GetXmax(),
				  ndiv,"SDH");
    
    
    TGaxis *newaxisup =  new TGaxis(gPad->GetUxmin(),gPad->GetUymax(),
				    gPad->GetUxmax(),gPad->GetUymax(),
				    axmin,
				    axmax,
				    //meanplots[i]->GetXaxis()->GetXmin(),                                                                                                     
				    //meanplots[i]->GetXaxis()->GetXmax(),                                                                                                     
				    ndiv,"-SDH");
    
    newaxis->SetLabelOffset(0.02);
    newaxis->SetLabelFont(42);
    newaxis->SetLabelSize(.05);
    newaxis->Draw();

    newaxisup->SetLabelOffset(-0.02);
    newaxisup->SetLabelFont(42);
    newaxisup->SetLabelSize(0);
    newaxisup->Draw();
    
    if(i==0){
      //meanplots[i]->GetYaxis()->SetRangeUser(absmin-safeDelta/2.,absmax+safeDelta);
      std::cout<<"name is: "<< meanplots[i]->GetName() << " absmin:" <<absmin<<" absmax: "<<absmax<<" safeDelta: "<<safeDelta<<std::endl;
      TString theTitle = meanplots[i]->GetName();
      if( theTitle.Contains("Norm")){
	meanplots[i]->GetYaxis()->SetRangeUser(std::min(-0.48,absmin-safeDelta),std::max(0.48,absmax+safeDelta));
      } else {
	if(!onlyBias){
	  meanplots[i]->GetYaxis()->SetRangeUser(absmin-safeDelta,absmax+safeDelta);
	} else {
	  meanplots[i]->GetYaxis()->SetRangeUser(-theExtreme-(TMath::Abs(absmin)/10.),theExtreme+(TMath::Abs(absmax/10.)));
	}
	//meanplots[i]->GetYaxis()->SetRangeUser(-theExtreme,theExtreme);
      } 
      meanplots[i]->Draw("e1");

      if(onlyBias){
	Int_t nbins =  meanplots[i]->GetNbinsX();
	Double_t lowedge  = meanplots[i]->GetBinLowEdge(1);
	Double_t highedge = meanplots[i]->GetBinLowEdge(nbins+1);
	
	TH1F* hzero = DrawZero(meanplots[i],nbins,lowedge,highedge);
	hzero->Draw("PLsame");
      }

    }
    else meanplots[i]->Draw("e1sames");
    lego->AddEntry(meanplots[i],LegLabels[i]); 
  }  
  

  //ali->Draw();
  lego->Draw();
  pt->Draw("same");
  pt2->Draw("same");
  pt3->Draw("same");


  if(!onlyBias){

    canv->cd(2);
    Double_t absmax2(-999.);
    
    for(Int_t i=0; i<nFiles; i++){
      if(widthplots[i]->GetMaximum()>absmax2) absmax2 = widthplots[i]->GetMaximum();
    }
    
    Double_t safeDelta2=absmax2/3.;
    
    for(Int_t i=0; i<nFiles; i++){

      TString myTitle = widthplots[i]->GetName();
      float axmin = -999;
      float axmax = 999.;
      int ndiv = 510;
      if(myTitle.Contains("eta")){
	axmin = -2.5;
	axmax = 2.5;
	ndiv = 505;
      } else if (myTitle.Contains("phi")){
	axmin = -TMath::Pi();
	axmax = TMath::Pi();
	ndiv = 510;
      } else  {
	std::cout<<"unrecongnized variable";
      }
      
      widthplots[i]->GetXaxis()->SetLabelOffset(999);
      widthplots[i]->GetXaxis()->SetTickLength(0);
      
      // Redraw the new axis 
      gPad->Update();
      TGaxis *newaxis2 = new TGaxis(gPad->GetUxmin(),gPad->GetUymin(),
				    gPad->GetUxmax(),gPad->GetUymin(),
				    axmin,
				    axmax,
				    //widthplots[i]->GetXaxis()->GetXmin(),
				    //widthplots[i]->GetXaxis()->GetXmax(),
				    ndiv,"SDH");
      
      newaxis2->SetLabelOffset(0.02);
      newaxis2->SetLabelFont(42);
      newaxis2->SetLabelSize(.05);
      newaxis2->Draw();

      TGaxis *newaxis2up = new TGaxis(gPad->GetUxmin(),gPad->GetUymax(),
				      gPad->GetUxmax(),gPad->GetUymax(),
				      axmin,
				      axmax,
				      //widthplots[i]->GetXaxis()->GetXmin(),
				      //widthplots[i]->GetXaxis()->GetXmax(),
				      ndiv,"-SDH");
      
      newaxis2up->SetLabelOffset(-0.02);
      newaxis2up->SetLabelFont(42);
      newaxis2up->SetLabelSize(0.);
      newaxis2up->Draw();

      if(i==0) widthplots[i]->Draw("e1");
      else widthplots[i]->Draw("e1sames");
      widthplots[i]->SetMinimum(0.5);
      widthplots[i]->SetMaximum(absmax2+safeDelta2);
    }
    
    lego->Draw();
    pt->Draw("same");
    pt2->Draw("same");
    pt3->Draw("same");

  }
}
void 
HTT_EE_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="ee_$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("ee_0jet_low"             )){ category = "ee, 0 jet";          }    
  if(std::string(directory) == std::string("ee_0jet_low"             )){ category_extra = "p_{T}(lep1) low";          }    
  if(std::string(directory) == std::string("ee_0jet_high"            )){ category = "ee, 0 jet";          }    
  if(std::string(directory) == std::string("ee_0jet_high"            )){ category_extra = "p_{T}(lep1) high";         }    
  if(std::string(directory) == std::string("ee_1jet_low"          )){ category = "ee, 1 jet";          }    
  if(std::string(directory) == std::string("ee_1jet_low"          )){ category_extra = "p_{T}(lep1) low";       }    
  if(std::string(directory) == std::string("ee_1jet_high"          )){ category = "ee, 1 jet";          }    
  if(std::string(directory) == std::string("ee_1jet_high"          )){ category_extra = "p_{T}(lep1) high";       }    
  if(std::string(directory) == std::string("ee_vbf"            )){ category = "ee, 2 jet";          }    
  if(std::string(directory) == std::string("ee_vbf"            )){ category_extra = "VBF";              }    
  if(std::string(directory) == std::string("ee_nobtag"               )){ category = "ee";          }    
  if(std::string(directory) == std::string("ee_nobtag"               )){ category_extra = "No B-Tag";                        }    
  if(std::string(directory) == std::string("ee_btag"                 )){ category = "ee";          }    
  if(std::string(directory) == std::string("ee_btag"                 )){ category_extra = "B-Tag";                           }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 19.8 fb^{-1} at 8 TeV";}
 
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* ZTT     = refill((TH1F*)input ->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"     ); InitHist(ZTT     , "", "", kOrange  -  4, 1001);
  TH1F* ZEE     = refill((TH1F*)input ->Get(TString::Format("%s/ZEE"     , directory)), "ZEE"     ); InitHist(ZEE     , "", "", kAzure   +  2, 1001);
  TH1F* TTJ     = refill((TH1F*)input ->Get(TString::Format("%s/TTJ"     , directory)), "TTJ"     ); InitHist(TTJ     , "", "", kBlue    -  8, 1001);
  TH1F* QCD     = refill((TH1F*)input ->Get(TString::Format("%s/QCD"     , directory)), "QCD"     ); InitHist(QCD     , "", "", kMagenta - 10, 1001);
  TH1F* Dibosons= refill((TH1F*)input ->Get(TString::Format("%s/Dibosons", directory)), "Dibosons"); InitHist(Dibosons, "", "", kGreen   -  4, 1001);
  TH1F* WJets   = refill((TH1F*)input ->Get(TString::Format("%s/WJets"   , directory)), "WJets"   ); InitHist(WJets   , "", "", kRed     +  2, 1001);
#ifdef MSSM
  TH1F* ggH     = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA"  , directory)), "ggH"     ); InitSignal(ggH); ggH->Scale($TANB);
  TH1F* bbH     = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA"  , directory)), "bbH"     ); InitSignal(bbH); bbH->Scale($TANB);
#else
#ifndef DROP_SIGNAL
  TH1F* ggH     = refill((TH1F*)input ->Get(TString::Format("%s/ggH125"  , directory)), "ggH"     ); InitSignal(ggH); ggH->Scale(SIGNAL_SCALE);
  TH1F* qqH     = refill((TH1F*)input ->Get(TString::Format("%s/qqH125"  , directory)), "qqH"     ); InitSignal(qqH); qqH->Scale(SIGNAL_SCALE);
  TH1F* VH      = refill((TH1F*)input ->Get(TString::Format("%s/VH125"   , directory)), "VH"      ); InitSignal(VH ); VH ->Scale(SIGNAL_SCALE);
#endif
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
#ifdef MSSM
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}" , "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);
#else
  InitHist(data, "#bf{D}", "#bf{dN/dD}"     ); InitData(data);
#endif

  TH1F* ref=(TH1F*)ZTT->Clone("ref");
  ref->Add(ZEE);
  ref->Add(TTJ);
  ref->Add(QCD);
  ref->Add(Dibosons);
  ref->Add(WJets);

  double unscaled[9];
  unscaled[0] = ZTT->Integral();
  unscaled[1] = ZEE->Integral();
  unscaled[2] = TTJ->Integral();
  unscaled[3] = QCD->Integral();
  unscaled[4] = Dibosons->Integral();
  unscaled[5] = WJets->Integral();
#ifdef MSSM
  unscaled[6] = ggH->Integral();
  unscaled[7] = bbH->Integral();
  unscaled[8] = 0;
#else
#ifndef DROP_SIGNAL
  unscaled[6] = ggH->Integral();
  unscaled[7] = qqH->Integral();
  unscaled[8] = VH ->Integral();
#endif
#endif
  
  if(scaled){
    rescale(ZTT, 1); 
    rescale(ZEE, 2); 
    rescale(TTJ, 3); 
    rescale(QCD, 4); 
    rescale(Dibosons, 5); 
    rescale(WJets,    6);
#ifdef MSSM 
    rescale(ggH, 7);
    rescale(bbH, 8);
#else
#ifndef DROP_SIGNAL
    rescale(ggH, 7);
    rescale(qqH, 8);
    rescale(VH,  9);
#endif
#endif
  }

  TH1F* scales[9];
  scales[0] = new TH1F("scales-ZTT", "", 9, 0, 9);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (ZTT->Integral()/unscaled[0]-1.)      : 0.);
  scales[1] = new TH1F("scales-ZEE"  , "", 9, 0, 9);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (ZEE->Integral()/unscaled[1]-1.)      : 0.);
  scales[2] = new TH1F("scales-TTJ", "", 9, 0, 9);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (TTJ->Integral()/unscaled[2]-1.)      : 0.);
  scales[3] = new TH1F("scales-QCD"  , "", 9, 0, 9);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (QCD->Integral()/unscaled[3]-1.)      : 0.);
  scales[4] = new TH1F("scales-Dibosons", "", 9, 0, 9);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (Dibosons->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-WJets"  , "", 9, 0, 9);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (WJets->Integral()/unscaled[5]-1.)    : 0.);
#ifdef MSSM
  scales[6] = new TH1F("scales-ggH"  , "", 9, 0, 9);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggH->Integral()/unscaled[6]-1.)      : 0.);
  scales[7] = new TH1F("scales-bbH"  , "", 9, 0, 9);
  scales[7]->SetBinContent(8, unscaled[7]>0 ? (bbH->Integral()/unscaled[7]-1.)      : 0.);
  scales[8] = new TH1F("scales-NONE" , "", 9, 0, 9);
  scales[8]->SetBinContent(9, 0.);
#else
#ifndef DROP_SIGNAL
  scales[6] = new TH1F("scales-ggH"  , "", 9, 0, 9);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggH->Integral()/unscaled[4]-1.)      : 0.);
  scales[7] = new TH1F("scales-qqH"  , "", 9, 0, 9);
  scales[7]->SetBinContent(8, unscaled[7]>0 ? (qqH->Integral()/unscaled[5]-1.)      : 0.);
  scales[8] = new TH1F("scales-VH"   , "", 9, 0, 9);
  scales[8]->SetBinContent(9, unscaled[8]>0 ? (VH ->Integral()/unscaled[6]-1.)      : 0.);
#endif
#endif

  WJets->Add(Dibosons);
  QCD->Add(WJets);
  TTJ->Add(QCD);
  ZTT->Add(TTJ);
  ZEE->Add(ZTT);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM
    bbH  ->Add(WJets);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    VH   ->Add(WJets);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }


  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(345));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
#ifndef DROP_SIGNAL
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(ZTT, log)), maximum(ggH, log)));
#else
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(ZTT, log)));
#endif
  data->Draw("e");

  TH1F* errorBand = (TH1F*)ZEE ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    ZEE->Draw("histsame");
    ZTT->Draw("histsame");
    TTJ->Draw("histsame");
    QCD->Draw("histsame");
    WJets->Draw("histsame");
    //Dibosons->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH->Draw("histsame");
#endif

  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
    ZEE->Draw("histsame");
    ZTT->Draw("histsame");
    TTJ->Draw("histsame");
    QCD->Draw("histsame");
    WJets->Draw("histsame");
    //Dibosons->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{e}#tau_{e}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.20, (category_extra2 && category_extra2[0]=='\0') ? 0.65+0.061 : 0.65+0.061, 0.32, 0.75+0.161, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
  chan->AddText(category_extra2);
  chan->Draw();

/*  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();
*/
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.55, 0.50+0.061, 0.95, 0.50+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m^{h}_{max} (m_{A}=$MA GeV, tan#beta=$TANB)");
  massA->Draw();
#endif

#ifdef MSSM  
  TLegend* leg = new TLegend(0.55, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.50, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + H(125)"           , "LP");
#else
  leg->AddEntry(data , "observed"                    , "LP");
#endif
  leg->AddEntry(ZEE  , "Z#rightarrowee"              , "F" );
  leg->AddEntry(ZTT  , "Z#rightarrow#tau#tau"        , "F" );
  leg->AddEntry(TTJ  , "t#bar{t}"                    , "F" );
  leg->AddEntry(QCD  , "QCD"                         , "F" );
  leg->AddEntry(WJets, "electroweak"                 , "F" );
  //leg->AddEntry(Dibosons  , "Dibosons"             , "F" );
  $ERROR_LEGEND
  leg->Draw();

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* model = (TH1F*)ZEE ->Clone("model");
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, ZEE->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/ZEE->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, ZEE->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/ZEE->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, ZEE->GetBinContent(ibin+1)>0 ? ZEE ->GetBinError  (ibin+1)/ZEE->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
#ifdef MSSM
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}"); 
#else
  rat1->GetXaxis()->SetTitle("#bf{D}");
#endif
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
  TH1F* rat2 = (TH1F*) ZEE->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? ZEE->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? ZEE->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(0, rat2->FindBin(345)); } else{ rat2->GetXaxis()->SetRange(0, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+ 3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
#if defined MSSM
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}"); 
#else
  rat2->GetXaxis()->SetTitle("#bf{D}");
#endif
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kOrange  -  4, 1001);
  InitHist  (scales[1], "", "", kAzure   +  2, 1001);
  InitHist  (scales[2], "", "", kBlue    -  8, 1001);
  InitHist  (scales[3], "", "", kMagenta - 10, 1001);
  InitHist  (scales[4], "", "", kGreen   -  4, 1001);
  InitHist  (scales[5], "", "", kRed     +  2, 1001);  
#ifndef DROP_SIGNAL
  InitSignal(scales[6]);
  InitSignal(scales[7]);
  InitSignal(scales[8]);
#endif
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{ZTT}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{ZEE}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{TTJ}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{QCD}"  );
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{Dibosons}");
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{WJets}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(8, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(9, "#bf{NONE}" );
#else
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(8, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(9, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
  scales[4]->Draw("same");
  scales[5]->Draw("same");
#ifndef DROP_SIGNAL
  scales[6]->Draw("same");
  scales[7]->Draw("same");
  scales[8]->Draw("same");
#endif
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
 bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd();
  data ->Write("data_obs");
  ZTT->Write("Ztt"  );
  ZEE->Write("Zee"  );
  TTJ->Write("ttbar");
  QCD->Write("Fakes");
  Dibosons->Write("Dibosons");
  WJets->Write("EWK");
#ifdef MSSM
  ggH  ->Write("ggH");
  bbH  ->Write("bbH");
#else
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH");
  qqH  ->Write("qqH");
  VH   ->Write("VH" );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}
void 
postfit_use(const char* inputfile, const char* analysis = "SM", const char* dataset = "2011+2012", const char* extra="", const char* extra2="", float min=0.1, float max=-1., bool log=true)
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  // switch for MSSM/SM
  bool MSSM = std::string(analysis) == std::string("MSSM");
  // determine label
  if (std::string(dataset) == std::string("2011"     )){ dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV"; }
  if (std::string(dataset) == std::string("2012"     )){ dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 19.8 fb^{-1} at 8 TeV"; }
  if (std::string(dataset) == std::string("2011+2012")){ dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV, 19.8 fb^{-1} at 8 TeV"; }
  // determine category tag
  const char* category_extra = "";
  if(std::string(extra2) == std::string("0jet_low"  )){ category_extra = "0 jet, low p_{T}";  }
  if(std::string(extra2) == std::string("0jet_high" )){ category_extra = "0 jet, high p_{T}"; }
  if(std::string(extra2) == std::string("0jet"      )){ category_extra = "0 jet";             }
  if(std::string(extra2) == std::string("1jet_low"  )){ category_extra = "1 jet, low p_{T}";  }
  if(std::string(extra2) == std::string("1jet_high" )){ category_extra = "1 jet, high p_{T}"; }
  if(std::string(extra2) == std::string("1jet"      )){ category_extra = "1 jet";             }
  if(std::string(extra2) == std::string("vbf"       )){ category_extra = "2 jet (VBF)";       }
  if(std::string(extra2) == std::string("nobtag"    )){ category_extra = "No B-Tag";          }
  if(std::string(extra2) == std::string("btag"      )){ category_extra = "B-Tag";             }

  TFile* input = new TFile(inputfile);
  TH1F* Fakes  = refill((TH1F*)input->Get("Fakes"   ), "Fakes/QCD"); 
  TH1F* EWK    = refill((TH1F*)input->Get("EWK"     ), "EWK"      ); 
  TH1F* ttbar  = refill((TH1F*)input->Get("ttbar"   ), "ttbar"    ); 
  TH1F* Ztt    = refill((TH1F*)input->Get("Ztt"     ), "Ztt"      ); 
  TH1F* Zmm    = refill((TH1F*)input->Get("Zmm"     ), "Zmm"      ); 
  TH1F* Zee    = refill((TH1F*)input->Get("Zee"     ), "Zee"      ); 
  TH1F* ggH    = refill((TH1F*)input->Get("ggH"     ), "ggH"      ); 
  TH1F* data   = (TH1F*)input->Get("data_obs"); 
  // determine channel for etau Z->ee (EWK) will be shown separated from the rest (EWK1)
  TH1F* EWK1   = 0;
  if(std::string(extra) == std::string("e#tau_{h}")){
    EWK1 = refill((TH1F*)input->Get("EWK1"),  "EWK1");
  }
  TH1F* ggH_hww = 0;
  if(std::string(extra) == std::string("e#mu") and HWWBG){
    ggH_hww= refill((TH1F*)input->Get("ggH_hww" ), "ggH_hww"  ); 
  }
  TH1F* errorBand = (TH1F*)input->Get("errorBand");

  /* 
    mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);
  if(log) canv->SetLogy(1);
  // reduce the axis range if necessary for linea plots and SM
  if(MSSM && !log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
  if(!MSSM){ data->GetXaxis()->SetRange(0, data->FindBin(345)); }
  data->SetNdivisions(505);
  data->SetMinimum(min);
  if(std::string(extra) == std::string("#mu#mu")){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Zmm, log)));
    data->Draw("e");
    if(log){
      Zmm  ->Draw("same");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      Fakes->Draw("same");
      EWK  ->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
  }
  else if(std::string(extra) == std::string("ee")){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Zee, log)));
    data->Draw("e");
    if(log){
      Zee  ->Draw("same");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      Fakes->Draw("same");
      EWK  ->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
  }
  else if(std::string(extra) == std::string("e#tau_{h}")){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
    data->Draw("e");
    if(log){
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      EWK1 ->Draw("same");
      Fakes->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
    else{
      if(ggH) ggH  ->Draw("histsame");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      EWK1 ->Draw("same");
      Fakes->Draw("same");
    } 
  }
  else if(std::string(extra) == std::string("e#mu") && HWWBG){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(ggH_hww, log)));
    data->Draw("e");
    if(log){
      ggH_hww -> Draw("same");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      Fakes->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
    else{
      if(ggH) ggH  ->Draw("histsame");
      ggH_hww -> Draw("same");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      Fakes->Draw("same");
    } 
  }
  else{
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
    data->Draw("e");
    if(log){
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      Fakes->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
    else{
      if(ggH) ggH  ->Draw("histsame");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      Fakes->Draw("same");
    } 
  }
  if(errorBand){
    errorBand->Draw("e2same");
  }
  data->Draw("esame");
  canv->RedrawAxis();




  //CMSPrelim(dataset, extra, 0.17, 0.835);
  CMSPrelim(dataset, "", 0.18, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(extra);
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

  if(MSSM){
    float lower_bound = EWK1 ? 0.45 : 0.50;
    TPaveText* massA      = new TPaveText(0.55, lower_bound+0.061, 0.95, lower_bound+0.161, "NDC");
    massA->SetBorderSize(   0 );
    massA->SetFillStyle(    0 );
    massA->SetTextAlign(   12 );
    massA->SetTextSize ( 0.03 );
    massA->SetTextColor(    1 );
    massA->SetTextFont (   62 );
    massA->AddText("m^{h}_{max} (m_{A}=$MA GeV, tan#beta=$TANB)");
    massA->Draw();
  }    
  float lower_bound = EWK1 ? 0.60 : 0.65;
  TLegend* leg = new TLegend(MSSM ? 0.55 : 0.50, lower_bound, 0.93, 0.90);
  SetLegendStyle(leg);
  if(MSSM){
    leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau", "L" );
  }
  else{
    if(ggH){
      if(SIGNAL_SCALE!=1){
	leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
      }
      else{
	leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
      }
    }
  }
  leg->AddEntry(data , "observed"                       , "LP");
  
  if(std::string(extra) == std::string("#mu#mu")){
    leg->AddEntry(Zmm  , "Z#rightarrow#mu#mu"    , "F" );
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
  }
  else if(std::string(extra) == std::string("ee")){
    leg->AddEntry(Zee  , "Z#rightarrowee"        , "F" );
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
  }
  else if(std::string(extra) == std::string("e#tau_{h}")){
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(EWK  , "Z#rightarrow ee"              , "F" );
    leg->AddEntry(EWK1 , "electroweak"                  , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
  }
  else if(std::string(extra) == std::string("e#mu") && HWWBG){
    leg->AddEntry(ggH_hww  , "H(125 GeV)#rightarrowWW" , "F" );
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
  }
  else{
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
  }
  if(errorBand){
    leg->AddEntry(errorBand, "bkg. uncertainty" , "F" );
  }
  leg->Draw();

  /*
    prepare output
  */
  std::string newName = std::string(inputfile).substr(0, std::string(inputfile).find(".root"));
  canv->Print(TString::Format("%s.png", newName.c_str())); 
  canv->Print(TString::Format("%s.pdf", newName.c_str())); 
  canv->Print(TString::Format("%s.eps", newName.c_str())); 

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd(); 
  TH1F* model;
  if(CONSERVATIVE_CHI2){
    if(std::string(extra) == std::string("#mu#mu")){
      model = (TH1F*)Zmm ->Clone("model");
    }
    else if(std::string(extra) == std::string("ee")){
      model = (TH1F*)Zee ->Clone("model");
    }
    else if(std::string(extra) == std::string("e#mu") && HWWBG){
      model = (TH1F*)ggH_hww ->Clone("model");
    }
    else{  
      model = (TH1F*)Ztt ->Clone("model");
    }
  }
  else{
    model = (TH1F*)errorBand->Clone("model");
  }
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONSERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)Ztt->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, errorBand->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/errorBand->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, errorBand->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/errorBand->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, errorBand->GetBinContent(ibin+1)>0 ? errorBand ->GetBinError  (ibin+1)/errorBand->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
    zero->SetBinContent(ibin+1, 0.);
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  if((std::string(extra) == std::string("#mu#mu") || std::string(extra) == std::string("ee")) && !MSSM){
    rat1->GetXaxis()->SetTitle("#bf{D}");
  }
  else{
    rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  }
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f,  P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    prepare output
  */
  newName = std::string(inputfile).substr(0, std::string(inputfile).find(".root")) + "_datamc";
  canv0->Print(TString::Format("%s.png", newName.c_str())); 
  canv0->Print(TString::Format("%s.pdf", newName.c_str())); 
  canv0->Print(TString::Format("%s.eps", newName.c_str())); 
}
void 
//HTT_ET_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="eleTau_$CATEGORY")
HTT_ET_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., TString datacard="htt_et_1_7TeV", string inputfile="root/$HISTFILE", const char* directory="eleTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("eleTau_0jet_low"             )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_low"             )){ category_extra = "0-jet low p_{T}^{#tau_{h}}";          }
  if(std::string(directory) == std::string("eleTau_0jet_medium"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_medium"          )){ category_extra = "0-jet low p_{T}^{#tau_{h}}";       }
  if(std::string(directory) == std::string("eleTau_0jet_high"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_high"            )){ category_extra = "0-jet high p_{T}^{#tau_{h}}";         }
  if(std::string(directory) == std::string("eleTau_1jet_medium"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_1jet_medium"          )){ category_extra = "1-jet low p_{T}^{#tau_{h}}";       }
  if(std::string(directory) == std::string("eleTau_1jet_high_lowhiggs"   )){ category = "e#tau_{h}";                          }
  if(std::string(directory) == std::string("eleTau_1jet_high_lowhiggs"   )){ category_extra= "1-jet high p_{T}^{#tau_{h}}";  }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category = "e#tau_{h}";                          }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category_extra= "1-jet high p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category_extra2= "boosted"; }
  if(std::string(directory) == std::string("eleTau_vbf"                  )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf"                  )){ category_extra = "VBF tag";              }
  if(std::string(directory) == std::string("eleTau_vbf_loose"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf_loose"            )){ category_extra = "Loose VBF tag";              }
  if(std::string(directory) == std::string("eleTau_vbf_tight"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf_tight"            )){ category_extra = "Tight VBF tag";              }
  if(std::string(directory) == std::string("eleTau_nobtag"               )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag"               )){ category_extra = "no b-tag";     }
  if(std::string(directory) == std::string("eleTau_btag"                 )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag"                 )){ category_extra = "b-tag";  }        
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category_extra2 = "low p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category_extra2 = "medium p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category_extra2 = "high p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category_extra = "b-tag"; }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category_extra2 = "low p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category_extra = "b-tag"; }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category_extra2 = "high p_{T}^{#tau_{h}}"; }

  const char* dataset;
#ifdef MSSM
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                 4.9 fb^{-1} (7 TeV)";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                19.7 fb^{-1} (8 TeV)";}
#else
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS, 19.7 fb^{-1} at 8 TeV";}
#endif
  
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/QCD"     , directory)), "QCD"); InitHist(Fakes, "", "", TColor::GetColor(250,202,255), 1001); 
  TH1F* EWK0   = refill((TH1F*)input->Get(TString::Format("%s/VV"      , directory)), "VV" ); InitHist(EWK0 , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* EWK1   = refill((TH1F*)input->Get(TString::Format("%s/W"       , directory)), "W"  ); InitHist(EWK1 , "", "", TColor::GetColor(222,90,106), 1001);
#ifdef EXTRA_SAMPLES
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZJ"      , directory)), "ZJ" ); InitHist(EWK2 , "", "", TColor::GetColor(100,182,232), 1001);
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/ZL"      , directory)), "ZL" ); InitHist(EWK  , "", "", TColor::GetColor(100,182,232), 1001);
#else
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/ZLL"     , directory)), "ZLL"); InitHist(EWK  , "", "", TColor::GetColor(100,182,232), 1001);
#endif
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/TT"      , directory)), "TT" ); InitHist(ttbar, "", "", TColor::GetColor(155,152,204), 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"); InitHist(Ztt  , "", "", TColor::GetColor(248,206,104), 1001);
#ifdef MSSM
  TH1F* ggH    = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA" , directory)), "ggH"); InitSignal(ggH); ggH->Scale($TANB);
  TH1F* bbH    = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA" , directory)), "bbH"); InitSignal(bbH); bbH->Scale($TANB);
#else
#ifndef DROP_SIGNAL
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH125"  , directory)), "ggH"); InitSignal(ggH); ggH->Scale(SIGNAL_SCALE);
  TH1F* qqH    = refill((TH1F*)input->Get(TString::Format("%s/qqH125"  , directory)), "qqH"); InitSignal(qqH); qqH->Scale(SIGNAL_SCALE);
  TH1F* VH     = refill((TH1F*)input->Get(TString::Format("%s/VH125"   , directory)), "VH" ); InitSignal(VH ); VH ->Scale(SIGNAL_SCALE);
#endif
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK0 );
  ref->Add(EWK1 );
#ifdef EXTRA_SAMPLES
  ref->Add(EWK2 );
#endif
  ref->Add(EWK  );
  ref->Add(ttbar);
  ref->Add(Ztt  );

  double unscaled[7];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[1]+= EWK0 ->Integral();
  unscaled[1]+= EWK1 ->Integral();
#ifdef EXTRA_SAMPLES
  unscaled[1]+= EWK2 ->Integral();
#endif
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = bbH  ->Integral();
  unscaled[6] = 0;
#else
#ifndef DROP_SIGNAL
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = qqH  ->Integral();
  unscaled[6] = VH   ->Integral();
#endif
#endif

  if(scaled){

/*    Fakes = refill(shape_histos(Fakes, datacard, "QCD"), "QCD");
    EWK0 = refill(shape_histos(EWK0, datacard, "VV"), "VV"); 
    EWK1 = refill(shape_histos(EWK1, datacard, "W"), "W"); 
#ifdef EXTRA_SAMPLES
    EWK2 = refill(shape_histos(EWK2, datacard, "ZJ"), "ZJ");
    EWK = refill(shape_histos(EWK, datacard, "ZL"), "ZL");
#else
    //    EWK = refill(shape_histos(EWK, datacard, "ZLL"), "ZLL");
#endif
    ttbar = refill(shape_histos(ttbar, datacard, "TT"), "TT");
    Ztt = refill(shape_histos(Ztt, datacard, "ZTT"), "ZTT");
#ifdef MSSM
    ggH = refill(shape_histos(ggH, datacard, "ggH$MA"), "ggH$MA"); 
    bbH = refill(shape_histos(bbH, datacard, "bbH$MA"), "bbH$MA"); 
#else
#ifndef DROP_SIGNAL
    ggH = refill(shape_histos(ggH, datacard, "ggH"), "ggH"); 
    qqH = refill(shape_histos(qqH, datacard, "qqH"), "qqH"); 
    VH = refill(shape_histos(VH, datacard, "VH"), "VH"); 
#endif  
#endif
*/

    rescale(Fakes, 7); 
    rescale(EWK0 , 6); 
    rescale(EWK1 , 3); 
#ifdef EXTRA_SAMPLES
    rescale(EWK2 , 4); 
    rescale(EWK  , 5);
#else
    rescale(EWK  , 4);
#endif 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggH  , 8); 
    rescale(bbH  , 9);  
#else
#ifndef DROP_SIGNAL
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
    rescale(VH   ,10);
#endif  
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-Fakes", "", 7, 0, 7);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", 7, 0, 7);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? ((EWK  ->Integral()
					       +EWK0 ->Integral()
					       +EWK1 ->Integral()
#ifdef EXTRA_SAMPLES
					       +EWK2 ->Integral()
#endif
						)/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", 7, 0, 7);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", 7, 0, 7);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-bbH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", 7, 0, 7);
  scales[6]->SetBinContent(7, 0.);
#else
#ifndef DROP_SIGNAL
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (qqH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-VH"   , "", 7, 0, 7);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (VH   ->Integral()/unscaled[6]-1.) : 0.);
#endif
#endif

  EWK0 ->Add(Fakes);
  EWK1 ->Add(EWK0 );
#ifdef EXTRA_SAMPLES
  EWK2 ->Add(EWK1 );
  EWK  ->Add(EWK2 );
#else
  EWK  ->Add(EWK1 );
#endif
  ttbar->Add(EWK  );
  Ztt  ->Add(ttbar);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM
    bbH  ->Add(Ztt);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    VH   ->Add(Ztt);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }

  /*
    Mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(345));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
#ifndef DROP_SIGNAL
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(Ztt, log)), maximum(ggH, log)));
#else
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
#endif
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Ztt ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    EWK1 ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    EWK1 ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{e}#tau_{h}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);
#if defined MSSM
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "tlbrNDC");
  if (category_extra2!="") chan     = new TPaveText(0.20, 0.69+0.061, 0.32, 0.74+0.161, "tlbrNDC");
#else
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
#endif
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
#if defined MSSM
  if (category_extra2!="") chan->AddText(category_extra2);
#else
  chan->AddText(category_extra2);
#endif
  chan->Draw();

/*  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

  TPaveText* cat2      = new TPaveText(0.20, 0.66+0.061, 0.32, 0.66+0.161, "NDC");
  cat2->SetBorderSize(   0 );
  cat2->SetFillStyle(    0 );
  cat2->SetTextAlign(   12 );
  cat2->SetTextSize ( 0.05 );
  cat2->SetTextColor(    1 );
  cat2->SetTextFont (   62 );
  cat2->AddText(category_extra2);
  cat2->Draw();
*/  
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.53, 0.44+0.061, 0.95, 0.44+0.151, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("MSSM m^{h}_{max} scenario");
  massA->AddText("m_{A}=$MA GeV, tan#beta=$TANB");
  massA->Draw();
#endif

#ifdef MSSM
  TLegend* leg = new TLegend(0.53, 0.60, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "h,A,H#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.52, 0.58, 0.92, 0.89);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "SM H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + H(125)"              , "LP");
#else
  leg->AddEntry(data , "Observed"                       , "LP");
#endif
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(EWK  , "Z#rightarrow ee"                , "F" );
  leg->AddEntry(EWK1 , "W+jets"                         , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  leg->AddEntry(Fakes, "QCD"                            , "F" );
  $ERROR_LEGEND
  leg->Draw();

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* model = (TH1F*)Ztt ->Clone("model");
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ref->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(0, rat2->FindBin(345)); } else{ rat2->GetXaxis()->SetRange(0, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+ 3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", TColor::GetColor(250,202,255), 1001);
  InitHist  (scales[1], "", "", TColor::GetColor(222,90,106), 1001);
  InitHist  (scales[2], "", "", TColor::GetColor(155,152,204), 1001);
  InitHist  (scales[3], "", "", TColor::GetColor(248,206,104), 1001);
#ifndef DROP_SIGNAL
  InitSignal(scales[4]);
  InitSignal(scales[5]);
  InitSignal(scales[6]);
#endif
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "NONE"      );
#else
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
#ifndef DROP_SIGNAL
  scales[4]->Draw("same");
  scales[5]->Draw("same");
  scales[6]->Draw("same");
#endif
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same"); 
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd();
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
    EWK  ->Write("Zee"     );
    EWK1 ->Write("EWK"    );
  //EWK  ->Write("EWK"     );
  EWK1 ->Write("EWK1"    );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggH  ->Write("ggH"     );
  bbH  ->Write("bbH"     );
#else
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH"     );
  qqH  ->Write("qqH"     );
  VH   ->Write("VH"      );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}
示例#27
0
void PlotRakeBunch( const TString &sim, Int_t time, Int_t index = 0, const TString &options="") {
  
#ifdef __CINT__  
  gSystem->Load("libplasma.so");
#endif

  PlasmaGlob::Initialize();

  TString opt = options;
 
  // Palettes!
  gROOT->Macro("PlasmaPalettes.C");

  if(opt.Contains("grid")) {
    gStyle->SetPadGridX(1);
    gStyle->SetPadGridY(1);
  }
  gStyle->SetLabelFont(42,"xyz");
  gStyle->SetTextFont(62);
 

  // Load PData
  PData *pData = PData::Get(sim.Data());
  pData->LoadFileNames(time);
  if(!pData->IsInit()) return;

  Bool_t CYL = kFALSE;
  if(sim.Contains("cyl")) CYL = kTRUE; 
    
  Bool_t ThreeD = kFALSE;
  if(sim.Contains("3D")) ThreeD = kTRUE; 

  // Some plasma constants
  Double_t n0 = pData->GetPlasmaDensity();
  Double_t kp = pData->GetPlasmaK();
  Double_t skindepth = 1.;
  if(kp!=0.0) skindepth = 1/kp;
  Double_t E0 = pData->GetPlasmaE0();

  // Time in OU
  Float_t Time = pData->GetRealTime();
  // z start of the plasma in normalized units.
  Float_t zStartPlasma = pData->GetPlasmaStart()*kp;
  // z start of the beam in normalized units.
  Float_t zStartBeam = pData->GetBeamStart()*kp;
  
  opt += "comovcenter";

  // Centering time and z position:
  Double_t shiftz = pData->Shift(opt);
  TString sshiftz = Form("(x1-%f)",shiftz);

  if(opt.Contains("center")) {
    Time -= zStartPlasma;
    if(opt.Contains("comov"))      // Centers on the head of the beam.
      Time += zStartBeam;
  } 
  
  // Spatial coordinates intervals:
  Float_t x1Min = -4.3;
  Float_t x1Max = -3.9;
  Float_t x2Min = -0.5;
  Float_t x2Max =  0.5;
  Float_t x3Min = -0.5;
  Float_t x3Max =  0.5;

  // Momentum coordinates intervals:
  Float_t p1Min =  6500.01;
  Float_t p1Max =  10099.99;
  Float_t p2Min = -20.0;
  Float_t p2Max =  20.0;
  Float_t p3Min = -20.0;
  Float_t p3Max =  20.0;

  // Bining, intervals, labels, etc.
  Int_t xNbin = 200;
  Int_t yNbin = 200;

  if(sim.Contains("DR")) {
    xNbin = 200;
    yNbin = 200;
   
    // p1Min =  2200.01;
    // p1Max =  3399.99;
    // p1Min =  3500.01;
    // p1Max =  4999.99;
    p1Min =  1800.01;
    p1Max =  3999.99;

    // x1Min = -4.0;
    // x1Max = -3.2;
    x1Min = 8637.0;
    x1Max = 8639.0;
    x2Min = -0.5;
    x2Max =  0.5;
    x3Min = -0.5;
    x3Max =  0.5;
  } else if(sim.Contains("flash") && sim.Contains(".G.") ) {
    
    x1Min = -6.3;
    x1Max = -5.0;

    //p1Min =  0.001;
    p1Min =  650.001;
    p1Max =  1499.99;
    
  } else if(sim.Contains("facet_v23kA.G.A")) {
    x1Min = -7.8;
    x1Max = -7.1;

    x2Min = -1.0;
    x2Max =  1.0;
    x3Min = -1.0;
    x3Max =  1.0;
    // t=150
    p1Min =  1100.001;
    p1Max =  1999.99;
  } else if(sim.Contains("facet_v23kA.G")) {
    x1Min = -7.8;
    x1Max = -7.0;

    x2Min = -1.0;
    x2Max =  1.0;
    x3Min = -1.0;
    x3Max =  1.0;
    // t=60
     p1Min =  350.01;
     p1Max =  799.99;
    // t = 100
    // p1Min =  700.01;
    // p1Max =  1399.99;
    // t=105
    //p1Min =  800.001;
    //p1Max =  1399.99;
    // t=183
    // p1Min =  1500.001;
    // p1Max =  2499.99;
    // t=235
    // p1Min =  2000.01;
    // p1Max =  3499.99; 
    // t=310
    // p1Min =  2800.01;
    // p1Max =  4799.99; 
  }
  
  
  // Get phasespace histos
  Int_t Nspecies = pData->NSpecies();
  if(index>Nspecies-1) {
    return;
  }
  if(!pData->GetRawFileName(index)) {
    return;    
  }
  TH1F *hX1 = NULL;
  TH1F *hP1 = NULL;
  TH2F *hP1X1 = NULL;
  TH2F *hP2X2 = NULL;


  cout << Form("\n1. Getting data... ") << endl; 
  char cutString[512];
  sprintf(cutString,"TMath::Abs(q)*(%s > %.1f && %s < %.1f && x2 > %.1f && x2 < %.1f && x3 > %.1f && x3 < %.1f)",sshiftz.Data(),x1Min,sshiftz.Data(),x1Max,x2Min,x2Max,x3Min,x3Max); 
  TCut Cut = cutString;
  cout << Form("   (applied cut: \n %s)",cutString) << endl;
  TTree *tree = pData->GetTreeRaw(pData->GetRawFileName(index)->c_str(),opt);
  
  char hName[24];
  char dCommand[128];

  cout << Form("\n2. Dumping 1D histograms.. ") << endl;
  
  sprintf(hName,"hX1");
  hX1 = (TH1F*) gROOT->FindObject(hName);
  if(hX1) delete hX1;
  hX1 = new TH1F(hName,"",xNbin,x1Min,x1Max);
  sprintf(dCommand,"%s>>%s",sshiftz.Data(),hName);
  cout << Form("   - x1. ") << endl;    
  tree->Draw(dCommand,Cut,"goff");

  sprintf(hName,"hP1");
  hP1 = (TH1F*) gROOT->FindObject(hName);
  if(hP1) delete hP1;
  hP1 = new TH1F(hName,"",yNbin,p1Min,p1Max);
  sprintf(dCommand,"p1>>%s",hName);
  cout << Form("   - p1. ") << endl;    
  tree->Draw(dCommand,Cut,"goff");

  cout << Form("\n3. Dumping 2D histograms.. ") << endl;

  sprintf(hName,"hP1X1");
  hP1X1 = (TH2F*) gROOT->FindObject(hName);
  if(hP1X1) delete hP1X1;
  hP1X1 = new TH2F(hName,"",xNbin,x1Min,x1Max,yNbin,p1Min,p1Max);
  sprintf(dCommand,"p1:%s>>%s",sshiftz.Data(),hName);
  cout << Form("   - p1 vs. x1 ") << endl;    
  tree->Draw(dCommand,Cut,"goff");
  
  sprintf(hName,"hP2X2");
  hP2X2 = (TH2F*) gROOT->FindObject(hName);
  if(hP2X2) delete hP2X2;
  hP2X2 = new TH2F(hName,"",xNbin,x2Min,x2Max,yNbin,p2Min,p2Max);
  sprintf(dCommand,"p2:x2>>%s",hName);
  cout << Form("   - p2 vs. x2 ") << endl;    
  tree->Draw(dCommand,Cut,"goff");
  
  hX1->GetXaxis()->CenterTitle();
  hX1->GetYaxis()->CenterTitle();
  hX1->GetZaxis()->CenterTitle();
  hP1X1->GetXaxis()->CenterTitle();
  hP1X1->GetYaxis()->CenterTitle();
  hP1X1->GetZaxis()->CenterTitle();
  hP2X2->GetXaxis()->CenterTitle();
  hP2X2->GetYaxis()->CenterTitle();
  hP2X2->GetZaxis()->CenterTitle();
   
  // Integrated long. emittance:

  cout << Form("\n4. Calculating integrated quantities.. ") << endl;

  Double_t xmean = 0.0;
  Double_t ymean = 0.0;
  Double_t x2mean = 0.0;
  Double_t y2mean = 0.0;
  Double_t xymean = 0.0;
  Double_t Ntotal = 0.0;
  for(Int_t i=1;i<=xNbin;i++) {
    Double_t x = hP1X1->GetXaxis()->GetBinCenter(i);
    // if(x<xmin || x>xmax) continue;
    for(Int_t j=1;j<=yNbin;j++) {
      Double_t y = hP1X1->GetYaxis()->GetBinCenter(j);
      // if(y<ymin || y>ymax) continue;
      Double_t value = TMath::Abs(hP1X1->GetBinContent(i,j));
      xmean += x*value;
      ymean += y*value;
      x2mean += x*x*value;
      y2mean += y*y*value;
      xymean += x*y*value;

      Ntotal += value;
    }
  }
  
  xmean  /= Ntotal;
  ymean  /= Ntotal;
  x2mean /= Ntotal;
  y2mean /= Ntotal;
  xymean /= Ntotal;

  Double_t xrms2  = x2mean - xmean*xmean;
  Double_t yrms2  = y2mean - ymean*ymean;
  Double_t xrms   = TMath::Sqrt(xrms2);
  Double_t yrms   = TMath::Sqrt(yrms2);
  Double_t xyrms2 = xymean - xmean*ymean;

  Double_t emittance = TMath::Sqrt(xrms2*yrms2 - xyrms2*xyrms2);
  
  // cout << " xrms = " << xrms << endl;
  
  // Sliced emittance:
  // --------------------------------------------------------------------------

  cout << Form("\n5. Slicing ") << endl;


  // Bining for sliced quantities:
  // const Int_t SNbin = 7;
  // Float_t sBinLim[SNbin+1] = {-4.16,-4.14,-4.12,-4.10,-4.08,-4.06,-4.04,-4.02};
  // const Int_t SNbin = 7;
  // Float_t sBinLim[SNbin+1] = {-4.20,-4.17,-4.14,-4.12,-4.10,-4.08,-4.06,-4.00};
  // const Int_t SNbin = 8;
  // Float_t sBinLim[SNbin+1] = {-3.93,-3.87,-3.81,-3.75,-3.69,-3.63,-3.57,-3.51,-3.45};
  
  Int_t SNbin = 7;
  Float_t nsigma = 2;
  Float_t x1BinMin = -4.16;
  Float_t x1BinMax = -4.02;
  if(sim.Contains("DR")) {
    SNbin = 150; 
    nsigma = 1.4;
  } else if(sim.Contains("facet_v23kA.G.A")) {
    SNbin = 46;
    nsigma = 1;
    x1BinMin = -7.55;
    x1BinMax = -7.25;
  } else if(sim.Contains("facet_v23kA.G")) {
    SNbin = 10;
    nsigma = 1;
    x1BinMin = -7.55;
    x1BinMax = -7.15;
  }
  
  Float_t *sBinLim = new Float_t[SNbin+1];

  if(opt.Contains("rms")) {
    sBinLim[0] = xmean - nsigma*xrms;
    sBinLim[SNbin] = xmean + nsigma*xrms;
  } else {
    sBinLim[0] = x1BinMin;
    sBinLim[SNbin] = x1BinMax;
  }

  Float_t slbinSize = (sBinLim[SNbin] - sBinLim[0])/SNbin;
  
  for(Int_t i=1;i<SNbin;i++) {
    sBinLim[i] = sBinLim[i-1] + slbinSize;
  }
  
  TH1F **hP1sl = new TH1F*[SNbin];
  TH2F **hP2X2sl = new TH2F*[SNbin];

  cout << Form("\n   - Dumping in %i bins ",SNbin) << endl;

  
  for(Int_t k=0;k<SNbin;k++) {

    cout<< Form("k = %i : (x1 > %f && x1 < %f)",k,sBinLim[k],sBinLim[k+1]) << endl; 

    sprintf(hName,"hP2X2sl_%2i",k);
    hP2X2sl[k] = (TH2F*) gROOT->FindObject(hName);
    if(hP2X2sl[k]) delete hP2X2sl[k];
    hP2X2sl[k] = new TH2F(hName,"",xNbin,x2Min,x2Max,yNbin,p2Min,p2Max);

    char zCutString[128];
    sprintf(zCutString,"(%s > %f && %s < %f)",sshiftz.Data(),sBinLim[k],sshiftz.Data(),sBinLim[k+1]); 
    TCut zCut = zCutString;
    tree->Project(hName,"p2:x2",Cut + zCut);

    sprintf(hName,"hP1sl_%2i",k);
    hP1sl[k] = (TH1F*) gROOT->FindObject(hName);
    if(hP1sl[k]) delete hP1sl[k];
    hP1sl[k] = new TH1F(hName,"",yNbin,p1Min,p1Max);
    tree->Project(hName,"p1",Cut + zCut);

  }
  

  cout << Form("\n6. Calculating sliced quantities.. ") << endl;

  TGraph *gemit = NULL;
  TGraph *gYrms = NULL;
  TGraph *gErms = NULL;
  TGraph *gErmsB = NULL;
 
  Double_t * sxmean = new Double_t[SNbin];
  Double_t * symean = new Double_t[SNbin];
  Double_t * sx2mean = new Double_t[SNbin];
  Double_t * sy2mean = new Double_t[SNbin];
  Double_t * sxymean = new Double_t[SNbin];
  Double_t * sNtotal = new Double_t[SNbin];
  Double_t * sxrms2 = new Double_t[SNbin];  
  Double_t * syrms2 = new Double_t[SNbin]; 
  Double_t * sxrms = new Double_t[SNbin];  
  Double_t * syrms = new Double_t[SNbin];  
  Double_t * sxyrms2 = new Double_t[SNbin];
 
  Double_t * xbin = new Double_t[SNbin];
  Double_t * semittance = new Double_t[SNbin];

  Double_t * sNEtotal = new Double_t[SNbin]; 
  Double_t * sEmean = new Double_t[SNbin];
  Double_t * sE2mean = new Double_t[SNbin];
  Double_t * sErms = new Double_t[SNbin];

  for(Int_t k=0;k<SNbin;k++) {
    sxmean[k] = symean[k] = sx2mean[k] = sy2mean[k] = sxymean[k] 
      = sNtotal[k] = sxrms2[k] = syrms2[k] = sxrms[k] = syrms[k]
      = sxyrms2[k] = xbin[k] = semittance[k] = 0.0;
    sNEtotal[k] = sEmean[k] = sE2mean[k] = sErms[k] = 0.0;
    
    xbin[k] = (sBinLim[k] + sBinLim[k+1])/2.;
    
    for(Int_t i=1;i<=xNbin;i++) {
      Double_t x = hP2X2sl[k]->GetXaxis()->GetBinCenter(i);
      // if(x<xmin || x>xmax) continue;
      for(Int_t j=1;j<=yNbin;j++) {
	Double_t y = hP2X2sl[k]->GetYaxis()->GetBinCenter(j);
	// if(y<ymin || y>ymax) continue;
	Double_t value = TMath::Abs(hP2X2sl[k]->GetBinContent(i,j));
	sxmean[k] += x*value;
	symean[k] += y*value;
	sx2mean[k] += x*x*value;
	sy2mean[k] += y*y*value;
	sxymean[k] += x*y*value;
	
	sNtotal[k] += value;
      }	
    }
    
    for(Int_t i=1;i<=yNbin;i++) {
      Double_t y = hP1sl[k]->GetXaxis()->GetBinCenter(i);
      Double_t value = TMath::Abs(hP1sl[k]->GetBinContent(i));
      sEmean[k] += y*value;
      sE2mean[k] += y*y*value;
      sNEtotal[k] += value;
    }
    
    sxmean[k]  /= sNtotal[k];
    symean[k]  /= sNtotal[k];
    sx2mean[k] /= sNtotal[k];
    sy2mean[k] /= sNtotal[k];
    sxymean[k] /= sNtotal[k];
      
    sxrms2[k]  = sx2mean[k] - sxmean[k]*sxmean[k];
    syrms2[k]  = sy2mean[k] - symean[k]*symean[k];
    sxrms[k]   = TMath::Sqrt(sxrms2[k]);
    syrms[k]   = TMath::Sqrt(syrms2[k]);
    sxyrms2[k] = sxymean[k] - sxmean[k]*symean[k];
      
    semittance[k] = TMath::Sqrt(sxrms2[k]*syrms2[k] - sxyrms2[k]*sxyrms2[k]);

    sEmean[k]  /= sNEtotal[k];
    sE2mean[k] /= sNEtotal[k];
    sErms[k]   =  TMath::Sqrt(sE2mean[k] - sEmean[k]*sEmean[k]);
    
    
    cout << " Bunch properties: " << endl;
    cout << Form("  xMean = %7.3f   yMean = %7.3f",sxmean[k],symean[k]) << endl;
    cout << Form("  xRms  = %7.3f   yRms  = %7.3f",sxrms[k],syrms[k]) << endl;
    cout << Form("  Emittance = %7.3f",semittance[k]) << endl;

    cout << Form("  Emean = %7.3f   Erms = %7.3f",sEmean[k],sErms[k]) << endl;
    

  }

  // Charge
  Double_t dx1 = pData->GetDX(0);
  Double_t dx2 = pData->GetDX(1);
  Double_t dx3 = pData->GetDX(2);
  
  hX1->Scale(dx1*dx2*dx3);
  Double_t Charge = hX1->Integral();
  
  // Charge *= dx1*dx2*dx3;
 
  if(opt.Contains("units")) {
    Double_t dV = skindepth * skindepth * skindepth;
    Charge *= n0 * dV * (PConst::ElectronCharge/PUnits::picocoulomb);
    cout << Form(" Integrated charge (RAW) of specie %3i = %8f pC",index,Charge) << endl;
  } else {
    cout << Form(" Integrated charge (RAW) of specie %3i = %8.4f n0 * kp^-3",index,Charge) << endl;
  }
  

  // Chaning to user units: 
  // --------------------------
  
  if(opt.Contains("units") && n0) {
    
    Int_t NbinsX = hP1X1->GetNbinsX();
    Double_t xMin = skindepth * hP1X1->GetXaxis()->GetXmin() / PUnits::um;
    Double_t xMax = skindepth * hP1X1->GetXaxis()->GetXmax() / PUnits::um;
    Int_t NbinsY = hP1X1->GetNbinsY();
    Double_t yMin = hP1X1->GetYaxis()->GetXmin() * pData->GetBeamMass() / PUnits::GeV;
    Double_t yMax = hP1X1->GetYaxis()->GetXmax() * pData->GetBeamMass() / PUnits::GeV;
    hP1X1->SetBins(NbinsX,xMin,xMax,NbinsY,yMin,yMax);
    // Converting electron density
    Double_t dVb = skindepth * skindepth * skindepth;
    Double_t dX = (xMax-xMin)/NbinsX; 
    Double_t dE = (yMax-yMin)/NbinsY; 
    for(Int_t j=0;j<hP1X1->GetNbinsX();j++) {
      for(Int_t k=0;k<hP1X1->GetNbinsY();k++) {
	Double_t binValue =  fabs(hP1X1->GetBinContent(j,k) * dx1 * dx2 * dx3 * dVb * n0 *
				  (PConst::ElectronCharge/PUnits::picocoulomb));
     	//cout << Form(" value = %f",binValue) << endl;
	hP1X1->SetBinContent(j,k,binValue);
	
      }
    }
    
    if(opt.Contains("comov"))
      hP1X1->GetXaxis()->SetTitle("#zeta [#mum]");
    else
      hP1X1->GetXaxis()->SetTitle("z [#mum]");
    
    hP1X1->GetYaxis()->SetTitle("p_{z} [GeV/c]");
    
    hP1X1->GetZaxis()->SetTitle("dQ/d#zetadp_{z} [pC]");

    hP1->SetBins(NbinsY,yMin,yMax);
    hP1->GetYaxis()->SetTitle("p_{z} [GeV/c]");

    hX1->SetBins(NbinsX,xMin,xMax);
    Double_t binSize = (xMax - xMin)/NbinsX;

    Double_t dV = skindepth * skindepth * skindepth;
    Double_t  lightspeed =  PConst::c_light / (PUnits::um/PUnits::femtosecond);
    cout << Form("Speed of light = %f",lightspeed) << endl;
    hX1->Scale(TMath::Abs(n0 * dV * (PConst::ElectronCharge/PUnits::picocoulomb) * (lightspeed/binSize)));
    
    // hX1->Scale(TMath::Abs((PUnits::um/skindepth)*(PConst::ElectronCharge/PUnits::picocoulomb)*PConst::c_light));
    
    // hX1->GetYaxis()->SetTitle("I[kA]");
    hX1->GetYaxis()->SetTitle("");
    if(opt.Contains("comov"))
      hX1->GetXaxis()->SetTitle("#zeta [#mum]");
    else
      hX1->GetXaxis()->SetTitle("z [#mum]");
    
    
    xmean *= skindepth / PUnits::um;
    xrms  *= skindepth / PUnits::um;
    ymean *= pData->GetBeamMass() / PUnits::GeV;
    yrms  *= pData->GetBeamMass() / PUnits::GeV;
    
    emittance *= (skindepth / PUnits::um);
    
    for(Int_t k=0;k<SNbin;k++) {
      xbin[k] *= skindepth / PUnits::um;

      sxmean[k] *= skindepth / PUnits::um;
      sxrms[k]  *= skindepth / PUnits::um;
      symean[k] *= pData->GetBeamMass() / PUnits::MeV;
      syrms[k] *= pData->GetBeamMass() / PUnits::MeV;
      
      semittance[k] *= (skindepth / PUnits::um);

      sEmean[k] *= pData->GetBeamMass() / PUnits::GeV;
      sErms[k]  *= 100 * pData->GetBeamMass() / PUnits::GeV / ymean; //sEmean[k];
      // sErms[k]  *= pData->GetBeamMass() / PUnits::GeV;

    }

  }


  // Create the graph with the emittances:
  gemit = new TGraph(SNbin,xbin,semittance);
  gYrms = new TGraph(SNbin,xbin,sxrms);
  gErms = new TGraph(SNbin,xbin,sErms);
  
  
  // Profile energy for p1 vs x1:
  TString pname = hP1X1->GetName();
  pname += "_pfx";
  TProfile *hP1X1prof = (TProfile*) gROOT->FindObject(pname.Data());
  if(hP1X1prof) { delete hP1X1prof; hP1X1prof = NULL; }
  hP1X1prof = hP1X1->ProfileX("_pfx",1,-1,"s");

  // get the errors from the profile:
  Int_t NP1X1Bins = hP1X1prof->GetNbinsX();
  Double_t *x1bins = new Double_t[NP1X1Bins];
  Double_t *eRms   = new Double_t[NP1X1Bins];
  for(Int_t i=1;i<=hP1X1prof->GetNbinsX();i++) {
    x1bins[i] = hP1X1prof->GetBinCenter(i);
    eRms[i] = 100 * hP1X1prof->GetBinError(i) / hP1X1prof->GetBinContent(i);
  }
  gErmsB = new TGraph(NP1X1Bins,x1bins,eRms);
  
  // Vertical Energy histogram:
  // --------------------------------------------------------------------------------   
  TGraph *gP1left = NULL;
  if(hP1) {
    Double_t *yarray   = new Double_t[yNbin];
    Double_t *xarray   = new Double_t[yNbin];
    
    // This is for the right side:
    // Double_t xMax = x1Min + (x1Max-x1Min) * 0.9;
    // Double_t xMin = x1Max;
    // And this for left:
    Double_t xMin = hX1->GetXaxis()->GetXmin();
    Double_t xMax = hX1->GetXaxis()->GetXmin() + (hX1->GetXaxis()->GetXmax()
						  -hX1->GetXaxis()->GetXmin()) * 0.2;
    Double_t EneMax = hP1->GetMaximum();
    // cout << Form("  EneMax = %f ", EneMax) << endl;
 
    for(Int_t j=0; j<yNbin; j++) {
      yarray[j] = hP1->GetBinCenter(j+1);
      xarray[j] = ((xMax-xMin)/EneMax)*hP1->GetBinContent(j+1) + xMin;

      // cout << Form("  x = %f  y = %f ", xarray[j],yarray[j]) << endl;
    }

    gP1left = new TGraph(yNbin,xarray,yarray);
    gP1left->SetLineColor(PlasmaGlob::elecLine);
    gP1left->SetLineWidth(2);
    gP1left->SetFillStyle(1001);
    gP1left->SetFillColor(PlasmaGlob::elecFill);
       
  }

  

  // Plotting
  // -----------------------------------------------
    
  // Canvas setup
  // Create the canvas and the pads before the Frame loop
  // Resolution:
  Int_t sizex = 800;
  Int_t sizey = 600;
  if(opt.Contains("hres")) {
    Int_t sizex = 1600;
    Int_t sizey = 1200;    
  }
  
  TCanvas *C = new TCanvas("C1","Evolution of Injection",sizex,sizey);
  C->cd();

  // Set palette:
  PPalette * pPalette = (PPalette*) gROOT->FindObject("electron");
  pPalette->cd();

  // Float_t Max  = hP1X1->GetMaximum();
  // Float_t Min  = hP1X1->GetMinimum();
  
  // hP1X1->GetZaxis()->SetRangeUser(Min,Max); 


  // Text objects
  TPaveText *textTime = new TPaveText(0.55,0.8,0.82,0.9,"NDC");
  PlasmaGlob::SetPaveTextStyle(textTime,32); 
  textTime->SetTextColor(kGray+2);
  char ctext[128];
  if(opt.Contains("units") && pData->GetPlasmaDensity()) 
    sprintf(ctext,"z = %5.1f mm", Time * skindepth / PUnits::mm);
  else
    sprintf(ctext,"t = %5.1f #omega_{p}^{-1}",Time);
  textTime->AddText(ctext);
 
  TPaveText *textDen = new TPaveText(0.15,0.85,0.48,0.9,"NDC");
  PlasmaGlob::SetPaveTextStyle(textDen,12); 
  textDen->SetTextColor(kOrange+10);
  if(opt.Contains("units") && pData->GetPlasmaDensity())
    sprintf(ctext,"n_{0} = %5.2f x 10^{17} / cc", n0 / (1e17/PUnits::cm3));
  else if(pData->GetBeamDensity() && pData->GetPlasmaDensity())
    sprintf(ctext,"n_{b}/n_{0} = %5.2f", pData->GetBeamDensity()/n0);
  textDen->AddText(ctext);

  TPaveText *textWav = new TPaveText(0.15,0.2,0.48,0.25,"NDC");
  PlasmaGlob::SetPaveTextStyle(textWav,12); 
  textWav->SetTextColor(kGray+2);
  sprintf(ctext,"#lambda_{p} = %5.2f #mum", pData->GetPlasmaWaveLength() / PUnits::um);
  textWav->AddText(ctext);

  TPaveText *textCharge = new TPaveText(0.15,0.25,0.48,0.3,"NDC");
  PlasmaGlob::SetPaveTextStyle(textCharge,12); 
  textCharge->SetTextColor(kGray+2);
  if(opt.Contains("units") && pData->GetPlasmaDensity())
    sprintf(ctext,"Charge = %5.2f pC", Charge);
  else
    sprintf(ctext,"Charge = %5.2f n0#timeskp^{-3}", Charge);    
  textCharge->AddText(ctext);

  TPaveText *textMom = new TPaveText(0.55,0.03,0.82,0.13,"NDC");
  PlasmaGlob::SetPaveTextStyle(textMom,32); 
  textMom->SetTextColor(kGray+3);
  textMom->SetTextFont(62);
  if(opt.Contains("units") && pData->GetPlasmaDensity())
    sprintf(ctext,"#LTp_{z}#GT = %5.2f GeV/c", ymean);
  else
    sprintf(ctext,"Mom = %5.2f mc", ymean);    
  textMom->AddText(ctext);


  TPaveText *textInfo = new TPaveText(0.55,0.52,0.82,0.75,"NDC");
  PlasmaGlob::SetPaveTextStyle(textInfo,32); 
  textInfo->SetTextColor(kGray+2);
  textInfo->SetTextFont(42);
  sprintf(ctext,"Charge = %5.2f pC",Charge);
  textInfo->AddText(ctext);
  sprintf(ctext,"#LT#zeta#GT_{rms} = %5.2f #mum",xrms);
  textInfo->AddText(ctext);
  sprintf(ctext,"#LTp_{z}#GT_{rms} = %5.2f GeV/c",yrms);
  textInfo->AddText(ctext);
  // sprintf(ctext,"#epsilon_{N} = %5.2f #mum",emittance);
  // textInfo->AddText(ctext);
  
  // Setup Pad layout:
  const Int_t NFrames = 2;
  TPad **pad = new TPad*[NFrames];
  TH1F *hFrame[NFrames];

  Double_t lMargin = 0.15;
  Double_t rMargin = 0.18;
  Double_t bMargin = 0.15;
  Double_t tMargin = 0.04;
  Double_t vSpacing = 0.00; 
  Double_t hStep = (1.-lMargin-rMargin);
  Double_t vStep = (1.- bMargin - tMargin - (NFrames-1) * vSpacing) / NFrames;
  
  Float_t vposd = 0.0;
  Float_t vposu = 0.0;
  Float_t vmard = 0.0;
  Float_t vmaru = 0.0;
  Float_t vfactor = 0.0;
  Float_t hposl = 0.0;
  Float_t hposr = 1.0;
  Float_t hmarl = lMargin;
  Float_t hmarr = rMargin;
  Float_t hfactor = 1.0;
  
  // Actual Plotting!
  // ------------------------------------------------------------
  
  
  for(Int_t k=0;k<NFrames;k++) {

    // PLOTTING!
    if(k==0) {
      vposd = 0.0;
      vposu = bMargin + vStep;
      vfactor = vposu-vposd;  
      vmard = bMargin / vfactor;
      vmaru = 0.0;
    } else if(k == NFrames-1) {
      vposd = vposu + vSpacing;
      vposu = vposd + vStep + tMargin;
      vfactor = vposu-vposd;   
      vmard = 0.0;
      vmaru = tMargin / (vposu-vposd);
    } else {
      vposd = vposu + vSpacing;
      vposu = vposd + vStep; 
      vfactor = vposu-vposd;
      vmard = 0.0;
      vmaru = 0.0;
    } 
    hfactor = hposl-hposr;

    char name[16];
    sprintf(name,"pad_%i",k);
    pad[k] = new TPad(name,"",hposl,vposd,hposr,vposu);
    // // cout << Form("%f %f %f %f",hposl,vposd,hposr,vposu) << endl;
    // // cout << Form("%f %f %f %f",hmarl,vmard,hmarr,vmaru) << endl;
    pad[k]->SetLeftMargin(hmarl);
    pad[k]->SetRightMargin(hmarr);  
    pad[k]->SetBottomMargin(vmard);
    pad[k]->SetTopMargin(vmaru);
    pad[k]->SetFrameLineWidth(3);
    
    sprintf(name,"hFrame_%i",k);  
    hFrame[k] = (TH1F*) gROOT->FindObject(name);
    if(hFrame[k]) delete hFrame[k];
    hFrame[k] = (TH1F*) hX1->Clone(name);
    hFrame[k]->Reset();
    
    hFrame[k]->GetXaxis()->CenterTitle();
    hFrame[k]->GetYaxis()->CenterTitle();
    hFrame[k]->GetZaxis()->CenterTitle();
    hFrame[k]->SetLabelFont(42,"xyz");
    hFrame[k]->SetTitleFont(42,"xyz");
  
    hFrame[k]->SetNdivisions(505,"xyz");
  
    hFrame[k]->SetTickLength(0.04,"xyz");
    hFrame[k]->SetTickLength(0.04*vfactor,"y");
  
    hFrame[k]->GetYaxis()->SetLabelSize(0.04/vfactor);
    hFrame[k]->GetYaxis()->SetLabelOffset(0.02);
  
    hFrame[k]->GetYaxis()->SetTitleSize(0.05/vfactor);
    hFrame[k]->GetYaxis()->SetTitleOffset(1.2*vfactor);

    if(k==0) {  
      hFrame[k]->GetXaxis()->SetLabelSize(0.08);
      hFrame[k]->GetXaxis()->SetLabelOffset(0.02);
      hFrame[k]->GetXaxis()->SetTitleSize(0.12);
      hFrame[k]->GetXaxis()->SetTitleOffset(1.0);
    } else {
      hFrame[k]->GetXaxis()->SetLabelSize(0.0);
      hFrame[k]->GetXaxis()->SetTitleSize(0.0);
    }


  }

  // Ranges!!
  Double_t yMin =  999.9;
  Double_t yMax =  -999.9;
  for(Int_t k=0;k<SNbin;k++) {
    if(semittance[k]<yMin)
      yMin = semittance[k];
    
    if(semittance[k]>yMax)
      yMax = semittance[k];

    if(sErms[k]<yMin)
      yMin = sErms[k];
    
    if(sErms[k]>yMax)
      yMax = sErms[k];
  }

  for(Int_t k=1;k<=xNbin;k++) {
    Double_t value = hX1->GetBinContent(k);
    if(value<yMin)
      yMin = value;
    
    if(value>yMax)
      yMax = value;

  }
  
  C->cd();

  pad[1]->Draw();
  pad[1]->cd();

  if(opt.Contains("logz")) {
    gPad->SetLogz(1);
  } else {
    gPad->SetLogz(0);
  }
  
  hFrame[1]->GetYaxis()->SetRangeUser(hP1X1->GetYaxis()->GetXmin(),hP1X1->GetYaxis()->GetXmax());

  if(opt.Contains("units"))
    hFrame[1]->GetYaxis()->SetTitle("p_{z} [GeV/c]");
  
  hFrame[1]->Draw();

  gP1left->SetLineWidth(2);
  gP1left->Draw("F");
  gP1left->Draw("L");

  TLine lZmean(xmean,hP1X1->GetYaxis()->GetXmin(),xmean,hP1X1->GetYaxis()->GetXmax());
  lZmean.SetLineColor(kGray+2);
  lZmean.SetLineStyle(2);
  lZmean.Draw();

  TLine lPmean(hP1X1->GetXaxis()->GetXmin(),ymean,hP1X1->GetXaxis()->GetXmax(),ymean);
  lPmean.SetLineColor(kGray+2);
  lPmean.SetLineStyle(2);
  lPmean.Draw();


  hP1X1->GetYaxis()->SetNdivisions(503);
  hP1X1->GetZaxis()->SetNdivisions(503);
  hP1X1->GetZaxis()->SetRangeUser(0.001*hP1X1->GetMaximum(),hP1X1->GetMaximum());
  hP1X1->GetZaxis()->SetLabelSize(0.05);
  hP1X1->GetZaxis()->SetTitleSize(0.04);
  hP1X1->GetZaxis()->SetTitleFont(42);

  hP1X1->Draw("colzsame");
  // hP1X1->SetContour(20);
  // hP1X1->Draw("contzsame");
  // hP1X1prof->SetMarkerStyle(1);
  // hP1X1prof->SetLineWidth(2);
  // hP1X1prof->Draw("zsame");

  //hP1->Draw("C");
  
  gPad->Update();

  TPaletteAxis *palette = (TPaletteAxis*)hP1X1->GetListOfFunctions()->FindObject("palette");
  if(palette) {
    Float_t y1 = gPad->GetBottomMargin();
    Float_t y2 = 1 - gPad->GetTopMargin();
    Float_t x1 = 1 - gPad->GetRightMargin();
    palette->SetY2NDC(y2 - 0.04);
    palette->SetY1NDC(y1 + 0.04);
    palette->SetX1NDC(x1 + 0.01);
    palette->SetX2NDC(x1 + 0.04);
    
    palette->SetLabelFont(42);
    
    palette->SetLabelSize(0.08);
    //palette->SetLabelOffset(0.005/vfactor);
    palette->SetTitleSize(0.10);
    //    palette->SetTitleOffset(9999.0*vfactor);
    palette->SetTitleOffset(0.6);
    
    palette->SetBorderSize(2);
    palette->SetLineColor(1);
  }


  textTime->Draw();
  textInfo->Draw();
  // textCharge->Draw();
  textMom->Draw();
   
  gPad->RedrawAxis(); 

  // Bottom plot -----------------------------------------

  C->cd();

  pad[0]->Draw();
  pad[0]->cd();

  hFrame[0]->GetYaxis()->SetRangeUser(0.0,1.1*yMax);
  hFrame[0]->Draw();
    

  hX1->SetLineWidth(2);
  hX1->SetFillStyle(1001);
  hX1->SetFillColor(PlasmaGlob::elecFill);
  // hX1->SetLineColor(kBlue);
  hX1->Draw("FL same");
  //hX1->Draw("C");

  TLine lZmean2(xmean,0.0,xmean,1.1*yMax);
  lZmean2.SetLineColor(kGray+2);
  lZmean2.SetLineStyle(2);
  lZmean2.Draw();

  Int_t markerSize = 1.2; 
  Int_t lineWidth  = 2.0;   

  gYrms->SetMarkerStyle(20);
  gYrms->SetLineStyle(1);
  gYrms->SetMarkerColor(kGray+1);
  gYrms->SetMarkerSize(markerSize); 
  gYrms->SetLineColor(kGray+1);
  gYrms->SetLineWidth(lineWidth);
  gYrms->Draw("PL");
  
  // hP2X2sl[0]->Draw("colz");
  gemit->SetMarkerStyle(20);
  //  gemit->SetMarkerColor(kMagenta-2);
  gemit->SetMarkerColor(kGray+2);
  gemit->SetMarkerSize(markerSize);
  gemit->SetLineWidth(lineWidth);
  gemit->SetLineColor(kGray+2);
  gemit->Draw("PL");

  gErms->SetMarkerStyle(20);
  gErms->SetMarkerSize(markerSize);
  gErms->SetMarkerColor(kOrange+10);
  gErms->SetLineColor(kOrange+10);
  gErms->SetLineWidth(lineWidth);
  gErms->Draw("PL");


  TLegend *Leg;
  if(!sim.Contains("DR")) 
    Leg=new TLegend(0.55,0.60,1 - gPad->GetRightMargin() - 0.02,0.95);
  else
    Leg=new TLegend(gPad->GetLeftMargin() + 0.02, 1.0-gPad->GetTopMargin()-0.20,
		    gPad->GetLeftMargin() + 0.30, 1.0-gPad->GetTopMargin()-0.02);
  
  
  PlasmaGlob::SetPaveStyle(Leg);
  Leg->SetTextAlign(12);
  Leg->SetTextColor(kGray+3);
  Leg->SetTextFont(42);
  Leg->SetLineColor(1);
  Leg->SetBorderSize(0);
  Leg->SetFillColor(0);
  Leg->SetFillStyle(1001);
  Leg->SetFillStyle(0); // Hollow
 
  Leg->AddEntry(hX1  ,"Current [kA]","L");
  //  Leg->AddEntry(gErms,"Energy spread (GeV)","PL");
  Leg->AddEntry(gErms,"Energy spread [%]","PL");
  Leg->AddEntry(gemit,"Emittance [#mum]","PL");
  Leg->AddEntry(gYrms,"Bunch width [#mum]","PL");
 
  Leg->Draw();

  gPad->RedrawAxis(); 

  gPad->Update();
  

  // Print to file --------------------------------------
  
  C->cd();
  
  // Print to a file
  // Output file
  TString fOutName = Form("./%s/Plots/RakeBunch/RakeBunch",sim.Data());
  fOutName += Form("-%s_%i",sim.Data(),time);

  PlasmaGlob::imgconv(C,fOutName,opt);
  // ---------------------------------------------------------
  
}
示例#28
0
文件: ratio.C 项目: cranelli/WGamGam
void drawMeasurement(int i, double m[5], char label[2][100], int aux[5],
		     double vstep, TH2F* histo, TCanvas* canvas) {

 
    double lowY = (i+1)*vstep;
    double uppY = (i+2)*vstep;

  //double lowX = histo->GetBinLowEdge(1);
  //double uppX = histo->GetBinLowEdge(histo->GetNbinsX()) +
  //              histo->GetBinWidth(histo->GetNbinsX());
    double lowX = 0.25;
    double uppX = 2.80;
    double widthX = uppX - lowX;

 
  // y-range of the histogram is [0...1]

  double startX = lowX + 0.04*widthX;
  
  TPaveText* text = new TPaveText(startX, lowY,
				  startX, uppY, "BR");
  text->SetTextAlign(12);
  text->SetFillColor(aux[1]);
  text->SetTextColor(aux[0]);
  text->SetLineColor(1);
  text->SetBorderSize(0);
  TText* t0 = text->AddText("    ");
  t0->SetTextSize(0.08);
  t0->SetTextFont(aux[2]);
  TText* t1 = text->AddText(label[0]);
  t1->SetTextSize(0.08);
  t1->SetTextFont(aux[2]);
  TText* t2 = text->AddText(label[1]);
  t2->SetTextSize(0.08);
  t2->SetTextFont(aux[2]);
  text->Draw();


  double ypos = 0.5*(lowY+uppY);
  double mean = m[0];
  double nErr1 = m[1];
  double pErr1 = m[2];
  double nErr2 = sqrt(m[1]*m[1]+m[3]*m[3]);
  double pErr2 = sqrt(m[2]*m[2]+m[4]*m[4]);

  // draw TGraphAsymmErrors 1 (stat only) |---*---|
  TMarker* measurement = new TMarker(mean, ypos, aux[4]);
  measurement->SetMarkerColor(aux[0]);
  measurement->SetMarkerStyle(aux[4]);

  measurement->SetMarkerSize(1.5);
  //measurement->SetMarkerSize(1.75);
  measurement->Draw();

  double vsizeErr1 = 0.09*vstep;
  TLine* l1 = new TLine(mean, ypos, mean-nErr1, ypos);
  l1->SetLineWidth(aux[3]);
  l1->SetLineColor(aux[0]);
  l1->Draw();
  TLine* l2 = new TLine(mean, ypos, mean+pErr1, ypos);
  l2->SetLineWidth(aux[3]);
  l2->SetLineColor(aux[0]);
  l2->Draw();
  TLine* l3 = new TLine(mean-nErr1, ypos-vsizeErr1,
			mean-nErr1, ypos+vsizeErr1);
  l3->SetLineWidth(aux[3]);
  l3->SetLineColor(aux[0]);
  l3->Draw();
  TLine* l4 = new TLine(mean+pErr1, ypos-vsizeErr1,
			mean+pErr1, ypos+vsizeErr1);
  l4->SetLineWidth(aux[3]);
  l4->SetLineColor(aux[0]);
  l4->Draw();

  // overlay TGraphAsymmErrors 2 (stat+syst) |----*-----|
  double vsizeErr2 = 0.12*vstep; 
  TLine* l5 = new TLine(mean, ypos, mean-nErr2, ypos);
  l5->SetLineWidth(aux[3]);
  l5->SetLineColor(aux[0]);
  l5->Draw();
  TLine* l6 = new TLine(mean, ypos, mean+pErr2, ypos);
  l6->SetLineWidth(aux[3]);
  l6->SetLineColor(aux[0]);
  l6->Draw();
  TLine* l7 = new TLine(mean-nErr2, ypos-vsizeErr2,
			mean-nErr2, ypos+vsizeErr2);
  l7->SetLineWidth(aux[3]);
  l7->SetLineColor(aux[0]);
  l7->Draw();
  TLine* l8 = new TLine(mean+pErr2, ypos-vsizeErr2,
			mean+pErr2, ypos+vsizeErr2);
  l8->SetLineWidth(aux[3]);
  l8->SetLineColor(aux[0]);
  l8->Draw();

  // draw measurement label "XXX+/-YY+/-ZZ"
  TPaveText* num = new TPaveText(uppX-0.32*widthX,
				 lowY, uppX-0.02*widthX, uppY, "BR");
  num->SetTextAlign(12);
  num->SetFillColor(aux[1]);
  num->SetTextColor(aux[0]);
  num->SetLineColor(aux[0]);
  num->SetBorderSize(0);
  TString str;
  char s[100];

  sprintf(s, "%4.2f#color[%d]{X}", m[0], aux[1]); str +=s;
  if (m[1]==m[2]) { // sym. stat. errors
    sprintf(s, "#pm %4.2f",  m[1]); str +=s;
  } else {
    sprintf(s, "^{+%4.2f}",  m[2]); str +=s;
    sprintf(s, "_{-#color[%d]{|}%4.2f}", aux[1], m[1]); str +=s;
  }
  str += " (stat)";
  if (m[3]!=0.0 || m[4]!=0.0) {
    if (m[3]==m[4]) { // sym. syst. errors
      sprintf(s, "#color[%d]{X}#pm% 4.2f", aux[1], m[3]); str +=s;
    } else {
      sprintf(s, "#color[%d]{X}", aux[1]); str +=s;
      sprintf(s, "^{+%4.2f}",  m[4]); str +=s;
      sprintf(s, "_{-#color[%d]{|}%4.2f}", aux[1], m[3]); str +=s;
    }
  }
  str += " (syst)";


  TText* n0 = num->AddText(str);
  n0->SetTextFont(aux[2]);
  num->Draw();

  return;
}
示例#29
0
void 
HTT_MT_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., const char* inputfile="root/$HISTFILE", const char* directory="muTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category_extra = "";
  if(std::string(directory) == std::string("muTau_0jet_low"  )){ category_extra = "0 jet, low p_{T}";  }
  if(std::string(directory) == std::string("muTau_0jet_high" )){ category_extra = "0 jet, high p_{T}"; }
  if(std::string(directory) == std::string("muTau_boost_low" )){ category_extra = "1 jet, low p_{T}";  }
  if(std::string(directory) == std::string("muTau_boost_high")){ category_extra = "1 jet, high p_{T}"; }
  if(std::string(directory) == std::string("muTau_vbf"       )){ category_extra = "2 jet (VBF)";       }
  if(std::string(directory) == std::string("muTau_nobtag"    )){ category_extra = "No B-Tag";          }
  if(std::string(directory) == std::string("muTau_btag"      )){ category_extra = "B-Tag";             }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 19.4 fb^{-1} at 8 TeV";}
#ifdef MSSM
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 12.1 fb^{-1} at 8 TeV";}
#endif
 
  // open example histogram file
  TFile* input = new TFile(inputfile);
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/QCD"   , directory)), "QCD"); InitHist(Fakes, "", "", kMagenta-10, 1001);
  TH1F* EWK1   = refill((TH1F*)input->Get(TString::Format("%s/W"     , directory)), "W"  ); InitHist(EWK1 , "", "", kRed    + 2, 1001);
#ifdef EXTRA_SAMPLES
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZJ"    , directory)), "ZJ" ); InitHist(EWK2 , "", "", kRed    + 2, 1001);
  TH1F* EWK3   = refill((TH1F*)input->Get(TString::Format("%s/ZL"    , directory)), "ZL" ); InitHist(EWK3 , "", "", kRed    + 2, 1001);
#else
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZLL"   , directory)), "ZLL"); InitHist(EWK2 , "", "", kRed    + 2, 1001);
#endif
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/VV"    , directory)), "VV" ); InitHist(EWK  , "", "", kRed    + 2, 1001);
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/TT"    , directory)), "TT" ); InitHist(ttbar, "", "", kBlue   - 8, 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/ZTT"   , directory)), "ZTT"); InitHist(Ztt  , "", "", kOrange - 4, 1001);
#ifdef MSSM
  float ggHScale = 1., bbHScale = 1.; // scenario for MSSM, mhmax, mA=160, tanb=20, A + H for the time being
  if(std::string(inputfile).find("7TeV")!=std::string::npos){ ggHScale = ( 9157.9*0.119 + 10180.7*0.120)/1000.;
                                                             bbHScale = (23314.3*0.119 + 21999.3*0.120)/1000.; }
  if(std::string(inputfile).find("8TeV")!=std::string::npos){ ggHScale = (11815.3*0.119 + 13124.9*0.120)/1000.;
                                                             bbHScale = (31087.9*0.119 + 29317.8*0.120)/1000.; }
 //  float ggHScale = 1., bbHScale = 1.; // scenario for MSSM, mhmax, mA=160, tanb=10, A + H for the time being
//   if(std::string(inputfile).find("7TeV")!=std::string::npos){ ggHScale = (2111.4*0.11 + 4022.9*0.11)/1000.;
//                                                               bbHScale = (6211.6*0.11 + 5147.0*0.11)/1000.; }
//   if(std::string(inputfile).find("8TeV")!=std::string::npos){ ggHScale = (2729.9*0.11 + 5193.2*0.11)/1000.;
//                                                               bbHScale = (8282.7*0.11 + 6867.8*0.11)/1000.; }
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH160", directory)), "ggH"); InitSignal(ggH); ggH ->Scale(ggHScale);
  TH1F* bbH    = refill((TH1F*)input->Get(TString::Format("%s/bbH160", directory)), "bbH"); InitSignal(bbH); bbH ->Scale(bbHScale);
#else
#ifndef DROP_SIGNAL
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH125", directory)), "ggH"); InitSignal(ggH); ggH ->Scale(SIGNAL_SCALE);
  TH1F* qqH    = refill((TH1F*)input->Get(TString::Format("%s/qqH125", directory)), "qqH"); InitSignal(qqH); qqH ->Scale(SIGNAL_SCALE);
  TH1F* VH     = refill((TH1F*)input->Get(TString::Format("%s/VH125" , directory)), "VH" ); InitSignal(VH ); VH  ->Scale(SIGNAL_SCALE);
#endif
#endif
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK1 );
  ref->Add(EWK2 );
#ifdef EXTRA_SAMPLES
  ref->Add(EWK3 );
#endif
  ref->Add(EWK  );
  ref->Add(ttbar);
  ref->Add(Ztt  );

  double unscaled[7];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[1]+= EWK1 ->Integral();
  unscaled[1]+= EWK2 ->Integral();
#ifdef EXTRA_SAMPLES
  unscaled[1]+= EWK3 ->Integral();
#endif
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = bbH  ->Integral();
  unscaled[6] = 0;
#else
#ifndef DROP_SIGNAL
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = qqH  ->Integral();
  unscaled[6] = VH   ->Integral();
#endif
#endif

  if(scaled){
    rescale(Fakes, 7); 
    rescale(EWK1 , 3); 
    rescale(EWK2 , 4); 
#ifdef EXTRA_SAMPLES
    rescale(EWK3 , 5);
#endif 
    rescale(EWK  , 6); 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggH  , 8); 
    rescale(bbH  , 9);  
#else
#ifndef DROP_SIGNAL
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
    rescale(VH   ,10);  
#endif
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-Fakes", "", 7, 0, 7);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", 7, 0, 7);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? ((EWK  ->Integral()
					       +EWK1 ->Integral()
					       +EWK2 ->Integral()
#ifdef EXTRA_SAMPLES
					       +EWK3 ->Integral()
#endif
						)/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", 7, 0, 7);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", 7, 0, 7);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-bbH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", 7, 0, 7);
  scales[6]->SetBinContent(7, 0.);
#else
#ifndef DROP_SIGNAL
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (qqH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-VH"   , "", 7, 0, 7);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (VH   ->Integral()/unscaled[6]-1.) : 0.);
#endif
#endif

  EWK1 ->Add(Fakes);
  EWK2 ->Add(EWK1 );
#ifdef EXTRA_SAMPLES
  EWK3 ->Add(EWK2 );
  EWK  ->Add(EWK3 );
#else
  EWK  ->Add(EWK2 );
#endif
  ttbar->Add(EWK  );
  Ztt  ->Add(ttbar);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM    
    bbH  ->Add(Ztt);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    VH   ->Add(Ztt);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }

  /*
    Mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(350)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(1000)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(350));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Ztt ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{#mu}#tau_{h}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText("#mu#tau_{h}");
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m_{A}=160GeV");
  massA->Draw();

  TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
  tanb->SetBorderSize(   0 );
  tanb->SetFillStyle(    0 );
  tanb->SetTextAlign(   12 );
  tanb->SetTextSize ( 0.03 );
  tanb->SetTextColor(    1 );
  tanb->SetTextFont (   62 );
  tanb->AddText("tan#beta=20");
  tanb->Draw();

  TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
  scen->SetBorderSize(   0 );
  scen->SetFillStyle(    0 );
  scen->SetTextAlign(   12 );
  scen->SetTextSize ( 0.03 );
  scen->SetTextColor(    1 );
  scen->SetTextFont (   62 );
  scen->AddText("mhmax");
  scen->Draw();
#endif

#ifdef MSSM
  TLegend* leg = new TLegend(0.45, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.50, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#endif
  leg->AddEntry(data , "observed"                       , "LP");
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  leg->AddEntry(EWK  , "electroweak"                    , "F" );
  leg->AddEntry(Fakes, "QCD"                            , "F" );
  $ERROR_LEGEND
  leg->Draw();

//#ifdef MSSM
//  TPaveText* mssm  = new TPaveText(0.69, 0.85, 0.90, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("(m_{A}=120, tan#beta=10)");
//  mssm->Draw();
//#else
//  TPaveText* mssm  = new TPaveText(0.83, 0.85, 0.95, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("m_{H}=125");
//  mssm->Draw();
//#endif

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* zero = (TH1F*)ref->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
  rat1->Divide(Ztt);
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
    zero->SetBinContent(ibin+1, 0.);
  }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+0.5);
  rat1->SetMinimum(-0.5);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv0->RedrawAxis();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  rat2->Divide(ref);
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  rat2->SetLineColor(kRed+ 3);
  rat2->SetFillColor(kRed-10);
  rat2->SetMaximum(+0.3);
  rat2->SetMinimum(-0.3);
  rat2->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat2->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kMagenta-10, 1001);
  InitHist  (scales[1], "", "", kRed    + 2, 1001);
  InitHist  (scales[2], "", "", kBlue   - 8, 1001);
  InitHist  (scales[3], "", "", kOrange - 4, 1001);
#ifndef DROP_SIGNAL
  InitSignal(scales[4]);
  InitSignal(scales[5]);
  InitSignal(scales[6]);
#endif
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "NONE"      );
#else
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+1.0);
  scales[0]->SetMinimum(-1.0);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
#ifndef DROP_SIGNAL
  scales[4]->Draw("same");
  scales[5]->Draw("same");
  scales[6]->Draw("same");
#endif
  zero->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.png"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.pdf"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.eps"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  TFile* output = new TFile(TString::Format("%s_%sscaled_%s_%s.root", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""), "update");
  output->cd();
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
  EWK  ->Write("EWK"     );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggH  ->Write("ggH"     );
  bbH  ->Write("bbH"     );
#else
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH"     );
  qqH  ->Write("qqH"     );
  VH   ->Write("VH"      );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
}
示例#30
0
void mergePlotResponse(const string& canvasName, TMultiGraph *mgResponse, TGraph *gResponseMC_MJB, TGraph *gResponseData_MJB, TGraph *gratio_MJB, TGraph *gResponseMC_MPF, TGraph *gResponseData_MPF, TGraph *gratio_MPF, double y_min, double y_max, const string& label_MJB, const string& label_MPF, const string& path) { // Mikko's tdrstyle_mod14
  TCanvas *c3 = tdrDiCanvas(canvasName.c_str(),mgResponse,gratio_MJB,2,0);
  c3->cd(1);

  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  mgResponse->SetMaximum(y_max);
  mgResponse->SetMinimum(y_min);
  mgResponse->Draw("P");
  gPad->RedrawAxis();
  //c3->SetLogx(1);

  //TLegend* legend = new TLegend(0.55, 0.15, 0.92, 0.38);
  TLegend* legend = new TLegend(0.63, 0.15, 0.93, 0.30);
  legend->SetFillColor(kWhite);
  legend->SetFillStyle(kNone);
  legend->SetTextFont(43);
  legend->SetBorderSize(0);
  //legend->SetTextSize(0.045);
  string toLeg = label_MJB + ", MC";
  legend->AddEntry(gResponseMC_MJB, toLeg.c_str(),"p");
  toLeg = label_MJB + ", data";
  legend->AddEntry(gResponseData_MJB,toLeg.c_str(),"p");
  toLeg = label_MPF + ", MC";
  legend->AddEntry(gResponseMC_MPF,toLeg.c_str(),"p");
  toLeg = label_MPF + ", data";
  legend->AddEntry(gResponseData_MPF,toLeg.c_str(),"p");
  legend->Draw("same");


  c3->cd(2);
  TF1* ratioFit_MJB = new TF1("ratioFit_MJB", "[0]", mgResponse->GetXaxis()->GetXmin(),mgResponse->GetXaxis()->GetXmax());
  ratioFit_MJB->SetParameter(0, 0.);
  ratioFit_MJB->SetLineColor(gratio_MJB->GetLineColor());
  ratioFit_MJB->SetLineWidth(0);

  gratio_MJB->Draw("APE1");
  gratio_MJB->GetYaxis()->SetTitle("Data / MC");
  gratio_MJB->SetMarkerSize(1.0);
  gratio_MJB->SetMaximum(1.05);
  gratio_MJB->SetMinimum(0.95);
  gratio_MJB->GetXaxis()->SetLimits(mgResponse->GetXaxis()->GetXmin(),mgResponse->GetXaxis()->GetXmax());

  gratio_MPF->Draw("PE1same");

  c3->Update();
  gratio_MJB->Fit(ratioFit_MJB, "RQ");
  //gratio_MJB->GetYaxis()->SetRangeUser(-1,3);
  double fitValue_MJB = ratioFit_MJB->GetParameter(0);
  double fitError_MJB = ratioFit_MJB->GetParError(0);

  TF1* ratioFit_MPF = new TF1("ratioFit_MPF", "[0]", mgResponse->GetXaxis()->GetXmin(),mgResponse->GetXaxis()->GetXmax());
  ratioFit_MPF->SetParameter(0, 0.);
  ratioFit_MPF->SetLineColor(gratio_MPF->GetLineColor());
  ratioFit_MPF->SetLineWidth(0);
  gratio_MPF->Fit(ratioFit_MPF, "RQ");
  //gratio_MPF->GetYaxis()->SetRangeUser(-1,3);
  double fitValue_MPF = ratioFit_MPF->GetParameter(0);
  double fitError_MPF = ratioFit_MPF->GetParError(0);

  TPaveText* fitlabel = new TPaveText(0.57, 0.82, 0.85, 0.84, "brNDC");
  fitlabel->SetTextSize(0.08);
  fitlabel->SetFillColor(0);
  fitlabel->SetTextFont(42);
  fitlabel->SetTextColor(gratio_MJB->GetLineColor());
  TString fitLabelTextMJB = TString::Format("Fit %s: %.4f #pm %.4f", label_MJB.c_str(), fitValue_MJB, fitError_MJB);
  fitlabel->AddText(fitLabelTextMJB);
  fitlabel->Draw("same");

  TPaveText* fitlabel_MPF = new TPaveText(0.57, 0.72, 0.85, 0.74, "brNDC");
  fitlabel_MPF->SetTextSize(0.08);
  fitlabel_MPF->SetFillColor(0);
  fitlabel_MPF->SetTextFont(42);
  fitlabel_MPF->SetTextColor(gratio_MPF->GetLineColor());
  TString fitLabelTextMPF = TString::Format("Fit %s: %.4f #pm %.4f", label_MPF.c_str(), fitValue_MPF, fitError_MPF);
  fitlabel_MPF->AddText(fitLabelTextMPF);
  fitlabel_MPF->Draw("same");

  gPad->RedrawAxis();
  c3->SaveAs(path.c_str());
}