void KVINDRAReconEvent::SecondaryAnalyseGroup(KVGroup* grp)
{
   // Perform identifications and calibrations of particles not included
   // in first round (methods IdentifyEvent() and CalibrateEvent()).
   //
   // Here we treat particles with GetStatus()==KVReconstructedNucleus::kStatusOKafterSub
   // after subtracting the energy losses of all previously calibrated particles in group from the
   // measured energy losses in the detectors they crossed.

   // loop over al identified & calibrated particles in group and subtract calculated
   // energy losses from all detectors
   KVINDRAReconNuc* nuc;
   TList sixparts;
   TIter parts(grp->GetParticles());
   while ((nuc = (KVINDRAReconNuc*)parts())) {
      if (nuc->IsIdentified() && nuc->IsCalibrated()) {
         nuc->SubtractEnergyFromAllDetectors();
         // reconstruct particles from pile-up in silicon detectors revealed by coherency CsIR/L - SiCsI
         if (nuc->IsSiPileup() && nuc->GetSi()->GetEnergy() > 0.1) {
            KVINDRAReconNuc* SIX = AddParticle();
            SIX->Reconstruct(nuc->GetSi());
            sixparts.Add(SIX);
         }
         // reconstruct particles from pile-up in si75 detectors revealed by coherency
         if (nuc->IsSi75Pileup()) {
            KVINDRAReconNuc* SIX = AddParticle();
            SIX->Reconstruct(nuc->GetSi75());
            sixparts.Add(SIX);
         }
         // reconstruct particles from pile-up in sili detectors revealed by coherency
         if (nuc->IsSiLiPileup()) {
            KVINDRAReconNuc* SIX = AddParticle();
            SIX->Reconstruct(nuc->GetSiLi());
            sixparts.Add(SIX);
         }

         // reconstruct particles from pile-up in ChIo detectors revealed by coherency CsIR/L - ChIoCsI
         if (nuc->IsChIoPileup() && nuc->GetChIo()->GetEnergy() > 1.0) {
            KVINDRAReconNuc* SIX = AddParticle();
            SIX->Reconstruct(nuc->GetChIo());
            sixparts.Add(SIX);
         }
      }
   }
   // reanalyse group
   KVReconstructedNucleus::AnalyseParticlesInGroup(grp);

   Int_t nident = 0; //number of particles identified in each step
   if (sixparts.GetEntries()) { // identify any particles added by coherency CsIR/L - SiCsI
      KVINDRAReconNuc* SIX;
      TIter nextsix(&sixparts);
      while ((SIX = (KVINDRAReconNuc*)nextsix())) {
         if (SIX->GetStatus() == KVReconstructedNucleus::kStatusOK) {
            SIX->Identify();
            if (SIX->IsIdentified()) {
               nident++;
               if (SIX->GetCodes().TestIDCode(kIDCode5)) SIX->SetIDCode(kIDCode7);
               else SIX->SetIDCode(kIDCode6);
               SIX->Calibrate();
               if (SIX->IsCalibrated()) SIX->SubtractEnergyFromAllDetectors();
            } else {
               // failure of ChIo-Si identification: particle stopped in ChIo ?
               // estimation of Z (minimum) from energy loss (if detector is calibrated)
               UInt_t zmin = ((KVDetector*)SIX->GetDetectorList()->Last())->FindZmin(-1., SIX->GetMassFormula());
               if (zmin) {
                  SIX->SetZ(zmin);
                  SIX->SetIsIdentified();
                  SIX->SetIDCode(kIDCode7);
                  // "Identifying" telescope is taken from list of ID telescopes
                  // to which stopping detector belongs
                  SIX->SetIdentifyingTelescope((KVIDTelescope*)SIX->GetStoppingDetector()->GetIDTelescopes()->Last());
                  SIX->Calibrate();
               }
            }
         }
      }
   }
   if (nident) { // newly-identified particles may change status of others in group
      // reanalyse group
      KVReconstructedNucleus::AnalyseParticlesInGroup(grp);
      nident = 0;
   }

   TIter parts2(grp->GetParticles()); // list may have changed if we have added particles
   // identify & calibrate any remaining particles with status=KVReconstructedNucleus::kStatusOK
   while ((nuc = (KVINDRAReconNuc*)parts2())) {
      if (!nuc->IsIdentified() && nuc->GetStatus() == KVReconstructedNucleus::kStatusOK) {
         nuc->ResetNSegDet();
         nuc->Identify();
         if (nuc->IsIdentified()) {
            nident++;
            nuc->Calibrate();
            if (nuc->IsCalibrated()) nuc->SubtractEnergyFromAllDetectors();
         }
      }
   }
   if (nident) { // newly-identified particles may change status of others in group
      // reanalyse group
      KVReconstructedNucleus::AnalyseParticlesInGroup(grp);
      nident = 0;
   }

   // any kStatusOKafterShare particles ?
   TList shareChIo;
   parts2.Reset();
   while ((nuc = (KVINDRAReconNuc*)parts2())) {
      if (!nuc->IsIdentified() && nuc->GetStatus() == KVReconstructedNucleus::kStatusOKafterShare) {
         shareChIo.Add(nuc);
      }
   }
   Int_t nshares = shareChIo.GetEntries();
   if (nshares) {
      KVChIo* theChIo = ((KVINDRAReconNuc*)shareChIo.At(0))->GetChIo();
      if (theChIo && nshares > 1) {
         // divide chio energy equally
         Double_t Eshare = theChIo->GetEnergyLoss() / nshares;
         theChIo->SetEnergyLoss(Eshare);
         // modify PG and GG of ChIo according to new energy loss
         Double_t volts = theChIo->GetVoltsFromEnergy(Eshare);
         Double_t GG = theChIo->GetCanalGGFromVolts(volts);
         Double_t PG = theChIo->GetCanalPGFromVolts(volts);
         theChIo->GetACQParam("PG")->SetData(TMath::Min(4095, (Int_t)PG));
         theChIo->GetACQParam("GG")->SetData(TMath::Min(4095, (Int_t)GG));
      }
      // now try to identify
      TIter nextSh(&shareChIo);
      while ((nuc = (KVINDRAReconNuc*)nextSh())) {
         nuc->SetNSegDet(10);
         nuc->Identify();
         if (nuc->IsIdentified()) {
            nuc->SetIDCode(kIDCode8);
            nuc->Calibrate();
         }
      }
   }

   // any remaining stopped in first stage particles ?
   parts2.Reset();
   while ((nuc = (KVINDRAReconNuc*)parts2())) {
      if (!nuc->IsIdentified() && nuc->GetStatus() == KVReconstructedNucleus::kStatusStopFirstStage) {
         // estimation of Z (minimum) from energy loss (if detector is calibrated)
         UInt_t zmin = ((KVDetector*)nuc->GetDetectorList()->Last())->FindZmin(-1., nuc->GetMassFormula());
         if (zmin) {
            nuc->SetZ(zmin);
            nuc->SetIsIdentified();
            nuc->SetIDCode(kIDCode5);
            // "Identifying" telescope is taken from list of ID telescopes
            // to which stopping detector belongs
            nuc->SetIdentifyingTelescope((KVIDTelescope*)nuc->GetStoppingDetector()->GetIDTelescopes()->Last());
            nuc->Calibrate();
         }
      }
   }
}
Example #2
0
TTree *ToyTree(TString dirname="test/dato/fitres/Hgg_Et-toys/0.01-0.00", TString fname="outProfile-scaleStep2smearing_7-Et_25-trigger-noPF-EB.root", TString opt="", int nSmooth=10){
  TString outDir=dirname; outDir.ReplaceAll("fitres","img");
  outDir="tmp/";
  //std::map<TString, TH2F *> deltaNLL_map;

  //bool smooth=false;
  //if(opt.Contains("smooth")) smooth=true;
  

  /*------------------------------ Plotto */
  TCanvas c("ctoy","c");
  
  
  TTree *toys = new TTree("toys","");
  toys->SetDirectory(0);
  Double_t constTerm_tree, constTermTrue_tree;
  Double_t alpha_tree, alphaTrue_tree;
  char catName[100]; 
  Int_t catIndex;
  toys->Branch("constTerm", &constTerm_tree, "constTerm/D");
  toys->Branch("alpha", &alpha_tree, "alpha/D");
  toys->Branch("constTermTrue", &constTermTrue_tree, "constTermTrue/D");
  toys->Branch("alphaTrue", &alphaTrue_tree, "alphaTrue/D");

  toys->Branch("catName", catName, "catName/C");
  toys->Branch("catIndex", &catIndex, "catIndex/I");
  std::map<TString, Int_t> catIndexMap;

  ///1/
  for(int itoy =2; itoy <= 50; itoy++){
    TString filename=dirname+"/"; filename+=itoy; filename+="/"+fname;
    TString fout=dirname+"/"; fout+=itoy; fout+="/";    
    TFile f_in(filename, "read");
    if(f_in.IsZombie()){
      std::cerr << "File opening error: " << filename << std::endl;
      continue; //return NULL;
    }
    //std::cout << filename << std::endl;
    TList *KeyList = f_in.GetListOfKeys();
    //std::cout << KeyList->GetEntries() << std::endl;
    for(int i =0; i <  KeyList->GetEntries(); i++){
      c.Clear();
      TKey *key = (TKey *)KeyList->At(i);
      if(TString(key->GetClassName())!="RooDataSet") continue;
      RooDataSet *dataset = (RooDataSet *) key->ReadObj();
    
      TString constTermName = dataset->GetName();
      TString alphaName=constTermName; alphaName.ReplaceAll("constTerm","alpha");
      if(constTermName.Contains("scale")) continue;
      if(constTermName.Contains("alpha")) continue;
      if(constTermName.Contains("1.4442-gold")) continue;
      TTree *tree = dataset2tree(dataset);

      TGraph *rhoGraph = GetRho(tree, alphaName, constTermName);

      rhoGraph->SaveAs(fout+"rhoGraph-"+constTermName+".root");


      TGraphErrors bestFit_ = bestFit(tree, alphaName, constTermName);
      //TString binning="(241,-0.0005,0.2405,61,-0.00025,0.03025)"; //"(40,0.00025,0.02025,61,-0.0022975,0.1401475)";
      TString binning="(241,-0.0005,0.2405,301,-0.00005,0.03005)"; 

      TH2F *hist = prof2d(tree, constTermName, alphaName, "nll", binning, true, nSmooth, opt);
      //hist->SaveAs("myhist.root");
      
      Int_t iBinX, iBinY;
      hist->GetBinWithContent2(0.0002,iBinX,iBinY,1,-1,1,-1,0.0000001);
	
      //      if(iBinX!=0 && iBinY!=0 && iBinX < 41 && iBinY < 62){
      {
	TString catName_=constTermName; catName_.ReplaceAll("constTerm_",""); catName_.ReplaceAll("-","_");
	if(catIndexMap.count(catName_)==0) catIndexMap.insert(std::pair<TString,Int_t>(catName_,catIndexMap.size()));
	catIndex=catIndexMap[catName_];	
	constTerm_tree =  hist->GetYaxis()->GetBinCenter(iBinY);
	alpha_tree = hist->GetXaxis()->GetBinCenter(iBinX);
	sprintf(catName,"%s", catName_.Data());
	bestFit_.GetPoint(0, constTermTrue_tree,alphaTrue_tree);
// 	std::cout << constTerm_tree << " " << constTermTrue_tree 
// 		  << "\t" << alpha_tree << " " << alphaTrue_tree 
// 		  << std::endl;

	if(opt.Contains("scandiff")){
	  constTermTrue_tree = getMinimumFromTree(tree, "nll",TString(constTermName).ReplaceAll("-","_"));
	} else       if(opt.Contains("scan")){
	  constTerm_tree = getMinimumFromTree(tree, "nll",TString(constTermName).ReplaceAll("-","_"));
	}
	//std::cout << iBinX << "\t" << iBinY << "\t" << constTerm_tree - getMinimumFromTree(tree, "nll",TString(constTermName).ReplaceAll("-","_")) << std::endl;
	
	toys->Fill();
//       }else{
// 	hist->SaveAs("myhist.root");
// 	exit(0);
      }

      
      delete tree;
      delete hist;
    
    }
    f_in.Close();
  }
  //toys->SaveAs("tmp/toysTree.root");
  

  return toys;
}
Example #3
0
void ContourList(){
 
   const Double_t PI = TMath::Pi(); 
    
   TCanvas* c = new TCanvas("c","Contour List",0,0,600,600);
   c->SetRightMargin(0.15);
   c->SetTopMargin(0.15);
 
   Int_t i, j, TotalConts;
    
   Int_t nZsamples   = 80;
   Int_t nPhiSamples = 80;

   Double_t HofZwavelength = 4.0;       // 4 meters 
   Double_t dZ             =  HofZwavelength/(Double_t)(nZsamples - 1);
   Double_t dPhi           = 2*PI/(Double_t)(nPhiSamples - 1);
 
   TArrayD z(nZsamples);
   TArrayD HofZ(nZsamples);
   TArrayD phi(nPhiSamples);
   TArrayD FofPhi(nPhiSamples);

   
   // Discretized Z and Phi Values
   for ( i = 0; i < nZsamples; i++) {
      z[i] = (i)*dZ - HofZwavelength/2.0;
      HofZ[i] = SawTooth(z[i], HofZwavelength);
   }

   for(Int_t i=0; i < nPhiSamples; i++){
      phi[i] = (i)*dPhi;      
      FofPhi[i] = sin(phi[i]); 
   }

   // Create Histogram
   TH2D *HistStreamFn = new TH2D("HstreamFn", 
   "#splitline{Histogram with negative and positive contents. Six contours are defined.}{It is plotted with options CONT LIST to retrieve the contours points in TGraphs}", 
   nZsamples, z[0], z[nZsamples-1], nPhiSamples, phi[0], phi[nPhiSamples-1]);
     
   // Load Histogram Data
   for (Int_t i = 0; i < nZsamples; i++) {
      for(Int_t j = 0; j < nPhiSamples; j++){
         HistStreamFn->SetBinContent(i,j, HofZ[i]*FofPhi[j]);
      } 
   }

   gStyle->SetPalette(1); 
   gStyle->SetOptStat(0);
   gStyle->SetTitleW(0.99);
   gStyle->SetTitleH(0.08);
   
   Double_t contours[6];
   contours[0] = -0.7;
   contours[1] = -0.5;
   contours[2] = -0.1;
   contours[3] =  0.1;
   contours[4] =  0.4;
   contours[5] =  0.8;
     
   HistStreamFn->SetContour(6, contours); 
 
   // Draw contours as filled regions, and Save points
   HistStreamFn->Draw("CONT Z LIST");
   c->Update(); // Needed to force the plotting and retrieve the contours in TGraphs
    
   // Get Contours
   TObjArray *conts = (TObjArray*)gROOT->GetListOfSpecials()->FindObject("contours");
   TList* contLevel = NULL;
   TGraph* curv     = NULL;    
   Int_t nGraphs    = 0;
   Int_t TotalConts = 0;
    
   
   if (conts == NULL){
      printf("*** No Contours Were Extracted!\n");
      TotalConts = 0;
      return;
   } else {
      TotalConts = conts->GetSize();
   }

   printf("TotalConts = %d\n", TotalConts);
        
   for(i = 0; i < TotalConts; i++){       
      contLevel = (TList*)conts->At(i);
      printf("Contour %d has %d Graphs\n", i, contLevel->GetSize());
      nGraphs += contLevel->GetSize();
   }
    
   nGraphs = 0;
    
   TCanvas* c1 = new TCanvas("c1","Contour List",610,0,600,600);
   c1->SetTopMargin(0.15);
   TH2F *hr = new TH2F("hr",
   "#splitline{Negative contours are returned first (highest to lowest). Positive contours are returned from}{lowest to highest. On this plot Negative contours are drawn in red and positive contours in blue.}",
   2, -2, 2, 2, 0, 6.5);

   hr->Draw();
   Double_t x0, y0, z0;
   TLatex l;
   l.SetTextSize(0.03);
   char val[20];
   
   for(i = 0; i < TotalConts; i++){       
      contLevel = (TList*)conts->At(i);
      if (i<3) z0 = contours[2-i];
      else     z0 = contours[i];
      printf("Z-Level Passed in as:  Z = %f\n", z0);

      // Get first graph from list on curves on this level
      curv = (TGraph*)contLevel->First();
      for(j = 0; j < contLevel->GetSize(); j++){
         curv->GetPoint(0, x0, y0);
         if (z0<0) curv->SetLineColor(kRed);
         if (z0>0) curv->SetLineColor(kBlue);
         nGraphs ++;
         printf("\tGraph: %d  -- %d Elements\n", nGraphs,curv->GetN());
         curv->Draw("C");
         sprintf(val,"%g",z0);
         l.DrawLatex(x0,y0,val);
         curv = (TGraph*)contLevel->After(curv); // Get Next graph 
      }
   }
   c1->Update();
   printf("\n\n\tExtracted %d Contours and %d Graphs \n", TotalConts, nGraphs );
}
Example #4
0
TProfile *extractFlowVZEROsingle(Int_t icentr,Int_t spec,Int_t arm,Bool_t isMC,Float_t pTh,Int_t addbin,const char *nameSp,Float_t detMin,Float_t detMax,Int_t chMin,Int_t chMax){
  LoadLib();

  pTh += 0.00001;

  // NUA correction currently are missing
  char name[100];
  char stringa[200];

  snprintf(name,100,"AnalysisResults.root");
  if(!fo) fo = new TFile(name);
  snprintf(name,100,"contVZEROv%i",arm);
  TList *cont = (TList *) fo->Get(name);

  cont->ls();

  Float_t xMin[5] = {icentr/*centrality bin*/,chMin/*charge*/,pTh/*prob*/,-TMath::Pi()/arm/*Psi*/,detMin/*PID mask*/};
  Float_t xMax[5] = {icentr+addbin,chMax,1.0,TMath::Pi()/arm,detMax};

  cont->ls();

  TProfile *p1 = cont->At(2);
  TProfile *p2 = cont->At(3);
  TProfile *p3 = cont->At(4);

  TH2F *hPsi2DA = cont->At(5);
  TH2F *hPsi2DC = cont->At(6);

  TH1D *hPsiA = hPsi2DA->ProjectionY("PsiA",icentr+1,icentr+addbin+1);
  TH1D *hPsiC = hPsi2DC->ProjectionY("PsiC",icentr+1,icentr+addbin+1);

  if(!fPsi) fPsi = new TF1("fPsi","pol0",-TMath::Pi()/arm,TMath::Pi()/arm);
  hPsiA->Fit(fPsi,"0");
  Float_t offsetA = fPsi->GetParameter(0);
  hPsiC->Fit(fPsi,"0");
  Float_t offsetC = fPsi->GetParameter(0);

  Int_t nbinPsi = hPsiA->GetNbinsX();

  Float_t *NUAcorrA = new Float_t[nbinPsi];
  Float_t *NUAcorrC = new Float_t[nbinPsi];

  for(Int_t i=0;i < nbinPsi;i++){
    NUAcorrA[i] = offsetA/(hPsiA->GetBinContent(i+1));
    NUAcorrC[i] = offsetC/(hPsiC->GetBinContent(i+1));
  }

  Float_t res1=0,res2=0,res3=0; 
  Float_t eres1=0,eres2=0,eres3=0; 

  for(Int_t i = icentr; i <= icentr+addbin;i++){
    if(p1->GetBinError(i+1)){
      eres1 += 1./p1->GetBinError(i+1)/p1->GetBinError(i+1);
      res1 += p1->GetBinContent(i+1)/p1->GetBinError(i+1)/p1->GetBinError(i+1);      
    }
    if(p2->GetBinError(i+1)){
      eres2 += 1./p2->GetBinError(i+1)/p2->GetBinError(i+1);
      res2 += p2->GetBinContent(i+1)/p2->GetBinError(i+1)/p2->GetBinError(i+1);      
    }
    if(p3->GetBinError(i+1)){
      eres3 += 1./p3->GetBinError(i+1)/p3->GetBinError(i+1);
      res3 += p3->GetBinContent(i+1)/p3->GetBinError(i+1)/p3->GetBinError(i+1);      
    }
  }

  res1 /= eres1;
  res2 /= eres2;
  res3 /= eres3;
  
  eres1 = sqrt(1./eres1);
  eres2 = sqrt(1./eres2);
  eres3 = sqrt(1./eres3);

  AliFlowVZEROResults *a = (AliFlowVZEROResults *) cont->At(0);
  AliFlowVZEROResults *b = (AliFlowVZEROResults *) cont->At(1);
  TProfile *pp,*pp2;
  if(kNUAcorr){ // with NUA corrections
    pp = a->GetV2reweight(spec,xMin,xMax,3,NUAcorrA);
    pp2 = b->GetV2reweight(spec,xMin,xMax,3,NUAcorrC);
  }
  else{
    pp = a->GetV2(spec,xMin,xMax);
    pp2 = b->GetV2(spec,xMin,xMax);
  }
  
  Float_t scaling = sqrt(res1*res3/res2);
  if(kVZEROrescorr){
    pp->Scale(1./scaling);
  }

  Float_t err1_2 = eres1*eres1/res1/res1/4 +
    eres2*eres2/res2/res2/4 +
    eres3*eres3/res3/res3/4;
  Float_t err2_2 = err1_2;
  err1_2 /= scaling*scaling;
  printf("resolution V0A = %f +/- %f\n",scaling,err1_2);
  scaling = sqrt(res2*res3/res1);
  err2_2 /= scaling*scaling;
  if(kVZEROrescorr){
    pp2->Scale(1./scaling);
  }
  printf("resolution V0C =%f +/- %f\n",scaling,err2_2);

  pp->SetName("V0A");
  pp2->SetName("V0C");

  if(! kCleanMemory){
    new TCanvas();  
    pp->Draw();
    pp2->Draw("SAME");
  }

  TProfile *pData = new TProfile(*pp);
  pData->Add(pp2);
  snprintf(stringa,100,"%sData",nameSp);
  pData->SetName(stringa);

  TProfile *pMc = NULL;
  
  TProfile *ppMC;
  TProfile *ppMC2;
  
  if(isMC){
    snprintf(name,100,"contVZEROmc");
    cont = (TList *) fo->Get(name);
    cont->ls();
    if(arm == 2){
      AliFlowVZEROResults *c = (AliFlowVZEROResults *) cont->At(0);
      if(! kCleanMemory) c->GetV2(spec,xMin,xMax)->Draw("SAME");
    }
    AliFlowVZEROResults *cA;
    if(fo->Get("contVZEROv2")) cA = (AliFlowVZEROResults *) cont->At(1+2*(arm==3));
    else cA = (AliFlowVZEROResults *) cont->At(0);
    AliFlowVZEROResults *cC;
    if(fo->Get("contVZEROv2")) cC = (AliFlowVZEROResults *) cont->At(2+2*(arm==3));
    else cC = (AliFlowVZEROResults *) cont->At(1);

    TProfile *p1mc = cont->At(5+3*(arm==3));
    TProfile *p2mc = cont->At(6+3*(arm==3));
    TProfile *p3mc = cont->At(7+3*(arm==3));

    Float_t resMC1=0,resMC2=0,resMC3=0; 
    Float_t eresMC1=0,eresMC2=0,eresMC3=0; 

    for(Int_t i = icentr; i <= icentr+addbin;i++){
      if(p1mc->GetBinError(i+1)){
	eresMC1 += 1./p1mc->GetBinError(i+1)/p1mc->GetBinError(i+1);
	resMC1 += p1mc->GetBinContent(i+1)/p1mc->GetBinError(i+1)/p1mc->GetBinError(i+1);      
      }
      if(p2mc->GetBinError(i+1)){
	eresMC2 += 1./p2mc->GetBinError(i+1)/p2mc->GetBinError(i+1);
	resMC2 += p2mc->GetBinContent(i+1)/p2mc->GetBinError(i+1)/p2mc->GetBinError(i+1);      
      }
      if(p3mc->GetBinError(i+1)){
	eresMC3 += 1./p3mc->GetBinError(i+1)/p3mc->GetBinError(i+1);
	resMC3 += p3mc->GetBinContent(i+1)/p3mc->GetBinError(i+1)/p3mc->GetBinError(i+1);      
      }
    }
    
    resMC1 /= eresMC1;
    resMC2 /= eresMC2;
    resMC3 /= eresMC3;
    
    eresMC1 = sqrt(1./eresMC1);
    eresMC2 = sqrt(1./eresMC2);
    eresMC3 = sqrt(1./eresMC3);

    ppMC = cA->GetV2(spec,xMin,xMax);
    ppMC2 = cC->GetV2(spec,xMin,xMax);
    
    scaling = sqrt(resMC1*resMC3/resMC2);
    ppMC->Scale(1./scaling);
  
    err1_2 = eresMC1*eresMC1/resMC1/resMC1/4 +
      eresMC2*eresMC2/resMC2/resMC2/4 +
      eresMC3*eresMC3/resMC3/resMC3/4;
    err2_2 = err1_2;
    err1_2 /= scaling*scaling;
    printf("resolution V0A (MC) = %f +/- %f\n",scaling,err1_2);
    scaling = sqrt(resMC2*resMC3/resMC1);
    err2_2 /= scaling*scaling;
    ppMC2->Scale(1./scaling);
    printf("resolution V0C (MC) =%f +/- %f\n",scaling,err2_2);

    ppMC->SetName("V0Amc");
    ppMC2->SetName("V0Cmc");

    if(! kCleanMemory){
      ppMC->Draw("SAME");
      ppMC2->Draw("SAME");
    }

    pMc = new TProfile(*ppMC);
    pMc->Add(ppMC2);
    snprintf(stringa,100,"%sMC",nameSp);
    pMc->SetName(stringa);
    pMc->SetLineColor(2);
  }

  if(! kCleanMemory){
    new TCanvas();  
    pData->Draw();
  }
  if(pMc && !kCleanMemory){
    pMc->Draw("SAME");
    TH1D *hData = pData->ProjectionX();
    TH1D *hMc = pMc->ProjectionX();
    hData->Divide(hMc);
    new TCanvas();  
    hData->Draw();
  }

  delete[] NUAcorrA;
  delete[] NUAcorrC;

  if(kCleanMemory){
    if(pp) delete pp;
    if(pp2) delete pp2;
    if(ppMC) delete ppMC;
    if(ppMC2) delete ppMC2;
  }

  delete cont;

  if(isMC) return pMc;
  return pData;
}
Example #5
0
void MakePIDqaReport(const char* inputFile, const char* outputFile="PIDqaReport.pdf", TString dirInFile = "")
{
  //
  // Make a pdf file with the efficiency report
  //

  LoadLibs();
  SetupStyle();

  TFile f(inputFile);
  if (!f.IsOpen()){
    printf("Could not open file '%s'\n",f.GetName());
    return;
  }
  
  TString listName = "PIDqa";
  if (dirInFile != "")
    listName = listName.Prepend(Form("%s/", dirInFile.Data()));
  
  printf("%s", listName.Data());
  TList *qaList = (TList*) f.Get(listName.Data());
  if (!qaList){
    printf("Could not find list '%s' in file '%s'\n",listName.Data(), f.GetName());
    return;
  }

  fCanvas=new TCanvas;

  TPDF p(outputFile);

  //
  // Invariant mass plots
  //


  //
  // Make QA info
  //

  // ITS PID
  PublishCanvas(qaList,"ITS","hNsigmaP_ITS_%s");

  // TPC PID
  TList *qaListTPC = (TList*)qaList->FindObject("TPC");
  if (qaListTPC){
    PublishCanvas(qaListTPC,"TPCBasic","hNsigmaP_TPC_Basic_%s");
    PublishCanvas(qaListTPC,"TPCV0","hNsigmaP_TPC_V0_%s");
    //   if (man->GetCurrentPeriod()=="11h"){
      //     PublishCanvas(qaListTPC,"TPC","hNsigmaP_TPC_Basic_%s_Hybrid","Hybrid");
    //     PublishCanvas(qaListTPC,"TPC","hNsigmaP_TPC_Basic_%s_OROChigh","OROChigh");
    //   }
  }
  else {
    printf("Could not find list '%s/TPC' in file '%s'\n", listName.Data(), f.GetName());
  }

  // TPC PID after 3 sigma TOF cut
  PublishCanvas(qaList,"TPC_TOF","hNsigmaP_TPC_TOF_%s");

  // TOF PID
  PublishCanvas(qaList,"TOF","hNsigmaP_TOF_%s");

  // TRD PID
  fCanvas->Divide(2,3);
  TH2 *hLikeP_TRD_3tls_electron=Get2DHistogramfromList(qaList,"TRD","hLikeP_TRD_3tls_electron");
  TH2 *hLikeP_TRD_3tls_pion=Get2DHistogramfromList(qaList,"TRD","hLikeP_TRD_3tls_pion");
  TH2 *hLikeP_TRD_4tls_electron=Get2DHistogramfromList(qaList,"TRD","hLikeP_TRD_4tls_electron");
  TH2 *hLikeP_TRD_4tls_pion=Get2DHistogramfromList(qaList,"TRD","hLikeP_TRD_4tls_pion");
  TH2 *hLikeP_TRD_5tls_electron=Get2DHistogramfromList(qaList,"TRD","hLikeP_TRD_5tls_electron");
  TH2 *hLikeP_TRD_5tls_pion=Get2DHistogramfromList(qaList,"TRD","hLikeP_TRD_5tls_pion");

  /*
   *  cTRDnsigma[countcanvas]->cd(1);
   *  TPaveText pt3TRD(.02,.02,.49,.52);
   *  pt3TRD.SetTextAlign(11);
   *  pt3TRD.SetTextSizePixels(16);
   *  pt3TRD.AddText(Form(" TRD PID QA %s.%s.%d", first.Data(), man->GetCurrentPeriod().Data(), pass));
   *  pt3TRD.Draw();
   */
  fCanvas->cd(1);
  SetupPadStyle();
  hLikeP_TRD_3tls_electron->Draw("colz");
  fCanvas->cd(2);
  SetupPadStyle();
  hLikeP_TRD_3tls_pion->Draw("colz");
  fCanvas->cd(3);
  SetupPadStyle();
  hLikeP_TRD_4tls_electron->Draw("colz");
  fCanvas->cd(4);
  SetupPadStyle();
  hLikeP_TRD_4tls_pion->Draw("colz");
  fCanvas->cd(5);
  SetupPadStyle();
  hLikeP_TRD_5tls_electron->Draw("colz");
  fCanvas->cd(6);
  SetupPadStyle();
  hLikeP_TRD_5tls_pion->Draw("colz");

  fCanvas->Update();
  fCanvas->Clear();

  // TPC Response info
  TObjArray *qaInfo=(TObjArray*)qaList->FindObject("QAinfo");
  TObjArray *tpcInfo=0x0;
  if (qaInfo && (tpcInfo=(TObjArray*)qaInfo->FindObject("TPC_info"))){
    TObjArray *tpcSplineInfo=(TObjArray*)tpcInfo->FindObject("TPC_spline_names");
    TObjArray *tpcConfigInfo=(TObjArray*)tpcInfo->FindObject("TPC_config_info");
    fCanvas->Divide(1,2);
  
    TPaveText pt(.1,.1,.9,.9,"NDC");
    pt.SetBorderSize(1);
    pt.SetFillColor(0);
    pt.SetTextSizePixels(16);

    if (tpcSplineInfo){
      for (Int_t i=0; i<tpcSplineInfo->GetEntriesFast();++i) pt.AddText(tpcSplineInfo->At(i)->GetName());
    }
    
    TPaveText pt2(.1,.1,.9,.9,"NDC");
    pt2.SetBorderSize(1);
    pt2.SetFillColor(0);
    pt2.SetTextSizePixels(16);
    if (tpcConfigInfo){
      for (Int_t i=0; i<tpcConfigInfo->GetEntriesFast();++i) pt2.AddText(tpcConfigInfo->At(i)->GetName());
    }

    fCanvas->cd(1);
    pt.Draw();
    fCanvas->cd(2);
    pt2.Draw();
    
    fCanvas->Update();
    fCanvas->Clear();
  }
  
  delete qaList;

  p.Close();
  delete fCanvas;
}
void makePlots( const char * inputA, const char * inputB, const char * option) 
{
  
  //Output path
  TString path("./paper01-plots/probs/");
  
  TString dataPxxA = TString( "EarthA" ) + TString("_") + TString( "0" ) + TString("_") + TString("Pme") +  TString("/data");
  TString dataPxxB = TString( "EarthB" ) + TString("_") + TString( "0" ) + TString("_") + TString("Pme") +  TString("/data");
  
  TList * v_Labels = new TList();
  TObjString *label;
  label = new TObjString( "Earth: Step function" );
  v_Labels->Add( label ); 
  label = new TObjString( "Earth: Realistic" );
  v_Labels->Add( label ); 
  
  TFile * f1 = new TFile(inputA);
  TFile * f2 = new TFile(inputB);
  
  f1->cd();
  TTree * PxxATreeNu = (TTree*)gDirectory->Get( dataPxxA.Data() );
    
  f2->cd();
  TTree * PxxBTreeNu = (TTree*)gDirectory->Get( dataPxxB.Data() );
  
  //Branches
  double xx = 0.0;
  double yy = 0.0;
  
  TString cname = TString("Earth") + TString("_") + TString("Pee");
  
  TGraph * ProbNu[3];
  ProbNu[0] = new TGraph();
  ProbNu[1] = new TGraph();
  
  PxxATreeNu->SetBranchAddress("Ex",&xx);
  PxxATreeNu->SetBranchAddress("Pb",&yy);
  
  Long64_t nentries = PxxATreeNu->GetEntries();
  
  for (Long64_t i=0;i<nentries;i++) {
    PxxATreeNu->GetEntry(i);
    ProbNu[0]->SetPoint( i, xx, yy);
    if( i < 5 ) 
      std::cout << i << " " << xx << " " << yy << std::endl;
  }
  
  PxxBTreeNu->SetBranchAddress("Ex",&xx);
  PxxBTreeNu->SetBranchAddress("Pb",&yy);
  
  nentries = PxxBTreeNu->GetEntries();
  
  for (Long64_t i=0;i<nentries;i++) {
    PxxBTreeNu->GetEntry(i);
    ProbNu[1]->SetPoint( i, xx, yy);
  }
  
  int ndataset = 0;
  TList * allgraphs = new TList(); //this is a ROOT container. It will store all of your Graphs
  
  allgraphs->Add( ProbNu[0] ); 
  ndataset++;

  allgraphs->Add( ProbNu[1] ); 
  ndataset++;
  
  //Datasets options (Markers: style, color, size) : You can also do it by hand using the interactive Editor
  int style[5];
  int color[5];
  float size[5];
  
  //For dataset No1
  style[0] = 21;
  color[0] = 2;
  size[0]  = 0.7;
  
  //For dataset No2
  style[1] = 20;
  color[1] = 4;
  size[1]  = 0.8;
  
  //For dataset No3
  style[2] = 22;
  color[2] = 38;
  size[2]  = 0.8;

  TCanvas * c1 = new TCanvas( cname.Data(), "Oscillation probabilities", 184,60,861,263); 
  c1->cd();
  gPad->SetGridx();
  gPad->SetGridy();
  gPad->SetLogx();

  float ymin = 0.0;
  float ymax = 0.5;
  float xmin = 0.9e9;
  float xmax = 1.0e10;

  TLegend * leg = new TLegend(0.14,0.58,0.35,0.85);
    
  leg->SetBorderSize(0);
  leg->SetTextSize(0.1);
  leg->SetLineColor(1);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(0);
  leg->SetFillStyle(1001);
  leg->SetTextFont(62);
  leg->SetTextSize(0.085);

  ndataset = allgraphs->GetSize(); //Get the ndatasets from the size of the List

  // Loop now over the List using the index k
  
  for(int k=0; k < ndataset; ++k) {
    
    if( k == 0 ) {
      //this is our first graph and it is special (to define axis min,max)
      ((TGraph*)allgraphs->At(k))->SetMinimum(ymin);
      ((TGraph*)allgraphs->At(k))->SetMaximum(ymax);
      ((TGraph*)allgraphs->At(k))->Draw("AP");
      ((TGraph*)allgraphs->At(k))->GetXaxis()->SetLimits(xmin, xmax);
      //set the color options
      ((TGraph*)allgraphs->At(k))->SetMarkerStyle( style[k] );
      ((TGraph*)allgraphs->At(k))->SetMarkerSize( size[k] );
      ((TGraph*)allgraphs->At(k))->SetMarkerColor( color[k] );
      ((TGraph*)allgraphs->At(k))->SetLineColor( color[k] );
      ((TGraph*)allgraphs->At(k))->SetFillColor( 10 );
      ((TGraph*)allgraphs->At(k))->GetYaxis()->SetNdivisions(505);
      ((TGraph*)allgraphs->At(k))->GetXaxis()->SetTitle("E [eV]");
      ((TGraph*)allgraphs->At(k))->GetYaxis()->SetTitle("P_{#mue}");

      ((TGraph*)allgraphs->At(k))->GetYaxis()->CenterTitle(true); 
      ((TGraph*)allgraphs->At(k))->GetXaxis()->CenterTitle(true); 
      ((TGraph*)allgraphs->At(k))->GetXaxis()->SetLabelOffset(0.007);
      ((TGraph*)allgraphs->At(k))->GetXaxis()->SetLabelSize(0.08);
      ((TGraph*)allgraphs->At(k))->GetXaxis()->SetTitleSize(0.07);
      ((TGraph*)allgraphs->At(k))->GetXaxis()->SetTitleOffset(0.9);
      ((TGraph*)allgraphs->At(k))->GetXaxis()->SetLabelFont(42);
      ((TGraph*)allgraphs->At(k))->GetYaxis()->SetLabelOffset(0.007);
      ((TGraph*)allgraphs->At(k))->GetYaxis()->SetLabelSize(0.08);
      ((TGraph*)allgraphs->At(k))->GetYaxis()->SetLabelFont(42);
      ((TGraph*)allgraphs->At(k))->GetYaxis()->SetTitleSize(0.09);
      ((TGraph*)allgraphs->At(k))->GetYaxis()->SetTitleOffset(0.45);
      ((TGraph*)allgraphs->At(k))->GetYaxis()->SetTitleFont(42);
      
      ((TGraph*)allgraphs->At(k))->Draw("APL"); // Draw option AP A=draw axis P=draw a marker for the data
      
      TString name = ((TObjString*)v_Labels->At(k))->GetString();
      leg->AddEntry( (TGraph*)allgraphs->At(k), name.Data());
      
      
    }
    else {
      ((TGraph*)allgraphs->At(k))->SetMarkerStyle( style[k] );
      ((TGraph*)allgraphs->At(k))->SetMarkerSize( size[k] );
      ((TGraph*)allgraphs->At(k))->SetMarkerColor( color[k] );
      ((TGraph*)allgraphs->At(k))->SetLineColor( color[k] );
      ((TGraph*)allgraphs->At(k))->SetFillColor( 10 );

      ((TGraph*)allgraphs->At(k))->Draw("PL"); // since we have already plotted the axis on the first graph we only need option P
      
      TString name = ((TObjString*)v_Labels->At(k))->GetString();
      leg->AddEntry( (TGraph*)allgraphs->At(k), name.Data());
    
    }
    
    
  }
  
  topTitle("Earth (corrected)");
  
  /// All done!
  leg->Draw();
  std::stringstream saveAs;
    
  saveAs.str("");
  saveAs << path << "EarthA" << "/pdf/" << "nueosc_earth_AB_" << option << ".pdf";
  c1->SaveAs( saveAs.str().c_str() );
  
  saveAs.str("");
  saveAs << path << "EarthA" << "/png/" << "nueosc_earth_AB_" << option << ".png";
  c1->SaveAs( saveAs.str().c_str() );
  
  saveAs.str("");
  saveAs << path << "EarthA" << "/eps/" << "nueosc_earth_AB_" << option << ".eps";
  c1->SaveAs( saveAs.str().c_str() );
    
  
  
}
Example #7
0
void kees_gen() {
  gROOT->SetStyle("HALLA");
  TCanvas *cn = new TCanvas("cn");
  cn->Draw();
  cn->UseCurrentStyle();
  TH1F *frm = new TH1F("frm","",100,0.,10.);
  frm->GetXaxis()->SetTitle("Q^{2}  [GeV^{2}]");
  frm->GetYaxis()->SetTitle("G_{E}^{n}");
  frm->SetMinimum(-.02);
  frm->SetMaximum(0.1);
  frm->UseCurrentStyle();
  frm->Draw();
  frm->SetAxisRange(0.,5.,"X");

  TF1 *genf = new TF1("genf",genff,1.,10.,1);
  genf->SetLineColor(2);
  genf->SetLineStyle(2);
  genf->SetParameter(0,1.);
  genf->SetParameter(1,.3);
  genf->SetParameter(0,-0.632);
  // match to Madey point just below 1.5
  //  genf->SetParameter(0,.0411/genf->Eval(1.45));
  
  TMultiGraph* mgrDta = new TMultiGraph("Data","G_{E}^{n}");
  TLegend *legDta = new TLegend(.54,.6,.875,.90,"","brNDC");

  TMultiGraph* wgr = mgrDta;
  TLegend *wlg = legDta;

   // the data
  legDta->SetBorderSize(0); // turn off border
  legDta->SetFillStyle(0);
  
  datafile_t *f = datafiles;
  TGraph* gr=0;
  while ( f && f->filename ) {
    gr=OneGraph(f);
    if (gr) {
      if (f->lnpt) {
	mgrDta->Add(gr,f->lnpt);
	legDta->AddEntry(gr,f->label,f->lnpt);
      }
      else if (gr->GetMarkerStyle()>=20) {
	mgrDta->Add(gr,"p");
	legDta->AddEntry(gr,f->label,"p");
      }	
      else {
	mgrDta->Add(gr,"l");
	legDta->AddEntry(gr,f->label,"l");
      }
    }
    f++;
  }
    

  mgrDta->Draw("p");
  //  legDta->Draw();   don't draw the data legend
  
  TMultiGraph* mgrThry = new TMultiGraph("Theory","G_{E}^{n}");
  TLegend *legThry = new TLegend(.54,.6,.875,.9,"","brNDC");

  wgr = mgrThry;
  wlg = legThry;

  // the theory
  wlg->SetBorderSize(0); // turn off border
  wlg->SetFillStyle(0);
  
  f = theoryfiles1;
  gr=0;
  while ( f && f->filename ) {
    gr=OneGraph(f);
    if (gr) {
      TGraphAsymmErrors *egr = dynamic_cast<TGraphAsymmErrors*>(gr);
      if (egr && egr->GetN()>1 && egr->GetEYhigh() && egr->GetEYhigh()[1]>0) {
	gr = toerror_band(egr);
	gr->SetFillStyle(3000+f->style);
      }
      if (f->lnpt) {
	wgr->Add(gr,f->lnpt);
	wlg->AddEntry(gr,f->label,f->lnpt);
      }
      else if (gr->GetMarkerStyle()>=20) {
	wgr->Add(gr,"p");
	wlg->AddEntry(gr,f->label,"p");
      }	
      else {
	wgr->Add(gr,"l");
	wlg->AddEntry(gr,f->label,"l");
      }
    }
    f++;
  }

  genf->Draw("same");
  mgrThry->Draw("c");
  legThry->AddEntry(genf,"F_{2}/F_{1} #propto ln^{2}(Q^{2}/#Lambda^{2})/Q^{2}","l");
  legThry->Draw();

  // draw a line at 1
  cn->Modified();

  cn->Update();
  cn->SaveAs(Form("%s.eps",psfile));
  cn->SaveAs(Form("%s.root",psfile));
  gSystem->Exec(Form("./replace_symbols.pl %s.eps",psfile));
  // now an overlay, hopefully matching dimensions

  // remove everything but the graph
  cn->Update();
  TList *clist = cn->GetListOfPrimitives();
  TFrame* frame = cn->GetFrame();
  for (int i=0; i<clist->GetSize(); ) {
    if (clist->At(i) != frame) {
      clist->RemoveAt(i);
    } else i++;
  }
  // draw markers in the corners
  TMarker *mkr = new TMarker(frame->GetX1(),frame->GetY1(),2);
  mkr->Draw();
  mkr = new TMarker(frame->GetX2(),frame->GetY1(),2);
  mkr->Draw();
  mkr = new TMarker(frame->GetX1(),frame->GetY2(),2);
  mkr->Draw();
  mkr = new TMarker(frame->GetX2(),frame->GetY2(),2);
  mkr->Draw();
  frame->SetLineColor(10);
  cn->Update();

  datafile_t miller = { "figure_input/Miller/lattice.GEn.rtf","Miller",
			"[0]","[1]","[1]-[3]","[2]-[1]",0,0,1,3,"F" };

  gr = OneGraph(&miller);
  TGraphAsymmErrors* egr = dynamic_cast<TGraphAsymmErrors*>(gr);
  if (egr && egr->GetEYhigh() && egr->GetEYhigh()[egr->GetN()/2]>0) {
    gr = toerror_band(egr);
    gr->SetLineStyle(1);
    gr->SetFillColor(gr->GetLineColor());
    gr->SetFillStyle(3000+miller.style);
  }
  
  gr->Draw("F");

  cn->Update();
  cn->SaveAs("gen_Miller_Overlay.eps");
  cn->SaveAs("gen_Miller_Overlay.root");
  
}
Example #8
0
void plot_efficiencies( TFile* file, Int_t type = 2, TDirectory* BinDir=0)
{
   // input:   - Input file (result from TMVA),
   //          - type = 1 --> plot efficiency(B) versus eff(S)
   //                 = 2 --> plot rejection (B) versus efficiency (S)
   //                 = 3 --> plot 1/eff(B) versus efficiency (S)

   Bool_t __PLOT_LOGO__  = kTRUE;
   Bool_t __SAVE_IMAGE__ = kTRUE;

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

   // reverse order if "rejection"
   if (type == 2) {
      Float_t z = y1;
      y1 = 1 - y2;
      y2 = 1 - z;
      //      cout << "--- type==2: plot background rejection versus signal efficiency" << endl;
   } else if (type == 3) {
      y1 = 0;
      y2 = -1; // will be set to the max found in the histograms

   } else {
      //  cout << "--- type==1: plot background efficiency versus signal efficiency" << endl;
   }
   // create canvas
   TCanvas* c = new TCanvas( "c", "the canvas", 200, 0, 650, 500 );

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

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

   TString xtit = "Signal efficiency";
   TString ytit = "Background efficiency";
   if (type == 2) ytit = "Background rejection";
   if (type == 3) ytit = "1/(Background eff.)";
   TString ftit = ytit + " versus " + xtit;

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


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

   TList xhists;
   TList xmethods;
   UInt_t xnm = TMVAGlob::GetListOfMethods( xmethods );
   TIter xnext(&xmethods);
   // loop over all methods
   TKey *xkey;
   while ((xkey = (TKey*)xnext())) {
      TDirectory * mDir = (TDirectory*)xkey->ReadObj();
      TList titles;
      UInt_t ninst = TMVAGlob::GetListOfTitles(mDir,titles);
      TIter nextTitle(&titles);
      TKey *titkey;
      TDirectory *titDir;
      while ((titkey = TMVAGlob::NextKey(nextTitle,"TDirectory"))) {
         titDir = (TDirectory *)titkey->ReadObj();
         TString methodTitle;
         TMVAGlob::GetMethodTitle(methodTitle,titDir);
         TIter nextKey( titDir->GetListOfKeys() );
         TKey *hkey2;
         while ((hkey2 = TMVAGlob::NextKey(nextKey,"TH1"))) {
            TH1 *h = (TH1*)hkey2->ReadObj();
            TString hname = h->GetName();
            if (hname.Contains( hNameRef ) && hname.BeginsWith( "MVA_" )) {
               if (type==3 && h->GetMaximum() > y2) y2 = h->GetMaximum();
            }
         }
      }
   }


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

   frame->Draw();

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

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

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

   while (hists.GetSize()) {
      TListIter hIt(&hists);
      TH1* hist(0);
      Double_t largestInt=-1;
      TH1* histWithLargestInt(0);
      while ((hist = (TH1*)hIt())!=0) {
         Double_t integral = hist->Integral(1,hist->FindBin(0.9999));
         if (integral>largestInt) {
            largestInt = integral;
            histWithLargestInt = hist;
         }
      }
      if (histWithLargestInt == 0) {
         cout << "ERROR - unknown hist \"histWithLargestInt\" --> serious problem in ROOT file" << endl;
         break;
      }
      legend->AddEntry(histWithLargestInt,TString(histWithLargestInt->GetTitle()).ReplaceAll("MVA_",""),"l");
      hists.Remove(histWithLargestInt);
   }

   // rescale legend box size
   // current box size has been tuned for 3 MVAs + 1 title
   if (type == 1) {
      dyH *= (1.0 + Float_t(nmva - 3.0)/4.0);
      legend->SetY1( y0H - dyH );
   }
   else {
      dyH *= (Float_t(TMath::Min(10,nmva) - 3.0)/4.0);
      legend->SetY2( y0H + dyH);
   }

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

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

   if (__PLOT_LOGO__) TMVAGlob::plot_logo();

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

   c->Update();

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

   return;
}
Example #9
0
void RecoMuonValHistoPublisher(const char* newFile="NEW_FILE",const char* refFile="REF_FILE") {
  cout << ">> Starting RecoMuonValHistoPublisher(" << newFile << "," << refFile << ")..." << endl;

  //====  To be replaced from python ====================
  
  const char* dataType = "DATATYPE";
  const char* refLabel("REF_LABEL, REF_RELEASE REFSELECTION");
  const char* newLabel("NEW_LABEL, NEW_RELEASE NEWSELECTION");
  const char* fastSim = "IS_FSIM";


  // ==== Initial settings and loads
  //gROOT->ProcessLine(".x HistoCompare_Tracks.C");
  //gROOT ->Reset();
  gROOT ->SetBatch();
  gErrorIgnoreLevel = kWarning; // Get rid of the info messages


  SetGlobalStyle();


  // ==== Some cleaning... is this needed?  
  delete gROOT->GetListOfFiles()->FindObject(refFile);
  delete gROOT->GetListOfFiles()->FindObject(newFile); 
  


  // ==== Opening files, moving to the right branch and getting the list of sub-branches
  cout << ">> Openning file, moving to the right branch and getting sub-branches..." << endl;

  cout << ">> Finding sources..." << endl;
  TFile* sfile = new TFile(newFile);
  TList* sl = getListOfBranches(dataType, sfile, "RecoMuonV");
  if (!sl) {
    cout << "ERROR: Could not find keys!!!" << endl;
    cerr << "ERROR: Could not find keys!!!" << endl;
    return;
  }
  TDirectory*  sdir  = gDirectory;
  for (unsigned int i = 0; i < sl->GetEntries(); i++)
    cout << "   + " << sl->At(i)->GetName() << endl;
    
  cout << ">> Finding references..." << endl;
  TFile* rfile = new TFile(refFile);
  TList* rl = getListOfBranches(dataType, rfile, "RecoMuonV");
  if (!rl) {
    cout << "ERROR: Could not find keys!!!" << endl;
    cerr << "ERROR: Could not find keys!!!" << endl;
    return;
  }
  TDirectory* rdir  = gDirectory;
  for (unsigned int i = 0; i < sl->GetEntries(); i++)
    cout << "   + " << sl->At(i)->GetName() << endl;

  Float_t maxPT;
  TString File = newFile;
  if (File.Contains("SingleMuPt1000") ||File.Contains("WpM")||File.Contains("ZpMM")   ) maxPT=1400.;
  else if(File.Contains("SingleMuPt10")) {maxPT = 70.;}
  else if (File.Contains("SingleMuPt100")) {maxPT = 400.;}
  else maxPT = 400.;

  TIter iter_r( rl );
  TIter iter_s( sl );
  TKey* rKey = 0;
  TKey* sKey = 0;
  TString rcollname;
  TString scollname;

  while ( (rKey = (TKey*)iter_r()) ) {
    TString myName = rKey->GetName();
#ifdef DEBUG
    cout << "DEBUG: Checking key " << myName << endl;
#endif
    rcollname = myName;
    sKey = (TKey*)iter_s();
    if (!sKey) continue;
    scollname = sKey->GetName();
    if ( (rcollname != scollname) && (rcollname+"FS" != scollname) && (rcollname != scollname+"FS") ) {
      cerr << "ERROR: Different collection names, please check: " << rcollname << " : " << scollname << endl;
      cout << "ERROR: Different collection names, please check: " << rcollname << " : " << scollname << endl;
      continue;
    }

    // ==== Now let's go for the plotting...
    cout << ">> Comparing plots in " << myName << "..." << endl;    
    cerr << ">> Comparing plots in " << myName << "..." << endl;    
    TString newDir("NEW_RELEASE/NEWSELECTION/NEW_LABEL/");
    newDir+=myName;
    gSystem->mkdir(newDir,kTRUE);
    bool resolx = false;
    bool *resol = &resolx;
    bool    logy    [] = {false,   false,  false,      false    };
    bool    doKolmo [] = {true,    true,   true,       true     };
    Double_t minx   [] = {-1E100, -1E100,    -1E100,   5.,    -1E100, -1E100 };
    Double_t maxx   [] = {-1E100, -1E100,-1E100, maxPT,  -1E100, -1E100 };
 
    Double_t norm   [] = {0.,0.,-999.,-999.,0.,0.}; //Normalize to first histogram

 
   //===== reco muon distributions: GLB
    //TString baseh     = Form("RecoMuon_MuonAssoc_Glb%s/",fastSim);

    const char* plots1[] = {"RecoMuon_MuonAssoc_Glb/ErrPt", 
    			    "RecoMuon_MuonAssoc_Glb/ErrP", 
    			    "RecoMuon_MuonAssoc_Glb/ErrPt_vs_Eta_Sigma", 
    			    "RecoMuon_MuonAssoc_Glb/ErrPt_vs_Pt_Sigma"};
    const char* plotst1[] = {"GlobalMuon(GLB) #Delta p_{T}/p_{T}", 
			     "GlobalMuon(GLB) #Delta p/p", 
			     "GlobalMuon(GLB) #Delta p_{T}/p_{T} vs #sigma(#eta)", 
			     "GlobalMuon(GLB) #Delta p_{T}/p_{T} vs #sigma(p_{T})"};
    Plot4Histograms(newDir + "/muonRecoGlb.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecHistosGlb", "Distributions for GlobalMuons (GLB)",
		    refLabel, newLabel,
		    plots1, plotst1,
		    logy, doKolmo, norm,resol,minx,maxx);
    
    
    //==== efficiencies and fractions GLB
    const char* plots2 [] = {"RecoMuon_MuonAssoc_Glb/EffP", 
			     "RecoMuon_MuonAssoc_Glb/EffEta", 
			     "RecoMuon_MuonAssoc_Glb/FractP", 
			     "RecoMuon_MuonAssoc_Glb/FractEta"};   
    const char* plotst2[] = {"GlobalMuon(GLB) #epsilon vs. p", 
			     "GlobalMuon(GLB) #epsilon vs. #eta", 
			     "GlobalMuon(GLB) fraction vs. p", 
			     "GlobalMuon(GLB) fraction vs. #eta"};
    Double_t minx1   [] = {5., -1E100,    5.,   -1E100,    -1E100, -1E100 };
    Double_t maxx1   [] = {maxPT, -1E100,maxPT, -1E100,  -1E100, -1E100 };
    Double_t norm2   [] = {-999.,-999.,-999.,-999.,-999.,-999.}; //Normalize to first histogram 
    Plot4Histograms(newDir + "/muonRecoGlbEff.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecEffHistosGlb", "Distributions for GlobalMuons (GLB), efficiencies and fractions",
		    refLabel, newLabel,
		    plots2, plotst2,
		    logy, doKolmo,norm2,resol,minx1,maxx1);
    
    /*
    //===== reco muon distributions: GLBPF
    baseh             = Form("RecoMuon_MuonAssoc_GlbPF%s/",fastSim);
    const char* plots3[]  = {(baseh + "ErrPt").Data(), (baseh + "ErrP").Data(), 
			     (baseh + "ErrPt_vs_Eta_Sigma").Data(), (baseh + "ErrPt_vs_Pt_Sigma").Data()};   
    const char* plotst3[] = {"PFGlobalMuon(GLBPF) #Delta p_{T}/p_{T}", "PFGlobalMuon(GLBPF) #Delta p/p", 
			     "PFGlobalMuon(GLBPF) #Delta p_{T}/p_{T} vs #sigma(#eta)", "PFGlobalMuon(GLBPF) #Delta p_{T}/p_{T} vs #sigma(p_{T})"};
    Plot4Histograms(newDir + "/muonRecoGlbPF.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecHistosGlbPF", "Distributions for PFGlobalMuons (GLBPF)",
		    refLabel, newLabel,
		    plots3, plotst3,
		    logy, doKolmo, norm);
    
    
    //==== efficiencies and fractions GLBPF
    const char* plots4 [] = {(baseh + "EffP").Data(), (baseh + "EffEta").Data(), 
			     (baseh + "FractP").Data(), (baseh + "FractEta").Data()};   
    const char* plotst4[] = {"PFGlobalMuon(GLBPF) #epsilon vs. p", "PFGlobalMuon(GLBPF) #epsilon vs. #eta", 
			     "PFGlobalMuon(GLBPF) fraction vs. p", "PFGlobalMuon(GLBPF) fraction vs. #eta"};
    Plot4Histograms(newDir + "/muonRecoGlbPFEff.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecEffHistosGlbPF", "Distributions for PFGlobalMuons (GLBPF), efficiencies and fractions",
		    refLabel, newLabel,
		    plots4, plotst4,
		    logy, doKolmo, norm);
    */
    
    //===== reco muon distributions: STA
    //baseh             = Form("RecoMuon_MuonAssoc_Sta%s/",fastSim);
    const char* plots5 [] = {"RecoMuon_MuonAssoc_Sta/ErrPt", 
			     "RecoMuon_MuonAssoc_Sta/ErrP", 
			     "RecoMuon_MuonAssoc_Sta/ErrPt_vs_Eta_Sigma", 
			     "RecoMuon_MuonAssoc_Sta/ErrPt_vs_Pt_Sigma"};   
    const char* plotst5[] = {"StandAloneMuon(STA) #Delta p_{T}/p_{T}", 
			     "StandAloneMuon(STA) #Delta p/p", 
			     "StandAloneMuon(STA) #Delta p_{T}/p_{T} vs #sigma(#eta)", 
			     "StandAloneMuon(STA) #Delta p_{T}/p_{T} vs #sigma(p_{T})"};
    Plot4Histograms(newDir + "/muonRecoSta.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecHistosSta", "Distributions for StandAloneMuons (STA)",
		    refLabel, newLabel,
		    plots5, plotst5,
		    logy, doKolmo, norm,resol, minx,maxx);
    
    
    
    //==== efficiencies and fractions STA
    const char* plots6 [] = {"RecoMuon_MuonAssoc_Sta/EffP", 
			     "RecoMuon_MuonAssoc_Sta/EffEta", 
			     "RecoMuon_MuonAssoc_Sta/FractP", 
			     "RecoMuon_MuonAssoc_Sta/FractEta"};   
    const char* plotst6[] = {"StandAloneMuon(STA) #epsilon vs. p", 
			     "StandAloneMuon(STA) #epsilon vs. #eta", 
			     "StandAloneMuon(STA) fraction vs. p", 
			     "StandAloneMuon(STA) fraction vs. #eta"};
    Plot4Histograms(newDir + "/muonRecoStaEff.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecEffHistosSta", "Distributions for StandAloneMuons (STA), efficiencies and fractions",
		    refLabel, newLabel,
		    plots6, plotst6,
		    logy, doKolmo, norm2,resol,minx1,maxx1);



   //===== reco muon distributions: TRK
    //baseh             = Form("RecoMuon_MuonAssoc_Trk%s/",fastSim);
    const char* plots7 [] = {"RecoMuon_MuonAssoc_Trk/ErrPt", 
			     "RecoMuon_MuonAssoc_Trk/ErrP", 
			     "RecoMuon_MuonAssoc_Trk/ErrPt_vs_Eta_Sigma", 
			     "RecoMuon_MuonAssoc_Trk/ErrPt_vs_Pt_Sigma"};   
    const char* plotst7[] = {"TrackerMuon(TRK) #Delta p_{T}/p_{T}", 
			     "TrackerMuon(TRK) #Delta p/p", 
			     "TrackerMuon(TRK) #Delta p_{T}/p_{T} vs #sigma(#eta)", 
			     "TrackerMuon(TRK) #Delta p_{T}/p_{T} vs #sigma(p_{T})"};
    Plot4Histograms(newDir + "/muonRecoTrk.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecHistosTrk", "Distributions for TrackerMuons (TRK)",
		    refLabel, newLabel,
		    plots7, plotst7,
		    logy, doKolmo, norm,resol,minx,maxx);



   //==== efficiencies and fractions TRK
    const char* plots8 [] = {"RecoMuon_MuonAssoc_Trk/EffP", 
			     "RecoMuon_MuonAssoc_Trk/EffEta", 
			     "RecoMuon_MuonAssoc_Trk/FractP", 
			     "RecoMuon_MuonAssoc_Trk/FractEta"};   
    const char* plotst8[] = {"TrackerMuon(TRK) #epsilon vs. p", 
			     "TrackerMuon(TRK) #epsilon vs. #eta", 
			     "TrackerMuon(TRK) fraction vs. p", 
			     "TrackerMuon(TRK) fraction vs. #eta"};
    Plot4Histograms(newDir + "/muonRecoTrkEff.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecEffHistosTrk", "Distributions for TrackerMuons (TRK), efficiencies and fractions",
		    refLabel, newLabel,
		    plots8, plotst8,
		    logy, doKolmo, norm2,resol,minx1,maxx1);

    
    //
    //===== reco muon distributions: Tight Muons
    //
    //baseh             = Form("RecoMuon_MuonAssoc_Tgt%s/",fastSim);
    const char* plots9 [] = {"RecoMuon_MuonAssoc_Tgt/ErrPt", 
			     "RecoMuon_MuonAssoc_Tgt/ErrP", 
			     "RecoMuon_MuonAssoc_Tgt/ErrPt_vs_Eta_Sigma", 
			     "RecoMuon_MuonAssoc_Tgt/ErrPt_vs_Pt_Sigma"};   
    const char* plotst9[] = {"Tight Muon #Delta p_{T}/p_{T}", 
			     "Tight Muon #Delta p/p", 
			     "Tight Muon #Delta p_{T}/p_{T} vs #sigma(#eta)", 
			     "Tight Muon #Delta p_{T}/p_{T} vs #sigma(p_{T})"};
    Plot4Histograms(newDir + "/muonRecoTgt.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecHistosTgt", "Distributions for Tight Muons",
		    refLabel, newLabel,
		    plots9, plotst9,
		    logy, doKolmo, norm,resol,minx,maxx);



   //==== efficiencies and fractions Tight Muons
    const char* plots10 [] = {"RecoMuon_MuonAssoc_Tgt/EffP", 
			      "RecoMuon_MuonAssoc_Tgt/EffEta", 
			      "RecoMuon_MuonAssoc_Tgt/FractP", 
			      "RecoMuon_MuonAssoc_Tgt/FractEta"};   
    const char* plotst10[] = {"Tight Muon #epsilon vs. p", 
			      "Tight Muon #epsilon vs. #eta", 
			      "Tight Muon fraction vs. p", 
			      "Tight Muon fraction vs. #eta"};
    Plot4Histograms(newDir + "/muonRecoTgtEff.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecEffHistosTgt", "Distributions for Tight Muons, efficiencies and fractions",
		    refLabel, newLabel,
		    plots10, plotst10,
		    logy, doKolmo, norm2,resol,minx1,maxx1);
    
    
    
    //
    // Merge pdf histograms together into larger files, and name them based on the collection names
    //
    TString mergefile = "merged_recomuonval.pdf"; // File name where partial pdfs will be merged
    TString destfile  = newDir + "/../" + myName + ".pdf"; // Destination file name
    TString gscommand = "gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="+ mergefile + " "
      +newDir+"/muonRecoGlb.pdf "
      +newDir+"/muonRecoGlbEff.pdf "
      //      +newDir+"/muonRecoGlbPF.pdf "
      //      +newDir+"/muonRecoGlbPFEff.pdf "
      +newDir+"/muonRecoSta.pdf "
      +newDir+"/muonRecoStaEff.pdf "
      +newDir+"/muonRecoTrk.pdf "
      +newDir+"/muonRecoTrkEff.pdf "
      +newDir+"/muonRecoTgt.pdf "
      +newDir+"/muonRecoTgtEff.pdf ";

    cout << ">> Merging partial pdfs to " << mergefile << "..." << endl;
#ifdef DEBUG
    cout << "DEBUG: ...with command \"" << gscommand << "\"" << endl;
#endif
    gSystem->Exec(gscommand);
    cout << ">> Moving " << mergefile << " to " << destfile << "..." << endl;
    gSystem->Rename(mergefile, destfile);
    cout << "   ... Done" << endl;
   
    cout << ">> Deleting partial pdf files" << endl;
    gSystem->Exec("rm -r "+newDir);
    
  }  // end of "while loop"
  
  cout << ">> Removing the relval files from ROOT before closing..." << endl;
  gROOT->GetListOfFiles()->Remove(sfile);
  gROOT->GetListOfFiles()->Remove(rfile);
  
#ifdef DEBUG
  cout << "DEBUG: Exiting!" << endl;
  cerr << "DEBUG: Exiting!" << endl;
#endif
}
Example #10
0
///
/// Process a directory recursively.
///
void html_a_directory(TDirectory *f, TString path, TEnv *params)
{
  TCanvas *c_h1 = 0;
  if (c_h1 == 0) {
    int x = params->GetValue("H1.XSize", 150);
    int y = params->GetValue("H1.YSize", 100);
    c_h1 = new TCanvas ("c_h1", "1d plots", x, y);
  }

  ///
  /// Check how to make gif plots
  ///

  char command[512];
  sprintf(command, "which pstoimg &> /dev/null");
  bool UsePstoimg = ! system(command);

  ///
  /// Generate the output directory
  ///

  gSystem->MakeDirectory (path);

  ///
  /// Get the html started
  ///

  ofstream html (path + "/index.html");
  html << "<html><head><title>" << f->GetName() << "</title></head>" << endl;
  html << "<body>" << endl;
  html << "<h1>" << f->GetName() << "</h1>" << endl;
  cout << "Processing directory " << f->GetName() << endl;

  ///
  /// Now loop over all the keys in the directory
  ///

  f->cd();
  TList *objlist = f->GetListOfKeys();
  objlist->Sort(); // order alphabetically, instead of order in which they were written
  TIterator *itr = objlist->MakeIterator();
  TKey *key;
  while ((key = static_cast<TKey*>(itr->Next())) != 0) {
    TObject *obj = key->ReadObj();

    if (obj->IsA()->InheritsFrom("TDirectory")) {
      TDirectory *d = static_cast<TDirectory*>(obj);
      html << "<br><a href=\"" << d->GetName() << "/\">" << d->GetName() << "</a>" << endl;
      html_a_directory(d, path + "/" + d->GetName(), params);
    }

    else if (obj->IsA()->InheritsFrom("TObjString")) {
      TObjString *s = static_cast<TObjString*>(obj);
      html << "<p><h2>" << key->GetName() << "</h2>" << endl;
      //html << "<blockquote><pre>" << static_cast<char*>(s->GetString())
	  // << "</pre></blockquote></p>"
	  // << endl;
      html << "<blockquote><pre>" << (s->GetString()).Data() << "</pre></blockquote></p>"<< endl;
      

    }

    //    else if (obj->IsA()->InheritsFrom("CutFlowTable")) {
    //      CutFlowTable *c = static_cast<CutFlowTable*> (obj);
    //      
    //      html << "<p><h2>" << key->GetName() << "</h2>" << endl;
    //
    //      CFTPrinterHTML txt (html);
    //      f->cd();
    //      c->PrintGlobal (txt, "All Events", "");
    //      html << "</p>" << endl;
    //    }

    else if (obj->IsA()->InheritsFrom("TCanvas")) {
      TCanvas *cnv = static_cast<TCanvas*>(obj);

      cnv->Draw();
      cnv->SaveAs(path + "/" + key->GetName() + ".eps");
      if (UsePstoimg) {
	sprintf(command, "pstoimg -type=gif %s &> /dev/null",(path + "/" + key->GetName() + ".eps").Data());
	if (system(command) != 0) {
	  cout<<"Could not convert to gif: "<<path + "/" + key->GetName() + ".eps"<<endl;
	  abort();
	}
      } else cnv->SaveAs(path + "/" + key->GetName() + ".gif");

      cnv->Close();

      html << "<p><a href=\"" << key->GetName() << ".eps\">";
      html << "<img src=\"" << key->GetName() << ".gif\">";
      html << "</a> <br> " << key->GetName() << ".gif </p>" << endl;								   
    }

    else if (obj->IsA()->InheritsFrom("TH1") && !(obj->IsA()->InheritsFrom("TH2"))) {
      TH1 *h = static_cast<TH1*> (obj);

      c_h1->cd();
      h->Draw();
      c_h1->SaveAs(path + "/" + key->GetName() + ".eps");
      if (UsePstoimg) {
	sprintf(command, "pstoimg -type=gif %s &> /dev/null",(path + "/" + key->GetName() + ".eps").Data());
	if (system(command) != 0) {
	  cout<<"Could not convert to gif: "<<path + "/" + key->GetName() + ".eps"<<endl;
	  abort();
	}
      } else c_h1->SaveAs(path + "/" + key->GetName() + ".gif");

      html << "<p><a href=\"" << key->GetName() << ".eps\">";
      html << "<img src=\"" << key->GetName() << ".gif\">";
      html << "</a> <br> " << key->GetName() << ".gif </p>" << endl;
    }
    f->cd();
  }

  ///
  /// Done!
  ///

  html << "</body></html>" << endl;
  html.close();
}
Example #11
0
void checkRsnPIDqa(TString filename, TString foldername, Bool_t savePng,
		   TString plotTPCpi, TString plotTPCka, TString plotTPCpro,
		   TString plotTTOFpi, TString plotTOFka, TString plotTOFpro)
{
  //Open input file 
  TFile * fin = TFile::Open(filename.Data());
  if (!fin) return 0x0;
  
  //Access output of specific wagon
  TList * list = (TList*) fin->Get(foldername.Data());
  if (!list) return 0x0;

  //Set range for fit
  Float_t RangeFitMomMin = 0.1; //range in momentum where to check the mean and pull
  Float_t RangeFitMomMax = 2.0;
  Int_t xbinFitMin = 0;
  Int_t xbinFitMax = -1;
  Float_t RangeFitNsigmaPIDmin = -2.0; //range in Nsigma where the fit is to be performed
  Float_t RangeFitNsigmaPIDmax = 2.0;

  //Set range for visualisation
  Float_t RangeShowTPC[2] = {0.1, 2.0}; 
  Float_t RangeShowTOF[2] = {0.25, 2.0};
    
  //--------------------------
  // TPC PID Nsigma
  // fit with simple gaussian
  //--------------------------
  //Gaussian function
  TF1 *fGaus = new TF1("f","gaus", -7.0, 7.0);

  //--- pions
  TH2F * hTPCsigmaPi = (TH2F*)list->FindObject(plotTPCpi.Data());
  hTPCsigmaPi->RebinX(2);
  hTPCsigmaPi->SetTitle("TPC Pions");
  MakeUpHisto(hTPCsigmaPi,"p_{TPC} (GeV/c)", "N#sigma_{TPC}", 1, kBlack, 2);
  hTPCsigmaPi->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTPCsigmaPi->GetXaxis()->SetRangeUser(RangeShowTPC[0], RangeShowTPC[1]);
  xbinFitMin = hTPCsigmaPi->GetXaxis()->FindBin(RangeFitMomMin);
  xbinFitMax = hTPCsigmaPi->GetXaxis()->FindBin(RangeFitMomMax);
  hTPCsigmaPi->FitSlicesY(fGaus, xbinFitMin, xbinFitMax );
  TH1D * hTPCsigmaPi_mean = ((TH1D*)gDirectory->FindObject(Form("%s_1", plotTPCpi.Data())))->Clone("hNsigmaTPCpi_mean");
  TH1D * hTPCsigmaPi_pull = ((TH1D*)gDirectory->FindObject(Form("%s_2", plotTPCpi.Data())))->Clone("hNsigmaTPCpi_pull");
  MakeUpHisto(hTPCsigmaPi_mean, "", "", 1, kBlack, 2);
  MakeUpHisto(hTPCsigmaPi_pull, "", "", 1, kRed+2, 2);

  //--- kaons
  TH2F * hTPCsigmaKa = (TH2F*)list->FindObject(plotTPCka.Data());
  hTPCsigmaKa->RebinX(2);
  hTPCsigmaKa->SetTitle("TPC Kaons");
  hTPCsigmaKa->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTPCsigmaKa->GetXaxis()->SetRangeUser(RangeShowTPC[0], RangeShowTPC[1]);
  hTPCsigmaKa->FitSlicesY(fGaus, xbinFitMin, xbinFitMax );
  MakeUpHisto(hTPCsigmaKa,"p_{TPC} (GeV/c)", "N#sigma_{TPC}", 1, kBlack, 2);
  TH1D * hTPCsigmaKa_mean = ((TH1D*)gDirectory->FindObject(Form("%s_1", plotTPCka.Data())))->Clone("hNsigmaTPCka_mean");
  TH1D * hTPCsigmaKa_pull = ((TH1D*)gDirectory->FindObject(Form("%s_2", plotTPCka.Data())))->Clone("hNsigmaTPCka_pull");
  MakeUpHisto(hTPCsigmaKa_mean, "", "", 1, kBlack, 2);
  MakeUpHisto(hTPCsigmaKa_pull, "", "", 1, kRed+2, 2);

  //--- protons
  TH2F * hTPCsigmaPro = (TH2F*)list->FindObject(plotTPCpro.Data());
  hTPCsigmaPro->RebinX(2);
  hTPCsigmaPro->SetTitle("TPC Protons");
  MakeUpHisto(hTPCsigmaPro,"p_{TPC} (GeV/c)", "N#sigma_{TPC}", 1, kBlack, 2);
  hTPCsigmaPro->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTPCsigmaPro->GetXaxis()->SetRangeUser(RangeShowTPC[0], RangeShowTPC[1]);
  hTPCsigmaPro->FitSlicesY(fGaus, xbinFitMin, xbinFitMax );
  TH1D * hTPCsigmaPro_mean = ((TH1D*)gDirectory->FindObject(Form("%s_1", plotTPCpro.Data())))->Clone("hNsigmaTPCpro_mean");
  TH1D * hTPCsigmaPro_pull = ((TH1D*)gDirectory->FindObject(Form("%s_2", plotTPCpro.Data())))->Clone("hNsigmaTPCpro_pull");
  MakeUpHisto(hTPCsigmaPro_mean, "", "", 1, kBlack, 2);
  MakeUpHisto(hTPCsigmaPro_pull, "", "", 1, kRed+2, 2);

   //--- plot TPC
  TLine *l11=new TLine(RangeShowTPC[0],0.,RangeShowTPC[1],0.); l11->SetLineWidth(1); l11->SetLineStyle(7);
  TLine *l12=new TLine(RangeShowTPC[0],1.,RangeShowTPC[1],1.); l12->SetLineWidth(1); l12->SetLineStyle(7);

  gStyle->SetOptStat(0);
  TCanvas *cPidPerformance4 = new TCanvas("cPIDperformance4","TPC PID",1200,500);
  cPidPerformance4->Divide(3,1);
  cPidPerformance4->cd(1);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTPCsigmaPi->DrawCopy("colz");
  hTPCsigmaPi_mean->DrawCopy("same");
  hTPCsigmaPi_pull->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  cPidPerformance4->cd(2);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTPCsigmaKa->DrawCopy("colz");
  hTPCsigmaKa_mean->DrawCopy("same");
  hTPCsigmaKa_pull->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  cPidPerformance4->cd(3);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTPCsigmaPro->DrawCopy("colz");
  hTPCsigmaPro_mean->DrawCopy("same");
  hTPCsigmaPro_pull->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  TLegend * pidLegTPC = new TLegend(0.15,0.8,0.88,0.88);
  pidLegTPC->SetBorderSize(0); pidLegTPC->SetFillStyle(1001); pidLegTPC->SetFillColor(kWhite);
  pidLegTPC->SetTextSize(0.04); pidLegTPC->SetNColumns(2);
  pidLegTPC->AddEntry(hTPCsigmaPro_mean,"Mean","lp");
  pidLegTPC->AddEntry(hTPCsigmaPro_pull,Form("#sigma, Gaus fit (%2.1f,%2.1f)",RangeFitNsigmaPIDmin,RangeFitNsigmaPIDmax),"lp");
  pidLegTPC->Draw("same");

  if (savePng) cPidPerformance4->SaveAs("RsnQA_TPC_Nsigma.png");
  
  //----------------------------------------------------
  // TOF
  // fit with signal model = gaussian + exponential tail
  //----------------------------------------------------
  //Signal model for TOF signal = gaus + exp tail
  const Int_t npars = 6;
  TF1 *fSignalModel = new TF1("fSignalModel", TOFsignal, -7.0, 7.0, npars);
  fSignalModel->SetTitle("TOF Signal");
  fSignalModel->SetParameter(0, 1.);
  fSignalModel->SetParameter(1, 0.);
  fSignalModel->SetParLimits(1, -2., 1.);
  fSignalModel->SetParameter(2, 1.);
  fSignalModel->SetParLimits(2, 0.5, 2.);
  fSignalModel->SetParameter(3, 1.);
  fSignalModel->SetParLimits(3, 0.5, 1.5);
  fSignalModel->SetParameter(4, 1.);
  fSignalModel->SetParLimits(4, 0., 1.e8);
  fSignalModel->SetParameter(5, 0.);
  fSignalModel->SetParLimits(5, -10., 10.);
  fSignalModel->SetNpx(2000);
  fSignalModel->SetParNames("Norm", "Mean", "Sigma", "Tail", "Shift", "Slope"/*, "Square"*/);
  fSignalModel->SetLineColor(kRed+1);

  //results
  TObjArray *results[3];
  for(Int_t i = 0; i < 3; i++){
    results[i] = new TObjArray(10);
  }
  TH1D * par[3][npars];
  //--- pions
  TH2F * hTOFsigmaPi = (TH2F*)list->FindObject(plotTOFpi.Data());
  hTOFsigmaPi->SetTitle("TOF Pions");
  hTOFsigmaPi->RebinX(2);
  MakeUpHisto(hTOFsigmaPi,"p (GeV/c)", "N#sigma_{TOF}", 1, kBlack, 2);
  hTOFsigmaPi->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTOFsigmaPi->GetXaxis()->SetRangeUser(RangeShowTOF[0], RangeShowTOF[1]);
  fSignalModel->SetParLimits(4, 0., hTOFsigmaPi->GetMaximum()*0.5);
  fSignalModel->SetParLimits(0, 0., hTOFsigmaPi->GetMaximum()*1.2);
  hTOFsigmaPi->FitSlicesY(fSignalModel, xbinFitMin, xbinFitMax, 0, "QR", results[0] );
  for(Int_t cc = 0; cc < npars ; cc++) {
    par[0][cc] = (TH1D*)gDirectory->FindObject(Form("%s_%i", plotTOFpi.Data(), cc));
  }
  MakeUpHisto(par[0][1], "", "", 1, kBlue, 2);
  MakeUpHisto(par[0][2], "", "", 1, kMagenta+2, 2);
  
  //--- KAONS
  TH2F * hTOFsigmaKa = (TH2F*)list->FindObject(plotTOFka.Data());
  hTOFsigmaKa->SetTitle("TOF Kaons");
  hTOFsigmaKa->RebinX(2);
  MakeUpHisto(hTOFsigmaKa,"p (GeV/c)", "N#sigma_{TOF}", 1, kBlack, 2);
  hTOFsigmaKa->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTOFsigmaKa->GetXaxis()->SetRangeUser(RangeShowTOF[0], RangeShowTOF[1]);
  fSignalModel->SetParLimits(4, 0., hTOFsigmaKa->GetMaximum()*0.5);
  fSignalModel->SetParLimits(0, 0., hTOFsigmaKa->GetMaximum()*1.2);
  hTOFsigmaKa->FitSlicesY(fSignalModel, xbinFitMin, xbinFitMax, 0, "QR", results[0] );
  for(Int_t cc = 0; cc < npars ; cc++) {
    par[1][cc] = (TH1D*)gDirectory->FindObject(Form("%s_%i", plotTOFka.Data(), cc));
  }
  MakeUpHisto(par[1][1], "", "", 1, kBlue, 2);
  MakeUpHisto(par[1][2], "", "", 1, kMagenta+2, 2);

  //--- protons
  TH2F * hTOFsigmaPro = (TH2F*)list->FindObject(plotTOFpro.Data());
  hTOFsigmaPro->SetTitle("TOF Protons");
  hTOFsigmaPro->RebinX(2);
  MakeUpHisto(hTOFsigmaPro,"p (GeV/c)", "N#sigma_{TOF}", 1, kBlack, 2);
  hTOFsigmaPro->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTOFsigmaPro->GetXaxis()->SetRangeUser(RangeShowTOF[0], RangeShowTOF[1]);
  fSignalModel->SetParLimits(4, 0., hTOFsigmaPro->GetMaximum()*0.5);
  fSignalModel->SetParLimits(0, 0., hTOFsigmaPro->GetMaximum()*1.2);
  hTOFsigmaPro->FitSlicesY(fSignalModel, xbinFitMin, xbinFitMax, 0, "QR", results[0] );
  for(Int_t cc = 0; cc < npars ; cc++) {
    par[2][cc] = (TH1D*)gDirectory->FindObject(Form("%s_%i", plotTOFpro.Data(), cc));
  }
  MakeUpHisto(par[2][1], "", "", 1, kBlue, 2);
  MakeUpHisto(par[2][2], "", "", 1, kMagenta+2, 2);

  //--- plot TOF
  gStyle->SetOptStat(0);
  TCanvas *cPidPerformance3 = new TCanvas("cPidPerformance3","TOF PID performance",1200,500);
  cPidPerformance3->Divide(3,1);
  cPidPerformance3->cd(1);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTOFsigmaPi->DrawCopy("colz");
  if(par[0][1]) par[0][1]->DrawCopy("same");
  if(par[0][2]) par[0][2]->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  cPidPerformance3->cd(2);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTOFsigmaKa->DrawCopy("colz");
  if(par[1][1]) par[1][1]->DrawCopy("same");
  if(par[1][2]) par[1][2]->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  cPidPerformance3->cd(3);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTOFsigmaPro->DrawCopy("colz");
  if(par[2][1]) par[2][1]->DrawCopy("same");
  if(par[2][2]) par[2][2]->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  TLegend * pidLegTOF = new TLegend(0.15,0.8,0.88,0.88);
  pidLegTOF->SetBorderSize(0); pidLegTOF->SetFillStyle(1001); pidLegTOF->SetFillColor(kWhite);
  pidLegTOF->SetTextSize(0.04); pidLegTOF->SetNColumns(2);
  pidLegTOF->AddEntry(par[0][1],"Mean","lp");
  pidLegTOF->AddEntry(par[0][2], Form("#sigma, Gaus+Tail fit (%2.1f,%2.1f)",RangeFitNsigmaPIDmin, RangeFitNsigmaPIDmax),"lp");
  pidLegTOF->Draw("same");
  
  if (savePng) cPidPerformance3->Print("RsnQA_TOF_Nsigma.png");
  return;
}
Example #12
0
int main(int argc, char *argv[]) 
{
  if (argc != 3 && argc != 4 && argc != 7) {
    cout << "Usage: quickDraw path drawstring [selection [nbins xmin xmax]]" << endl;
    cout << "       will create a file histogram.pdf from the given files" << endl 
	 << endl;
    cout << "path           points to a directory containing ROOT files" << endl;
    cout << "drawstring     is a string usable in TTree::Draw()" << endl;
    cout << "selection      e.g. (muo_n>0)&&(jet_n>0) or 1. if no selection" << endl;
    cout << "nbins          number of bins in histogram" << endl;
    cout << "xmin           low x edge of histogram" << endl;
    cout << "xmax           high x edge of histogram" << endl;
    cout << endl;
    cout << "Example: quickDraw ~/data \"muo_pt[0]\" \"(jet_n>2)\" 100 0 1000" << endl;
    cout << "          will draw muo_pt of the leading muon (index 0) for all events" << endl;
    cout << "          that contain at least three jets in a histogram with 100 bins," << endl;
    cout << "          ranging from 0 to 1000 GeV" << endl;
    cout << endl;
    cout << "Example: quickDraw ~/data vtx_n global_weight" << endl;
    cout << "         will draw vtx_n for all events in an automatically binned histogram " << endl;
    cout << "         The histogram weight will be taken from the leaf global_weight for each event" << endl;
    exit (1);
  }
  // Loop over all files in directory <path> and fill
  // root file names into list <filelist>
  Text_t   lpath[strlen(argv[1])+8];
  sprintf(lpath, "%s", argv[1]);
  Text_t * basepath  = gSystem->ExpandPathName(lpath); // delete it later...
  void   * dirhandle = gSystem->OpenDirectory(basepath);
  const Text_t * basename;
  if (gLogLevel)
    cout << "Reading file names from directory " << basepath << endl;
  TList  * filelist  = new TList;
  while ((basename = gSystem->GetDirEntry(dirhandle))) {
    // Skip non-ROOT files
    if (!strstr(basename, ".root")) 
      continue;
    Text_t * fullname = new Text_t[strlen(basepath)+strlen(basename)+2];
    strcpy(fullname, basepath);
    strcat(fullname, "/");
    strcat(fullname, basename);
    filelist->Add(new TObjString(fullname));
    delete fullname;
  }

  // check if we have read some files
  if (filelist->GetSize() < 1) {
    cerr << "ERR: No *.root files available in " << basepath << " Exiting. " << endl;
    exit(EXIT_FAILURE);
  }

  // Add all root files to a TChain
  if (gLogLevel)
    cout << "Adding files to TChain" << endl;

  TChain * chain = new TChain("ACSkimAnalysis/allData");
  TIter next(filelist);
  while (TObjString * obj = (TObjString *) next()) {
    chain->Add(obj->GetString());
    if (gLogLevel > 3)
      cout << "FILE: " << obj->GetString() << " added to TChain" << endl;
  }

  // Delete all filelist elements and the list itself
  // (They are not deleted automatically when the TList is deleted!!!)
  filelist->Delete();
  delete filelist;
  delete basepath;

  long int events_from_tree = chain->GetEntries();
  cout << "Found a total of " << events_from_tree << " events in chain" << endl;
  
  gROOT->SetBatch();
  TCanvas * c1 = new TCanvas();
  TFile * f  = new TFile("histo.root", "RECREATE");
  Int_t nbins = 200;
  double xmin = 0;
  double xmax = 1;
  if (argc == 7) {
    nbins = atoi(argv[4]);
    xmin = atof(argv[5]);
    xmax = atof(argv[6]);
  }
  TH1D * h1 = new TH1D("h1", argv[2], nbins, xmin, xmax);
  if (argc < 5) {
    h1->SetBit(TH1::kCanRebin);
  }

  const char * selection = "1.";
  if (argc >= 4)
    selection = argv[3];
  
  chain->Draw(Form("%s>>h1", argv[2]), selection);
  h1->Draw();
  c1->Print("histo.pdf");
  f->Write();
  f->Close();
  delete f;
  return 0;
}
Example #13
0
void browseStacks( bool makePictures=false, bool wait=true , bool addHistName = false, Double_t maxYScaleF = 1., 
                  bool logScale = false, bool setMinZero = true) {


  gStyle->SetOptTitle(0);

  bool keep2D=false;

  //fix the hNJet histos
  TList *list = gDirectory->GetList();
  TIterator *iter = list->MakeIterator();
  TObject *obj = 0;
  while(obj = iter->Next()) {
  
    if(TString(obj->GetName()).Contains("hnJet") && obj->InheritsFrom(TH1::Class())) {
      
      int nbins = ((TH1F*)obj)->GetNbinsX();
      float overflow = ((TH1F*)obj)->GetBinContent(nbins+1);
      float lastbinval = ((TH1F*)obj)->GetBinContent(nbins);
      ((TH1F*)obj)->SetBinContent(nbins, overflow+lastbinval);
      ((TH1F*)obj)->GetXaxis()->SetBinLabel(nbins, "#geq4");
    }
  }
  
    
    
    
  // Find out what the names of the existing histograms are
  // The histogram names are XX_YY_ZZ, where XX is the sample,
  // eg, "tt", YY is the actual name, ZZ is the final state, eg, "ee"
  TObjArray* myNames = getMyHistosNames("ttdil","ee",keep2D);
    

  // Now loop over histograms, and make stacks
  TCanvas *c = new TCanvas();
  c->Divide(2,2);
  char* suffix[4];
  suffix[0] = "ee";
  suffix[1] = "mm";
  suffix[2] = "em";
  suffix[3] = "all";
  if (makePictures) c->Print("out/stacks.ps[");
  for (int i=0; i<myNames->GetEntries(); i++) {
     
    for (int sample=0; sample<4; sample++) {
       
       
      hist::stack(Form("st_%s_%s",myNames->At(i)->GetName(),suffix[sample]),
		  Form("%s_%s$",myNames->At(i)->GetName(), suffix[sample]));
      THStack* thisStack = (THStack*) gROOT->FindObjectAny(
							   Form("st_%s_%s", myNames->At(i)->GetName(), suffix[sample]));
       
      thisStack->SetMaximum(thisStack->GetMaximum()*maxYScaleF);
      if(TString(myNames->At(i)->GetName()).Contains("hnJet")) {
	TList* histolist = thisStack->GetHists();
	int hatchcount = 0;
	// 	for(int j = 0; j<histolist->GetSize();j++) {
	// 	  if(TString(histolist->At(j)->GetName()).Contains("tt") ||
	// 	     TString(histolist->At(j)->GetName()).Contains("tautau") ||
	// 	     TString(histolist->At(j)->GetName()).Contains("ww") ) continue;
	// 	  hatch(histolist->At(j)->GetName(), FavoriteHatches[hatchcount]);
	// 	  hatchcount++;
	// 	}
      }
	 
	 
      TLegend* thisLeg = hist::legend(thisStack, "lpf", 0, 0, 0.75, 0.65, 0.99, 0.99);
      c->cd(sample+1);
      if (logScale) gPad->SetLogy(); else gPad->SetLogy(0);
      double stackMax = ((TH1*)thisStack->GetHists()->At(0))->GetMaximum();
      double stackMin = ((TH1*)thisStack->GetHists()->At(0))->GetMinimum();
      thisStack->SetMinimum(stackMin);
      if (setMinZero) thisStack->SetMinimum(0);
      if (logScale && stackMin <=0) thisStack->SetMinimum(1e-2*stackMax);
      if (logScale && stackMax == 0) thisStack->SetMinimum(1e-12); 
      thisStack->Draw("hist");
      string xtitle( ((TH1*)gROOT->FindObjectAny(Form("ttdil_%s_%s", myNames->At(i)->GetName(), suffix[sample])))->GetXaxis()->GetTitle());
      string ytitle( ((TH1*)gROOT->FindObjectAny(Form("ttdil_%s_%s", myNames->At(i)->GetName(), suffix[sample])))->GetYaxis()->GetTitle());
      thisStack->GetXaxis()->SetTitle(xtitle.c_str());
      thisStack->GetYaxis()->SetTitle(ytitle.c_str());
      TString hname = thisStack->GetName();
      if(hname.Contains("hnJet")) {
	thisStack->GetXaxis()->SetLabelSize(0.075);
	thisStack->GetYaxis()->SetLabelSize(0.05);
	thisStack->GetXaxis()->SetTitle("N_{jets}");
      }
      thisLeg->Draw();
	
      TPaveText *pt1 = new TPaveText(0.1, 0.95, 0.4, 0.999, "brNDC");
      pt1->SetName("pt1name");
      pt1->SetBorderSize(0);
      pt1->SetFillStyle(0);
	
      TText *blah;
      if (addHistName) blah = pt1->AddText(hname);
      else blah = pt1->AddText("CMS Preliminary");
      blah->SetTextSize(0.05);
      pt1->Draw();
      c->Modified();
	
      c->Update();
    }
    if (makePictures) {
      c->Print("out/stacks.ps");
      //       c->Print(Form("out/stacks_%d.png",i+1));
      //c->Print(Form("out/stacks_%s.png",myNames->At(i)->GetName()));
      c->Print(Form("out/stacks_%s.eps",myNames->At(i)->GetName()));
    }
    if (wait) {
      cout << "Enter carriage return for the next set of plots....q to quit" << endl;
      char in = getchar();
      if (in == 'q') break;
    }
  }
  if (makePictures) c->Print("out/stacks.ps]");
}
void new_TrackValHistoPublisher(const char* newFile="NEW_FILE",const char* refFile="REF_FILE") {

  cout << ">> Starting new_TrackValHistoPublisher(" 
       << newFile << "," << refFile << ")..." << endl;

  //====  To be replaced from python ====================
  
  const char* dataType = "DATATYPE";
  const char* refLabel("REF_LABEL, REF_RELEASE REFSELECTION");
  const char* newLabel("NEW_LABEL, NEW_RELEASE NEWSELECTION");


  // ==== Initial settings and loads
  gROOT ->SetBatch();
  gErrorIgnoreLevel = kWarning; // Get rid of the info messages
  SetGlobalStyle();

  // ==== Some cleaning... is this needed?  
  delete gROOT->GetListOfFiles()->FindObject(refFile);
  delete gROOT->GetListOfFiles()->FindObject(newFile); 
  
  // ==== Opening files, moving to the right branch and getting the list of sub-branches
  cout << ">> Opening files, moving to the right branch and getting the list of sub-branches..." << endl;

  cout << ">> Finding new DQM file ..." << endl;
  TFile * sfile = new TFile(newFile);
  TList* sl = GetListOfBranches(dataType, sfile);

  if (!sl) {
    cout << "ERROR: Could not find keys!!!" << endl;
    cerr << "ERROR: Could not find keys!!!" << endl;
    return;
  }
  TDirectory*  sdir  = gDirectory;

  if (DEBUG) {
    for (unsigned int i = 0; i < sl->GetEntries(); i++)
      cout << "   + " << sl->At(i)->GetName() << endl;
  }
  
  cout << ">> Finding reference DQM file ..." << endl;
  TFile * rfile = new TFile(refFile);
  TList* rl = GetListOfBranches(dataType, rfile);

  if (!rl) {
    cout << "ERROR: Could not find keys!!!" << endl;
    cerr << "ERROR: Could not find keys!!!" << endl;
    return;
  }
  TDirectory* rdir  = gDirectory;

  if (DEBUG) {
    for (unsigned int i = 0; i < rl->GetEntries(); i++)
      cout << "   + " << rl->At(i)->GetName() << endl;
  }

  //==== Iterate now over histograms and collections
  cout << ">> Iterating over histograms and collections..." << endl;

  bool logy[6]     = {false,  false,  false,  false,   false,  false  };
  bool logx[6]     = {false,  false,  false,  false,   false,  false  };
  bool doKolmo[6]  = {true,   true,   true,   true,    true,   true };
  Double_t norm[6] =  {-1.,-1.,-1.,-1.,-1.,-1.};  // initial default: do not normalize
  Double_t minx[6] = {0, 0, 0, 0, 0, 0};
  Double_t maxx[6] = {0, 0, 0, 0, 0, 0};
  Double_t miny[6] = {0, 0, 0, 0, 0, 0};
  Double_t maxy[6] = {0, 0, 0, 0, 0, 0};
  const char* drawopt[6] = {"", "", "", "", "", ""};
  TString plots[6]       = {"", "", "", "", "", ""};
  TString titles[6]      = {"", "", "", "", "", ""};

  TString rcollname;
  TString scollname;
  TIter iter_r( rl );
  TIter iter_s( sl );
  TString newDirBase("NEW_RELEASE/NEWSELECTION/NEW_LABEL/");
  TKey* rKey = 0;

  // before CMSSW_10_1_0_pre1 a few collection names were different
  bool NEWcollNames = false;
  TString Ref_CMSSW_Release("REF_RELEASE");
  if (Ref_CMSSW_Release.Contains("CMSSW_9") || Ref_CMSSW_Release.Contains("CMSSW_10_0")) NEWcollNames=true;

  while ( (rKey = (TKey*)iter_r()) ) {
    TString myName = rKey->GetName();
    rcollname = myName;
    if (DEBUG) {
      cout << " Checking collection: " << myName << endl;
      cerr << " Checking collection: " << myName << endl;
    }

    TString myName2 = myName;
    if (NEWcollNames) {
      if (myName=="NEWprobeTrks") myName2="probeTrks";
      else if (myName=="NEWprobeTrks_TkAsso") myName2="probeTrks_TkAsso";
      else if (myName=="NEWseedsOfSTAmuons") myName2="seedsOfSTAmuons";
      else if (myName=="NEWseedsOfDisplacedSTAmuons") myName2="seedsOfDisplacedSTAmuons";
      else if (myName=="NEWcutsRecoTrkMuons") myName2="cutsRecoTrkMuons";
      else if (myName=="NEWextractGemMuons") myName2="extractGemMuons";
      else if (myName=="NEWextractMe0Muons") myName2="extractMe0Muons";
    }
    scollname = myName2;
    
    if (DEBUG) {
      cout << " Comparing " << rcollname << " and " << scollname << endl;
      cerr << " Comparing " << rcollname << " and " << scollname << endl;
    }

    // ==== Now let's go for the plotting...
    TString newDir = newDirBase+myName2;
    cout<<"creating directory: "<<newDir<<endl;
    gSystem->mkdir(newDir,kTRUE);
   
    // efficiency and fake rate Vs eta and phi
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="effic_vs_eta"    ; titles[0]="Efficiency vs #eta";
    plots[1]="fakerate_vs_eta" ; titles[1]="Fake rate vs #eta" ;
    plots[2]="effic_vs_phi"    ; titles[2]="Efficiency vs #phi" ;
    plots[3]="fakerate_vs_phi" ; titles[3]="Fake rate vs #phi" ;
    
    miny[0]=-0.0001;
    miny[1]=-0.0001;
    miny[2]=-0.0001;
    miny[3]=-0.0001;
    
    maxy[0]=1.09;
    maxy[1]=0.;
    maxy[2]=1.09;
    maxy[3]=0.;
    
    Plot4Histograms(newDir + "/eff_eta_phi",
		    rdir, sdir, 
		    rcollname, scollname,
		    "eff_eta_phi", "Efficiency vs eta and Vs phi",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);     
    

    // efficiency and fake rate Vs pt
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="effic_vs_pt"    ; titles[0]="Efficiency vs pt";
    plots[1]="fakerate_vs_pt" ; titles[1]="Fake rate vs pt" ;
    plots[2]="num_simul_pT"   ; titles[2]="N of simulated tracks vs pt" ;
    plots[3]="num_reco_pT"    ; titles[3]="N of reco track vs pt" ;

    logx[0]=true;
    logx[1]=true;
    logx[2]=true;
    logx[3]=true;

    drawopt[0]="";
    drawopt[1]="";
    drawopt[2]="hist";
    drawopt[3]="hist";

    norm[0]= -1.;
    norm[1]= -1.;
    norm[2]= 2.;
    norm[3]= 2.;

    miny[0]= -0.0001;
    miny[1]= -0.0001;
    miny[2]= 0.;
    miny[3]= 0.;

    maxy[0]= 1.09;
    maxy[1]= 0.;
    maxy[2]= 0.;
    maxy[3]= 0.;

    Plot4Histograms(newDir + "/eff_pt",
		    rdir, sdir, 
		    rcollname, scollname,
		    "eff_pt", "Efficiency vs pt and sim,reco distributions",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);     
 

    // efficiency and fake rate vs Number of Hits; Hit multiplicity per track; Ave.N.hits vs eta
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="effic_vs_hit"      ; titles[0]="Efficiency vs Number of hits";
    plots[1]="fakerate_vs_hit"   ; titles[1]="Fake rate vs Number of hits" ;
    plots[2]="nhits"             ; titles[2]="number of hits per track" ;
    plots[3]="nhits_vs_eta_prof" ; titles[3]="mean number of Hits vs eta" ;

    drawopt[0]="";
    drawopt[1]="";
    drawopt[2]="hist";
    drawopt[3]="";

    norm[0]= -1.;
    norm[1]= -1.;
    norm[2]=  0.;
    norm[3]= -1.;

    miny[0]= -0.0001;
    miny[1]= -0.0001;
    miny[2]= 0.;
    miny[3]= 0.;

    maxy[0]= 1.09;
    maxy[1]= 0.;
    maxy[2]= 0.;
    maxy[3]= 0.;

    Plot4Histograms(newDir + "/eff_hits",
		    rdir, sdir, 
		    rcollname, scollname,
		    "eff_hits", "Efficiency vs Number of hits and hit multiplicity per track",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);
    
    // efficiency and fake rate vs PU
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="effic_vs_pu"      ; titles[0]="Efficiency vs n.PU interactions";
    plots[1]="fakerate_vs_pu"   ; titles[1]="Fake rate vs n.PU interactions" ;

    //maxx[0]= 100.;
    //maxx[1]= 100.;

    miny[0]= -0.0001;
    miny[1]=  0.;

    maxy[0]= 1.09;
    maxy[1]= 0.;

    Plot4Histograms(newDir + "/eff_pu",
		    rdir, sdir, 
		    rcollname, scollname,
		    "eff_pu", "Efficiency vs n.PU interactions",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);     
    
    // skip other plots for seeds
    if (!scollname.Contains("seeds")) {

    //===== normalized chi2, chi2 probability, ave. norm. chi2 vs eta; ave. pt bias vs eta
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="chi2"              ; titles[0]="Track #chi^{2}";
    plots[1]="chi2prob"          ; titles[1]="Probability of track #chi^{2}";
    plots[2]="chi2_vs_eta_prof"  ; titles[2]="Mean normalized #chi^{2} vs #eta" ;

    drawopt[0]="hist";
    drawopt[1]="hist";
    drawopt[2]="";

    norm[0]= -1.;
    norm[1]=  2.;
    norm[2]= -1.;

    logy[0]=true;
    logy[1]=false;
    logy[2]=false;
    
    Plot4Histograms(newDir + "/chi2",
		    rdir, sdir, 
		    rcollname, scollname,
		    "chi2", "chi2 distributions",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);
    
    //===== pull distributions
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="ptpull"     ; titles[0]="p_{T} Pull";
    plots[1]="qoverppull" ; titles[1]="q/p Pull" ;
    plots[2]="phipull"    ; titles[2]="#phi Pull" ;
    plots[3]="thetapull"  ; titles[3]="#theta Pull" ;
    plots[4]="dxypull"    ; titles[4]="dxy Pull" ;
    plots[5]="dzpull"     ; titles[5]="dz Pull" ;

    logy[0]=true;
    logy[1]=true;
    logy[2]=true;
    logy[3]=true;
    logy[4]=true;
    logy[5]=true;

    drawopt[0]="hist";
    drawopt[1]="hist";
    drawopt[2]="hist";
    drawopt[3]="hist";
    drawopt[4]="hist";
    drawopt[5]="hist";

    norm[0]= 2.;
    norm[1]= 2.;
    norm[2]= 2.;
    norm[3]= 2.;
    norm[4]= 2.;
    norm[5]= 2.;

    Plot6Histograms(newDir + "/pulls",
		    rdir, sdir, 
		    rcollname, scollname,
		    "pulls", "pull distributions",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);     
    
    
    //===== residual distributions (projected on Y-axis from the 2D histos with residuals vs eta)
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="ptres_vs_eta"       ; titles[0]="p_{T} Relative Residual";
    plots[1]="etares_vs_eta"      ; titles[1]="#eta Residual" ;
    plots[2]="phires_vs_eta"      ; titles[2]="#phi Residual" ;
    plots[3]="thetaCotres_vs_eta" ; titles[3]="cot(#theta) Residual" ;
    plots[4]="dxyres_vs_eta"      ; titles[4]="dxy Residual" ;
    plots[5]="dzres_vs_eta"       ; titles[5]="dz Residual" ;

    logy[0]=true;
    logy[1]=true;
    logy[2]=true;
    logy[3]=true;
    logy[4]=true;
    logy[5]=true;

    drawopt[0]="hist";
    drawopt[1]="hist";
    drawopt[2]="hist";
    drawopt[3]="hist";
    drawopt[4]="hist";
    drawopt[5]="hist";

    norm[0]= 2.;
    norm[1]= 2.;
    norm[2]= 2.;
    norm[3]= 2.;
    norm[4]= 2.;
    norm[5]= 2.;

    Plot6Histograms(newDir + "/residuals",
		    rdir, sdir, 
		    rcollname, scollname,
		    "residuals", "residual distributions",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);      
    
      
    //===== resolutions vs eta; pt relative bias vs eta
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="phires_vs_eta_Sigma"      ; titles[0]="width #phi Residual vs #eta";
    plots[1]="thetaCotres_vs_eta_Sigma" ; titles[1]="width cot(#theta) Residual vs #eta" ;
    plots[2]="dxyres_vs_eta_Sigma"      ; titles[2]="width dxy Residual vs #eta" ;
    plots[3]="dzres_vs_eta_Sigma"       ; titles[3]="width dz Residual vs #eta" ;
    plots[4]="ptres_vs_eta_Sigma"       ; titles[4]="width p_{T} Relative Residual vs #eta" ;
    plots[5]="ptres_vs_eta_Mean"        ; titles[5]="mean p_{T} Relative Residual vs #eta" ;

    logy[0]=true;
    logy[1]=true;
    logy[2]=true;
    logy[3]=true;
    logy[4]=true;
    logy[5]=false;
    
    Plot6Histograms(newDir + "/resol_eta",
		    rdir, sdir, 
		    rcollname, scollname,
		    "resol_eta", "resolutions vs eta",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);     

    //===== resolutions vs pt; pt relative bias vs eta
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="phires_vs_pt_Sigma"      ; titles[0]="width #phi Residual vs p_{T}";
    plots[1]="thetaCotres_vs_pt_Sigma" ; titles[1]="width cot(#theta) Residual vs p_{T}" ;
    plots[2]="dxyres_vs_pt_Sigma"      ; titles[2]="width dxy Residual vs p_{T}" ;
    plots[3]="dzres_vs_pt_Sigma"       ; titles[3]="width dz Residual vs p_{T}" ;
    plots[4]="ptres_vs_pt_Sigma"       ; titles[4]="width p_{T} Relative Residual vs p_{T}" ;
    plots[5]="ptres_vs_pt_Mean"        ; titles[5]="mean p_{T} Relative Residual vs p_{T}" ;

    logx[0]=true;
    logx[1]=true;
    logx[2]=true;
    logx[3]=true;
    logx[4]=true;
    logx[5]=true;

    logy[0]=true;
    logy[1]=true;
    logy[2]=true;
    logy[3]=true;
    logy[4]=true;
    logy[5]=false;
    
    Plot6Histograms(newDir + "/resol_pt",
		    rdir, sdir, 
		    rcollname, scollname,
		    "resol_pt", "resolutions vs pt",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);     
    

    // ================= charge misid rate vs eta, pt, n.hits, PU
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="chargeMisId_vs_eta" ; titles[0]="Charge MisId rate vs #eta";
    plots[1]="chargeMisId_vs_pt"  ; titles[1]="Charge MisID rate vs p_{T}" ;
    plots[2]="chargeMisId_vs_hit" ; titles[2]="Charge MisID rate vs number of RecHits" ;
    plots[3]="chargeMisId_vs_pu"  ; titles[3]="Charge MisID rate vs n.PU interactions" ;

    logx[0]=false;
    logx[1]=true;
    logx[2]=false;
    logx[3]=false;

    //maxx[0]= 0.;
    //maxx[1]= 0.;
    //maxx[2]= 0.;
    //maxx[3]= 100.;

    miny[0]= -0.0001;
    miny[1]=  0.;
    miny[2]= -0.0001;
    miny[3]=  0.;

    maxy[0]= 0.;
    maxy[1]= 0.;
    maxy[2]= 0.;
    maxy[3]= 0.;

    Plot4Histograms(newDir + "/chargeMisId",
		    rdir, sdir, 
		    rcollname, scollname,
		    "chargeMisId", "charge misId rate vs eta, pt, nhits, PU",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);     

    } // if (!scollname.Contains("seeds"))

    //// Merge pdf files together and rename the merged pdf after the collection name
    TString mergefile = "merged_plots.pdf"; // File name where partial pdfs will be merged
    TString destfile  = newDir + "/../" + myName + ".pdf"; // Destination file name
    TString gscommand = "gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="  + mergefile + " "
      + newDir + "/eff_eta_phi.pdf "
      + newDir + "/eff_pt.pdf "
      + newDir + "/eff_hits.pdf "
      + newDir + "/eff_pu.pdf "
      + newDir + "/chi2.pdf "
      + newDir + "/pulls.pdf "
      + newDir + "/residuals.pdf "
      + newDir + "/resol_eta.pdf "
      + newDir + "/resol_pt.pdf "
      + newDir + "/chargeMisId.pdf ";

    if (scollname.Contains("seeds"))
      gscommand = "gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="  + mergefile + " "
	+ newDir + "/eff_eta_phi.pdf "
	+ newDir + "/eff_pt.pdf "
	+ newDir + "/eff_hits.pdf "
	+ newDir + "/eff_pu.pdf ";
  
    cout << ">> Merging partial pdfs to " << mergefile << "..." << endl;
    if (DEBUG) cout << " ...with command \"" << gscommand << "\"" << endl;

    gSystem->Exec(gscommand);
    cout << ">> Moving " << mergefile << " to " << destfile << "..." << endl;
    gSystem->Rename(mergefile, destfile);

    cout << ">> Deleting partial pdf files" << endl;
    gSystem->Exec("rm -rf "+newDir+"/*.pdf"); 
    cout << "   ... Done" << endl;
    
    }  // end of "while loop"

  ///////////////////////////////////////////////////////////////////////////////
  // comparison plots of Muon and Track associators on the probeTracks

  TString dir_MABH_vs_TABH = newDirBase + "probeTrks_MABH_vs_TABH";
  gSystem->mkdir(dir_MABH_vs_TABH, kTRUE);

  // in case of HLT or HeavyIons skip the following
  TString new_Sample_Name("NEW_LABEL");

  if (TString(dataType) == "HLT" || new_Sample_Name.Contains("_HI")) {
    cout << ">> Removing the relval files from ROOT before closing..." << endl;
    gROOT->GetListOfFiles()->Remove(sfile);
    gROOT->GetListOfFiles()->Remove(rfile);

    if (DEBUG) {
      cout << " Exiting!" << endl;
      cerr << " Exiting!" << endl;
    }

    return;
  }

  if (DEBUG) {
    cout << " Comparing MuonAssociatorByHits with quickTrackAssociatorByHits on probeTracks (for the new release)" << endl;
    cerr << " Comparing MuonAssociatorByHits with quickTrackAssociatorByHits on probeTracks (for the new release)" << endl;
  }
  
  sfile->cd("DQMData/Run 1/Muons/Run summary/RecoMuonV/MuonTrack");
  sdir = gDirectory;
  rcollname = "probeTrks_TkAsso";
  scollname = "probeTrks";

  // for releases before CMSSW_10_1_0_pre1 and New Muon Validation
  TString New_CMSSW_Release("NEW_RELEASE");
  bool NEWprobeTrksNames = false;
  if (New_CMSSW_Release.Contains("CMSSW_9") || New_CMSSW_Release.Contains("CMSSW_10_0")) NEWprobeTrksNames=true;
  if (NEWprobeTrksNames) {
    rcollname = "NEWprobeTrks_TkAsso";
    scollname = "NEWprobeTrks";
  }

  const char* _refLabel("NEW_LABEL, NEW_RELEASE NEWSELECTION quickTrackAssociatorByHits");
  const char* _newLabel("NEW_LABEL, NEW_RELEASE NEWSELECTION MuonAssociatorByHits");

  // efficiency and fake rate Vs eta and phi
  plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
  plots[0]="effic_vs_eta"    ; titles[0]="Efficiency vs #eta";
  plots[1]="fakerate_vs_eta" ; titles[1]="Fake rate vs #eta" ;
  plots[2]="effic_vs_pt"     ; titles[2]="Efficiency vs pt" ;
  plots[3]="fakerate_vs_pt"  ; titles[3]="Fake rate vs pt" ;

  logx[0]=false;
  logx[1]=false;
  logx[2]=true;
  logx[3]=true;

  miny[0]=-0.0001;
  miny[1]=-0.0001;
  miny[2]=-0.0001;
  miny[3]=-0.0001;
  
  maxy[0]=1.09;
  maxy[1]=0.;
  maxy[2]=1.09;
  maxy[3]=0.;

  Plot4Histograms(dir_MABH_vs_TABH + "/eff_pt_eta",
		  sdir, sdir,
		  rcollname, scollname,
		  "eff_pt_eta_MABHvsTABH", "Efficiency vs eta and pt - Muon vs Track Associator",
		  _refLabel, _newLabel,
		  plots, titles, drawopt,
		  logy, logx, doKolmo, norm, minx, maxx, miny, maxy);

  // efficiency and fake rate Vs N.hits and phi
  plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
  plots[0]="effic_vs_hit"    ; titles[0]="Efficiency vs Number of hits";
  plots[1]="fakerate_vs_hit" ; titles[1]="Fake rate vs Number of hits" ;
  plots[2]="effic_vs_phi"    ; titles[2]="Efficiency vs #phi" ;
  plots[3]="fakerate_vs_phi" ; titles[3]="Fake rate vs #phi" ;

  miny[0]=-0.0001;
  miny[1]=-0.0001;
  miny[2]=-0.0001;
  miny[3]=-0.0001;
  
  maxy[0]=1.09;
  maxy[1]=0.;
  maxy[2]=1.09;
  maxy[3]=0.;
  
  Plot4Histograms(dir_MABH_vs_TABH + "/eff_phi_hits",
		  sdir, sdir,
		  rcollname, scollname,
		  "eff_phi_hits_MABHvsTABH", "Efficiency vs phi and N. hits - Muon vs Track Associator",
		  _refLabel, _newLabel,
		  plots, titles, drawopt,
		  logy, logx, doKolmo, norm, minx, maxx, miny, maxy);
  
  // efficiency and fake rate Vs PU
  plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
  plots[0]="effic_vs_pu"    ; titles[0]="Efficiency vs n.PU interactions";
  plots[1]="fakerate_vs_pu" ; titles[1]="Fake rate vs  n.PU interactions" ;
  
  //maxx[0]= 100.;
  //maxx[1]= 100.;
  
  miny[0]= -0.0001;
  miny[1]=  0.;
  
  maxy[0]= 1.09;
  maxy[1]= 0.;
  
  PlotNHistograms(dir_MABH_vs_TABH + "/eff_pu",
		  sdir, sdir,
		  rcollname, scollname,
		  "eff_pu_MABHvsTABH", "Efficiency vs N.PU interactions - Muon vs Track Associator",
		  _refLabel, _newLabel,
		  4, plots, titles, drawopt,
		  logy, logx, doKolmo, norm, minx, maxx, miny, maxy);
  
  //// Merge pdf files together and rename the merged pdf after the 
  TString _destfile  = newDirBase + "probeTrks_MABH_vs_TABH" + ".pdf"; // Destination file name
  TString _gscommand = "gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="  + _destfile + " "
    + dir_MABH_vs_TABH + "/eff_pt_eta.pdf "
    + dir_MABH_vs_TABH + "/eff_phi_hits.pdf "
    + dir_MABH_vs_TABH + "/eff_pu.pdf ";
  
  cout << ">> Merging partial pdfs to " << _destfile << "..." << endl;
  if (DEBUG) cout << " ...with command \"" << _gscommand << "\"" << endl;
  gSystem->Exec(_gscommand);
  
  cout << ">> Deleting partial pdf files" << endl;
  gSystem->Exec("rm -rf "+ dir_MABH_vs_TABH +"/eff_*.pdf"); 
  cout << "   ... Done" << endl;
  
  cout << ">> Removing the relval files from ROOT before closing..." << endl;
  gROOT->GetListOfFiles()->Remove(sfile);
  gROOT->GetListOfFiles()->Remove(rfile);
  
  if (DEBUG) {
    cout << " Exiting!" << endl;
    cerr << " Exiting!" << endl;
  }
}
Example #15
0
void qaitsAddMetadata(TTree*tree, Int_t verbose){
  //
  // Set metadata infomation 
  //
  if (tree==NULL) {
    ::Error("qaitsAddMetadata","Start processing. Emtpy tree");
    return;
  }
  ::Info("qaitsAddMetadata","Start processing Tree %s",tree->GetName());
  TObjArray * branches=tree->GetListOfBranches();
  // Clasigication of variables
  //   regular expression to defined automaticaly some variables following naming conventions - used to define classes/Axis/legends 
  //           default description
  //   regular expression used can be tested on site https://regex101.com/
  //           hovewer root (perl)  regular expression looks to be in some cases different - in some case double escape had to be used
  //           e.g to math c.  expression c\\. has to be used
  //   variables
  const TString kineVariableClass[11]={"X", "Y","Z", "Phi", "Theta", "Pt", "QOverPt"};
  const TString kineVariableAxisTitle[11]={"x(cm)", "y(cm)","z(cm)", "#phi", "#Theta", "p_{T}", "q/p_{T}(c/GeV)"};
  const TString kineVariableLegend[11]={"x", "y","z", "#phi", "#Theta", "p_{T}", "q/p_{T}"};
  const TString kineVariableTitle[11]={"x", "y","z", "#phi", "#Theta", "p_{T}", "q/p_{T}"};
  TPRegexp regKineVariables[11];
  regKineVariables[0]=TPRegexp("^x|x$");               // X - varaible begining on X
  regKineVariables[1]=TPRegexp("(^y|^infoy|y$)");      // Y - 
  regKineVariables[2]=TPRegexp("(^z|^infoz|z$)");      // Z
  regKineVariables[3]=TPRegexp("(phi|infophi)");              // phi
  regKineVariables[4]=TPRegexp("(theta|lambda|infolambda)");   // theta
  regKineVariables[5]=TPRegexp("(^pt)");           // pt
  regKineVariables[6]=TPRegexp("qoverpt");          // qoverPt
  //
  //   QA variables  
  const TString qaVariableClass[11]={"Frac", "$","dEdx","ChargeRatio"};
  const TString qaVariableAxisTitle[11]={"Frac","$","dEdx","ChargeRatio"};
  const TString qaVariableLegend[11]={"Frac","$","dEdx","ChargeRatio"};
  const TString qaVariableTitle[11]={"Frac","$","dEdx","ChargeRatio"};
  TPRegexp regQAVariable[11];
  regQAVariable[0]=TPRegexp("frac");              // Frac
  regQAVariable[1]=TPRegexp("(eff[0-9]|effone|^eff)");          // eff layer?
  regQAVariable[2]=TPRegexp("(mpv|dedx)");         // dEdx 
  regQAVariable[3]=TPRegexp("chargeratio");        // ChargeRatio

 
  //
  // statistic
  //
  const TString statClass[10]={"Constrain", "Mean","Delta","Median", "RMS","Pull", "Err","Chi2", "StatInfo[]","FitInfo[]"};
  const TString statAxisTitle[10]={"Constrain", "mean","#Delta","med.", "rms","pull", "#sigma"," #chi2","stat[]","fit[]"};
  const TString statTitle[10]={"Constrain", "mean","#Delta","med.", "rms","pull", "#sigma"," #chi2","stat[]","fit[]" };
  TPRegexp regStat[10];
  regStat[0]=TPRegexp("constrain");        // constrain
  regStat[1]=TPRegexp("^mean");            // mean
  regStat[2]=TPRegexp("^delta");           // delta
  regStat[3]=TPRegexp("^median");          // median variable
  regStat[4]=TPRegexp("(^rms|resolution|sigma)");// rms resolution        
  regStat[5]=TPRegexp("pull");             // pull
  regStat[6]=TPRegexp("err");              // error
  regStat[7]=TPRegexp("chi2");             // chi2
  regStat[8]=TPRegexp("^info");            // stat info array 
  regStat[9]=TPRegexp("^fit");             // fit info  array
  //
  // 
  const TString categoryClass[10]={"Vertex","$1","$1"};
  const TString categoryLegend[10]={"Vertex","$1","$1"};
  const TString categoryTitle[10]={"Vertex","$1","$1"};
  TPRegexp regCategory[10];   // proper parsing of layer numbers to be added
  regCategory[0]=TPRegexp("(vertex|vtx)");             //
  regCategory[1]=TPRegexp("s(p|d|d)d[0-2]?");    // reg.exp match silical layers+number 
  regCategory[2]=TPRegexp("pt[0-9]+");         // pt bin
  


  for (Int_t ibr=0; ibr<branches->GetEntriesFast(); ibr++){
    TBranch * branch = (TBranch*)branches->At(ibr);
    TString matchClass="";   // class match
    TString brClass="";
    TString brAxisTitle="";
    TString brTitle="";
    TString brLegend="";
    //
    TString brNameCase(branches->At(ibr)->GetName());
    brNameCase.ToLower();
    //
    // define met
    brClass="ITS";
    brAxisTitle="";
    // stat
    for (Int_t ivar=0; ivar<11; ivar++) if  (brNameCase.Contains( regStat[ivar])) { 
      brClass+=" "+statClass[ivar];
      brTitle+=statTitle[ivar];
    }
    // kine variables
    for (Int_t ivar=0; ivar<7; ivar++) if  (brNameCase.Contains( regKineVariables[ivar])) {
      brClass+=" "+kineVariableClass[ivar];      
      brAxisTitle+=" "+kineVariableAxisTitle[ivar];
      brTitle+=" "+kineVariableTitle[ivar];
      brLegend+=" "+kineVariableLegend[ivar];
    }
    // QA variables
    for (Int_t ivar=0; ivar<5; ivar++) if  (brNameCase.Contains( regQAVariable[ivar])) {
      if ( qaVariableClass[ivar].Contains("$")==kFALSE){
	brClass+=" "+ qaVariableClass[ivar];
	brLegend+=" "+ qaVariableLegend[ivar];
	brTitle+=" "+ qaVariableTitle[ivar];
      }else{
	TObjArray *amatch=regQAVariable[ivar].MatchS(brNameCase);
	if (amatch){
	  TString match=amatch->At(0)->GetName();
	  brClass+=" "+match;
	  brLegend+=" "+match;
	  brTitle+=" "+match;
	}
      }
    }
    // category
    for (Int_t ivar=0; ivar<3; ivar++) if  (brNameCase.Contains(regCategory[ivar])) {
      if (categoryClass[ivar].Contains("$")==kFALSE){
	brClass+=" "+categoryClass[ivar];
	brLegend+=" "+categoryLegend[ivar];
	brTitle+=" "+categoryTitle[ivar];
      }else{
	TObjArray *amatch=regCategory[ivar].MatchS(brNameCase);
	if (amatch){
	  TString match=amatch->At(0)->GetName();
	  brClass+=" "+match;
	  brLegend+=" "+match;
	  brTitle+=" "+match;
	}
      }
    }
    if (branch!=NULL && branch->GetClassName()!=NULL && strlen(branch->GetClassName())>0){
      brClass+=" Class:";
      brClass+=branch->GetClassName();
    }
    
    //
    TStatToolkit::AddMetadata(tree,TString::Format("%s.Description",branches->At(ibr)->GetName()).Data(),
			      TString::Format("ITS standard QA variables.  Class %s", brClass.Data()).Data());
    TStatToolkit::AddMetadata(tree,TString::Format("%s.class",branches->At(ibr)->GetName()).Data(),brClass.Data());    
    TStatToolkit::AddMetadata(tree,TString::Format("%s.AxisTitle",branches->At(ibr)->GetName()).Data(),brAxisTitle.Data());    
    TStatToolkit::AddMetadata(tree,TString::Format("%s.Title",branches->At(ibr)->GetName()).Data(),brTitle.Data());    
    TStatToolkit::AddMetadata(tree,TString::Format("%s.Legend",branches->At(ibr)->GetName()).Data(),brLegend.Data());    
    if (verbose&4) printf("Class %s: \t%s\n", branches->At(ibr)->GetName(),brClass.Data());
    if (verbose&8) printf("Axis title %s: \t%s\n", branches->At(ibr)->GetName(),brAxisTitle.Data());
    if (verbose&16) printf("Title %s: \t%s\n", branches->At(ibr)->GetName(),brTitle.Data());
    if (verbose&32) printf("Legend %s: \t%s\n", branches->At(ibr)->GetName(),brLegend.Data());

    
  }

  // Fill Based and  custom metadata
  //
  // Index
  TStatToolkit::AddMetadata(tree,"run.class","Base Index");
  TStatToolkit::AddMetadata(tree,"run.Title","run");
  TStatToolkit::AddMetadata(tree,"run.AxisTitle","run");
  //
  TList * mlist = (TList*)(tree->GetUserInfo()->FindObject("metaTable"));
  mlist->Sort();
  if ((verbose&1)>0){
    mlist->Print();
  }
  if ((verbose&2)>0){
    AliTreePlayer::selectMetadata(tree, "[class==\"\"]",0)->Print();
  }
  ::Info("qaitsAddMetadata","End");

}
void plotGJetsScaleFactorSystematics(string label) {

  TFile *inf = new TFile(Form("data/ScaleFactors/RazorMADD2015/RazorScaleFactors_%s.root",label.c_str()),"READ");

  TH2Poly *ttbarNominal = (TH2Poly*)inf->Get("TTJetsScaleFactors");
  TH2Poly *ttbarUp = (TH2Poly*)inf->Get("TTJetsScaleFactorsUp");
  TH2Poly *ttbarDown = (TH2Poly*)inf->Get("TTJetsScaleFactorsDown");
  TH2Poly *wNominal = (TH2Poly*)inf->Get("WJetsScaleFactors");
  TH2Poly *wUp = (TH2Poly*)inf->Get("WJetsScaleFactorsUp");
  TH2Poly *wDown = (TH2Poly*)inf->Get("WJetsScaleFactorsDown");
  TH2Poly *wInvNominal = (TH2Poly*)inf->Get("WJetsInvScaleFactors");
  TH2Poly *wInvUp = (TH2Poly*)inf->Get("WJetsInvScaleFactorsUp");
  TH2Poly *wInvDown = (TH2Poly*)inf->Get("WJetsInvScaleFactorsDown");
  TH2Poly *GJetInvNominal = (TH2Poly*)inf->Get("GJetsInvScaleFactors");

  TCanvas *cv = 0;
  gStyle->SetPaintTextFormat("4.2f");

  //****************************************************
  //Systematic Uncertainty and GJets Down SF Histogram
  //****************************************************
  TH2Poly *GJetsSystematicUnc = (TH2Poly*)GJetInvNominal->Clone("GJetsSystematicUnc");
  TH2Poly *GJetsScaleFactor_Down = (TH2Poly*)GJetInvNominal->Clone("GJetsInvScaleFactors_Down");

  //Get bins of each histogram
  TList *wInvBins = wInvNominal->GetBins();
  TList *gInvBins = GJetInvNominal->GetBins();

  //Loop over GJets bins
  TH2PolyBin *gBin, *wBin; //temp variables to hold bin info
  for (int i = 1; i < GJetsSystematicUnc->GetNumberOfBins()+1; ++i) {

      //Get GJets bin
      gBin = (TH2PolyBin*)gInvBins->At(i-1);

      cout << "In bin " << i << " of GJets histogram" << endl;
      //cout << gBin->GetXMin() << " " << gBin->GetXMax() << " " << gBin->GetYMin() << " " << gBin->GetYMax() << endl;

      //Find out which WJets bin we are in
      int wBinNum = -1;
      for (int j = 1; j < wInvNominal->GetNumberOfBins()+1; ++j) {

          //Get WJets bin
          wBin = (TH2PolyBin*)wInvBins->At(j-1);

          //cout << "In bin " << j << " of WJets histogram" << endl;
          //cout << wBin->GetXMin() << " " << wBin->GetXMax() << " " << wBin->GetYMin() << " " << wBin->GetYMax() << endl;

          //Check if this GJets bin is inside this WJets bin
          if ( gBin->GetXMin() >= wBin->GetXMin() &&
               gBin->GetXMax() <= wBin->GetXMax() &&
               gBin->GetYMin() >= wBin->GetYMin() &&
               gBin->GetYMax() <= wBin->GetYMax() ) {
              cout << "This GJets bin is inside bin " << j << " of WJets histogram" << endl;
              wBinNum = j;
              break;
          }
      }

      double gjet = GJetInvNominal->GetBinContent(i);
      double wjet = wInvNominal->GetBinContent(wBinNum);

      //Set bin content of each histogram
      GJetsSystematicUnc->SetBinContent(i, (gjet - wjet)/gjet );
      GJetsScaleFactor_Down->SetBinContent(i, gjet - (wjet - gjet) );

      cout << "Bin " << i << " : " << gjet << " , " << wjet << " , " <<  gjet - (wjet - gjet) << "\n";
  }

  cv = new TCanvas("cv","cv", 800,600);
  gStyle->SetPalette(1);
  GJetsSystematicUnc->Draw("colztext");
  cv->SetLogx();
  cv->SetLogy();
  cv->SetRightMargin(0.175);
  cv->SetBottomMargin(0.12);
  GJetsSystematicUnc->GetXaxis()->SetRangeUser(400,4000);
  GJetsSystematicUnc->GetYaxis()->SetRangeUser(0.25,1.5);
  GJetsSystematicUnc->GetZaxis()->SetTitle("Systematic Uncertainty");
  GJetsSystematicUnc->GetXaxis()->SetTitle("M_{R} [GeV/c^{2}]");
  GJetsSystematicUnc->GetYaxis()->SetTitle("R^{2}");
  GJetsSystematicUnc->SetTitle("");
  GJetsSystematicUnc->GetZaxis()->SetLabelSize(0.05);
  GJetsSystematicUnc->GetZaxis()->SetTitleSize(0.05);
  GJetsSystematicUnc->GetXaxis()->SetLabelSize(0.05);
  GJetsSystematicUnc->GetXaxis()->SetTitleSize(0.05);
  GJetsSystematicUnc->GetXaxis()->SetTitleOffset(0.8);
  GJetsSystematicUnc->GetYaxis()->SetLabelSize(0.05);
  GJetsSystematicUnc->GetYaxis()->SetTitleSize(0.05);
  GJetsSystematicUnc->GetYaxis()->SetTitleOffset(0.8);
  GJetsSystematicUnc->SetStats(false);
  GJetsSystematicUnc->SetMaximum(1.0);
  GJetsSystematicUnc->SetMinimum(-1.0);

  lumi_13TeV = "35.9 fb^{-1}";
  writeExtraText = true;
  relPosX = 0.13;
  lumiTextSize = 0.5;
  cmsTextSize = 0.6;
  extraOverCmsTextSize = 0.85;
  CMS_lumi(cv,4,0);
  cv->SaveAs(Form("GJetsVsWJetsSystematic_%s.png",label.c_str()));
  cv->SaveAs(Form("GJetsVsWJetsSystematic_%s.pdf",label.c_str()));

  TFile *outf = new TFile(Form("data/ScaleFactors/RazorMADD2015/RazorScaleFactors_%s.root",label.c_str()),"UPDATE");
  outf->WriteTObject(GJetsScaleFactor_Down, GJetsScaleFactor_Down->GetName(), "WRITEDELETE");
  outf->Close();

}
void Overlap2D()
{

	gROOT->SetStyle ("Plain");
	gStyle->SetPalette (1);
	gStyle->SetTextFont(22) ;
	gStyle->SetTitleFont(22,"xyz") ;
	gStyle->SetLabelFont(22,"xyz") ;
	setTDRStyle();

	vector <string> titles;
	//TTrees
	TList *FileList;
	TFile *Target;
	titles.clear();
	int np=1;
	Float_t value=0;
	vector<float> xsecs_;
	signal_names.clear();
	ifstream ifs("datasets2D_C1N2");
	string line;
	while(std::getline(ifs, line)) // read one line from ifs
	{
		istringstream iss(line); // access line as a stream
		string dataname;
		float XSec;	
		float xs,fact,fact2;
		xs=0;fact=1;fact2=1;
		iss >> dataname >> xs >> fact >> fact2;
		titles.push_back(dataname+"_B.root");
		XSec= xs*fact*fact2;
		cout<<" Found the correct cross section "<<xs<<" for Dataset "<<dataname<<" XSec "<<XSec<<"  "<<fact<<"  "<<fact2<<endl;
		xsecs_.push_back(XSec);
	}

	//string fout = "mergedplotsTau.root";

	FileList = new TList ();


	for (unsigned int i=0; i <titles.size();++i){
		//string ext=".root";
		cout<<" loading dataset "<<titles[i]<<endl;
		//string file=titles[i]+".root";
		string file=titles[i];
		FileList->Add (TFile::Open (file.c_str()));

	}

	string sign_="C1";
	string sign2_="stau";
	string n_;
	//signal_names.clear();
	for (unsigned int k=0; k<titles.size();k++)
	{
		if (   std::string::npos != titles[k].find(sign_) ||  std::string::npos != titles[k].find(sign2_)){
			n_ = titles[k];
			n_.erase(n_.length()-5);
			//string nn_ = n_+"_out.root";
			signal_names.push_back(n_.c_str());
			signalnames[k] = n_.c_str();
		}
	}

	//return;
	//Target = TFile::Open (fout.c_str (), "RECREATE");

	string np_title = titles[0];
	vector <string>  variables;
	variables.push_back("met_MT_17");
	variables.push_back("met_MTsum_17");
	variables.push_back("met_MTtot_17");
	variables.push_back("met_MCTb_17");
	variables.push_back("met_MT2lester_17");
	variables.push_back("met_TauPt_17");
	variables.push_back("met_DZeta_17");

	variables.push_back("MT_MTsum_17");
	variables.push_back("MT_MTtot_17");
	variables.push_back("MT_MCTb_17");
	variables.push_back("MT_MT2lester_17");
	variables.push_back("MT_TauPt_17");
	variables.push_back("MT_DZeta_17");

	variables.push_back("MTsum_MTtot_17");
	variables.push_back("MTsum_MCTb_17");
	variables.push_back("MTsum_MT2lester_17");
	variables.push_back("MTsum_TauPt_17");
	variables.push_back("MTsum_DZeta_17");

	variables.push_back("MTtot_MCTb_17");
	variables.push_back("MTtot_MT2lester_17");
	variables.push_back("MTtot_TauPt_17");
	variables.push_back("MTtot_DZeta_17");

	variables.push_back("MCTb_MT2lester_17");
	variables.push_back("MCTb_TauPt_17");
	variables.push_back("MCTb_DZeta_17");

	variables.push_back("MT2lester_TauPt_17");
	variables.push_back("MT2lester_DZeta_17");
	variables.push_back("MTauPt_DZeta_17");



	for (int vr=0;vr<variables.size();vr++){

	variable=variables[vr].c_str();

	cout<< " the variable name  "<<variable<<endl;
	Impose (FileList, np_title,titles,xsecs_, variable);
	}
	delete FileList;
	delete Target;
}
void test_counting_experiment() {

//////////////////////   MODEL BUILDING    /////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/*
N_s = N_tot_theory(Mass,Xsec) * Acceptance_SR * Eff_AmBe_bin_i * mu
N_b = N_Co_SR_bin_i * Norm_factor

Xesec: considered 10^-40 cm^2
Norm_factor = N_Data_CR / N_Co_CR   --> assuming no difference between Co and Data in CR and SR.
N_tot_theory(Mass,Xsec): for 225 livedays, 45kg and considering Xsec. It is a constant, no uncertainty at the moment.

---Costraint Signal
   nuissance parameter = Acceptance_SR, Eff_AmBe_bin_i
   Gauss(Acceptance_SR_obs | Acceptance_SR, err.)
   Poisson(S0_i | S_tot_SR  * Eff_AmBe_bin_i)
   
---Costraint Bkg
   nuissance parameter = N_Co_SR_bin_i, Norm_factor
   Gauss(Norm_factor_obs |  Norm_factor, err)
   Poisson(B0_i | N_Co_SR_bin_i)

---- WARNING:: convergence problems: mu_hat should always be >> 1, too small values have problem in finding minimum
	because mu is set >0. ---> Try to fix Xsec in order to have mu_hat ~ 10

*/

  RooWorkspace w("w");

  //gROOT->ProcessLine(".L retrieve_input_from_histo_NoSys.C+");
  gROOT->ProcessLine(".L retrieve_input_from_histo.C+");

  retrieve_input_from_histo(w);


// Building the model
   ModelConfig mc("ModelConfig",&w);
   mc.SetPdf(*w.pdf("model"));
   mc.SetParametersOfInterest(*w.var("mu"));

// Setting nuissance parameter
   mc.SetNuisanceParameters(*w.set("nuissance_parameter"));

// need now to set the global observable
   mc.SetGlobalObservables(*w.set("g_observables"));

   mc.SetObservables(*w.set("observables"));

// this is needed for the hypothesis tests
   mc.SetSnapshot(*w.var("mu"));


// make data set with the number of observed events
   RooDataSet data("data","", *w.set("observables"));
   data.add(*w.set("observables"));

// import data set in workspace and save it in a file
   w.import(data);

// import model in the workspace 
   w.import(mc);

   w.writeToFile("CountingModel.root", true);




w.Print();

data.Print();

/* 
cout << w.var("S_i")->getValV() << endl;//<< "   "   <<  w.var("S_i_exp")->getValV() << endl;
///////////////////////////////////////////////////////////////////////
ProfileLikelihoodCalculator pl(data,mc);
  pl.SetConfidenceLevel(0.95);
  LikelihoodInterval* interval = pl.GetInterval();

   // find the iterval on the first Parameter of Interest
  RooRealVar* firstPOI = (RooRealVar*) mc.GetParametersOfInterest()->first();

  double lowerLimit = interval->LowerLimit(*firstPOI);
  double upperLimit = interval->UpperLimit(*firstPOI);


  cout << "\n95% interval on " <<firstPOI->GetName()<<" is : ["<<
    lowerLimit << ", "<<
    upperLimit <<"] "<<endl;


  LikelihoodIntervalPlot * plot = new LikelihoodIntervalPlot(interval);
//  plot->SetRange(0,50);  // possible eventually to change ranges
  //plot->SetNPoints(50);  // do not use too many points, it could become very slow for some models
  plot->Draw("");  // use option TF1 if too slow (plot.Draw("tf1")

*/




//////////////////////////  hypo test 
  // get the modelConfig (S+B) out of the file
  // and create the B model from the S+B model
  ModelConfig * sbModel = (ModelConfig*) mc.Clone();
  sbModel->SetName("S+B Model");      
  RooRealVar* poi = (RooRealVar*) sbModel->GetParametersOfInterest()->first();
  poi->setVal(1);  // set POI snapshot in S+B model for expected significance
  sbModel->SetSnapshot(*poi);
  ModelConfig * bModel = (ModelConfig*) mc.Clone();
  bModel->SetName("B Model");      
  RooRealVar* poi2 = (RooRealVar*) bModel->GetParametersOfInterest()->first();
  poi2->setVal(0);
  bModel->SetSnapshot( *poi2  );

//------------------Limit calculation for N_th event expected = 10


	  AsymptoticCalculator  ac(data, *bModel, *sbModel);
	  //ac.SetOneSidedDiscovery(true);  // for one-side discovery test
//	  ac.SetOneSided(true);  // for one-side tests (limits)
	    ac.SetQTilde(true);
	  ac.SetPrintLevel(2);  // to suppress print level 


	// create hypotest inverter 
	  // passing the desired calculator 
	  HypoTestInverter *calc = new HypoTestInverter(ac);    // for asymptotic 
	  //HypoTestInverter calc(fc);  // for frequentist

	  calc->SetConfidenceLevel(0.90);
	  //calc->UseCLs(false);
	  calc->UseCLs(true);
	  int npoints = 500;  // number of points to scan
	  //int npoints = 1000;  // number of points to scan default 1000
	  // min and max (better to choose smaller intervals)
	  double poimin = poi->getMin();
	  double poimax = poi->getMax();
	  //poimin = 0; poimax=10;

	  std::cout << "Doing a fixed scan  in interval : " << poimin << " , " << poimax << std::endl;
	  calc->SetFixedScan(npoints,poimin,poimax);
 	  calc->SetVerbose(2); 
	  HypoTestInverterResult * r = calc->GetInterval();

	  double upperLimit = r->UpperLimit();

	  std::cout << "The computed Expected upper limit is: " <<  r->GetExpectedUpperLimit(0) << std::endl;

//------------ Getting the interval as function of m --------------//
/*   ifstream in;
   in.open("integral_mass.dat");
   

  vector <double> masses_v;
  vector <double> observed_v;
  vector <double> expected_v;
  vector <double> expected_gaud_v;
  vector <double> expected_S1_up_v;
  vector <double> expected_S1_dw_v;
  vector <double> expected_S2_up_v;
  vector <double> expected_S2_dw_v;

  double mass_itr =0.;
  double Nev_exp_th_itr =0.;
  double xsec_modifier = 10.;
  double N_tot_theory = w.var("N_tot_theory")->getValV();

  while(mass_itr <1000.){
	in >> mass_itr;
	in >> Nev_exp_th_itr;

 	
	xsec_modifier = Nev_exp_th_itr * 225.009 * 34.;  //225.009 livedays and 34 kg and 10^-40 cm2 Xsec.

	masses_v.push_back(mass_itr);
	observed_v.push_back( 1.e-40  * N_tot_theory / xsec_modifier * upperLimit );
	expected_v.push_back( 1.e-40  * N_tot_theory / xsec_modifier * r->GetExpectedUpperLimit(0) );
	expected_gaud_v.push_back(7e-38 *  1.37590955945e-05 / Nev_exp_th_itr );
	expected_S1_up_v.push_back(1.e-40  * N_tot_theory / xsec_modifier * r->GetExpectedUpperLimit(1));
	expected_S2_up_v.push_back(1.e-40  * N_tot_theory / xsec_modifier * r->GetExpectedUpperLimit(2));
	expected_S2_dw_v.push_back(1.e-40  * N_tot_theory / xsec_modifier * r->GetExpectedUpperLimit(-2));
	expected_S1_dw_v.push_back(1.e-40  * N_tot_theory / xsec_modifier * r->GetExpectedUpperLimit(-1));

	cout << "Expected median limit for mass " << mass_itr << " GeV  = " << 1.e-40  * N_tot_theory / xsec_modifier * r->GetExpectedUpperLimit(0) << " cm^2 " << endl;
	
//	observed_v.push_back( w.var("Xsec")->getValV() *  w.var("K_m")->getValV()* upperLimit );
//	expected_v.push_back( w.var("Xsec")->getValV() * w.var("K_m")->getValV()* r->GetExpectedUpperLimit(0) );
//	expected_S1_up_v.push_back(w.var("Xsec")->getValV() * w.var("K_m")->getValV()* r->GetExpectedUpperLimit(1));
//	expected_S2_up_v.push_back(w.var("Xsec")->getValV() * w.var("K_m")->getValV()* r->GetExpectedUpperLimit(2));
//	expected_S2_dw_v.push_back(w.var("Xsec")->getValV() * w.var("K_m")->getValV()* r->GetExpectedUpperLimit(-2));
//	expected_S1_dw_v.push_back(w.var("Xsec")->getValV() * w.var("K_m")->getValV()* r->GetExpectedUpperLimit(-1));


   }


in.close();

const int n = masses_v.size();
double xe[n];
double mA[n];
double observed[n];
double expected[n];
double expected_gaudenz[n];
double exSigma1_l[n];
double exSigma1_u[n];
double exSigma2_l[n];
double exSigma2_u[n];

for(int k=0; k< n; k++){

	mA[k] = masses_v[k];
	observed[k] = observed_v[k];
	expected[k] = expected_v[k];
	expected_gaudenz[k] = expected_gaud_v[k];
	exSigma1_l[k] =expected_v[k] -  expected_S1_dw_v[k] ;
 	exSigma1_u[k] = expected_S1_up_v[k] - expected_v[k];
	exSigma2_l[k] = expected_v[k] - expected_S2_dw_v[k];
	exSigma2_u[k] = expected_S2_up_v[k] - expected_v[k] ;
}

TGraphErrors *obs_limits = new TGraphErrors(n, mA, observed);
TGraphErrors *Exp_limits = new TGraphErrors(n, mA, expected );
TGraphAsymmErrors *Exp_limitsS1 = new TGraphAsymmErrors(n, mA, expected ,xe, xe, exSigma1_l, exSigma1_u );
TGraphAsymmErrors *Exp_limitsS2 = new TGraphAsymmErrors(n, mA, expected ,xe, xe, exSigma2_l, exSigma2_u);

TGraphErrors *Exp_limits_gaudenz = new TGraphErrors( n, mA, expected_gaudenz);

//double expected_xmass[15] = {8e-36,7e-37, 2e-37, 1e-37, 8e-38, 6e-38, 5.5e-38, 5e-38,  4.3e-38, 5e-38, 6e-38, 7e-38, 9e-38, 1.2e-37, 1.5e-37};
//double m_xmass[15] = { 20, 30., 40., 50., 60., 70., 80., 90.,  100., 200., 300., 400, 500.,700., 1000.};

TGraphErrors *Exp_limits_xmass = new TGraphErrors(16);
   Exp_limits_xmass->SetPoint(0,20,8e-36);
   Exp_limits_xmass->SetPointError(0,0,0);
   Exp_limits_xmass->SetPoint(1,29.8071,7.162923e-37);
   Exp_limits_xmass->SetPointError(1,0,0);
   Exp_limits_xmass->SetPoint(2,39.90202,2.027528e-37);
   Exp_limits_xmass->SetPointError(2,0,0);
   Exp_limits_xmass->SetPoint(3,53.41583,9.91722e-38);
   Exp_limits_xmass->SetPointError(3,0,0);
   Exp_limits_xmass->SetPoint(4,62.16429,7.461589e-38);
   Exp_limits_xmass->SetPointError(4,0,0);
   Exp_limits_xmass->SetPoint(5,69.85718,6.3506e-38);
   Exp_limits_xmass->SetPointError(5,0,0);
   Exp_limits_xmass->SetPoint(6,83.21777,5.354015e-38);
   Exp_limits_xmass->SetPointError(6,0,0);
   Exp_limits_xmass->SetPoint(7,90,5e-38);
   Exp_limits_xmass->SetPointError(7,0,0);
   Exp_limits_xmass->SetPoint(8,105.0887,4.600252e-38);
   Exp_limits_xmass->SetPointError(8,0,0);
   Exp_limits_xmass->SetPoint(9,200,5e-38);
   Exp_limits_xmass->SetPointError(9,0,0);
   Exp_limits_xmass->SetPoint(10,300,6e-38);
   Exp_limits_xmass->SetPointError(10,0,0);
   Exp_limits_xmass->SetPoint(11,388.2045,7.252295e-38);
   Exp_limits_xmass->SetPointError(11,0,0);
   Exp_limits_xmass->SetPoint(12,590.8438,9.823615e-38);
   Exp_limits_xmass->SetPointError(12,0,0);
   Exp_limits_xmass->SetPoint(13,746.1269,1.210266e-37);
   Exp_limits_xmass->SetPointError(13,0,0);
   Exp_limits_xmass->SetPoint(14,1000,1.5e-37);
   Exp_limits_xmass->SetPointError(14,0,0);
   Exp_limits_xmass->SetPoint(15,4244.204,4.354065e-37);
   Exp_limits_xmass->SetPointError(15,0,0);


TCanvas *c1 = new TCanvas("limits", "limit", 600, 600);

Exp_limitsS1->SetFillColor(3);
Exp_limitsS1->SetLineColor(3);
Exp_limitsS1->SetMarkerColor(3);
Exp_limitsS1->SetMarkerSize(0);

Exp_limitsS2->SetFillColor(5);
Exp_limitsS2->SetLineColor(5);
Exp_limitsS2->SetMarkerColor(5);
Exp_limitsS2->SetMarkerSize(0);

obs_limits->SetFillColor(0);
obs_limits->SetLineWidth(3);
obs_limits->SetMarkerSize(0);

Exp_limits->SetFillColor(0);
Exp_limits->SetMarkerSize(0);
Exp_limits->SetLineStyle(7);
Exp_limits->SetLineWidth(3);

Exp_limits_gaudenz->SetFillColor(0);
Exp_limits_gaudenz->SetMarkerSize(0);
Exp_limits_gaudenz->SetLineWidth(3);
Exp_limits_gaudenz->SetLineColor(4);

Exp_limits_xmass->SetFillColor(0);
Exp_limits_xmass->SetMarkerSize(0);
Exp_limits_xmass->SetLineWidth(3);
Exp_limits_xmass->SetLineColor(2);

//Exp_limitsS2->GetYaxis()->SetTitle("#sigma#timesBR( #phi #rightarrow #tau#tau )  [pb]");
Exp_limitsS2->GetYaxis()->SetTitle("#sigma");

Exp_limitsS2->GetXaxis()->SetTitle("M  [GeV]");


Exp_limitsS2->GetXaxis()->SetLimits(9.,1000.);
Exp_limitsS2->GetYaxis()->SetRangeUser(1E-38,1E-30);

Exp_limits->GetXaxis()->SetLimits(9.,1000.);
Exp_limits->GetYaxis()->SetRangeUser(1E-38,1E-30);


Exp_limitsS2->Draw("Al3");
Exp_limitsS1->Draw("sameL3");
Exp_limits->Draw("PL");
Exp_limits_gaudenz->Draw("PC");
Exp_limits_xmass->Draw("PC");
//obs_limits->Draw("PL");


TLegend* lego = new TLegend(0.2,0.9,0.5,0.7);
  lego->SetTextSize(0.033);
  lego->SetFillColor(0);
  lego->SetBorderSize(0);
  lego->AddEntry(obs_limits,"Observed 90\% CLs limit");
  lego->AddEntry(Exp_limits_gaudenz, "Expected 90\% Gaudenz");
  lego->AddEntry(Exp_limits_xmass, "Expected 90\% XMASS");
  lego->AddEntry(Exp_limits, "Expected 90\% CLs limit");
  lego->AddEntry(Exp_limitsS1,"1 #sigma","f");
  lego->AddEntry(Exp_limitsS2,"2 #sigma","f");
  lego->Draw();


gPad->SetLogy();
gPad->SetLogx();
gPad->RedrawAxis("g");

myText(0.4,0.86,2,"Test");

*/


  // now use the profile inspector
  ProfileInspector p;
  TList* list = p.GetListOfProfilePlots(data,&mc);
  
  // now make plots
  TCanvas* c1 = new TCanvas("c1","ProfileInspectorDemo",800,200);
  if(list->GetSize()>4){
    double n = list->GetSize();
    int nx = (int)sqrt(n) ;
    int ny = TMath::CeilNint(n/nx);
    nx = TMath::CeilNint( sqrt(n) );
    c1->Divide(ny,nx);
  } else
    c1->Divide(list->GetSize());
  for(int i=0; i<list->GetSize(); ++i){
    c1->cd(i+1);
    list->At(i)->Draw("al");
  }
  
  cout << endl;



/*  // plot now the result of the scan 
  HypoTestInverterPlot *plot = new HypoTestInverterPlot("HTI_Result_Plot","HypoTest Scan Result",r);

  // plot in a new canvas with style
  TCanvas * c1 = new TCanvas("HypoTestInverter Scan"); 
  c1->SetLogy(false);

  plot->Draw("2CL");  // plot also CLb and CLs+b 
  //plot->Draw("OBS");  // plot only observed p-value

*/



  // plot also in a new canvas the test statistics distributions 
  
  // plot test statistics distributions for the two hypothesis
/*  // when distribution is generated (case of FrequentistCalculators)
  const int n = r->ArraySize();
  if (n> 0 &&  r->GetResult(0)->GetNullDistribution() ) { 
     TCanvas * c2 = new TCanvas("Test Statistic Distributions","",2);
     if (n > 1) {
        int ny = TMath::CeilNint( sqrt(n) );
        int nx = TMath::CeilNint(double(n)/ny);
        c2->Divide( nx,ny);
     }
     for (int i=0; i<n; i++) {
        if (n > 1) c2->cd(i+1);
        SamplingDistPlot * pl = plot->MakeTestStatPlot(i);
        pl->SetLogYaxis(true);
        pl->Draw();
     }
  }
*/




}
Example #19
0
void deltarPHJET1( TString myMethodList = "" ) 
{   

 
   // Book output histograms
   UInt_t nbin = 14;
   double min=0;
   double max=6;
   TFile *input(0);

std::vector<string> samples_;
std::vector<string> datasamples_;
std::vector<TH1F*> datahists;
std::vector<TH1F*> revDATAhists;
std::vector<TH1F*> ihists;
std::vector<TH1F*> iSBhists;

float scales[] = {0.0978,1.491,0.0961,0.0253,0.0224,0.0145,0.0125,0.0160,0.0158,0.0341,0.0341,0.0341,0.020,0.0017,0.0055,0.0032,0.00084,0.02,0.01139,0.01139,0.049094905,0.049094905,0.049094905,0.049094905,0.049094905/19.145};


//samples_.push_back("WJET.root");
samples_.push_back("ZJET.root");
samples_.push_back("PHJET200400.root");
samples_.push_back("WPHJET.root");
samples_.push_back("T-W-CH.root");
samples_.push_back("TBAR-W-CH.root");
samples_.push_back("T-S-CH.root");
samples_.push_back("TBAR-S-CH.root");
samples_.push_back("T-T-CH.root");
samples_.push_back("TBAR-T-CH.root");
samples_.push_back("TTBAR1.root");
samples_.push_back("TTBAR2.root");
samples_.push_back("TTBAR3.root");
samples_.push_back("TTG.root");
samples_.push_back("WWG.root");
samples_.push_back("WW.root");
samples_.push_back("WZ.root");
samples_.push_back("ZZ.root");
samples_.push_back("ZGAMMA.root");
samples_.push_back("SINGLE-TOP-PH.root");
samples_.push_back("SINGLE-ANTITOP-PH.root");
samples_.push_back("SIGNALtGu.root");
samples_.push_back("SIGNALtGu.root");
samples_.push_back("SIGNALtGu.root");
samples_.push_back("SIGNALtGu.root");
samples_.push_back("SIGNALtGu.root");


datasamples_.push_back("REALDATA1.root");
datasamples_.push_back("REALDATA2.root");
datasamples_.push_back("REALDATA3.root");

std::vector<string> datasamplesreverse_;
datasamplesreverse_.push_back("etarev/REALDATA1.root");
datasamplesreverse_.push_back("etarev/REALDATA2.root");
datasamplesreverse_.push_back("etarev/REALDATA3.root");

std::vector<string> systematics;
systematics.push_back("__JES__plus");
systematics.push_back("__JES__minus");
systematics.push_back("__JER__plus");
systematics.push_back("__JER__minus");
systematics.push_back("__PhES__plus");
systematics.push_back("__PhES__minus");
systematics.push_back("__btagSF__plus");
systematics.push_back("__btagSF__minus");
systematics.push_back("__PU__plus");
systematics.push_back("__PU__minus");
systematics.push_back("__TRIG__plus");
systematics.push_back("__TRIG__minus");

//systematics.push_back("__MISSTAG__plus");
//systematics.push_back("__MISSTAG__minus");
systematics.push_back("__MUON__plus");
systematics.push_back("__MUON__minus");
systematics.push_back("__PHOTON__plus");
systematics.push_back("__PHOTON__minus");
systematics.push_back("");

map<string, double> eventwight;
TList* hList = new TList();      // list of histograms to store
double insidewphjet;
double outsidewphjet;
double insidewjet;
double outsidewjet;
double mtopup=220;
double mtopdown=130;

for(unsigned int phi=0; phi<systematics.size(); ++phi){
insidewphjet=0;
outsidewphjet=0;
insidewjet=0;
outsidewjet=0;

std::vector<TH1F*> hists;
std::vector<TH1F*> SBhists;

TH1F   *wphjethist(0), *zjethist(0) , *phjethist(0), *wjethist(0), *twchhist(0), *tbarwhist(0),  *tschhist(0), *tbarschhist(0), *ttchhist(0), *tbartchhist(0), *tt1hist(0) ,*tt2hist(0), *tt3hist(0), *ttphhist(0), *wwphhist(0), *wwhist(0), *wzhist(0), *zzhist(0), *zgammahist(0),*singletopphotonhist(0), *singleantitopphotonhist(0), *signalhist5(0) , *signalhist10(0), *signalhist20(0), *signalhist30(0), *signalhist40(0);

TH1F   *wphjethistSB(0), *zjethistSB(0) , *phjethistSB(0), *wjethistSB(0), *twchhistSB(0), *tbarwhistSB(0),  *tschhistSB(0), *tbarschhistSB(0), *ttchhistSB(0), *tbartchhistSB(0), *tt1histSB(0) ,*tt2histSB(0), *tt3histSB(0), *ttphhistSB(0), *wwphhistSB(0), *wwhistSB(0), *wzhistSB(0), *zzhistSB(0), *zgammahistSB(0),*singletopphotonhistSB(0), *singleantitopphotonhistSB(0), *signalhistSB5(0) , *signalhistSB10(0), *signalhistSB20(0), *signalhistSB30(0), *signalhistSB40(0);

TH1F *data1histrev(0), *data2histrev(0) ,*data3histrev(0),*datahistsideband(0);

wphjethist = new TH1F( std::string("BDT__wphjethists").append(systematics[phi]).c_str(), std::string("BDT__wphjethists").append(systematics[phi]).c_str()  , nbin,  min, max    );
zjethist = new TH1F( std::string("BDT__zjethist").append(systematics[phi]).c_str(), std::string("BDT__zjethist").append(systematics[phi]).c_str(),  nbin,  min, max    );
phjethist = new TH1F( std::string("BDT__phjethist").append(systematics[phi]).c_str(),std::string("BDT__phjethist").append(systematics[phi]).c_str() , nbin,  min, max   );
//wjethist = new TH1F( std::string("BDT__wjethist").append(systematics[phi]).c_str(),std::string("BDT__wjethist").append(systematics[phi]).c_str() , nbin, -0.8, 0.8 );
twchhist = new TH1F( std::string("BDT__twchhist").append(systematics[phi]).c_str(),std::string("BDT__twchhist").append(systematics[phi]).c_str() ,nbin,  min, max   );
tbarwhist = new TH1F( std::string("BDT__tbarwhist").append(systematics[phi]).c_str(),std::string("BDT__tbarwhist").append(systematics[phi]).c_str() ,nbin,  min, max    );
tschhist = new TH1F( std::string("BDT__tschhist").append(systematics[phi]).c_str(), std::string("BDT__tschhist").append(systematics[phi]).c_str(), nbin,  min, max  );
tbarschhist = new TH1F( std::string("BDT__tbarschhist").append(systematics[phi]).c_str(),std::string("BDT__tbarschhist").append(systematics[phi]).c_str(), nbin,  min, max  );
ttchhist = new TH1F( std::string("BDT__ttchhist").append(systematics[phi]).c_str(),std::string("BDT__ttchhist").append(systematics[phi]).c_str(), nbin,  min, max   );
tbartchhist = new TH1F( std::string("BDT__tbartchhist").append(systematics[phi]).c_str(), std::string("BDT__tbartchhist").append(systematics[phi]).c_str(), nbin, min, max   );
tt1hist = new TH1F( std::string("BDT__tt1hist").append(systematics[phi]).c_str(), std::string("BDT__tt1hist").append(systematics[phi]).c_str(), nbin, min, max  );
tt2hist = new TH1F( std::string("BDT__tt2hist").append(systematics[phi]).c_str(), std::string("BDT__tt2hist").append(systematics[phi]).c_str(), nbin, min, max  );
tt3hist = new TH1F( std::string("BDT__tt3hist").append(systematics[phi]).c_str(),std::string("BDT__tt3hist").append(systematics[phi]).c_str() , nbin,  min, max  );
ttphhist = new TH1F( std::string("BDT__ttphhist").append(systematics[phi]).c_str(),std::string("BDT__ttphhist").append(systematics[phi]).c_str() ,nbin, min, max   );
wwphhist = new TH1F( std::string("BDT__wwphhist").append(systematics[phi]).c_str(),std::string("BDT__wwphhist").append(systematics[phi]).c_str(), nbin,min, max   );
wwhist = new TH1F( std::string("BDT__wwhist").append(systematics[phi]).c_str(),std::string("BDT__wwhist").append(systematics[phi]).c_str()  ,nbin,  min, max );
wzhist = new TH1F( std::string("BDT__wzhist").append(systematics[phi]).c_str(),std::string("BDT__wzhist").append(systematics[phi]).c_str(), nbin, min, max   );
zzhist = new TH1F( std::string("BDT__zzhist").append(systematics[phi]).c_str(),std::string("BDT__zzhist").append(systematics[phi]).c_str() ,nbin,  min, max  );
zgammahist = new TH1F( std::string("BDT__zgammahist").append(systematics[phi]).c_str(),std::string("BDT__zgammahist").append(systematics[phi]).c_str() ,nbin, min, max  );
singletopphotonhist = new TH1F( std::string("BDT__singletopphotonhist").append(systematics[phi]).c_str(),  std::string("BDT__singletopphotonhist").append(systematics[phi]).c_str(),nbin, min, max );
singleantitopphotonhist = new TH1F( std::string("BDT__singleantitopphotonhist").append(systematics[phi]).c_str(),           std::string("BDT__singleantitopphotonhist").append(systematics[phi]).c_str(),nbin, min, max );
signalhist5 = new TH1F( std::string("BDT__signal5").append(systematics[phi]).c_str(),std::string("BDT__signal5").append(systematics[phi]).c_str()  ,nbin, min, max    );
signalhist10 = new TH1F( std::string("BDT__signal10").append(systematics[phi]).c_str(),std::string("BDT__signal10").append(systematics[phi]).c_str() ,nbin,  min, max   );
signalhist20 = new TH1F( std::string("BDT__signal20").append(systematics[phi]).c_str(),std::string("BDT__signal20").append(systematics[phi]).c_str() ,nbin, min, max    );
signalhist30 = new TH1F( std::string("BDT__signal30").append(systematics[phi]).c_str(),std::string("BDT__signal30").append(systematics[phi]).c_str() ,nbin, min, max  );
signalhist40 = new TH1F( std::string("BDT__signal40").append(systematics[phi]).c_str(),std::string("BDT__signal40").append(systematics[phi]).c_str() ,nbin,min, max  );


//side band region histograms out of top mass
wphjethistSB = new TH1F( std::string("BDT__wphjethistSB").append(systematics[phi]).c_str(), std::string("BDT__wphjethistSB").append(systematics[phi]).c_str()  , nbin,  min, max   );
zjethistSB = new TH1F( std::string("BDT__zjethistSB").append(systematics[phi]).c_str(), std::string("BDT__zjethistSB").append(systematics[phi]).c_str(),  nbin, min, max    );
phjethistSB = new TH1F( std::string("BDT__phjethistSB").append(systematics[phi]).c_str(),std::string("BDT__phjethistSB").append(systematics[phi]).c_str() , nbin,  min, max  );
//wjethist = new TH1F( std::string("BDT__wjethist").append(systematics[phi]).c_str(),std::string("BDT__wjethist").append(systematics[phi]).c_str() , nbin, -0.8, 0.8 );
twchhistSB = new TH1F( std::string("BDT__twchhistSB").append(systematics[phi]).c_str(),std::string("BDT__twchhistSB").append(systematics[phi]).c_str() ,nbin,  min, max  );
tbarwhistSB = new TH1F( std::string("BDT__tbarwhistSB").append(systematics[phi]).c_str(),std::string("BDT__tbarwhistSB").append(systematics[phi]).c_str() ,nbin,  min, max  );
tschhistSB = new TH1F( std::string("BDT__tschhistSB").append(systematics[phi]).c_str(), std::string("BDT__tschhistSB").append(systematics[phi]).c_str(), nbin, min, max   );
tbarschhistSB = new TH1F( std::string("BDT__tbarschhistSB").append(systematics[phi]).c_str(),std::string("BDT__tbarschhistSB").append(systematics[phi]).c_str(), nbin, min, max   );
ttchhistSB = new TH1F( std::string("BDT__ttchhistSB").append(systematics[phi]).c_str(),std::string("BDT__ttchhistSB").append(systematics[phi]).c_str(), nbin, min, max   );
tbartchhistSB = new TH1F( std::string("BDT__tbartchhistSB").append(systematics[phi]).c_str(), std::string("BDT__tbartchhistSB").append(systematics[phi]).c_str(), nbin,  min, max   );
tt1histSB = new TH1F( std::string("BDT__tt1histSB").append(systematics[phi]).c_str(), std::string("BDT__tt1histSB").append(systematics[phi]).c_str(), nbin, min, max   );
tt2histSB = new TH1F( std::string("BDT__tt2histSB").append(systematics[phi]).c_str(), std::string("BDT__tt2histSB").append(systematics[phi]).c_str(), nbin, min, max   );
tt3histSB = new TH1F( std::string("BDT__tt3histSB").append(systematics[phi]).c_str(),std::string("BDT__tt3histSB").append(systematics[phi]).c_str() , nbin, min, max   );
ttphhistSB = new TH1F( std::string("BDT__ttphhistSB").append(systematics[phi]).c_str(),std::string("BDT__ttphhistSB").append(systematics[phi]).c_str() ,nbin, min, max   );
wwphhistSB = new TH1F( std::string("BDT__wwphhistSB").append(systematics[phi]).c_str(),std::string("BDT__wwphhistSB").append(systematics[phi]).c_str(), nbin,  min, max   );
wwhistSB = new TH1F( std::string("BDT__wwhistSB").append(systematics[phi]).c_str(),std::string("BDT__wwhistSB").append(systematics[phi]).c_str()  ,nbin, min, max   );
wzhistSB = new TH1F( std::string("BDT__wzhistSB").append(systematics[phi]).c_str(),std::string("BDT__wzhistSB").append(systematics[phi]).c_str(), nbin,  min, max  );
zzhistSB = new TH1F( std::string("BDT__zzhistSB").append(systematics[phi]).c_str(),std::string("BDT__zzhistSB").append(systematics[phi]).c_str() ,nbin,  min, max   );
zgammahistSB = new TH1F( std::string("BDT__zgammahistSB").append(systematics[phi]).c_str(),std::string("BDT__zgammahistSB").append(systematics[phi]).c_str() ,nbin,  min, max    );
singletopphotonhistSB = new TH1F( std::string("BDT__singletopphotonhistSB").append(systematics[phi]).c_str(),  std::string("BDT__singletopphotonhistSB").append(systematics[phi]).c_str(),nbin, min, max);
singleantitopphotonhistSB = new TH1F( std::string("BDT__singleantitopphotonhistSB").append(systematics[phi]).c_str(),           std::string("BDT__singleantitopphotonhistSB").append(systematics[phi]).c_str(),nbin, min, max  );
signalhistSB5= new TH1F( std::string("BDT__signal5SB").append(systematics[phi]).c_str(),std::string("BDT__signal5SB").append(systematics[phi]).c_str()  ,nbin,  min, max   );
signalhistSB10 = new TH1F( std::string("BDT__signalSB10").append(systematics[phi]).c_str(),std::string("BDT__signalSB10").append(systematics[phi]).c_str() ,nbin, min, max   );
signalhistSB20 = new TH1F( std::string("BDT__signalSB20").append(systematics[phi]).c_str(),std::string("BDT__signalSB20").append(systematics[phi]).c_str() ,nbin, min, max   );
signalhistSB30 = new TH1F( std::string("BDT__signalSB30").append(systematics[phi]).c_str(),std::string("BDT__signalSB30").append(systematics[phi]).c_str() ,nbin,min, max  );
signalhistSB40 = new TH1F( std::string("BDT__signalSB40").append(systematics[phi]).c_str(),std::string("BDT__signalSB40").append(systematics[phi]).c_str() ,nbin,min, max   );


hists.push_back(zjethist);
hists.push_back(phjethist);
hists.push_back(wphjethist);
//hists.push_back(wjethist);
hists.push_back(twchhist);
hists.push_back(tbarwhist);
hists.push_back(tschhist);
hists.push_back(tbarschhist);
hists.push_back(ttchhist);
hists.push_back(tbartchhist);
hists.push_back(tt1hist);
hists.push_back(tt2hist);
hists.push_back(tt3hist);
hists.push_back(ttphhist);
hists.push_back(wwphhist);
hists.push_back(wwhist);
hists.push_back(wzhist);
hists.push_back(zzhist);
hists.push_back(zgammahist);
hists.push_back(singletopphotonhist);
hists.push_back(singleantitopphotonhist);
hists.push_back(signalhist5);
hists.push_back(signalhist10);
hists.push_back(signalhist20);
hists.push_back(signalhist30);
hists.push_back(signalhist40);


SBhists.push_back(zjethistSB);
SBhists.push_back(phjethistSB);
SBhists.push_back(wphjethistSB);
SBhists.push_back(twchhistSB);
SBhists.push_back(tbarwhistSB);
SBhists.push_back(tschhistSB);
SBhists.push_back(tbarschhistSB);
SBhists.push_back(ttchhistSB);
SBhists.push_back(tbartchhistSB);
SBhists.push_back(tt1histSB);
SBhists.push_back(tt2histSB);
SBhists.push_back(tt3histSB);
SBhists.push_back(ttphhistSB);
SBhists.push_back(wwphhistSB);
SBhists.push_back(wwhistSB);
SBhists.push_back(wzhistSB);
SBhists.push_back(zzhistSB);
SBhists.push_back(zgammahistSB);
SBhists.push_back(singletopphotonhistSB);
SBhists.push_back(singleantitopphotonhistSB);
SBhists.push_back(signalhistSB5);
SBhists.push_back(signalhistSB10);
SBhists.push_back(signalhistSB20);
SBhists.push_back(signalhistSB30);
SBhists.push_back(signalhistSB40);

for(unsigned int idx=0; idx<samples_.size(); ++idx){
hists[idx]->Sumw2();}

for(unsigned int idx=0; idx<samples_.size(); ++idx){
   TFile *input(0);
TString fname;
if (phi<6) fname =systematics[phi]+"/"+samples_[idx];
    else fname =samples_[idx];
   if (!gSystem->AccessPathName( fname )) input = TFile::Open( fname ); // check if file in local directory exists
   else    
      input = TFile::Open( "http://root.cern.ch/files/tmva_class_example.root" ); // if not: download from ROOT server
   
   if (!input) {
      std::cout << "ERROR: could not open data file" << std::endl;
      exit(1);
   }
   std::cout << "--- TMVAClassificationApp    : Using input file: " << input->GetName() << std::endl;
  
   // --- Event loop


std::vector<double> *myptphoton=0;
std::vector<double> *myetaphoton=0;
std::vector<double> *myptmuon=0;
std::vector<double> *myetamuon=0;
std::vector<double> *myptjet=0;
std::vector<double> *myetajet=0;
std::vector<double> *mymasstop=0;
//std::vector<double> *mymtw=0;
std::vector<double> *mydeltaRphotonjet=0;
std::vector<double> *mydeltaRphotonmuon=0;
//std::vector<double> *myht=0;
std::vector<double> *mycostopphoton=0;
std::vector<double> *mydeltaphiphotonmet=0;
std::vector<double> *mycvsdiscriminant=0;
std::vector<double> *myjetmultiplicity=0;
//std::vector<double> *mybjetmultiplicity=0;
//std::vector<double> *myleptoncharge=0;
std::vector<double> *myweight=0;
std::vector<double> *mybtagSF=0;
std::vector<double> *mybtagSFup=0;
std::vector<double> *mybtagSFdown=0;
std::vector<double> *mymistagSFup=0;
std::vector<double> *mymistagSFdown=0;
std::vector<double> *mytriggerSF=0;
std::vector<double> *mytriggerSFup=0;
std::vector<double> *mytriggerSFdown=0;
std::vector<double> *myphotonSF=0;
std::vector<double> *myphotonSFup=0;
std::vector<double> *myphotonSFdown=0;
std::vector<double> *mypileupSF=0;
std::vector<double> *mypileupSFup=0;
std::vector<double> *mypileupSFdown=0;
std::vector<double> *mymuonSFup=0;
std::vector<double> *mymuonSFdown=0;
std::vector<double> *mymuonSF=0;
std::vector<double> *myjetmatchinginfo=0;
std::vector<double> *mycoswphoton=0;
std::vector<double> *myphiphoton=0;
std::vector<double> *mysigmaietaieta=0;


   std::cout << "--- Select signal sample" << std::endl;
   TTree* theTree = (TTree*)input->Get("analyzestep2/atq");
//   Int_t myjetmultiplicity, mybjetmultiplicity , myleptoncharge;
//   Float_t userVar1, userVar2;

   theTree->SetBranchAddress("ptphoton", &myptphoton  );
   theTree->SetBranchAddress( "etaphoton", &myetaphoton );
   theTree->SetBranchAddress( "ptmuon", &myptmuon );
   theTree->SetBranchAddress( "etamuon", &myetamuon );
   theTree->SetBranchAddress( "ptjet", &myptjet );
   theTree->SetBranchAddress( "etajet", &myetajet );
   theTree->SetBranchAddress( "masstop", &mymasstop );
//   theTree->SetBranchAddress( "mtw", &mymtw );
   theTree->SetBranchAddress( "deltaRphotonjet", &mydeltaRphotonjet );
   theTree->SetBranchAddress( "deltaRphotonmuon", &mydeltaRphotonmuon );
//   theTree->SetBranchAddress( "ht", &myht );
   theTree->SetBranchAddress( "costopphoton", &mycostopphoton );
   theTree->SetBranchAddress( "jetmultiplicity", &myjetmultiplicity );
//   theTree->SetBranchAddress( "bjetmultiplicity", &mybjetmultiplicity );
   theTree->SetBranchAddress( "deltaphiphotonmet", &mydeltaphiphotonmet );
   theTree->SetBranchAddress( "cvsdiscriminant", &mycvsdiscriminant );
   theTree->SetBranchAddress( "coswphoton", &mycoswphoton );
//   theTree->SetBranchAddress( "leptoncharge", &myleptoncharge );
   theTree->SetBranchAddress( "weight", &myweight);
   theTree->SetBranchAddress( "btagSF", &mybtagSF);
   theTree->SetBranchAddress( "btagSFup", &mybtagSFup);
   theTree->SetBranchAddress( "btagSFdown", &mybtagSFdown);
   theTree->SetBranchAddress( "mistagSFup", &mymistagSFup);
   theTree->SetBranchAddress( "mistagSFdown", &mymistagSFdown);
   theTree->SetBranchAddress( "triggerSF", &mytriggerSF);
   theTree->SetBranchAddress( "triggerSFup", &mytriggerSFup);
   theTree->SetBranchAddress( "triggerSFdown", &mytriggerSFdown);
   theTree->SetBranchAddress( "photonSF", &myphotonSF);
   theTree->SetBranchAddress( "photonSFup", &myphotonSFup);
   theTree->SetBranchAddress( "photonSFdown", &myphotonSFdown);
   theTree->SetBranchAddress( "muonSF", &mymuonSF);
   theTree->SetBranchAddress( "muonSFup", &mymuonSFup);
   theTree->SetBranchAddress( "muonSFdown", &mymuonSFdown);
   theTree->SetBranchAddress( "pileupSF", &mypileupSF);
   theTree->SetBranchAddress( "pileupSFup", &mypileupSFup);
   theTree->SetBranchAddress( "pileupSFdown", &mypileupSFdown);
   theTree->SetBranchAddress( "jetmatchinginfo", &myjetmatchinginfo );
theTree->SetBranchAddress( "phiphoton", &myphiphoton );
 theTree->SetBranchAddress( "sigmaieta", &mysigmaietaieta );
 

//   std::cout << "--- Processing: " << theTree->GetEntries() << " events" << std::endl;
   TStopwatch sw;
   sw.Start();
   for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) {
//   std::cout << "--- ... Processing event: " << ievt << std::endl;
double finalweight;

      if (ievt%5000 == 0) std::cout << "--- ... Processing event: " << ievt << std::endl;

      theTree->GetEntry(ievt);
//for (int l=0;l<sizeof(myptphoton);l++){
//std::cout << "--- ... reza: " << myptphoton[l] <<std::endl;
//}
//std::cout << "--- ......................."<< (*mycvsdiscriminant)[0]<<std::endl;
      // --- Return the MVA outputs and fill into histograms

finalweight=(*myweight)[0];
//cout<<(*myweight)[0]<<endl;
eventwight["__PU__plus"]=((*myweight)[0]*(*mypileupSFup)[0])/(*mypileupSF)[0];
eventwight["__PU__minus"]=((*myweight)[0]*(*mypileupSFdown)[0])/(*mypileupSF)[0];
eventwight["__TRIG__plus"]=((*myweight)[0]*(*mytriggerSFup)[0])/(*mytriggerSF)[0];
eventwight["__TRIG__minus"]=((*myweight)[0]*(*mytriggerSFdown)[0])/(*mytriggerSF)[0];
eventwight["__BTAG__plus"]=((*myweight)[0]*(*mybtagSFup)[0])/(*mybtagSF)[0];
eventwight["__BTAG__minus"]=((*myweight)[0]*(*mybtagSFdown)[0])/(*mybtagSF)[0];
eventwight["__MISSTAG__plus"]=((*myweight)[0]*(*mymistagSFup)[0])/(*mybtagSF)[0];
eventwight["__MISSTAG__minus"]=((*myweight)[0]*(*mymistagSFdown)[0])/(*mybtagSF)[0];
eventwight["__MUON__plus"]=((*myweight)[0]*(*mymuonSFup)[0])/(*mymuonSF)[0];
eventwight["__MUON__minus"]=((*myweight)[0]*(*mymuonSFdown)[0])/(*mymuonSF)[0];
eventwight["__PHOTON__plus"]=((*myweight)[0]*(*myphotonSFup)[0])/(*myphotonSF)[0];
eventwight["__PHOTON__minus"]=((*myweight)[0]*(*myphotonSFdown)[0])/(*myphotonSF)[0];
eventwight[""]=(*myweight)[0];
//if (phi<4) finalweight=(*myweight)[0];
if (phi>7) finalweight=eventwight[systematics[phi].c_str()];
//if (samples_[idx]=="SIGNALtGu.root") cout<<"negative event weight"<<finalweight<<"            "<<endl;
//if (samples_[idx]=="WPHJET")  finalweight=(*mypileupSF)[0]*(*mytriggerSF)[0]*(*mybtagSF)[0]*(*mymuonSF)[0]*(*myphotonSF)[0];
//if (finalweight<0) finalweight=30;
//cout<<"negative event weight"<<finalweight<<"            "<<ptphoton<<endl;
 if(sqrt(pow((*myetaphoton )[0]+1.76,2)+pow((*myphiphoton )[0]-1.37,2))>0.05 && sqrt(pow((*myetaphoton )[0]-2.37,2)+pow((*myphiphoton )[0]-2.69,2))>0.05){
if(sqrt(pow((*myetaphoton )[0]- 1.61,2)+pow((*myphiphoton )[0]+2.05,2))>0.05 && sqrt(pow((*myetaphoton )[0]-1.75,2)+pow((*myphiphoton )[0]-2.12,2))>0.05){
if((*mymasstop )[0]>mtopdown && (*mymasstop )[0]<mtopup){

hists[idx] ->Fill( (*mydeltaRphotonjet)[0] ,finalweight*scales[idx] );
if (samples_[idx]=="WPHJET.root") insidewphjet=insidewphjet+finalweight;
}
else {
SBhists[idx] ->Fill( (*mydeltaRphotonjet)[0] ,finalweight*scales[idx] );
if (samples_[idx]=="WPHJET.root") outsidewphjet=outsidewphjet+finalweight;}
  }} }

   // Get elapsed time
   sw.Stop();
   std::cout << "--- End of event loop: "; sw.Print();

delete myptphoton;
delete myetaphoton;
delete myptmuon;
delete myetamuon;
delete myptjet;
delete myetajet;
delete mymasstop;
//delete mymtw;
delete mydeltaRphotonjet;
delete mydeltaRphotonmuon;
//delete myht;
delete mycostopphoton;
delete mydeltaphiphotonmet;
delete mycvsdiscriminant;
delete myjetmultiplicity;
//delete mybjetmultiplicity;
//delete myleptoncharge;
//delete myplot;
delete mybtagSF;
delete mybtagSFup;
delete mybtagSFdown;
delete mymistagSFup;
delete mytriggerSF;
delete mytriggerSFup;
delete mytriggerSFdown;
delete myphotonSF;
delete myphotonSFup;
delete myphotonSFdown;
delete mypileupSF;
delete mypileupSFup;
delete mypileupSFdown;
delete input;
delete myjetmatchinginfo;
//if (idx==samples_.size()-5) hists[idx]->Scale(5/hists[idx]->Integral());
//if (idx==samples_.size()-4) hists[idx]->Scale(10/hists[idx]->Integral());
//if (idx==samples_.size()-3) hists[idx]->Scale(20/hists[idx]->Integral());
//if (idx==samples_.size()-2) hists[idx]->Scale(30/hists[idx]->Integral());
//if (idx==samples_.size()-1) hists[idx]->Scale(40/hists[idx]->Integral());

if (samples_[idx]=="WPHJET.root") hists[idx]->Scale(3173/hists[idx]->Integral());
if (samples_[idx]=="TTBAR2.root") hists[idx]->Add(hists[idx-1]);
if (samples_[idx]=="TTBAR3.root") hists[idx]->Add(hists[idx-1]);
if (samples_[idx]=="SINGLE-ANTITOP-PH.root") hists[idx]->Add(hists[idx-1]);
if (samples_[idx]=="TBAR-W-CH.root") hists[idx]->Add(hists[idx-1]);
if (samples_[idx]=="T-S-CH.root") hists[idx]->Add(hists[idx-1]);
if (samples_[idx]=="TBAR-S-CH.root") hists[idx]->Add(hists[idx-1]);
if (samples_[idx]=="T-T-CH.root") hists[idx]->Add(hists[idx-1]);
if (samples_[idx]=="TBAR-T-CH.root") hists[idx]->Add(hists[idx-1]);
if (samples_[idx]=="WZ.root") hists[idx]->Add(hists[idx-1]);
if (samples_[idx]=="ZZ.root") hists[idx]->Add(hists[idx-1]);

if (!(samples_[idx]=="TTBAR1.root" || samples_[idx]=="TTBAR2.root"|| samples_[idx]=="SINGLE-TOP-PH.root"||samples_[idx]=="SIGNALtGu.root" || samples_[idx]=="WPHJET.root"||samples_[idx]=="T-W-CH.root" ||samples_[idx]=="TBAR-W-CH.root" ||samples_[idx]=="T-S-CH.root" ||samples_[idx]=="TBAR-S-CH.root" ||samples_[idx]=="T-T-CH.root" ||samples_[idx]=="WW.root" ||samples_[idx]=="WZ.root")  ) hList->Add(hists[idx]);
if (idx==samples_.size()-1)hList->Add(hists[idx]);
if (systematics[phi]==""){
ihists.push_back(hists[idx]);
iSBhists.push_back(SBhists[idx]);}
}
}
TH1F *data1hist(0), *data2hist(0) ,*data3hist(0),*datahistsideband(0);
data1hist = new TH1F( "mu_BDT__data1hist",           "mu_BDT__data1hist",           nbin, min, max );
data1hist->Sumw2();
data2hist = new TH1F( "mu_BDT__data2hist",           "mu_BDT__data2hist",           nbin, min, max );
data2hist->Sumw2();
data3hist = new TH1F( "BDT__DATA",           "BDT__DATA",           nbin, min, max );
data3hist->Sumw2();
datahistsideband = new TH1F( "BDT__wphjethist",           "BDT__wphjethist",           nbin,min, max );
datahistsideband->Sumw2();

datahists.push_back(data1hist);
datahists.push_back(data2hist);
datahists.push_back(data3hist);
datahists.push_back(datahistsideband);



for(unsigned int idx=0; idx<datasamples_.size(); ++idx){
   TFile *input(0);
   TString fname =datasamples_[idx];
   if (!gSystem->AccessPathName( fname )) input = TFile::Open( fname ); // check if file in local directory exists
   else    
      input = TFile::Open( "http://root.cern.ch/files/tmva_class_example.root" ); // if not: download from ROOT server
   
   if (!input) {
      std::cout << "ERROR: could not open data file" << std::endl;
      exit(1);
   }
   std::cout << "--- TMVAClassificationApp    : Using input file: " << input->GetName() << std::endl;
   
   // --- Event loop

   // Prepare the event tree
   // - here the variable names have to corres[1]ponds to your tree
   // - you can use the same variables as above which is slightly faster,
   //   but of course you can use different ones and copy the values inside the event loop
   //

std::vector<double> *myptphoton=0;
std::vector<double> *myetaphoton=0;
std::vector<double> *myptmuon=0;
std::vector<double> *myetamuon=0;
std::vector<double> *myptjet=0;
std::vector<double> *myetajet=0;
std::vector<double> *mymasstop=0;
//std::vector<double> *mymtw=0;
std::vector<double> *mydeltaRphotonjet=0;
std::vector<double> *mydeltaRphotonmuon=0;
//std::vector<double> *myht=0;
std::vector<double> *mycostopphoton=0;
std::vector<double> *mydeltaphiphotonmet=0;
std::vector<double> *mycvsdiscriminant=0;
std::vector<double> *myjetmultiplicity=0;
//std::vector<double> *mybjetmultiplicity=0;
//std::vector<double> *myleptoncharge=0;
std::vector<double> *mycoswphoton=0;
std::vector<double> *myphiphoton=0;
std::vector<double> *mysigmaietaieta=0;


   std::cout << "--- Select signal sample" << std::endl;
   TTree* theTree = (TTree*)input->Get("analyzestep2/atq");
//   Int_t myjetmultiplicity, mybjetmultiplicity , myleptoncharge;
//   Float_t userVar1, userVar2;

   theTree->SetBranchAddress("ptphoton", &myptphoton  );
   theTree->SetBranchAddress( "etaphoton", &myetaphoton );
   theTree->SetBranchAddress( "ptmuon", &myptmuon );
   theTree->SetBranchAddress( "etamuon", &myetamuon );
   theTree->SetBranchAddress( "ptjet", &myptjet );
   theTree->SetBranchAddress( "etajet", &myetajet );
   theTree->SetBranchAddress( "masstop", &mymasstop );
//   theTree->SetBranchAddress( "mtw", &mymtw );
   theTree->SetBranchAddress( "deltaRphotonjet", &mydeltaRphotonjet );
   theTree->SetBranchAddress( "deltaRphotonmuon", &mydeltaRphotonmuon );
//   theTree->SetBranchAddress( "ht", &myht );
   theTree->SetBranchAddress( "costopphoton", &mycostopphoton );
   theTree->SetBranchAddress( "jetmultiplicity", &myjetmultiplicity );
//   theTree->SetBranchAddress( "bjetmultiplicity", &mybjetmultiplicity );
   theTree->SetBranchAddress( "deltaphiphotonmet", &mydeltaphiphotonmet );
   theTree->SetBranchAddress( "cvsdiscriminant", &mycvsdiscriminant );
   theTree->SetBranchAddress( "coswphoton", &mycoswphoton );
//   theTree->SetBranchAddress( "leptoncharge", &myleptoncharge );
theTree->SetBranchAddress( "phiphoton", &myphiphoton );
 theTree->SetBranchAddress( "sigmaieta", &mysigmaietaieta );
 


   std::cout << "--- Processing: " << theTree->GetEntries() << " events" << std::endl;
   TStopwatch sw;
   sw.Start();
   for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) {
//   std::cout << "--- ... Processing event: " << ievt << std::endl;

      if (ievt%5000 == 0) std::cout << "--- ... Processing event: " << ievt << std::endl;

      theTree->GetEntry(ievt);

 if(sqrt(pow((*myetaphoton )[0]+1.76,2)+pow((*myphiphoton )[0]-1.37,2))>0.05 && sqrt(pow((*myetaphoton )[0]-2.37,2)+pow((*myphiphoton )[0]-2.69,2))>0.05){
if(sqrt(pow((*myetaphoton )[0]- 1.61,2)+pow((*myphiphoton )[0]+2.05,2))>0.05 && sqrt(pow((*myetaphoton )[0]-1.75,2)+pow((*myphiphoton )[0]-2.12,2))>0.05){
if((*mymasstop )[0]>mtopdown && (*mymasstop )[0]<mtopup) datahists[idx] ->Fill( (*mydeltaRphotonjet)[0]);
else datahists[3]->Fill( (*mydeltaRphotonjet)[0] );
}}}
   // Get elapsed time
   sw.Stop();
   std::cout << "--- End of event loop: "; sw.Print();

delete myptphoton;
delete myetaphoton;
delete myptmuon;
delete myetamuon;
delete myptjet;
delete myetajet;
delete mymasstop;
//delete mymtw;
delete mydeltaRphotonjet;
delete mydeltaRphotonmuon;
//delete myht;
delete mycostopphoton;
delete mydeltaphiphotonmet;
delete mycvsdiscriminant;
delete myjetmultiplicity;
//delete mybjetmultiplicity;
//delete myleptoncharge;
//delete myplot;
delete input;
}

for(unsigned int idx=1; idx<datasamples_.size(); ++idx){
datahists[idx]->Add(datahists[idx-1]);
}
hList->Add(datahists[2]);

TH1F *data1histrev(0), *data2histrev(0) ,*data3histrev(0), *datahistrevsideband(0);

data1histrev = new TH1F( "BDT__data1histrev",           "BDT__data1histrev",           nbin,min, max );
data2histrev = new TH1F( "BDT__data2histrev",           "BDT__data2histrev",           nbin,min, max );
data3histrev = new TH1F( "BDT__wjet",           "BDT__wjet",           nbin, min, max );
datahistrevsideband = new TH1F( "mu_BDT__DATArevsideband",           "mu_BDT__DATArevsideband",           nbin, min, max );

revDATAhists.push_back(data1histrev);
revDATAhists.push_back(data2histrev);
revDATAhists.push_back(data3histrev);
revDATAhists.push_back(datahistrevsideband);

for(unsigned int idx=0; idx<datasamplesreverse_.size(); ++idx){
   TFile *input(0);

   TString fname =datasamplesreverse_[idx];
   if (!gSystem->AccessPathName( fname )) input = TFile::Open( fname ); // check if file in local directory exists
   else
      input = TFile::Open( "http://root.cern.ch/files/tmva_class_example.root" ); // if not: download from ROOT server

   if (!input) {
      std::cout << "ERROR: could not open data file" << std::endl;
      exit(1);
   }
   std::cout << "--- TMVAClassificationApp    : Using input file: " << input->GetName() << std::endl;

std::vector<double> *myptphoton=0;
std::vector<double> *myetaphoton=0;
 std::vector<double> *myptmuon=0;
 std::vector<double> *myetamuon=0;
 std::vector<double> *myptjet=0;
 std::vector<double> *myetajet=0;
 std::vector<double> *mymasstop=0;
 //std::vector<double> *mymtw=0;
 std::vector<double> *mydeltaRphotonjet=0;
std::vector<double> *mydeltaRphotonmuon=0;
 //std::vector<double> *myht=0;
 std::vector<double> *mycostopphoton=0;
 std::vector<double> *mydeltaphiphotonmet=0;
 std::vector<double> *mycvsdiscriminant=0;
 std::vector<double> *myjetmultiplicity=0;
std::vector<double> *mycoswphoton=0;
 //std::vector<double> *mybjetmultiplicity=0;
 //std::vector<double> *myleptoncharge=0;
std::vector<double> *myphiphoton=0;
std::vector<double> *mysigmaietaieta=0;


   TTree* theTree = (TTree*)input->Get("analyzestep2/atq");
   theTree->SetBranchAddress("ptphoton", &myptphoton  );
   theTree->SetBranchAddress( "etaphoton", &myetaphoton );
   theTree->SetBranchAddress( "ptmuon", &myptmuon );
   theTree->SetBranchAddress( "etamuon", &myetamuon );
   theTree->SetBranchAddress( "ptjet", &myptjet );
   theTree->SetBranchAddress( "etajet", &myetajet );
   theTree->SetBranchAddress( "masstop", &mymasstop );
//   theTree->SetBranchAddress( "mtw", &mymtw );
   theTree->SetBranchAddress( "deltaRphotonjet", &mydeltaRphotonjet );
   theTree->SetBranchAddress( "deltaRphotonmuon", &mydeltaRphotonmuon );
//   theTree->SetBranchAddress( "ht", &myht );
    theTree->SetBranchAddress( "costopphoton", &mycostopphoton );
    theTree->SetBranchAddress( "jetmultiplicity", &myjetmultiplicity );
//   theTree->SetBranchAddress( "bjetmultiplicity", &mybjetmultiplicity );
    theTree->SetBranchAddress( "deltaphiphotonmet", &mydeltaphiphotonmet );
    theTree->SetBranchAddress( "cvsdiscriminant", &mycvsdiscriminant );
   theTree->SetBranchAddress( "coswphoton", &mycoswphoton );
//   theTree->SetBranchAddress( "leptoncharge", &myleptoncharge );
theTree->SetBranchAddress( "phiphoton", &myphiphoton );
 theTree->SetBranchAddress( "sigmaieta", &mysigmaietaieta );
 
 // Efficiency calculator for cut method
 
              std::cout << "--- Processing: " << theTree->GetEntries() << " events" << std::endl;
                 TStopwatch sw;
                    sw.Start();
                       for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) {
                       //   std::cout << "--- ... Processing event: " << ievt << std::endl;
                             if (ievt%5000 == 0) std::cout << "--- ... Processing event: " << ievt << std::endl;
 
                                   theTree->GetEntry(ievt);
                                   //for (int l=0;l<sizeof(myptphoton);l++){
 if(sqrt(pow((*myetaphoton )[0]+1.76,2)+pow((*myphiphoton )[0]-1.37,2))>0.05 && sqrt(pow((*myetaphoton )[0]-2.37,2)+pow((*myphiphoton )[0]-2.69,2))>0.05){
if(sqrt(pow((*myetaphoton )[0]- 1.61,2)+pow((*myphiphoton )[0]+2.05,2))>0.05 && sqrt(pow((*myetaphoton )[0]-1.75,2)+pow((*myphiphoton )[0]-2.12,2))>0.05){
if ((abs((*myetaphoton )[0]) >1.444 && (*mysigmaietaieta)[0] >0.031)||(abs((*myetaphoton )[0]) <1.444 && (*mysigmaietaieta)[0] >0.011)) {
if((*mymasstop )[0]>mtopdown && (*mymasstop )[0]<mtopup) {
revDATAhists[idx]->Fill( (*mydeltaRphotonjet)[0]);
insidewjet=insidewjet+1;}
else {revDATAhists[3]->Fill( (*mydeltaRphotonjet)[0] );
outsidewjet=outsidewjet+1;}
}}}
}
   sw.Stop();
   std::cout << "--- End of event loop: "; sw.Print();

delete myptphoton;
delete myetaphoton;
delete myptmuon;
delete myetamuon;
delete myptjet;
delete myetajet;
delete mymasstop;
//delete mymtw;
delete mydeltaRphotonjet;
delete mydeltaRphotonmuon;
//delete myht;
delete mycostopphoton;
delete mydeltaphiphotonmet;
delete mycvsdiscriminant;
delete myjetmultiplicity;
////delete mybjetmultiplicity;
////delete myleptoncharge;
////delete myplot;
//
delete input;
}


double wphjetscale;
wphjetscale=insidewphjet/(insidewphjet+outsidewphjet);
double wjetscale;
wjetscale=insidewjet/(insidewjet+outsidewjet);
//cout<<insidewphjet<<"insidewphjet"<<"       "<<wphjetscale<<"       "<<insidewjet/(insidewjet+outsidewjet)<<endl;
float lumi = 1;
for(unsigned int idx=1; idx<datasamplesreverse_.size(); ++idx){
revDATAhists[idx]->Add(revDATAhists[idx-1]);
 } 
revDATAhists[2]->Scale(302.91/revDATAhists[2]->Integral());
for(unsigned int idx=1; idx<revDATAhists[2]->GetNbinsX()+1; ++idx){
revDATAhists[2]->SetBinError(idx,(revDATAhists[2]->GetBinContent(idx)/revDATAhists[2]->Integral())*74.84);
//if (revDATAhists[2]->GetBinError(idx)>revDATAhists[2]->GetBinContent(idx)) revDATAhists[2]->SetBinError(idx, revDATAhists[2]->GetBinContent(idx)/2); 
}

hList->Add(revDATAhists[2]);
revDATAhists[3]->Scale(302.91/revDATAhists[3]->Integral());
revDATAhists[3]->Scale((1-wjetscale)/wjetscale);

//cout<<revDATAhists[2]->Integral()<<endl;

datahists[3]->Add(revDATAhists[3],-1);
datahists[3]->Add(iSBhists[0],-1);
datahists[3]->Add(iSBhists[1],-1);

for(unsigned int idx=3; idx<samples_.size()-5; ++idx){
datahists[3]->Add(iSBhists[idx],-1);}
for(unsigned int idx=1; idx<nbin; ++idx){
if (datahists[3]->GetBinContent(idx)<0)datahists[3]->SetBinContent(idx,0);
} 
datahists[3]->Scale(985.18/datahists[3]->Integral());
for(unsigned int idx=1; idx<datahists[3]->GetNbinsX()+1; ++idx){
datahists[3]->SetBinError(idx,(datahists[3]->GetBinContent(idx)/datahists[3]->Integral())*139.11);}
hList->Add(datahists[3]);

cout<<datahists[3]->Integral()<<endl;
/////////////////////////////////////////////////////////////////////////
std::vector<string> signalsystematics;
std::vector<string> signalsamples_;


signalsystematics.push_back("__Qscale__plus");
signalsystematics.push_back("__Qscale__minus");
signalsystematics.push_back("__Topmass__plus");
signalsystematics.push_back("__Topmass__minus");

signalsamples_.push_back("SIGNALtGu_scaleup.root");
signalsamples_.push_back("SIGNALtGu_scaledown.root");
signalsamples_.push_back("SIGNALtGu_massup.root");
signalsamples_.push_back("SIGNALtGu_massdown.root");

float signalscales[] ={0.1084/19.145,0.0933/19.145,0.0838/19.145,0.0892/19.145};

for(unsigned int phi=0; phi<signalsystematics.size(); ++phi){

TH1F *shist5(0) , *shist10(0), *shist20(0), *shist30(0), *shist40(0);
std::vector<TH1F*> Shists;

shist5 = new TH1F( std::string("BDT__signal5").append(signalsystematics[phi]).c_str(),std::string("BDT__signal5").append(signalsystematics[phi]).c_str()  ,nbin, min, max    );
shist10 = new TH1F( std::string("BDT__signal10").append(signalsystematics[phi]).c_str(),std::string("BDT__signal10").append(signalsystematics[phi]).c_str() ,nbin,  min, max   );
shist20 = new TH1F( std::string("BDT__signal20").append(signalsystematics[phi]).c_str(),std::string("BDT__signal20").append(signalsystematics[phi]).c_str() ,nbin, min, max    );
shist30 = new TH1F( std::string("BDT__signal30").append(signalsystematics[phi]).c_str(),std::string("BDT__signal30").append(signalsystematics[phi]).c_str() ,nbin, min, max  );
shist40 = new TH1F( std::string("BDT__signal40").append(signalsystematics[phi]).c_str(),std::string("BDT__signal40").append(signalsystematics[phi]).c_str() ,nbin,min, max  );

Shists.push_back(shist5);
Shists.push_back(shist10);
Shists.push_back(shist20);
Shists.push_back(shist30);
Shists.push_back(shist40);

for(unsigned int idx=0; idx<Shists.size(); ++idx){
Shists[idx]->Sumw2();}

TFile *input(0);
TString fname;
fname =signalsamples_[phi];
input = TFile::Open( fname );
std::vector<double> *myptphoton=0;
std::vector<double> *myetaphoton=0;
std::vector<double> *myptmuon=0;
std::vector<double> *myetamuon=0;
std::vector<double> *myptjet=0;
std::vector<double> *myetajet=0;
std::vector<double> *mymasstop=0;
//std::vector<double> *mymtw=0;
std::vector<double> *mydeltaRphotonjet=0;
std::vector<double> *mydeltaRphotonmuon=0;
//std::vector<double> *myht=0;
std::vector<double> *mycostopphoton=0;
std::vector<double> *mydeltaphiphotonmet=0;
std::vector<double> *mycvsdiscriminant=0;
std::vector<double> *myjetmultiplicity=0;
//std::vector<double> *mybjetmultiplicity=0;
//std::vector<double> *myleptoncharge=0;
std::vector<double> *myweight=0;
std::vector<double> *mybtagSF=0;
std::vector<double> *mybtagSFup=0;
std::vector<double> *mybtagSFdown=0;
std::vector<double> *mymistagSFup=0;
std::vector<double> *mymistagSFdown=0;
std::vector<double> *mytriggerSF=0;
std::vector<double> *mytriggerSFup=0;
std::vector<double> *mytriggerSFdown=0;
std::vector<double> *myphotonSF=0;
std::vector<double> *myphotonSFup=0;
std::vector<double> *myphotonSFdown=0;
std::vector<double> *mypileupSF=0;
std::vector<double> *mypileupSFup=0;
std::vector<double> *mypileupSFdown=0;
std::vector<double> *mymuonSFup=0;
std::vector<double> *mymuonSFdown=0;
std::vector<double> *mymuonSF=0;
std::vector<double> *myjetmatchinginfo=0;
std::vector<double> *mycoswphoton=0;


   std::cout << "--- Select signal sample" << std::endl;
   TTree* theTree = (TTree*)input->Get("analyzestep2/atq");

   theTree->SetBranchAddress("ptphoton", &myptphoton  );
   theTree->SetBranchAddress( "etaphoton", &myetaphoton );
   theTree->SetBranchAddress( "ptmuon", &myptmuon );
   theTree->SetBranchAddress( "etamuon", &myetamuon );
   theTree->SetBranchAddress( "ptjet", &myptjet );
   theTree->SetBranchAddress( "etajet", &myetajet );
   theTree->SetBranchAddress( "masstop", &mymasstop );
//   theTree->SetBranchAddress( "mtw", &mymtw );
   theTree->SetBranchAddress( "deltaRphotonjet", &mydeltaRphotonjet );
   theTree->SetBranchAddress( "deltaRphotonmuon", &mydeltaRphotonmuon );
//   theTree->SetBranchAddress( "ht", &myht );
   theTree->SetBranchAddress( "costopphoton", &mycostopphoton );
   theTree->SetBranchAddress( "jetmultiplicity", &myjetmultiplicity );
//   theTree->SetBranchAddress( "bjetmultiplicity", &mybjetmultiplicity );
   theTree->SetBranchAddress( "deltaphiphotonmet", &mydeltaphiphotonmet );
   theTree->SetBranchAddress( "cvsdiscriminant", &mycvsdiscriminant );
   theTree->SetBranchAddress( "coswphoton", &mycoswphoton );
//   theTree->SetBranchAddress( "leptoncharge", &myleptoncharge );
   theTree->SetBranchAddress( "weight", &myweight);
   theTree->SetBranchAddress( "btagSF", &mybtagSF);
   theTree->SetBranchAddress( "btagSFup", &mybtagSFup);
   theTree->SetBranchAddress( "btagSFdown", &mybtagSFdown);
   theTree->SetBranchAddress( "mistagSFup", &mymistagSFup);
   theTree->SetBranchAddress( "mistagSFdown", &mymistagSFdown);
   theTree->SetBranchAddress( "triggerSF", &mytriggerSF);
   theTree->SetBranchAddress( "triggerSFup", &mytriggerSFup);
   theTree->SetBranchAddress( "triggerSFdown", &mytriggerSFdown);
   theTree->SetBranchAddress( "photonSF", &myphotonSF);
   theTree->SetBranchAddress( "photonSFup", &myphotonSFup);
   theTree->SetBranchAddress( "photonSFdown", &myphotonSFdown);
   theTree->SetBranchAddress( "muonSF", &mymuonSF);
   theTree->SetBranchAddress( "muonSFup", &mymuonSFup);
   theTree->SetBranchAddress( "muonSFdown", &mymuonSFdown);
   theTree->SetBranchAddress( "pileupSF", &mypileupSF);
   theTree->SetBranchAddress( "pileupSFup", &mypileupSFup);
   theTree->SetBranchAddress( "pileupSFdown", &mypileupSFdown);
   theTree->SetBranchAddress( "jetmatchinginfo", &myjetmatchinginfo );

   for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) {
   double finalweight;
   theTree->GetEntry(ievt);

finalweight=(*myweight)[0];

//cout<<(*myweight)[0]<<endl;

if((*mymasstop )[0]>mtopdown && (*mymasstop )[0]<mtopup){
Shists[0] ->Fill( (*mydeltaRphotonjet)[0],finalweight*signalscales[phi]);
Shists[1] ->Fill((*mydeltaRphotonjet)[0],finalweight*signalscales[phi]);
Shists[2] ->Fill( (*mydeltaRphotonjet)[0],finalweight*signalscales[phi]);
Shists[3] ->Fill( (*mydeltaRphotonjet)[0],finalweight*signalscales[phi]);
Shists[4] ->Fill( (*mydeltaRphotonjet)[0],finalweight*signalscales[phi]);
}
}

delete myptphoton;
delete myetaphoton;
delete myptmuon;
delete myetamuon;
delete myptjet;
delete myetajet;
delete mymasstop;
//delete mymtw;
delete mydeltaRphotonjet;
delete mydeltaRphotonmuon;
//delete myht;
delete mycostopphoton;
delete mydeltaphiphotonmet;
delete mycvsdiscriminant;
delete myjetmultiplicity;
//delete mybjetmultiplicity;
//delete myleptoncharge;
//delete myplot;
delete mybtagSF;
delete mybtagSFup;
delete mybtagSFdown;
delete mymistagSFup;
delete mytriggerSF;
delete mytriggerSFup;
delete mytriggerSFdown;
delete myphotonSF;
delete myphotonSFup;
delete myphotonSFdown;
delete mypileupSF;
delete mypileupSFup;
delete mypileupSFdown;
delete input;
delete myjetmatchinginfo;
/*Shists[0]->Scale(5/Shists[0]->Integral());
Shists[1]->Scale(10/Shists[1]->Integral());
Shists[2]->Scale(20/Shists[2]->Integral());
Shists[3]->Scale(30/Shists[3]->Integral());
*/
//Shists[4]->Scale(40/Shists[4]->Integral());

//hList->Add(Shists[0]);
//hList->Add(Shists[1]);
//hList->Add(Shists[2]);
//hList->Add(Shists[3]);
hList->Add(Shists[4]);
}


/////////////////////////////////////////////////////////////////////////
TFile *target  = new TFile( "DELTARIPHJET.root","RECREATE" );
  hList->Write();
   target->Close();
}
Example #20
0
void analyzeJES(std::vector<std::string> urls, const char *outname = "eventObjects.root", Long64_t nentries = 20, Int_t firstF = -1, Int_t lastF = -1, Int_t firstEvent = 0) {

  /*
    ptminType: minimum raw pt for particles used by puppi
    0 : 0 GeV
    1 : 1 GeV
    2 : 2 GeV

    jetSignalType: jets used to select jetty region in events
    0 : detector-level jets (akPu4PF)
    1 : particle-level jets (gen jets)
   */

  const int njetTypes = 3;//4;
  int rad[njetTypes] = {3,4,5};//{2,3,4,5};
  TString jetName[njetTypes] = {"aktR030","aktR040","aktR050"};
  TString jetTreeName[njetTypes] = {"ak3PFJetAnalyzer","ak4PFJetAnalyzer","ak5PFJetAnalyzer",};
  //TString jetName[njetTypes] = {"aktR020","aktR030","aktR040","aktR050"};
  //TString jetTreeName[njetTypes] = {"ak2PFJetAnalyzer","ak3PFJetAnalyzer","ak4PFJetAnalyzer","ak5PFJetAnalyzer",};

  for(int i = 0; i<njetTypes; ++i)
    std::cout << "analyzing JES for: " << jetName[i] << " tree: " << jetTreeName[i] << std::endl;
   
  std::cout << "nfiles: " << urls.size() << std::endl;
  for (auto i = urls.begin(); i != urls.end(); ++i)
    std::cout << *i << std::endl;

  size_t firstFile = 0;
  size_t lastFile = urls.size();

  if(firstF>-1) {
    firstFile = (size_t)firstF;
    lastFile = (size_t)lastF;
  }
  std::cout << "firstFile: " << firstFile << "  lastFile: " << lastFile << std::endl;

  Int_t lastEvent = nentries;
  if(firstEvent>0) {
    lastEvent = firstEvent + nentries;
  }
  std::cout << "firstEvent: " << firstEvent << std::endl;
  
  //add files to chain
  TChain *chain = NULL;
  chain = new TChain("hiEvtAnalyzer/HiTree");
  for(size_t i=firstFile; i<lastFile; i++) chain->Add(urls[i].c_str());
  Printf("hiTree done");
  
  TChain *jetTree[njetTypes];
  for(int ij = 0; ij<njetTypes; ++ij) {
    jetTree[ij] = new TChain(Form("%s/t",jetTreeName[ij].Data()));
    for(size_t i=firstFile; i<lastFile; i++) jetTree[ij]->Add(urls[i].c_str());
    //chain->AddFriend(jetTree[ij]);
    Printf("jetTree %s done",jetTreeName[ij].Data());
  }

  TList *fEventObjects = new TList();

  //---------------------------------------------------------------
  // producers
  //
  hiEventProducer *p_evt = new hiEventProducer("hiEvtProd");
  p_evt->SetInput(chain);
  p_evt->SetHIEventContName("hiEventContainer");
  p_evt->SetEventObjects(fEventObjects);

  lwJetFromForestProducer *p_PUJet[njetTypes];
  for(int ij = 0; ij<njetTypes; ++ij) {
    p_PUJet[ij] = new lwJetFromForestProducer(Form("lwJetForestProd_%d",ij));
    p_PUJet[ij]->SetInput(jetTree[ij]);
    p_PUJet[ij]->SetJetContName(jetName[ij]);
    p_PUJet[ij]->SetGenJetContName(Form("akt%dGen",rad[ij]));
    p_PUJet[ij]->SetEventObjects(fEventObjects);
    p_PUJet[ij]->SetRadius((double)rad[ij]/10.);
  }
  
  //---------------------------------------------------------------
  //analysis modules
  //

  //handler to which all modules will be added
  anaBaseTask *handler = new anaBaseTask("handler","handler");

  anaJetEnergyScale *anajesForest[njetTypes];
  for(int ij = 0; ij<njetTypes; ++ij) {
    anajesForest[ij] = new anaJetEnergyScale(Form("anaJESForest_%d",rad[ij]),Form("anaJESForest_%d",rad[ij]));
    anajesForest[ij]->ConnectEventObject(fEventObjects);
    anajesForest[ij]->SetHiEvtName("hiEventContainer");
    anajesForest[ij]->SetGenJetsName(Form("akt%dGen",rad[ij]));
    anajesForest[ij]->SetRecJetsName(jetName[ij]);
    anajesForest[ij]->SetNCentBins(1);
    anajesForest[ij]->SetUseForestMatching(true);
    //anajesForest[ij]->SetMaxDistance(0.2);
    handler->Add(anajesForest[ij]);
  }

  // anaJetEnergyScale *anajesForestQuarks = new anaJetEnergyScale("anaJESForestQuarks","anaJESForestQuarks");
  // anajesForestQuarks->ConnectEventObject(fEventObjects);
  // anajesForestQuarks->SetHiEvtName("hiEventContainer");
  // anajesForestQuarks->SetGenJetsName("akt4Gen");
  // anajesForestQuarks->SetRecJetsName(jetName);
  // anajesForestQuarks->SetNCentBins(1);
  // anajesForestQuarks->SetUseForestMatching(true);
  // //anajesForestQuarks->SetMaxDistance(0.2);
  // anajesForestQuarks->SetRefPartonFlavor(0,2);
  // handler->Add(anajesForestQuarks);

  // anaJetEnergyScale *anajesForestGluons = new anaJetEnergyScale("anaJESForestGluons","anaJESForestGluons");
  // anajesForestGluons->ConnectEventObject(fEventObjects);
  // anajesForestGluons->SetHiEvtName("hiEventContainer");
  // anajesForestGluons->SetGenJetsName("akt4Gen");
  // anajesForestGluons->SetRecJetsName(jetName);
  // anajesForestGluons->SetNCentBins(1);
  // anajesForestGluons->SetUseForestMatching(true);
  // //anajesForestGluons->SetMaxDistance(0.2);
  // anajesForestGluons->SetRefPartonFlavor(21,21);
  // handler->Add(anajesForestGluons);
  
  // anaJetEnergyScale *anajesForestRaw = new anaJetEnergyScale("anaJESForestRaw","anaJESForestRaw");
  // anajesForestRaw->ConnectEventObject(fEventObjects);
  // anajesForestRaw->SetHiEvtName("hiEventContainer");
  // anajesForestRaw->SetGenJetsName("");
  // anajesForestRaw->SetRecJetsName(jetName);
  // anajesForestRaw->SetNCentBins(1);
  // anajesForestRaw->SetUseForestMatching(true);
  // anajesForestRaw->SetUseRawPt(true);
  //handler->Add(anajesForestRaw);

 
  //---------------------------------------------------------------
  //Event loop
  //---------------------------------------------------------------
  Long64_t entries_tot =  chain->GetEntries(); //93064
  if(nentries<0) lastEvent = chain->GetEntries();
  Printf("nentries: %lld  tot: %lld",nentries,entries_tot);
  for (Long64_t jentry=firstEvent; jentry<lastEvent; ++jentry) {
    if(jentry%10000==0) cout << "entry: "<< jentry << endl;
    //Run producers
    //Printf("produce hiEvent");
    p_evt->Run(jentry);   //hi event properties
    //Printf("produce PU jets");
    for(int ij = 0; ij<njetTypes; ++ij)
      p_PUJet[ij]->Run(jentry); //forest jets
	    
    //Execute all analysis tasks
    handler->ExecuteTask();
  }
    
  fEventObjects->Print();

  TFile *out = new TFile(outname,"RECREATE");
  TList *tasks = handler->GetListOfTasks();
  TIter next(tasks);
  anaBaseTask *obj;
  while ((obj = dynamic_cast<anaBaseTask*>(next()) ))
    if(obj->GetOutput()) obj->GetOutput()->Write(obj->GetName(),TObject::kSingleKey);
  
  out->Write();
  out->Close();
  
}
Example #21
0
Bool_t AddPair(AliAnalysisTaskSE *task, Bool_t isMC,Bool_t isMixing, AliPID::EParticleType pType1,Int_t listID1, AliPID::EParticleType pType2,Int_t listID2, Int_t pdgMother,Double_t massMother, AliRsnCutSet *commonEventCuts=0,AliRsnCutSet *commonPairCuts=0, TString name = "") {

   Bool_t valid;
   Int_t useMCMomentum = AliAnalysisManager::GetGlobalInt("rsnUseMCMomentum",valid);
   Bool_t typeSame = (pType1 == pType2);

   Printf("------------- id1=%d id2=%d",pType1,pType2);

   TList *listLoops = new TList;

   // pair definition
   AliRsnPairDef  *pairDefPM         = new AliRsnPairDef((AliRsnDaughter::ESpecies)pType1, '+', (AliRsnDaughter::ESpecies)pType2, '-', pdgMother, massMother);
   AliRsnPairDef  *pairDefMP         = new AliRsnPairDef((AliRsnDaughter::ESpecies)pType1, '-', (AliRsnDaughter::ESpecies)pType2, '+', pdgMother, massMother);
   AliRsnPairDef  *pairDefPP         = new AliRsnPairDef((AliRsnDaughter::ESpecies)pType1, '+', (AliRsnDaughter::ESpecies)pType2, '+', pdgMother, massMother);
   AliRsnPairDef  *pairDefMM         = new AliRsnPairDef((AliRsnDaughter::ESpecies)pType1, '-', (AliRsnDaughter::ESpecies)pType2, '-', pdgMother, massMother);

   // loop object creation
   AliRsnLoopPair *lp = 0;

   // sets +-
   lp = new AliRsnLoopPair(Form("%s.RecPM", name.Data()), pairDefPM, kFALSE);
   listLoops->Add(lp);

   if (!typeSame) {
      lp = new AliRsnLoopPair(Form("%s.RecMP", name.Data()), pairDefMP, kFALSE);
      listLoops->Add(lp);
   }

   // sets +- TRUE pairs
   if (isMC) {
      lp = new AliRsnLoopPair(Form("%s.RecPM_RecMother", name.Data()), pairDefPM, kFALSE);
      lp->SetOnlyTrue(kTRUE);
      lp->SetCheckDecay(kTRUE);
      listLoops->Add(lp);
      if (!typeSame) {
         lp = new AliRsnLoopPair(Form("%s.RecMP_RecMother", name.Data()), pairDefMP, kFALSE);
         lp->SetOnlyTrue(kTRUE);
         lp->SetCheckDecay(kTRUE);
         listLoops->Add(lp);
      }
      // sets +- TRUE paris (MC is used for momentum)
      lp = new AliRsnLoopPair(Form("%s.GenPM_RecMother", name.Data()), pairDefPM, kFALSE);
      lp->SetTrueMC(kTRUE);
      listLoops->Add(lp);
      if (!typeSame) {
         // sets +- TRUE paris (MC is used for momentum)
         lp = new AliRsnLoopPair(Form("%s.GenMP_RecMother", name.Data()), pairDefMP, kFALSE);
         lp->SetTrueMC(kTRUE);
         listLoops->Add(lp);
      }
   }

   // sets ++
   lp = new AliRsnLoopPair(Form("%s.RecPP", name.Data()), pairDefPP, kFALSE);
   listLoops->Add(lp);

   // sets --
   lp = new AliRsnLoopPair(Form("%s.RecMM", name.Data()), pairDefMM, kFALSE);
   listLoops->Add(lp);

   if (isMixing) {
      // sets +- Mixing (NOT mini)
      lp = new AliRsnLoopPair(Form("%s.RecPM_mix", name.Data()), pairDefPM, kTRUE);
      listLoops->Add(lp);

      // sets -+ Mixing (NOT mini)
      lp = new AliRsnLoopPair(Form("%s.RecMP_mix", name.Data()), pairDefMP, kTRUE);
      listLoops->Add(lp);

      // sets ++ Mixing (NOT mini)
      lp = new AliRsnLoopPair(Form("%s.RecPP_mix", name.Data()), pairDefPP, kTRUE);
      listLoops->Add(lp);

      // sets -- Mixing (NOT mini)
      lp = new AliRsnLoopPair(Form("%s.RecMM_mix", name.Data()), pairDefMM, kTRUE);
      listLoops->Add(lp);
   }


   // loops over all AliRsnLoops and sets everything (don't touch it if you don't know what you are doing)
   TIter next(listLoops);
   while ((lp = (AliRsnLoopPair *)next.Next())) {
      lp->SetListID(0, listID1);
      lp->SetListID(1, listID2);
      lp->SetMCRefInfo(useMCMomentum);
      if (commonPairCuts) lp->SetPairCuts(commonPairCuts);
      if (commonEventCuts) lp->SetEventCuts(commonEventCuts);
      if (name.Contains("phi")) AddPairOutputPhi(lp);
      else if (name.Contains("kstar")) AddPairOutputKStar(lp);
      else if (name.Contains("rho")) AddPairOutputRho(lp);
      else if (name.Contains("lambda")) AddPairOutputLambda(lp);
      else if (name.Contains("sigma")) AddPairOutputSigma(lp);
      else continue;
      ((AliRsnAnalysisTask *)task)->AddLoop(lp);
   }
   return kTRUE;
}
Example #22
0
void MultiHistoOverlap(TString namesandlabels, Int_t nOfFiles, const TString& outDir="./"){

  gROOT->Reset();
  gROOT->ProcessLine(".L tdrstyle.C"); 
  gROOT->ProcessLine("setTDRStyle()");
 
 //  gSystem->Load("libRooFit");
 //  using namespace RooFit;
 // preamble
  TPaveText *cmsprel = new TPaveText(0.19, 0.95, 0.95, 0.99, "NDC");
  cmsprel->SetTextSize(0.03);
  cmsprel->SetTextFont(42);
  cmsprel->SetFillColor(0);
  cmsprel->SetBorderSize(0);
  cmsprel->SetMargin(0.01);
  cmsprel->SetTextAlign(12); // align left
  TString text = "CMS Preliminary 2011";
  cmsprel->AddText(0.0, 0.5,text);  
  TString text2 = "#sqrt{s} = 7 TeV  |#eta_{#mu}|<2.4";             
  cmsprel->AddText(0.8, 0.5, text2);


  TList* FileList  = new TList();  
  TList* LabelList = new TList();    
  TObjArray *nameandlabelpairs = namesandlabels.Tokenize(",");  
  for (Int_t i = 0; i < nameandlabelpairs->GetEntries(); ++i) {    
    TObjArray *aFileLegPair = TString(nameandlabelpairs->At(i)->GetName()).Tokenize("=");       
    if(aFileLegPair->GetEntries() == 2) {      
      FileList->Add( TFile::Open(aFileLegPair->At(0)->GetName())  ); 
      LabelList->Add( aFileLegPair->At(1) );    
    } else {      
      std::cout << "Please give file name and legend entry in the following form:\n" 		<< " filename1=legendentry1,filename2=legendentry2\n";          
    }  
  }
  

 Int_t NOfFiles =  FileList->GetSize();  
 if ( NOfFiles!=nOfFiles ){
   std::cout<<"&MSG-e: NOfFiles = "<<nOfFiles<<std::endl;  
   return;
 }  
 

 std::vector<TString> LegLabels;
 LegLabels.reserve(nOfFiles);    
 for(Int_t j=0; j < nOfFiles; j++) {       
   TObjString* legend = (TObjString*)LabelList->At(j);    
   LegLabels.push_back(legend->String());
   std::cout<<"LegLabels["<<j<<"]"<<LegLabels[j]<<std::endl;  
 }

 TLegend *leg=0; 

 TCanvas* c0 = new TCanvas("c0", "c0",50, 20, 800,600);
 TCanvas* c1 = new TCanvas("c1", "c1",50, 20, 800,600);
 TCanvas* c2 = new TCanvas("c2", "c2",50, 20, 800,600);
 TCanvas* c3 = new TCanvas("c3", "c3",50, 20, 800,600);
 TCanvas* c4 = new TCanvas("c4", "c4",50, 20, 800,600);
 TCanvas* c5 = new TCanvas("c5", "c5",50, 20, 1200,800);
 TCanvas* c6 = new TCanvas("c6", "c6",50, 20, 1200,800);

 TCanvas* c0s = new TCanvas("c0s", "c0s",50, 20, 800,600);
 TCanvas* c1s = new TCanvas("c1s", "c1s",50, 20, 800,600);
 TCanvas* c2s = new TCanvas("c2s", "c2s",50, 20, 800,600);
 TCanvas* c3s = new TCanvas("c3s", "c3s",50, 20, 800,600);

 TCanvas* cFit = new TCanvas("cFit", "cFit",50, 20, 1600, 800);


 //----------------- CANVAS C0 --------------//
 c0->SetFillColor(0);  
 c0->cd();

 leg = new TLegend(0.50,0.25,0.90,0.40);  
 leg->SetBorderSize(1);
 leg->SetFillColor(0);
 leg->SetTextFont(42);
 
// Mass VS muon phi plus -------------------------------
 TH1D *histoMassVsPhiPlus[nOfFiles];
 for(Int_t j=0; j < nOfFiles; j++) {     
   
   TFile *fin = (TFile*)FileList->At(j);    
   if (( histoMassVsPhiPlus[j] = (TH1D*)fin->Get("MassVsPhiPlus/allHistos/meanHisto"))){
     histoMassVsPhiPlus[j]->SetLineStyle(linestylelist[j]);
     histoMassVsPhiPlus[j]->SetMarkerColor(colorlist[j]);
     histoMassVsPhiPlus[j]->SetLineColor(colorlist[j]);
     histoMassVsPhiPlus[j]->SetMarkerStyle(markerstylelist[j]); 
     //     histoMassVsPhiPlus[j]->SetMarkerSize(0.75);
     if ( j == 0 ) {
       histoMassVsPhiPlus[j]->GetXaxis()->SetTitle("positive muon #phi (rad)");
       histoMassVsPhiPlus[j]->GetYaxis()->SetTitle("M_{#mu#mu} (GeV)");
       //       histoMassVsPhiPlus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
       histoMassVsPhiPlus[j]->GetYaxis()->SetRangeUser(90.0,91.5);
       histoMassVsPhiPlus[j]->GetXaxis()->SetRangeUser(-3.14,3.14);
       histoMassVsPhiPlus[j]->Draw();
     } else {
       histoMassVsPhiPlus[j]->Draw("SAME");
     }
     leg->AddEntry(histoMassVsPhiPlus[j],LegLabels[j],"PL");  
   }
 }
 //cmsprel->Draw("same");
 leg->Draw("same");
 c0->SaveAs(outDir+"MassVsPhiPlus.png"); 


 //----------------- CANVAS C1 --------------//
 c1->SetFillColor(0);  
 c1->cd();

 leg = new TLegend(0.50,0.25,0.90,0.40);  
 leg->SetBorderSize(1);
 leg->SetFillColor(0);
 leg->SetTextFont(42);
 
// Mass VS muon eta plus -------------------------------
 TH1D *histoMassVsEtaPlus[nOfFiles];
 for(Int_t j=0; j < nOfFiles; j++) {     
   
   TFile *fin = (TFile*)FileList->At(j);    
   if (( histoMassVsEtaPlus[j] = (TH1D*)fin->Get("MassVsEtaPlus/allHistos/meanHisto"))){
     histoMassVsEtaPlus[j]->SetLineStyle(linestylelist[j]);
     histoMassVsEtaPlus[j]->SetMarkerColor(colorlist[j]);
     histoMassVsEtaPlus[j]->SetLineColor(colorlist[j]);
     histoMassVsEtaPlus[j]->SetMarkerStyle(markerstylelist[j]); 
     //     histoMassVsEtaPlus[j]->SetMarkerSize(0.75);
     if ( j == 0 ) {
       histoMassVsEtaPlus[j]->GetXaxis()->SetTitle("positive muon #eta");
       histoMassVsEtaPlus[j]->GetYaxis()->SetTitle("M_{#mu#mu} (GeV)");
       //       histoMassVsEtaPlus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
       histoMassVsEtaPlus[j]->GetYaxis()->SetRangeUser(90.0,91.5);
       histoMassVsEtaPlus[j]->GetXaxis()->SetRangeUser(-2.41,2.41);
       histoMassVsEtaPlus[j]->Draw();
     } else {
       histoMassVsEtaPlus[j]->Draw("SAME");
     }
     leg->AddEntry(histoMassVsEtaPlus[j],LegLabels[j],"PL");  
   }
 }
 //cmsprel->Draw("same");
 leg->Draw("same");
 c1->SaveAs(outDir+"MassVsEtaPlus.png"); 


 //----------------- CANVAS C2 --------------//
 c2->SetFillColor(0);  
 c2->cd();

 leg = new TLegend(0.50,0.25,0.90,0.40);  
 leg->SetBorderSize(1);
 leg->SetFillColor(0);
 leg->SetTextFont(42);
 
// Mass VS muon eta plus - eta minus  -------------------------------
 TH1D *histoMassVsEtaPlusMinusDiff[nOfFiles];
 for(Int_t j=0; j < nOfFiles; j++) {     
   
   TFile *fin = (TFile*)FileList->At(j);    
   if (( histoMassVsEtaPlusMinusDiff[j] = (TH1D*)fin->Get("MassVsEtaPlusMinusDiff/allHistos/meanHisto"))){
     histoMassVsEtaPlusMinusDiff[j]->SetLineStyle(linestylelist[j]);
     histoMassVsEtaPlusMinusDiff[j]->SetMarkerColor(colorlist[j]);
     histoMassVsEtaPlusMinusDiff[j]->SetLineColor(colorlist[j]);
     histoMassVsEtaPlusMinusDiff[j]->SetMarkerStyle(markerstylelist[j]); 
     //     histoMassVsEtaPlusMinusDiff[j]->SetMarkerSize(0.75);
     if ( j == 0 ) {
       histoMassVsEtaPlusMinusDiff[j]->GetXaxis()->SetTitle("#eta pos. muon  #eta neg. muon");
       histoMassVsEtaPlusMinusDiff[j]->GetYaxis()->SetTitle("M_{#mu#mu} (GeV)");
       //       histoMassVsEtaPlusMinusDiff[j]->GetYaxis()->SetRangeUser(88.0,96.0);
       histoMassVsEtaPlusMinusDiff[j]->GetYaxis()->SetRangeUser(90.0,91.5);
       histoMassVsEtaPlusMinusDiff[j]->GetXaxis()->SetRangeUser(-3,3);
       histoMassVsEtaPlusMinusDiff[j]->Draw();
     } else {
       histoMassVsEtaPlusMinusDiff[j]->Draw("SAME");
     }
     leg->AddEntry(histoMassVsEtaPlusMinusDiff[j],LegLabels[j],"PL");  
   }
 }
 //cmsprel->Draw("same");
 leg->Draw("same");
 c2->SaveAs(outDir+"MassVsEtaPlusMinusDiff.png"); 

 //----------------- CANVAS C3 --------------//
 c3->SetFillColor(0);  
 c3->cd();

 leg = new TLegend(0.50,0.25,0.90,0.40);  
 leg->SetBorderSize(1);
 leg->SetFillColor(0);
 leg->SetTextFont(42);
 
// Mass VS muon phi minus -------------------------------
 TH1D *histoMassVsPhiMinus[nOfFiles];
 for(Int_t j=0; j < nOfFiles; j++) {     
   
   TFile *fin = (TFile*)FileList->At(j);    
   if (( histoMassVsPhiMinus[j] = (TH1D*)fin->Get("MassVsPhiMinus/allHistos/meanHisto"))){
     histoMassVsPhiMinus[j]->SetLineStyle(linestylelist[j]);
     histoMassVsPhiMinus[j]->SetMarkerColor(colorlist[j]);
     histoMassVsPhiMinus[j]->SetLineColor(colorlist[j]);
     histoMassVsPhiMinus[j]->SetMarkerStyle(markerstylelist[j]); 
     //     histoMassVsPhiMinus[j]->SetMarkerSize(0.75);
     if ( j == 0 ) {
       histoMassVsPhiMinus[j]->GetXaxis()->SetTitle("negative muon #phi (rad)");
       histoMassVsPhiMinus[j]->GetYaxis()->SetTitle("M_{#mu#mu} (GeV)");
       //       histoMassVsPhiMinus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
       histoMassVsPhiMinus[j]->GetYaxis()->SetRangeUser(90.0,91.5);
       histoMassVsPhiMinus[j]->GetXaxis()->SetRangeUser(-3.14,3.14);
       histoMassVsPhiMinus[j]->Draw();
     } else {
       histoMassVsPhiMinus[j]->Draw("SAME");
     }
     leg->AddEntry(histoMassVsPhiMinus[j],LegLabels[j],"PL");  
   }
 }
 //cmsprel->Draw("same");
 leg->Draw("same");
 c3->SaveAs(outDir+"MassVsPhiMinus.png"); 


 //----------------- CANVAS C4 --------------//
 c4->SetFillColor(0);  
 c4->cd();

 leg = new TLegend(0.50,0.25,0.90,0.40);  
 leg->SetBorderSize(1);
 leg->SetFillColor(0);
 leg->SetTextFont(42);
 
// Mass VS muon eta minus -------------------------------
 TH1D *histoMassVsEtaMinus[nOfFiles];
 for(Int_t j=0; j < nOfFiles; j++) {     
   
   TFile *fin = (TFile*)FileList->At(j);    
   if (( histoMassVsEtaMinus[j] = (TH1D*)fin->Get("MassVsEtaMinus/allHistos/meanHisto"))){
     histoMassVsEtaMinus[j]->SetLineStyle(linestylelist[j]);
     histoMassVsEtaMinus[j]->SetMarkerColor(colorlist[j]);
     histoMassVsEtaMinus[j]->SetLineColor(colorlist[j]);
     histoMassVsEtaMinus[j]->SetMarkerStyle(markerstylelist[j]); 
     //     histoMassVsEtaMinus[j]->SetMarkerSize(0.75);
     if ( j == 0 ) {
       histoMassVsEtaMinus[j]->GetXaxis()->SetTitle("negative muon #eta");
       histoMassVsEtaMinus[j]->GetYaxis()->SetTitle("M_{#mu#mu} (GeV)");
       //       histoMassVsEtaMinus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
       histoMassVsEtaMinus[j]->GetYaxis()->SetRangeUser(90.0,91.5);
       histoMassVsEtaMinus[j]->GetXaxis()->SetRangeUser(-2.41,2.41);
       histoMassVsEtaMinus[j]->Draw();
     } else {
       histoMassVsEtaMinus[j]->Draw("SAME");
     }
     leg->AddEntry(histoMassVsEtaMinus[j],LegLabels[j],"PL");  
   }
 }
 //cmsprel->Draw("same");
 leg->Draw("same");
 c4->SaveAs(outDir+"MassVsEtaMinus.png"); 

 //----------------- CANVAS C5 --------------//
 c5->SetFillColor(0);  
 c5->cd();

 leg = new TLegend(0.50,0.25,0.90,0.40);  
 leg->SetBorderSize(1);
 leg->SetFillColor(0);
 leg->SetTextFont(42);
 
 // Mass VS muon phi plus -------------------------------
 TH2D *histoMassVsEtaPhiPlus[nOfFiles];

 TStyle *newStyle;
 newStyle->SetPalette(1);
 // newStyle->SetOptTitle(1);

 Double_t zMin(82.);
 Double_t zMax(96.);
 for(Int_t j=0; j < nOfFiles; j++) {     
   
   TFile *fin = (TFile*)FileList->At(j);    
   if (( histoMassVsEtaPhiPlus[j] = (TH2D*)fin->Get("MassVsEtaPhiPlus/allHistos/meanHisto"))){
     if ( j == 0 ) {
       histoMassVsEtaPhiPlus[j]->SetTitle(LegLabels[j]);
       histoMassVsEtaPhiPlus[j]->GetXaxis()->SetTitle("positive muon #phi (rad)");
       histoMassVsEtaPhiPlus[j]->GetYaxis()->SetTitle("positive muon #eta");
       zMin = histoMassVsEtaPhiPlus[j]->GetMinimum();
       zMax = histoMassVsEtaPhiPlus[j]->GetMaximum();
       histoMassVsEtaPhiPlus[j]->Draw("COLZ");
       c5->SaveAs(outDir+"MassVsEtaPhiPlus_file0.png"); 
     } else {
       histoMassVsEtaPhiPlus[j]->SetTitle(LegLabels[j]);
       histoMassVsEtaPhiPlus[j]->SetMinimum(zMin);
       histoMassVsEtaPhiPlus[j]->SetMaximum(zMax);
       histoMassVsEtaPhiPlus[j]->Draw("COLZ");
       c5->SaveAs(outDir+"MassVsEtaPhiPlus_file"+(TString)Form("%d",(Int_t)j)+".png"); 
     }

   }
 }
 //cmsprel->Draw("same");

//  //----------------- CANVAS C6 --------------//
//  c6->SetFillColor(0);  
//  c6->cd();

//  leg = new TLegend(0.50,0.25,0.90,0.40);  
//  leg->SetBorderSize(1);
//  leg->SetFillColor(0);
//  leg->SetTextFont(42);
 
//  // Mass VS muon phi minus -------------------------------
//  TH2D *histoMassVsEtaPhiMinus[nOfFiles];

//  for(Int_t j=0; j < nOfFiles; j++) {     
   
//    TFile *fin = (TFile*)FileList->At(j);    
//    if (( histoMassVsEtaPhiMinus[j] = (TH2D*)fin->Get("MassVsEtaPhiMinus/allHistos/meanHisto"))){
//      if ( j == 0 ) {
//        histoMassVsEtaPhiMinus[j]->GetXaxis()->SetTitle("negative muon #phi (rad)");
//        histoMassVsEtaPhiMinus[j]->GetYaxis()->SetTitle("negative muon #eta");
//        zMin = histoMassVsEtaPhiMinus[j]->GetMinimum();
//        zMax = histoMassVsEtaPhiMinus[j]->GetMaximum();
//        histoMassVsEtaPhiMinus[j]->Draw();
//      } else {
//        histoMassVsEtaPhiMinus[j]->SetMinimum(zMin);
//        histoMassVsEtaPhiMinus[j]->SetMaximum(zMax);
//        histoMassVsEtaPhiMinus[j]->Draw("SAME");
//      }
//      leg->AddEntry(histoMassVsEtaPhiMinus[j],LegLabels[j],"PL");  
//    }
//  }
//  //cmsprel->Draw("same");
//  leg->Draw("same");
//  c6->SaveAs(outDir+"MassVsEtaPhiMinus.png"); 

// newStyle->SetOptTitle(0);

 const Color_t colorlist_resol[7]={kBlack,kGreen,kBlue,kMagenta,kCyan,kTeal,kRed};
 const Int_t linestylelist_resol[7]={1,1,1,1,1,1,1};
 const Int_t stylelist_resol[7]={1,1,1,1,1,1,1};
 const Style_t markerstylelist_resol[7]={kOpenCircle,kOpenTriangleUp,kOpenTriangleUp,kOpenCircle,kOpenTriangleUp,kOpenCircle,kOpenTriangleUp};


//  //----------------- CANVAS C0S --------------//
//  c0s->SetFillColor(0);  
//  c0s->cd();

//  leg = new TLegend(0.50,0.25,0.90,0.40);  
//  leg->SetBorderSize(1);
//  leg->SetFillColor(0);
//  leg->SetTextFont(42);

// // Sigma VS muon phi plus -------------------------------
//  TH1D *histoSigmaVsPhiPlus[nOfFiles];
//  for(Int_t j=0; j < nOfFiles; j++) {     
   
//    TFile *fin = (TFile*)FileList->At(j);    
//    if (( histoSigmaVsPhiPlus[j] = (TH1D*)fin->Get("MassVsPhiPlus/allHistos/sigmaHisto"))){
//      histoSigmaVsPhiPlus[j]->SetLineStyle(linestylelist_resol[j]);
//      histoSigmaVsPhiPlus[j]->SetMarkerColor(colorlist_resol[j]);
//      histoSigmaVsPhiPlus[j]->SetLineColor(colorlist_resol[j]);
//      histoSigmaVsPhiPlus[j]->SetMarkerStyle(markerstylelist_resol[j]); 
//      //     histoSigmaVsPhiPlus[j]->SetMarkerSize(0.75);
//      if ( j == 0 ) {
//        histoSigmaVsPhiPlus[j]->GetXaxis()->SetTitle("positive muon #phi (rad)");
//        histoSigmaVsPhiPlus[j]->GetYaxis()->SetTitle("#sigma(M_{#mu#mu}) (GeV)");
//        //       histoSigmaVsPhiPlus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
//        histoSigmaVsPhiPlus[j]->GetYaxis()->SetRangeUser(0.,3.);
//        histoSigmaVsPhiPlus[j]->GetXaxis()->SetRangeUser(-3.14,3.14);
//        histoSigmaVsPhiPlus[j]->Draw();
//      } else {
//        histoSigmaVsPhiPlus[j]->Draw("SAME");
//      }
//      leg->AddEntry(histoSigmaVsPhiPlus[j],LegLabels[j],"PL");  
//    }
//  }
//  //cmsprel->Draw("same");
//  leg->Draw("same");
//  c0s->SaveAs(outDir+"SigmaVsPhiPlus.png"); 


 //----------------- CANVAS C1S --------------//
 c1s->SetFillColor(0);  
 c1s->cd();

 leg = new TLegend(0.50,0.25,0.90,0.40);  
 leg->SetBorderSize(1);
 leg->SetFillColor(0);
 leg->SetTextFont(42);

 
// Sigma VS muon eta plus -------------------------------
 TH1D *histoSigmaVsEtaPlus[nOfFiles];
 for(Int_t j=0; j < nOfFiles; j++) {     
   
   TFile *fin = (TFile*)FileList->At(j);    
   if (( histoSigmaVsEtaPlus[j] = (TH1D*)fin->Get("MassVsEtaPlus/allHistos/sigmaHisto"))){
     histoSigmaVsEtaPlus[j]->SetLineStyle(linestylelist_resol[j]);
     histoSigmaVsEtaPlus[j]->SetMarkerColor(colorlist_resol[j]);
     histoSigmaVsEtaPlus[j]->SetLineColor(colorlist_resol[j]);
     histoSigmaVsEtaPlus[j]->SetMarkerStyle(markerstylelist_resol[j]); 
     //     histoSigmaVsEtaPlus[j]->SetMarkerSize(0.75);
     if ( j == 0 ) {
       histoSigmaVsEtaPlus[j]->GetXaxis()->SetTitle("positive muon #eta");
       histoSigmaVsEtaPlus[j]->GetYaxis()->SetTitle("#sigma(M_{#mu#mu}) (GeV)");
       //       histoSigmaVsEtaPlus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
       histoSigmaVsEtaPlus[j]->GetYaxis()->SetRangeUser(0.,3.);
       histoSigmaVsEtaPlus[j]->GetXaxis()->SetRangeUser(-2.41,2.41);
       histoSigmaVsEtaPlus[j]->Draw();
     } else {
       histoSigmaVsEtaPlus[j]->Draw("SAME");
     }
     leg->AddEntry(histoSigmaVsEtaPlus[j],LegLabels[j],"PL");  
   }
 }
 //cmsprel->Draw("same");
 leg->Draw("same");
 c1s->SaveAs(outDir+"SigmaVsEtaPlus.png"); 


//  //----------------- CANVAS C2S --------------//
//  c2s->SetFillColor(0);  
//  c2s->cd();

//  leg = new TLegend(0.50,0.25,0.90,0.40);  
//  leg->SetBorderSize(1);
//  leg->SetFillColor(0);
//  leg->SetTextFont(42);

// // Sigma VS muon eta plus - eta minus  -------------------------------
//  TH1D *histoSigmaVsEtaPlusMinusDiff[nOfFiles];
//  for(Int_t j=0; j < nOfFiles; j++) {     
   
//    TFile *fin = (TFile*)FileList->At(j);    
//    if (( histoSigmaVsEtaPlusMinusDiff[j] = (TH1D*)fin->Get("MassVsEtaPlusMinusDiff/allHistos/sigmaHisto"))){
//      histoSigmaVsEtaPlusMinusDiff[j]->SetLineStyle(linestylelist_resol[j]);
//      histoSigmaVsEtaPlusMinusDiff[j]->SetMarkerColor(colorlist_resol[j]);
//      histoSigmaVsEtaPlusMinusDiff[j]->SetLineColor(colorlist_resol[j]);
//      histoSigmaVsEtaPlusMinusDiff[j]->SetMarkerStyle(markerstylelist_resol[j]); 
//      //     histoSigmaVsEtaPlusMinusDiff[j]->SetMarkerSize(0.75);
//      if ( j == 0 ) {
//        histoSigmaVsEtaPlusMinusDiff[j]->GetXaxis()->SetTitle("#eta pos. muon - #eta neg. muon");
//        histoSigmaVsEtaPlusMinusDiff[j]->GetYaxis()->SetTitle("#sigma(M_{#mu#mu}) (GeV)");
//        //       histoSigmaVsEtaPlusMinusDiff[j]->GetYaxis()->SetRangeUser(88.0,96.0);
//        histoSigmaVsEtaPlusMinusDiff[j]->GetYaxis()->SetRangeUser(0.,3.);
//        //histoSigmaVsEtaPlusMinusDiff[j]->GetYaxis()->SetRangeUser(90.60,90.75);
//        histoSigmaVsEtaPlusMinusDiff[j]->GetXaxis()->SetRangeUser(-3.2,3.2);
//        histoSigmaVsEtaPlusMinusDiff[j]->Draw();
//      } else {
//        histoSigmaVsEtaPlusMinusDiff[j]->Draw("SAME");
//      }
//      leg->AddEntry(histoSigmaVsEtaPlusMinusDiff[j],LegLabels[j],"PL");  
//    }
//  }
//  //cmsprel->Draw("same");
//  leg->Draw("same");
//  c2s->SaveAs(outDir+"SigmaVsEtaPlusMinusDiff.png"); 


//  //----------------- CANVAS C3S --------------//
//  c3s->SetFillColor(0);  
//  c3s->cd();

//  leg = new TLegend(0.35,0.15,0.55,0.35);  
//  leg->SetBorderSize(1);
//  leg->SetFillColor(0);
//  leg->SetTextFont(42);
 
// // Sigma VS muon pT  -------------------------------
//  TH1D *histoSigmaVsPt[nOfFiles];
//  for(Int_t j=0; j < nOfFiles; j++) {     
   
//    TFile *fin = (TFile*)FileList->At(j);    
//    if (( histoSigmaVsPt[j] = (TH1D*)fin->Get("MassVsPt/allHistos/sigmaHisto"))){
//      histoSigmaVsPt[j]->SetLineStyle(linestylelist_resol[j]);
//      histoSigmaVsPt[j]->SetMarkerColor(colorlist_resol[j]);
//      histoSigmaVsPt[j]->SetLineColor(colorlist_resol[j]);
//      histoSigmaVsPt[j]->SetMarkerStyle(markerstylelist_resol[j]); 
//      //     histoSigmaVsPt[j]->SetMarkerSize(0.75);
//      if ( j == 0 ) {
//        histoSigmaVsPt[j]->GetXaxis()->SetTitle("muon p_T (GeV)");
//        histoSigmaVsPt[j]->GetYaxis()->SetTitle("#sigma(M_{#mu#mu}) (GeV)");
//        //       histoSigmaVsPt[j]->GetYaxis()->SetRangeUser(88.0,96.0);
//        histoSigmaVsPt[j]->GetYaxis()->SetRangeUser(0.,3.);
//        //histoSigmaVsPt[j]->GetYaxis()->SetRangeUser(90.60,90.75);
//        histoSigmaVsPt[j]->GetXaxis()->SetRangeUser(15.,105.);
//        histoSigmaVsPt[j]->Draw();
//      } else {
//        histoSigmaVsPt[j]->Draw("SAME");
//      }
//      leg->AddEntry(histoSigmaVsPt[j],LegLabels[j],"PL");  
//    }
//  }
//  //cmsprel->Draw("same");
//  leg->Draw("same");
//  c3s->SaveAs(outDir+"SigmaVsPt.png"); 

 //----------------- CANVAS CFIT --------------//
 cFit->SetFillColor(0);  
 cFit->cd();
 Float_t nN = TMath::Sqrt(nOfFiles);
 Int_t nX = (Int_t)nN;
 if ( nN-nX > 0.5 ) nX++;
 Int_t nY = (Int_t)(nOfFiles/nX);
 std::cout << nX << " ," << nY << std::endl;
 cFit->Divide(nOfFiles,1);
 
// Mass VS muon phi plus -------------------------------
 TFile *ZFitFile = new TFile("ZFitFile.root","RECREATE");
 RooPlot *histoLineShape[nOfFiles];
 for(Int_t j=0; j < nOfFiles; j++) {     
   
   TFile *fin = (TFile*)FileList->At(j);    
   if (( histoLineShape[j] = (RooPlot*)fin->Get("hRecBestResAllEvents_Mass_frame"))){
     std::cout<<"Writing fit histogrem file n. "<<j<<std::endl;
     histoLineShape[j]->Write();
     cFit->cd(j+1);
     histoLineShape[j]->SetTitle(LegLabels[j]);
     histoLineShape[j]->Draw();
     histoLineShape[j]->GetXaxis()->SetTitle("M_{#mu#mu} (GeV)");
//      TPaveText *cmsprel2 = new TPaveText(0.19, 0.95, 0.95, 0.99, "NDC");
//      cmsprel2->SetTextSize(0.03);
//      cmsprel2->SetTextFont(42);
//      cmsprel2->SetFillColor(0);
//      cmsprel2->SetBorderSize(0);
//      cmsprel2->SetMargin(0.01);
//      cmsprel2->SetTextAlign(12); // align left
//      cmsprel2->AddText(0.666666, 0.5, LegLabels[j]);

   }
 }
 ZFitFile->Close();
 // cmsprel2->Draw("same");
 cFit->SaveAs("ZFitFile.root");


 
 return; 
};
Example #23
0
void fullCombination(analysisType ana)
{
  TString type("");
  bool electrons=false;
  if ( ana==_2eTrack) {
    electrons=true;
    type = "2eTrack";
  }
  else if ( ana==_2globalOrTrackerMu ) type = "2globalOrTrackerMu";
  else if ( ana==_2muTrack ) type = "2muTrack";
  else if ( ana==_2globalMu ) type = "2globalMu";
  else if ( ana==_2trackerMu ) type = "2trackerMu";
  else if ( ana==_2saMu ) type = "2saMu";

  std::map<TString, TList*> categories;
  // Loop over all files
  std::map<TString, double> fw(filesAndWeightsMap( electrons ));
  std::map<TString, double>::const_iterator it = fw.begin();
  for( ; it != fw.end(); ++it ) {
    TString category(getCategory(it->first));

    // Skip unkown categories and signal MC
    if ( category=="" ) {
      std::cout << "Skipping file " << (it->first).Data() << std::endl;
      continue;
    }
    else std::cout << "Got sample " << it->first.Data() << " for category " << category.Data() << std::endl;

    if( categories[category] == 0 ) categories[category] = new TList();

    TString fileName("WeightedFiles/"+std::string(it->first).substr(std::string(it->first).find_last_of("/")+1)+"_weighted_"+type+".root");
    categories[category]->Add( TFile::Open(fileName) );

    // Check for tau version
    if ( category != "Data" && !category.BeginsWith("HTo2LongLived") && !category.BeginsWith("Chi0ToNuLL") ) {
      TString tauFileName("WeightedFiles/"+std::string(it->first).substr(std::string(it->first).find_last_of("/")+1)+"_weighted_"+type+"_tau.root");
      if ( categories["Tau"] == 0 ) categories["Tau"] = new TList();
      std::cout << "Adding tau version : " << tauFileName << std::endl;
      categories["Tau"]->Add( TFile::Open(tauFileName) );
    }
    // Check for d0 corrected fiels
    if ( category == "Data" ) {
      TString correctedFileName("WeightedFiles/"+std::string(it->first).substr(std::string(it->first).find_last_of("/")+1)+"_weighted_"+type+"_tipLipCorrected.root");
      if ( categories["Data_tipLipCorrected"] == 0 ) categories["Data_tipLipCorrected"] = new TList();
      std::cout << "Adding tip lip corrected version : " << correctedFileName << std::endl;
      categories["Data_tipLipCorrected"]->Add( TFile::Open(correctedFileName) );
    }
    else if ( category == "Data22Jan") {
      TString correctedFileName("WeightedFiles/"+std::string(it->first).substr(std::string(it->first).find_last_of("/")+1)+"_weighted_"+type+"_tipLipCorrected.root");
      if ( categories["Data22Jan_tipLipCorrected"] == 0 ) categories["Data22Jan_tipLipCorrected"] = new TList();
      std::cout << "Adding tip lip corrected version : " << correctedFileName << std::endl;
      categories["Data22Jan_tipLipCorrected"]->Add( TFile::Open(correctedFileName) );    }

    //    if ( category=="DYJets" ) {
    //      if ( categories["DYJetsTau"] == 0 ) categories["DYJetsTau"] = new TList();
    //      categories["DYJetsTau"]->Add( TFile::Open("WeightedFiles/"+std::string(it->first).substr(std::string(it->first).find_last_of("/")+1)+"_weighted_"+type+"_tau.root") );
    //    }
  }

  TList * combinationsList = new TList();
  std::map<TString, TList*>::const_iterator it2 = categories.begin();
  for( ; it2 != categories.end(); ++it2 ) {
    std::cout << "Doing category : " << it2->first << std::endl;
    TFile *Target = TFile::Open( "CombinedFiles/"+it2->first+"_combined_"+type+".root", "RECREATE" );
    combinationsList->Add( Target );
    mergeFiles( Target, it2->second );
  }
}
void analyzeZgHistos(std::vector<std::string> urls, const char *outname = "eventObjects.root", Long64_t nentries = 20, Int_t firstF = -1, Int_t lastF = -1, Int_t firstEvent = 0, int activateJetShift = 0) {

  /*
    ptminType: minimum raw pt for particles used by puppi
    0 : 0 GeV
    1 : 1 GeV
    2 : 2 GeV

    jetSignalType: jets used to select jetty region in events
    0 : detector-level jets (akPu4PF)
    1 : particle-level jets (gen jets)
   */

  TString jetSDName = "aktCs4PFSoftDrop";
  TString jetTreeSDName = "akCsSoftDrop4PFJetAnalyzer";//"akCs4PFSoftDropJetAnalyzer";//
  TString jetName = "aktPu4Calo";
  TString jetTreeName = "akPu4CaloJetAnalyzer";

  bool doDRVar = false;

  bool doJetShift = false;
  if(activateJetShift>0) doJetShift = true;
  float jetShift = 0.04;
  if(activateJetShift==1) jetShift = 0.04;
  if(activateJetShift==2) jetShift = -0.04;

  double minptjet = 30.;
  //bool doDijet = false;
  //if(!doDijet) minptjet = 80.;

  std::cout << "analyzing subjets for: " << jetName << " tree: " << jetTreeName << std::endl;
  std::cout << "analyzing subjets for: " << jetSDName << " tree: " << jetTreeSDName << std::endl;
   
  std::cout << "nfiles: " << urls.size() << std::endl;
  for (auto i = urls.begin(); i != urls.end(); ++i)
    std::cout << *i << std::endl;

  size_t firstFile = 0;
  size_t lastFile = urls.size();

  if(firstF>-1) {
    firstFile = (size_t)firstF;
    lastFile = std::min((size_t)lastF,lastFile);
  }
  std::cout << "firstFile: " << firstFile << "  lastFile: " << lastFile << std::endl;

  Int_t lastEvent = nentries;
  if(firstEvent>0) {
    lastEvent = firstEvent + nentries;
  }
  std::cout << "firstEvent: " << firstEvent << std::endl;
  
  //add files to chain
  TChain *chain = NULL;
  chain = new TChain("hiEvtAnalyzer/HiTree");
  for(size_t i=firstFile; i<lastFile; i++) chain->Add(urls[i].c_str());
  Printf("hiTree done");

  TChain *skimTree = new TChain("skimanalysis/HltTree");
  for(size_t i=firstFile; i<lastFile; i++) skimTree->Add(urls[i].c_str());
  chain->AddFriend(skimTree);
  Printf("skimTree done");

  TChain *hltTree = new TChain("hltanalysis/HltTree");
  for(size_t i=firstFile; i<lastFile; i++) hltTree->Add(urls[i].c_str());
  chain->AddFriend(hltTree);
  Printf("hltTree done");

  TChain *jetTreeSD = new TChain(Form("%s/t",jetTreeSDName.Data()));
  for(size_t i=firstFile; i<lastFile; i++) jetTreeSD->Add(urls[i].c_str());
  chain->AddFriend(jetTreeSD);
  Printf("jetTreeSD done");

  TChain *jetTree = new TChain(Form("%s/t",jetTreeName.Data()));
  for(size_t i=firstFile; i<lastFile; i++) jetTree->Add(urls[i].c_str());
  Printf("jetTree done");

  TChain *rhoTree = new TChain("hiFJRhoAnalyzer/t");
  for(size_t i=firstFile; i<lastFile; i++) rhoTree->Add(urls[i].c_str());
  chain->AddFriend(rhoTree);
  
  TList *fEventObjects = new TList();

  //---------------------------------------------------------------
  // producers
  //
  hiEventProducer *p_evt = new hiEventProducer("hiEvtProd");
  p_evt->SetInput(chain);
  p_evt->SetHIEventContName("hiEventContainer");
  p_evt->SetEventObjects(fEventObjects);

  triggerProducer *p_trg = new triggerProducer("trigProd");
  p_trg->SetInput(chain);
  p_trg->SetTriggerMapName("triggerMap");
  p_trg->AddTrigger("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  p_trg->AddTrigger("HLT_HIPuAK4CaloJet100_Eta5p1_Cent30_100_v1");
  p_trg->SetEventObjects(fEventObjects);

  lwJetFromForestProducer *p_SDJet = new lwJetFromForestProducer("lwJetForestProdSD");
  p_SDJet->SetInput(chain);
  p_SDJet->SetJetContName(jetSDName);
  p_SDJet->SetGenJetContName("");
  p_SDJet->SetEventObjects(fEventObjects);
  p_SDJet->SetMinJetPt(minptjet);
  p_SDJet->SetRadius(0.4);

  lwJetFromForestProducer *p_Jet = new lwJetFromForestProducer("lwJetForestProd");
  p_Jet->SetInput(jetTree);
  p_Jet->SetJetContName(jetName);
  p_Jet->SetGenJetContName("akt4Gen");
  p_Jet->SetEventObjects(fEventObjects);
  p_Jet->SetMinJetPt(minptjet);
  p_Jet->SetRadius(0.4);
  
  //---------------------------------------------------------------
  //analysis modules
  //

  //handler to which all modules will be added
  anaBaseTask *handler = new anaBaseTask("handler","handler");

  anaJetQA *jetQA = new anaJetQA("anaJetQA","anaJetQA");
  jetQA->ConnectEventObject(fEventObjects);
  jetQA->SetJetsName(jetName);
  jetQA->SetTriggerMapName("triggerMap");
  jetQA->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  jetQA->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_Cent30_100_v1");
  handler->Add(jetQA);

  anaJetMatching *match = new anaJetMatching("jetMatching","jetMatching");
  match->ConnectEventObject(fEventObjects);
  match->SetHiEvtName("hiEventContainer");
  match->SetTriggerMapName("triggerMap");
  match->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  match->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_Cent30_100_v1");
  match->SetJetsNameBase(jetName);
  match->SetJetsNameTag(jetSDName);
  match->SetMatchingType(0);
  handler->Add(match);

  anaZgHistos *anazghistos = new anaZgHistos("anaZgHistos","anaZgHistos");
  anazghistos->ConnectEventObject(fEventObjects);
  anazghistos->SetHiEvtName("hiEventContainer");
  anazghistos->DoCollisionEventSel(true);
  anazghistos->DoHBHENoiseFilter(true);
  anazghistos->DoHBHENoiseFilterLoose(true);
  anazghistos->DoPrimaryVertexFilter(true);
  anazghistos->DoClusterCompatibilityFilter(true);
  anazghistos->DoHFCoincFilter(true);
  anazghistos->SetTriggerMapName("triggerMap");
  anazghistos->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  anazghistos->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_Cent30_100_v1");
  anazghistos->SetRhoMax(330.);
  anazghistos->SetJetsName(jetSDName);
  anazghistos->SetJetsRefName(jetName);
  anazghistos->SetNCentBins(4);
  anazghistos->SetJetEtaRange(-1.3,1.3);
  anazghistos->SetDeltaRRange(0.1,999.);
  anazghistos->DoJetShift(doJetShift,jetShift);
  handler->Add(anazghistos);

  anaZgHistos *anazghistosdrSmall = new anaZgHistos("anaZgHistosDrSmall","anaZgHistosDrSmall");
  anazghistosdrSmall->ConnectEventObject(fEventObjects);
  anazghistosdrSmall->SetHiEvtName("hiEventContainer");
  anazghistosdrSmall->DoCollisionEventSel(true);
  anazghistosdrSmall->DoHBHENoiseFilter(true);
  anazghistosdrSmall->DoHBHENoiseFilterLoose(true);
  anazghistosdrSmall->DoPrimaryVertexFilter(true);
  anazghistosdrSmall->DoClusterCompatibilityFilter(true);
  anazghistosdrSmall->DoHFCoincFilter(true);
  anazghistosdrSmall->SetTriggerMapName("triggerMap");
  anazghistosdrSmall->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  anazghistosdrSmall->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_Cent30_100_v1");
  anazghistosdrSmall->SetRhoMax(330.);
  anazghistosdrSmall->SetJetsName(jetSDName);
  anazghistosdrSmall->SetJetsRefName(jetName);
  anazghistosdrSmall->SetNCentBins(4);
  anazghistosdrSmall->SetJetEtaRange(-1.3,1.3);
  anazghistosdrSmall->SetDeltaRRange(0.1,0.2);
  anazghistosdrSmall->DoJetShift(doJetShift,jetShift);
  handler->Add(anazghistosdrSmall);

  anaZgHistos *anazghistosdrLarge = new anaZgHistos("anaZgHistosDrLarge","anaZgHistosDrLarge");
  anazghistosdrLarge->ConnectEventObject(fEventObjects);
  anazghistosdrLarge->SetHiEvtName("hiEventContainer");
  anazghistosdrLarge->DoCollisionEventSel(true);
  anazghistosdrLarge->DoHBHENoiseFilter(true);
  anazghistosdrLarge->DoHBHENoiseFilterLoose(true);
  anazghistosdrLarge->DoPrimaryVertexFilter(true);
  anazghistosdrLarge->DoClusterCompatibilityFilter(true);
  anazghistosdrLarge->DoHFCoincFilter(true);
  anazghistosdrLarge->SetTriggerMapName("triggerMap");
  anazghistosdrLarge->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  anazghistosdrLarge->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_Cent30_100_v1");
  anazghistosdrLarge->SetRhoMax(330.);
  anazghistosdrLarge->SetJetsName(jetSDName);
  anazghistosdrLarge->SetJetsRefName(jetName);
  anazghistosdrLarge->SetNCentBins(4);
  anazghistosdrLarge->SetJetEtaRange(-1.3,1.3);
  anazghistosdrLarge->SetDeltaRRange(0.2,999.);
  anazghistosdrLarge->DoJetShift(doJetShift,jetShift);
  handler->Add(anazghistosdrLarge);

  if(doDRVar) {
    anaZgHistos *anazghistosDRVarDown = new anaZgHistos("anaZgHistosDrVarDown","anaZgHistosDrVarDown");
    anazghistosDRVarDown->ConnectEventObject(fEventObjects);
    anazghistosDRVarDown->SetHiEvtName("hiEventContainer");
    anazghistosDRVarDown->DoCollisionEventSel(true);
    anazghistosDRVarDown->DoHBHENoiseFilter(true);
    anazghistosDRVarDown->DoHBHENoiseFilterLoose(true);
    anazghistosDRVarDown->DoPrimaryVertexFilter(true);
    anazghistosDRVarDown->DoClusterCompatibilityFilter(true);
    anazghistosDRVarDown->DoHFCoincFilter(true);
    anazghistosDRVarDown->SetTriggerMapName("triggerMap");
    anazghistosDRVarDown->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
    anazghistosDRVarDown->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_Cent30_100_v1");
    anazghistosDRVarDown->SetRhoMax(330.);
    anazghistosDRVarDown->SetJetsName(jetSDName);
    anazghistosDRVarDown->SetJetsRefName(jetName);
    anazghistosDRVarDown->SetNCentBins(4);
    anazghistosDRVarDown->SetJetEtaRange(-1.3,1.3);
    anazghistosDRVarDown->SetDeltaRRange(0.1*0.85,999.);
    anazghistosDRVarDown->DoJetShift(doJetShift,jetShift);
    handler->Add(anazghistosDRVarDown);

    anaZgHistos *anazghistosDRVarUp = new anaZgHistos("anaZgHistosDrVarUp","anaZgHistosDrVarUp");
    anazghistosDRVarUp->ConnectEventObject(fEventObjects);
    anazghistosDRVarUp->SetHiEvtName("hiEventContainer");
    anazghistosDRVarUp->DoCollisionEventSel(true);
    anazghistosDRVarUp->DoHBHENoiseFilter(true);
    anazghistosDRVarUp->DoHBHENoiseFilterLoose(true);
    anazghistosDRVarUp->DoPrimaryVertexFilter(true);
    anazghistosDRVarUp->DoClusterCompatibilityFilter(true);
    anazghistosDRVarUp->DoHFCoincFilter(true);
    anazghistosDRVarUp->SetTriggerMapName("triggerMap");
    anazghistosDRVarUp->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
    anazghistosDRVarUp->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_Cent30_100_v1");
    anazghistosDRVarUp->SetRhoMax(330.);
    anazghistosDRVarUp->SetJetsName(jetSDName);
    anazghistosDRVarUp->SetJetsRefName(jetName);
    anazghistosDRVarUp->SetNCentBins(4);
    anazghistosDRVarUp->SetJetEtaRange(-1.3,1.3);
    anazghistosDRVarUp->SetDeltaRRange(0.1*1.15,999.);
    anazghistosDRVarUp->DoJetShift(doJetShift,jetShift);
    handler->Add(anazghistosDRVarUp);
  }

  //---------------------------------------------------------------
  //Event loop
  //---------------------------------------------------------------
  Long64_t entries_tot =  chain->GetEntries(); //93064
  if(nentries<0) lastEvent = chain->GetEntries();
  Printf("nentries: %lld  tot: %lld",nentries,entries_tot);
  for (Long64_t jentry=firstEvent; jentry<lastEvent; ++jentry) {
    if(jentry%10000==0) cout << "entry: "<< jentry << endl;
    //Run producers
    //Printf("produce hiEvent");
    p_evt->Run(jentry);   //hi event properties
    p_trg->Run(jentry);
    //Printf("produce jets");
    p_SDJet->Run(jentry); //forest SoftDrop jets
    p_Jet->Run(jentry); //forest jets

    //Execute all analysis tasks
    handler->ExecuteTask();
  }
    
  fEventObjects->Print();

  TFile *out = new TFile(outname,"RECREATE");
  TList *tasks = handler->GetListOfTasks();
  TIter next(tasks);
  anaBaseTask *obj;
  while ((obj = dynamic_cast<anaBaseTask*>(next()) ))
    if(obj->GetOutput()) obj->GetOutput()->Write(obj->GetName(),TObject::kSingleKey);
  
  out->Write();
  out->Close();
  
}
void misalignmentDependence(TCanvas *c1old,
                            Int_t nFiles,TString *names,TString misalignment,Double_t *values,Double_t *phases,TString xvar,TString yvar,
                            TF1 *function,Int_t parameter,TString parametername = "",TString functionname = "",
                            Bool_t resolution = false,
                            TString saveas = "")
{
    cout << saveas << endl;
    if (c1old == 0) return;
    c1old = (TCanvas*)c1old->Clone("c1old");
    if (misalignment == "" || yvar == "") return;
    Bool_t drawfits = (parameter < 0);
    if (parameter < 0)
        parameter = -parameter - 1;   //-1 --> 0, -2 --> 1, -3 --> 2, ...
    TString yaxislabel = nPart(1,parametername);
    TString parameterunits = nPart(2,parametername);
    if (parameterunits != "")
        yaxislabel.Append(" (").Append(parameterunits).Append(")");
    TList *list = c1old->GetListOfPrimitives();
    int n = list->GetEntries() - 2 - (xvar == "");

    setTDRStyle();
    gStyle->SetOptStat(0);
    gStyle->SetOptFit(0);
    gStyle->SetFitFormat("5.4g");
    gStyle->SetFuncColor(2);
    gStyle->SetFuncStyle(1);
    gStyle->SetFuncWidth(1);
    if (!drawfits)
    {
        gStyle->SetCanvasDefW(678);
        gStyle->SetPadRightMargin(0.115);
    }

    TH1 **p = new TH1*[n];
    TF1 **f = new TF1*[n];
    Bool_t used[n];
    for (Int_t i = 0; i < n; i++)
    {
        stringstream s0;
        s0 << "p" << i;
        TString pname = s0.str();
        p[i] = (TH1*)list->/*At(i+1+(xvar == ""))*/FindObject(pname);
        used[i] = (p[i] != 0);
        if (used[i])
            p[i]->SetDirectory(0);
        if (xvar == "" && function == 0)
            continue;
        stringstream s;
        s << function->GetName() << i;
        TString newname = s.str();
        f[i] = (TF1*)function->Clone(newname);
        stufftodelete->Add(f[i]);
    }

    Double_t *result = new Double_t[nFiles];
    Double_t *error  = new Double_t[nFiles];
    if (xvar == "" && function == 0)
    {
        yaxislabel = axislabel(yvar,'y',resolution);
        for (Int_t i = 0; i < nFiles; i++)
        {
            if (!used[i]) continue;
            if (!resolution)
            {
                result[i] = p[i]->GetMean();
                error[i]  = p[i]->GetMeanError();
            }
            else
            {
                result[i] = p[i]->GetRMS();
                error[i]  = p[i]->GetRMSError();
            }
            cout << result[i] << " +/- " << error[i] << endl;
        }
    }
    else
    {
        for (int i = 0; i < n; i++)
        {
            if (!used[i]) continue;
            f[i]->SetLineColor(colors[i]);
            f[i]->SetLineStyle(styles[i]);
            f[i]->SetLineWidth(1);
            p[i]->SetMarkerColor(colors[i]);
            p[i]->SetMarkerStyle(20+i);
            p[i]->SetLineColor(colors[i]);
            p[i]->SetLineStyle(styles[i]);
            p[i]->Fit(f[i],"IM");
            error[i]  = f[i]->GetParError (parameter);
            if (function->GetName() == TString("sine"))
            {
                if (f[i]->GetParameter(0) < 0)
                {
                    f[i]->SetParameter(0,-f[i]->GetParameter(0));
                    f[i]->SetParameter(2,f[i]->GetParameter(2)+pi);
                }
                while(f[i]->GetParameter(2) >= 2*pi)
                    f[i]->SetParameter(2,f[i]->GetParameter(2)-2*pi);
                while(f[i]->GetParameter(2) < 0)
                    f[i]->SetParameter(2,f[i]->GetParameter(2)+2*pi);
            }
            result[i] = f[i]->GetParameter(parameter);
        }
    }


    TCanvas *c1 = TCanvas::MakeDefCanvas();

    if (drawfits && !(xvar == "" && function == 0) && yvar != "")
    {
        TString legendtitle = "[";
        legendtitle.Append(functionname);
        legendtitle.Append("]");
        TLegend *legend = new TLegend(.7,.7,.9,.9,legendtitle,"br");
        stufftodelete->Add(legend);
        TString drawoption = "";
        TH1 *maxp = (TH1*)list->FindObject("maxp");
        if (maxp != 0)
        {
            maxp->Draw();
            drawoption = "same";
        }
        for (int i = 0; i < n; i++)
        {
            if (!used[i]) continue;
            p[i]->Draw(drawoption);
            f[i]->Draw("same");
            drawoption = "same";

            stringstream s;
            s.precision(3);
            s << nPart(1,parametername) << " = " <<  result[i] << " #pm " << error[i];
            if (parameterunits != "") s << " " << parameterunits;
            TString str = s.str();
            legend->AddEntry(p[i],names[i],"pl");
            legend->AddEntry(f[i],str,"l");
        }
        c1->Update();
        Double_t x1min  = .98*gPad->GetUxmin() + .02*gPad->GetUxmax();
        Double_t x2max  = .02*gPad->GetUxmin() + .98*gPad->GetUxmax();
        Double_t y1min  = .98*gPad->GetUymin() + .02*gPad->GetUymax();
        Double_t y2max  = .02*gPad->GetUymin() + .98*gPad->GetUymax();
        Double_t width  = .4*(x2max-x1min);
        Double_t height = (1./20)*legend->GetListOfPrimitives()->GetEntries()*(y2max-y1min);
        width *= 2;
        height /= 2;
        legend->SetNColumns(2);

        Double_t newy2max = placeLegend(legend,width,height,x1min,y1min,x2max,y2max);
        p[0]->GetYaxis()->SetRangeUser(gPad->GetUymin(),(newy2max-.02*gPad->GetUymin())/.98);
        if (maxp != 0)
            maxp->GetYaxis()->SetRangeUser(gPad->GetUymin(),(newy2max-.02*gPad->GetUymin())/.98);

        legend->SetFillStyle(0);
        legend->Draw();
    }
    else
    {
        if (values == 0) return;

        Bool_t phasesmatter = false;
        if (misalignment == "elliptical" || misalignment == "sagitta" || misalignment == "skew")
        {
            if (phases == 0)
            {
                cout << "This misalignment has a phase, but you didn't supply the phases!" << endl
                     << "Can't produce plots depending on the misalignment value." << endl;
                return;
            }
            int firstnonzero = -1;
            for (Int_t i = 0; i < nFiles; i++)
            {
                if (values[i] == 0) continue;                    //if the amplitude is 0 the phase is arbitrary
                if (firstnonzero == -1) firstnonzero = i;
                if (phases[i] != phases[firstnonzero])
                    phasesmatter = true;
            }
        }

        if (!phasesmatter)
        {
            TGraphErrors *g = new TGraphErrors(nFiles,values,result,(Double_t*)0,error);
            g->SetName("");
            stufftodelete->Add(g);

            TString xaxislabel = "#epsilon_{";
            xaxislabel.Append(misalignment);
            xaxislabel.Append("}");
            g->GetXaxis()->SetTitle(xaxislabel);
            if (xvar != "")
            {
                yaxislabel.Append("   [");
                yaxislabel.Append(functionname);
                yaxislabel.Append("]");
            }
            g->GetYaxis()->SetTitle(yaxislabel);

            g->SetMarkerColor(colors[0]);
            g->SetMarkerStyle(20);

            g->Draw("AP");
            Double_t yaxismax = g->GetYaxis()->GetXmax();
            Double_t yaxismin = g->GetYaxis()->GetXmin();
            if (yaxismin > 0)
            {
                yaxismax += yaxismin;
                yaxismin = 0;
            }
            g->GetYaxis()->SetRangeUser(yaxismin,yaxismax);
            g->Draw("AP");
        }
        else
        {
            double *xvalues = new double[nFiles];
            double *yvalues = new double[nFiles];      //these are not physically x and y (except in the case of skew)
            for (int i = 0; i < nFiles; i++)
            {
                xvalues[i] = values[i] * cos(phases[i]);
                yvalues[i] = values[i] * sin(phases[i]);
            }
            TGraph2DErrors *g = new TGraph2DErrors(nFiles,xvalues,yvalues,result,(Double_t*)0,(Double_t*)0,error);
            g->SetName("");
            stufftodelete->Add(g);
            delete[] xvalues;        //A TGraph2DErrors has its own copy of xvalues and yvalues, so it's ok to delete these copies.
            delete[] yvalues;
            
            TString xaxislabel = "#epsilon_{";
            xaxislabel.Append(misalignment);
            xaxislabel.Append("}cos(#delta)");
            TString realyaxislabel = xaxislabel;
            realyaxislabel.ReplaceAll("cos(#delta)","sin(#delta)");
            g->GetXaxis()->SetTitle(xaxislabel);
            g->GetYaxis()->SetTitle(realyaxislabel);
            TString zaxislabel = /*"fake"*/yaxislabel;         //yaxislabel is defined earlier
            if (xvar != "")
            {
                zaxislabel.Append("   [");
                zaxislabel.Append(functionname);
                zaxislabel.Append("]");
            }
            g->GetZaxis()->SetTitle(zaxislabel);
            g->SetMarkerStyle(20);
            g->Draw("pcolerr");
        }
    }

    if (saveas != "")
    {
        saveplot(c1,saveas);
        delete[] p;
        delete[] f;
        delete[] result;
        delete[] error;
        delete c1old;
    }
}
Example #26
0
/********************************************************************************
 *    Copyright (C) 2014 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH    *
 *                                                                              *
 *              This software is distributed under the terms of the             *
 *              GNU Lesser General Public Licence (LGPL) version 3,             *
 *                  copied verbatim in the file "LICENSE"                       *
 ********************************************************************************/
void run_reco( TString mcEngine="TGeant3", Bool_t AlignDone=true )
{
   // ----  Load libraries   -------------------------------------------------
  FairLogger *logger = FairLogger::GetLogger();
//  logger->SetLogFileName("MyLog.log");
  logger->SetLogToScreen(kTRUE);
//  logger->SetLogToFile(kTRUE);
//  logger->SetLogVerbosityLevel("HIGH");
//  logger->SetLogFileLevel("DEBUG4");
  logger->SetLogScreenLevel("INFO");

  // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug)
  Int_t iVerbose = 0; // just forget about it, for the moment

  TString Align= "";
  if (AlignDone) {
    Align= "align_";
  }
  TString InDir = "./data/";
  // Input file (MC Events)
  TString  inFile     ="testrun_";
  inFile = InDir +inFile + Align + mcEngine + ".root";

  // Output file name
  TString  outFile     ="testreco_";
  outFile = InDir + outFile + Align + mcEngine + ".root";

  // Parameter file
  TString  parFile     ="testparams_";
  parFile = InDir + parFile + Align + mcEngine + ".root";

  // Millepede file name
  TString  milleFile     ="testmille_";
  milleFile = InDir + milleFile + Align + mcEngine;

  TList *parFileList = new TList();

  TString workDir = gSystem->Getenv("VMCWORKDIR");
  TString paramDir = workDir + "/simulation/Tutorial4/parameters/";
  TString paramFile = paramDir + "example.par";

  TObjString tutDetDigiFile;
  tutDetDigiFile.SetString(paramFile);
  parFileList->Add(&tutDetDigiFile);

  // -----   Timer   --------------------------------------------------------
  TStopwatch timer;

  // -----   Reconstruction run   -------------------------------------------
  FairRunAna *fRun= new FairRunAna();
  FairFileSource *fFileSource = new FairFileSource(inFile);
  fRun->SetSource(fFileSource);
  fRun->SetSink(new FairRootFileSink(outFile));

  FairRuntimeDb* rtdb = fRun->GetRuntimeDb();
  FairParRootFileIo* parInput1 = new FairParRootFileIo();
  FairParAsciiFileIo* parIo2 = new FairParAsciiFileIo();
  parIo2->open(parFileList, "in");
  parInput1->open(parFile.Data());
  parIo2->open(parFileList, "in");
  rtdb->setFirstInput(parInput1);
  rtdb->setSecondInput(parIo2);
  rtdb->setOutput(parInput1);
  rtdb->saveOutput();

  // -----   TorinoDetector hit  producers   ---------------------------------
  FairTutorialDet4HitProducerIdealMisalign* hitProducer = new FairTutorialDet4HitProducerIdealMisalign();
  hitProducer->DoMisalignment(kFALSE);
  fRun->AddTask(hitProducer);

  FairTutorialDet4StraightLineFitter* fitter = new FairTutorialDet4StraightLineFitter();
  fitter->SetVersion(2);
  fRun->AddTask(fitter);

  FairTutorialDet4MilleWriter* writer = new FairTutorialDet4MilleWriter();
//  writer->SetWriteAscii(kTRUE);
  writer->SetVersion(2);
  writer->SetFileName(milleFile);
  fRun->AddTask(writer);


  fRun->Init();

  timer.Start();
  fRun->Run();

  // -----   Finish   -------------------------------------------------------

  cout << endl << endl;

  // Extract the maximal used memory an add is as Dart measurement
  // This line is filtered by CTest and the value send to CDash
  FairSystemInfo sysInfo;
  Float_t maxMemory=sysInfo.GetMaxMemory();
  cout << "<DartMeasurement name=\"MaxMemory\" type=\"numeric/double\">";
  cout << maxMemory;
  cout << "</DartMeasurement>" << endl;

  timer.Stop();
  Double_t rtime = timer.RealTime();
  Double_t ctime = timer.CpuTime();

  Float_t cpuUsage=ctime/rtime;
  cout << "<DartMeasurement name=\"CpuLoad\" type=\"numeric/double\">";
  cout << cpuUsage;
  cout << "</DartMeasurement>" << endl;

  cout << endl << endl;
  cout << "Output file is "    << outFile << endl;
  cout << "Parameter file is " << parFile << endl;
  cout << "Real time " << rtime << " s, CPU time " << ctime
       << "s" << endl << endl;
  cout << "Macro finished successfully." << endl;
  // ------------------------------------------------------------------------
}
Example #27
0
void StAssociator(Int_t nevents=1,
const char *MainFile="/afs/rhic.bnl.gov/star/data/samples/*.geant.root")
{

  // Dynamically link needed shared libs
  gSystem->Load("St_base");
  gSystem->Load("StChain");
  gSystem->Load("StBFChain");

  gSystem->Load("St_Tables");
  gSystem->Load("StUtilities");
  gSystem->Load("StIOMaker");
  gSystem->Load("StarClassLibrary");
  gSystem->Load("StDetectorDbMaker");


  gSystem->Load("StTpcDb");
  gSystem->Load("StEvent");
//   gSystem->Load("StEventMaker"); //not needed if event.root branch present
  gSystem->Load("StEmcUtil"); 
  gSystem->Load("StEEmcUtil");
  
  gSystem->Load("StMcEvent");
  gSystem->Load("StMcEventMaker");
  gSystem->Load("StAssociationMaker");
  gSystem->Load("StMcAnalysisMaker");
    
  chain = new StChain("StChain"); 
  chain->SetDebug();
   
  // Now we add Makers to the chain...

  StIOMaker* ioMaker = new StIOMaker("IO","r",MainFile,"bfcTree");
  ioMaker->SetDebug();
  ioMaker->SetIOMode("r");
  ioMaker->SetBranch("*",0,"0");                 //deactivate all branches
  ioMaker->SetBranch("geantBranch",0,"r"); //activate geant Branch
  ioMaker->SetBranch("eventBranch",0,"r"); //activate geant Branch
//   ioMaker->SetBranch("dstBranch",0,"r"); //activate Event Branch
//   ioMaker->SetBranch("runcoBranch",0,"r"); //activate runco Branch

  // Note, the title "events" is used in the Association Maker, so don't change it.
  // StEventMaker is not needed for event.root files
//   StEventMaker*       eventReader   = new StEventMaker("events","title");
//   eventReader->doPrintMemoryInfo = kFALSE;
  StMcEventMaker*     mcEventReader = new StMcEventMaker; // Make an instance...
  StAssociationMaker* associator    = new StAssociationMaker;

  // If you need to use L3 TRIGGER uncomment the line:
  // associator->useL3Trigger();
  //associator->SetDebug();
  // For tracks created with the Sti package (ITTF), uncomment the next line:
  //associator->useInTracker();
  // Switch to use the distance or id association.
  associator->useDistanceAssoc();
  //associator->useIdAssoc();
  // Note: useDistanceAssoc and useIdAssoc are mutually exclusive
  // and they set and unset the same flag.
  // The flag will be set by the call done at the end.
  //associator->doPrintMemoryInfo = kTRUE;
  StMcAnalysisMaker*  examples      = new StMcAnalysisMaker;

  // Define the cuts for the Associations

  StMcParameterDB* parameterDB = StMcParameterDB::instance();  
  // TPC
  parameterDB->setXCutTpc(.6); // 6 mm
  parameterDB->setYCutTpc(.6); // 6 mm
  parameterDB->setZCutTpc(.6); // 6 mm
  parameterDB->setReqCommonHitsTpc(3); // Require 3 hits in common for tracks to be associated
  // FTPC
  parameterDB->setRCutFtpc(.3); // 3 mm
  parameterDB->setPhiCutFtpc(5*(3.1415927/180.0)); // 5 degrees
  parameterDB->setReqCommonHitsFtpc(3); // Require 3 hits in common for tracks to be associated
  // SVT
  parameterDB->setXCutSvt(.08); // 800 um
  parameterDB->setYCutSvt(.08); // 800 um
  parameterDB->setZCutSvt(.08); // 800 um
  parameterDB->setReqCommonHitsSvt(1); // Require 1 hits in common for tracks to be associated
    
    
  // now execute the chain member functions

  chain->PrintInfo();
  Int_t initStat = chain->Init(); // This should call the Init() method in ALL makers
  if (initStat) chain->Fatal(initStat, "during Init()");
    
  int istat=0,iev=1;
 EventLoop: if (iev<=nevents && istat!=2) {
   chain->Clear();
   cout << "---------------------- Processing Event : " << iev << " ----------------------" << endl;
   istat = chain->Make(iev); // This should call the Make() method in ALL makers
   if (istat == 2) { cout << "Last  Event Processed. Status = " << istat << endl; }
   if (istat == 3) { cout << "Error Event Processed. Status = " << istat << endl; }
   iev++; goto EventLoop;
 } // Event Loop
  examples->mAssociationCanvas = new TCanvas("mAssociationCanvas", "Histograms",200,10,600,600);
  TCanvas* myCanvas = examples->mAssociationCanvas;
  myCanvas->Divide(2,2);
  
  myCanvas->cd(1);
  gPad->SetLogy(0);
  examples->mTrackNtuple->Draw("(p-prec)/p:commTpcHits","prec!=0");

  TList* dList = chain->GetMaker("StMcAnalysisMaker")->Histograms();
  TH2F* hitRes = dList->At(0);
  TH1F* momRes = dList->At(1);
  TH2F* coordRc = dList->At(2);
  TH2F* coordMc = dList->At(3);
    
  myCanvas->cd(2);
  gPad->SetLogy(0);
  hitRes->Draw("box");
  
  myCanvas->cd(3);
  gPad->SetLogy(0);
  momRes->Draw();
  
  myCanvas->cd(4);
  gPad->SetLogy(0);
  coordRc->SetMarkerStyle(20);
  coordRc->Draw();
    
  myCanvas->cd(4);
  gPad->SetLogy(0);
  coordMc->SetMarkerColor(2);
  coordMc->SetMarkerStyle(20);
  coordMc->Draw("same");
  
  if(iev>200) chain->Finish(); // This should call the Finish() method in ALL makers,
  // comment it out if you want to keep the objects
  // available at the command line after running
  // the macro.

  // To look at the ntuple after the macro has executed:
  // f1 = new TFile("TrackMapNtuple.root");  //This opens the file, and loads the Ntuple
  // TrackNtuple->Draw("px:pxrec")  //Once loaded, the Ntuple is available by name.
  // To look at the Histograms once the Macro has executed:
  // TList* dList = chain->GetMaker("McAnalysis")->Histograms();
  // TH2F* hitRes = dList->At(0);  //or whatever index from 0 to 3
}
Example #28
0
int main(int argc, char* argv[])
{
  TApplication theApp(srcName.Data(), &argc, argv);
//=============================================================================

  if (argc<5) return -1;
  TString sPath = argv[1]; if (sPath.IsNull()) return -1;
  TString sFile = argv[2]; if (sFile.IsNull()) return -1;
  TString sJetR = argv[3]; if (sJetR.IsNull()) return -1;
  TString sSjeR = argv[4]; if (sSjeR.IsNull()) return -1;
//=============================================================================

  sPath.ReplaceAll("#", "/");
//=============================================================================

  double dJetR = -1.;
  if (sJetR=="JetR02") dJetR = 0.2;
  if (sJetR=="JetR03") dJetR = 0.3;
  if (sJetR=="JetR04") dJetR = 0.4;
  if (sJetR=="JetR05") dJetR = 0.5;

  if (dJetR<0.) return -1;
  cout << "Jet R = " << dJetR << endl;
//=============================================================================

  double dSjeR = -1.;
  if (sSjeR=="SjeR01") dSjeR = 0.1;
  if (sSjeR=="SjeR02") dSjeR = 0.2;
  if (sSjeR=="SjeR03") dSjeR = 0.3;
  if (sSjeR=="SjeR04") dSjeR = 0.4;

  if (dSjeR<0.) return -1;
  cout << "Sub-jet R = " << dSjeR << endl;
//=============================================================================

  const double dJetsPtMin  = 0.001;
  const double dCutEtaMax  = 1.6;
  const double dJetEtaMax  = 1.;
  const double dJetAreaRef = TMath::Pi() * dJetR * dJetR;

  fastjet::GhostedAreaSpec areaSpc(dCutEtaMax);
  fastjet::JetDefinition   jetsDef(fastjet::antikt_algorithm, dJetR, fastjet::BIpt_scheme, fastjet::Best);

//fastjet::AreaDefinition  areaDef(fastjet::active_area,areaSpc);
  fastjet::AreaDefinition  areaDef(fastjet::active_area_explicit_ghosts,areaSpc);

//fastjet::JetDefinition   bkgsDef(fastjet::kt_algorithm, 0.2, fastjet::BIpt_scheme, fastjet::Best);
//fastjet::AreaDefinition  aBkgDef(fastjet::active_area_explicit_ghosts, areaSpc);

  fastjet::Selector selectJet = fastjet::SelectorAbsEtaMax(dJetEtaMax);
//fastjet::Selector selectRho = fastjet::SelectorAbsEtaMax(dCutEtaMax-0.2);
//fastjet::Selector selecHard = fastjet::SelectorNHardest(2);
//fastjet::Selector selectBkg = selectRho * (!(selecHard));
//fastjet::JetMedianBackgroundEstimator bkgsEstimator(selectBkg, bkgsDef, aBkgDef);
//fastjet::Subtractor                   bkgSubtractor(&bkgsEstimator);

  fastjet::JetDefinition subjDef(fastjet::antikt_algorithm, dSjeR, fastjet::BIpt_scheme, fastjet::Best);
//=============================================================================

  std::vector<fastjet::PseudoJet> fjInput;
//=============================================================================

  TList *list = new TList();
  TH1D *hWeightSum = new TH1D("hWeightSum", "", 1, 0., 1.); list->Add(hWeightSum);

  TH1D *hJet = new TH1D("hJet", "", 1000, 0., 1000.); hJet->Sumw2(); list->Add(hJet);
  TH2D *hJetNsj = new TH2D("hJetNsj", "", 1000, 0., 1000., 101, -0.5, 100.5); hJetNsj->Sumw2(); list->Add(hJetNsj);

  TH2D *hJetIsj = new TH2D("hJetIsj", "", 1000, 0., 1000., 1000, 0., 1000.); hJetIsj->Sumw2(); list->Add(hJetIsj);
  TH2D *hJet1sj = new TH2D("hJet1sj", "", 1000, 0., 1000., 1000, 0., 1000.); hJet1sj->Sumw2(); list->Add(hJet1sj);
  TH2D *hJet2sj = new TH2D("hJet2sj", "", 1000, 0., 1000., 1000, 0., 1000.); hJet2sj->Sumw2(); list->Add(hJet2sj);
  TH2D *hJetDsj = new TH2D("hJetDsj", "", 1000, 0., 1000., 1000, 0., 1000.); hJetDsj->Sumw2(); list->Add(hJetDsj);

  TH2D *hJetIsz = new TH2D("hJetIsz", "", 1000, 0., 1000., 120, 0., 1.2); hJetIsz->Sumw2(); list->Add(hJetIsz);
  TH2D *hJet1sz = new TH2D("hJet1sz", "", 1000, 0., 1000., 120, 0., 1.2); hJet1sz->Sumw2(); list->Add(hJet1sz);
  TH2D *hJet2sz = new TH2D("hJet2sz", "", 1000, 0., 1000., 120, 0., 1.2); hJet2sz->Sumw2(); list->Add(hJet2sz);
  TH2D *hJetDsz = new TH2D("hJetDsz", "", 1000, 0., 1000., 120, 0., 1.2); hJetDsz->Sumw2(); list->Add(hJetDsz);
//=============================================================================

  HepMC::IO_GenEvent ascii_in(Form("%s/%s.hepmc",sPath.Data(),sFile.Data()), std::ios::in);
  HepMC::GenEvent *evt = ascii_in.read_next_event();

  while (evt) {
    fjInput.resize(0);
    double dXsect  = evt->cross_section()->cross_section() / 1e9;
    double dWeight = evt->weights().back();
    double dNorm = dWeight * dXsect;
    hWeightSum->Fill(0.5, dWeight);

    TVector3 vPar;
    for (HepMC::GenEvent::particle_const_iterator p=evt->particles_begin(); p!=evt->particles_end(); ++p) if ((*p)->status()==1) {
      vPar.SetXYZ((*p)->momentum().px(), (*p)->momentum().py(), (*p)->momentum().pz());

      if ((TMath::Abs(vPar.Eta())<dCutEtaMax)) {
        fjInput.push_back(fastjet::PseudoJet(vPar.Px(), vPar.Py(), vPar.Pz(), vPar.Mag()));
      }
    }
//=============================================================================

    fastjet::ClusterSequenceArea clustSeq(fjInput, jetsDef, areaDef);
    std::vector<fastjet::PseudoJet> includJets = clustSeq.inclusive_jets(dJetsPtMin);
//  std::vector<fastjet::PseudoJet> subtedJets = bkgSubtractor(includJets);
    std::vector<fastjet::PseudoJet> selectJets = selectJet(includJets);
//  std::vector<fastjet::PseudoJet> sortedJets = fastjet::sorted_by_pt(selectJets);

    for (int j=0; j<selectJets.size(); j++) {
      double dJet = selectJets[j].pt();

      hJet->Fill(dJet, dNorm);
//=============================================================================

      fastjet::Filter trimmer(subjDef, fastjet::SelectorPtFractionMin(0.));
      fastjet::PseudoJet trimmdJet = trimmer(selectJets[j]);
      std::vector<fastjet::PseudoJet> trimmdSj = trimmdJet.pieces();

      double nIsj = 0.;
      double d1sj = -1.; int k1sj = -1;
      double d2sj = -1.; int k2sj = -1;
      for (int i=0; i<trimmdSj.size(); i++) {
        double dIsj = trimmdSj[i].pt(); if (dIsj<0.001) continue;

        hJetIsj->Fill(dJet, dIsj, dNorm);
        hJetIsz->Fill(dJet, dIsj/dJet, dNorm);

        if (dIsj>d1sj) {
          d2sj = d1sj; k2sj = k1sj;
          d1sj = dIsj; k1sj = i;
        } else if (dIsj>d2sj) {
          d2sj = dIsj; k2sj = i;
        } nIsj += 1.;
      }

      hJetNsj->Fill(dJet, nIsj, dNorm);
      if (d1sj>0.) { hJet1sj->Fill(dJet, d1sj, dNorm); hJet1sz->Fill(dJet, d1sj/dJet, dNorm); }
      if (d2sj>0.) { hJet2sj->Fill(dJet, d2sj, dNorm); hJet2sz->Fill(dJet, d2sj/dJet, dNorm); }

      if ((d1sj>0.) && (d2sj>0.)) {
        double dsj = d1sj - d2sj;
        double dsz = dsj / dJet;

        hJetDsj->Fill(dJet, dsj, dNorm);
        hJetDsz->Fill(dJet, dsz, dNorm);
      }
    }
//=============================================================================

    delete evt;
    ascii_in >> evt;
  }
//=============================================================================

  TFile *file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  list->Write();
  file->Close();
//=============================================================================

  cout << "DONE" << endl;
  return 0;
}
void
draw2DLimitBFstyle(map<string,TList *>& m_contours,
		     const TString& par1,
		     const TString& par2,
		     const TString& plotprefix,
		     TLegend *legend)
{

  //from here we build the two-dimensional aTGC limit

  TCanvas *finalPlot = new TCanvas("final","limits",500,500);
  finalPlot->cd();

  cout << "Drawing +2s" << endl;

  TList *contLevel = m_contours["+2s"];
  TGraph *curv;

  assert(contLevel);

  curv = (TGraph*)(contLevel->First());

  //curv->GetYaxis()->SetRangeUser(-1.25*curv->GetYaxis()->GetXmax(),
	  			   //+2.0*curv->GetYaxis()->GetXmax());
  //curv->GetYaxis()->SetRangeUser(-0.1,0.15);
  curv->GetYaxis()->SetRangeUser(parmin(par2),parmax(par2));

  curv->SetTitle();
  curv->GetXaxis()->SetTitle(par2latex(par1));
  curv->GetXaxis()->SetTitleFont(42);
  curv->GetYaxis()->SetTitle(par2latex(par2));
  curv->GetYaxis()->SetTitleFont(42);
  curv->GetYaxis()->SetTitleOffset(1.20);

  for (int i=0; i<contLevel->GetSize(); i++) {
    assert(curv);
    curv->SetLineColor(kYellow);
    curv->SetFillColor(kYellow);
    curv->GetXaxis()->SetLimits(parmin(par1),parmax(par1));
    if (!i) {
      curv->Draw("ACF");
      legend->AddEntry(curv,"#pm 2#sigma","F");
    } else 
      curv->Draw("SAME CF");
    curv=(TGraph *)(contLevel->After(curv));
  }

  cout << "Drawing +1s" << endl;
  
  contLevel = m_contours["+1s"];

  curv = (TGraph*)(contLevel->First());

  for (int i=0; i<contLevel->GetSize(); i++) {
    curv->SetLineColor(kGreen);
    curv->SetFillColor(kGreen);
    curv->Draw("SAME CF");
    if (!i) legend->AddEntry(curv,"#pm 1#sigma","F");
    curv=(TGraph *)(contLevel->After(curv));
  }

  cout << "Drawing -1s" << endl;

  contLevel = m_contours["-1s"];
  curv = (TGraph*)(contLevel->First());
  for (int i=0; i<contLevel->GetSize(); i++) {
    curv->SetLineColor(kYellow);
    curv->SetFillColor(kYellow);
    curv->Draw("SAME CF");
    curv=(TGraph *)(contLevel->After(curv));
  }

  cout << "Drawing -2s" << endl;
  
  contLevel = m_contours["-2s"];

  if (!contLevel)
    //  this can happen more often for this contour if there is insufficient
    // sensitivity close to the SM
    cerr << "No contour level for +2s, have to fill in the central region" << endl;
  else {
    curv = (TGraph*)(contLevel->First());
    for (int i=0; i<contLevel->GetSize(); i++) {
      curv->SetFillColor(kWhite);
      curv->SetLineColor(kYellow);
      curv->Draw("SAME CF");
      curv=(TGraph *)(contLevel->After(curv));
    }
  }
  cout << "Drawing median" << endl;
  
  curv = (TGraph*)(m_contours["median"]->First());
  curv->SetLineColor(kBlack);
  curv->SetLineWidth(2);
  curv->SetLineStyle(2);
  curv->Draw("SAME C");

  legend->AddEntry(curv,"Expected","L");
  
  cout << "Drawing obs" << endl;

  contLevel = m_contours["obs"];
  curv = (TGraph*)(contLevel->First());
  for (int i=0; i<contLevel->GetSize(); i++) {
    curv->SetLineColor(kBlack);
    curv->SetLineWidth(2);
    curv->Draw("SAME C");
    if (!i) legend->AddEntry(curv,"Observed","L");
    curv=(TGraph *)(contLevel->After(curv));
  }

  
  TGraph *SMpoint = new TGraph(1);
  SMpoint->SetPoint(1,0,0);
  SMpoint->Draw("SAME Po");
  
  // smLabel = TPaveText(0,
  //                     m_contours["-2s"]->GetYaxis()->GetXmax()/8,
  //                     m_contours["-2s"]->GetXaxis()->GetXmax()/3->5,
  //                     -m_contours["-2s"]->GetYaxis()->GetXmax()/8);
  // smLabel->SetFillStyle(0);
  // smLabel->SetBorderSize(0);
  // smLabel->AddText(" SM");
  // smLabel->Draw();

  legend->Draw();

  TPaveText *text = new TPaveText(0.566,0.87,0.965,1.101,"NDC");
  text->SetFillStyle(0);
  text->SetBorderSize(0);
  text->AddText(Form("95%% CL Limit on %s and %s",par2latex(par1).Data(),par2latex(par2).Data()));
  text->AddText(0,0.35,Form("#intL dt= %.1f fb^{-1}, #sqrt{s} = %d TeV",intlumifbinv,beamcometev));
  text->Draw();

  // text2 = TPaveText(0.155,0.199,0.974,0.244,"NDC");
  // text2->SetFillStyle(0);
  // text2->SetBorderSize(0);
  // text2->AddText("Values outside contour excluded");
  // text2->Draw();

  //text3 = TPaveText(0.506,0.699,0.905,0.758,"NDC");
  //text3->SetFillStyle(0);
  //text3->SetBorderSize(0);
  //text3->AddText(options.flavorText);
  //text3->Draw();    
  
  finalPlot->RedrawAxis();
  finalPlot->ResetAttPad();
  finalPlot->Update();

  finalPlot->Draw();
  finalPlot->Update();
  finalPlot->Modified();
  finalPlot->Update();
  finalPlot->Print(Form("%s.pdf",plotprefix.Data()));
  finalPlot->Print(Form("%s.eps",plotprefix.Data()));
  finalPlot->Print(Form("%s.png",plotprefix.Data()));

}                                                  // draw2DlimitBFstyle
Example #30
0
void MakePlots(TString filename, float zmax=30, int nSmooth=10, TString opt="", TString energy="8TeV", TString lumi=""){
  TString outDir=filename; outDir.Remove(outDir.Last('/')); outDir+="/img/"+opt;
  //outDir="tmp/k5b/";
  //std::map<TString, TH2F *> deltaNLL_map;
  
  /*------------------------------ Plotto */
  TCanvas *c = new TCanvas("c","c");
  
  TFile f_in(filename, "read");
  if(f_in.IsZombie()){
    std::cerr << "File opening error: " << filename << std::endl;
    return;
  }
  
  TList *KeyList = f_in.GetListOfKeys();
  std::cout << KeyList->GetEntries() << std::endl;
  for(int i =0; i <  KeyList->GetEntries(); i++){
    c->Clear();
    TKey *key = (TKey *)KeyList->At(i);
    if(TString(key->GetClassName())!="RooDataSet") continue;
    RooDataSet *dataset = (RooDataSet *) key->ReadObj();
    if(dataset==NULL){
      std::cerr << "[WARNING] No dataset for " << key->GetName() << "\t" << key->GetTitle() << std::endl;
      continue;
    }
    TString constTermName = dataset->GetName();
    TString alphaName=constTermName; alphaName.ReplaceAll("constTerm","alpha");

    if(constTermName.Contains("absEta_1_1.4442-gold")) continue;
    if(constTermName.Contains("rho") || constTermName.Contains("phi")) continue;
        if(constTermName.Contains("scale")) continue;
    TTree *tree = dataset2tree(dataset);
    TGraphErrors bestFit_ = bestFit(tree, alphaName, constTermName);
    //    TString binning="(241,-0.0005,0.2405,60,0.00025,0.03025)"; 
    TString binning="(241,-0.0005,0.2405,301,-0.00005,0.03005)"; 
    
    TH2F *hist = prof2d(tree, constTermName, alphaName, "nll", binning, true,nSmooth, opt);
//     std::cout << "Bin width = " << hist->GetXaxis()->GetBinWidth(10) << "\t" << hist->GetYaxis()->GetBinWidth(10) << std::endl; 
//     std::cout << "Bin 1 center = " << hist->GetXaxis()->GetBinCenter(1) << "\t" << hist->GetYaxis()->GetBinCenter(1) << std::endl; 
//     std::cout << "Bin 10 center = " << hist->GetXaxis()->GetBinCenter(10) << "\t" << hist->GetYaxis()->GetBinCenter(10) << std::endl; 
//     return;
    hist->Draw("colz");
    hist->GetZaxis()->SetRangeUser(0,zmax);
    hist->GetXaxis()->SetRangeUser(0,0.15);
    hist->GetYaxis()->SetRangeUser(0,0.018);

    hist->GetXaxis()->SetTitle("#Delta S");
    hist->GetYaxis()->SetTitle("#Delta C");

    Int_t iBinX, iBinY;
    Double_t x,y;
    hist->GetBinWithContent2(0.0002,iBinX,iBinY,1,-1,1,-1,0.0000001);
    x= hist->GetXaxis()->GetBinCenter(iBinX);
    y= hist->GetYaxis()->GetBinCenter(iBinY);
    std::cout << "Best Fit: " << x << "\t" << y << std::endl;
    TGraph nllBestFit(1,&x,&y);

    TString fileName=outDir+"/"+constTermName;
    fileName+="-"; fileName+=nSmooth;
    
    nllBestFit.SetMarkerStyle(3);
    nllBestFit.SetMarkerColor(kRed);
    nllBestFit.Draw("P same");

    std::cout << fileName << std::endl;
    ofstream fout(fileName+".dat", ios_base::app);
    fout << constTermName << "\t" << x << "\t" << y << std::endl;


    c->SaveAs(fileName+".png");
    c->SaveAs(fileName+".eps");
    if(fileName.Contains("constTerm")) c->SaveAs(fileName+".C");

    fileName+="-zoom";
    hist->GetZaxis()->SetRangeUser(0,1);
    //hist->GetXaxis()->SetRangeUser(0.00,0.12);
    //hist->GetYaxis()->SetRangeUser(0,0.005);
    c->SaveAs(fileName+".png");
    c->SaveAs(fileName+".eps");


//     hist->SaveAs(outDir+"/deltaNLL-"+constTermName+".root");
//     hist->Draw("colz");
//     bestFit_.Draw("P same");
//     bestFit_.SetMarkerSize(2);


    
//     nllBestFit.SetMarkerStyle(3);
//     nllBestFit.SetMarkerColor(kRed);
//     TList* contour68 = contourFromTH2(hist, 0.68);

//     hist->Draw("colz");
//     hist->GetZaxis()->SetRangeUser(0,zmax);
//     //bestFit_.Draw("P same");
//     nllBestFit.Draw("P same");
//     //contour68->Draw("same");
    delete hist;
    RooAbsPdf *histPdf = NULL;
    if(!opt.Contains("keys")){
      hist = prof2d(tree, alphaName, constTermName, "nll", 
		    binning, false, nSmooth, opt);
      histPdf = nllToL(hist);
    }else{
      hist = prof2d(tree, alphaName, constTermName, "nll", 
		    binning, false,nSmooth);
      histPdf = Smooth(hist,1,"keys");
    }
    delete hist;


//     RooDataSet *gen_dataset=histPdf->generate(*histPdf->getVariables(),1000000,kTRUE,kFALSE);
//     TTree *genTree = dataset2tree(gen_dataset);
//     genTree->SaveAs(fileName+"-genTree.root");
//     delete gen_dataset;
//     delete histPdf;
    
//     TGraphErrors toyGraph = g(genTree, constTermName);
//     TGraphErrors bestFitGraph = g(tree,alphaName, constTermName);
//     TGraphErrors bestFitScanGraph = g(y, x);
//     delete genTree;
//     delete tree;
//     toyGraph.SetFillColor(kGreen);
//     toyGraph.SetLineColor(kBlue);
//     toyGraph.SetLineStyle(2);
//     bestFitGraph.SetLineColor(kBlack);
//     bestFitScanGraph.SetLineColor(kRed);
//     bestFitScanGraph.SetLineWidth(2);


    
//     TMultiGraph g_multi("multigraph","");
//     g_multi.Add(&toyGraph,"L3");
//     g_multi.Add(&toyGraph,"L");
//     g_multi.Add(&bestFitGraph, "L");
//     g_multi.Add(&bestFitScanGraph, "L");
   
//     g_multi.Draw("A");

//     c->Clear();
//     g_multi.Draw("A");
//     c->SaveAs(outDir+"/smearing_vs_energy-"+constTermName+".png");
//     c->SaveAs(outDir+"/smearing_vs_energy-"+constTermName+".eps");
//     //    TPaveText *pv = new TPaveText(0.7,0.7,1, 0.8);    
// //     TLegend *legend = new TLegend(0.7,0.8,0.95,0.92);
// //     legend->SetFillStyle(3001);
// //     legend->SetFillColor(1);
// //     legend->SetTextFont(22); // 132
// //     legend->SetTextSize(0.04); // l'ho preso mettendo i punti con l'editor e poi ho ricavato il valore con il metodo GetTextSize()
// //   //  legend->SetFillColor(0); // colore di riempimento bianco
// //     legend->SetMargin(0.4);  // percentuale della larghezza del simbolo
//     //    SetLegendStyle(legend);
	
//     //Plot(c, data,mc,mcSmeared,legend, region, filename, energy, lumi);
  }
  
  f_in.Close();
  
  return;
}