예제 #1
0
void Occupancy::postProcessing()
{
  if (_postProcessed) return;

  // Generate the bounds of the 1D occupancy hist
  unsigned int totalHits = 0;
  unsigned int maxHits = 0;
  for (unsigned int nsens = 0; nsens < _device->getNumSensors(); nsens++)
  {
    Mechanics::Sensor* sensor = _device->getSensor(nsens);
    TH2D* occ = _hitOcc.at(nsens);

    for (unsigned int x = 0; x < sensor->getNumX(); x++)
    {
      for (unsigned int y = 0; y < sensor->getNumY(); y++)
      {
        const unsigned int numHits = occ->GetBinContent(x + 1, y + 1);
        totalHits += numHits;
        if (numHits > maxHits) maxHits = numHits;
      }
    }
  }

  TDirectory* plotDir = makeGetDirectory("Occupancy");

  std::stringstream name;
  std::stringstream title;

  name << "OccupancyDistribution";
  title << "Occupancy Distribution";

  _occDistribution = new TH1D(name.str().c_str(), title.str().c_str(),
                              100, 0, (double)maxHits / (double)totalHits);

  _occDistribution->SetDirectory(_dir);
  _occDistribution->GetXaxis()->SetTitle("Hits per trigger");
  _occDistribution->GetYaxis()->SetTitle("Pixels");
  _occDistribution->SetDirectory(plotDir);

  // Fill the occupancy distribution
  for (unsigned int nsens = 0; nsens < _device->getNumSensors(); nsens++)
  {
    Mechanics::Sensor* sensor = _device->getSensor(nsens);
    TH2D* occ = _hitOcc.at(nsens);

    for (unsigned int x = 0; x < sensor->getNumX(); x++)
    {
      for (unsigned int y = 0; y < sensor->getNumY(); y++)
      {
        const unsigned int numHits = occ->GetBinContent(x + 1, y + 1);
        _occDistribution->Fill((double)numHits / (double)totalHits);
      }
    }
  }

  _postProcessed = true;
}
예제 #2
0
TH2D* GetJetCorrFunc2D_ZYAM(int itrg, int jass)
{
                    TH2D* hcorr = (TH2D*)GetRawCorrFunc2D_ratio(itrg,jass);
                    TH2D* hcorr_clone = (TH2D*)hcorr->Clone(Form("corr_clone_itrg%d_jass%d",itrg,jass));
                    hcorr_clone->Reset();
		    for(int ietabin=1;ietabin<=hcorr->GetNbinsX();ietabin++)
		    {
                      TH1D* hcorrphi = (TH1D*)hcorr->ProjectionY(Form("corrphi_%d",ietabin),ietabin,ietabin,"e");  
                     // hcorrphi->SetAxisRange(0.35,1.57,"X");
                      double histminX = hcorrphi->GetBinCenter(hcorrphi->GetMinimumBin());
                      double histminY = hcorrphi->GetBinContent(hcorrphi->GetMinimumBin());
	   	      fitfunc = new TF1(Form("fitfunc_%d",ietabin),"[0]+[1]*(x-[2])*(x-[2])",0.6,1.2);		    
                      fitfunc->SetParameters(histminY,1,histminX);
                      fitfunc->SetParLimits(1,0,0.10000);
                  //    fitfunc->SetParLimits(2,0.35,1.57);
		      for(int ifit=0;ifit<3;ifit++) hcorrphi->Fit(Form("fitfunc_%d",ietabin),"RNO");                     		  
		      float level = fitfunc->GetParameter(0);
		      for(int iphibin=1;iphibin<=hcorr->GetNbinsY();iphibin++) 
                        hcorr_clone->SetBinContent(ietabin,iphibin,hcorr->GetBinContent(ietabin,iphibin)-level);
		    }
                    
                    float max = hcorr_clone->GetBinContent(hcorr_clone->GetMaximumBin());
                    hcorr_clone->SetAxisRange(ymin,max*1.3,"Z");		    
                    return hcorr_clone;
}
예제 #3
0
파일: runcorr.C 프로젝트: velicanu/UserCode
void runcorr(int filenum)
{


  string buffer;
  vector<string> listoffiles;
  int nlines = 0;
  ifstream infile("/net/hisrv0001/home/dav2105/corrana/makecorrhists/oldstuff/sortedforests.txt");

  if (!infile.is_open()) {
    cout << "Error opening file. Exiting." << endl;
    return;
  } else {
    while (!infile.eof()) {
      infile >> buffer;
      listoffiles.push_back(buffer);
      nlines++;
    }
  }


  corrana(listoffiles[filenum].data());
  
  double pttriglow[] = {1,4};
  double pttrighigh[] = {2,8};
  double ptasslow[] = {1,2};
  double ptasshigh[] = {2,3};
  int centmin[] = {0,4,8,12,16,20,24,28,32};
  int centmax[] = {40,8,12,16,20,24,28,32,36};
  TFile * outf = new TFile(Form("corrhists_%d.root",filenum),"recreate");
  
  // for(int i = 0 ; i < 9 ; ++i)
  // for(int i = 0 ; i < 2 ; ++i)
  for(int i = 0 ; i < 1 ; ++i)
  {
    cout<<"pt iteration "<<i<<endl;
    // for(int cent = 0 ; cent < 3 ; ++cent)
    // for(int cent = 0 ; cent < 9 ; ++cent)
    for(int cent = 0 ; cent < 1 ; ++cent)
    {
      cout<<"cent iteration "<<cent<<endl;
      TH2D * ttsig = TrackTrackSignal(pttriglow[i],pttrighigh[i],ptasslow[i],ptasshigh[i],centmin[cent],centmax[cent]);
      TH2D * ttbak = TrackTrackBackground(pttriglow[i],pttrighigh[i],ptasslow[i],ptasshigh[i],centmin[cent],centmax[cent]);
      // TCanvas * c1 = new TCanvas();
      // ttsig->Draw("surf1");
      // TCanvas * c2 = new TCanvas();
      // ttbak->Draw("surf1");
      // TCanvas * c3 = new TCanvas();
      TH2D * ttcorr = (TH2D*)ttsig->Clone(Form("corr_trg%d_%d_ass%d_%d_cmin%d_cmax%d",(int)pttriglow[i],(int)pttrighigh[i],(int)ptasslow[i],(int)ptasshigh[i],centmin[cent],centmax[cent]));
      ttcorr->Divide(ttbak);
      ttcorr->Scale(ttbak->GetBinContent(ttbak->FindBin(0,0)));
      ttcorr->GetXaxis()->SetRange(ttcorr->GetXaxis()->FindBin(-4.0),ttcorr->GetXaxis()->FindBin(4.0));
      ttcorr->GetYaxis()->SetRange(ttcorr->GetYaxis()->FindBin(-3.1415926/2.0),ttcorr->GetYaxis()->FindBin(3*3.1415926/2.0));
      // ttcorr->Draw("surf1");
    }
  }
  
  outf->Write();
  outf->Close();
}
예제 #4
0
TH2D* GetJetCorrFunc2D_doublegaussian(int itrg, int jass)
{
                    TH2D* hcorr = (TH2D*)GetRawCorrFunc2D_ratio(itrg,jass);
                    TH2D* hcorr_clone = (TH2D*)hcorr->Clone(Form("corr_clone_itrg%d_jass%d",itrg,jass));
                    hcorr_clone->Reset();
		    for(int ietabin=1;ietabin<=hcorr->GetNbinsX();ietabin++)
		    {
                      TH1D* hcorrphi = (TH1D*)hcorr->ProjectionY(Form("corrphi_%d",ietabin),ietabin,ietabin,"e");  
                      float min = hcorrphi->GetMinimum();
                      hcorrphi->SetAxisRange(-1,1,"X");
                      float nearmax = hcorrphi->GetMaximum();
                      hcorrphi->SetAxisRange(PI-1,PI+1,"X");
                      float awaymax = hcorrphi->GetMaximum();

		      TF1* fitfunc = new TF1("fitfunc",doubleGaussian,-PI/2.,3.*PI/2.,5);		    
                      fitfunc->SetParameters(min,nearmax-min,0.3,awaymax-min,0.5);  
                      fitfunc->SetParLimits(0,0,100000);
                      fitfunc->SetParLimits(1,0,100000);
                      fitfunc->SetParLimits(2,0,100000);
                      fitfunc->SetParLimits(3,0,100000);
                      fitfunc->SetParLimits(4,0,100000);		    
		      for(int ifit=0;ifit<3;ifit++) hcorrphi->Fit(Form("fitfunc_%d",ietabin),"RNO");                     
		      float level = fitfunc->GetParameter(0);

		      for(int iphibin=1;iphibin<=hcorr->GetNbinsY();iphibin++) 
                        hcorr_clone->SetBinContent(ietabin,iphibin,hcorr->GetBinContent(ietabin,iphibin)-level);                      
                      delete fitfunc;
		    }

                    float max = hcorr_clone->GetBinContent(hcorr_clone->GetMaximumBin());
                    hcorr_clone->SetAxisRange(ymin,max*1.3,"Z");
                    return hcorr_clone;
}
void fukuchiPhantom2microPhantom_muon2(){

  gROOT->Reset();
  TFile *fin = new TFile("fukuchiPhantom.root");
  TH2D *hin = (TH2D *)fin->Get("phantom");

  int nbinx = hin->GetXaxis()->GetNbins();
  int nbiny = hin->GetYaxis()->GetNbins();


  TH2D *hout = new TH2D("phantom","phantom",nbinx,-0.75,0.75,nbiny,-0.75,0.75);

  for(int i=1;i<=nbinx;i++){
    for(int j=1;j<=nbiny;j++){
      double v = hin->GetBinContent(i,j);
      hout->SetBinContent(i,j,v);
    }
  }


  TFile *fout = new TFile("microPhantom_muon2.root","recreate");
  fout->cd();
  hout->Write();
  fout->Close();

}
예제 #6
0
void HitInfo::postProcessing()
{
  for (unsigned int nsens = 0; nsens < _device->getNumSensors(); nsens++)
  {
    TH2D* map = _totMap.at(nsens);
    TH2D* count = _totMapCnt.at(nsens);

    for (Int_t x = 1; x <= map->GetNbinsX(); x++)
    {
      for (Int_t y = 1; y <= map->GetNbinsY(); y++)
      {
        const double average = map->GetBinContent(x, y) / count->GetBinContent(x, y);
        map->SetBinContent(x, y, average);
      }
    }
  }
}
예제 #7
0
void Matching::postProcessing()
{
  for (unsigned int nsens = 0; nsens < _dutDevice->getNumSensors(); nsens++)
  {
    Mechanics::Sensor* sensor = _dutDevice->getSensor(nsens);

    TH2D* tot = _inPixelTot.at(nsens);
    TH2D* hits = _inPixelTracks.at(nsens);

    assert(hits->GetNbinsX() == tot->GetNbinsX() &&
           hits->GetNbinsY() == tot->GetNbinsY() &&
           "Matching: histograms should have the same number of bins");

    for (int nx = 1; nx <= tot->GetNbinsX(); nx++)
    {
      for (int ny = 1; ny <= tot->GetNbinsY(); ny++)
      {
        const unsigned int num = hits->GetBinContent(nx, ny);
        if (num == 0) continue;
        const double average = tot->GetBinContent(nx, ny) / (double)num;
        tot->SetBinContent(nx, ny, average);
      }
    }

    for (unsigned int axis = 0; axis < 2; axis++)
    {
      TH1D* dist = axis ? _matchDistX.at(nsens) :
                          _matchDistY.at(nsens);

      double pixelWidth = axis ? sensor->getPitchX() :
                                 sensor->getPitchY();
      double beamSigma = axis ? _refDevice->getSensor(0)->getPitchX() :
                                _refDevice->getSensor(0)->getPitchY();

      TF1* fit = Processors::fitPixelBeam(dist, pixelWidth, beamSigma, false);

      std::stringstream ss;
      ss << _dutDevice->getName() << sensor->getName() << "PixelBeamFit"
         << ( axis ? "X" : "Y") << _nameSuffix;
      _plotDir->WriteObject(fit, ss.str().c_str());
    }
  }
}
예제 #8
0
TH2D* GetFinalCorrFunc2D(int itrg, int jass)
{
                    TH2D* hbackground = (TH2D*)GetRawBackground2D(itrg,jass);
		    TH2D* hcorr = (TH2D*)GetJetCorrFunc2D_ZYAM(itrg,jass);
                    hcorr->Multiply(hbackground);
                    float max = hcorr->GetBinContent(hcorr->GetMaximumBin());
		    hcorr->SetAxisRange(ymin,max*1.3,"Z");
                    hcorr->SetAxisRange(detamin,detamax,"X");
                    hcorr->SetZTitle("#frac{1}{N^{trg}}#frac{d^{2}N}{d#Delta#eta#Delta#phi}");
		    return hcorr;
}
예제 #9
0
파일: macro.C 프로젝트: Andrej-CMS/cmssw
void DrawTH2DZ(TFile* File, char* Histos_Name, char* legend, char* Title, char* Xlegend, char* Ylegend, double xmin, double xmax, double ymin, double ymax,  bool save, char* save_path, bool Normalization)
{
   TH2D* Histos = File->Get(Histos_Name);
   Histos->SetTitle();
   Histos->SetStats(kFALSE);
   Histos->GetXaxis()->SetTitle(Xlegend);
   Histos->GetYaxis()->SetTitle(Ylegend);
   Histos->GetYaxis()->SetTitleOffset(1.20);
//   Histos->GetYaxis()->SetTitleOffset(1.0);
   if(xmin!=xmax)Histos->SetAxisRange(xmin,xmax,"X");
   if(ymin!=ymax)Histos->SetAxisRange(ymin,ymax,"Y");

   if(Normalization){
      for(int x=0;x<Histos->GetXaxis()->GetNbins();x++){     
         TH1D* tmp = Histos->ProjectionY("",x,x);
	 double Integral = tmp->Integral();
         if(Integral==0)continue;
         double Factor = 1/Integral;
         for(int y=0;y<Histos->GetYaxis()->GetNbins();y++){
            Histos->SetBinContent(x,y, Histos->GetBinContent(x,y)*Factor );
            Histos->SetBinError  (x,y, Histos->GetBinError  (x,y)*Factor );
         }
      }
   }




   Histos->Draw("COLZ");
   gPad->SetLogz(1);
/*   c1->Update();
   TPaletteAxis* palette = (TPaletteAxis*)Histos->GetListOfFunctions()->FindObject("palette");
   palette->SetLabelOffset(0.1);
   palette->SetTitleOffset(0.1);
   c1->Modified();
*/

  
   if(save==1){
//        char path[255]; sprintf(path,"Pictures/PNG/%s.png",save_path);  c1->SaveAs(path);
//        char path[255]; sprintf(path,"Pictures/EPS/%s.eps",save_path);  c1->SaveAs(path);
//        char path[255]; sprintf(path,"Pictures/C/%s.C"  ,save_path);  c1->SaveAs(path);
           c1->SaveAs(save_path);

   }
}
예제 #10
0
void MakeGraph()
{
    InitPar();

    for(Int_t i = 0; i < kNData; i++) {
        TFile *file = new TFile(Form("Att%d.root", i * 100), "OPEN");
        TH2D *hist = (TH2D*)file->Get("HisPlate");

        thickness[i] = i * 100.;
        Double_t nHit[16] = {0};

        for(Int_t x = 0; x < 12; x++) {
            for(Int_t y = 0; y < 8; y++) {
                Int_t index = GetIndex(GetDistance(x - 5.5, y - 3.5));
                if(index == -1) cout << "Error" << endl;
                else {
                    nHit[index]++;
                    depEnergy[index][i] += hist->GetBinContent(x + 1, y + 1);
                }
            }
        }

        for(Int_t index = 0; index < 16; index++) {
            if( nHit[index > 0]) depEnergy[index][i] /= nHit[index];
            else cout << "Really?" << endl;
        }

        delete hist;
        delete file;
    }

    for(Int_t index = 0; index < 16; index++) {
        Double_t max =  depEnergy[index][0];
        for(Int_t iT = 0; iT < 31; iT++) {
            depEnergy[index][iT] /= max;
        }
    }

    for(Int_t i = 0; i < 16; i++) {
        gr[i] = new TGraph(kNData, thickness, depEnergy[i]);
        fitFnc[i] = new TF1(Form("fitFnc%02d", i), "pol9", 0, 3000);
        fitFnc[i]->FixParameter(0, 1.);
        gr[i]->Fit(fitFnc[i], "R");
    }

}
예제 #11
0
void mytestreweight(){


  TFile*finput=new TFile("fworking.root");
  TH1D*hBPtFONLL=(TH1D*)finput->Get("hBPt");
  TH1D*hDPtFONLL=(TH1D*)finput->Get("hDPt");
  TH2D*hD=(TH2D*)finput->Get("hD");
  
   hD->SetXTitle("B p_{T} (GeV/c)");
   hD->SetYTitle("D^{0} p_{T} (GeV/c)");
   hBPtFONLL->SetXTitle("B p_{T} (GeV/c)");
   hDPtFONLL->SetXTitle("D p_{T} (GeV/c)");
  
  TH2D *hDreweight = (TH2D*)hD->Clone("hDreweight");
  TH1D *hBPtPythia = hD->ProjectionX("hBPtPythia");
  TH1D *hDPtPythia = hD->ProjectionY("hDPtPythia");

   for (int x=1;x<=hDreweight->GetNbinsX()+1;x++){  //loop over the B pt bins
      if (hBPtPythia->GetBinContent(x)==0) continue;
      double ratio = hBPtFONLL->GetBinContent(x)/hBPtPythia->GetBinContent(x);  // in each pt bin we calculate the ratio of pythiaB/FONLLB 
       
      for (int y=1;y<=hDreweight->GetNbinsY()+1;y++){   //loop over the D pt bins
         double ratio2 = ratio;                                              //copy the ratio for each B bin
         double val = hDreweight->GetBinContent(x,y)*ratio2;
         double valError = hDreweight->GetBinError(x,y)*ratio2;
	 hDreweight->SetBinContent(x,y,val);
	 hDreweight->SetBinError(x,y,valError);
      }   
   }

  TH1D *hBPtPythiaReweight = hDreweight->ProjectionX("hBPtPythiaReweight");
  TH1D *hDPtPythiaReweight = hDreweight->ProjectionY("hDPtPythiaReweight");
  
  hBPtPythiaReweight->Divide(hBPtFONLL);
   
  TCanvas*canvas=new TCanvas("canvas","canvas",1000,500);  
  canvas->SetLogy();
  canvas->Divide(3,1);
  canvas->cd(1);
  hBPtFONLL->Draw();
  canvas->cd(2);
  hBPtPythia->Draw();
  canvas->cd(3);
  hBPtPythiaReweight->Draw();

}
예제 #12
0
파일: root.cpp 프로젝트: dnowatsc/rootana
std::pair<Matrix, Matrix> roothist_to_matrix(const TH2D & hist, bool transpose){
    int ngen = hist.GetNbinsY();
    int nreco = hist.GetNbinsX();
    if(transpose){
        swap(ngen, nreco);
    }
    
    Matrix m = Matrix(nreco, ngen);
    Matrix m_e = Matrix(nreco, ngen);
    
    for(int i=0; i<nreco; ++i){
        for(int j=0; j<ngen; ++j){
            int nx = i+1;
            int ny = j+1;
            if(transpose) swap(nx, ny);
            m(i,j) = hist.GetBinContent(nx, ny);
            m_e(i,j) = hist.GetBinError(nx, ny);
        }
    }
    return pair<Matrix, Matrix>(move(m), move(m_e));
}
예제 #13
0
TH2D* GetJetCorrFunc2D_ZYA1(int itrg, int jass)
{
                    TH2D* hcorr = (TH2D*)GetRawCorrFunc2D_ratio(itrg,jass);
                    TH2D* hcorr_clone = (TH2D*)hcorr->Clone(Form("corr_clone_itrg%d_jass%d",itrg,jass));
                    hcorr_clone->Reset();
		    for(int ietabin=1;ietabin<=hcorr->GetNbinsX();ietabin++)
		    {
                      TH1D* hcorrphi = (TH1D*)hcorr->ProjectionY(Form("corrphi_%d",ietabin),ietabin,ietabin,"e");  
                      hcorrphi->SetAxisRange(0.5,2.0,"X");
                      double histminY = hcorrphi->GetMinimum();
		      fitfunc = new TF1("fitfunc","[0]+[1]*x",0.8,1.2);		    
                      fitfunc->SetParameters(histminY,0);
                      fitfunc->FixParameter(1,0);
		      for(int ifit=0;ifit<3;ifit++) hcorrphi->Fit(Form("fitfunc_%d",ietabin),"RNO");                     
		      float level = fitfunc->GetParameter(0);
		      for(int iphibin=1;iphibin<=hcorrphi->GetNbinsY();iphibin++)
                        hcorr_clone->SetBinContent(ietabin,iphibin,hcorr->GetBinContent(ietabin,iphibin)-level);
                      delete fitfunc;
		    }

                    float max = hcorr_clone->GetBinContent(hcorr_clone->GetMaximumBin());
                    hcorr_clone->SetAxisRange(ymin,max*1.3,"Z");
                    return hcorr_clone;
}
예제 #14
0
void addn2() {

  // open existing f1:

  char* fn[99];
  int ni;

  // SR90 maps, mod D003

  ni = -1;
  ni++; fn[ni] = "SR90-map-00a.root";
  ni++; fn[ni] = "SR90-map-00b.root";
  ni++; fn[ni] = "SR90-map-01a.root";
  ni++; fn[ni] = "SR90-map-01b.root";
  ni++; fn[ni] = "SR90-map-02.root";
  ni++; fn[ni] = "SR90-map-03.root";
  ni++; fn[ni] = "SR90-map-05a.root";
  ni++; fn[ni] = "SR90-map-05b.root";
  ni++; fn[ni] = "SR90-map-07a.root";
  ni++; fn[ni] = "SR90-map-07b.root";
  ni++; fn[ni] = "SR90-map-07c.root";
  ni++; fn[ni] = "SR90-map-07d.root";

  // direct X-rays 9.4.2014 module D0003

  ni = -1;
  ni++; fn[ni] = "X-ray-20-modtd40000.root";
  ni++; fn[ni] = "X-ray-20-vthr60-modtd1000.root";
  ni++; fn[ni] = "X-ray-27-vthr60-modtd1000.root";
  ni++; fn[ni] = "X-ray-35-modtd40000.root";
  ni++; fn[ni] = "X-ray-35-vthr60-close-modtd65000.root";
  ni++; fn[ni] = "X-ray-35-vthr60-midpos-0p1mA-modtd10000.root";
  ni++; fn[ni] = "X-ray-35-vthr60-midpos-halfcur-modtd40000.root";
  ni++; fn[ni] = "X-ray-35-vthr60-modtd40000.root";

  int nmax = ni;

  TFile f1(fn[0]);

  if( f1.IsZombie() ) {
    cout << "Error opening " << fn[0] << endl;
    return;
  }
  cout << "opened " << fn[0] << endl;

  //--------------------------------------------------------------------
  // create f0:

  TFile f0("fileA.root", "RECREATE");
  cout << "created ";
  gDirectory->pwd();

  /*
  TFile options:  
  NEW or CREATE   create a new file and open it for writing,
                  if the file already exists the file is
                  not opened.
  RECREATE        create a new file, if the file already
                  exists it will be overwritten.
  UPDATE          open an existing file for writing.
                  if no file exists, it is created.
  READ            open an existing file for reading (default).
  NET             used by derived remote file access
                  classes, not a user callable option
  WEB             used by derived remote http access
                  class, not a user callable option
  "" (default), READ is assumed.
  */

  //--------------------------------------------------------------------
  // copy f1 to f0:

  f1.cd();

  cout << "keys:\n";
  f1.GetListOfKeys()->Print();

  cout << "pwd: ";
  f1.pwd();

  cout << "ls: \n";
  f1.ls();

  // f1 has sub-dir:

  cout << "First: " << f1.GetListOfKeys()->First()->GetName() << endl;
  cout << "First: " << f1.GetListOfKeys()->First()->ClassName() << endl;
  char* dir1 = f1.GetListOfKeys()->First()->GetName();
  cout << "cd to " << dir1 << endl;
  f1.cd( dir1 );
  cout << "we are in ";
  gDirectory->pwd();

  gDirectory->ReadAll(); // load histos

  TList * lst = gDirectory->GetList();
  cout << lst->GetName() << endl;
  cout << lst->GetTitle() << endl;
  cout << "size    " << lst->GetSize() << endl;
  cout << "entries " << lst->GetEntries() << endl;
  cout << "last    " << lst->LastIndex() << endl;

  TIterator *iter = lst->MakeIterator();
  int ii = 0;
  TObject *obj;
  TH1D *h;
  TH1D *h0;
  TH2D *H;
  TH2D *H0;

  while( obj = iter->Next() ){
    ii++;
    cout << setw(4) << ii << ": ";
    cout << obj->ClassName() << " ";
    cout << obj->InheritsFrom("TH1D") << " ";
    cout << obj->GetName() << " \"";
    cout << obj->GetTitle() << "\"";
    cout << endl;
    //    if( obj->ClassName() == "TH1D" ){
    if( obj->InheritsFrom("TH1D") ){
      h = (TH1D*) obj;
      cout << "       1D";
      cout << h->GetNbinsX() << " bins, ";
      cout << h->GetEntries() << " entries, ";
      cout << h->GetSumOfWeights() << " inside, ";
      cout << h->GetBinContent(0) << " under, ";
      cout << h->GetBinContent(h->GetNbinsX()+1) << " over";
      cout << endl;

      f0.cd(); // output file

      //      TH1D* h0 = (TH1D*) h->Clone();
      h0 = h; // copy
      h0->Write(); // write to file f0
      
      f1.cd(); // back to file 1 for the loop
    }
    else{

      if( obj->InheritsFrom("TH2D") ){

	H = (TH2D*) obj;
	cout << "       2D";
	cout << H->GetNbinsX() << " bins, ";
	cout << H->GetEntries() << " entries, ";
	cout << H->GetSumOfWeights() << " inside, ";
	cout << H->GetBinContent(0) << " under, ";
	cout << H->GetBinContent(H->GetNbinsX()+1) << " over";
	cout << endl;
	
	f0.cd(); // output file
	
	H0 = H; // copy
	H0->Write(); // write to file f0
	
	f1.cd(); // back to file 1 for the loop
      }
      else cout << "other class " << obj->ClassName() << endl;
    }
  }
  cout << "copied " << ii << endl;
  cout << "f1 " << f1.GetName() << " close = " << f1.Close() << endl;
    
  f0.cd();
  cout << "we are in ";
  gDirectory->pwd();

  cout << "f0 " << f0.GetName() << " size  = " << f0.GetSize() << endl;

  cout << "f0 " << f0.GetName() << " write = " << f0.Write() << endl;

  cout << "f0 " << f0.GetName() << " size  = " << f0.GetSize() << endl;

  cout << "f0 " << f0.GetName() << " close = " << f0.Close() << endl;

  f0.Delete();

  //--------------------------------------------------------------------
  // list of files 2:

  bool lAB = true;

  for( int nn = 1; nn <= nmax; ++nn ){

    cout << "\n\n";
    cout << "loop " << nn << ": fn = " << fn[nn] << endl;
    cout << "lAB = " << lAB << endl;

    if( lAB ) { // A+2 -> B
      char* fn3 = "fileA.root";
      char* fn4 = "fileB.root";
    }
    else{ // B+2 -> A
      char* fn3 = "fileB.root";
      char* fn4 = "fileA.root";
    }

    // create f4:

    TFile f4( fn4, "recreate" );
    if( f4.IsZombie() ) {
      cout << "Error creating f4\n";
      return;
    }
    cout << "created f4   = " << f4.GetName() << endl;

    // re-open as f3:

    TFile f3( fn3 );
    if( f3.IsZombie() ) {
      cout << "Error opening f3\n";
      return;
    }
    cout << "re-opened f3 = " << f3.GetName() << endl;

    lAB = !lAB;
    cout << "lAB = " << lAB << " for next loop\n";

    cout << "f4 = " << f4.GetName() << endl;
    cout << "f3 = " << f3.GetName() << endl;

    f3.cd();
    gDirectory->ReadAll(); // load histos into f3 memory

    //    cout << "f3 list size = " << gDirectory->GetList()->GetSize() << endl;
    cout << "f3 list size = " << gDirectory->GetList()->GetSize() << endl;

    TFile f2(fn[nn]);
    //    TFile *f2 = new TFile(fn[nn]);

    if( f2.IsZombie() ) {
    //    if( f2 == NULL ) {
      cout << "Error opening " << fn[nn] << endl;
      return;
    }
    cout << "opened " << fn[nn] << endl;

    // f2 has sub-dir:

    f2.cd( f2.GetListOfKeys()->First()->GetName() );
    cout << "we are in ";
    gDirectory->pwd();

    gDirectory->ReadAll(); // load histos into f2 memory

    // loop over f2:

    cout << "f2 list size = " << gDirectory->GetList()->GetSize() << endl;

    int jj = 0;
    TObject *ob2;
    TH1D *h2;
    TH1D *h3;
    TH2D *H2;
    TH2D *H3;

    TIterator *ite2 = gDirectory->GetList()->MakeIterator();

    while( ob2 = ite2->Next() ){

      jj++;

      //      if( jj > 9 ) continue;

      cout << jj << ". ";
      cout << "ob2 is ";
      cout << ob2->GetName() << " ";
      cout << ob2->ClassName() << " ";
      cout << ob2->GetTitle();
      cout << endl;

      if( ob2->InheritsFrom("TH1D") ) {

	h2 = (TH1D*) ob2;
	cout << "h2 " << h2->GetName() << "  " << h2->GetNbinsX() << " bins\n";
	cout << "h2 " << h2->GetName() << "  " << h2->GetEntries() << " entries\n";
	char* hnm2 = h2->GetName();

	// search in f3:

	cout << "search for " << hnm2 << " in f3\n";
	f3.cd();
	cout << "we are in ";
	gDirectory->pwd();
	
	h3 = (TH1D*) gDirectory->GetList()->FindObject(hnm2);
	if( h3 == NULL ) {
	  cout << "h3 is null\n" ;
	  continue;
	}
	
	cout << "found h3 = ";
	cout << h3->GetName() << "  ";
	cout << h3->ClassName() << "  ";
	cout << h3->GetTitle();
	cout << endl;
	cout << "h3  " << h3->GetName() << "  " << h3->GetNbinsX() << " bins\n";
	cout << "h3  " << h3->GetName() << "  " << h3->GetEntries() << " entries\n";

	// add:

	f4.cd();
	cout << "we are in ";
	gDirectory->pwd();
	//TH1D h4 = *h3 + *h2;
	TH1D* h4 = (TH1D*) h3->Clone();
	h4->Add(h2);
	
	cout << "h4  " << h4->GetEntries() << " entries\n";
	cout << "h4  ";
	cout << h4->GetName() << " ";
	cout << h4->ClassName() << " ";
	cout << h4->GetTitle();
	cout << endl;
	cout << "h4 dir " << h4->GetDirectory()->GetName() << endl;
	cout << "f4 size " << f4.GetSize() << endl;

	// back to f2 for next iter:

	f2.cd( f2.GetListOfKeys()->First()->GetName() );

      }//1D

      if( ob2->InheritsFrom("TH2D") ) {

	H2 = (TH2D*) ob2;
	cout << "H2 " << H2->GetName() << "  " << H2->GetNbinsX() << " bins\n";
	cout << "H2 " << H2->GetName() << "  " << H2->GetEntries() << " entries\n";
	char* Hnm2 = H2->GetName();

	// search in f3:

	cout << "search for " << Hnm2 << " in f3\n";
	f3.cd();
	cout << "we are in ";
	gDirectory->pwd();
	
	H3 = (TH2D*) gDirectory->GetList()->FindObject(Hnm2);
	if( H3 == NULL ) {
	  cout << "H3 is null\n" ;
	  continue;
	}
	
	cout << "found H3 = ";
	cout << H3->GetName() << "  ";
	cout << H3->ClassName() << "  ";
	cout << H3->GetTitle();
	cout << endl;
	cout << "H3  " << H3->GetName() << "  " << H3->GetNbinsX() << " bins\n";
	cout << "H3  " << H3->GetName() << "  " << H3->GetEntries() << " entries\n";

	// add:

	f4.cd();
	cout << "we are in ";
	gDirectory->pwd();

	TH2D* H4 = (TH2D*) H3->Clone();
	H4->Add(H2);
	
	cout << "H4  " << H4->GetEntries() << " entries\n";
	cout << "H4  ";
	cout << H4->GetName() << " ";
	cout << H4->ClassName() << " ";
	cout << H4->GetTitle();
	cout << endl;
	cout << "H4 dir " << H4->GetDirectory()->GetName() << endl;
	cout << "f4 size " << f4.GetSize() << endl;

	// back to f2 for next iter:

	f2.cd( f2.GetListOfKeys()->First()->GetName() );
      }//2D

    } //while

    cout << "processed " << jj << endl;
    cout << "f4 " << f4.GetName() << " size " << f4.GetSize() << endl;

    //  cout << "f4 map:\n";
    //  f4.Map();

    cout << "f4 " << f4.GetName() << " write = " << f4.Write() << endl;

    cout << "f4 " << f4.GetName() << " size  = " << f4.GetSize() << endl;
    
  }// loop over files 2

  cout << endl;
  cout << "combined " << nmax + 1 << " files\n";
  cout << "Final file is " << f4.GetName() << endl;

  f2.Close();
  f3.Close();
  f4.Close();

}
예제 #15
0
/** 
 * 
 * 
 * @param o 
 * @param useWeights 
 * @param correct
 *
 * @ingroup pwglf_forward_scripts_tests
 */
void
TestPoisson(Double_t o=.3, bool useWeights=false, bool correct=true)
{
  const char* load = "$ALICE_PHYSICS/PWGLF/FORWARD/analysis2/scripts/LoadLibs.C";
  if (!gROOT->GetClass("AliAODForwardMult")) {
    gROOT->Macro(load);
    gROOT->GetInterpreter()->UnloadFile(gSystem->ExpandPathName(load));
  }
  
  // --- Parameters of this script -----------------------------------
  Int_t      nBin =  5;  // Our detector matrix size 
  Int_t      nMax = TMath::Max(Int_t(nBin * nBin * o + .5)+nBin/2,nBin);  
  Int_t      nEv  = 10000; // Number of events
  Double_t   mp   = o;   // The 'hit' probability 


  TH2D* base = new TH2D("base", "Basic histogram", 
			nBin,-.5, nBin-.5, nBin, -.5, nBin-.5);
  base->SetXTitle("#eta");
  base->SetYTitle("#varphi");
  base->SetDirectory(0);
  base->SetOption("colz");

  Int_t tN1=nMax;    Double_t tMin1; Double_t tMax1;
  Int_t tN2=nMax*10; Double_t tMin2; Double_t tMax2=nMax;
  MakeIntegerAxis(tN1, tMin1, tMax1);
  MakeIntegerAxis(tN2, tMin2, tMax2);
  TH2D* corr = new TH2D("comp", "Comparison", 
			tN1, tMin1, tMax1, tN2, tMin2, tMax2);
  corr->SetXTitle("Input");
  corr->SetYTitle("Poisson");
  corr->SetDirectory(0);
  corr->SetOption("colz");
  corr->SetStats(0);
  TLine* lcorr = new TLine(0, 0, tMax2, tMax2);

  Int_t mm = TMath::Max(Int_t(nBin * o + .5),nBin/2);
  tN2=mm*10; tMax2 = mm;
  MakeIntegerAxis(tN2, tMin2, tMax2);
  Info("", "Making mean w/nbins=%d,range=[%f,%f]", tN2, tMin2, tMax2);
  TH2D* mean = new TH2D("mean", "Mean comparison", 
			tN2, tMin2, tMax2, tN2, tMin2, tMax2);
  mean->SetXTitle("Input");
  mean->SetYTitle("Poisson");
  mean->SetDirectory(0);
  mean->SetOption("colz");
  mean->SetStats(0);
  TLine* lmean = new TLine(tMin2, tMin2, tMax2, tMax2);

  TH1D* dist = new TH1D("dist", "Distribution of hits", tN1, tMin1, tMax1);
  dist->SetXTitle("s");
  dist->SetYTitle("P(s)");
  dist->SetFillColor(kRed+1);
  dist->SetFillStyle(3001);
  dist->SetDirectory(0);

  TH1D* diff = new TH1D("diff", "P-T", 100, -25, 25);
  diff->SetXTitle("Difference");
  diff->SetFillColor(kRed+1);
  diff->SetFillStyle(3001);
  diff->SetYTitle("Prob");

  AliPoissonCalculator* c = new AliPoissonCalculator("ignored");
  c->Init(nBin ,nBin);

  for (Int_t i = 0; i < nEv; i++) { 
    c->Reset(base);
    base->Reset();

    for (Int_t iEta = 0; iEta < nBin; iEta++) { 
      for (Int_t iPhi = 0; iPhi < nBin; iPhi++) { 
	// Throw a die 
	Int_t m = gRandom->Poisson(mp);
	dist->Fill(m);

	// Fill into our base histogram 
	base->Fill(iEta, iPhi, m);

	// Fill into poisson calculator 
	c->Fill(iEta, iPhi, m > 0, (useWeights ? m : 1));
      }
    }
    // Calculate the result 
    TH2D* res = c->Result(correct);
    
    // Now loop and compare 
    Double_t mBase = 0;
    Double_t mPois = 0;
    for (Int_t iEta = 0; iEta < nBin; iEta++) { 
      for (Int_t iPhi = 0; iPhi < nBin; iPhi++) { 
	Double_t p = res->GetBinContent(iEta, iPhi);
	Double_t t = base->GetBinContent(iEta, iPhi);

	mBase += t;
	mPois += p;
	corr->Fill(t, p);
	diff->Fill(p-t);
      }
    }
    Int_t nn = nBin * nBin;
    mean->Fill(mBase / nn, mPois / nn);
  }

  TCanvas* cc = new TCanvas("c", "c", 900, 900);
  cc->SetFillColor(0);
  cc->SetFillStyle(0);
  cc->SetBorderMode(0);
  cc->SetRightMargin(0.02);
  cc->SetTopMargin(0.02);
  cc->Divide(2,2);
  
  TVirtualPad* pp = cc->cd(1);
  pp->SetFillColor(0);
  pp->SetFillStyle(0);
  pp->SetBorderMode(0);
  pp->SetRightMargin(0.15);
  pp->SetTopMargin(0.02);
  pp->SetLogz();
  pp->SetGridx();
  pp->SetGridy();
  corr->Draw();
  lcorr->Draw();

  pp = cc->cd(2);
  pp->SetFillColor(0);
  pp->SetFillStyle(0);
  pp->SetBorderMode(0);
  pp->SetRightMargin(0.02);
  pp->SetTopMargin(0.02);
#if 0
  c->GetMean()->Draw();
#elif 1 
  pp->SetLogy();
  diff->Draw();
#elif 1
  c->GetOccupancy()->Draw();
#else
  pp->SetLogy();
  dist->SetStats(0);
  dist->Scale(1. / dist->Integral());
  dist->Draw();
  TH1D* m1 = c->GetMean();
  m1->Scale(1. / m1->Integral());
  m1->Draw("same");
  Double_t eI;
  Double_t ii = 100 * dist->Integral(2, 0);
  TLatex* ll = new TLatex(.97, .85, 
			  Form("Input #bar{m}: %5.3f", mp));
  ll->SetNDC();
  ll->SetTextFont(132);
  ll->SetTextAlign(31);
  ll->Draw();
  ll->DrawLatex(.97, .75, Form("Result #bar{m}: %5.3f", dist->GetMean()));
  ll->DrawLatex(.97, .65, Form("Occupancy: #int_{1}^{#infty}P(s)ds = %6.2f%%",
			       ii));
			 
#endif

  pp = cc->cd(3);
  pp->SetFillColor(0);
  pp->SetFillStyle(0);
  pp->SetBorderMode(0);
  pp->SetRightMargin(0.15);
  pp->SetTopMargin(0.02);
  pp->SetGridx();
  pp->SetGridy();
  c->GetCorrection()->Draw();

  pp = cc->cd(4);
  pp->SetFillColor(0);
  pp->SetFillStyle(0);
  pp->SetBorderMode(0);
  pp->SetRightMargin(0.15);
  pp->SetTopMargin(0.02);
  pp->SetLogz();
  pp->SetGridx();
  pp->SetGridy();
  mean->Draw();
  lmean->Draw();

  cc->cd();
}
예제 #16
0
void Plot_2D(string filename){
  
  //string filename = "data/scan_CH1-50_masked.root";
 
  // string varXname = "VMM # [1-8]";
  // string varYname = "CH # [1-64]";

  string varXname = "Pulsed CH # [1-64]";
  string varYname = "Recorded CH # [1-64]";
  string varZname = "# Recorded Pulses [/100 pulsed]";
  //string varZname = "#sigma(PDO) / #bar{PDO}";
  // int Nx = 8;
  // double Xmin = 0.5;
  // double Xmax = 8.5;
  int Nx = 64;
  double Xmin = 0.5;
  double Xmax = 64.5;
  // int Ny = 64;
  // double Ymin = 0.5;
  // double Ymax = 64.5;
  int Ny = 4097;
  double Ymin = -0.5;
  double Ymax = 4096.5;

  ///////////////////////////////////////////////////////
  setstyle(0);
  
  TChain* tree = new TChain("VMM_data","VMM_data");

  tree->AddFile(filename.c_str());

  MMFE8Base* base = new MMFE8Base(tree);

  int N = tree->GetEntries();

  TH2D* hist = new TH2D("hist","hist",
			Nx, Xmin, Xmax,
			Ny, Ymin, Ymax);

  TH2D* hist2 = new TH2D("hist2","hist2",
			 Nx, Xmin, Xmax,
			 Ny, Ymin, Ymax);

  TH2D* histN = new TH2D("histN","histN",
			 Nx, Xmin, Xmax,
			 Ny, Ymin, Ymax);

  for(int i = 0; i < N; i++){
    base->GetEntry(i);

    if(base->VMM != 0)
      continue;

    if(base->CHword == 24)
      continue;

    if(base->Delay != 30)
      continue;
    
    // hist->Fill(base->CHpulse,base->CHword,base->PDO);
    //histN->Fill(base->CHpulse,base->CHword);
    histN->Fill(base->CHpulse,base->BCID);

    // if(base->CHpulse != 5)
    //   continue;
    // base->CHpulse = base->CHword;

    hist->Fill(base->VMM,base->CHpulse,base->PDO);
    hist2->Fill(base->VMM,base->CHpulse,base->PDO*base->PDO);
    // if(histN->GetBinContent(base->VMM,base->CHpulse) <= 0)
    //   histN->SetBinContent(base->VMM,base->CHpulse,base->BCID);
    // else
    //   if(histN->GetBinContent(base->VMM,base->CHpulse) > base->BCID)
    // histN->SetBinContent(base->VMM,base->CHpulse,base->BCID);
    // histN->Fill(base->VMM,base->CHpulse);
  
  }

  for(int x = 0; x < Nx; x++){
    for(int y = 0; y < Ny; y++){
      double v = hist->GetBinContent(x+1,y+1);
      double v2 = hist2->GetBinContent(x+1,y+1);
      double N = histN->GetBinContent(x+1,y+1);
      double vbar = v/max(int(N),1);
      double v2bar = v2/max(int(N),1);
      //hist->SetBinContent(x+1,y+1,sqrt(v2bar-vbar*vbar)/vbar);
      hist->SetBinContent(x+1,y+1,vbar);
    }
  }

  TCanvas* can = new TCanvas("can","can",600,500);
  can->SetLeftMargin(0.15);
  can->SetRightMargin(0.22);
  can->SetBottomMargin(0.15);
  can->SetTopMargin(0.08);

  can->Draw();
  can->SetGridx();
  can->SetGridy();
  
  can->cd();

  hist = histN;

  hist->Draw("COLZ");

  hist->GetXaxis()->CenterTitle();
  hist->GetXaxis()->SetTitleFont(132);
  hist->GetXaxis()->SetTitleSize(0.06);
  hist->GetXaxis()->SetTitleOffset(1.06);
  hist->GetXaxis()->SetLabelFont(132);
  hist->GetXaxis()->SetLabelSize(0.05);
  hist->GetXaxis()->SetTitle(varXname.c_str());
  hist->GetYaxis()->CenterTitle();
  hist->GetYaxis()->SetTitleFont(132);
  hist->GetYaxis()->SetTitleSize(0.06);
  hist->GetYaxis()->SetTitleOffset(1.12);
  hist->GetYaxis()->SetLabelFont(132);
  hist->GetYaxis()->SetLabelSize(0.05);
  hist->GetYaxis()->SetTitle(varYname.c_str());
  hist->GetZaxis()->CenterTitle();
  hist->GetZaxis()->SetTitleFont(132);
  hist->GetZaxis()->SetTitleSize(0.06);
  hist->GetZaxis()->SetTitleOffset(1.3);
  hist->GetZaxis()->SetLabelFont(132);
  hist->GetZaxis()->SetLabelSize(0.05);
  hist->GetZaxis()->SetTitle(varZname.c_str());
  hist->GetZaxis()->SetRangeUser(0.9*hist->GetMinimum(),1.1*hist->GetMaximum());

  TLatex l;
  l.SetTextFont(132);
  l.SetNDC();
  l.SetTextSize(0.05);
  l.SetTextFont(132);
  l.DrawLatex(0.5,0.943,"MMFE8 Analysis");
  l.SetTextSize(0.04);
  l.SetTextFont(42);
  l.DrawLatex(0.15,0.943,"#bf{#it{ATLAS}} Internal");

  l.SetTextSize(0.06);
  l.SetTextFont(132);
  l.DrawLatex(0.80,0.04, "VMM #6");

 
}
void advancedNoiseAnalysis( unsigned int runNumber, unsigned int loop = 1) {
  
  string inputFileName = "./histo/run00" + toString( runNumber ) + "-ped-histo.root";
  string outputFileName = "./histo/run00" + toString( runNumber ) + "-adv-noise.root";
  

  // before opening the input and the output files, try to see if they
  // are not opened yet and in case close them before continue   
  TList * listOfOpenedFile = (TList*) gROOT->GetListOfFiles();
  for ( int i = 0; i < listOfOpenedFile->GetSize() ; ++i ) {
    TFile * file = (TFile*) listOfOpenedFile->At( i ) ;
    TString fileName(file->GetName());
    TString inputFileName1( inputFileName.c_str() );
    TString outputFileName1( outputFileName.c_str() );

    if (  ( fileName.Contains( inputFileName1 ) ) ||
	  ( inputFileName1.Contains( fileName ) ) ||
	  ( fileName.Contains( outputFileName1 ) ) ||
	  ( outputFileName1.Contains( fileName ) ) ) {
      cout << "Closing " << fileName << " before reopen " << endl;
      file->Close();
    }
  }


  // close also all the previously opened canvas
  TList * listOfOpenedCanvas = (TList*) gROOT->GetListOfCanvases();
  for ( int i = 0 ; i < listOfOpenedCanvas->GetSize() ; ++i ) {
    TCanvas * canvas = (TCanvas*) listOfOpenedCanvas->At( i );
    TString canvasName2 = canvas->GetName();
    if ( canvasName2.Contains( "det" ) ) {
      canvas->Close();
    }
  }

	 
  // now safely open the file
  TFile * inputFile = TFile::Open( inputFileName.c_str() ) ;
  TFile * outputFile = TFile::Open( outputFileName.c_str(), "RECREATE") ;
  TList * outputHistoList = new TList;

  // look into the inputFile for a folder named
  string pedeProcessorFolderName = "PedestalAndNoiseCalculator";
  TDirectoryFile * pedeProcessorFolder = (TDirectoryFile*) inputFile->Get( pedeProcessorFolderName.c_str() );
  
  if ( pedeProcessorFolder == 0 ) { 
    cerr << "No pedestal processor folder found in file " << inputFileName << endl;
    return ;
  }

  // this folder should contain one folder for each loop.
  string loopFolderName = "loop-" + toString( loop );
  TDirectoryFile * loopFolder = (TDirectoryFile *) pedeProcessorFolder->Get( loopFolderName.c_str() );
  
  if ( loopFolder == 0 ) {
    cerr << "No " << loopFolderName << " found in file " << inputFileName << endl;
    return ;
  }

  // guess the number of sensors from the number of subfolder in the loopfolder
  size_t nDetector = loopFolder->GetListOfKeys()->GetSize();
  cout << "This file contains " << nDetector << " detectors" << endl;

  // prepare arrays to store the mean and the rms of the noise distribution
  if ( noiseMean == NULL ) {
    delete [] noiseMean;
    noiseMean = NULL;
  }
  if ( noiseRMS == NULL ) {
    delete [] noiseRMS;
    noiseRMS = NULL;
  }
  if ( channel == NULL ) {
    delete [] channel;
    channel = NULL;
  }

  noiseMean = new double[ nDetector * kNChan ];
  noiseRMS  = new double[ nDetector * kNChan ];
  channel   = new double[ kNChan ];

  string canvasName = "comparison";
  string canvasTitle = "Noise comparison";

  TCanvas * comparisonCanvas = new TCanvas( canvasName.c_str(), canvasTitle.c_str(), 1000, 500 );
  comparisonCanvas->Divide(1,2);
  
  TPad * topPad = (TPad*) comparisonCanvas->cd(1);
  topPad->Divide( nDetector );
  
  TPad * middlePad = (TPad *) comparisonCanvas->cd(2);
  middlePad->Divide( kNChan );


  // for each detector we have to get the noise map and to prepare 4
  // separe histos and maps
  for ( unsigned int iDetector = 0; iDetector < nDetector; iDetector++ ) {

    // get the noise map.
    string noiseMapName = "detector-" + toString( iDetector ) ;
    noiseMapName += "/NoiseMap-d" + toString( iDetector )  ;
    noiseMapName += "-l" + toString( loop ) ;
 
    TH2D * noiseMap = ( TH2D* ) loopFolder->Get( noiseMapName.c_str() ); 
    

    // create a folder in the output file
    TDirectory * subfolder = outputFile->mkdir( string( "detector_" + toString( iDetector ) ).c_str(),
						string( "detector_" + toString( iDetector ) ).c_str()
						);
    subfolder->cd();

    
    string canvasName = "det" + toString( iDetector );
    string canvasTitle = "Detector " + toString( iDetector );
    
    TCanvas * canvas = new TCanvas( canvasName.c_str(), canvasTitle.c_str(), 1000, 500 );
    canvas->Divide( kNChan, 2 );

    // ok now start the loop on channels
    for ( size_t iChan = 0 ; iChan < kNChan ; ++iChan ) { 
	
      if ( iDetector == 0 ) channel[iChan] = iChan - 0.5;

      string tempName = "NoiseMap_d" + toString( iDetector ) + "_l" + toString( loop )	+ "_ch" + toString( iChan ) ;
      string tempTitle = "NoiseMap Det. " + toString( iDetector ) + " - Ch. " + toString( iChan ) ;

      TH2D * noiseMapCh = new TH2D ( tempName.c_str() , tempTitle.c_str(), 
				     kXPixel / kNChan , -0.5 + xLimit[ iChan ] , -0.5 + xLimit[ iChan + 1 ],
				     kYPixel, -0.5, -0.5 + kYPixel );
      noiseMapCh->SetXTitle("X [pixel]");
      noiseMapCh->SetYTitle("Y [pixel]");
      noiseMapCh->SetZTitle("Noise [ADC]");
      noiseMapCh->SetStats( false );
      outputHistoList->Add( noiseMapCh ) ;

      tempName = "NoiseDist_d" + toString( iDetector ) + "_l" + toString( loop )	+ "_ch" + toString( iChan ) ;
      
      tempTitle = "NoiseDist Det. " + toString( iDetector ) + " - Ch. " + toString( iChan ) ; 

      TH1D * noiseDistCh = new TH1D( tempName.c_str(), tempTitle.c_str(), 50, 0., 10. );
      noiseDistCh->SetXTitle("Noise [ADC]");
      noiseDistCh->SetLineColor( kColor[iDetector]  );
      noiseDistCh->SetLineStyle( iChan + 2 );
      noiseDistCh->SetLineWidth( 2 );
      outputHistoList->Add( noiseDistCh );

      // let's start looping on pixels now
      for ( size_t yPixel = 1 ; yPixel <= kYPixel ; ++yPixel ) {
	for ( size_t xPixel = xLimit[ iChan ] + 1; xPixel <= xLimit[ iChan +1 ] ; ++xPixel ) {
	  double noise = noiseMap->GetBinContent( xPixel , yPixel );
	  noiseMapCh->Fill( xPixel - 1 , yPixel - 1, noise );
	  noiseDistCh->Fill( noise );
	  
	}
      }

      canvas->cd( iChan + 1 ) ;
      noiseMapCh->Draw("colz");
      canvas->cd( iChan + kNChan + 1  );
      noiseDistCh->Draw();
      
      topPad->cd( iDetector + 1 );
      if ( iChan == 0 ) {
	noiseDistCh->Draw();
      } else {
	noiseDistCh->Draw("same");
      }

      middlePad->cd( iChan + 1 );
      if ( iDetector == 0 ) {
	noiseDistCh->Draw();
      } else {
	noiseDistCh->Draw("same");
      }


      noiseMean[ kNChan * iDetector + iChan ] = noiseDistCh->GetMean();
      noiseRMS[ kNChan * iDetector  + iChan ] = noiseDistCh->GetRMS();
    }
    canvas->Write();

  }

  canvasName = "summary";
  canvasTitle = "Noise summary";

  TCanvas * summaryCanvas = new TCanvas( canvasName.c_str(), canvasTitle.c_str(), 1000, 500 );
  summaryCanvas->SetGridx(1);
  TLegend * legend = new TLegend(0.5, 4.8, 1.5, 4.3,"","br");;
  

  for ( size_t iDetector = 0 ; iDetector < nDetector ; ++iDetector ) {
    
    TGraphErrors * gr = new TGraphErrors( kNChan, channel, &noiseMean[ iDetector * kNChan ], NULL, &noiseRMS[ iDetector * kNChan ] );
    gr->SetName( string( "NoisePerChannel_d" + toString( iDetector )).c_str());
    gr->SetTitle(string("Detector " + toString( iDetector )).c_str());
    gr->GetXaxis()->SetTitle("Channel #");
    gr->GetYaxis()->SetTitle("Noise [ADC]");
    gr->GetXaxis()->SetNdivisions( 5 );
    gr->GetXaxis()->SetLabelSize( 0 );
    gr->SetMarkerStyle( iDetector + 1 );
    gr->SetMarkerColor( kColor[iDetector] );
    gr->SetLineColor( kColor[iDetector] );
    gr->SetLineWidth( 2 );

    
    legend->AddEntry( gr, string("Detector " + toString( iDetector )).c_str(), "LP");

    if ( iDetector == 0 ) {
      gr->Draw("ALP");
    } else {
      gr->Draw("LP");
    }
    

  }

  
  
  legend->Draw();

  for ( size_t iChan = 0 ; iChan < kNChan ; ++iChan ) {
    
    TPaveLabel * label = new TPaveLabel( iChan - 0.75 , 3.2 , iChan -0.25 , 3, string("Ch " + toString( iChan ) ).c_str());
    label->Draw();
  }


  summaryCanvas->Write();
  comparisonCanvas->Write();

  outputHistoList->Write();

  

 
} 
예제 #18
0
void ExtractOutputHistos(Bool_t onlyPrims=0,Bool_t onlyPion=0,Int_t plotFlag=0) {

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

  const Int_t nbins=20;
  Double_t ptmin=0.06;//04;
  Double_t ptmax=2.0;//GeV
  Double_t logxmin = TMath::Log10(ptmin);
  Double_t logxmax = TMath::Log10(ptmax);
  Double_t binwidth = (logxmax-logxmin)/(nbins+1);
  enum {nb=nbins+1};
  Double_t xbins[nb];
  xbins[0] = ptmin;
  for (Int_t i=1;i<=nbins;i++) {
    xbins[i] = ptmin + TMath::Power(10,logxmin+(i)*binwidth);
    //    cout<<xbins[i]<<endl;
  }
  //  TH1F *h = new TH1F("h","hist with log x axis",nbins,xbins);

  TH1F *hMultCount = new TH1F("mult","averaged multiplicity (charg. prim)",80,-4.,4.);
  hMultCount->GetXaxis()->SetTitle("eta");
  hMultCount->GetYaxis()->SetTitle("N/d#eta");

  TH1F *hAllMC = new TH1F("allMC","All Tracks MC primaries",nbins,xbins);
  TH1F *hAllFound = new TH1F("allFound","All Tracks found",nbins,xbins);
  TH1F *hImperfect = new TH1F("imperfect","Imperfect tracks",nbins,xbins);
  TH1F *hPerfect = new TH1F("perfect","Perfect tracks",nbins,xbins);
  TH1F *hEff = new TH1F("efficiency","Efficiency (Perfect tracks in \"ALL MC\")",nbins,xbins);
  TH1F *hFake = new TH1F("fake","Fake tracks (Inperfect tracks in \"ALL MC\")",nbins,xbins);
  TH1F *hPurity = new TH1F("purity","Purity (Perfect tracks in \"All Found\")",nbins,xbins);
  TH1F *hAnna = new TH1F("annaEff","AnnalisaEff ",nbins,xbins);
  TH1F *hNoMCTrack = new TH1F("noMCtrack","noMCtrack ",nbins,xbins);

  TH1F *hEta = new TH1F("","",50,-2,2);
  //  TH1F *hEtaMC = new TH1F("","",50,-2,2);

  TH2D *h2Ddca = new TH2D("dca2D","DCAvsPt2D",nbins,xbins,50,-0.05,0.05);
  TH2D *h2Dpt = new TH2D("dPt2D","dPtdvsPt2D",nbins,xbins,50,-25,25);

  // open run loader and load gAlice, kinematics and header
  AliRunLoader* runLoader = AliRunLoader::Open("galice.root");
  if (!runLoader) {
    Error("Check kine", "getting run loader from file %s failed",
          "galice.root");
    return;
  }
  runLoader->LoadgAlice();
  gAlice = runLoader->GetAliRun();
  if (!gAlice) {
    Error("Check kine", "no galice object found");
    return;
  }
  runLoader->LoadHeader();
  runLoader->LoadKinematics();

  TFile* esdFile = TFile::Open("AliESDs.root");
  if (!esdFile || !esdFile->IsOpen()) {
    Error("CheckESD", "opening ESD file %s failed", "AliESDs.root");
    return;
  }
  AliESDEvent *esd = new AliESDEvent();
  TTree* tree = (TTree*) esdFile->Get("esdTree");
  if (!tree) {
    Error("CheckESD", "no ESD tree found");
    return;
  }
  esd->ReadFromTree(tree);
  
  Int_t nTrackTotalMC = 0;
  Int_t nTrackFound = 0;
  Int_t nTrackImperfect = 0;
  Int_t nTrackPerfect = 0;
  Int_t nNoMCTrack = 0;

  
  for(Int_t iEv =0; iEv<tree->GetEntries(); iEv++){
    tree->GetEvent(iEv);
    runLoader->GetEvent(iEv);
    
    printf("+++ event %i (of %lld) +++++++++++++++++++++++  # ESDtracks: %d \n",iEv,tree->GetEntries()-1,esd->GetNumberOfTracks());
    Int_t nESDtracks = esd->GetNumberOfTracks();
    for (Int_t iTrack = 0; iTrack < nESDtracks; iTrack++) {
      AliESDtrack* track = esd->GetTrack(iTrack);
      if (!(iTrack%1000)) printf("event %i: ESD track count %d (of %d)\n",iEv,iTrack,nESDtracks);

      Int_t label = track->GetLabel();
  
      Int_t idx[12];
      //      Int_t ncl = track->GetITSclusters(idx);
   
      if(label<0) {
	//	cout<< " ESD track label " << label;
	//	cout<<"  ---> imperfect track (label "<<label<<"<0) !! -> track Pt: "<< track->Pt() << endl;
      }

      AliStack* stack = runLoader->Stack();
      //     nTrackTotalMC += stack->GetNprimary();
    

      TParticle* particle = stack->Particle(TMath::Abs(label)); 
      Double_t pt = track->Pt();
      
      if(particle) {

	if (TMath::Abs(particle->Eta())>etaCut) continue;

	Double_t ptMC = particle->Pt();

	// Efficiencies
	if (onlyPion && TMath::Abs(particle->GetPdgCode())!=211) continue;

	if ( (!onlyPrims) || stack->IsPhysicalPrimary(TMath::Abs(label))) {
	  //  cout<<" # clusters "<<ncl<<endl;

	  nTrackFound++;
	  hAllFound->Fill(ptMC);
	  hEta->Fill(track->Eta());
	  
	  if (label<0) {
	    nTrackImperfect++;
	    hImperfect->Fill(ptMC);
	  } else {
	    nTrackPerfect++;
	    hPerfect->Fill(ptMC);
	  }

	}


	// following only for "true tracks, pions

	if(particle->Pt() < 0.001)continue;
	if (TMath::Abs(particle->GetPdgCode())!=211) continue;
	if (label>0) {
	  
	  // Impact parameters for Pions only
	  Double_t dca = track->GetD(0,0,0.5);
	  h2Ddca->Fill(ptMC,dca);
	  
	  // Pt resolution for Pions only
	  Double_t dPt = (pt-ptMC)/ptMC*100;
	  h2Dpt->Fill(ptMC,dPt);
	}

      } else {
	nNoMCTrackFound++;
	hNoMCTrack->Fill(pt);
	cout<<" according MC particle not found"<<endl;
      }
      
    } //entries track esd
  

  }//entries tree
  runLoader->UnloadHeader();
  runLoader->UnloadKinematics();
  delete runLoader;

 
  // Count trackable MC tracks
  CountTrackableMCs(hAllMC, onlyPrims, onlyPion);


  // Count trackable MC tracks
  CountPrimaries(hMultCount);

 


  // Get Errors right
  hMultCount->Sumw2();
  hAllMC->Sumw2();   
  hAllFound->Sumw2();
  hPerfect->Sumw2(); 
  hImperfect->Sumw2(); 
  h2Dpt->Sumw2();
  h2Ddca->Sumw2();

  // -- Global efficienies

  nTrackTotalMC = hAllMC->GetEntries();
  Double_t eff = ((Double_t)nTrackPerfect)/nTrackTotalMC;
  printf("-> Total number of events: %lld -> MCtracks %d -> nPerfect %d  -> Eff: %3.2lf \n",
	 tree->GetEntries(),nTrackTotalMC,nTrackPerfect,eff);

  Double_t purity = ((Double_t)nTrackPerfect)/nTrackFound;
  printf("-> Total number of events: %lld -> FoundTracks %d -> nPerfect %d  -> Purity: %3.2lf \n",
	 tree->GetEntries(),nTrackFound,nTrackPerfect,purity);

  // Efficiencies - and normalize to 100%

  TF1 f1("f1","100+x*0",0.,1.e3);

  hPurity->Divide(hPerfect,hAllFound,1,1,"b"); 
  hPurity->Multiply(&f1);
  hPurity->SetMarkerColor(kGreen);
  hPurity->SetMarkerStyle(21);
  hPurity->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  hPurity->SetStats(0);

  hPurity->GetYaxis()->SetRangeUser(0,100);
  hPurity->SetTitle("Efficiency & Purity");

  hEff->Divide(hPerfect,hAllMC,1,1,"b");
  hEff->Multiply(&f1);
  hEff->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  hEff->SetMarkerColor(kBlue);
  hEff->SetMarkerStyle(21);
  hEff->SetStats(0);

  hFake->Divide(hImperfect,hAllMC,1,1,"b");
  hFake->Multiply(&f1);
  hFake->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  hFake->SetMarkerColor(kRed);
  hFake->SetMarkerStyle(21);
  hFake->SetStats(0);


  hAnna->Divide(hAllFound,hAllMC,1,1,"b");
  hAnna->Multiply(&f1);
  hAnna->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  hAnna->SetMarkerColor(kBlack);
  hAnna->SetMarkerStyle(21);
  hAnna->SetStats(0);

  TCanvas *c1 = new TCanvas("c1","NoMCTrackFound");//,200,10,900,900);
  TVirtualPad *pad =   c1->cd();
  pad->SetGridx();   pad->SetGridy();
  hNoMCTrack->Draw();

  TCanvas *c2 = new TCanvas("c2","Eff&Purity");//,200,10,900,900);
  TVirtualPad *pad =   c2->cd();
  pad->SetGridx();   pad->SetGridy();
  //  pad->SetLogx();

  hPurity->Draw("E");
  hEff->Draw("Same E");
  hFake->Draw("Same E");
  hAnna->Draw("Same E");

  TLegend *leg = new TLegend(0.1,0.8,0.6,0.9);leg->SetFillColor(0);
  leg->AddEntry(hPurity,"Purity (\"Perfect tracks\" within \"Found Tracks\")","PE");
  leg->AddEntry(hEff,"Efficiency (\"Perfect tracks\" within \"MC findable Tracks\")","PE");
  leg->AddEntry(hFake,"Fake (\"Inperfect tracks\" within \"MC findable Tracks\")","PE");
  leg->AddEntry(hAnna,"AnnaLisa - Efficiency (\"Found tracks\" within \"MC findable Tracks\")","PE");
  leg->Draw();


  if (plotFlag==1){
    hAllMC->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    hAllMC->Draw();  // MC pt distribution
    hAllFound->SetLineColor(2);
    hAllFound->Draw("same");  // MC pt distribution
  }
 
 
  /*

  .L ~/ITSupgrade/BuildDetector/DetectorK.cxx+
  
  // All NEW
  DetectorK its("ALICE","ITS");
  its.MakeAliceAllNew(0);
  its.SetMaxRadiusOfSlowDetectors(0.01);
  its.SolveViaBilloir(0);
  TGraph *c = its.GetGraphRecoEfficiency(0,3,2);
  c->Draw("C");


  // Current
  DetectorK its("ALICE","ITS");
  its.MakeAliceCurrent(0,0);
  its.SetMaxRadiusOfSlowDetectors(0.01);
  its.SolveViaBilloir(0);
  TGraph *c = its.GetGraphRecoEfficiency(0,4,2);
  c->Draw("C");

  */

  TCanvas *c3 = new TCanvas("c3","impact");//,200,10,900,900);
  c3->Divide(2,1); c3->cd(1);
  // Impact parameter

  // Impact parameter resolution ---------------
  h2Ddca->Draw("colz");
  h2Ddca->FitSlicesY() ;
  TH2D *dcaM = (TH2D*)gDirectory->Get("dca2D_1"); dcaM->Draw("same");
  TH2D *dcaRMS = (TH2D*)gDirectory->Get("dca2D_2"); //dcaRMS->Draw();
  TGraphErrors *d0 = new TGraphErrors(); 
  for (Int_t ibin =1; ibin<=dcaRMS->GetXaxis()->GetNbins(); ibin++) {
    d0->SetPoint(     ibin-1,dcaRMS->GetBinCenter(ibin),dcaRMS->GetBinContent(ibin)*1e4); // microns
    d0->SetPointError(ibin-1,0,dcaRMS->GetBinError(ibin)*1e4); // microns
  }
  d0->SetMarkerStyle(21);
  d0->SetMaximum(200);  d0->SetMinimum(0);
  d0->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  d0->GetYaxis()->SetTitle("R-#phi Pointing Resolution (#mum)");
  d0->SetName("dca");  d0->SetTitle("DCAvsPt");

  c3->cd(1);  h2Ddca->Draw("surf2");
  c3->cd(2);  d0->Draw("APE");

  // PT RESOLUTION ------------
  TCanvas *c4 = new TCanvas("c4","pt resolution");//,200,10,900,900);
  c4->Divide(2,1); c4->cd(1);
  // Impact parameter
  h2Dpt->Draw("colz");
  h2Dpt->FitSlicesY() ;
  TH2D *dPtM = (TH2D*)gDirectory->Get("dPt2D_1"); dPtM->Draw("same");
  TH2D *dPtRMS = (TH2D*)gDirectory->Get("dPt2D_2"); // dPtRMS->Draw("");
  TGraphErrors *gPt = new TGraphErrors(); 
  for (Int_t ibin =1; ibin<=dPtRMS->GetXaxis()->GetNbins(); ibin++) {
    gPt->SetPoint(     ibin-1,dPtRMS->GetBinCenter(ibin),dPtRMS->GetBinContent(ibin)); 
    gPt->SetPointError(ibin-1,0,dPtRMS->GetBinError(ibin)); 
  }
  gPt->SetMarkerStyle(21);
  gPt->SetMaximum(20);  gPt->SetMinimum(0);
  gPt->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  gPt->GetYaxis()->SetTitle("relative momentum resolution (%)");
  gPt->SetName("dPt");  gPt->SetTitle("DPTvsPt");

  c4->cd(1);  h2Dpt->Draw("surf2");
  c4->cd(2);  gPt->Draw("APE");


  // EXPORT --------

  TFile f("histos.root","RECREATE");

  hMultCount->Write();
  hAllMC->Write();
  hAllFound->Write();
  hImperfect->Write();
  hPerfect->Write();
  hNoMCTrack->Write();

  hPurity->Write();
  hEff->Write();
  hFake->Write();
  hAnna->Write();

  h2Ddca->Write();
  d0->Write();

  h2Dpt->Write();
  gPt->Write();

  f.Close();

  return;

}
예제 #19
0
void plotMerged(Bool_t onlyPlot=0) {

  gStyle->SetPalette(1);
 
  TFile f("histoSum.root","UPDATE");

  TH1F* hAllMC = f.Get("allMC");
  TH1F* hAllFound= f.Get("allFound");
  TH1F* hImperfect= f.Get("imperfect");
  TH1F* hPerfect= f.Get("perfect");
  TH1F* hNoMCTrack= f.Get("noMCtrack");
  
  
  // have to be recalculated
  TH1F* hPurity = f.Get("purity");
  TH1F* hEff= f.Get("efficiency");
  TH1F* hFake= f.Get("fake");
  TH1F* hAnna= f.Get("annaEff");

  TH2D* h2Ddca= f.Get("dca2D");
  TGraphErrors *d0= f.Get("dca");

  TH2D* h2Dpt= f.Get("dPt2D");
  TGraphErrors *gPt= f.Get("dPt");


  if (!onlyPlot) {
    /*    // Get Errors right
    hAllMC->Sumw2();   
    hAllFound->Sumw2();
    hPerfect->Sumw2(); 
    hImperfect->Sumw2(); 
    h2Dpt->Sumw2();
    h2Ddca->Sumw2();
    */

    // Efficiencies - and normalize to 100%
    
    TF1 f1("f1","100+x*0",0.,1.e3);
    
    hPurity->Divide(hPerfect,hAllFound,1,1,"b"); 
    hPurity->Multiply(&f1);
    hPurity->SetMarkerColor(kGreen);
    hPurity->SetMarkerStyle(21);
    hPurity->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    hPurity->SetStats(0);
    
    hPurity->GetYaxis()->SetRangeUser(0,100);
    hPurity->SetTitle("Efficiency & Purity");
    
    hEff->Divide(hPerfect,hAllMC,1,1,"b");
    hEff->Multiply(&f1);
    hEff->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    hEff->SetMarkerColor(kBlue);
    hEff->SetMarkerStyle(21);
    hEff->SetStats(0);
    
    hFake->Divide(hImperfect,hAllMC,1,1,"b");
    hFake->Multiply(&f1);
    hFake->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    hFake->SetMarkerColor(kRed);
    hFake->SetMarkerStyle(21);
    hFake->SetStats(0);
    
    hAnna->Divide(hAllFound,hAllMC,1,1,"b");
    hAnna->Multiply(&f1);
    hAnna->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    hAnna->SetMarkerColor(kBlack);
    hAnna->SetMarkerStyle(21);
    hAnna->SetStats(0);
    
    
    // Impact parameter resolution ---------------
    TCanvas *c3 = new TCanvas("c3","impact");//,200,10,900,900);
    c3->Divide(2,1); c3->cd(1);
    h2Ddca->DrawCopy("colz");
    h2Ddca->FitSlicesY() ;
    TH2D *dcaM = (TH2D*)gDirectory->Get("dca2D_1"); dcaM->Draw("same");
    TH2D *dcaRMS = (TH2D*)gDirectory->Get("dca2D_2"); //dcaRMS->Draw();
    TGraphErrors *d0 = new TGraphErrors(); 
    for (Int_t ibin =1; ibin<=dcaRMS->GetXaxis()->GetNbins(); ibin++) {
      d0->SetPoint(     ibin-1,dcaRMS->GetBinCenter(ibin),dcaRMS->GetBinContent(ibin)*1e4); // microns
      d0->SetPointError(ibin-1,0,dcaRMS->GetBinError(ibin)*1e4); // microns
    }
    d0->SetMarkerStyle(21);
    d0->SetMaximum(200);  d0->SetMinimum(0);
    d0->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    d0->GetYaxis()->SetTitle("R-#phi Pointing Resolution (#mum)");
    d0->SetName("dca");  d0->SetTitle("DCAvsPt");
    //  c3->cd(1);  h2Ddca->Draw("surf2");
    c3->cd(2);  d0->Draw("APE");
    
    // PT RESOLUTION ------------
    TCanvas *c4 = new TCanvas("c4","pt resolution");//,200,10,900,900);  
    c4->Divide(2,1); c4->cd(1);
    h2Dpt->DrawCopy("colz");
    h2Dpt->FitSlicesY() ;
    TH2D *dPtM = (TH2D*)gDirectory->Get("dPt2D_1"); dPtM->Draw("same");
    TH2D *dPtRMS = (TH2D*)gDirectory->Get("dPt2D_2"); // dPtRMS->Draw("");
    TGraphErrors *gPt = new TGraphErrors(); 
    for (Int_t ibin =1; ibin<=dPtRMS->GetXaxis()->GetNbins(); ibin++) {
      gPt->SetPoint(     ibin-1,dPtRMS->GetBinCenter(ibin),dPtRMS->GetBinContent(ibin)); 
      gPt->SetPointError(ibin-1,0,dPtRMS->GetBinError(ibin)); 
    }
    gPt->SetMarkerStyle(21);
    gPt->SetMaximum(20);  gPt->SetMinimum(0);
    gPt->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    gPt->GetYaxis()->SetTitle("relative momentum resolution (%)");
    gPt->SetName("dPt");  gPt->SetTitle("DPTvsPt");
    //  c4->cd(1);  h2Dpt->Draw("surf2");
    c4->cd(2);  gPt->Draw("APE");


    // overwrite with normalized graphs
    hPurity->Write();
    hEff->Write();
    hFake->Write();
    hAnna->Write();
    h2Ddca->Write();
    d0->Write();
    h2Dpt->Write();
    gPt->Write();
   
  }
  
  // Plots

  TCanvas *c2 = new TCanvas("c2","Eff&Purity");//,200,10,900,900);
  TVirtualPad *pad =   c2->cd();
  pad->SetGridx();   pad->SetGridy();
  //  pad->SetLogx();

  TLegend *leg = new TLegend(0.1,0.8,0.6,0.9);leg->SetFillColor(0);
  leg->AddEntry(hPurity,"Purity (\"Perfect tracks\" within \"Found Tracks\")","PE");
  leg->AddEntry(hEff,"Efficiency (\"Perfect tracks\" within \"MC findable Tracks\")","PE");
  leg->AddEntry(hFake,"Fake (\"Inperfect tracks\" within \"MC findable Tracks\")","PE");
  leg->AddEntry(hAnna,"AnnaLisa - Efficiency (\"Found tracks\" within \"MC findable Tracks\")","PE");
 

  hPurity->DrawCopy("E");
  hEff->DrawCopy("Same E");
  hFake->DrawCopy("Same E");
  hAnna->DrawCopy("Same E");
  leg->Draw();

  c2->SaveAs("EffPlot.png");

  f.Close();



}
예제 #20
0
void TSVDUnfoldExample()
{
   gROOT->Reset();
   gROOT->SetStyle("Plain");
   gStyle->SetOptStat(0);

   TRandom3 R;

   const Double_t cutdummy= -99999.0;

   // --- Data/MC toy generation -----------------------------------

   // The MC input
   Int_t nbins = 40;
   TH1D *xini = new TH1D("xini", "MC truth", nbins, -10.0, 10.0);
   TH1D *bini = new TH1D("bini", "MC reco", nbins, -10.0, 10.0);
   TH2D *Adet = new TH2D("Adet", "detector response", nbins, -10.0, 10.0, nbins, -10.0, 10.0);

   // Data
   TH1D *data = new TH1D("data", "data", nbins, -10.0, 10.0);
   // Data "truth" distribution to test the unfolding
   TH1D *datatrue = new TH1D("datatrue", "data truth", nbins, -10.0, 10.0);
   // Statistical covariance matrix
   TH2D *statcov = new TH2D("statcov", "covariance matrix", nbins, -10.0, 10.0, nbins, -10.0, 10.0);

   // Fill the MC using a Breit-Wigner, mean 0.3 and width 2.5.
   for (Int_t i= 0; i<100000; i++) {
      Double_t xt = R.BreitWigner(0.3, 2.5);
      xini->Fill(xt);
      Double_t x = Reconstruct( xt, R );
      if (x != cutdummy) {
         Adet->Fill(x, xt);
         bini->Fill(x);
      }
   }

   // Fill the "data" with a Gaussian, mean 0 and width 2.
   for (Int_t i=0; i<10000; i++) {
      Double_t xt = R.Gaus(0.0, 2.0);
      datatrue->Fill(xt);
      Double_t x = Reconstruct( xt, R );
      if (x != cutdummy)
      data->Fill(x);
   }

   cout << "Created toy distributions and errors for: " << endl;
   cout << "... \"true MC\"   and \"reconstructed (smeared) MC\"" << endl;
   cout << "... \"true data\" and \"reconstructed (smeared) data\"" << endl;
   cout << "... the \"detector response matrix\"" << endl;

   // Fill the data covariance matrix
   for (int i=1; i<=data->GetNbinsX(); i++) {
       statcov->SetBinContent(i,i,data->GetBinError(i)*data->GetBinError(i));
   }

   // --- Here starts the actual unfolding -------------------------

   // Create TSVDUnfold object and initialise
   TSVDUnfold *tsvdunf = new TSVDUnfold( data, statcov, bini, xini, Adet );

   // It is possible to normalise unfolded spectrum to unit area
   tsvdunf->SetNormalize( kFALSE ); // no normalisation here

   // Perform the unfolding with regularisation parameter kreg = 13
   // - the larger kreg, the finer grained the unfolding, but the more fluctuations occur
   // - the smaller kreg, the stronger is the regularisation and the bias
   TH1D* unfres = tsvdunf->Unfold( 13 );

   // Get the distribution of the d to cross check the regularization
   // - choose kreg to be the point where |d_i| stop being statistically significantly >>1
   TH1D* ddist = tsvdunf->GetD();

   // Get the distribution of the singular values
   TH1D* svdist = tsvdunf->GetSV();

   // Compute the error matrix for the unfolded spectrum using toy MC
   // using the measured covariance matrix as input to generate the toys
   // 100 toys should usually be enough
   // The same method can be used for different covariance matrices separately.
   TH2D* ustatcov = tsvdunf->GetUnfoldCovMatrix( statcov, 100 );

   // Now compute the error matrix on the unfolded distribution originating
   // from the finite detector matrix statistics
   TH2D* uadetcov = tsvdunf->GetAdetCovMatrix( 100 );

   // Sum up the two (they are uncorrelated)
   ustatcov->Add( uadetcov );

   //Get the computed regularized covariance matrix (always corresponding to total uncertainty passed in constructor) and add uncertainties from finite MC statistics.
   TH2D* utaucov = tsvdunf->GetXtau();
   utaucov->Add( uadetcov );

   //Get the computed inverse of the covariance matrix
   TH2D* uinvcov = tsvdunf->GetXinv();


   // --- Only plotting stuff below ------------------------------

   for (int i=1; i<=unfres->GetNbinsX(); i++) {
      unfres->SetBinError(i, TMath::Sqrt(utaucov->GetBinContent(i,i)));
   }

   // Renormalize just to be able to plot on the same scale
   xini->Scale(0.7*datatrue->Integral()/xini->Integral());

   TLegend *leg = new TLegend(0.58,0.68,0.99,0.88);
   leg->SetBorderSize(0);
   leg->SetFillColor(0);
   leg->SetFillStyle(0);
   leg->AddEntry(unfres,"Unfolded Data","p");
   leg->AddEntry(datatrue,"True Data","l");
   leg->AddEntry(data,"Reconstructed Data","l");
   leg->AddEntry(xini,"True MC","l");

   TCanvas *c1 = new TCanvas( "c1", "Unfolding toy example with TSVDUnfold", 900, 800 );

   // --- Style settings -----------------------------------------
   Int_t c_Canvas    = TColor::GetColor( "#f0f0f0" );
   Int_t c_FrameFill = TColor::GetColor( "#fffffd" );
   Int_t c_TitleBox  = TColor::GetColor( "#6D7B8D" );
   Int_t c_TitleText = TColor::GetColor( "#FFFFFF" );

   c1->SetFrameFillColor( c_FrameFill );
   c1->SetFillColor     ( c_Canvas    );
   c1->Divide(1,2);
   TVirtualPad * c11 = c1->cd(1);
   c11->SetFrameFillColor( c_FrameFill );
   c11->SetFillColor     ( c_Canvas    );

   gStyle->SetTitleFillColor( c_TitleBox  );
   gStyle->SetTitleTextColor( c_TitleText );
   gStyle->SetTitleBorderSize( 1 );
   gStyle->SetTitleH( 0.052 );
   gStyle->SetTitleX( c1->GetLeftMargin() );
   gStyle->SetTitleY( 1 - c1->GetTopMargin() + gStyle->GetTitleH() );
   gStyle->SetTitleW( 1 - c1->GetLeftMargin() - c1->GetRightMargin() );

   TH1D* frame = new TH1D( *unfres );
   frame->SetTitle( "Unfolding toy example with TSVDUnfold" );
   frame->GetXaxis()->SetTitle( "x variable" );
   frame->GetYaxis()->SetTitle( "Events" );
   frame->GetXaxis()->SetTitleOffset( 1.25 );
   frame->GetYaxis()->SetTitleOffset( 1.29 );
   frame->Draw();

   data->SetLineStyle(2);
   data->SetLineColor(4);
   data->SetLineWidth(2);
   unfres->SetMarkerStyle(20);
   datatrue->SetLineColor(2);
   datatrue->SetLineWidth(2);
   xini->SetLineStyle(2);
   xini->SetLineColor(8);
   xini->SetLineWidth(2);
   // ------------------------------------------------------------

   // add histograms
   unfres->Draw("same");
   datatrue->Draw("same");
   data->Draw("same");
   xini->Draw("same");

   leg->Draw();

   // covariance matrix
   gStyle->SetPalette(1,0);
   TVirtualPad * c12 = c1->cd(2);
   c12->Divide(2,1);
   TVirtualPad * c2 = c12->cd(1);
   c2->SetFrameFillColor( c_FrameFill );
   c2->SetFillColor     ( c_Canvas    );
   c2->SetRightMargin   ( 0.15         );

   TH2D* covframe = new TH2D( *ustatcov );
   covframe->SetTitle( "TSVDUnfold covariance matrix" );
   covframe->GetXaxis()->SetTitle( "x variable" );
   covframe->GetYaxis()->SetTitle( "x variable" );
   covframe->GetXaxis()->SetTitleOffset( 1.25 );
   covframe->GetYaxis()->SetTitleOffset( 1.29 );
   covframe->Draw();

   ustatcov->SetLineWidth( 2 );
   ustatcov->Draw( "colzsame" );

   // distribution of the d quantity
   TVirtualPad * c3 = c12->cd(2);
   c3->SetFrameFillColor( c_FrameFill );
   c3->SetFillColor     ( c_Canvas    );
   c3->SetLogy();

   TLine *line = new TLine( 0.,1.,40.,1. );
   line->SetLineStyle(2);

   TH1D* dframe = new TH1D( *ddist );
   dframe->SetTitle( "TSVDUnfold |d_{i}|" );
   dframe->GetXaxis()->SetTitle( "i" );
   dframe->GetYaxis()->SetTitle( "|d_{i}|" );
   dframe->GetXaxis()->SetTitleOffset( 1.25 );
   dframe->GetYaxis()->SetTitleOffset( 1.29 );
   dframe->SetMinimum( 0.001 );
   dframe->Draw();

   ddist->SetLineWidth( 2 );
   ddist->Draw( "same" );
   line->Draw();
}
예제 #21
0
int main()
{
  TFile * apro = new TFile(inputFile.c_str(), "READ");
  TH2D * sig_templ = (TH2D*)apro->Get("MC_BDT_vs_mass_4CSV");   //4btag MC
  TH2D * bkg_templ = (TH2D*)apro->Get("BDT_vs_mass_3CSV");      //3btag Data
  TH2D * test = (TH2D*)apro->Get("BDT_vs_mass_4CSV");           //4btag Data
  TH2D * Twobtag = (TH2D*)apro->Get("BDT_vs_mass_2CSV");        //2btag Data

  // Apply Signal Scale Factor (f'=Lbkg/Lsig)
 //--------------------------------------------
  sig_templ->Scale(scaleFactorSig);

  // Set Bin Content and compute shape sys uncert.
  //-------------------------------------------------
//systematic scale error 0.63e-4 ?? -- DEBUG
  int binX_bdt = sig_templ->GetXaxis()->GetNbins();
  int binY_mass = sig_templ->GetYaxis()->GetNbins();
  int binTOT = binX_bdt*binY_mass;
  for(int i=1; i<=binTOT; i++) {  // to avoid zeros for the fit? - debug
    if(sig_templ->GetBinContent(i) == 0) sig_templ->SetBinContent(i,0.000000001); 
    if(bkg_templ->GetBinContent(i) == 0) bkg_templ->SetBinContent(i,0.000000001); 
  }

  TH1D * sig_1D = new TH1D("sig1D_temp", "sig1D_temp", binTOT, 0, binTOT); //MC 4b
  TH1D * bkg_1D = new TH1D("bkg1D_temp", "bkg1D_temp", binTOT, 0, binTOT); //data 3b
  TH1D * test_1D = new TH1D("data_obs_temp", "data_obs_temp", binTOT, 0, binTOT);  //data 4b
  TH1D * err_1D_up = new TH1D("bkg1D_systUp_temp", "bkg1D_systUp_temp", binTOT, 0, binTOT);  //shape syst computed below
  TH1D * err_1D_down = new TH1D("bkg1D_systDown_temp", "bkg1D_systDown_temp", binTOT, 0, binTOT);  //shape syst computed below
  double delta = 0, SdeltaQ = 0, err = 0, up = 0, down = 0;
  double N2 = Twobtag->Integral();
  double N3 = bkg_templ->Integral();
  double f = N3/N2;
  double b3, b2;
  for(int i=1; i<=binY_mass; i++) {
    for(int j=1; j<=binX_bdt; j++) {
      sig_1D->SetBinContent((i-1)*binX_bdt+j, sig_templ->GetBinContent(i,j)); 
      bkg_1D->SetBinContent((i-1)*binX_bdt+j, bkg_templ->GetBinContent(i,j)); 
      test_1D->SetBinContent((i-1)*binX_bdt+j, test->GetBinContent(i,j));
	
      b2=Twobtag->GetBinContent(i,j);
      b3=bkg_templ->GetBinContent(i,j);
      delta = (b3-(f*b2));
      SdeltaQ = (b3 + (f*f)*b2 + (b2/N2)*(b2/N2)*N3 + ((b2*N3)/(N2*N2))*((b2*N3)/(N2*N2))*N2);  // debug - to be checked
      if((delta*delta - SdeltaQ)>0.0) err = sqrt(delta*delta - SdeltaQ);
      if((delta*delta - SdeltaQ)<=0.0) err = 0.0;  // DEBUG
      up = bkg_templ->GetBinContent(i,j)+err;
      down = bkg_templ->GetBinContent(i,j)-err;
      err_1D_up->SetBinContent((i-1)*binX_bdt+j, up );
      err_1D_down->SetBinContent((i-1)*binX_bdt+j, down );
    }
  }

  // Final Histos
  //-----------------
  int Xmax = 330, finalBins = 330; //was 330
  TH1D * sig_1D_crop = new TH1D("sig1D", "sig1D", finalBins, 0, Xmax);
  TH1D * bkg_1D_crop = new TH1D("bkg1D", "bkg1D", finalBins, 0, Xmax);
  TH1D * test_1D_crop = new TH1D("data_obs", "data_obs", finalBins, 0, Xmax);
  TH1D * err_1D_crop_up = new TH1D("bkg1D_systUp", "bkg1D_systUp", finalBins, 0, Xmax);
  TH1D * err_1D_crop_down = new TH1D("bkg1D_systDown", "bkg1D_systDown", finalBins, 0, Xmax);
  int bin0 = 19; //was 19
  for(int i=bin0+1; i<=binTOT; i++) {
    if(i>=351)continue; //debug--
    sig_1D_crop  -> SetBinContent(i-bin0, sig_1D->GetBinContent(i));
    bkg_1D_crop  -> SetBinContent(i-bin0, bkg_1D->GetBinContent(i));
    test_1D_crop -> SetBinContent(i-bin0, test_1D->GetBinContent(i));
    err_1D_crop_up -> SetBinContent(i-bin0, err_1D_up->GetBinContent(i));
    err_1D_crop_down -> SetBinContent(i-bin0, err_1D_down->GetBinContent(i));
  }

  // Apply Scale Factor (f=tot4bTag/tot3bTag)
  //--------------------------------------------
  scaleFactorBkg = test_1D_crop->Integral()/bkg_1D_crop->Integral();
  bkg_1D_crop->Scale(scaleFactorBkg );
  err_1D_crop_up->Scale(scaleFactorBkg );
  err_1D_crop_down->Scale(scaleFactorBkg );


  // Output for combine
  //-----------------------
  std::cout << "Integrals for Combine datacard" << std::endl;
  std::cout << "data_obs: \t" << test_1D_crop->Integral() << std::endl;
  std::cout << "signal: \t" << sig_1D_crop->Integral() << std::endl;
  std::cout << "background: \t" << bkg_1D_crop->Integral() << std::endl;  //with f scale factor

  TFile * output = new TFile(outFile.c_str(), "RECREATE");
  sig_1D_crop->Write();
  bkg_1D_crop->Write();
  test_1D_crop->Write();
  err_1D_crop_up->Write();
  err_1D_crop_down->Write();
  output->Close();
  apro->Close();

  return 0;
}
예제 #22
0
void makeVNDet(){

  bool testrun          = 0;
  const int norder_     = 2;
  const int QnBinOrder_ = 2;
  const double vtxCut   = 15.;

  static const int ptBinMin  = 0;
  static const int ptBinMax  = nptbinsDefault-1;
  static const int etaBinMin = 0; //0;
  static const int etaBinMax = netabinsDefault-1;

  TFile * fAna;
  TTree * tree;
  double centval;
  double vtx;
  TH2D * sumw;
  TH2D * sumwqx;
  TH2D * sumwqy;
  TH2I * hMult;
  double qnHFx_EP[NumEPNames];
  double qnHFy_EP[NumEPNames];
  double sumET_EP[NumEPNames];

  TFile * fQNDet;
  TH1D * hqnHFDet_x[NumEPNames];
  TH1D * hqnHFDet_y[NumEPNames];

  TFile * fQN;
  TH1D * hqbins[NCENT][NEPSymm];

  TFile * fOut;
  TDirectory * SubEvt_0;
  TDirectory * SubEvt_1;
  TDirectory * FullEvt;

  TH2D * hVNDetX_0[NQN];
  TH2D * hVNDetY_0[NQN];
  TH2D * hVNDetX_1[NQN];
  TH2D * hVNDetY_1[NQN];
  TH2D * hVNDetX_full[NQN];
  TH2D * hVNDetY_full[NQN];

  double VNRawX_0[NCENT][NEPSymm][NQN];
  double VNRawY_0[NCENT][NEPSymm][NQN];
  double VNRawX_1[NCENT][NEPSymm][NQN];
  double VNRawY_1[NCENT][NEPSymm][NQN];
  double VNRawX_full[NCENT][NEPSymm][NQN];
  double VNRawY_full[NCENT][NEPSymm][NQN];

  double sumw_0[NCENT][NEPSymm][NQN];
  double sumw_1[NCENT][NEPSymm][NQN];
  double sumw_full[NCENT][NEPSymm][NQN];

  int evtMult_0[NCENT][NEPSymm][NQN];
  int evtMult_1[NCENT][NEPSymm][NQN];
  int evtMult_full[NCENT][NEPSymm][NQN];
 
  double VNDetX_0[NCENT][NEPSymm][NQN];
  double VNDetY_0[NCENT][NEPSymm][NQN];
  double VNDetX_1[NCENT][NEPSymm][NQN];
  double VNDetY_1[NCENT][NEPSymm][NQN];
  double VNDetX_full[NCENT][NEPSymm][NQN];
  double VNDetY_full[NCENT][NEPSymm][NQN];

  int Nevents[NCENT][NEPSymm][NQN];
  int NFails[NCENT][NEPSymm][NQN];

  //
  // MAIN
  //


  //-- Set up the analyzer objects
  fAna = new TFile(fAnaTreeName);

  tree = (TTree*) fAna->Get("ebyeana/tree");
  sumwqx = new TH2D(Form("sumwqx%i", norder_), Form("sumwqx%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumwqy = new TH2D(Form("sumwqy%i", norder_), Form("sumwqy%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumw   = new TH2D("sumw",                    "sumw",                    nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  hMult  = new TH2I("hMult",                   "hMult",                   nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
    
  tree->SetBranchAddress("Cent",                    &centval);
  tree->SetBranchAddress("Vtx",                     &vtx);
  tree->SetBranchAddress("mult",                    &hMult);
  tree->SetBranchAddress(Form("sumwqx%i", norder_), &sumwqx);
  tree->SetBranchAddress(Form("sumwqy%i", norder_), &sumwqy);
  tree->SetBranchAddress("sumw",                    &sumw);
  tree->SetBranchAddress("qnHFx_EP",                &qnHFx_EP);
  tree->SetBranchAddress("qnHFy_EP",                &qnHFy_EP);
  tree->SetBranchAddress("sumET_EP",                &sumET_EP);

  //-- Get the QN Detector histograms                                                                                                                                                                                             
  fQNDet = new TFile( Form("../../../../../../v%i/eta2.4/systematicStudies/vtxCut/vtx3_15/AnalyzerResults/Q%iDet.root", QnBinOrder_, QnBinOrder_) );
  for(int iEP = 0; iEP < NumEPNames; iEP++){
    int EPbin  = EPSymmPartnerBin[iEP];
    if( EPbin != EPSymmBin ) continue;
    hqnHFDet_x[iEP] = (TH1D*) fQNDet->Get( Form("hqnHFDet_x_%s", EPNames[iEP].data()) );
    hqnHFDet_y[iEP] = (TH1D*) fQNDet->Get( Form("hqnHFDet_y_%s", EPNames[iEP].data()) );
  }

  //-- Setup the QN binning objects
  fQN = new TFile( Form( "../../../../../../v%i/eta2.4/systematicStudies/vtxCut/vtx3_15/AnalyzerResults/q%iCuts.root", QnBinOrder_, QnBinOrder_) );
  for(int icent = 0; icent < NCENT; icent++){
    for(int iEP = 0; iEP < NEPSymm; iEP++){
      if( iEP != EPSymmBin ) continue;
      hqbins[icent][iEP] = (TH1D*) fQN->Get( Form("hqbins_%s_c%i", EPSymmNames[iEP].data(), icent) );
    }
  }

  //-- Setup the output objects
  fOut     = new TFile( Form("V%iDet.root", norder_), "recreate" );
  SubEvt_0 = fOut->mkdir("SubEvt_0");
  SubEvt_1 = fOut->mkdir("SubEvt_1");
  FullEvt  = fOut->mkdir("FullEvt");
    
  for(int iqn = 0; iqn < NQN; iqn++){
    SubEvt_0->cd();
    hVNDetX_0[iqn]    = new TH2D( Form("hVNDetX_0_qbin%i", iqn),    Form("hVNDetX_0_qbin%i", iqn),    NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetX_0[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetX_0[iqn]->SetOption("colz");
    
    hVNDetY_0[iqn]    = new TH2D( Form("hVNDetY_0_qbin%i", iqn),    Form("hVNDetY_0_qbin%i", iqn),    NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetY_0[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetY_0[iqn]->SetOption("colz");
    
    SubEvt_1->cd();
    hVNDetX_1[iqn]    = new TH2D( Form("hVNDetX_1_qbin%i", iqn),    Form("hVNDetX_1_qbin%i", iqn),    NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetX_1[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetX_1[iqn]->SetOption("colz");
    
    hVNDetY_1[iqn]    = new TH2D( Form("hVNDetY_1_qbin%i", iqn),    Form("hVNDetY_1_qbin%i", iqn),    NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetY_1[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetY_1[iqn]->SetOption("colz");
  
    FullEvt->cd();
    hVNDetX_full[iqn] = new TH2D( Form("hVNDetX_full_qbin%i", iqn), Form("hVNDetX_full_qbin%i", iqn), NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetX_full[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetX_full[iqn]->SetOption("colz");
    
    hVNDetY_full[iqn] = new TH2D( Form("hVNDetY_full_qbin%i", iqn), Form("hVNDetY_full_qbin%i", iqn), NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetY_full[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetY_full[iqn]->SetOption("colz");
    
    for(int iEP = 0; iEP < NEPSymm; iEP++){
      hVNDetX_0[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
      hVNDetY_0[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
      hVNDetX_1[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
      hVNDetY_1[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
      hVNDetX_full[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
      hVNDetY_full[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
    }

  }
    
  //-- initialize all variables
  for(int icent = 0; icent<NCENT; icent++){
    for(int iEP = 0; iEP < NEPSymm; iEP++){
      if( iEP != EPSymmBin ) continue;
      for(int iqn = 0; iqn < NQN; iqn++){

	VNDetX_0[icent][iEP][iqn]     = 0.;
	VNDetY_0[icent][iEP][iqn]     = 0.;
	VNDetX_1[icent][iEP][iqn]     = 0.;
	VNDetY_1[icent][iEP][iqn]     = 0.;
	VNDetX_full[icent][iEP][iqn]  = 0.;
	VNDetY_full[icent][iEP][iqn]  = 0.;

	evtMult_0[icent][iEP][iqn]    = 0;
	evtMult_1[icent][iEP][iqn]    = 0;
	evtMult_full[icent][iEP][iqn] = 0;

	Nevents[icent][iEP][iqn]      = 0;
	NFails[icent][iEP][iqn]       = 0;

      }
    }
  }
    
    
  //
  // Calculate Vn_det
  //
    
  cout<<"Begin DETECTOR loop, contains "<<tree->GetEntries()<<" Events"<<endl;
    
  int N;
  if(testrun) N = 10000; 
  else        N = tree->GetEntries();


  //-- Begin event loop
  for(int ievent = 0; ievent < N; ievent++) {
        
    if((ievent+1)% 500000 == 0) cout << "Processing Event " << ievent+1 << "\t" << (100.*(ievent+1)/N) << "% Completed" << endl;
        
    tree->GetEntry(ievent);
      
    //-- Vertex Cut
    if(TMath::Abs(vtx) < 3. || TMath::Abs(vtx) > 15.) continue;
      
    //-- Calculate centbin
    if( centval > cent_max[NCENT-1]) continue;
    int icent = hCentBins.FindBin(centval)-1;

    //-- begin EP loop
    for(int iEP = 0; iEP < NEP; iEP++){

      int EPbin  = EPSymmPartnerBin[iEP];
      if( EPbin != EPSymmBin ) continue;

      //-- Calculate qbin
      double qx    = qnHFx_EP[iEP];
      double qy    = qnHFy_EP[iEP];
      double qxDet = hqnHFDet_x[iEP]->GetBinContent(icent+1);
      double qyDet = hqnHFDet_y[iEP]->GetBinContent(icent+1);
      double sumET = sumET_EP[iEP];
      if(sumET == 0) continue;
      qx -= qxDet;
      qy -= qyDet;
      qx /= sumET;
      qy /= sumET;
      double qn = TMath::Sqrt( qx*qx + qy*qy );
      int   iqn = hqbins[icent][EPbin]->FindBin( qn ) - 1;
      if(iqn >= NQN) continue;

      //-- Reset Raw and sumw values
      VNRawX_0[icent][EPbin][iqn]     = 0.;
      VNRawY_0[icent][EPbin][iqn]     = 0.;
      VNRawX_1[icent][EPbin][iqn]     = 0.;
      VNRawY_1[icent][EPbin][iqn]     = 0.;
      VNRawX_full[icent][EPbin][iqn]  = 0.;
      VNRawY_full[icent][EPbin][iqn]  = 0.;            
	
      sumw_0[icent][EPbin][iqn]       = 0.;
      sumw_1[icent][EPbin][iqn]       = 0.;
      sumw_full[icent][EPbin][iqn]    = 0.;
      
      evtMult_0[icent][EPbin][iqn]    = 0;
      evtMult_1[icent][EPbin][iqn]    = 0;
      evtMult_full[icent][EPbin][iqn] = 0;
      
      Nevents[icent][EPbin][iqn]++;

      //-- Begin analyzer histogram loops
      for(int ipt = ptBinMin; ipt <= ptBinMax; ipt++){
	for(int ieta = etaBinMin; ieta <= etaBinMax; ieta++){
	  
	  if(sumw->GetBinContent(ipt+1,ieta+1) !=0){
	    
	    //-- Subevent 0 (eta >= 0)
	    if(etabinsDefault[ieta] >= 0){
	      VNRawX_0[icent][EPbin][iqn]   += sumwqx->GetBinContent(ipt+1,ieta+1);
	      VNRawY_0[icent][EPbin][iqn]   += sumwqy->GetBinContent(ipt+1,ieta+1);
	      
	      sumw_0[icent][EPbin][iqn]     += sumw->GetBinContent(ipt+1,ieta+1);
	      evtMult_0[icent][EPbin][iqn]  += hMult->GetBinContent(ipt+1,ieta+1);
	    }
	    //-- Subevent 1 (eta < 0)
	    else{
	      VNRawX_1[icent][EPbin][iqn]   += sumwqx->GetBinContent(ipt+1,ieta+1);
	      VNRawY_1[icent][EPbin][iqn]   += sumwqy->GetBinContent(ipt+1,ieta+1);
	      
	      sumw_1[icent][EPbin][iqn]     += sumw->GetBinContent(ipt+1,ieta+1);
	      evtMult_1[icent][EPbin][iqn]  += hMult->GetBinContent(ipt+1,ieta+1);
	    }
	    //-- Full Event
	    VNRawX_full[icent][EPbin][iqn]  += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VNRawY_full[icent][EPbin][iqn]  += sumwqy->GetBinContent(ipt+1,ieta+1);
	    
	    sumw_full[icent][EPbin][iqn]    += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_full[icent][EPbin][iqn] += hMult->GetBinContent(ipt+1,ieta+1);
	  }
	  
	} //-- End eta loop
	
      } //-- End pt loop
      
      //-- Only use events that have tracks in all subevents AND subevents that have at least two tracks to determine VN
      if( sumw_0[icent][EPbin][iqn] == 0 || sumw_1[icent][EPbin][iqn] == 0 || evtMult_0[icent][EPbin][iqn] < 2 || evtMult_1[icent][EPbin][iqn] < 2 ){
	NFails[icent][EPbin][iqn]++;
      }
      else{      
	VNDetX_0[icent][EPbin][iqn]    += VNRawX_0[icent][EPbin][iqn]    / sumw_0[icent][EPbin][iqn];
	VNDetY_0[icent][EPbin][iqn]    += VNRawY_0[icent][EPbin][iqn]    / sumw_0[icent][EPbin][iqn];
	VNDetX_1[icent][EPbin][iqn]    += VNRawX_1[icent][EPbin][iqn]    / sumw_1[icent][EPbin][iqn];
	VNDetY_1[icent][EPbin][iqn]    += VNRawY_1[icent][EPbin][iqn]    / sumw_1[icent][EPbin][iqn];
	VNDetX_full[icent][EPbin][iqn] += VNRawX_full[icent][EPbin][iqn] / sumw_full[icent][EPbin][iqn];
	VNDetY_full[icent][EPbin][iqn] += VNRawY_full[icent][EPbin][iqn] / sumw_full[icent][EPbin][iqn];
      }

    } //-- End EP loop

  } //-- End event loop
    
  std::cout<<"End DETECTOR loop"<<std::endl;

  //-- Average VNDet over all events for each centrality, EP and, qn bin
  for(int iqn = 0; iqn < NQN; iqn++){
    for(int icent = 0; icent < NCENT; icent++){
      for(int iEP = 0; iEP < NEPSymm; iEP++){
	if( iEP != EPSymmBin ) continue;

	double  Neffective = (double) Nevents[icent][iEP][iqn] - (double) NFails[icent][iEP][iqn];
	if( Neffective == 0) continue;

	VNDetX_0[icent][iEP][iqn]    /= Neffective;
	VNDetY_0[icent][iEP][iqn]    /= Neffective;
	VNDetX_1[icent][iEP][iqn]    /= Neffective;
	VNDetY_1[icent][iEP][iqn]    /= Neffective;
	VNDetX_full[icent][iEP][iqn] /= Neffective;
	VNDetY_full[icent][iEP][iqn] /= Neffective;

	//-- Populate histograms that will be used by ReadTree_normDet.C
	hVNDetX_0[iqn]    -> SetBinContent(icent+1, iEP+1, VNDetX_0[icent][iEP][iqn]);
	hVNDetX_1[iqn]    -> SetBinContent(icent+1, iEP+1, VNDetX_1[icent][iEP][iqn]);
	hVNDetX_full[iqn] -> SetBinContent(icent+1, iEP+1, VNDetX_full[icent][iEP][iqn]);
        
	hVNDetY_0[iqn]    -> SetBinContent(icent+1, iEP+1, VNDetY_0[icent][iEP][iqn]);
	hVNDetY_1[iqn]    -> SetBinContent(icent+1, iEP+1, VNDetY_1[icent][iEP][iqn]);
	hVNDetY_full[iqn] -> SetBinContent(icent+1, iEP+1, VNDetY_full[icent][iEP][iqn]);

      }
    }
  } //-- END TRIPLE LOOP

  fOut->Write();
  cout<<"File written, process completed"<<endl;

}
예제 #23
0
void residualAlignment(TH2D* residualX, TH2D* residualY, double& offsetX,
                       double& offsetY, double& rotation,
                       double relaxation, bool display)
{
  assert(residualX && residualY && "Processors: can't perform residual alignment without histograms");

  rotation = 0;
  offsetX = 0;
  offsetY = 0;
  double angleWeights = 0;
  double fitChi2 = 0;

  for (int axis = 0; axis < 2; axis++)
  {
    TH2D* hist = 0;
    if (axis) hist = residualX;
    else      hist = residualY;

    // Project the histogram and fit with a gaussian to center the sensor
    TH1D* project = hist->ProjectionX("ResidualProjetion", 1, hist->GetNbinsY());
    project->SetDirectory(0);

    double sigma = project->GetBinWidth(1);
    double mean = 0;
    fitGaussian(project, mean, sigma, false);

    if (axis) offsetX = mean;
    else      offsetY = mean;

    delete project;

    std::vector<double> ptsX;
    std::vector<double> ptsY;
    std::vector<double> ptsErr;

    const unsigned int numSlices = hist->GetNbinsY();

    for (Int_t row = 1; row <= (int)numSlices; row++)
    {
      TH1D* slice = hist->ProjectionX("ResidualSlice", row, row);
      slice->SetDirectory(0);

      double mean = 0;
      double sigma = 0;
      double factor = 0;
      double background = 0;

      if (slice->Integral() < 1) { delete slice; continue; }
      fitGaussian(slice, mean, sigma, factor, background, false);

      const double sliceMin = slice->GetBinCenter(1);
      const double sliceMax = slice->GetBinCenter(slice->GetNbinsX());
      delete slice;

      // Quality assurance

      // Sigma is contained in the slice's range
      if (sigma > (sliceMax - sliceMin)) continue;
      // Mean is contained in the slice's range
      if (mean > sliceMax || mean < sliceMin) continue;
      // Peak is contains sufficient events
      if (factor < 100) continue;
      // Sufficient signal to noise ratio
      if (factor / background < 10) continue;

      // Get the total number of events in the gaussian 1 sigma
      Int_t sigRangeLow = hist->FindBin(mean - sigma);
      Int_t sigRangeHigh = hist->FindBin(mean + sigma);

      double sigRangeTotal = 0;
      for (Int_t bin = sigRangeLow; bin <= sigRangeHigh; bin++)
        sigRangeTotal += hist->GetBinContent(bin);

      // 2 * 1 sigma integral shoudl give ~ area under gaussian
      sigma /= sqrt(2 * sigRangeTotal);

      ptsX.push_back(hist->GetYaxis()->GetBinCenter(row));
      ptsY.push_back(mean);
      ptsErr.push_back(sigma);
    }

    if (ptsX.size() < 3) continue;

    std::vector<double> yvals = ptsY;
    std::sort(yvals.begin(), yvals.end());
    const double median = yvals[yvals.size()/2];
    double avgDeviation = 0;
    for (unsigned int i = 0; i < yvals.size(); i++)
      avgDeviation += fabs(yvals[i] - median);
    avgDeviation /= (double)yvals.size();

    std::vector<double> ptsXGood;
    std::vector<double> ptsYGood;
    std::vector<double> ptsErrGood;

    for (unsigned int i = 0; i < ptsX.size(); i++)
    {
      if (fabs(ptsY[i] - median) > 1.5*avgDeviation) continue;
      ptsXGood.push_back(ptsX[i]);
      ptsYGood.push_back(ptsY[i]);
      ptsErrGood.push_back(ptsErr[i]);
    }

    if (ptsXGood.size() < 3) continue;

    TGraphErrors* graph = new TGraphErrors(ptsXGood.size(),
                                           &(ptsXGood.at(0)),
                                           &(ptsYGood.at(0)), 0,
                                           &(ptsErrGood.at(0)));

    TF1* fitFunc = new TF1("f1", "1 ++ x");
    TF1* result = 0;

    graph->Fit(fitFunc, "Q0E").Get();
    result = graph->GetFunction(fitFunc->GetName());

    // Weight the angle by the slope uncertainty and the inverse of the chi2 normalized
    double weight = result->GetParError(1);
    const double chi2 = result->GetChisquare() / (double)result->GetNDF();
    fitChi2 += chi2;
    weight *= chi2;
    if (weight > 10 * DBL_MIN) weight = 1.0 / weight;
    else weight = 1.0;

    if (axis)
    {
      rotation -= weight * atan(result->GetParameter(1));
      offsetX = result->GetParameter(0);
    }
    else
    {
      rotation += weight * atan(result->GetParameter(1));
      offsetY = result->GetParameter(0);
    }

    angleWeights += weight;

    if (display)
    {
      TCanvas* can = new TCanvas("ResidualAlignment", "Residual Alignment", 900, 600);
      can->Divide(2);
      can->cd(1);
      hist->Draw("COLZ");
      can->cd(2);
      result->SetLineColor(46);
      result->SetLineWidth(2);
      graph->Draw("ap");
      result->Draw("SAME");
      can->Update();
      can->WaitPrimitive();
    }

    delete fitFunc;
    delete graph;
  }

  if (angleWeights > 10 * DBL_MIN)
    rotation /= angleWeights;
  std::cout << "relaxation: " << relaxation << std::endl;
  rotation *= relaxation;
  offsetX *= relaxation;
  offsetY *= relaxation;
}
void run_radius_correction ()
{
    TStopwatch timer;
    timer.Start();

    gStyle->SetPalette(1,0);
    gStyle->SetHistLineWidth(2);

    // ----  Load libraries   -------------------------------------------------
    gROOT->LoadMacro("$VMCWORKDIR/gconfig/basiclibs.C");
    basiclibs();
    gROOT->LoadMacro("$VMCWORKDIR/macro/rich/cbmlibs.C");
    cbmlibs();

   // gROOT->LoadMacro("$VMCWORKDIR/macro/rich/setstyle.C");
   // setphdStyle();
    SetStyles();

    char fileMC[200], fileRec[200];

    sprintf(fileMC,"/d/cbm02/slebedev/rich/JUL09/correction/mc.00.root");
    cout<<fileMC<<endl;
    TFile *f1 = new TFile(fileMC,"R");
    TTree* t1 = f1->Get("cbmsim");
    TFolder *fd1 = f1->Get("cbmroot");
    TClonesArray* fMCTracks = (TClonesArray*) fd1->FindObjectAny("MCTrack");
    t1->SetBranchAddress(fMCTracks->GetName(),&fMCTracks);

    sprintf(fileRec, "/d/cbm02/slebedev/rich/JUL09/correction/reco.00.root");
    TFile *f = new TFile(fileRec,"R");
    TTree* t = f->Get("cbmsim");
    TFolder *fd = f->Get("cbmout");
    TClonesArray *fRichRings = (TClonesArray*) fd->FindObjectAny("RichRing");
    t->SetBranchAddress(fRichRings->GetName(),&fRichRings);
    TClonesArray *fRichMatches = (TClonesArray*) fd->FindObjectAny("RichRingMatch");
    t->SetBranchAddress(fRichMatches->GetName(),&fRichMatches);

    //Int_t fNofBinsX = 40;
    //Int_t fNofBinsY = 50;
    Int_t fNofBinsX = 25;
    Int_t fNofBinsY = 25;
    ///A axis
    TH2D* fh_axisAXYCount;
    TH2D* fh_axisAXYW;
    TH2D* fh_axisAXY;
    TH2D* fh_axisASigma;
    TH2D* mapaxisAXY;


    ///B axis
    TH2D* fh_axisBXYCount;
    TH2D* fh_axisBXYW;
    TH2D* fh_axisBXY;
    TH2D* fh_axisBSigma;
    TH2D* mapaxisBXY;

    mapaxisAXY = new TH2D("fh_mapaxisAXY","dA distribution (x,y);X, [cm];Y, [cm]",fNofBinsX,-200,200,fNofBinsY,-250,250);
    mapaxisBXY = new TH2D("fh_mapaxisBXY","dB distribution (x,y);X, [cm];Y, [cm]",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisAXYCount = new TH2D("fh_axisAXYCount","A Count",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisAXYW = new TH2D("fh_axisAXYW","",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisBXYCount = new TH2D("fh_axisBXYCount","B Count",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisBXYW = new TH2D("fh_axisBXYW","",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisAXY = new TH2D("fh_axisAXY","A distribution (x,y);X, [cm];Y, [cm]",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisBXY = new TH2D("fh_axisBXY","B distribution (x,y);X, [cm];Y, [cm]",fNofBinsX,-200,200,fNofBinsY,-250,250);

    Double_t fMinAaxis = 4.5;
    Double_t fMaxAaxis = 7.5;

    ///Set Mean value of A and B axeses, Compact RICH
    //Double_t fMeanAaxis = 5.06;
    //Double_t fMeanBaxis = 4.65;

    ///Set Mean value of A and B axeses, Large RICH
    Double_t fMeanAaxis = 6.17;
    Double_t fMeanBaxis = 5.6;

    Int_t nEvents=t->GetEntries();
    cout<<" nEvents ="<<nEvents<<endl;
    for(Int_t ievent=0;ievent<nEvents; ievent++ ) {
        cout<<"ievent = "<<ievent;
        CbmRichRing *ring=NULL;
        CbmRichRingMatch *match=NULL;
        t->GetEntry(ievent);
        t1->GetEntry(ievent);
        Int_t nofRings = fRichRings->GetEntries();
        cout<<"  nofRings = "<<nofRings;
        cout<<"  nofMatches = "<< fRichMatches->GetEntries() ;
        cout<<"  nofMCTracks = "<<fMCTracks->GetEntries() << endl;

        for(Int_t iRing=0; iRing < nofRings; iRing++){
            ring = (CbmRichRing*)fRichRings->At(iRing);
            if (!ring) continue;
            match = (CbmRichRingMatch*)fRichMatches->At(iRing);
            if (!match) continue;

            Int_t trackId = match->GetMCTrackID();
            if (trackId == -1) continue;
            if (trackId > fMCTracks->GetEntries()) continue;

            CbmMCTrack* mcTrack = (CbmMCTrack*)fMCTracks->At(trackId);
            if (!mcTrack) continue;
            Int_t pdg = TMath::Abs(mcTrack->GetPdgCode());
            Int_t motherId = mcTrack->GetMotherId();
            if (pdg != 11) continue;
            if (motherId != -1) continue;

            Double_t radius = ring->GetRadius();
            Double_t axisA = ring->GetAaxis();
            Double_t axisB = ring->GetBaxis();
            Double_t centerX = ring->GetCenterX();
            Double_t centerY = ring->GetCenterY();

            if (axisA > fMaxAaxis || axisB > fMaxAaxis) continue;
            if (axisA < fMinAaxis || axisB < fMinAaxis) continue;

            fh_axisAXYW->Fill(centerX, centerY, axisA);
            fh_axisAXYCount->Fill(centerX, centerY);

            fh_axisBXYW->Fill(centerX, centerY, axisB);
            fh_axisBXYCount->Fill(centerX, centerY);
        } //iRing
    } //iEvent

    fh_axisAXY->Divide(fh_axisAXYW,fh_axisAXYCount);
    fh_axisBXY->Divide(fh_axisBXYW,fh_axisBXYCount);


///create two correction maps
    for (Int_t iX = 1; iX < mapaxisAXY->GetNbinsX() + 1; iX++){
        for (Int_t iY = 1; iY < mapaxisAXY->GetNbinsY() + 1; iY++){
        	if (fh_axisAXYCount->GetBinContent(iX, iY) != 0){
        		mapaxisAXY->SetBinContent(iX, iY, fMeanAaxis - fh_axisAXY->GetBinContent(iX, iY) );
        	} else {
        		mapaxisAXY->SetBinContent(iX, iY, -99999999.);
        	}

        	if (fh_axisBXYCount->GetBinContent(iX, iY) != 0){
        		mapaxisBXY->SetBinContent(iX, iY, fMeanBaxis - fh_axisBXY->GetBinContent(iX, iY) );
        	} else {
        		mapaxisBXY->SetBinContent(iX, iY, -99999999.);
        	}
        }
    }

    c1_0 = new TCanvas("c1_0","c1_0",10,10,600,600);
    c1_0->Divide(1,2);
    c1_0->cd(1);
    fh_axisAXYCount->Draw("COLZ");
    c1_0->cd(2);
    fh_axisBXYCount->Draw("COLZ");

    c1 = new TCanvas("c1","c1",10,10,600,600);
    c1->Divide(1,2);
    c1->cd(1);
    fh_axisAXY->SetMinimum(5.0);
    fh_axisAXY->SetMaximum(6.4);
    fh_axisAXY->Draw("COLZ");
    c1->cd(2);
    fh_axisBXY->SetMinimum(5.0);
    fh_axisBXY->SetMaximum(6.0);
    fh_axisBXY->Draw("COLZ");

    c2 = new TCanvas("c2","c2",10,10,600,600);
    c2->Divide(1,2);
    c2->cd(1);
    mapaxisAXY->SetMinimum(-0.5);
    mapaxisAXY->SetMaximum(0.5);
    mapaxisAXY->Draw("COLZ");
    c2->cd(2);
    mapaxisBXY->SetMinimum(-0.5);
    mapaxisBXY->SetMaximum(0.5);
    mapaxisBXY->Draw("COLZ");


///// Check correction procedure
    TH1D* fh_Abefore = new TH1D("fh_Abefore","A before;A, [cm];yield", 300, 0., 9.);;
    TH1D* fh_Bbefore= new TH1D("fh_Bbefore","B before;B, [cm];yield", 300, 0., 9.);;

    TH1D* fh_A = new TH1D("fh_A","A after;A, [cm];yield", 300, 0., 9.);;
    TH1D* fh_B = new TH1D("fh_B","B after;B, [cm];yield", 300, 0., 9.);;

    cout <<"Check correction procedure......" << endl;
    for(Int_t ievent=0;ievent<nEvents;ievent++ ) {
        CbmRichRing *ring=NULL;
       // if (ievent % 100 == 0) cout << ievent << "   ";
        //t1->GetEntry(ievent);
        t->GetEntry(ievent);
        t1->GetEntry(ievent);
        Int_t nofRings = fRichRings->GetEntries();

        for(Int_t iRing=0; iRing < nofRings; iRing++){

            ring = (CbmRichRing*)fRichRings->At(iRing);
            if (!ring) continue;
            match = (CbmRichRingMatch*)fRichMatches->At(iRing);
            if (!match) continue;

            Int_t trackId = match->GetMCTrackID();
            if (trackId == -1) continue;
            if (trackId > fMCTracks->GetEntries()) continue;

            CbmMCTrack* mcTrack = (CbmMCTrack*)fMCTracks->At(trackId);
            if (!mcTrack) continue;
            Int_t pdg = TMath::Abs(mcTrack->GetPdgCode());
            Int_t motherId = mcTrack->GetMotherId();
            if (pdg != 11) continue;
            if (motherId != -1) continue;

            Double_t axisA = ring->GetAaxis();
            Double_t axisB = ring->GetBaxis();
            if (axisA > fMaxAaxis || axisB > fMaxAaxis) continue;
            if (axisA < fMinAaxis || axisB < fMinAaxis) continue;

            Double_t radius = ring->GetRadius();
            Double_t centerX = ring->GetCenterX();
            Double_t centerY = ring->GetCenterY();
            Double_t axisAbefore = ring->GetAaxis();
            Double_t axisBbefore = ring->GetBaxis();
            fh_Abefore->Fill(axisAbefore);
            fh_Bbefore->Fill(axisBbefore);

            Double_t axisA = ring->GetAaxis();
            Double_t axisB = ring->GetBaxis() ;

            axisA += mapaxisAXY->GetBinContent(mapaxisAXY->FindBin(centerX,centerY));
            axisB += mapaxisBXY->GetBinContent(mapaxisBXY->FindBin(centerX,centerY));

            fh_A->Fill(axisA);
            fh_B->Fill(axisB);
        } //iRing
    }//iEvent


  //  gStyle->SetOptStat(0);
    c3 = new TCanvas("c3","c3",10,10,600,600);
    c3->Divide(2,2);
    c3->cd(1);
    fh_Abefore->Scale(1./fh_Abefore->Integral());
    fh_Abefore->SetMaximum(fh_Abefore->GetMaximum()*1.3);
    fh_Abefore->Draw();
    fh_Abefore->SetAxisRange(fMinAaxis, fMaxAaxis);
    fh_Abefore->Fit("gaus");
    Double_t sigmaAb = fh_Abefore->GetFunction("gaus")->GetParameter("Sigma");
    char sigmaTxtAb[30];
    sprintf(sigmaTxtAb,"sigma = %.3f",sigmaAb);
    TText* txtAb = new TText(4.3, fh_Abefore->GetMaximum()*0.85, sigmaTxtAb);
    txtAb->SetTextSize(0.1);
    txtAb->Draw();
    gPad->SetGridx(true);
    gPad->SetGridy(true);

    c3->cd(2);
    fh_Bbefore->Scale(1./fh_Bbefore->Integral());
    fh_Bbefore->SetMaximum(fh_Bbefore->GetMaximum()*1.3);
    fh_Bbefore->Draw();
    fh_Bbefore->SetAxisRange(fMinAaxis, fMaxAaxis);
    fh_Bbefore->Fit("gaus");
    Double_t sigmaBb = fh_Bbefore->GetFunction("gaus")->GetParameter("Sigma");
    char sigmaTxtBb[30];
    sprintf(sigmaTxtBb,"sigma = %.3f",sigmaBb);
    TText* txtBb = new TText(4.3, fh_Bbefore->GetMaximum()*0.85, sigmaTxtBb);
    txtBb->SetTextSize(0.1);
    txtBb->Draw();
    gPad->SetGridx(true);
    gPad->SetGridy(true);

    c3->cd(3);
    fh_A->Scale(1./fh_A->Integral());
    fh_A->SetMaximum(fh_A->GetMaximum()*1.3);
    fh_A->SetAxisRange(fMinAaxis, fMaxAaxis);
    fh_A->Draw();
    fh_A->Fit("gaus");
    Double_t sigmaA = fh_A->GetFunction("gaus")->GetParameter("Sigma");
    char sigmaTxtA[30];
    sprintf(sigmaTxtA,"sigma = %.3f",sigmaA);
    TText* txtA = new TText(4.3, fh_A->GetMaximum()*0.85, sigmaTxtA);
    txtA->SetTextSize(0.1);
    txtA->Draw();
    gPad->SetGridx(true);
    gPad->SetGridy(true);

    c3->cd(4);
    fh_B->Scale(1./fh_B->Integral());
    fh_B->SetMaximum(fh_B->GetMaximum()*1.3);
    fh_B->SetAxisRange(fMinAaxis, fMaxAaxis);
    fh_B->Draw();
    fh_B->Fit("gaus");
    Double_t sigmaB = fh_B->GetFunction("gaus")->GetParameter("Sigma");
    char sigmaTxtB[30];
    sprintf(sigmaTxtB,"sigma = %.3f",sigmaB);
    TText* txtB = new TText(4.3, fh_B->GetMaximum()*0.85, sigmaTxtB);
    txtB->SetTextSize(0.1);
    txtB->Draw();
    gPad->SetGridx(true);
    gPad->SetGridy(true);


/// Write correction map to the file
    TFile *file = new TFile("radius_correction_map.root", "recreate");
    mapaxisAXY->Write();
    mapaxisBXY->Write();
    file->Close();

}
예제 #25
0
void ReadTree_normDet(){

  bool testrun          = 0;
  const int norder_     = 2;

  static const int ptBinMin  = 0;
  static const int ptBinMax  = nptbinsDefault-1;
  static const int etaBinMin = 0; //0;
  static const int etaBinMax = netabinsDefault-1;

  TFile * fAna;
  TTree * tree;
  double centval;
  double vtx;
  TH2D * sumw;
  TH2D * sumwqx;
  TH2D * sumwqy;
  TH2I * hMult;

  TFile * fVNDet;
  TH1D * hVNDetX_0;
  TH1D * hVNDetY_0;
  TH1D * hVNDetX_1;
  TH1D * hVNDetY_1;
  TH1D * hVNDetX_full;
  TH1D * hVNDetY_full;

  TFile * fHists;
  TDirectory * qwebye;
  TH2D * hVn2Dfull[NCENT];
  TH2D * hVn2Dsub0[NCENT];
  TH2D * hVn2Dsub1[NCENT];
  TH2D * hVn2D0v1[NCENT];
  TH1D * hVnFull[NCENT];
  TH1D * hVnSub0[NCENT];
  TH1D * hVnSub1[NCENT];
  TH1I * Mult[NCENT];
  TH2D * h2Vn2D0v1[NCENT];
  TH1D * h2Vn2D0v1Magnitude[NCENT];

  double VnRaw_x_0;
  double VnRaw_y_0;
  double VnRaw_x_1;
  double VnRaw_y_1;
  double VnRaw_x_full;
  double VnRaw_y_full;

  double sumw_0;
  double sumw_1;
  double sumw_full;

  double VnCorrected_x_0;
  double VnCorrected_y_0;
  double VnCorrected_x_1;
  double VnCorrected_y_1;
  double VnCorrected_x_full;
  double VnCorrected_y_full;

  int evtMult_0;
  int evtMult_1;
  int evtMult_full;

  //
  // MAIN
  //
  setTDRStyle();
  TH1D::SetDefaultSumw2();
  TH2D::SetDefaultSumw2();
  TH1I::SetDefaultSumw2();

  //-- Set up analyzer objects
  fAna = new TFile(fAnaTreeName);

  tree   = (TTree *) fAna->Get("ebyeana/tree");
  sumwqx = new TH2D(Form("sumwqx%i", norder_), Form("sumwqx%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumwqy = new TH2D(Form("sumwqy%i", norder_), Form("sumwqy%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumw   = new TH2D("sumw",                    "sumw",                    nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  hMult  = new TH2I("hMult",                   "hMult",                   nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);

  tree->SetBranchAddress("Cent",                    &centval);
  tree->SetBranchAddress("Vtx",                     &vtx);
  tree->SetBranchAddress("mult",                    &hMult);
  tree->SetBranchAddress(Form("sumwqx%i", norder_), &sumwqx);
  tree->SetBranchAddress(Form("sumwqy%i", norder_), &sumwqy);
  tree->SetBranchAddress("sumw",                    &sumw);

  //-- Set up VN detector objects 
  fVNDet = new TFile( Form("V%iDet.root", norder_ ) );
  hVNDetX_0    = (TH1D*) fVNDet->Get("SubEvt_0/hVNDetX_0");
  hVNDetY_0    = (TH1D*) fVNDet->Get("SubEvt_0/hVNDetY_0");
  hVNDetX_1    = (TH1D*) fVNDet->Get("SubEvt_1/hVNDetX_1");
  hVNDetY_1    = (TH1D*) fVNDet->Get("SubEvt_1/hVNDetY_1");
  hVNDetX_full = (TH1D*) fVNDet->Get("FullEvt/hVNDetX_full");
  hVNDetY_full = (TH1D*) fVNDet->Get("FullEvt/hVNDetY_full");

  //-- Setup the output objects
  fHists = new TFile("CastleEbyE.root","recreate");
  qwebye = (TDirectory*) fHists->mkdir("qwebye");

  for(int icent = 0; icent < NCENT; icent++){

    qwebye->cd();
    hVn2Dfull[icent]          = new TH2D(Form("hVn2Dfull_c%i", icent), Form("hVn2Dfull_c%i", icent), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
    hVn2Dfull[icent]->SetOption("colz");
    hVn2Dfull[icent]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs}", norder_) );
    hVn2Dfull[icent]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs}", norder_) );

    hVn2Dsub0[icent]          = new TH2D( Form("hVn2Dsub0_c%i", icent), Form("hVn2Dsub0_c%i", icent), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
    hVn2Dsub0[icent]->SetOption("colz");
    hVn2Dsub0[icent]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,a}", norder_) );
    hVn2Dsub0[icent]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,a}", norder_) );

    hVn2Dsub1[icent]          = new TH2D( Form("hVn2Dsub1_c%i", icent), Form("hVn2Dsub1_c%i", icent), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
    hVn2Dsub1[icent]->SetOption("colz");
    hVn2Dsub1[icent]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,b}", norder_) );
    hVn2Dsub1[icent]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,b}", norder_) );

    hVn2D0v1[icent]           = new TH2D( Form("hVn2D0v1_c%i", icent), Form("hVn2D0v1_c%i", icent), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
    hVn2D0v1[icent]->SetOption("colz");
    hVn2D0v1[icent]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b}", norder_, norder_) );
    hVn2D0v1[icent]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,a} - v_{%i,y}^{obs,b}", norder_, norder_) );

    hVnFull[icent]            = new TH1D( Form("hVnFull_c%i", icent), Form("hVnFull_c%i", icent), NBins, 0., vnMax[norder_] );
    hVnFull[icent]->GetXaxis()->SetTitle( Form("v_{%i}", norder_) );
    hVnFull[icent]->GetYaxis()->SetTitle( "Events" );

    hVnSub0[icent]            = new TH1D( Form("hVnSub0_c%i", icent), Form("hVnSub0_c%i", icent), NBins, 0., vnMax[norder_] );
    hVnSub0[icent]->GetXaxis()->SetTitle( Form("v_{%i}^{obs,a}", norder_) );

    hVnSub1[icent]            = new TH1D( Form("hVnSub1_c%i", icent), Form("hVnSub1_c%i", icent), NBins, 0., vnMax[norder_] );
    hVnSub1[icent]->GetXaxis()->SetTitle( Form("v_{%i}^{obs,b}", norder_) );
    
    Mult[icent]               = new TH1I( Form("Mult_c%i", icent), Form("Mult_c%i", icent), 250, 1, 10000 );
    Mult[icent]->GetXaxis()->SetTitle("Multiplicity");
	
    h2Vn2D0v1[icent]          = new TH2D( Form("h2Vn2D0v1_c%i", icent), Form("h2Vn2D0v1_c%i", icent), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
    h2Vn2D0v1[icent]->GetXaxis()->SetTitle( Form("(v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b})/2", norder_, norder_) );
    h2Vn2D0v1[icent]->GetYaxis()->SetTitle( Form("(v_{%i,y}^{obs,a} - v_{%i,y}^{obs,b})/2", norder_, norder_) );
    h2Vn2D0v1[icent]->SetOption("colz");

    h2Vn2D0v1Magnitude[icent] = new TH1D( Form("h2Vn2D0v1Magnitude_c%i", icent), Form("h2Vn2D0v1Magnitude_c%i", icent), NBins, 0., vnMax[norder_] );
    h2Vn2D0v1Magnitude[icent]->GetXaxis()->SetTitle( Form("|(v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b})/2|", norder_, norder_) );

  }
    
  //
  // Tree Loop
  //
    
  cout<<"Begin FINAL loop, contains "<<tree->GetEntries()<<" Events"<<endl;
    
  int N;
  if( testrun ) N = 10000;
  else          N = tree->GetEntries();

  for(int ievent = 0; ievent < N; ievent++) {
        
    if((ievent+1)% 500000 == 0) cout<<"Processing Event "<<ievent+1<<"\t"<<100.*(ievent+1)/(double)N<<"% Completed"<<endl;
      
    tree->GetEntry(ievent);

    //-- Vertex Cut
    if(TMath::Abs(vtx) < 3.0 || TMath::Abs(vtx) > 15.0) continue;

    //-- Calculate centbin
    if( centval > cent_max[NCENT-1]) continue;
    int icent = hCentBins.FindBin(centval)-1;

    //-- Reset raw and sumw values
    VnRaw_x_0    = 0;
    VnRaw_y_0    = 0;
    VnRaw_x_1    = 0;
    VnRaw_y_1    = 0;
    VnRaw_x_full = 0;
    VnRaw_y_full = 0;                

    sumw_0       = 0;
    sumw_1       = 0;
    sumw_full    = 0;

    evtMult_0    = 0;
    evtMult_1    = 0;
    evtMult_full = 0;

    //-- Begin analyzer histogram loops
    for(int ipt = ptBinMin; ipt <= ptBinMax; ipt++){
      for(int ieta = etaBinMin; ieta <= etaBinMax; ieta++){

	if(sumw->GetBinContent(ipt+1,ieta+1) !=0){

	  //-- Subevent 0 (eta >= 0)
	  if(etabinsDefault[ieta] >= 0){
	    VnRaw_x_0     += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VnRaw_y_0     += sumwqy->GetBinContent(ipt+1,ieta+1);
	    sumw_0        += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_0     += hMult->GetBinContent(ipt+1,ieta+1);
	  }
	  //-- Subevent 1 (eta < 0)
	  else{
	    VnRaw_x_1     += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VnRaw_y_1     += sumwqy->GetBinContent(ipt+1,ieta+1);
	    sumw_1        += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_1     += hMult->GetBinContent(ipt+1,ieta+1);
	  }
	  //-- Full Event
	  VnRaw_x_full    += sumwqx->GetBinContent(ipt+1,ieta+1);
	  VnRaw_y_full    += sumwqy->GetBinContent(ipt+1,ieta+1);
	  sumw_full       += sumw->GetBinContent(ipt+1,ieta+1);
	  evtMult_full    += hMult->GetBinContent(ipt+1,ieta+1);

	}

      } //-- End eta loop
    } //-- End pt loop

    //-- Fill Histograms, only use events that have at least two tracks in each SE
    if(sumw_0 == 0 || sumw_1 == 0 || evtMult_1 < 2 || evtMult_full < 2) continue;

    VnRaw_x_full /= sumw_full;
    VnRaw_y_full /= sumw_full;
    
    VnRaw_x_0 /= sumw_0;
    VnRaw_y_0 /= sumw_0;
	
    VnRaw_x_1 /= sumw_1;
    VnRaw_y_1 /= sumw_1;
                
    //-- Full Tracker
    VnCorrected_x_full = VnRaw_x_full - hVNDetX_full->GetBinContent(icent+1);
    VnCorrected_y_full = VnRaw_y_full - hVNDetY_full->GetBinContent(icent+1);
    double vn_full     = TMath::Sqrt( VnCorrected_x_full * VnCorrected_x_full +  VnCorrected_y_full * VnCorrected_y_full);

    hVnFull[icent]   -> Fill( vn_full );
    hVn2Dfull[icent] -> Fill(VnCorrected_x_full, VnCorrected_y_full);

    Mult[icent]->Fill(evtMult_full);

    //-- SubEvt 0 (Eta > 0)
    VnCorrected_x_0 = VnRaw_x_0 - hVNDetX_0->GetBinContent(icent+1);
    VnCorrected_y_0 = VnRaw_y_0 - hVNDetY_0->GetBinContent(icent+1);
    double vn_0     = TMath::Sqrt( VnCorrected_x_0 * VnCorrected_x_0 + VnCorrected_y_0 * VnCorrected_y_0 );

    hVnSub0[icent]   -> Fill( vn_0 );
    hVn2Dsub0[icent] -> Fill(VnCorrected_x_0, VnCorrected_y_0);
                
    //-- SubEvt 1 (Eta < 0)
    VnCorrected_x_1 = VnRaw_x_1 - hVNDetX_1->GetBinContent(icent+1);
    VnCorrected_y_1 = VnRaw_y_1 - hVNDetY_1->GetBinContent(icent+1);
    double vn_1     = TMath::Sqrt( VnCorrected_x_1 * VnCorrected_x_1 + VnCorrected_y_1 *VnCorrected_y_1 );

    hVnSub1[icent]   -> Fill( vn_1 );
    hVn2Dsub1[icent] -> Fill(VnCorrected_x_1, VnCorrected_y_1);

    //-- SubEvt Difference
    double vn0m1_x = VnCorrected_x_0 - VnCorrected_x_1;
    double vn0m1_y = VnCorrected_y_0 - VnCorrected_y_1;
    hVn2D0v1[icent]->Fill(vn0m1_x, vn0m1_y);	

    //-- SubEvt Difference for DD response
    double vn0m1_x2 = (VnCorrected_x_0 - VnCorrected_x_1) / 2.;
    double vn0m1_y2 = (VnCorrected_y_0 - VnCorrected_y_1) / 2.;
    h2Vn2D0v1[icent]->Fill(vn0m1_x2, vn0m1_y2);

    double vn0m12 = TMath::Sqrt( pow(vn0m1_x2, 2) + pow(vn0m1_y2, 2) );
    h2Vn2D0v1Magnitude[icent]->Fill(vn0m12);

  } //-- End Event loop

  cout<<"End FINAL loop!"<<endl;
        
  fHists->Write();
  cout<<"File written, process completed"<<endl;
   
}
예제 #26
0
void chipSummary(const char *dirName, int chipId)
{
        directory = TString(dirName);
	
	if (f && f->IsOpen()) f->Close();
	if (f1 && f1->IsOpen()) f1->Close();
	if (g && g->IsOpen()) g->Close();

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

	gStyle->SetStatFont(132);
	gStyle->SetTextFont(132);
	gStyle->SetLabelFont(132, "X");
	gStyle->SetLabelFont(132, "Y");
	gStyle->SetLabelSize(0.08, "X");
	gStyle->SetLabelSize(0.08, "Y");
	gStyle->SetNdivisions(6, "X");
	gStyle->SetNdivisions(8, "Y");
	gStyle->SetTitleFont(132);

	gROOT->ForceStyle();

	tl = new TLatex;
	tl->SetNDC(kTRUE);
	tl->SetTextSize(0.09);

	ts = new TLatex;
	ts->SetNDC(kTRUE);
	ts->SetTextSize(0.08);

	line = new TLine;
	line->SetLineColor(kRed);
	line->SetLineStyle(kSolid);
	
	box = new TBox;
	box->SetFillColor(kRed);
	box->SetFillStyle(3002);

	f = new TFile(Form("%s/%s", dirName, fileName), "READ");
	
	if (strcmp(fileName, adFileName) == 0) f1 = f;
	else f1 = new TFile(Form("%s/%s", dirName, adFileName), "READ");
	
	if (strcmp(fileName, trimFileName) == 0) g = f;
	else g = new TFile(Form("%s/%s", dirName, trimFileName), "READ");
 
	sprintf(fname, "%s/../../macros/criteria-full.dat", dirName);
	if ( !readCriteria(fname) ) { 
	  
	  printf("\nchipSummary> ----> COULD NOT READ GRADING CRITERIA !!!");
	  printf("chipSummary> ----> Aborting execution of chipgSummaryPage.C ... \n\n", fileName, dirName);  
	  break;
	}

	TH1D *h1;
	TH2D *h2;

	c1 = new TCanvas("c1", "", 800, 800);
	c1->Clear();
	c1->Divide(4,4, 0.01, 0.04);

  //	shrinkPad(0.1, 0.1, 0.1, 0.3);

	FILE *sCurveFile, *phLinearFile, *phTanhFile;

        TString noslash(dirName);
        noslash.ReplaceAll("/", " ");
        noslash.ReplaceAll(".. ", "");
	
	char string[200];
	int pixel_alive;

	int nDeadPixel(0);
	int nIneffPixel(0);
	int nMaskDefect(0);
	int nNoisy1Pixel(0);
	int nDeadBumps(0);
	int nDeadTrimbits(0);
	int nAddressProblems(0);

	int nNoisy2Pixel(0);
	int nThrDefect(0);
	int nGainDefect(0);
	int nPedDefect(0);
	int nPar1Defect(0);

	int nRootFileProblems(0);

	int nDoubleFunctCounts(0);
	int nDoublePerfCounts(0);
	int nDoubleCounts(0);
	int nDoubleTrims(0);
	int nDoublePHs(0);

        int vcal = dac_findParameter(dirName, "Vcal", chipId);
	
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Row 1
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	// -- Dead pixels
	c1->cd(1);

	TH2D *hpm;
	hpm = (TH2D*)f->Get(Form("PixelMap_C%i", chipId));

        if (hpm) {

	  for (int icol = 0; icol < 52; ++icol) {
	    for (int irow = 0; irow < 80; ++irow) {      
	      
	      hpm->SetTitle("");
	      hpm->Draw("colz");
	      tl->DrawLatex(0.1, 0.92, "Pixel Map");
	    }
	  }

	} else { 
	  
	  ++nRootFileProblems; 
	}


	// -- sCurve width and noise level
	TH1D *hw = new TH1D("hw", "", 100, 0., 600.);
	TH1D *hd = new TH1D("hd", "", 100, 0., 600.);  // Noise in unbonded pixel (not displayed)
	TH2D *ht = new TH2D("ht", "", 52, 0., 52., 80, 0., 80.);
	TH1D *htmp;

	float mN(0.), sN(0.), nN(0.), nN_entries(0.);
	int over(0), under(0);

	double htmax(255.), htmin(0.);
	
	float thr, sig;
	int a,b;

	double minThrDiff(-5.);
	double maxThrDiff(5.);

	h2 = (TH2D*)f->Get(Form("vcals_xtalk_C%i", chipId));
        
	sprintf(string, "%s/SCurve_C%i.dat", dirName, chipId);
	sCurveFile = fopen(string, "r");

	if (!sCurveFile) {

	  printf("chipSummary> !!!!!!!!!  ----> SCurve: Could not open file %s to read fit results\n", string);
	
	} else {
	  
	  for (int i = 0; i < 2; i++) fgets(string, 200, sCurveFile);
	  
	  for (int icol = 0; icol < 52; ++icol)	{
	    for (int irow = 0; irow < 80; ++irow) {
	      
	      fscanf(sCurveFile, "%e %e %s %2i %2i", &thr, &sig, string, &a, &b);
	      //  				printf("chipSummary> sig %e thr %e\n", sig, thr);
	      
	      hw->Fill(sig);
	      thr = thr / 65.;
	      
	      ht->SetBinContent(icol+1, irow+1, thr); 
	      
	      if ( h2 ) {
		if( h2->GetBinContent(icol+1, irow+1)  >= minThrDiff) {
		  
		  hd->Fill(sig);
		}
	      }
	    }
	  }
	  
	  fclose(sCurveFile);

	  c1->cd(2);
	  hw->Draw();
	  tl->DrawLatex(0.1, 0.92, "S-Curve widths: Noise (e^{-})");
	  
	  
	  /*		c1->cd(15);
			hd->SetLineColor(kRed);
			hd->Draw();
			tl->DrawLatex(0.1, 0.92, "S-Curve widths of dead bumps");
			if ( hd->GetEntries() > 0 ) {
			ts->DrawLatex(0.55, 0.82, Form("entries: %4.0f", hd->GetEntries()));
			ts->DrawLatex(0.55, 0.74, Form("#mu:%4.2f", hd->GetMean()));
			ts->DrawLatex(0.55, 0.66, Form("#sigma: %4.2f", hd->GetRMS()));
			}
	  */
	  
	  mN =  hw->GetMean();
	  sN =  hw->GetRMS();
	  nN =  hw->Integral(hw->GetXaxis()->GetFirst(), hw->GetXaxis()->GetLast());
	  nN_entries =  hw->GetEntries();
	  
	  under = hw->GetBinContent(0);
	  over  = hw->GetBinContent(hw->GetNbinsX()+1);
	  
	  
	  ts->DrawLatex(0.65, 0.82, Form("N: %4.0f", nN));
	  ts->DrawLatex(0.65, 0.74, Form("#mu: %4.1f", mN));
	  ts->DrawLatex(0.65, 0.66, Form("#sigma: %4.1f", sN));
	  
	  if ( under ) ts->DrawLatex(0.15, 0.55, Form("<= %i", under));			               
	  if ( over  ) ts->DrawLatex(0.75, 0.55, Form("%i =>", over ));
	  
	  c1->cd(3);
	  if ( ht->GetMaximum() < htmax ) { 
	    htmax = ht->GetMaximum();
	  }
	  if ( ht->GetMinimum() > htmin ) {
	    htmin = ht->GetMinimum();
	  }
	  ht->GetZaxis()->SetRangeUser(htmin,htmax);
	  ht->Draw("colz");
	  tl->DrawLatex(0.1, 0.92, "Vcal Threshold Untrimmed");
	  
	}
	
	// -- Noise level map
	c1->cd(4);
        gPad->SetLogy(1);
 	gStyle->SetOptStat(1);

	float mV(0.), sV(0.), nV(0.), nV_entries(0.);
	over = 0.; under = 0.;

	if (!g->IsZombie())
	{
	      h1 = (TH1D*)g->Get(Form("VcalThresholdMap_C%iDistribution;7", chipId));
              if (h1) {
		h1->SetTitle("");
		h1->SetAxisRange(0., 100.);
		h1->Draw();

		mV = h1->GetMean();
		sV = h1->GetRMS();
		nV = h1->Integral(h1->GetXaxis()->GetFirst(), h1->GetXaxis()->GetLast());
		nV_entries = h1->GetEntries();

		under = h1->GetBinContent(0);
		over  = h1->GetBinContent(h1->GetNbinsX()+1);
              }
              else {

	        ++nRootFileProblems;
		mV = 0.;
		sV = 0.;
               
              }

	      ts->DrawLatex(0.15, 0.82, Form("N: %4.0f", nV));
	      ts->DrawLatex(0.15, 0.74, Form("#mu: %4.1f", mV));
	      ts->DrawLatex(0.15, 0.66, Form("#sigma: %4.1f", sV));
	      
	      if ( under ) ts->DrawLatex(0.15, 0.55, Form("<= %i", under));			               
	      if ( over  ) ts->DrawLatex(0.75, 0.55, Form("%i =>", over ));
	}

	tl->DrawLatex(0.1, 0.92, "Vcal Threshold Trimmed");

	
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Row 2
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	// -- Bump Map
	TH2D *hbm;

	c1->cd(5);
	gStyle->SetOptStat(0);
	hbm = (TH2D*)f->Get(Form("vcals_xtalk_C%i", chipId));
        
        if (hbm) {

	  h2->SetTitle("");
	  h2->GetZaxis()->SetRangeUser(minThrDiff, maxThrDiff);
	  h2->Draw("colz");
	  tl->DrawLatex(0.1, 0.92, "Bump Bonding Problems");
	}

	else { ++nRootFileProblems; }

	// -- Bump Map
	c1->cd(6);  
	gPad->SetLogy(1);
	//gStyle->SetOptStat(1);
	h1 = (TH1D*)f->Get(Form("vcals_xtalk_C%iDistribution", chipId));

        if (h1) {
  	  h1->SetTitle("");
	  h1->GetXaxis()->SetRangeUser(-50., 50.);
	  h1->GetYaxis()->SetRangeUser(0.5, 5.0*h1->GetMaximum());
	  h1->DrawCopy();
	  tl->DrawLatex(0.1, 0.92, "Bump Bonding");
	
	} else { 
	  
	  ++nRootFileProblems; 
	}
	
	// -- Trim bits
	int trimbitbins(3);
	c1->cd(7); 
	gPad->SetLogy(1);
	h1 = (TH1D*)f->Get(Form("TrimBit14_C%i", chipId));
	if (h1) {
	  h1->SetTitle("");
	  h1->SetAxisRange(0., 60.);
	  h1->SetMinimum(0.5);
	  h1->Draw("");
	  tl->DrawLatex(0.1, 0.92, "Trim Bit Test");          
	}
	else { ++nRootFileProblems; }

	h1 = (TH1D*)f->Get(Form("TrimBit13_C%i", chipId));
	if (h1) {
	  h1->SetLineColor(kRed);
	  h1->Draw("same");
	}
	else { ++nRootFileProblems; }

	h1 = (TH1D*)f->Get(Form("TrimBit11_C%i", chipId));
	if (h1) {
	  h1->SetLineColor(kBlue);
	  h1->Draw("same");
	}
	else { ++nRootFileProblems; }

	h1 = (TH1D*)f->Get(Form("TrimBit7_C%i", chipId));
	if (h1) {
	  h1->SetLineColor(kGreen);
	  h1->Draw("same");
	}	
	else { ++nRootFileProblems; }
	
	// -- For numerics and titels see at end


	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Row 3
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	// -- Address decoding	
	// --------------------

	TH2D *ham;
	ham = (TH2D*)f1->Get(Form("AddressDecoding_C%i", chipId));

	c1->cd(9);
	gStyle->SetOptStat(0);
        if (ham) {

	  ham->SetTitle("");
	  ham->Draw("colz");
	  tl->DrawLatex(0.1, 0.92, "Address decoding");
	}

	else { ++nRootFileProblems; }

	// -- Address levels

	c1->cd(10); 
	gPad->SetLogy(1);
	h1 = (TH1D*)f1->Get(Form("AddressLevels_C%i", chipId));
        if (h1) {
	  h1->SetTitle("");
	  h1->SetAxisRange(-1500., 1500.);
	  h1->Draw();
	  tl->DrawLatex(0.1, 0.92, "Address Levels");
	
	} else { 
	  
	  ++nRootFileProblems; 
	}


	// -- PHCalibration: Linear Fit (Gain & Pedesdtal)
	// -----------------------------------------------

	TH1D *hg = new TH1D("hg", "", 300, -2.0, 5.5);
	TH2D *hgm = new TH2D("hgm", "", 52, 0., 52., 80, 0., 80.);
	
	TH1D *hp = new TH1D("hp", "", 900, -300., 600.);
	hp->StatOverflows(kTRUE);

	TH1D *rp = new TH1D("rp", "", 900, -300., 600.);
	rp->StatOverflows(kFALSE);

	TH1D *htmp;

	float par0, par1, par2, par3, par4, par5; // Parameters of Vcal vs. Pulse Height Fit

	float mG(0.), sG(0.), nG(0.), nG_entries(0.);
	float mP(0.), sP(0.), nP(0.), nP_entries(0.); 
	over = 0.; under = 0.;

	float ped, gain;
	int a,b;
	
	int mPbin(0), xlow(-100), xup(255), extra(0);       // for restricted RMS
	float pedMin(0), pedMax(1000);
	double integral(0.);

	sprintf(string, "%s/phCalibrationFit_C%i.dat", dirName, chipId);
	phLinearFile = fopen(string, "r");

	if (!phLinearFile) {
	  
	  printf("chipSummary> !!!!!!!!!  ----> phCal: Could not open file %s to read fit results\n", string);
	
	} else {
		
	  for (int i = 0; i < 2; i++) fgets(string, 200, phLinearFile);
	  
	  for (int icol = 0; icol < 52; ++icol)	{
	    for (int irow = 0; irow < 80; ++irow) {
	      fscanf(phLinearFile, "%e %e %e %e %e %e %s %2i %2i", 
		     &par0, &par1, &par2, &par3, &par4, &par5, string, &a, &b);
	      
	      if (par2 != 0.)  {  // dead pixels have par2 == 0.
		
		gain = 1./par2;
		ped = par3;
		hp->Fill(ped);
		hg->Fill(gain);
		hgm->SetBinContent(icol + 1, irow + 1, gain);
	      }
	    }
	  }
	  
	  fclose(phLinearFile);
	  

	  // -- Gain

	  c1->cd(11);

	  mG =  hg->GetMean();
	  sG =  hg->GetRMS();
	  nG =  hg->Integral(hg->GetXaxis()->GetFirst(), hg->GetXaxis()->GetLast());
	  nG_entries = hg->GetEntries();
	  
	  under = hg->GetBinContent(0);
	  over  = hg->GetBinContent(hp->GetNbinsX()+1);
	  	  
	  gPad->SetLogy(1);
	  hg->GetYaxis()->SetRangeUser(0.5, 5.0*hg->GetMaximum());
	  hg->Draw();
	  tl->DrawLatex(0.1, 0.92, "PH Calibration: Gain (ADC/DAC)");
	  
	  if ( hg->GetMean() > 1.75 ) {

	    ts->DrawLatex(0.15, 0.80, Form("N: %4.0f", nG));
	    ts->DrawLatex(0.15, 0.72, Form("#mu: %4.2f", mG));
	    ts->DrawLatex(0.15, 0.64, Form("#sigma: %4.2f", sG));

	  } else {

	    ts->DrawLatex(0.65, 0.80, Form("N: %4.0f", nG));
	    ts->DrawLatex(0.65, 0.72, Form("#mu: %4.2f", mG));
	    ts->DrawLatex(0.65, 0.64, Form("#sigma: %4.2f", sG));
	  }
	  
	    
	  if ( under ) ts->DrawLatex(0.15, 0.55, Form("<= %i", under));			               
	  if ( over  ) ts->DrawLatex(0.75, 0.55, Form("%i =>", over ));
	  
	  c1->cd(15);

	  hgm->Draw("colz");
	  tl->DrawLatex(0.1, 0.92, "PH Calibration: Gain (ADC/DAC)");

	  // -- Pedestal

	  c1->cd(12);

	  mP =  hp->GetMean();
	  sP =  hp->GetRMS();
	  nP =  hp->Integral(hp->GetXaxis()->GetFirst(), hp->GetXaxis()->GetLast());
	  nP_entries = hp->GetEntries();
	  
	  if ( nP > 0 ) {
	    
	    // -- restricted RMS
	    integral = 0.;
	    mPbin = -1000; xlow = -1000; xup = 1000;
	    over = 0.; under = 0.;
	    
	    mPbin = hp->GetXaxis()->FindBin(mP);
	    
	    for (int i = 0; integral <  pedDistr; i++) { 
		    
	      xlow = mPbin-i;
	      xup =  mPbin+i;
	      integral = hp->Integral(xlow, xup)/nP;
		    
	    }
		  
	    extra = xup - xlow;
	  }
	  else {

	    xlow = -300; xup = 600; extra = 0;
	    over = 0.; under = 0.;
	  }

  	  under = hp->Integral(0, xlow - extra);
  	  over  = hp->Integral(xup + 1.5*extra, hp->GetNbinsX());
		  
	  hp->GetXaxis()->SetRange(xlow - extra, xup + 1.5*extra);

	  nP    = hp->Integral(hp->GetXaxis()->GetFirst(), hp->GetXaxis()->GetLast());

	  pedMin = hp->GetBinCenter(xlow-extra);
	  pedMax = hp->GetBinCenter(xup+1.5*extra);


	  cout<< " ========> Ped min  " << pedMin << " Ped max " << pedMax 
	      << ", over: " << over << " under: " << under << endl;		

	  hp->DrawCopy();

	  rp->Add(hp);
	  rp->GetXaxis()->SetRange(xlow, xup);

	  mP =  rp->GetMean();
	  sP =  rp->GetRMS();

	  // box->DrawBox( rp->GetBinCenter(xlow), 0, rp->GetBinCenter(xup), 1.05*rp->GetMaximum());
	  rp->SetFillColor(kRed);
	  rp->SetFillStyle(3002);
	  rp->Draw("same");
	  line->DrawLine(rp->GetBinCenter(xlow), 0, rp->GetBinCenter(xlow), 0.6*rp->GetMaximum());
	  line->DrawLine(rp->GetBinCenter(xup),  0, rp->GetBinCenter(xup),  0.6*rp->GetMaximum());
	 
	  tl->DrawLatex(0.1, 0.92, "PH Calibration: Pedestal (DAC)");
		
	  if ( hp->GetMean() < 126. ) {

	    ts->DrawLatex(0.65, 0.82, Form("N: %4.0f", nP));
	    ts->SetTextColor(kRed);
	    ts->DrawLatex(0.65, 0.74, Form("#mu: %4.1f", mP));
	    ts->DrawLatex(0.65, 0.66, Form("#sigma: %4.1f", sP));
				
	  } else {

	    ts->DrawLatex(0.16, 0.82, Form("N: %4.0f", nP));
	    ts->SetTextColor(kRed);
	    ts->DrawLatex(0.16, 0.74, Form("#mu: %4.1f", mP));
	    ts->DrawLatex(0.16, 0.66, Form("#sigma: %4.1f", sP));
	  }

	  if ( under ) ts->DrawLatex(0.15, 0.55, Form("<= %i", under));			               
	  if ( over  ) ts->DrawLatex(0.75, 0.55, Form("%i =>", over ));
	  ts->SetTextColor(kBlack);
	  

		
	}

	
	// -- PHCalibration: Tanh Fit (Parameter1)
	// ----------------------------------------
	
	c1->cd(11);

	over = 0.; under = 0.;

	float nPar1(0.), nPar1_entries(0.), mPar1(0.), sPar1(0.);
	
        TH1D *hPar1 = new TH1D("par1", "", 350, -1., 6.);

	sprintf(string, "%s/phCalibrationFitTan_C%i.dat", dirName, chipId);
	phTanhFile = fopen(string, "r");
	
	if (!phTanhFile) {
	  
	  printf("chipSummary> !!!!!!!!!  ----> phCal: Could not open file %s to read fit results\n", string);
	
	} else {
	  
	  for (int i = 0; i < 2; i++) fgets(string, 200, phTanhFile);
	  
	  for (int icol = 0; icol < 52; ++icol) {
	    for (int irow = 0; irow < 80; ++irow) {
	      
	      fscanf(phTanhFile, "%e %e %e %e %s %2i %2i", &par0, &par1, &par2, &par3, string, &a, &b);		
	      hPar1->Fill(par1);
	    }
	  }
	  
	  fclose(phTanhFile);	


	  // -- Parameter 1

	  hPar1->SetLineColor(kBlue);
	  hPar1->Draw("same");
	  
	  mPar1 =  hPar1->GetMean();
	  sPar1 =  hPar1->GetRMS();
	  nPar1 =  hPar1->Integral(hPar1->GetXaxis()->GetFirst(), hPar1->GetXaxis()->GetLast());	
	  nPar1_entries = hPar1->GetEntries();
	  
	  under = hPar1->GetBinContent(0);
	  over  = hPar1->GetBinContent(hPar1->GetNbinsX()+1);
	  
	  ts->SetTextColor(kBlue);
	  
	  if ( hg->GetMean() > 1.75 ) {
	  
	    ts->DrawLatex(0.15, 0.40, "Par1:");
	    ts->DrawLatex(0.15, 0.30, Form("N: %4.0f", nPar1));
	    ts->DrawLatex(0.15, 0.22, Form("#mu: %4.2f", mPar1));
	    ts->DrawLatex(0.15, 0.14, Form("#sigma: %4.2f", sPar1));
	  
	  } else {

	    ts->DrawLatex(0.65, 0.40, "Par1:");
	    ts->DrawLatex(0.65, 0.30, Form("N: %4.0f", nPar1));
	    ts->DrawLatex(0.65, 0.22, Form("#mu: %4.2f", mPar1));
	    ts->DrawLatex(0.65, 0.14, Form("#sigma: %4.2f", sPar1));
	  }
	  
	    
	  if ( under ) ts->DrawLatex(0.15, 0.48, Form("<= %i", under));			               
	  if ( over  ) ts->DrawLatex(0.75, 0.48, Form("%i =>", over ));
	  ts->SetTextColor(kBlack);
	}



	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Row 4
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	// Trim Bits
	// ----------

	TH2D *htm = new TH2D("htm", "", 80, 0., 80., 52, 0., 52.);

	c1->cd(13);
	
	gStyle->SetOptStat(0);
	h2 = (TH2D*)f->Get(Form("TrimMap_C%i;8", chipId));

        if (h2) {
	  for (int icol = 0; icol < 52; ++icol) {
	    for (int irow = 0; irow < 80; ++irow) {
	      
	      htm->SetBinContent(irow+1, icol+1, h2->GetBinContent(icol+1, irow+1));
	    }
	  }
  	  h2->SetTitle("");
	  h2->GetZaxis()->SetRangeUser(0., 16.);
	  h2->Draw("colz");
	}

	else { ++nRootFileProblems; }

	tl->DrawLatex(0.1, 0.92, "Trim Bits");


	FILE *tCalFile;
	sprintf(string, "%s/../T-calibration/TemperatureCalibration_C%i.dat", dirName, chipId);
	tCalFile = fopen(string, "r");
	char tCalDir[200];
	sprintf(tCalDir, "%s/../T-calibration", dirName);

	if ( tCalFile ) {
	
	  analyse(tCalDir, chipId);
	}
	else {

	  c1->cd(14);
	  TGraph *graph = (TGraph*)f->Get(Form("TempCalibration_C%i", chipId));
	  if ( graph ) { graph->Draw("A*"); }
	  else { ++nRootFileProblems; }
	  tl->DrawLatex(0.1, 0.92, "Temperature calibration");
	}



	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// -- Count defects and double counting
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	float fl0, fl1, fl2, fl3, fl4, fl5, tmp;
	int   i1, i2;
	char hname[200];

//  	TH2D *get = 0, *hget = 0, *htb0 = 0, *htb1 = 0, *htb2 = 0, *htb3 = 0, *htb4 = 0;

//  	for (int i = 1; i < 6; ++i) {
	  
//  	  get = (TH2D*)f->Get(Form("CalThresholdMap_C%i;%i", chipId, i));

//  	  if (get) {
//  	    hget = (TH2D*)get->Clone();
//  	    hget->SetName(Form("TB0C%i", i));

//  	    if (i == 1) htb0 = hget;
//  	    if (i == 2) htb1 = hget;
//  	    if (i == 3) htb2 = hget;
//  	    if (i == 4) htb3 = hget;
//  	    if (i == 5) htb4 = hget;

//  	  }
//  	}


 	TH2D *htb[5];
 	for (int i = 0; i < 5; ++i) {

 	  htb[i] = (TH2D*)f->Get(Form("CalThresholdMap_C%i;%i", chipId, i+1));
	  htb[i]->SetName(Form("tbC%i%i", chipId, i+1));
 	}

	TH2D *htthr = 0;
 	htthr = (TH2D*)f->Get(Form("VcalThresholdMap_C%d;8", chipId));

	sprintf(string, "%s/SCurve_C%i.dat", dirName, chipId);
	sCurveFile = fopen(string, "r");

	sprintf(string, "%s/phCalibrationFit_C%i.dat", dirName, chipId);
	phLinearFile = fopen(string, "r");
	
	sprintf(string, "%s/phCalibrationFitTan_C%i.dat", dirName, chipId);
	phTanhFile = fopen(string, "r");
	
	if (sCurveFile)   for (int i = 0; i < 2; i++) fgets(string, 200, sCurveFile);
	if (phLinearFile) for (int i = 0; i < 2; i++) fgets(string, 200, phLinearFile);
	if (phTanhFile)   for (int i = 0; i < 2; i++) fgets(string, 200, phTanhFile);

	int px_counted    = 0;
	int px_funct_counted    = 0;
	int px_perf_counted    = 0;
	int trim_counted    = 0;
	int ph_counted    = 0;
	float tb_diff = 0;
	float tb, tb0;
	    
	for (int icol = 0; icol < 52; ++icol) {
	  for (int irow = 0; irow < 80; ++irow) {
	    
	    pixel_alive   = 1;
	    px_funct_counted = 0;
	    px_perf_counted = 0;
	    px_counted = 0;

	    trim_counted = 0;
	    ph_counted = 0;
	    
	    // -- Pixel alive
	    if (hpm && hpm->GetBinContent(icol+1, irow+1)  == 0)  { 
	      
	      pixel_alive = 0; 
	      
	      ++nDeadPixel;   
	      cout << Form("chipSummary> dead pixel %3d %3d: %7.5f", 
			   icol, irow, hpm->GetBinContent(icol+1, irow+1)) << endl;
	    }

	    if (hpm && hpm->GetBinContent(icol+1,irow+1)  > 10) { ++nNoisy1Pixel; px_counted = 1; px_funct_counted = 1;}
	    if (hpm && hpm->GetBinContent(icol+1, irow+1)  < 0) { ++nMaskDefect;  px_counted = 1; px_funct_counted = 1;}

	    if (hpm && (hpm->GetBinContent(icol+1, irow+1) < 10) 
		  && (hpm->GetBinContent(icol+1, irow+1) > 0) ) { ++nIneffPixel;  px_counted = 1; px_funct_counted = 1;}
	    
	    
	    // -- Bump bonding
	    if ( pixel_alive && hbm ) {
	      if ( hbm->GetBinContent(icol+1, irow+1)  >= minThrDiff ) {

		if ( px_counted )      nDoubleCounts++;
		px_counted = 1;

		if ( px_funct_counted ) nDoubleFunctCounts++;
		px_funct_counted = 1;
		
		++nDeadBumps;	
		
		cout << Form("chipSummary> bump defect %3d %3d: %7.5f", 
			     icol, irow, hbm->GetBinContent(icol+1, irow+1)) << endl;
	      }
	    }
	    
	    
	    // -- Trim bits 1 - 4
	    if ( pixel_alive && htb[0] ) {

	      tb0 = htb[0]->GetBinContent(icol+1, irow+1);
	      
	      for ( int i = 1; i <= 4; i++ ) {

		if ( htb[i] ) {
		  
		  tb = htb[i]->GetBinContent(icol+1, irow+1);

		  tb_diff = TMath::Abs(tb-tb0);

		  if (tb_diff  <= 2) {
		    
		    if ( px_counted ) nDoubleCounts++;
		    px_counted = 1;
		    
		    if ( px_funct_counted ) nDoubleFunctCounts++;
		    px_funct_counted = 1;
		    
		    if ( trim_counted ) nDoubleTrims++;
		    trim_counted = 1;
		    
		    ++nDeadTrimbits;
		    
		    cout << Form("chipSummary> trim bit defect %3d %3d: %4.2f", icol, irow, tb_diff) << endl;
		  }
		}
	      }
	    }

	    // -- Address decoding
	    if (pixel_alive && ham) {

	      if( ham->GetBinContent(icol+1, irow+1) < 1 ) {

		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;
		    
		if ( px_funct_counted ) nDoubleFunctCounts++;
		px_funct_counted = 1;

		++nAddressProblems;

		cout << Form("chipSummary> address problem %3d %3d: %7.5f", 
			     icol, irow, ham->GetBinContent(icol+1, irow+1)) << endl;
	      }
	    }
	    
	    // -- Threshold
	    if (pixel_alive && htthr) {

	      if ( TMath::Abs(htthr->GetBinContent(icol+1, irow+1) - vcalTrim) > tthrTol ) {

		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;
		    
		if ( px_perf_counted ) nDoublePerfCounts++;
		px_perf_counted = 1;

		++nThrDefect;

		cout << Form("chipSummary> threshold problem %3d %3d: %7.5f", 
			     icol, irow, htthr->GetBinContent(icol+1, irow+1)) << endl;
	      }
	    }

	    // -- Noise
	    fscanf(sCurveFile, "%e %e %s %2i %2i", &fl1, &fl2, string, &i1, &i2);

	    if (pixel_alive) {
	      if ( (fl2 < noiseMin) 
		   || (fl2 > noiseMax) ) {
		
		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;
		    
		if ( px_perf_counted ) nDoublePerfCounts++;
		px_perf_counted = 1;
		
		++nNoisy2Pixel; 

		cout << Form("chipSummary> noise defect %3d %3d: %7.5f (%2i %2i)", 
			     icol, irow, fl2, i1, i2) << endl;
	      } 
	    }
	    
	    // -- Gain & Pedestal
	    fscanf(phLinearFile, "%e %e %e %e %e %e %s %2i %2i", 
		   &fl0, &fl1, &fl2, &fl3, &fl4, &fl5, string, &i1, &i2);

	    if (pixel_alive) {
	      
	      if (fl2 != 0) gain = 1./fl2;
	      ped = fl3;

	      if ( (gain < gainMin) || (gain > gainMax) ) {
		
		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;
		    
		if ( px_perf_counted ) nDoublePerfCounts++;
		px_perf_counted = 1;

		if ( ph_counted ) nDoublePHs++;
		ph_counted = 1;

		++nGainDefect;

		cout << Form("chipSummary> gain defect %3d %3d: %7.5f (%2i %2i)", 
			     icol, irow, gain, i1, i2) << endl;
	      }

	      if ( (ped < pedMin) 
		   || (ped > pedMax) ) {
		
		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;

		if ( px_perf_counted ) nDoublePerfCounts++;
		px_perf_counted = 1;

		if ( ph_counted ) nDoublePHs++;
		ph_counted = 1;

		++nPedDefect;

		cout << Form("chipSummary> pedestal defect %3d %3d: %7.5f (%2i %2i)", 
			     icol, irow, ped, i1, i2) << endl;
	      }
		
	      
	    }
	    

	    // -- Par1
	    fscanf(phTanhFile, "%e %e %e %e %s %2i %2i", 
		   &fl0, &fl1, &fl2, &fl3, string, &i1, &i2);
	    
	    if (pixel_alive && phTanhFile) {
	      
	      if ( (fl1 < par1Min) 
		   || (fl1 > par1Max) ) {
		
		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;

		if ( px_perf_counted ) nDoublePerfCounts++;
		px_perf_counted = 1;

		if ( ph_counted ) nDoublePHs++;
		ph_counted = 1;

		++nPar1Defect;

		cout << Form("chipSummary> par1 defect %3d %3d: %7.5f (%2i %2i)", 
			     icol, irow, par1, i1, i2) << endl;
	      }
	    }
	    
	  }
	}
			
	fclose(sCurveFile); 
	fclose(phLinearFile);
	fclose(phTanhFile);
	      

	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Numerics and Titles
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	// -- Compute the final verdict on this chip  //?? FIXME (below is pure randomness)
	float finalVerdict(0);
	if (nDeadTrimbits > 0)    finalVerdict += 1;
	if (nDeadPixel > 0)       finalVerdict += 10;
	if (nNoisy1Pixel > 0)     finalVerdict += 10;
	if (nAddressProblems > 0) finalVerdict += 10;
	if (nDeadBumps > 0)       finalVerdict += 100;
	if (nNoisy2Pixel > 0)     finalVerdict += 1000;
	if (nThrDefect > 0)       finalVerdict += 10000;
	if (nGainDefect > 0)      finalVerdict += 100000;
	if (nPedDefect > 0)       finalVerdict += 100000;
	if (nPar1Defect > 0)      finalVerdict += 100000;

	// -- Defects
	c1->cd(8);
	tl->SetTextSize(0.10);
	tl->SetTextFont(22);
	double y = 0.98;

	y -= 0.11;
	tl->DrawLatex(0.1, y, "Summary");
// 	tl->DrawLatex(0.6, y, Form("%06d", finalVerdict));

	tl->SetTextFont(132);
	tl->SetTextSize(0.09);
	y -= 0.11;
	tl->DrawLatex(0.1, y, Form("Dead Pixels: "));
	tl->DrawLatex(0.7, y, Form("%4d", nDeadPixel));

// 	y -= 0.10;
// 	tl->DrawLatex(0.1, y, Form("Noisy Pixels 1: "));
// 	tl->DrawLatex(0.7, y, Form("%4d", nNoisy1Pixel));
	
	y -= 0.10;
	tl->DrawLatex(0.1, y, "Mask defects: ");
	tl->DrawLatex(0.7, y, Form("%4d", nMaskDefect));

	y -= 0.10;
	tl->DrawLatex(0.1, y, "Dead Bumps: ");
	tl->DrawLatex(0.7, y, Form("%4d", nDeadBumps));

	y -= 0.10;
	tl->DrawLatex(0.1, y, "Dead Trimbits: ");
	tl->DrawLatex(0.7, y, Form("%4d", nDeadTrimbits));

	y -= 0.10;
	tl->DrawLatex(0.1, y, "Address Probl: ");
	tl->DrawLatex(0.7, y, Form("%4d", nAddressProblems));

	y -= 0.10;
	tl->DrawLatex(0.1, y, Form("Noisy Pixels 2: "));
	tl->DrawLatex(0.7, y, Form("%4d", nNoisy2Pixel));

	y -= 0.10;
	tl->DrawLatex(0.1, y, Form("Trim Probl.: "));
	tl->DrawLatex(0.7, y, Form("%4d", nThrDefect));

	y -= 0.10;
	tl->DrawLatex(0.1, y, Form("PH defects: "));
	tl->DrawLatex(0.5, y, Form("%4d/", nGainDefect));

	tl->SetTextColor(kRed);
	tl->DrawLatex(0.6, y, Form("%4d/",nPedDefect));
	tl->SetTextColor(kBlack);

	tl->SetTextColor(kBlue);
	tl->DrawLatex(0.7, y, Form("%4d",nPar1Defect));
	tl->SetTextColor(kBlack);

// 	y -= 0.10;
// 	tl->DrawLatex(0.1, y, Form("Par1 defect: "));
// 	tl->DrawLatex(0.7, y, Form("%4d", nPar1Defect));


	// -- Operation Parameters
	c1->cd(16);
	
	y = 0.92;
	tl->SetTextSize(0.10);
	tl->SetTextFont(22);
	y -= 0.11;
	tl->DrawLatex(0.1, y, Form("Op. Parameters"));

	tl->SetTextFont(132);
	tl->SetTextSize(0.09);

	y -= 0.11;
	int vana(-1.);
        vana = dac_findParameter(dirName, "Vana", chipId);
	tl->DrawLatex(0.1, y, "VANA: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3i DAC", vana));
	else tl->DrawLatex(0.7, y, "N/A");

	y -= 0.10;
	int caldel(-1.);
        caldel = dac_findParameter(dirName, "CalDel", chipId);
	tl->DrawLatex(0.1, y, "CALDEL: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", caldel));
	else tl->DrawLatex(0.7, y, "N/A");

	y -= 0.10;
	int vthrcomp(-1.);
        vthrcomp = dac_findParameter(dirName, "VthrComp", chipId);
	tl->DrawLatex(0.1, y, "VTHR: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", vthrcomp));
	else tl->DrawLatex(0.7, y, "N/A");

	y -= 0.10;
	int vtrim(-1.);
        vtrim = dac_findParameter(dirName, "Vtrim", chipId);
	tl->DrawLatex(0.1, y, "VTRIM: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", vtrim));
	else tl->DrawLatex(0.7, y, "N/A");
	
	y -= 0.10;
	int ibias(-1.);
        ibias = dac_findParameter(dirName, "Ibias_DAC", chipId);
	tl->DrawLatex(0.1, y, "IBIAS_DAC: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", ibias));
	else tl->DrawLatex(0.7, y, "N/A");
       
	y -= 0.10;
	int voffset(-1.);
        voffset = dac_findParameter(dirName, "VoffsetOp", chipId);
	tl->DrawLatex(0.1, y, "VOFFSETOP: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", voffset));
	else tl->DrawLatex(0.7, y, "N/A");

	// -- Page title
	c1->cd(0);
	tl->SetTextSize(0.04);
	tl->SetTextFont(22);
	tl->DrawLatex(0.02, 0.97, Form("%s (C%i)", noslash.Data(), chipId));

	TDatime date;
	tl->SetTextSize(0.02);
	tl->DrawLatex(0.75, 0.97, Form("%s", date.AsString()));

	c1->SaveAs(Form("%s/chipSummary_C%i.ps", dirName, chipId));
	c1->SaveAs(Form("%s/C%i.png", dirName, chipId));
		

	// -- Dump into logfile
	ofstream OUT(Form("%s/summary_C%i.txt", dirName, chipId));
	OUT << "nDeadPixel: "         << nDeadPixel << endl;
	OUT << "nNoisy1Pixel: "       << nNoisy1Pixel << endl;
	OUT << "nDeadTrimbits: "      << nDeadTrimbits << endl;
	OUT << "nDeadBumps: "         << nDeadBumps << endl;
	OUT << "nMaskDefect: "        << nMaskDefect << endl;
	OUT << "nAddressProblems: "   << nAddressProblems << endl;
	OUT << "nNoisy2Pixel: "       << nNoisy2Pixel << endl;
	OUT << "nTThrDefect: "        << nThrDefect << endl;
	OUT << "nGainDefect: "        << nGainDefect << endl;
	OUT << "nPedDefect: "         << nPedDefect << endl;
	OUT << "nParDefect: "         << nPar1Defect << endl;
	OUT << "nDoubleCounts: "      << nDoubleCounts << endl;
	OUT << "nDoubleFunctCounts: " << nDoubleFunctCounts << endl;
	OUT << "nDoublePerfCounts: "  << nDoublePerfCounts << endl;
	OUT << "nDoubleTrims: "       << nDoubleTrims << endl;
	OUT << "nDoublePHs: "         << nDoublePHs << endl;
        OUT << "nRootFileProblems: "  << nRootFileProblems << endl;
	OUT << "SCurve "              << nN_entries    << " " << mN << " " << sN << endl;
	OUT << "Threshold "           << nV_entries    << " " << mV  << " " << sV << endl;
	OUT << "Gain "                << nG_entries    << " " << mG << " " << sG << endl;
	OUT << "Pedestal "            << nP_entries    << " " << mP << " " << sP << endl;
	OUT << "Parameter1 "          << nPar1_entries << " " << mPar1 << " " << sPar1 << endl;
	OUT.close();
	
}
예제 #27
0
void NewCosmicstest(){
	//gROOT->Reset();	
	
	TStopwatch *clock0 = new TStopwatch();
	TFile *fout = new TFile("Cosmictest.root","RECREATE");
	bool high = 1;
	
	//Float_t z0 = 1400;
	Float_t z0 = 0;
	Float_t yTop = 600;
	Float_t xTop = 300;
	Float_t zTop = 3650;
	
	Float_t xdist = 3000;
	Float_t zdist = 9000;
	
	TH2D *StartXZ = new TH2D("xz","xz;x[cm];z[cm]",30,-(xdist/2),xdist/2,90,z0 - 4500,z0 + 4500);
	TH1D *StartTheta = new TH1D("#theta","#theta; #theta_Zenith",100,0,2);
	TH1D *StartPhi = new TH1D("#phi","#phi; #phi",50,0,7);
	TH1D *StartPHigh = new TH1D("PHigh","P; P[GeV]",100,-1,3);
	TH1D *StartP = new TH1D("P","P;P[GeV]",100,-1,3);
	TH1D *StartPLow = new TH1D("PLow","P;P[GeV]",100,-1,3);
	//TH1D *StartP = new TH1D("P","P;P[GeV]",100,0.1,1000);
	BinLogX(StartP);
	BinLogX(StartPHigh);
	BinLogX(StartPLow);
	
	TH2D *StartPTheta = new TH2D("P,Theta","P-Theta;P[GeV];#theta",150,-1,3,50,0,2);
	BinLogX(StartPTheta);
	
	TH2D *MCXZ = new TH2D("MCxz","xz;x[cm];z[cm]",30,-(xdist/2),xdist/2,90,z0 - 4500,z0 + 4500);
	TH1D *MCTheta = new TH1D("MC#theta","#theta; #theta",100,0,2);
	TH1D *MCPhi = new TH1D("MC#phi","#phi, #phi",50,0,7);
	
	TH1I *MCnTry = new TH1I("nTry","nTry",100,4.6,5);
	
	Double_t totalweightsum=0;
	Double_t px,py,pz,x,y,z,w, weighttest, weight;
	Int_t nTry,nInside,nEvent,nTest;	
	Co3Rng *fRandomEngine = new Co3Rng();
	
	int EVENTS = 400000;
	Int_t kmax = 40000;
	float weight1,weight1Low,weight1High;
	weight1Low = 123*xdist*zdist/EVENTS/10000; // expected #muons per spill/ #simulated events per spill 174*30*90/500000
	cout<<weight1Low<<endl;
	
	double I = fRandomEngine->fSpectrumH->Integral(100,1000);
	weight1High = 2*TMath::Pi()/3*I*xdist*zdist/EVENTS/10000;
		//weight2 = 900/I; // 1/(mean momentum weight), P_max-P_min/(3*0.3044/2pi)
	
	cout<< weight1High<<endl;
	Float_t weight3 = 4.833931503; // MC average of nTry/nEvents 4.833949997 +- 0.000010494			
	weight1 = 1;								
	weight = weight1 / weight3;
	
	nInside = 0; nEvent = 0; nTest = 0; weighttest = 0;
	y = 1900; //20m over beam axis

	w = weight/kmax;
	clock0->Start();
	for(Int_t k = 0;k<kmax;k++){
		cout<<k<<endl;
		nTry =0;
		for(Int_t i=0;i<EVENTS;i++){
		   Bool_t hit = 0;   
		   do{
				// shower characteristics
			   double phi = fRandomEngine->Uniform(0,2*TMath::Pi());
			   double theta = fRandomEngine->fTheta->GetRandom();
			  				  			    		 
	   	   //momentum components
				px = TMath::Sin(phi)*TMath::Sin(theta); 
				pz = TMath::Cos(phi)*TMath::Sin(theta);
				py = -TMath::Cos(theta);
				
				// start position, area 1120m^2
				x = fRandomEngine->Uniform(-xdist/2,xdist/2);
				z = fRandomEngine->Uniform(z0 - zdist/2, z0 + zdist/2);
				
				// claim for flight close to the actual detector
				if((abs(x-(y+yTop)*px/py) < xTop && abs(z-z0-(y+yTop)*pz/py) < zTop) || (abs(x-(y-yTop)*px/py) < xTop && abs(z-z0-(y-yTop)*pz/py) <  zTop)|| abs(y-(x+xTop)*py/px)<yTop && abs(z-z0-(x+xTop)*pz/px)<zTop || abs(y-(x-xTop)*py/px)<yTop && abs(z-z0-(x-xTop)*pz/px)<zTop){
					
					// muon momentum
					double P;
					//if (!high) {P = fRandomEngine->NEWstest(theta);}
					//else {P = fRandomEngine->fSpectrumH->GetRandom();}
					// high
					P = fRandomEngine->fSpectrumH->GetRandom();
					w = weight1High/weight3/kmax;
					StartP->Fill(P,w);
					StartPHigh->Fill(P,w);
					StartPTheta->Fill(P,theta,w);
					// low
					P = fRandomEngine->NEWstest(theta);
					w = weight1Low/weight3/kmax;
					StartP->Fill(P,w);
					StartPLow->Fill(P,w);
					StartPTheta->Fill(P,theta,w);
					
					
					px = px*P;
					py = py*P;
					pz = pz*P;
					
					//muon or anti-muon
					hit = 1; nInside++; 
					// StartP->Fill(P,w);
					
					w = weight1Low/weight3/kmax + weight1High/weight3/kmax;
					
					StartTheta->Fill(theta,w); // kein Weight!
					StartPhi->Fill(phi,w);	// kein Weight!	
					StartXZ->Fill(x,z,w); // kein Weight!	
					StartPTheta->Fill(P,theta,w);	
			   }
			   nTry++;
				weighttest += w;
				MCTheta->Fill(theta,w); // kein Weight!
				MCPhi->Fill(phi,w);
				MCXZ->Fill(x,z,w);
				nTest++;
			}while(!hit);
			nEvent++;
		}
		MCnTry->Fill(1.0*nTry/EVENTS);
	}
	clock0->Stop();
	
	delete fRandomEngine;
	cout<<nEvent<<" events have been generated."<<endl;
	cout<<"There is a total of "<<nInside<<"/"<<nTest<<" muons that passed close enough to the detector."<<endl;
	cout<<"Including the given weight this corresponds to ";
	cout<<kmax*weighttest/xdist/zdist*10000/123.3044<<" spills (1 spill = "<<xdist*zdist*123.3044/10000;
	cout<<" real cosmic muons = "<<EVENTS<<" simulated events)."<<endl;
   
   cout<<weighttest<<endl;
   clock0->Print();
   
   Double_t meanflux = 0;
   Int_t binsum = 0;
   for (Int_t ix = 2; ix<29;ix++){
	   for (Int_t iz = 2; iz<89;iz++){
		 	binsum++;
		   meanflux += MCXZ->GetBinContent(ix,iz);
		}
	}
	cout<< "meanflux: "<<meanflux/binsum<<"  "<< meanflux<<endl<<endl;
   printf("MCnTry: %.9f +- %.9f",MCnTry->GetMean(),MCnTry->GetMeanError());
   cout<<endl<<endl;
     
    TCanvas *c1 = new TCanvas("c1","c1",400,400);
	 c1->Divide(1,1);
	 c1->cd(1);
	 MCnTry->DrawCopy();
	
	 TCanvas *c4 = new TCanvas("c4","c4",400,400);
	 c4->Divide(1,1);
	 c4->cd(1);
	 StartPTheta->DrawCopy("SURF2");
	 gPad->SetLogx();
	
	 //TCanvas *c2 = new TCanvas("c2","c2",400,400);
	 //c2->Divide(1,1);
	 //c2->cd(1);
	 //gPad->SetLogy();
	 //wei->DrawCopy();
	
    TCanvas *c3 = new TCanvas("c3","c3",1600,800);
	 c3->Divide(4,2);
	 c3->cd(1);
	 StartXZ->DrawCopy("COLZ");
	 c3->cd(2);
	 //MCP->SetLineColor(kGreen);
	// MCP->DrawCopy();
	 //StartP->DrawCopy();
	 //TF1 *fs = new TF1("fs",NEWs,1,100,2);
	 //fs->FixParameter(0, 0);
	 //fs->FixParameter(1, 500);
	 //StartP->Add(fs,-1);
	 StartP->DrawCopy();
	 //StartP->Fit(fs,"I");
	 
	 
	// 
	 //fs->DrawCopy("SAME");
	 
	 //gPad->SetLogy();
	 gPad->SetLogx();
	 c3->cd(3);
	 MCTheta->SetLineColor(kGreen);
	 MCTheta->DrawCopy();
	 StartTheta->DrawCopy("SAME");
	 //TF1 *f1 = new TF1("f1","[0]*cos(x)*cos(x)",1.57,3.14);
	 //StartTheta->Fit(f1,"","",1.57,3.14);	
	 gPad->SetLogy(0);
	 gPad->SetLogx(0);
	 c3->cd(4);
	 MCPhi->SetLineColor(kGreen);
	 MCPhi->DrawCopy();
	 StartPhi->DrawCopy("SAME");
	//TF1 *f1 = new TF1("f1","[0]*cos(x)*cos(x)",1.57,3.14);
	//StartTheta->Fit(f1,"","",1.57,3.14);	
	 gPad->SetLogy(0);
	 gPad->SetLogx(0);
	 c3->cd(5);
	 MCXZ->DrawCopy("COLZ");
	 c3->cd(6);
	 //MCP->Divide(StartP);
	// MCP->DrawCopy();
	 gPad->SetLogy(0);
	 gPad->SetLogx(0);
	 c3->cd(7);
	 //MCTheta->Divide(StartTheta);
	 MCTheta->DrawCopy();
	 gPad->SetLogy();
	 gPad->SetLogx(0);
	 c3->cd(8);
	 //MCPhi->Divide(StartPhi);
	 MCPhi->DrawCopy();
	 gPad->SetLogy(0);
	 gPad->SetLogx(0);
	 c3->Update();
	 c3->SaveAs("Start.png");
	 
	 
	 
	 
	 StartXZ->Write();
	 StartTheta->Write();
	 StartPhi->Write();
	 StartP->Write();
	 StartPLow->Write();
	 StartPHigh->Write();
	
    StartPTheta->Write();
		
	 MCXZ->Write();
	 MCTheta->Write();
	 MCPhi->Write();
	
	 MCnTry->Write();
	 fout ->Close();
	 
	 
  
}
예제 #28
0
void mcruncorr(int filenum = 0)
{


  string buffer;
  vector<string> listoffiles;
  int nlines = 0;
  ifstream infile("/net/hisrv0001/home/dav2105/corrana/makecorrhists/franksorted.txt");

  if (!infile.is_open()) {
    cout << "Error opening file. Exiting." << endl;
    return;
  } else {
    while (!infile.eof()) {
      infile >> buffer;
      listoffiles.push_back(buffer);
      nlines++;
    }
  }

  // int filenum = 13;
  
  cout<<"opening: "<<listoffiles[filenum].data()<<endl;
  // alicecorrana("/mnt/hadoop/cms/store/user/velicanu/mergedv1_sortedforest/mergesortv1_2.root");
  mccorrana(listoffiles[filenum].data());
  
  // double leadingjetptlow[] =     {0  ,70 ,70 ,120,90 ,60 ,120,90 ,60 };
  // double leadingjetpthigh[] =    {300,90 ,300,300,300,300,300,300,300};
  // double subleadingjetptlow[] =  {70 ,0  ,50 ,50 ,50 ,50 ,50 ,50 ,50 };
  // double subleadingjetpthigh[] = {90 ,300,300,300,300,300,300,300,300};
  // double ptasslow[] = {1,1,1,2,2,2,3,3,3};
  // double ptasshigh[] = {2,2,2,3,3,3,4,4,4};
  // int centmin[] = {0,4,8,16,24};
  // int centmax[] = {4,8,16,24,28};
  
  
  
  double leadingjetptlow[] =     {0  ,70 ,0  ,70 ,0  ,70 ,90 ,90 ,90 };
  double leadingjetpthigh[] =    {300,90 ,300,90 ,300,90 ,300,300,300};
  double subleadingjetptlow[] =  {70 ,0  ,70 ,0  ,70 ,0  ,50 ,50 ,50 };
  double subleadingjetpthigh[] = {90 ,300,300,300,300,300,300,300,300};
  double ptasslow[] =            {1  ,1  ,2  ,2  ,3  ,3  ,1  ,2  ,3  };
  double ptasshigh[] =           {2  ,2  ,3  ,3  ,4  ,4  ,2  ,3  ,4  };
  int centmin[] = {0,4,8,12,16,20};
  int centmax[] = {4,8,12,16,20,24};
  TFile * outf = new TFile(Form("frank_pf3_%d.root",filenum),"recreate");
  
  for(int i = 6 ; i < 9 ; ++i)
  {
    cout<<"pt iteration "<<i<<endl;
    // for(int cent = 0 ; cent < 3 ; ++cent)
    // for(int cent = 0 ; cent < 9 ; ++cent)
    for(int cent = 0 ; cent < 6 ; ++cent)
    {
      cout<<"cent iteration "<<cent<<endl;
      TH2D * ljtsig = JetTrackSignal(0, leadingjetptlow[i], leadingjetpthigh[i] , subleadingjetptlow[i] , subleadingjetpthigh[i] , ptasslow[i] , ptasshigh[i], centmin[cent], centmax[cent]);
      TH2D * ljtbak = JetTrackBackground(0, leadingjetptlow[i], leadingjetpthigh[i] , subleadingjetptlow[i] , subleadingjetpthigh[i] , ptasslow[i] , ptasshigh[i], centmin[cent], centmax[cent]);
      TH2D * ljtcorr = (TH2D*)ljtsig->Clone(Form("corr_leadingjet%d_%d_ass%d_%d_cmin%d_cmax%d",(int)leadingjetptlow[i],(int)leadingjetpthigh[i],(int)ptasslow[i],(int)ptasshigh[i],centmin[cent],centmax[cent]));
      ljtcorr->Divide(ljtbak);
      ljtcorr->Scale(ljtbak->GetBinContent(ljtbak->FindBin(0,0)));
      ljtcorr->GetXaxis()->SetRange(ljtcorr->GetXaxis()->FindBin(-1.6),ljtcorr->GetXaxis()->FindBin(1.6));
      ljtcorr->GetYaxis()->SetRange(ljtcorr->GetYaxis()->FindBin(-3.1415926/2.0),ljtcorr->GetYaxis()->FindBin(3*3.1415926/2.0));
      
        TH2D * sljtsig = JetTrackSignal(1, leadingjetptlow[i], leadingjetpthigh[i] , subleadingjetptlow[i] , subleadingjetpthigh[i] , ptasslow[i] , ptasshigh[i], centmin[cent], centmax[cent]);
      TH2D * sljtbak = JetTrackBackground(1, leadingjetptlow[i], leadingjetpthigh[i] , subleadingjetptlow[i] , subleadingjetpthigh[i] , ptasslow[i] , ptasshigh[i], centmin[cent], centmax[cent]);
      TH2D * sljtcorr = (TH2D*)sljtsig->Clone(Form("corr_subleadingjet%d_%d_ass%d_%d_cmin%d_cmax%d",(int)leadingjetptlow[i],(int)leadingjetpthigh[i],(int)ptasslow[i],(int)ptasshigh[i],centmin[cent],centmax[cent]));
      sljtcorr->Divide(sljtbak);
      sljtcorr->Scale(sljtbak->GetBinContent(sljtbak->FindBin(0,0)));
      sljtcorr->GetXaxis()->SetRange(sljtcorr->GetXaxis()->FindBin(-1.6),sljtcorr->GetXaxis()->FindBin(1.6));
      sljtcorr->GetYaxis()->SetRange(sljtcorr->GetYaxis()->FindBin(-3.1415926/2.0),sljtcorr->GetYaxis()->FindBin(3*3.1415926/2.0));
      
      
    }
  }
  outf->Write();
  outf->Close();
}
예제 #29
0
void ROC_Occupancy() {
  gStyle->SetPalette(1);

  TH2D* l1 = new TH2D("l1","Layer 1;Modules along Z;Ladders",72, -4.5, 4.5,  42, -10.5,  10.5);
  TH2D* l2 = new TH2D("l2","Layer 2;Modules along Z;Ladders",72, -4.5, 4.5,  66, -16.5,  16.5);
  TH2D* l3 = new TH2D("l3","Layer 3;Modules along Z;Ladders",72, -4.5, 4.5,  90, -22.5,  22.5);
  TH2D* fpixI = new TH2D("fpixI","FPix Inner Shells (+x);;Blades", 72, -4.5, 4.5, 144,   0.5,  12.5);
  TH2D* fpixO = new TH2D("fpixO","FPix Outer Shells (-X);;Blades", 72, -4.5, 4.5, 144, -12.5,  -0.5);
  fpixI->GetXaxis()->SetBinLabel(1, "Disk-2 Pnl2");
  fpixI->GetXaxis()->SetBinLabel(9, "Disk-2 Pnl1");
  fpixI->GetXaxis()->SetBinLabel(19, "Disk-1 Pnl2");
  fpixI->GetXaxis()->SetBinLabel(27, "Disk-1 Pnl1");
  fpixI->GetXaxis()->SetBinLabel(41, "Disk+1 Pnl1");
  fpixI->GetXaxis()->SetBinLabel(49, "Disk+1 Pnl2");
  fpixI->GetXaxis()->SetBinLabel(59, "Disk+2 Pnl1");
  fpixI->GetXaxis()->SetBinLabel(67, "Disk+2 Pnl2");
  fpixI->GetXaxis()->LabelsOption("d");
  fpixO->GetXaxis()->SetBinLabel(1, "Disk-2 Pnl2");
  fpixO->GetXaxis()->SetBinLabel(9, "Disk-2 Pnl1");
  fpixO->GetXaxis()->SetBinLabel(19, "Disk-1 Pnl2");
  fpixO->GetXaxis()->SetBinLabel(27, "Disk-1 Pnl1");
  fpixO->GetXaxis()->SetBinLabel(41, "Disk+1 Pnl1");
  fpixO->GetXaxis()->SetBinLabel(49, "Disk+1 Pnl2");
  fpixO->GetXaxis()->SetBinLabel(59, "Disk+2 Pnl1");
  fpixO->GetXaxis()->SetBinLabel(67, "Disk+2 Pnl2");
  fpixO->GetXaxis()->LabelsOption("d");

  TreeReader tr;
  TChain *filechain = new TChain("filechain");
  filechain->Add("Ntuple.root");

  
  gROOT->SetStyle("Plain");
  gStyle->SetOptStat(0);
  TCanvas c("c","c",1200,800);
  c.Divide(3,2);

  TObjArray* files=filechain->GetListOfFiles();
  for (int nf=0; nf<files->GetEntries(); ++nf) {
    TFile* file = TFile::Open(files->At(nf)->GetTitle());
    tr.readtrees(*file);
    
    for (Long64_t i=0; i<tr.nclu(); i++) {
      tr.clu_read(i);
      Cluster clu = tr.clu();
      EventData e = tr.clu_evt();
      
      int clu_sdpx = ((clu.mod_on.disk>0) ? 1 : -1) * (2 * (abs(clu.mod_on.disk) - 1) + clu.mod_on.panel);
      // Roc BinX number for ROC map plots (clust branch)
      int clu_roc_binx = NOVAL_I;
      if (clu.mod_on.det==0) {
	for (int j=1;j<=8;j++) if (clu.y>=((8-j)*52.0)&&clu.y<((9-j)*52.0))
          clu_roc_binx = (clu.mod_on.module+4)*8 + j;
      } else if (clu.mod_on.det==1) {
        // Roc is left (0) or right (1) on the ROC map plot (+Z side)
        int binselx = (clu.mod_on.panel==1&&(clu.mod_on.module==1||clu.mod_on.module==4)) ? (clu.mod_on.module==1)
          : ((clu.mod_on.panel==1&&clu.x<80.0)||(clu.mod_on.panel==2&&clu.x>=80.0));
        // Gives the Roc location inside a panel (0 to 5 on +Z side)
        int nperpan = 2 * clu.mod_on.module + clu.mod_on.panel - 1 + binselx;
        clu_roc_binx = ((clu.mod_on.disk>0) ? nperpan : 9 - nperpan) + (clu_sdpx + 4) * 8 
          - 2 * ((abs(clu.mod_on.disk)==1) ? clu.mod_on.disk : 0);
      }
      // Roc BinY number for ROC map plots (c branch)
      int clu_roc_biny = NOVAL_I; 
      if (clu.mod_on.det==0) {
        // Roc is in bottom (0) or top bin (1) inside a ladder on th ROC map plot
        int binsely = ((clu.mod_on.half==1&&((clu.mod_on.ladder<0&&clu.mod_on.ladder%2==0)||clu.mod_on.ladder%2==1))
        	       ||(clu.mod_on.half==0&&((clu.mod_on.ladder<0 &&((clu.mod_on.ladder%2==-1&&clu.x<80.0)
        								   ||(clu.mod_on.ladder%2==0&&clu.x>=80.0)))
        					 ||(clu.mod_on.ladder>0 &&((clu.mod_on.ladder%2==0&&clu.x<80.0)
        								     ||(clu.mod_on.ladder%2==1&&clu.x>=80.0))))));
        clu_roc_biny = (clu.mod_on.layer * 6 + clu.mod_on.ladder + 4) * 2 + 1 + binsely;
      } else if (clu.mod_on.det==1) {
        // Gives the number of ROCs along ly
        int nrocly = clu.mod_on.module + clu.mod_on.panel;
        for (int j=0; j<nrocly; j++) {
          // ROC number = nrocly - 1 - j for + LX and nrocly + j for -LX.
          int k = (clu.mod_on.disk<0) ? j : nrocly - 1 - j;
          if (clu.y>=(k*52.0)&&clu.y<((k+1)*52.0))
            clu_roc_biny = 6 - nrocly + 2 * j + ((clu.mod_on.blade>0) ? clu.mod_on.blade-1 : clu.mod_on.blade + 12)*12 + 1;
        }
      }
      
      if (clu.mod_on.layer==1) l1->SetBinContent(clu_roc_binx,clu_roc_biny, l1->GetBinContent(clu_roc_binx,clu_roc_biny)+1);
      else if (clu.mod_on.layer==2) l2->SetBinContent(clu_roc_binx,clu_roc_biny, l2->GetBinContent(clu_roc_binx,clu_roc_biny)+1);
      else if (clu.mod_on.layer==3) l3->SetBinContent(clu_roc_binx,clu_roc_biny, l3->GetBinContent(clu_roc_binx,clu_roc_biny)+1);
      else if (clu.mod_on.blade>0) {
	fpixI->SetBinContent(clu_roc_binx,clu_roc_biny, fpixI->GetBinContent(clu_roc_binx,clu_roc_biny)+1);
	fpixI->SetBinContent(clu_roc_binx,clu_roc_biny+1, fpixI->GetBinContent(clu_roc_binx,clu_roc_biny+1)+1);
      } else if (clu.mod_on.blade<0) {
	fpixO->SetBinContent(clu_roc_binx,clu_roc_biny, fpixO->GetBinContent(clu_roc_binx,clu_roc_biny)+1);
	fpixO->SetBinContent(clu_roc_binx,clu_roc_biny+1, fpixO->GetBinContent(clu_roc_binx,clu_roc_biny+1)+1);
      }
	
      if (i%500000==0) {
	c.cd(1);
	l1->Draw("COLZ");
	c.cd(2);
	l2->Draw("COLZ");
	c.cd(3);
	l3->Draw("COLZ");
	c.cd(4);
	fpixI->Draw("COLZ");
	c.cd(5);
	fpixO->Draw("COLZ");
	gPad->Update();
      }
    }
	c.SaveAs("output.root");
  } std::cout<<"Done."<<std::endl;
}
예제 #30
0
void run_alt_smooth(){
  gROOT->LoadMacro("Fitter.cpp");
  TPostScript *myps = new TPostScript("upara_eff_check022008_check.ps",111);
  // mass range
  double xmin = 50., xmax = 130.;
  
  // data
  TFile *data=new TFile("result_0221.root");
  gDirectory->cd("ZCand_Hist");
  
  const Int_t NBins = 15; //2 gev upara bins
  const Int_t NBinsX = 100; //1 gev mass bins
   
  TH2D *before = (TH2D *)gROOT->FindObject("ZCandUPara_V_Mass_NoCuts");
  TH2D *after = (TH2D *)gROOT->FindObject("ZCandUPara_V_Mass_BothWithGoodSpatialMatch_IsoHMxCut");
  
  //these x bins are mass
  int rbinpt = 4;
  before->RebinX(rbinpt);

  after->RebinX(rbinpt);
 
  //y bins are upara:
  int rbinupara = 8;
  before->RebinY(rbinupara);
  after->RebinY(rbinupara);
    
  Int_t NBins_X = before->GetNbinsX();
  Double_t Axis_XMin = before->GetXaxis()->GetXmin();
  Double_t Axis_XMax = before->GetXaxis()->GetXmax();
  
  if(NBins_X != NBinsX) {
    cout<<"NBins="<<NBinsX<<" while NBins_X="<<NBins_X<<" make sure they are the same"<<endl;
    exit;
  }
  
  Int_t NBins_Y = before->GetNbinsY();
  Double_t Axis_YMin = before->GetYaxis()->GetXmin();
  Double_t Axis_YMax = before->GetYaxis()->GetXmax();
  cout<<"Mass bin "<<NBins_Y<<" from "<<Axis_YMin<<" to "<<Axis_YMax<<endl;
  
  // 1D histogram
  TH1D *before_mass[NBins], *after_mass[NBins], *diff_mass[NBins], *bkgnd_mass[NBins];
  double variable[NBins], variable_err[NBins];
  
  char name[50];
  for (int ybin = 0; ybin <NBins_Y; ybin ++){   //include underflow, but doesnt go to upper limit. 
                                                 //not really a problem because there are few events there
                                                 //and we know the correct position anyway. 
    sprintf(name, "%s%d", "before_", ybin);
    before_mass[ybin] = new TH1D(name, name, NBins_X, Axis_XMin, Axis_XMax);
    sprintf(name, "%s%d", "after_", ybin);
    after_mass[ybin] = new TH1D(name, name, NBins_X, Axis_XMin, Axis_XMax);
    sprintf(name, "%s%d", "diff_", ybin);
    diff_mass[ybin] =  new TH1D(name, name, NBins_X, Axis_XMin, Axis_XMax);
    
    variable[ybin] = before->GetYaxis()->GetBinCenter(ybin);
    variable_err[ybin] = 1.0;
    
    for(int xbin=0; xbin < NBins_X; xbin ++) {
      
      cout<<"x,y: "<<xbin<<","<<ybin<<" before "<<before->GetBinContent(xbin, ybin)<<" after "<<after->GetBinContent(xbin, ybin)<<" diff " << (before->GetBinContent(xbin, ybin) - after->GetBinContent(xbin, ybin))<< endl;
      before_mass[ybin] -> SetBinContent(xbin, before->GetBinContent(xbin, ybin));
      after_mass[ybin] -> SetBinContent(xbin, after->GetBinContent(xbin, ybin));
      diff_mass[ybin]-> SetBinContent(xbin, (before->GetBinContent(xbin, ybin) - after->GetBinContent(xbin, ybin)) );
    }
   before_mass[ybin]->Draw();
  }
  
  // signal
  TFile *mc = new TFile("signal.root");
  gDirectory->cd("smeared");

  TH2D *sig2 = (TH2D *)gROOT->FindObject("smeared_hZcandMass_V_UPara_CCCC");
  sig2->RebinY(rbinupara);  //here x is the mass, y is upara
  //sig2->RebinX(rbinpt);  //here x is the mass, y is upara
  
  Int_t NBins_X = sig2->GetNbinsX();
  Double_t Axis_XMin = sig2->GetXaxis()->GetXmin();
  Double_t Axis_XMax = sig2->GetXaxis()->GetXmax();
   
  Int_t NBins_Y = sig2->GetNbinsY();
  Double_t Axis_YMin = sig2->GetYaxis()->GetXmin();
  Double_t Axis_YMax = sig2->GetYaxis()->GetXmax();
  cout<<"upara bin "<<NBins_Y<<" from "<<Axis_YMin<<" to "<<Axis_YMax<<endl;
  
  if(NBins_Y != NBins) {
    cout<<"NBins="<<NBins<<" while NBins_Y="<<NBins_Y<<" make sure they are the same"<<endl;
    exit;
  }
   
  cout<<"NBinsx="<<NBinsX<<" while NBins_X="<<NBins_X<<" make sure they are the same"<<endl;
  NBins_X = NBinsX;
  Axis_XMin = 50.;

  // 1D histogram
  TH1D *Sig_All[NBins];
  double variable[NBins], variable_err[NBins];
  TH1D *QCDBkg_All[NBins];
  
  //now for the bkg histogram:
  TFile *data=new TFile("result_bkg.root");
  gDirectory->cd("ZCand_Hist");
  TH2D *bkgnd = (TH2D *)gROOT->FindObject("ZCandUPara_V_Mass_0");
  bkgnd->RebinX(rbinupara); //upara is x
  bkgnd->RebinY(4); //mass is y. great
  //bkgnd->Draw("colz");

  char name[50];
  for (int ybin = 0; ybin < NBins_Y; ybin ++){
    sprintf(name, "%s%d", "sig_", ybin);
    Sig_All[ybin] = new TH1D(name, name, NBins_X, Axis_XMin, Axis_XMax); //note range
    //now is consistent with wmass analysis
    
    // variable[ybin] = sig2->GetYaxis()->GetBinCenter(ybin);
    //variable_err[ybin] = 0.;
    
    for(int xbin=50; xbin < 150; xbin ++) { //now is consistent with wmass analysis
      Sig_All[ybin] -> SetBinContent(xbin-50, sig2->GetBinContent(xbin,ybin)); //note order
    }  //pmcs ranges is from 0 to 150 instead of 50 to 150
    // Sig_All[ybin] -> Draw();

    sprintf(name, "%s%d", "bkgnd_", ybin);
    QCDBkg_All[ybin] = new TH1D(name, name, NBins_X, Axis_XMin, Axis_XMax);
    sprintf(name, "%s%d", "bkgnd_orig_", ybin);
    bkgnd_mass[ybin] = new TH1D(name, name, NBins_X, Axis_XMin, Axis_XMax);
    
    for(int xbin=0; xbin < NBins_X; xbin ++) {
      bkgnd_mass[ybin] -> SetBinContent((xbin), bkgnd->GetBinContent(ybin, xbin)); //note order
    }
    bkgnd_mass[ybin]->Sumw2();
    // bkgnd_mass[ybin]->Draw("pe");
    //TF1 *func = new TF1("func","[0] + [1]*x + [2]*x*x + [3]*x*x*x + [4]*x*x*x*x + [5]*x*x*x*x*x", Axis_YMin, Axis_YMax);
    //func -> SetParameters(-28900.202091,1544.3,-31.665,0.3172,0.00000305);
    TF1 *func = new TF1("func","landau", Axis_XMin, Axis_XMax);
    if (bkgnd_mass[ybin]->Integral()>10){
      bkgnd_mass[ybin]->Fit(func,"QN");//QN
    } else {
      cout<< " not enough events for bkgnd determination "<<endl;
      func -> SetParameters(3.93055e+02,5.64712e+01,3.26891e+00); 
      //this is for the bins < 25 GeV (for now) the parameters are from the 25-26 gev bin. 
    }
    //bkgnd_mass[xbin]->Draw();
    //QCDBkg_All[xbin] = (TH1D *)Sig_All[xbin]->Clone();
    
    for(int i=1; i<=QCDBkg_All[ybin]->GetNbinsX(); i++) {
      double center = QCDBkg_All[ybin]->GetBinCenter(i);
      
      QCDBkg_All[ybin] -> SetBinContent(i, 0);
      QCDBkg_All[ybin] -> SetBinError(i, 0);
      
      if(center>xmin && center<xmax) {
	double bin_min = QCDBkg_All[ybin]->GetBinLowEdge(i);
	double bin_max = bin_min + QCDBkg_All[ybin]->GetBinWidth(i);
	
	double integral = func->Integral(bin_min, bin_max);
	QCDBkg_All[ybin] -> SetBinContent(i, integral);
	QCDBkg_All[ybin] -> SetBinError(i, TMath::Sqrt(integral));
      }
    } // for all bins
    
    QCDBkg_All[ybin]->Sumw2();
    //  QCDBkg_All[ybin]->Draw();
     //Sig_All[ybin]->Draw();  
  }
  //bkgnd->Draw("colz");
  //TH1D *Sig_All = (TH1D *)gROOT->FindObject("smeared_hZcandMass_CCCC");
  
  //
  // fitter
  //
  Fitter fitter;
  double data_entry_before[NBins], mc_entry_before[NBins], mc_entry_diff[NBins], bkg_entry_before[NBins], mc_error_before[NBins], mc_error_diff[NBins];
  double data_entry_after[NBins], mc_entry_after[NBins], bkg_entry_after[NBins], mc_error_after[NBins];
  double eff[NBins], eff_err[NBins], deff[NBins], deff_err[NBins] ,reff[NBins], reff_err[NBins];
  double chisq1[NBins], chisq2[NBins];
  
  TCanvas *ctemp;
  int npad = 1;
  cout<< " nbins upara now "<<NBins<<endl;
  for(int i=0; i<NBins; i++) {  
    int cbin = 2;
    /*before_mass[i]->Rebin(cbin);
    after_mass[i]->Rebin(cbin);
    diff_mass[i]->Rebin(cbin);
    Sig_All[i]->Rebin(cbin);
    QCDBkg_All[i]->Rebin(cbin);
    */

    if (!(i%2)) {
      myps->NewPage();
      ctemp = new TCanvas("ctemp","ctemp",600,800);
      ctemp->Divide(2,2); 
      npad = 1;
      cout<<"NEWPAGE!!!"<<endl;
    }
    cout<<"=================================Starting number "<<i<<" =============================="<<endl;
    ctemp->cd(npad); 
    // before becomes diff 
    double sb = Sig_All[i]->Integral();
    double bb = QCDBkg_All[i]->Integral();
    cout<<diff_mass[i]->Integral()<<" "<< Sig_All[i]->Integral()<<" "<<QCDBkg_All[i]->Integral()<<endl;
    if(diff_mass[i]->Integral()>1. && Sig_All[i]->Integral()>2. && QCDBkg_All[i]->Integral()>1.) {
      cout<<"b mass "<<diff_mass[i]->Integral()<<endl;
      fitter.Update(diff_mass[i], Sig_All[i], QCDBkg_All[i], xmin, xmax);
      fitter.FitMass();
      fitter.Compare(ctemp);
      fitter.GetDataSignalBkg(data_entry_before[i], mc_entry_before[i], bkg_entry_before[i], mc_error_before[i], chisq1[i]);
    } else {
      diff_mass[i]->SetTitle("no fit");
      diff_mass[i]->Draw("pe");
      //Sig_All[i]->Scale(diff_mass[i]->Integral()/Sig_All[i]->Integral());
      Sig_All[i]->SetLineColor(kRed);
      Sig_All[i]->SetTitle("no fit");
      Sig_All[i]->Draw("hist && same");
      data_entry_before[i]=0.;
      mc_entry_before[i]=0.;
      bkg_entry_before[i]=0.;
      mc_error_before[i]=0.;
      
    }
    npad++;
    ctemp->cd(npad);
    if (Sig_All[i]->Integral()>0){
      Sig_All[i]->Scale(sb/Sig_All[i]->Integral());
    }
    if(QCDBkg_All[i]->Integral()>0){
      QCDBkg_All[i]->Scale(bb/QCDBkg_All[i]->Integral());
    }
    cout<<"---------------------------------------------------------------------------------here i am"<<endl;
    cout<<after_mass[i]->Integral()<<" "<< Sig_All[i]->Integral()<<" "<<QCDBkg_All[i]->Integral()<<endl;
    if(after_mass[i]->Integral()>1. && Sig_All[i]->Integral()>2. && QCDBkg_All[i]->Integral()>1.) {
      cout<<"---------------------------------------------------------------------------------here i am 2"<<endl;
      fitter.Update(after_mass[i], Sig_All[i], QCDBkg_All[i], xmin, xmax);
      fitter.FitMass();
      //ctemp->cd(npad);
      fitter.Compare(ctemp);
      fitter.GetDataSignalBkg(data_entry_after[i], mc_entry_after[i], bkg_entry_after[i], mc_error_after[i], chisq2[i]);
    } else {
      cout<<"-----------------------------------------------------------------------------------here i am 3"<<endl;
      after_mass[i]->SetTitle("no fit");
      after_mass[i]->Draw("pe");
      //Sig_All[i]->Scale(after_mass[i]->Integral()/Sig_All[i]->Integral());
      Sig_All[i]->SetLineColor(kRed);
      Sig_All[i]->SetTitle("no fit");
      Sig_All[i]->Draw("hist && same");
      data_entry_after[i]=0.;
      mc_entry_after[i]=0.;
      bkg_entry_after[i]=0.;
      mc_error_after[i]=0.;
      
    }
    npad++;

  } // for each histogram

  // plot efficiency

 myps->NewPage();
  TCanvas *eff_canvas = new TCanvas("eff","eff",600,600);


  eff_canvas->Divide(1,1);
    eff_canvas->cd(1);

  cout<<"double cccc_mc_entry_after["<<NBins<<"]={";
  for(int i=0; i<NBins; i++) {
    cout<<mc_entry_after[i]<<",";
  }
  cout<<"}"<<endl;
  cout<<"double cccc_mc_error_after["<<NBins<<"]={";
  for(int i=0; i<NBins; i++) {
    cout<<mc_error_after[i]<<",";
  }
  cout<<"}"<<endl;
  cout<<"double cccc_mc_entry_before["<<NBins<<"]={";
  for(int i=0; i<NBins; i++) {
    cout<<mc_entry_before[i]<<",";
  }
  cout<<"}"<<endl;
  cout<<"double cccc_mc_error_before["<<NBins<<"]={";
  for(int i=0; i<NBins; i++) {
    cout<<mc_error_before[i]<<",";
  }
  cout<<"}"<<endl;
  cout<<"double variable[NBins]={";
  for(int i=0; i<NBins; i++) {
    cout<<variable[i]<<",";
  }
  cout<<"}"<<endl;
  
  for(int i=0; i<NBins; i++) {
    if(mc_entry_before[i]>1.&&  mc_entry_after[i]>1.) {  // at least >one entry
      
      eff[i] = mc_entry_after[i]/(mc_entry_before[i] + mc_entry_after[i]);
      eff_err[i] = sqrt(mc_entry_before[i]*mc_entry_before[i]*mc_error_after[i]*mc_error_after[i]+ mc_entry_after[i]*mc_entry_after[i]*mc_error_before[i]*mc_error_before[i])/(mc_entry_before[i]+mc_entry_after[i])/(mc_entry_before[i]+mc_entry_after[i]);
      cout<<"what "<<i << " b "<<mc_entry_before[i]<<" a "<<mc_entry_after[i]<<" eff i "<<eff[i]<<" err i "<<eff_err[i] << " be "<<mc_error_before[i]<<" ae "<<mc_error_after[i]<<endl;    
      
    } else {
      eff[i] = 0;
      eff_err[i] = 0.05;
    }
  }
  
  TF1 *afunc = new TF1("afunc",fitf,-15,15,3);
  afunc->SetParameters(-1.0,0.010,0.74);
  
  //  TF1 *efffit2 = new TF1("efffit2","0.5 * [2] * (1. + TMath::Erf((x-[0])/(sqrt(2)*[1])))*(1. + TMath::Erf((x-[4])/(sqrt(2)*[3])))",15,55 );
  //  efffit2->SetParameters(23.,2.0,0.4,2.0,20.);
  TGraphErrors *ge = new TGraphErrors(NBins, variable, eff, variable_err, eff_err);
  ge->GetYaxis()->SetRangeUser(0.4,0.9);
  ge->SetMarkerColor(kRed);
  ge->SetMarkerSize(2);
  ge->SetLineColor(kRed);
  ge->GetXaxis()->SetTitle("Electron U_{||} [GeV]");
  ge->GetYaxis()->SetTitle("Efficiency");
  ge->GetYaxis()->SetTitleOffset(1.4);
  ge->SetTitle("Z->ee Candidates, U_{||} Eff."); 
  
  ge->Fit("afunc","R");
  
  TF1 *apol1 = new TF1("apol1","[0] + [1]*x", -20. ,0.);
  ge -> Draw("AP");
  //  ge->Fit("apol1","R");
  // apol1->Draw("same");
  TF1 *bpol1 = new TF1("bpol1","[0] + [1]*x", 0. ,20.);
  // ge->Fit("bpol1","R");
  //bpol1->Draw("same");
  

  // eff_canvas->Update();
  
  // eff_canvas->cd(2);
  eff_canvas->SaveAs("upara_out_new.eps");


  for(int i=0; i<NBins; i++) {
    if(data_entry_before[i]>1. && data_entry_after[i]>1.) {// at least one entry
      cout<<"what 2 "<<data_entry_before[i]<<" "<<data_entry_after[i]<< " "<<i<<endl;
      deff[i] = data_entry_after[i]/(data_entry_before[i]+data_entry_after[i]);
      deff_err[i] = sqrt(data_entry_before[i]*data_entry_before[i]*mc_error_after[i]*mc_error_after[i]
			 + data_entry_after[i]*data_entry_after[i]*mc_error_before[i]*mc_error_before[i])
	/(data_entry_before[i]+data_entry_after[i])/(data_entry_before[i]+data_entry_after[i]);
      //for this you really should have plain binominal errors (no background subtraction here)
    } else {
      deff[i] = 0;
      deff_err[i] = 0.05;
    }
  }
  
  
  TGraphErrors *de = new TGraphErrors(NBins, variable, deff, variable_err, deff_err);
  de->GetYaxis()->SetRangeUser(0.4,0.9);
  de->SetMarkerColor(kBlue);
  de->SetMarkerSize(2);
  de->SetLineColor(kBlue);
  //de->Fit("efffit2","RME");
  //de -> Draw("SAME");
  
  //eff_canvas->Update();
  
  //now get full MC "answer":
  /*
  TFile *data=new TFile("/rooms/porcelain/tandeen/WMASS/output/FULL/Zee/UPARAEFF/result_MCzee_upara_1.root");
  gDirectory->cd("ZCand_Hist");
  TH1D *before2 = (TH1D *)gROOT->FindObject("ZCandUPara_NoCuts");
  TH1D *after2 = (TH1D *)gROOT->FindObject("ZCandUPara_BothWithGoodSpatialMatch_IsoHMxCut");  
  before2->Rebin(8);
  after2->Rebin(8);
  
  TGraphAsymmErrors *effb = new TGraphAsymmErrors();
  effb->BayesDivide(after2,before2,""); //"debug"
  // effb->Fit("pol1","","",0,15);
  
  effb->Draw("same");
  effb->Fit("pol1","","",-20,0);
  double thep0 = pol1->GetParameter(0);
  double thep1 = pol1->GetParameter(1);
  cout<<"p0 "<<thep0<<" p1 "<<thep0<<endl;
  effb->Fit("pol1","","",0,20);
  //TF1 *cpol1 = new TF1("cpol1","[0] + [1]*x", -20. ,0.);
  //cout<<"cpol"<<endl;
  //effb->Fit("cpol1","R");
  //cpol1->Draw("same");
  TF1 *dpol1 = new TF1("dpol1","[0] + [1]*x", -20. , 0.);
  dpol1->SetParameters(thep0,thep1);
  //cout<<"dpol"<<endl;
  //effb->Fit("dpol1","R");
  dpol1->Draw("same");

  //effb->SetTitle(ZCandUPara_BothWithGoodSpatialMatch_IsoHMxCut->GetTitle());
  //effb->GetXaxis()->SetTitle("trk deteta");
  */
  /*
  eff_canvas->cd(3);
  
  for(int i=0; i<NBins; i++) {
    if(eff[i]>0. && deff[i]>0.) {// at least one entry
      reff[i] = eff[i]/deff[i]; 
      //reff_err[i] = sqrt(data_entry_before[i]*data_entry_before[i]*mc_error_after[i]*mc_error_after[i]+ data_entry_after[i]*data_entry_after[i]*mc_error_before[i]*mc_error_before[i])/(data_entry_before[i]+data_entry_after[i])/(data_entry_before[i]+data_entry_after[i]);
    } else {
      reff[i] = 1.0;
      //reff_err[i] = 0.1;
    }
  }

  TGraphErrors *erat = new TGraphErrors(NBins, variable, reff, variable_err, eff_err);
  erat->GetXaxis()->SetRangeUser(10,70);
  erat->SetMarkerColor(kRed);
  erat->SetMarkerSize(2);
  erat->SetLineColor(kRed);
  erat -> Draw("AP");
  */


  eff_canvas->Update();

  myps->NewPage();
  TCanvas *chi_canvas = new TCanvas("eff","eff",600,800);
  

  chi_canvas->Divide(1,2);
  chi_canvas->cd(1);
  
  TGraph *chi1 = new TGraph(NBins, variable, chisq1);
  // de->GetYaxis()->SetRangeUser(0.4,0.9);
  //de->SetMarkerColor(kBlue);
  //de->SetMarkerSize(2);
  //de->SetLineColor(kBlue);
  //de->Fit("efffit2","RME");
  chi1-> Draw("A*");
   

  chi_canvas->cd(2);

  TGraph *chi2 = new TGraphErrors(NBins, variable, chisq2);
  //de->GetYaxis()->SetRangeUser(0.4,0.9);
  
  //de->SetMarkerColor(kBlue);
  //de->SetMarkerSize(2);
  //de->SetLineColor(kBlue);
  //de->Fit("efffit2","RME");
  chi2 -> Draw("A*");
  
  chi_canvas->Update();


  myps->Close();
}