Beispiel #1
0
int main (int argc, char **argv)
{
  /// Mc Ntuplas
  TString input = Form("/data1/rgerosa/NTUPLES_FINAL_CALIB/MC/WJetsToLNu_DYJetsToLL_7TeV-madgraph-tauola_Fall11_All.root"); 
  /// MC Calibration result E/p
  TString input2 = Form("/data1/rgerosa/L3_Weight/MC_WJets/EB_Z_recoFlag/WJetsToLNu_DYJetsToLL_7TeV-madgraph-tauola_Fall11_Z_noEP.root"); 

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

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

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

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

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

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

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

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

      double E_seed=0;
      int seed_hashedIndex=-1;// iseed;

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

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

   }
 }

 /// Map of IC normalized in eta rings

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

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

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

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

 /// ratio map

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

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

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

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

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

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

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

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

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

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

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


 theApp->Run();
 return 0;
}
Beispiel #2
0
void DoEvolutions( const TString &sim, Int_t time, Int_t Nbins=1, const TString &options="") { 
  
#ifdef __CINT__  
  gSystem->Load("libptools.so");
#endif

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

  TString opt = options;
  // cout << "options = " << opt << endl;

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

  Bool_t CYL = kFALSE;
  if(sim.Contains("cyl")) { CYL = kTRUE; opt += "cyl"; } 
    
  Bool_t ThreeD = kFALSE;
  if(sim.Contains("3D")) ThreeD = kTRUE; 
  
  // Some plasma constants
  Double_t n0 = pData->GetPlasmaDensity();
  Double_t kp = pData->GetPlasmaK();
  Double_t skindepth = 1.0;
  if(kp!=0.0) skindepth = 1/kp;
  Double_t E0 = pData->GetPlasmaE0();

  // Some initial beam properties:
  Float_t Ebeam = pData->GetBeamEnergy() * PUnits::MeV;
  Float_t gamma = pData->GetBeamGamma();
  Float_t vbeam = pData->GetBeamVelocity();
  
  Double_t rms0 = pData->GetBeamRmsY() * kp;
  if(CYL)  rms0 = pData->GetBeamRmsR() * kp;
  
  // Time in OU
  Float_t Time = pData->GetRealTime();
  // z start of the plasma in normalized units.
  Float_t zStartPlasma = pData->GetPlasmaStart() * kp;
  // z start of the beam in normalized units.
  Float_t zStartBeam = pData->GetBeamStart() * kp;
  
  if(opt.Contains("center")) {
    Time -= zStartPlasma;
    if(opt.Contains("comov"))      // Centers on the head of the beam.
      Time += zStartBeam;
  }

  // Beam charge 2D and 1D histogram (on-axis)
  // ------------------------------------------------------------------
  TH2F *hDen2D = NULL;
  if(pData->GetChargeFileName(1)) {
    char hName[24];
    sprintf(hName,"hDen2D");
    hDen2D = (TH2F*) gROOT->FindObject(hName);
    if(hDen2D) { delete hDen2D; hDen2D = NULL; }

    if(!ThreeD)
      hDen2D = pData->GetCharge(1,opt);
    else
      hDen2D = pData->GetCharge2DSliceZY(1,-1,1,opt+"avg");

    hDen2D->SetName(hName);
    hDen2D->GetXaxis()->CenterTitle();
    hDen2D->GetYaxis()->CenterTitle();
    hDen2D->GetZaxis()->CenterTitle();
    
    if(opt.Contains("comov"))
      hDen2D->GetXaxis()->SetTitle("k_{p}#zeta");
    else
      hDen2D->GetXaxis()->SetTitle("k_{p}z");
    
    if(CYL) 
      hDen2D->GetYaxis()->SetTitle("k_{p}r");
    else
      hDen2D->GetYaxis()->SetTitle("k_{p}y");

    hDen2D->GetZaxis()->SetTitle("n_{b}/n_{0}");

 
  }
  
  // Define ranges from the charge 2D histogram:
  // Binning for 2D histograms:
  // We get this values from the 2D density histogram.
  Int_t   x1Nbin    = hDen2D->GetNbinsX();
  Float_t x1Range   = (hDen2D->GetXaxis()->GetXmax() - hDen2D->GetXaxis()->GetXmin());
  Float_t x1Mid     = (hDen2D->GetXaxis()->GetXmax() + hDen2D->GetXaxis()->GetXmin())/2.;
  Float_t x1Min     = hDen2D->GetXaxis()->GetXmin();
  Float_t x1Max     = hDen2D->GetXaxis()->GetXmax();
  
  Int_t   x2Nbin    = hDen2D->GetNbinsY();      
  Float_t x2Range   = (hDen2D->GetYaxis()->GetXmax() - hDen2D->GetYaxis()->GetXmin());
  Float_t x2Mid     = (hDen2D->GetYaxis()->GetXmax() + hDen2D->GetYaxis()->GetXmin())/2.;
  Float_t x2Min     = x2Mid - x2Range/2;
  Float_t x2Max     = x2Mid + x2Range/2;
  
  if(Nbins==0) {
    Nbins = TMath::Nint(rms0 / hDen2D->GetYaxis()->GetBinWidth(1)) ;
    // cout << Form(" Rms0 = %6.2f  Dx = %6.2f  Nbins = %4i .", 
    // 	   rms0, hDen2D->GetYaxis()->GetBinWidth(1), Nbins) << endl;
  }
  
  // Slice width limits.
  Int_t FirstyBin = 0;
  Int_t LastyBin  = 0;
  if(!CYL) {
    FirstyBin = hDen2D->GetNbinsY()/2 + 1 - Nbins;
    LastyBin =  hDen2D->GetNbinsY()/2 + Nbins;
  } else {
    FirstyBin = 1; 
    LastyBin  = Nbins;
  }  


  // OUTPUT ROOT FILE WITH THE PLOTS:
  TString filename = Form("./%s/Plots/Evolutions/Evolutions-%s.root",sim.Data(),sim.Data());
  TFile * ifile = (TFile*) gROOT->GetListOfFiles()->FindObject(filename);
  // if doesn't exist the directory should be created
  if (!ifile) {
    TString f = filename;
    TString dir2 = f.Remove( f.Last( '/' ), f.Length() - f.Last( '/' ) );
    TString dir1 = f.Remove( f.Last( '/' ), f.Length() - f.Last( '/' ) );
    gSystem->mkdir( dir1 );
    gSystem->mkdir( dir2 );
    ifile = new TFile(filename,"UPDATE");
  }  

  
  // Charge 1D histogram on axis
  TH1F *hDen1D = NULL;
  if(pData->GetChargeFileName(1)) {
    TString opth1 = opt;
    opth1 += "avg";
    
    char hName[24];
    sprintf(hName,"hDen1D");
    hDen1D = (TH1F*) gROOT->FindObject(hName);
    if(hDen1D) delete hDen1D;
    
    if(ThreeD) {
      hDen1D = pData->GetH1SliceZ3D(pData->GetChargeFileName(1)->c_str(),"charge",-1,Nbins,-1,Nbins,opth1.Data());
    } else if(CYL) { // Cylindrical: The first bin with r>0 is actually the number 1 (not the 0).
      hDen1D = pData->GetH1SliceZ(pData->GetChargeFileName(1)->c_str(),"charge",1,Nbins,opth1.Data());
    } else { // 2D cartesian
      hDen1D = pData->GetH1SliceZ(pData->GetChargeFileName(1)->c_str(),"charge",-1,Nbins,opth1.Data());
    }
    hDen1D->SetName(hName); 
    
    if(opt.Contains("comov"))
      hDen1D->GetXaxis()->SetTitle("k_{p}#zeta");
    else
      hDen1D->GetXaxis()->SetTitle("k_{p}z");
  
    hDen1D->GetYaxis()->SetTitle("n_{b}/n_{0}");
  }

  // On-axis beam density vs \zeta vs time! _________________________________
  TH2F *hDen1DvsTime = NULL; 
  if(hDen1D) {
    char hName[24];
    sprintf(hName,"hDen1DvsTime");
    TH2F *hDen1DvsTimeOld = (TH2F*) ifile->Get(hName);

    Int_t nBins   = 1;
    Float_t edge0 = Time-0.5;
    Float_t edge1 = Time+0.5;
    if(hDen1DvsTimeOld!=NULL) {
      nBins = hDen1DvsTimeOld->GetNbinsX()+1;
      Float_t binwidth =  (Time - hDen1DvsTimeOld->GetXaxis()->GetBinCenter(1))/(nBins-1);
      edge0 = hDen1DvsTimeOld->GetXaxis()->GetBinCenter(1) - binwidth/2.;
      edge1 = Time + binwidth/2.;
    }
    hDen1DvsTime = new TH2F("temp","",nBins,edge0,edge1,
		       	hDen1D->GetNbinsX(),
			hDen1D->GetBinLowEdge(1),
			hDen1D->GetBinLowEdge(hDen1D->GetNbinsX()+1));
    
    for(Int_t ix=1;ix<hDen1DvsTime->GetNbinsX();ix++) {
      for(Int_t iy=1;iy<hDen1DvsTime->GetNbinsY();iy++) {
	hDen1DvsTime->SetBinContent(ix,iy,hDen1DvsTimeOld->GetBinContent(ix,iy));
      }
    }  
    delete hDen1DvsTimeOld;
  
    // Fill last bin with the newest values.
    for(Int_t iy=1;iy<=hDen1D->GetNbinsX();iy++) {
      hDen1DvsTime->SetBinContent(nBins,iy,hDen1D->GetBinContent(iy));
    }   

    hDen1DvsTime->GetZaxis()->SetTitle("n_{b}/n_{0}");
    hDen1DvsTime->GetYaxis()->SetTitle("k_{p}#zeta");
    hDen1DvsTime->GetXaxis()->SetTitle("k_{p}z");
    hDen1DvsTime->GetZaxis()->CenterTitle();
    hDen1DvsTime->GetYaxis()->CenterTitle();
    hDen1DvsTime->GetXaxis()->CenterTitle();
    hDen1DvsTime->SetName(hName);

    // Change the range of z axis 
    Float_t Denmax = hDen1DvsTime->GetMaximum();
    hDen1DvsTime->GetZaxis()->SetRangeUser(0,Denmax); 
    hDen1DvsTime->Write(hName,TObject::kOverwrite);

  }

  // RMS (vs z) of the beam's charge distribution: 
  TProfile *hDen2Dprof = NULL;
  TH1F *hRms = NULL;
  Double_t axisPos = x2Mid;
  if(hDen2D) {
    TString pname = hDen2D->GetName();
    pname += "_pfx";
    
    hDen2Dprof =  (TProfile*) gROOT->FindObject(pname.Data());
    if(hDen2Dprof) { delete hDen2Dprof; hDen2Dprof = NULL; }
    hDen2Dprof = hDen2D->ProfileX("_pfx",1,-1,"s");
    
    hRms = (TH1F*) gROOT->FindObject("hRms");
    if(hRms) delete hRms;
    
    hRms = new TH1F("hRms","",x1Nbin,x1Min,x1Max);
    
    if(CYL) axisPos = 0.0;
    
    for(Int_t j=0;j<hRms->GetNbinsX();j++) {
      Double_t rms = 0;
      Double_t total = 0;
      for(Int_t k=1;k<=x2Nbin;k++) {
	Double_t value  = hDen2D->GetBinContent(j,k);
	Double_t radius = hDen2D->GetYaxis()->GetBinCenter(k) - axisPos;
	if(CYL) {
	  rms += radius*radius*radius*value;
	  total += radius*value;
	} else {
	  rms += radius*radius*value;
	  total += value;
	}
	// cout << Form(" (%i,%i) -> radius = %7.4f ,  density = %7.4f",j,k,radius,value) << endl;
      }
      
      rms /= total;
      rms = sqrt(rms);
      
      hRms->SetBinContent(j,rms); 
      
    }
    
    hRms->GetXaxis()->SetTitle("k_{p}z");
    if(opt.Contains("comov"))
      hRms->GetXaxis()->SetTitle("k_{p}#zeta");
    
    hRms->GetYaxis()->SetTitle("k_{p}#LTr#GT_{rms}");
  }
  
  // Transverse charge RMS vs \zeta vs time! _________________________________
  TH2F *hRmsvsTime = NULL; 
  if(hRms) {
    char hName[24];
    sprintf(hName,"hRmsvsTime");
    TH2F *hRmsvsTimeOld = (TH2F*) ifile->Get(hName);

    Int_t nBins   = 1;
    Float_t edge0 = Time-0.5;
    Float_t edge1 = Time+0.5;
    if(hRmsvsTimeOld!=NULL) {
      nBins = hRmsvsTimeOld->GetNbinsX()+1;
      Float_t binwidth =  (Time - hRmsvsTimeOld->GetXaxis()->GetBinCenter(1))/(nBins-1);
      edge0 = hRmsvsTimeOld->GetXaxis()->GetBinCenter(1) - binwidth/2.;
      edge1 = Time + binwidth/2.;
    }
    hRmsvsTime = new TH2F("temp","",nBins,edge0,edge1,
		       	hRms->GetNbinsX(),
			hRms->GetBinLowEdge(1),
			hRms->GetBinLowEdge(hRms->GetNbinsX()+1));
    
    for(Int_t ix=1;ix<hRmsvsTime->GetNbinsX();ix++) {
      for(Int_t iy=1;iy<hRmsvsTime->GetNbinsY();iy++) {
	hRmsvsTime->SetBinContent(ix,iy,hRmsvsTimeOld->GetBinContent(ix,iy));
      }
    }  
    delete hRmsvsTimeOld;
  
    // Fill last bin with the newest values.
    for(Int_t iy=1;iy<=hRms->GetNbinsX();iy++) {
      hRmsvsTime->SetBinContent(nBins,iy,hRms->GetBinContent(iy));
    }   

    hRmsvsTime->GetZaxis()->SetTitle("#LTr#GT_{rms}");
    hRmsvsTime->GetYaxis()->SetTitle("k_{p}#zeta");
    hRmsvsTime->GetXaxis()->SetTitle("k_{p}z");
    hRmsvsTime->GetZaxis()->CenterTitle();
    hRmsvsTime->GetYaxis()->CenterTitle();
    hRmsvsTime->GetXaxis()->CenterTitle();
    hRmsvsTime->SetName(hName);

    // Change the range of z axis
    Float_t Rmsmax = hRmsvsTime->GetMaximum();
    hRmsvsTime->GetZaxis()->SetRangeUser(0,Rmsmax); 
    hRmsvsTime->Write(hName,TObject::kOverwrite);

  }

  // INTEGRATED Beam's Charge:
  // Total charge vs time :
  TGraph *gQvsTime = NULL;
  if(hDen2D) {
    Double_t Q = 0;
    for(Int_t i=1;i<=x1Nbin;i++) {
      for(Int_t j=1;j<=x2Nbin;j++) {
	Double_t value  = hDen2D->GetBinContent(i,j);
	if(CYL) {
	  Double_t radius = hDen2D->GetYaxis()->GetBinCenter(j);
	  Q += radius * value;
	  // cout << Form(" (%i,%i) -> radius = %7.4f , value = %7.4f",i,j,radius,value) << endl;
	} else {
	  Q += value;
	}
      }    
    }
    Double_t xbinsize = hDen2D->GetXaxis()->GetBinWidth(1);
    Double_t ybinsize = hDen2D->GetYaxis()->GetBinWidth(1); 
    Q *= xbinsize * ybinsize;
    
    if(!CYL && !ThreeD) {
      Q *= TMath::Sqrt(2*TMath::Pi()) * rms0; 
    } else if(CYL) {
      Q *= 2*TMath::Pi();
    }
    
    if(opt.Contains("units")) {
      Double_t dV = skindepth * skindepth * skindepth;
      Q *= n0 * dV;
      Q *= (PConst::ElectronCharge/PUnits::picocoulomb); 
      cout << Form(" Integrated charge     = %8i pC", TMath::Nint(Q)) << endl;
    } else {
      cout << Form(" Integrated charge     = %8.4f n0 * kp^-3",Q) << endl;
    }
    
    Int_t nPoints = 0;
    char gName[32];
    sprintf(gName,"gQvsTime");     
    gQvsTime = (TGraph*) ifile->Get(gName);
    if(gQvsTime==NULL) {
      gQvsTime = new TGraph();
      gQvsTime->SetName(gName);
      nPoints = 0;
      // Some cosmetics at creation time:
      gQvsTime->SetLineWidth(3);
      gQvsTime->SetLineColor(PGlobals::fieldLine);
      gQvsTime->SetMarkerStyle(20);
      gQvsTime->SetMarkerSize(0.4);
      gQvsTime->SetMarkerColor(PGlobals::fieldLine);	
      gQvsTime->GetYaxis()->SetTitle("charge [n_{0}/k_{p}^{3}]");
      gQvsTime->GetXaxis()->SetTitle("k_{p}z");
    } else {
      nPoints = gQvsTime->GetN(); 
    }  
    
    gQvsTime->Set(nPoints+1);
    gQvsTime->SetPoint(nPoints,Time,Q);
    gQvsTime->Write(gName,TObject::kOverwrite);
  }
  
  // ------------------------------------------------------------------------------------
  

  // Longitudinal phasespace 
  Int_t  gNbin = 100;
  // Float_t gMin = 80;
  // Float_t gMax = 120;
  Float_t gMin = 43.07 - 1.2;
  Float_t gMax = 43.07 + 1.2;
  TH2F *hGvsZ = NULL;
  if(pData->GetRawFileName(1)) {
    char hName[24];
    sprintf(hName,"hGvsZ");
    hGvsZ = (TH2F*) gROOT->FindObject(hName);
    if(hGvsZ) { delete hGvsZ; hGvsZ = NULL; }
    hGvsZ = new TH2F(hName,"",x1Nbin,x1Min,x1Max,gNbin,gMin,gMax);
    pData->GetH2Raw(pData->GetRawFileName(1)->c_str(),"x1","gamma",hGvsZ,opt);
    
    hGvsZ->GetXaxis()->CenterTitle();
    hGvsZ->GetYaxis()->CenterTitle();
    hGvsZ->GetZaxis()->CenterTitle();
    hGvsZ->GetYaxis()->SetTitle("#gamma");
    if(opt.Contains("comov")) {
      hGvsZ->GetXaxis()->SetTitle("k_{p}#zeta");
      hGvsZ->GetZaxis()->SetTitle("dN/d#zetad#gamma [a.u.]");
    }  else {
      hGvsZ->GetXaxis()->SetTitle("k_{p}z");
      hGvsZ->GetZaxis()->SetTitle("dN/dzd#gamma [a.u.]");
    }    
  } else {
    cout << Form("--> No RAW data file is present for species 1") << endl;
  }

  TH2F *hGvsTime = NULL; 
  TProfile *hGvsZprof = NULL;
  TGraphErrors *gGvsZ = NULL;
  if(hGvsZ) {
    TString pname = hGvsZ->GetName();
    pname += "_pfx";
    hGvsZprof =  (TProfile*) gROOT->FindObject(pname.Data());
    if(hGvsZprof) delete hGvsZprof;

    hGvsZprof = hGvsZ->ProfileX("_pfx",1,-1,"s");

    gGvsZ = (TGraphErrors*) gROOT->FindObject("gGvsZ");
    if(gGvsZ) delete gGvsZ;

    Int_t Npoints = hGvsZprof->GetNbinsX();
    Double_t *x = new Double_t[Npoints];
    Double_t *y = new Double_t[Npoints];
    Double_t *ex = new Double_t[Npoints];
    Double_t *ey = new Double_t[Npoints];
    
    for(Int_t j=0;j<Npoints;j++) {
      x[j] = hGvsZprof->GetBinCenter(j);
      y[j] = hGvsZprof->GetBinContent(j);
      ex[j] = 0;
      ey[j] = hGvsZprof->GetBinError(j);   
    }
    
    gGvsZ = new TGraphErrors(Npoints,x,y,ex,ey);
    gGvsZ->SetName("gGvsZ");
        
    // PGlobals::SetH1Style((TH1*)gGvsZ,1);
    PGlobals::SetGraphStyle(gGvsZ,1);

   
    if(opt.Contains("comov")) 
      gGvsZ->GetXaxis()->SetTitle("k_{p}#zeta");
    else
      gGvsZ->GetXaxis()->SetTitle("k_{p}z");
    
    gGvsZ->GetYaxis()->SetTitle("#LT#gamma#GT [MeV]");

    char hName[24];
    sprintf(hName,"hGvsTime");
    TH2F *hGvsTimeOld = (TH2F*) ifile->Get(hName);

    Int_t nBins   = 1;
    Float_t edge0 = Time-0.5;
    Float_t edge1 = Time+0.5;
    if(hGvsTimeOld!=NULL) {
      nBins = hGvsTimeOld->GetNbinsX()+1;
      Float_t binwidth =  (Time - hGvsTimeOld->GetXaxis()->GetBinCenter(1))/(nBins-1);
      edge0 = hGvsTimeOld->GetXaxis()->GetBinCenter(1) - binwidth/2.;
      edge1 = Time + binwidth/2.;
    }
    hGvsTime = new TH2F("temp","",nBins,edge0,edge1,
		       	hGvsZprof->GetNbinsX(),
			hGvsZprof->GetBinLowEdge(1),
			hGvsZprof->GetBinLowEdge(hGvsZprof->GetNbinsX()+1));
    
    for(Int_t ix=1;ix<hGvsTime->GetNbinsX();ix++) {
      for(Int_t iy=1;iy<hGvsTime->GetNbinsY();iy++) {
	hGvsTime->SetBinContent(ix,iy,hGvsTimeOld->GetBinContent(ix,iy));
      }
    }  
    delete hGvsTimeOld;
  
    // Fill last bin with the newest values.
    for(Int_t iy=1;iy<=hGvsZprof->GetNbinsX();iy++) {
      hGvsTime->SetBinContent(nBins,iy,hGvsZprof->GetBinContent(iy));
    }   

    hGvsTime->GetZaxis()->SetTitle("#LT#gamma#GT");
    hGvsTime->GetYaxis()->SetTitle("k_{p}#zeta");
    hGvsTime->GetXaxis()->SetTitle("k_{p}z");
    hGvsTime->GetZaxis()->CenterTitle();
    hGvsTime->GetYaxis()->CenterTitle();
    hGvsTime->GetXaxis()->CenterTitle();
    hGvsTime->SetName(hName);

    // Change the range of z axis
    Float_t Gmax = hGvsTime->GetMaximum();
    Float_t Gmin = hGvsTime->GetMinimum();    
    hGvsTime->GetZaxis()->SetRangeUser(Gmin,Gmax); 
    hGvsTime->Write(hName,TObject::kOverwrite);
    
  }

  // ---------------------------------------------------------------------------------


  // EM fields on - axis :

  TString opth1 = opt;
  opth1 += "avg";
  // Get electric fields
  const Int_t Nfields = 2;
  TH1F **hE1D = new TH1F*[Nfields];
  for(Int_t i=0;i<Nfields;i++) {
    hE1D[i] = NULL;
    if(!pData->GetEfieldFileName(i))
      continue;
    
    char nam[3]; sprintf(nam,"e%i",i+1);
    if(ThreeD) {
      if(i==0) 
	hE1D[i] = pData->GetH1SliceZ3D(pData->GetEfieldFileName(i)->c_str(),nam,-1,Nbins,-1,Nbins,opth1.Data());
      else  
	hE1D[i] = pData->GetH1SliceZ3D(pData->GetEfieldFileName(i)->c_str(),nam,-Nbins,Nbins,-Nbins,Nbins,opth1.Data());
    } else if(CYL) { // Cylindrical: The first bin with r>0 is actually the number 1 (not the 0).
      if(i==0) 
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,1,Nbins,opth1.Data());
      else
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,1,Nbins,opth1.Data());
    } else { // 2D cartesian
      if(i==0) 
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,-1,Nbins,opth1.Data());
      else 
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,-Nbins,Nbins,opth1.Data());
    }
    
    char hName[24];
    sprintf(hName,"hE_%i_%i",i,time);
    hE1D[i]->SetName(hName);
    if(opt.Contains("comov"))
      hE1D[i]->GetXaxis()->SetTitle("k_{p}#zeta");
    else
      hE1D[i]->GetXaxis()->SetTitle("k_{p}z");
   
    if(i==0)
      hE1D[i]->GetYaxis()->SetTitle("E_{z}/E_{0}");
    else if(i==1)
      hE1D[i]->GetYaxis()->SetTitle("E_{y}/E_{0}");
    else if(i==2)
      hE1D[i]->GetYaxis()->SetTitle("E_{x}/E_{0}");
    
    hE1D[i]->GetYaxis()->CenterTitle();
    hE1D[i]->GetXaxis()->CenterTitle();
    
  }  
  
  // Calculate wave positions:
  // ----------------------------------------------------------------
    
  // Calculate the crossings and the extremes of the Electric fields
  Float_t Ecross[Nfields][100] = {{0.0}};
  Float_t Eextr[Nfields][100] = {{0.0}};
  Int_t Ncross[Nfields] = {0};

  for(Int_t i=0;i<Nfields;i++) {
    Ncross[i] = 0;
    
    if(!hE1D[i]) continue;
    
    // Only smooths the focusing if flag activated..
    if(i>0 && opt.Contains("smooth")) {
      // cout << " Smoothing fields on axis..." << endl;
      hE1D[i]->Smooth(10);
    } 

    Float_t maxZeta = zStartBeam;
    if(opt.Contains("center")) 
      maxZeta -= zStartBeam;
          
    for(Int_t ip=hE1D[i]->GetNbinsX();ip>1;ip--) {

      Float_t Z2 = hE1D[i]->GetBinCenter(ip-1);
      if(Z2 > maxZeta) continue;
      Float_t E1 = hE1D[i]->GetBinContent(ip);
      Float_t E2 = hE1D[i]->GetBinContent(ip-1);
      Float_t Z1 = hE1D[i]->GetBinCenter(ip);
      
      // cout << Form("Z1 = %6.4f  Z2 = %6.4f   E1 = %6.4f   E2 = %6.4f", Z1, Z2, E1, E2) << endl; 

      if(E1*E2 >= 0) { // No change of sign means we are in a side of the zero axis.
	if(fabs(E2)>fabs(Eextr[i][Ncross[i]])) {
	  Eextr[i][Ncross[i]] = E2;
	} 
      }
      
      if(E1*E2 < 0) { // change of sign means a crossing!
	
	// The next crossing has to be far enough from the previous one:
	Float_t zcross =  -E1 * ( (Z2-Z1)/(E2-E1) ) + Z1;
        if(Ncross[i]>0 && fabs(Ecross[i][Ncross[i]-1]-zcross)<TMath::PiOver2() ) continue;	
	// cout << " CROSS! " << endl;

	// add the point
	Ecross[i][Ncross[i]] = zcross;
	Ncross[i]++;
      }
    }
    
    cout << "  -> Number of crossings for field " << i << " : " << Ncross[i] << endl;
    for(Int_t ic=0;ic<Ncross[i];ic++) {
      //  cout << Form(" %2i:  zeta = %6.4f  E = %6.4f", ic, Ecross[i][ic], Eextr[i][ic]) << endl; 
    }  
    
    
    hE1D[i]->SetLineColor(kRed);
    hE1D[i]->Write(hE1D[i]->GetName(),TObject::kOverwrite);

  }
  
  // Get the Graphs and histos from file
  Int_t nPoints = 0;
  TGraph ***gEcross = new TGraph**[Nfields]; 
  TGraph ***gEextr  = new TGraph**[Nfields]; 
  TH2F **hEvsTime = new TH2F*[Nfields]; 
  for(Int_t i=0;i<Nfields;i++) {
    char hName[24];
    sprintf(hName,"hEvsTime_%i",i);
    TH2F *hEvsTimeOld = (TH2F*) ifile->Get(hName);
    Int_t nBins   = 1;
    Float_t edge0 = Time-0.5;
    Float_t edge1 = Time+0.5;
    if(hEvsTimeOld!=NULL) {
      nBins = hEvsTimeOld->GetNbinsX()+1;
      Float_t binwidth =  (Time - hEvsTimeOld->GetXaxis()->GetBinCenter(1))/(nBins-1);
      edge0 = hEvsTimeOld->GetXaxis()->GetBinCenter(1) - binwidth/2.;
      edge1 = Time + binwidth/2.;
    }
    hEvsTime[i] = new TH2F("temp","",nBins,edge0,edge1,
			hE1D[i]->GetNbinsX(),
			hE1D[i]->GetBinLowEdge(1),
			hE1D[i]->GetBinLowEdge(hE1D[i]->GetNbinsX()+1));
    
    for(Int_t ix=1;ix<hEvsTime[i]->GetNbinsX();ix++) {
      for(Int_t iy=1;iy<hEvsTime[i]->GetNbinsY();iy++) {
	hEvsTime[i]->SetBinContent(ix,iy,hEvsTimeOld->GetBinContent(ix,iy));
      }
    }  
    delete hEvsTimeOld;
  
    // Fill last bin with the newest values.
    for(Int_t iy=1;iy<=hE1D[i]->GetNbinsX();iy++) {
      hEvsTime[i]->SetBinContent(nBins,iy,hE1D[i]->GetBinContent(iy));
    }   

    if(i==0) 
      hEvsTime[i]->GetZaxis()->SetTitle("E_{z}/E_{0}");
    else if(i==1)
      hEvsTime[i]->GetZaxis()->SetTitle("E_{y}/E_{0}");
    else if(i==2)
      hEvsTime[i]->GetZaxis()->SetTitle("E_{x}/E_{0}");
  
    hEvsTime[i]->GetYaxis()->SetTitle("k_{p}#zeta");
    hEvsTime[i]->GetXaxis()->SetTitle("k_{p}z");
    hEvsTime[i]->GetZaxis()->CenterTitle();
    hEvsTime[i]->GetYaxis()->CenterTitle();
    hEvsTime[i]->GetXaxis()->CenterTitle();
    hEvsTime[i]->SetName(hName);

    // Change the range of z axis for the fields to be symmetric.
    Float_t Emax = hEvsTime[i]->GetMaximum();
    Float_t Emin = hEvsTime[i]->GetMinimum();
    if(Emax > TMath::Abs(Emin))
      Emin = -Emax;
    else
      Emax = -Emin;
    hEvsTime[i]->GetZaxis()->SetRangeUser(Emin,Emax); 
    
    hEvsTime[i]->Write(hName,TObject::kOverwrite);

    // ---

    gEcross[i] = new TGraph*[Ncross[i]];
    gEextr[i] = new TGraph*[Ncross[i]];
    char gName[24];
    Int_t ifail = 0;
    for(Int_t ic=0;ic<Ncross[i];ic++) {
      sprintf(gName,"gEcross_%i_%i",i,ic);     
      gEcross[i][ic] = (TGraph*) ifile->Get(gName);
      if(gEcross[i][ic]==NULL) {
	gEcross[i][ic] = new TGraph();
	gEcross[i][ic]->SetName(gName);
	nPoints = 0;
	// Some cosmetics at creation time:
	if(i==1) gEcross[i][ic]->SetLineStyle(2);
	else gEcross[i][ic]->SetLineStyle(1);
	gEcross[i][ic]->SetLineWidth(1);
	gEcross[i][ic]->SetLineColor(kGray+1);
	gEcross[i][ic]->SetMarkerStyle(20);
	gEcross[i][ic]->SetMarkerSize(0.4);
	gEcross[i][ic]->SetMarkerColor(kGray+1);	
	gEcross[i][ic]->GetYaxis()->SetTitle("k_{p}#zeta]");
	gEcross[i][ic]->GetXaxis()->SetTitle("k_{p}z");
      } else {
	nPoints = gEcross[i][ic]->GetN(); 
      }  
      
      // Check the new crossings respect the previous ones:
      // Double_t t,zeta;
      // if(nPoints>0) {
      // 	gEcross[i][ic]->GetPoint(nPoints-1,t,zeta);
      // 	if(fabs(zeta-Ecross[i][ic+ifail])>TMath::Pi()) {
      // 	  ic--;
      // 	  ifail++;
      // 	  continue;
      // 	}
      // }
      
      gEcross[i][ic]->Set(nPoints+1);
      gEcross[i][ic]->SetPoint(nPoints,Time,Ecross[i][ic+ifail]);
      gEcross[i][ic]->Write(gName,TObject::kOverwrite);
      
      // if(ic==Ncross[i]-1) continue;
      
      sprintf(gName,"gEextr_%i_%i",i,ic);     
      gEextr[i][ic] = (TGraph*) ifile->Get(gName);
      if(gEextr[i][ic]==NULL) {
	gEextr[i][ic] = new TGraph();
	gEextr[i][ic]->SetName(gName);
	nPoints = 0;
	// Some cosmetics at creation time:
	if(i==0) {
	  gEextr[i][ic]->SetLineWidth(3);
	  gEextr[i][ic]->SetLineColor(PGlobals::fieldLine);
	  gEextr[i][ic]->SetMarkerStyle(20);
	  gEextr[i][ic]->SetMarkerSize(0.4);
	  gEextr[i][ic]->SetMarkerColor(PGlobals::fieldLine);	
	  gEextr[i][ic]->GetYaxis()->SetTitle("E_{z}/E_{0}");
	  gEextr[i][ic]->GetXaxis()->SetTitle("k_{p}z");
	} else if(i==1) {
	  gEextr[i][ic]->SetLineWidth(1);
	  gEextr[i][ic]->SetLineColor(kGray+2);
	  gEextr[i][ic]->SetMarkerStyle(20);
	  gEextr[i][ic]->SetMarkerSize(0.4);
	  gEextr[i][ic]->SetMarkerColor(kGray+2);	
	  gEextr[i][ic]->GetYaxis()->SetTitle("E_{y}/E_{0}");
	  gEextr[i][ic]->GetXaxis()->SetTitle("k_{p}z");	  
	}
      } else {
	nPoints = gEextr[i][ic]->GetN(); 
      }  
      
      gEextr[i][ic]->Set(nPoints+1);
      gEextr[i][ic]->SetPoint(nPoints,Time,Eextr[i][ic]);
      gEextr[i][ic]->Write(gName,TObject::kOverwrite);
    }
  }

  
  ifile->Close();
  
}
Beispiel #3
0
void AverageMW()
{
   // include NuTeV?
   if( inclNuTeV ) nVals = 5;
   else            nVals = 4;

   // number of parameters
   const int npar = 1;
   
   // create minuit pointer
   TMinuit *minuit = new TMinuit( npar );
   
   // set FCN function
   minuit->SetFCN( &fcn );
 
   // -1=quiet, 0=normal, 1=verbose
   minuit->SetPrintLevel( 0 );

   // start values
   Double_t startVal = 80;
   Double_t fitStep  = 0.1;
   Double_t limitMin = 70;
   Double_t limitMax = 90;
   minuit->DefineParameter( 0, "MW", startVal, fitStep, limitMin, limitMax);

   // minimize with MIGRAD
   Int_t ierr = 0;
   Double_t args[2];
   args[0] = 0; // maximum function calls (0=default)
   args[1] = 0; // tolerance at minimum (0=default)
   minuit->mnexcm( "MIGrad", args, 2, ierr );
   if ( ierr != 0 )
      cout << "Warning: Maybe fit didn't converge!" << endl;

   // fit results
   Double_t fitval_MW[1], fiterr_MW[1]; 
   minuit->GetParameter( 0, fitval_MW[0], fiterr_MW[0] );

   cout << "\n\n*************************************************" << endl;
   cout << "          chi2Min = " << chi2Min  << endl;
   cout << "          n_dof   = " << nVals-1  << endl;
   cout << "          p-value = " << TMath::Prob(chi2Min, nVals-1)  << endl;
   cout << "          MW      = " << fitval_MW[0] << " +- " << fiterr_MW[0] << endl;
   cout << "*************************************************" << endl;

   // make plot
   gStyle->SetOptTitle(0);
   gStyle->SetOptStat(0);
   gStyle->SetOptFit(0);
   TCanvas* c = new TCanvas( "c", "Mean of W boson mass", 0, 0, 850, 500 );
   c->SetGridy();
   TH2F *frame = new TH2F("frame", "Mean of W boson mass", 1, 80, 80.6, 5, 0, 5. );
   frame->SetLineColor(0);
   frame->SetTickLength(0,"Y");
   frame->SetXTitle("M_{W} [GeV]");  
   frame->GetYaxis()->CenterLabels( 1 );
   frame->GetYaxis()->SetNdivisions( frame->GetNbinsY()+10, 1 );
   frame->GetYaxis()->SetBinLabel( 1, "" ); // no labels
   frame->Draw();
   
   // make labels
   MakeLabels(frame);
   
   // draw fit value
   DrawFitValue( frame, fitval_MW[0], fiterr_MW[0] );
      
   // draw measurements
   for( Int_t i=0; i<5; i++ ){
      DrawMeasurement( frame, 4-i, val_MW[i], err_MW[i] ); 
   }

   // Redraw axis
   frame->Draw("sameaxis");
   
}
int main (int argc, char *argv[])
{

  printBoxedMessage("Starting plot generation");

  // ####################
  // ##   Init tools   ##
  // ####################
 
     string signalCategory = "T2tt";

     // Create a sonic Screwdriver
      SonicScrewdriver screwdriver;

  // ##########################
  // ##   Create Variables   ##
  // ##########################

     screwdriver.AddVariable("METoverSqrtHT",  "MET / #sqrt{H_{T}}",      "",       32,0,32,         &(myEvent.METoverSqrtHT),       "");
     screwdriver.AddVariable("MET",            "MET",                     "GeV",    15,50,500,       &(myEvent.MET),                 "logY=true");
     screwdriver.AddVariable("MT",             "MT",                      "GeV",    20,0,400,        &(myEvent.MT),                  "logY=true");
     screwdriver.AddVariable("MT2W",           "M_{T2}^{W}",              "GeV",    20,0,500,        &(myEvent.MT2W),                "");
     screwdriver.AddVariable("deltaPhiMETJets","#Delta#Phi(MET,j_{1,2})", "rad",    16,0,3.2,        &(myEvent.deltaPhiMETJets),     "");
     screwdriver.AddVariable("HadronicChi2",   "Hadronic #chi^{2}",       "",       40,0,20,         &(myEvent.hadronicChi2),        "");
     
     screwdriver.AddVariable("mStop",          "m_{#tilde{t}}",           "GeV",    28,112.5,812.5,  &(myEvent.mStop),               "");
     screwdriver.AddVariable("mNeutralino",    "m_{#chi^{0}}",            "GeV",    16,-12.5,387.5,  &(myEvent.mNeutralino),         "noOverflowInLastBin");
     
     // #########################################################
     // ##   Create ProcessClasses (and associated datasets)   ##
     // #########################################################

     screwdriver.AddProcessClass("1ltop",                        "1l top", "background",kRed-7);
         #ifdef USING_TTBAR_POWHEG
             screwdriver.AddDataset("ttbar_powheg",              "1ltop",  0, 0);
         #endif
         #ifdef USING_TTBAR_MADGRAPH
             screwdriver.AddDataset("ttbar_madgraph_1l",         "1ltop",  0, 0);
         #endif
         screwdriver.AddDataset("singleTop_st",                  "1ltop",  0, 0);


     screwdriver.AddProcessClass("ttbar_2l", "t#bar{t} #rightarrow l^{+}l^{-}", "background",kCyan-3);
         #ifdef USING_TTBAR_MADGRAPH
             screwdriver.AddDataset("ttbar_madgraph_2l",   "ttbar_2l",  0, 0);
         #endif

     screwdriver.AddProcessClass("W+jets",         "W+jets",                    "background", kOrange-2);
             screwdriver.AddDataset("W+jets",      "W+jets", 0, 0);
                                                   
     screwdriver.AddProcessClass("rare",           "rare",                      "background", kMagenta-5);
             screwdriver.AddDataset("rare",        "rare", 0, 0);
                                                   
     screwdriver.AddProcessClass(signalCategory,    signalCategory,             "signal",     kViolet-1);
             screwdriver.AddDataset(signalCategory, signalCategory,   0, 0);

     screwdriver.AddProcessClass("signal_250_100",  signalCategory+" (250/100)",      "signal",COLORPLOT_BLUE   );
     screwdriver.AddProcessClass("signal_450_100",  signalCategory+" (450/100)",      "signal",COLORPLOT_GREEN2 ); 
     screwdriver.AddProcessClass("signal_650_100",  signalCategory+" (650/100)",      "signal",COLORPLOT_GREEN  );

  // ##########################
  // ##    Create Regions    ##
  // ##########################

     screwdriver.AddRegion("presel",            "Preselection",              &goesInPreselectionMTtail);

     screwdriver.AddRegion("offShell_Loose", "Cut&Count;Off-shell Loose", &Selector_cutAndCount_offShellLoose);
     screwdriver.AddRegion("offShell_Tight", "Cut&Count;Off-shell tight", &Selector_cutAndCount_offShellTight);
     screwdriver.AddRegion("lowDM",          "Cut&Count;Low #DeltaM",     &Selector_cutAndCount_lowDeltaM    );
     screwdriver.AddRegion("mediumDM",       "Cut&Count;Medium #DeltaM",  &Selector_cutAndCount_mediumDeltaM );
     screwdriver.AddRegion("highDM",         "Cut&Count;High #DeltaM",    &Selector_cutAndCount_highDeltaM   );
   
  // ##########################
  // ##   Create Channels    ##
  // ##########################
      
     screwdriver.AddChannel("singleLepton", "e/#mu-channels",  &goesInSingleLeptonChannel);

  // ########################################
  // ##       Create histograms and        ##
  // ##  schedule type of plots to produce ##
  // ########################################

     screwdriver.SetLumi(20000);

     // Create histograms
     screwdriver.Create1DHistos();
     screwdriver.Add2DHisto("mStop","mNeutralino");

     screwdriver.SetGlobalBoolOption  ("1DSuperimposed",   "includeSignal",                   true   );

     screwdriver.SetGlobalStringOption("1DStack",          "includeSignal",                   "stack");
     screwdriver.SetGlobalFloatOption ("1DStack",          "factorSignal",                    1.0    );

     screwdriver.SetGlobalStringOption("DataMCComparison", "includeSignal",                   "stack");
     screwdriver.SetGlobalFloatOption ("DataMCComparison", "factorSignal",                    1.0    );

     // Schedule plots
     screwdriver.SchedulePlots("1DSuperimposed");
     screwdriver.SchedulePlots("1DStack");
     screwdriver.SchedulePlots("2D");
     screwdriver.SchedulePlots("2DSuperimposed");

     // Config plots

     screwdriver.SetGlobalStringOption("Plot", "infoTopRight", "CMS Internal");
     screwdriver.SetGlobalStringOption("Plot", "infoTopLeft",  "#sqrt{s} = 8 TeV, L = 20 fb^{-1}");

     screwdriver.SetGlobalBoolOption("Plot", "exportPdf", true);
     screwdriver.SetGlobalBoolOption("Plot", "exportEps", false);
     screwdriver.SetGlobalBoolOption("Plot", "exportPng", false);

  // ########################################
  // ##       Run over the datasets        ##
  // ########################################

  vector<string> datasetsList;
  screwdriver.GetDatasetList(&datasetsList);

  cout << "   > Reading datasets... " << endl;
  cout << endl;

  for (unsigned int d = 0 ; d < datasetsList.size() ; d++)
  {
     string currentDataset = datasetsList[d];
     string currentProcessClass = screwdriver.GetProcessClass(currentDataset); 
     // Open the tree
     TFile f((string(FOLDER_BABYTUPLES)+currentDataset+".root").c_str());
     TTree* theTree = (TTree*) f.Get("babyTuple"); 

     intermediatePointers pointers;
     InitializeBranchesForReading(theTree,&myEvent,&pointers);

     sampleName = currentDataset;
     sampleType = screwdriver.GetProcessClassType(currentProcessClass);

     if (currentDataset == signalCategory)
     {
         theTree->SetBranchAddress("mStop",       &(myEvent.mStop));
         theTree->SetBranchAddress("mNeutralino", &(myEvent.mNeutralino));
     }
     else
     {
         myEvent.mStop       = -1;
         myEvent.mNeutralino = -1;
     }

  // ########################################
  // ##        Run over the events         ##
  // ########################################

      int nEntries = theTree->GetEntries();
      for (int i = 0 ; i < nEntries ; i++)
      //for (int i = 0 ; i < min(200000, (int) theTree->GetEntries()); i++)
      {
          if (i % (theTree->GetEntries() / 50) == 0) 
              printProgressBar(i,nEntries,currentDataset);

          // Get the i-th entry
          ReadEvent(theTree,i,&pointers,&myEvent);

          // Split 1-lepton ttbar and 2-lepton ttbar
          string currentProcessClass_ = currentProcessClass;
          if ((currentDataset == "ttbar_powheg") && (myEvent.numberOfGenLepton == 2)) 
              currentProcessClass_ = "ttbar_2l";

          screwdriver.AutoFillProcessClass(currentProcessClass_,getWeight());

          if ((myEvent.mStop == 250) && (myEvent.mNeutralino == 100))
              screwdriver.AutoFillProcessClass("signal_250_100",getWeight());
          if ((myEvent.mStop == 450) && (myEvent.mNeutralino == 100))
              screwdriver.AutoFillProcessClass("signal_450_100",getWeight());
          if ((myEvent.mStop == 650) && (myEvent.mNeutralino == 100))
              screwdriver.AutoFillProcessClass("signal_650_100",getWeight());
      }

      printProgressBar(nEntries,nEntries,currentDataset);
      cout << endl;
      f.Close();

  }

  // ###################################
  // ##   Make plots and write them   ##
  // ###################################
 
  cout << endl;
  cout << "   > Making plots..." << endl;
  screwdriver.MakePlots();
  cout << "   > Saving plots..." << endl;
  screwdriver.WritePlots("../plots/cutAndCount_performances/"+signalCategory+"/");

  printBoxedMessage("Plot generation completed");

  // #############################
  // ##   Post-plotting tests   ##
  // #############################
 
  printBoxedMessage("Now computing misc tests ... ");


  vector<string> cutAndCountRegions =
  {
      "offShell_Loose",
      "offShell_Tight",
      "lowDM",
      "mediumDM",
      "highDM"
  };

  TableBackgroundSignal(&screwdriver,cutAndCountRegions,"singleLepton").Print();
  TableBackgroundSignal(&screwdriver,cutAndCountRegions,"singleLepton").PrintLatex();

  // ##########################
  // ##   Compute FOM maps   ##
  // ##########################

  float SF_1ltop = 5;  

  vector<float> globalBackgroundUncertainty =
  {
      0.17,
      0.21,
      0.22,
      0.37,
      0.37
  };
  
  vector<TH2F*> signalMaps;
  vector<TH2F*> FOMdiscoveryMaps;
  vector<TH2F*> FOMexclusionMaps;
  vector<TH2F*> efficiencies;

  int nBinsX = -1;
  int nBinsY = -1;

  TH2F* signalMapPresel  = screwdriver.get2DHistoClone("mStop","mNeutralino",signalCategory,"presel","singleLepton");
  TH2F* backgroundPresel = screwdriver.get2DCompositeHistoClone("mStop","mNeutralino","2DSumBackground","presel","singleLepton","");

  if (nBinsX == -1) nBinsX = signalMapPresel->GetNbinsX();
  if (nBinsY == -1) nBinsY = signalMapPresel->GetNbinsY();

  // Store background eff in (mStop,mLSP) = (200,300)
  int backgroundBin = signalMapPresel->FindBin(200,300);
  float backgroundYieldPresel = backgroundPresel->Integral(0,nBinsX+1,0,nBinsY+1);

  for (unsigned int i = 0 ; i < cutAndCountRegions.size() ; i++)
  {
      signalMaps.push_back(screwdriver.get2DHistoClone("mStop","mNeutralino",signalCategory,cutAndCountRegions[i],"singleLepton"));
      signalMaps[i]->SetName((string("signalMap_")+cutAndCountRegions[i]).c_str());

      float B =   screwdriver.GetYieldAndError("1ltop",    cutAndCountRegions[i],"singleLepton").value() //* SF_1ltop
                + screwdriver.GetYieldAndError("ttbar_2l", cutAndCountRegions[i],"singleLepton").value()
                + screwdriver.GetYieldAndError("W+jets",   cutAndCountRegions[i],"singleLepton").value() 
                + screwdriver.GetYieldAndError("rare",     cutAndCountRegions[i],"singleLepton").value();

      // Apply scale factor from background prediction
      //float f_B = globalBackgroundUncertainty[i];
      float f_B = 0.15;

      if (B < 1.0) B = 1.0;
 
      efficiencies.push_back((TH2F*) signalMaps[i]->Clone());
      efficiencies[i]->SetName((string("eff_")+cutAndCountRegions[i]).c_str());
      efficiencies[i]->Divide(signalMapPresel);
      efficiencies[i]->SetBinContent(backgroundBin,B/backgroundYieldPresel);
      
      FOMdiscoveryMaps.push_back((TH2F*) signalMaps[i]->Clone());
      FOMdiscoveryMaps[i]->SetName((string("FOMdisco_")+cutAndCountRegions[i]).c_str());

      FOMexclusionMaps.push_back((TH2F*) signalMaps[i]->Clone());
      FOMexclusionMaps[i]->SetName((string("FOMexclu_")+cutAndCountRegions[i]).c_str());

      for (int x = 1 ; x <= nBinsX ; x++)
      for (int y = 1 ; y <= nBinsY ; y++)
      {
          float S = signalMaps[i]->GetBinContent(x,y);

          float FOMdiscovery = figureOfMerit(S,B,"discovery",false,f_B);
          FOMdiscoveryMaps[i]->SetBinContent(x,y,FOMdiscovery);
          
          float FOMexclusion = figureOfMerit(S,B,"exclusion",false,f_B);
          FOMexclusionMaps[i]->SetBinContent(x,y,FOMexclusion);
      }

  }

  // ################################
  // ##   Compute "best" FOM map   ##
  // ################################

  TH2F* bestDiscoFOMMap = (TH2F*) signalMaps[0]->Clone();  bestDiscoFOMMap->SetName("bestDiscoFOM");
  TH2F* bestDiscoSetMap = (TH2F*) signalMaps[0]->Clone();  bestDiscoSetMap->SetName("bestDiscoSet");
  TH2F* bestDiscoSigEff = (TH2F*) signalMaps[0]->Clone();  bestDiscoSigEff->SetName("bestDiscoSigEff");
  TH2F* bestDiscoBkgEff = (TH2F*) signalMaps[0]->Clone();  bestDiscoBkgEff->SetName("bestDiscoBkgEff");
  
  TH2F* bestExcluFOMMap = (TH2F*) signalMaps[0]->Clone();  bestExcluFOMMap->SetName("bestExcluFOM");
  TH2F* bestExcluSetMap = (TH2F*) signalMaps[0]->Clone();  bestExcluSetMap->SetName("bestExcluSet");
  TH2F* bestExcluSigEff = (TH2F*) signalMaps[0]->Clone();  bestExcluSigEff->SetName("bestExcluSigEff");
  TH2F* bestExcluBkgEff = (TH2F*) signalMaps[0]->Clone();  bestExcluBkgEff->SetName("bestExcluBkgEff");
  
  for (int x = 1 ; x <= nBinsX ; x++)
  for (int y = 1 ; y <= nBinsY ; y++)
  {
      float bestDiscoFOM = -1.0;
      int   bestDiscoSet = 0;
      float bestDiscoSigEff_ = -1.0;
      float bestDiscoBkgEff_ = -1.0;
      for (unsigned int i = 0 ; i < cutAndCountRegions.size() ; i++)
      {
          float DiscoFOM = FOMdiscoveryMaps[i]->GetBinContent(x,y);
          if (bestDiscoFOM < DiscoFOM)
          {
              bestDiscoFOM = DiscoFOM;
              if (bestDiscoFOM > 0) bestDiscoSet = i+1;
              bestDiscoSigEff_ = efficiencies[i]->GetBinContent(x,y);
              bestDiscoBkgEff_ = efficiencies[i]->GetBinContent(backgroundBin);
          }
      }
      bestDiscoFOMMap->SetBinContent(x,y,bestDiscoFOM);
      bestDiscoSetMap->SetBinContent(x,y,bestDiscoSet);
      bestDiscoSigEff->SetBinContent(x,y,bestDiscoSigEff_);
      bestDiscoBkgEff->SetBinContent(x,y,bestDiscoBkgEff_);

      float bestExcluFOM = -1.0;
      int   bestExcluSet = 0;
      float bestExcluSigEff_ = -1.0;
      float bestExcluBkgEff_ = -1.0;
      for (unsigned int i = 0 ; i < cutAndCountRegions.size() ; i++)
      {
          float ExcluFOM = FOMexclusionMaps[i]->GetBinContent(x,y);
          if (bestExcluFOM < ExcluFOM)
          {
              bestExcluFOM = ExcluFOM;
              if (bestExcluFOM > 0) bestExcluSet = i+1;
              bestExcluSigEff_ = efficiencies[i]->GetBinContent(x,y);
              bestExcluBkgEff_ = efficiencies[i]->GetBinContent(backgroundBin);
          }
      }
      bestExcluFOMMap->SetBinContent(x,y,bestExcluFOM);
      bestExcluSetMap->SetBinContent(x,y,bestExcluSet);
      bestExcluSigEff->SetBinContent(x,y,bestExcluSigEff_);
      bestExcluBkgEff->SetBinContent(x,y,bestExcluBkgEff_);

  }

  // #########################
  // ##   Save those maps   ##
  // #########################

  float lineOffset = 0.0;
  string label;
  if (signalCategory == "T2tt"    ) { lineOffset = 172; label = "T2tt;";            }
  if (signalCategory == "T2bw-025") { lineOffset = 320; label = "T2bw (x = 0.25);"; }
  if (signalCategory == "T2bw-050") { lineOffset = 160; label = "T2bw (x = 0.50);"; }
  if (signalCategory == "T2bw-075") { lineOffset = 105; label = "T2bw (x = 0.75);"; }

  TFile fOutput(("../plots/cutAndCount_performances/"+signalCategory+"/custom.root").c_str(),"RECREATE");
  string pathExport = "../plots/cutAndCount_performances/"+signalCategory+"/";
  gStyle->SetPaintTextFormat("4.0f");
  formatAndWriteMapPlot(&screwdriver,bestDiscoSetMap,bestDiscoSetMap->GetName(),label+"Best set of cuts;(for discovery)",pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestExcluSetMap,bestExcluSetMap->GetName(),label+"Best set of cuts;(for exclusion)",pathExport,lineOffset);
  gStyle->SetPaintTextFormat("4.1f");
  for (unsigned int i = 0 ; i < cutAndCountRegions.size() ; i++)
  {
      FOMdiscoveryMaps[i]->SetMaximum(5.0);
      formatAndWriteMapPlot(&screwdriver,FOMdiscoveryMaps[i],FOMdiscoveryMaps[i]->GetName(),string("Discovery FOM for ")+cutAndCountRegions[i], pathExport,lineOffset);
      formatAndWriteMapPlot(&screwdriver,    efficiencies[i],    efficiencies[i]->GetName(),string("Efficiencies for " )+cutAndCountRegions[i], pathExport,lineOffset);
  }
  bestDiscoFOMMap->SetMaximum(5.0);
  bestExcluFOMMap->SetMaximum(5.0);
  formatAndWriteMapPlot(&screwdriver,bestDiscoFOMMap,bestDiscoFOMMap->GetName(),label+"Best FOM;(for discovery)"              ,pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestDiscoSigEff,bestDiscoSigEff->GetName(),label+"Best signal efficiency;(for discovery)",pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestDiscoBkgEff,bestDiscoBkgEff->GetName(),label+"Best backgr efficiency;(for discovery)",pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestExcluFOMMap,bestExcluFOMMap->GetName(),label+"Best FOM;(for exclusion)"              ,pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestExcluSigEff,bestExcluSigEff->GetName(),label+"Best signal efficiency;(for exclusion)",pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestExcluBkgEff,bestExcluBkgEff->GetName(),label+"Best backgr efficiency;(for exclusion)",pathExport,lineOffset);
  fOutput.Close();

  printBoxedMessage("Program done.");
  return (0);
}
Beispiel #5
0
void Optimize2D(TString signal, TString background, TString histname,
		int minxwidth = 2, int minywidth = 2, float minsigeff=0.5){

  TFile *sigfile = TFile::Open(signal);
  TFile *bkgfile = TFile::Open(background);

  TH2F *sighist = (TH2F*)sigfile->Get(histname);
  TH2F *bkghist = (TH2F*)bkgfile->Get(histname);

  int nxbins = sighist->GetNbinsX();
  int nybins = sighist->GetNbinsY();
  if ( nxbins != bkghist->GetNbinsX() || nybins != bkghist->GetNbinsY() ) {
    cout << "Error! The two input histograms do not have the same number of bins!" << endl;
    return; }

  int nsigtot = sighist->Integral(1,nxbins,1,nybins);
  int nbkgtot = bkghist->Integral(1,nxbins,1,nybins);
  
  cout << "Total number of entries in the signal histogram: " << nsigtot << endl;
  cout << "Total number of entries in the bkgrnd histogram: " << nbkgtot << endl;

  if ( nsigtot==0 || nbkgtot==0 ) {
    cout << "Error! At least one of the input histograms is empty!" << endl;
    return; }

  TH1D *projx = sighist->ProjectionX("projx");
  TH1D *projy = sighist->ProjectionY("projy");

  float bestsob = (float)nsigtot / nbkgtot;
  cout << "Starting with a \"no-cuts\" s/b of " << bestsob << endl;

  float x1=0, y1=0, x2=0, y2=0; // corner coordinates for the window

  for (int i=1; i<=nxbins; ++i)
    for (int j=minxwidth-1; i+j<=nxbins; ++j) 
      for (int k=1; k<=nybins; ++k)
	for (int l=minywidth-1; k+l<=nybins; ++l) {

	  int nsig = sighist->Integral(i, i+j, k, k+l);
	  if ( nsig == 0 ) continue;
	  if ( nsig < nsigtot*minsigeff ) continue;

	  int nbkg = bkghist->Integral(i, i+j, k, k+l);
	  if ( nbkg == 0 ) continue;

	  float sob = (float)nsig / nbkg;

	  if ( (float)nsig / nbkg > bestsob ) {
	    bestsob = sob;
	    x1 = projx->GetBinLowEdge(i);
	    x2 = projx->GetBinLowEdge(i+j+1);
	    y1 = projy->GetBinLowEdge(k);
	    y2 = projy->GetBinLowEdge(k+l+1);
	    cout << "x-range " << i << " (" << x1
		 << ") to " << i+j << " (" << x2
		 << ") ; \t y-range " << k << " (" << y1
		 <<") to " << k+l << " (" << y2
		 << ") ; \t signal= " << nsig
		 << " bkgrnd= " << nbkg << " s/b= " << sob << endl;
	  }
	  
	}

  TCanvas *cnv = TCanvas::MakeDefCanvas();
  cnv->Divide(2);
  TBox *box = new TBox(x1, y1, x2, y2);
  box->SetFillStyle(0);
  box->SetLineColor(2);
  box->SetLineWidth(2);
  cnv->cd(1); sighist->Draw("colbox"); box->Draw();
  cnv->cd(2); bkghist->Draw("colbox"); box->Draw();
  cnv->SaveAs("Optimize2D"+histname+".eps");

}
void twoDlinearcombination(TH2F* first, int firsttype, TH2F* second, int secondtype, TH2F* input, int inputtype, TH2F* finaloutput, int outputtype, TH2F* finaloutput2, int output2type){
	TH2F* output = (TH2F*) input->Clone();
	TH2F* output2 = (TH2F*) output->Clone();
	if(outputtype==kIntHist || outputtype==kSigHist){
		if(inputtype==kBSI25Hist && firsttype==kSigHist && secondtype==kBkgHist){
			output->Add(first, -25.0);
			output->Add(second, -1.0);
			output->Scale(0.2);
			if (outputtype == kSigHist){ delete output; output = (TH2F*) first->Clone(); }

			output2->Add(first, -25.0);
			output2->Add(second, -1.0);
			output2->Scale(0.2);
			if (output2type == kSigHist){ delete output2; output2 = (TH2F*) first->Clone(); }
		}
		if(inputtype==kBSI25Hist && firsttype==kBSIHist && secondtype==kBkgHist){
			for (int binx = 1; binx <= output->GetNbinsX(); binx++){
				for (int biny = 1; biny <= output->GetNbinsY(); biny++){
					double bsi = first->GetBinContent(binx,biny);
					double bkg = second->GetBinContent(binx,biny);
					double bsi25 = output->GetBinContent(binx,biny);

					double weight=doLinearCombination(bsi25,25,bsi,1,bkg,outputtype);
					output->SetBinContent(binx,biny,weight);
					if (finaloutput2 != 0){
						double weight2 = doLinearCombination(bsi25, 25, bsi, 1, bkg, output2type);
						output2->SetBinContent(binx, biny, weight2);
					}
				}
			}
		}		
		if(inputtype==kBSI25Hist && firsttype==kBSI10Hist && secondtype==kBkgHist){
			//double scaleval = 1./(-50. + 25.*sqrt(10.));
			for (int binx = 1; binx <= output->GetNbinsX(); binx++){
				for (int biny = 1; biny <= output->GetNbinsY(); biny++){
					double bsi10 = first->GetBinContent(binx,biny);
					double bkg = second->GetBinContent(binx,biny);
					double bsi25 = output->GetBinContent(binx,biny);

					double weight=doLinearCombination(bsi25,25,bsi10,10,bkg,outputtype);
					output->SetBinContent(binx,biny,weight);
					if (finaloutput2 != 0){
						double weight2 = doLinearCombination(bsi25, 25, bsi10, 10, bkg, output2type);
						output2->SetBinContent(binx, biny, weight2);
					}
				}
			}
		}
		if(inputtype==kBSI10Hist && firsttype==kBSIHist && secondtype==kBkgHist){
			//double scaleval = 1./(10 - sqrt(10));
			for (int binx = 1; binx <= output->GetNbinsX(); binx++){
				for (int biny = 1; biny <= output->GetNbinsY(); biny++){
					double bsi = first->GetBinContent(binx,biny);
					double bkg = second->GetBinContent(binx,biny);
					double bsi10 = output->GetBinContent(binx,biny);

					double weight=doLinearCombination(bsi10,10,bsi,1,bkg,outputtype);
					output->SetBinContent(binx,biny,weight);
					if (finaloutput2 != 0){
						double weight2 = doLinearCombination(bsi10, 10, bsi, 1, bkg, output2type);
						output2->SetBinContent(binx, biny, weight2);
					}
				}
			}
		}
		for (int binx = 1; binx <= output->GetNbinsX(); binx++){
			for (int biny = 1; biny <= output->GetNbinsY(); biny++){
				finaloutput->SetBinContent(binx, biny, output->GetBinContent(binx, biny));
				if (finaloutput2 != 0) finaloutput2->SetBinContent(binx,biny,output2->GetBinContent(binx,biny));
			}
		}
	}
	else{cout<<"Option not yet supported. Exiting..."<<endl; assert(0);};
	delete output;
	delete output2;
}
Beispiel #7
0
void ana_Run11_eff()
{

  const int rebin = 1;

  TFile *f = TFile::Open("Rootfiles/Run11_eff.root","read");

  // Run with weigth
  TH2F *hMcPtVsEta = (TH2F*)f->Get("mcJpsiPtY");
  TH2F *hRcPtVsEta = (TH2F*)f->Get("hHt2JpsiPE");

  draw2D(hMcPtVsEta);
  draw2D(hRcPtVsEta);

  hMcPtVsEta->GetXaxis()->SetRangeUser(-1+1e-6,1-1e-6);
  TH1F *hMcPt = (TH1F*)hMcPtVsEta->ProjectionY("hMcPt");
  hMcPt->Rebin(rebin);
  hMcPt->SetMarkerStyle(20);
  draw1D(hMcPt,"",kTRUE);

  hRcPtVsEta->GetXaxis()->SetRangeUser(-1+1e-6,1-1e-6);
  TH1F *hRcPt = (TH1F*)hRcPtVsEta->ProjectionY("hRcPt");
  hRcPt->Rebin(rebin);
  hRcPt->SetMarkerStyle(21);
  hRcPt->SetMarkerColor(2);
  hRcPt->SetLineColor(2);
  hRcPt->Draw("sames P");

  TH1F *hRatio = (TH1F*)hRcPt->Clone("hRatio_fromRunning");
  hRatio->Rebin(100);
  hMcPt->Rebin(100);
  hRatio->Divide(hMcPt);
  cEff = draw1D(hRatio,"");

  // Run without weight
  TH2F *hMcPtVsEtaNoWeight = (TH2F*)f->Get("mcJpsiPtY_Or");
  draw2D(hMcPtVsEtaNoWeight);  

  TH2F *hMcPtVsRcNoWeight = (TH2F*)f->Get("hJpsiRcvsMC_Cut1");
  hMcPtVsRcNoWeight->RebinX(rebin);
  hMcPtVsRcNoWeight->RebinY(rebin);
  draw2D(hMcPtVsRcNoWeight);

  hMcPtVsEtaNoWeight->GetXaxis()->SetRangeUser(-1+1e-6,1-1e-6);
  TH1F *hMcPtNoWeight = (TH1F*)hMcPtVsEtaNoWeight->ProjectionY("hMcPtNoWeight");
  hMcPtNoWeight->Rebin(rebin);
  hMcPtNoWeight->SetMarkerStyle(20);
  hMcPtNoWeight->SetMinimum(1);
  draw1D(hMcPtNoWeight,"",kTRUE);

  TH1F *hRcPtNoWeight = (TH1F*)hMcPtVsRcNoWeight->ProjectionX("hRcPtNoWeight");
  hRcPtNoWeight->SetMarkerStyle(21);
  hRcPtNoWeight->SetMarkerColor(2);
  hRcPtNoWeight->SetLineColor(2);
  hRcPtNoWeight->Draw("sames P");

  TH1F *hRatioNoWeight = (TH1F*)hRcPtNoWeight->Clone("hRatioNoWeight");
  hRatioNoWeight->Divide(hMcPtNoWeight);
  cEff->cd();
  hRatioNoWeight->SetMarkerColor(4);
  hRatioNoWeight->Draw("samesP");

  // weight with input histogram
  TH1F *hMcPtWeight = (TH1F*)hMcPtNoWeight->Clone("hMcPtWeight");
  TH2F *hMcPtVsRcWeight = (TH2F*)hMcPtVsRcNoWeight->Clone("hMcPtVsRcWeight");
  for(int ibin=1; ibin<=hMcPtVsRcNoWeight->GetNbinsX(); ibin++)
    {
      double scale = hMcPt->GetBinContent(ibin);
      hMcPtWeight->SetBinContent(ibin,hMcPtWeight->GetBinContent(ibin)*scale);
      hMcPtWeight->SetBinError(ibin,hMcPtWeight->GetBinError(ibin)*scale);
      for(int jbin=1; jbin<=hMcPtVsRcNoWeight->GetNbinsY(); jbin++)
	{
	  hMcPtVsRcWeight->SetBinContent(ibin,jbin,hMcPtVsRcWeight->GetBinContent(ibin,jbin)*scale);
	  hMcPtVsRcWeight->SetBinError(ibin,jbin,hMcPtVsRcWeight->GetBinError(ibin,jbin)*scale);
	}
    }
  TH1F *hRcPtWeight = (TH1F*)hMcPtVsRcWeight->ProjectionY("hRcPtWeight");
  hRcPtWeight->SetMarkerStyle(21);
  hRcPtWeight->SetMarkerColor(2);
  hRcPtWeight->SetLineColor(2);

  draw2D(hMcPtVsRcWeight);
  draw1D(hMcPtWeight,"",kTRUE);
  hRcPtWeight->Draw("sames P");
  
  TH1F *hRatioWeight = (TH1F*)hRcPtWeight->Clone("hRatioWeight");
  hRatioWeight->Divide(hMcPtWeight);
  cEff->cd();
  hRatioWeight->SetMarkerColor(6);
  hRatioWeight->Draw("samesP");

  TH1F *hCheck = (TH1F*)hRatioWeight->Clone("check");
  hCheck->Divide(hRatio);
  draw1D(hCheck);

  // weight with fitted function
  TCanvas *c = new TCanvas("Fit","Fit",800,600);
  SetPadMargin(gPad,0.15,0.15);
  gPad->SetLogy();
  TH1F *h = new TH1F("histogram",";;;",7,0,30);
  h->GetYaxis()->SetRangeUser(1e-7,100);
  h->Draw();

  TFile *fdata = TFile::Open("Rootfiles/Spectrum_in_bin.root","read");
  TGraphErrors	*gr = (TGraphErrors*)fdata->Get("gall");
  gr->SetMarkerColor(1);
  gr->SetLineColor(1);
  gr->GetXaxis()->SetRangeUser(0,30);
  gr->Draw("sames PE");
  TF1 *func = new TF1("func",InvPt,0,30,4);
  func->SetParameters(0.4,-0.4796,4.229,-7.54);
  gr->Fit(func,"RL");

  TH1F *hMcPtFunc = (TH1F*)hMcPtNoWeight->Clone("hMcPtFunc");
  TH2F *hMcPtVsRcFunc = (TH2F*)hMcPtVsRcNoWeight->Clone("hMcPtVsRcFunc");
  for(int ibin=1; ibin<=hMcPtVsRcFunc->GetNbinsX(); ibin++)
    {
      double scale = func->Eval(hMcPtFunc->GetBinCenter(ibin));
      hMcPtFunc->SetBinContent(ibin,hMcPtFunc->GetBinContent(ibin)*scale);
      hMcPtFunc->SetBinError(ibin,hMcPtFunc->GetBinError(ibin)*scale);
      for(int jbin=1; jbin<=hMcPtVsRcNoWeight->GetNbinsY(); jbin++)
	{
	  hMcPtVsRcFunc->SetBinContent(ibin,jbin,hMcPtVsRcFunc->GetBinContent(ibin,jbin)*scale);
	  hMcPtVsRcFunc->SetBinError(ibin,jbin,hMcPtVsRcFunc->GetBinError(ibin,jbin)*scale);
	}
    }
  TH1F *hRcPtFunc = (TH1F*)hMcPtVsRcFunc->ProjectionY("hRcPtFunc");
  hRcPtFunc->SetMarkerStyle(21);
  hRcPtFunc->SetMarkerColor(2);
  hRcPtFunc->SetLineColor(2);
  hMcPtVsRcFunc->GetZaxis()->SetRangeUser(1e-4,1e2);
  draw2D(hMcPtVsRcFunc);
  hMcPtFunc->GetYaxis()->SetRangeUser(1e-4,5e4);
  draw1D(hMcPtFunc,"",kTRUE);
  hRcPtFunc->Draw("sames P");

  TH1F *hRatioFunc = (TH1F*)hRcPtFunc->Clone("hRatioFunc");
  hRatioFunc->Rebin(100);
  hMcPtFunc->Rebin(100);
  hRatioFunc->Divide(hMcPtFunc);
  cEff->cd();
  hRatioFunc->SetMarkerColor(5);
  hRatioFunc->Draw("samesP");
  
  TH1F *hCheck2 = (TH1F*)hRatioFunc->Clone("check2");
  hCheck2->Divide(hRatio);
  draw1D(hCheck2);

}
void xformTaggingEfficiency() {


    TFile *fMatrix = new TFile("output/reco2GenMatrix.root");
    TFile *fin = new TFile("output/NewFormatV5_bFractionMCTemplate_pppp1_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root");

    // reco 2 gen matrix
    TH2F *hXform = (TH2F*)fMatrix->Get("hRecoVsGenNorm");

    // grab reco binned histos
    TH1F *hRecoEffMC = (TH1F*)fin->Get("hBEfficiencyMC");
    TH1F *hRecoEffDataLTJP = (TH1F*)fin->Get("hBEfficiencyDataLTJP");

    TH1F *hRecoPurMC = (TH1F*)fin->Get("hBPurityMC");
    TH1F *hRecoPurData = (TH1F*)fin->Get("hBPurityData");

    TH1F *hRecoSpecMC = (TH1F*)fin->Get("hRawBMC");
    TH1F *hRecoSpecData = (TH1F*)fin->Get("hRawBData");


    // declar gen binned histos

    TH1F *hGenEffMC = hRecoEffMC->Clone("hGenEffMC");
    hGenEffMC->Reset();
    TH1F *hGenEffDataLTJP = hRecoEffDataLTJP->Clone("hGenEffDataLTJP");
    hGenEffDataLTJP->Reset();

    TH1F *hGenPurMC = hRecoPurMC->Clone("hGenPurMC");
    hGenPurMC->Reset();
    TH1F *hGenPurData = hRecoPurData->Clone("hGenPurData");
    hGenPurData->Reset();

    TH1F *hGenSpecMC = hRecoSpecMC->Clone("hGenSpecMC");
    hGenSpecMC->Reset();
    TH1F *hGenSpecData = hRecoSpecData->Clone("hGenSpecData");
    hGenSpecData->Reset();

    if(hRecoEffMC->GetNbinsX() != hXform->GetNbinsX()) {
        cout<<" FAIL "<<endl;
        return;
    }


    for(int i=0; i<hXform->GetNbinsX(); i++) {

        float genEffMC = 0;
        float genEffErrMC = 0;
        float genEffDataLTJP = 0;
        float genEffErrDataLTJP = 0;

        float genPurMC = 0;
        float genPurErrMC = 0;
        float genPurData = 0;
        float genPurErrData = 0;

        float genSpecMC = 0;
        float genSpecErrMC = 0;
        float genSpecData = 0;
        float genSpecErrData = 0;

        for(int j=0; j<hXform->GetNbinsY(); j++) {

            float coeff = hXform->GetBinContent(i+1,j+1);

            float recoEffMC = hRecoEffMC->GetBinContent(j+1);
            float recoEffErrMC = hRecoEffMC->GetBinError(j+1);
            genEffMC += coeff * recoEffMC;
            genEffErrMC +=  coeff * recoEffErrMC * coeff * recoEffErrMC;

            float recoEffDataLTJP = hRecoEffDataLTJP->GetBinContent(j+1);
            float recoEffErrDataLTJP = hRecoEffDataLTJP->GetBinError(j+1);
            genEffDataLTJP += coeff * recoEffDataLTJP;
            genEffErrDataLTJP +=  coeff * recoEffErrDataLTJP * coeff * recoEffErrDataLTJP;

            float recoPurMC = hRecoPurMC->GetBinContent(j+1);
            float recoPurErrMC = hRecoPurMC->GetBinError(j+1);
            genPurMC += coeff * recoPurMC;
            genPurErrMC +=  coeff * recoPurErrMC * coeff * recoPurErrMC;

            float recoPurData = hRecoPurData->GetBinContent(j+1);
            float recoPurErrData = hRecoPurData->GetBinError(j+1);
            genPurData += coeff * recoPurData;
            genPurErrData +=  coeff * recoPurErrData * coeff * recoPurErrData;

            float recoSpecMC = hRecoSpecMC->GetBinContent(j+1);
            float recoSpecErrMC = hRecoSpecMC->GetBinError(j+1);
            genSpecMC += coeff * recoSpecMC;
            genSpecErrMC +=  coeff * recoSpecErrMC * coeff * recoSpecErrMC;

            float recoSpecData = hRecoSpecData->GetBinContent(j+1);
            float recoSpecErrData = hRecoSpecData->GetBinError(j+1);
            genSpecData += coeff * recoSpecData;
            genSpecErrData +=  coeff * recoSpecErrData * coeff * recoSpecErrData;

        }

        genEffErrMC = sqrt(genEffErrMC);
        hGenEffMC->SetBinContent(i+1, recoEffMC);
        hGenEffMC->SetBinError(i+1, recoEffErrMC);

        genEffErrDataLTJP = sqrt(genEffErrDataLTJP);
        hGenEffDataLTJP->SetBinContent(i+1, recoEffDataLTJP);
        hGenEffDataLTJP->SetBinError(i+1, recoEffErrDataLTJP);

        hGenEffMC->SetBinContent(i+1, genEffMC);
        hGenEffMC->SetBinError(i+1, genEffErrMC);

        hGenEffDataLTJP->SetBinContent(i+1, genEffDataLTJP);
        hGenEffDataLTJP->SetBinError(i+1, genEffErrDataLTJP);

        genPurErrMC = sqrt(genPurErrMC);
        hGenPurMC->SetBinContent(i+1, recoPurMC);
        hGenPurMC->SetBinError(i+1, recoPurErrMC);

        genPurErrData = sqrt(genPurErrData);
        hGenPurData->SetBinContent(i+1, recoPurData);
        hGenPurData->SetBinError(i+1, recoPurErrData);

        hGenPurMC->SetBinContent(i+1, genPurMC);
        hGenPurMC->SetBinError(i+1, genPurErrMC);

        hGenPurData->SetBinContent(i+1, genPurData);
        hGenPurData->SetBinError(i+1, genPurErrData);

        genSpecErrMC = sqrt(genSpecErrMC);
        hGenSpecMC->SetBinContent(i+1, recoSpecMC);
        hGenSpecMC->SetBinError(i+1, recoSpecErrMC);

        genSpecErrData = sqrt(genSpecErrData);
        hGenSpecData->SetBinContent(i+1, recoSpecData);
        hGenSpecData->SetBinError(i+1, recoSpecErrData);

        hGenSpecMC->SetBinContent(i+1, genSpecMC);
        hGenSpecMC->SetBinError(i+1, genSpecErrMC);

        hGenSpecData->SetBinContent(i+1, genSpecData);
        hGenSpecData->SetBinError(i+1, genSpecErrData);


    }

    TFile *fout=new TFile("outputTowardsFinal/genBinnedHistos.root","recreate");

    hRecoEffMC->SetXTitle("recoJet p_{T} (GeV/c)");
    hRecoEffDataLTJP->SetXTitle("recoJet p_{T} (GeV/c)");
    hGenEffMC->SetXTitle("genJet p_{T} (GeV/c)");
    hGenEffDataLTJP->SetXTitle("genJet p_{T} (GeV/c)");
    hRecoEffMC->Write();
    hRecoEffDataLTJP->Write();
    hGenEffMC->Write();
    hGenEffDataLTJP->Write();

    hRecoPurMC->SetXTitle("recoJet p_{T} (GeV/c)");
    hRecoPurData->SetXTitle("recoJet p_{T} (GeV/c)");
    hGenPurMC->SetXTitle("genJet p_{T} (GeV/c)");
    hGenPurData->SetXTitle("genJet p_{T} (GeV/c)");
    hRecoPurMC->Write();
    hRecoPurData->Write();
    hGenPurMC->Write();
    hGenPurData->Write();

    hRecoSpecMC->SetXTitle("recoJet p_{T} (GeV/c)");
    hRecoSpecData->SetXTitle("recoJet p_{T} (GeV/c)");
    hGenSpecMC->SetXTitle("genJet p_{T} (GeV/c)");
    hGenSpecData->SetXTitle("genJet p_{T} (GeV/c)");
    hRecoSpecMC->Write();
    hRecoSpecData->Write();
    hGenSpecMC->Write();
    hGenSpecData->Write();

    fout->Close();

}