コード例 #1
0
int InputForLimits(){
  TH1::SetDefaultSumw2(true);
  if(pcp)cout<<"going to set inputs"<<endl;

  Int_t NBR = 3;
  Float_t BR[] = { 1., 0.75, 0.5};

  TFile* bkgFile = new TFile( "../../BkgPrediction/BkgPrediction.root", "READ"); 
  TTree* bkgTree;
  bkgFile->GetObject( "ElAndMu", bkgTree);
  
  Float_t bkg = 0.;
  Float_t bkgTotUnc = 0.;

  Float_t obs = 0.;

  bkgTree->SetBranchAddress( "srData", &obs);
  bkgTree->SetBranchAddress( "srAllBkgCorr", &bkg);
  bkgTree->SetBranchAddress( "TotUnc", &bkgTotUnc);

  TFile* sigFile = new TFile( "../../SignalSystematics/SignalSys.root", "READ"); 

  std::vector<std::vector<TString> > sysColl;
  std::vector<TString> sys;
  sys.push_back(TString("JES_Up"));
  sys.push_back(TString("JES_Down"));
  sysColl.push_back(sys);

  sys.clear();
  sys.push_back(TString("BTagReweight_UpBC"));
  sys.push_back(TString("BTagReweight_DownBC"));
  sysColl.push_back(sys);

  sys.clear();
  sys.push_back(TString("BTagReweight_UpLight"));
  sys.push_back(TString("BTagReweight_DownLight"));
  sysColl.push_back(sys);

  std::vector<TString> decayMode;
  decayMode.push_back(TString("tt"));
  decayMode.push_back(TString("tb"));
  decayMode.push_back(TString("bb"));
		      
  Systematics* systematics[3];
  TString dirname;
  TString histoname;

  TDirectory* srDir;
  TDirectory* histoDir;

  TFile* outFile = new TFile( "InputForLimits.root", "RECREATE");
  TDirectory* outBRDir;
  TDirectory* outSRDir;

  TH1F* datah = new TH1F( "data", "data", 1, 0., 1.);
  TH1F* bkgh = new TH1F( "bkg", "bkg", 1, 0., 1.);

  TH2F* sigh;
  TH2F* sig_toth;
  TH2F* effh;
  
  TH2F* sigLh;
  TH2F* effLh;

  TH2F* sigRh;
  TH2F* effRh;
  
  TH2F* jesh;
  TH2F* btagBCh;
  TH2F* btagLighth;
  TH2F* btagh;
  
  TH2F* sysh;

  TH2F* unch;

  TH2F* jesPercenth;
  TH2F* btagBCPercenth;
  TH2F* btagLightPercenth;
  TH2F* btagPercenth;
  
  TH2F* sysPercenth;

  TH2F* uncPercenth;

  Float_t sig = 0.;
  Float_t stat = 0.;

  Float_t jes = 0.;
  Float_t bc = 0.;
  Float_t light = 0.;
  
  Float_t unc = 0.;

  int N = bkgTree->GetEntries();

  for ( int ibr = 0; ibr < NBR; ibr++){
    dirname = ""; dirname += BR[ibr];
    outFile->mkdir(dirname);
    outBRDir = outFile->GetDirectory(dirname);

    for ( int iSR = 0; iSR < 9; iSR++){
      bkgTree->GetEntry(iSR);      
      datah->SetBinContent( 1, obs);
      bkgh->SetBinContent( 1, bkg);
      bkgh->SetBinError( 1, bkgTotUnc);

      dirname = ""; dirname += iSR;
      outBRDir->mkdir(dirname);
      outSRDir = outBRDir->GetDirectory(dirname);
      
      dirname = ""; dirname += iSR; dirname += ".root";      
      srDir = sigFile->GetDirectory( dirname);
      for ( int isys = 0; isys < (int) sysColl.size(); isys++){
	systematics[isys] = new Systematics();
	systematics[isys]->BR = BR[ibr];

	histoDir = srDir->GetDirectory( "NoSystematic");
	for ( int idecay = 0; idecay < (int) decayMode.size(); idecay++){
	  histoDir->GetObject( decayMode.at(idecay), systematics[isys]->h[idecay]);
	  histoDir->GetObject( decayMode.at(idecay) + "l", systematics[isys]->Lh);
	  histoDir->GetObject( decayMode.at(idecay) + "r", systematics[isys]->Rh);
	}
	histoDir->GetObject( decayMode.at(0) + "l", systematics[isys]->Lh);
	histoDir->GetObject( decayMode.at(0) + "r", systematics[isys]->Rh);
	histoDir->GetObject( "sig_tot", systematics[isys]->sig_toth);

	for ( int ishift = 0; ishift < 2; ishift++){
	  histoDir = srDir->GetDirectory(sysColl.at(isys).at(ishift));
	  for ( int idecay = 0; idecay < (int) decayMode.size(); idecay++){
	    histoDir->GetObject( decayMode.at(idecay), systematics[isys]->shifth[ishift][idecay]);
	  }
	}
	systematics[isys]->Calc();
      }
      sig_toth = new TH2F( *systematics[0]->sig_toth);
      sig_toth->SetName("sig_tot");
      sig_toth->SetTitle("sig_tot");    

      sigh = new TH2F( *systematics[0]->sigh);
      sigh->SetName("sig");
      sigh->SetTitle("sig");

      effh = new TH2F( *systematics[0]->effh);
      effh->SetName("eff");
      effh->SetTitle("eff");

      sigLh = new TH2F( *systematics[0]->sigRh);
      sigLh->SetName("sigL");
      sigLh->SetTitle("sigL");

      effLh = new TH2F( *systematics[0]->effLh);
      effLh->SetName("effL");
      effLh->SetTitle("effL");

      sigRh = new TH2F( *systematics[0]->sigRh);
      sigRh->SetName("sigR");
      sigRh->SetTitle("sigR");

      effRh = new TH2F( *systematics[0]->effRh);
      effRh->SetName("effR");
      effRh->SetTitle("effR");

      jesh = new TH2F( *systematics[0]->sysh);
      jesh->SetName("jes");
      jesh->SetTitle("jes");

      btagBCh = new TH2F( *systematics[1]->sysh);
      btagBCh->SetName("btagBC");
      btagBCh->SetTitle("btagBC");
      
      btagLighth = new TH2F( *systematics[2]->sysh);
      btagLighth->SetName("btagLight");
      btagLighth->SetTitle("btagLight");
      
      btagh = new TH2F( *btagBCh);
      btagh->Reset();
      btagh->SetName("btag");
      btagh->SetTitle("btag");
 
      sysh = new TH2F( *jesh);
      sysh->Reset();
      sysh->SetName("sys");
      sysh->SetTitle("sys");

      unch = new TH2F( *jesh);
      unch->Reset();
      unch->SetName("unc");
      unch->SetTitle("unc");


      jesPercenth = new TH2F( *systematics[0]->sysh);
      jesPercenth->SetName("jesPercent");
      jesPercenth->SetTitle("jesPercent");
      jesPercenth->Divide( sigh);
      jesPercenth->Scale( 100.);      

      btagBCPercenth = new TH2F( *systematics[1]->sysh);
      btagBCPercenth->SetName("btagBCPercent");
      btagBCPercenth->SetTitle("btagBCPercent");
      btagBCPercenth->Divide( sigh);
      btagBCPercenth->Scale( 100.);   

      btagLightPercenth = new TH2F( *systematics[2]->sysh);
      btagLightPercenth->SetName("btagLightPercent");
      btagLightPercenth->SetTitle("btagLightPercent");
      btagLightPercenth->Divide( sigh);
      btagLightPercenth->Scale( 100.);   

      btagPercenth = new TH2F( *btagBCh);
      btagPercenth->Reset();
      btagPercenth->SetName("btagPercent");
      btagPercenth->SetTitle("btagPercent");
 
      sysPercenth = new TH2F( *jesh);
      sysPercenth->Reset();
      sysPercenth->SetName("sysPercent");
      sysPercenth->SetTitle("sysPercent");

      uncPercenth = new TH2F( *jesh);
      uncPercenth->Reset();
      uncPercenth->SetName("uncPercent");
      uncPercenth->SetTitle("uncPercent");

      for (int ibin = 0; ibin < sigh->GetSize(); ibin++){	
	sig = sigh->GetBinContent( ibin);
	stat = sigh->GetBinError( ibin);

	jes = jesh->GetBinContent(ibin);
	bc = btagBCh->GetBinContent(ibin);
	light = btagLighth->GetBinContent(ibin);
    
	unc = sqrt( bc * bc + light * light);
	btagh->SetBinContent( ibin, unc);
	btagPercenth->SetBinContent( ibin, unc / sig * 100.);
	
	unc = sqrt( jes * jes + bc * bc + light * light +
		    sig * sig * (0.044 * 0.044 + // Lumi
				 0.03  * 0.03  + // Trigger
				 0.05  * 0.05    // Lep Id
				 )
		    );       
	sysh->SetBinContent( ibin, unc);
	sysPercenth->SetBinContent( ibin, unc / sig * 100.);
	
	unc = sqrt( jes * jes + bc * bc + light * light + stat * stat +  
		    sig * sig * (0.044 * 0.044 + // Lumi
				 0.03  * 0.03  + // Trigger
				 0.05  * 0.05    // Lep Id
				 )
		    );	
	unch->SetBinContent( ibin, unc);
	uncPercenth->SetBinContent( ibin, unc / sig * 100.);
      }
      outSRDir->cd();

      datah->Write();
      bkgh->Write();

      sig_toth->Write();
      sigh->Write();
      effh->Write();
      
      sigLh->Write();
      effLh->Write();

      sigRh->Write();
      effRh->Write();

      jesh->Write();
      btagBCh->Write(); 
      btagLighth->Write();
      btagh->Write();
      
      sysh->Write();
      unch->Write();

      jesPercenth->Write();
      btagBCPercenth->Write(); 
      btagLightPercenth->Write();
      btagPercenth->Write();
      
      sysPercenth->Write();
      uncPercenth->Write();
    }
  }

  delete systematics[0];
  delete systematics[1];
  delete systematics[2];

  outFile->Close();
  sigFile->Close();
  bkgFile->Close();

  return 0;
}
コード例 #2
0
ファイル: evtmatching.C プロジェクト: boundino/Dntuple
int evtmatching(TString infdfinder=Form("/export/d00/scratch/jwang/Dmeson/evtmatchingInput/DfinderMC_Pyquen_D0tokaonpion_D0pt%.0fp0_Pthat%.0f_TuneZ2_Unquenched_5020GeV_GENSIM_75x_v2_20151027.root",pthat,pthat), TString infhlt=Form("/export/d00/scratch/jwang/Dmeson/evtmatchingInput/openHLT_HF_HLTHeavyFlavour_MVA_Pyquen_D0tokaonpion_D0pt%.0fp0_Pthat%.0f_1026.root",pthat,pthat),TString outfile=Form("/export/d00/scratch/jwang/Dmeson/DfinderMC_20151028_EvtMatching_Pyquen_D0tokaonpion_D0pt%.0fp0_Pthat%.0f_TuneZ2_Unquenched_5020GeV_GENSIM_75x_v2_20151027.root",pthat,pthat))
{
  TFile* fdfinder = new TFile(infdfinder);
  TFile* fhlt = new TFile(infhlt);
  TTree* root = (TTree*)fdfinder->Get("Dfinder/root");
  TTree* hiroot = (TTree*)fdfinder->Get("hiEvtAnalyzer/HiTree");
  TTree* hltroot = (TTree*)fhlt->Get("hltbitanalysis/HltTree");

  TFile* outf = new TFile(outfile,"recreate");
  TDirectory* droot = outf->mkdir("Dfinder","");
  TDirectory* dhltroot = outf->mkdir("hltbitanalysis","");
  TDirectory* dhiroot = outf->mkdir("hiEvtAnalyzer","");
  droot->cd();
  TTree* ntReco = root->CloneTree(0);
  dhltroot->cd();
  TTree* ntHlt = hltroot->CloneTree(0);
  dhiroot->cd();
  TTree* ntHi = hiroot->CloneTree(0);

  setEvtDBranch(root);
  setEvtHLTBranch(hltroot);
  setEvtHIBranch(hiroot);
  cout<<"---- Check evt no. for three trees"<<endl;
  cout<<root->GetEntries()<<", "<<hltroot->GetEntries()<<", "<<hiroot->GetEntries()<<endl;
  Long64_t nentriesReco = root->GetEntries();
  Long64_t nentriesHlt = hltroot->GetEntries();
  Long64_t nentriesHi = hiroot->GetEntries();
  Int_t aRecoRunNo[nentriesReco],aRecoEvtNo[nentriesReco],aRecoLumiNo[nentriesReco];
  Int_t aHltRun[nentriesHlt],aHltEvent[nentriesHlt],aHltLumiBlock[nentriesHlt];
  Int_t aHiRun[nentriesHi],aHiEvt[nentriesHi],aHiLumi[nentriesHi];
  cout<<"---- Event reading"<<endl;
  Long64_t nentriesMax;
  if(nentriesHi>((nentriesReco>nentriesHlt)?nentriesReco:nentriesHlt)) nentriesMax=nentriesHi;
  else nentriesMax=((nentriesReco>nentriesHlt)?nentriesReco:nentriesHlt);
  for(Int_t i=0;i<nentriesMax;i++)
    {
      if(i%10000==0)
	{
	  cout<<setw(7)<<i<<" / "<<nentriesMax<<endl;
	}
      if(i<nentriesReco)
	{
	  root->GetEntry(i);
	  aRecoRunNo[i] = RecoRunNo;
	  aRecoEvtNo[i] = RecoEvtNo;
	  aRecoLumiNo[i] = RecoLumiNo;
	}
      if(i<nentriesHlt)
	{
	  hltroot->GetEntry(i);
	  aHltRun[i] = HltRun;
	  aHltEvent[i] = (Int_t)HltEvent;
	  aHltLumiBlock[i] = HltLumiBlock;
	}
      if(i<nentriesHi)
	{
	  hiroot->GetEntry(i);
	  aHiRun[i] = HiRun;
	  aHiEvt[i] = HiEvt;
	  aHiLumi[i] = HiLumi;
	}
    }

  Int_t hltmatching[nentriesReco],himatching[nentriesReco];
  ofstream fout("evtmatchingResult/evtmatching.dat");
  cout<<"---- Event matching"<<endl;
  for(Int_t ievt=0;ievt<nentriesReco;ievt++)
    {
      if(ievt%10000==0) cout<<setw(7)<<ievt<<" / "<<nentriesReco<<endl;
      hltmatching[ievt] = -1;
      himatching[ievt] = -1;
      for(Int_t jevt=0;jevt<nentriesHlt;jevt++)
	{
	  if(aRecoRunNo[ievt]==aHltRun[jevt]&&aRecoEvtNo[ievt]==aHltEvent[jevt]&&aRecoLumiNo[ievt]==aHltLumiBlock[jevt])
	    {
	      hltmatching[ievt] = jevt;
	      break;
	    }
	}
      for(Int_t jevt=0;jevt<nentriesHi;jevt++)
	{
	  if(aRecoRunNo[ievt]==aHiRun[jevt]&&aRecoEvtNo[ievt]==aHiEvt[jevt]&&aRecoLumiNo[ievt]==aHiLumi[jevt])
	    {
	      himatching[ievt] = jevt;
	      break;
	    }
	}
      fout<<hltmatching[ievt]<<" "<<himatching[ievt]<<endl;
    }
  cout<<"---- Event matching done"<<endl;
  cout<<"---- Writing hlt tree"<<endl;
  for(Int_t i=0;i<nentriesReco;i++)
    {
      if (i%1000==0) cout<<setw(7)<<i<<" / "<<nentriesReco<<"  HI index:"<<setiosflags(ios::left)<<setw(7)<<himatching[i]<<" HLT index:"<<hltmatching[i]<<endl;
      if(hltmatching[i]<0)
	{
	  continue;
	}
      root->GetEntry(i);
      droot->cd();
      ntReco->Fill();
      hiroot->GetEntry(himatching[i]);
      dhiroot->cd();
      ntHi->Fill();
      hltroot->GetEntry(hltmatching[i]);
      dhltroot->cd();
      ntHlt->Fill();
    }
  outf->Write();
  cout<<"---- Writing hlt tree done"<<endl;
  outf->Close();

  return 1;
}
コード例 #3
0
void NormalizeRunTo1Paddle(const Int_t run, const TString& histname)
{

    cout << fnm.GetSclrFileName(true) << endl;

    ScalerTool st(fnm.GetSclrFileName(true).data());

    stringstream ss;
    ss << fnm.GetHistFileBase(true) << run << ".root";
    TFile f(ss.str().data(),"UPDATE");
    cout << "Reading " << ss.str() << endl;
    TDirectory *dir = f.GetDirectory(histname.Data());
    if (dir==NULL)
    {
        cout << histname.Data() <<" is not a directory" << endl;
        return;
    }
    else
    {
        dir->cd();
    }
    vector<TH1*> vec = ROOTUtils::GetAllTH1InFile(dir);
    // the order is not important
    //ROOTUtils::EnforceProperOrdering(vec);
    cout << "Found " << vec.size() << " histograms" << endl;

    stringstream ss1;
    ss1 << normed_file << run << ".root";
    TFile normf(ss1.str().data(),"UPDATE");
    TDirectory *normdir = normf.GetDirectory(histname.Data());
    if (normdir==NULL)
    {
        normdir = normf.mkdir(histname.Data());
    }
    normdir->cd();

    vector<TH1*>::iterator it;
    Int_t val = st.GetValue(run,14);
    cout << endl;
    cout << "Normalization by 1Pad/100 = " << val << endl;
    for (it=vec.begin(); it!=vec.end(); it++)
    {
        if (val!=0)
            (*it)->Scale(0.01/val);
        else
            continue;

        string name = (*it)->GetName();
        name.append("_norm_1pad");
        (*it)->SetName(name.data());
        name = (*it)->GetTitle();
        name.append(" Normed to 1Pad");
        (*it)->SetTitle(name.data());
    //    normf.cd();
        normdir->cd();
        (*it)->Write();
    }
    cout << "Normalized histograms saved in " << normed_file << endl;

    //  return 0;

}
コード例 #4
0
ファイル: looper.C プロジェクト: hooberman/UserCode
void looper::ScanChain (TChain* chain, const char* prefix, bool isData, int nEvents){

  bookHistos();

  set_goodrun_file("Cert_TopAug13_Merged_135059-142664_goodruns.txt");
  ofile.open( Form( "output/%s_%s_events.txt" , prefix , iter ) );

  TObjArray *listOfFiles = chain->GetListOfFiles();

  unsigned int nEventsChain = 0;
  if(nEvents == -1) 
    nEvents = chain->GetEntries();
  nEventsChain = nEvents;
  unsigned int nEventsTotal = 0;

  MakeBabyNtuple( Form( "output/%s_%s_baby.root" , prefix , iter) );

  DorkyEventIdentifier dei;

  //pass fail counters
  int nPassDuplicate  = 0;
  int nPassGoodRun    = 0;

  float nGoodMu = 0;
  float nGoodEl = 0;

  if( debug ) cout << "Begin looping over files" << endl;

  if( isData ){
    cout << "|" << setw(8)  << "run"          << setw(4) 
         << "|" << setw(6)  << "lumi"         << setw(4) 
         << "|" << setw(12) << "event"        << setw(4) 
         << "|" << setw(6)  << "type"         << setw(4) 
         << "|" << setw(6)  << "njets"        << setw(4) 
         << "|" << setw(6)  << "nbtags"       << setw(4) 
         << "|" << setw(8)  << "tcmet"        << setw(4) 
         << "|" << setw(8)  << "cltcmet"      << setw(4) 
         << "|" << setw(8)  << "pftcmet"      << setw(4) 
         << "|" << setw(8)  << "pfmet"        << setw(4) 
         << "|" << setw(8)  << "dphi"         << setw(4) << "|" << endl; 
  }

  // file loop
  TIter fileIter(listOfFiles);
  TFile* currentFile = 0;
  while ((currentFile = (TFile*)fileIter.Next()))
    {
      TFile f(currentFile->GetTitle());
      TTree *tree = (TTree*)f.Get("Events");
      cms2.Init(tree);

      // event loop
      unsigned int nEvents = tree->GetEntries();

      for (unsigned int event = 0; event < nEvents; ++event)
        {
          if( debug ) cout << "Event " << event << endl;

          cms2.GetEntry(event);
          ++nEventsTotal;

          // progress feedback to user
          if (nEventsTotal % 1000 == 0)
            {
              // xterm magic from L. Vacavant and A. Cerri
              if (isatty(1))
                {
                  printf("\015\033[32m ---> \033[1m\033[31m%4.1f%%"
                         "\033[0m\033[32m <---\033[0m\015", (float)nEventsTotal/(nEventsChain*0.01));
                  fflush(stdout);
                }
            }
	  

          //APPLY BASIC EVENT SELECTIONS
          //TRIGGER, TRACKING AND VERTEX
          if( dei.is_duplicate( DorkyEvent() ) ) continue;
          nPassDuplicate++;

          if (!isData || goodrun(cms2.evt_run(), cms2.evt_lumiBlock()))
            nPassGoodRun++;
	  else continue;
        
          float weight = 1.;
          if     ( strcmp(prefix,"data") == 0  ) weight = 1;
          else if( strcmp(prefix,"ZJets") == 0 ) weight = 1.27 * 2.2121427 * 0.84e-3;
          else if( strcmp(prefix,"TTBar") == 0 ) weight = 0.1112306 * 0.84e-3;
          else if( strcmp(prefix,"Vqq") == 0   ) weight = 0.0408562 * 0.84e-3;
          else{
            cout << "I DON'T RECOGNIZE " << prefix << endl;
            exit(0);
          }

          for( unsigned int hypIdx = 0 ; hypIdx < hyp_type().size() ; hypIdx++ ){
      
            InitBabyNtuple();
            
            int myType = 99;
            if (hyp_type()[hypIdx] == 3) myType = 0;                          // ee
            if (hyp_type()[hypIdx] == 0) myType = 1;                          // mm
            if (hyp_type()[hypIdx] == 1 || hyp_type()[hypIdx] == 2) myType=2; // em
            if (myType == 99) {
              cout << "Skipping unknown dilepton type = " << hyp_type()[hypIdx] << endl;
              continue;
            }

            //----------SELECTION----------------------------------------------------

            //pT > (20,20) GeV
            if( hyp_ll_p4()[hypIdx].pt() < 20 ) continue;
            if( hyp_lt_p4()[hypIdx].pt() < 20 ) continue;
 
            //ttbar muon ID
            if (abs(hyp_ll_id()[hypIdx]) == 13  && (! (fabs(hyp_ll_p4()[hypIdx].eta()) < 2.4 && muonId(hyp_ll_index()[hypIdx],NominalTTbar))))   continue;
            if (abs(hyp_lt_id()[hypIdx]) == 13  && (! (fabs(hyp_lt_p4()[hypIdx].eta()) < 2.4 && muonId(hyp_lt_index()[hypIdx],NominalTTbar))))   continue;
         
            //ttbarV1 electron ID
            if (abs(hyp_ll_id()[hypIdx]) == 11  && (! pass_electronSelection( hyp_ll_index()[hypIdx] , electronSelection_ttbarV1 , isData ))) continue;
            if (abs(hyp_lt_id()[hypIdx]) == 11  && (! pass_electronSelection( hyp_lt_index()[hypIdx] , electronSelection_ttbarV1 , isData ))) continue;

            //ttbar electron ID
            //if (abs(hyp_ll_id()[hypIdx]) == 11  && (! pass_electronSelection( hyp_ll_index()[hypIdx] , electronSelection_ttbar , isData ))) continue;
            //if (abs(hyp_lt_id()[hypIdx]) == 11  && (! pass_electronSelection( hyp_lt_index()[hypIdx] , electronSelection_ttbar , isData ))) continue;

            //nominal muon ID
            //if (abs(hyp_ll_id()[hypIdx]) == 13  && (! (fabs(hyp_ll_p4()[hypIdx].eta()) < 2.4 && muonId(hyp_ll_index()[hypIdx]))))   continue;
            //if (abs(hyp_lt_id()[hypIdx]) == 13  && (! (fabs(hyp_lt_p4()[hypIdx].eta()) < 2.4 && muonId(hyp_lt_index()[hypIdx]))))   continue;
         
            //ttbar electron ID
            //if (abs(hyp_ll_id()[hypIdx]) == 11  && (! pass_electronSelection( hyp_ll_index()[hypIdx] , electronSelection_cand01 ))) continue;
            //if (abs(hyp_lt_id()[hypIdx]) == 11  && (! pass_electronSelection( hyp_lt_index()[hypIdx] , electronSelection_cand01 ))) continue;

            //same flavor
            if( hyp_type()[hypIdx] == 1 ) continue;
            if( hyp_type()[hypIdx] == 2 ) continue;
            
            //opposite sign
            if( hyp_lt_id()[hypIdx] *  hyp_ll_id()[hypIdx] > 0 ) continue;

            //fill dilmass histo before cutting on dilmass
            dilMass_ = hyp_p4()[hypIdx].mass();
            fillHistos( hdilMass          , dilMass_  , weight , myType );

            if( dilMass_ < 76. || dilMass_ > 106. ) continue;

            if( myType == 0 ) nGoodEl+=weight;
            if( myType == 1 ) nGoodMu+=weight;

            //----------CORRECT TCMET FOR HYP MUONS---------------------------------------------

            metStruct tcmetStruct = correctTCMETforHypMuons( hypIdx , 
                                                             evt_tcmet() * cos( evt_tcmetPhi() ), 
                                                             evt_tcmet() * sin( evt_tcmetPhi() ),
                                                             evt_tcsumet() );
              
 

            // out-of-the-box  tcmet stuff (corrected for hyp muons)
            tcmet_    = tcmetStruct.met;
            tcmetphi_ = tcmetStruct.metphi;
            tcsumet_  = tcmetStruct.sumet;

            if( isData ){
              
              metStruct tcmetStructNewCalo = correctTCMETforHypMuons( hypIdx , 
                                                                      evtNew_tcmet() * cos( evtNew_tcmetPhi() ), 
                                                                      evtNew_tcmet() * sin( evtNew_tcmetPhi() ),
                                                                      evtNew_tcsumet() );
              tcmetNew_calo_ = tcmetStructNewCalo.met;

              metStruct tcmetStructNewPFC = correctTCMETforHypMuons( hypIdx , 
                                                                     evtNewPFC_tcmet() * cos( evtNewPFC_tcmetPhi() ), 
                                                                     evtNewPFC_tcmet() * sin( evtNewPFC_tcmetPhi() ),
                                                                     evtNewPFC_tcsumet() );
              tcmetNew_pfc_ = tcmetStructNewPFC.met;

            }else{
              tcmetNew_calo_ = tcmet_;
              tcmetNew_pfc_  = tcmet_;
            }


            //---------JET STUFF--------------------------------------------------------------

            int nJets        = 0;
            float sumJetPt   = 0;
            int nBTags       = 0;
            float maxcosdphi = -99;
            int imax         = -1;
            
            for (unsigned int ijet = 0; ijet < pfjets_p4().size(); ijet++) {

              LorentzVector vjet = pfjets_p4().at(ijet);
              LorentzVector vlt  = hyp_lt_p4()[hypIdx];
              LorentzVector vll  = hyp_ll_p4()[hypIdx];
              if (dRbetweenVectors(vjet, vll) < 0.4) continue;
              if (dRbetweenVectors(vjet, vlt) < 0.4) continue;
              
              if ( vjet.pt() > 30. && fabs(vjet.eta()) < 2.5 ) {
                nJets++;
                sumJetPt+=vjet.pt();
                fillHistos( hjetpt , vjet.pt() , weight , myType );

                float dRmin = 100;
                int imin = -1;
                
                if( fabs( cos( tcmetphi_ - vjet.phi() ) ) > maxcosdphi ){
                  maxcosdphi = fabs( cos( tcmetphi_ - vjet.phi() ) );
                  imax = ijet;
                  dphijetmet_ = fabs( tcmetphi_ - vjet.phi() );
                  if( dphijetmet_ > TMath::Pi() ) dphijetmet_ = TMath::TwoPi() - dphijetmet_;
                }

                //find closest calojet to use btagging info
                for( unsigned int icalojet = 0 ; icalojet < jets_p4().size() ; icalojet++ ){

                  LorentzVector vcalojet = jets_p4().at(icalojet);
                  if( vcalojet.pt() * jets_cor().at(icalojet) < 10 ) continue;
                  
                  float dR = dRbetweenVectors(vjet, vcalojet);
                  if( dR < dRmin ){
                    dRmin = dR;
                    imin = icalojet;
                  }
                }

                if( imin > -1 ){
                  if( jets_simpleSecondaryVertexHighEffBJetTag().at(imin) > 1.74 ) nBTags++;
                  //if( jets_trackCountingHighEffBJetTag().at(imin) > 1.7 ) nBTags++;
                }

              }
            }

          
            
      

            // event stuff
            run_    = cms2.evt_run();
            lumi_   = cms2.evt_lumiBlock();
            event_  = cms2.evt_event();

            // pf met stuff
            pfmet_    = cms2.evt_pfmet();
            pfmetphi_ = cms2.evt_pfmetPhi();
            pfsumet_  = cms2.evt_pfsumet();

            //calomet
            met_       = cms2.evt_met();
            metphi_    = cms2.evt_metPhi();
            sumet_     = cms2.evt_sumet();
     
            //electron eta
            if( myType == 0 ){
              if( tcmet_ < 20 ){
                fillUnderOverFlow( heleta_metlt20 , hyp_lt_p4()[hypIdx].eta() , weight );
                fillUnderOverFlow( heleta_metlt20 , hyp_ll_p4()[hypIdx].eta() , weight );
              }
              else if( tcmet_ > 30 ){
                fillUnderOverFlow( heleta_metgt30 , hyp_lt_p4()[hypIdx].eta() , weight );
                fillUnderOverFlow( heleta_metgt30 , hyp_ll_p4()[hypIdx].eta() , weight );
              }
            }

            //muon eta
            if( myType == 1 ){
              if( tcmet_ < 20 ){
                fillUnderOverFlow( hmueta_metlt20 , hyp_lt_p4()[hypIdx].eta() , weight );
                fillUnderOverFlow( hmueta_metlt20 , hyp_ll_p4()[hypIdx].eta() , weight );
              }
              else if( tcmet_ > 30 ){
                fillUnderOverFlow( hmueta_metgt30 , hyp_lt_p4()[hypIdx].eta() , weight );
                fillUnderOverFlow( hmueta_metgt30 , hyp_ll_p4()[hypIdx].eta() , weight );
              }
            }

            //look at track pT's near electron
            if( myType == 0 && tcmet_ > 30 ){
              for( unsigned int itrk = 0 ; itrk < trks_trk_p4().size() ; ++itrk ){
               
                if( isMuon( itrk ) )            continue;
                if( isElectron( itrk ) )        continue;
                if( !isGoodTrack( itrk ) )      continue;
             
                LorentzVector vtrk = trks_trk_p4().at(itrk);
                LorentzVector vlt  = hyp_lt_p4()[hypIdx];
                LorentzVector vll  = hyp_ll_p4()[hypIdx];

                float drll = dRbetweenVectors(vtrk, vll);
                float drlt = dRbetweenVectors(vtrk, vlt);

                if( drll < 0.3 || drlt < 0.3 ){
                  fillUnderOverFlow( htrkptnearel , trks_trk_p4().at(itrk).pt() , weight );
                  //printEvent();
                  //cout << "pt eta phi " << vtrk.pt() << " " << vtrk.eta() << " " << vtrk.phi() << endl;
                }
              }
            }

            string leptype[2]={"ee","mm"};

            if( isData && ( tcmet_ > 30. || pfmet_ > 30. ) ){

              if( calculateTCMET ){
                
                // calculate tcmet on-the-fly
                metStruct structMET = correctedTCMET( true, ofile );
                
              }

              cout << "|" << setw(8)  << evt_run()                   << setw(4) 
                   << "|" << setw(6)  << evt_lumiBlock()             << setw(4) 
                   << "|" << setw(12) << evt_event()                 << setw(4) 
                   << "|" << setw(6)  << leptype[myType]             << setw(4) 
                   << "|" << setw(6)  << nJets                       << setw(4) 
                   << "|" << setw(6)  << nBTags                      << setw(4) 
                   << "|" << setw(8)  << fround(tcmet_,1)            << setw(4) 
                   << "|" << setw(8)  << fround(tcmetNew_calo_,1)    << setw(4) 
                   << "|" << setw(8)  << fround(tcmetNew_pfc_,1)     << setw(4) 
                   << "|" << setw(8)  << fround(pfmet_,1)            << setw(4) 
                   << "|" << setw(8)  << fround(dphijetmet_,2)       << setw(4) << "|" << endl; 
            }

            if( imax > -1 ){

              if( tcmet_ < 20 )
                fillHistos( hdphijetmet_metlt20  , dphijetmet_    , weight , myType , nJets  );

              if( tcmet_ > 30 )
                fillHistos( hdphijetmet_metgt30  , dphijetmet_    , weight , myType , nJets  );

            }

            fillHistos( hnjets            , nJets            , weight , myType );
            fillHistos( htcmet            , tcmet_           , weight , myType , nJets );
            fillHistos( htcmetNew_calo    , tcmetNew_calo_   , weight , myType , nJets  );
            fillHistos( htcmetNew_pfc     , tcmetNew_pfc_    , weight , myType , nJets  );
            fillHistos( hpfmet            , pfmet_           , weight , myType , nJets  );
            
            njets_   = nJets;
            leptype_ = myType;

            eventTree_->Fill();
          }// end loop over hypotheses
        } // end loop over events
    } // end loop over files
  
  cout << "\n\n********************SUMMARY********************" << endl;
  cout << "Total number of events: " << nEventsTotal << endl;
  cout << "Total number of events that pass dup veto: " << nPassDuplicate 
       << " (" << 100*(double)nPassDuplicate/nEventsTotal << "% of total)" << endl;
  cout << "Total number of events that pass good run/lumi: " << nPassGoodRun 
       << " (" << 100*(double)nPassGoodRun/nEventsTotal << "% of total)" << endl;

  cout << nGoodEl << " ee events in Z mass window" << endl;
  cout << nGoodMu << " mm events in Z mass window" << endl;

  if (nEventsChain != nEventsTotal)
    std::cout << "ERROR: number of events from files is not equal to total number of events" << std::endl;

  CloseBabyNtuple();

  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  rootdir->cd();
  saveHist( Form( "output/%s_%s_histos.root" , prefix , iter ) );
  deleteHistos();

  
} // end ScanChain
コード例 #5
0
int fillCSHistos(string vetoedInputFileName, string nonVetoInputFileName, bool useVetoPaddle, string macropulseFileName, string gammaCorrectionFileName, ofstream& logFile, string outputFileName)
{
    ifstream f(outputFileName);

    if(f.good())
    {
        cout << outputFileName << " already exists; skipping gated histogramming of events." << endl;
        logFile << outputFileName << " already exists; skipping gated histogramming of events." << endl;
        return 2;
    }

    logFile << endl << "*** Filling CS histos ***" << endl;

    TFile* vetoedInputFile;
    if(useVetoPaddle)
    {
        // open vetoed input tree
        vetoedInputFile = new TFile(vetoedInputFileName.c_str(),"READ");
        if(!vetoedInputFile->IsOpen())
        {
            cerr << "Error: failed to open " << vetoedInputFileName << "  to fill histos." << endl;
            return 1;
        }
    }

    // open non-vetoed input tree
    TFile* nonVetoInputFile = new TFile(nonVetoInputFileName.c_str(),"READ");
    if(!nonVetoInputFile->IsOpen())
    {
        cerr << "Error: failed to open " << nonVetoInputFileName << "  to fill histos." << endl;
        return 1;
    }

    // open macropulse tree
    TFile* macropulseFile = new TFile(macropulseFileName.c_str(),"READ");
    if(!macropulseFile->IsOpen())
    {
        cerr << "Error: failed to open " << macropulseFileName << "  to fill histos." << endl;
        vetoedInputFile->Close();
        return 1;
    }

    TTree* macropulseTree = (TTree*)(macropulseFile->Get("macropulses"));
    if(!macropulseTree)
    {
        cerr << "Error: failed to open macropulses tree to gate histos." << endl;
        vetoedInputFile->Close();
        macropulseFile->Close();
        return 1;
    }

    MacropulseEvent me;

    macropulseTree->SetBranchAddress("cycleNumber",&me.cycleNumber);
    macropulseTree->SetBranchAddress("macroNo",&me.macroNo);
    macropulseTree->SetBranchAddress("macroTime",&me.macroTime);
    macropulseTree->SetBranchAddress("targetPos",&me.targetPos);
    macropulseTree->SetBranchAddress("numberOfEventsInMacro",&me.numberOfEventsInMacro);
    macropulseTree->SetBranchAddress("numberOfMonitorsInMacro",&me.numberOfMonitorsInMacro);
    macropulseTree->SetBranchAddress("isGoodMacro",&me.isGoodMacro);

    vector<MacropulseEvent> macropulseList;

    int numberOfEntries = macropulseTree->GetEntries();

    if(numberOfEntries==0)
    {
        cerr << "Error: no macropulses found in macropulseTree during fillCSHistos." << endl;

        if(vetoedInputFile)
        {
            vetoedInputFile->Close();
        }

        nonVetoInputFile->Close();
        macropulseFile->Close();
        return 1;
    }

    for(int i=0; i<numberOfEntries; i++)
    {
        macropulseTree->GetEntry(i);

        macropulseList.push_back(me);
    }

    // open gamma correction file
    TFile* gammaCorrectionFile = new TFile(gammaCorrectionFileName.c_str(),"READ");
    if(!gammaCorrectionFile->IsOpen())
    {
        cerr << "Error: failed to open " << gammaCorrectionFileName << "  to read gamma correction." << endl;

        if(vetoedInputFile)
        {
            vetoedInputFile->Close();
        }

        nonVetoInputFile->Close();
        macropulseFile->Close();
        return 1;
    }

    TDirectory* gammaDirectory = (TDirectory*)gammaCorrectionFile->Get(config.analysis.GAMMA_CORRECTION_TREE_NAME.c_str());
    if(!gammaDirectory)
    {
        cerr << "Error: failed to open summedDet directory in " << gammaCorrectionFileName << " for reading gamma corrections." << endl;

        if(vetoedInputFile)
        {
            vetoedInputFile->Close();
        }

        nonVetoInputFile->Close();
        macropulseFile->Close();
        gammaCorrectionFile->Close();
        return 1;
    }

    gammaDirectory->cd();

    TH1D* gammaCorrectionHisto = (TH1D*)gammaDirectory->Get("gammaCorrection");
    if(!gammaCorrectionHisto)
    {
        cerr << "Error: failed to open gammaCorrections histo in " << gammaCorrectionFileName << " for reading gamma corrections." << endl;

        if(vetoedInputFile)
        {
            vetoedInputFile->Close();
        }

        nonVetoInputFile->Close();
        macropulseFile->Close();
        gammaCorrectionFile->Close();

        return 1;
    }

    vector<double> gammaCorrectionList;

    int gammaCorrectionBins = gammaCorrectionHisto->GetNbinsX();
    for(int i=1; i<=gammaCorrectionBins; i++)
    {
        gammaCorrectionList.push_back(gammaCorrectionHisto->GetBinContent(i));
    }

    // define gamma times
    const double GAMMA_TIME = pow(10,7)*config.facility.FLIGHT_DISTANCE/C;
    const double GAMMA_WINDOW_WIDTH = config.time.GAMMA_WINDOW_SIZE/2;

    // create outputFile
    TFile* outputFile = new TFile(outputFileName.c_str(),"UPDATE");

    for(auto& channel : config.digitizer.CHANNEL_MAP)
    {
        if(channel.second == "-" || channel.second == "macroTime"
                || channel.second == "targetChanger")
        {
            continue;
        }

        bool isDetector = false;

        TTree* tree;

        for(auto& detName : config.cs.DETECTOR_NAMES)
        {
            if(channel.second == detName)
            {
                isDetector = true;
                break;
            }
        }

        cout << "Filling gated histograms for tree \"" << channel.second << "\"..." << endl;

        if(isDetector && useVetoPaddle)
        {
            tree = (TTree*)vetoedInputFile->Get(channel.second.c_str());
        }

        else
        {
            tree = (TTree*)nonVetoInputFile->Get(channel.second.c_str());
        }

        if(!tree)
        {
            cerr << "Error: tried to populate advanced histos, but failed to find " << channel.second << " in " << vetoedInputFileName << endl;
            vetoedInputFile->Close();
            macropulseFile->Close();
            gammaCorrectionFile->Close();

            return 1;
        }

        // connect input tree to event data buffer
        DetectorEvent event;
        vector<int>* waveformPointer = 0;

        tree->SetBranchAddress("cycleNumber",&event.cycleNumber);
        tree->SetBranchAddress("macroNo",&event.macroNo);
        tree->SetBranchAddress("macroTime",&event.macroTime);
        tree->SetBranchAddress("fineTime",&event.fineTime);
        tree->SetBranchAddress("eventNo",&event.eventNo);
        tree->SetBranchAddress("completeTime",&event.completeTime);
        tree->SetBranchAddress("targetPos",&event.targetPos);
        tree->SetBranchAddress("sgQ",&event.sgQ);
        tree->SetBranchAddress("lgQ",&event.lgQ);
        tree->SetBranchAddress("waveform",&waveformPointer);

        if(isDetector)
        {
            tree->SetBranchAddress("vetoed",&event.vetoed);
        }

        TDirectory* directory = outputFile->mkdir(channel.second.c_str(),channel.second.c_str());
        directory->cd();

        vector<TH1D*> goodMacroHistos;
        for(string targetName : config.target.TARGET_ORDER)
        {
            string macroNumberName = targetName + "GoodMacros";
            goodMacroHistos.push_back(new TH1D(macroNumberName.c_str(),
                        macroNumberName.c_str(), 500000, 0, 500000));
        }

        // create other diagnostic histograms used to examine run data
        TH1D* timeDiffHisto = new TH1D("time since last event","time since last event",
                config.plot.TOF_RANGE,0,config.plot.TOF_RANGE);
        TH2D* timeDiffVEnergy1 = new TH2D("time difference vs. energy of first",
                "time difference vs. energy of first",config.plot.TOF_RANGE,
                0,config.plot.TOF_RANGE,10*config.plot.NUMBER_ENERGY_BINS,2,700);

        TH2D* time1Vtime2 = new TH2D("time of first vs. time of second",
                "time of first vs. time of second",config.plot.TOF_RANGE,0,
                config.plot.TOF_RANGE,config.plot.TOF_RANGE,0,
                config.plot.TOF_RANGE);

        TH2D* energy1VEnergy2 = new TH2D("energy of first vs. energy of second",
                "energy of first vs. energy of second",
                10*config.plot.NUMBER_ENERGY_BINS, floor(config.plot.ENERGY_LOWER_BOUND), ceil(config.plot.ENERGY_UPPER_BOUND),
                10*config.plot.NUMBER_ENERGY_BINS, floor(config.plot.ENERGY_LOWER_BOUND), ceil(config.plot.ENERGY_UPPER_BOUND));

        TH1D* microNoH = new TH1D("microNoH","microNo",config.facility.MICROS_PER_MACRO+1
                ,0,config.facility.MICROS_PER_MACRO+1);

        vector<TH1D*> TOFHistos;
        vector<TH2D*> triangleHistos;
        vector<TH1D*> vetoTOFHistos;
        vector<TH2D*> vetoTriangleHistos;

        for(string targetName : config.target.TARGET_ORDER)
        {
            string TOFName = targetName + "TOF";
            TOFHistos.push_back(new TH1D(TOFName.c_str(),
                        TOFName.c_str(),
                        config.plot.TOF_BINS,
                        config.plot.TOF_LOWER_BOUND,
                        config.plot.TOF_UPPER_BOUND));

            string triangleName = targetName + "Triangle";
            triangleHistos.push_back(new TH2D(triangleName.c_str(),
                        triangleName.c_str(),
                        config.plot.TOF_RANGE,
                        config.plot.TOF_LOWER_BOUND,
                        config.plot.TOF_UPPER_BOUND,
                        pow(2,9),0,pow(2,15)));

            string vetoTOFName = "veto" + TOFName;
            vetoTOFHistos.push_back(new TH1D(vetoTOFName.c_str(),
                        vetoTOFName.c_str(),
                        config.plot.TOF_BINS,
                        config.plot.TOF_LOWER_BOUND,
                        config.plot.TOF_UPPER_BOUND));

            string vetoTriangleName = "veto" + triangleName;
            vetoTriangleHistos.push_back(new TH2D(vetoTriangleName.c_str(),
                        vetoTriangleName.c_str(),
                        config.plot.TOF_RANGE,
                        config.plot.TOF_LOWER_BOUND,
                        config.plot.TOF_UPPER_BOUND,
                        pow(2,9),0,pow(2,15)));
        }

        double prevCompleteTime = 0;
        double prevlgQ = 0;

        double microTime;
        double prevMicroTime = 0;
        int microNo;

        double timeDiff;
        double eventTimeDiff = 0;
        double velocity;
        double rKE;
        double prevRKE = 0;

        double prevAverageTime = 0;

        const double MACRO_LENGTH = config.facility.MICROS_PER_MACRO*config.facility.MICRO_LENGTH;

        long badMacroEvent = 0;
        long badChargeGateEvent = 0;
        long badChargeRatioEvent = 0;
        long outsideMacro = 0;

        int totalEntries = tree->GetEntries();

        int currentMacropulse = 0;
        bool endGatedHistoFill = false;

        int startOfCycleMacro = 0;
        int prevCycleNumber = 0;

        int facilityCounter = 0;

        vector<int> targetPositionPreviousMacro(7,-1);
        vector<int> targetPositionMacroCounter(7,0);

        // fill advanced histos
        for(long i=0; i<totalEntries; i++)
        {
            tree->GetEntry(i);

            if(event.cycleNumber > prevCycleNumber)
            {
                startOfCycleMacro = event.macroNo;
                prevCycleNumber = event.cycleNumber;
            }

            if(event.macroNo > macropulseList[currentMacropulse].macroNo)
            {
                currentMacropulse++;
                if(currentMacropulse>(macropulseList.size()-1))
                {
                    cout << "Reached end of gatedMacropulseList; ending fillCSHistos." << endl;
                    break;
                }

                facilityCounter++;

                if(macropulseList[currentMacropulse].macroTime - 8.4*pow(10,6) > macropulseList[currentMacropulse-1].macroTime)
                {
                    facilityCounter = 0;
                }

                continue;
            }

            // throw away events during "bad" macropulses
            if(!(macropulseList[currentMacropulse].isGoodMacro))
            {
                badMacroEvent++;
                continue;
            }

            if((int)event.macroNo > targetPositionPreviousMacro[event.targetPos])
            {
                targetPositionPreviousMacro[event.targetPos] = event.macroNo;
                targetPositionMacroCounter[event.targetPos]++;
            }

            // charge gates:
            if(isDetector)
            {
                if(event.lgQ<config.analysis.CHARGE_GATE_LOW_THRESHOLD
                        || event.lgQ>config.analysis.CHARGE_GATE_HIGH_THRESHOLD)
                {
                    badChargeGateEvent++;
                    continue;
                }

                /*if(event.sgQ/(double)event.lgQ < config.analysis.Q_RATIO_LOW_THRESHOLD
                        || event.sgQ/(double)event.lgQ > config.analysis.Q_RATIO_HIGH_THRESHOLD)
                {
                    badChargeRatioEvent++;
                    continue;
                }*/
            }

            /*****************************************************************/
            // Calculate event properties

            // find which micropulse the event is in and the time since the start of
            // the micropulse (the TOF)
            timeDiff = event.completeTime-event.macroTime;

            // correct times using average gamma time
            timeDiff -= gammaCorrectionList[event.macroNo];

            // timing gate
            if(timeDiff > MACRO_LENGTH)
            {
                outsideMacro++;
                continue;
            }

            eventTimeDiff = event.completeTime-prevCompleteTime;
            microNo = floor(timeDiff/config.facility.MICRO_LENGTH);
            microTime = fmod(timeDiff,config.facility.MICRO_LENGTH);

            // micropulse gate:
            if(microNo < config.facility.FIRST_GOOD_MICRO
                    || microNo >= config.facility.LAST_GOOD_MICRO)
            {
                continue;
            }

            // veto gate: apply to neutron events only
            if(event.vetoed && microTime > GAMMA_TIME+GAMMA_WINDOW_WIDTH*2)
            {
                vetoTOFHistos[event.targetPos]->Fill(microTime);
                vetoTriangleHistos[event.targetPos]->Fill(microTime, event.lgQ);

                continue;
            }

            // convert micropulse time into neutron velocity based on flight path distance
            velocity = (pow(10.,7.)*config.facility.FLIGHT_DISTANCE)/microTime; // in meters/sec 

            // convert velocity to relativistic kinetic energy
            rKE = (pow((1.-pow((velocity/C),2.)),-0.5)-1.)*NEUTRON_MASS; // in MeV

            TOFHistos[event.targetPos]->Fill(microTime);
            triangleHistos[event.targetPos]->Fill(microTime, event.lgQ);

            // fill detector histograms with event data
            timeDiffHisto->Fill(eventTimeDiff);
            timeDiffVEnergy1->Fill(eventTimeDiff,prevRKE);
            time1Vtime2->Fill(prevMicroTime,microTime);
            energy1VEnergy2->Fill(prevRKE,rKE);
            microNoH->Fill(microNo);

            prevlgQ = event.lgQ;
            prevMicroTime = microTime;
            prevCompleteTime = event.completeTime;
            prevRKE = rKE;

            goodMacroHistos[event.targetPos]->Fill(event.macroNo+1);

            if(i%10000==0)
            {
                cout << "Processed " << i << " " << channel.second << " events into advanced CS histos...\r";
            }
        }

        cout << endl << "Finished populating \"" << channel.second << "\" events into CS histos." << endl;
        cout << "Total events processed = " << totalEntries << endl;

        logFile << endl << "Fraction events filtered out by good macro gate: "
            << 100*(double)badMacroEvent/totalEntries << "%." << endl;

        logFile << "Fraction events filtered out by charge gate (" << config.analysis.CHARGE_GATE_LOW_THRESHOLD
            << " < lgQ < " << config.analysis.CHARGE_GATE_HIGH_THRESHOLD << "): "
            << 100*(double)badChargeGateEvent/totalEntries << "%." << endl;

        logFile << "Fraction events filtered out by charge ratio gate (" << config.analysis.Q_RATIO_LOW_THRESHOLD
            << " < lgQ < " << config.analysis.Q_RATIO_HIGH_THRESHOLD << "): "
            << 100*(double)badChargeRatioEvent/totalEntries << "%." << endl;

        logFile << "Fraction events outside macropulse: "
            << 100*(double)outsideMacro/totalEntries << "%." << endl;

        for(auto& histo : TOFHistos)
        {
            histo->Write();
        }

        for(auto& histo : triangleHistos)
        {
            histo->Write();
        }

        for(auto& histo : vetoTOFHistos)
        {
            histo->Write();
        }

        for(auto& histo : vetoTriangleHistos)
        {
            histo->Write();
        }

        timeDiffHisto->Write();
        timeDiffVEnergy1->Write();
        time1Vtime2->Write();
        energy1VEnergy2->Write();
        microNoH->Write();

        for(auto& histo : goodMacroHistos)
        {
            histo->Write();
        }
    }

    macropulseFile->Close();

    if(useVetoPaddle)
    {
        vetoedInputFile->Close();
    }

    nonVetoInputFile->Close();

    outputFile->Close();

    logFile << endl << "*** Finished filling CS histos ***" << endl;

    return 0;
}
コード例 #6
0
ファイル: ExclusionPlot.C プロジェクト: wa01/usercode
void CommandMSUGRA(TString plotName,Int_t tanBeta_, Bool_t plotLO_, Bool_t tb40_plotExpected) {
  
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  gStyle->SetPalette(1); 
  gStyle->SetTextFont(42);
  gStyle->SetFrameBorderMode(0);

  //convert tanb value to string
  std::stringstream tmp;
  tmp << tanBeta_;
  TString tanb( tmp.str() );
  
  
  // Output file
  std::cout << " create " << plotName << std::endl;
  TFile* output = new TFile( plotName, "RECREATE" );
  if ( !output || output->IsZombie() ) { std::cout << " zombie alarm output is a zombie " << std::endl; }
  

  //set old exclusion Limits
  TGraph* LEP_ch = set_lep_ch(tanBeta_);
  TGraph* LEP_sl = set_lep_sl(tanBeta_);//slepton curve
  TGraph* TEV_sg_cdf = set_tev_sg_cdf(tanBeta_);//squark gluino cdf
  TGraph* TEV_sg_d0 = set_tev_sg_d0(tanBeta_);//squark gluino d0
  //  TGraph* TEV_tlp_cdf = set_tev_tlp_cdf(tanBeta_);//trilepton cdf
  //  TGraph* TEV_tlp_d0 = set_tev_tlp_d0(tanBeta_);//trilepton d0
  TGraph* stau   = set_tev_stau(tanBeta_);//stau 
  TGraph* NoEWSB = set_NoEWSB(tanBeta_); 

  TGraph* TEV_sn_d0_1 = set_sneutrino_d0_1(tanBeta_);
  TGraph* TEV_sn_d0_2 = set_sneutrino_d0_2(tanBeta_);

  //some tan beta 40 stuff (load the squark and gluino mass lines)
  TGraph2D* squarkMasses=0;
  TGraph2D* gluinoMasses=0;
  if (tanBeta_==40) {
    const int nPoints = nSusyGridPoints();
    double m0[nPoints],m12[nPoints],squarkMass[nPoints],gluinoMass[nPoints];
    
    susyGrid(m0,m12,squarkMass,gluinoMass);
    
    squarkMasses = new TGraph2D("squarkMasses","",nPoints,m0,m12,squarkMass);
    gluinoMasses = new TGraph2D("gluinoMasses","",nPoints,m0,m12,gluinoMass);
    
    gluinoMasses->GetHistogram();
    squarkMasses->GetHistogram();
  }
  // end of tan beta 40 stuff

  //constant squark and gluino lines
  TF1* lnsq[10];
  TF1* lngl[10];
  TLatex* sq_text[10];
  TLatex* gl_text[10];

  //versions for tan beta 40
  TGraph* lnsq_40[15];
  TGraph* lngl_40[15];
  TLatex* sq_40_text[15];
  TLatex* gl_40_text[15];

  int loopmax = 6;
  if (tanBeta_==40) loopmax=15;
  for(int i = 0; i < loopmax; i++){
    if (tanBeta_==10) {
      lnsq[i] = constant_squark(tanBeta_,i);
      sq_text[i] = constant_squark_text(i,*lnsq[i],tanBeta_);
      lngl[i] = constant_gluino(tanBeta_,i);
      gl_text[i] = constant_gluino_text(i,*lngl[i]);
    }
    else if (tanBeta_==40) {
      lnsq_40[i] = constant_mass(i*250,squarkMasses);
      lngl_40[i] = constant_mass(i*250,gluinoMasses);
      sq_40_text[i] = constant_squark_text_tanBeta40(i*250,lnsq_40[i]);
      gl_40_text[i] = constant_gluino_text_tanBeta40(i*250,lngl_40[i]);;
    }
  }
  

  //Legends
  TLegend* legst  = makeStauLegend(0.05,tanBeta_);
//   TLegend* legNoEWSB  = makeNoEWSBLegend(0.05,tanBeta_);
  TLegend* legexp = makeExpLegend( *TEV_sg_cdf,*TEV_sg_d0,*LEP_ch,*LEP_sl,*TEV_sn_d0_1,0.035,tanBeta_);
  
 
  //make Canvas
  TCanvas* cvsSys = new TCanvas("cvsnm","cvsnm",0,0,800,600);
  gStyle->SetOptTitle(0);
  cvsSys->SetFillColor(0);
  cvsSys->GetPad(0)->SetRightMargin(0.07);
  cvsSys->Range(-120.5298,26.16437,736.0927,750);
  //  cvsSys->Range(-50.5298,26.16437,736.0927,500);
  cvsSys->SetFillColor(0);
  cvsSys->SetBorderMode(0);
  cvsSys->GetPad(0)->SetBorderMode(0);
  cvsSys->GetPad(0)->SetBorderSize(2);
  cvsSys->GetPad(0)->SetLeftMargin(0.1407035);
  cvsSys->GetPad(0)->SetTopMargin(0.08);
  cvsSys->GetPad(0)->SetBottomMargin(0.13);

  cvsSys->SetTitle("tan#beta="+tanb);
 
  output->cd();
  
  TDirectory* curDir = gDirectory;
//   TFile* f = new TFile("limits_binc_ht1000_met350-contours.root");
//   TFile* f = new TFile("limits_msugraNLO_multibtag_ht1000_met250_m12_0-550_HN_comb-contours.root");
  TFile* f = ContourFile;
  TGraph* ra4VieObs = (TGraph*)f->Get("gObs");
  TGraph* ra4VieExpM2 = (TGraph*)f->Get("gExpMinus2");
  TGraph* ra4VieExpM1 = (TGraph*)f->Get("gExpMinus1");
  TGraph* ra4VieExp = (TGraph*)f->Get("gExpMedian");
  TGraph* ra4VieExpP1 = (TGraph*)f->Get("gExpPlus1");
  TGraph* ra4VieExpP2 = (TGraph*)f->Get("gExpPlus2");
  TGraph* ra4VieExpArea(0);

  TGraph* ra4VieObsThM(0);
  TGraph* ra4VieExpThM(0);
  if ( ContourFileM ) {
    ra4VieObsThM = (TGraph*)ContourFileM->Get("gObs");
    ra4VieExpThM = (TGraph*)ContourFileM->Get("gExpMedian");
  }
  TGraph* ra4VieObsThP(0);
  TGraph* ra4VieExpThP(0);
  if ( ContourFileP ) {
    ra4VieObsThP = (TGraph*)ContourFileP->Get("gObs");
    ra4VieExpThP = (TGraph*)ContourFileP->Get("gExpMedian");
  }

  curDir->cd();


  double m0min = 0;
  double m0max=1600;
//   double m0max=1800;
  double xscale = m0max-m0min;
  if (tanBeta_ == 50) m0min=200;
  if (tanBeta_ == 40) {m0min=400;  m0max=2000;}
  xscale = (m0max-m0min)/xscale;
  TH2D* hist = new TH2D("h","h",100,m0min,m0max,100,120,700);
  hist->Draw();  
  hist->GetXaxis()->SetTitle("m_{0} (GeV/c^{2})");
  hist->GetYaxis()->SetTitle("m_{1/2} (GeV/c^{2})");
  hist->GetXaxis()->SetTitleOffset(.9);
  hist->GetXaxis()->SetTitleSize(0.06);
  hist->GetYaxis()->SetTitleOffset(1.0);
  hist->GetYaxis()->SetTitleSize(0.06);

  hist->GetXaxis()->SetNdivisions(506);
  //  if (tanBeta_ == 50)  hist->GetXaxis()->SetNdivisions(504);
  hist->GetYaxis()->SetNdivisions(506);

  int col[]={2,3,4};

  TSpline3 *sRA4_LP =0;
  TSpline3 *sRA1 = 0;
  TSpline3 *sRA2 = 0;
  TSpline3 *sRA4_old =0;
  TSpline3 *sRAZ =0;

  if (tanBeta_==10) {
    ra4VieObs->SetLineWidth(3);
    ra4VieObs->SetLineColor(2);
    ra4VieExp->SetLineWidth(3);
//     ra4VieExp->SetLineStyle(2);
    ra4VieExp->SetLineColor(4);
//     ra4VieObs->RemovePoint(0);
//     ra4VieObs->RemovePoint(0);
//     double x,y;
//     ra4VieObs->GetPoint(36,x,y);
//     std::cout << x << " " << y << std::endl;
//     ra4VieObs->RemovePoint(37);
//     ra4VieObs->RemovePoint(37);
//     ra4VieObs->RemovePoint(37);
    if ( ra4VieExpM1 && ra4VieExpP1 ) {
      ra4VieExpArea = new TGraph();
      int np(0);
      double* xExp = ra4VieExpM1->GetX();
      double* yExp = ra4VieExpM1->GetY();
      for ( int i=0; i<ra4VieExpM1->GetN(); ++i ) 
	ra4VieExpArea->SetPoint(np++,xExp[i],yExp[i]);
      xExp = ra4VieExpP1->GetX();
      yExp = ra4VieExpP1->GetY();
      for ( int i=ra4VieExpP1->GetN()-1; i>=0; --i ) 
	ra4VieExpArea->SetPoint(np++,xExp[i],yExp[i]);
      ra4VieExpArea->SetLineColor(7);
      ra4VieExpArea->SetFillColor(7);
      ra4VieExpArea->Draw("F");
      ra4VieExpM1->SetLineWidth(1);
      ra4VieExpM1->SetLineStyle(3);
      ra4VieExpM1->SetLineColor(4);
      ra4VieExpP1->SetLineWidth(1);
      ra4VieExpP1->SetLineStyle(3);
      ra4VieExpP1->SetLineColor(4);
      ra4VieExpM1->Draw();
      ra4VieExpP1->Draw();
    }
    if ( ra4VieObsThM && ra4VieObsThP ) {
      ra4VieObsThM->SetLineWidth(2);
      ra4VieObsThM->SetLineColor(2);
      ra4VieObsThM->SetLineStyle(2);
      ra4VieObsThM->Draw();
      ra4VieObsThP->SetLineWidth(2);
      ra4VieObsThP->SetLineColor(2);
      ra4VieObsThP->SetLineStyle(2);
      ra4VieObsThP->Draw();
      
      ra4VieExpThM->SetLineWidth(2);
      ra4VieExpThM->SetLineColor(4);
      ra4VieExpThM->SetLineStyle(2);
      ra4VieExpThM->Draw();
      ra4VieExpThP->SetLineWidth(2);
      ra4VieExpThP->SetLineColor(4);
      ra4VieExpThP->SetLineStyle(2);
      ra4VieExpThP->Draw();
      
    }
    ra4VieExp->Draw();
    ra4VieObs->Draw();
//     if ( ra4VieExpM2 && ra4VieExpP2 ) {
//       ra4VieExpM2->SetLineWidth(2);
//       ra4VieExpM2->SetLineStyle(3);
//       ra4VieExpM2->SetLineColor(4);
//       ra4VieExpP2->SetLineWidth(2);
//       ra4VieExpP2->SetLineStyle(3);
//       ra4VieExpP2->SetLineColor(4);
//       ra4VieExpM2->Draw();
//       ra4VieExpP2->Draw();
//     }
  }
  else if (tanBeta_==40 ) {

  }
  
  TLegend* myleg;

  float leg_x1=0.39+0.23;
  float leg_y1=0.65+0.05;
  float leg_x2= 0.55+0.25;
  float leg_y2= 0.84+0.05;

  if( plotLO_ ) {
    if ( ContourFileM && ContourFileP )
      myleg = new TLegend(0.3,0.55,0.6,0.7,NULL,"brNDC");
//       myleg = new TLegend(0.3,0.55,0.6,0.8,NULL,"brNDC");
    else
      myleg = new TLegend(0.3,0.65,0.6,0.7,NULL,"brNDC");
  }
  else if (tb40_plotExpected) myleg = new TLegend(0.25,0.76,0.44,0.91,NULL,"brNDC"); // copied from else block below
  else if (tanBeta_==40) myleg = new TLegend(leg_x1,leg_y1,leg_x2,leg_y2,NULL,"brNDC");
  else          myleg = new TLegend(0.25,0.76,0.44,0.91,NULL,"brNDC");


  myleg->SetFillColor(0); 
  myleg->SetShadowColor(0);
  myleg->SetTextSize(0.03);
  myleg->SetBorderSize(0);

  TLegendEntry *entry=0;

  if (tanBeta_ == 10 ) {
//     myleg->SetHeader("RA4Tmpl, (NLO, exp. unc.)");
    myleg->SetHeader("95% CL exclusion limits");
    myleg->AddEntry(ra4VieObs,"observed","l");
    myleg->AddEntry(ra4VieExp,"median expected","l");
    if ( ra4VieExpM1 && ra4VieExpP1 ) {
//       myleg->AddEntry(ra4VieExpP1,"exp #pm 1#sigma","l");
      myleg->AddEntry(ra4VieExpArea,"expected #pm 1#sigma exp.","f");
    }
    if ( ra4VieObsThM && ra4VieObsThP ) {
      myleg->AddEntry(ra4VieObsThM,"observed / sig.cont.","l");
      myleg->AddEntry(ra4VieExpThM,"expected / sig.cont.","l");
//       myleg->AddEntry(ra4VieObsThM,"observed #pm 1#sigma theor.","l");
//       myleg->AddEntry(ra4VieExpThM,"expected #pm 1#sigma theor.","l");
    }
    //     entry=myleg->AddEntry("RA1","2011 Limits","l");
    //     entry->SetLineColor(1);
    //     entry->SetLineStyle(1);
    //     entry->SetLineWidth(3);
    
    //     entry=myleg->AddEntry("sRA1","2010 Limits","l");
    //     entry->SetLineColor(1);
    //     entry->SetLineStyle(2);
    //     entry->SetLineWidth(3);
  }
  else if (tanBeta_==40) {

    //     entry=myleg->AddEntry("obs","Observed Limit","l");
    //     entry->SetLineColor(1);
    //     entry->SetLineStyle(1);
    //     entry->SetLineWidth(3);
    //     entry->SetTextColor(1);

    //     entry=myleg->AddEntry("exp","Expected Limit #pm 1#sigma","lf");
    //     entry->SetFillColor(kGray);
    //     entry->SetTextColor(1);
    //     entry->SetLineColor(1);
    //     entry->SetLineStyle(7);
    //     entry->SetLineWidth(3);
    //     entry->SetFillStyle(3002);


  }
  
  //constant squark and gluino mass contours
  if (tanBeta_==10) {
    for (int it=0;it<5;it++) {   
      lngl[it]->Draw("same");   
      lnsq[it]->Draw("same");
      sq_text[it]->Draw();
      gl_text[it]->Draw();
    }
  }
  else if (tanBeta_==40) {
    for (int it=2;it<9;it++) {  
      if(it<7){
	if(lngl_40[it]!=0)lngl_40[it]->Draw("samec");   
	if(gl_40_text[it]!=0)gl_40_text[it]->Draw();
      }
      if(lnsq_40[it]!=0)lnsq_40[it]->Draw("samec");
      if(it<6){
	if(sq_40_text[it]!=0)sq_40_text[it]->Draw();
      }
    }
  }

  if (tanBeta_==10) {
    //     SSdilep->Draw("samec");
    //     OSdilep->Draw("samec");
    //     Multilep->Draw("samec");
    //     RA1->Draw("samec");
    //     RA2->Draw("samec");
    //     MT2->Draw("samec");
    //     sRA4_LP->Draw("samec");
    // 	RAZ->Draw("samec");
    
    //     sRA1->Draw("same"); 
    //     sRA2->Draw("same"); 
    //     sRA4_old->Draw("samec");
    // 	sRAZ->Draw("samec");
    //     RA5_old->Draw("c same");
    //     RA6_old->Draw("c same");
  }
  else if (tanBeta_==40) {

    //     //expected curves and errors bands
    //     if ( tb40_plotExpected) {
    //       //not drawing the expected curves for better legibility
    // //       RA1_tb40_exp_p->Draw("samel");
    // //       RA1_tb40_exp_m->Draw("samel");
    // //       RA2b_1b_tight_exp_p->Draw("samel");
    // //       RA2b_1b_tight_exp_m->Draw("samel");
    // //keep the expected +/-1 sigma band
    //       RA1_tb40_exp_band->Draw("f") ;
    //       RA2b_1b_tight_exp_band->Draw("f") ;

    //       //important to draw lines after fill
    //       RA1_tb40_exp->Draw("samel");
    //       RA2b_1b_tight_exp->Draw("samel") ;

  }

  //     RA2b_1b_tight->Draw("samel");
  //     RA1_tb40->Draw("samel");

  // }
  
  TLegend* leg2=0;
  if (tanBeta_==10) {
    //     TLatex* RA1label = new TLatex(670,370.,"#alpha_{T}");
    //     RA1label->SetTextFont(42);
    //     RA1label->SetTextSize(0.05);
    //     RA1label->SetTextColor(kRed+2);
    //     RA1label->Draw("same");
    
    //     TLatex* RA2label = new TLatex(640,465.,"Jets+MHT");
    //     RA2label->SetTextFont(42);
    //     RA2label->SetTextSize(0.04);
    //     RA2label->SetTextColor(kBlue+2);
    //     RA2label->Draw("same");
	  
    //     TLatex* RAZlabel = new TLatex(740,415.,"Razor (0.8 fb^{-1})");
    //     RAZlabel->SetTextFont(42);
    //     RAZlabel->SetTextSize(0.04);
    //     RAZlabel->SetTextColor(kMagenta+1);
    //     RAZlabel->Draw("same");
    
    //     TLatex* RA5label = new TLatex(300,350.,"SS Dilepton");
    //     RA5label->SetTextFont(42);
    //     //RA5label->SetTextAngle(-10);
    //     RA5label->SetTextSize(0.04);
    //     RA5label->SetTextColor(kGreen+2);
    //     RA5label->Draw("same");
    
    //     //TLatex* RA6label = new TLatex(400,280.,"OS Dilepton");
    //     TLatex* RA6label = new TLatex(355,285.,"OS Dilepton");
    //     RA6label->SetTextFont(42);
    //     //RA6label->SetTextAngle(-15);
    //     RA6label->SetTextSize(0.04);
    //     RA6label->SetTextColor(kCyan+2);
    //     RA6label->Draw("same");

    //     TLatex* RA7label = new TLatex(338,215.,"Multi-Lepton");
    //     RA7label->SetTextFont(42);
    //     RA7label->SetTextSize(0.04);
    //     RA7label->SetTextColor(kYellow+2);
    //     RA7label->Draw("same");
    //     TLatex* RA7lumi = new TLatex(450,185.,"(2.1 fb^{-1})");
    //     RA7lumi->SetTextFont(42);
    //     RA7lumi->SetTextSize(0.04);
    //     RA7lumi->SetTextColor(kYellow+2);
    //     RA7lumi->Draw("same");

    
    //     TLatex* MT2label = new TLatex(400,440.,"MT2");
    //     MT2label->SetTextFont(42);
    //     MT2label->SetTextSize(0.04);
    //     MT2label->SetTextColor(kRed);
    //     MT2label->Draw("same");
    
    //     TLatex* RA4label = new TLatex(250,400.,"1 Lepton");
    //     RA4label->SetTextFont(42);
    //     RA4label->SetTextSize(0.04);
    //     RA4label->SetTextColor(kBlue);
    //     RA4label->Draw("same");
  }
  else if (tanBeta_==40  && !tb40_plotExpected) {
    //     int xposRA1 = 480;
    //     int yposRA1 = 510;

    //     int xposRA2b=450;
    //     int yposRA2b=275;

    //     TLatex* RA1label = new TLatex(xposRA1,yposRA1,"#alpha_{T}");
    //     RA1label->SetTextFont(42);
    //     RA1label->SetTextSize(0.05);
    //     RA1label->SetTextColor(kRed+2);
    //     RA1label->Draw("same");

    //     TLatex* RA2blabel = new TLatex(xposRA2b,yposRA2b,"Jets+MET+b");
    //     RA2blabel->SetTextFont(42);
    //     RA2blabel->SetTextSize(0.05);
    //     RA2blabel->SetTextColor(kBlue+1);
    //     RA2blabel->Draw("same");
    //   }
    //   else if (tanBeta_==40 && tb40_plotExpected) {

    //     leg2 = new TLegend(0.63,0.76,0.94,0.91,NULL,"brNDC");
    //     leg2->SetFillColor(0); 
    //     leg2->SetShadowColor(0);
    //     leg2->SetTextSize(0.04);
    //     leg2->SetBorderSize(0);
    
    //     entry=leg2->AddEntry("RA1_tb40","#alpha_{T}","l");
    //     entry->SetLineColor(kRed+2);
    //     entry->SetLineStyle(1);
    //     entry->SetLineWidth(3);
    //     entry->SetTextColor(kRed+2);

    //     entry=leg2->AddEntry("RA2b_1btight","Jets+MET+b","l");
    //     entry->SetLineColor(kBlue+1);
    //     entry->SetLineStyle(1);
    //     entry->SetLineWidth(3);
    //     entry->SetTextColor(kBlue+1);

  }

  //exclusion limits previous experiments
  if(tanBeta_ == 3){
    TEV_sn_d0_1->Draw("fsame");
    TEV_sn_d0_2->Draw("fsame");
  }
  if (tanBeta_==10)   LEP_ch->Draw("fsame");
  if (tanBeta_ != 50 && tanBeta_!=40) LEP_sl->Draw("fsame");

//   //remove CDF/D0 excluded regions
//   if (tanBeta_==10) {
//     TEV_sg_cdf->Draw("fsame");
//     TEV_sg_d0->Draw("same");  
//     TEV_sg_d0->Draw("fsame");
//   }

  //other labels
  Double_t xpos = 0;
  Double_t xposi = 0;
  Double_t ypos = 0;
  if(tanBeta_ == 50) xposi = 100;
  if(tanBeta_ == 50) xpos = 200;
  if(tanBeta_ == 50) ypos = -10;

  if(tanBeta_ == 40) xposi = 180+160;
  if(tanBeta_ == 40) xpos = 400;//240;
  if(tanBeta_ == 40) ypos = 100;

 
  //TLatex* lumilabel = new TLatex(750 +xposi + 100,767.-154,"#sqrt{s} = 7 TeV, #scale[0.65]{#int}Ldt = 0.98 fb^{-1}");
  TLatex* lumilabel = new TLatex(450*xscale+xpos,767.-154+100,"#sqrt{s} = 7 TeV,   Ldt 4.98 fb^{ -1}");
  TLatex* integral_symbol = new TLatex((577+100)*xscale+xpos,767.-145+100,"#int");

  lumilabel->SetTextSize(0.03);
  integral_symbol->SetTextSize(0.015);
  lumilabel->Draw("same");
  integral_symbol->Draw("same");

  TLatex* cmslabel = new TLatex(10.+xpos,767.-154+100,"CMS Preliminary");
  cmslabel->SetTextSize(0.03);
  cmslabel->Draw("same");

  TString text_tanBeta;
  TString a0str="0";
  if (tanBeta_==40) a0str = "-500 GeV";
  text_tanBeta =  "tan#beta = "+tanb+",  A_{0} = "+a0str+",  #mu > 0";
  int anotherOffset = (tb40_plotExpected && tanBeta_==40) ? -100 : 0;
//   TLatex* cmssmpars = new TLatex(/*530.+xpos,690.+ypos-130*/120+xpos,555+ypos+anotherOffset,text_tanBeta);
//   TLatex* cmssmpars = new TLatex(0.61,0.60,text_tanBeta);
  TLatex* cmssmpars = new TLatex(0.61,0.70,text_tanBeta);
  cmssmpars->SetNDC(1);

  cmssmpars->SetTextSize(0.04);
  cmssmpars->Draw("same");

  TLatex* lep_chargino = new TLatex(250,135,"LEP2 #tilde{#chi}_{1}^{#pm}");
  lep_chargino->SetTextSize(0.03);
  lep_chargino->SetTextFont(42);
  //  lep_chargino->Draw("same");

  TLatex* lep_slepton = new TLatex(26,190,"LEP2 #tilde{#font[12]{l}}^{#pm}");
  lep_slepton->SetTextSize(0.03);
  lep_slepton->SetTextAngle(-83);
  lep_slepton->SetTextFont(42);
  //  lep_slepton->Draw("same");



  //LM points
  TMarker* LM0 = new TMarker(200.,160.,20);
  TMarker* LM1 = new TMarker(60.,250.,20);
  TMarker* LM3 = new TMarker(330.,240.,20);
  TMarker* LM6 = new TMarker(80.,400.,20);
    
  LM0->SetMarkerSize(1.2);
  LM1->SetMarkerSize(1.2);
    
  TLatex* tLM0 = new TLatex(205.,160.," LM0");
  tLM0->SetTextSize(0.035);
    
  TLatex* tLM1 = new TLatex(80.,245.,"LM1");
  tLM1->SetTextSize(0.035);
  
  //TLatex* tLM3 = new TLatex(350.,235.,"LM3 (tan#beta=20)");
  TLatex* tLM3 = new TLatex(350.,235.,"LM3");
  tLM3->SetTextSize(0.035);
  
  TLatex* tLM6 = new TLatex(100.,395.,"LM6");
  tLM6->SetTextSize(0.035);
  
  //  if (tanBeta_ != 50){
  //  LM0->Draw("same");   
  //  tLM0->Draw("same");
  //  LM1->Draw("same");   
  //  tLM1->Draw("same");
  // }

  /*
    if (tanBeta_ == 10){ 
    LM1->Draw("same");
    tLM1->Draw("same");
    LM3->Draw("same");
    tLM3->Draw("same");
    LM6->Draw("same");
    tLM6->Draw("same");
    }
  */



  //stau=LSP contour
  if (tanBeta_==10) {
    stau->Draw("fsame");
//     NoEWSB->Draw("fsame");
    
    //legends
    legexp->Draw();
    legst->Draw();
    //legNoEWSB->Draw();
  }
  if (tanBeta_!=40 || tb40_plotExpected)  myleg->Draw();
  if (tanBeta_==40 && tb40_plotExpected) leg2->Draw();

  hist->Draw("sameaxis");
  cvsSys->RedrawAxis();
  cvsSys->Update();
  cvsSys->Write();
  
  if( plotLO_ ){
    cvsSys->SaveAs("ExclusionLimit_tanb"+tanb+"_LO.pdf");
    cvsSys->SaveAs("ExclusionLimit_tanb"+tanb+"_LO.png");
  }else{
    cvsSys->SaveAs("ExclusionLimit_tanb"+tanb+".eps");
    cvsSys->SaveAs("ExclusionLimit_tanb"+tanb+".ps");
    cvsSys->SaveAs("ExclusionLimit_tanb"+tanb+".pdf");
    cvsSys->SaveAs("ExclusionLimit_tanb"+tanb+".png");
  }
  
  output->Write();

  //output->Close();
  //delete output; 

}
コード例 #7
0
ファイル: deviations.C プロジェクト: CMSAachen3B/RWTH3b
// input: - Input file (result from TMVA)
//        - use of TMVA plotting TStyle
void deviations( TString fin = "TMVAReg.root", 
                 HistType htype = MVAType, Bool_t showTarget, Bool_t useTMVAStyle = kTRUE )
{
   // set style and remove existing canvas'
   TMVAGlob::Initialize( useTMVAStyle );
   gStyle->SetNumberContours(999);

   // switches
   const Bool_t Save_Images     = kTRUE;

   // checks if file with name "fin" is already open, and if not opens one
   TFile* file = TMVAGlob::OpenFile( fin );  

   // define Canvas layout here!
   Int_t xPad = 1; // no of plots in x
   Int_t yPad = 1; // no of plots in y
   Int_t noPad = xPad * yPad ; 
   const Int_t width = 650;   // size of canvas

   // this defines how many canvases we need
   TCanvas* c[100];

   // counter variables
   Int_t countCanvas = 0;

   // search for the right histograms in full list of keys
   //    TList* methods = new TMap();

   TIter next(file->GetListOfKeys());
   TKey *key(0);   
   while ((key = (TKey*)next())) {

      if (!TString(key->GetName()).BeginsWith("Method_")) continue;
      if (!gROOT->GetClass(key->GetClassName())->InheritsFrom("TDirectory")) continue;

      TString methodName;
      TMVAGlob::GetMethodName(methodName,key);
      cout << "--- Plotting deviation for method: " << methodName << endl;

      TObjString *mN  = new TObjString( methodName );
      TDirectory* mDir = (TDirectory*)key->ReadObj();

      TList* jobNames = new TList();

      TIter keyIt(mDir->GetListOfKeys());
      TKey *titkey;
      while ((titkey = (TKey*)keyIt())) {

         if (!gROOT->GetClass(titkey->GetClassName())->InheritsFrom("TDirectory")) continue;

         TDirectory *titDir = (TDirectory *)titkey->ReadObj();

         TObjString *jN = new TObjString( titDir->GetName() );
         if (!jobNames->Contains( jN )) jobNames->Add( jN );
         else delete jN;
	    
         TString methodTitle;
         TMVAGlob::GetMethodTitle(methodTitle,titDir);

         TString hname = "MVA_" + methodTitle;
         TIter   dirKeyIt( titDir->GetListOfKeys() );
         TKey*   dirKey;

         Int_t countPlots = 0;
         while ((dirKey = (TKey*)dirKeyIt())){
            if (dirKey->ReadObj()->InheritsFrom("TH2F")) {
               TString s(dirKey->ReadObj()->GetName());
               if (s.Contains("_reg_") && 
                   ( (showTarget && s.Contains("_tgt")) || (!showTarget && !s.Contains("_tgt")) ) && 
                   s.Contains( (htype == CompareType ? "train" : "test" ))) {
                  c[countCanvas] = new TCanvas( Form("canvas%d", countCanvas+1), 
                                                Form( "Regression output deviation versus %s for method: %s",
                                                      (showTarget ? "target" : "input variables"), methodName.Data() ),
                                                countCanvas*50+100, (countCanvas+1)*20, width, (Int_t)width*0.72 ); 
                  c[countCanvas]->SetRightMargin(0.10); // leave space for border
                  TH1* h = (TH1*)dirKey->ReadObj();
                  h->SetTitle( Form("Output deviation for method: %s (%s sample)", 
                                    hname.Data(), (htype == CompareType ? "training" : "test" )) );
                  //                                    methodName.Data(), (htype == CompareType ? "training" : "test" )) );
                  h->Draw("colz");
                  TLine* l = new TLine( h->GetXaxis()->GetXmin(), 0, h->GetXaxis()->GetXmax(), 0 );
                  l->SetLineStyle(2);
                  l->Draw();

                  // update and print
                  cout << "plotting logo" << endl;
                  TMVAGlob::plot_logo(1.058);
                  c[countCanvas]->Update();

                  TString fname = Form( "plots/deviation_%s_%s_%s_c%i", 
                                        methodName.Data(), 
                                        (showTarget ? "target" : "vars"),
                                        (htype == CompareType ? "training" : "test" ), countPlots );
                  TMVAGlob::imgconv( c[countCanvas], fname );

                  countPlots++;
                  countCanvas++;
               }
            }
         }         
      }
   }
}
コード例 #8
0
void LeptonPreselectionCMG( PreselType type, RooWorkspace * w ) {
	const Options & opt = Options::getInstance(); 
	if (type == ELE)
		cout << "Running Electron Preselection :" << endl;
	else if (type == MU)
		cout << "Running Muon Preselection :" << endl;
	else if (type == EMU)
		cout << "Running Electron-Muon Preselection() ..." << endl;
	else if (type == PHOT)
		cout << "Running Photon Preselection :" << endl;

	string systVar;
	try {
		systVar = opt.checkStringOption("SYSTEMATIC_VAR");
	} catch (const std::string & exc) {
		cout << exc << endl;
	}
	if (systVar == "NONE")
		systVar.clear();

#ifdef CMSSWENV
	JetCorrectionUncertainty jecUnc("Summer13_V4_MC_Uncertainty_AK5PFchs.txt");
#endif

	string inputDir = opt.checkStringOption("INPUT_DIR");
	string outputDir = opt.checkStringOption("OUTPUT_DIR");
	string sampleName = opt.checkStringOption("SAMPLE_NAME");
	string inputFile = inputDir + '/' + sampleName + ".root";
	cout << "\tInput file: " << inputFile << endl;

	bool isSignal = opt.checkBoolOption("SIGNAL");
	TGraph * higgsW = 0;
	TGraph * higgsI = 0;
	if (isSignal) {
		double higgsM = opt.checkDoubleOption("HIGGS_MASS");
		if (higgsM >= 400) {
			string dirName = "H" + double2string(higgsM);
			bool isVBF = opt.checkBoolOption("VBF");
			string lshapeHistName = "cps";
			string intHistName = "nominal";
			
			if (systVar == "LSHAPE_UP") {
				intHistName = "up";
			} else if (systVar == "LSHAPE_DOWN") {
				intHistName = "down";
			}

			if (isVBF) {
				TFile weightFile("VBF_LineShapes.root");
				higgsW = (TGraph *) ( (TDirectory *) weightFile.Get(dirName.c_str()))->Get( lshapeHistName.c_str() )->Clone();

			} else {
				TFile weightFile("GG_LineShapes.root");
				higgsW = (TGraph *) ( (TDirectory *) weightFile.Get(dirName.c_str()))->Get( lshapeHistName.c_str() )->Clone();
				TFile interfFile("newwgts_interf.root");
				higgsI = (TGraph *) ( (TDirectory *) interfFile.Get(dirName.c_str()))->Get( intHistName.c_str() )->Clone();
			}
		}
	}

	TFile * file = new TFile( inputFile.c_str() );
	if (!file->IsOpen())
		throw string("ERROR: Can't open the file: " + inputFile + "!");
	TDirectory * dir = (TDirectory *) file->Get("dataAnalyzer");
	TH1D * nEvHisto = (TH1D *) dir->Get("cutflow");
	TH1D * puHisto = (TH1D *) dir->Get("pileup");
	TTree * tree = ( TTree * ) dir->Get( "data" );
	Event ev( tree );
	const int * runP = ev.getSVA<int>("run"); 
	const int * lumiP = ev.getSVA<int>("lumi"); 
	const int * eventP = ev.getSVA<int>("event"); 
	const bool * trigBits = ev.getAVA<bool>("t_bits");
	const int * trigPres = ev.getAVA<int>("t_prescale");
	const float * metPtA = ev.getAVA<float>("met_pt");
	const float * metPhiA = ev.getAVA<float>("met_phi");
	const float * rhoP = ev.getSVA<float>("rho");
	const float * rho25P = ev.getSVA<float>("rho25");
	const int * nvtxP = ev.getSVA<int>("nvtx"); 
	const int * niP = ev.getSVA<int>("ngenITpu"); 
	
#ifdef PRINTEVENTS
	string eventFileName;
	if (type == ELE)
		eventFileName = "events_ele.txt";
	else if (type == MU)
		eventFileName = "events_mu.txt";
	else if (type == EMU)
		eventFileName = "events_emu.txt";

	EventPrinter evPrint(ev, type, eventFileName);
	evPrint.readInEvents("diff.txt");
	evPrint.printElectrons();
	evPrint.printMuons();
	evPrint.printZboson();
	evPrint.printJets();
	evPrint.printHeader();
#endif

	string outputFile = outputDir + '/' + sampleName;

	if (systVar.size())
		outputFile += ('_' + systVar);

	if (type == ELE)
		outputFile += "_elePresel.root";
	else if (type == MU)
		outputFile += "_muPresel.root";
	else if (type == EMU)
		outputFile += "_emuPresel.root";
	else if (type == PHOT)
		outputFile += "_phPresel.root";
	cout << "\tOutput file: " << outputFile << endl;

	TFile * out = new TFile( outputFile.c_str(), "recreate" );
	TH1D * outNEvHisto = new TH1D("nevt", "nevt", 1, 0, 1);
	outNEvHisto->SetBinContent(1, nEvHisto->GetBinContent(1));
	outNEvHisto->Write("nevt");

	TH1D * outPuHisto = new TH1D( *puHisto );
	outPuHisto->Write("pileup");

	std::vector< std::tuple<std::string, std::string> > eleVars;
	eleVars.push_back( std::make_tuple("ln_px", "F") );
	eleVars.push_back( std::make_tuple("ln_py", "F") );
	eleVars.push_back( std::make_tuple("ln_pz", "F") );
	eleVars.push_back( std::make_tuple("ln_en", "F") );
	eleVars.push_back( std::make_tuple("ln_idbits", "I") );
	eleVars.push_back( std::make_tuple("ln_d0", "F") );
	eleVars.push_back( std::make_tuple("ln_dZ", "F") );
	eleVars.push_back( std::make_tuple("ln_nhIso03", "F") );
	eleVars.push_back( std::make_tuple("ln_gIso03", "F") );
	eleVars.push_back( std::make_tuple("ln_chIso03", "F") );
	eleVars.push_back( std::make_tuple("ln_trkLostInnerHits", "F") );

	std::vector< std::tuple<std::string, std::string> > addEleVars;
	addEleVars.push_back( std::make_tuple("egn_sceta", "F") );
	addEleVars.push_back( std::make_tuple("egn_detain", "F") );
	addEleVars.push_back( std::make_tuple("egn_dphiin", "F") );
	addEleVars.push_back( std::make_tuple("egn_sihih", "F") );
	addEleVars.push_back( std::make_tuple("egn_hoe", "F") );
	addEleVars.push_back( std::make_tuple("egn_ooemoop", "F") );
	addEleVars.push_back( std::make_tuple("egn_isConv", "B") );

	std::vector< std::tuple<std::string, std::string> > muVars;
	muVars.push_back( std::make_tuple("ln_px", "F") );
	muVars.push_back( std::make_tuple("ln_py", "F") );
	muVars.push_back( std::make_tuple("ln_pz", "F") );
	muVars.push_back( std::make_tuple("ln_en", "F") );
	muVars.push_back( std::make_tuple("ln_idbits", "I") );
	muVars.push_back( std::make_tuple("ln_d0", "F") );
	muVars.push_back( std::make_tuple("ln_dZ", "F") );
	muVars.push_back( std::make_tuple("ln_nhIso04", "F") );
	muVars.push_back( std::make_tuple("ln_gIso04", "F") );
	muVars.push_back( std::make_tuple("ln_chIso04", "F") );
	muVars.push_back( std::make_tuple("ln_puchIso04", "F") );
	muVars.push_back( std::make_tuple("ln_trkchi2", "F") );
	muVars.push_back( std::make_tuple("ln_trkValidPixelHits", "F") );

	std::vector< std::tuple<std::string, std::string> > addMuVars;
	addMuVars.push_back( std::make_tuple("mn_trkLayersWithMeasurement", "F") );
	addMuVars.push_back( std::make_tuple("mn_pixelLayersWithMeasurement", "F") );
	addMuVars.push_back( std::make_tuple("mn_innerTrackChi2", "F") );
	addMuVars.push_back( std::make_tuple("mn_validMuonHits", "F") );
	addMuVars.push_back( std::make_tuple("mn_nMatchedStations", "F") );

	unsigned run;
	unsigned lumi;
	unsigned event;
	double pfmet;
	int nele;
	int nmu;
	int nsoftmu;
	double l1pt;
	double l1eta;
	double l1phi;
	double l2pt;
	double l2eta;
	double l2phi;
	double zmass;
	double zpt;
	double zeta;
	double mt;
	int nsoftjet;
	int nhardjet;
	double maxJetBTag;
	double minDeltaPhiJetMet;
	double detajj;
	double mjj;
	int nvtx;
	int ni;
	int category;
	double weight;
	double hmass;
	double hweight;

	TTree * smallTree = new TTree("HZZ2l2nuAnalysis", "HZZ2l2nu Analysis Tree");
	smallTree->Branch( "Run", &run, "Run/i" );
	smallTree->Branch( "Lumi", &lumi, "Lumi/i" );
	smallTree->Branch( "Event", &event, "Event/i" );
	smallTree->Branch( "PFMET", &pfmet, "PFMET/D" );
	smallTree->Branch( "NELE", &nele, "NELE/I" );
	smallTree->Branch( "NMU", &nmu, "NMU/I" );
	smallTree->Branch( "NSOFTMU", &nsoftmu, "NSOFTMU/I" );
	smallTree->Branch( "L1PT", &l1pt, "L1PT/D" );
	smallTree->Branch( "L1ETA", &l1eta, "L1ETA/D" );
	smallTree->Branch( "L1PHI", &l1phi, "L1PHI/D" );
	smallTree->Branch( "L2PT", &l2pt, "L2PT/D" );
	smallTree->Branch( "L2ETA", &l2eta, "L2ETA/D" );
	smallTree->Branch( "L2PHI", &l2phi, "L2PHI/D" );
	smallTree->Branch( "ZMASS", &zmass, "ZMASS/D" );
	smallTree->Branch( "ZPT", &zpt, "ZPT/D" );
	smallTree->Branch( "ZETA", &zeta, "ZETA/D" );
	smallTree->Branch( "MT", &mt, "MT/D" );
	smallTree->Branch( "NSOFTJET", &nsoftjet, "NSOFTJET/I" );
	smallTree->Branch( "NHARDJET", &nhardjet, "NHARDJET/I" );
	smallTree->Branch( "MAXJETBTAG", &maxJetBTag, "MAXJETBTAG/D" );
	smallTree->Branch( "MINDPJETMET", &minDeltaPhiJetMet, "MINDPJETMET/D" );
	smallTree->Branch( "DETAJJ", &detajj, "DETAJJ/D" );
	smallTree->Branch( "MJJ", &mjj, "MJJ/D" );
	smallTree->Branch( "NVTX", &nvtx, "NVTX/I" );
	smallTree->Branch( "nInter" , &ni, "nInter/I" );
	smallTree->Branch( "CATEGORY", &category, "CATEGORY/I" );
	smallTree->Branch( "Weight" , &weight, "Weight/D" );
	smallTree->Branch( "HMASS", &hmass, "HMASS/D" );
	smallTree->Branch( "HWEIGHT", &hweight, "HWEIGHT/D" );

	bool isData = opt.checkBoolOption("DATA");

	unsigned long nentries = tree->GetEntries();

	RooDataSet * events = nullptr;

	PhotonPrescale photonPrescales;

	vector<int> thresholds;
	if (type == PHOT) {
		if (w == nullptr)
			throw string("ERROR: No mass peak pdf!");
		RooRealVar * zmass = w->var("mass");
		zmass->setRange(76.0, 106.0);
		RooAbsPdf * pdf = w->pdf("massPDF");
		events = pdf->generate(*zmass, nentries);

		photonPrescales.addTrigger("HLT_Photon36_R9Id90_HE10_Iso40_EBOnly", 36, 3, 7);
		photonPrescales.addTrigger("HLT_Photon50_R9Id90_HE10_Iso40_EBOnly", 50, 5, 8);
		photonPrescales.addTrigger("HLT_Photon75_R9Id90_HE10_Iso40_EBOnly", 75, 7, 9);
		photonPrescales.addTrigger("HLT_Photon90_R9Id90_HE10_Iso40_EBOnly", 90, 10, 10);
	}

	TH1D ptSpectrum("ptSpectrum", "ptSpectrum", 200, 55, 755);
	ptSpectrum.Sumw2();

	unordered_set<EventAdr> eventsSet;
	for ( unsigned long iEvent = 0; iEvent < nentries; iEvent++ ) {
//		if (iEvent < 6060000)
//			continue;

		if ( iEvent % 10000 == 0) {
			cout << string(40, '\b');
			cout << setw(10) << iEvent << " / " << setw(10) << nentries << " done ..." << std::flush;
		}

		tree->GetEntry( iEvent );

		run = -999;
		lumi = -999;
		event = -999;
		pfmet = -999;
		nele = -999;
		nmu = -999;
		nsoftmu = -999;
		l1pt = -999;
		l1eta = -999;
		l1phi = -999;
		l2pt = -999;
		l2eta = -999;
		l2phi = -999;
		zmass = -999;
		zpt = -999;
		zeta = -999;
		mt = -999;
		nsoftjet = -999;
		nhardjet = -999;
		maxJetBTag = -999;
		minDeltaPhiJetMet = -999;
		detajj = -999;
		mjj = -999;
		nvtx = -999;
		ni = -999;
		weight = -999;
		category = -1;
		hmass = -999;
		hweight = -999;

		run = *runP;
		lumi = *lumiP;
		event = *eventP;

		EventAdr tmp(run, lumi, event);
		if (eventsSet.find( tmp ) != eventsSet.end()) {
			continue;
		}
		eventsSet.insert( tmp );

		if (type == ELE && isData) {
			if (trigBits[0] != 1 || trigPres[0] != 1)
				continue;
		}

		if (type == MU && isData) {
			if ( (trigBits[2] != 1 || trigPres[2] != 1)
				&& (trigBits[3] != 1 || trigPres[3] != 1)
				&& (trigBits[6] != 1 || trigPres[6] != 1)
			   )
				continue;
		}

		if (type == EMU && isData) {
			if ( (trigBits[4] != 1 || trigPres[4] != 1)
				&& (trigBits[5] != 1 || trigPres[5] != 1)
			   )
				continue;
		}

		vector<Electron> electrons = buildLeptonCollection<Electron, 11>(ev, eleVars, addEleVars);
		vector<Muon> muons = buildLeptonCollection<Muon, 13>(ev, muVars, addMuVars);

		float rho = *rhoP;
		float rho25 = *rho25P;

		vector<Electron> looseElectrons;
		vector<Electron> selectedElectrons;
		for (unsigned j = 0; j < electrons.size(); ++j) {
			try {
			TLorentzVector lv = electrons[j].lorentzVector();
			if (
					lv.Pt() > 10 &&
					fabs(lv.Eta()) < 2.5 &&
					!electrons[j].isInCrack() &&
					electrons[j].passesVetoID() &&
					electrons[j].isPFIsolatedLoose(rho25)
				) {
				looseElectrons.push_back(electrons[j]);
			}

			if (
					lv.Pt() > 20 &&
					fabs(lv.Eta()) < 2.5 &&
					!electrons[j].isInCrack() &&
					electrons[j].passesMediumID() &&
					electrons[j].isPFIsolatedMedium(rho25)
				) {
				selectedElectrons.push_back(electrons[j]);
			}
			} catch (const string & exc) {
				cout << exc << endl;
				cout << "run = " << run << endl;
				cout << "lumi = " << lumi << endl;
				cout << "event = " << event << endl;
			}
		}

		vector<Muon> looseMuons;
		vector<Muon> softMuons;
		vector<Muon> selectedMuons;
		for (unsigned j = 0; j < muons.size(); ++j) {
			TLorentzVector lv = muons[j].lorentzVector();
			if (
					lv.Pt() > 10 &&
					fabs(lv.Eta()) < 2.4 &&
					muons[j].isLooseMuon() &&
					muons[j].isPFIsolatedLoose()
				) {
				looseMuons.push_back(muons[j]);
			} else if (
					lv.Pt() > 3 &&
					fabs(lv.Eta()) < 2.4 &&
					muons[j].isSoftMuon()
				) {
				softMuons.push_back(muons[j]);
			}
			if (
					lv.Pt() > 20 &&
					fabs(lv.Eta()) < 2.4 &&
					muons[j].isTightMuon() &&
					muons[j].isPFIsolatedTight()
				) {
				selectedMuons.push_back(muons[j]);
			}
		}

		vector<Lepton> looseLeptons;
		for (unsigned i = 0; i < looseElectrons.size(); ++i)
			looseLeptons.push_back(looseElectrons[i]);
		for (unsigned i = 0; i < looseMuons.size(); ++i)
			looseLeptons.push_back(looseMuons[i]);
		for (unsigned i = 0; i < softMuons.size(); ++i)
			looseLeptons.push_back(softMuons[i]);

#ifdef PRINTEVENTS
		evPrint.setElectronCollection(selectedElectrons);
		evPrint.setMuonCollection(selectedMuons);
#endif

		vector<Photon> photons = selectPhotonsCMG( ev );
		vector<Photon> selectedPhotons;
		for (unsigned i = 0; i < photons.size(); ++i) {
			if (photons[i].isSelected(rho) && photons[i].lorentzVector().Pt() > 55)
				selectedPhotons.push_back( photons[i] );
		}

		if (type == PHOT) {
			vector<Electron> tmpElectrons;
			for (unsigned i = 0; i < selectedPhotons.size(); ++i) {
				TLorentzVector phVec = selectedPhotons[i].lorentzVector();
				for (unsigned j = 0; j < looseElectrons.size(); ++j) {
					TLorentzVector elVec = looseElectrons[j].lorentzVector();
					double dR = deltaR(phVec.Eta(), phVec.Phi(), elVec.Eta(), elVec.Phi());
					if ( dR > 0.05 )
						tmpElectrons.push_back( looseElectrons[j] );
				}
			}
			looseElectrons = tmpElectrons;
		}

		string leptonsType;
		Lepton * selectedLeptons[2] = {0};
		if (type == ELE) {
			if (selectedElectrons.size() < 2) {
				continue;
			} else {
				selectedLeptons[0] = &selectedElectrons[0];
				selectedLeptons[1] = &selectedElectrons[1];
			}
		} else if (type == MU) {
			if (selectedMuons.size() < 2) {
				continue;
			} else {
				selectedLeptons[0] = &selectedMuons[0];
				selectedLeptons[1] = &selectedMuons[1];
			}
		} else if (type == EMU) {
			if (selectedElectrons.size() < 1 || selectedMuons.size() < 1) {
				continue;
			} else {
				selectedLeptons[0] = &selectedElectrons[0];
				selectedLeptons[1] = &selectedMuons[0];
			}
		} else if (type == PHOT) {
			if (selectedPhotons.size() != 1) {
				continue;
			}
		}

		nele = looseElectrons.size();
		nmu = looseMuons.size();
		nsoftmu = softMuons.size();

		TLorentzVector Zcand;

		if (type == ELE || type == MU || type == EMU) {
			TLorentzVector lep1 = selectedLeptons[0]->lorentzVector();
			TLorentzVector lep2 = selectedLeptons[1]->lorentzVector();

			if (lep2.Pt() > lep1.Pt() && type != EMU) {
				TLorentzVector temp = lep1;
				lep1 = lep2;
				lep2 = temp;
			}

			l1pt = lep1.Pt();
			l1eta = lep1.Eta();
			l1phi = lep1.Phi();

			l2pt = lep2.Pt();
			l2eta = lep2.Eta();
			l2phi = lep2.Phi();

			Zcand = lep1 + lep2;
			zmass = Zcand.M();
		} else if (type == PHOT) {
			Zcand = selectedPhotons[0].lorentzVector();
			zmass = events->get(iEvent)->getRealValue("mass");
		}

		zpt = Zcand.Pt();
		zeta = Zcand.Eta();

		if (type == PHOT) {
			unsigned idx = photonPrescales.getIndex(zpt);
			if (trigBits[idx])
				weight = trigPres[idx];
			else
				continue;
			ptSpectrum.Fill(zpt, weight);
		}

		TLorentzVector met;
		met.SetPtEtaPhiM(metPtA[0], 0.0, metPhiA[0], 0.0);
		TLorentzVector clusteredFlux;

		unsigned mode = 0;
		if (systVar == "JES_UP")
			mode = 1;
		else if (systVar == "JES_DOWN")
			mode = 2;
		TLorentzVector jecCorr;

#ifdef CMSSWENV
		vector<Jet> jetsAll = selectJetsCMG( ev, looseLeptons, jecUnc, &jecCorr, mode );
#else
		vector<Jet> jetsAll = selectJetsCMG( ev, looseLeptons, &jecCorr, mode );
#endif

		met -= jecCorr;

		mode = 0;
		if (systVar == "JER_UP")
			mode = 1;
		else if (systVar == "JER_DOWN")
			mode = 2;
		TLorentzVector smearCorr = smearJets( jetsAll, mode );
		if (isData && smearCorr != TLorentzVector())
			throw std::string("Jet smearing corrections different from zero in DATA!");
		met -= smearCorr;

		vector<Jet> selectedJets;
		for (unsigned i = 0; i < jetsAll.size(); ++i) {
			if (
					jetsAll[i].lorentzVector().Pt() > 10
					&& fabs(jetsAll[i].lorentzVector().Eta()) < 4.7
					&& jetsAll[i].passesPUID() &&
					jetsAll[i].passesPFLooseID()
				)
				selectedJets.push_back( jetsAll[i] );
		}
		if (type == PHOT) {
			vector<Jet> tmpJets;
			for (unsigned i = 0; i < selectedPhotons.size(); ++i) {
				TLorentzVector phVec = selectedPhotons[i].lorentzVector();
				for (unsigned j = 0; j < selectedJets.size(); ++j) {
					TLorentzVector jVec = selectedJets[j].lorentzVector();
					double dR = deltaR(phVec.Eta(), phVec.Phi(), jVec.Eta(), jVec.Phi());
					if ( dR > 0.4 )
						tmpJets.push_back( selectedJets[j] );
				}
			}
			selectedJets = tmpJets;
		}

		if (systVar == "UMET_UP" || systVar == "UMET_DOWN") {
			for (unsigned i = 0; i < jetsAll.size(); ++i)
				clusteredFlux += jetsAll[i].lorentzVector();
			for (unsigned i = 0; i < looseElectrons.size(); ++i)
				clusteredFlux += looseElectrons[i].lorentzVector();
			for (unsigned i = 0; i < looseMuons.size(); ++i)
				clusteredFlux += looseMuons[i].lorentzVector();

			TLorentzVector unclusteredFlux = -(met + clusteredFlux);
			if (systVar == "UMET_UP")
				unclusteredFlux *= 1.1;
			else
				unclusteredFlux *= 0.9;
			met = -(clusteredFlux + unclusteredFlux);
		}

		if (systVar == "LES_UP" || systVar == "LES_DOWN") {
			TLorentzVector diff;
			double sign = 1.0;
			if (systVar == "LES_DOWN")
				sign = -1.0;
			for (unsigned i = 0; i < looseElectrons.size(); ++i) {
				TLorentzVector tempEle = looseElectrons[i].lorentzVector();
				if (looseElectrons[i].isEB())
					diff += sign * 0.02 * tempEle;
				else
					diff += sign * 0.05 * tempEle;
			}
			for (unsigned i = 0; i < looseMuons.size(); ++i)
				diff += sign * 0.01 * looseMuons[i].lorentzVector();

			met -= diff;
		}

		pfmet = met.Pt();

		double px = met.Px() + Zcand.Px();
		double py = met.Py() + Zcand.Py();
		double pt2 = px * px + py * py;
		double e = sqrt(zpt * zpt + zmass * zmass) + sqrt(pfmet * pfmet + zmass * zmass);
		double mt2 = e * e - pt2;
		mt = (mt2 > 0) ? sqrt(mt2) : 0;

		vector<Jet> hardjets;
		vector<Jet> softjets;
		maxJetBTag = -999;
		minDeltaPhiJetMet = 999;
		for ( unsigned j = 0; j < selectedJets.size(); ++j ) {
			TLorentzVector jet = selectedJets[j].lorentzVector();

			if ( jet.Pt() > 30 ) {
				hardjets.push_back( selectedJets[j] );
			}
			if ( jet.Pt() > 15 )
				softjets.push_back( selectedJets[j] );
		}
		nhardjet = hardjets.size();
		nsoftjet = softjets.size();
//		if ( type == PHOT && nsoftjet == 0 )
//			continue;

		if (nhardjet > 1) {
			sort(hardjets.begin(), hardjets.end(), [](const Jet & a, const Jet & b) {
					return a.lorentzVector().Pt() > b.lorentzVector().Pt();
				});
			TLorentzVector jet1 = hardjets[0].lorentzVector();
			TLorentzVector jet2 = hardjets[1].lorentzVector();
			const double maxEta = max( jet1.Eta(), jet2.Eta() );
			const double minEta = min( jet1.Eta(), jet2.Eta() );
			bool passCJV = true;
			for (unsigned j = 2; j < hardjets.size(); ++j) {
				double tmpEta = hardjets[j].lorentzVector().Eta();
				if ( tmpEta > minEta && tmpEta < maxEta )
					passCJV = false;
			}
			const double tmpDelEta = std::fabs(jet2.Eta() - jet1.Eta());
			TLorentzVector diJetSystem = jet1 + jet2;
			const double tmpMass = diJetSystem.M();
			if ( type == PHOT) {
				if (passCJV && tmpDelEta > 4.0 && tmpMass > 500 && zeta > minEta && maxEta > zeta) {
					detajj = tmpDelEta;
					mjj = tmpMass;
				}
			} else {
				if (passCJV && tmpDelEta > 4.0 && tmpMass > 500 && l1eta > minEta && l2eta > minEta && maxEta > l1eta && maxEta > l2eta) {
					detajj = tmpDelEta;
					mjj = tmpMass;
				}
			}
		}

		category = evCategory(nhardjet, nsoftjet, detajj, mjj, type == PHOT);

		minDeltaPhiJetMet = 10;
		for ( unsigned j = 0; j < hardjets.size(); ++j ) {
			TLorentzVector jet = hardjets[j].lorentzVector();
			if ( hardjets[j].getVarF("jn_jp") > maxJetBTag && fabs(jet.Eta()) < 2.5 )
				maxJetBTag = hardjets[j].getVarF("jn_jp");
			double tempDelPhiJetMet = deltaPhi(met.Phi(), jet.Phi());
			if ( tempDelPhiJetMet < minDeltaPhiJetMet )
				minDeltaPhiJetMet = tempDelPhiJetMet;
		}

		nvtx = *nvtxP;

		if (isData)
			ni = -1;
		else
			ni = *niP;

		if (isSignal) {
			const int nMC = ev.getSVV<int>("mcn");
			const int * mcID = ev.getAVA<int>("mc_id");
			int hIdx = 0;
			for (; hIdx < nMC; ++hIdx)
				if (fabs(mcID[hIdx]) == 25)
					break;
			if (hIdx == nMC)
				throw string("ERROR: Higgs not found in signal sample!");

			float Hpx = ev.getAVV<float>("mc_px", hIdx);
			float Hpy = ev.getAVV<float>("mc_py", hIdx);
			float Hpz = ev.getAVV<float>("mc_pz", hIdx);
			float Hen = ev.getAVV<float>("mc_en", hIdx);
			TLorentzVector higgs;
			higgs.SetPxPyPzE( Hpx, Hpy, Hpz, Hen );
			hmass = higgs.M();

			if (higgsW) {
				hweight = higgsW->Eval(hmass);
				if (higgsI)
					hweight *= higgsI->Eval(hmass);
			} else
				hweight = 1;
		}

		if ( opt.checkBoolOption("ADDITIONAL_LEPTON_VETO") && (type == ELE || type == MU || type == EMU) && ((nele + nmu + nsoftmu) > 2) )
			continue;
		if ( opt.checkBoolOption("ADDITIONAL_LEPTON_VETO") && (type == PHOT) && ((nele + nmu + nsoftmu) > 0) )
			continue;
		if ( opt.checkBoolOption("ZPT_CUT") && zpt < 55 )
			continue;
		// for different background estimation methods different window should be applied:
		// * sample for photons should have 76.0 < zmass < 106.0
		// * sample for non-resonant background should not have this cut applied
		if ( opt.checkBoolOption("TIGHT_ZMASS_CUT") && (type == ELE || type == MU) && (zmass < 76.0 || zmass > 106.0))
			continue;
		if ( opt.checkBoolOption("WIDE_ZMASS_CUT") && (type == ELE || type == MU) && (zmass < 76.0 || zmass > 106.0))
			continue;
		if ( opt.checkBoolOption("BTAG_CUT") && ( maxJetBTag > 0.264) )
			continue;
		if ( opt.checkBoolOption("DPHI_CUT") && ( minDeltaPhiJetMet < 0.5) )
			continue;


#ifdef PRINTEVENTS
		evPrint.setJetCollection(hardjets);
		evPrint.setMET(met);
		evPrint.setMT(mt);
		string channelType;
		if (type == ELE)
			channelType = "ee";
		else if (type == MU)
			channelType = "mumu";
		else if (type == EMU)
			channelType = "emu";
		if (category == 1)
			channelType += "eq0jets";
		else if (category == 2)
			channelType += "geq1jets";
		else
			channelType += "vbf";
		evPrint.setChannel(channelType);
		unsigned bits = 0;
		bits |= (0x7);
		bits |= ((zmass > 76.0 && zmass < 106.0) << 3);
		bits |= ((zpt > 55) << 4);
		bits |= (((nele + nmu + nsoftmu) == 2) << 5);
		bits |= ((maxJetBTag < 0.275) << 6);
		bits |= ((minDeltaPhiJetMet > 0.5) << 7);
		evPrint.setBits(bits);
		evPrint.print();
#endif
		
		smallTree->Fill();
	}
	cout << endl;
	
	TCanvas canv("canv", "canv", 800, 600);
	//effNum.Sumw2();
	//effDen.Sumw2();
	//effNum.Divide(&effDen);
	//effNum.Draw();
	canv.SetGridy();
	canv.SetGridx();
	//canv.SaveAs("triggEff.ps");
	//canv.Clear();
	ptSpectrum.SetMarkerStyle(20);
	ptSpectrum.SetMarkerSize(0.5);
	ptSpectrum.Draw("P0E");
	//ptSpectrum.Draw("COLZ");
	canv.SetLogy();
	canv.SaveAs("ptSpectrum.ps");

	delete file;
	smallTree->Write("", TObject::kOverwrite);
	delete smallTree;
	delete out;
}
コード例 #9
0
ファイル: ProofAux.C プロジェクト: gganis/proof
//_____________________________________________________________________________
Int_t ProofAux::GenerateTree(const char *fnt, Long64_t ent, TString &fn)
{
   // Generate the main tree for the 'friends' tutorial; the tree is called
   // 'Tmain', has 'ent' entries and is saved to file 'fnt'.
   // The full file path is returned in 'fn'.
   // Return 0 on success, -1 on error.

   Int_t rc = -1;

   // Check the filename
   fn = fnt;
   if (fn.IsNull()) {
      Error("GenerateTree", "file name undefined!");
      return rc;
   }
   TUrl uu(fn, kTRUE);
   if (!strcmp(uu.GetProtocol(), "file") && !fn.BeginsWith("/")) {
      // Local file with relative path: create under the data directory
      if (!gProofServ ||
          !(gProofServ->GetDataDir()) || strlen(gProofServ->GetDataDir()) <= 0) {
         Error("GenerateTree", "data directory undefined!");
         return rc;
      }
      // Insert data directory
      fn.Insert(0, TString::Format("%s/", gProofServ->GetDataDir()));
      // Make sure the directory exists
      TString dir = gSystem->DirName(fn);
      if (gSystem->AccessPathName(dir, kWritePermission)) {
         if (gSystem->mkdir(dir, kTRUE) != 0) {
            Error("GenerateTree", "problems creating directory %s to store the file", dir.Data());
            return rc;
         }
      }
   }

   // Create the file
   TDirectory* savedir = gDirectory;
   TFile *f = new TFile(fn, "RECREATE");
   if (!f || f->IsZombie()) {
      Error("GenerateTree", "problems opening file %s", fn.Data());
      return rc;
   }
   savedir->cd();
   rc = 0;

   // Create the tree
   TTree *T = new TTree("Tmain","Main tree for tutorial friends");
   T->SetDirectory(f);
   Int_t Run = 1;
   T->Branch("Run",&Run,"Run/I");
   Long64_t Event = 0;
   T->Branch("Event",&Event,"Event/L");
   Float_t x = 0., y = 0., z = 0.;
   T->Branch("x",&x,"x/F");
   T->Branch("y",&y,"y/F");
   T->Branch("z",&z,"z/F");
   TRandom r;
   for (Long64_t i = 0; i < ent; i++) {
      if (i > 0 && i%1000 == 0) Run++;
      Event = i;
      x = r.Gaus(10,1);
      y = r.Gaus(20,2);
      z = r.Landau(2,1);
      T->Fill();
   }
   T->Print();
   f->cd();
   T->Write();
   T->SetDirectory(0);
   f->Close();
   delete f;
   delete T;

   // Notify success
   Info("GenerateTree", "file '%s' successfully created", fn.Data());

   // Add to the list
   TString fds(fn);
   if (!strcmp(uu.GetProtocol(), "file")) {
      if (gSystem->Getenv("LOCALDATASERVER")) {
         if (strcmp(TUrl(gSystem->Getenv("LOCALDATASERVER"), kTRUE).GetProtocol(), "file"))
            fds.Insert(0, TString::Format("%s/", gSystem->Getenv("LOCALDATASERVER")));
      } else {
         fds.Insert(0, TString::Format("root://%s/", gSystem->HostName()));
      }
   }
   fMainList->Add(new TObjString(fds));

   // Done
   return rc;
}
コード例 #10
0
ファイル: PlotEC.C プロジェクト: cmenpgroup/jlab
//
// Plot_ECvsP - plot the EC/P vs P distributions with cuts
//
//                  fAna = output from eg2a DMS
//                  target = target name
//
void Plot_ECvsP(char *fAna="Ana.root", char *fitParams="ECvsP_Fit.dat", char *target)
{
    Int_t i, j;
    Int_t iSector;
    
    const Int_t NPARAM = 3;
    TF1 *fitMean[NSECTORS];
    TF1 *fitCut[NSECTORS];
    TH2D *h2D[NSECTORS];
    
    char funcName[50];
    
    Double_t a, b, c, d, f;
    Double_t parMean[5];
    Double_t parSigma[2];
    
    // open text file for fit parameters
    ifstream fin(fitParams);

    // data files contain the trees
    printf("Analyzing file %s\n",fAna);
    TFile *fm = new TFile(fAna,"READ");
    TDirectory *tmp = fm->GetDirectory("ElectronID");
    
    // Canvas to plot histogram
    TCanvas *c1 = new TCanvas("c1","c1",0,0,1200,800);
    c1->SetBorderMode(1);  //Bordermode (-1=down, 0 = no border, 1=up)
    c1->SetBorderSize(5);
    gStyle->SetOptStat(1111);
    c1->SetFillStyle(4000);
    c1->Divide(3,2);
    
    for(j=0; j<NSECTORS; j++){
        sprintf(hname,"ECtotP_VS_P_Sector%i",j+1);
        h2D[j] = (TH2D*)tmp->Get(hname);
        
        c1->cd(j+1);
        gPad->SetLeftMargin(Lmar);
        gPad->SetRightMargin(Rmar);
        gPad->SetFillColor(0);
        
        h2D[j]->GetXaxis()->CenterTitle();
        h2D[j]->GetYaxis()->CenterTitle();
        h2D[j]->GetYaxis()->SetTitleOffset(yoff);
        
        h2D[j]->SetAxisRange(0.0,3.0,"X");
        h2D[j]->Draw("colz");
        
        fin >> iSector >> a >> b >> c >> d >> f;
        parMean[0] = a;
        parMean[1] = b;
        parMean[2] = c;
        parMean[3] = d;
        parMean[4] = f;
        
        sprintf(funcName,"fitMean%i",j+1);
        fitMean[j] = new TF1(funcName,polFit,0.0,3.0,3);
        fitMean[j]->SetParameters(&parMean[0]);
        fitMean[j]->SetLineWidth(2);
        fitMean[j]->Draw("same");
        
        sprintf(funcName,"fitCut%i",j+1);
        fitCut[j] = new TF1(funcName,CutBelow,0.0,3.0,5);
        fitCut[j]->SetParameters(parMean);
        fitCut[j]->SetLineColor(4);
        fitCut[j]->SetLineWidth(2);
        fitCut[j]->Draw("same");
        
        sprintf(funcName,"fitCut%i",j+1);
        fitCut[j] = new TF1(funcName,CutAbove,0.0,3.0,5);
        fitCut[j]->SetParameters(parMean);
        fitCut[j]->SetLineColor(4);
        fitCut[j]->SetLineWidth(2);
        fitCut[j]->Draw("same");
    }
    sprintf(OutCan,"Plot_ECvsP_%s.gif",target);
    c1->Print(OutCan);
    sprintf(OutCan,"Plot_ECvsP_%s.eps",target);
    c1->Print(OutCan);
    
    fin.close();
}
コード例 #11
0
ファイル: makeVNDet.C プロジェクト: jrcastle/EbyEAnalysis
void makeVNDet(){

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

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

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

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

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

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

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

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

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

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

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

  //
  // MAIN
  //


  //-- Set up the analyzer objects
  fAna = new TFile("/rfs/jcastle/PbPb2015/PixelTracking_MB2/EbyETree_pixel_tight.root");

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

    } //-- End EP loop

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

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

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

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

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

      }
    }
  } //-- END TRIPLE LOOP

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

}
コード例 #12
0
ファイル: PlotEC.C プロジェクト: cmenpgroup/jlab
//
// Analyze_ECvsP - fit the EC/P vs P distributions
//
//                  fAna = output from eg2a DMS
//                  target = target name
//
void Analyze_ECvsP(char *fAna="Ana.root", char *target)
{
    Int_t i, j;
    
    const Int_t NPARAM = 3;
    TH1D *h1D[NSECTORS][NPARAM];
    TH2D *h2D[NSECTORS];
    
    char HistName2D[50];
    char strname[50];
    char *yname[NPARAM] = {"Amplitude","Mean","Sigma"};
    
    // open text file for the yields
    char OutFile[100];
    sprintf(OutFile,"ECvsP_Fit_%s.dat",target);
    ofstream fout(OutFile);
    
    TCanvas *can[NSECTORS]; // Canvas to plot histogram
    
    Double_t par[3]={1.0,1.0,1.0};
    TF1 *pol;
    TF1 *sig;
    
    // data files contain the trees
    printf("Analyzing file %s\n",fAna);
    TFile *fm = new TFile(fAna,"READ");
    TDirectory *tmp = fm->GetDirectory("ElectronID");
    
    for(j=0; j<NSECTORS; j++){
        sprintf(cname,"can%i",j+1);
        sprintf(cname,"Canvas, Sector %i",j+1);
        can[j] = new TCanvas(cname,ctitle,50*j,0,600,600);
        can[j]->SetBorderMode(1);  //Bordermode (-1=down, 0 = no border, 1=up)
        can[j]->SetBorderSize(5);
        gStyle->SetOptStat(1111);
        can[j]->SetFillStyle(4000);
        can[j]->Divide(2,2);
        
        sprintf(HistName2D,"ECtotP_VS_P_Sector%i",j+1);
        h2D[j] = (TH2D*)tmp->Get(HistName2D);

        can[j]->cd(1);
        gPad->SetLeftMargin(Lmar);
        gPad->SetRightMargin(Rmar);
        gPad->SetFillColor(0);

        h2D[j]->GetXaxis()->CenterTitle();
        h2D[j]->GetYaxis()->CenterTitle();
        h2D[j]->GetYaxis()->SetTitleOffset(yoff);
    
        h2D[j]->SetAxisRange(0.0,3.0,"X");
        h2D[j]->Draw("colz");
    
        h2D[j]->FitSlicesY(0,0,-1,20);
    
        fout<<j+1<<"\t";
        
        for(i=0; i<NPARAM; i++){
            can[j]->cd(i+2);
            gPad->SetLeftMargin(Lmar);
            gPad->SetRightMargin(Rmar);
            gPad->SetFillColor(0);

            sprintf(strname,"%s_%i",HistName2D,i);
            h1D[j][i] = (TH1D*)gDirectory->Get(strname);
            h1D[j][i]->GetXaxis()->CenterTitle();
            h1D[j][i]->GetYaxis()->CenterTitle();
            h1D[j][i]->GetYaxis()->SetTitle(yname[i]);
            h1D[j][i]->GetYaxis()->SetTitleOffset(yoff);
            h1D[j][i]->SetAxisRange(0.0,2.5,"X");
            if (i==0){
                h1D[j][i]->SetAxisRange(0.0,40.0,"Y");
            }
            if (i==1) {
                h1D[j][i]->SetAxisRange(0.15,0.35,"Y");
                pol = new TF1("pol","pol2",0.5,3.0);
                h1D[j][i]->Fit("pol","R");
                fout<<pol->GetParameter(0)<<"\t"<<pol->GetParameter(1)<<"\t"<<pol->GetParameter(2)<<"\t";
            }
            if (i==2) {
                par[0] = 10.0;
                par[1] = 0.1;
                par[2] = 0.1;
                h1D[j][i]->SetAxisRange(0.0,0.3,"Y");
                sig = new TF1("sig",SigmaFit,0.5,3.0,2);
                sig->SetParameters(par);
                h1D[j][i]->Fit("sig","R");
                fout<<sig->GetParameter(0)<<"\t"<<sig->GetParameter(1)<<endl;
            }
            h1D[j][i]->Draw();
        }
       	sprintf(OutCan,"Analyze_ECvsP_S%i_%s.gif",j+1,target);
        can[j]->Print(OutCan);
        sprintf(OutCan,"Analyze_ECvsP_S%i_%s.eps",j+1,target);
        can[j]->Print(OutCan);
    }
    fout.close(); // close the text file
}
コード例 #13
0
/*************************************************************************************
 * createMFOutfile: moves the MLB distributions into an output file for use in 
 *                  R. Nally's MassFit.C code.
 *  input:  the main() arguments array
 *  output: writes to an output file the histograms, in a MassFit.C-readable format 
 *
 *  Structure-wise: can be implemented into class easily.
 ***********************************/
void createMFOutfile(const char* argv[]) {
  TFile *f = new TFile(argv[2]);

  //create the output file we'd like to write histograms to
  TFile *output = new TFile(outfileName, "RECREATE");
  
  //get the filesystem information from the file
  f->cd();
  TList *alokDirs = (TList*) f->GetListOfKeys();

  //create a list of "All" histograms and initialize (TODO)
  TList *allHists = new TList;

  //loop through the directories in the input file
  for(int idir=0; alokDirs->At(idir-1) != alokDirs->Last(); idir++) {
    //if it's not mlb, we don't care
    if(!TString(alokDirs->At(idir)->GetName()).Contains("_Mlb")) continue;
    
    //get the file directory information, its histograms
    TDirectory *cDir  = (TDirectory*) f->Get(alokDirs->At(idir)->GetName());
    TList *alokHistos = (TList*)      cDir->GetListOfKeys();

    //loop through the histograms in the current directory 
    for(int ihisto=0; alokHistos->At(ihisto-1) != alokHistos->Last(); ihisto++) {
      // don't consider the graph objects
      if(TString(alokHistos->At(ihisto)->GetName()).Contains("Graph_")) continue; 

      // clone the histogram, give it a new name
      TString cloneName = formatName(alokHistos->At(ihisto)->GetName(),nominalWidth);
      TH1F *thisto = (TH1F*) cDir->Get(alokHistos->At(ihisto)->GetName());
      TH1F *tclone = (TH1F*) thisto->Clone(cloneName);

      // open the outfile and write the histo in
      output->cd();
      TList *outkeys = (TList*) output->GetListOfKeys();

      // if the histogram already exists, add thisto to the existing one
      // messy, but removes the need for magic
      for(int iout=0; outkeys->At(iout-1) != outkeys->Last(); iout++) {
        if(outkeys->At(iout)->GetName() == cloneName) {
          cout<<" - found another histogram in output with name "<<cloneName<<endl;
          TH1F *theHisto = (TH1F*) output->Get(cloneName);
          cout<<" - got the same histogram from the output file"<<endl;
          TH1F *tHclone  = (TH1F*) theHisto->Clone(cloneName);
          cout<<" - cloned the histogram"<<endl;

          cout<<" - adding in clone"<<endl;
          tclone->Add(tHclone);

          cout<<" - deleting the original histogram from the output file"<<endl;
          output->Delete(cloneName + TString(";1"));
          cout<<" - deleted thing from output file"<<endl;
          cout<<" - tclone looks like "<<tclone<<endl;
        }
      }
      cout<<" - writing the tclone to file"<<endl;
      tclone->Write();

      // reopen the input root file and clean up
      f->cd();
      delete thisto;
      delete tclone;
    }
  }

  f->Close();
  output->cd();
  output->Close();

  // if we want to interpolate, start making more histograms
  if(interpolate) {
    // Have to reopen the outfile because ROOT is odd
    TFile *output2 = new TFile(outfileName, "UPDATE");
    output2->cd();

    std::pair<double,TString> maxPair = *moreFiles.begin();
    double maxWidth = maxPair.first;

    // check that it makes sense to interpolate with our settings
    if(maxWidth <= nominalWidth) {
      cout<<"\n\nERROR: Max width is less than or equal to the nominal width! Exiting."<<endl;
      exit(EXIT_FAILURE);
    }

    // open the input file and loop through the relevant directories
    TFile *maxFile = new TFile(maxPair.second);
    for(int i=0; i<lepsSize; i++) {
      // change directory and get the name of the folder we want to access
      maxFile->cd();
      char a[128];
      sprintf(a, "mlbwa_%s_Mlb", leps[i]);
      TDirectory *tDir = (TDirectory*) maxFile->Get(a);
      TList *alok = tDir->GetListOfKeys();

      // get the maxWidth histogram in this folder, clone and rename it
      TString maxHName = alok->First()->GetName();
      TString maxCloneName = formatName(maxHName, maxWidth);
      TH1F *maxHisto = (TH1F*) tDir->Get(maxHName);
      TH1F *maxClone = (TH1F*) maxHisto->Clone(maxCloneName);

      // write this max histogram to the outfile
      output2->cd();
      maxClone->Write();

      // get the corresponding nominal histogram from the outfile
      TH1F *nomHisto = (TH1F*) output2->Get(formatName(maxHName,nominalWidth));

      TCanvas *c = new TCanvas("");
      nomHisto->Draw();
      c->SaveAs(formatName(maxHName,nominalWidth)+TString(".pdf"));


      // for each interpolation, create a morphed histogram and write to outfile
      for(int i=interpolations; i>0; i--) {
        double tWidth = nominalWidth + i*(maxWidth - nominalWidth)/(interpolations+1);
        TString interpName = formatName(maxHName, tWidth);
        TH1F *interpHisto = (TH1F*) th1fmorph(interpName, interpName,nomHisto,maxHisto,
                                               nominalWidth,maxWidth,tWidth,nomHisto->Integral(),1);
        interpHisto->Write();
      }
    }

    maxFile->cd();
    maxFile->Close();
    output2->cd();
    output2->Close();

    // Otherwise, we want to collect signal histograms of different weights
  } else {
    // Have to reopen the outfile because ROOT is odd
    TFile *output2 = new TFile(outfileName, "UPDATE");
    output2->cd();

    // Loop through the additional files
    for(std::vector<std::pair<double, TString> >::const_iterator pf=moreFiles.begin();
                                                                 pf!=moreFiles.end();
                                                                 pf++) {

        // This is the current file and width
        TFile *curFile = new TFile(pf->second, "READ");
        double curWid  = pf->first;

        // Loop through lepton final states
        for(int i=0; i<lepsSize; i++) {
            curFile->cd();

            // Get the desired directory
            char dirName[128];
            sprintf(dirName, "mlbwa_%s_Mlb", leps[i]);
            TDirectory *curDir = (TDirectory*) curFile->Get(dirName);

            // Get the names of the first histogram in the directory
            //     (we don't want more than one additional signal histo per extra file)
            // Format it with the usual method
            TString histName   = TString(curDir->GetListOfKeys()->First()->GetName());
            TString cloneName  = formatName(histName,curWid);
            
            // Get the mlb histo
            TH1D *curHisto = (TH1D*) curDir->Get(histName)->Clone(cloneName);

            // Write to the outfile
            output2->cd();
            curHisto->Write();
        }

        curFile->Close();
    }

    output2->cd();
    output2->Close();
  }

}
コード例 #14
0
/*************************************************************************************
 * getYields: Goes through each Counts histogram for every process and subprocess
 *            (i.e., EE & Drell-Yan, E & WJets, etc.) and properly adds the yields
 *            for data and MC. Reports ratios of Data:MC as well.
 *  input:  the main() arguments array
 *  output: writes to stdout the LaTeX-formatted table of yields (pipe the output to 
 *          save)
 ***********************************/
void getYields(const char* argv[]) { 
  //open mlbwidth output file
  TFile *f = new TFile(argv[2]);
  f->cd();

  //very inefficient, but for now it works
  //loop over all procs, leps and figure out the event counts
  for(int i=0; i<lepsSize; i++) {
    char a[128];
    sprintf(a, "mlbwa_%s_Count", leps[i]);
    TDirectory *tDir = (TDirectory*) f->Get(a);
    TList *alok = tDir->GetListOfKeys();

    for(int j=0; j<procsSize; j++) {
      for(int k=0; alok->At(k)->GetName() != alok->Last()->GetName(); k++) {
        if(TString(alok->At(k)->GetName()).Contains(TRegexp(procs[j]))) {
          char b[128];
          sprintf(b, "mlbwa_%s_Count/%s", leps[i], alok->At(k)->GetName());

          TH1F *h = (TH1F*) f->Get(b);
          eCounts[i][j] += h->GetSumOfWeights();
          eErrors[i][j] =  sqrt(pow(eErrors[i][j],2) + pow(h->GetBinError(2),2));

          delete h;
        }
      }
    }

    char d[128];
    sprintf(d, "mlbwa_%s_Count/%s", leps[i], alok->Last()->GetName());
    if(d == "") { exit(EXIT_FAILURE); }

    TH1F *tth = (TH1F*) f->Get(d);
    eCounts[i][procsSize] = tth->GetEntries();
    double integral = tth->GetSumOfWeights();
    eErrors[i][procsSize] = tth->GetBinError(2)*eCounts[i][procsSize]/integral;
    delete tth;
  }

  //Get a string to tell us how many columns we want (size leps + 1)
  char cols[] = "c";
  for(int i=0; i<lepsSize; i++) {
    strcat(cols, "c");
  }

  //print out LaTeX:
  //formatting
  cout<<"\\documentclass[12pt,a4paper,titlepage]{article}"<<endl;
  cout<<"\\usepackage[utf8]{inputenc}"<<endl;
  cout<<"\\usepackage{amsmath}"<<endl;
  cout<<"\\usepackage{amsfonts}"<<endl;
  cout<<"\\usepackage{amssymb}"<<endl;
  cout<<"\\usepackage{hyperref}\n\n"<<endl;
  cout<<"\\usepackage[margin=0.0025in]{geometry}"<<endl;
  cout<<"\\begin{document}"<<endl;
  cout<<"\\begin{tabular}{l|"<<cols<<"} \\\\"<<endl;

  //Print out the table header
  cout<<"Sample & ";
  for(int i=0; i<lepsLaTeXSize; i++) {
    cout<<lepsLaTeX[i]<<" & ";
  }
  cout<<"Sum \\\\ \\hline\\hline"<<endl;

  //Printing out the yields for each process
  for(int i=0; i<procsSize; i++) {
      cout<<yieldLaTeX[i]<<" & ";
    for(int j=0; j<lepsSize; j++) {
      cout<<GetLatex(j,i)<<" & ";
    }
    cout<<GetLatexSum(true,i)<<"\\\\"<<(i==procsSize-1 ? "\\hline" : "")<<endl;
  }
 
  //Print out the total MC yield
  cout<<"Total MC & ";
  for(int i=0; i<lepsSize; i++) {
    cout<<GetLatexSum(false,i)<<" & ";
  }
  cout<<GetLatexSum(false,-1)<<"\\\\"<<endl;

  //Print out the data yield
  cout<<"Data & ";
  for(int i=0; i<lepsSize; i++) {
    cout<<GetLatex(i,lepsSize+1)<<" & ";
  }
  cout<<GetLatexSum(true,lepsSize+1)<<"\\\\\\hline\\hline"<<endl;
  
  //Print out the data:MC ratio
  cout<<"Data/MC & ";
  for(int i=1; i<=procsSize;i++) {
    cout<<GetLatexRatio(i)<<(i==procsSize ? "" : " & ");
  }
  cout<<"\\\\"<<endl;

  //We did it! End the document
  cout<<"\\end{tabular}"<<endl;
  cout<<"\\end{document}"<<endl;
}
コード例 #15
0
ファイル: ProcessingTime.C プロジェクト: HEPcodes/Delphes3
void ProcessingTime(const char *inputFile)
{
  TChain *chain = new TChain("Delphes");
  chain->Add(inputFile);

  TH1F hist("time", "time", 50, 0, 0.01);
  Int_t i;

  TDirectory *currentDirectory = gDirectory;

  // Graphics style parameters to avoid grey background on figures
  gStyle->SetCanvasColor(kExRootBackgroundColor);
  gStyle->SetStatColor(kExRootBackgroundColor);
  //  gStyle->SetTitleColor(kExRootBackgroundColor);
  gStyle->SetPadColor(kExRootBackgroundColor);

  gStyle->SetPadTopMargin(0.10);
  gStyle->SetPadRightMargin(0.10);
  gStyle->SetPadBottomMargin(0.15);
  gStyle->SetPadLeftMargin(0.15);

  gStyle->SetStatFont(kExRootFont);
  gStyle->SetStatFontSize(kExRootFontSize);

  gStyle->SetTitleFont(kExRootFont, "");
  gStyle->SetTitleFont(kExRootFont, "X");
  gStyle->SetTitleFont(kExRootFont, "Y");
  gStyle->SetTitleFont(kExRootFont, "Z");
  gStyle->SetTitleSize(kExRootFontSize, "");
  gStyle->SetTitleSize(kExRootFontSize, "X");
  gStyle->SetTitleSize(kExRootFontSize, "Y");
  gStyle->SetTitleSize(kExRootFontSize, "Z");

  gStyle->SetLabelFont(kExRootFont, "X");
  gStyle->SetLabelFont(kExRootFont, "Y");
  gStyle->SetLabelFont(kExRootFont, "Z");
  gStyle->SetLabelSize(kExRootFontSize, "X");
  gStyle->SetLabelSize(kExRootFontSize, "Y");
  gStyle->SetLabelSize(kExRootFontSize, "Z");

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

  gStyle->SetTextFont(kExRootFont);
  gStyle->SetTextSize(kExRootFontSize);

  gStyle->SetOptStat(111110);
  // gStyle->SetOptFit(101);

  canvas = static_cast<TCanvas*>(gROOT->FindObject("c1"));
  if(canvas)
  {
    canvas->Clear();
    canvas->UseCurrentStyle();
    canvas->SetWindowSize(800, 650);
  }
  else
  {
    canvas = new TCanvas("c1", "c1", 800, 650);
  }
  canvas->SetGrid();
  canvas->SetHighLightColor(kExRootBackgroundColor);

  currentDirectory->cd();

  for(i = 0; i < 9; ++i)
  {
    chain->Draw("Event.ProcTime >> time", TString::Format("Jet_size == %d", i+2));
    gr.SetPoint(i, i+2, hist.GetMean()*1000);
    grerr.SetPoint(i, i+2, hist.GetMean()*1000);
    grerr.SetPointError(i, 0, hist.GetRMS()*1000);
  }

  grerr.GetXaxis()->SetLimits(1.0, 11.0);
  grerr.GetXaxis()->SetTitleOffset(1.5);
  grerr.GetYaxis()->SetTitleOffset(1.75);
  grerr.GetXaxis()->SetTitle("jet multiplicity");
  grerr.GetYaxis()->SetTitle("processing time per event, ms");
  gr.SetMarkerStyle(kFullCircle);
  gr.SetMarkerColor(kBlack);
  gr.SetMarkerSize(1);
  gr.SetLineColor(kBlack);
  gr.SetLineWidth(2);
  grerr.SetFillStyle(1001);
  grerr.SetFillColor(17);
  grerr.Draw("A3");
  gr.Draw("P");

  comment.SetTextSize(kExRootFontSize);
  comment.SetTextFont(kExRootFont);
  comment.SetTextAlign(22);
  comment.SetFillColor(kExRootBackgroundColor);
  comment.SetBorderSize(0);
  comment.AddText("ttbar + jets events");
  comment.Draw();
}
コード例 #16
0
ファイル: ProofAux.C プロジェクト: gganis/proof
//_____________________________________________________________________________
Int_t ProofAux::GenerateFriend(const char *fnt, const char *fnf)
{
   // Generate the friend tree for the main tree in the 'friends' tutorial fetched
   // from 'fnt'.
   // the tree is called 'Tfriend', has the same number of entries as the main
   // tree and is saved to file 'fnf'. If 'fnf' is not defined the filename is
   // derived from 'fnt' either replacing 'tree' with 'friend', or adding '_friend'
   // before the '.root' extension.
   // Return 0 on success, -1 on error.

   Int_t rc = -1;
   // Check the input filename
   TString fin(fnt);
   if (fin.IsNull()) {
      Error("GenerateFriend", "file name for the main tree undefined!");
      return rc;
   }
   // Make sure that the file can be read
   if (gSystem->AccessPathName(fin, kReadPermission)) {
      Error("GenerateFriend", "input file does not exist or cannot be read: %s", fin.Data());
      return rc;
   }

   // File handlers
   Bool_t sameFile = kTRUE;
   const char *openMain = "UPDATE";

   // The output filename
   TString fout(fnf);
   if (!fout.IsNull()) {
      sameFile = kFALSE;
      openMain = "READ";
      // Make sure the directory exists
      TString dir = gSystem->DirName(fout);
      if (gSystem->AccessPathName(dir, kWritePermission)) {
         if (gSystem->mkdir(dir, kTRUE) != 0) {
            Error("GenerateFriend", "problems creating directory %s to store the file", dir.Data());
            return rc;
         }
      }
   } else {
      // We set the same name
      fout = fin;
   }

   // Get main tree
   TFile *fi = TFile::Open(fin, openMain);
   if (!fi || fi->IsZombie()) {
      Error("GenerateFriend", "problems opening input file %s", fin.Data());
      return rc;
   }
   TTree *Tin = (TTree *) fi->Get("Tmain");
   if (!Tin) {
      Error("GenerateFriend", "problems getting tree 'Tmain' from file %s", fin.Data());
      delete fi;
      return rc;
   }
   // Set branches
   Float_t x, y, z;
   Tin->SetBranchAddress("x", &x);
   Tin->SetBranchAddress("y", &y);
   Tin->SetBranchAddress("z", &z);
   TBranch *b_x = Tin->GetBranch("x");
   TBranch *b_y = Tin->GetBranch("y");
   TBranch *b_z = Tin->GetBranch("z");

   TDirectory* savedir = gDirectory;
   // Create output file
   TFile *fo = 0;
   if (!sameFile) {
      fo = new TFile(fout, "RECREATE");
      if (!fo || fo->IsZombie()) {
         Error("GenerateFriend", "problems opening file %s", fout.Data());
         delete fi;
         return rc;
      }
      savedir->cd();
   } else {
      // Same file
      fo = fi;
   }
   rc = 0;

   // Create the tree
   TTree *Tfrnd = new TTree("Tfrnd", "Friend tree for tutorial 'friends'");
   Tfrnd->SetDirectory(fo);
   Float_t r = 0;
   Tfrnd->Branch("r",&r,"r/F");
   Long64_t ent = Tin->GetEntries();
   for (Long64_t i = 0; i < ent; i++) {
      b_x->GetEntry(i);
      b_y->GetEntry(i);
      b_z->GetEntry(i);
      r = TMath::Sqrt(x*x + y*y + z*z);
      Tfrnd->Fill();
   }
   if (!sameFile) {
      fi->Close();
      delete fi;
   }
   Tfrnd->Print();
   fo->cd();
   Tfrnd->Write();
   Tfrnd->SetDirectory(0);
   fo->Close();
   delete fo;
   delete Tfrnd;

   // Notify success
   Info("GenerateFriend", "friend file '%s' successfully created", fout.Data());

   // Add to the list
   TUrl uu(fout);
   if (!strcmp(uu.GetProtocol(), "file")) {
      if (gSystem->Getenv("LOCALDATASERVER")) {
         if (strcmp(TUrl(gSystem->Getenv("LOCALDATASERVER"), kTRUE).GetProtocol(), "file"))
            fout.Insert(0, TString::Format("%s/", gSystem->Getenv("LOCALDATASERVER")));
      } else {
         fout.Insert(0, TString::Format("root://%s/", gSystem->HostName()));
      }
   }
   fFriendList->Add(new TObjString(fout));

   // Done
   return rc;
}
コード例 #17
0
ファイル: makeVNDet.C プロジェクト: jrcastle/EbyEAnalysis
void makeVNDet(){

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

  const double ptMin = 0.3;
  const double ptMax = 3.00;
  const double etaMax = 1.0;

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

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

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

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

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

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

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

  int Nevents[NCENT];
  int NFails[NCENT];

  //
  // MAIN
  //


  //-- Set up the analyzer objects
  fAna = new TFile("/rfs/jcastle/PbPb2015/PixelTracking_MB2/EbyETree_EPOS_LHC_RECO_SMEAR5.root");

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

  //-- Setup the output objects
  fOut     = new TFile( Form("V%iDet.root", norder_), "recreate" );
  SubEvt_0 = fOut->mkdir("SubEvt_0");
  SubEvt_1 = fOut->mkdir("SubEvt_1");
  FullEvt  = fOut->mkdir("FullEvt");
    
  SubEvt_0->cd();
  hVNDetX_0    = new TH1D( "hVNDetX_0",    "hVNDetX_0",    NCENT, centbinsDefault);
  hVNDetX_0->GetXaxis()->SetTitle("Centrality %");
    
  hVNDetY_0    = new TH1D( "hVNDetY_0",    "hVNDetY_0",    NCENT, centbinsDefault);
  hVNDetY_0->GetXaxis()->SetTitle("Centrality %");
    
  SubEvt_1->cd();
  hVNDetX_1    = new TH1D( "hVNDetX_1",    "hVNDetX_1",    NCENT, centbinsDefault);
  hVNDetX_1->GetXaxis()->SetTitle("Centrality %");
    
  hVNDetY_1    = new TH1D( "hVNDetY_1",    "hVNDetY_1",    NCENT, centbinsDefault);
  hVNDetY_1->GetXaxis()->SetTitle("Centrality %");
  
  FullEvt->cd();
  hVNDetX_full = new TH1D( "hVNDetX_full", "hVNDetX_full", NCENT, centbinsDefault);
  hVNDetX_full->GetXaxis()->SetTitle("Centrality %");
    
  hVNDetY_full = new TH1D( "hVNDetY_full", "hVNDetY_full", NCENT, centbinsDefault);
  hVNDetY_full->GetXaxis()->SetTitle("Centrality %");
    
  //-- initialize all variables
  for(int icent = 0; icent<NCENT; icent++){

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

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

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

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

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

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

    //-- Begin analyzer histogram loops
    for(int ipt = ptBinMin; ipt <= ptBinMax; ipt++){
      for(int ieta = etaBinMin; ieta <= etaBinMax; ieta++){
	  
	double pt  = sumw->GetXaxis()->GetBinCenter(ipt+1);
        double eta = sumw->GetYaxis()->GetBinCenter(ieta+1);
        if( pt < ptMin || pt > ptMax ) continue;
        if( fabs( eta ) > etaMax )     continue;

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

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

  //-- Average VNDet over all events for each centrality, EP and, qn bin
  for(int icent = 0; icent < NCENT; icent++){
  
    double  Neffective = (double) Nevents[icent] - (double) NFails[icent];
    if( Neffective == 0 ) continue;
    
    VNDetX_0[icent]    /= Neffective;
    VNDetY_0[icent]    /= Neffective;
    VNDetX_1[icent]    /= Neffective;
    VNDetY_1[icent]    /= Neffective;
    VNDetX_full[icent] /= Neffective;
    VNDetY_full[icent] /= Neffective;

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

  }

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

}
コード例 #18
0
void HHbbbbAnalyzerBase(int wM, string st,string st2,double Xsec=1,int SignalBkgNum=0){
	
	//for (int massP=0;massP<1;massP++){
		
		
		
	    
		
		int nPass[10]={0};
		int total=0;
		TH1D* th[30];
		
			th[0]=new TH1D("deltaEta","deltaEta",30,0,3);
			th[1]=new TH1D("Mjj","Mjj",2000,400,4000);
			th[2]=new TH1D("SDMass1","SDMass1",200,0,200);
			th[3]=new TH1D("SDMass2","SDMass2",200,0,200);
			th[4]=new TH1D("PRMass1","PRMass1",200,0,200);
			th[5]=new TH1D("PRMass2","PRMass2",200,0,200);
			th[6]=new TH1D("deltaR1","deltaR1",20,0,1);
			th[7]=new TH1D("deltaR2","deltaR2",20,0,1);
			th[8]=new TH1D("CSV1","CSV1",20,0,1);
			th[9]=new TH1D("CSV2","CSV2",20,0,1);
			th[10]=new TH1D("CSVSum","CSVSum",20,0,2);
			th[11]=new TH1D("CSVMax","CSVMax",20,0,1);
			th[12]=new TH1D("CSVMin","CSVMin",20,0,1);
			th[13]=new TH1D("tau21_1","tau21_1",20,0,1);
			th[14]=new TH1D("tau21_2","tau21_2",20,0,1);
			th[15]=new TH1D("jetPt1","jetPt1",1500,0,1500);
			th[16]=new TH1D("jetPt2","jetPt2",1500,0,1500);
			th[17]=new TH1D("PRMassC1","PRMassC1",600,0,600);
			th[18]=new TH1D("PRMassC2","PRMassC2",600,0,600);
			
			th[19]=new TH1D("FATjetPRmassL2L3Corr","FATjetPRmassL2L3Corr",600,0,600);
			th[20]=new TH1D("FATjetPRmassL2L3Corr_2","FATjetPRmassL2L3Corr_2",600,0,600);
			th[21]=new TH1D("FATjetPRmassL2L3CorrC","FATjetPRmassL2L3CorrC",600,0,600);
			th[22]=new TH1D("FATjetPRmassL2L3CorrC_2","FATjetPRmassL2L3CorrC_2",600,0,600);
			
			th[23]=new TH1D("MjjC","MjjC",2000,400,4000);
			th[24]=new TH1D("Mbb1","Mbb1",600,0,600);
			th[25]=new TH1D("Mbb2","Mbb2",600,0,600);
			th[26]=new TH1D("MbbC1","MbbC1",600,0,600);
			th[27]=new TH1D("MbbC2","MbbC2",600,0,600);
			
			TH1D* cs1=new TH1D("case1","case1",2000,400,6000);
			TH1D* cs2=new TH1D("case2","case2",2000,400,6000);
			TH1D* cs3=new TH1D("case3","case3",2000,400,6000);
			TH1D* cs4=new TH1D("case4","case4",2000,400,6000);
			TH1D* cs5=new TH1D("case5","case5",2000,400,6000);
			TH1D* csS=new TH1D("caseS","caseS",2000,400,6000);
		
			TH2F* th2f=new TH2F("2d","2d",600,0,600,600,0,600);
		for (int w=1;w<wM;w++){
			//cout<<Form("%s%d.root",st.data(),w)<<endl;
		//if(SignalBkgNum==1)f = TFile::Open(Form("%s",st.data()));
		//else 
			TFile *f;
			f = TFile::Open(Form("%s%d.root",st.data(),w));
		if (!f || !f->IsOpen())continue;
		TDirectory * dir;
		//if(SignalBkgNum==1)dir = (TDirectory*)f->Get(Form("%s:/tree",st.data()));
		//else 
			dir = (TDirectory*)f->Get(Form("%s%d.root:/tree",st.data(),w));
		
		cout<<w<<endl;
		
		TTree *tree;
		dir->GetObject("treeMaker",tree);
		
		TreeReader data(tree);
		
		total+=data.GetEntriesFast();
		
		
		
			
			

		
		for(Long64_t jEntry=0; jEntry<data.GetEntriesFast() ;jEntry++){
			data.GetEntry(jEntry);
			
			Int_t nJet         = data.GetInt("FATnJet");
			TClonesArray* FATjetP4 = (TClonesArray*) data.GetPtrTObject("FATjetP4");
			float*   FATjetPRmass= data.GetPtrFloat("FATjetPRmass");  
			float*   FATjetSDmass= data.GetPtrFloat("FATjetSDmass");
			float*  FATjetCISVV2 = data.GetPtrFloat("FATjetCISVV2"); 
			float* FATjetTau1=data.GetPtrFloat("FATjetTau1");
		    float* FATjetTau2=data.GetPtrFloat("FATjetTau2");
			Int_t* FATnSubSDJet=data.GetPtrInt("FATnSubSDJet");
			vector<float>   *FATsubjetSDCSV = data.GetPtrVectorFloat("FATsubjetSDCSV");
		    vector<float>   *FATsubjetSDPx =  data.GetPtrVectorFloat("FATsubjetSDPx");
		    vector<float>   *FATsubjetSDPy =  data.GetPtrVectorFloat("FATsubjetSDPy");
		    vector<float>   *FATsubjetSDPz =  data.GetPtrVectorFloat("FATsubjetSDPz");
			Float_t*  jetPRmassL2L3Corr = data.GetPtrFloat("FATjetPRmassL2L3Corr");
			
			string fixName ="";if(SignalBkgNum==1)fixName="";
			
		    vector<float>   *FATsubjetSDE =  data.GetPtrVectorFloat(Form("FATsubjetSD%sE",fixName.data()));
			
			if(nJet<1)continue;
			
			vector<int> FatjetPreSelection;
			for(int i=0;i<nJet;i++){
				TLorentzVector* thisHiggs = (TLorentzVector*)FATjetP4->At(i);
				if(thisHiggs->Pt()<200)continue;
				if(fabs(thisHiggs->Eta())>2.4)continue;
				FatjetPreSelection.push_back(i);
			}
			if(FatjetPreSelection.size()<2)continue;
			
			//TH1D* th1=new TH1D("","",,0,);
			
			TLorentzVector* thisHiggs = (TLorentzVector*)FATjetP4->At(FatjetPreSelection[0]);
			TLorentzVector* thatHiggs = (TLorentzVector*)FATjetP4->At(FatjetPreSelection[1]);
			TLorentzVector mjj=*thisHiggs+*thatHiggs;
			csS->Fill(mjj.M()+250-thisHiggs->M()-thatHiggs->M());
			th[24]->Fill(thisHiggs->M());
			th[25]->Fill(thatHiggs->M());
			
			th[0]->Fill(fabs(thisHiggs->Eta()-thatHiggs->Eta()));
			th[1]->Fill(mjj.M());
			th[2]->Fill(FATjetSDmass[FatjetPreSelection[0]]);
			th[3]->Fill(FATjetSDmass[FatjetPreSelection[1]]);
			th[4]->Fill(FATjetPRmass[FatjetPreSelection[0]]);
			th[5]->Fill(FATjetPRmass[FatjetPreSelection[1]]);
			
			TLorentzVector  FATsubjet_1,FATsubjet_2,FATsubjet_3,FATsubjet_4;;
			FATsubjet_1.SetPxPyPzE(FATsubjetSDPx[FatjetPreSelection[0]][0],FATsubjetSDPy[FatjetPreSelection[0]][0],FATsubjetSDPz[FatjetPreSelection[0]][0],FATsubjetSDE[FatjetPreSelection[0]][0]);
			FATsubjet_2.SetPxPyPzE(FATsubjetSDPx[FatjetPreSelection[0]][1],FATsubjetSDPy[FatjetPreSelection[0]][1],FATsubjetSDPz[FatjetPreSelection[0]][1],FATsubjetSDE[FatjetPreSelection[0]][1]);
			FATsubjet_3.SetPxPyPzE(FATsubjetSDPx[FatjetPreSelection[1]][0],FATsubjetSDPy[FatjetPreSelection[1]][0],FATsubjetSDPz[FatjetPreSelection[1]][0],FATsubjetSDE[FatjetPreSelection[1]][0]);
			FATsubjet_4.SetPxPyPzE(FATsubjetSDPx[FatjetPreSelection[1]][1],FATsubjetSDPy[FatjetPreSelection[1]][1],FATsubjetSDPz[FatjetPreSelection[1]][1],FATsubjetSDE[FatjetPreSelection[1]][1]);
				
				
			th[6]->Fill(FATsubjet_1.DeltaR(FATsubjet_2));
			th[7]->Fill(FATsubjet_3.DeltaR(FATsubjet_4));
			
			
			th[8]->Fill(FATjetCISVV2[FatjetPreSelection[0]]);
			th[9]->Fill(FATjetCISVV2[FatjetPreSelection[1]]);
			
			th[10]->Fill(FATjetCISVV2[FatjetPreSelection[0]]+FATjetCISVV2[FatjetPreSelection[1]]);
			double temp=FATjetCISVV2[FatjetPreSelection[0]]>FATjetCISVV2[FatjetPreSelection[1]]?FATjetCISVV2[FatjetPreSelection[0]]:FATjetCISVV2[FatjetPreSelection[1]];
			th[11]->Fill(temp);
			temp=FATjetCISVV2[FatjetPreSelection[0]]<FATjetCISVV2[FatjetPreSelection[1]]?FATjetCISVV2[FatjetPreSelection[0]]:FATjetCISVV2[FatjetPreSelection[1]];
			th[12]->Fill(temp);
			
			
			
			th[13]->Fill(FATjetTau2[FatjetPreSelection[0]]/FATjetTau1[FatjetPreSelection[0]]);
			th[14]->Fill(FATjetTau2[FatjetPreSelection[1]]/FATjetTau1[FatjetPreSelection[1]]);
			
			th[15]->Fill(thisHiggs->Pt());
			//cout<<thisHiggs->Pt()<<endl;
			th[16]->Fill(thatHiggs->Pt());
			

			vector<int> FatjetPreSelection1i,FatjetPreSelection1j;
			for(unsigned int i=0;i<FatjetPreSelection.size();i++){
				TLorentzVector* thisHiggs = (TLorentzVector*)FATjetP4->At(FatjetPreSelection[i]);
				for(unsigned int j=i+1;j<FatjetPreSelection.size();j++){
					TLorentzVector* thatHiggs = (TLorentzVector*)FATjetP4->At(FatjetPreSelection[j]);
				    if(fabs(thisHiggs->Eta()-thatHiggs->Eta())<1.3){
						FatjetPreSelection1i.push_back(FatjetPreSelection[i]);
						FatjetPreSelection1j.push_back(FatjetPreSelection[j]);
					}
				}
				//if(isDeltaEta13)break;
			}
			if(FatjetPreSelection1i.size()<1)continue;
	
			nPass[0]++;
			
			vector<int> FatjetPreSelection2i,FatjetPreSelection2j;
			for(unsigned int i=0;i<FatjetPreSelection1i.size();i++){
				TLorentzVector* thisHiggs = (TLorentzVector*)FATjetP4->At(FatjetPreSelection1i[i]);
				TLorentzVector* thatHiggs = (TLorentzVector*)FATjetP4->At(FatjetPreSelection1j[i]);
				TLorentzVector mjj=*thisHiggs+*thatHiggs;
				//cout<<mjj.M()<<endl;
				if(mjj.M()>1000){
					//cout<<"y"<<endl;
					FatjetPreSelection2i.push_back(FatjetPreSelection1i[i]);
				    FatjetPreSelection2j.push_back(FatjetPreSelection1j[i]);
					
				}
				
				
			}
			if(FatjetPreSelection2i.size()<1)continue;
			nPass[1]++;
			
			vector<int> FatjetPreSelection3i,FatjetPreSelection3j;
			for(unsigned int i=0;i<FatjetPreSelection2i.size();i++){
				
				th[19]->Fill(jetPRmassL2L3Corr[FatjetPreSelection2i[i]]);
				th[20]->Fill(jetPRmassL2L3Corr[FatjetPreSelection2j[i]]);
				th2f->Fill(jetPRmassL2L3Corr[FatjetPreSelection2i[i]],jetPRmassL2L3Corr[FatjetPreSelection2j[i]]);
				
				if(jetPRmassL2L3Corr[FatjetPreSelection2i[i]]>135||jetPRmassL2L3Corr[FatjetPreSelection2i[i]]<105)continue;
				if(jetPRmassL2L3Corr[FatjetPreSelection2j[i]]>135||jetPRmassL2L3Corr[FatjetPreSelection2j[i]]<105)continue;
				//if(FATjetPRmass[FatjetPreSelection2j[i]]>130||FATjetPRmass[FatjetPreSelection2j[i]]<95)continue;
				//if(FATjetPRmass[FatjetPreSelection2i[i]]>150||FATjetPRmass[FatjetPreSelection2i[i]]<90)continue;
				//if(FATjetPRmass[FatjetPreSelection2j[i]]>150||FATjetPRmass[FatjetPreSelection2j[i]]<90)continue;
				
				
				
				FatjetPreSelection3i.push_back(FatjetPreSelection2i[i]);
				FatjetPreSelection3j.push_back(FatjetPreSelection2j[i]);
			}
			if(FatjetPreSelection3i.size()<1)continue;
			nPass[2]++;
			
			vector<int> FatjetPreSelection4i,FatjetPreSelection4j;
			for(unsigned int i=0;i<FatjetPreSelection3i.size();i++){
				if(FATnSubSDJet[FatjetPreSelection3i[i]]<2||FATnSubSDJet[FatjetPreSelection3j[i]]<2)continue;
				TLorentzVector  FATsubjet_1,FATsubjet_2;
				bool thisHiggsBTagTight=0,thisHiggsBTagLoose=0;
				FATsubjet_1.SetPxPyPzE(FATsubjetSDPx[FatjetPreSelection3i[i]][0],FATsubjetSDPy[FatjetPreSelection3i[i]][0],FATsubjetSDPz[FatjetPreSelection3i[i]][0],FATsubjetSDE[FatjetPreSelection3i[i]][0]);
				FATsubjet_2.SetPxPyPzE(FATsubjetSDPx[FatjetPreSelection3i[i]][1],FATsubjetSDPy[FatjetPreSelection3i[i]][1],FATsubjetSDPz[FatjetPreSelection3i[i]][1],FATsubjetSDE[FatjetPreSelection3i[i]][1]);
				if(FATsubjet_1.DeltaR(FATsubjet_2)<0.3 && FATjetCISVV2[FatjetPreSelection3i[i]]<0.244)continue;
				if(FATsubjet_1.DeltaR(FATsubjet_2)>0.3 && (FATsubjetSDCSV[FatjetPreSelection3i[i]][0]>0.244 || FATsubjetSDCSV[FatjetPreSelection3i[i]][1]>0.244))thisHiggsBTagLoose=1;
				if(FATsubjet_1.DeltaR(FATsubjet_2)>0.3 && (FATsubjetSDCSV[FatjetPreSelection3i[i]][0]>0.244 && FATsubjetSDCSV[FatjetPreSelection3i[i]][1]>0.244))thisHiggsBTagTight=1;
				if(FATsubjet_1.DeltaR(FATsubjet_2)<0.3){
					thisHiggsBTagTight=1;
					thisHiggsBTagLoose=1;
				}
				FATsubjet_1.SetPxPyPzE(FATsubjetSDPx[FatjetPreSelection3j[i]][0],FATsubjetSDPy[FatjetPreSelection3j[i]][0],FATsubjetSDPz[FatjetPreSelection3j[i]][0],FATsubjetSDE[FatjetPreSelection3j[i]][0]);
				FATsubjet_2.SetPxPyPzE(FATsubjetSDPx[FatjetPreSelection3j[i]][1],FATsubjetSDPy[FatjetPreSelection3j[i]][1],FATsubjetSDPz[FatjetPreSelection3j[i]][1],FATsubjetSDE[FatjetPreSelection3j[i]][1]);
				TLorentzVector  FATsubjet_3,FATsubjet_4;
				bool thatHiggsBTagTight=0,thatHiggsBTagLoose=0;
				if(FATsubjet_3.DeltaR(FATsubjet_4)<0.3 && FATjetCISVV2[FatjetPreSelection3j[i]]<0.244)continue;
				if(FATsubjet_3.DeltaR(FATsubjet_4)>0.3 && (FATsubjetSDCSV[FatjetPreSelection3j[i]][0]>0.244 || FATsubjetSDCSV[FatjetPreSelection3j[i]][1]>0.244))thatHiggsBTagLoose=1;
				if(FATsubjet_3.DeltaR(FATsubjet_4)>0.3 && (FATsubjetSDCSV[FatjetPreSelection3j[i]][0]>0.244 && FATsubjetSDCSV[FatjetPreSelection3j[i]][1]>0.244))thatHiggsBTagTight=1;
				if(FATsubjet_3.DeltaR(FATsubjet_4)<0.3){
					thatHiggsBTagTight=1;
					thatHiggsBTagLoose=1;
				}
				//if(FATsubjet_3.DeltaR(FATsubjet_4)>0.3)cout<<"Y"<<endl;
				if(thisHiggsBTagLoose==0 || thatHiggsBTagLoose==0 ){
					//cout<<thisHiggsBTagLoose<<","<<thatHiggsBTagLoose<<endl;
					//if(FATsubjet_3.DeltaR(FATsubjet_4)>0.3)cout<<FATsubjetSDCSV[FatjetPreSelection3j[i]][0]<<","<<FATsubjetSDCSV[FatjetPreSelection3j[i]][1]<<endl;
					continue;
					
				}
				if(thisHiggsBTagTight==0 && thatHiggsBTagTight==0) continue;
				FatjetPreSelection4i.push_back(FatjetPreSelection3i[i]);
				FatjetPreSelection4j.push_back(FatjetPreSelection3j[i]);
				
				
			}
			//if(numHiggsBTagLoose<2||numHiggsBTagTight<1)continue;
            if(FatjetPreSelection4i.size()<1)continue;
			nPass[3]++;
			
			//int numHiggsHP=0,numHiggsLP=0;
			
			bool isPassingTau=0;
			for(unsigned int i=0;i<FatjetPreSelection4i.size();i++){
				bool thisHiggsHP=0,thisHiggsLP=0;
				if(FATjetTau2[FatjetPreSelection4i[i]]/FATjetTau1[FatjetPreSelection4i[i]]<0.5)thisHiggsHP=1;
				if(FATjetTau2[FatjetPreSelection4i[i]]/FATjetTau1[FatjetPreSelection4i[i]]<0.75 && FATjetTau2[FatjetPreSelection4i[i]]/FATjetTau1[FatjetPreSelection4i[i]]>0.5)thisHiggsLP=1;
				if(thisHiggsHP)thisHiggsLP=1;
				bool thatHiggsHP=0,thatHiggsLP=0;
			
				
				if(FATjetTau2[FatjetPreSelection4j[i]]/FATjetTau1[FatjetPreSelection4j[i]]<0.5)thatHiggsHP=1;
				if(FATjetTau2[FatjetPreSelection4j[i]]/FATjetTau1[FatjetPreSelection4j[i]]<0.75 && FATjetTau2[FatjetPreSelection4j[i]]/FATjetTau1[FatjetPreSelection4j[i]]>0.5)thatHiggsLP=1;
				if(thatHiggsHP)thatHiggsLP=1;
				
				if(thisHiggsLP==0 || thatHiggsLP==0 )continue;
				if(thisHiggsHP==0 && thatHiggsHP==0) continue;
				
				isPassingTau=1;
			}
			if(isPassingTau==0)continue;
			
  
			nPass[4]++;
			
			TLorentzVector* thisHiggsCs = (TLorentzVector*)FATjetP4->At(FatjetPreSelection4i[0]);
			TLorentzVector* thatHiggsCs = (TLorentzVector*)FATjetP4->At(FatjetPreSelection4j[0]);
			TLorentzVector mjjCs=*thisHiggsCs+*thatHiggsCs;
			cs1->Fill(mjjCs.M());
			
			
			thatHiggsCs ->SetPxPyPzE(thatHiggsCs->Px()*125/jetPRmassL2L3Corr[FatjetPreSelection4j[0]],thatHiggsCs->Py()*125/jetPRmassL2L3Corr[FatjetPreSelection4j[0]],thatHiggsCs->Pz()*125/jetPRmassL2L3Corr[FatjetPreSelection4j[0]],thatHiggsCs->E()*125/jetPRmassL2L3Corr[FatjetPreSelection4j[0]]);
			
			mjjCs=*thisHiggsCs+*thatHiggsCs;
			cs2->Fill(mjjCs.M());
			
			thisHiggsCs ->SetPxPyPzE(thisHiggsCs->Px()*125/jetPRmassL2L3Corr[FatjetPreSelection4i[0]],thisHiggsCs->Py()*125/jetPRmassL2L3Corr[FatjetPreSelection4i[0]],thisHiggsCs->Pz()*125/jetPRmassL2L3Corr[FatjetPreSelection4i[0]],thisHiggsCs->E()*125/jetPRmassL2L3Corr[FatjetPreSelection4i[0]]);
			
			mjjCs=*thisHiggsCs+*thatHiggsCs;
			cs3->Fill(mjjCs.M());
			
			thisHiggsCs = (TLorentzVector*)FATjetP4->At(FatjetPreSelection4i[0]);
			thatHiggsCs = (TLorentzVector*)FATjetP4->At(FatjetPreSelection4j[0]);
			double scaleThis = 125/thisHiggsCs->M();
			double scaleThat = 125/thatHiggsCs->M();
			
			thisHiggsCs ->SetPxPyPzE(thisHiggsCs->Px()*scaleThis,thisHiggsCs->Py()*scaleThis,thisHiggsCs->Pz()*scaleThis,thisHiggsCs->E()*scaleThis);
			thatHiggsCs ->SetPxPyPzE(thatHiggsCs->Px()*scaleThat,thatHiggsCs->Py()*scaleThat,thatHiggsCs->Pz()*scaleThat,thatHiggsCs->E()*scaleThat);
		
			mjjCs=*thisHiggsCs+*thatHiggsCs;
			cs4->Fill(mjjCs.M());
			
			thisHiggsCs = (TLorentzVector*)FATjetP4->At(FatjetPreSelection4i[0]);
			thatHiggsCs = (TLorentzVector*)FATjetP4->At(FatjetPreSelection4j[0]);
			mjjCs=*thisHiggsCs+*thatHiggsCs;
			
			cs5->Fill(mjjCs.M()+250-thisHiggsCs->M()-thatHiggsCs->M());
			
			th[21]->Fill(jetPRmassL2L3Corr[FatjetPreSelection4i[0]]);
			th[22]->Fill(jetPRmassL2L3Corr[FatjetPreSelection4j[0]]);
			
			th[17]->Fill(FATjetPRmass[FatjetPreSelection4i[0]]);
			th[18]->Fill(FATjetPRmass[FatjetPreSelection4j[0]]);
			
			th[26]->Fill(thisHiggsCs->M());
			th[27]->Fill(thatHiggsCs->M());
			th[23]->Fill(mjjCs.M());
		}
		
		
		
		
		}
		
		
	for(int i=0 ;i< 28;i++)th[i]->Scale(1000*Xsec/total);
	
	th2f->Scale(1000*Xsec/total);
	cs1->Scale(1000*Xsec/total);
	cs2->Scale(1000*Xsec/total);
	cs3->Scale(1000*Xsec/total);
	cs4->Scale(1000*Xsec/total);
	cs5->Scale(1000*Xsec/total);
	csS->Scale(1000*Xsec/total);
		
	TFile* outFile = new TFile(Form("root_files/%s.root",st2.data()),"recreate");   
	
	for(int i=0 ;i< 28;i++)th[i]->Write();
	
	cs1->Write();
	cs2->Write();
	cs3->Write();
	cs4->Write();
	cs5->Write();
	csS->Write();

	th2f->Write();
	//cout<<th2f->GetCorrelationFactor();
	outFile->Close();
	
	for(int i=0 ;i<28;i++)th[i]->Clear();
	
	cs1->Clear();
	cs2->Clear();
	cs3->Clear();
	cs4->Clear();
	cs5->Clear();
	csS->Clear();
	th2f->Clear();
	
	//dir->Close();
	//delete f;
}
コード例 #19
0
ファイル: view.C プロジェクト: jhgoh/CMSSW-UserCode-Backup
TList* makePlots(TDirectory* baseDir, int colorTable[], bool doFillColor)
{
  if ( !baseDir ) return 0;
  TList* dirList = baseDir->GetListOfKeys();

  if ( !dirList ) return 0;
  const int nKeys = dirList->GetSize();

  THStack* hStackMuonPt = new THStack("hMuonPt", "Muon p_{T};Transverse momentum [GeV/c]");
  THStack* hStackMuonEta = new THStack("hMuonEta", "Muon #eta;Pseudorapidity");
  THStack* hStackMuonPhi = new THStack("hMuonPhi", "Muon #phi;Azimuthal angle");
  THStack* hStackMuonRelIso = new THStack("hMuonRelIso", "Muon relative isolation;Relative isolation");

  THStack* hStackMuon1Pt = new THStack("hMuon1Pt", "Leading Muon p_{T};Transverse momentum [GeV/c]");
  THStack* hStackMuon1Eta = new THStack("hMuon1Eta", "Leading Muon #eta;Pseudorapidity");
  THStack* hStackMuon1Phi = new THStack("hMuon1Phi", "Leading Muon #phi;Azimuthal angle");
  THStack* hStackMuon1RelIso = new THStack("hMuon1RelIso", "Leading Muon relative isolation;Relative isolation");

  THStack* hStackElectronPt = new THStack("hElectronPt", "Electron p_{T};Transverse momentum [GeV/c]");
  THStack* hStackElectronEta = new THStack("hElectronEta", "Electron #eta;Pseudorapidity");
  THStack* hStackElectronPhi = new THStack("hElectronPhi", "Electron #phi;Azimuthal angle");
  THStack* hStackElectronRelIso = new THStack("hElectronRelIso", "Electron relative isolation;Relative isolation");

  THStack* hStackElectron1Pt = new THStack("hElectron1Pt", "Leading Electron p_{T};Transverse momentum [GeV/c]");
  THStack* hStackElectron1Eta = new THStack("hElectron1Eta", "Leading Electron #eta;Pseudorapidity");
  THStack* hStackElectron1Phi = new THStack("hElectron1Phi", "Leading Electron #phi;Azimuthal angle");
  THStack* hStackElectron1RelIso = new THStack("hElectron1RelIso", "Leading Electron relative isolation;Relative isolation");

  THStack* hStackPosEMuMass = new THStack("hPosEMuMass", "H^{++} #rightarrow e#mu mass;Mass [GeV/c^{2}]");
  THStack* hStackPosEMuPt = new THStack("hPosEMuPt", "H^{++} #rightarrow e#mu p_{T};Transverse momentum [GeV/c]");
  THStack* hStackPosEMuEta = new THStack("hPosEMuEta", "H^{++} #rightarrow e#mu #eta;Pseudorapidity");
  THStack* hStackPosEMuPhi = new THStack("hPosEMuPhi", "H^{++} #rightarrow e#mu #phi;Azimuthal angle");

  THStack* hStackNegEMuMass = new THStack("hNegEMuMass", "H^{--} #rightarrow e#mu mass;Mass [GeV/c^{2}]");
  THStack* hStackNegEMuPt = new THStack("hNegEMuPt", "H^{--} #rightarrow e#mu p_{T};Transverse momentum [GeV/c]");
  THStack* hStackNegEMuEta = new THStack("hNegEMuEta", "H^{--} #rightarrow e#mu #eta;Pseudorapidity");
  THStack* hStackNegEMuPhi = new THStack("hNegEMuPhi", "H^{--} #rightarrow e#mu #phi;Azimuthal angle");

  THStack* hStackPosEMuZVetoMass = new THStack("hPosEMuZVetoMass", "H^{++} #rightarrow e#mu mass after Z-veto cut;Mass [GeV/c^{2}]");
  THStack* hStackNegEMuZVetoMass = new THStack("hNegEMuZVetoMass", "H^{--} #rightarrow e#mu mass after Z-veto cut;Mass [GeV/c^{2}]");

  THStack* hStackPosEMuBestMass = new THStack("hPosEMuBestMass", "Best matching H^{++} #rightarrow e#mu mass;Mass [GeV/c^{2}]");
  THStack* hStackNegEMuBestMass = new THStack("hNegEMuBestMass", "Best matching H^{--} #rightarrow e#mu mass;Mass [GeV/c^{2}]");

  THStack* hStackZMuMuMass = new THStack("hZMuMuMass", "Opposite signed dimuon mass;Mass [GeV/c^{2}]");
  THStack* hStackZEEMass = new THStack("hZEEMass", "Opposite signed dielectron mass;Mass [GeV/c^{2}]");
  THStack* hStackFourLeptonSumPt = new THStack("hFourLeptonSumPt", "Scalar sum of four lepton p_{T};#Sigma p_{T} [GeV/c]");
  THStack* hStackDHDeltaPhi = new THStack("hDHDeltaPhi", "Azimuthal angle difference between two H^{#pm#pm} candidates;#Delta#phi [Radian]");

  for ( int i=0; i<nKeys; ++i )
  {
    const int color = colorTable[i];

    TString keyName = dirList->At(i)->GetName();
    TObject* obj = baseDir->Get(keyName);

    if ( !obj || !obj->IsA()->InheritsFrom("TDirectory") ) continue;
    TDirectory* dir = (TDirectory*)obj;

    // Muon histograms
    addPlot(dir->Get("m/hPt"), keyName, color, hStackMuonPt, doFillColor);
    addPlot(dir->Get("m/hEta"), keyName, color, hStackMuonEta, doFillColor);
    addPlot(dir->Get("m/hPhi"), keyName, color, hStackMuonPhi, doFillColor);
    addPlot(dir->Get("m/hRelIso"), keyName, color, hStackMuonRelIso, doFillColor);

    addPlot(dir->Get("m/m1/hPt"), keyName, color, hStackMuon1Pt, doFillColor);
    addPlot(dir->Get("m/m1/hEta"), keyName, color, hStackMuon1Eta, doFillColor);
    addPlot(dir->Get("m/m1/hPhi"), keyName, color, hStackMuon1Phi, doFillColor);
    addPlot(dir->Get("m/m1/hRelIso"), keyName, color, hStackMuon1RelIso, doFillColor);

    // Electron histograms
    addPlot(dir->Get("e/hPt"), keyName, color, hStackElectronPt, doFillColor);
    addPlot(dir->Get("e/hEta"), keyName, color, hStackElectronEta, doFillColor);
    addPlot(dir->Get("e/hPhi"), keyName, color, hStackElectronPhi, doFillColor);
    addPlot(dir->Get("e/hRelIso"), keyName, color, hStackElectronRelIso, doFillColor);

    addPlot(dir->Get("e/e1/hPt"), keyName, color, hStackElectron1Pt, doFillColor);
    addPlot(dir->Get("e/e1/hEta"), keyName, color, hStackElectron1Eta, doFillColor);
    addPlot(dir->Get("e/e1/hPhi"), keyName, color, hStackElectron1Phi, doFillColor);
    addPlot(dir->Get("e/e1/hRelIso"), keyName, color, hStackElectron1RelIso, doFillColor);

    // H++ candidates
    addPlot(dir->Get("posEMuCand/hMass"), keyName, color, hStackPosEMuMass, doFillColor);
    addPlot(dir->Get("posEMuCand/hPt"), keyName, color, hStackPosEMuPt, doFillColor);
    addPlot(dir->Get("posEMuCand/hEta"), keyName, color, hStackPosEMuEta, doFillColor);
    addPlot(dir->Get("posEMuCand/hPhi"), keyName, color, hStackPosEMuPhi, doFillColor);

    // H-- candidates
    addPlot(dir->Get("negEMuCand/hMass"), keyName, color, hStackNegEMuMass, doFillColor);
    addPlot(dir->Get("negEMuCand/hPt"), keyName, color, hStackNegEMuPt, doFillColor);
    addPlot(dir->Get("negEMuCand/hEta"), keyName, color, hStackNegEMuEta, doFillColor);
    addPlot(dir->Get("negEMuCand/hPhi"), keyName, color, hStackNegEMuPhi, doFillColor);

    // Four-lepton cut variables
    addPlot(dir->Get("fourLeptons/hZMuMuMass"), keyName, color, hStackZMuMuMass, doFillColor);
    addPlot(dir->Get("fourLeptons/hZEEMass"), keyName, color, hStackZEEMass, doFillColor);
    addPlot(dir->Get("fourLeptons/hFourLeptonSumPt"), keyName, color, hStackFourLeptonSumPt, doFillColor);
    addPlot(dir->Get("fourLeptons/hDHDeltaPhi"), keyName, color, hStackDHDeltaPhi, doFillColor);

    // DH z-veto and best matching
    addPlot(dir->Get("posEMuCand/posEMuZVeto/hMass"), keyName, color, hStackPosEMuZVetoMass, doFillColor);
    addPlot(dir->Get("negEMuCand/negEMuZVeto/hMass"), keyName, color, hStackNegEMuZVetoMass, doFillColor);
    addPlot(dir->Get("posEMuCand/posEMuBest/hMass"), keyName, color, hStackPosEMuBestMass, doFillColor);
    addPlot(dir->Get("negEMuCand/negEMuBest/hMass"), keyName, color, hStackNegEMuBestMass, doFillColor);
  }

  TList* plotList = new TList;

  plotList->Add(hStackMuonPt);
  plotList->Add(hStackMuonEta);
  plotList->Add(hStackMuonPhi);
  plotList->Add(hStackMuonRelIso);

  plotList->Add(hStackMuon1Pt);
  plotList->Add(hStackMuon1Eta);
  plotList->Add(hStackMuon1Phi);
  plotList->Add(hStackMuon1RelIso);

  plotList->Add(hStackElectronPt);
  plotList->Add(hStackElectronEta);
  plotList->Add(hStackElectronPhi);
  plotList->Add(hStackElectronRelIso);

  plotList->Add(hStackElectron1Pt);
  plotList->Add(hStackElectron1Eta);
  plotList->Add(hStackElectron1Phi);
  plotList->Add(hStackElectron1RelIso);

  plotList->Add(hStackPosEMuMass);
  plotList->Add(hStackPosEMuPt);
  plotList->Add(hStackPosEMuEta);
  plotList->Add(hStackPosEMuPhi);

  plotList->Add(hStackNegEMuMass);
  plotList->Add(hStackNegEMuPt);
  plotList->Add(hStackNegEMuEta);
  plotList->Add(hStackNegEMuPhi);

  plotList->Add(hStackPosEMuZVetoMass);
  plotList->Add(hStackNegEMuZVetoMass);
                       
  plotList->Add(hStackPosEMuBestMass);
  plotList->Add(hStackNegEMuBestMass);
                       
  plotList->Add(hStackZMuMuMass);
  plotList->Add(hStackZEEMass);
  plotList->Add(hStackFourLeptonSumPt);
  plotList->Add(hStackDHDeltaPhi);

  return plotList;
}
コード例 #20
0
ファイル: Stack.cpp プロジェクト: hatakeyamak/RA2-RA2b-2015
mainClass(int luminosity=5000){ // luminosity is in /pb unit



  cutname[0]="nocut";cutname[1]="Njet_4";cutname[2]="ht_500" ;cutname[3]="mht_200";
  cutname[4]="delphi";cutname[5]="iso";
  cutname[6]="CSVM_0";
  cutname[7]="CSVM_1";
  cutname[8]="CSVM_2";
  cutname[9]="CSVM_3";

  WJtype[0]="EventsWith_1RecoMuon_0RecoElectron";
  TTbartype[0]="EventsWith_1RecoMuon_0RecoElectron";



// .....................................................................................................................................................//
// WJ Section
// .....................................................................................................................................................//

  //build a vector of scale factors
  //first load the cross sections into a vector
  vector<double> WJ_xs_vec;

  WJ_xs_vec.push_back(1817.0); // HT 100-200
  WJ_xs_vec.push_back(471.6);  // HT 200-400
  WJ_xs_vec.push_back(55.61);  // HT 400-600
  WJ_xs_vec.push_back(18.81);  // HT 600-Inf

  const int wjnHT = (int) WJ_xs_vec.size();   // Total number of HT bin samples

  for(int i=1; i<=wjnHT ; i++){
    if(i==1)sprintf(tempname,"../Results/results_WJ_HT-100to200_.root");
    else if(i==2)sprintf(tempname,"../Results/results_WJ_HT-200to400_.root");
    else if(i==3)sprintf(tempname,"../Results/results_WJ_HT-400to600_.root");
    else if(i==4)sprintf(tempname,"../Results/results_WJ_HT-600toInf_.root");
    else{cout << " Error!! There are only 4 WJet ht binned sample " << endl;}
    file = new TFile(tempname, "R");
    sprintf(tempname,"allEvents/nocut/MHT_nocut_allEvents");
    tempvalue = (luminosity*WJ_xs_vec[i-1])/((* (TH1D* ) file->Get(tempname)).GetEntries());

printf("Scale: %g, N: %g, Lum: %d, XS: %g \n ",tempvalue,((* (TH1D* ) file->Get(tempname)).GetEntries()),luminosity,WJ_xs_vec[i-1]);

    WJ_scalevec.push_back(tempvalue);
  }//end of loop over HTbins 
  std::cout << "WJ normalization scale factor determination done \n " << std::endl;




//..........................................//
// main histograms like HT, MHT, ...
//..........................................//

  // Load the files to a vector 
  // These are the HT, MHT, .. variables
  for(int i=1; i<=wjnHT ; i++){
    if(i==1)sprintf(tempname,"HadTauEstimation_WJ_HT-100to200_.root");
    else if(i==2)sprintf(tempname,"HadTauEstimation_WJ_HT-200to400_.root");
    else if(i==3)sprintf(tempname,"HadTauEstimation_WJ_HT-400to600_.root");
    else if(i==4)sprintf(tempname,"HadTauEstimation_WJ_HT-600toInf_.root");
    else{cout << " Error!! There are only 4 WJet ht binned sample " << endl;}
    WJ_inputfilevec.push_back(TFile::Open(tempname,"R"));
  }//end of loop over HTbins 

  // Stack
  tempstack = new THStack("stack","Binned Sample Stack");
  sprintf(tempname,"HadTauEstimation_WJ_stacked.root");
  file = new TFile(tempname,"RECREATE");
  histname.clear();
  histname[0]="weight";
  histname[1]="HT";
  histname[2]="MHT";
  histname[3]="NJet";
  histname[4]="NBtag";
  histname[5]="MuonPt";
  histname[6]="MtW";

  for(map<int , string >::iterator itt=WJtype.begin(); itt!=WJtype.end();itt++){        // loop over different event types

    cdtoitt = file->mkdir((itt->second).c_str());
    cdtoitt->cd();

    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames

      cdtoit =  cdtoitt->mkdir((it->second).c_str());
      cdtoit->cd();

      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms

        for(int i=0; i<wjnHT ; i++){                                                  // loop over different HT bins

          //cout << "================================" << endl;
          //cout << "HT#: " <<i << ", WJtype: " << itt->second << ", cutname: " << it->second << ", hist#: " << j << endl;  
          sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
          temphist = (TH1D *) WJ_inputfilevec.at(i)->Get(tempname)->Clone();
          temphist->Scale(WJ_scalevec[i]);
          temphist->SetFillColor(i+2);
          tempstack->Add(temphist);

        }//end of loop over HTbins 1..7

        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
        tempstack->Write(tempname);

        delete tempstack;
        tempstack = new THStack("stack","Binned Sample Stack");

      }//end of loop over histograms

    }//end of loop over cutnames 

  }//end of loop over event types

  file->Close();
  printf("WJ main histograms stacked \n ");






// .....................................................................................................................................................//
// TTbar Section
// .....................................................................................................................................................//

  //build a vector of scale factors
  //first load the cross sections into a vector
  vector<double> TTbar_xs_vec;

  TTbar_xs_vec.push_back(806.1); // 

  const int ttbarnHT = (int) TTbar_xs_vec.size();   // Total number of HT bin samples

  for(int i=1; i<=ttbarnHT ; i++){
    if(i==1)sprintf(tempname,"../Results/results_TTbar_.root");
    else{cout << " Error!! There are only 1 TTbaret ht binned sample " << endl;}
    file = new TFile(tempname, "R");
    sprintf(tempname,"allEvents/nocut/MHT_nocut_allEvents");
    tempvalue = (luminosity*TTbar_xs_vec[i-1])/((* (TH1D* ) file->Get(tempname)).GetEntries());

printf("Scale: %g, N: %g, Lum: %d, XS: %g \n ",tempvalue,((* (TH1D* ) file->Get(tempname)).GetEntries()),luminosity,TTbar_xs_vec[i-1]);

    TTbar_scalevec.push_back(tempvalue);
  }//end of loop over HTbins 
  std::cout << "TTbar normalization scale factor determination done \n " << std::endl;
  



//..........................................//
// main histograms like HT, MHT, ...
//..........................................//

  // Load the files to a vector 
  // These are the HT, MHT, .. variables
  for(int i=1; i<=ttbarnHT ; i++){
    if(i==1)sprintf(tempname,"HadTauEstimation_TTbar_.root");
    else{cout << " Error!! There are only 1 TTbaret ht binned sample " << endl;}
    TTbar_inputfilevec.push_back(TFile::Open(tempname,"R"));
  }//end of loop over HTbins 

  // Stack
  tempstack = new THStack("stack","Binned Sample Stack");
  sprintf(tempname,"HadTauEstimation_TTbar_stacked.root");
  file = new TFile(tempname,"RECREATE");
  histname.clear();
  histname[0]="weight";
  histname[1]="HT";
  histname[2]="MHT";
  histname[3]="NJet";
  histname[4]="NBtag";
  histname[5]="MuonPt";
  histname[6]="MtW";

  for(map<int , string >::iterator itt=TTbartype.begin(); itt!=TTbartype.end();itt++){        // loop over different event types

    cdtoitt = file->mkdir((itt->second).c_str());
    cdtoitt->cd();

    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames

      cdtoit =  cdtoitt->mkdir((it->second).c_str());
      cdtoit->cd();

      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms

        for(int i=0; i<ttbarnHT ; i++){                                                  // loop over different HT bins

          //cout << "================================" << endl;
          //cout << "HT#: " <<i << ", TTbartype: " << itt->second << ", cutname: " << it->second << ", hist#: " << j << endl;  
          sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
          temphist = (TH1D *) TTbar_inputfilevec.at(i)->Get(tempname)->Clone();
          temphist->Scale(TTbar_scalevec[i]);
          temphist->SetFillColor(i+2);
          tempstack->Add(temphist);

        }//end of loop over HTbins 1..7

        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
        tempstack->Write(tempname);
        delete tempstack;
        tempstack = new THStack("stack","Binned Sample Stack");

      }//end of loop over histograms

    }//end of loop over cutnames 

  }//end of loop over event types

  file->Close();
  printf("TTbar main histograms stacked \n ");



// ..................................................................................................................................................... //
// Stack main histograms from TTbar and WJet
// ..................................................................................................................................................... //

  // There are two contributors 1-TTbar and 2-WJ
  int NSamples=2;

  // A vector that contains all the samples
  vector<TFile*> sample_inputfilevec;

  THStack * tempstack2 = new THStack("stack","Binned Sample Stack");

  // Load the files to a vector 
  // These are the HT, MHT, .. variables
  for(int i=1; i<=NSamples ; i++){
    if(i==1)sprintf(tempname,"HadTauEstimation_TTbar_stacked.root");
    else if(i==2)sprintf(tempname,"HadTauEstimation_WJ_stacked.root");
    else{cout << " Error!! There are only 2 contributors! " << endl;}
    sample_inputfilevec.push_back(TFile::Open(tempname,"R"));
  }//end of loop over HTbins 

  // Stack
  delete tempstack;
  tempstack = new THStack("stack","Binned Sample Stack");
  sprintf(tempname,"HadTauEstimation_stacked.root");
  file = new TFile(tempname,"RECREATE");
  histname.clear();
  histname[0]="weight";
  histname[1]="HT";
  histname[2]="MHT";
  histname[3]="NJet";
  histname[4]="NBtag";
  histname[5]="MuonPt";
  histname[6]="MtW";

  for(map<int , string >::iterator itt=WJtype.begin(); itt!=WJtype.end();itt++){        // loop over different event types

    cdtoitt = file->mkdir((itt->second).c_str());
    cdtoitt->cd();

    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames

      cdtoit =  cdtoitt->mkdir((it->second).c_str());
      cdtoit->cd();


      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms

        for(int i=0; i<NSamples ; i++){                                                  // loop over different HT bins

          //cout << "================================" << endl;
          //cout << "HT#: " <<i << ", WJtype: " << itt->second << ", cutname: " << it->second << ", hist#: " << j << endl;  
          sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
          tempstack2 = (THStack *) sample_inputfilevec.at(i)->Get(tempname)->Clone();
          temphist = (TH1D*)tempstack2->GetStack()->Last(); 
          
          temphist->SetFillColor(i+2);
          tempstack->Add(temphist);

        }//end of loop over HTbins 1..7

        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
        tempstack->Write(tempname);
        delete tempstack;
        tempstack = new THStack("stack","Binned Sample Stack");

      }//end of loop over histograms

    }//end of loop over cutnames 

  }//end of loop over event types

  file->Close();
  printf("All samples main histograms stacked \n ");






} // End of the constructor 
コード例 #21
0
ファイル: doAll.C プロジェクト: hooberman/UserCode
void doAll(bool skipFWLite = true)
{

  //---------------------------------------------------------------
  // choose version, output will be written to output/[version]
  //---------------------------------------------------------------
  
  const char* version    = "V00-01-06";
  const char* jsonfile   = "jsons/Cert_EPSFINAL_May10ReReco_v2_PromptReco_160404_167913_JSON_goodruns.txt";
  const bool  useMCSkims = true;

  cout << "Version : " << version     << endl;
  cout << "json    : " << jsonfile    << endl;

  //Load CORE stuff
  gROOT->ProcessLine(".L ../CORE/CMS2.cc+");
  gROOT->ProcessLine(".L ../CORE/utilities.cc+");
  gROOT->ProcessLine(".L ../CORE/trackSelections.cc+");
  gROOT->ProcessLine(".L ../CORE/eventSelections.cc+");
  gROOT->ProcessLine(".L ../CORE/MITConversionUtilities.cc+");
  gROOT->ProcessLine(".L ../CORE/muonSelections.cc+");
  gROOT->ProcessLine(".L ../CORE/electronSelectionsParameters.cc+");
  gROOT->ProcessLine(".L ../CORE/electronSelections.cc+");
  gROOT->ProcessLine(".L ../CORE/metSelections.cc+");
  gROOT->ProcessLine(".L ../CORE/SimpleFakeRate.cc+");
  gROOT->ProcessLine(".L ../CORE/mcSelections.cc+");
  gROOT->ProcessLine(".L ../CORE/MT2/MT2.cc+");
  gROOT->ProcessLine(".L ../CORE/triggerUtils.cc+");  
  gROOT->ProcessLine(".L ../CORE/susySelections.cc+");
  gROOT->ProcessLine(".L ../CORE/mcSUSYkfactor.cc+");
  gROOT->ProcessLine(".L ../CORE/triggerSuperModel.cc+");
  gROOT->ProcessLine(".L ../CORE/triggerUtils.cc+");
  //gROOT->ProcessLine(".L ../CORE/jetSelections.cc+");
  gROOT->ProcessLine(".L ../CORE/ttbarSelections.cc+");

  // Load various tools  
  gROOT->ProcessLine(Form(".x setup.C(%d)", skipFWLite));
  //gROOT->ProcessLine(".L ../CORE/topmass/ttdilepsolve.cpp+"); 

  // Load FWLite
  gSystem->Load("../Tools/MiniFWLite/libMiniFWLite.so");

  // Load and compile the looping code
  gSystem->CompileMacro("singleLeptonLooper.C","++k", "libsingleLeptonLooper");
  
  singleLeptonLooper* looper = new singleLeptonLooper();

  //set looper parameters
  looper->set_susybaseline(0);
  //make baby ntuple
  looper->set_createTree(1);
  //use bitmask selection
  looper->set_useBitMask(0);
  //set version
  looper->set_version(version);
  //set json
  looper->set_json( jsonfile );

  // k-factors
  float kttall    = 1.;
  float kqcd      = 1.;  
  float kWjets    = 1.;  
  float kDYtot    = 1.;  
  float ktW       = 1.;

  // prescales
  int preqcd      = 1;
  int prettall    = 1;
  int preWjets    = 1;
  int preDYtot    = 1;
  int pretW       = 1;
 
  // flags for files to run over
  bool rundata     = 0;
  bool runttall    = 1;
  bool runWjets    = 0;
  bool runQCD      = 0;
  bool runtW       = 0;
  bool runDYtot    = 0;
  bool runT2tt     = 0; 
  bool runT2tt_few = 0;
  bool runT2bw     = 0;

  if( useMCSkims )  cout << "Using MC skims" << endl;
  else              cout << "Using full MC samples" << endl;

  //----------------------------------------
  // QCD
  //----------------------------------------

  TChain* chQCD = new  TChain("Events");

  if(runQCD){

    string skimdir = "/home/users/benhoob/filters/output/";

    //SingleLeptonSkim ntuples
    if( useMCSkims ){
      pickSkimIfExists(chQCD, skimdir+"QCD_Pt-15to30_TuneZ2_7TeV_pythia6_Summer11-PU_S4_START42_V11-v1/V04-02-31/SingleLeptonSkim/merged*root");
      pickSkimIfExists(chQCD, skimdir+"QCD_Pt-30to50_TuneZ2_7TeV_pythia6_Summer11-PU_S4_START42_V11-v1/V04-02-31/SingleLeptonSkim/merged*root");
      pickSkimIfExists(chQCD, skimdir+"QCD_Pt-50to80_TuneZ2_7TeV_pythia6_Summer11-PU_S4_START42_V11-v1/V04-02-31/SingleLeptonSkim/merged*root");
      pickSkimIfExists(chQCD, skimdir+"QCD_Pt-80to120_TuneZ2_7TeV_pythia6_Summer11-PU_S4_START42_V11-v1/V04-02-31/SingleLeptonSkim/merged*root");
      pickSkimIfExists(chQCD, skimdir+"QCD_Pt-120to170_TuneZ2_7TeV_pythia6_Summer11-PU_S4_START42_V11-v1/V04-02-31/SingleLeptonSkim/merged*root");
      pickSkimIfExists(chQCD, skimdir+"QCD_Pt-170to300_TuneZ2_7TeV_pythia6_Summer11-PU_S4_START42_V11-v1/V04-02-31/SingleLeptonSkim/merged*root");
    }

    //full cms2 ntuples
    else{
      pickSkimIfExists(chQCD, "/nfs-7/userdata/cms2/QCD_Pt-15to30_TuneZ2_7TeV_pythia6_Summer11-PU_S4_START42_V11-v1/V04-02-31/merged*root");
      pickSkimIfExists(chQCD, "/nfs-7/userdata/cms2/QCD_Pt-30to50_TuneZ2_7TeV_pythia6_Summer11-PU_S4_START42_V11-v1/V04-02-31/merged*root");
      pickSkimIfExists(chQCD, "/nfs-7/userdata/cms2/QCD_Pt-50to80_TuneZ2_7TeV_pythia6_Summer11-PU_S4_START42_V11-v1/V04-02-31/merged*root");
      pickSkimIfExists(chQCD, "/nfs-7/userdata/cms2/QCD_Pt-80to120_TuneZ2_7TeV_pythia6_Summer11-PU_S4_START42_V11-v1/V04-02-31/merged*root");
      pickSkimIfExists(chQCD, "/nfs-7/userdata/cms2/QCD_Pt-120to170_TuneZ2_7TeV_pythia6_Summer11-PU_S4_START42_V11-v1/V04-02-31/merged*root");
      pickSkimIfExists(chQCD, "/nfs-7/userdata/cms2/QCD_Pt-170to300_TuneZ2_7TeV_pythia6_Summer11-PU_S4_START42_V11-v1/V04-02-31/merged*root");
    }
  }

  //----------------------------------------
  // ttbar
  //----------------------------------------

  TChain* chtopall = new TChain("Events");
  if (runttall) {
    pickSkimIfExists(chtopall,"/nfs-7/userdata/cms2/TTJets_TuneZ2_7TeV-madgraph-tauola_Summer11-PU_S4_START42_V11-v1/V04-02-29_singleLepton/merged*root");
    //pickSkimIfExists(chtopall,"/nfs-7/userdata/cms2/TTJets_TuneZ2_7TeV-madgraph-tauola_Summer11-PU_S4_START42_V11-v1/V04-02-29_singleLepton/merged_ntuple.root");
  }

  //----------------------------------------
  // W+jets
  //----------------------------------------

  TChain* chWjets = new  TChain("Events");
  if(runWjets){

    //SingleLeptonSkim ntuples
    if( useMCSkims ){
      pickSkimIfExists(chWjets,"/hadoop/cms/store/group/snt/papers2011/Summer11MC/WJetsToLNu_TuneZ2_7TeV-madgraph-tauola_Summer11-PU_S4_START42_V11-v1/V04-02-29/SingleLeptonAndTwoJets/merged_ntuple_*.root");
      //pickSkimIfExists(chWjets,"/nfs-7/userdata/cms2/WJetsToLNu_TuneZ2_7TeV-madgraph-tauola_Summer11-PU_S4_START42_V11-v1/V04-02-29/SingleLeptonAndJets/merged*root");//l+3j filtered
      //pickSkimIfExists(chWjets,"/hadoop/cms/store/user/imacneill/Summer11MC/WJetsToLNu_TuneZ2_7TeV-madgraph-tauola_Summer11-PU_S4_START42_V11-v1/V04-02-29/SingleLeptonAndJets/merged*root");
    }

    //full cms2 ntuples
    else{
      pickSkimIfExists(chWjets,"/nfs-7/userdata/cms2/WJetsToLNu_TuneZ2_7TeV-madgraph-tauola_Summer11-PU_S4_START42_V11-v1/V04-02-29_singleLepton/merged*root");
    }

  }

  //----------------------------------------
  // DY
  //----------------------------------------

  TChain* chDYtot = new  TChain("Events");
  if(runDYtot){
    cout << "ERROR! NEED TO ADD SINGLE LEPTON SKIM OF DY SAMPLES!!!" << endl;
    exit(0);
  }

  //----------------------------------------
  // single top
  //----------------------------------------
  
  TChain* chtW = new  TChain("Events");
  if (runtW) {

    pickSkimIfExists(chtW,"/nfs-7/userdata/benhoob/cms2/T_TuneZ2_s-channel_7TeV-powheg-tauola_Summer11-PU_S4_START42_V11-v1/V04-02-29/merged*root");
    pickSkimIfExists(chtW,"/nfs-7/userdata/benhoob/cms2/Tbar_TuneZ2_s-channel_7TeV-powheg-tauola_Summer11-PU_S4_START42_V11-v1/V04-02-29/merged*root");
    
    pickSkimIfExists(chtW,"/nfs-7/userdata/benhoob/cms2/T_TuneZ2_t-channel_7TeV-powheg-tauola_Summer11-PU_S4_START42_V11-v1/V04-02-29/merged*root");
    pickSkimIfExists(chtW,"/nfs-7/userdata/benhoob/cms2/Tbar_TuneZ2_t-channel_7TeV-powheg-tauola_Summer11-PU_S4_START42_V11-v1/V04-02-29/merged*root");

    pickSkimIfExists(chtW,"/nfs-7/userdata/benhoob/cms2/T_TuneZ2_tW-channel-DR_7TeV-powheg-tauola_Summer11-PU_S4_START42_V11-v1/V04-02-29/merged*root");
    pickSkimIfExists(chtW,"/nfs-7/userdata/benhoob/cms2/Tbar_TuneZ2_tW-channel-DR_7TeV-powheg-tauola_Summer11-PU_S4_START42_V11-v1/V04-02-29/merged*root");

  }

  //----------------------------------------
  // T2tt (a few sample points)
  //----------------------------------------

  TChain *chT2tt_few = new TChain("Events");
  if (runT2tt_few) {
    
    // these are the T2tt files with m(stop),m(LSP) = 400,100 OR 500,100 OR 500,300
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_37.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_46.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_66.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_71.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_84.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_85.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_88.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_147.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_149.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_151.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_191.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_193.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_212.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_213.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_222.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_225.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_232.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_268.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_328.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_390.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_395.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_396.root");
    
    // these are the T2tt files with m(stop),m(LSP) = 250,50 OR 300,50 OR 400,50 OR 400,200
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_1.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_5.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_6.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_16.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_62.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_63.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_70.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_91.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_105.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_149.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_150.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_160.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_171.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_243.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_246.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_264.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_274.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_312.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_315.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_325.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_326.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_333.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_335.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_349.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_351.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_369.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_388.root");
    // pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_394.root");

    //350/100 (from ATLAS paper)
    pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_122.root");
    pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_274.root");
    pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_286.root");
    pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_326.root");
    pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_347.root");
    pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_364.root");
    pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_391.root");
    pickSkimIfExists(chT2tt_few,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged_ntuple_392.root");
  }

  //----------------------------------------
  // T2tt (a few sample points)
  //----------------------------------------

  TChain *chT2tt = new TChain("Events");
  if (runT2tt) {
    pickSkimIfExists(chT2tt,"/nfs-7/userdata/cms2/SMS-T2tt_Mstop-225to1200_mLSP-50to1025_7TeV-Pythia6Z_Summer11-PU_START42_V11_FastSim-v1/V04-02-20-04/merged*root");
  }

  //----------------------------------------
  // T2bw
  //----------------------------------------

  TChain *chT2bw = new TChain("Events");
  if (runT2bw) {
    // pickSkimIfExists(chT2bw,"/nfs-7a/userdata/cms2/SMS-T2bw_x-0p25to0p75_mStop-50to850_mLSP-50to800_7TeV-Pythia6Z_Summer11-PU_START42_V11_FSIM-v1/VB04-02-29_Fastsim/merged_ntuple_98.root");
    //    pickSkimIfExists(chT2bw,"/nfs-7a/userdata/cms2/SMS-T2bw_x-0p25to0p75_mStop-50to850_mLSP-50to800_7TeV-Pythia6Z_Summer11-PU_START42_V11_FSIM-v1/VB04-02-29_Fastsim/merged_ntuple_99.root");
    //    pickSkimIfExists(chT2bw,"/nfs-7a/userdata/cms2/SMS-T2bw_x-0p25to0p75_mStop-50to850_mLSP-50to800_7TeV-Pythia6Z_Summer11-PU_START42_V11_FSIM-v1/VB04-02-29_Fastsim/merged_ntuple_100.root");
    //    pickSkimIfExists(chT2bw,"/nfs-7a/userdata/cms2/SMS-T2bw_x-0p25to0p75_mStop-50to850_mLSP-50to800_7TeV-Pythia6Z_Summer11-PU_START42_V11_FSIM-v1/VB04-02-29_Fastsim/merged_ntuple_101.root");
    pickSkimIfExists(chT2bw,"/nfs-7a/userdata/cms2/SMS-T2bw_x-0p25to0p75_mStop-50to850_mLSP-50to800_7TeV-Pythia6Z_Summer11-PU_START42_V11_FSIM-v1/VB04-02-29_Fastsim/merged*root");
  }

  //----------------------------------------
  // DATA
  //----------------------------------------

  TChain* chdata     = new  TChain("Events");

  if(rundata){
    
    cout << "adding ElectronHad and MuHad or SingleMu data" << endl;
    
    //---------------------------
    // May10 rereco
    //---------------------------
   
    //pickSkimIfExists(chdata,"/hadoop/cms/store/user/yanjuntu/CMSSW_4_2_7_patch1_V04-02-33/MuHad_Run2011A-May10ReReco-v1_AOD/CMSSW_4_2_7_patch1_V04-02-33_merged/V04-02-33/merged*root"); 
    //pickSkimIfExists(chdata,"/hadoop/cms/store/user/yanjuntu/CMSSW_4_2_7_patch1_V04-02-33/ElectronHad_Run2011A-May10ReReco-v1_AOD/CMSSW_4_2_7_patch1_V04-02-33_merged/V04-02-33/merged*root");    

    // pickSkimIfExists(chdata,"/nfs-7/userdata/cms2/ElectronHad_Run2011A-May10ReReco-v1_AOD/V04-02-33/SingleLeptonAndJets/merged*root");//l+3j filtered
    // pickSkimIfExists(chdata,"/nfs-7/userdata/cms2/MuHad_Run2011A-May10ReReco-v1_AOD/V04-02-33/SingleLeptonAndJets/merged*root");//l+3j filtered

    pickSkimIfExists(chdata,"/hadoop/cms/store/user/vimartin/SingleLeptonAndTwoJets/SingleMu_Run2011A-May10ReReco-v1_AOD/V04-02-33/SingleLeptonAndTwoJets/merged*root");//l+2j filtered
    pickSkimIfExists(chdata,"/hadoop/cms/store/user/vimartin/SingleLeptonAndTwoJets/ElectronHad_Run2011A-May10ReReco-v1_AOD/V04-02-33/SingleLeptonAndTwoJets/merged*root");//l+2j filtered

    //---------------------------
    // prompt reco v4
    //---------------------------
    
    //pickSkimIfExists(chdata,"/hadoop/cms/store/user/yanjuntu/CMSSW_4_2_7_patch1_V04-02-33/ElectronHad_Run2011A-PromptReco-v4_AOD/CMSSW_4_2_7_patch1_V04-02-33_merged/V04-02-33/merged*root");
    //pickSkimIfExists(chdata,"/hadoop/cms/store/user/yanjuntu/CMSSW_4_2_7_patch1_V04-02-33/MuHad_Run2011A-PromptReco-v4_AOD/CMSSW_4_2_7_patch1_V04-02-33_merged/V04-02-33/merged*root");

    // pickSkimIfExists(chdata,"/nfs-7/userdata/cms2/ElectronHad_Run2011A-PromptReco-v4_AOD/V04-02-33/SingleLeptonAndJets/merged*root");//l+3j filtered
    // pickSkimIfExists(chdata,"/nfs-7/userdata/cms2/MuHad_Run2011A-PromptReco-v4_AOD/V04-02-33/SingleLeptonAndJets/merged*root");//l+3j filtered

    pickSkimIfExists(chdata,"/hadoop/cms/store/user/vimartin/SingleLeptonAndTwoJets/SingleMu_Run2011A-PromptReco-v4_AOD/V04-02-33/SingleLeptonAndTwoJets/merged*root");//l+2j filtered
    pickSkimIfExists(chdata,"/hadoop/cms/store/user/vimartin/SingleLeptonAndTwoJets/ElectronHad_Run2011A-PromptReco-v4_AOD/V04-02-33/SingleLeptonAndTwoJets/merged*root");//l+2j filtered
    
  }



  
  //--------------------------------
  //set luminosity to scale to
  //--------------------------------

  float lumi              = 1.0; 
  bool  calculateTCMET    = false; //redo tcmet calculation on the fly

  char* jetTypeStrings[3] = {"JPT", "calo","pfjet"};
  char* metTypeStrings[4] = {"tcmet", "muon", "muonjes","pfmet"};
  char* zvetoStrings[4]   = {"", "_allzveto", "_nozveto","_selectz"};
  char* frmodeStrings[2]  = {"QCDType","WjetsType"}; //e_qcd = 0, e_wjets
  bool doFakeApp          = false;

  singleLeptonLooper::TrigEnum trig;

  for (int jetTypeIdx = 2; jetTypeIdx < 3; ++jetTypeIdx)
    {
      for (int metTypeIdx = 3; metTypeIdx < 4; ++metTypeIdx)
	{
	  for (int zvetoIdx = 0; zvetoIdx < 1; ++zvetoIdx)
	    {
	      for (int frmodeIdx = 0; frmodeIdx < (2-(1*!doFakeApp)); ++frmodeIdx)
		//for (int frmodeIdx = 0; frmodeIdx < 1; ++frmodeIdx)
		{
                  
		  singleLeptonLooper::JetTypeEnum  jetType(jetTypeIdx);
		  singleLeptonLooper::MetTypeEnum  metType(metTypeIdx);
		  singleLeptonLooper::ZVetoEnum    zveto(zvetoIdx);
		  singleLeptonLooper::FREnum       frmode(frmodeIdx);

		  if( doFakeApp ){
		    if( frmodeIdx == 0 ) cout << "Doing double fake estimate" << endl;
		    if( frmodeIdx == 1 ) cout << "Doing single fake estimate" << endl;
		  }

		  //--------------------------------------------------------------------
		  if (runttall) {
		    cout << "Processing ttbar all.. " << endl;
		    looper->ScanChain(chtopall,"ttall", kttall, prettall, lumi, jetType, metType, zveto, frmode, doFakeApp, calculateTCMET);
		    cout << "Done processing ttbar all.. " << endl;
		  }
		  //--------------------------------------------------------------------
		  if (rundata) {
		    cout << "Processing data" << endl;
		    looper->ScanChain(chdata,"data", 1, 1, lumi, jetType, metType, zveto, frmode, doFakeApp, calculateTCMET);
		    cout << "Done processing data" << endl;
		  }
		  //--------------------------------------------------------------------
		  if (runDYtot) {
		    cout << "Processing DY->all" << endl;
		    looper->ScanChain(chDYtot,"DYtot", kDYtot, preDYtot, lumi, jetType, metType, zveto, frmode, doFakeApp, calculateTCMET);
		    cout << "Done rocessing DY->ee" << endl;
		  }
		  //--------------------------------------------------------------------
		  if (runQCD) {
		    cout << "Processing QCD.. " << endl;
		    looper->ScanChain(chQCD,"qcd", kqcd, preqcd, lumi, jetType, metType, zveto,frmode, doFakeApp, calculateTCMET);
		    cout << "Done processing  QCD.. " << endl;
		  }
		  //--------------------------------------------------------------------
		  if (runWjets) {
		    cout << "Processing Wjets.." << endl;
		    looper->ScanChain(chWjets,"wjets", kWjets, preWjets, lumi, jetType, metType, zveto, frmode, doFakeApp, calculateTCMET);
		    cout << "Done processing Wjets.." << endl;
		  }
		  //--------------------------------------------------------------------
		  if (runtW) {
		    cout << "Processing tW" << endl;
		    looper->ScanChain(chtW,"tW", ktW, pretW, lumi, jetType, metType, zveto, frmode, doFakeApp, calculateTCMET);
		    cout << "Done processing tW" << endl;
		  }
		  //--------------------------------------------------------------------
		  if (runT2tt) {
		    cout << "Processing T2tt" << endl;
		    looper->ScanChain(chT2tt, "T2tt", 1, 1, lumi, jetType, metType, zveto, frmode, doFakeApp, calculateTCMET);
		    cout << "Done processing T2tt" << endl;
		  }
		  //--------------------------------------------------------------------
		  if (runT2tt_few) {
		    cout << "Processing T2tt_few" << endl;
		    looper->ScanChain(chT2tt_few, "T2tt_few", 1, 1, lumi, jetType, metType, zveto, frmode, doFakeApp, calculateTCMET);
		    cout << "Done processing T2tt_few" << endl;
		  }
		  //--------------------------------------------------------------------
		  if (runT2bw) {
		    cout << "Processing T2bw all.. " << endl;
		    looper->ScanChain(chT2bw,"T2bw", 1, 1, lumi, jetType, metType, zveto, frmode, doFakeApp, calculateTCMET);
		    cout << "Done processing T2bw all.. " << endl;
		  }

		  // save all the histograms
		  const char* outFile;
		  if(doFakeApp) {
		    outFile = Form("../output/%s/singleLepton_%s_%s%s_%s_FakeApp.root", version,
				   jetTypeStrings[jetTypeIdx], metTypeStrings[metTypeIdx],zvetoStrings[zvetoIdx],frmodeStrings[frmode]);
		  }
		  else {
		    outFile = Form("../output/%s/singleLepton_%s_%s%s.root", version,
				   jetTypeStrings[jetTypeIdx], metTypeStrings[metTypeIdx],zvetoStrings[zvetoIdx]);
		  }
                  
		  //const char* outFile = Form("victory_baseline_genmetgt50_nosumjetptcut_%s_%s_pleasework_varbins.root", 
		  //jetTypeStrings[jetTypeIdx], metTypeStrings[metTypeIdx]);
		  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
		  rootdir->cd();
		  saveHist(outFile);
		  deleteHistos();
                  
		} // frmodeIdx
	    }//zvetoIdx
	} // metTypeIdx
    } // jetTypeIdx
  //}

  gSystem->Exit(0);
  
}
コード例 #22
0
ファイル: dataCardSM.C プロジェクト: 12345ieee/cmg-cmssw
void dataCardSM(Int_t channel, Int_t cat, Int_t year, Int_t dataset, TString mass, TString path, TString tag, Int_t option=0){

  if(tag!="")path=path+"_"+tag;

  TString ChannelName;
  if(channel==1)ChannelName="muTau";
  else if(channel==2)ChannelName="eleTau";
  else return;
  cout<<"ChannelName "<<ChannelName<<endl;
  
  if(channel==1){
    TauMuPlotter * analysis=0;
    
    if(year==2011){
      analysis=configTauMu2011("analysis",path);
    }
    if(year==2012){
      if(dataset==1)analysis=configTauMu2012AB("analysis",path);
      if(dataset==2)analysis=configTauMu2012ABC("analysis",path);
      if(dataset==3)analysis=configTauMu2012D("analysis",path);
      if(dataset==4)analysis=configTauMu2012ABCD("analysis",path);
      if(dataset==5)analysis=configTauMu2012Summer13("analysis",path);
      if(dataset==6)analysis=configTauMu2012Summer13ReReco("analysis",path);
    }
  }
  if(channel==2){
    TauElePlotter * analysis=0;

    if(year==2011){
      analysis=configTauEle2011("analysis",path);
    }
    if(year==2012){
      if(dataset==1)analysis=configTauEle2012AB("analysis",path);
      if(dataset==2)analysis=configTauEle2012ABC("analysis",path);
      if(dataset==3)analysis=configTauEle2012D("analysis",path);
      if(dataset==4)analysis=configTauEle2012ABCD("analysis",path);
      if(dataset==5)analysis=configTauEle2012Summer13("analysis",path);
    }
  }
  
 
  bool Blind=0;
  analysis->nbins_=0;
  analysis->Isocat_=1;
  analysis->MTcat_=1; 
  analysis->Chcat_=1; 

  cout<<endl<<"optimizaion with option "<<option<<endl;

//   ///Simple isolation scan
//   char isocutoption[100];
//   if(option<10){
//     sprintf(isocutoption,"(tauisomva2raw>%.3f)",0.80+0.02*option);
//     analysis->tauIsoCutQCD_="(tauisomva2raw>0.5)";
//   }else if(option<20){
//     sprintf(isocutoption,"(tauiso3hitraw<%.3f)",2.2-0.2*(option-10));
//     analysis->tauIsoCutQCD_="(tauiso3hitraw<6.0)";
//   }
//   analysis->tauIsoCut_=isocutoption;

  
//   ////////////////////////optimization of mT cut
//   if(option>0){
//     //use the digits of the option for each variable
//     analysis->mTCut_=5+abs(option)*5;
//   }
//   //////////////////////////////////////////////////

  ////////////////////////optimization of 1Jet : with 2 tau pT categories
  if(option>0){

    //optimize tau pT without higgs pT cut
    if((option/10)==0)analysis->taupTCut_ = 20+(option)*5;//1->6
    ///optimize higgs pT cut at low Tau pT
    if((option/10)==1)analysis->higgspTCutLow_=(option%10-1)*20;//11->18
    ///optimize higgs pT cut at high Tau pT
    if((option/10)==2)analysis->higgspTCutHigh_=(option%10-1)*20;//21->28

    //optimize tau and higgs pT cuts at the same time
    if((option/100)==1){
      analysis->taupTCut_ = 20+((option%100)/10 - 1)*5;//first digit: 1->6
      analysis->higgspTCutHigh_=(option%10-1)*20;//second digit: 1->8
    }

  }
  //////////////////////////////////////////////////

  analysis->scaleSamplesLumi();
  TFile output(ChannelName+"_SM"+(long)cat+"_"+mass+"_"+tag+".root","recreate");
  for(long sm=0; sm<NCAT; sm++){
    if(cat==9)continue;
    if(cat==13 && (sm==2 || sm==4))continue;//skip boost_low and vbf
    if(cat==20 && (sm==3 || sm==4))continue;//skip boost_high and vbf
    if(cat==23 && (sm==4))continue;//skip vbf
    if(cat==15 && (sm==2 || sm==3))continue;//skip boost_low and boost_high

    TDirectory* dir = output.mkdir(ChannelName+"_"+catdirname[sm]);  
    gROOT->cd();

//     if(sm==0 || sm==1){
//       analysis->plotvar_="ditaumass";//switch to visible mass for 0jet
//       analysis->setVariableBinning(NXBINS0JET,xbinsValues0Jet);
//     }else{
    analysis->plotvar_=mass;
    if(sm==4)analysis->setVariableBinning(NXBINSVBF,xbinsValuesVBF);
    else analysis->setVariableBinning(NXBINS,xbinsValues);
    //    }
    
      ///Category definition
    analysis->extrasel_ = analysis->getSMcut(sm);
    //analysis->extrasel_ = analysis->getSMcutOpt(sm);//possible higgs pT cuts
    //analysis->extrasel_ = analysis->getSMcutSummer13(sm);//use higgs pT < 20 in control regions


//     if(option==0)analysis->extrasel_ = analysis->getSMcut(sm) + "*(taudecaymode==0)";
//     if(option==1)analysis->extrasel_ = analysis->getSMcut(sm) + "*(taudecaymode==1)";
//     if(option==10)analysis->extrasel_ = analysis->getSMcut(sm) + "*(taudecaymode==10)";

//     //for ZTT decaymode ratios
//     analysis->mTCut_=40;
//     if(20<=option&&option<30) analysis->extrasel_ = TString("(metpt<40&&njet<=2)*")+"(taudecaymode==0)"+"*("+(long)(20+(option-20)*5)+"<taupt&&taupt<"+(long)(20+(option-20+1)*5)+")";
//     if(30<=option&&option<40) analysis->extrasel_ = TString("(metpt<40&&njet<=2)*")+"(taudecaymode==1)"+"*("+(long)(20+(option-30)*5)+"<taupt&&taupt<"+(long)(20+(option-30+1)*5)+")";
//     if(40<=option&&option<50) analysis->extrasel_ = TString("(metpt<40&&njet<=2)*")+"(taudecaymode==10)"+"*("+(long)(20+(option-40)*5)+"<taupt&&taupt<"+(long)(20+(option-40+1)*5)+")";


    TH1F* QCD = 0;
    if(channel==1){//mu-tau
      if(year==2011){
	if(sm==0 || sm==2 ) QCD=analysis->getQCDInc();
	if(sm==1 || sm==3 ) QCD=analysis->getQCDIncLooseShape();
	if(sm==4)           QCD=analysis->getQCDMike();
      }
      if(year==2012){
	if(sm==0) QCD=analysis->getQCDIncWNJet(); 
	if(sm==1) QCD=analysis->getQCDMuIsoSM(); 
	if(sm==2) QCD=analysis->getQCDIncLowPt(); 
	if(sm==3) QCD=analysis->getQCDMuIsoSM(); 
	if(sm==4) QCD=analysis->getQCDVBFHCP();
      }
    }
    if(channel==2){//e-tau
      if(year==2011){
	if(sm==0 || sm==2) QCD=analysis->getQCDInc();
	if(sm==1 || sm==3) QCD=analysis->getQCDIncLooseShape();
	if(sm==4)          QCD=analysis->getQCDMike();
      }
      if(year==2012){
	if(sm==0) QCD=analysis->getQCDIncWNJet(); 
	if(sm==1) QCD=analysis->getQCDMuIsoSM();
	if(sm==2) QCD=analysis->getQCDIncLowPt();//getQCDIncWNJet(); //
	if(sm==3) QCD=analysis->getQCDIncHighPt();
	if(sm==4) QCD=analysis->getQCDVBFHCP2();
      }
    }
    QCD->SetName("QCD");


    TH1F* W = 0;
    if(channel==1){//mu-tau
      if(year==2011){
	if(sm==0 || sm==1) W = analysis->getWJetsInc();
	if(sm==2 || sm==3) W = analysis->getWJetsInc();
	if(sm==4) W = analysis->getW3JetsVBF();
      }
      if(year==2012){
	if(sm==0) W = analysis->getWJetsNJet();
	if(sm==1) W = analysis->getWJetsNJetNoChCut();
	if(sm==2) W = analysis->getWJetsNJet();
	if(sm==3) W = analysis->getWJetsNJetNoChCut();
	if(sm==4) W = analysis->getWJetsNJetVBFHCP(); 
      }
    }
    if(channel==2){//e-tau
      if(year==2011){
	if(sm==0 || sm==1) W = analysis->getWJetsInc();
	if(sm==2 || sm==3) W = analysis->getWJetsInc();
	if(sm==4)  W = analysis->getW3JetsVBF();
      }
      if(year==2012){
	if(sm==0) W = analysis->getWJetsNJet();
	if(sm==1) W = analysis->getWJetsNJetNoChCut();
	if(sm==2) W = analysis->getWJetsNJetNoChCut();
	if(sm==3) W = analysis->getWJetsNJetNoChCut();
	if(sm==4) W = analysis->getWJetsNJetVBFHCP(); 
      }
    }
    W->SetName("W");
    
    TH1F* ZTT = 0;
    ZTT = analysis->getZToTauTau();
    ZTT->SetName("ZTT");

    TH1F* TT = 0;
    if(sm==0 || sm==2 || sm==1 || sm==3)        TT=analysis->getTTJetsInc(); 
    if(sm==4)                                   TT=analysis->getTTJetsVBFHCP(); 
    TT->SetName("TT");

    TH1F* ZL =0;
    if(channel==1){//mu-Tau
      if(sm==0 || sm==2 || sm==1 || sm==3) 	ZL =analysis->getZLInc();
      if(sm==4)                            	ZL =analysis->getZLVBFHCP();
    }
    if(channel==2){//e-Tau
      if(sm==0 || sm==2 || sm==1) 	        ZL =analysis->getZL2012();//analysis->getZL2012Type2();//
      if(sm==3)                            	ZL =analysis->getZLBoost();
      if(sm==4)                            	ZL =analysis->getZLVBFHCP();
    }
    ZL->SetName("ZL");

    TH1F* ZJ = 0;
    if(sm==0 || sm==2 || sm==1 || sm==3)        ZJ=analysis->getZToLJetInc();
    if(sm==4)                                   ZJ=analysis->getZToLJetVBFHCP();                   
    ZJ->SetName("ZJ");

    TH1F* VV = 0;
    if(sm==0 || sm==2 || sm==1 || sm==3)        VV=analysis->getDiBoson();
    if(sm==4)                                   VV=analysis->getDiBosonVBFHCP();
    VV->SetName("VV");

    TH1F* ZLL=(TH1F*)ZL->Clone("ZLL");
    ZLL->SetName("ZLL");
    ZLL->Add(ZJ);

    //blind
    TString tmpsel=analysis->extrasel_;
    if(Blind)analysis->extrasel_ += "*(svfitmass<100||160<svfitmass)"; 
    TH1F* data_obs = analysis->getTotalData();
    data_obs->SetName("data_obs");
    analysis->extrasel_ =tmpsel;



    TH1F* MC=(TH1F*)ZTT->Clone("MC");//needed below
    MC->Add(ZL);
    MC->Add(ZJ);
    MC->Add(W);
    MC->Add(TT);
    MC->Add(VV);
    MC->Add(QCD);


    dir->cd();
  
    
    fix0Bins(ZTT); ZTT->Write(); 
    ZTT->SetName("ZTT125"); ZTT->Write();//needed for ZTT fits
    fix0Bins(ZL);  ZL->Write();
    fix0Bins(ZJ);  ZJ->Write();
    fix0Bins(ZLL); ZLL->Write();
    fix0Bins(W);   W->Write();
    fix0Bins(TT);  TT->Write();
    fix0Bins(VV);  VV->Write();
    fix0Bins(QCD); QCD->Write();
    data_obs->Write();
 
    gROOT->cd();
    
    delete ZTT ;
    delete ZL;
    delete ZJ;
    delete ZLL;
    delete W;
    delete TT;
    delete VV;
    delete QCD;

 
    for(Int_t m=0;m<NMASS;m++){
      long ma=massValues[m];

      //Nominal h 
      TH1F* SM = analysis->getSample(TString("HiggsGG")+ma);
      SM->SetName(TString("ggH")+ma);

      TH1F* VBF = analysis->getSample(TString("HiggsVBF")+ma);
      VBF->SetName(TString("qqH")+ma);

      TH1F* VH = analysis->getSample(TString("HiggsVH")+ma);
      VH->SetName(TString("VH")+ma);

      SM->Scale(1./analysis->findSample(TString("HiggsGG")+ma)->getCrossection());
      VBF->Scale(1./analysis->findSample(TString("HiggsVBF")+ma)->getCrossection());
      VH->Scale(1./analysis->findSample(TString("HiggsVH")+ma)->getCrossection());
      
      //check for empty histos
      if( SM->Integral()<=0.){  SM->SetBinContent(SM->GetNbinsX()/2,1e-4);    SM->SetBinError(SM->GetNbinsX()/2,1e-4); }
      if( VBF->Integral()<=0.){ VBF->SetBinContent(VBF->GetNbinsX()/2,1e-4);  VBF->SetBinError(VBF->GetNbinsX()/2,1e-4); }
      if( VH->Integral()<=0.){  VH->SetBinContent(VH->GetNbinsX()/2,1e-4);    VH->SetBinError(VH->GetNbinsX()/2,1e-4); }

      dir->cd();
      
     
      
      fixSignal(data_obs,MC,VH);  fix0Bins(VH);   VH->Write();
      fixSignal(data_obs,MC,SM);  fix0Bins(SM);   SM->Write();
      fixSignal(data_obs,MC,VBF); fix0Bins(VBF);  VBF->Write();
      gROOT->cd();

      delete VH;
      delete SM;
      delete VBF;

    }

    delete MC;
    delete data_obs;

  }
  
  output.ls();
  output.Close();
  gROOT->ProcessLine(".q");
}
コード例 #23
0
int main(void)
{
	gStyle->SetOptStat(1111);
	TDirectory *locTopDirectory = gDirectory;

	//Goto Beam Path
	TDirectory *locDirectory = (TDirectory*)gDirectory->FindObjectAny("RF");
	if(!locDirectory)
		return 0;
	locDirectory->cd();

	//Get RF DeltaT Histograms
	gDirectory->cd("RF_SignalPeriod");
	TH1I* locHist_FDCRF_SignalPeriod = (TH1I*)gDirectory->Get("FDCRF_SignalPeriod");
	TH1I* locHist_TOFRF_SignalPeriod = (TH1I*)gDirectory->Get("TOFRF_SignalPeriod");
	TH1I* locHist_TAGHRF_SignalPeriod = (TH1I*)gDirectory->Get("TAGHRF_SignalPeriod");
	TH1I* locHist_PSCRF_SignalPeriod = (TH1I*)gDirectory->Get("PSCRF_SignalPeriod");

	//Get/Make Canvas
	TCanvas *locCanvas = NULL;
	if(TVirtualPad::Pad() == NULL)
		locCanvas = new TCanvas("RF_SignalPeriod", "RF_SignalPeriod", 1200, 800); //for testing
	else
		locCanvas = gPad->GetCanvas();
	locCanvas->Divide(2, 2);

	//Draw
	locCanvas->cd(1);
	gPad->SetTicks();
	gPad->SetGrid();
	if(locHist_TOFRF_SignalPeriod != NULL)
	{
		TH1I* locHist = locHist_TOFRF_SignalPeriod;
		locHist->GetXaxis()->SetTitleSize(0.05);
		locHist->GetYaxis()->SetTitleSize(0.05);
		locHist->GetXaxis()->SetLabelSize(0.05);
		locHist->GetYaxis()->SetLabelSize(0.05);
		locHist->Draw();
	}

	locCanvas->cd(2);
	gPad->SetTicks();
	gPad->SetGrid();
	if(locHist_TAGHRF_SignalPeriod != NULL)
	{
		TH1I* locHist = locHist_TAGHRF_SignalPeriod;
		locHist->GetXaxis()->SetTitleSize(0.05);
		locHist->GetYaxis()->SetTitleSize(0.05);
		locHist->GetXaxis()->SetLabelSize(0.05);
		locHist->GetYaxis()->SetLabelSize(0.05);
		locHist->Draw();
	}

	locCanvas->cd(3);
	gPad->SetTicks();
	gPad->SetGrid();
	if(locHist_PSCRF_SignalPeriod != NULL)
	{
		TH1I* locHist = locHist_PSCRF_SignalPeriod;
		locHist->GetXaxis()->SetTitleSize(0.05);
		locHist->GetYaxis()->SetTitleSize(0.05);
		locHist->GetXaxis()->SetLabelSize(0.05);
		locHist->GetYaxis()->SetLabelSize(0.05);
		locHist->Draw();
	}

	locCanvas->cd(4);
	gPad->SetTicks();
	gPad->SetGrid();
	if(locHist_FDCRF_SignalPeriod != NULL)
	{
		TH1I* locHist = locHist_FDCRF_SignalPeriod;
		locHist->GetXaxis()->SetTitleSize(0.05);
		locHist->GetYaxis()->SetTitleSize(0.05);
		locHist->GetXaxis()->SetLabelSize(0.05);
		locHist->GetYaxis()->SetLabelSize(0.05);
		locHist->Draw();
	}
}
コード例 #24
0
ファイル: PlotOmega_dmsOmega.C プロジェクト: cmenpgroup/jlab
// 
// PlotOmega_CutIndex - plot omega inv. mass for a specific cut selection
//                  
//                  fAna = output from eg2a DMS
//                  tgtIndex = target index
//                  bankIndex = bank name
//                  chanLo = lower bin
//                  chanHi = upper bin
//
void PlotOmega_CutIndex(char *fAna, Int_t histIndex =0, Int_t tgtIndex = 0, Int_t bankIndex = 0, Int_t chanLo = 0, Int_t chanHi=0)
{
    Int_t i;
    char OutCan[100];
    char strname[100];
    char hname[50];
    char title[100];
    char strname[100];
    char legLabel[50];
    
    TH1D *h1D[10];
    
    Check_HistIndex(histIndex);
    Check_TgtIndex(tgtIndex);
    Check_BankIndex(bankIndex);
    Check_CutIndex(chanLo);
    Check_CutIndex(chanHi);
    Check_CutLoHi(chanLo,chanHi);
    
	// Canvas to plot histogram
	TCanvas *c1 = new TCanvas("c1","c1",0,0,600,600);
	c1->SetBorderMode(1);  //Bordermode (-1=down, 0 = no border, 1=up)
	c1->SetBorderSize(5); 
	gStyle->SetOptStat(0);
	c1->SetFillStyle(4000);
	
	// data files contain the trees
	printf("Analyzing file %s\n",fAna);  
	TFile *fm = new TFile(fAna,"READ");
    TDirectory *tmp = fm->GetDirectory(TgtName[tgtIndex]);
    
	c1->cd();
	gPad->SetLeftMargin(Lmar);
	gPad->SetRightMargin(Rmar);
	gPad->SetFillColor(0);
    
    TLegend *leg = new TLegend(0.6,0.5,1.0,0.875);
    
    sprintf(hname,"%s%s",HistName[histIndex],TgtName[tgtIndex]);
	TH2D *h2D = (TH2D*)tmp->Get(hname);
    
    for(i=chanLo; i<chanHi+1; i++){
        sprintf(strname,"%s_%i",hname,i);
        h1D[i] = (TH1D*)h2D->ProjectionX(strname,i+1,i+1,"");
    
        sprintf(title,"Target: %s",TgtName[tgtIndex]);
        h1D[i]->SetTitle(title);
        h1D[i]->GetXaxis()->CenterTitle();
        h1D[i]->GetYaxis()->CenterTitle();
        h1D[i]->GetYaxis()->SetTitle("Counts");
        h1D[i]->GetYaxis()->SetTitleOffset(yoff);
        h1D[i]->SetLineWidth(2);
        if(chanLo!=chanHi) h1D[i]->SetLineColor(lcol[i]);
        h1D[i]->Draw(fSame[i]);
        
        sprintf(legLabel,"%s",CutName[i]);
        leg->AddEntry(h1D[i],legLabel,"l");
    }
    
    leg->SetLineColor(0);
    leg->SetFillStyle(0);
    leg->SetHeader(legHeader[histIndex]);
    leg->Draw();
    
	sprintf(OutCan,"PlotOmega_%s_%s_%i_%i.gif",hname,BankName[bankIndex],chanLo,chanHi);
	c1->Print(OutCan);
	sprintf(OutCan,"PlotOmega_%s_%s_%i_%i.eps",hname,BankName[bankIndex],chanLo,chanHi);
	c1->Print(OutCan);
}
コード例 #25
0
ファイル: dumpCats.C プロジェクト: janveverka/MitHgg
//_____________________________________________________________________________
void dumpCats(bool debug, TString fileName, TString dirName,
              bool smearMassError) {
 
  TFile* file = TFile::Open(fileName.Data());
  TDirectory* theDir = (TDirectory*) file->FindObjectAny(dirName.Data());
  TTree* theTree = (TTree*) theDir->Get("hPhotonTree");

  UInt_t run, lumi, evt;
  float rho, mass;
  Int_t tth, vhLep, vhMet, vhHad, vbf, cat;


  theTree->SetBranchAddress("run", &run);
  theTree->SetBranchAddress("lumi",&lumi);
  theTree->SetBranchAddress("evt", &evt);

  theTree->SetBranchAddress("mass",&mass);
  theTree->SetBranchAddress("rho",&rho);

  theTree->SetBranchAddress("tthTag",&tth);
  theTree->SetBranchAddress("VHLepTag",&vhLep);
  theTree->SetBranchAddress("VHHadTag",&vhHad);
  theTree->SetBranchAddress("vbfTag",&vbf);
  
  float ph1e, ph1pt, ph1eerr, ph1eerrsmeared, teta1, phi1;
  float ph2e, ph2pt, ph2eerr, ph2eerrsmeared, teta2, phi2;

  theTree->SetBranchAddress("ph1.pt",&ph1pt);
  theTree->SetBranchAddress("ph1.e",&ph1e);
  theTree->SetBranchAddress("ph1.eerr",&ph1eerr);
  theTree->SetBranchAddress("ph1.eerrsmeared",&ph1eerrsmeared);
  theTree->SetBranchAddress("ph1.eta",&teta1);
  theTree->SetBranchAddress("ph1.phi",&phi1);

  theTree->SetBranchAddress("ph2.pt",&ph2pt);
  theTree->SetBranchAddress("ph2.e",&ph2e);
  theTree->SetBranchAddress("ph2.eerr",&ph2eerr);
  theTree->SetBranchAddress("ph2.eerrsmeared",&ph2eerrsmeared);
  theTree->SetBranchAddress("ph2.eta",&teta2);
  theTree->SetBranchAddress("ph2.phi",&phi2);

  Float_t ele1_pt, ele1_eta;
  Float_t mu1_pt, mu1_eta;
  
  theTree->SetBranchAddress("elePt"  , &ele1_pt );
  theTree->SetBranchAddress("eleEta" , &ele1_eta);
  theTree->SetBranchAddress("muonPt" , &mu1_pt  );
  theTree->SetBranchAddress("muonEta", &mu1_eta );
  
  float jet1pt, jet1eta, jet1phi;
  float jet2pt, jet2eta, jet2phi;

  theTree->SetBranchAddress("jet1pt",&jet1pt);
  theTree->SetBranchAddress("jet1eta",&jet1eta);
  theTree->SetBranchAddress("jet1phi",&jet1phi);
  theTree->SetBranchAddress("jet2pt",&jet2pt);
  theTree->SetBranchAddress("jet2eta",&jet2eta);
  theTree->SetBranchAddress("jet2phi",&jet2phi);

  float masserr, masserrwvtx, masserr_ns, masserrwvtx_ns, vtxprob, idmva_1, idmva_2;
  theTree->SetBranchAddress("masserrsmeared",&masserr);
  theTree->SetBranchAddress("masserrsmearedwrongvtx",&masserrwvtx);
  theTree->SetBranchAddress("masserr",&masserr_ns);
  theTree->SetBranchAddress("masserrwrongvtx",&masserrwvtx_ns);
  theTree->SetBranchAddress("vtxprob",&vtxprob);
  theTree->SetBranchAddress("ph1.idmva",&idmva_1);
  theTree->SetBranchAddress("ph2.idmva",&idmva_2);

  // MET tag stuff
  float corrpfmet, corrpfmetphi, pfmet, pfmetphi;
  theTree->SetBranchAddress("corrpfmet",&corrpfmet);
  theTree->SetBranchAddress("corrpfmetphi",&corrpfmetphi);
  theTree->SetBranchAddress("pfmet",&pfmet);
  theTree->SetBranchAddress("pfmetphi",&pfmetphi);

  float phigg, jetleadNoIDpt, jetleadNoIDphi, jetleadNoIDeta;
  float ph1sceta, ph1scphi;
  float ph2sceta, ph2scphi;

  theTree->SetBranchAddress("phigg",&phigg);
  theTree->SetBranchAddress("jetleadNoIDpt",&jetleadNoIDpt);
  theTree->SetBranchAddress("jetleadNoIDphi",&jetleadNoIDphi);
  theTree->SetBranchAddress("jetleadNoIDeta",&jetleadNoIDeta);

  theTree->SetBranchAddress("ph1.sceta",&ph1sceta);
  theTree->SetBranchAddress("ph1.scphi",&ph1scphi);

  theTree->SetBranchAddress("ph2.sceta",&ph2sceta);
  theTree->SetBranchAddress("ph2.scphi",&ph2scphi);
 

  // Setup the diphoton BDT
  Float_t rVtxSigmaMoM, wVtxSigmaMoM, cosDPhi;
  Float_t pho1_ptOverM;
  Float_t pho2_ptOverM;
  Float_t diphoMVA;
  
  TMVA::Reader* reader = new TMVA::Reader("Silent");
  reader->AddVariable("masserrsmeared/mass"        , &rVtxSigmaMoM);
  reader->AddVariable("masserrsmearedwrongvtx/mass", &wVtxSigmaMoM);
  reader->AddVariable("vtxprob"                    , &vtxprob     );
  reader->AddVariable("ph1.pt/mass"                , &pho1_ptOverM);
  reader->AddVariable("ph2.pt/mass"                , &pho2_ptOverM);
  reader->AddVariable("ph1.eta"                    , &teta1       );
  reader->AddVariable("ph2.eta"                    , &teta2       );
  reader->AddVariable("TMath::Cos(ph1.phi-ph2.phi)", &cosDPhi     );
  reader->AddVariable("ph1.idmva"                  , &idmva_1     );
  reader->AddVariable("ph2.idmva"                  , &idmva_2     );
  const char *diphotonWeights = (
    "/home/veverka/cms/cmssw/031/CMSSW_5_3_10_patch1/src/MitPhysics/data/"
    "HggBambu_SMDipho_Oct01_redqcdweightallsigevenbkg_BDTG.weights.xml"
    );
  reader->BookMVA("BDTG", diphotonWeights);

  TRandom3 rng(0);

  int eventCounter=0;

  // Loop over the entries.
  std::cout << "Looping over " << theTree->GetEntries() << " entries." << std::endl;
  for (int i=0; i < theTree->GetEntries(); ++i) {
   
    if (eventCounter > 9 && debug ) break;
    if (debug) {
      cout << "Processing entry " << i << " :" << endl
           << "    mass:   " << mass << endl
           << "    ph1pt:  " << ph1pt << endl
           << "    ph2pt:  " << ph2pt << endl
           << "    idmva_1:" << idmva_1 << endl
           << "    idmva_2:" << idmva_2 << endl;
    }
    
    theTree->GetEntry(i);

    // MET category
    vhMet = 0;
    double dEtaJPh1 = ph1sceta - jetleadNoIDeta;
    double dPhiJPh1 = TMath::ACos(TMath::Cos(ph1scphi - jetleadNoIDphi));
    double dRJPh1 = TMath::Sqrt(TMath::Power(dEtaJPh1, 2) +
                                TMath::Power(dPhiJPh1, 2));
    double dEtaJPh2 = ph2sceta - jetleadNoIDeta;
    double dPhiJPh2 = TMath::ACos(TMath::Cos(ph2scphi - jetleadNoIDphi));
    double dRJPh2 = TMath::Sqrt(TMath::Power(dEtaJPh2, 2) +
                                TMath::Power(dPhiJPh2, 2));
    double dPhiMetGG = TMath::ACos(TMath::Cos(phigg - corrpfmetphi));
    double dPhiMetJet = TMath::ACos(
             TMath::Cos(TMath::Abs(jetleadNoIDphi - corrpfmetphi))
             );
    if (TMath::Abs(ph1sceta) < 1.4442 &&
        TMath::Abs(ph2sceta) < 1.4442 &&
        corrpfmet > 70. &&
        ph1pt/mass > 45./120. &&
        dPhiMetGG > 2.1 &&
        (
          jetleadNoIDpt < 50. ||
          dRJPh1 < 0.5 ||
          dRJPh2 < 0.5 ||
          dPhiMetJet < 2.7
        ) &&
        ph2pt > mass/4) {
       vhMet = 1;
    }

    // Calculate needed variables for the diphoMVA
    if (smearMassError) {
      rVtxSigmaMoM = masserr / mass;          // with smearing
      wVtxSigmaMoM = masserrwvtx / mass;      // with smearing
    } else {
      rVtxSigmaMoM = masserr_ns / mass;       // no smearing
      wVtxSigmaMoM = masserrwvtx_ns / mass;   // no smearing
    }
    cosDPhi = TMath::Cos(phi1 - phi2);
    pho1_ptOverM = ph1pt / mass;
    pho2_ptOverM = ph2pt / mass;
    diphoMVA = reader->EvaluateMVA("BDTG");

    bool passPreselection = (mass > 100 &&
                             mass < 180 &&
                             ph1pt > mass/3 &&
                             ph2pt > mass/4 &&
                             idmva_1 > -0.2 &&
                             idmva_2 > -0.2);

    if (passPreselection == false) {
      if (debug) {
        cout << "    passPreselection: " << passPreselection << endl;
      }
      continue;
    }

    if (debug) {
      cout << "    ... passed preselection." << endl;
    }

    eventCounter++;
    if      (tth   == 1) tth = 2;
    else if (tth   == 2) tth = 1;

    if      (vhHad == 2) vhHad = 1;

    cat = kIncl0;
    if      (tth   == 2) cat = kTTHLep;
    else if (vhLep == 2) cat = kVHLepTight;
    else if (vhLep == 1) cat = kVHLepLoose;
    else if (vbf   >  0) cat = kDijet0;
    else if (vhMet == 1) cat = kVHMet;
    else if (tth   == 1) cat = kTTHHad;
    else if (vhHad == 1) cat = kVHHad;

    // if (cat == kIncl0 && diphoMVA < -0.4) continue;
    
    // Event Variables
    dumpVar("run"                    , run                    ); //  1
    dumpVar("lumi"                   , lumi                   ); //  2
    dumpVar("event"                  , evt                    ); //  3

    dumpVar("cat"                    , cat                    );
    dumpVar("tth"                    , tth                    );
    dumpVar("vhLep"                  , vhLep                  );
    dumpVar("vhMet"                  , vhMet                  );
    dumpVar("vhHad"                  , vhHad                  );
    dumpVar("vbf"                    , vbf                    );


    // Leading Photon Variables
    dumpVar("pho1_e"                 , ph1e                   ); // 10
    dumpVar("pho1_eErr"              , ph1eerr                ); // 11
    dumpVar("pho1_eta"               , teta1                  ); //  8
    dumpVar("pho1_phi"               , phi1                   ); //  9
    dumpVar("pho1_idMVA"             , idmva_1                );

    // Trailing Photon Variables
    dumpVar("pho2_e"                 , ph2e                   ); // 36
    dumpVar("pho2_eErr"              , ph2eerr                ); // 37
    dumpVar("pho2_eta"               , teta2                  ); // 34
    dumpVar("pho2_phi"               , phi2                   ); // 35
    dumpVar("pho2_idMVA"             , idmva_2                );

    // Diphoton Variables
    dumpVar("mass"                   , mass                   );
    dumpVar("met"                    , corrpfmet              );
    dumpVar("met_phi"                , corrpfmetphi           );
    dumpVar("uncorrMet"              , pfmet                  );
    dumpVar("uncorrMet_phi"          , pfmetphi               );
    dumpVar("diphoMVA"               , diphoMVA               );

    // Muon Variables
    if (mu1_pt < 0) {
      mu1_pt = -999;
      mu1_eta = -999;
    }
    dumpVar("mu1_pt"                , mu1_pt                 );
    dumpVar("mu1_eta"               , mu1_eta                );

    // Electron Variables
    if (ele1_pt < 0) {
      ele1_pt = -999;
      ele1_eta = -999;
    }
    dumpVar("ele1_pt"                , ele1_pt                 );
    dumpVar("ele1_eta"               , ele1_eta                );

    
    // Leading Jet Variables
    if (jet1pt < 0) {
      jet1pt = -999;
      jet1eta = -999;
    }
    dumpVar("jet1_pt"                , jet1pt                 ); // 69
    dumpVar("jet1_eta"               , jet1eta                ); // 70
    dumpVar("jet1_phi"               , jet1phi                ); // 70

    // Trailing Jet Variables
    if (jet2pt < 0) {
      jet2pt = -999;
      jet2eta = -999;
    }
    dumpVar("jet2_pt"                , jet2pt                 ); // 72
    dumpVar("jet2_eta"               , jet2eta                ); // 73
    dumpVar("jet2_phi"               , jet2phi                ); // 70

    std::cout << std::endl;
  } // Loop over the tree entries.
  
  return;

} // void dumpMvaInputs(bool debug, TString fileName)
コード例 #26
0
int doHistAnalysis () {
    
    // plot options
    gStyle->SetOptFit(111111111);
    gStyle->SetOptStat(11111111);
    
    // paths to files
    string Bfile_path = "rootfiles/DataScouting_V00-01-06_Run2012B_runrange_193752-197044_dijet_alfaT_razor_dijetpairs_trijetpairs.root";
    string Cfile_path = "rootfiles/DataScouting_V00-01-06_Run2012C_runrange_197885-203755_dijet_alfaT_razor_dijetpairs_trijetpairs.root";
    string Dfile_path = "rootfiles/DataScouting_V00-01-06_Run2012D_runrange_203773-208686_dijet_alfaT_razor_dijetpairs_trijetpairs.root";
    string BCDfile_path = "rootfiles/DataScouting_V00-01-06_Run2012B_Run2012C_Run2012D_runrange_193752-208686_dijet_alfaT_razor_dijetpairs_trijetpairs.root";
    string histPath = "DQMData/Run 999999/DataScouting/Run summary/DiJet";
    string mjj_histName = "h1_MjjWide_finalSel_varbin;1"; // use VARIABLE BINS
    //string mjj_histName = "h1_MjjWide_finalSel;1"; // use 1 GEV BINS
    
    // luminosities, as given on the twiki
    double BLum_fb = 4.445, CLum_fb = 6.806, DLum_fb = 7.384; // in inverse fb
    double BCDLum_fb = BLum_fb + CLum_fb + DLum_fb;
    double BLum_pb = BLum_fb * 1e3;
    double CLum_pb = CLum_fb * 1e3;
    double DLum_pb = DLum_fb * 1e3;
    double BCDLum_pb = BCDLum_fb * 1e3; // converts to inverse pb
    
    // read in the files and get histograms
    TFile * Bfile = new TFile (Bfile_path.c_str());
    TDirectory * BHistDir = Bfile->GetDirectory(histPath.c_str());
    TH1D * BmjjHist = (TH1D*)BHistDir->Get(mjj_histName.c_str());
    BmjjHist->SetName("RunB dijet mass");
    BmjjHist->SetTitle("RunB dijet mass");
    
    TFile * Cfile = new TFile (Cfile_path.c_str());
    TDirectory * CHistDir = Cfile->GetDirectory(histPath.c_str());
    TH1D * CmjjHist = (TH1D*)CHistDir->Get(mjj_histName.c_str());
    CmjjHist->SetName("RunC dijet mass");
    CmjjHist->SetTitle("RunC dijet mass");
    
    TFile * Dfile = new TFile (Dfile_path.c_str());
    TDirectory * DHistDir = Dfile->GetDirectory(histPath.c_str());
    TH1D * DmjjHist = (TH1D*)DHistDir->Get(mjj_histName.c_str());
    DmjjHist->SetName("RunD dijet mass");
    DmjjHist->SetTitle("RunD dijet mass");
    
    TFile * BCDfile = new TFile (BCDfile_path.c_str());
    TDirectory * BCDHistDir = BCDfile->GetDirectory(histPath.c_str());
    TH1D * BCDmjjHist = (TH1D*)BCDHistDir->Get(mjj_histName.c_str());
    BCDmjjHist->SetName("RunsBCD dijet mass");
    BCDmjjHist->SetTitle("RunsBCD dijet mass");
    
    // read out into memory and close the files
    TFile * writefile = new TFile("fTestHists.root","recreate");
    BmjjHist->SetDirectory(writefile);
    CmjjHist->SetDirectory(writefile);
    DmjjHist->SetDirectory(writefile);
    BCDmjjHist->SetDirectory(writefile);
    Bfile->Close();
    Cfile->Close();
    Dfile->Close();
    BCDfile->Close();
    
    // normalise histograms
    NormaliseByLuminosity(BmjjHist, BLum_pb);
    NormaliseByBinWidth(BmjjHist);
    NormaliseByLuminosity(CmjjHist, CLum_pb);
    NormaliseByBinWidth(CmjjHist);
    NormaliseByLuminosity(DmjjHist, DLum_pb);
    NormaliseByBinWidth(DmjjHist);
    NormaliseByLuminosity(BCDmjjHist, BCDLum_pb);
    NormaliseByBinWidth(BCDmjjHist);
    
    // make ratio histograms
    TH1D * BCratio = (TH1D*)BmjjHist->Clone();
    BCratio->Divide(CmjjHist);
    BCratio->SetName("B/C ratio");
    BCratio->SetTitle("B/C ratio");
    
    TH1D * BDratio = (TH1D*)BmjjHist->Clone();
    BDratio->Divide(DmjjHist);
    BDratio->SetName("B/D ratio");
    BDratio->SetTitle("B/D ratio");
    
    TH1D * CDratio = (TH1D*)CmjjHist->Clone();
    CDratio->Divide(DmjjHist);
    CDratio->SetName("C/D ratio");
    CDratio->SetTitle("C/D ratio");
    
    // choose the range to do the fit in
    Float_t fitRangeLow = 270.;
    Float_t fitRangeHigh = 3000.;
    
    // set plot ranges
    BmjjHist->SetAxisRange(500, 3000, "X");
    CmjjHist->SetAxisRange(500, 3000, "X");
    DmjjHist->SetAxisRange(500, 3000, "X");
    BCDmjjHist->SetAxisRange(fitRangeLow, fitRangeHigh, "X");
    
    // write these histograms to file
    writefile->Write();
    
    // F-test loop
    // repeat until the F-test is satisfied
    int nBasePars = 4;
    int nExtraPars = 0;
    float RSSold = 0;
    float RSS = 0;
    int stopTest = 0;
    while (stopTest == 0) {
        // get number of fit parameters
        // (one of the parameters holds the number of parameters... tricky!)
        int nTotalPars = 1 + nBasePars + nExtraPars;

        // set the name of the fit/histogram
        std::ostringstream s;
        s << "FTest" << nExtraPars;
        string fitNameStr = s.str();
        
        // make a canvas to put fit and residual on
        TCanvas* canvas = new TCanvas((fitNameStr + "-canv").c_str(), (fitNameStr + "-canv").c_str(), 800, 600);
        canvas->cd();
        
        //create 3 pads in the canvas
        TPad* fPads1 = NULL;
        TPad* fPads2 = NULL;

        fPads1 = new TPad("pad1", "", 0.00, 0.20, 0.99, 0.99);
        fPads2 = new TPad("pad3", "", 0.00, 0.00, 0.99, 0.20);
        fPads1->SetFillColor(0);
        fPads1->SetLineColor(0);
        fPads2->SetFillColor(0);
        fPads2->SetLineColor(0);
        fPads1->Draw();
        fPads2->Draw();
        
        // make a new histogram to do the fit on
        fPads1->cd();
        TH1D * fitHist = new TH1D;
        fitHist = BCDmjjHist;
        fitHist->SetName(fitNameStr.c_str());

        // set up the background fit
        TF1 *bkfit = new TF1(fitNameStr.c_str(),BackgroundShape, fitRangeLow, fitRangeHigh, nTotalPars);
        bkfit->SetParName(0,"nPar");
        for (int i=1;i<nTotalPars;++i) {
            std::ostringstream p;
            p << "P" << i-1;
            string parNameStr = p.str();
            bkfit->SetParName(i,parNameStr.c_str());
        }
        
        // set the initial parameter values
        bkfit->FixParameter(0,nTotalPars*1.); // number of parameters does not change!
        bkfit->SetParameter(0+1,2.6e-06); // P0
        bkfit->SetParameter(1+1,5.8); // P1
        bkfit->SetParameter(2+1,6.7); // P2
        bkfit->SetParameter(3+1,0.3); // P3
        for (int i=nBasePars+1;i<nTotalPars;++i) {
            // all others to zero
            bkfit->SetParameter(i+1,0.0);
        }
        
        // Fit and get parameters
        fitHist->Fit(bkfit,"IM"); // MRQ (M=improve, R=use fn range, Q=quiet, I=integral, L=likelihood)
        Double_t * params = bkfit->GetParameters();
        fitHist->Write();
        fitHist->SetDirectory(0);
        
        // Make new TGraph for the residual plot
        fPads2->cd();
        TVectorD nsigma_x(fitHist->GetNbinsX()); 
        TVectorD nsigma_y(fitHist->GetNbinsX()); 
      
        for(int i = 1; i <= fitHist->GetNbinsX(); ++i) {
            double binLow = fitHist->GetXaxis()->GetBinLowEdge(i);
            double binHigh = fitHist->GetXaxis()->GetBinUpEdge(i);
            double exp = fitHist->GetBinContent(i);
            double obs = bkfit->Integral(binLow, binHigh, params) / (binHigh - binLow);
            double error = fitHist->GetBinError(i);
            double x = fitHist->GetBinCenter(i);
            
            double diff = obs - exp;
            double sigma = sqrt(error*error);
        
            if (sigma != 0.0 && obs != 0.0 ) {
                nsigma_x[i] = x;
                nsigma_y[i] = diff / sigma;
            } else {
                nsigma_x[i] = +999999;
                nsigma_y[i] = 0;
            }       
        }
        
        // plot the graph of residuals 
        if (nsigma_x.GetNoElements() != 0 ) {
            TGraph *nsigmaGraph = new TGraph(nsigma_x,nsigma_y);
            nsigmaGraph->SetName((fitNameStr+"-resid").c_str());
            nsigmaGraph->SetTitle("");
            nsigmaGraph->GetYaxis()->SetRangeUser(-5,5);
            nsigmaGraph->GetYaxis()->SetTitle("(Data-Fit)/#sigma");
            nsigmaGraph->GetYaxis()->SetTitleOffset(0.1);
            nsigmaGraph->GetYaxis()->SetTitleSize(0.15);
            nsigmaGraph->GetYaxis()->SetLabelSize(0.07);
            nsigmaGraph->GetXaxis()->SetTitle("");
            nsigmaGraph->GetXaxis()->SetLimits(fitRangeLow, fitRangeHigh);
            nsigmaGraph->GetXaxis()->SetRangeUser(fitRangeLow, fitRangeHigh);
            nsigmaGraph->GetXaxis()->SetTitleOffset(0.01);
            nsigmaGraph->GetXaxis()->SetLabelSize(0.09);
            nsigmaGraph->SetMarkerStyle(8);
            nsigmaGraph->SetMarkerSize(0.8);
            nsigmaGraph->Draw("AP");
            nsigmaGraph->Write();
        }
        
        canvas->Write();
        
        // Get degrees of freedom
        int dof = GetNBinsInRange(fitHist, fitRangeLow, fitRangeHigh) - nTotalPars + 1;
        cout << dof << endl;
        
        // Get the RSS value between fit and histogram
        RSSold = RSS;
        RSS = GetResidualSumSquares(BCDmjjHist, bkfit, params, fitRangeLow, fitRangeHigh);
        cout << nExtraPars << endl;
        cout << RSSold << endl;
        cout << RSS << endl;
        
        if (RSSold==0) {
            // we must do it again with an extra parameter before we can do the f-test
            nExtraPars += 1;
            continue;
        }
        
        // otherwise, do a F-test
        const double alphaFTest=0.05;
        cout << "Starting F-Test evaluation with alpha = " << alphaFTest << endl;
        double fTestVal = (RSSold-RSS) * dof / RSS;
        if (fTestVal < 0) {
            // the fit got WORSE - try again!
            
            // TODO: probably look at this, as at present it will add an extra parameter
            // any time the fit worsens from the last time, even slightly.
            // Really we should only do this if the fit is significantly worse. 
            
            cout << "Fit worsened; automatically trying extra parameter\n";
            nExtraPars += 1;
            continue;
        }
        cout  << "F-test value = " << fTestVal << endl;
        double goodCL =  1.-TMath::FDistI(fTestVal,1,dof);
        cout  << "F-test CL = " << goodCL << endl;
        
        if (goodCL > alphaFTest) {
            // the fit got better but not by much - stop here
            cout << "Requires " << nExtraPars-1 << " extra parameters.\n";
            stopTest = 1;
        } else if (nExtraPars == 10) {
            // 10 extra parameters is enough for anyone
            cout << "Reached 10 extra parameters without success - aborting\n";
            stopTest = 1;
        } else {
            // it got significantly better - try still more parameters
            cout << "F-test failed; trying more parameters\n";
            nExtraPars += 1;
        }
    }
    
    // finish up
    writefile->Close();
    
    return 1;
}
コード例 #27
0
ファイル: concatenateTrees.C プロジェクト: bianchini/usercode
void makeTree(string sample = "DY", string selection = "", float Lumi = 1){

  vector<pair<string,float> > files;
  vector< TH1F* > histos;

  vector<string> directories;
  
  if(sample.find("DY")!=string::npos){
    files.push_back( make_pair("DY-madgraph-10to50.root",      (310*0.19*Lumi)  ) );
    files.push_back( make_pair("DY-madgraph-50.root",          (2289*0.56*Lumi)  ) );
  }
  
  if(sample.find("Wjets")!=string::npos){
    files.push_back( make_pair("W1Jets_ptW-0to100.root",       (3.693e+03*0.44*Lumi)  ) );
    files.push_back( make_pair("W1Jets_ptW-100to300.root",     (7.197e+01*0.58*Lumi)  ) );
    files.push_back( make_pair("W1Jets_ptW-300to800.root",     (5.658e-01*0.73*Lumi)  ) );
    files.push_back( make_pair("W2Jets_ptW-0to100.root",       (9.434e+02*0.46*Lumi)  ) );
    files.push_back( make_pair("W2Jets_ptW-100to300.root",     (6.718e+01*0.59*Lumi)  ) );
    files.push_back( make_pair("W2Jets_ptW-300to800.root",     (8.553e-01*0.75*Lumi)  ) );
    files.push_back( make_pair("W3Jets_ptW-0to100.root",       (2.087e+02*0.48*Lumi)  ) );
    files.push_back( make_pair("W3Jets_ptW-100to300.root",     (3.243e+01*0.60*Lumi)  ) );
    files.push_back( make_pair("W3Jets_ptW-300to800.root",     (6.229e-01*0.76*Lumi)  ) );
    files.push_back( make_pair("W4Jets_ptW-0to100.root",       (4.446e+01*0.50*Lumi)  ) );
    files.push_back( make_pair("W4Jets_ptW-100to300.root",     (1.138e+01*0.61*Lumi)  ) );
    files.push_back( make_pair("W4Jets_ptW-300to800.root",     (2.950e-01*0.77*Lumi)  ) );
    files.push_back( make_pair("W5Jets_ptW-0to100.root",       (1.111e+01*0.53*Lumi)  ) );
    files.push_back( make_pair("W5Jets_ptW-100to300.root",     (3.789e+00*0.65*Lumi)  ) );
    files.push_back( make_pair("W5Jets_ptW-300to800.root",     (1.565e-01*0.79*Lumi)  ) );
  }
  if(sample.find("TT")!=string::npos){
    files.push_back( make_pair("TT.root",                      (94*Lumi)  ) );
  }
  if(sample.find("QCD")!=string::npos){
    files.push_back( make_pair("QCD_Pt-0to5.root",             (4.84e+10*6.07E-07*Lumi)) );
    files.push_back( make_pair("QCD_Pt-5to15.root",            (3.68e+10*1.82E-06*Lumi)) );
    files.push_back( make_pair("QCD_Pt-15to30.root",           (8.16e+08*0.000113*Lumi)) );
    files.push_back( make_pair("QCD_Pt-30to50.root",           (5.31e+07*0.00388126*Lumi)) );
    files.push_back( make_pair("QCD_Pt-50to80.root",           (6.36e+06*0.02321727*Lumi)) );
    files.push_back( make_pair("QCD_Pt-80to120.root",          (7.84e+05*0.06100585*Lumi)) );
    files.push_back( make_pair("QCD_Pt-120to170.root",         (1.15e+05*0.11389810*Lumi)) );
    files.push_back( make_pair("QCD_Pt-170to300.root",         (2.43e+04*0.13732413*Lumi)) );
    files.push_back( make_pair("QCD_Pt-300to470.root",         (1.17e+03*0.317390358*Lumi)) );
    files.push_back( make_pair("QCD_Pt_470to600.root",         (7.02e+01*0.431763719*Lumi)) );
    files.push_back( make_pair("QCD_Pt_600to800.root",         (1.56e+01*0.508048972*Lumi)) );
    files.push_back( make_pair("QCD_Pt_800to1000.root",        (1.84e+00*0.385363968*Lumi)) );
    files.push_back( make_pair("QCD_Pt_1000to1400.root",       (3.32e-01*0.661857989*Lumi)) );
    //files.push_back( make_pair("QCD_Pt_1400to1800.root",       (1.09e-02*0.784767648*Lumi)) );
  }

  
  directories.push_back("etoTauMargLooseNoCracks80");
  directories.push_back("etoTauMargLooseNoCracks70");
  directories.push_back("etoTauMargLooseNoCracks60");
  directories.push_back("etoTauMargMediumNoCracks80");
  directories.push_back("etoTauMargMediumNoCracks70");
  directories.push_back("etoTauMargMediumNoCracks60");
  directories.push_back("etoTauMargTightNoCracks80");
  directories.push_back("etoTauMargTightNoCracks70");
  directories.push_back("etoTauMargTightNoCracks60");

  directories.push_back("etoTauSCMargNoCracks80");
  directories.push_back("etoTauSCMargNoCracks70");
  directories.push_back("etoTauSCMargNoCracks60");
    

  TFile *outFile = new TFile(("testNewWriteFromPAT_soup"+selection+".root").c_str(),"RECREATE");
  
  int numFiles = 0;

  for(unsigned int j = 0; j<directories.size(); j++){

    numFiles = 0;

    histos.clear();

    for(unsigned int i = 0; i<files.size();i++){
      histos.push_back( new TH1F(Form("h_%d",i),Form("file %s",(files[i].first).c_str()),20,40,120) );
    }

    THStack* aStack = new THStack("aStack","");
    TLegend* leg = new TLegend(0.1331269,0.5926573,0.3622291,0.8671329,NULL,"brNDC");
    leg->SetFillStyle(4000);
    leg->SetBorderSize(0);
    leg->SetFillColor(10);
    leg->SetTextSize(0.03);

    cout << "Directory " <<  directories[j] << endl;

    TChain* outChain = new TChain((directories[j]+"/fitter_tree").c_str());

    int counter = 0;
    for(unsigned int i = 0; i<files.size();i++){

      TFile *file = new TFile(("/data_CMS/cms/lbianchini/35pb/testNewWriteFromPAT_"+files[i].first).c_str(),"READ");
      if(file->IsZombie()){
	cout << "No file " << files[i].first << " is found" << endl;
	continue;
      }

      file->cd("allEventsFilter");
      TH1F* totalEvents = (TH1F*)gDirectory->Get("totalEvents");
      float readEvents = totalEvents->GetBinContent(1);

      file->cd(directories[j].c_str());
      TTree *oldTree = (TTree*) gDirectory->Get("fitter_tree");

      float scaleToNNLO = 1.0;
      if((files[i].first).find("DY")!=string::npos)    scaleToNNLO = 1.33;
      if((files[i].first).find("W")!=string::npos)     scaleToNNLO = 1.23;
      if((files[i].first).find("TT")!=string::npos)    scaleToNNLO = 1.75;
     
      int entries = std::min( (int)oldTree->GetEntries(),  
			      (int)(((files[i].second*scaleToNNLO)/readEvents)*oldTree->GetEntries()) );

      TFile *newFile = new TFile( ("/data_CMS/cms/lbianchini/35pb/testNewWriteFromPAT_"+files[i].first+"new").c_str(), "RECREATE");
      TDirectory* dir = (TDirectory*) newFile->mkdir(directories[j].c_str());
      TTree *tree = oldTree->CloneTree( entries );

      // weight for the tree: 1 if you require less than the overall tree entries, otherwise set it to L*sigma/processed 
      //float weight = std::max((double)files[i].second,1.0);
      //tree->SetWeight( weight );
      double weight;
      tree->Branch("weight", &weight,"weight/D");
      weight = std::max((double)(files[i].second/readEvents),1.0);
      tree->Fill();

      TH1F* h = new TH1F("h","",20,40,120);
      tree->Draw("mass>>h",("weight*("+selection+")").c_str());
      histos[i]->Add(h,1);
      histos[i]->SetFillColor(i+1);
      histos[i]->SetLineColor(i+1);
      //setUpHisto(histos[i],Lumi, directories[j]);
      aStack->Add( histos[i] );
      leg->AddEntry( histos[i], (files[i].first).c_str(),"F");

      dir->cd();
      tree->Write();
      newFile->Write();

      counter+=entries;

      cout << files[i].first 
	   << " ==> total entries " << oldTree->GetEntries() 
	   << " --- Required " <<  (int)(files[i].second/readEvents*oldTree->GetEntries())
	   << " --- Provided " << entries
	   <<  endl;
      std::cout << "The tree will have weight: " << weight << std::endl; 
      //outTree->CopyEntries(tree,entries);

      if(entries>0){
	int isOK =  outChain->AddFile( ("/data_CMS/cms/lbianchini/35pb/testNewWriteFromPAT_"+files[i].first+"new").c_str());
	if( isOK == 0) cout << "No linked file" << endl;
	numFiles += isOK;
      }
      cout << " outChain has " << outChain->GetEntries() 
	   << " and attached files " << numFiles
	   << endl;

      file->Close();
      newFile->Close();
      //delete h;
      delete file;
      delete newFile;
    } // file

    //outFile->cd();
    TDirectory* dir = (TDirectory*) outFile->mkdir(directories[j].c_str());
    
    TTree* outTree = (TTree*) outChain->CopyTree("");
  
    //outTree->Draw("mass");

    cout<< "Total events copied in output directory " << outTree->GetEntries() << " from requested " << counter << endl;

    dir->cd();
    outTree->Write("", TObject::kOverwrite);

    TCanvas *c1 = new TCanvas("c1","stacked mass",10,30,650,600);
    c1->SetGrid(0,0);
    c1->SetFillStyle(4000);
    c1->SetFillColor(10);
    c1->SetTicky();
    c1->SetObjectStat(0);

    aStack->Draw("HIST");

    setUpHisto( (TH1F*)aStack->GetHistogram(), Lumi, directories[j] );
    leg->SetHeader(directories[j].c_str());
    leg->Draw(); 
    c1->Write();

    for(int i = 0; i<histos.size(); i++){
      delete histos[i];
    }
    delete aStack;
    delete leg;

  }//directories

  


  outFile->Write();
  outFile->Close();
  delete outFile;

}
コード例 #28
0
ファイル: getResVsub.C プロジェクト: satan1028/HI
void getResvsub(int ispt=1){

	double theta[ntheta];
	TFile *f[nFileAll];
		
	for(int itheta=0;itheta<ntheta;itheta++)
        	theta[itheta]=itheta*TMath::Pi()/ntheta/nn;

        int nvv;
        const double *binv;

        if(ispt){             nvv = nptv;       binv = ptbinv;}
            else{             nvv = netav;          binv = etabinv;}

	string SumorProd = getenv("SUMORPROD");
	string mdir = getenv("DIR");
	ofstream fstrv;
        if(ispt){
	if(SumorProd=="Sum")fstrv.open("v_sub.txt");
	else fstrv.open("v_2_sub.txt");
        }
        else{
	if(SumorProd=="Sum")fstrv.open("v_eta_sub.txt");
	else fstrv.open("v_2_coarse_eta_sub.txt");
        }
	
	TVectorD Nevent[nbin], totmultall[nbin], totmultall_[nbin];
	TVectorD totmult[nbin], totpt[nbin],toteta[nbin];
	TVectorD totmulthisto[nbin], totmulthistocorr[nbin];
	TVectorD V_int[nbin], V_interr[nbin];
	TVectorD V_intcorr[nbin], V_intcorrerr[nbin];
	TVectorD* V_mean;
	TVectorD* deltaV_mean;
	TVectorD vmeanmean[nbin], deltavmeanmean[nbin], sigmavmeanmean[nbin], avgavgpt[nbin], avgavgeta[nbin];
	TVectorD* V[nbin]; TVectorD* chi[nbin];
	TVectorD* dDRe[nbin]; TVectorD* dDIm[nbin];
	TVectorD* dNRe[nbin][ntheta]; TVectorD* dNIm[nbin][ntheta];
	TComplex dD[nbin][ntheta], dN[nbin][ntheta][nvv];
	TVectorD avgmult[nbin];	TVectorD avgmultall;
	TVectorD avgpt[nbin],avgeta[nbin];
	TVectorD v[nbin][ntheta],vmean[nbin],deltav[nbin][ntheta],deltavmean[nbin];
	TVectorD IFILE[nbin];
	if(SumorProd=="Sum")	TFile *infile = TFile::Open("mergedV_Sum.root");
	else	TFile *infile = TFile::Open("mergedV_Prod.root");
        if(ispt){
	if(SumorProd=="Sum")TFile *fout = new TFile("mergedv_Prod_sub.root","Recreate");
	else TFile *fout = new TFile("mergedv_Prod2_sub.root","Recreate");
        }
        else{
	if(SumorProd=="Sum")TFile *fout = new TFile("mergedv_Prod_eta_sub.root","Recreate");
	else TFile *fout = new TFile("mergedv_Prod2_coarse_eta_sub.root","Recreate");
        }

	TVectorD Nevent_;       Nevent_.ResizeTo(nbin);  Nevent_.Zero();
	TH1D* hpt[nbin];
	TH1D* hpteffcorr[nbin];
	for(int ibin=0;ibin<nbin;ibin++){
        for(int ifile=0; ifile<nFileAll; ifile++){
            if(ispt){
        if(SumorProd=="Sum") f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/%s/Anav_Prod_%d.root",mdir.c_str(),ifile));
        else f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/%s/Anav_Prod2_%d.root",mdir.c_str(),ifile));
            }
            else{
        if(SumorProd=="Sum") f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6c/coarsebins/%s/Anaveta_Prod_%d.root",mdir.c_str(),ifile));
        else f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/coarsebins/%s/Anaveta_Prod2_%d.root",mdir.c_str(),ifile));
            }
        TVectorD* Nevent_t =  (TVectorD*)f[ifile]->Get(Form("Nevent"));
        Nevent_[ibin]+=(*Nevent_t)[ibin];
        f[ifile]->Close();
        }
	IFILE[ibin].ResizeTo(nsamples);
        Nevent[ibin].ResizeTo(nsamples);  Nevent[ibin].Zero();
        totmultall[ibin].ResizeTo(nsamples);      totmultall[ibin].Zero();
        totmultall_[ibin].ResizeTo(nsamples);      totmultall_[ibin].Zero();
        TDirectory *dir0 = fout->mkdir(Form("D_%d",ibin));


      	vmeanmean[ibin].ResizeTo(nvv);  vmeanmean[ibin].Zero();
        deltavmeanmean[ibin].ResizeTo(nvv);  deltavmeanmean[ibin].Zero();
       	sigmavmeanmean[ibin].ResizeTo(nvv);  sigmavmeanmean[ibin].Zero();
	avgavgpt[ibin].ResizeTo(nvv);	avgavgpt[ibin].Zero();
	avgavgeta[ibin].ResizeTo(nvv);	avgavgeta[ibin].Zero();
	V_interr[ibin].ResizeTo(nsamples);	V_interr[ibin].Zero();
	V_int[ibin].ResizeTo(nsamples);	V_int[ibin].Zero();
        if(ispt){
	V_intcorr[ibin].ResizeTo(nsamples);	V_intcorr[ibin].Zero();
	V_intcorrerr[ibin].ResizeTo(nsamples);	V_intcorrerr[ibin].Zero();
        }
        for(int isample=0;isample<nsamples;isample++){

	TVectorD Nevent0; Nevent0.ResizeTo(nbin);	Nevent0.Zero();
	avgmultall.ResizeTo(nbin);
		totmult[ibin].ResizeTo(nvv);	totmult[ibin].Zero();
                if(ispt){
		totmulthisto[ibin].ResizeTo(nvv); totmulthisto[ibin].Zero();
		totmulthistocorr[ibin].ResizeTo(nvv);totmulthistocorr[ibin].Zero();
                }
		avgmult[ibin].ResizeTo(nvv);	avgpt[ibin].ResizeTo(nvv);  avgeta[ibin].ResizeTo(nvv);
		totpt[ibin].ResizeTo(nvv);	totpt[ibin].Zero();
		toteta[ibin].ResizeTo(nvv);	toteta[ibin].Zero();
		vmean[ibin].ResizeTo(nvv);	deltavmean[ibin].ResizeTo(nvv);
		V[ibin] = (TVectorD*) infile->Get(Form("D_%d/V",ibin,isample));
		chi[ibin] = (TVectorD*) infile->Get(Form("chi",ibin,isample));
		V_mean = (TVectorD*) infile->Get(Form("Vmean",ibin,isample));
		deltaV_mean = (TVectorD*) infile->Get(Form("deltaVmean",ibin,isample));
		for(int itheta=0;itheta<ntheta;itheta++){
			v[ibin][itheta].ResizeTo(nvv);	deltav[ibin][itheta].ResizeTo(nvv);
			dD[ibin][itheta]=0;
			for(int ivbin=0;ivbin<nvv;ivbin++){
				dN[ibin][itheta][ivbin]=0;
			}
		}

        for(int ifile=0; ifile<nFileAll; ifile++){
            if(ispt){
	        if(SumorProd=="Sum") f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/%s/Anav_Prod__%d.root",mdir.c_str(),ifile));
	        else f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/%s/Anav_Prod2_%d.root",mdir.c_str(),ifile));
            }
            else{
	        if(SumorProd=="Sum") f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/coarsebins/%s/Anaveta_Prod_%d.root",mdir.c_str(),ifile));
	        else f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/coarsebins/%s/Anaveta_Prod2_%d.root",mdir.c_str(),ifile));
            }
		TVectorD* Nevent_t = (TVectorD*)f[ifile]->Get("Nevent");	
		TVectorD* totmultall_t = (TVectorD*)f[ifile]->Get("totmultall");
		Nevent0[ibin] += (*Nevent_t)[ibin];
                double start=isample*Nevent_[ibin]/nsamples;
                double end=(isample+1)*Nevent_[ibin]/nsamples;
                if(Nevent0[ibin]>start && Nevent0[ibin]<=end){
                        IFILE[ibin][isample]=(double)ifile;
                        Nevent[ibin][isample] += (*Nevent_t)[ibin];
			TVectorD* totmult_t = (TVectorD*)f[ifile]->Get(Form("totmult_%d",ibin));
			TVectorD* totpt_t = (TVectorD*)f[ifile]->Get(Form("totpt_%d",ibin));
			TVectorD* toteta_t = (TVectorD*)f[ifile]->Get(Form("toteta_%d",ibin));
			dDRe[ibin] = (TVectorD*)f[ifile]->Get(Form("dDRe_%d",ibin));
			dDIm[ibin] = (TVectorD*)f[ifile]->Get(Form("dDIm_%d",ibin));
			totmultall[ibin][isample]+=(*totmultall_t)[ibin];
			for(int ivbin=0;ivbin<nvv;ivbin++){
				totmult[ibin][ivbin]+=(*totmult_t)[ivbin];
				totpt[ibin][ivbin]+=(*totpt_t)[ivbin];
				toteta[ibin][ivbin]+=(*toteta_t)[ivbin];
			}
			for(int itheta=0;itheta<ntheta;itheta++){
				dNRe[ibin][itheta] = (TVectorD*)f[ifile]->Get(Form("dNRe_%d_%d",ibin,itheta));
				dNIm[ibin][itheta] = (TVectorD*)f[ifile]->Get(Form("dNIm_%d_%d",ibin,itheta));
				dD[ibin][itheta]+=TComplex((*dDRe[ibin])[itheta],(*dDIm[ibin])[itheta]);
				for(int ivbin=0;ivbin<nvv;ivbin++){
					if(ifile<188) dN[ibin][itheta][ivbin]+=TComplex((*dNRe[ibin][itheta])[ivbin],(*dNIm[ibin][itheta])[ivbin]);
                                        else dN[ibin][itheta][nvv-ivbin-1]+=TComplex((*dNRe[ibin][itheta])[ivbin],(*dNIm[ibin][itheta])[ivbin]);
                                }
			}
		}
	f[ifile]->Close();
	}
	
	TFile *fhisto = TFile::Open("histomerged.root");
	TFile *feff = TFile::Open("/home/xuq7/HI/flow/LYZ/v2/TrackCorrections_HIJING_538_OFFICIAL_Mar24.root");
	TH2F* heff = (TH2F*)feff->Get("rTotalEff3D");
      	TH1D* hpteff = (TH1D*)heff->ProjectionY("hpteff",heff->GetXaxis()->FindBin(-2.4),heff->GetXaxis()->FindBin(2.4)-1,"o");
	TArrayD *ptarr = (TArrayD*)heff->GetYaxis()->GetXbins();
	double *ptbinhisto = ptarr->GetArray();
	int NbinX = heff->GetXaxis()->GetNbins();
	int NbinY = heff->GetYaxis()->GetNbins();
	hpteff->Scale(1.0/NbinX);
        
		for(int itheta=0;itheta<ntheta;itheta++)
			dD[ibin][itheta]*=TComplex::Power(TComplex::I(),mm-1)/(Double_t)Nevent[ibin][isample];
	
		avgmultall[ibin]=1.0*totmultall[ibin][isample]/Nevent[ibin][isample];
                hpt[ibin] = (TH1D*)fhisto->Get(Form("D_%d/hpt",ibin));
                //TH1D* hptre = (TH1D*)hpt[ibin]->Rebin(NbinY,"hptre",ptbinhisto);
                //hpteffcorr[ibin] = (TH1D*)hptre->Clone(Form("hpteffcorr_%d",ibin));
                //hpteffcorr[ibin]->Divide(hpteff);
		for(int ivbin=0;ivbin<nvv; ivbin++){
			vmean[ibin][ivbin]=0;
			deltavmean[ibin][ivbin]=0;
			avgmult[ibin][ivbin]=1.0*totmult[ibin][ivbin]/Nevent[ibin][isample];
			avgpt[ibin][ivbin]=1.0*totpt[ibin][ivbin]/totmult[ibin][ivbin];
			avgeta[ibin][ivbin]=1.0*toteta[ibin][ivbin]/totmult[ibin][ivbin];
			for(int itheta=0;itheta<ntheta;itheta++){
				dN[ibin][itheta][ivbin]/=totmult[ibin][ivbin];
				TComplex Res=dN[ibin][itheta][ivbin]/dD[ibin][itheta];
				v[ibin][itheta][ivbin]=(*V[ibin])[itheta]*avgmultall[ibin]*TMath::BesselJ1(j01)/Besselj01(mm)*Res.Re();
				vmean[ibin][ivbin]+=v[ibin][itheta][ivbin];
				deltav[ibin][itheta][ivbin]=TMath::Cos(mm*nn*theta[itheta])/totmult[ibin][ivbin]*(TMath::Exp(j01*j01/2./(*chi[ibin])[0]/(*chi[ibin])[0]*TMath::Cos(nn*theta[itheta]))*TMath::BesselJ0(2*j01*TMath::Sin(nn*theta[itheta]/2.))+TMath::Power(-1,mm)*TMath::Exp(-j01*j01/2./(*chi[ibin])[0]/(*chi[ibin])[0]*TMath::Cos(nn*theta[itheta]))*TMath::BesselJ0(2*j01*TMath::Cos(nn*theta[itheta]/2.)));
				deltavmean[ibin][ivbin]+=deltav[ibin][itheta][ivbin];
			//	fstrv<<itheta<<"\t"<<v[ibin][itheta][ivbin]<<"\t"<<deltav[ibin][itheta][ivbin]<<endl;
			}
		deltavmean[ibin][ivbin]=TMath::Sqrt(deltavmean[ibin][ivbin])/2./Besselj01(mm);
		//fstrv<<endl;
		vmean[ibin][ivbin]/=ntheta;
		deltavmean[ibin][ivbin]/=TMath::Sqrt(ntheta);
		fstrv<<binv[ivbin]<<"-"<<binv[ivbin+1]<<"\t"<<vmean[ibin][ivbin]<<"\t"<<deltavmean[ibin][ivbin]<<endl;
                if(ispt){
		if(binv[ivbin+1]>3.0) continue;
                totmulthisto[ibin][ivbin]=hpt[ibin]->Integral(hpt[ibin]->GetXaxis()->FindBin(binv[ivbin]),hpt[ibin]->GetXaxis()->FindBin(binv[ivbin+1])-1);
//                totmulthistocorr[ibin][ivbin]=hpteffcorr[ibin]->Integral(hpteffcorr[ibin]->GetXaxis()->FindBin(binv[ivbin]),hpteffcorr[ibin]->GetXaxis()->FindBin(binv[ivbin+1])-1);
                totmulthistocorr[ibin][ivbin]=totmulthisto[ibin][ivbin]/hpteff->GetBinContent(hpteff->FindBin((binv[ivbin]+binv[ivbin+1])/2));
		V_int[ibin][isample]+=vmean[ibin][ivbin]*totmult[ibin][ivbin];
		V_interr[ibin][isample]+=deltavmean[ibin][ivbin]*totmult[ibin][ivbin];
		V_intcorr[ibin][isample]+=vmean[ibin][ivbin]*totmulthistocorr[ibin][ivbin];
		V_intcorrerr[ibin][isample]+=deltavmean[ibin][ivbin]*totmulthistocorr[ibin][ivbin];
                }
		totmultall_[ibin][isample]+=totmult[ibin][ivbin];
		}
		V_int[ibin][isample]/=totmultall_[ibin][isample];
		V_interr[ibin][isample]/=totmultall_[ibin][isample];
		//V_intcorr[ibin][isample]/=hpteffcorr[ibin]->Integral(hpteffcorr[ibin]->GetXaxis()->FindBin(binv[0]),hpteffcorr[ibin]->GetXaxis()->FindBin(3.0)-1);
		//V_intcorr[ibin][isample]/=totmulthistocorr[ibin];
		//V_intcorrerr[ibin][isample]/=hpteffcorr[ibin]->Integral(hpteffcorr[ibin]->GetXaxis()->FindBin(binv[0]),hpteffcorr[ibin]->GetXaxis()->FindBin(3.0)-1);

                if(ispt){
        fstrv<<endl<<"pt range\t\t"<<"totmult"<<"\t\t"<<"totmult from histo"<<"\t"<<"totmult corrected"<<endl;
		for(int ivbin=0;ivbin<nvv; ivbin++){
                fstrv<<binv[ivbin]<<"-"<<binv[ivbin+1]<<"\t\t"<<totmult[ibin][ivbin]<<"\t"<<totmulthisto[ibin][ivbin]<<"\t"<<totmulthistocorr[ibin][ivbin]<<endl;
		}
		//fstrv<<"Integral\t\t"<<totmultall[ibin][isample]<<"\t"<<hpt[ibin]->Integral(hpt[ibin]->GetXaxis()->FindBin(binv[0]),hpt[ibin]->GetXaxis()->FindBin(3.0)-1)<<"\t"<<hpteffcorr[ibin]->Integral(hpteffcorr[ibin]->GetXaxis()->FindBin(binv[0]),hpteffcorr[ibin]->GetXaxis()->FindBin(3.0)-1)<<endl;
		fstrv<<"V ref="<<(*V_mean)[ibin]<<"\t"<<"V int="<<V_int[ibin][isample]<<"\t"<<"V int corr="<<V_intcorr[ibin][isample]<<endl;
		fstrv<<"V ref err="<<(*deltaV_mean)[ibin]<<"\t"<<"V int err="<<V_interr[ibin][isample]<<"\t"<<"V int corr err="<<V_intcorrerr[ibin][isample]<<endl;
                }
	TDirectory *dirsample = dir0->mkdir(Form("s_%d",isample));
        dirsample->cd();
	avgpt[ibin].Write("avgpt");
	avgeta[ibin].Write("avgeta");
	totmult[ibin].Write("totmult");
	vmean[ibin].Write("vmean");
	deltavmean[ibin].Write("deltavmean");
	for(int ivbin=0;ivbin<nvv; ivbin++){
		avgavgpt[ibin][ivbin]+=avgpt[ibin][ivbin]*Nevent[ibin][isample];
		avgavgeta[ibin][ivbin]+=avgeta[ibin][ivbin]*Nevent[ibin][isample];
		vmeanmean[ibin][ivbin]+=vmean[ibin][ivbin]/nsamples;
        	deltavmeanmean[ibin][ivbin]+=deltavmean[ibin][ivbin]/nsamples;
	        sigmavmeanmean[ibin][ivbin]+=TMath::Power(vmean[ibin][ivbin]/nsamples,2);
	}
	}//subsample loop
	dir0->cd();
        IFILE[ibin].Write("IFILE");
	V_int[ibin].Write("V_int");
	V_interr[ibin].Write("V_interr");
	V_intcorr[ibin].Write("V_intcorr");
	V_intcorrerr[ibin].Write("V_intcorrerr");
	Nevent[ibin].Write("Nevent");
	totmultall[ibin].Write("totmultall");
	for(int ivbin=0;ivbin<nvv; ivbin++){
		avgavgpt[ibin][ivbin]/=Nevent_[ibin];
		avgavgeta[ibin][ivbin]/=Nevent_[ibin];
        	sigmavmeanmean[ibin][ivbin]=TMath::Sqrt(sigmavmeanmean[ibin][ivbin]*nsamples-vmeanmean[ibin][ivbin]*vmeanmean[ibin][ivbin])/TMath::Sqrt(nsamples);
		}
	avgavgpt[ibin].Write("avgavgpt");
	avgavgeta[ibin].Write("avgavgeta");
        vmeanmean[ibin].Write("vmeanmean");
	deltavmeanmean[ibin].Write("deltavmeanmean");
        sigmavmeanmean[ibin].Write("sigmavmeanmean");
	}//ntrk bin loop
	infile->Close();
	fout->Close();
}
コード例 #29
0
//_____________________________________________________________________________
void ProofSelectorMyCutFlow::SlaveBegin(TTree * tree)
{
   // The SlaveBegin() function is called after the Begin() function.
   // When running with PROOF SlaveBegin() is called on each slave server.
   // The tree argument is deprecated (on PROOF 0 is passed).

   TString option = GetOption();
   //--------------------------------------//
   //       Loading the xml file
   //--------------------------------------//
   TNamed *dsname = (TNamed *) fInput->FindObject("PROOF_DATASETNAME");
   string datasetName = dsname->GetTitle();
   cout << "dataset name " << datasetName << endl;
   TNamed *xfname = (TNamed *) fInput->FindObject("PROOF_XMLFILENAME");
   string xmlFileName = xfname->GetTitle();
   anaEL = new AnalysisEnvironmentLoader(xmlFileName.c_str());
   anaEL->LoadSamples (datasets); // now the list of datasets written in the xml file is known
   vector<Dataset> onedatasetonly;
   //retrieve the current dataset according to its name
   for(unsigned int d=0;d<datasets.size();d++){
	if(datasets[d].Name()==datasetName) { 
	dataset = &datasets[d]; 
	onedatasetonly.push_back(datasets[d]);
	cout<<" SlaveBegin on dataset : "<<dataset->Name()<<endl;
	}
   }
   anaEL->LoadSelection (sel); // now the parameters for the selection are given to the selection
   anaEL->LoadGeneralInfo(DataType, Luminosity_e, Luminosity_mu, verbosity );


   //--------------------------------------//
   //   Managing histos  	
   //--------------------------------------//
   histoManager = new TTbarMetHistoManager();
   // Only 1 dataset per job with PROOF
   histoManager->LoadDatasets (onedatasetonly);
   histoManager->LoadSelectionSteps (sel.GetCutList ());
   histoManager->LoadChannels (sel.GetChannelList ());
   histoManager->CreateHistos ();


   // PU from JL's code
   if (dataset->isData() == false) {
/*
    if(datasetName == "DY1" || datasetName == "signal" ){
      string datafile = "/opt/sbg/data/data1/cms/ccollard/CMSSW/CMSSW_4_2_8_patch7/src/NTuple/NTupleAnalysis/macros/data/PUdata.root";
      string mcfile   = "/opt/sbg/data/data1/cms/ccollard/CMSSW/CMSSW_4_2_8_patch7/src/NTuple/NTupleAnalysis/macros/data/PU3DMC_Fall11.root";
   
      LumiWeights    = new reweight::LumiReWeighting(mcfile, datafile, "histoMCPU", "pileup" );
     }
     else{
*/
      string datafile = "/opt/sbg/data/data1/cms/ccollard/CMSSW/CMSSW_4_2_8_patch7/src/NTuple/NTupleAnalysis/macros/data/default73.5mb.root";
      string mcfile   = "/opt/sbg/data/data1/cms/ccollard/CMSSW/CMSSW_4_2_8_patch7/src/NTuple/NTupleAnalysis/macros/data/PU3DMC.root";

      LumiWeights    = new reweight::LumiReWeighting(mcfile, datafile, "histoMCPU", "pileup" );
      LumiWeights->weight3D_init( 1. );

/*
     }
*/
    }
//    else {
//      // JEC from JL's code  ALREADY IN CARO's SKIMS
//      JEC_L2L3Residuals.LoadCorrections();
//    }


   //////////////////////

   cout << "The verbosity mode is " << verbosity << endl;
   cout << "The luminosity is equal to " << Luminosity_e << " for e  and " << Luminosity_mu << " for mu " << endl;
   cout << "The DataType is ";
   switch (DataType) {
   case 0:
     cout << "MC" << endl;
     break;
   case 1:
     cout << "Data" << endl;
     break;
   case 2:
     cout << "Data & MC" << endl;
     break;
   default:
     cout << " unknown" << endl;
     break;
   }
   //////////////////////



   //--------------------------------------//
   //   Output file 	
   //--------------------------------------//
   //retrieve info from the input:
   TNamed *out = (TNamed *) fInput->FindObject("PROOF_OUTPUTFILE");
   //this file will be THE file which will contains all the histograms
   fProofFile = new TProofOutputFile(out->GetTitle());
   // Open the file
   TDirectory *savedir = gDirectory;
   fFile = fProofFile->OpenFile("UPDATE");
   if (fFile && fFile->IsZombie()) SafeDelete(fFile);
   savedir->cd();

   //this line is very important !!!
   fFile->Write();
   //It is required to add in fOutput the histos you want to feedback
   fOutput->Add(fFile);

}
コード例 #30
0
ファイル: softrad.C プロジェクト: cihar29/jecsys
// Soft radiation corrections for L3Res
void softrad(double etamin=0.0, double etamax=1.3, bool dodijet=false) {

  setTDRStyle();
  writeExtraText = false; // for JEC paper CWR

  TDirectory *curdir = gDirectory;

  // Open jecdata.root produced by reprocess.C
  TFile *fin = new TFile("rootfiles/jecdata.root","UPDATE");
  assert(fin && !fin->IsZombie());
  
  const int ntypes = 3;
  const char* types[ntypes] = {"data", "mc", "ratio"};
  const int nmethods = 2;
  const char* methods[nmethods] = {"mpfchs1", "ptchs"};
  const int nsamples = (dodijet ? 4 : 3);
  const char* samples[4] = {"gamjet", "zeejet", "zmmjet", "dijet"};
  string sbin = Form("eta%02.0f-%02.0f",10*etamin,10*etamax);
  const char* bin = sbin.c_str();
  const int nalphas = 4;
  const int alphas[nalphas] = {30, 20, 15, 10};

  // Z+jet bins
  const double ptbins1[] = {30, 40, 50, 60, 75, 95, 125, 180, 300, 1000};
  const int npt1 = sizeof(ptbins1)/sizeof(ptbins1[0])-1;
  TH1D *hpt1 = new TH1D("hpt1","",npt1,&ptbins1[0]);
  TProfile *ppt1 = new TProfile("ppt1","",npt1,&ptbins1[0]);

  // gamma+jet bins
  const double ptbins2[] = {30, 40, 50, 60, 75, 100, 125, 155, 180,
			    210, 250, 300, 350, 400, 500, 600, 800};
  const int npt2 = sizeof(ptbins2)/sizeof(ptbins2[0])-1;
  TH1D *hpt2 = new TH1D("hpt2","",npt2,&ptbins2[0]);
  TProfile *ppt2 = new TProfile("ppt2","",npt2,&ptbins2[0]);

  // dijet bins
  const double ptbins4[] = {20, 62, 107, 175, 242, 310, 379, 467,
			    628, 839, 1121, 1497, 2000};
  const int npt4 = sizeof(ptbins4)/sizeof(ptbins4[0])-1;
  TH1D *hpt4 = new TH1D("hpt4","",npt4,&ptbins4[0]);
  TProfile *ppt4 = new TProfile("ppt4","",npt4,&ptbins4[0]);

  TLatex *tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSize(0.045);

  map<string,const char*> texlabel;
  texlabel["gamjet"] = "#gamma+jet";
  texlabel["zeejet"] = "Z#rightarrowee+jet";
  texlabel["zmmjet"] = "Z#rightarrow#mu#mu+jet";
  texlabel["dijet"] = "Dijet";
  texlabel["ptchs"] = "p_{T} balance (CHS)";
  texlabel["mpfchs"] = "MPF raw (CHS)";
  texlabel["mpfchs1"] = "MPF type-I (CHS)";

  // overlay of various alpha values
  TCanvas *c1 = new TCanvas("c1","c1",ntypes*400,nmethods*400);
  c1->Divide(ntypes,nmethods);

  TH1D *h1 = new TH1D("h1",";p_{T} (GeV);Response",1270,30,1300);

  // extrapolation vs alpha for each pT bin
  vector<TCanvas*> c2s(ntypes*nmethods);
  for (unsigned int icanvas = 0; icanvas != c2s.size(); ++icanvas) {
    TCanvas *c2 = new TCanvas(Form("c2_%d",icanvas),Form("c2_%d",icanvas),
			      1200,1200);
    c2->Divide(3,3);
    c2s[icanvas] = c2;
  }

  TH1D *h2 = new TH1D("h2",";#alpha;Response",10,0.,0.4);
  h2->SetMaximum(1.08);
  h2->SetMinimum(0.88);

  // krad corrections
  TCanvas *c3 = new TCanvas("c3","c3",ntypes*400,nmethods*400);
  c3->Divide(ntypes,nmethods);

  TH1D *h3 = new TH1D("h3",";p_{T,ref} (GeV);FSR sensitivity: -dR/d#alpha [%]",
		      1270,30,1300);

  cout << "Reading in data" << endl << flush;
  // Read in plots vs pT (and alpha)
  map<string, map<string, map<string, map<int, TGraphErrors*> > > > gemap;
  map<string, map<string, map<string, map<int, TGraphErrors*> > > > gamap;
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {
      for (int  isample = 0; isample != nsamples; ++isample) {

	for (int  ialpha = 0; ialpha != nalphas; ++ialpha) {

	  fin->cd();
	  assert(gDirectory->cd(types[itype]));
	  assert(gDirectory->cd(bin));
	  TDirectory *d = gDirectory;

	  const char *ct = types[itype];
	  const char *cm = methods[imethod];
	  const char *cs = samples[isample];
	  const int a = alphas[ialpha];
	  // Get graph made vs pT
	  string s = Form("%s/%s/%s_%s_a%d",types[itype],bin,cm,cs,a);
	  TGraphErrors *g = (TGraphErrors*)fin->Get(s.c_str());
	  if (!g) cout << "Missing " << s << endl << flush;
	  assert(g);

	  // Clean out empty points
	  // as well as trigger-biased ones for dijets
	  // as well as weird gamma+jet high pT point
	  for (int i = g->GetN()-1; i != -1; --i) {
	    if (g->GetY()[i]==0 || g->GetEY()[i]==0 ||
		(string(cs)=="dijet" && g->GetX()[i]<70.) ||
		(string(cs)=="gamjet" && g->GetX()[i]>600. && etamin!=0))
	      g->RemovePoint(i);
	  }

	  gemap[ct][cm][cs][a] = g;
	  
	  // Sort points into new graphs vs alpha
	  TH1D *hpt = (isample==0 ? hpt2 : hpt1);
	  TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	  if (isample==3) { hpt = hpt4; ppt = ppt4; } // pas-v6
	  for (int i = 0; i != g->GetN(); ++i) {
	    
	    double pt = g->GetX()[i];
	    ppt->Fill(pt, pt);
	    int ipt = int(hpt->GetBinLowEdge(hpt->FindBin(pt))+0.5);
	    //int ipt = int(pt+0.5);
	    TGraphErrors *ga = gamap[ct][cm][cs][ipt];
	    if (!ga) {
	      ga = new TGraphErrors(0);
	      ga->SetMarkerStyle(g->GetMarkerStyle());
	      ga->SetMarkerColor(g->GetMarkerColor());
	      ga->SetLineColor(g->GetLineColor());
	      gamap[ct][cm][cs][ipt] = ga;
	    }
	    int n = ga->GetN();
	    ga->SetPoint(n, 0.01*a, g->GetY()[i]);
	    ga->SetPointError(n, 0, g->GetEY()[i]);
	  } // for i 

	} // for ialpha

      } // for isample
    } // for imethod
  } // for itype

  cout << "Drawing plots vs pT for each alpha" << endl << flush;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      int ipad = ntypes*imethod + itype + 1; assert(ipad<=6);
      c1->cd(ipad);
      gPad->SetLogx();
      h1->SetMaximum(itype<2 ? 1.15 : 1.08);
      h1->SetMinimum(itype<2 ? 0.85 : 0.93);
      h1->SetYTitle(Form("Response (%s)",ct));
      h1->DrawClone("AXIS");
      tex->DrawLatex(0.20,0.85,texlabel[cm]);
      tex->DrawLatex(0.20,0.80,"|#eta| < 1.3, #alpha=0.1--0.3");
      TLegend *leg = tdrLeg(0.60,0.75,0.90,0.90);

      for (int  isample = 0; isample != nsamples; ++isample) {
	for (int  ialpha = 0; ialpha != nalphas; ++ialpha) {

	  const char *cs = samples[isample];
	  const int a = alphas[ialpha];
	  TGraphErrors *g = gemap[ct][cm][cs][a]; assert(g);

	  // Clean out points with very large uncertainty for plot readability
	  for (int i = g->GetN()-1; i != -1; --i) {
	    if (g->GetEY()[i]>0.02) g->RemovePoint(i);
	  }

	  g->Draw("SAME Pz");

	  if (ialpha==0) leg->AddEntry(g,texlabel[cs],"P");
	}
      } // for isample

      // Individual plots for JEC paper
      if ( true ) { // paper

	TH1D *h = new TH1D(Form("h_5%s_%s",ct,cm),
			   Form(";p_{T} (GeV);Response (%s)",ct),
			   1270,30,1300);
	h->GetXaxis()->SetMoreLogLabels();
	h->GetXaxis()->SetNoExponent();
	h->SetMinimum(0.88);
	h->SetMaximum(1.13);

	writeExtraText = true;
	extraText = (string(ct)=="mc" ? "Simulation" : "");
	lumi_8TeV = (string(ct)=="mc" ? "" : "19.7 fb^{-1}");
	TCanvas *c0 = tdrCanvas(Form("c0_%s_%s",cm,ct), h, 2, 11, true);
	c0->SetLogx();
	

	TLegend *leg = tdrLeg(0.55,0.68,0.85,0.83);
	tex->DrawLatex(0.55,0.85,texlabel[cm]);
	tex->DrawLatex(0.55,0.18,"|#eta| < 1.3, #alpha=0.3");
	//tex->DrawLatex(0.55,0.18,"Anti-k_{T} R=0.5");

	// Loop over Z+jet and gamma+jet (only, no dijet/multijet)
	for (int  isample = 0; isample != min(3,nsamples); ++isample) {
	  
	  const char *cs = samples[isample];
	  TGraphErrors *g = gemap[ct][cm][cs][30]; assert(g);
	  g->Draw("SAME Pz");
	  
	  leg->AddEntry(g,texlabel[cs],"P");
	} // for isample

	if (etamin==0) {
	  c0->SaveAs(Form("pdf/paper_softrad_%s_%s_vspt.pdf",ct,cm));
	  c0->SaveAs(Form("pdfC/paper_softrad_%s_%s_vspt.C",ct,cm));
	}
	else {
	  c0->SaveAs(Form("pdf/an_softrad_%s_%s_eta%1.0f-%1.0f_vspt.pdf",
			  ct,cm,10*etamin,10*etamax));
	}
      } // paper

    } // for imethod
  } // for itype
  
  c1->cd(0);
  //cmsPrel(_lumi, true);
  CMS_lumi(c1, 2, 33);
  c1->SaveAs("pdf/softrad_2x6_vspt.pdf");


  cout << "Drawing plots vs alpha for each pT" << endl << flush;
  cout << "...and fitting slope vs alpha" << endl << flush;

  map<string, map<string, map<string, TGraphErrors* > > > gkmap;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {
      
      int icanvas = nmethods*imethod + itype; assert(icanvas<=6);
      TCanvas *c2 = c2s[icanvas]; assert(c2);

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      const int npads = 9;
      for (int ipad = 0; ipad != npads; ++ipad) {
	c2->cd(ipad+1);
	h2->SetYTitle(Form("Response (%s)",ct));
	h2->DrawClone("AXIS");
	tex->DrawLatex(0.20,0.85,texlabel[cm]);
	tex->DrawLatex(0.20,0.80,"|#eta| < 1.3");
	tex->DrawLatex(0.20,0.75,Form("%1.0f < p_{T} < %1.0f GeV",
				      hpt1->GetBinLowEdge(ipad+1),
				      hpt1->GetBinLowEdge(ipad+2)));
	TLegend *leg = tdrLeg(0.65,0.75,0.90,0.90);
	leg->AddEntry(gemap[ct][cm]["gamjet"][30], texlabel["gamjet"], "P");
	leg->AddEntry(gemap[ct][cm]["zeejet"][30], texlabel["zeejet"], "P");
	leg->AddEntry(gemap[ct][cm]["zmmjet"][30], texlabel["zmmjet"], "P");
	leg->AddEntry(gemap[ct][cm]["dijet"][30], texlabel["dijet"], "P");
      }

      for (int  isample = 0; isample != nsamples; ++isample) {

	const char *cs = samples[isample];

	map<int, TGraphErrors*> &gam = gamap[ct][cm][cs];
	map<int, TGraphErrors*>::iterator itpt;
	for (itpt = gam.begin(); itpt != gam.end(); ++itpt) {

	  int ipt = itpt->first;
	  int jpt = hpt1->FindBin(ipt);
	  if (jpt>npads) continue;
	  assert(jpt<=npads);
	  c2->cd(jpt);
	  
	  TGraphErrors *ga = itpt->second; assert(ga);
	  
	  ga->Draw("SAME Pz");

	  // Fit slope
	  TF1 *f1 = new TF1(Form("f1_%s_%s_%s_%d",ct,cm,cs,ipt),
			    "(x<1)*([0]+[1]*x) + (x>1 && x<2)*[0] +"
			    "(x>2)*[1]",-1,1);
	  f1->SetLineColor(ga->GetLineColor());
	  f1->SetParameters(1,0);
	  const double minalpha = (isample==0 ? 10./ipt : 5./ipt);
	  // Constrain slope to within reasonable values
	  // in the absence of sufficient data using priors
	  if (true) { // use priors
	    int n = ga->GetN();
	    // For response, limit to 1+/-0.02 (we've corrected for L3Res
	    ga->SetPoint(n, 1.5, 1);
	    ga->SetPointError(n, 0, 0.02);
	    n = ga->GetN();
	    if (imethod==1) { // pT balance
	      // For pT balance, estimate slope of <vecpT2>/alpha from data
	      // => 7.5%/0.30 = 25%
	      // Approximate uncertainty on this to be
	      // 0.5%/0.30 ~ 1.5% for data, 0.5%/0.30 ~ 1.5% for Z+jet MC, and
	      // 2%/0.30 ~ 6% for gamma+jet MC (same as slope)
	      if (itype==0)               ga->SetPoint(n, 2.5, -0.250); // DT
	      if (itype==1 && isample!=0) ga->SetPoint(n, 2.5, -0.250); // MC
	      if (itype==1 && isample==0) ga->SetPoint(n, 2.5, -0.190);
	      if (itype==2 && isample!=0) ga->SetPoint(n, 2.5, -0.000); // rt
	      if (itype==2 && isample==0) ga->SetPoint(n, 2.5, -0.060); 
	      //
	      // BUG: found 2015-01-08 (no effect on ratio)
	      //if (itype==1)               ga->SetPointError(n, 0, -0.015);
	      if (itype==0)               ga->SetPointError(n, 0, -0.015); // DT
	      if (itype==1 && isample!=0) ga->SetPointError(n, 0, -0.015); // MC
	      if (itype==1 && isample==0) ga->SetPointError(n, 0, -0.060);
	      if (itype==2 && isample!=0) ga->SetPointError(n, 0, -0.015); // rt
	      if (itype==2 && isample==0) ga->SetPointError(n, 0, -0.060); 
	    }
	    if (imethod==0) { // MPF
	      // For MPF, expectation is no slope
	      // Maximal slope would be approximately
	      // (<vecpT2>/alpha ~ 25% from pT balance) times
	      // (response difference between pT1 and vecpT2~10%)
	      // => 0.25*0.10 = 2.5%
	      // For data/MC, estimate uncertainty as half of this
	      // => 1.25%
	      ga->SetPoint(n, 2.5, 0.);
	      if (itype!=2) ga->SetPointError(n, 0, 0.025);
	      if (itype==2) ga->SetPointError(n, 0, 0.0125);
	    } // MPF
	  } // use priors

	  if (ga->GetN()>2) {

	    f1->SetRange(minalpha, 3.);
	    ga->Fit(f1,"QRN");

	    if (f1->GetNDF()>=0) {
	      f1->DrawClone("SAME");
	      f1->SetRange(0,0.4);
	      f1->SetLineStyle(kDashed);
	      f1->DrawClone("SAME");

	      // Store results
	      TGraphErrors *gk = gkmap[ct][cm][cs];
	      if (!gk) {
		gk = new TGraphErrors(0);
		gk->SetMarkerStyle(ga->GetMarkerStyle());
		gk->SetMarkerColor(ga->GetMarkerColor());
		gk->SetLineColor(ga->GetLineColor());
		gkmap[ct][cm][cs] = gk;
	      }
	      int n = gk->GetN();
	      TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	      if (isample==3) { ppt = ppt4; } // pas-v6
	      double pt = ppt->GetBinContent(ppt->FindBin(ipt));
	      gk->SetPoint(n, pt, f1->GetParameter(1));
	      gk->SetPointError(n, 0, f1->GetParError(1));
	    } // f1->GetNDF()>=0
	  } // ga->GetN()>2
	} // for itpt
	
      } // for isample
      
      c2->SaveAs(Form("pdf/softrad_3x3_%s_%s_vsalpha.pdf",ct,cm));
      
    }
  }


  cout << "Drawing plots of kFSR vs pT" << endl;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      TMultiGraph *mgk = new TMultiGraph();

      int ipad = ntypes*imethod + itype + 1; assert(ipad<=6);
      c3->cd(ipad);
      gPad->SetLogx();
      h3->SetMaximum(imethod==0 ? 0.05 : (itype!=2 ? 0.1 : 0.25));
      h3->SetMinimum(imethod==0 ? -0.05 : (itype!=2 ? -0.4 : -0.25));
      h3->SetYTitle(Form("k_{FSR} = dR/d#alpha (%s)",ct));
      h3->DrawClone("AXIS");
      tex->DrawLatex(0.20,0.85,texlabel[cm]);
      tex->DrawLatex(0.20,0.80,"|#eta| < 1.3");
      TLegend *leg = tdrLeg(0.60,0.75,0.90,0.90);

      for (int  isample = 0; isample != nsamples; ++isample) {

	const char *cs = samples[isample];
	TGraphErrors *gk = gkmap[ct][cm][cs]; assert(gk);
	
	leg->AddEntry(gk,texlabel[cs],"P");

	// Fit each sample separately for pT balance
	if (true) {

	  TF1 *fk = new TF1(Form("fk_%s_%s_%s",ct,cm,cs),
			    "[0]+[1]*log(0.01*x)+[2]*pow(log(0.01*x),2)",
			    30,1300);
	  fk->SetParameters(-0.25,-0.5);
	  fk->SetLineColor(gk->GetLineColor());
	  gk->Fit(fk, "QRN");

	  tex->SetTextColor(fk->GetLineColor());
	  tex->DrawLatex(0.55,0.27-0.045*isample,
			 Form("#chi^{2}/NDF = %1.1f / %d",
			      fk->GetChisquare(), fk->GetNDF()));
	  tex->SetTextColor(kBlack);

	  // Error band
	  const int n = fk->GetNpar();
	  TMatrixD emat(n,n);
	  gMinuit->mnemat(emat.GetMatrixArray(), n);
	  TF1 *fke = new TF1(Form("fk_%s_%s_%s",ct,cm,cs),
			     sr_fitError, 30, 1300, 1);
	  _sr_fitError_func = fk;
	  _sr_fitError_emat = &emat;

	  fke->SetLineStyle(kSolid);
	  fke->SetLineColor(fk->GetLineColor()-10);
	  fke->SetParameter(0,-1);
	  fke->DrawClone("SAME");
	  fke->SetParameter(0,+1);
	  fke->DrawClone("SAME");

	  fk->DrawClone("SAME");
	  gk->DrawClone("SAME Pz");

	  // Store soft radiation corrections in fsr subdirectory
	  assert(fin->cd(ct));
	  assert(gDirectory->cd(bin));
	  if (!gDirectory->FindObject("fsr")) gDirectory->mkdir("fsr");
	  assert(gDirectory->cd("fsr"));

	  TH1D *hk = (TH1D*)(isample==0 ? hpt2->Clone() : hpt1->Clone());
	  hk->SetName(Form("hkfsr_%s_%s",cm,cs));
	  TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	  if (isample==3) { ppt = ppt4; } // pas-v6
	  for (int i = 1; i != hk->GetNbinsX()+1; ++i) {
	    double pt = ppt->GetBinContent(i);
	    if (pt>30 && pt<1300) {
	      hk->SetBinContent(i, fk->Eval(pt));
	      hk->SetBinError(i, fabs(fke->Eval(pt)-fk->Eval(pt)));
	    }
	    else {
	      hk->SetBinContent(i, 0);
	      hk->SetBinError(i, 0);
	    }
	  }
	  
	  hk->Write(hk->GetName(), TObject::kOverwrite);

	  // Factorize error matrix into eigenvectors
	  // Remember: A = Q*Lambda*Q^-1, where
	  // A is emat, Q is eigmat, and Lambda is a diagonal matrix with
	  // eigenvalues from eigvec on the diagonal. For eigenmatrix
	  // Q^-1 = Q^T, i.e. inverse matrix is the original transposed
	  TVectorD eigvec(n);
	  TMatrixD eigmat = emat.EigenVectors(eigvec);

	  // Eigenvectors are the columns and sum of eigenvectors squared
	  // equals original uncertainty. Calculate histograms from the
	  // eigenvectors and store them
	  TF1 *fkeig = (TF1*)fk->Clone(Form("%s_eig",fk->GetName()));
	  fkeig->SetLineStyle(kDotted);
	  for (int ieig = 0; ieig != n; ++ieig) {

	    // Eigenvector functions
	    for (int i = 0; i != n; ++i) {
	      fkeig->SetParameter(i, fk->GetParameter(i)
				  + eigmat[i][ieig] * sqrt(eigvec[ieig]));
	    }
	    fkeig->DrawClone("SAMEL");

	    // Eigenvector histograms evaluated at bin mean pT
	    TH1D *hke = (TH1D*)hk->Clone(Form("%s_eig%d",hk->GetName(),ieig));
	    hke->Reset();

	    for (int i = 0; i != gk->GetN(); ++i) {

	      double pt = gk->GetX()[i];
	      int ipt = hke->FindBin(pt);
	      // Need to store central value as well, because
	      // uncertainty sources are signed
	      hke->SetBinContent(ipt, fkeig->Eval(pt)-fk->Eval(pt));
	      hke->SetBinError(ipt, fabs(fkeig->Eval(pt)-fk->Eval(pt)));
	    }
	    hke->Write(hke->GetName(), TObject::kOverwrite);
	  }

	  cout << "." << flush;
	} // if tree
      } // for isample
    } // for imethod
  } // for itype
  
  c3->cd(0);
  //cmsPrel(_lumi, true);
  CMS_lumi(c3, 2, 33);
  c3->SaveAs("pdf/softrad_2x6_kfsr.pdf");

  fin->Close();
  curdir->cd();
} // softrad