Exemple #1
0
TH2F *prof2d(TTree *tree, TString var1Name, TString var2Name, TString nllName, TString binning="(40,0,0.05,40,0,0.2)", bool delta=false){

  var1Name.ReplaceAll("-","_");
  var2Name.ReplaceAll("-","_");
  //  tree->Print();
  TString histName="h";
  std::cout << var1Name << "\t" << var2Name << "\t" << histName << std::endl;
  tree->Draw(var1Name+":"+var2Name+">>"+histName+binning);
  TH2F *hEntries = (TH2F*)gROOT->FindObject(histName);
  if(hEntries==NULL) return NULL;
  //std::cerr << "e qui ci sono?" << std::endl;
  tree->Draw(var1Name+":"+var2Name+">>shervin"+binning,nllName);

  TH2F *h = (TH2F*)gROOT->FindObject("shervin");
  if(h==NULL) return NULL;
  h->Divide(hEntries);


  //std::cerr << "io sono qui" << std::endl;    
  delete hEntries;
  Double_t min=1e20, max=0;

  if(delta){
    for(Int_t iBinX=1; iBinX <= h->GetNbinsX(); iBinX++){
      for(Int_t iBinY=1; iBinY <= h->GetNbinsY(); iBinY++){
	Double_t binContent=h->GetBinContent(iBinX, iBinY);
	if(min>binContent && binContent!=0) min=binContent;
	if(max<binContent) max=binContent;
      }
    }
    std::cout << "min=" << min << "\tmax=" << max<<std::endl;    
    for(Int_t iBinX=1; iBinX <= h->GetNbinsX(); iBinX++){
      for(Int_t iBinY=1; iBinY <= h->GetNbinsY(); iBinY++){
	Double_t binContent=h->GetBinContent(iBinX, iBinY);
	//std::cout << binContent << std::endl;
	if(binContent!=0) binContent-=min;
	else binContent=-1;
	h->SetBinContent(iBinX,iBinY,binContent);
      }
    }
  }
  h->GetZaxis()->SetRangeUser(0,500);
  //std::cerr << "io sono qui 3" << std::endl;    
  return h;
//   Double_t variables[2];
//   Double_t nll;
//   tree->SetBranchAddress(var1Name, &(variables[0]));
//   tree->SetBranchAddress(var2Name, &(variables[1]));
//   tree->SetBranchAddress(nllName, &(nll));

  
//   Long64_t nEntries=tree->GetEntries();
//   for(Long64_t jentry=0; jentry<nEntries; jentry++){
    
}
Exemple #2
0
void makeTable(TString rootfilename, 
	       TString histname, char* tablefilename)
{

  TFile myhistos(rootfilename); 
  TH2F* h = (TH2F*) myhistos.Get(histname);
  int nX = h->GetNbinsX();
  int nY = h->GetNbinsY();


  FILE *file = fopen(tablefilename,"w+");


  for(int i=1; i<=nX; ++i) {
  
    Double_t pT0 = h->GetXaxis()->GetBinLowEdge(i);
    Double_t pT1 = h->GetXaxis()->GetBinLowEdge(i+1);

    for(int j=1; j<=nY; ++j) {
      Double_t x = h->GetBinContent(i,j);
      Double_t dx = 8.0 * h->GetBinError(i,j);
      if( dx > 1.0 ) dx = 1.0;
      Double_t eta0 = h->GetYaxis()->GetBinLowEdge(j);
      Double_t eta1 = h->GetYaxis()->GetBinLowEdge(j+1);

      fprintf( file ,"%4.1f  %4.1f   %+6.4f   %+6.4f  %6.4f   %6.4f \n", 
	       pT0, pT1, eta0, eta1, x, dx);
    }
  }

  fclose(file);
}
Exemple #3
0
void plotDeltaT()
{
  Double_t nTopOfIce=1.4;
  Double_t ant1[3]={8,-5,-25};
  Double_t ant2[3]={8,5,-30};
  Double_t rho1=TMath::Sqrt(ant1[0]*ant1[0]+ant1[1]*ant1[1]);
  Double_t rho2=TMath::Sqrt(ant2[0]*ant2[0]+ant2[1]*ant2[1]);
  Double_t phi1=TMath::ATan2(ant1[1],ant1[0]);
  Double_t phi2=TMath::ATan2(ant2[1],ant2[0]);
  std::cout << phi1*TMath::RadToDeg() << "\t" << phi2*TMath::RadToDeg() << "\n";
  TH2F *histDt = new TH2F("histDt","histDt",360,-180,180,180,-90,90);
  for(int binx=1;binx<=histDt->GetNbinsX();binx++) {
    Double_t phiWaveDeg=histDt->GetXaxis()->GetBinCenter(binx);
    for(int biny=1;biny<=histDt->GetNbinsY();biny++) {
      Double_t thetaWaveDeg=histDt->GetYaxis()->GetBinCenter(biny);
      Double_t phiWave=phiWaveDeg*TMath::DegToRad();
      Double_t thetaWave=thetaWaveDeg*TMath::DegToRad();
      
      Double_t d1=TMath::Cos(thetaWave)*(ant1[2]*TMath::Tan(thetaWave)+rho1*TMath::Cos(phi1-phiWave));
      Double_t d2=TMath::Cos(thetaWave)*(ant2[2]*TMath::Tan(thetaWave)+rho2*TMath::Cos(phi2-phiWave));
      Double_t t2t1=(d1-d2)*nTopOfIce/TMath::C();
      t2t1*=1e9;
      histDt->Fill(phiWaveDeg,thetaWaveDeg,t2t1);
    }
  }
  histDt->Draw("colz");

}
Exemple #4
0
void quickWorldModelTest() {
    gSystem->Load("lib/libPropagation.so");
//    BedmapTable *iceTable = new BedmapTable (RyansCons::kBathymetry);
    WorldModel *myWorld = new WorldModel();
    TH2F *iceHist = new TH2F("iceHist","Ice Thickness",1000,-3e6,3e6,1000,-3e6,3e6);
    TH2F *iceHist2 = new TH2F("iceHist2","Ice Thickness (Bedmap)",1000,-3e6,3e6,1000,-3e6,3e6);
    TH2F *surfaceHist = new TH2F("surfaceHist","Surface",1000,-3e6,3e6,1000,-3e6,3e6);
//    int goodFlag;
    for(int binx=1;binx<=iceHist->GetNbinsX();binx++) {
	Double_t x=iceHist->GetXaxis()->GetBinCenter(binx);
	for(int biny=1;biny<=iceHist->GetNbinsY();biny++) {
	    Double_t y=iceHist->GetYaxis()->GetBinCenter(biny);
	    Double_t value=myWorld->getCrust2Data(x,y,RyansCons::kThicknessOfIce);
	    iceHist->SetBinContent(binx,biny,value);
	    value=myWorld->getIceThickness(x,y);
	    iceHist2->SetBinContent(binx,biny,value);
	    value=myWorld->getSurface(x,y);
	    surfaceHist->SetBinContent(binx,biny,value/1e6);
	    if(value>1e7 || value<1e6) cout << x << "\t" << y << "\t" << value << endl;
	}
    }
    TCanvas *can = new TCanvas("can","can");
    can->Divide(1,2);
    can->cd(1);
    iceHist->Draw("colz");
    can->cd(2);
    iceHist2->Draw("colz");
	
    TCanvas *can2 = new TCanvas("can2","can2");
    surfaceHist->Draw("colz");
    
}
void smoothHorizontal(TH2F* h, float threshold) {
    TH2F* hist = (TH2F*)(h->Clone((std::string(h->GetName())+"_hori").c_str()));
    for (int i = 1; i <= hist->GetNbinsX(); ++i) {
        for(int j = 1; j <= hist->GetNbinsY(); ++j) {
            float val = hist->GetBinContent(i,j);
            float count = 0.;
            if (val < threshold) { 
                if (i-1 != 0)                                                  val += hist->GetBinContent(i-1,j  );
                else                                                           count -= 1.0;;
                if (i+1 != hist->GetNbinsX()+1)                                val += hist->GetBinContent(i+1,j  );
                else                                                           count -= 1.0;
                val /= (3.0+count);
                h->SetBinContent(i,j,val);
            }
        }
    }
}
TH2F* InterpolateThisHistogram(TH2F *hold/*, TH2F* hnew*/){
  float binsize = hold->GetXaxis()->GetBinWidth(1)/2.;
  TString name = hold->GetName();
  name.ReplaceAll("Org","");
  TGraph2D *g = new TGraph2D(hold);
  //cout << g->GetXmax() << " " << g->GetXmin() << " " << g->GetYmax() << " " << g->GetYmin() << " " << binsize << endl;
  g->SetNpx(int(g->GetXmax()-g->GetXmin())/binsize);
  g->SetNpy(int(g->GetYmax()-g->GetYmin())/binsize);
  TH2F *hnew = (TH2F*)g->GetHistogram();
  //TH2F *htemp = (TH2F*)hnew->Clone(name);
  //name.ReplaceAll("YXZ","");
  TH2F *h = new TH2F(name.Data(),hold->GetTitle(),hnew->GetNbinsX(),g->GetXmin()-binsize,g->GetXmax()-binsize,hnew->GetNbinsY(),g->GetYmin()-binsize,g->GetYmax()-binsize);
  for(unsigned int x = 1; x<=hnew->GetNbinsX(); ++x){
    for(unsigned int y = 1; y<=hnew->GetNbinsY(); ++y){
      h->SetBinContent(x,y,hnew->GetBinContent(x,y));
    }
  }
  delete g;
  return h;
}
TH2F* Bin2DTree::fillHistogram()
/*****************************************************************/
{
        if(!m_gridConstraint)
        {
            cerr<<"ERROR: Bin2DLeaf.fillHistogram(): Trying to fill histogram, but the binning is unknown. Define first the gridConstraint.\n";
            exit(1);
        }
        TH2F* histo = (TH2F*)m_gridConstraint->Clone("histoFromTree");
        int nbinsx = histo->GetNbinsX();
        int nbinsy = histo->GetNbinsY();
        map<Bin2DLeaf*, vector< pair<int,int> > > binsInLeaf;
        // First find the list of TH2 bins for each Bin2DLeaf bin
        for(int bx=1;bx<nbinsx+1;bx++) 
        {
            for(int by=1;by<nbinsy+1;by++)
            {
                histo->SetBinContent(bx,by,0);
                histo->SetBinError(bx,by,0);
                double x = histo->GetXaxis()->GetBinCenter(bx);
                double y = histo->GetYaxis()->GetBinCenter(by);
                Bin2DLeaf* leaf = getLeaf(x,y);
                if(binsInLeaf.find(leaf)==binsInLeaf.end())
                {
                    vector< pair<int,int> > empty;
                    binsInLeaf[leaf] = empty;
                }
                binsInLeaf[leaf].push_back(make_pair(bx,by));
            }
        }
        // Then all the TH2 bins are filled according to the entries in the Bin2DLeaf bins
        map<Bin2DLeaf*, vector< pair<int,int> > >::iterator it = binsInLeaf.begin();
        map<Bin2DLeaf*, vector< pair<int,int> > >::iterator itE = binsInLeaf.end();
        for(;it!=itE;++it)
        {
            Bin2DLeaf* leaf = it->first;
            vector< pair<int,int> > bins = it->second;
            vector< vector<double> > entries = leaf->getEntries();
            int nbins = bins.size();
            for(int b=0;b<nbins;b++)
            {
                int bx = bins[b].first;
                int by = bins[b].second;
                double x = histo->GetXaxis()->GetBinCenter(bx);
                double y = histo->GetYaxis()->GetBinCenter(by);
                for(unsigned int e=0;e<entries.size();e++)
                {
                    double value = entries[e][2]/(double)nbins;
                    histo->Fill(x,y,value);
                }
            }
        }
        return histo;
}
pair<TH2F*,TH2F*> Bin2DTree::fillWidths()
/*****************************************************************/
{
        if(!m_gridConstraint)
        {
            cerr<<"ERROR: Bin2DLeaf.fillWidths(): Trying to fill histogram, but the binning is unknown. Define first the gridConstraint.\n";
            exit(1);
        }
        TH2F* hWidthX = (TH2F*)m_gridConstraint->Clone("widthXFromTree");
        TH2F* hWidthY = (TH2F*)m_gridConstraint->Clone("widthYFromTree");
        int nbinsx = hWidthX->GetNbinsX();
        int nbinsy = hWidthX->GetNbinsY();
        map<Bin2DLeaf*, vector< pair<int,int> > > binsInLeaf;
        for(int bx=1;bx<nbinsx+1;bx++) 
        {
            for(int by=1;by<nbinsy+1;by++)
            {
                double x = hWidthX->GetXaxis()->GetBinCenter(bx);
                double y = hWidthX->GetYaxis()->GetBinCenter(by);
                Bin2DLeaf* leaf = getLeaf(x, y);
                vector<Bin2DLeaf*> neighborLeaves = findNeighborLeaves(leaf);
                neighborLeaves.push_back(leaf);
                vector<Bin2DLeaf*>::iterator itLeaf = neighborLeaves.begin();
                vector<Bin2DLeaf*>::iterator itELeaf = neighborLeaves.end();
                double sumw = 0.;
                double sumwx = 0.;
                double sumwy = 0.;
                for(;itLeaf!=itELeaf;++itLeaf)
                {
                    double xi = (*itLeaf)->getXCenter();
                    double yi = (*itLeaf)->getYCenter();
                    double dx = xi-x;
                    double dy = yi-y;
                    double wxi = (*itLeaf)->getXWidth();
                    double wyi = (*itLeaf)->getYWidth();
                    if(dx<0.05*wxi) dx = 0.05*wxi;
                    if(dy<0.05*wyi) dy = 0.05*wyi;
                    double dr2 = dx*dx+dy*dy;
                    sumw += 1./dr2;
                    sumwx += wxi/dr2;
                    sumwy += wyi/dr2;
                }
                double widthx = sumwx/sumw;
                double widthy = sumwy/sumw;
                hWidthX->SetBinContent(bx,by,widthx);
                hWidthY->SetBinContent(bx,by,widthy);
                hWidthX->SetBinError(bx,by,0.);
                hWidthY->SetBinError(bx,by,0.);
            }
        }
        return make_pair(hWidthX, hWidthY);
}
void smooth(TH2F* h, int binmin, int binmax, float arraysize) {
    TH2F* hist = (TH2F*)(h->Clone((std::string(h->GetName())+"_temp").c_str()));
    for (int i = binmin; i <= hist->GetNbinsX() && i <= binmax; ++i) {
        for(int j = 1; j <= hist->GetNbinsY(); ++j) {
            float count = 0.;
            float val = 0;
            for (int m = i-arraysize; m <= i+arraysize; m++) {
                //for (int n = j-arraysize; n <= j+arraysize; n++) {
                //for (int n = j-1; n <= j+1; n++) {
                    int n = j;
                    if (m >= binmin && m <= hist->GetNbinsX() && m <= binmax && n > 0 && n <= hist->GetNbinsY()) {
                        count += 1.0;
                        val += hist->GetBinContent(m, n);
                    }
                //}
            }
            val /= count;
            if (val > 0.0) h->SetBinContent(i,j,val);
            else h->SetBinContent(i,j,0.00001);
        }
    }
}
TH2F* XsecThisHistogram(TH2F *hold, TH1D *hxsec){
  TString name = hold->GetName() + (TString)"Xsec";
  TH2F *hnew = (TH2F*)hold->Clone(name);
  for(int x = 1; x<=hnew->GetNbinsX(); ++x){
    for(int y = 1; y<=hnew->GetNbinsY(); ++y){
      float val = hnew->GetBinContent(x,y);
      float mstop = hnew->GetXaxis()->GetBinLowEdge(x);
      //cout << "check " << "bin " << x << " gets me mstop " << mstop << endl;
      float xsec = hxsec->GetBinContent(hxsec->FindBin(mstop));
      hnew->SetBinContent(x,y,val*xsec);
    }
  }
  return hnew;
}
TH2F* PassThisHistogram(TH2F *hold){
  TString name = hold->GetName() + (TString)"Pass";
  TH2F *hnew = (TH2F*)hold->Clone(name);
  for(int x = 1; x<=hnew->GetNbinsX(); ++x){
    for(int y = 1; y<=hnew->GetNbinsY(); ++y){
      float val = hnew->GetBinContent(x,y);
      float pass = 0;
      if(val>1) pass = 0.001;
      else if(val>0) pass = 1;
      hnew->SetBinContent(x,y,pass);
    }
  }
  return hnew;
}
TH2F SantanderMatching(TH2F const& h4f, TH2F const& h5f, TH2F const* mass) {
  TH2F res = h4f;
  for (int x = 1; x <= h4f.GetNbinsX(); ++x) {
    for (int y = 1; y <= h4f.GetNbinsY(); ++y) {
      double mh =
          mass ? mass->GetBinContent(x, y) : h4f.GetXaxis()->GetBinCenter(x);
      double t = log(mh / 4.75) - 2.;
      double fourflav = h4f.GetBinContent(x, y);
      double fiveflav = h5f.GetBinContent(x, y);
      double sigma = (1. / (1. + t)) * (fourflav + t * fiveflav);
      res.SetBinContent(x, y, sigma);
    }
  }
  return res;
}
HcalElectronicsSelector::HcalElectronicsSelector(Callbacks* cb,
						 int htrChan_lo, int htrChan_hi,
						 int fpga_lo, int fpga_hi,int crate)
{
  m_crate=crate;
  m_cb=cb;
  m_canvas=new TCanvas("HcalSelector");
 
  
  int htrChan_bins=htrChan_hi-htrChan_lo+1;
  int fpga_bins=(fpga_hi-fpga_lo+1)*2;
  
  char name[10];
  char title[256];
 
  sprintf(title,"htrChan/fpga Space Crate %d",crate);
  sprintf(name,"Crate %d",crate);
  TH2F* h = new TH2F(title,name,
		     fpga_bins, fpga_lo-0.25, fpga_hi+0.75,
		     htrChan_bins, htrChan_lo-0.5, htrChan_hi+0.5);
		  
  h->GetYaxis()->SetTitle("HTR CHANNEL");
  h->GetXaxis()->SetTitle("Slot");
  h->SetStats(0);
  // Set bins to a 'badval' in order to distinguish
  // between zero-mean cells and unconnected cells
  //
  for (int binx=1; binx<=h->GetNbinsX(); binx++)
    for (int biny=1; biny<=h->GetNbinsY(); biny++)
      h->SetBinContent(binx,biny,BADVAL);
  m_hist = h;
 
  TStyle* ms=new TStyle("hvs","hvs");
  ms->SetPalette(1,0);
  ms->cd();
  
 
  m_canvas->cd();
    m_hist->Draw("COLZ");
    m_canvas->Update();
  
  m_canvas->Connect("ProcessedEvent(Int_t,Int_t,Int_t,TObject*)",
		    "HcalElectronicsSelector", this,
		    "onEvent(Int_t,Int_t,Int_t,TObject*)");//add crate
  
  m_canvas->cd();
}
TH2F* RemoveHistoDiagonal(TH2F *hold){
  int nbinsX = hold->GetNbinsX();
  int nbinsY = hold->GetNbinsY();
  TString name = hold->GetName();
  name.ReplaceAll("_x","");
  TH2F *h = (TH2F*)hold->Clone(name);

  for(int x = 1; x<=h->GetNbinsX(); ++x){
    for(int y = 1; y<=h->GetNbinsY(); ++y){
      float xlow = h->GetXaxis()->GetBinLowEdge(x);
      float xup  = xlow + h->GetXaxis()->GetBinWidth(x);
      float ylow = h->GetYaxis()->GetBinLowEdge(y);
      float yup  = ylow + h->GetYaxis()->GetBinWidth(y);
      //if(name=="hExp") cout << "xlow " << xlow << " xup " << xup << " ylow " << ylow << " yup " << yup << endl;
      if(((xlow-ylow)>=172.5&&((xlow-ylow)<=175))||((xup-yup)>=172.5&&(xup-yup)<=175.) ) //continue;
      h->SetBinContent(x,y,0);
    }
  }
  return h;
}
TH2F* ZMassVsDRHist2D(TString name, TString bininfo, DiMuPlottingSystem* dps)
{
  // Plot a 2D hist of the dimuon mass vs ZPt for either positive or negative reco muons. 
  // This function uses the DiMuonPlottingSystem class which facilitates the application of cuts. 

  // Get the titles and units straight.
  TString xtitle = TString("dR");

  TString title = TString ("Z Mass vs ");
  title+=xtitle;
  xtitle+= TString("");

  TString ytitle = TString("Z Mass (GeV)");

  // Initialize some pointers to be filled. h2 takes in reco2 info which will be added to reco1 info in order to get
  // all of the positive or all of the negative reco muons.
  TH2F* h = 0;

  TString dR = TString("((reco1.phi - reco2.phi)**2 + (reco1.eta - reco2.eta)**2 )**0.5");

  h = dps->hist2D("recoCandMass:"+dR, bininfo, "");

  // Print out the number of muons in the different histograms to make sure they add up right.
  std::cout << "nentries: " << h->GetEntries() << std::endl;

  // Set the title info for the histogram.
  h->SetTitle(title);
  h->GetXaxis()->SetTitle(xtitle);
  h->GetYaxis()->SetTitle(ytitle);
  h->SetName(name);
  std::cout << "xtitle: " << h->GetXaxis()->GetTitle() << std::endl;
  std::cout << "title: " << h->GetTitle() << std::endl;

  h->Draw("colz");
  std::cout << "nxbins: " << h->GetXaxis()->GetNbins() << std::endl;
  std::cout << "nybins: " << h->GetYaxis()->GetNbins() << std::endl;
  std::cout << "nbinsx: " << h->GetNbinsX() << std::endl;

  return h;
}
Exemple #16
0
TH2F* fixrange(TH2F* old, int numB) {

  float x1, x2;
  string name = old->GetName();

  if (name.find("Ht")!=string::npos) {
    x1 = 30.;
    x2 = 500.;
    if (numB==2) x2 = 400.;
  } else if (name.find("jet_pt")!=string::npos) {
    x1 = 30.;
    x2 = 300.;
    if (numB==2) {
      if (name.find("first")!=string::npos) x2 = 200.;
      if (name.find("second")!=string::npos) x2 = 120.;
    }
  } else if (name.find("pt_Z")!=string::npos) {
    x1 = 0.;
    x2 = 300.;
    if (numB==2) x2 = 230.;
  } else {
    x1 = old->GetXaxis()->GetBinCenter(1);
    x2 = old->GetXaxis()->GetBinCenter(old->GetNbinsX());
  }

  float y1=x1;
  float y2=x2;

  int nx = old->GetXaxis()->FindBin(x2)-old->GetXaxis()->FindBin(x1)+1;
  int ny = old->GetYaxis()->FindBin(y2)-old->GetYaxis()->FindBin(y1)+1;

  x1 = old->GetXaxis()->GetBinLowEdge(old->GetXaxis()->FindBin(x1));
  x2 = old->GetXaxis()->GetBinUpEdge(old->GetXaxis()->FindBin(x2));
  y1 = old->GetYaxis()->GetBinLowEdge(old->GetYaxis()->FindBin(y1));
  y2 = old->GetYaxis()->GetBinUpEdge(old->GetYaxis()->FindBin(y2));

  TH2F* tmp = new TH2F("tmp",old->GetTitle(),nx,x1,x2,ny,y1,y2);
  tmp->Sumw2();

  tmp->GetXaxis()->SetTitle(old->GetXaxis()->GetTitle());
  tmp->GetYaxis()->SetTitle(old->GetYaxis()->GetTitle());

  for (int i=0;i<=old->GetNbinsX()+1;i++) {
    for (int j=0;j<=old->GetNbinsY()+1;j++) {
      int ii = tmp->GetXaxis()->FindBin(old->GetXaxis()->GetBinCenter(i));
      int jj = tmp->GetYaxis()->FindBin(old->GetYaxis()->GetBinCenter(j));
      float c1 = tmp->GetBinContent(ii,jj);
      float e1 = tmp->GetBinError(ii,jj);
      float c2 = old->GetBinContent(i,j);
      float e2 = old->GetBinError(i,j);
//
// underflows and overflows *must* be discarded before the unfolding:
// inefficiencies and fakes/background are taken from the additional entries
// in the 'reco' and 'truth' histograms, respectively
//
      if (ii==0) continue;
      if (ii==tmp->GetNbinsX()+1) continue;
      if (jj==0) continue;
      if (jj==tmp->GetNbinsY()+1) continue;

      tmp->SetBinContent(ii,jj,c1+c2);
      tmp->SetBinError(ii,jj,TMath::Sqrt(e1*e1+e2*e2));
    }
  }

  tmp->SetEntries(old->GetEntries());

  old->Delete();
  tmp->SetName(name.c_str());

  return tmp;
}
Exemple #17
0
void drawICmap(const string& wwwPath = "",
	       const string& eosPath = "", 
	       const string& dirName = "", 
	       const string& iterNumber = "", 
	       const string& tagName = "") {

  gStyle->SetPalette(1, 0);  // raibow palette                                                
  gStyle->SetNumberContours(50); // default is 20 

  string filename = "root://eoscms//eos/cms" + eosPath + dirName + "/" + iterNumber + "/" + tagName + "calibMap.root";

  TFile* f = TFile::Open(filename.c_str(),"READ");
  if (!f || !f->IsOpen()) {
    cout<<"*******************************"<<endl;
    cout<<"Error opening file \""<<filename<<"\".\nApplication will be terminated."<<endl;
    cout<<"*******************************"<<endl;
    exit(EXIT_FAILURE);
  }

  TH2F *mapEB = (TH2F*) f->Get("calibMap_EB");
  TH2F *h = NULL;
  h = (TH2F*) f->Get("calibMap_EEp");
  TH2F *mapEEp = (TH2F*) h->Clone();
  h = (TH2F*) f->Get("calibMap_EEm");
  TH2F *mapEEm = (TH2F*) h->Clone();

  if (!mapEB || !mapEEp || !mapEEm) {
    cout << "Error: could not get one or more histograms. End of programme" << endl;
    exit(EXIT_FAILURE);
  }

  TH2F *mapEB_new = new TH2F("mapEB_new","EB calib coefficients", 360, 0.5, 360.5, 171,-85.5,85.5 );

  // profile along ieta. ieta goea from -85 to 85, exluding 0, for a total of 170 non empty bins (they are 171 including ieta = 0 which is actually empty)
  // in the profile, ieta = 30 is the bin with x from 29.5 to 30.5
  // simila logic for profile along iphi
  TProfile * EB_ieta_profile = new TProfile("EB_ieta_profile","EB calib coefficients - i#eta profile",171,-85.5,85.5);
  TProfile * EB_iphi_profile = new TProfile("EB_iphi_profile","EB calib coefficients - i#phi profile",360,0.5,360.5);


  Int_t nbinsX = mapEB->GetNbinsX(); // ieta
  Int_t nbinsY = mapEB->GetNbinsY(); // iphi

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

      for (Int_t j = 1; j <= nbinsY; j++) {
	
	mapEB_new->Fill(j,(i-86.0),mapEB->GetBinContent(i,j));
	EB_ieta_profile->Fill((i-86.0),mapEB->GetBinContent(i,j));
	EB_iphi_profile->Fill(j,mapEB->GetBinContent(i,j));

      }

  }

  string wwwAllPath = wwwPath + dirName + "/" + iterNumber + "/2DMaps/";
  string name = "";
  TPaletteAxis *palette = NULL;

  //EB
  TCanvas *cEB = new TCanvas("cEB","IC map EB");
  mapEB_new->Draw("COLZ");
  mapEB_new->GetXaxis()->SetTitle("i #phi");
  mapEB_new->GetXaxis()->SetTitleSize(0.06);
  mapEB_new->GetXaxis()->SetTitleOffset(0.7);
  mapEB_new->GetYaxis()->SetTitle("i #eta");
  mapEB_new->GetYaxis()->SetTitleSize(0.06);
  mapEB_new->GetYaxis()->SetTitleOffset(0.8);
  mapEB_new->GetZaxis()->SetRangeUser(0.9,1.1);
  mapEB_new->SetStats(0);
  gPad->Update();
  palette = (TPaletteAxis*)mapEB_new->GetListOfFunctions()->FindObject("palette");
  // the following lines move the palette. Choose the values you need for the position.                                                                              
  palette->SetX1NDC(0.91);
  palette->SetX2NDC(0.94);
  gPad->Modified();
  gPad->Update();
  // end of palette fixes                                                                                                                                             
  name = wwwAllPath + "Barrel/IC_calibMapEB";
  cEB->SaveAs((name + ".pdf").c_str());
  cEB->SaveAs((name + ".png").c_str());

  TCanvas *cEB_ietaProfile = new TCanvas("cEB_ietaProfile","IC map EB - i#eta profile");
  EB_ieta_profile->Draw("HIST");
  EB_ieta_profile->GetXaxis()->SetTitle("i #eta");
  EB_ieta_profile->GetXaxis()->SetTitleSize(0.06);
  EB_ieta_profile->GetXaxis()->SetTitleOffset(0.7);
  EB_ieta_profile->GetYaxis()->SetTitle("IC");
  EB_ieta_profile->GetYaxis()->SetTitleSize(0.06);
  EB_ieta_profile->GetYaxis()->SetTitleOffset(0.8);
  // Double_t maxY = EB_ieta_profile->GetBinContent(EB_ieta_profile->GetMaximumBin());
  // Double_t scale_factor = 1.1;
  // Double_t minY = 999.9; // minimum would be 0, corresponding to ieta = 0; look for minimum excluding ieta = 0
  // for (Int_t ieta = -85; ieta<= 85; ieta++) {
  //   if (ieta == 0) continue;
  //   minY = (EB_ieta_profile->GetBinContent(ieta+86) < minY) ? EB_ieta_profile->GetBinContent(ieta+86) : minY;
  // }
  // Double_t offset = scale_factor * (maxY -minY); 
  // EB_ieta_profile->GetYaxis()->SetRangeUser(minY - offset, maxY + offset);
  EB_ieta_profile->GetYaxis()->SetRangeUser(0.89,0.99);
  EB_ieta_profile->SetStats(0);
  gPad->Update();
  name = wwwAllPath + "Barrel/IC_calibMapEB_ietaProfile";
  cEB_ietaProfile->SaveAs((name + ".pdf").c_str());
  cEB_ietaProfile->SaveAs((name + ".png").c_str());


  TCanvas *cEB_iphiProfile = new TCanvas("cEB_iphiProfile","IC map EB - i#phi profile");
  EB_iphi_profile->Draw("HIST");
  EB_iphi_profile->GetXaxis()->SetTitle("i #phi");
  EB_iphi_profile->GetXaxis()->SetTitleSize(0.06);
  EB_iphi_profile->GetXaxis()->SetTitleOffset(0.7);
  EB_iphi_profile->GetYaxis()->SetTitle("IC");
  EB_iphi_profile->GetYaxis()->SetTitleSize(0.06);
  EB_iphi_profile->GetYaxis()->SetTitleOffset(0.8);
  // maxY = EB_iphi_profile->GetBinContent(EB_iphi_profile->GetMaximumBin());
  // minY = EB_iphi_profile->GetBinContent(EB_iphi_profile->GetMinimumBin()); 
  // offset = scale_factor * (maxY -minY); 
  // EB_iphi_profile->GetYaxis()->SetRangeUser(minY - offset, maxY + offset);
  EB_iphi_profile->GetYaxis()->SetRangeUser(0.91,0.97);
  EB_iphi_profile->SetStats(0);
  gPad->Update();
  name = wwwAllPath + "Barrel/IC_calibMapEB_iphiProfile";
  cEB_iphiProfile->SaveAs((name + ".pdf").c_str());
  cEB_iphiProfile->SaveAs((name + ".png").c_str());


  //EE+
  TCanvas *cEEp = new TCanvas("cEEp","IC map EE+");
  mapEEp->Draw("COLZ");
  mapEEp->GetXaxis()->SetTitle("iX");
  mapEEp->GetXaxis()->SetTitleSize(0.06);
  mapEEp->GetXaxis()->SetTitleOffset(0.7);
  mapEEp->GetYaxis()->SetTitle("iY");
  mapEEp->GetYaxis()->SetTitleSize(0.06);
  mapEEp->GetYaxis()->SetTitleOffset(0.8);
  mapEEp->GetZaxis()->SetRangeUser(0.75,1.25);
  mapEEp->SetStats(0);
  gPad->Update();
  palette = (TPaletteAxis*)mapEEp->GetListOfFunctions()->FindObject("palette");
  // the following lines move the palette. Choose the values you need for the position.                    
  palette->SetX1NDC(0.91);
  palette->SetX2NDC(0.94);
  gPad->Modified();
  gPad->Update();
  // end of palette fixes                                    
  name = wwwAllPath + "Endcap/EEp/IC_calibMapEEp";
  cEEp->SaveAs((name + ".pdf").c_str());
  cEEp->SaveAs((name + ".png").c_str());

  //EE-
  TCanvas *cEEm = new TCanvas("cEEm","IC map EE-");
  mapEEm->Draw("COLZ");
  mapEEm->GetXaxis()->SetTitle("iX");
  mapEEm->GetXaxis()->SetTitleSize(0.06);
  mapEEm->GetXaxis()->SetTitleOffset(0.7);
  mapEEm->GetYaxis()->SetTitle("iY");
  mapEEm->GetYaxis()->SetTitleSize(0.06);
  mapEEm->GetYaxis()->SetTitleOffset(0.8);
  mapEEm->GetZaxis()->SetRangeUser(0.75,1.25);
  mapEEm->SetStats(0);
  gPad->Update();
  palette = (TPaletteAxis*)mapEEm->GetListOfFunctions()->FindObject("palette");
  // the following lines move the palette. Choose the values you need for the position.                    
  palette->SetX1NDC(0.91);
  palette->SetX2NDC(0.94);
  gPad->Modified();
  gPad->Update();
  // end of palette fixes                                    
  name = wwwAllPath + "Endcap/EEm/IC_calibMapEEm";
  cEEm->SaveAs((name + ".pdf").c_str());
  cEEm->SaveAs((name + ".png").c_str());

  


}
Exemple #18
0
void jpsiAnalize(TFile* f)
{
	TH2F* h = (TH2F*)f->Get("runLumi");
	std::map<int, std::vector < int > > runs;	
	std::map<int, std::vector < int > >::iterator runsIt;
	int nBinY = h->GetNbinsY();
	int nBinX = h->GetNbinsX();
		
	std::vector <int> lumis;
	double x, y;
	//std::cout << "{";
	double prevY=0;
	double lumicount=0;
	double lumMax = 0;
	for(int i = 0; i < nBinX + 4 ;++i)
	{
		prevY=0.0;
		double runcounter = 0;
		//x = h->GetXaxis()->GetBinCenter(i);
		//std::cout << "\""<<x<<"\":[";
		double candcounter=0.;
		for(int j = 0; j< nBinY + 4; ++j)
			{
			
				int bin = h->GetBin(i,j);
				double cont = h->GetBinContent(bin);
			
				x = h->GetXaxis()->GetBinCenter(i);
				candcounter +=cont;
			
				if(cont>0.0)
				{	
					runcounter++;					
					runs[int(x)] = lumis; 
					y = h->GetYaxis()->GetBinCenter(j);	
					if(prevY<y-1 && prevY!=0.0)
					std::cout << x << " " << y << " " << prevY <<std::endl;
					prevY=y;
				}
							
			}
		//std::cout<<"], ";
		if(runcounter >0.0)		
		std::cout << x <<" -> run counter " << runcounter << " -> cand counter :" << candcounter <<std::endl; 
		lumMax = std::max(lumMax,runcounter);
	}
	//std::cout<<"}";
	
	for(int i = 0; i < nBinX + 4 ;++i)
	{
		 for(int j = 0; j< nBinY + 4; ++j)
		 {
			 x = h->GetXaxis()->GetBinCenter(i) ;
			 int bin = h->GetBin(i,j);
			 double cont = h->GetBinContent(bin);
		 	 if(cont>0.0)
			 {
				 y = h->GetYaxis()->GetBinCenter(j);  
				 runs[int(x)].push_back(int(y));
				 ++lumicount;
			 }

		 }
	}

	std::cout << "{";	
	for(runsIt=runs.begin();runsIt!=runs.end();runsIt++)
	{

		std::cout << "\""<<runsIt->first<<"\":[";
		int prevLum=0;
		for(int k = 0; k<runsIt->second.size();k++)
		{
			if(k==0)
			{
				std::cout<<"[";
				std::cout<<(runsIt->second)[k]<<", ";	
			
				if(k==runsIt->second.size()-1)
			                        {
					                                std::cout<<(runsIt->second)[k]<<"]";
							                        }

			}
			else
			if(!((runsIt->second)[k]==prevLum+1))
			{
				std::cout<<prevLum<<"], ["<<(runsIt->second)[k]<<", ";		
				if(k==runsIt->second.size()-1)
				{
					std::cout<<(runsIt->second)[k]<<"]";
				}
				
			}
			else
			{
				if(k==runsIt->second.size()-1)
					                                {
										                                        std::cout<<(runsIt->second)[k]<<"]";
															                                }
			}

			

			prevLum = (runsIt->second)[k];
		}	
			
		
		std::cout << "], ";
	}
	std::cout<<"}";
	std::cout<<std::endl;
	std::cout<<lumicount<<std::endl;
	std::cout<<lumMax<<std::endl;
}
// ****************************************************************
//XXX: main
int main(int argc, char* argv[])
{
  //
  // **** May 20 2010 update ****
  // Usage: CreateEcalTimingCalibsEE fileWithTree options...
  //

  using namespace std;
  // Ao dependent timing corrections
  timeCorrectionEE_ = new TF1("timeCorrectionEE_","pol4(0)",0,1.2);
  //coefficients obtained in the interval (0, 1.5) from Low eta region < 2.2, run 144011
  timeCorrectionEE_->SetParameters(-0.461192,0.0876435,-0.234752,0.143774,-0.051990);

  // For selection cuts
  string inBxs, inOrbits, inTrig, inTTrig, inLumi, inRuns;
  float avgTimeMin, avgTimeMax;
  float minAmpEB, minAmpEE;
  float maxE1E9, maxSwissCrossNoise;  // EB only, no spikes seen in EE
  float maxHitTimeEE, minHitTimeEE;
  // init to sensible defaults
  avgTimeMin = -1; // in ns
  avgTimeMax = 1; // in ns
  minAmpEB = 5; // GeV
  minAmpEE = 5; // GeV
  maxHitTimeEE = 15; // ns
  minHitTimeEE = -15; // ns
  maxE1E9 = 0.95; // EB only
  maxSwissCrossNoise = 0.95; // EB only
  inBxs = "-1";
  inOrbits = "-1";
  inTrig = "-1";
  inTTrig = "-1";
  inLumi = "-1";
  inRuns = "-1";

  char* infile = argv[1];
  if (!infile)
  {
    cout << " No input file specified !" << endl;
    return -1;
  }

  //TODO: Replace this with the parseArguments function from the pi0 binary
  std::string stringGenericOption    = "--";
  for (int i=1 ; i<argc ; i++) {
    if (argv[i] == std::string("-bxs") && argc>i+1) inBxs = std::string(argv[i+1]);
    if (argv[i] == std::string("-orbits") && argc>i+1) inOrbits = std::string(argv[i+1]);
    if (argv[i] == std::string("-trig") && argc>i+1) inTrig = std::string(argv[i+1]);
    if (argv[i] == std::string("-ttrig") && argc>i+1) inTTrig = std::string(argv[i+1]);
    if (argv[i] == std::string("-lumi") && argc>i+1) inLumi = std::string(argv[i+1]);
    if (argv[i] == std::string("-runs") && argc>i+1) inRuns = std::string(argv[i+1]);
    if (argv[i] == std::string("-ebampmin") && argc>i+1) minAmpEB = atof(argv[i+1]);
    if (argv[i] == std::string("-eeampmin") && argc>i+1) minAmpEE = atof(argv[i+1]);
    if (argv[i] == std::string("-e1e9max") && argc>i+1) maxE1E9 = atof(argv[i+1]);
    if (argv[i] == std::string("-swisskmax") && argc>i+1) maxSwissCrossNoise = atof(argv[i+1]);
    if (argv[i] == std::string("-avgtimemin") && argc>i+1) avgTimeMin = atof(argv[i+1]);
    if (argv[i] == std::string("-avgtimemax") && argc>i+1) avgTimeMax = atof(argv[i+1]);
    if (argv[i] == std::string("-eehittimemax") && argc>i+1) maxHitTimeEE = atof(argv[i+1]);
    if (argv[i] == std::string("-eehittimemin") && argc>i+1) minHitTimeEE = atof(argv[i+1]);
    // handle here the case of multiple arguments for input files
    if (argv[i] == std::string("--i"))// && argc>i+1)
    {
      for (int u=i+1; u<argc; u++)
      {
        if ( 0==std::string(argv[u]).find( stringGenericOption ) )
        {
          if ( 0==listOfFiles_.size())  {std::cout << "no input files listed" << std::cout;}
          else  {std::cout << "no more files listed, found: " << argv[u] << std::cout;}
          break;
        }
        else
        {
          listOfFiles_.push_back(argv[u]);
          i++;
        }
      }// loop on arguments following --i
      continue;
    }//end 'if input files'

  }
  // Open the input files
  if (listOfFiles_.size()==0){
    std::cout << "\tno input file found" << std::endl;
    return(1);
  }
  else{
    std::cout << "\tfound " << listOfFiles_.size() << " input files: " << std::endl;
    for(std::vector<std::string>::const_iterator  file_itr=listOfFiles_.begin(); file_itr!=listOfFiles_.end(); file_itr++){
      std::cout << "\t" << (*file_itr) << std::endl;
    }
  }
  // Tree construction
  TChain* chain = new TChain ("EcalTimeAnalysis") ;
  std::vector<std::string>::const_iterator file_itr;
  for(file_itr=listOfFiles_.begin(); file_itr!=listOfFiles_.end(); file_itr++){
    chain->Add( (*file_itr).c_str() );
  }


  cout << "Running with options: "
    << "avgTimeMin: " << avgTimeMin << " avgTimeMax: " << avgTimeMax
    << " minAmpEB: " << minAmpEB << " minAmpEE: " << minAmpEE
    << " maxHitTimeEE: " << maxHitTimeEE << " minHitTimeEE: " << minHitTimeEE
    << " inTrig: " << inTrig << " inTTrig: " << inTTrig << " inLumi: " << inLumi 
    << " inBxs: " << inBxs << " inRuns: " << inRuns << " inOrbits: " << inOrbits
    << endl;

  // Ignore warnings
  gErrorIgnoreLevel = 2001;

  setBranchAddresses(chain,treeVars_);

  // Generate all the vectors for skipping selections
  std::vector<std::vector<double> > bxIncludeVector;
  std::vector<std::vector<double> > bxExcludeVector;
  std::vector<std::vector<double> > orbitIncludeVector;
  std::vector<std::vector<double> > orbitExcludeVector;
  std::vector<std::vector<double> > trigIncludeVector;
  std::vector<std::vector<double> > trigExcludeVector;
  std::vector<std::vector<double> > ttrigIncludeVector;
  std::vector<std::vector<double> > ttrigExcludeVector;
  std::vector<std::vector<double> > lumiIncludeVector;
  std::vector<std::vector<double> > lumiExcludeVector;
  std::vector<std::vector<double> > runIncludeVector;
  std::vector<std::vector<double> > runExcludeVector;
  //recall: string inBxs, inOrbits, inTrig, inTTrig, inLumi, inRuns;
  genIncludeExcludeVectors(inBxs,bxIncludeVector,bxExcludeVector);
  genIncludeExcludeVectors(inOrbits,orbitIncludeVector,orbitExcludeVector);
  genIncludeExcludeVectors(inTrig,trigIncludeVector,trigExcludeVector);
  genIncludeExcludeVectors(inTTrig,ttrigIncludeVector,ttrigExcludeVector);
  genIncludeExcludeVectors(inLumi,lumiIncludeVector,lumiExcludeVector);
  genIncludeExcludeVectors(inRuns,runIncludeVector,runExcludeVector);

  // Open output file and book hists
  string fileNameBeg = "timingCalibsEE";
  string rootFilename = fileNameBeg+".root";
  TFile* outfile = new TFile(rootFilename.c_str(),"RECREATE");
  outfile->cd();

  TH1F* calibHistEE = new TH1F("timingCalibsEE","timingCalibs EE [ns]",2000,-100,100);
  TH1F* calibErrorHistEE = new TH1F("timingCalibErrorEE","timingCalibError EE [ns]",500,0,5);
  calibHistEE->Sumw2();
  calibErrorHistEE->Sumw2();

  TH2F* calibsVsErrors = new TH2F("timingCalibsAndErrors","TimingCalibs vs. errors [ns]",500,0,5,100,0,10);
  calibsVsErrors->Sumw2();

  //TH2F* calibMapEE = new TH2F("calibMapEE","time calib map EE",360,1,361,170,-86,86);
  //TH2F* calibMapEEFlip = new TH2F("calibMapEEFlip","time calib map EE",170,-86,86,360,1,361);
  //TH2F* calibMapEEPhase = new TH2F("calibMapEEPhase","time calib map EE (phase of Tmax)",360,1,361,170,-86,86);
  
  //TH2F* calibMapEtaAvgEE = new TH2F("calibMapEtaAvgEE","time calibs raw eta avg map EE",360,1,361,170,-86,86);
  //TH1F* calibHistEtaAvgEE = new TH1F("timingCalibsEtaAvgEE","EtaAvgTimingCalibs EE [ns]",2000,-100,100);

  TH2F* hitsPerCryMapEEM = new TH2F("hitsPerCryMapEEM","Hits per cry EEM;ix;iy",100,1,101,100,1,101);
  TH2F* hitsPerCryMapEEP = new TH2F("hitsPerCryMapEEP","Hits per cry EEP;ix;iy",100,1,101,100,1,101);
  TH1F* hitsPerCryHistEEM = new TH1F("hitsPerCryHistEEM","Hits per cry EEM;hashedIndex",14648,0,14648);
  TH1F* hitsPerCryHistEEP = new TH1F("hitsPerCryHistEEP","Hits per cry EEP;hashedIndex",14648,0,14648);
  //TH1C* eventsEEMHist = new TH1C("numEventsEEM","Number of events, EEM",100,0,100);
  //TH1C* eventsEEPHist = new TH1C("numEventsEEP","Number of events, EEP",100,0,100);
  TProfile* ampProfileEEM = new TProfile("ampProfileEEM","Amp. profile EEM;hashedIndex",14648,0,14648);
  TProfile* ampProfileEEP = new TProfile("ampProfileEEP","Amp. profile EEP;hashedIndex",14648,0,14648);
  TProfile2D* ampProfileMapEEP = new TProfile2D("ampProfileMapEEP","Amp. profile EEP;ix;iy",100,1,101,100,1,101);
  TProfile2D* ampProfileMapEEM = new TProfile2D("ampProfileMapEEM","Amp. profile EEM;ix;iy",100,1,101,100,1,101);

  //TH1F* eventsEEHist = new TH1F("numEventsEE","Number of events, EE",100,0,100);
  //TH1F* calibSigmaHist = new TH1F("timingSpreadEE","Crystal timing spread [ns]",1000,-5,5);

  TH1F* sigmaHistEE = new TH1F("sigmaCalibsEE"," Sigma of calib distributions EE [ns]",100,0,1);

  //TH1F* chiSquaredEachEventHist = new TH1F("chi2eachEvent","Chi2 of each event",500,0,500);
  //TH2F* chiSquaredVsAmpEachEventHist = new TH2F("chi2VsAmpEachEvent","Chi2 vs. amplitude of each event",500,0,500,750,0,750);
  //TH2F* chiSquaredHighMap = new TH2F("chi2HighMap","Channels with event #Chi^{2} > 100",360,1,361,170,-86,86);
  //TH1F* chiSquaredTotalHist = new TH1F("chi2Total","Total chi2 of all events in each crystal",500,0,500);
  //TH1F* chiSquaredSingleOverTotalHist = new TH1F("chi2SingleOverTotal","Chi2 of each event over total chi2",100,0,1);
  //TH1F* ampEachEventHist = new TH1F("energyEachEvent","Energy of all events [GeV]",1000,0,10);
  //TH1F* numPointsErasedHist = new TH1F("numPointsErased","Number of points erased per crystal",25,0,25);
  
  //TProfile2D* myAmpProfile = (TProfile2D*)EBampProfile->Clone();
  //myAmpProfile->Write();
  TH1F* expectedStatPresHistEEM = new TH1F("expectedStatPresEEM","Avg. expected statistical precision EEM [ns], all crys",200,0,2);
  TH2F* expectedStatPresVsObservedMeanErrHistEEM = new TH2F("expectedStatPresVsObsEEM","Expected stat. pres. vs. obs. error on mean each event EEM [ns]",200,0,2,200,0,2);
  TH1F* expectedStatPresEachEventHistEEM = new TH1F("expectedStatPresSingleEventEEM","Expected stat. pres. each event EEM [ns]",200,0,2);
  TH1F* expectedStatPresHistEEP = new TH1F("expectedStatPresEEP","Avg. expected statistical precision EEP [ns], all crys",200,0,2);
  TH2F* expectedStatPresVsObservedMeanErrHistEEP = new TH2F("expectedStatPresVsObsEEP","Expected stat. pres. vs. obs. error on mean each event [ns] EEP",200,0,2,200,0,2);
  TH1F* expectedStatPresEachEventHistEEP = new TH1F("expectedStatPresSingleEventEEP","Expected stat. pres. each event EEP [ns]",200,0,2);
  
  TH2F* errorOnMeanVsNumEvtsHist = new TH2F("errorOnMeanVsNumEvts","Error_on_mean vs. number of events",50,0,50,200,0,2);
  errorOnMeanVsNumEvtsHist->Sumw2();
  
  TH1F* calibHistEEM = new TH1F("timingCalibsEEM","timingCalibs EEM [ns]",500,-25,25);
  TH1F* calibHistEEP = new TH1F("timingCalibsEEP","timingCalibs EEP [ns]",500,-25,25);
  TH1F* calibErrorHistEEM = new TH1F("calibErrorEEM","timingCalibError EEM [ns]",250,0,5);
  TH1F* calibErrorHistEEP = new TH1F("calibErrorEEP","timingCalibError EEP [ns]",250,0,5);
  calibHistEEM->Sumw2();
  calibHistEEP->Sumw2();
  calibErrorHistEEM->Sumw2();
  calibErrorHistEEP->Sumw2();

  TH2F* calibMapEEM = new TH2F("calibMapEEM","time calib map EEM",100,1,101,100,1,101);
  TH2F* calibMapEEP = new TH2F("calibMapEEP","time calib map EEP",100,1,101,100,1,101);
  calibMapEEM->Sumw2();
  calibMapEEP->Sumw2();

  TH2F* sigmaMapEEM = new TH2F("sigmaMapEEM","Sigma of time calib map EEM [ns];ix;iy",100,1.,101.,100,1,101);
  TH2F* sigmaMapEEP = new TH2F("sigmaMapEEP","Sigma of time calib map EEP [ns];ix;iy",100,1.,101.,100,1,101);
  TH2F* calibErrorMapEEM = new TH2F("calibErrorMapEEM","Error of time calib map EEM [ns];ix;iy",100,1.,101.,100,1,101);
  TH2F* calibErrorMapEEP = new TH2F("calibErrorMapEEP","Error of time calib map EEP [ns];ix;iy",100,1.,101.,100,1,101);

  TDirectory* cryDirEEP = gDirectory->mkdir("crystalTimingHistsEEP");
  cryDirEEP->cd();
  TH1C* cryTimingHistsEEP[100][100]; // [0][0] = ix 1, iy 1
  for(int x=0; x < 100; ++x)
  {
    for(int y=0; y < 100; ++y)
    {
      if(!EEDetId::validDetId(x+1,y+1,1))
        continue;
      string histname = "EEP_cryTiming_ix";
      histname+=intToString(x+1);
      histname+="_iy";
      histname+=intToString(y+1);
      cryTimingHistsEEP[x][y] = new TH1C(histname.c_str(),histname.c_str(),660,-33,33);
      cryTimingHistsEEP[x][y]->Sumw2();
    }
  }
  outfile->cd();
  TDirectory* cryDirEEM = gDirectory->mkdir("crystalTimingHistsEEM");
  cryDirEEM->cd();
  TH1C* cryTimingHistsEEM[100][100]; // [0][0] = ix 1, iy 1
  for(int x=0; x < 100; ++x)
  {
    for(int y=0; y < 100; ++y)
    {
      if(!EEDetId::validDetId(x+1,y+1,-1))
        continue;
      string histname = "EEM_cryTiming_ix";
      histname+=intToString(x+1);
      histname+="_iy";
      histname+=intToString(y+1);
      cryTimingHistsEEM[x][y] = new TH1C(histname.c_str(),histname.c_str(),660,-33,33);
      cryTimingHistsEEM[x][y]->Sumw2();
    }
  }
  outfile->cd();
  
  cout << "Making calibs..." << endl;

  CrystalCalibration* eeCryCalibs[14648];
  //XXX: Making calibs with weighted/unweighted mean
  for(int i=0; i < 14648; ++i)
    eeCryCalibs[i] = new CrystalCalibration(); //use weighted mean!
    //eeCryCalibs[i] = new CrystalCalibration(false); //don't use weighted mean!

  cout << "Looping over TTree...";

  // Loop over the TTree
  int numEventsUsed = 0;
  int nEntries = chain->GetEntries();
  cout << "Begin loop over TTree." << endl;

  for(int entry = 0; entry < nEntries; ++entry)
  {
    chain->GetEntry(entry);

    // Loop once to calculate average event time
    float sumTime = 0;
    int numCrysEE = 0;
    for(int bCluster=0; bCluster < treeVars_.nClusters; bCluster++)
    {
      if(treeVars_.xtalInBCIEta[bCluster][0] != -999999) continue; // skip EB clusters
      for(int cryInBC=0; cryInBC < treeVars_.nXtalsInCluster[bCluster]; cryInBC++)
      {
        sumTime += treeVars_.xtalInBCTime[bCluster][cryInBC];
        numCrysEE++;
      }
    }
    //debug
    //cout << "Number of EE crys in event: " << numEEcrys << endl;

    //XXX: Event cuts
    if(sumTime/numCrysEE > avgTimeMax || sumTime/numCrysEE < avgTimeMin)
    {
      //cout << "Average event time: " << sumTime/numCrysEE  << " so event rejected." << endl;
      continue;
    }
    // check BX, orbit, lumi, run, L1 tech/phys triggers
    bool keepEvent = includeEvent(treeVars_.bx,bxIncludeVector,bxExcludeVector)
      && includeEvent(treeVars_.orbit,orbitIncludeVector,orbitExcludeVector)
      && includeEvent(treeVars_.lumiSection,lumiIncludeVector,lumiExcludeVector)
      && includeEvent(treeVars_.runId,runIncludeVector,runExcludeVector)
      && includeEvent(treeVars_.l1ActiveTriggers,
          treeVars_.l1NActiveTriggers,trigIncludeVector,trigExcludeVector)
      && includeEvent(treeVars_.l1ActiveTechTriggers,
          treeVars_.l1NActiveTechTriggers,ttrigIncludeVector,ttrigExcludeVector);
    if(!keepEvent)
      continue;
      
    numEventsUsed++;

    // Loop over the EE crys and fill the map
    for(int bCluster=0; bCluster < treeVars_.nClusters; bCluster++)
    {
      if(treeVars_.xtalInBCIEta[bCluster][0] != -999999) continue; // skip EB clusters
      for(int cryInBC=0; cryInBC < treeVars_.nXtalsInCluster[bCluster]; cryInBC++)
      {
        int hashedIndex = treeVars_.xtalInBCHashedIndex[bCluster][cryInBC];
        float cryTime = treeVars_.xtalInBCTime[bCluster][cryInBC];
        float cryTimeError = treeVars_.xtalInBCTimeErr[bCluster][cryInBC];
        float cryAmp = treeVars_.xtalInBCAmplitudeADC[bCluster][cryInBC];
	float Ao = cryAmp/sigmaNoiseEE;
	float AoLog = log10(Ao/25);

        EEDetId det = EEDetId::unhashIndex(hashedIndex);
        if(det==EEDetId()) // make sure DetId is valid
          continue;

        int ix = det.ix();
        int iy = det.iy();

        //XXX: RecHit cuts
        bool keepHit = cryAmp >= minAmpEE
          && cryTime > minHitTimeEE
          && cryTime < maxHitTimeEE
	  && AoLog > 0
          && AoLog < 1.2;
        if(!keepHit)
          continue;

        //cout << "STUPID DEBUG: " << hashedIndex << " cryTime: " << cryTime << " cryTimeError: " << cryTimeError << " cryAmp: " << cryAmp << endl;

	// Timing correction to take out the energy dependence if log10(ampliOverSigOfThis/25)
        // is between 0 and 1.2 (about 1 and 13 GeV)
	// amplitude dependent timing corrections
        float timing = cryTime - timeCorrectionEE_->Eval(AoLog);
        //FIXME
        cryTimeError = 1;
        eeCryCalibs[hashedIndex]->insertEvent(cryAmp,timing,cryTimeError,false);

        //SIC Use when we don't have time_error available
        //eeCryCalibs[hashedIndex]->insertEvent(cryAmp,cryTime,35/(cryAmp/1.2),false);
        if(det.zside() < 0)
        {
          ampProfileEEM->Fill(hashedIndex,cryAmp);
          ampProfileMapEEM->Fill(ix,iy,cryAmp);
        }
        else
        {
          ampProfileEEP->Fill(hashedIndex,cryAmp);
          ampProfileMapEEP->Fill(ix,iy,cryAmp);
        }
      }
    }
  }

  //create output text file
  ofstream fileStream;
  string fileName = fileNameBeg+".calibs.txt";
  fileStream.open(fileName.c_str());
  if(!fileStream.good() || !fileStream.is_open())
  {
    cout << "Couldn't open text file." << endl;
    return -1;
  }
  //create problem channels text file
  ofstream fileStreamProb;
  string fileName2 = fileNameBeg+".problems.txt";
  fileStreamProb.open(fileName2.c_str());
  if(!fileStreamProb.good() || !fileStreamProb.is_open())
  {
    cout << "Couldn't open text file." << endl;
    return -1;
  }

  // Create calibration container objects
  EcalTimeCalibConstants timeCalibConstants;
  EcalTimeCalibErrors timeCalibErrors;

  cout << "Using " << numEventsUsed << " out of " << nEntries << " in the tree." << endl;
  cout << "Creating calibs..." << endl;
  float cryCalibAvg = 0;
  int numCrysCalibrated = 0;
  vector<int> hashesToCalibrateToAvg;
  //Loop over all the crys
  for(int hashedIndex=0; hashedIndex < 14648; ++hashedIndex)
  {
    EEDetId det = EEDetId::unhashIndex(hashedIndex);
    if(det==EEDetId())
      continue;
    CrystalCalibration cryCalib = *(eeCryCalibs[hashedIndex]);
    int x = det.ix();
    int y = det.iy();

    //chiSquaredTotalHist->Fill(cryCalib.totalChi2);
    //expectedStatPresHistEB->Fill(sqrt(1/expectedPresSumEB));
    //expectedStatPresVsObservedMeanErrHistEB->Fill(sigmaM,sqrt(1/expectedPresSumEB));

    //XXX: Filter events at default 0.5*meanE threshold
    cryCalib.filterOutliers();
    
    //numPointsErasedHist->Fill(numPointsErased);
    
    //Write cryTimingHists
    vector<TimingEvent> times = cryCalib.timingEvents;
    for(vector<TimingEvent>::const_iterator timeItr = times.begin();
        timeItr != times.end(); ++timeItr)
    {
      if(det.zside() < 0)
      {
        float weight = 1/((timeItr->sigmaTime)*(timeItr->sigmaTime));
        cryTimingHistsEEM[x-1][y-1]->Fill(timeItr->time,weight);
      }
      else
      {
        float weight = 1/((timeItr->sigmaTime)*(timeItr->sigmaTime));
        cryTimingHistsEEP[x-1][y-1]->Fill(timeItr->time,weight);
      }
    }
    if(det.zside() < 0)
    {
      cryDirEEM->cd();
      cryTimingHistsEEM[x-1][y-1]->Write();
    }
    else
    {
      cryDirEEP->cd();
      cryTimingHistsEEP[x-1][y-1]->Write();
    }
    outfile->cd();

    if(det.zside() < 0)
    {
      hitsPerCryHistEEM->SetBinContent(hashedIndex+1,cryCalib.timingEvents.size());
      hitsPerCryMapEEM->Fill(x,y,cryCalib.timingEvents.size());
    }
    else
    {
      hitsPerCryHistEEP->SetBinContent(hashedIndex+1,cryCalib.timingEvents.size());
      hitsPerCryMapEEP->Fill(x,y,cryCalib.timingEvents.size());
    }
    
    // Make timing calibs
    double p1 = cryCalib.mean;
    double p1err = cryCalib.meanE;
    //cout << "cry ieta: " << ieta << " cry iphi: " << iphi << " p1: " << p1 << " p1err: " << p1err << endl;
    if(cryCalib.timingEvents.size() < 10)
    {
      fileStreamProb << "Cry (only " << cryCalib.timingEvents.size() << " events) was calibrated to avg: " << det.zside() << ", "
                                                                                        << x <<", " << y << ", hash: "
                                                                        << hashedIndex
                                                                          << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
      hashesToCalibrateToAvg.push_back(hashedIndex);
      continue;
    }
    // Make it so we can add calib to reco time
    p1*=-1;
    if(p1err < 0.5 && p1err > 0)
    {
      fileStream << "EE\t" << hashedIndex << "\t" << p1 << "\t\t" << p1err << endl;
      if(det.zside() < 0)
      {
        calibHistEEM->Fill(p1);
        //calibMapEEMFlip->Fill(y-85,x+1,p1);
        calibMapEEM->Fill(x,y,p1);
        //calibMapEEMPhase->Fill(x+1,y-85,p1/25-floor(p1/25));
        //errorOnMeanVsNumEvtsHist->Fill(times.size(),p1err);
      }
      else
      {
        calibHistEEP->Fill(p1);
        //calibMapEEPFlip->Fill(y-85,x+1,p1);
        calibMapEEP->Fill(x,y,p1);
        //calibMapEEPPhase->Fill(x+1,y-85,p1/25-floor(p1/25));
        //errorOnMeanVsNumEvtsHist->Fill(times.size(),p1err);
      }
      cryCalibAvg+=p1;
      ++numCrysCalibrated;
      //Store in timeCalibration container
      EcalTimeCalibConstant tcConstant = p1;
      EcalTimeCalibError tcError = p1err;
      uint32_t rawId = EEDetId::unhashIndex(hashedIndex);
      timeCalibConstants[rawId] = tcConstant;
      timeCalibErrors[rawId] = tcError;
    }
    else
    {
      //std::cout << "Cry: " << y <<", " << x << ", hash: " << itr->first
      //  << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
      fileStreamProb << "Cry was calibrated to avg: " << x <<", " << y << ", hash: " << hashedIndex
        << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
    }

    sigmaHistEE->Fill(cryCalib.stdDev);
    if(det.zside() < 0)
    {
      //calibsVsErrorsEEM->Fill(p1err, p1 > 0 ? p1 : -1*p1);
      calibErrorHistEEM->Fill(p1err);
      calibErrorMapEEM->Fill(x,y,p1err);
      sigmaMapEEM->Fill(x,y,cryCalib.stdDev);
    }
    else
    {
      //calibsVsErrorsEEP->Fill(p1err, p1 > 0 ? p1 : -1*p1);
      calibErrorHistEEP->Fill(p1err);
      calibErrorMapEEP->Fill(x,y,p1err);
      sigmaMapEEP->Fill(x,y,cryCalib.stdDev);
    }
  }
  
  fileStream.close();
  fileStreamProb.close();
  // Calc average
  if(numCrysCalibrated > 0)
    cryCalibAvg/=numCrysCalibrated;
  cryCalibAvg-= 2.0833; // Global phase shift
  // calibrate uncalibratable crys
  for(vector<int>::const_iterator hashItr = hashesToCalibrateToAvg.begin();
      hashItr != hashesToCalibrateToAvg.end(); ++hashItr)
  {
    //Store in timeCalibration container
    EcalTimeCalibConstant tcConstant = cryCalibAvg;
    EcalTimeCalibError tcError = 999;
    uint32_t rawId = EEDetId::unhashIndex(*hashItr);
    timeCalibConstants[rawId] = tcConstant;
    timeCalibErrors[rawId] = tcError;
  }

  //Write XML files
  cout << "Writing XML files." << endl;
  EcalCondHeader header;
  header.method_="testmethod";
  header.version_="testversion";
  header.datasource_="testdata";
  header.since_=123;
  header.tag_="testtag";
  header.date_="Mar 24 1973";
  string timeCalibFile = "EcalTimeCalibsEE.xml";
  string timeCalibErrFile = "EcalTimeCalibErrorsEE.xml";
  // Hack to prevent seg fault
  EcalTimeCalibConstant tcConstant = 0;
  EcalTimeCalibError tcError = 0;
  uint32_t rawId = EBDetId::unhashIndex(0);
  timeCalibConstants[rawId] = tcConstant;
  timeCalibErrors[rawId] = tcError;
  // End hack
  EcalTimeCalibConstantsXMLTranslator::writeXML(timeCalibFile,header,timeCalibConstants);
  EcalTimeCalibErrorsXMLTranslator::writeXML(timeCalibErrFile,header,timeCalibErrors);

  cout << "Writing histograms." << endl;
  outfile->cd();
  calibHistEEM->SetXTitle("timingCalib [ns]");
  calibHistEEM->Write();
  calibHistEEP->SetXTitle("timingCalib [ns]");
  calibHistEEP->Write();
  calibErrorHistEEP->SetXTitle("uncertainty on mean [ns]");
  calibErrorHistEEP->Write();
  calibErrorHistEEM->SetXTitle("uncertainty on mean [ns]");
  calibErrorHistEEM->Write();
  calibErrorMapEEP->Write();
  calibErrorMapEEM->Write();
  sigmaHistEE->Write();
  sigmaMapEEM->Write();
  sigmaMapEEP->Write();

  //can->Print("calibs1D.png");
  //cout << "Writing calibVsErrors" << endl;
  //calibsVsErrors->SetYTitle("AbsCalibConst");
  //calibsVsErrors->SetXTitle("calibConstError");
  //calibsVsErrors->Write();

  //Move empty bins out of the way
  int nxbins = calibMapEEM->GetNbinsX();
  int nybins = calibMapEEM->GetNbinsY();
  for(int i=0;i<=(nxbins+2)*(nybins+2); ++i)
  {
    double binentsM = calibMapEEM->GetBinContent(i);
    if(binentsM==0)
    {
      calibMapEEM->SetBinContent(i,-1000);
    }
    double binentsP = calibMapEEP->GetBinContent(i);
    if(binentsP==0)
    {
      calibMapEEP->SetBinContent(i,-1000);
    }
  }
  calibMapEEM->SetXTitle("ix");
  calibMapEEM->SetYTitle("iy");
  calibMapEEM->Write();
  calibMapEEP->SetXTitle("ix");
  calibMapEEP->SetYTitle("iy");
  calibMapEEP->Write();

  //calibSigmaHist->SetXTitle("#sigma_{cryTime} [ns]");
  //calibSigmaHist->Write();
  
  // Old hist, commented Jun 15 2009
  //avgAmpVsSigmaTHist->SetXTitle("#sigma_{cryTime} [ns]");
  //avgAmpVsSigmaTHist->SetYTitle("Avg. amp. [adc]");
  //avgAmpVsSigmaTHist->Write();
 
  //errorOnMeanVsNumEvtsHist->SetXTitle("Events");
  //errorOnMeanVsNumEvtsHist->SetYTitle("Error_on_mean [ns]");
  //TProfile* theProf = (TProfile*) errorOnMeanVsNumEvtsHist->ProfileX();
  //TF1* myFit = new TF1("myFit","[0]/sqrt(x)+[1]",0,50);
  //myFit->SetRange(0,50);
  ////theProf->Fit("myFit");
  //theProf->Write();
  //errorOnMeanVsNumEvtsHist->Write();
  //
  //chiSquaredEachEventHist->Write();
  //chiSquaredVsAmpEachEventHist->SetXTitle("amplitude [ADC]");
  //chiSquaredVsAmpEachEventHist->SetYTitle("#Chi^{2}");
  //chiSquaredVsAmpEachEventHist->Write();
  //chiSquaredHighMap->SetXTitle("iphi");
  //chiSquaredHighMap->SetYTitle("ieta");
  //chiSquaredHighMap->Write();
  //chiSquaredTotalHist->Write();
  //chiSquaredSingleOverTotalHist->Write();

  expectedStatPresHistEEM->Write();
  expectedStatPresVsObservedMeanErrHistEEM->Write();
  expectedStatPresEachEventHistEEM->Write();
  expectedStatPresHistEEP->Write();
  expectedStatPresVsObservedMeanErrHistEEP->Write();
  expectedStatPresEachEventHistEEP->Write();
  //ampEachEventHist->Write();
  //numPointsErasedHist->Write();
  hitsPerCryHistEEP->Write();
  hitsPerCryMapEEP->Write();
  hitsPerCryHistEEM->Write();
  hitsPerCryMapEEM->Write();
  ampProfileEEP->Write();
  ampProfileMapEEP->Write();
  ampProfileEEM->Write();
  ampProfileMapEEM->Write();
  
  //cout << "All done!  Close input." << endl;
  //f->Close();
  //cout << "Close output and quit!" << endl;
  outfile->Close();
  cout << "done." << endl;
}
void draw_mSUGRA_exclusion(TH2F *ocrosssection, TH2F *oFilterEfficiency, TH2F *oabsXS, TH2F *limitmap, TH2F *expmap, TH2F *expplusmap, TH2F *expminusmap, TH2F *exp2plusmap, TH2F *exp2minusmap, bool isobserved) {
  TH2F *crosssection = (TH2F*)ocrosssection->Clone("crosssection");
//  TH2F *limitmap = (TH2F*)olimitmap->Clone(((string)olimitmap->GetName()+"clone").c_str());
  TH2F *cleanhisto = (TH2F*)limitmap->Clone("clean");
  for(int ix=1;ix<=cleanhisto->GetNbinsX();ix++) {
    for(int iy=1;iy<=cleanhisto->GetNbinsY();iy++) {
      cleanhisto->SetBinContent(ix,iy,0);
    }
  }
  
  
  TH2F *FilterEfficiency;
  TH2F *absXS;

  
  
  
  write_warning(__FUNCTION__,"You'll want to switch off 'wrongwaytodothis')");
  
  if(wrongwaytodothis) {
    //this part is the one you want to remove.
    TFile *Efficiencies = new TFile("FilterEfficiencyv3.root");
    FilterEfficiency = cast_into_shape((TH2F*) Efficiencies->Get("FilterEfficiency"),limitmap);
    assert(FilterEfficiency);
    assert(crosssection);
    absXS=(TH2F*)crosssection->Clone("absXS");
    crosssection->Multiply(FilterEfficiency);
  } else {
    //this part is the one you want to keep!
    FilterEfficiency=(TH2F*)oFilterEfficiency->Clone("FilterEfficiency");
    absXS=(TH2F*)oabsXS->Clone("absXS");
  }
    
  

  TH2F *limits = (TH2F*)limitmap->Clone("limits");
  set_range(limits,true,false);
  limitmap->Divide(crosssection);
  expminusmap->Divide(crosssection);
  expplusmap->Divide(crosssection);
  exp2minusmap->Divide(crosssection);
  exp2plusmap->Divide(crosssection);
  expmap->Divide(crosssection);
  TGraph *observed = get_mSUGRA_exclusion_line(limitmap, PlottingSetup::mSUGRA);
  observed->SetLineColor(kRed);
  TGraph *expminus = get_mSUGRA_exclusion_line(expminusmap, PlottingSetup::mSUGRA);
  TGraph *expplus  = get_mSUGRA_exclusion_line(expplusmap, PlottingSetup::mSUGRA);
  TGraph *exp2minus;
  if(draw2sigma) exp2minus = get_mSUGRA_exclusion_line(exp2minusmap, PlottingSetup::mSUGRA);
  TGraph *exp2plus;
  if(draw2sigma) exp2plus = get_mSUGRA_exclusion_line(exp2plusmap, PlottingSetup::mSUGRA);

  TGraph *expected = new TGraph(expminus->GetN()+expplus->GetN());
  TGraph *expected2; 
  if(draw2sigma) expected2 = new TGraph(exp2minus->GetN()+exp2plus->GetN());
  for(int i=0;i<=expminus->GetN();i++) {
    Double_t x,y;
    expminus->GetPoint(i,x,y);
    expected->SetPoint(i,x,y);
  }
    
  for(int i=0;i<=exp2minus->GetN();i++) {
    Double_t x,y;
    exp2minus->GetPoint(i,x,y);
    expected2->SetPoint(i,x,y);
  }
  for(int i=exp2plus->GetN()-1;i>=0;i--) {
    Double_t x,y;
    exp2plus->GetPoint(i,x,y);
    expected2->SetPoint(exp2minus->GetN()+(exp2plus->GetN()-i),x,y);
  }
  for(int i=expplus->GetN()-1;i>=0;i--) {
    Double_t x,y;
    expplus->GetPoint(i,x,y);
    expected->SetPoint(expminus->GetN()+(expplus->GetN()-i),x,y);
  }
  expected->SetFillColor(TColor::GetColor("#9FF781"));
  if(draw2sigma) expected2->SetFillColor(TColor::GetColor("#F3F781"));
  
  smooth_line(observed);
  smooth_line(expected);
  if(draw2sigma) smooth_line(expected2);
  
  TCanvas *te = new TCanvas("te","te");
  te->SetRightMargin(standardmargin);
//  decorate_mSUGRA(cleanhisto,te,expected,expected2,observed);
  TH2F *noh = new TH2F("noh","noh",1,1,2,1,1,2);
  SugarCoatThis(te,10,noh,observed);
//  expected->Draw("c");
//  observed->Draw("c");
  stringstream saveas;
  if((int)((string)limitmap->GetName()).find("limitmap")>0) {
    saveas << "Limits/";
    if(!isobserved) saveas << "expected/expected_";
    saveas << "final_exclusion_for_JZB_geq_" << ((string)limitmap->GetName()).substr(((string)limitmap->GetName()).find("limitmap")+8,10);
  } else {
    saveas << "Limits/";
    if(!isobserved) saveas << "expected/expected";
    saveas << "final_exclusion_for_bestlimits";
  }
  CompleteSave(te,saveas.str());
  delete te;
  
  TCanvas *overview = new TCanvas("overview","overview",1500,1000);
  
  set_range(crosssection,true,false);
  set_range(limits,true,false);
  set_range(limitmap,true,false);
  
  overview->Divide(3,2);
  overview->cd(1);
  overview->cd(1)->SetLogz(1);
  absXS->GetZaxis()->SetRangeUser(0.0001,100);
  absXS->Draw("COLZ");
  TText *title0 = write_title("Cross Section");
  title0->Draw("same");
  overview->cd(2);
  FilterEfficiency->GetZaxis()->SetRangeUser(0.01,0.7);
  FilterEfficiency->Draw("COLZ");
  TText *title0aa = write_title("Filter #epsilon");
  title0aa->Draw("same");
  overview->cd(3);
  overview->cd(3)->SetLogz(1);
  crosssection->GetZaxis()->SetRangeUser(0.0001,100);
  crosssection->Draw("COLZ");
  TText *title0a = write_title("Filter #epsilon x Cross Section");
  title0a->Draw("same");
  
  overview->cd(4);
  overview->cd(4)->SetLogz(1);
  limits->GetZaxis()->SetRangeUser(0.01,100);
  limits->Draw("COLZ");
  TText *title1 = write_title("Cross Section Upper Limit");
  title1->Draw("same");
  overview->cd(5);
  limitmap->Draw("COLZ");
  TText *title2 = write_title("UL/XS");
  title2->Draw("same");
  observed->Draw("c");
  overview->cd(6);
  overview->cd(6)->SetRightMargin(standardmargin);
//  decorate_mSUGRA(cleanhisto,overview->cd(4),expected,expected2,observed);
  SugarCoatThis(overview->cd(6),10,noh,observed);
//  observed->Draw("c");
  stringstream saveas2;
  if((int)((string)limitmap->GetName()).find("limitmap")>0) {
    saveas2 << "Limits/";
    if(!isobserved) saveas << "expected/expected_";
    saveas2 << "exclusion_overview_for_JZB_geq_" << ((string)limitmap->GetName()).substr(((string)limitmap->GetName()).find("limitmap")+8,10);
  } else {
    saveas2 << "Limits/";
    if(!isobserved) saveas << "expected/expected_";
    saveas2 << "exclusion_overview_for_bestlimits";
  }
  CompleteSave(overview,saveas2.str());
  delete overview;
  delete noh;
  delete crosssection;
  delete absXS;
  delete FilterEfficiency;
  
}
void make_SMS_exclusion(TH2F *rawlimits,TH2F *xsec,int scantype,std::string& scanx, bool isobserved) {
  TH2F *limits = prep_histo(rawlimits,scantype); // this is to be independent of the style used at creation time
  //here we get some limits and the cross section; we want to make an exclusion plot!
  TH2F *rellimits = (TH2F*)limits->Clone("rellimits");
  TH2F *rellimitsd3 = (TH2F*)limits->Clone("rellimitsd3"); // one third the cross section ("divided by 3" -> d3)
  TH2F *rellimitst3 = (TH2F*)limits->Clone("rellimitst3"); // three times the cross section ("times 3" -> t3)
  
  if(!xsec ) {
    cout << "Watch out, cross section map is invalid!" << endl;
    delete limits;
    return;
  }
  
  rellimits->Divide(xsec);
  
  
  for(int i=1;i<=rellimits->GetNbinsX();i++) {
    for(int j=1;j<=rellimits->GetNbinsY();j++) {
      rellimitst3->SetBinContent(i,j,(rellimits->GetBinContent(i,j))/3.0);
      rellimitsd3->SetBinContent(i,j,(rellimits->GetBinContent(i,j))*3.0);
    }
  }
  

//  TH2F *exclusionshape = make_exclusion_shape(rellimits,1);
//  TH2F *exclusionshapet3 = make_exclusion_shape(rellimitst3,2);
//  TH2F *exclusionshaped3 = make_exclusion_shape(rellimitsd3,3);
  
  //Now let's produce the plots!
  
  set_range(xsec,scantype,false);
  set_range(limits,scantype,false);
  limits->GetZaxis()->SetRangeUser(limits_lower_bound,limits_upper_bound);
  
  bool drawdoubleline=false; //draw nice thin line on top of thick outer line
  TGraph *exclline = MarcosExclusionLine(rellimits, scantype);
  TGraph *thinexcline = thin_line(exclline);
  
  TGraph *excllinet3 = MarcosExclusionLine(rellimitst3, scantype);
  excllinet3->SetLineStyle(2);
  TGraph *thinexclinet3 = thin_line(excllinet3);

  TGraph *excllined3 = MarcosExclusionLine(rellimitsd3, scantype);
  excllined3->SetLineStyle(3);
  TGraph *thinexclined3 = thin_line(excllined3);

//  produce_extensive_plots(xsec,limits,rellimits, rellimitst3, rellimitsd3,scantype);
  
  TCanvas *finalcanvas = new TCanvas("finalcanvas","finalcanvas");
  finalcanvas->SetLogz(1);
  finalcanvas->cd();
  limits->SetZTitle("95% CL upper limit on #sigma [pb]");
  limits->Draw("COLZ");

  TLine *desertline;
  if(drawefficiencydesertline) {
	desertline = new TLine(375,50,1200,875);
	desertline->SetLineWidth(3);
	//desertline->SetLineWidth(4); // paper style
	desertline->SetLineColor(kBlack);
	desertline->Draw("same");
  }


//  fill_with_text(exclline,excllined3,excllinet3,finalcanvas,scantype,scanx);
  stringstream real;
  real << "Limits/";
  if(!isobserved) real << "expected/expected_";
  real << "final_exclusion__" << limits->GetName();
  
  if(Contains(limits->GetName(),"bestlimits")) {
    cout << "----------> " << limits->GetName() << endl;
    TFile *f = new TFile("limits.root","RECREATE");
    thinexcline->SetName("ExclusionLine");
    limits->SetName("UpperLimits");
    limits->Write();
    thinexcline->Write();
    f->Close();
  }
  
  
  exclline->Draw("l");
  if(drawdoubleline) thinexcline->Draw("");
  excllinet3->Draw("");
  if(drawdoubleline) thinexclinet3->Draw("");
  excllined3->Draw("");
  if(drawdoubleline) thinexclined3->Draw("");
  
  CompleteSave(finalcanvas,real.str());

  
  
  //-------------------------------------- extensive plots 
  
  TCanvas *ca = new TCanvas("ca","ca",2400,1200);
  ca->Divide(4,2);
  ca->cd(1);
  ca->cd(1)->SetLogz(1);
  xsec->GetZaxis()->SetRangeUser(0.001,1000);
  xsec->Draw("COLZ");
  TText *title0 = write_title("Reference Cross Section");
  title0->Draw("same");
  ca->cd(2);
  ca->cd(2)->SetLogz(1);
  limits->GetZaxis()->SetRangeUser(limits_lower_bound,limits_upper_bound);
  limits->Draw("COLZ");
  TText *title = write_title("Cross Section Upper Limit");
  title->Draw("same");
  ca->cd(3);
  ca->cd(3)->SetLogz(1);
  TH2F *limit_ref = (TH2F*)limits->Clone("limit_ref");
  limit_ref->Divide(xsec);
  limit_ref->GetZaxis()->SetRangeUser(limits_ratio_lower_bound,limits_ratio_upper_bound);
  limit_ref->Draw("COLZ");
  TText *title2 = write_title("Cross Section UL / XS");
  title2->Draw("same");
  ca->cd(4);
  ca->cd(4)->SetLogz(1);
  limits->SetTitle("");
  limits->GetZaxis()->SetRangeUser(limits_lower_bound,limits_upper_bound);
  limits->SetZTitle("95% CL upper limit on #sigma [pb]");

  limits->Draw("COLZ");


  ca->cd(4);
  exclline->Draw();
  thinexcline->Draw();
  excllinet3->Draw();
  thinexclinet3->Draw();
  excllined3->Draw();
  thinexclined3->Draw();
  stringstream partial;
  partial << "Limits/";
  if(!isobserved) real << "expected/expected_";
  partial << "exclusion__" << limits->GetName();
  fill_with_text(exclline,excllined3,excllinet3,ca->cd(4),scantype);
//  CompleteSave(ca,partial.str());

  ca->cd(5);
  (hardlimit(rellimitsd3))->Draw("COL");
  TText *c = write_title("Exclusion shape for #sigma_{ref}/3");
  c->Draw();
  excllined3->Draw("same");
  
  ca->cd(6);
  (hardlimit(rellimits))->Draw("COL");
  exclline->Draw("same");
  TText *b = write_title("Exclusion shape for #sigma_{ref}");
  b->Draw();
  
  ca->cd(7);
  (hardlimit(rellimitst3))->Draw("COL");
  excllinet3->Draw("same");
  TText *a = write_title("Exclusion shape for 3x#sigma_{ref}");
  a->Draw();
  
  CompleteSave(ca,partial.str()+"__PlusInfo");
  delete ca;
  delete limits;
  
  //---------------------------------------</extensive plots>
  delete finalcanvas;
}
void draw_network(TDirectory* d)
{
   Bool_t __PRINT_LOGO__ = kTRUE;

   // create canvas
   TStyle* TMVAStyle = gROOT->GetStyle("TMVA"); // the TMVA style
   Int_t canvasColor = TMVAStyle->GetCanvasColor(); // backup
   TMVAStyle->SetCanvasColor( c_DarkBackground );

   static icanvas = -1;
   icanvas++;
   TCanvas* c = new TCanvas( Form( "c%i", icanvas ), Form("Neural Network Layout for: %s", d->GetName()), 
                             100 + (icanvas)*40, 0 + (icanvas+1)*20, 1000, 650  );

   TIter next = d->GetListOfKeys();
   TKey *key;
   TString hName = "weights_hist";
   Int_t numHists = 0;

   // loop over all histograms with hName in name
   while (key = (TKey*)next()) {
      TClass *cl = gROOT->GetClass(key->GetClassName());
      if (!cl->InheritsFrom("TH2F")) continue;    
      TH2F *h = (TH2F*)key->ReadObj();    
      if (TString(h->GetName()).Contains( hName )) {
         numHists++;
      }
   }

   // loop over all histograms with hName in name again
   next.Reset();
   Double_t maxWeight = 0;

   // find max weight
   while (key = (TKey*)next()) {

      //cout << "Title: " << key->GetTitle() << endl;
      TClass *cl = gROOT->GetClass(key->GetClassName());
      if (!cl->InheritsFrom("TH2F")) continue;    

      TH2F* h = (TH2F*)key->ReadObj();    
      if (TString(h->GetName()).Contains( hName )){
 
         Int_t n1 = h->GetNbinsX();
         Int_t n2 = h->GetNbinsY();
         for (Int_t i = 0; i < n1; i++) {
            for (Int_t j = 0; j < n2; j++) {
               Double_t weight = TMath::Abs(h->GetBinContent(i+1, j+1));
               if (maxWeight < weight) maxWeight = weight;
            }
         }
      }
   }

   // draw network
   next.Reset();
   Int_t count = 0;
   while (key = (TKey*)next()) {

      TClass *cl = gROOT->GetClass(key->GetClassName());
      if (!cl->InheritsFrom("TH2F")) continue;    

      TH2F* h = (TH2F*)key->ReadObj();    
      if (TString(h->GetName()).Contains( hName )){
         draw_layer(c, h, count++, numHists+1, maxWeight);
      }
   }

   draw_layer_labels(numHists+1);

   // ============================================================
   if (__PRINT_LOGO__) TMVAGlob::plot_logo();
   // ============================================================  

   c->Update();

   TString fname = "plots/network";
   TMVAGlob::imgconv( c, fname );

   TMVAStyle->SetCanvasColor( canvasColor );
}
Exemple #23
0
void PlotEvolutionsWIII(const TString &sim, UInt_t mask = 3, const TString &options="png") { 
  
#ifdef __CINT__  
  gSystem->Load("libptools.so");
#endif

  string imask = DecToBin(mask);
  cout << Form("\n Plotting Evolultion with mask: %s",imask.c_str()) << endl; 

  PGlobals::Initialize();
  
  // Palettes!
  gROOT->Macro("PPalettes.C");

  TString opt = options;
  
  // More makeup            
  Float_t margins[4] = {0.15,0.15,0.20,0.10};
  gStyle->SetPadLeftMargin(margins[0]);  // Margin left axis  
  gStyle->SetPadRightMargin(margins[2]);
  gStyle->SetPadTopMargin(margins[3]);  // Margin left axis  
  gStyle->SetPadBottomMargin(margins[1]);

  gStyle->SetPadTickX(0);
  gStyle->SetPadTickY(0);


  if(opt.Contains("grid")) {
    gStyle->SetPadGridX(1);
    gStyle->SetPadGridY(1);
  }

  // Load first simulation data (for instance)
  PData *pData = PData::Get(sim.Data());
  Double_t E0 = pData->GetPlasmaE0();
  
  Float_t maxEcross = -999.;
  Float_t minEcross = 999.;
  Float_t maxEextr  = -999.;
  Float_t minEextr  = 999.;
  Float_t maxEdephas  = -999.;
  Float_t minEdephas  = 999.;
 
  const Int_t Nfields = 2; // E_z, E_x 
  TH2F   *hEvsTime[Nfields];
  Int_t NCross[Nfields];
  TGraph **gEcross[Nfields]; 
  TGraph **gEextr[Nfields]; 
  TGraph **gEdephas[Nfields]; 
  TGraph *gTRatio;

  TH2F   *hFvsTime;
  TGraph **gFcross = NULL;
  TGraph **gFextr = NULL;

  TH2F   *hETvsTime;
  TGraph **gETcross = NULL;
  TGraph **gETextr = NULL;

  TH2F   *hVvsTime;
  TGraph **gVcross = NULL;
  TGraph **gVextr = NULL;

  const Int_t NAtoms = 3;
  char atNames[NAtoms][4] = {"H","He","He2"};
  TH2F   *hIonProbvsTime[NAtoms]; // For H, He and He+. 
  TGraph *gIonProb10[NAtoms];
  TGraph *gIonProb100[NAtoms];
  Float_t IonTh[NAtoms] = {33.8,92.75,234.96} ;  // GV/m
  // if(!opt.Contains("units")) 
  //   for(Int_t i=0;i<NAtoms;i++) IonTh[i]  /= ( E0 / (PUnits::GV/PUnits::m));

  char hName[24];
  char gName[24];
  
  TString filename;
  filename = Form("./%s/Plots/Evolutions/Evolutions-%s.root",sim.Data(),sim.Data());
  
  TFile  *ifile = (TFile*) gROOT->GetListOfFiles()->FindObject(filename.Data());
  if (!ifile) ifile = new TFile(filename,"READ");

  TH2F *hDen1DvsTime = NULL;
  sprintf(hName,"hDenvsTime_1"); 
  hDen1DvsTime = (TH2F*) ifile->Get(hName);

  TH2F *hRmsvsTime = NULL;
  sprintf(hName,"hRmsvsTime_1"); 
  hRmsvsTime = (TH2F*) ifile->Get(hName);
    
  for(Int_t i=0;i<Nfields;i++) {
    
    sprintf(hName,"hEvsTime_%i",i); 
    hEvsTime[i] = (TH2F*) ifile->Get(hName);
    if(!hEvsTime[i]) continue;
    
    cout << Form("ANALYZING FIELD %i ...",i) << endl;

    Int_t NTBins = hEvsTime[i]->GetNbinsX();
    for(Int_t it=NTBins;it>0;it--) {
      
      // 1D field at certain timestep "it".
      TH1F *hE1D = (TH1F*) hEvsTime[i]->ProjectionY("_py",it,it);
      
      Int_t MAXCROSS = 2;
      Float_t *Cross = new Float_t[MAXCROSS];
      Float_t *Extr = new Float_t[MAXCROSS];
      memset(Cross,0,sizeof(Float_t)*MAXCROSS);
      memset(Extr,0,sizeof(Float_t)*MAXCROSS);

      Int_t auxNcross = PGlobals::HCrossings(hE1D,Cross,Extr,MAXCROSS,0.,0.);
      // cout << Form("  -> Number of crossings for histogram \"%s\" : %i ",hE1D->GetName(),auxNcross) << endl;
      // for(Int_t ic=0;ic<auxNcross;ic++) {
      // 	cout << Form(" %2i:  cross = %6.4f  extreme = %6.4f", ic, Cross[ic], Extr[ic]) << endl; 
      // }
      
      if(it==NTBins) {
	NCross[i] = auxNcross;
	
	gEcross[i] = new TGraph*[NCross[i]];
	gEextr[i] = new TGraph*[NCross[i]];

	for(Int_t ic = 0;ic<NCross[i];ic++) {
	  gEcross[i][ic] = new TGraph(NTBins);
	  sprintf(gName,"gEcross_%i_%i",i,ic); 
	  gEcross[i][ic]->SetName(gName);
	  
	  gEextr[i][ic] = new TGraph(NTBins);
	  sprintf(gName,"gEextr_%i_%i",i,ic); 
	  gEextr[i][ic]->SetName(gName);
	}

      }

      Float_t time = hEvsTime[i]->GetXaxis()->GetBinCenter(it);
      // cout << Form("Time step %i (%.2f): %i crossings",it,time,NCross[i]) << endl;
     
      for(Int_t ic=0;ic<NCross[i];ic++) {
	// cout << Form("  - Adding %i crossing: cross = %6.4f extreme = %6.4f",ic,Cross[ic],Extr[ic]) << endl;
	
	gEcross[i][ic]->SetPoint(it-1,time,Cross[ic]);
	gEextr[i][ic]->SetPoint(it-1,time,Extr[ic]);
      }
      
    }

    
    // Calculate the max and min of every crossing.
    // Also calculates dephasing:
    gEdephas[i] = new TGraph*[NCross[i]];
    for(Int_t ic = 0;ic<NCross[i];ic++) {

      Int_t Npoints = gEcross[i][ic]->GetN();
      Double_t *yEcross = gEcross[i][ic]->GetY();
      Double_t *yEextr  = gEextr[i][ic]->GetY();
      Double_t *xEextr  = gEextr[i][ic]->GetX();
      
      Double_t *yEdephas = new Double_t[Npoints];
      for(Int_t j=0;j<Npoints;j++) {
	yEdephas[j] = yEcross[j] - yEcross[0];
      }
      gEdephas[i][ic] = new TGraph(Npoints,xEextr,yEdephas);
      sprintf(gName,"gEdephas_%i_%i",i,ic); 
      gEdephas[i][ic]->SetName(gName);
      
      for(Int_t j=0;j<Npoints;j++) {
	if(yEcross[j]>maxEcross)
	  maxEcross = yEcross[j];
	if(yEcross[j]<minEcross)
	  minEcross = yEcross[j];
	
	if(yEextr[j]>maxEextr)
	  maxEextr = yEextr[j];
	if(yEextr[j]<minEextr)
	  minEextr = yEextr[j];
      
	// Only takes into account the minimums of the accelerating field:
	if(ic%2 || i!=0) continue;
	if(yEdephas[j]>maxEdephas)
	  maxEdephas = yEdephas[j];
	if(yEdephas[j]<minEdephas)
	  minEdephas = yEdephas[j];
	
      }
    
    }
  }

  // Transformer ratio vs time:
  // Take the ratio of the minimum over the maximum of the first oscillation of the Ez.
  {
    Int_t Npoints = gEextr[0][1]->GetN();
    Double_t *TR = new Double_t[Npoints];
    Double_t *yExtrPrev = gEextr[0][0]->GetY();
    Double_t *yExtr = gEextr[0][1]->GetY();
    Double_t *xExtr = gEextr[0][1]->GetX();
    for(Int_t j=0;j<Npoints;j++) {
      TR[j] = TMath::Abs(yExtr[j]/yExtrPrev[j]);	
    }
    
    gTRatio = new TGraph(Npoints,xExtr,TR);
    sprintf(gName,"gTRatio"); 
    gTRatio->SetName(gName);
  }
  

  sprintf(hName,"hVvsTime"); 
  hVvsTime = (TH2F*) ifile->Get(hName);
  Int_t NVCross = 0;
  cout << Form("ANALYZING POTENTIAL") << endl;

  Int_t NTBins = hVvsTime->GetNbinsX();
  for(Int_t it=NTBins;it>0;it--) {
      
    // 1D field at certain timestep "it".
    TH1F *hV1D = (TH1F*) hVvsTime->ProjectionY("_py",it,it);
      
    Int_t MAXCROSS = 2;
    Float_t *Cross = new Float_t[MAXCROSS];
    Float_t *Extr = new Float_t[MAXCROSS];
    memset(Cross,0,sizeof(Float_t)*MAXCROSS);
    memset(Extr,0,sizeof(Float_t)*MAXCROSS);
    
    Int_t auxNcross = PGlobals::HCrossings(hV1D,Cross,Extr,MAXCROSS,0.,20.);
    // cout << Form("  -> Number of crossings for histogram \"%s\" : %i ",hV1D->GetName(),auxNcross) << endl;
    // for(Int_t ic=0;ic<auxNcross;ic++) {
    // 	cout << Form(" %2i:  cross = %6.4f  extreme = %6.4f", ic, Cross[ic], Extr[ic]) << endl; 
    // }
    
    if(it==NTBins) {
      NVCross = auxNcross;
	
      gVcross = new TGraph*[NVCross];
      gVextr = new TGraph*[NVCross];

      for(Int_t ic = 0;ic<NVCross;ic++) {
	gVcross[ic] = new TGraph(NTBins);
	sprintf(gName,"gVcross_%i",ic); 
	gVcross[ic]->SetName(gName);
	  
	gVextr[ic] = new TGraph(NTBins);
	sprintf(gName,"gVextr_%i",ic); 
	gVextr[ic]->SetName(gName);
      }

    }

    Float_t time = hVvsTime->GetXaxis()->GetBinCenter(it);
    // cout << Form("Time step %i (%.2f): %i crossings",it,time,NVCross) << endl;
     
    for(Int_t ic=0;ic<NVCross;ic++) {
      // cout << Form("  - Adding %i crossing: cross = %6.4f extreme = %6.4f",ic,Cross[ic],Extr[ic]) << endl;
	
      gVcross[ic]->SetPoint(it-1,time,Cross[ic]);
      gVextr[ic]->SetPoint(it-1,time,Extr[ic]);
    }
      
  }


  sprintf(hName,"hETotalvsTime"); 
  hETvsTime = (TH2F*) ifile->Get(hName);
  Int_t NETCross = 0;
  cout << Form("ANALYZING TOTAL ELECTRIC FIELD") << endl;

  NTBins = hETvsTime->GetNbinsX();
  for(Int_t it=NTBins;it>0;it--) {
      
    // 1D field at certain timestep "it".
    TH1F *hET1D = (TH1F*) hETvsTime->ProjectionY("_py",it,it);
      
    Int_t MAXCROSS = 2;
    Float_t *Cross = new Float_t[MAXCROSS];
    Float_t *Extr = new Float_t[MAXCROSS];
    memset(Cross,0,sizeof(Float_t)*MAXCROSS);
    memset(Extr,0,sizeof(Float_t)*MAXCROSS);

    Float_t baseline = 0.5;
    if(opt.Contains("units"))
      baseline *= E0 / (PUnits::GV/PUnits::m);
    
    Int_t auxNcross = PGlobals::HCrossings(hET1D,Cross,Extr,MAXCROSS,baseline,-999,-999,"cum");
    // cout << Form("  -> Number of crossings for histogram \"%s\" : %i ",hET1D->GetName(),auxNcross) << endl;
    // for(Int_t ic=0;ic<auxNcross;ic++) {
    // 	cout << Form(" %2i:  cross = %6.4f  extreme = %6.4f", ic, Cross[ic], Extr[ic]) << endl; 
    // }
    
    if(it==NTBins) {
      NETCross = auxNcross;
	
      gETcross = new TGraph*[NETCross];
      gETextr = new TGraph*[NETCross];

      for(Int_t ic = 0;ic<NETCross;ic++) {
	gETcross[ic] = new TGraph(NTBins);
	sprintf(gName,"gETcross_%i",ic); 
	gETcross[ic]->SetName(gName);
	  
	gETextr[ic] = new TGraph(NTBins);
	sprintf(gName,"gETextr_%i",ic); 
	gETextr[ic]->SetName(gName);
      }

    }

    Float_t time = hETvsTime->GetXaxis()->GetBinCenter(it);
    // if(it==1)
    //   cout << Form("Time step %i (%.2f): %i crossings",it,time,NETCross) << endl;
     
    for(Int_t ic=0;ic<NETCross;ic++) {
      //if(it==1)
      //	cout << Form("  - Adding %i crossing: cross = %6.4f extreme = %6.4f",ic,Cross[ic],Extr[ic]) << endl;
	
      gETcross[ic]->SetPoint(it-1,time,Cross[ic]);
      gETextr[ic]->SetPoint(it-1,time,Extr[ic]);
      

    }
    
  }

  sprintf(hName,"hFocusvsTime"); 
  hFvsTime = (TH2F*) ifile->Get(hName);
  Int_t NFCross = 0;
  cout << Form("ANALYZING FOCUSING") << endl;

  NTBins = hFvsTime->GetNbinsX();
  for(Int_t it=NTBins;it>0;it--) {
      
    // 1D field at certain timestep "it".
    TH1F *hF1D = (TH1F*) hFvsTime->ProjectionY("_py",it,it);
      
    Int_t MAXCROSS = 2;
    Float_t *Cross = new Float_t[MAXCROSS];
    Float_t *Extr = new Float_t[MAXCROSS];
    memset(Cross,0,sizeof(Float_t)*MAXCROSS);
    memset(Extr,0,sizeof(Float_t)*MAXCROSS);

    Int_t auxNcross = PGlobals::HCrossings(hF1D,Cross,Extr,MAXCROSS,0.,0.);
    // cout << Form("  -> Number of crossings for histogram \"%s\" : %i ",hF1D->GetName(),auxNcross) << endl;
    // for(Int_t ic=0;ic<auxNcross;ic++) {
    // 	cout << Form(" %2i:  cross = %6.4f  extreme = %6.4f", ic, Cross[ic], Extr[ic]) << endl; 
    // }
    
    if(it==NTBins) {
      NFCross = auxNcross;
	
      gFcross = new TGraph*[NFCross];
      gFextr = new TGraph*[NFCross];

      for(Int_t ic = 0;ic<NFCross;ic++) {
	gFcross[ic] = new TGraph(NTBins);
	sprintf(gName,"gFcross_%i",ic); 
	gFcross[ic]->SetName(gName);
	  
	gFextr[ic] = new TGraph(NTBins);
	sprintf(gName,"gFextr_%i",ic); 
	gFextr[ic]->SetName(gName);
      }

    }

    Float_t time = hFvsTime->GetXaxis()->GetBinCenter(it);
    // cout << Form("Time step %i (%.2f): %i crossings",it,time,NFCross) << endl;
     
    for(Int_t ic=0;ic<NFCross;ic++) {
      // cout << Form("  - Adding %i crossing: cross = %6.4f extreme = %6.4f",ic,Cross[ic],Extr[ic]) << endl;
	
      gFcross[ic]->SetPoint(it-1,time,Cross[ic]);
      gFextr[ic]->SetPoint(it-1,time,Extr[ic]);
      

    }
    
  }
  

  for(Int_t i=0;i<NAtoms;i++) {
    sprintf(hName,"hIonProbvsTime_%s",atNames[i]); 
    hIonProbvsTime[i] = (TH2F*) ifile->Get(hName);
    if(!hIonProbvsTime[i]) continue;
    
    cout << Form("ANALYZING Ionization probability %i ...",i) << endl;

    Int_t NTBins = hIonProbvsTime[i]->GetNbinsX();
    for(Int_t it=NTBins;it>0;it--) {
      
      // 1D field at certain timestep "it".
      TH1F *hIonProb1D = (TH1F*) hIonProbvsTime[i]->ProjectionY("_py",it,it);
      
      Int_t MAXCROSS = 2;
      Float_t *Cross = new Float_t[MAXCROSS];
      Float_t *Extr = new Float_t[MAXCROSS];
      memset(Cross,0,sizeof(Float_t)*MAXCROSS);
      memset(Extr,0,sizeof(Float_t)*MAXCROSS);
      
      Int_t auxNcross = PGlobals::HCrossings(hIonProb1D,Cross,Extr,MAXCROSS,10.0);

      if(it==NTBins) {
	gIonProb10[i] = new TGraph(NTBins);
	sprintf(gName,"gIonProb10_%i",i); 
	gIonProb10[i]->SetName(gName);
      }

      Float_t time = hIonProbvsTime[i]->GetXaxis()->GetBinCenter(it);
      gIonProb10[i]->SetPoint(it-1,time,Cross[0]);
     
      memset(Cross,0,sizeof(Float_t)*MAXCROSS);
      memset(Extr,0,sizeof(Float_t)*MAXCROSS);
      auxNcross = PGlobals::HCrossings(hIonProb1D,Cross,Extr,MAXCROSS,99.0);
      
      if(it==NTBins) {
	gIonProb100[i] = new TGraph(NTBins);
	sprintf(gName,"gIonProb100_%i",i); 
	gIonProb100[i]->SetName(gName);
      }
      
      gIonProb100[i]->SetPoint(it-1,time,Cross[0]);
    }
  }

  // Set the color of the different evolutions according to a palette
  // UInt_t np = 50;
  // PPalette * colorPalette = (PPalette*) gROOT->FindObject("colorPalette");
  // if(!colorPalette) {
  //   const UInt_t Number = 3;
  //   Double_t Red[Number] = { 1.00, 0.00, 0.00};
  //   Double_t Green[Number]  = { 0.00, 1.00, 0.00};
  //   Double_t Blue[Number]   = { 1.00, 0.00, 1.00};
  //   Double_t Length[Number] = { 0.00, 0.50, 1.00 };
  //   colorPalette = new PPalette("colorPalette");
  //   colorPalette->CreateGradientColorTable(Number,Length,Red,Green,Blue,np);
  // }
  
  // for(Int_t i=0;i<Nfields;i++) { 
  //   for(Int_t ic=0;ic<Ncross;ic++) {
  //     Float_t step = (np/Nosc);
  //     Int_t icolor = TMath::Nint( ((ic+1)/2) * step - 1 );
  //     gEextr[i][ic]->SetLineColor(colorPalette->GetColor(icolor));
  //     gEextr[i][ic]->SetLineWidth(2);
  //     gEdephas[i][ic]->SetLineColor(colorPalette->GetColor(icolor));
  //     gEdephas[i][ic]->SetLineWidth(2);
  //   }
  // }
  // --------------------------------------------------------------------------

  // Manual coloring:
  const Int_t NCOLORS = 5;
  //  Int_t colors[NCOLORS] = {kMagenta+2,kRed,kBlue,kYellow+2,kCyan+2};
  Int_t colors[NCOLORS] = {kGray+3,kGray+2,kGray+1,kGray};
  for(Int_t i=0;i<Nfields;i++) { 
    for(Int_t ic=0;ic<NCross[i];ic++) {

      if( !gEcross[i][ic] || !gEextr[i][ic] ) continue;
            
      Int_t index = ic/2;
      if(index>=NCOLORS) index = NCOLORS-1;
      gEcross[i][ic]->SetLineColor(colors[index]);
      gEextr[i][ic]->SetLineColor(colors[index]);
      gEextr[i][ic]->SetLineWidth(1);
      gEdephas[i][ic]->SetLineColor(colors[index]);
      gEdephas[i][ic]->SetLineWidth(1);

      // cout << "EEEOOO" << endl;
      // if(ic%2) { 
      // 	gEcross[i][ic]->SetLineStyle(2);
      // 	gEextr[i][ic]->SetLineStyle(2);
      // 	gEdephas[i][ic]->SetLineStyle(2);
      // } else {
      // 	gEcross[i][ic]->SetLineStyle(1);
      // 	gEextr[i][ic]->SetLineStyle(1);
      // 	gEdephas[i][ic]->SetLineStyle(1);
      // }
      
      
    }
  }


  for(Int_t ic = 0;ic<NFCross;ic++) {
    // Graph's attributes
    Int_t index = ic/2;
    if(index>=NCOLORS) index = NCOLORS-1;
    gFcross[ic]->SetLineColor(colors[index]);
    if(ic%2-1) { 
      gFcross[ic]->SetLineStyle(2);
      gFextr[ic]->SetLineStyle(2);
      
    } else {
      gFcross[ic]->SetLineStyle(1);
      gFextr[ic]->SetLineStyle(1);
    }
  }

  for(Int_t ic = 0;ic<NVCross;ic++) {
    // Graph's attributes
    Int_t index = ic/2;
    if(index>=NCOLORS) index = NCOLORS-1;
    gVcross[ic]->SetLineColor(colors[index]);
    gVcross[ic]->SetLineStyle(3);
    gVextr[ic]->SetLineStyle(1);
  }
  
  for(Int_t ic = 0;ic<NETCross;ic++) {
    // Graph's attributes
    Int_t index = ic/2;
    if(index>=NCOLORS) index = NCOLORS-1;
    gETcross[ic]->SetLineColor(colors[index]);
    if(ic%2-1) { 
      gETcross[ic]->SetLineStyle(2);
      gETextr[ic]->SetLineStyle(2);
      
    } else {
      gETcross[ic]->SetLineStyle(1);
      gETextr[ic]->SetLineStyle(1);
    }
  }
  
  for(Int_t i=0;i<NAtoms;i++) {
    gIonProb10[i]->SetLineStyle(2);
    gIonProb10[i]->SetLineColor(kGray+2);

    gIonProb100[i]->SetLineStyle(1);
    gIonProb100[i]->SetLineColor(kGray+2);
  }
  

  // Plotting
  // ------------------------------------------------------------
  
  // Canvas setup
  UInt_t NPad = BitCounter(mask);
  if(NPad==0) NPad = 1;
  Float_t ypadsize = 250;
  Float_t ymarginsize = 200;
  if(NPad==1) ypadsize = 300;
  Float_t ysize = ypadsize * NPad + ymarginsize; 
  Float_t boom = 1.2;
  if(opt.Contains("boom"))
    ysize *= boom;
  TCanvas *C = new TCanvas("C","Snapshot",1050,ysize);
  C->SetFillStyle(4000);

  UInt_t lineColor = kOrange+10;
  //UInt_t lineColor =  TColor::GetColor(196,30,78);
  
  // Setup Pad layout:
  TPad **pad = new TPad*[NPad];
  TH2F **hFrame = new TH2F*[NPad];
  Float_t bMargin = 0.12 * (950/ysize);
  Float_t tMargin = 0.04 * (950/ysize);
  Float_t lMargin = 0.14;
  Float_t rMargin = 0.18;
  Float_t mMargin = 0.015 * (950/ysize);
  Float_t pfactor = 1.0;
  if(opt.Contains("nomar"))
    bMargin = tMargin = lMargin = rMargin = mMargin = 0.0;
  if(NPad==1)
    PGlobals::CanvasPartition(C,NPad,lMargin,rMargin,bMargin,tMargin,mMargin);
  else
    PGlobals::CanvasAsymPartition(C,NPad,lMargin,rMargin,bMargin,tMargin,pfactor,mMargin);
 
  // Define the frames for plotting
  Int_t fonttype = 43;
  Int_t fontsize = 32;
  Int_t tfontsize = 38;
  Int_t txsize = tfontsize+6;
  Int_t lxsize = fontsize;
  Int_t tysize = tfontsize;
  Int_t lysize = fontsize-2;
  Int_t tzsize = tfontsize-4;
  Int_t lzsize = fontsize-2;
  Float_t txoffset = (250/ypadsize) * 2.4 / (950/ysize);
  Float_t lxoffset = 0.015;
  Float_t tyoffset = 1.2 / (950/ysize);
  Float_t lyoffset = 0.01;
  Float_t tzoffset = 1.4 / (950/ysize);
  Float_t lzoffset = 0.01;
  Float_t tylength = 0.015;
  Float_t txlength = 0.04;
  for(Int_t i=NPad-1;i>=0;i--) {
    char name[16];
    sprintf(name,"pad_%i",i);
    pad[i] = (TPad*) gROOT->FindObject(name);
    pad[i]->SetFrameLineWidth(2);  
    pad[i]->SetTickx(1);
    pad[i]->SetTicky(1);
    if(opt.Contains("trans"))
      pad[i]->SetFillStyle(4000);
    pad[i]->SetFrameFillStyle(4000);

    sprintf(name,"hFrame_%i",i);
    hFrame[i] = (TH2F*) gROOT->FindObject(name);
    if(hFrame[i]) delete hFrame[i];
    hFrame[i] = (TH2F*) hEvsTime[0]->Clone(name);
    hFrame[i]->Reset();
    
    Float_t xFactor = pad[NPad-1]->GetAbsWNDC()/pad[i]->GetAbsWNDC();
    Float_t yFactor = pad[NPad-1]->GetAbsHNDC()/pad[i]->GetAbsHNDC();

    // Format for y axis
    hFrame[i]->GetYaxis()->SetLabelFont(fonttype);
    hFrame[i]->GetYaxis()->SetLabelSize(lysize);
    hFrame[i]->GetYaxis()->SetLabelOffset(lyoffset);
    hFrame[i]->GetYaxis()->SetTitleFont(fonttype);
    hFrame[i]->GetYaxis()->SetTitleSize(tysize);
    hFrame[i]->GetYaxis()->SetTitleOffset(tyoffset);

    hFrame[i]->GetYaxis()->SetTickLength(xFactor*tylength/yFactor);

    // Format for x axis
    hFrame[i]->GetXaxis()->SetLabelFont(fonttype);
    hFrame[i]->GetXaxis()->SetLabelSize(lxsize);
    hFrame[i]->GetXaxis()->SetLabelOffset(lxoffset);
    hFrame[i]->GetXaxis()->SetTitleFont(fonttype);
    hFrame[i]->GetXaxis()->SetTitleSize(txsize);
    hFrame[i]->GetXaxis()->SetTitleOffset(txoffset);
    
    hFrame[i]->GetXaxis()->SetTickLength(yFactor*txlength/xFactor);      

    if(i>0) { // skip x axis labels except for the lowest one
      hFrame[i]->GetXaxis()->SetLabelSize(0.0);
      hFrame[i]->GetXaxis()->SetTitleSize(0.0);
    }

    if(opt.Contains("nomar")) {
      hFrame[i]->GetYaxis()->SetTickLength(0.0);
      hFrame[i]->GetXaxis()->SetTickLength(0.0);      
    }

    // Labels for the frames

  }

  // Access to color Palettes 
  TExec *exPlasma = new TExec("exPlasma","plasmaPalette->cd();");
  TExec *exElec   = new TExec("exElec","electron0Palette->cd();");
  TExec *exHot    = new TExec("exHot","hotPalette->cd();");
  TExec *exField  = new TExec("exField","rbowwhitePalette->cd();");
  TExec *exFieldT = new TExec("exFieldT","red0Palette->cd();");
  TExec *exIonP   = new TExec("exIonP","redelectron0Palette->cd();");
  TExec *exPot    = new TExec("exPot","rbowinvPalette->cd();");

  

  // Actual Plotting!
  // ------------------------------------------------------------

  C->cd(0);

  Float_t x1,x2,y1,y2;
  Float_t gap = 0.01;
  TPaletteAxis *palette = NULL;
  UInt_t ip = NPad-1;

  if(mask & 0x1) {

    pad[ip]->Draw();
    pad[ip]->cd(); 
    if(opt.Contains("logz")) {
      pad[ip]->SetLogz(1);
    } else {
      pad[ip]->SetLogz(0);
    }

    hFrame[ip]->Draw("col");

    //  hDen1DvsTime->GetZaxis()->SetNdivisions(503);
    hDen1DvsTime->GetZaxis()->SetTitleFont(fonttype);
    Float_t xFactor = pad[0]->GetAbsWNDC()/pad[ip]->GetAbsWNDC();
    Float_t yFactor = pad[0]->GetAbsHNDC()/pad[ip]->GetAbsHNDC();
    hDen1DvsTime->GetZaxis()->SetTickLength(xFactor*tylength/yFactor);
    
    exElec->Draw();
    hDen1DvsTime->Draw("colz same");

    pad[ip]->Update();
  
    y1 = pad[ip]->GetBottomMargin();
    y2 = 1 - pad[ip]->GetTopMargin();
    x1 = pad[ip]->GetLeftMargin();
    x2 = 1 - pad[ip]->GetRightMargin();
  
    palette = (TPaletteAxis*) hDen1DvsTime->GetListOfFunctions()->FindObject("palette");  
    if(palette) {
      palette->SetY2NDC(y2 - gap);
      palette->SetY1NDC(y1 + gap);
      palette->SetX1NDC(x2 + 0.005);
      palette->SetX2NDC(x2 + 0.03);
      palette->SetTitleOffset(tzoffset);
      palette->SetTitleSize(tzsize);
      palette->SetLabelFont(fonttype);
      palette->SetLabelSize(lzsize);
      palette->SetLabelOffset(lyoffset);
      palette->SetBorderSize(2);
      palette->SetLineColor(1);
    }
   
    pad[ip]->RedrawAxis(); 

    ip--;
    C->cd(0);
    
  }

  if(mask & 0x2) {

    pad[ip]->Draw();
    pad[ip]->cd(); 
    if(opt.Contains("logz")) {
      pad[ip]->SetLogz(1);
    } else {
      pad[ip]->SetLogz(0);
    }

    hFrame[ip]->Draw("col");

    //  hRmsvsTime->GetZaxis()->SetNdivisions(503);
    hRmsvsTime->GetZaxis()->SetTitleFont(fonttype);
    Float_t xFactor = pad[0]->GetAbsWNDC()/pad[ip]->GetAbsWNDC();
    Float_t yFactor = pad[0]->GetAbsHNDC()/pad[ip]->GetAbsHNDC();
    hRmsvsTime->GetZaxis()->SetTickLength(xFactor*tylength/yFactor);
    
    exElec->Draw();
    hRmsvsTime->Draw("colz same");

    pad[ip]->Update();
  
    y1 = pad[ip]->GetBottomMargin();
    y2 = 1 - pad[ip]->GetTopMargin();
    x1 = pad[ip]->GetLeftMargin();
    x2 = 1 - pad[ip]->GetRightMargin();
  
    palette = (TPaletteAxis*) hRmsvsTime->GetListOfFunctions()->FindObject("palette");  
    if(palette) {
      palette->SetY2NDC(y2 - gap);
      palette->SetY1NDC(y1 + gap);
      palette->SetX1NDC(x2 + 0.005);
      palette->SetX2NDC(x2 + 0.03);
      palette->SetTitleOffset(tzoffset);
      palette->SetTitleSize(tzsize);
      palette->SetLabelFont(fonttype);
      palette->SetLabelSize(lzsize);
      palette->SetLabelOffset(lyoffset);
      palette->SetBorderSize(2);
      palette->SetLineColor(1);
    }
   
    pad[ip]->RedrawAxis(); 

    ip--;
    C->cd(0);
    
  }

  if(mask & 0x4) {

    pad[ip]->Draw();
    pad[ip]->cd(); 
    if(opt.Contains("logz")) {
      pad[ip]->SetLogz(1);
    } else {
      pad[ip]->SetLogz(0);
    }

    hFrame[ip]->Draw("col");

    //  hEvsTime[0]->GetZaxis()->SetNdivisions(503);
    hEvsTime[0]->GetZaxis()->SetTitleFont(fonttype);
    Float_t xFactor = pad[0]->GetAbsWNDC()/pad[ip]->GetAbsWNDC();
    Float_t yFactor = pad[0]->GetAbsHNDC()/pad[ip]->GetAbsHNDC();
    hEvsTime[0]->GetZaxis()->SetTickLength(xFactor*tylength/yFactor);
    
    exField->Draw();
    hEvsTime[0]->Draw("colz same");

    pad[ip]->Update();
  
    y1 = pad[ip]->GetBottomMargin();
    y2 = 1 - pad[ip]->GetTopMargin();
    x1 = pad[ip]->GetLeftMargin();
    x2 = 1 - pad[ip]->GetRightMargin();
  
    palette = (TPaletteAxis*) hEvsTime[0]->GetListOfFunctions()->FindObject("palette");  
    if(palette) {
      palette->SetY2NDC(y2 - gap);
      palette->SetY1NDC(y1 + gap);
      palette->SetX1NDC(x2 + 0.005);
      palette->SetX2NDC(x2 + 0.03);
      palette->SetTitleOffset(tzoffset);
      palette->SetTitleSize(tzsize);
      palette->SetLabelFont(fonttype);
      palette->SetLabelSize(lzsize);
      palette->SetLabelOffset(lyoffset);
      palette->SetBorderSize(2);
      palette->SetLineColor(1);
    }

    if(!opt.Contains("nocross")) {
    
      for(Int_t ic=0;ic<NVCross;ic++) {
	if( gVcross[ic] )
	  gVcross[ic]->Draw("L");
      }

      if(gEcross[1][0]) {
	gEcross[1][0]->SetLineStyle(4);
	gEcross[1][0]->Draw("L");
      }
    }

    pad[ip]->RedrawAxis(); 

    ip--;
    C->cd(0);
    
  }

  if(mask & 0x8) {

    pad[ip]->Draw();
    pad[ip]->cd(); 
    if(opt.Contains("logz")) {
      pad[ip]->SetLogz(1);
    } else {
      pad[ip]->SetLogz(0);
    }

    hFrame[ip]->Draw("col");

    //  hEvsTime[1]->GetZaxis()->SetNdivisions(503);
    hEvsTime[1]->GetZaxis()->SetTitleFont(fonttype);
    Float_t xFactor = pad[0]->GetAbsWNDC()/pad[ip]->GetAbsWNDC();
    Float_t yFactor = pad[0]->GetAbsHNDC()/pad[ip]->GetAbsHNDC();
    hEvsTime[1]->GetZaxis()->SetTickLength(xFactor*tylength/yFactor);
    
    exField->Draw();
    hEvsTime[1]->Draw("colz same");

    pad[ip]->Update();
  
    y1 = pad[ip]->GetBottomMargin();
    y2 = 1 - pad[ip]->GetTopMargin();
    x1 = pad[ip]->GetLeftMargin();
    x2 = 1 - pad[ip]->GetRightMargin();
  
    palette = (TPaletteAxis*) hEvsTime[1]->GetListOfFunctions()->FindObject("palette");  
    if(palette) {
      palette->SetY2NDC(y2 - gap);
      palette->SetY1NDC(y1 + gap);
      palette->SetX1NDC(x2 + 0.005);
      palette->SetX2NDC(x2 + 0.03);
      palette->SetTitleOffset(tzoffset);
      palette->SetTitleSize(tzsize);
      palette->SetLabelFont(fonttype);
      palette->SetLabelSize(lzsize);
      palette->SetLabelOffset(lyoffset);
      palette->SetBorderSize(2);
      palette->SetLineColor(1);
    }
   
    pad[ip]->RedrawAxis(); 

    ip--;
    C->cd(0);
    
  }

  if(mask & 0x10) {

    pad[ip]->Draw();
    pad[ip]->cd(); 
    if(opt.Contains("logz")) {
      pad[ip]->SetLogz(1);
    } else {
      pad[ip]->SetLogz(0);
    }

    hFrame[ip]->Draw("col");

    //  hETvsTime->GetZaxis()->SetNdivisions(503);
    hETvsTime->GetZaxis()->SetTitleFont(fonttype);
    Float_t xFactor = pad[0]->GetAbsWNDC()/pad[ip]->GetAbsWNDC();
    Float_t yFactor = pad[0]->GetAbsHNDC()/pad[ip]->GetAbsHNDC();
    hETvsTime->GetZaxis()->SetTickLength(xFactor*tylength/yFactor);
    
    exFieldT->Draw();
    hETvsTime->Draw("colz same");

    pad[ip]->Update();
  
    y1 = pad[ip]->GetBottomMargin();
    y2 = 1 - pad[ip]->GetTopMargin();
    x1 = pad[ip]->GetLeftMargin();
    x2 = 1 - pad[ip]->GetRightMargin();
  
    palette = (TPaletteAxis*) hETvsTime->GetListOfFunctions()->FindObject("palette");  
    if(palette) {
      palette->SetY2NDC(y2 - gap);
      palette->SetY1NDC(y1 + gap);
      palette->SetX1NDC(x2 + 0.005);
      palette->SetX2NDC(x2 + 0.03);
      palette->SetTitleOffset(tzoffset);
      palette->SetTitleSize(tzsize);
      palette->SetLabelFont(fonttype);
      palette->SetLabelSize(lzsize);
      palette->SetLabelOffset(lyoffset);
      palette->SetBorderSize(2);
      palette->SetLineColor(1);
    }

    if(!opt.Contains("nocross")) {
    
      for(Int_t ic=0;ic<NVCross;ic++) {
	if( gVcross[ic] )
	  gVcross[ic]->Draw("L");
      }

      if(gEcross[1][0]) {
	gEcross[1][0]->SetLineStyle(4);
	gEcross[1][0]->Draw("L");
      }
    }
     
    pad[ip]->RedrawAxis(); 

    ip--;
    C->cd(0);
    
  }

  if(mask & 0x20) {

    pad[ip]->Draw();
    pad[ip]->cd(); 
    if(opt.Contains("logz")) {
      pad[ip]->SetLogz(1);
    } else {
      pad[ip]->SetLogz(0);
    }

    hFrame[ip]->Draw("col");

    //  hVvsTime->GetZaxis()->SetNdivisions(503);
    hVvsTime->GetZaxis()->SetTitleFont(fonttype);
    Float_t xFactor = pad[0]->GetAbsWNDC()/pad[ip]->GetAbsWNDC();
    Float_t yFactor = pad[0]->GetAbsHNDC()/pad[ip]->GetAbsHNDC();
    hVvsTime->GetZaxis()->SetTickLength(xFactor*tylength/yFactor);
    
    exPot->Draw();
    hVvsTime->Draw("colz same");

    pad[ip]->Update();
  
    y1 = pad[ip]->GetBottomMargin();
    y2 = 1 - pad[ip]->GetTopMargin();
    x1 = pad[ip]->GetLeftMargin();
    x2 = 1 - pad[ip]->GetRightMargin();
  
    palette = (TPaletteAxis*) hVvsTime->GetListOfFunctions()->FindObject("palette");  
    if(palette) {
      palette->SetY2NDC(y2 - gap);
      palette->SetY1NDC(y1 + gap);
      palette->SetX1NDC(x2 + 0.005);
      palette->SetX2NDC(x2 + 0.03);
      palette->SetTitleOffset(tzoffset);
      palette->SetTitleSize(tzsize);
      palette->SetLabelFont(fonttype);
      palette->SetLabelSize(lzsize);
      palette->SetLabelOffset(lyoffset);
      palette->SetBorderSize(2);
      palette->SetLineColor(1);
    }
   
    pad[ip]->RedrawAxis(); 

    ip--;
    C->cd(0);
    
  }
  

  if(mask & 0x40) {

    pad[ip]->Draw();
    pad[ip]->cd(); 
    if(opt.Contains("logz")) {
      pad[ip]->SetLogz(1);
    } else {
      pad[ip]->SetLogz(0);
    }

    hFrame[ip]->Draw("col");

    hIonProbvsTime[1]->GetZaxis()->SetNdivisions(503);
    hIonProbvsTime[1]->GetZaxis()->SetTitleFont(fonttype);
    Float_t xFactor = pad[0]->GetAbsWNDC()/pad[ip]->GetAbsWNDC();
    Float_t yFactor = pad[0]->GetAbsHNDC()/pad[ip]->GetAbsHNDC();
    hIonProbvsTime[1]->GetZaxis()->SetTickLength(xFactor*tylength/yFactor);
    hIonProbvsTime[1]->GetZaxis()->SetRangeUser(0.,0.12);
    
    // exFieldT->Draw();
    // exPlasma->Draw();
    exIonP->Draw();
    hIonProbvsTime[1]->Draw("colz same");

    pad[ip]->Update();
  
    y1 = pad[ip]->GetBottomMargin();
    y2 = 1 - pad[ip]->GetTopMargin();
    x1 = pad[ip]->GetLeftMargin();
    x2 = 1 - pad[ip]->GetRightMargin();
  
    palette = (TPaletteAxis*) hIonProbvsTime[1]->GetListOfFunctions()->FindObject("palette");  
    if(palette) {
      palette->SetY2NDC(y2 - gap);
      palette->SetY1NDC(y1 + gap);
      palette->SetX1NDC(x2 + 0.005);
      palette->SetX2NDC(x2 + 0.03);
      palette->SetTitleOffset(tzoffset);
      palette->SetTitleSize(tzsize);
      palette->SetLabelFont(fonttype);
      palette->SetLabelSize(lzsize);
      palette->SetLabelOffset(lyoffset);
      palette->SetBorderSize(2);
      palette->SetLineColor(1);
    }

    if(!opt.Contains("nocross")) {
      
      for(Int_t ic=0;ic<NVCross;ic++) {
	if( gVcross[ic] )
	  gVcross[ic]->Draw("L");
      }
      
      if(gEcross[1][0]) {
	gEcross[1][0]->SetLineStyle(4);
	gEcross[1][0]->Draw("L");
      }
    }
     
    pad[ip]->RedrawAxis(); 

    ip--;
    C->cd(0);
    
  }
  
  // Print to a file
  // Output file
  TString fOutName = Form("./%s/Plots/Evolutions/Evolutions%s-WII-%s",sim.Data(),imask.c_str(),sim.Data());
  PGlobals::imgconv(C,fOutName,opt);
  // ---------------------------------------------------------

  
  ifile->Close();
  cout << endl;
}
void DrawMigrationMatrix(TTree* tr)
{

  TEventTree evTr;
  evTr.Init(tr);
  
  long nentries = tr->GetEntries();
  //nentries = 100000;

 // TFile fOut("testGenHists.root","RECREATE");
  TConfiguration config;
  float binLimits[config.GetNPhoPtBins()+1];
  vector <float> vecLimits = config.GetPhoPtBinsLimits();
  for (int i=0; i<config.GetNPhoPtBins()+1; i++){
    binLimits[i]=vecLimits[i];
  }
  TH2F* histMigr = new TH2F("hist","migration matrix", config.GetNPhoPtBins(),binLimits,config.GetNPhoPtBins(),binLimits);

  for (long entry=0; entry<100000; entry++)
  //for (long entry=0; entry<nentries; entry++)
 
    {
      evTr.GetEntryNeededBranchesOnly(entry);
      evTr.GetEntryMCSpecific(entry);

      if (evTr.treeLeaf.nMC==0) continue;

      for (int iMC=0; iMC<evTr.treeLeaf.nMC; iMC++)
        {

          /////////////////////////////////////
          // photons check starts
          /////////////////////////////////////

          if (fabs(evTr.treeLeaf.mcPID[iMC])==22){
            for (int ipho=0; ipho<evTr.treeLeaf.nPho; ipho++){
              if (evTr.treeLeaf.mcIndex[iMC]==evTr.treeLeaf.phoGenIndex[ipho]){
                int binx = config.FindPhoPtBinByPhoPt(evTr.treeLeaf.mcEt[iMC])+1;
                int biny = config.FindPhoPtBinByPhoPt(evTr.treeLeaf.phoEt[ipho])+1;
                float binCont = histMigr->GetBinContent(binx,biny)+1;
                //std::cout<<"binx="<<binx<<", biny="<<biny<<", binCont="<<binCont<<std::endl;
                histMigr->SetBinContent(binx,biny,binCont);
             
              } //end of if (mcIndex[iMC]==phoGenIndex[ipho])
            } //end of loop over photons
          } //end of if (fabs(mcPID[iMC])==22)

          /////////////////////////////////////
          // photons check ends
          /////////////////////////////////////


        } //end of loop over iMC    
    } //end of loop over entry 

  for (int iy=1; iy<histMigr->GetNbinsY()+1; iy++){
    float totalGen=0;
    for (int ix=1; ix<histMigr->GetNbinsX()+1; ix++){
      totalGen+=histMigr->GetBinContent(ix,iy);
    }
    for (int ix=1; ix<histMigr->GetNbinsX()+1; ix++){
      float cont = histMigr->GetBinContent(ix,iy)/totalGen;
      histMigr->SetBinContent(ix,iy,cont);
    }
  }

  TCanvas c("matrMigr","matrMigr");
  histMigr->Print();
  for (int ix=1; ix<histMigr->GetNbinsX()+1; ix++){
    for (int iy=1; iy<histMigr->GetNbinsY()+1; iy++){
      std::cout<<histMigr->GetBinContent(ix,iy)<<" ";
    }
    std::cout<<std::endl;
  }
  histMigr->SetStats(0);
  histMigr->GetXaxis()->SetMoreLogLabels(1);
  histMigr->GetYaxis()->SetMoreLogLabels(1);
  histMigr->SetMarkerSize(1);
  histMigr->Draw("COLZ TEXT");
  c.SetLogx();
  c.SetLogy();
  c.SaveAs("matrMigr.png");
}
int main (int argc, char **argv)
{
  /// Mc Ntuplas
  TString input = Form("/data1/rgerosa/NTUPLES_FINAL_CALIB/MC/WJetsToLNu_DYJetsToLL_7TeV-madgraph-tauola_Fall11_All.root"); 
  /// MC Calibration result E/p
  TString input2 = Form("/data1/rgerosa/L3_Weight/MC_WJets/EB_Z_recoFlag/WJetsToLNu_DYJetsToLL_7TeV-madgraph-tauola_Fall11_Z_noEP.root"); 

  TApplication* theApp = new TApplication("Application",&argc, argv);

  TFile *f = new TFile(input,"");
  TTree *inputTree = (TTree*)f->Get("ntu");

  TFile *f2 = new TFile(input2,"");
  TH2F *h_scale_EB = (TH2F*)f2->Get("h_scale_EB");
  TH2F *hcmap = (TH2F*) h_scale_EB->Clone("hcmap");
  
  hcmap -> Reset("ICEMS");
  hcmap -> ResetStats();
  
  /// Taking infos

  std::vector<float>* ele1_recHit_E=0;
  std::vector<float>* ele2_recHit_E=0;
  std::vector<int>* ele1_recHit_hashedIndex=0;
  std::vector<int>* ele2_recHit_hashedIndex=0;
  std::vector<int>* ele1_recHit_flag=0;
  std::vector<int>* ele2_recHit_flag=0;
  float ele1_E_true,ele2_E_true;
  float ele1_tkP,ele2_tkP;
  int ele1_isEB, ele2_isEB;
  float   ele1_fbrem,ele2_fbrem;
  int isW, isZ;
  
  inputTree->SetBranchAddress("ele1_recHit_E", &ele1_recHit_E);
  inputTree->SetBranchAddress("ele2_recHit_E", &ele2_recHit_E);
  inputTree->SetBranchAddress("ele1_recHit_hashedIndex", &ele1_recHit_hashedIndex);
  inputTree->SetBranchAddress("ele2_recHit_hashedIndex", &ele2_recHit_hashedIndex);
  inputTree->SetBranchAddress("ele1_recHit_flag", &ele1_recHit_flag);
  inputTree->SetBranchAddress("ele2_recHit_flag", &ele2_recHit_flag);
  inputTree->SetBranchAddress("ele1_E_true", &ele1_E_true);
  inputTree->SetBranchAddress("ele2_E_true", &ele2_E_true);
  inputTree->SetBranchAddress("ele1_tkP", &ele1_tkP);
  inputTree->SetBranchAddress("ele2_tkP", &ele2_tkP);
  inputTree->SetBranchAddress("ele1_isEB", &ele1_isEB);
  inputTree->SetBranchAddress("ele2_isEB", &ele2_isEB);
  inputTree->SetBranchAddress("ele1_fbrem", &ele1_fbrem);
  inputTree->SetBranchAddress("ele2_fbrem", &ele2_fbrem);
  inputTree->SetBranchAddress("isW", &isW);
  inputTree->SetBranchAddress("isZ", &isZ);
 
  TProfile2D* mapMomentum = new TProfile2D("mapMomentum","mapMomentum",360,0,360,170,-85,85);
  TProfile2D* mapfbrem = new TProfile2D("mapfbrem","mapfbrem",360,0,360,170,-85,85);

  /// Make fbrem and p/ptrue map cycling on MC --> all the events 

  for(Long64_t i=0; i< inputTree->GetEntries(); i++)
  {
   inputTree->GetEntry(i);
   if (!(i%100000))std::cerr<<i;
   if (!(i%10000)) std::cerr<<".";
       
   if (ele1_isEB == 1 && (isW==1 || isZ==1)) {
  
      double E_seed=0;
      int seed_hashedIndex, iseed;

      for (unsigned int iRecHit = 0; iRecHit < ele1_recHit_E->size(); iRecHit++ ) {
            
            if(ele1_recHit_E -> at(iRecHit) > E_seed &&  ele1_recHit_flag->at(iRecHit) < 4 ) /// control if this recHit is good
            {
              seed_hashedIndex=ele1_recHit_hashedIndex -> at(iRecHit);
              iseed=iRecHit;
              E_seed=ele1_recHit_E -> at(iRecHit);  ///! Seed search

            }
      }
    
   int eta_seed = GetIetaFromHashedIndex(seed_hashedIndex);
   int phi_seed = GetIphiFromHashedIndex(seed_hashedIndex);
   if(ele1_tkP>0 && ele1_E_true>0 && abs(ele1_tkP/ele1_E_true)<2. && abs(ele1_tkP/ele1_E_true)>0.5) mapMomentum->Fill(phi_seed,eta_seed,abs(ele1_tkP/ele1_E_true));
   mapfbrem->Fill(phi_seed,eta_seed,abs(ele1_fbrem)); 
   }
   
   if (ele2_isEB == 1 && isZ==1) {

      double E_seed=0;
      int seed_hashedIndex, iseed;

      for (unsigned int iRecHit = 0; iRecHit < ele2_recHit_E->size(); iRecHit++ ) {
            
            if(ele2_recHit_E -> at(iRecHit) > E_seed &&  ele2_recHit_flag->at(iRecHit) < 4 ) /// control if this recHit is good
            {
              seed_hashedIndex=ele2_recHit_hashedIndex -> at(iRecHit);
              iseed=iRecHit;
              E_seed=ele2_recHit_E -> at(iRecHit);  ///! Seed search

            }
      }
    
   int eta_seed = GetIetaFromHashedIndex(seed_hashedIndex);
   int phi_seed = GetIphiFromHashedIndex(seed_hashedIndex);
   if(ele2_tkP>0 && ele2_E_true>0 && abs(ele2_tkP/ele2_E_true)<2. && abs(ele2_tkP/ele2_E_true)>0.5) mapMomentum->Fill(phi_seed,eta_seed,abs(ele2_tkP/ele2_E_true));
   mapfbrem->Fill(phi_seed,eta_seed,abs(ele2_fbrem));

   }
 }

 /// Map of IC normalized in eta rings

 std::vector< std::pair<int,int> > TT_centre ;
 
 TT_centre.push_back(std::pair<int,int> (58,49));
 TT_centre.push_back(std::pair<int,int> (53,109));
 TT_centre.push_back(std::pair<int,int> (8,114));
 TT_centre.push_back(std::pair<int,int> (83,169));
 TT_centre.push_back(std::pair<int,int> (53,174));
 TT_centre.push_back(std::pair<int,int> (63,194));
 TT_centre.push_back(std::pair<int,int> (83,224));
 TT_centre.push_back(std::pair<int,int> (73,344));
 TT_centre.push_back(std::pair<int,int> (83,358));
 TT_centre.push_back(std::pair<int,int> (-13,18));
 TT_centre.push_back(std::pair<int,int> (-18,23));
 TT_centre.push_back(std::pair<int,int> (-8,53));
 TT_centre.push_back(std::pair<int,int> (-3,63));
 TT_centre.push_back(std::pair<int,int> (-53,128));
 TT_centre.push_back(std::pair<int,int> (-53,183));
 TT_centre.push_back(std::pair<int,int> (-83,193));
 TT_centre.push_back(std::pair<int,int> (-74,218));
 TT_centre.push_back(std::pair<int,int> (-8,223));
 TT_centre.push_back(std::pair<int,int> (-68,303));
 TT_centre.push_back(std::pair<int,int> (-43,328));
 
 /// Mean over phi corrected skipping dead channel 

 for (int iEta = 1 ; iEta < h_scale_EB->GetNbinsY()+1; iEta ++)
 {
   float SumIC = 0;
   int numIC = 0;
   
   for(int iPhi = 1 ; iPhi < h_scale_EB->GetNbinsX()+1 ; iPhi++)
   {
    bool isGood = CheckxtalIC(h_scale_EB,iPhi,iEta);
    bool isGoodTT = CheckxtalTT(iPhi,iEta,TT_centre);
 
     if(isGood && isGoodTT)
     {
      SumIC = SumIC + h_scale_EB->GetBinContent(iPhi,iEta);
      numIC ++ ;
     }
    }
   //fede: skip bad channels and bad TTs
   for (int iPhi = 1; iPhi< h_scale_EB->GetNbinsX()+1  ; iPhi++)
   { 
     if(numIC==0 || SumIC==0) continue;

     bool isGood = CheckxtalIC(h_scale_EB,iPhi,iEta);
     bool isGoodTT = CheckxtalTT(iPhi,iEta,TT_centre);
     if (!isGood || !isGoodTT) continue;

     hcmap->SetBinContent(iPhi,iEta,h_scale_EB->GetBinContent(iPhi,iEta)/(SumIC/numIC));
   }
  }

 /// ratio map

 TH2F* ratioMap = (TH2F*) hcmap -> Clone("ratioMap");
 ratioMap->Reset();

 for( int i =0 ; i<hcmap->GetNbinsX() ; i++){
  for( int j=0; j<hcmap->GetNbinsY() ; j++){
   if(hcmap->GetBinContent(i,j)!=0 && mapMomentum->GetBinContent(i,j)!=0)
    ratioMap->SetBinContent(i+1,j+1,mapMomentum->GetBinContent(i,j)/hcmap->GetBinContent(i,j));
  }
 }

 /// Profile along phi taking into account dead channels
 TGraphErrors *coeffEBp = new TGraphErrors();
 TGraphErrors *coeffEBm = new TGraphErrors();

 for (int iPhi =1; iPhi< hcmap->GetNbinsX()+1 ; iPhi++){
  double SumEBp =0, SumEBm=0;
  double iEBp=0, iEBm=0;
  for(int iEta = 1; iEta<hcmap->GetNbinsY()+1 ; iEta++){
     if(hcmap->GetBinContent(iPhi,iEta)==0)continue;
     if(iEta>85) {SumEBp=SumEBp+mapMomentum->GetBinContent(iPhi,iEta)/hcmap->GetBinContent(iPhi,iEta);
                  iEBp++;}
     else{ SumEBm=SumEBm+mapMomentum->GetBinContent(iPhi,iEta)/hcmap->GetBinContent(iPhi,iEta);
           iEBm++;}
     }
  coeffEBp->SetPoint(iPhi-1,iPhi-1,SumEBp/iEBp);
  coeffEBm->SetPoint(iPhi-1,iPhi-1,SumEBm/iEBm);

  }
     
 TFile* outputGraph = new TFile("output/GraphFor_P_Correction.root","RECREATE");
 outputGraph->cd();

 coeffEBp->Write("coeffEBp");
 coeffEBm->Write("coeffEBm");
 outputGraph->Close();
     
 gROOT->Reset();
 gROOT->SetStyle("Plain");

 gStyle->SetPadTickX(1);
 gStyle->SetPadTickY(1);
 gStyle->SetOptTitle(1); 
 gStyle->SetOptStat(0); 
 gStyle->SetOptFit(0); 
 gStyle->SetFitFormat("6.3g"); 
 gStyle->SetPalette(1); 
  
 gStyle->SetTextFont(42);
 gStyle->SetTextSize(0.05);
 gStyle->SetTitleFont(42,"xyz");
 gStyle->SetTitleSize(0.05);
 gStyle->SetLabelFont(42,"xyz");
 gStyle->SetLabelSize(0.05);
 gStyle->SetTitleXOffset(0.8);
 gStyle->SetTitleYOffset(1.1);
 gROOT->ForceStyle();
 
 TCanvas* c1 = new TCanvas("mapMomentum","mapMomentum",1);
 c1->cd();
 mapMomentum->GetXaxis()->SetTitle("#phi");
 mapMomentum->GetXaxis()->SetNdivisions(20);
 c1->SetGridx(); 
 mapMomentum->GetYaxis()->SetTitle("#eta");
 mapMomentum->GetZaxis()->SetRangeUser(0.7,1.3);
 mapMomentum->Draw("colz");

 TCanvas* c2 = new TCanvas("mapfbrem","mapfbrem",1);
 c2->cd();
 mapfbrem->GetXaxis()->SetTitle("#phi");
 mapfbrem->GetYaxis()->SetTitle("#eta");
 mapfbrem->GetXaxis()->SetNdivisions(20);
 c2->SetGridx(); 
 mapfbrem->GetZaxis()->SetRangeUser(0.,0.7);
 mapfbrem->Draw("colz");

 TCanvas* c3 = new TCanvas("ratioMap","ratioMap",1);
 c3->cd();
 ratioMap->GetXaxis()->SetTitle("#phi");
 ratioMap->GetYaxis()->SetTitle("#eta");
 ratioMap->GetXaxis()->SetNdivisions(20);
 c3->SetGridx(); 
 ratioMap->GetZaxis()->SetRangeUser(0.7,1.3);
 ratioMap->Draw("colz");

 TCanvas* c4 = new TCanvas("coeffEB","coeffEB",1);
 c4->cd();
 coeffEBp->GetXaxis()->SetTitle("#phi");
 coeffEBp->GetYaxis()->SetTitle("p/p_{true}");
 coeffEBp -> SetMarkerStyle(20);
 coeffEBp -> SetMarkerSize(1);
 coeffEBp -> SetMarkerColor(kRed+1); 
 coeffEBp -> SetLineColor(kRed+1); 
 c4->SetGridx(); 
 c4->SetGridy(); 
 ratioMap->Draw("ap");

 coeffEBm->GetXaxis()->SetTitle("#phi");
 coeffEBm->GetYaxis()->SetTitle("p/p_{true}");
 coeffEBm -> SetMarkerStyle(20);
 coeffEBm -> SetMarkerSize(1);
 coeffEBm -> SetMarkerColor(kBlue+1); 
 coeffEBm -> SetLineColor(kBlue+1); 
 coeffEBm->Draw("ap same");


 theApp->Run();
 return 0;
}
Exemple #26
0
void Unfold2(int algo= 3,bool useSpectraFromFile=0, bool useMatrixFromFile=0, int doToy = 0, int isMC = 0,char *spectraFileName = (char*)"pbpb_spectra_akPu3PF.root",double recoJetPtCut = 60.,double trackMaxPtCut = 0, int nBayesianIter = 4, int doBjets=1, int doTrigEffCorr=1) // algo 2 =akpu2 ; 3 =akpu3 ; 4 =akpu4 ;1 = icpu5
{
  
  gStyle->SetErrorX(0.);
  gStyle->SetPaintTextFormat("3.2f");
  gStyle->SetOptLogz(1);
  gStyle->SetPadRightMargin(0.13);	
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);


  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();
  
  // input files
  char *fileNamePP_mc = NULL;
  char *fileNamePbPb_mc = NULL;
  char *fileNamePP_data = NULL;
  char *fileNamePbPb_data = NULL;
  

  // pp file needs replacing
  if(doBjets)fileNamePP_data = (char*)"~/Work/bTagging/outputTowardsFinal/NewFormatV5_bFractionMCTemplate_pppp1_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root";
  //else fileNamePP_data = (char*)"../spectra/rawIncSpectra_MB_fixedBinSize_v4.root";
  else fileNamePP_data = (char*)"../spectra/rawIncSpectra_MB_varBinSize_v4.root";
  //if(doBjets)fileNamePbPb_data = (char*)"~/Work/bTagging/outputTowardsFinal/AltBinningV6_bFractionMCTemplate_ppPbPb1_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root";
  if(doBjets)fileNamePbPb_data = (char*)"~/Work/bTagging/outputTowardsFinal/bFractionMCTemplate_ppPbPb1_SSVHEat2.0FixCL0_bin_0_40_eta_0_2_binomErrors_jet55_wideBin_v2.root";
  //else fileNamePbPb_data = (char*)"../spectra/rawIncSpectra_MB_fixedBinSize_v4.root";
  else fileNamePbPb_data = (char*)"../spectra/rawIncSpectra_MB_varBinSize_v4.root";
  if(doBjets) fileNamePP_mc = (char*)"~/Work/bTagging/histos/ppMC_ppReco_ak3PF_BjetTrig_noIPupperCut.root";
  else fileNamePP_mc = (char*)"~/Work/bTagging/histos/ppMC_ppReco_ak3PF_QCDjetTrig_noIPupperCut.root";
  if(doBjets)fileNamePbPb_mc = (char*) "~/Work/bTagging/histos/PbPbBMC_pt30by3_ipHICalibCentWeight_noTrig.root";
  else fileNamePbPb_mc = (char*) "~/Work/bTagging/histos/PbPbQCDMC_pt30by3_ipHICalibCentWeight_noTrig.root";


  // grab ntuples
  TFile *infPbPb_mc = new TFile(fileNamePbPb_mc);
  TFile *infPP_mc = new TFile(fileNamePP_mc);
  

  string bJetString = "Inc";
  if(doBjets) bJetString = "bJets";

  // Output file
  TFile *pbpb_Unfo;
  if (isMC) pbpb_Unfo = new TFile(Form("pbpb_Unfo_%s_MC_v2.root",algoName[algo]),"RECREATE");
  else pbpb_Unfo  = new TFile(Form("pbpb_Unfo_%s_jtpt%.0f_%s_v4.root",algoName[algo],recoJetPtCut,bJetString.c_str()),"RECREATE");

  // Histograms used by RooUnfold
  UnfoldingHistos *uhist[nbins_cent+1];
		
  // Initialize Histograms   
	
  for (int i=0;i<=nbins_cent;i++) uhist[i] = new UnfoldingHistos(i);
	
  // Initialize reweighting functions
  /*
  TCut dataSelection;
  TCut dataSelectionPP;
  TCut TriggerSelectionPP;
  TCut TriggerSelectionPbPb80;

  if(doBjets)dataSelection = "weight*(abs(refparton_flavorForB)==5&&abs(jteta)<2)";
  else dataSelection = "weight*(abs(jteta)<2)";
  */

  if (isMC) cout<<"This is a MC closure test"<<endl;
  else cout<< "This is a data analysis"<<endl;    		     
	     	
  // Setup jet data branches, basically the jet tree branches are assigned to this object when we loop over the events
	
  JetDataPbPb *dataPbPb   = new JetDataPbPb(fileNamePbPb_mc,(char*)"nt"); // PbPb data	
  JetDataPP *dataPP = new JetDataPP(fileNamePP_mc,(char*)"nt");	// pp data
	
  TFile *fSpectra(0);		
  if (useSpectraFromFile||useMatrixFromFile){
    fSpectra = new TFile(spectraFileName,"read");
  }
  
  // Come back to the output file dir
  pbpb_Unfo->cd();

  cout <<"MC..."<<endl;	
  
  TH1F *hCent = new TH1F("hCent","",nbins_cent,boundaries_cent);
 

  // if you change the binning you have to change these, too
  // inclusive trig eff
  /*
    float trigEffInc[6]={0.777265,
			 0.95765,
			 0.998357,
			 0.999941,
			 1.,
			 1.};
  */

    // b-jet trig eff
    /*
    float trigEffbJet[6]={0.660276,
		      0.908997,
		      0.980793,
		      0.998767,
		      0.999442,
		      1.};
    */



 
		
  // Fill PbPb MC   
  if (!useMatrixFromFile) {
    for (Long64_t jentry2=0; jentry2<dataPbPb->tJet->GetEntries();jentry2++) {
      dataPbPb->tJet->GetEntry(jentry2);
      
      // change when we switch to centrality binning
      int cBin = 0;
            
      if ( dataPbPb->refpt  < 0. ) continue;
      if ( dataPbPb->jteta  > 2. || dataPbPb->jteta < -2. ) continue;
      if ( dataPbPb->refpt<0) dataPbPb->refpt=0;
      if (doBjets && fabs(dataPbPb->refparton_flavorForB)!=5) continue;
      //if (doBjets&& dataPbPb->discr_ssvHighEff<2) continue;
      if (doBjets && dataPbPb->jtptB < recoJetPtCut) continue;
      if (!doBjets && dataPbPb->jtptA < recoJetPtCut) continue;
      //if (!doTrigEffCorr && dataPbPb->isTrig <1) continue;
      if ( dataPbPb->isTrig <1) continue;
      
      //if(!doBjets)if(dataPbPb->refpt < 50 && dataPbPb->jtptA>120) continue;
      //if(doBjets)if(dataPbPb->refpt < 50 && dataPbPb->jtptB>120) continue;

      float weight = dataPbPb->weight;

      if(doTrigEffCorr){
	for(int iBin = 0; iBin<nbins_rec; iBin++){
	  float myJtPt = 0.;
	  if(doBjets) myJtPt = dataPbPb->jtptB;
	  else myJtPt = dataPbPb->jtptA;
	  if(myJtPt > boundaries_rec[iBin] && myJtPt < boundaries_rec[iBin+1]){
	    if(doBjets) weight/= trigEffbJet[iBin];
	    else weight/= trigEffInc[iBin];
	  }							  
	}
      }
      if (!isMC||jentry2 % 2 == 1) {
	if(doBjets)uhist[cBin]-> hMatrix->Fill(dataPbPb->refpt,dataPbPb->jtptB,weight);
	else uhist[cBin]-> hMatrix->Fill(dataPbPb->refpt,dataPbPb->jtptA,weight);
      }	  
      if (jentry2 % 2 == 0) {
	uhist[cBin]-> hGen->Fill(dataPbPb->refpt,weight);   
	if(doBjets)uhist[cBin]-> hMeas->Fill(dataPbPb->jtptB,weight);  	 
	else uhist[cBin]-> hMeas->Fill(dataPbPb->jtptA,weight);  	 
	//uhist[cBin]-> hMeasJECSys->Fill(dataPbPb->jtpt*(1.+0.02/nbins_cent*(nbins_cent-i)),weight); 
	// FIXME!!!!!!  i is supposed to be a loop over centrality !!!!
	if(doBjets)uhist[cBin]-> hMeasJECSys->Fill(dataPbPb->jtptB*(1.+0.02/nbins_cent*(nbins_cent-0)),weight); 
	else uhist[cBin]-> hMeasJECSys->Fill(dataPbPb->jtptA*(1.+0.02/nbins_cent*(nbins_cent-0)),weight); 
      }
    }

    //pp will just fill the last index of the centrality array

    // fill pp MC
    for (Long64_t jentry2=0; jentry2<dataPP->tJet->GetEntries();jentry2++) {
      dataPP->tJet->GetEntry(jentry2);
      
      if ( dataPP->refpt<0) continue;
      if ( dataPP->jteta  > 2. || dataPP->jteta < -2. ) continue;
      if ( dataPP->refpt<0) dataPP->refpt=0;
      if ( doBjets && fabs(dataPP->refparton_flavorForB)!=5) continue;
      //if ( doBjets && dataPP->discr_ssvHighEff<2) continue;
      if ( dataPP->jtpt < recoJetPtCut) continue;
      
      if (!isMC||jentry2 % 2 == 1) {
	uhist[nbins_cent]-> hMatrix->Fill(dataPP->refpt,dataPP->jtpt,dataPP->weight);
      }	  
      if (jentry2 % 2 == 0) {
	uhist[nbins_cent]-> hGen->Fill(dataPP->refpt,dataPP->weight);   
	uhist[nbins_cent]-> hMeas->Fill(dataPP->jtpt,dataPP->weight); 
      }           
    }
  }
  /*
  for (int i=0;i<=nbins_cent;i++){
    for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
	float binContent = uhist[i]->hGen->GetBinContent(x);
	float binError = uhist[i]->hGen->GetBinError(x);
	float binWidth =  uhist[i]->hGen->GetXaxis()->GetBinWidth(x);
	uhist[i]->hGen->SetBinContent(x,binContent/binWidth);
	uhist[i]->hGen->SetBinError(x,binError/binWidth);
    }
  }

<<<<<<< HEAD
  for (int i=0;i<=nbins_cent;i++){
    for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
	float binContent = uhist[i]->hMeas->GetBinContent(x);
	float binError = uhist[i]->hMeas->GetBinError(x);
	float binWidth =  uhist[i]->hMeas->GetXaxis()->GetBinWidth(x);
	uhist[i]->hMeas->SetBinContent(x,binContent/binWidth);
	uhist[i]->hMeas->SetBinError(x,binError/binWidth);
    }
  }

  for (int i=0;i<=nbins_cent;i++){
    for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
      for (int y=1;y<=uhist[i]->hMatrix->GetNbinsY();y++) {
	float binContent = uhist[i]->hMatrix->GetBinContent(x,y);
	float binError = uhist[i]->hMatrix->GetBinError(x,y);
	float binWidth2 =  uhist[i]->hMatrix->GetXaxis()->GetBinWidth(x)*uhist[i]->hMatrix->GetYaxis()->GetBinWidth(y);
	uhist[i]->hMatrix->SetBinContent(x,y,binContent/binWidth2);
	uhist[i]->hMatrix->SetBinError(x,y,binError/binWidth2);
      }      
    }
  }	
  */


  if (isMC==0) {
    // Use measured histogram from Matt & Kurt's file
	   
    // PbPb file:

    TFile *infMatt = new TFile(fileNamePbPb_data);
    TH1F *hMattPbPb = NULL;
    TH1F *hTagEffPbPb = NULL;

    if(doBjets){
      hMattPbPb = (TH1F*) infMatt->Get("hRawBData");
      hTagEffPbPb = (TH1F*) infMatt->Get("hBEfficiencyMC");
    }
    else hMattPbPb = (TH1F*) infMatt->Get("hPbPb");
    //divideBinWidth(hMattPbPb);
           
    // Need to match the binning carefully, please double check whenever you change the binning
    for (int i=1;i<=hMattPbPb->GetNbinsX();i++)
      {
     	float binContent = hMattPbPb->GetBinContent(i);  
	float binError = hMattPbPb->GetBinError(i); 

	if(doBjets){
	  float tagEff =hTagEffPbPb->GetBinContent(i);
	  float tagEffErr =     hTagEffPbPb->GetBinError(i);   
	  
	  if(tagEff>0){
	    // careful of the order here!
	    binError=binContent/tagEff *sqrt(tagEffErr*tagEffErr/tagEff/tagEff + binError*binError/binContent/binContent);
	    binContent /= tagEff;
	  }
	  else cout<<" TAGEFF = 0"<<endl;	  
	}

	float binCenter = hMattPbPb->GetBinCenter(i);  
	if(binCenter - hMattPbPb->GetBinWidth(i)/2.  < recoJetPtCut) continue;
	
	int ibin=0;
	
	for(ibin=1;ibin<=uhist[0]->hMeas->GetNbinsX();ibin++){
	  float testLowEdge = uhist[0]->hMeas->GetBinLowEdge(ibin);
	  float testBinWidth = uhist[0]->hMeas->GetBinWidth(ibin);
	  if(binCenter>testLowEdge && binCenter < testLowEdge+testBinWidth) break;
	}
	
	
	if(doTrigEffCorr){
	  float trigEff = 0;
	  if(doBjets) trigEff = trigEffbJet[ibin-1];
	  else  trigEff = trigEffInc[ibin-1];

	  cout<<" binCenter = "<<binCenter<<" trigEff "<<trigEff<<endl;

	  if(trigEff>0){
	    // careful of the order here!
	    binContent /= trigEff;
	    binError /= trigEff;
	  }
	  else cout<<" TRIGEFF = 0"<<endl;	  
	}


     
	uhist[0]->hMeas->SetBinContent(ibin,binContent);  
	uhist[0]->hMeas->SetBinError(ibin,binError);  

      }

    // pp file:
    TFile *infMattPP = new TFile(fileNamePP_data);
    TH1F *hMattPP = NULL;
    TH1F *hTagEffPP = NULL;
    if(doBjets){
      hMattPP = (TH1F*) infMattPP->Get("hRawBData");
      hTagEffPP = (TH1F*) infMattPP->Get("hBEfficiencyMC");
    }
    else hMattPP = (TH1F*) infMattPP->Get("hpp");
    //divideBinWidth(hMattPP);	   
    for (int i=1;i<=hMattPP->GetNbinsX();i++)
      {
      	float binContent = hMattPP->GetBinContent(i);  
	float binError = hMattPP->GetBinError(i);  
	
	if(doBjets){
	  float tagEff =hTagEffPP->GetBinContent(i);
	  float tagEffErr =     hTagEffPP->GetBinError(i);   
	  if(tagEff>0){
	    // careful of the order here!
	    binError=binContent/tagEff *sqrt(tagEffErr*tagEffErr/tagEff/tagEff + binError*binError/binContent/binContent);
	    binContent /= tagEff;
	  }
	  else cout<<" TAGEFF = 0"<<endl;	  
	}
	
     	float binCenter = hMattPP->GetBinCenter(i);  
	if(binCenter - hMattPP->GetBinWidth(i)/2.  < recoJetPtCut) continue;

	int ibin=0;

	for(ibin=1;ibin<=uhist[nbins_cent]->hMeas->GetNbinsX();ibin++){
	  float testLowEdge = uhist[nbins_cent]->hMeas->GetBinLowEdge(ibin);
	  float testBinWidth = uhist[nbins_cent]->hMeas->GetBinWidth(ibin);
	  if(binCenter>testLowEdge && binCenter < testLowEdge+testBinWidth) break;
	}
	uhist[nbins_cent]->hMeas->SetBinContent(ibin,binContent);  
	uhist[nbins_cent]->hMeas->SetBinError(ibin,binError);  

    
	/*
	cout<<" i "<<i<<endl;
	int newBin = i+uhist[nbins_cent]->hMeas->FindBin(61)-1;

	cout<<" newBin "<<newBin<<endl;
	cout<<"hMattPP->GetBinCenter(i) "<<hMattPP->GetBinCenter(i)<<endl;
	cout<<"uhist[nbins_cent]->hMeas->GetBinCenter(newBin) "<<uhist[nbins_cent]->hMeas->GetBinCenter(newBin)<<endl;
	*/
      }

  }



   //=========================================Response Matrix========================================================= 

  cout <<"Response Matrix..."<<endl;
	
  TCanvas * cMatrix = new TCanvas("cMatrix","Matrix",800,400);
  cMatrix->Divide(2,1);

  for (int i=0;i<=nbins_cent;i++){
    cMatrix->cd(i+1);
    if (!useMatrixFromFile) {
      TF1 *f = new TF1("f","[0]*pow(x+[2],[1])");
      f->SetParameters(1e10,-8.8,40);
      for (int y=1;y<=uhist[i]->hMatrix->GetNbinsY();y++) {
	double sum=0;
	for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
	  if (uhist[i]->hMatrix->GetBinContent(x,y)<=1*uhist[i]->hMatrix->GetBinError(x,y)) {
	    uhist[i]->hMatrix->SetBinContent(x,y,0);
	    uhist[i]->hMatrix->SetBinError(x,y,0);
	  }
	  sum+=uhist[i]->hMatrix->GetBinContent(x,y);
	}
				
	for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {	   
	  double ratio = 1;
	  uhist[i]->hMatrix->SetBinContent(x,y,uhist[i]->hMatrix->GetBinContent(x,y)*ratio);
	  uhist[i]->hMatrix->SetBinError(x,y,uhist[i]->hMatrix->GetBinError(x,y)*ratio);
	}
      }
    }
    uhist[i]->hResponse = (TH2F*)uhist[i]->hMatrix->Clone(Form("hResponse_cent%d",i));

    for (int y=1;y<=uhist[i]->hResponse->GetNbinsY();y++) {
      double sum=0;
      for (int x=1;x<=uhist[i]->hResponse->GetNbinsX();x++) {
	if (uhist[i]->hResponse->GetBinContent(x,y)<=0*uhist[i]->hResponse->GetBinError(x,y)) {
	  uhist[i]->hResponse->SetBinContent(x,y,0);
	  uhist[i]->hResponse->SetBinError(x,y,0);
	}
	sum+=uhist[i]->hResponse->GetBinContent(x,y);
      }
			
      for (int x=1;x<=uhist[i]->hResponse->GetNbinsX();x++) {  	
	if (sum==0) continue;
	double ratio = uhist[i]->hMeas->GetBinContent(y)/sum;
	if (uhist[i]->hMeas->GetBinContent(y)==0) ratio = 1e-100/sum;
      }
    }
		
    TH1F *hProj = (TH1F*)uhist[i]->hResponse->ProjectionY(Form("hProj_cent%d",i));
    
    for (int y=1;y<=uhist[i]->hResponse->GetNbinsY();y++) {
      for (int x=1;x<=uhist[i]->hResponse->GetNbinsX();x++) {  	
	double sum=hProj->GetBinContent(y);
	cout <<y<<" "<<x<<" "<<sum<<endl;
	if (sum==0) continue;
	double ratio = uhist[i]->hMeas->GetBinContent(y)/sum;
	if (uhist[i]->hMeas->GetBinContent(y)==0) ratio = 1e-100/sum;
        uhist[i]->hResponse->SetBinContent(x,y,uhist[i]->hResponse->GetBinContent(x,y)*ratio);
	uhist[i]->hResponse->SetBinError(x,y,uhist[i]->hResponse->GetBinError(x,y)*ratio);
      }
    }

    uhist[i]->hResponseNorm = (TH2F*)uhist[i]->hMatrix->Clone(Form("hResponseNorm_cent%d",i));
    for (int x=1;x<=uhist[i]->hResponseNorm->GetNbinsX();x++) {
      double sum=0;
      for (int y=1;y<=uhist[i]->hResponseNorm->GetNbinsY();y++) {
	if (uhist[i]->hResponseNorm->GetBinContent(x,y)<=0*uhist[i]->hResponseNorm->GetBinError(x,y)) {
	  uhist[i]->hResponseNorm->SetBinContent(x,y,0);
	  uhist[i]->hResponseNorm->SetBinError(x,y,0);
	}
	sum+=uhist[i]->hResponseNorm->GetBinContent(x,y);
      }
			
      for (int y=1;y<=uhist[i]->hResponseNorm->GetNbinsY();y++) {  	
	if (sum==0) continue;
	double ratio = 1./sum;
	uhist[i]->hResponseNorm->SetBinContent(x,y,uhist[i]->hResponseNorm->GetBinContent(x,y)*ratio);
	uhist[i]->hResponseNorm->SetBinError(x,y,uhist[i]->hResponseNorm->GetBinError(x,y)*ratio);
      }
    }
		
    uhist[i]->hResponse->Draw("colz");
		
    if (!useMatrixFromFile) uhist[i]->hMatrixFit = uhist[i]->hMatrix;
    uhist[i]->hMatrixFit->SetName(Form("hMatrixFit_cent%d",i));
  }

  pbpb_Unfo->cd();
	
  cout << "==================================== UNFOLD ===================================" << endl;
	
  //char chmet[100]; 
	
  // ======================= Reconstructed pp and PbPb spectra =========================================================
  TCanvas * cPbPb = new TCanvas("cPbPb","Comparison",1200,600);
  cPbPb->Divide(2,1); 
  cPbPb->cd(1);
	
  TH1F *hRecoBW[nbins_cent+1], *hRecoBinByBinBW[nbins_cent+1], *hMeasBW[nbins_cent+1], *hGenBW[nbins_cent+1];


  TCanvas * cPbPbMeas = new TCanvas("cPbPbMeas","Measurement",1200,600);
  cPbPbMeas->Divide(2,1); 
  cPbPbMeas->cd(1);
	

  for (int i=0;i<=nbins_cent;i++) {
    cPbPb->cd(i+1)->SetLogy();   
    // Do Bin-by-bin
    TH1F *hBinByBinCorRaw = (TH1F*)uhist[i]->hResponse->ProjectionY(); 
    TH1F *hMCGen           = (TH1F*)uhist[i]->hResponse->ProjectionX(); // gen
    hBinByBinCorRaw->Divide(hMCGen);
    TF1 *f = new TF1("f","[0]+[1]*x");
    hBinByBinCorRaw->Fit("f","LL ","",90,300);
    TH1F* hBinByBinCor = (TH1F*)hBinByBinCorRaw->Clone();//functionHist(f,hBinByBinCorRaw,Form("hBinByBinCor_cent%d",i));
    uhist[i]->hRecoBinByBin = (TH1F*) uhist[i]->hMeas->Clone(Form("hRecoBinByBin_cent%d",i));
    uhist[i]->hRecoBinByBin->Divide(hBinByBinCor);
		
    // Do unfolding
    //if (isMC) uhist[i]->hMeas = (TH1F*)uhist[i]->hMatrix->ProjectionY()->Clone(Form("hMeas_cent%d",i));
    prior myPrior(uhist[i]->hMatrixFit,uhist[i]->hMeas,0);
    myPrior.unfold(uhist[i]->hMeas,1);
    TH1F *hPrior;//=(TH1F*) functionHist(fPow,uhist[i]->hMeas,Form("hPrior_cent%d",i));
//    hPrior = (TH1F*)uhist[i]->hGen->Clone("hPrior");
//    hPrior = (TH1F*)uhist[i]->hMeas->Clone(Form("hPrior_cent%d",i));
    hPrior=(TH1F*)hMCGen->Clone("hPrior");
    removeZero(hPrior);
    TH1F *hReweighted = (TH1F*)(TH1F*)uhist[i]->hResponse->ProjectionY(Form("hReweighted_cent%d",i));
		
    bayesianUnfold myUnfoldingJECSys(uhist[i]->hMatrixFit,hPrior,0);
    myUnfoldingJECSys.unfold(uhist[i]->hMeasJECSys,nBayesianIter);
    bayesianUnfold myUnfoldingSmearSys(uhist[i]->hMatrixFit,hPrior,0);
    myUnfoldingSmearSys.unfold(uhist[i]->hMeasSmearSys,nBayesianIter);
    bayesianUnfold myUnfolding(uhist[i]->hMatrixFit,myPrior.hPrior,0);
    myUnfolding.unfold(uhist[i]->hMeas,nBayesianIter);
    cout <<"Unfolding bin "<<i<<endl;

    delete hBinByBinCorRaw;
    delete hMCGen;

    // Iteration Systematics
    for (int j=2;j<=7;j++)
      {

	bayesianUnfold myUnfoldingSys(uhist[i]->hMatrixFit,hPrior,0);
	myUnfoldingSys.unfold(uhist[i]->hMeas,j);
	uhist[i]->hRecoIterSys[j]  = (TH1F*) myUnfoldingSys.hPrior->Clone(Form("hRecoRAA_IterSys%d_cent%d",j,i));
      }
    
    
    uhist[i]->hReco         = (TH1F*) uhist[i]->hRecoIterSys[nBayesianIter]->Clone(Form("Unfolded_cent%i",i));
    uhist[i]->hRecoJECSys   = (TH1F*) myUnfoldingJECSys.hPrior->Clone(Form("UnfoldedJeCSys_cent%i",i));
    uhist[i]->hRecoSmearSys   = (TH1F*) myUnfoldingSmearSys.hPrior->Clone(Form("UnfoldedSmearSys_cent%i",i));
    uhist[i]->hRecoBinByBin->SetName(Form("UnfoldedBinByBin_cent%i",i));
    
    if (doToy) {
      TCanvas *cToy = new TCanvas("cToy","toy",600,600);
      cToy->cd();
      int nExp=1000;
      TH1F *hTmp[nbins_truth+1];
      TH1F *hTmp2[nbins_truth+1];
      for (int j=1;j<=nbins_truth;j++) {
	hTmp[j] = new TH1F(Form("hTmp%d",j),"",200,0,10.+uhist[i]->hReco->GetBinContent(j)*2);
	hTmp2[j] = new TH1F(Form("hTmp2%d",j),"",200,0,10.+uhist[i]->hRecoBinByBin->GetBinContent(j)*2);
      }
      for (int exp =0; exp<nExp; exp++) {
	TH1F *hToy = (TH1F*)uhist[i]->hMeas->Clone();   
	TH2F *hMatrixToy = (TH2F*)uhist[i]->hMatrixFit->Clone();
	hToy->SetName("hToy");
	if (exp%100==0) cout <<"Pseudo-experiment "<<exp<<endl;
	for (int j=1;j<=hToy->GetNbinsX();j++) {
	  double value = gRandom->Poisson(uhist[i]->hMeas->GetBinContent(j));
	  hToy->SetBinContent(j,value);
	}
				
	for (int j=1;j<=hMatrixToy->GetNbinsX();j++) {
	  for (int k=1;k<=hMatrixToy->GetNbinsY();k++) {
	    double value = gRandom->Gaus(uhist[i]->hMatrixFit->GetBinContent(j,k),uhist[i]->hMatrixFit->GetBinError(j,k));
	    hMatrixToy->SetBinContent(j,k,value);
	  }
	}

	prior myPriorToy(hMatrixToy,hToy,0.0);
	myPriorToy.unfold(hToy,1);
	bayesianUnfold myUnfoldingToy(hMatrixToy,myPriorToy.hPrior,0.0);
	myUnfoldingToy.unfold(hToy,nBayesianIter);
	TH1F *hRecoTmp = (TH1F*) myUnfoldingToy.hPrior->Clone();
				
	for (int j=1;j<=hRecoTmp->GetNbinsX();j++) {
	  hTmp[j]->Fill(hRecoTmp->GetBinContent(j));
	}
	delete hToy;
	delete hRecoTmp;
	delete hMatrixToy;
      }
      TF1 *fGaus = new TF1("fGaus","[0]*TMath::Gaus(x,[1],[2])");
      for (int j=1;j<=nbins_truth;j++)
	{

	  f->SetParameters(hTmp[j]->GetMaximum(),hTmp[j]->GetMean(),hTmp[j]->GetRMS());
				
	  if (hTmp[j]->GetMean()>0) {
	    hTmp[j]->Fit(fGaus,"LL Q ");
	    hTmp[j]->Fit(fGaus,"LL Q ");
	    uhist[i]->hReco->SetBinError(j,f->GetParameter(2));
	  }	       
	  f->SetParameters(hTmp2[j]->GetMaximum(),hTmp2[j]->GetMean(),hTmp2[j]->GetRMS());
	  if (hTmp2[j]->GetMean()>0) {
	    hTmp2[j]->Fit(fGaus,"LL Q ");
	    hTmp2[j]->Fit(fGaus,"LL Q ");
	    uhist[i]->hRecoBinByBin->SetBinError(j,f->GetParameter(2));
	  }	       
	  delete hTmp[j];
	  delete hTmp2[j];
	}
      cPbPb->cd(i+1);
    }

    uhist[i]->hMeas->SetMarkerStyle(20);
    uhist[i]->hMeas->SetMarkerColor(2);
    uhist[i]->hReco->SetMarkerStyle(25);
    uhist[i]->hReco->SetName(Form("hReco_cent%d",i));
    
    uhist[i]->hReco->SetXTitle("p_{T} (GeV/c)");    
    uhist[i]->hReco->SetYTitle("Counts");    
    uhist[i]->hReco->GetXaxis()->SetNdivisions(505);
    //uhist[i]->hReco->Draw("");    
    uhist[i]->hReco->SetAxisRange(0,250,"X");
    uhist[i]->hReco->Draw("");   
     
    uhist[i]->hGen->SetLineWidth(2);
    uhist[i]->hGen->SetLineColor(2);
    //if(isMC)uhist[i]->hGen->Draw("hist same");
    //uhist[i]->hReco->Draw("same");    
    uhist[i]->hRecoBinByBin->SetMarkerStyle(28);
    uhist[i]->hRecoBinByBin->Draw("same");    

    uhist[i]->hReco->SetAxisRange(recoJetPtCut,300);
    TH1F *hReproduced = (TH1F*)myUnfolding.hReproduced->Clone(Form("hReproduced_cent%d",i));
    hReproduced->SetMarkerColor(4);
    hReproduced->SetMarkerStyle(24);
    //uhist[i]->hMeas->Draw("same");    

    hRecoBW[i] = (TH1F*)uhist[i]->hReco->Clone(Form("hReco%d",i));
    hRecoBinByBinBW[i] = (TH1F*)uhist[i]->hRecoBinByBin->Clone(Form("hRecoBinByBin%d",i));
    hMeasBW[i] = (TH1F*)uhist[i]->hMeas->Clone(Form("hMeas%d",i));
    if(isMC)hGenBW[i] = (TH1F*)uhist[i]->hGen->Clone(Form("hGen%d",i));

    divideBinWidth(hRecoBW[i]);    
    if(isMC)divideBinWidth(hGenBW[i]);    
    divideBinWidth(hRecoBinByBinBW[i]);    
    divideBinWidth(hMeasBW[i]);    

    hRecoBW[i]->Draw();
    if(isMC)hGenBW[i]->Draw("hist,same");
    hRecoBinByBinBW[i]->Draw("same");
    hMeasBW[i]->Draw("same");
    

    uhist[i]->hReco->SetTitle("Baysian Unfolded");
    uhist[i]->hRecoBinByBin->SetTitle("Bin-by-bin Unfolded");

    TLegend *leg = new TLegend(0.45,0.65,0.85,0.95);
    leg->SetBorderSize(0);
    leg->SetFillStyle(0);
    leg->AddEntry(uhist[i]->hMeas,"Measured","pl");
    leg->AddEntry(uhist[i]->hReco,"Bayesian unfolded","pl");
    leg->AddEntry(uhist[i]->hRecoBinByBin,"Bin-by-bin unfolded","pl");
    if(isMC)leg->AddEntry(uhist[i]->hGen,"Generator level truth","l");
    leg->Draw();

    cPbPbMeas->cd(i+1)->SetLogy();   
    uhist[i]->hMeas->SetAxisRange(0,240,"X");
    uhist[i]->hMeas->Draw();
    hReproduced->Draw("same");

    TLegend *leg2 = new TLegend(0.5,0.5,0.85,0.9);
    leg2->SetBorderSize(0);
    leg2->SetFillStyle(0);
    leg2->AddEntry(uhist[i]->hMeas,"Measured","pl");
    leg2->AddEntry(hReproduced,"Reproduced","pl");

    leg2->Draw();
  }	     
  
 
  pbpb_Unfo->Write();

  SysData systematics;
  TLine *line = new TLine(60,1,250,1);

  // Iteration systematics
  TCanvas *cIterSys = new TCanvas("cIterSys","cIterSys",1200,600);
  cIterSys->Divide(2,1);
  cIterSys->cd(2);
  TH1F *hRecoIterSysPP[100];
  TH1F *hRebinPP_tmp         = rebin(uhist[nbins_cent]->hReco, (char*)"hRebinPP_tmp");
  TLegend *legBayesianIterPP = myLegend(0.4,0.7,0.9,0.9);
  legBayesianIterPP->AddEntry("","PP","");
         
  for (int j=2;j<7;j++) {
    hRecoIterSysPP[j] = rebin(uhist[nbins_cent]->hRecoIterSys[j],Form("hRecoIterSysPP_IterSys%d",j));
    hRecoIterSysPP[j]->SetLineColor(colorCode[j-2]);
    hRecoIterSysPP[j]->SetMarkerColor(colorCode[j-2]);
    hRecoIterSysPP[j]->Divide(hRebinPP_tmp);
    if (j==2){
      makeHistTitle(hRecoIterSysPP[j],(char*)"",(char*)"Jet p_{T} (GeV/c)",(char*)"Ratio (Unfolded / Nominal)");
      hRecoIterSysPP[j]->SetTitleOffset(1.4,"Y");
      hRecoIterSysPP[j]->SetTitleOffset(1.2,"X");
      hRecoIterSysPP[j]->SetAxisRange(0.5,1.5,"Y");
      hRecoIterSysPP[j]->Draw(); 
    } else {
      hRecoIterSysPP[j]->Draw("same");
    }
         
    checkMaximumSys(systematics.hSysIter[nbins_cent],hRecoIterSysPP[j],0,1.1);
    legBayesianIterPP->AddEntry(hRecoIterSysPP[j],Form("Iteration %d",j),"pl");     
  }

  legBayesianIterPP->Draw();
  line->Draw();
  drawEnvelope(systematics.hSysIter[nbins_cent],(char*)"hist same");


  cIterSys->cd(1);
  TH1F *hRecoIterSysPbPb[100];
  TH1F *hRebinPbPb_tmp         = rebin(uhist[0]->hReco, (char*)"hRebinPbPb_tmp");
  TLegend *legBayesianIterPbPb = myLegend(0.4,0.7,0.9,0.9);
  legBayesianIterPbPb->AddEntry("","PbPb","");
  for (int j=2;j<7;j++) {
    hRecoIterSysPbPb[j] = rebin(uhist[0]->hRecoIterSys[j],Form("hRecoIterSysPbPb_IterSys%d",j));
    hRecoIterSysPbPb[j]->SetLineColor(colorCode[j-2]);
    hRecoIterSysPbPb[j]->SetMarkerColor(colorCode[j-2]);
    hRecoIterSysPbPb[j]->Divide(hRebinPbPb_tmp);
    if (j==2){
      makeHistTitle(hRecoIterSysPbPb[j],(char*)"",(char*)"Jet p_{T} (GeV/c)",(char*)"Ratio (Unfolded / Nominal)");
      hRecoIterSysPbPb[j]->SetTitleOffset(1.4,"Y");
      hRecoIterSysPbPb[j]->SetTitleOffset(1.2,"X");
      hRecoIterSysPbPb[j]->SetAxisRange(0.5,1.5,"Y");
      hRecoIterSysPbPb[j]->Draw(); 
    } else {
      hRecoIterSysPbPb[j]->Draw("same");
    }
         
    checkMaximumSys(systematics.hSysIter[0],hRecoIterSysPbPb[j],0,1.1);
    legBayesianIterPbPb->AddEntry(hRecoIterSysPbPb[j],Form("Iteration %d",j),"pl");     
  }
  legBayesianIterPbPb->Draw();
  line->Draw();
  drawEnvelope(systematics.hSysIter[0],(char*)"hist same");
}
void combineBins(int mass, double scale_factor = 1.0){ //mass = mass of tprime quark

  //define some parameters
  //char fname[100]={"data/mujets_821/tprime_mujets_2D_821ipb.root"}; //input file name
  char fname[100]={"data/ejets_3560/tprime_ejets_2D_3560ipb.root"}; //input file name
  char oname[256]; //output file name
  char sname[100]; //name of signal histogram
  //sprintf(oname,"data/mujets_821/tprime_%i_mujets_2D_821ipb_merged_15jul2011test.root",mass);
  sprintf(oname,"data/mujets_821/tprime_%i_mujets_2D_821ipb_merged_test.root",mass);
  sprintf(sname,"TPrime%i_HtvsMfit",mass);
  char bname[20][100]={ //array of data and background histograms
    "Data_HtvsMfit", //data histogram must be first in this list
    "TTjets_HtvsMfit",
    "Ewk_HtvsMfit",
    "TPrime%i_HtvsMfit_JESup",
    "TPrime%i_HtvsMfit_JESdown",
    "TTjets_HtvsMfit_JESup",
    "TTjets_HtvsMfit_JESdown",
    "Ewk_HtvsMfit_JESup",
    "Ewk_HtvsMfit_JESdown"
  };
  
  int nb=9; //number of histograms in list
  int n_skip=3; // starting with this index, do not consider for background normalization
  float femax=0.20; //max fractional error in each bin of background histogram

  TFile *f = TFile::Open(fname);
  if (f==NULL) {
    printf("Cannot open file '%s'\n",fname);
    return;
  }

  TH2F* hs; f->GetObject(sname,hs); 
  // Gena: scale signal template to proper cross section
  hs->Scale(scale_factor);
  if (hs==NULL) {
    printf("Cannot find histogram '%s' in '%s'\n",sname,fname);
    return;
  }

  //figure out the binning
  int nx = hs->GetNbinsX()+2;
  int ny = hs->GetNbinsY()+2;

  // cross check printout
  std::cout << "2D hist name: " << hs->GetName() << std::endl;
  std::cout << "Integral with overflow: " << hs->Integral(0,nx-1,0,ny-1) << std::endl;
  std::cout << "Integral no overflow: " << hs->Integral(1,nx-2,1,ny-2) << std::endl << std::endl;

  TH2F *hb = (TH2F*)hs->Clone(); 
  hb->SetName("hb");
  hb->Reset();
  TH2F *hX[20];
  for (int i=0;i<nb;i++){
    std::string sBName(bname[i]);
    // GENA: get names for signal JES histos
    if (sBName.find("TPrime")!=std::string::npos ||
	sBName.find("Tprime")!=std::string::npos ||
	sBName.find("tprime")!=std::string::npos){

      sprintf(bname[i],sBName.c_str(),mass);
      std::cout << bname[i] << std::endl;
    }

    f->GetObject(bname[i],hX[i]); 

    // GENA: scale JES signal templates to proper cross section
    if (sBName.find("TPrime")!=std::string::npos ||
	sBName.find("Tprime")!=std::string::npos ||
	sBName.find("tprime")!=std::string::npos){
      hX[i]->Scale(scale_factor);      
    }
    if (hX[i]==NULL) {
      printf("Cannot find histogram '%s' in '%s'\n",bname[i],fname);
      return;
    }
    //hX[i]->Print("base");
    std::cout << "2D hist name: " << hX[i]->GetName() << std::endl;
    std::cout << "Integral with overflow: " << hX[i]->Integral(0,nx-1,0,ny-1) << std::endl;
    std::cout << "Integral no overflow: " << hX[i]->Integral(1,nx-2,1,ny-2) << std::endl << std::endl;
    //sum all background histograms into hb; do not add the data histogram
    if (i>0 && i<n_skip) hb->Add(hX[i]); 
  }

  //figure out the binning
  //int nx = hs->GetNbinsX()+2;
  //int ny = hs->GetNbinsY()+2;
  int nbin=nx*ny;
  std::cout << "number of bins: x="<<nx<<", y="<<ny<<std::endl;
  
  //book some 1d histograms with the same number of bins for diagnostics
  TH1F *h1sb = new TH1F("h1sb","h1sb",nbin,0,nbin);
  TH1F *h1s = new TH1F("h1s","h1s",nbin,0,nbin);
  TH1F *h1b = new TH1F("h1b","h1b",nbin,0,nbin);
  // GENA: vector to create 2D->1D bin map
  std::vector<std::vector<int> > vMap(nbin);

  float xs,xb;
  //xsb holds the s/b values for each bin
  //xx are the histogram contents 
  //(0=signal, 1=total background, 2=data, 3...nb-1=individual backgrounds) GENA: nb+1 ?
  float xsb[30000],xx[30000][20],xe[30000][20];
  int ibin; 
  double _sum = 0.0;
  for (int i=0;i<nx;i++){
    for (int j=0;j<ny;j++){

      ibin=hs->GetBin(i,j);

      // GENA: Will fill each bin with its original index
      vMap[ibin].push_back(ibin);

      xs=hs->GetBinContent(ibin);
      xb=hb->GetBinContent(ibin);
      //compute signal/background
      if (xb>0) {
	xsb[ibin]=xs/xb;
      }else{
	if (xs>0){
	  xsb[ibin]=999;
	}else{
	  xsb[ibin]=0;
	}
      }
      xx[ibin][0]=xs;
      xe[ibin][0]=hs->GetBinError(ibin);
      xx[ibin][1]=xb;
      xe[ibin][1]=hb->GetBinError(ibin);
      for (int k=0;k<nb;k++){
	xx[ibin][k+2]=hX[k]->GetBinContent(ibin);
	xe[ibin][k+2]=hX[k]->GetBinError(ibin);
      }
      if (xb>0) h1sb->SetBinContent(ibin,xs/xb);
      h1s->SetBinContent(ibin,xx[ibin][0]);
      h1s->SetBinError(ibin,xe[ibin][0]);
      h1b->SetBinContent(ibin,xx[ibin][1]);
      h1b->SetBinError(ibin,xe[ibin][1]);
      
      _sum += xx[ibin][0];
    }
  }

  std::cout << "SUM: " << _sum << std::endl;

  //sort all histogram bins in decreasing s/b
  int nswap=1;
  float xtmp;

  // GENA: for bin map
  int ibin_tmp;

  while (nswap>0) {
    nswap=0;
    for (int i=0;i<nbin-1;i++) {
      if (xsb[i]<xsb[i+1]){
	xtmp=xsb[i];
	xsb[i]=xsb[i+1];
	xsb[i+1]=xtmp;

	// GENA: for bin map
	ibin_tmp = vMap[i][0];
	vMap[i][0] = vMap[i+1][0];
	vMap[i+1][0] = ibin_tmp;

	for (int j=0;j<nb+2;j++){
	  xtmp=xx[i][j];
	  xx[i][j]=xx[i+1][j];
	  xx[i+1][j]=xtmp;

	  xtmp=xe[i][j];
	  xe[i][j]=xe[i+1][j];
	  xe[i+1][j]=xtmp;
	}
	nswap=nswap+1;
      }
    }
  }

  //these histograms have the bins ordered in decrerasing s/b for diagnostics
  TH1F *h1sb1 = new TH1F("h1sb1","h1sb1",nbin,0,nbin);
  TH1F *h1fe1 = new TH1F("h1fe1","h1fe1",nbin,0,nbin);
  TH1F *h1s1 = new TH1F("h1s1","h1s1",nbin,0,nbin);
  TH1F *h1b1 = new TH1F("h1b1","h1b1",nbin,0,nbin);
  for (int i=0;i<nbin;i++){
    h1sb1->SetBinContent(i+1,xsb[i]);
    if (xx[i][1]>0) h1fe1->SetBinContent(i+1,xe[i][1]/xx[i][1]);
    h1s1->SetBinContent(i+1,xx[i][0]);
    h1s1->SetBinError(i+1,xe[i][0]);
    h1b1->SetBinContent(i+1,xx[i][1]);
    h1b1->SetBinError(i+1,xe[i][1]);
  }


  //combine bins starting with the highest s/b until the fractional error in
  //the total backround in every bin is smaller than femax
  int ncomb=1;
  //float xtmp;
  float fe=0;
  while (ncomb>0) {
    ncomb=0;
    for (int i=0;i<nbin-1;i++){

      if (xx[i][1]>0){
	fe=xe[i][1]/xx[i][1]; //fractional error in background
      }else{
	fe=1;
      }
      if (fe>femax){

	// GENA: write down bin
	for (std::vector<int>::const_iterator vi=vMap[i+1].begin();
	     vi != vMap[i+1].end(); ++vi){
	  vMap[i].push_back(*vi);
	}
	//move all successive bins up
	vMap.erase(vMap.begin()+i+1);

	for (int k=0;k<nb+2;k++){ //add the next bin
	  xx[i][k]=xx[i][k]+xx[i+1][k];
	  xe[i][k]=sqrt(xe[i][k]*xe[i][k]+xe[i+1][k]*xe[i+1][k]);
	  for (int j=i+1;j<nbin-1;j++){ //move all successive bins up
	    xx[j][k]=xx[j+1][k];
	    xe[j][k]=xe[j+1][k];
	  }
	}
	ncomb++;
	nbin=nbin-1; //decrease the total number of bins

      }
    }
  }


  //GENA: open the map file
  std::ofstream mapFile;
  mapFile.open("bin.map");
  int bin_count = 0;
  for (std::vector<std::vector<int> >::const_iterator i=vMap.begin();
       i != vMap.end(); ++i){

    mapFile << " " << i-vMap.begin()+1 << ":";

    for(std::vector<int>::const_iterator j=i->begin();
	j != i->end(); ++j){
      mapFile << " " << *j;
      ++bin_count;
    }

    mapFile << std::endl;

  }
  //GENA: close the map file
  mapFile.close();

  //these are the output histograms
  TFile *f2 = TFile::Open(oname,"recreate");
  TH1F *h1feb2 = new TH1F("h1fe2","h1fe2",nbin,0,nbin);
  TH1F *h1s2 = new TH1F(sname,sname,nbin,0,nbin);
  TH1F *h1b2 = new TH1F("h1b2","h1b2",nbin,0,nbin);
  TH1F *h1X2[20];
  for (int i=0;i<nb;i++){
    h1X2[i] = new TH1F(bname[i],bname[i],nbin,0,nbin);
  }
  for (int i=0;i<nbin;i++){
    h1feb2->SetBinContent(i+1,xe[i][1]/xx[i][1]);
    h1s2->SetBinContent(i+1,xx[i][0]);
    h1s2->SetBinError(i+1,xe[i][0]);
    h1b2->SetBinContent(i+1,xx[i][1]);
    h1b2->SetBinError(i+1,xe[i][1]);
    for (int j=0;j<nb;j++){
      h1X2[j]->SetBinContent(i+1,xx[i][j+2]);
      h1X2[j]->SetBinError(i+1,xe[i][j+2]);
    }
  }
  
  std::cout << "Merged 1D hist name: " << h1s2->GetName() << std::endl;
  std::cout << "Integral with overflow: " << h1s2->Integral(0,nbin+1) << std::endl;
  std::cout << "Integral no overflow: " << h1s2->Integral(1,nbin) << std::endl << std::endl;
  h1s2->Write();
  for (int j=0;j<nb;j++){
    std::cout << "Merged 1D hist name: " << h1X2[j]->GetName() << std::endl;
    std::cout << "Integral with overflow: " << h1X2[j]->Integral(0,nbin+1) << std::endl;
    std::cout << "Integral no overflow: " << h1X2[j]->Integral(1,nbin) << std::endl << std::endl;
    h1X2[j]->Write();
  }
  
  h1s2->Print("base");

  f2->Close();
  f->Close();

  std::cout << "map size: " << vMap.size() << " combined bins" << std::endl;
  std::cout << "total bins merged: " << bin_count << std::endl;
}
void readTimeConstants()
 {

 // read basic.dat file
 //  file has 5 coulumns of data
 //  but we want to read only first 4 collumns
 
 TString dir = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName());
 dir.ReplaceAll("readTimeConstants.C","");
 dir.ReplaceAll("/./","/");
 ifstream in;
 //in.open(Form("%sbasic.dat",dir.Data()));
 in.open(Form("dumpConstants-0.dat",dir.Data()));

  int x;
  int y;
  int z;
 Float_t t, id;
 Int_t nlines = 0;

 TFile *f = new TFile("TimeCalibs.root","RECREATE");
 TH2F* calibMapEB = new TH2F("calibMapEB","Mean Time map EB [ns];i#phi;i#eta",360,1.,361.,171,-85,86);
 calibMapEB->Sumw2();
 TH2F* calibMapEEM = new TH2F("calibMapEEM","Mean Time map EE-; ix; iy",100,1,101,100,1,101);
 calibMapEEM->Sumw2();
 TH2F* calibMapEEP = new TH2F("calibMapEEP","Mean Time map EE+ ;ix;iy",100,1,101,100,1,101);
 calibMapEEP->Sumw2();

 //while (!in.eof()) {
 while (1) {
      in >> x >> y >> z >> t >> id ;
      if (!in.good()) break;
     // if (nlines < 5)  printf("x=%3i, y=%3i, z=%1i\n, t=%8f\n",x,y,z,t);continue;
      if(z == 0) { 
                     calibMapEB->Fill(y,x,t);
		     //printf("x=%3i, y=%3i, z=%1i\n, t=%8f\n",x,y,z,t);
		     }
      else{
          if( z < 1) { calibMapEEM->Fill(x,y, t);}
	  else{ calibMapEEP->Fill(x,y,t);}
	  }
      nlines++;

   }   


 printf(" found %d points\n",nlines);
 in.close();


//Move empty bins out of the way -- EB
  int nxbins = calibMapEB->GetNbinsX();
  int nybins = calibMapEB->GetNbinsY();
  for (int p=1;p<=nxbins;++p)
  {
    for (int q=1;q<=nybins;++q)
    {
      double binentsM = calibMapEB->GetBinContent(p,q);
      if(binentsM==0)
      {
        calibMapEB->SetBinContent(p,q,-1000);
      }
    }
  }

  //Move empty bins out of the way -- EE
  nxbins = calibMapEEM->GetNbinsX();
  nybins = calibMapEEM->GetNbinsY();
  for (int n=1;n<=nxbins;++n)
  {
    for (int m=1;m<=nybins;++m)
    {
      double binentsM = calibMapEEM->GetBinContent(n,m);
      if(binentsM==0)
      {
        calibMapEEM->SetBinContent(n,m,-1000);
      }
      double binentsP = calibMapEEP->GetBinContent(n,m);
      if(binentsP==0)
      {
        calibMapEEP->SetBinContent(n,m,-1000);
      }
    }
  }

int min = -10;

int max = 10;

calibMapEB->GetZaxis()->SetRangeUser(min, max); // ... set the range ...
calibMapEEM->GetZaxis()->SetRangeUser(min, max); // ... set the range ...
calibMapEEP->GetZaxis()->SetRangeUser(min, max); // ... set the range ...
 f->Write();

 }
Exemple #29
0
//------------------------------------------------------------------------------
// DrawIt
//------------------------------------------------------------------------------
void DrawIt(TString filename,
	    TString hname,
	    TString cname,
	    TString title)
{
  TFile* inputfile = TFile::Open("../AuxiliaryFilesWZXS8TeV/" + filename + ".root");

  TH2F* h = (TH2F*)inputfile->Get(hname)->Clone(cname);

  h->SetDirectory(0);

  inputfile->Close();

  TString name = h->GetName();

  TCanvas* canvas = new TCanvas(name, name, 600, 600);

  if (name.Contains("PR")) canvas->SetLogx();
  if (name.Contains("SF")) canvas->SetLogx();

  canvas->SetLeftMargin (0.9 * canvas->GetLeftMargin());
  canvas->SetRightMargin(3.5 * canvas->GetRightMargin());
  canvas->SetTopMargin  (1.2 * canvas->GetTopMargin());

  TH2FAxisFonts(h, "x", "p_{T} [GeV]");
  TH2FAxisFonts(h, "y", "#eta");

  h->Draw("colz");

  h->SetTitle("");

  DrawTLatex(42, 0.940, 0.976, _bigLabelSize, 33, title);

  if (!title.Contains("trigger")) {

    Double_t hmin = h->GetMinimum();
    Double_t hmax = h->GetMaximum();

    for (Int_t i=1; i<=h->GetNbinsX(); i++) {
      for (Int_t j=1; j<=h->GetNbinsY(); j++) {

	Double_t value = h->GetBinContent(i,j);

	Double_t ypos = h->GetYaxis()->GetBinCenter(j);
	Double_t xpos = h->GetXaxis()->GetBinCenter(i);
      
	if (gPad->GetLogx()) xpos = h->GetXaxis()->GetBinCenterLog(i);

	TLatex* latex = new TLatex(xpos, ypos, Form("%.2f", value));

	latex->SetTextAlign(   22);
	latex->SetTextFont (   42);
	latex->SetTextSize (0.027);

	if (value < hmin + 0.3*(hmax - hmin)) latex->SetTextColor(kWhite);
	
	latex->Draw();
      }
    }
  }


  // Set the palette font
  //----------------------------------------------------------------------------
  canvas->Update();

  TPaletteAxis* palette = (TPaletteAxis*)h->GetListOfFunctions()->FindObject("palette");

  palette->SetLabelFont(42);


  // Save the plot
  //----------------------------------------------------------------------------
  canvas->Update();
  
  canvas->Modified();

  canvas->GetFrame()->DrawClone();

  canvas->SaveAs("pdf/scale_factors/" + name + ".pdf");
  canvas->SaveAs("png/scale_factors/" + name + ".png");
}
TH2F* mirrortemplates(int sampleIndex){
  TFile* alt1,*orig;
  if (sampleIndex==1){
    alt1 = new TFile(destDir + "qqH_vbfMELA_alt.root","OPEN");
    orig = new TFile(destDir + "qqH_vbfMELA.root","OPEN");
  }
  if (sampleIndex==2){
    //cout<<"here?"<<endl;
    alt1 = new TFile(destDir + "qqZZ_vbfMELA_old_alt.root","OPEN");
    orig = new TFile(destDir + "qqZZ_vbfMELA_old.root","OPEN");
  }
  TH2F* altfisher = (TH2F*)alt1->Get("H_Djet");
  TH2F* origfisher = (TH2F*)orig->Get("H_Djet");
  TH2F* alt2fisher = new TH2F("H_Djet","H_Djet",int((highMzz-100.)/mBinSize+0.5),100,highMzz,50,0.,1.);

  gStyle->SetPalette(1);

  TCanvas* c1 = new TCanvas("c1","c1",800,800);
  c1->cd();
  altfisher->Draw("colz");

  TCanvas* c2 = new TCanvas("c2","c2",800,800);
  c2->cd();
  origfisher->Draw("colz");

  for(int i=1;i<=origfisher->GetNbinsX();i++){
    for(int j=1;j<=origfisher->GetNbinsY();j++){
      float origval=origfisher->GetBinContent(i,j);
      float alt1val=altfisher->GetBinContent(i,j);
      //cout<<origfisher->GetXaxis()->GetBinCenter(i)<<" "<<origfisher->GetYaxis()->GetBinCenter(j)<<" "<<origval<<" "<<alt1val<<endl;
      float scale=origval/alt1val;
      float alt2val=scale*origval;
      //TH1F* origproj = (TH1F*) origfisher->GetProjection("origproj",i,i);
      //TH1F* altproj = (TH1F*) altfisher->GetProjection("altproj",i,i);      
      alt2fisher->SetBinContent(i,j,alt2val);
    }
  }
  
  TCanvas* c3 = new TCanvas("c3","c3",800,800);
  c3->cd();
  alt2fisher->Draw("colz");

  //Renormalize
  TH1F* tempProj;
  double norm;
  for(int i=1; i<=alt2fisher->GetNbinsX(); i++){
    tempProj = (TH1F*) alt2fisher->ProjectionY("tempProj",i,i);
    norm=tempProj->Integral();
    if (norm>0) { // Avoid introducing NaNs in the histogram
      for(int j=1; j<=alt2fisher->GetNbinsY(); j++){
	alt2fisher->SetBinContent(i,j,alt2fisher->GetBinContent(i,j)/norm);
      }
    }
    //if(norm==0.) cout<<"HERE?"<<endl;
  }

  TCanvas* c4 = new TCanvas("c4","c4",800,800);
  c4->cd();
  alt2fisher->Draw("colz");
	 	 
  return alt2fisher;
}