コード例 #1
0
		double pValueFromPoint2PointDissimilarity(IDataSet * data, IDataSet * mcData)
		{
            std::cout << "GC: calculating T stat for data" << std::endl;
            double T = calculateTstatistic( data, mcData );
			char buffer[20];
			sprintf( buffer, "Tdata = %f", T );
			cout << buffer << endl;

			int nPerm = 25;
			vector<double> Tvalues = permutation( data, mcData, nPerm );

            int count = 0;
			vector<double>::iterator Titer;
			for ( Titer = Tvalues.begin(); Titer != Tvalues.end(); ++Titer ){
				if ( T < *Titer ) count++;
			}

			double pvalue = count/double(nPerm);

	    string fileName = ResultFormatter::GetOutputFolder();	
	    fileName.append("/tvalues.root");
	    	
            TFile * outputFile = new TFile(fileName.c_str(), "RECREATE");
            TNtuple * ntuple = new TNtuple("tvalues", "tvalues", "T:Tdata:pvalue");
            for ( int i = 0; i < nPerm; i++ ) ntuple->Fill(Tvalues[i], T, pvalue);
            ntuple->Write();
            outputFile->Close();
            delete outputFile;

       		return pvalue;
        }
コード例 #2
0
ファイル: test.cpp プロジェクト: bonventre/threef
int main(){

  std::vector<double> initparams;
  initparams.push_back(5.0);

  FFF::FitSimple fit(&myNLL,&myMC);
  FFF::DataWrapper* data = fit.GenerateData(initparams);
  std::cout << "The correct answer is 5.0, with a likelihood of 0.0" << std::endl;


  std::vector<double> results = fit.MigradFit(initparams,data);
  std::cout << "Migrad: " << results[0] << " L=" << results[1] << std::endl;

  TNtuple *lspace = fit.MCMCMapLikelihood(initparams,data);
  TFile f("lspace.root","RECREATE");
  lspace->Write();
  f.Close();
  results = fit.MCMCFit(initparams,data);
  std::cout << "MCMC: " << results[0] << " L=" << results[1] << std::endl;

  results = fit.SAnnealFit(initparams,data);
  std::cout << "SAnneal: " << results[0] << " L=" << results[1] << std::endl;

  // You can also do normal minuit2 stuff
  ROOT::Minuit2::FCNBase* migradfunc = fit.GetMinuit2FCNBase(data);
  std::vector<double> verrors;
  for (size_t i=0;i<initparams.size();i++)
    verrors.push_back(0.0); //FIXME
  ROOT::Minuit2::MnUserParameters mnParams(initparams,verrors);
  ROOT::Minuit2::MnMigrad migrad(*migradfunc,mnParams);  
  ROOT::Minuit2::FunctionMinimum theMin = migrad(); //FIXME maxfcn, tol
  ROOT::Minuit2::MnUserParameters migradresult = theMin.UserParameters();
  ROOT::Minuit2::MnMinos minos(*migradfunc,theMin);
  std::pair<double, double> errors = minos(0);

  std::cout << "Minos errors:" << std::endl;
  std::cout << migradresult.Params()[0] << " +" << errors.second << " -" << -1*errors.first << std::endl;

  return 0;

}
コード例 #3
0
void testPicoD0EventRead(TString filename)
{
	gROOT->LoadMacro("$STAR/StRoot/StMuDSTMaker/COMMON/macros/loadSharedLibraries.C");
	loadSharedLibraries();

	gSystem->Load("StPicoDstMaker");
	gSystem->Load("StPicoD0Maker");

	TFile* f = new TFile(filename.Data());
	TTree* T = (TTree*)f->Get("T");
	StPicoD0Event* event = new StPicoD0Event();
	T->SetBranchAddress("dEvent",&event);

	TFile ff("read_test.root","RECREATE");
  TNtuple* nt = new TNtuple("nt","","m:pt:eta:phi:theta:"
                                     "decayL:kDca:pDca:dca12:cosThetaStar");

	StKaonPion* kp = 0;

	for(Int_t i=0;i<100000;++i)
	{
		T->GetEntry(i);

		TClonesArray* arrKPi = event->kaonPionArray();

		for(int idx=0;idx<event->nKaonPion();++idx)
		{
			kp = (StKaonPion*)arrKPi->At(idx);

      nt->Fill(kp->m(),kp->pt(),kp->eta(),kp->phi(),kp->pointingAngle(),
              kp->decayLength(),kp->kaonDca(),kp->pionDca(),kp->dcaDaughters(),kp->cosThetaStar());
		}
	}

  nt->Write();
	ff.Close();
}
コード例 #4
0
int main(int argc, char* argv[])
{
  TApplication theApp(srcName.Data(), &argc, argv);
//=============================================================================

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

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

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

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

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

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

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

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

  fastjet::Selector selectJet = fastjet::SelectorAbsEtaMax(dJetEtaMax);
  fastjet::JetDefinition subjDef(fastjet::kt_algorithm, dSjeR, fastjet::BIpt_scheme, fastjet::Best);
//=============================================================================

  std::vector<fastjet::PseudoJet> fjInput;
  const Double_t dCut = TMath::TwoPi() / 3.;
//=============================================================================

  enum { kWgt, kXsc, kLje, kLjr, kLtk, kLtr, kJet, kAje, kMje, k1sz, k1sA, k1sm, k1sr, k2sz, k2sA, k2sm, k2sr, kDsm, kDsr, kVar };

  TFile *file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  TNtuple *nt = new TNtuple("nt", "", "fWgt:fXsc:fLje:fLjr:fLtk:fLtr:fJet:fAje:fMje:f1sj:f1sA:f1sm:f1sr:f2sj:f2sA:f2sm:f2sr:fDsm:fDsr");
//=============================================================================

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

  while (evt) {
    fjInput.resize(0);

    double dLtk = -1.;
    TVector3 vPar, vLtk;
    for (HepMC::GenEvent::particle_const_iterator p=evt->particles_begin(); p!=evt->particles_end(); ++p) if ((*p)->status()==1) {
      double dEta = (*p)->momentum().eta(); if (TMath::Abs(dEta)>dCutEtaMax) continue;

      double dTrk = (*p)->momentum().perp();
      double dPhi = (*p)->momentum().phi();
      vPar.SetPtEtaPhi(dTrk, dEta, dPhi);
      fjInput.push_back(fastjet::PseudoJet(vPar.Px(), vPar.Py(), vPar.Pz(), vPar.Mag()));
      if (dTrk>dLtk) { dLtk = dTrk; vLtk.SetPtEtaPhi(dTrk, dEta, dPhi); }
    }
//=============================================================================

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

    if (selectJets.size()>0) {
      std::vector<fastjet::PseudoJet> sortedJets = fastjet::sorted_by_pt(selectJets);
      TVector3 vLje; vLje.SetPtEtaPhi(sortedJets[0].pt(), sortedJets[0].eta(), sortedJets[0].phi());

      TVector3 vJet;
      int kJrl = -1; double dJrl = -1.;
      int kTrl = -1; double dTrl = -1.;
      for (int j=0; j<sortedJets.size(); j++) {
        double dJet = sortedJets[j].pt();
        sortedJets[j].set_user_index(-1);
        vJet.SetPtEtaPhi(dJet, sortedJets[j].eta(), sortedJets[j].phi());
        if (TMath::Abs(vJet.DeltaPhi(vLje))>dCut) { sortedJets[j].set_user_index(1); if (dJet>dJrl) { dJrl = dJet; kJrl = j; } }
        if (TMath::Abs(vJet.DeltaPhi(vLtk))>dCut) { sortedJets[j].set_user_index(2); if (dJet>dTrl) { dTrl = dJet; kTrl = j; } }
      }
//=============================================================================

      TVector3 v1sj, v2sj;
      for (int j=0; j<sortedJets.size(); j++) {
        Float_t dVar[kVar]; for (Int_t i=0; i<kVar; i++) dVar[i] = -1.;
        dVar[kWgt] = 1.; dVar[kXsc] = 1.;
        vJet.SetPtEtaPhi(sortedJets[j].pt(), sortedJets[j].eta(), sortedJets[j].phi());
//=============================================================================

        dVar[kLje] = vLje.Pt(); if (sortedJets[j].user_index()==1) { dVar[kLjr] = ((kJrl==j) ? 1.5 : 0.5); }
        dVar[kLtk] = vLtk.Pt(); if (sortedJets[j].user_index()==2) { dVar[kLtr] = ((kTrl==j) ? 1.5 : 0.5); }
//=============================================================================

        dVar[kJet] = sortedJets[j].pt();
        dVar[kAje] = sortedJets[j].area();
        dVar[kMje] = sortedJets[j].m();
//=============================================================================

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

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

          if (dIsj>d1sj) {
            d2sj = d1sj; k2sj = k1sj;
            d1sj = dIsj; k1sj = i;
          } else if (dIsj>d2sj) {
            d2sj = dIsj; k2sj = i;
          }
        }
//=============================================================================

        if (d1sj>0.) {
          v1sj.SetPtEtaPhi(d1sj, trimmdSj[k1sj].eta(), trimmdSj[k1sj].phi());
          dVar[k1sz] = d1sj;
          dVar[k1sA] = trimmdSj[k1sj].area();
          dVar[k1sm] = trimmdSj[k1sj].m();
          dVar[k1sr] = v1sj.DeltaR(vJet);
        }

        if (d2sj>0.) {
          v2sj.SetPtEtaPhi(d2sj, trimmdSj[k2sj].eta(), trimmdSj[k2sj].phi());
          dVar[k2sz] = d2sj;
          dVar[k2sA] = trimmdSj[k2sj].area();
          dVar[k2sm] = trimmdSj[k2sj].m();
          dVar[k2sr] = v2sj.DeltaR(vJet);
        }

        if ((d1sj>0.) && (d2sj>0.)) dVar[kDsr] = v2sj.DeltaR(v1sj);

        nt->Fill(dVar);
      }
    }
//=============================================================================

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

  file->cd(); nt->Write(); file->Close();
//=============================================================================

  TString sXsec = sFile; sXsec.ReplaceAll("out", "xsecs");
  file = TFile::Open(Form("%s/xsecs/%s.root",sPath.Data(),sXsec.Data()), "READ");
  TH1D *hPtHat        = (TH1D*)file->Get("hPtHat");        hPtHat->SetDirectory(0);
  TH1D *hWeightSum    = (TH1D*)file->Get("hWeightSum");    hWeightSum->SetDirectory(0);
  TProfile *hSigmaGen = (TProfile*)file->Get("hSigmaGen"); hSigmaGen->SetDirectory(0);
  file->Close();
//=============================================================================

  sFile.ReplaceAll("out", "wgt");
  file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  hPtHat->Write();
  hWeightSum->Write();
  hSigmaGen->Write();
  file->Close();
//=============================================================================

  cout << "DONE" << endl;
//=============================================================================

  return 0;
}
コード例 #5
0
ファイル: buildtupledata.C プロジェクト: Jelov/JetEnergy_SR
void buildtupledata(TString code)//(TString collision = "PbPbBJet", TString jetalgo = "akVs4PFJetAnalyzer")
{
  if (!dt(code)) { cout<<"Not data: "<<code<<", exiting..."<<endl; return;}
  
  bool PbPb = isPbPb(code);
  TString sample = getSample(code);
  jettree = getjettree(code);
  subTag = subTagging(code);

  Init(PbPb, sample);

  TString outputfilenamedj = outputfolder+"/"+code+"_djt.root";
  TString outputfilenameinc = outputfolder+"/"+code+"_inc.root";
  TString outputfilenameevt = outputfolder+"/"+code+"_evt.root";

  TString djvars = TString("run:lumi:event:prew:triggermatched:bin:vz:hiHF:hltCSV60:hltCSV80:hltCaloJet40:hltCaloJet60:hltCaloJet80:hltPFJet60:hltPFJet80:dijet:")+
      "hltCalo60jtpt:hltCalo60jtphi:hltCalo60jteta:hltCalo80jtpt:hltCalo80jtphi:hltCalo80jteta:hltCSV60jtpt:hltCSV60jtphi:hltCSV60jteta:hltCSV80jtpt:hltCSV80jtphi:hltCSV80jteta:"+
      "rawpt1:jtpt1:jtphi1:jteta1:discr_csvV1_1:svtxm1:discr_prob1:svtxdls1:svtxpt1:svtxntrk1:nsvtx1:nselIPtrk1:"+
      "rawpt2:jtpt2:jtphi2:jteta2:discr_csvV1_2:svtxm2:discr_prob2:svtxdls2:svtxpt2:svtxntrk2:nsvtx2:nselIPtrk2:dphi21:"+
      "rawpt3:jtpt3:jtphi3:jteta3:discr_csvV1_3:svtxm3:discr_prob3:svtxdls3:svtxpt3:svtxntrk3:nsvtx3:nselIPtrk3:dphi31:dphi32:"+
      "SLord:rawptSL:jtptSL:jtphiSL:jtetaSL:discr_csvV1_SL:svtxmSL:discr_probSL:svtxdlsSL:svtxptSL:svtxntrkSL:nsvtxSL:nselIPtrkSL:dphiSL1";





  for (auto w:weights) cout<<w<<"\t";
  cout<<endl;

  int totentries = 0;

  //now fill histos
  TFile *foutdj = new TFile(outputfilenamedj,"recreate");
  TNtuple *ntdj = new TNtuple("nt","ntdj",djvars);

  TFile *foutinc = new TFile(outputfilenameinc,"recreate");
  TNtuple *ntinc = new TNtuple("nt","ntinc","prew:goodevent:bin:vz:hiHF:hltCSV60:hltCSV80:hltCaloJet40:hltCaloJet60:hltCaloJet80:hltPFJet60:hltPFJet80:rawpt:jtpt:jtphi:jteta:discr_csvV1:svtxm:discr_prob:svtxdls:svtxpt:svtxntrk:nsvtx:nselIPtrk");
  TFile *foutevt = new TFile(outputfilenameevt,"recreate");
  TNtuple *ntevt = new TNtuple("nt","ntinc","prew:bin:vz:hiHF:hltCSV60:hltCSV80");
  
  for (unsigned i=0;i<subfoldernames.size();i++) {
    //get all files for unmerged forests
    auto files = list_files(TString::Format("%s/%s/",samplesfolder.Data(),subfoldernames[i].Data()));

    for (auto filename:files) {
    cout<<endl<<"Processing file "<<filename<<endl;

    TFile *f = new TFile(filename);
    TString treename = jettree;//f->Get(jettree) != 0 ? jettree : "ak3PFJetAnalyzer";
    TTreeReader reader(treename,f);
    TTreeReaderValue<int> nref(reader, "nref");
    TTreeReaderArray<float> rawpt(reader, "rawpt");
    TTreeReaderArray<float> jtpt(reader, "jtpt");
    TTreeReaderArray<float> jteta(reader, "jteta");
    TTreeReaderArray<float> jtphi(reader, "jtphi");
    TTreeReaderArray<float> discr_csvV1(reader, "discr_csvV1");

    TTreeReaderArray<float> discr_prob(reader, "discr_prob");
    TTreeReaderArray<float> svtxm(reader, "svtxm");
    TTreeReaderArray<float> svtxdls(reader, "svtxdls");
    TTreeReaderArray<float> svtxpt(reader, "svtxpt");

    TTreeReaderArray<int> svtxntrk(reader, "svtxntrk");
    TTreeReaderArray<int> nsvtx(reader, "nsvtx");
    TTreeReaderArray<int> nselIPtrk(reader, "nselIPtrk");

    TTreeReaderArray<float> *muMax=0, *muMaxTRK=0, *muMaxGBL=0;
    if (PbPb) {
      muMax = new TTreeReaderArray<float> (reader, "muMax");
      muMaxTRK = new TTreeReaderArray<float>(reader, "muMaxTRK");
      muMaxGBL = new TTreeReaderArray<float>(reader, "muMaxGBL");
    }


    //HLT_HIPuAK4CaloBJetCSV80_Eta2p1_v1 HLT_HIPuAK4CaloJet80_Eta5p1_v1

    TString calojet40trigger = !PbPb ? "HLT_AK4CaloJet40_Eta5p1_v1" : "HLT_HIPuAK4CaloJet40_Eta5p1_v1";
    TString calojet40triggerv2 = !PbPb ? "HLT_AK4CaloJet40_Eta5p1_v1" : "HLT_HIPuAK4CaloJet40_Eta5p1_v2";
    TString calojet60trigger = !PbPb ? "HLT_AK4CaloJet60_Eta5p1_v1" : "HLT_HIPuAK4CaloJet60_Eta5p1_v1";
    TString calojet80trigger = !PbPb ? "HLT_AK4CaloJet80_Eta5p1_v1" : "HLT_HIPuAK4CaloJet80_Eta5p1_v1";
    //dummy vars in PbPb case
    TString pfjet60trigger = !PbPb ? "HLT_AK4PFJet60_Eta5p1_v1" : "LumiBlock";
    TString pfjet80trigger = !PbPb ? "HLT_AK4PFJet80_Eta5p1_v1" : "LumiBlock";
    TString csv60trigger = !PbPb ? "HLT_AK4PFBJetBCSV60_Eta2p1_v1"  : "HLT_HIPuAK4CaloBJetCSV60_Eta2p1_v1";
    TString csv80trigger = !PbPb ? "HLT_AK4PFBJetBCSV80_Eta2p1_v1"  : "HLT_HIPuAK4CaloBJetCSV80_Eta2p1_v1";

    //PbPb pprimaryVertexFilter && pclusterCompatibilityFilter do nothing
    vector<TString> filterNames;
    if (PbPb) filterNames = {"pcollisionEventSelection", "HBHENoiseFilterResultRun2Loose"};
    else filterNames = {"pPAprimaryVertexFilter", "HBHENoiseFilterResultRun2Loose", "pBeamScrapingFilter"}; 

    TTreeReader readerhlt("hltanalysis/HltTree",f);
    TTreeReaderValue<int> PFJet60(readerhlt, pfjet60trigger);
    TTreeReaderValue<int> PFJet80(readerhlt, pfjet80trigger);


    TTreeReaderValue<int> CaloJet40(readerhlt, calojet40trigger);
    TTreeReaderValue<int> CaloJet40v2(readerhlt, calojet40triggerv2);
    TTreeReaderValue<int> CaloJet60(readerhlt, calojet60trigger);
    TTreeReaderValue<int> CaloJet80(readerhlt, calojet80trigger);

    TTreeReaderValue<int> CSV60(readerhlt, csv60trigger);
    TTreeReaderValue<int> CSV80(readerhlt, csv80trigger);

    TTreeReader readercsv60object("hltobject/HLT_HIPuAK4CaloBJetCSV60_Eta2p1_v",f);
    TTreeReaderValue<vector<Double_t> > csv60pt(readercsv60object, "pt");
    TTreeReaderValue<vector<Double_t> > csv60eta(readercsv60object, "eta");
    TTreeReaderValue<vector<Double_t> > csv60phi(readercsv60object, "phi");
    
    TTreeReader readercsv80object("hltobject/HLT_HIPuAK4CaloBJetCSV80_Eta2p1_v",f);
    TTreeReaderValue<vector<Double_t> > csv80pt(readercsv80object, "pt");
    TTreeReaderValue<vector<Double_t> > csv80eta(readercsv80object, "eta");
    TTreeReaderValue<vector<Double_t> > csv80phi(readercsv80object, "phi");
    
    TTreeReader readerCalo60object("hltobject/HLT_HIPuAK4CaloJet60_Eta5p1_v",f);
    TTreeReaderValue<vector<Double_t> > calo60pt(readerCalo60object, "pt");
    TTreeReaderValue<vector<Double_t> > calo60eta(readerCalo60object, "eta");
    TTreeReaderValue<vector<Double_t> > calo60phi(readerCalo60object, "phi");
    
    TTreeReader readerCalo80object("hltobject/HLT_HIPuAK4CaloJet80_Eta5p1_v",f);
    TTreeReaderValue<vector<Double_t> > calo80pt(readerCalo80object, "pt");
    TTreeReaderValue<vector<Double_t> > calo80eta(readerCalo80object, "eta");
    TTreeReaderValue<vector<Double_t> > calo80phi(readerCalo80object, "phi");


    TTreeReader readerevt("hiEvtAnalyzer/HiTree",f);
    TTreeReaderValue<float> vz(readerevt, "vz");
    TTreeReaderValue<int> bin(readerevt, "hiBin");
    TTreeReaderValue<float> hiHF(readerevt, "hiHF");
    
    TTreeReaderValue<unsigned int> run(readerevt, "run");
    TTreeReaderValue<unsigned int> lumi(readerevt, "lumi");
    TTreeReaderValue<unsigned long long> event(readerevt, "evt");

    TTreeReader readerskim("skimanalysis/HltTree",f);

    vector<TTreeReaderValue<int> *>filters;
    for (auto f:filterNames)
      filters.push_back(new TTreeReaderValue<int>(readerskim, f));
      
    cout<<"added filters"<<endl;
    
    int nev = reader.GetEntries(true); cout<<nev<<endl;
    totentries+=nev;
    int onep = nev/100;
    int evCounter = 0;
    TTimeStamp t0;
    
    //for testing - only 10% of data
    //while (evCounter<2*onep && reader.Next()) {
    //go full file
    while (reader.Next()) {
      readerhlt.Next();
      readerevt.Next();
      readerskim.Next();
      readercsv60object.Next();
      readercsv80object.Next();
      readerCalo60object.Next();
      readerCalo80object.Next();

      evCounter++;
      if (evCounter%onep==0) {
        std::cout << std::fixed;
        TTimeStamp t1; 
        cout<<" \r"<<evCounter/onep<<"%   "<<" total time "<<(int)round((t1-t0)*nev/(evCounter+.1))<<" s "<<flush;
      }


      int bPFJet60 = !PbPb ? *PFJet60 : 1;
      int bPFJet80 = !PbPb ? *PFJet80 : 1;

      //int jet40 = *CaloJet40 || *CaloJet40v2;

      float weight = 1;

      if (!PbPb)
        weight = getweight(subfoldernames[i], bPFJet60, bPFJet80);


      if (PbPb && sample=="j60")
        weight = *CaloJet60;//only calojet 40

      ntevt->Fill(weight, *bin, *vz, *hiHF, *CSV60, *CSV80);

      if (weight==0) continue;

      //good event is vertex cut and noise cuts
      bool goodevent = abs(*vz)<15;
      for (auto f:filters) 
        goodevent&=*(*f);

      int ind1=-1, ind2=-1, ind3=-1, indSL=-1; //indices of leading/subleading jets in jet array
      int indTrigCSV60=-1, indTrigCSV80=-1, indTrigCalo60=-1, indTrigCalo80=-1;
      int SLord = 0;
      bool foundJ1=false, foundJ2 = false, foundJ3 = false, foundSL = false; //found/not found yet, for convenience

      bool triggermatched = false;

      if (goodevent)
        for (int j=0;j<*nref;j++) {
          //acceptance selection
          if (abs(jteta[j])>1.5) continue;
          //muon cuts
          if (PbPb) {
            if((*muMax)[j]/rawpt[j]>0.95) continue;
            if( ((*muMaxTRK)[j]-(*muMaxGBL)[j]) / ((*muMaxTRK)[j]+(*muMaxGBL)[j]) > 0.1) continue;
          }
  
          if (!foundJ1) { //looking for the leading jet
              ind1 = j;
              foundJ1=true;

	      if (PbPb) {
		indTrigCSV60 = triggeredLeadingJetCSV(jtphi[j], jteta[j], *csv60pt, *csv60phi, *csv60eta);
		indTrigCSV80 = triggeredLeadingJetCSV(jtphi[j], jteta[j], *csv80pt, *csv80phi, *csv80eta);
		indTrigCalo60 = triggeredLeadingJetCalo(jtphi[j], jteta[j], *calo60pt, *calo60phi, *calo60eta);
		indTrigCalo80 = triggeredLeadingJetCalo(jtphi[j], jteta[j], *calo80pt, *calo80phi, *calo80eta);
	      }
             
	      triggermatched = !PbPb || indTrigCSV60!=-1 || indTrigCSV80!=-1;
	  } else
            if (foundJ1 && !foundJ2) {
              ind2 = j;
              foundJ2 = true;
            } else
            if (foundJ1 && foundJ2 && !foundJ3) {
              ind3 = j;
              foundJ3 = true;
            }

          //we need ordinal number of SL jets, so counting until found
          //indSL != SLord because some jets are not in acceptance region
            if (!foundSL) SLord++;

          //ind1!=j otherwise SL will be = J1
            if (foundJ1 && ind1!=j && !foundSL && discr_csvV1[j]>0.9) {
              indSL = j;
              foundSL = true;
            }  




          //at this point foundLJ = true always, so triggermatched is determined
          vector<float> vinc = {weight, (float)triggermatched, (float) *bin, *vz, *hiHF,(float)*CSV60, (float)*CSV80,(float)*CaloJet40, (float)*CaloJet60, (float)*CaloJet80,
            (float)bPFJet60,(float)bPFJet80, rawpt[j], jtpt[j], jtphi[j], jteta[j], discr_csvV1[j],svtxm[j],discr_prob[j],
            svtxdls[j],svtxpt[j],(float)svtxntrk[j],(float)nsvtx[j],(float)nselIPtrk[j]};
  
          ntinc->Fill(&vinc[0]);
        }

      //fill dijet ntuple
      vector<float> vdj;

      vdj = {(float)*run, (float)*lumi, (float)*event, weight, (float)triggermatched, (float)*bin, *vz,*hiHF,
        (float)*CSV60, (float)*CSV80,(float)*CaloJet40,(float)*CaloJet60, (float)*CaloJet80,(float)bPFJet60,(float)bPFJet80, 
        foundJ1 && foundJ2 ? (float)1 : (float)0,

        indTrigCalo60!=-1 ? (float)(*calo60pt)[indTrigCalo60] : NaN,
        indTrigCalo60!=-1 ? (float)(*calo60phi)[indTrigCalo60] : NaN,
        indTrigCalo60!=-1 ? (float)(*calo60eta)[indTrigCalo60] : NaN,

        indTrigCalo80!=-1 ? (float)(*calo80pt)[indTrigCalo80] : NaN,
        indTrigCalo80!=-1 ? (float)(*calo80phi)[indTrigCalo80] : NaN,
        indTrigCalo80!=-1 ? (float)(*calo80eta)[indTrigCalo80] : NaN,

        indTrigCSV60!=-1  ? (float)(*csv60pt)[indTrigCSV60] : NaN,
        indTrigCSV60!=-1  ? (float)(*csv60phi)[indTrigCSV60] : NaN,
        indTrigCSV60!=-1  ? (float)(*csv60eta)[indTrigCSV60] : NaN,

        indTrigCSV80!=-1  ? (float)(*csv80pt)[indTrigCSV80] : NaN,
        indTrigCSV80!=-1  ? (float)(*csv80phi)[indTrigCSV80] : NaN,
        indTrigCSV80!=-1  ? (float)(*csv80eta)[indTrigCSV80] : NaN,
                                
        foundJ1 ? rawpt[ind1] : NaN,
        foundJ1 ? jtpt[ind1] : NaN,
        foundJ1 ? jtphi[ind1] : NaN,
        foundJ1 ? jteta[ind1] : NaN,
        foundJ1 ? discr_csvV1[ind1] : NaN,
        foundJ1 ? svtxm[ind1] : NaN,
        foundJ1 ? discr_prob[ind1] : NaN,
        foundJ1 ? svtxdls[ind1] : NaN,
        foundJ1 ? svtxpt[ind1] : NaN,
        foundJ1 ? (float)svtxntrk[ind1] : NaN,
        foundJ1 ? (float)nsvtx[ind1] : NaN,
        foundJ1 ? (float)nselIPtrk[ind1] : NaN,

        foundJ2 ? rawpt[ind2] : NaN,
        foundJ2 ? jtpt[ind2] : NaN,
        foundJ2 ? jtphi[ind2] : NaN,
        foundJ2 ? jteta[ind2] : NaN,
        foundJ2 ? discr_csvV1[ind2] : NaN,
        foundJ2 ? svtxm[ind2] : NaN,
        foundJ2 ? discr_prob[ind2] : NaN,
        foundJ2 ? svtxdls[ind2] : NaN, 
        foundJ2 ? svtxpt[ind2] : NaN,
        foundJ2 ? (float)svtxntrk[ind2] : NaN,
        foundJ2 ? (float)nsvtx[ind2] : NaN,
        foundJ2 ? (float)nselIPtrk[ind2] : NaN,
        foundJ2 && foundJ1 ? acos(cos(jtphi[ind2]-jtphi[ind1])) : NaN,
    
        foundJ3 ? rawpt[ind3] : NaN,
        foundJ3 ? jtpt[ind3] : NaN,
        foundJ3 ? jtphi[ind3] : NaN,
        foundJ3 ? jteta[ind3] : NaN,
        foundJ3 ? discr_csvV1[ind3] : NaN,
        foundJ3 ? svtxm[ind3] : NaN,
        foundJ3 ? discr_prob[ind3] : NaN,
        foundJ3 ? svtxdls[ind3] : NaN, 
        foundJ3 ? svtxpt[ind3] : NaN,
        foundJ3 ? (float)svtxntrk[ind3] : NaN,
        foundJ3 ? (float)nsvtx[ind3] : NaN,
        foundJ3 ? (float)nselIPtrk[ind3] : NaN,
        foundJ3 && foundJ1 ? acos(cos(jtphi[ind3]-jtphi[ind1])) : NaN,
        foundJ3 && foundJ2 ? acos(cos(jtphi[ind3]-jtphi[ind2])) : NaN,

        foundSL ? (float)SLord : NaN,
        foundSL ? rawpt[indSL] : NaN,
        foundSL ? jtpt[indSL] : NaN,
        foundSL ? jtphi[indSL] : NaN,
        foundSL ? jteta[indSL] : NaN,
        foundSL ? discr_csvV1[indSL] : NaN,
        foundSL ? svtxm[indSL] : NaN,
        foundSL ? discr_prob[indSL] : NaN,
        foundSL ? svtxdls[indSL] : NaN, 
        foundSL ? svtxpt[indSL] : NaN,
        foundSL ? (float)svtxntrk[indSL] : NaN,
        foundSL ? (float)nsvtx[indSL] : NaN,
        foundSL ? (float)nselIPtrk[indSL] : NaN,
        foundSL && foundJ1 ? acos(cos(jtphi[indSL]-jtphi[ind1])) : NaN};


      ntdj->Fill(&vdj[0]);



    }

    f->Close();
    }
  }
  
  foutevt->cd();
  ntevt->Write();
  foutevt->Close();

  foutdj->cd();
  ntdj->Write();
  foutdj->Close();

  foutinc->cd();
  ntinc->Write();
  foutinc->Close();

  cout<<endl;
  cout<<"Total input entries "<<totentries<<endl;

  //making centrality-dependent ntuples
  //PutInCbins(outputfolder, code, {{0,40}, {80,200}});

  if (PbPb && sample=="bjt"){
    auto w = calculateWeightsBjet(outputfilenamedj);

    updatePbPbBtriggerweight(outputfilenamedj,w);
    updatePbPbBtriggerweight(outputfilenameinc,w);
    updatePbPbBtriggerweight(outputfilenameevt,w);
  } else {
    updateweight(outputfilenamedj);
    updateweight(outputfilenameinc);
    updateweight(outputfilenameevt);
    }

}
コード例 #6
0
TF1 *bFeedDownFraction(double ptMin=20,double ptMax=25)
{
/*
   TFile *infMCP = new TFile("miniNtuplePrompt.root");
   TFile *infMCNP = new TFile("miniNtupleNonPrompt.root");
   TFile *infData = new TFile("miniData.root");
*/

   TFile *infMCP = new TFile("ntD_EvtBase_20160303_Dfinder_20160302_pp_Pythia8_prompt_D0_dPt0tkPt0p5_pthatweight.root");
   TFile *infMCNP = new TFile("ntD_EvtBase_20160303_Dfinder_20160302_pp_Pythia8_nonprompt_D0_dPt0tkPt0p5_pthatweight.root");
   // TFile *infData = new TFile("miniData.root");
   TFile *infData = new TFile("ppData.root");
    
   TTree *tMCP = (TTree*)infMCP->Get("ntDkpi");
   TTree *tMCNP = (TTree*)infMCNP->Get("ntDkpi");
   TTree *tMCPHI = (TTree*)infMCP->Get("ntHi");
   TTree *tMCNPHI = (TTree*)infMCNP->Get("ntHi");
   TTree *tData = (TTree*)infData->Get("ntDkpi");
   tMCP->AddFriend(tMCPHI);
   tMCNP->AddFriend(tMCNPHI);
   
   
   TFile *outf = new TFile(Form("output-%.0f-%.0f.root",ptMin,ptMax),"recreate");
   TNtuple *nt = new TNtuple("nt","","ptMin:ptMax:Frac:FracErr");
   TCanvas *cSideband = new TCanvas("cSideband","Data Sideband",1200,1200);
   cSideband->Divide(2,2);
   cSideband->cd(1);


   TCut cutpp ="Dy>-1.&&Dy<1.&&Dtrk1highPurity&&Dtrk2highPurity&&Dtrk1Pt>2.0&&Dtrk2Pt>2.0&&(DsvpvDistance/DsvpvDisErr)>3.5&&(DlxyBS/DlxyBSErr)>2.5&&Dchi2cl>0.05&&Dalpha<0.12&&Dtrk1PtErr/Dtrk1Pt<0.1&&Dtrk2PtErr/Dtrk2Pt<0.1&&abs(Dtrk1Eta)<2.0&&abs(Dtrk2Eta)<2.0&&Dtrk1Algo>3&&Dtrk1Algo<8&&Dtrk2Algo>3&&Dtrk2Algo<8&&(Dtrk1PixelHit+Dtrk1StripHit)>=11&&(Dtrk2PixelHit+Dtrk2StripHit)>=11&&(Dtrk1Chi2ndf/(Dtrk1nStripLayer+Dtrk1nPixelLayer)<0.15)&&(Dtrk2Chi2ndf/(Dtrk2nStripLayer+Dtrk2nPixelLayer)<0.15)";
   TCut cutmc="(Dgen==23333||Dgen==23344)";
   TCut cutpt=Form("Dpt>%f&&Dpt<%f",ptMin,ptMax);
   TCut cutSignal = "abs(Dmass-1.8649)<0.025";
   TCut cutSideband = "abs(Dmass-1.8649)>0.075&&abs(Dmass-1.8649)<0.1";
 //  TCut weightfuncFtionreco="((TMath::Erf((log(DsvpvDisErr))*(Dgenpt*Dgenpt*(-0.001)+0.1021*Dgenpt+1.247)+(Dgenpt*Dgenpt*(-0.0032)+0.2912*Dgenpt+6.8275))+1))*(pow(10,-0.168499*Dgenpt+3.872855+Dgenpt*Dgenpt*0.000556)+pow(10,-0.068599*Dgenpt+2.512265+Dgenpt*Dgenpt*0.000331))";
   TCut weightfunctionreco = "pthatweight";
   int nBin=20;
   double binL=3.5;
   double binH=103.5;
   double fitRangeL=3.5;
   double fitRangeH=100.5;

   if (ptMax<=6) {
      fitRangeH=43.5;
      binH=43.5;
   }

   float bins[6+1]={3.5,5.5,8.5,10.5,20.5,30.5,50.5};
   
   TH1D *hSideband = new TH1D("hSideband","Sideband",nBin,binL,binH);
   TH1D *hData = new TH1D("hData","Data",nBin,binL,binH);
   TH1D *hMCPSignal = new TH1D("hMCPSignal","Prompt",nBin,binL,binH);
   TH1D *hMCNPSignal = new TH1D("hMCNPSignal","Non-prompt",nBin,binL,binH);
   TH1D *hMCPSideband = new TH1D("hMCPSideband","",nBin,binL,binH);
   TH1D *hMCNPSideband = new TH1D("hMCNPSideband","",nBin,binL,binH);
   hSideband->Sumw2();
   hData->Sumw2();
   hMCPSignal->Sumw2();
   hMCNPSignal->Sumw2();

   
   tData->Draw("(DsvpvDistance/DsvpvDisErr)>>hSideband",cutpt&&cutpp&&cutSideband);
   tData->Draw("(DsvpvDistance/DsvpvDisErr)>>hData",cutpt&&cutpp&&cutSignal);
   tMCP->Draw("(DsvpvDistance/DsvpvDisErr)>>hMCPSignal",weightfunctionreco*(cutpt&&cutpp&&cutSignal&&cutmc));
   //tMCP->Draw("(DsvpvDistance/DsvpvDisErr)>>hMCPSideband",cutpt&&cutpp&&cutSideband);
   tMCNP->Draw("(DsvpvDistance/DsvpvDisErr)>>hMCNPSignal",weightfunctionreco*(cutpt&&cutpp&&cutSignal&&cutmc));
   //tMCNP->Draw("(DsvpvDistance/DsvpvDisErr)>>hMCNPSideband",cutpt&&cutpp&&cutSideband);
   
   hSideband->Scale(1./1.);
   hData->Add(hSideband,-1);
   normalize(hData,1);
   normalize(hMCPSignal,2);
   normalize(hMCNPSignal,4);
   normalize(hSideband,kGreen+2);
   
   
   
   TF1 *fSideband = new TF1("fSideband","[0]*(exp([1]*x+[2])+[3]*exp([4]*x+[5])+[6]*exp([7]*x+[8]))");     
   TF1 *fMCPSignal = new TF1("fMCPSignal","[0]*(exp([1]*x+[2])+[3]*exp([4]*x+[5])+[6]*exp([7]*x+[8]))");
   TF1 *fMCNPSignal = new TF1("fMCNPSignal","[0]*(exp([1]*x+[2])+[3]*exp([4]*x+[5])+[6]*exp([7]*x+[8]))");
   
   fSideband->SetParameters(0,-0.1,0.2,-0,-2,0.006,-0.01,-0.11,-0.04,0,0.001);
   fMCNPSignal->SetParameters(0,-0.1,0.1,-0,-0.02,0.006,-0.01,-0.11,-0.04,0,0.001);
   fMCPSignal->SetParameters(0,-0.1,0.1,-0,-0.02,0.006,-0.01,-0.11,-0.04,0,0.001);
//   fMCNPSignal->FixParameter(3,0);
//   fMCPSignal->FixParameter(3,0);
   fMCPSignal->SetParLimits(1,-100,0);   
   fMCPSignal->SetParLimits(4,-100,0);   
   fMCPSignal->SetParLimits(7,-100,0);   
   fMCNPSignal->SetParLimits(1,-100,0);   
   fMCNPSignal->SetParLimits(4,-100,0);   
   fMCNPSignal->SetParLimits(7,-100,0);   
   fMCPSignal->SetParLimits(0,0,1e10);   
   fMCPSignal->SetParLimits(3,0,1e10);   
   fMCPSignal->SetParLimits(6,0,1e10);   
   fMCNPSignal->SetParLimits(0,0,1e10);   
   fMCNPSignal->SetParLimits(3,0,1e10);   
   fMCNPSignal->SetParLimits(6,0,1e10);   

   hSideband->Fit("fMCPSignal","LL q","",fitRangeL,fitRangeH);
   hSideband->Fit("fMCPSignal","LL q","",fitRangeL,fitRangeH);
   hSideband->Fit("fMCPSignal","LL q","",fitRangeL,fitRangeH);
   hSideband->Fit("fMCPSignal","LL q","",fitRangeL,fitRangeH);
   hSideband->Fit("fMCPSignal","LL q","",fitRangeL,fitRangeH);
   hSideband->Fit("fMCNPSignal","LL q","",fitRangeL,fitRangeH);
   hSideband->Fit("fMCNPSignal","LL q","",fitRangeL,fitRangeH);
   hSideband->Fit("fMCNPSignal","LL q","",fitRangeL,fitRangeH);
   hSideband->Fit("fMCNPSignal","LL q","",fitRangeL,fitRangeH);
   hSideband->Fit("fMCNPSignal","LL q","",fitRangeL,fitRangeH);
   
   
   hSideband->Fit("fSideband","LL q","",fitRangeL,fitRangeH);
   hSideband->Fit("fSideband","LL q","",fitRangeL,fitRangeH);
   hSideband->Fit("fSideband"," q","",fitRangeL,fitRangeH);
   hSideband->Fit("fSideband"," q","",fitRangeL,fitRangeH);
   hSideband->Fit("fSideband","LL q","",fitRangeL,fitRangeH);
   hSideband->Fit("fSideband","LL q","",fitRangeL,fitRangeH);
   hSideband->Fit("fSideband"," q","",fitRangeL,fitRangeH);
   hSideband->Fit("fSideband"," q","",fitRangeL,fitRangeH);
   hSideband->Fit("fSideband","m q","",fitRangeL,fitRangeH);
   hSideband->Fit("fSideband","m q","",fitRangeL,fitRangeH);
   hSideband->Fit("fSideband","m q","",fitRangeL,fitRangeH);
   hSideband->Fit("fSideband"," q","",fitRangeL,fitRangeH);
   double normSideband = hSideband->Integral(0,0.12);
   
   cSideband->cd(2);
   hMCPSignal->Fit("fMCPSignal","LL q","",fitRangeL,fitRangeH);
   hMCPSignal->Fit("fMCPSignal","LL q","",fitRangeL,fitRangeH);
   hMCPSignal->Fit("fMCPSignal"," q","",fitRangeL,fitRangeH);
   hMCPSignal->Fit("fMCPSignal"," q","",fitRangeL,fitRangeH);
   hMCPSignal->Fit("fMCPSignal","LL q","",fitRangeL,fitRangeH);
   hMCPSignal->Fit("fMCPSignal","LL q","",fitRangeL,fitRangeH);
   hMCPSignal->Fit("fMCPSignal"," q","",fitRangeL,fitRangeH);
   hMCPSignal->Fit("fMCPSignal"," q","",fitRangeL,fitRangeH);
   hMCPSignal->Fit("fMCPSignal","m q","",fitRangeL,fitRangeH);
   hMCPSignal->Fit("fMCPSignal","m q","",fitRangeL,fitRangeH);
   hMCPSignal->Fit("fMCPSignal","m q","",fitRangeL,fitRangeH);
   hMCPSignal->Fit("fMCPSignal"," m q","",fitRangeL,fitRangeH);
   double normMCPSignal = hMCPSignal->Integral(0,0.12);

   cSideband->cd(3);
   hMCNPSignal->Fit("fMCNPSignal","LL q","",fitRangeL,fitRangeH);
   hMCNPSignal->Fit("fMCNPSignal","LL q","",fitRangeL,fitRangeH);
   hMCNPSignal->Fit("fMCNPSignal"," q","",fitRangeL,fitRangeH);
   hMCNPSignal->Fit("fMCNPSignal"," q","",fitRangeL,fitRangeH);
   hMCNPSignal->Fit("fMCNPSignal","LL q","",fitRangeL,fitRangeH);
   hMCNPSignal->Fit("fMCNPSignal","LL q","",fitRangeL,fitRangeH);
   hMCNPSignal->Fit("fMCNPSignal"," q","",fitRangeL,fitRangeH);
   hMCNPSignal->Fit("fMCNPSignal"," q","",fitRangeL,fitRangeH);
   hMCNPSignal->Fit("fMCNPSignal","m q","",fitRangeL,fitRangeH);
   hMCNPSignal->Fit("fMCNPSignal","m q","",fitRangeL,fitRangeH);
   hMCNPSignal->Fit("fMCNPSignal","m q","",fitRangeL,fitRangeH);
   hMCNPSignal->Fit("fMCNPSignal","m q","",fitRangeL,fitRangeH);
   
   double normMCNPSignal = hMCNPSignal->Integral(0,0.12);
   
   
   string sSideband = Form("(%e)*(exp((%e)*x+(%e))+(%e)*exp((%e)*x+(%e))+(%e)*exp((%e)*x+(%e)))",fSideband->GetParameter(0),fSideband->GetParameter(1),fSideband->GetParameter(2),fSideband->GetParameter(3),fSideband->GetParameter(4),fSideband->GetParameter(5),fSideband->GetParameter(6),fSideband->GetParameter(7),fSideband->GetParameter(8));
   string sMCPSignal = Form("(%e)*(exp((%e)*x+(%e))+(%e)*exp((%e)*x+(%e))+(%e)*exp((%e)*x+(%e)))",fMCPSignal->GetParameter(0),fMCPSignal->GetParameter(1),fMCPSignal->GetParameter(2),fMCPSignal->GetParameter(3),fMCPSignal->GetParameter(4),fMCPSignal->GetParameter(5),fMCPSignal->GetParameter(6),fMCPSignal->GetParameter(7),fMCPSignal->GetParameter(8));
   
   string sMCNPSignal = Form("(%e)*(exp((%e)*x+(%e))+(%e)*exp((%e)*x+(%e))+(%e)*exp((%e)*x+(%e)))",fMCNPSignal->GetParameter(0),fMCNPSignal->GetParameter(1),fMCNPSignal->GetParameter(2),fMCNPSignal->GetParameter(3),fMCNPSignal->GetParameter(4),fMCNPSignal->GetParameter(5),fMCNPSignal->GetParameter(6),fMCNPSignal->GetParameter(7),fMCNPSignal->GetParameter(8));
   
   
   string function;
   function="0*("+sSideband+")+[1]*([2]*"+sMCPSignal+"+(1-[2])*("+sMCNPSignal+"))";
   string functionNP;
   functionNP="0*("+sSideband+")+[1]*(0*"+sMCPSignal+"+(1-[2])*("+sMCNPSignal+"))";
   
    
   TCanvas *cFit = new TCanvas("cFit","Fit",600,600);
   TF1 *f = new TF1("f",function.c_str());
   f->SetParameters(1,0.1,0.9,0,0.1);
   f->SetParLimits(0,0,1000);
   f->SetParLimits(2,-1,2);
   f->SetLineColor(2);
   f->SetFillColor(2);
   f->SetFillStyle(3001);
   f->Draw("same");   
   hData->SetAxisRange(fitRangeL,fitRangeH,"X");
   hData->Fit("f","LL");
   hData->Fit("f","LL");
   hData->Fit("f","LL");
   hData->Fit("f","LL");
   hData->Fit("f","m");
   hData->SetXTitle("Flight Distance Significance");
   hData->SetYTitle("Event Fraction");
   
   TF1 *fNP = new TF1("fNP",functionNP.c_str());
   fNP->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2));
   fNP->SetRange(fitRangeL,fitRangeH*2);
   fNP->SetLineColor(4);
   fNP->SetFillStyle(3001);
   fNP->SetFillColor(4);
   hData->SetStats(0);
   hData->Draw("same");
   fNP->Draw("same");  

   cout <<fNP->Integral(3.5,60)/f->Integral(3.5,60)<<endl;

   TLegend *leg = new TLegend(0.5,0.7,0.9,0.9);
   leg->SetBorderSize(0);
   leg->SetFillStyle(0);
   leg->AddEntry(hData,"pp data","pl");
   leg->AddEntry(f,Form("Prompt Fraction %.1f #pm %.1f %%",100*f->GetParameter(2),100*f->GetParError(2)),""); 
   leg->AddEntry(f,"Prompt D^{0}","f");
   leg->AddEntry(fNP,"Non-Prompt D^{0}","f");
   
   leg->Draw();
   
   cSideband->cd(4);
   hMCPSignal->Draw("hist");
   hSideband->Draw("hist same");
   hMCNPSignal->Draw("hist same");
   hData->Draw("same");
   nt->Fill(ptMin,ptMax,f->GetParameter(2),f->GetParError(2));
   nt->Write();
   outf->Write();
//   outf->Close();	
   return f;
}
コード例 #7
0
ファイル: Bd2JpsiKst_reflections.C プロジェクト: goi42/lhcb
void Bd2JpsiKst_reflections::Loop()
{
	gROOT->ProcessLine(".x /Users/gcowan/lhcb/lhcbStyle.C");
	if (fChain == 0) return;

	Long64_t nentries = fChain->GetEntriesFast();

	//TH1D * mKK  = new TH1D("mKK", "mKK", 100, 0.99, 1.050);
	TH1D * mKK  = new TH1D("mKK", "mKK", 100, 1.45, 1.55);
	//TH1D * mKK  = new TH1D("mKK", "mKK", 100, 0.4, 0.6);
	TH1D * mKpi = new TH1D("mKpi", "mKpi", 100, 0.826, 0.966);
	TH1D * massHisto  = new TH1D("mBd_DTF", "mBd_DTF", 100, 5.15, 5.4);
	TH1D * mBd  = new TH1D("mBd", "mBd", 100, 5.15, 5.4);
	TH1D * mBs  = new TH1D("mBs", "mBs", 100, 5.20, 5.55);
	//TH1D * mB_lower = new TH1D("lower_sideband", "lower_sideband", 100, 5.15, 5.4);
	//TH1D * mB_upper = new TH1D("upper_sideband", "upper_sideband", 100, 5.15, 5.4);
	//TH1D * mB_lower = new TH1D("lower_sideband", "lower_sideband", 60, 5.3, 5.45); // for looking at Bs -> JpsiKK where K -> pi misid
	//TH1D * mB_upper = new TH1D("upper_sideband", "upper_sideband", 60, 5.3, 5.45);// for looking at Bs -> JpsiKK where K -> pi misid
	TH1D * mB_lower = new TH1D("lower_sideband", "lower_sideband", 40, 5.55, 5.7);
	TH1D * mB_upper = new TH1D("upper_sideband", "upper_sideband", 40, 5.55, 5.7);
	TH1D * mJpsi_ = new TH1D("mJpsi", "mJpsi", 100, 3.03, 3.15);
	TH1D * mJpsi_constr = new TH1D("mJpsi_constr", "mJpsi", 100, 3.03, 3.15);
	
	Long64_t nbytes = 0, nb = 0;

	TFile * file = TFile::Open("reflection_upper_sideband.root", "RECREATE");
	TNtuple * tuple = new TNtuple("DecayTree","DecayTree", "mass");

	for (Long64_t jentry=0; jentry<nentries;jentry++) {
	//for (Long64_t jentry=0; jentry<1000;jentry++) {
		Long64_t ientry = LoadTree(jentry);
		if (ientry < 0) break;
		nb = fChain->GetEntry(jentry);   nbytes += nb;

		double mpi = 139.57018;
		double mK = 493.68;
		double mmu = 105.658;
		double mJpsi = 3096.916;
		double mp = 938.27;
		TLorentzVector Kplus(K1_Px, K1_Py, K1_Pz, sqrt(K1_Px*K1_Px+K1_Py*K1_Py+K1_Pz*K1_Pz + mK*mK));
		TLorentzVector Piminus(Pi1_Px, Pi1_Py, Pi1_Pz, sqrt(Pi1_Px*Pi1_Px+Pi1_Py*Pi1_Py+Pi1_Pz*Pi1_Pz + mpi*mpi));
		TLorentzVector KplusWrong(K1_Px, K1_Py, K1_Pz, sqrt(K1_Px*K1_Px+K1_Py*K1_Py+K1_Pz*K1_Pz + mpi*mpi));
		//TLorentzVector PiminusWrong(Pi1_Px, Pi1_Py, Pi1_Pz, sqrt(Pi1_Px*Pi1_Px+Pi1_Py*Pi1_Py+Pi1_Pz*Pi1_Pz + mK*mK));
		TLorentzVector PiminusWrong(Pi1_Px, Pi1_Py, Pi1_Pz, sqrt(Pi1_Px*Pi1_Px+Pi1_Py*Pi1_Py+Pi1_Pz*Pi1_Pz + mp*mp));
		TLorentzVector muplus(Mu1_Px, Mu1_Py, Mu1_Pz, sqrt(Mu1_P*Mu1_P + mmu*mmu));
		TLorentzVector muminus(Mu2_Px, Mu2_Py, Mu2_Pz, sqrt(Mu2_P*Mu2_P + mmu*mmu));
		TLorentzVector Jpsi = muplus + muminus;
		TLorentzVector Jpsi_constr(Mu2_Px+Mu1_Px, Mu2_Py+Mu1_Py, Mu2_Pz+Mu1_Pz, sqrt(Jpsi.P()*Jpsi.P() + mJpsi*mJpsi));
		
		TLorentzVector KK = Kplus + PiminusWrong; // testing Bs -> JpsiKK hypothesis
		//TLorentzVector KK = Piminus + KplusWrong; // testing Bd -> Jpsi pipi hypothesis
		TLorentzVector Kpi = Kplus + Piminus;
		TLorentzVector B = Jpsi_constr + Kpi;
		TLorentzVector BKK = Jpsi_constr + KK;
		
		mKK->Fill(KK.M()/1000.);
		mKpi->Fill(Kpi.M()/1000.);
		mBd->Fill(B.M()/1000.);
		massHisto->Fill(Bd_M/1000.);
		mJpsi_->Fill(Jpsi.M()/1000.);
		mJpsi_constr->Fill(Jpsi_constr.M()/1000.);
		if (Bd_M > 5320) mB_upper->Fill(BKK.M()/1000.);
		if (Bd_M < 5230) mB_lower->Fill(BKK.M()/1000.);
		if (Bd_M > 5320) tuple->Fill(BKK.M());
	}

	tuple->Write();
	file->Close();

	std::cout << "Number of B candidates " << mBs->GetEntries() << std::endl;

	TCanvas * c = new TCanvas("c","c",1600,1200);
	c->SetBottomMargin(0);
	c->Divide(3,2, 0.01, 0.01);
	c->cd(1);
	mKK->Draw();
	mKK->SetTitle("");
	//mKK->GetXaxis()->SetTitle("m(KK) [GeV/c^{2}]");
	mKK->GetXaxis()->SetTitle("m(Kp) [GeV/c^{2}]");
	c->cd(2);
	mJpsi_->Draw();
	mJpsi_->SetTitle("");
	mJpsi_->GetXaxis()->SetTitle("m(#mu#mu) [GeV/c^{2}]");
	c->cd(3);
	mKpi->Draw();
	mKpi->SetTitle("");
	mKpi->GetXaxis()->SetTitle("m(K#pi) [GeV/c^{2}]");
	c->cd(4);
	massHisto->Draw();
	//massHisto->SetMaximum(1500);
	mBd->SetLineColor(kRed);
	mBd->Draw("same");
	massHisto->SetTitle("");
	massHisto->GetXaxis()->SetTitle("DTF m(J/#psi K#pi) [GeV/c^{2}]");
	c->cd(5);
	mB_lower->Draw();
	mB_lower->SetTitle("");
	mB_lower->GetXaxis()->SetTitle("m(J/#psi Kp) [GeV/c^{2}]");
	//mB_lower->GetXaxis()->SetTitle("m(J/#psi KK) [GeV/c^{2}]");
	c->cd(6);
	mB_upper->Draw();
	mB_upper->SetTitle("");
	mB_upper->GetXaxis()->SetTitle("m(J/#psi Kp) [GeV/c^{2}]");
	//mB_upper->GetXaxis()->SetTitle("m(J/#psi KK) [GeV/c^{2}]");
	c->SaveAs("plots_Bd2JpsiKst_reflections.pdf");
}
コード例 #8
0
ファイル: phihist.cpp プロジェクト: rodmendezp/PiPlusAnalysis
int main(int argc, char **argv)
{
	TFile *f;
	TFile *newf;
	TNtuple *ntuple;
	TNtuple *newntuple;
	TH1F *h1;
	TF1 *func;
	TString Metal;
	TString dataLoc;
	Int_t dataSL;
	
	if(argc < 5 || argc > 6){
		std::cout << "The number of arguments is incorrect" << std::endl;
		return 0;
	}
	
	dataLoc = argv[1];
	PHI_MIN = (Double_t) std::stod(argv[2]);
	PHI_MAX = (Double_t) std::stod(argv[3]);
	N_PHI = (Int_t) std::stoi(argv[4]);
	if(argc >= 6) Metal = argv[5];
		
	dataSL = dataLoc.Length();
	if(dataLoc(dataSL-1, 1) != "/"){
		dataLoc = dataLoc + "/";
	}	
	
	std::cout << "The following settings are being used" << std::endl;
	std::cout << "Data Directory = " << dataLoc << std::endl;
	std::cout << PHI_MIN << " < PHI < " << PHI_MAX << ", N_PHI = " << N_PHI << std::endl;
	if(argc == 6) std::cout << "Running only for Metal "<< Metal << std::endl;
	else std::cout << "Running all Metals" << std::endl;	
	
	Float_t Q2, Xb, Zh, Pt, Phi, Val, Err;
	Float_t A, Ac, Acc;
	Float_t AErr, AcErr, AccErr;
	Float_t ChiSQ;

	Int_t nentries, empty;

	if(Metal == "") N_METAL = 6;
	else N_METAL = 1;
	
	for(Int_t met = 0; met < N_METAL; met++){
		if(Metal == ""){
			if(met == 0) Metal = "C";
			else if(met == 1) Metal = "Fe";
			else if(met == 2) Metal = "Pb";
			else if(met == 3) Metal = "D_C";
			else if(met == 4) Metal = "D_Fe";
			else if(met == 5) Metal = "D_Pb";
		}
		if(dataLoc == "")
			f = new TFile("../Gen5DimData/" + Metal + "_5_dim_dist.root", "READ");
		else
			f = new TFile(dataLoc + Metal + "_5_dim_dist.root", "READ");
		ntuple = (TNtuple*) f->Get("fit_data");

		nentries = ntuple->GetEntries();
		ntuple->SetBranchAddress("Xb", &Xb);
		ntuple->SetBranchAddress("Q2", &Q2);
		ntuple->SetBranchAddress("Xb", &Xb);
		ntuple->SetBranchAddress("Zh", &Zh);
		ntuple->SetBranchAddress("Pt", &Pt);
		ntuple->SetBranchAddress("Phi", &Phi);
		ntuple->SetBranchAddress("Val", &Val);
		ntuple->SetBranchAddress("Err", &Err);

		newntuple = new TNtuple("AAcAcc_data", "AAcAcc_data", "Q2:Xb:Zh:Pt:A:AErr:Ac:AcErr:Acc:AccErr:ChiSQ");
		func = new TF1("fit", "[0]+TMath::Cos(x*TMath::Pi()/180)*[1]+TMath::Cos(2*x*TMath::Pi()/180)*[2]");

		newf = new TFile(Metal + "newphihist.root", "RECREATE");
		newf->cd();

		for(Int_t i = 0; i < nentries; i = i + N_PHI){
			ntuple->GetEntry(i);
			h1 = new TH1F((const char*) Form("PhiDist Q2=%.3f Xb=%.3f Zh=%.3f Pt=%.3f", Q2, Xb, Zh, Pt), 
							(const char*) Form("PhiDist Q2=%.3f Xb=%.3f Zh=%.3f Pt=%.3f", Q2, Xb, Zh, Pt), N_PHI, PHI_MIN, PHI_MAX);
			empty = 0;
			for(Int_t j = 1; j <= N_PHI; j++){
				ntuple->GetEntry(i+j-1);
				h1->SetBinContent(j, Val);
				if(h1->GetBinContent(j) == 0)
					empty++;
				h1->SetBinError(j, Err*1.04);
			}
			if(empty <= (N_PHI - MIN_BIN)){
				h1->Fit(func, "q");
				h1->Write();
				if(func->GetNDF() != 0){
					ChiSQ = func->GetChisquare();
					A = func->GetParameter(0);
					AErr = func->GetParError(0);
					Ac = func->GetParameter(1);
					AcErr = func->GetParError(1);
					Acc = func->GetParameter(2);
					AccErr = func->GetParError(2);
					newntuple->Fill(Q2, Xb, Zh, Pt, A, AErr, Ac, AcErr, Acc, AccErr, ChiSQ);
				}
			}
			h1->Delete();
		}
		
		Metal = "";
		
		delete ntuple;
		
		newf->cd();
		newntuple->Write();
		newntuple->Delete();
		newf->Close();
		delete newf;
		f->Close();
		delete f;
	}
	return 0;
}
コード例 #9
0
void createGlauberTree(Int_t nEvents,
                       const char *outFileName) 
{
  AliPDG::AddParticlesToPdgDataBase();
  TDatabasePDG::Instance();

  // Run loader
  TFolder *folder = new TFolder("myfolder","myfolder");
  AliRunLoader* rl = new AliRunLoader(folder);
  rl->MakeHeader();
  rl->MakeStack();
  AliStack* stack = rl->Stack();
  //AliHeader* rheader = rl->GetHeader();

  AliGenHijing *genHi = new AliGenHijing(-1);
  genHi->SetStack(stack);
  genHi->SetEnergyCMS(2760);
  genHi->SetReferenceFrame("CMS");
  genHi->SetProjectile("A", 208, 82);
  genHi->SetTarget    ("A", 208, 82);
  genHi->SetPtHardMin (2.3);
  genHi->SetImpactParameterRange(0.,30);
  genHi->SetJetQuenching(0); // enable jet quenching
  genHi->SetShadowing(1);    // enable shadowing
  genHi->SetDecaysOff(1);    // neutral pion and heavy particle decays switched off
  genHi->Init();

  MyHeader  *myheader = new MyHeader;
  MyResponse *myresp  = new MyResponse;

  TFile *outFile = TFile::Open(outFileName, "RECREATE");
  outFile->SetCompressionLevel(5);
  TDirectory::TContext context(outFile);

  TTree *tree = new TTree("glaubertree", "Glauber tree");
  tree->Branch("header",&myheader, 32*1024, 99);
  tree->Branch("response",&myresp, 32*1024, 99);

  TNtuple *ntuple = new TNtuple("gnt", "Glauber ntuple", "npart:ncoll:b");

  Double_t etas[] = {-10,-5,-4,-3,-2,-1,0,1,2,3,4,5,10};
  TH1D *hNEta = new TH1D("hNeta","",12,etas);
  TH1D *hEtEta = new TH1D("hEteta","",12,etas);

  // create events and fill them
  for (Int_t iEvent = 0; iEvent < nEvents; ++iEvent) {

    cout << "Event " << iEvent+1 << "/" << nEvents << endl;;
    stack->Reset();
    hNEta->Reset();
    hEtEta->Reset();
    genHi->Generate();
  
    AliStack *s = genHi->GetStack();
    const TObjArray *parts = s->Particles();
    Int_t nents = parts->GetEntries();
    for (Int_t i = 0; i<nents; ++i) {
      TParticle *p = (TParticle*)parts->At(i);
      //p->Print();
      TParticlePDG *pdg = p->GetPDG(1);
      Int_t c = (Int_t)(TMath::Abs(pdg->Charge()));
      if (c!=0) {
        hNEta->Fill(p->Eta());
        hEtEta->Fill(p->Eta(),p->Pt());
      }
    }

    AliGenHijingEventHeader *h = (AliGenHijingEventHeader*)genHi->CollisionGeometry();
    myheader->fNATT = nents;
    myheader->fEATT = h->TotalEnergy();
    myheader->fJATT = h->HardScatters();
    myheader->fNT   = h->TargetParticipants();
    myheader->fNP   = h->ProjectileParticipants();
    myheader->fN00  = h->NwNw();
    myheader->fN01  = h->NwN();
    myheader->fN10  = h->NNw();
    myheader->fN11  = h->NN();
    myheader->fBB   = h->ImpactParameter();
    myheader->fRP   = h->ReactionPlaneAngle();
    myheader->fPSn  = h->ProjSpectatorsn();
    myheader->fPSp  = h->ProjSpectatorsp();
    myheader->fTSn  = h->TargSpectatorsn();
    myheader->fTSp  = h->TargSpectatorsn();

    myresp->fEtch0p = hEtEta->GetBinContent(hEtEta->FindBin(0.5));
    myresp->fEtch1p = hEtEta->GetBinContent(hEtEta->FindBin(1.5));
    myresp->fEtch2p = hEtEta->GetBinContent(hEtEta->FindBin(2.5));
    myresp->fEtch3p = hEtEta->GetBinContent(hEtEta->FindBin(3.5));
    myresp->fEtch4p = hEtEta->GetBinContent(hEtEta->FindBin(4.5));
    myresp->fEtch5p = hEtEta->GetBinContent(hEtEta->FindBin(5.5));
    myresp->fEtchrp = hEtEta->GetBinContent(hEtEta->FindBin(10.5));
    myresp->fEtch0n = hEtEta->GetBinContent(hEtEta->FindBin(-0.5));
    myresp->fEtch1n = hEtEta->GetBinContent(hEtEta->FindBin(-1.5));
    myresp->fEtch2n = hEtEta->GetBinContent(hEtEta->FindBin(-2.5));
    myresp->fEtch3n = hEtEta->GetBinContent(hEtEta->FindBin(-3.5));
    myresp->fEtch4n = hEtEta->GetBinContent(hEtEta->FindBin(-4.5));
    myresp->fEtch5n = hEtEta->GetBinContent(hEtEta->FindBin(-5.5));
    myresp->fEtchrn = hEtEta->GetBinContent(hEtEta->FindBin(-10.5));
    myresp->fNch0p  = hNEta->GetBinContent(hNEta->FindBin(0.5));
    myresp->fNch1p  = hNEta->GetBinContent(hNEta->FindBin(1.5));
    myresp->fNch2p  = hNEta->GetBinContent(hNEta->FindBin(2.5));
    myresp->fNch3p  = hNEta->GetBinContent(hNEta->FindBin(3.5));
    myresp->fNch4p  = hNEta->GetBinContent(hNEta->FindBin(4.5));
    myresp->fNch5p  = hNEta->GetBinContent(hNEta->FindBin(5.5));
    myresp->fNchrp  = hNEta->GetBinContent(hNEta->FindBin(10.5));
    myresp->fNch0n  = hNEta->GetBinContent(hNEta->FindBin(-0.5));
    myresp->fNch1n  = hNEta->GetBinContent(hNEta->FindBin(-1.5));
    myresp->fNch2n  = hNEta->GetBinContent(hNEta->FindBin(-2.5));
    myresp->fNch3n  = hNEta->GetBinContent(hNEta->FindBin(-3.5));
    myresp->fNch4n  = hNEta->GetBinContent(hNEta->FindBin(-4.5));
    myresp->fNch5n  = hNEta->GetBinContent(hNEta->FindBin(-5.5));
    myresp->fNchrn  = hNEta->GetBinContent(hNEta->FindBin(-10.5));

    tree->Fill();

    if (ntuple) {
      Int_t np = h->TargetParticipants() + h->ProjectileParticipants();
      Int_t nc = h->NwNw() + h->NwN() + h->NNw() + h->NN();
      Double_t b = h->ImpactParameter();
      ntuple->Fill(np,nc,b);
    }

  } // end of event loop

  tree->Write();
  ntuple->Write();
  outFile->Close();
}
コード例 #10
0
ファイル: makeSmearedTable.C プロジェクト: KiSooLee/TnP_B
//------------------------------------------------------------------------
void makeSmearedTable(const int nbins = 100, const string label = "HFtowersPlusTrunc", const char * tag = "CentralityTable_HFtowersPlusTrunc_SmearedGlauber_sigma74_eff0_v5", int eff = 0) {

 TH1::SetDefaultSumw2();
 const char * inputMCforest = Form("/tmp/azsigmon/HiForest_pPb_Hijing_NEWFIX_v2.root");

 ProduceResponsePlots2(inputMCforest);

 bool plot = false;
 if(plot) {
   TCanvas *c1 = new TCanvas();
   Npart_vs_PtGenPlusEta4[0]->Draw("colz");
   TCanvas *c2 = new TCanvas();
   PtGenPlusEta4_vs_HFplusEta4[0]->Draw("colz");
   TCanvas *c3 = new TCanvas();
   Npart_vs_PtGenMinusEta4[0]->Draw("colz");
   TCanvas *c4 = new TCanvas();
   PtGenMinusEta4_vs_HFminusEta4[0]->Draw("colz");
   TCanvas *c5 = new TCanvas();
   Npart_vs_Ngentrk[0]->Draw("colz");
   TCanvas *c6 = new TCanvas();
   Ngentrk_vs_Ntracks[0]->Draw("colz");
 }

 bool binHFplusTrunc = label.compare("HFtowersPlusTrunc") == 0;
 bool binHFminusTrunc = label.compare("HFtowersMinusTrunc") == 0;
 bool binTracks = label.compare("Tracks") == 0;

 if (binHFplusTrunc) {
   getProjections(Npart_vs_PtGenPlusEta4[eff],Proj1,"Proj1",1,30);
   getProjections(PtGenPlusEta4_vs_HFplusEta4[eff],Proj2,"Proj2",1,140);
 }
 else if (binHFminusTrunc) {
   getProjections(Npart_vs_PtGenMinusEta4[0],Proj1,"Proj1",1,30);
   getProjections(PtGenMinusEta4_vs_HFminusEta4[0],Proj2,"Proj2",1,140);
 }
 else if (binTracks) {
   getProjections(Npart_vs_Ngentrk[0],Proj1,"Proj1",1,30);
   getProjections(Ngentrk_vs_Ntracks[0],Proj2,"Proj2",1,200);
 }

 //input Glauber ntuple
 const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/Standard/Phob_Glau_pPb_sNN70mb_v15_1M_dmin04.root");
 //const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/D/D04914/Phob_Glau_pPb_sNN70mb_v15_1M_D04914.root");
 //const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/D/D06006/Phob_Glau_pPb_sNN70mb_v15_1M_D06006.root");
 //const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/R/R649/Phob_Glau_pPb_sNN70mb_v15_1M_R649.root");
 //const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/R/R675/Phob_Glau_pPb_sNN70mb_v15_1M_R675.root");
 //const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/dmin/dmin00/Phob_Glau_pPb_sNN70mb_v15_1M_dmin00.root");
 //const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/dmin/dmin08/Phob_Glau_pPb_sNN70mb_v15_1M_dmin08.root");
 //const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/sigma/sigma66/Phob_Glau_pPb_sNN66mb_v15_1M_dmin04.root");
 //const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/sigma/sigma74/Phob_Glau_pPb_sNN74mb_v15_1M_dmin04.root");
 TChain * t = new TChain("nt_p_Pb");
 t->Add(infilename);

 //output
 //const char* outfilename = "out/tables_Glauber2012B_AmptResponse_d20130116_v4.root";
 //const char* outfilename = "out/tables_Glauber2012B_EposLHCResponse_d20130118_v4.root";
 const char* outfilename = "out/tables_Glauber2012B_HijingResponse_d20130130_v5.root";
 TFile * outf = new TFile(outfilename,"update");
 outf->cd();
 TDirectory* dir = outf->mkdir(tag);
 dir->cd();
 TNtuple* nt = new TNtuple("nt","","HFbyPt:genPt:Bin:b:Npart:Ncoll:Nhard");
 CentralityBins * outputTable = new CentralityBins(Form("run%d",1), tag, nbins);
 outputTable->table_.reserve(nbins);

 ofstream txtfile("out/output.txt");
 txtfile << "Input Glauber tree: " << infilename << endl << "Input MC HiForest HIJING" << endl;

 //Setting up variables and branches
 double binboundaries[nbins+1];
 vector<float> values;

 float b, npart, ncoll, nhard, parameter;

 t->SetBranchAddress("B",&b);
 t->SetBranchAddress("Npart",&npart);
 t->SetBranchAddress("Ncoll",&ncoll);
 nhard = 0;

 //Event loop 1
 unsigned int Nevents = t->GetEntries();
 txtfile << "Number of events = " << Nevents << endl << endl;
 for(unsigned int iev = 0; iev < Nevents; iev++) {
   if(iev%20000 == 0) cout<<"Processing event: " << iev << endl;
   t->GetEntry(iev);

   if (binHFplusTrunc) parameter = getHFplusByPt(npart);
   if (binHFminusTrunc) parameter = getHFminusByPt(npart);
   if (binTracks) parameter = getTracksByGen(npart);

   values.push_back(parameter);
 }

 if(label.compare("b") == 0) sort(values.begin(),values.end(),descend);
 else sort(values.begin(),values.end());

 //Finding the bin boundaries
 txtfile << "-------------------------------------" << endl;
 txtfile << label.data() << " based cuts are: " << endl;
 txtfile << "(";

 int size = values.size();
 binboundaries[nbins] = values[size-1];

 for(int i = 0; i < nbins; i++) {
   int entry = (int)(i*(size/nbins));
   if(entry < 0 || i == 0) binboundaries[i] = 0;
   else binboundaries[i] = values[entry];
   txtfile << binboundaries[i] << ", ";
 }
 txtfile << binboundaries[nbins] << ")" << endl << "-------------------------------------" << endl;

 // Determining Glauber results in various bins
 TH2D* hNpart = new TH2D("hNpart","",nbins,binboundaries,40,0,40);
 TH2D* hNcoll = new TH2D("hNcoll","",nbins,binboundaries,40,0,40);
 TH2D* hNhard = new TH2D("hNhard","",nbins,binboundaries,50,0,50);
 TH2D* hb = new TH2D("hb","",nbins,binboundaries,600,0,30);

 for(unsigned int iev = 0; iev < Nevents; iev++) {
   if( iev % 20000 == 0 ) cout<<"Processing event : " << iev << endl;
   t->GetEntry(iev);

   if (binHFplusTrunc) parameter = getHFplusByPt(npart);
   if (binHFminusTrunc) parameter = getHFminusByPt(npart);
   if (binTracks) parameter = getTracksByGen(npart);

   hNpart->Fill(parameter,npart);
   hNcoll->Fill(parameter,ncoll);
   hNhard->Fill(parameter,nhard);
   hb->Fill(parameter,b);

   int bin = hNpart->GetXaxis()->FindBin(parameter) - 1;
   if(bin < 0) bin = 0;
   if(bin >= nbins) bin = nbins - 1;
   nt->Fill(parameter, et, bin, b, npart, ncoll, nhard);
 }

 TCanvas *cf = new TCanvas();
 TF1* fGaus = new TF1("fb","gaus(0)",0,2);
 fitSlices(hNpart,fGaus);
 fitSlices(hNcoll,fGaus);
 fitSlices(hNhard,fGaus);
 fitSlices(hb,fGaus);

 TH1D* hNpartMean = (TH1D*)gDirectory->Get("hNpart_1");
 TH1D* hNpartSigma = (TH1D*)gDirectory->Get("hNpart_2");
 TH1D* hNcollMean = (TH1D*)gDirectory->Get("hNcoll_1");
 TH1D* hNcollSigma = (TH1D*)gDirectory->Get("hNcoll_2");
 TH1D* hNhardMean = (TH1D*)gDirectory->Get("hNhard_1");
 TH1D* hNhardSigma = (TH1D*)gDirectory->Get("hNhard_2");
 TH1D* hbMean = (TH1D*)gDirectory->Get("hb_1");
 TH1D* hbSigma = (TH1D*)gDirectory->Get("hb_2");

 txtfile<<"-------------------------------------"<<endl;
 txtfile<<"# Bin NpartMean NpartSigma NcollMean NcollSigma bMean bSigma BinEdge"<<endl;
 for(int i = 0; i < nbins; i++){
   int ii = nbins-i;
   outputTable->table_[i].n_part_mean = hNpartMean->GetBinContent(ii);
   outputTable->table_[i].n_part_var = hNpartSigma->GetBinContent(ii);
   outputTable->table_[i].n_coll_mean = hNcollMean->GetBinContent(ii);
   outputTable->table_[i].n_coll_var = hNcollSigma->GetBinContent(ii);
   outputTable->table_[i].b_mean = hbMean->GetBinContent(ii);
   outputTable->table_[i].b_var = hbSigma->GetBinContent(ii);
   outputTable->table_[i].n_hard_mean = hNhardMean->GetBinContent(ii);
   outputTable->table_[i].n_hard_var = hNhardSigma->GetBinContent(ii);
   outputTable->table_[i].bin_edge = binboundaries[ii-1];

   txtfile << i << " " << hNpartMean->GetBinContent(ii) << " " << hNpartSigma->GetBinContent(ii) << " " << hNcollMean->GetBinContent(ii) << " " << hNcollSigma->GetBinContent(ii) << " " << hbMean->GetBinContent(ii) << " " <<hbSigma->GetBinContent(ii) << " " << binboundaries[ii-1] << " " <<endl;
 }
 txtfile<<"-------------------------------------"<<endl;

 outf->cd();
 dir->cd();
 outputTable->Write();
 nt->Write();
 for(int ih = 0; ih < nhist; ih++) {
   Npart_vs_PtGenPlusEta4[ih]->Write();
   PtGenPlusEta4_vs_HFplusEta4[ih]->Write();
   Npart_vs_PtGenMinusEta4[ih]->Write();
   PtGenMinusEta4_vs_HFminusEta4[ih]->Write();
   Npart_vs_Ngentrk[ih]->Write();
   Ngentrk_vs_Ntracks[ih]->Write();
 }
 outf->Write();
 txtfile.close();

}
コード例 #11
0
void jettrigger()
{
  TFile *f = new TFile("jettrig.root");
  TNtuple *nt = (TNtuple *)f->Get("nt");

//Declaration of leaves types
   Float_t         pt;
   Float_t         eta;
   Float_t         phi;
   Float_t         mass;
   Float_t         jt40;
   Float_t         jt60;
   Float_t         jt80;
   Float_t         jt100;
   Float_t         pscl40;
   Float_t         pscl60;
   Float_t         pscl80;
   Float_t         pscl100;
  

   // Set branch addresses.
   nt->SetBranchAddress("pt",&pt);
   nt->SetBranchAddress("eta",&eta);
   nt->SetBranchAddress("phi",&phi);
   nt->SetBranchAddress("mass",&mass);
   nt->SetBranchAddress("jt40",&jt40);
   nt->SetBranchAddress("jt60",&jt60);
   nt->SetBranchAddress("jt80",&jt80);
   nt->SetBranchAddress("jt100",&jt100);
   nt->SetBranchAddress("pscl40",&pscl40);
   nt->SetBranchAddress("pscl60",&pscl60);
   nt->SetBranchAddress("pscl80",&pscl80);
   nt->SetBranchAddress("pscl100",&pscl100);
  
   TFile *fout = new TFile("jettrig_withweight.root","recreate");
   TNtuple *ntout = new TNtuple("ntweight","ntweight","pt:eta:phi:mass:jt40:jt60:jt80:jt100:pscl40:pscl60:pscl80:weightJet:weight12003");
   //TTree *ntout=new TTree("ntweight","ntweight");
   ntout->SetDirectory(fout);

   /*   ntout->Branch("pt",&pt);
   ntout->Branch("eta",&eta);
   ntout->Branch("phi",&phi);
   ntout->Branch("mass",&mass);
   ntout->Branch("jt40",&jt40);
   ntout->Branch("jt60",&jt60);
   ntout->Branch("jt80",&jt80);
   ntout->Branch("jt100",&jt100);
   ntout->Branch("pscl40",&pscl40);
   ntout->Branch("pscl60",&pscl60);
   ntout->Branch("pscl80",&pscl80);
   ntout->Branch("pscl100",&pscl100);
   ntout->Branch("weight",&weight);
   */
   Long64_t nentries = nt->GetEntries();
   cout<<nentries<<endl;

   int oneperc = nentries/100;
   Long64_t nbytes = 0;

   //#ifndef __CINT__
   //#pragma omp parallel for ordered schedule(dynamic)
   //#endif
   for (Long64_t i=0; i<nentries;i++) {
           nbytes += nt->GetEntry(i);

      if (i % oneperc == 0) cout<<"\r"<<i/oneperc<<"%   "<<flush;

      float weightJet = 0, weight12003 = 0;

      if (jt40 && !jt60 && !jt80 && !jt100) weight12003 = 1/pscl40;
      if (jt60 && !jt80 && !jt100) weight12003 = 1;
      if (jt80 && !jt100) weight12003 = 1;
      if (jt100) weight12003 = 1;

      if (jt40 && pt>40 && pt<60) weightJet = pscl40;
      if (jt60 && pt>60 && pt<80) weightJet = pscl60;
      if (jt80 && pt>80 && pt<100) weightJet = pscl80;
      if (jt100 && pt>100) weightJet = pscl100;

      //#ifndef __CINT__
      //#pragma omp ordered
      //#endif
	ntout->Fill(pt,eta,phi,mass,jt40,jt60,jt80,jt100,pscl40,pscl60,pscl80,weightJet,weight12003);

   }
   cout<<endl;
   cout<<ntout->GetEntries()<<endl;
   ntout->Write();
   fout->Close();
   f->Close();

   f = new TFile("jettrig_withweight.root");
   nt = (TNtuple *)f->Get("ntweight");
   cout<<nt->GetEntries()<<endl;
   f->Close();

}
コード例 #12
0
ファイル: swaps.C プロジェクト: goi42/lhcb
void swaps::Loop()
{
	gROOT->ProcessLine(".x /home/gcowan/lhcb/lhcbStyle.C");
	if (fChain == 0) return;

	Long64_t nentries = fChain->GetEntriesFast();

	TH1D * mKK  = new TH1D("mKK", "mKK", 100, 0.99, 1.050);
	TH1D * mKpi = new TH1D("mKpi", "mKpi", 100, 0.826, 0.966);
	TH1D * mKp  = new TH1D("mKp", "mKp", 50, 1.45, 1.55);
	TH1D * massHisto  = new TH1D("mJpsiKK_DTF", "mJpsiKK_DTF", 100, 5.20, 5.55);
	TH1D * mBs  = new TH1D("mJpsiKK", "mJpsiKK", 100, 5.20, 5.55);
	TH1D * mBsVeto = new TH1D("mJpsiKKveto", "mJpsiKKveto", 100, 5.20, 5.55);
	//TH1D * mBsKpi = new TH1D("upper_Bs_sideband", "mJpsiKpi", 40, 5.21, 5.41);
	//TH1D * mBspiK = new TH1D("lower_Bs_sideband", "mJpsipiK", 40, 5.04, 5.24);
	TH1D * mBsKpi = new TH1D("upper_Bs_sideband", "mJpsiKpi", 40, 5.51, 5.71);
	TH1D * mBspiK = new TH1D("lower_Bs_sideband", "mJpsipiK", 40, 5.34, 5.54);
	TH1D * mJpsi_ = new TH1D("mJpsi", "mJpsi", 100, 3.03, 3.15);
	TH1D * mJpsi_constr = new TH1D("mJpsi_constr", "mJpsi", 100, 3.03, 3.15);
	
	Long64_t nbytes = 0, nb = 0;

	TFile * file = TFile::Open("reflection_upper_sideband.root", "RECREATE");
	TNtuple * tuple = new TNtuple("DecayTree","DecayTree", "mass");

	for (Long64_t jentry=0; jentry<nentries;jentry++) {
	//for (Long64_t jentry=0; jentry<1000;jentry++) {
		Long64_t ientry = LoadTree(jentry);
		if (ientry < 0) break;
		nb = fChain->GetEntry(jentry);   nbytes += nb;

		if ( !(sel_cleantail==1&&sel==1&&(triggerDecisionUnbiased==1||triggerDecisionBiasedExcl==1)&&time>.3&&time<14&&sigmat>0&&sigmat<0.12
//			&&(Kplus_pidK-Kplus_pidp)>-5
//			&&(Kminus_pidK-Kminus_pidp)>-5
		   )
			) continue;


		//double mpi = 139.57018;
		double mK = 493.68;
		double mmu = 105.658;
		double mJpsi = 3096.916;
		double mpi = 938.27;
		TLorentzVector Kplus(Kplus_PX, Kplus_PY, Kplus_PZ, sqrt(Kplus_PX*Kplus_PX+Kplus_PY*Kplus_PY+Kplus_PZ*Kplus_PZ + mK*mK));
		TLorentzVector Kminus(Kminus_PX, Kminus_PY, Kminus_PZ, sqrt(Kminus_PX*Kminus_PX+Kminus_PY*Kminus_PY+Kminus_PZ*Kminus_PZ + mK*mK));
		TLorentzVector KplusWrong(Kplus_PX, Kplus_PY, Kplus_PZ, sqrt(Kplus_PX*Kplus_PX+Kplus_PY*Kplus_PY+Kplus_PZ*Kplus_PZ + mpi*mpi));
		TLorentzVector KminusWrong(Kminus_PX, Kminus_PY, Kminus_PZ, sqrt(Kminus_PX*Kminus_PX+Kminus_PY*Kminus_PY+Kminus_PZ*Kminus_PZ + mpi*mpi));
		TLorentzVector muplus(muplus_PX, muplus_PY, muplus_PZ, sqrt(muplus_P*muplus_P + mmu*mmu));
		TLorentzVector muminus(muminus_PX, muminus_PY, muminus_PZ, sqrt(muminus_P*muminus_P + mmu*mmu));
		TLorentzVector Jpsi = muplus + muminus;
		TLorentzVector Jpsi_constr(muminus_PX+muplus_PX, muminus_PY+muplus_PY, muminus_PZ+muplus_PZ, sqrt(Jpsi.P()*Jpsi.P() + mJpsi*mJpsi));
		
		TLorentzVector KK = Kplus + Kminus;
		TLorentzVector Kpi = Kplus + KminusWrong;
		TLorentzVector piK = KplusWrong + Kminus;
		TLorentzVector B = Jpsi_constr + KK;
		TLorentzVector BKpi = Jpsi_constr + Kpi;
		TLorentzVector BpiK = Jpsi_constr + piK;
		//if ( ((BpiK.M() > 5600 && BpiK.M() < 5640) || (BKpi.M() > 5600 && BKpi.M() < 5640)) ) mBsVeto->Fill(mass/1000.); 
		//if ( ( Kpi.M() > 1490 && Kpi.M() < 1550 ) || ( piK.M() > 1490 && piK.M() < 1550 ) ) continue;//mBsVeto->Fill(mass/1000.); 
		mKK->Fill(KK.M()/1000.);
		mKp->Fill(Kpi.M()/1000.);
		mKp->Fill(piK.M()/1000.);
		mBs->Fill(B.M()/1000.);
		massHisto->Fill(mass/1000.);
		mJpsi_->Fill(Jpsi.M()/1000.);
		mJpsi_constr->Fill(Jpsi_constr.M()/1000.);
		if (mass > 5420) mBsKpi->Fill(BKpi.M()/1000.);
		if (mass > 5420) mBsKpi->Fill(BpiK.M()/1000.);
		if (mass < 5330) mBspiK->Fill(BKpi.M()/1000.);
		if (mass < 5330) mBspiK->Fill(BpiK.M()/1000.);
		if (mass > 5400) tuple->Fill(BKpi.M());
		if (mass > 5400) tuple->Fill(BpiK.M());
	}

	tuple->Write();
	file->Close();

	std::cout << "Number of B candidates " << mBs->GetEntries() << std::endl;
	std::cout << "Number of B candidates after Lambda_b veto" << mBsVeto->GetEntries() << std::endl;

	gROOT->SetStyle("Plain");
	
	TCanvas * c = new TCanvas("c","c",1600,1200);
	c->Divide(3,2);
	c->cd(1);
	mKK->Draw();
	mKK->SetTitle("");
	mKK->GetXaxis()->SetTitle("m(KK) [GeV/c^{2}]");
	c->cd(2);
	mJpsi_->Draw();
	mJpsi_->SetTitle("");
	mJpsi_->GetXaxis()->SetTitle("m(#mu#mu) [GeV/c^{2}]");
	c->cd(3);
	//mKp->Draw();
	mKp->SetTitle("");
	mKp->GetXaxis()->SetTitle("m(Kp) [GeV/c^{2}]");
	c->cd(4);
	massHisto->Draw();
	//massHisto->SetMaximum(1500);
	mBs->SetLineColor(kRed);
	mBs->Draw("same");
	mBsVeto->SetLineColor(kOrange);
	mBsVeto->Draw("same");
	massHisto->SetTitle("");
	massHisto->GetXaxis()->SetTitle("DTF m(J/#psi K^{+}K^{-}) [GeV/c^{2}]");
	c->cd(5);
	mBspiK->Draw();
	mBspiK->SetTitle("");
	//mBspiK->GetXaxis()->SetTitle("m(J/#psi K#pi) [GeV/c^{2}]");
	mBspiK->GetXaxis()->SetTitle("m(J/#psi Kp) [GeV/c^{2}]");
	c->cd(6);
	mBsKpi->Draw();
	mBsKpi->SetTitle("");
	//mBsKpi->GetXaxis()->SetTitle("m(J/#psi K#pi) [GeV/c^{2}]");
	mBsKpi->GetXaxis()->SetTitle("m(J/#psi Kp) [GeV/c^{2}]");
	c->SaveAs("plots_swaps.pdf");
}
コード例 #13
0
ファイル: plot_moments.C プロジェクト: goi42/lhcb
void plot_moments(char * filename, char * outputfilename)
{
    TFile * f = TFile::Open(filename);
    TTree * t = (TTree*)f->Get("partial");
    //TF1 * f1 = new TF1("f1", myfunction1, -1, 1, 3);
    //TF1 * f2 = new TF1("f2", myfunc, -1, 1, 2);
    TF1 * f1 = new TF1("f1","([0] + x*[1] +(3.*x*x-1.)/2.*[2])/5.", -1, 1);
    TF1 * f2 = new TF1("f2", "-1./sqrt(2.)/5.*([0]*sqrt(1.-x*x) + [1]*sqrt(3./4.)*2.*sqrt(1.-x*x)*x)", -1, 1);
    TF1 * f3 = new TF1("f3","[0]*(1-x*x)/5*sqrt(3./8.)", -1, 1);
    f1->SetParameter(0, 10000*0.1); // G020 = 0.1
    f1->SetParameter(1, 10000*0.2); // G021 = 0.2
    f1->SetParameter(2, 10000*0.1); // G022 = 0.1

    f2->SetParameter(0, 10000*0.5); //G121 = 0.5
    f2->SetParameter(1, 10000*0.2); //G122 = 0.2
   
    f3->SetParameter(0, 10000*0.3); //G222 = 0.3


    f1->SetLineColor(kRed);
    f2->SetLineColor(kRed);
    f3->SetLineColor(kRed);
    f1->SetLineWidth(3);
    f2->SetLineWidth(3);
    f3->SetLineWidth(3);
    
    TFile * outfile = TFile::Open(outputfilename, "RECREATE");
    TNtuple * tup = new TNtuple("coeffs","coeff", "f1_G020:f1_G021:f1_G022:f2_G121:f2_G122:f3_G222:f1_status:f2_status:f3_status");

    TH1D * h1 = new TH1D("h1", "h1", 100, -1., 1.);
    TH1D * h2 = new TH1D("h2", "h1", 100, -1., 1.);
    TH1D * h3 = new TH1D("h3", "h1", 100, -1., 1.);
    h1->Sumw2();
    h2->Sumw2();
    h3->Sumw2();

    TCanvas * c = new TCanvas("c","c",1200, 1000);
    c->Divide(3,2);
    c->cd(1);
    t->Draw("cosThetaL","","goff");
    c->cd(2);
    t->Draw("cosThetaK","","goff");
    c->cd(3);
    t->Draw("phi","","goff");

    c->cd(4);
    cout << "Doing Fit 1" << endl;
    t->Draw("cosThetaL>>h1", "D002","goff");
    TFitResultPtr f1_result = h1->Fit(f1, "RS");
    h1->GetXaxis()->SetTitle("cosThetaL (weighted with D_{0,0}^{2})");
    f1->Draw("samegoff");
    int f1_status = gMinuit->fStatus;

    
    c->cd(5);
    cout << "Doing Fit 2" << endl;
    t->Draw("cosThetaL>>h2", "D102","goff");
    TFitResultPtr f2_result = h2->Fit(f2, "RS");
    h2->GetXaxis()->SetTitle("cosThetaL (weighted with D_{1,0}^{2})");
    f2->Draw("samegoff");
    int f2_status = gMinuit->fStatus;
    
    c->cd(6);
    cout << "Doing Fit 3" << endl;
    t->Draw("cosThetaL>>h3", "D202","goff");
    h3->GetXaxis()->SetTitle("cosThetaL (weighted with D_{2,0}^{2})");
    c->Update();
    TFitResultPtr f3_result = h3->Fit(f3, "RS");
    f3->Draw("samegoff");
    int f3_status = gMinuit->fStatus;

    tup->Fill(f1->GetParameter(0), f1->GetParameter(1), f1->GetParameter(2)
            , f2->GetParameter(0), f2->GetParameter(1)
            , f3->GetParameter(0)
            , f1_status, f2_status, f3_status
            );
    tup->Write();
    outfile->Close();

    //c->SaveAs("B2Kstll_partial_moments_l_2.pdf");
}
コード例 #14
0
void anatup( Double_t pBeam=3.3077729, Int_t Did=19)

// Analyse ee events, and write tuples
{
  gROOT->LoadMacro("$VMCWORKDIR/gconfig/rootlogon.C");
  rootlogon();

  FILE *fp;
  Int_t NTmax=100000;
  //   Int_t NFmax=10;   // max number of files
  //   Int_t NTmax=100;   // max number per file
  Int_t NEVcount=0;   // max number per file
  //   Int_t NTmax=10000;
  //   Int_t NTmax=200;
  Int_t ip=0;
  Int_t iPart=3;

  Double_t mProt= 0.938272;
  Double_t mElec= 0.000511;
  Double_t mMuon= 0.105658;
  Double_t mPion= 0.139570;
  Double_t mZero= 0.134977;
  Double_t mZeroFit= 0.13;
  //  Double_t mZeroCut= 0.06;
  Double_t mZeroCut= 0.02;
  //  Double_t pBeam=4.00000;
  Double_t eBeam=sqrt(pBeam*pBeam+mProt*mProt);
  Double_t eSystem=eBeam+mProt;
  Double_t mElec2 = mElec*mElec;
  Double_t mZero2= mZero*mZero;
  Double_t radeg=180./3.1415926535;

  // electroncuts
  //   Double_t EmcCUT=0.8;
  //   Double_t SttCUT=0.5;
  Double_t EmcCUT=0.5;
  Double_t SttCUT=0.5;
  Double_t DiscCUT=0.5;
  Double_t DrcCUT=0.5;
  Double_t MuonCUT=0.5;
  Double_t MvdCUT=0.5;
  Double_t TOTCUT=0.50;
  Double_t TOT90CUT=0.90;
  Double_t TOT95CUT=0.95;
  Double_t TOT98CUT=0.98;
  Double_t TOT99CUT=0.99;


  // Set up the Lorentzvectors of the system
  TLorentzVector target(0.0, 0.0, 0.0, mProt);
  Double_t eBeam=sqrt(pBeam*pBeam+mProt*mProt);
  TLorentzVector beam(0.0, 0.0, pBeam, eBeam);
  TLorentzVector W = beam + target;
  TVector3 bSigma(0,0,-W.Pz()/W.E());

  // Construct filenames
  TString Directory[]={"rfiles3/","rootfiles/"      // vandewie
		       ,"ee01/","ee02/","ee03/","ee04/","ee05/"    // gosia + photos
		       ,"ee06/","ee07/","ee08/","ee09/","ee10/"
		       ,"ee11/","ee12/","ee13/","ee14/","ee15/"
		       ,"ee16/","ee17/"
		       ,"eeno01/","eeno02/","eeno03/","eeno04/"    // gosia + nophotos
  };

  TString name = "_complete.root";
  TString inRecoFile   = Directory[Did]+"reco"+name;
  TString inDigiFile   = Directory[Did]+"digi"+name;
  TString inSimFile    = Directory[Did]+"sim"+name;
  TString inPidFile    = Directory[Did]+"pid"+name;

  TString outAnaFile   = Directory[Did]+"ana"+name;
  TFile *out = TFile::Open(outAnaFile,"RECREATE");

  TNtuple* NTev = new TNtuple("NTev","NTev",
			      "p1MC:th1MC:ph1MC:p2MC:th2MC:ph2MC:costhMC:Q2:p1:th1:ph1:EMC1:NX1:pEMC1:pSTT1:pDIS1:pDRC1:pMVD1:pCOM1:p2:th2:ph2:EMC2:NX2:pEMC2:pSTT2:pDIS2:pDRC2:pMVD2:pCOM2:bestTH:bestPH:bestCOST",68000);

  Float_t atuple[33];

  cout << "filename:" << inPidFile << endl;
  TFile *inFile = TFile::Open(inPidFile,"READ");
  TTree *lhe=(TTree *) inFile->Get("cbmsim") ;
  TFile *outFile = TFile::Open(outAnaFile,"new");

  // adding other files as friends
  lhe->AddFriend("cbmsim",inSimFile);
  lhe->AddFriend("cbmsim",inDigiFile);

  PndEmcMapper::Init(6);
  // get the data  (correspondage with Inspect in TBrowser)

  TClonesArray* cCand_array=new TClonesArray("PndPidCandidate");
  lhe->SetBranchAddress("PidChargedCand", &cCand_array);

  TClonesArray* nCand_array=new TClonesArray("PndPidCandidate");
  lhe->SetBranchAddress("PidNeutralCand", &nCand_array);

  TClonesArray* mc_array=new TClonesArray("PndMCTrack");
  lhe->SetBranchAddress("MCTrack", &mc_array);

  TClonesArray* stthit_array=new TClonesArray("PndSttHit");
  lhe->SetBranchAddress("STTHit", &stthit_array);

  TClonesArray* sttpoint_array=new TClonesArray("PndSttPoint");
  lhe->SetBranchAddress("STTPoint", &sttpoint_array);

  TClonesArray* cluster_array=new TClonesArray("PndEmcCluster");
  lhe->SetBranchAddress("EmcCluster",&cluster_array);

  TClonesArray* digi_array=new TClonesArray("PndEmcSharedDigi");
  lhe->SetBranchAddress("EmcSharedDigi",&digi_array);

  TClonesArray* bump_array=new TClonesArray("PndEmcBump");
  lhe->SetBranchAddress("EmcBump",&bump_array);

  TClonesArray* drc_array=new TClonesArray("PndPidProbability");
  lhe->SetBranchAddress("PidAlgoDrc", &drc_array);

  TClonesArray* disc_array=new TClonesArray("PndPidProbability");
  lhe->SetBranchAddress("PidAlgoDisc", &disc_array);

  TClonesArray* mvd_array=new TClonesArray("PndPidProbability");
  lhe->SetBranchAddress("PidAlgoMvd", &mvd_array);

  TClonesArray* stt_array=new TClonesArray("PndPidProbability");
  lhe->SetBranchAddress("PidAlgoStt", &stt_array);

  TClonesArray* emcb_array=new TClonesArray("PndPidProbability");
  lhe->SetBranchAddress("PidAlgoEmcBayes", &emcb_array);

  // canvas and stuff
  gStyle->SetLabelSize(0.05,"X");
  gStyle->SetLabelSize(0.05,"Y");
  gStyle->SetLineWidth(2);
  gStyle->SetHistLineWidth(2);
  gStyle->SetLabelSize(0.05,"X");
  gStyle->SetLabelSize(0.05,"Y");
  gStyle->SetPalette(1);

  int off=32;
  int start=250;

  cMA = new TCanvas("cMA","cMA",200,0, 1000, 1000);
  cMA->Divide(3,3);

  //  cMCelec1 = new TCanvas("cMCelec1","cMCelec1",250,0, 1200, 1000);
  //  cMCelec1->Divide(3,2);

  // histos
  TH1F *h_costheta_mc = new TH1F("h_costheta_mc","cos_theta_ep",20,-1,1);
  TH1F *h_costheta = new TH1F("h_costheta","cos_theta_ep",20,-1,1);
  TH1F *h_costheta_sel = new TH1F("h_costheta_sel","cos_theta_ep",20,-1,1);
  TH1F *h_efficiency = new TH1F("h_efficiency","efficiency",20,-1,1);
  TH1F *h_theta = new TH1F("h_theta","theta_ep",400,-400,400);
  TH1F *h_dtheta = new TH1F("h_dtheta","dtheta_ep",100,170,190);
  TH1F *h_dphi = new TH1F("h_dphi","dphi_ep",100,170,190);

  TH1D* hcutE   = new TH1D("hcutE"  ,"hcutE",50,-eSystem,eSystem);
  TH1D* hcutx   = new TH1D("hcutx"  ,"hcutx",50,-1,1);
  TH1D* hcuty   = new TH1D("hcuty"  ,"hcuty",50,-1,1);
  TH1D* hcutz   = new TH1D("hcutz"  ,"hcutz",50,-1,1);
  TH1D* hMCz    = new TH1D("hMCz"  ,"hMCz",50,0,eSystem);
  TH1D* hpt2    = new TH1D("hpt2"  ,"hpt2",50,0,4);
  TH1D* hpair   = new TH1D("hpair"  ,"hpair",11,-0.5,10.5);

  cout << " finished histos " << endl;

  // process the data
  // Lorentz vectors MV
  TLorentzVector mcTrack[4];
  TLorentzVector QQ_MC;

  // loop over  events
  Double_t MCEnergy, MCTheta, MCPhi;
  Double_t MC1Energy, MC1Theta, MC1Phi;
  Double_t MC2Energy, MC2Theta, MC2Phi;

  NTevents=lhe->GetEntriesFast();
  cout << "NTevents: " << NTevents << endl;
  if(NTevents>NTmax) NTevents=NTmax;
  for (Int_t j=0; j< NTevents ; j++) {
    lhe->GetEntry(j);   // kinematics
    NEVcount++;
    if(j%1000 == 0) cout << "event: " << j << endl;
    //       cout << "processing event: " << j<< endl ;
    Int_t nmc      = mc_array->GetEntriesFast();
    Int_t ncCand=cCand_array->GetEntriesFast();
    Int_t nnCand=nCand_array->GetEntriesFast();
    if(j<5) {
      cout << " nMC: " << mc_array->GetEntriesFast() ;
      cout << " ncCand: " << cCand_array->GetEntriesFast() << endl;
      cout << " nnCand: " << nCand_array->GetEntriesFast() << endl;
    }
    // Loop over electron tracks, store in mcTrack[0,1], pizero_MC, QQ_MC
    Float_t mc_pp = 0, mc_E = 0, mc_mass = 0;
    Float_t mc_px = 0, mc_py = 0, mc_pz = 0;
    Int_t mc_pdg;
    Int_t nepi=0;
    Int_t mc0=0, mc1=1;
    if(Did>1) {mc0=1; mc1=2;}
    // positron
    PndMCTrack *mctrack = (PndMCTrack*)mc_array->At(mc0);
    //       Int_t MotherID = mctrack->GetMotherID();
    //       mc_pdg = (int) (mctrack->GetPdgCode());

    mc_pp = mctrack->GetMomentum().Mag();
    mc_px = mctrack->GetMomentum().Px();
    mc_py = mctrack->GetMomentum().Py();
    mc_pz = mctrack->GetMomentum().Pz();
    mc_E=TMath::Sqrt(mc_pp*mc_pp+mElec2);
    mcTrack[0].SetPxPyPzE(mc_px,mc_py,mc_pz,mc_E);
    // electron
    PndMCTrack *mctrack = (PndMCTrack*)mc_array->At(mc1);
    //       Int_t MotherID = mctrack->GetMotherID();
    //       mc_pdg = (int) (mctrack->GetPdgCode());

    mc_pp = mctrack->GetMomentum().Mag();
    mc_px = mctrack->GetMomentum().Px();
    mc_py = mctrack->GetMomentum().Py();
    mc_pz = mctrack->GetMomentum().Pz();
    mc_E=TMath::Sqrt(mc_pp*mc_pp+mElec2);
    mcTrack[1].SetPxPyPzE(mc_px,mc_py,mc_pz,mc_E);

    // elec1
    MC1Energy = mcTrack[0].E();
    MC1Theta  = radeg*(mcTrack[0].Theta());
    MC1Phi    = radeg*(mcTrack[0].Phi());
    //       hmc1E->Fill(MC1Energy);
    //       hmc1TH->Fill(MC1Theta);
    //       hmc1PH->Fill(MC1Phi);
    // elec2
    MC2Energy = mcTrack[1].E();
    MC2Theta  = radeg*(mcTrack[1].Theta());
    MC2Phi    = radeg*(mcTrack[1].Phi());
    //       hmc1E->Fill(MC2Energy);
    //       hmc1TH->Fill(MC2Theta);
    //       hmc1PH->Fill(MC2Phi);

    // quadrivecteur
    double elecMC=mcTrack[0].Angle(mcTrack[1].Vect());
    //       double Q2=4*mcTrack[0].E()*mcTrack[1].E()*(sin(elecMC/2))*(sin(elecMC/2));
    QQ_MC=mcTrack[0]+mcTrack[1];
    double Q2=QQ_MC.M2();
    //       hmcQ2->Fill(Q2);
    TLorentzVector *elecMC0 = new TLorentzVector(mcTrack[0].Px(),
						 mcTrack[0].Py(),
						 mcTrack[0].Pz(),
						 mcTrack[0].E());
    TLorentzVector *elecMC1 = new TLorentzVector(mcTrack[1].Px(),
						 mcTrack[1].Py(),
						 mcTrack[1].Pz(),
						 mcTrack[1].E());
    // boost
    elecMC0->Boost(bSigma);
    elecMC1->Boost(bSigma);
    Double_t THMC0=radeg*(elecMC0->Theta());
    Double_t THMC1=radeg*(elecMC1->Theta());
    Double_t THtot=THMC0+THMC1;
    Double_t COSTMC=TMath::Cos(elecMC0->Theta());
    h_costheta_mc-> Fill(COSTMC);
    // print some event data
    if(j<5) {
      cout << "event:" << j << endl;
      cout << "MC-eepi:" << MC1Energy << " " << MC2Energy << endl;
      cout << "theta:" << MC1Theta << " " << MC2Theta  << endl;
      cout << "phi:" << MC1Phi << " " << MC2Phi << endl;
      cout << "THMC0:" << THMC0 << "THMC1:" << THMC1 << endl;
      cout << "THtot:" << THtot << " Q2:" << Q2 << endl;
    }

    // fill tuple
    atuple[0]=MC1Energy;
    atuple[1]=MC1Theta;
    atuple[2]=MC1Phi;
    atuple[3]=MC2Energy;
    atuple[4]=MC2Theta;
    atuple[5]=MC2Phi;
    atuple[6]=COSTMC;
    atuple[7]=Q2;

    // print some event data
    if(j<5) {
      cout << "event:" << j << endl;
      cout << "MC-eepi:" << MC1Energy << " " << MC2Energy << " " << MCEnergy << endl;
      cout << "theta:" << MC1Theta << " " << MC2Theta << " " << MCTheta << endl;
      cout << "phi:" << MC1Phi << " " << MC2Phi << " " << MCPhi << endl;
      cout << "COSTMC:" << COSTMC << " Q2:" << Q2 << endl;
    }

    // Analysis starts here
    // loop over charged candidate tracks
    Float_t cc_pp = 0, cc_E = 0, cc_mass = 0, cc_TH = 0;
    Float_t cc_px = 0, cc_py = 0, cc_pz = 0;

    TLorentzVector reTrack[4], QQ_RE;

    Int_t nelec_pair = 0;
    Double_t bestTH=-999;
    Double_t bestPH=-999;
    Double_t bestCOST=-999;
    Int_t ix=-1, iy=-1;

    for (Int_t nc1 = 0; nc1 < ncCand; nc1++) {
      PndPidCandidate *pc1 = (PndPidCandidate*)cCand_array->At(nc1);
      Int_t Charge1 = pc1->GetCharge();
      if (Charge1<0) continue;
      cc_pp = pc1->GetMomentum().Mag();
      //         if (cc_pp>eSystem) continue;
      cc_px = pc1->GetMomentum().Px();
      cc_py = pc1->GetMomentum().Py();
      cc_pz = pc1->GetMomentum().Pz();
      cc_E=TMath::Sqrt(cc_pp*cc_pp+mElec2);
      reTrack[0].SetPxPyPzE(cc_px,cc_py,cc_pz,cc_E);
      for (Int_t nc2 = 0; nc2 < ncCand; nc2++) {
	PndPidCandidate *pc2 = (PndPidCandidate*)cCand_array->At(nc2);
	Int_t Charge2 = pc2->GetCharge();
	if (Charge2>0) continue;
	cc_pp = pc2->GetMomentum().Mag();
	//           if (cc_pp>eSystem) continue;
	cc_px = pc2->GetMomentum().Px();
	cc_py = pc2->GetMomentum().Py();
	cc_pz = pc2->GetMomentum().Pz();
	cc_E=TMath::Sqrt(cc_pp*cc_pp+mElec2);
	reTrack[1].SetPxPyPzE(cc_px,cc_py,cc_pz,cc_E);
	nelec_pair++;
	// selection on best kinematics
	// elec1
	RE1Energy = reTrack[0].E();
	RE1Theta  = radeg*(reTrack[0].Theta());
	RE1Phi    = radeg*(reTrack[0].Phi());
	// elec2
	RE2Energy = reTrack[1].E();
	RE2Theta  = radeg*(reTrack[1].Theta());
	RE2Phi    = radeg*(reTrack[1].Phi());
	// quadrivecteur
	double elecRE=reTrack[0].Angle(reTrack[1].Vect());
	//       double Q2=4*mcTrack[0].E()*mcTrack[1].E()*(sin(elecMC/2))*(sin(elecMC/2));
	QQ_RE=reTrack[0]+reTrack[1];
	double Q2=QQ_RE.M2();
	// Center of mass angle of electrons
	// boost vector
	TLorentzVector *elecRE0 = new TLorentzVector(reTrack[0].Px(),
						     reTrack[0].Py(),
						     reTrack[0].Pz(),
						     reTrack[0].E());
	TLorentzVector *elecRE1 = new TLorentzVector(reTrack[1].Px(),
						     reTrack[1].Py(),
						     reTrack[1].Pz(),
						     reTrack[1].E());
	elecRE0->Boost(bSigma);
	elecRE1->Boost(bSigma);
	Double_t THRE0=radeg*(elecRE0->Theta());
	Double_t COSTRE=TMath::Cos(elecRE0->Theta());
	Double_t THRE1=radeg*(elecRE1->Theta());
	Double_t PHRE0=radeg*(elecRE0->Phi());
	Double_t PHRE1=radeg*(elecRE1->Phi());
	Double_t THtot=THRE0+THRE1;
	Double_t PHtot=PHRE0-PHRE1;
	if(PHtot< -90) PHtot+360;
	if(abs(THtot-180) < abs(bestTH-180)) {
	  bestTH=THtot;
	  bestPH=PHtot;
	  bestCOST=COSTRE;
	  ix=nc1;
	  iy=nc2;
	}
	// print some event data
	if(j<5) {
	  cout << "event:" << j << endl;
	  cout << "RE-eepi:" << RE1Energy << " " << RE2Energy << endl;
	  cout << "theta:" << RE1Theta << " " << RE2Theta  << endl;
	  cout << "phi:" << RE1Phi << " " << RE2Phi << endl;
	  cout << "THRE0:" << THRE0 << "THRE1:" << THRE1 << endl;
	  cout << "THtot:" << THtot << " Q2:" << Q2 << endl;
	  cout << "PHtot:" << PHtot << endl;
	}
      }       // nc2
    }       // nc1
    h_costheta-> Fill(COSTRE);
    h_dtheta->Fill(bestTH);
    h_dphi->Fill(bestPH);
    hpair->Fill((double) nelec_pair);
    // Rebelotte with the best solution
    if(nelec_pair<1) continue;
    //
    PndPidCandidate *pc1 = (PndPidCandidate*)cCand_array->At(ix);
    PndPidCandidate *pc2 = (PndPidCandidate*)cCand_array->At(iy);
    // positron
    cc_pp = pc1->GetMomentum().Mag();
    cc_px = pc1->GetMomentum().Px();
    cc_py = pc1->GetMomentum().Py();
    cc_pz = pc1->GetMomentum().Pz();
    cc_E=TMath::Sqrt(cc_pp*cc_pp+mElec2);
    reTrack[0].SetPxPyPzE(cc_px,cc_py,cc_pz,cc_E);
    // electron
    cc_pp = pc2->GetMomentum().Mag();
    cc_px = pc2->GetMomentum().Px();
    cc_py = pc2->GetMomentum().Py();
    cc_pz = pc2->GetMomentum().Pz();
    cc_E=TMath::Sqrt(cc_pp*cc_pp+mElec2);
    reTrack[1].SetPxPyPzE(cc_px,cc_py,cc_pz,cc_E);

    // elec1
    // detector data
    PndPidProbability *drc_ele = (PndPidProbability *)drc_array->At(ix);
    PndPidProbability *disc_ele = (PndPidProbability *)disc_array->At(ix);
    PndPidProbability *mvd_ele = (PndPidProbability *)mvd_array->At(ix);
    PndPidProbability *stt_ele = (PndPidProbability *)stt_array->At(ix);
    PndPidProbability *emcb_ele = (PndPidProbability *)emcb_array->At(ix);
    Double_t k_drc_e = drc_ele->GetElectronPidProb();
    Double_t k_disc_e = disc_ele->GetElectronPidProb();
    Double_t k_mvd_e = mvd_ele->GetElectronPidProb();
    Double_t k_stt_e = stt_ele->GetElectronPidProb();
    Double_t k_emcb_e = emcb_ele->GetElectronPidProb();
    Double_t xx_e = (k_drc_e/(1-k_drc_e))*(k_disc_e/(1-k_disc_e))
      *(k_mvd_e/(1-k_mvd_e))*(k_stt_e/(1-k_stt_e))
      *(k_emcb_e/(1-k_emcb_e));
    Double_t k_comb_e = xx_e/(xx_e+1);
    atuple[ 8]=reTrack[0].P();
    atuple[ 9]=reTrack[0].Theta();
    atuple[10]=reTrack[0].Phi();
    atuple[11]=pc1->GetEmcRawEnergy();
    atuple[12]=pc1->GetEmcNumberOfCrystals();
    atuple[13]=k_emcb_e;
    atuple[14]=k_stt_e;
    atuple[15]=k_disc_e;
    atuple[16]=k_drc_e;
    atuple[17]=k_mvd_e;
    atuple[18]=k_comb_e;

    // elec2
    PndPidProbability *drc_posi = (PndPidProbability *)drc_array->At(iy);
    PndPidProbability *disc_posi = (PndPidProbability *)disc_array->At(iy);
    PndPidProbability *mvd_posi = (PndPidProbability *)mvd_array->At(iy);
    PndPidProbability *stt_posi = (PndPidProbability *)stt_array->At(iy);
    PndPidProbability *emcb_posi = (PndPidProbability *)emcb_array->At(iy);
    Double_t k_drc_p = drc_posi->GetElectronPidProb();
    Double_t k_disc_p = disc_posi->GetElectronPidProb();
    Double_t k_mvd_p = mvd_posi->GetElectronPidProb();
    Double_t k_stt_p = stt_posi->GetElectronPidProb();
    Double_t k_emcb_p = emcb_posi->GetElectronPidProb();
    Double_t xx_p = (k_drc_p/(1-k_drc_p))*(k_disc_p/(1-k_disc_p))
      *(k_mvd_p/(1-k_mvd_p))*(k_stt_p/(1-k_stt_p))
      *(k_emcb_p/(1-k_emcb_p));
    Double_t k_comb_p = xx_p/(xx_p+1);

    atuple[19]=reTrack[1].P();
    atuple[20]=reTrack[1].Theta();
    atuple[21]=reTrack[1].Phi();
    atuple[22]=pc2->GetEmcRawEnergy();
    atuple[23]=pc2->GetEmcNumberOfCrystals();
    atuple[24]=k_emcb_p;
    atuple[25]=k_stt_p;
    atuple[26]=k_disc_p;
    atuple[27]=k_drc_p;
    atuple[28]=k_mvd_p;
    atuple[29]=k_comb_p;
    atuple[30]=bestTH;
    atuple[31]=bestPH;
    atuple[32]=bestCOST;

    NTev->Fill(atuple);
    if(j<5) {
      cout << "k_comb_e:" << k_comb_e<< " k_comb_p:" << k_comb_p << endl;
    }

    // standard cuts for histos
    Bool_t com_ele_1 = drc_ele->GetElectronPidProb() > 0.05 &&
      disc_ele->GetElectronPidProb() > 0.05 &&
      mvd_ele->GetElectronPidProb() > 0.05 &&
      stt_ele->GetElectronPidProb() > 0.05 &&
      emcb_ele->GetElectronPidProb() > 0.05;
    Bool_t com_ele_2 = k_comb_e > 0.9;
    Bool_t com_ele_3 = pc1->GetEmcNumberOfCrystals() > 5;
    Bool_t com_ele_4 = bestTH >=178. && bestTH <= 182.;
    Bool_t com_ele_5 = bestPH >=178. && bestPH <= 182.;
    Bool_t com_posi_1 = drc_posi->GetElectronPidProb() > 0.05 &&
      disc_posi->GetElectronPidProb() > 0.05 &&
      mvd_posi->GetElectronPidProb() > 0.05 &&
      stt_posi->GetElectronPidProb() > 0.05 &&
      emcb_posi->GetElectronPidProb() > 0.05;
    Bool_t com_posi_2 =  k_comb_p > 0.9;
    Bool_t com_posi_3 = pc2->GetEmcNumberOfCrystals() > 5;

    if(j<5) {
      cout << com_ele_1 << com_ele_2 << com_ele_3 << com_ele_4
	   << com_ele_4 << com_posi_1 << com_posi_2 << com_posi_3 << endl;
    }
    if (com_ele_1&&com_ele_2&&com_ele_3&&com_ele_4
        &&com_ele_5&&com_posi_1&&com_posi_2&&com_posi_3) {
      h_costheta_sel->Fill(bestCOST);

    }
  }  // loop j over events

  cout << " NEVcount: " << NEVcount << endl;
  h_efficiency->Divide(h_costheta_sel,h_costheta_mc,1,1,"B");

  // output
  cMA->cd(1);gPad->SetLogy(); h_costheta_mc->Draw();
  cMA->cd(2);gPad->SetLogy(); h_costheta->Draw();
  cMA->cd(3);gPad->SetLogy(); h_costheta_sel->Draw();
  cMA->cd(4);gPad->SetLogy(); h_efficiency->Draw();
  cMA->cd(5);gPad->SetLogy(); h_dtheta->Draw();
  cMA->cd(6);gPad->SetLogy(); h_dphi->Draw();
  cMA->cd(7); hpair->Draw();
  cMA->cd(0);

  out->cd();

  hpair->Write();
  h_costheta_mc->Write();
  h_costheta->Write();
  h_costheta_sel->Write();
  h_efficiency->Write();
  h_dtheta->Write();
  h_dphi->Write();

  NTev->Write();

  out->Save();

  cout << " Yahoo! " << endl;

}
コード例 #15
0
ファイル: fakedata.c プロジェクト: laroque/P8Sandbox
int main(int argc, char* argv[])
{
  int outtype = 1;
  if (argc == 2) {
    outtype = atoi(argv[1]);
    cout << "output type will be " << outtype << endl;
  } else if (argc > 2) {
    cout << "fakedata takes 0 or 1 arguments" << endl;
    exit(1);
  }
  int status = 0;

  TFile *tf = new TFile("sin.root", "recreate");
  TTree *tt = new TTree("interF_1", "Just a continuous sine wave");
  INTERINFO fi;
  tt->Branch("fi", &fi, "i/L:t_ant/D:t_ret/D:x/D:y/D:z/D:ycen/D:zcen/D:rad/D:vx/D:vy/D:vz/D/:theta/D:Ef/D:fW_t/D:phase/D:dphdt/D:omega/D");

  //set antenna:
  double xend = 45;

  TNtuple *runcard = new TNtuple("runcard", "run parameters", "i:repeat:xi:yi:zi:ekin:thetai:phii:mass:charge:phasei:nscatters:n_temp:imp:x_ant:t_del:atten");
  float ntarray[18];
  double aphase = 0;
  ntarray[14] = xend;
  runcard->Fill(ntarray);
  runcard->Write();
  
  int imax = 440000;
  switch (outtype) {
    default: //pure sine
      cout << "doing sine" << endl;
      for (int i = 0; i<imax; i++) {
        fi.i = i;
        fi.x = 50. * TMath::Sin(2 * TMath::Pi() * i * 0.00007);
        fi.Ef = TMath::Sin(2 * TMath::Pi() * i * 0.01);
        aphase = fmod((2 * TMath::Pi() * i * 0.00007), (TMath::Pi() * 2));
        if ((aphase >= TMath::Pi() / 2.0) && (aphase < 3.0 * TMath::Pi() / 2.0)) {
          fi.vx = -1;
        } else {
          fi.vx = 1;
        }
        tt->Fill();
      }
      break;
    case 1: //sine with gaps that cause a phase shift
      cout << "doing sine with gaps and phase shift per gap" << endl;
      int ngaps = 0;
      double phase = TMath::Pi() / 3.0;
      int counted = 0;
      for (int i = 0; i<imax; i++) {
        fi.i = i;
        fi.x = 50. * TMath::Sin(2 * TMath::Pi() * i * 0.00007);
        if ((fi.x > xend) || (fi.x < -xend)){
          //fi.Ef = 0;
          fi.Ef = TMath::Sin(2 * TMath::Pi() * i * 0.01 + (ngaps * phase));
          if (counted == 0) {
            ngaps++;
            counted = 1;
          }
        } else {
          fi.Ef = TMath::Sin(2 * TMath::Pi() * i * 0.01 + (ngaps * phase));
          if (counted == 1) {
            counted = 0;
          }
        }
        aphase = fmod((2 * TMath::Pi() * i * 0.00007), (TMath::Pi() * 2));
        if ((aphase >= TMath::Pi() / 2.0) && (aphase < 3.0 * TMath::Pi() / 2.0)) {
          fi.vx = -1;
        } else {
          fi.vx = 1;
        }
        tt->Fill();
      }
      break;
  }

  tt->Write();
  tf->Close();
  return status;
}
コード例 #16
0
ファイル: AnaSjePy8Mass.C プロジェクト: xcheung/AnaSubjetsMC
int main(int argc, char* argv[])
{
  TApplication theApp(srcName.Data(), &argc, argv);
//=============================================================================

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

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

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

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

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

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

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

  fastjet::GhostedAreaSpec areaSpc(dCutEtaMax);
  fastjet::JetDefinition   jetsDef(fastjet::antikt_algorithm, dJetR, fastjet::E_scheme, fastjet::Best);
  fastjet::AreaDefinition  areaDef(fastjet::active_area_explicit_ghosts,areaSpc);


  fastjet::Selector selectJet = fastjet::SelectorAbsEtaMax(dJetEtaMax);
  fastjet::JetDefinition subjDef(fastjet::kt_algorithm, dSjeR, fastjet::E_scheme, fastjet::Best);
//=============================================================================

  std::vector<fastjet::PseudoJet> fjInput;
  const double dMass = TDatabasePDG::Instance()->GetParticle(211)->Mass();
//=============================================================================

  enum { kWgt, kJet, kAje, kMje, k1sz, k1sA, k1sr, k1sm, k2sz, k2sA, k2sr, k2sm, kDsr, kIsm, kVar };

  TFile *file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  TNtuple *nt = new TNtuple("nt", "", "fWgt:fJet:fAje:fMje:f1sj:f1sA:f1sr:f1sm:f2sj:f2sA:f2sr:f2sm:fDsr:fIsm");
//=============================================================================

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

  while (evt) {
    fjInput.resize(0);

    TLorentzVector vPar;
    for (HepMC::GenEvent::particle_const_iterator p=evt->particles_begin(); p!=evt->particles_end(); ++p) if ((*p)->status()==1) {
      vPar.SetPtEtaPhiM((*p)->momentum().perp(), (*p)->momentum().eta(), (*p)->momentum().phi(), dMass);

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

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

    TLorentzVector vJet, v1sj, v2sj, vIsj;
    for (int j=0; j<selectJets.size(); j++) {
      double dJet = selectJets[j].pt();
      vJet.SetPtEtaPhiM(dJet, selectJets[j].eta(), selectJets[j].phi(), selectJets[j].m());

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

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

        if (dIsj>d1sj) {
          d2sj = d1sj; k2sj = k1sj;
          d1sj = dIsj; k1sj = i;
        } else if (dIsj>d2sj) {
          d2sj = dIsj; k2sj = i;
        }
      }
//=============================================================================

      Float_t dVar[] = { 1., dJet, selectJets[j].area(), selectJets[j].m(), d1sj, -1., -1., -1., d2sj, -1., -1., -1., -1., -1. };

      if (d1sj>0.) {
        v1sj.SetPtEtaPhiM(d1sj, trimmdSj[k1sj].eta(), trimmdSj[k1sj].phi(), trimmdSj[k1sj].m());
        dVar[k1sr] = v1sj.DeltaR(vJet);
        dVar[k1sm] = trimmdSj[k1sj].m();
        dVar[k1sA] = trimmdSj[k1sj].area();
      }

      if (d2sj>0.) {
        v2sj.SetPtEtaPhiM(d2sj, trimmdSj[k2sj].eta(), trimmdSj[k2sj].phi(), trimmdSj[k2sj].m());
        dVar[k2sr] = v2sj.DeltaR(vJet);
        dVar[k2sm] = trimmdSj[k2sj].m();
        dVar[k2sA] = trimmdSj[k2sj].area();
      }

      if ((d1sj>0.) && (d2sj>0.)) {
        vIsj = v1sj + v2sj;
        dVar[kIsm] = vIsj.M();
        dVar[kDsr] = v2sj.DeltaR(v1sj);
      }

      nt->Fill(dVar);
    }
//=============================================================================

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

  file->cd(); nt->Write(); file->Close();
//=============================================================================

  TString sXsec = sFile; sXsec.ReplaceAll("out", "xsecs");
  file = TFile::Open(Form("%s/xsecs/%s.root",sPath.Data(),sXsec.Data()), "READ");
  TH1D *hPtHat        = (TH1D*)file->Get("hPtHat");        hPtHat->SetDirectory(0);
  TH1D *hWeightSum    = (TH1D*)file->Get("hWeightSum");    hWeightSum->SetDirectory(0);
  TProfile *hSigmaGen = (TProfile*)file->Get("hSigmaGen"); hSigmaGen->SetDirectory(0);
  file->Close();
//=============================================================================

  sFile.ReplaceAll("out", "wgt");
  file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  hPtHat->Write();
  hWeightSum->Write();
  hSigmaGen->Write();
  file->Close();
//=============================================================================

  cout << "DONE" << endl;
  return 0;
}
コード例 #17
0
ファイル: toyMC.C プロジェクト: CmsHI/CVS_MitHig
void toyMC(int run,int nevt)
{
    f = new TFile("output.root");

    // Random Seed
    gRandom->SetSeed( run );

    TH3F *nhits = (TH3F*) f->FindObjectAny("nhits");

    TFile *outf = new TFile (Form("exp-%05d.root",run),"recreate");
    TNtuple *ntmatched = new TNtuple("ntmatched","","eta1:matchedeta:phi1:matchedphi:deta:dphi:signalCheck:tid:r1id:r2id:evtid:nhit1:sid:ptype");
    TNtuple *ntHit1 = new TNtuple("ntHit1","","eta1:phi1:nhit1");
    TNtuple *ntHit2 = new TNtuple("ntHit2","","eta2:phi2:nhit1");

    for (int i=0;i<nevt;i++) {
       vector<double> hits1;
       vector<double> hits2;
       vector<Tracklet> protoTracklets;
       vector<Tracklet> recoTracklets;
       double mult,nhit1,nhit2;
       nhits->GetRandom3(mult,nhit1,nhit2);
       hits1.clear();
       hits2.clear();
       if (i% 1000 == 000 ) cout <<"Run: "<<run<<" Event "<<i<<" "<<(int)mult<<" "<<(int)nhit1<<" "<<hits1.size()<<" "<<(int)nhit2<<" "<<hits2.size()<<endl;
       genLayer1((int)nhit1,hits1);
       genLayer2((int)nhit2,hits2);
       
       for (int j=0;j<(int) hits1.size();j+=2)
       {
          ntHit1->Fill(hits1[j],hits1[j+1],mult);
          for (int k=0;k<(int)hits2.size();k+=2)
	  {
             ntHit2->Fill(hits2[k],hits2[k+1],mult);
	     Tracklet mytracklet(hits1[j],hits2[k],hits1[j+1],hits2[k+1]);
	     mytracklet.setIt1(j/2);
	     mytracklet.setIt2(k/2);
	     protoTracklets.push_back(mytracklet); 
	  }
       }
       recoTracklets = cleanTracklets(protoTracklets,0);
       for (int j=0;j<(int)recoTracklets.size();j++)
       {
           float var[100];
	   var[0] = recoTracklets[j].eta1();
	   var[1] = recoTracklets[j].eta2();
	   var[2] = recoTracklets[j].phi1();
	   var[3] = recoTracklets[j].phi2();
	   var[4] = recoTracklets[j].deta();
	   var[5] = recoTracklets[j].dphi();
	   var[6] = 0;
	   var[7] = recoTracklets[j].getId();
	   var[8] = recoTracklets[j].getId1();
	   var[9] = recoTracklets[j].getId2();
	   var[10] = i;
	   var[11] = (int)mult;
	   var[12] = recoTracklets[j].getSId();
	   var[13] = recoTracklets[j].getType();
	   ntmatched->Fill(var);
       }
    }

    ntmatched->Write();
    ntHit1->Write();
    ntHit2->Write();
    outf->Close();
}
コード例 #18
0
ファイル: StandardHypoTestDemo.C プロジェクト: Jdbermeo/HTHEP
void StandardHypoTestDemo(const char* infile = "",
                          const char* workspaceName = "combined",
                          const char* modelSBName = "ModelConfig",
                          const char* modelBName = "",
                          const char* dataName = "obsData",
                          int calcType = 0, // 0 freq 1 hybrid, 2 asymptotic
                          int testStatType = 3,   // 0 LEP, 1 TeV, 2 LHC, 3 LHC - one sided
                          bool newHypoTest = true,
                          int ntoys = 5000,
                          const char* hypoTestGraphFile = "hypoTestGraph.root",
                          bool useNC = false,
                          const char * nuisPriorName = 0)
{

/*

  Other Parameter to pass in tutorial
  apart from standard for filename, ws, modelconfig and data

  type = 0 Freq calculator
  type = 1 Hybrid calculator
  type = 2 Asymptotic calculator

  testStatType = 0 LEP
  = 1 Tevatron
  = 2 Profile Likelihood
  = 3 Profile Likelihood one sided (i.e. = 0 if mu < mu_hat)

  ntoys:         number of toys to use

  useNumberCounting:  set to true when using number counting events

  nuisPriorName:   name of prior for the nnuisance. This is often expressed as constraint term in the global model
  It is needed only when using the HybridCalculator (type=1)
  If not given by default the prior pdf from ModelConfig is used.

  extra options are available as global paramwters of the macro. They major ones are:

  generateBinned       generate binned data sets for toys (default is false) - be careful not to activate with
  a too large (>=3) number of observables
  nToyRatio            ratio of S+B/B toys (default is 2)
  printLevel

*/

   // disable - can cause some problems
   //ToyMCSampler::SetAlwaysUseMultiGen(true);

   SimpleLikelihoodRatioTestStat::SetAlwaysReuseNLL(true);
   ProfileLikelihoodTestStat::SetAlwaysReuseNLL(true);
   RatioOfProfiledLikelihoodsTestStat::SetAlwaysReuseNLL(true);

   //RooRandom::randomGenerator()->SetSeed(0);

   // to change minimizers
   // ROOT::Math::MinimizerOptions::SetDefaultStrategy(0);
   // ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit2");
   // ROOT::Math::MinimizerOptions::SetDefaultTolerance(1);

  /////////////////////////////////////////////////////////////
  // First part is just to access a user-defined file
  // or create the standard example file if it doesn't exist
  ////////////////////////////////////////////////////////////
   const char* filename = "";
   if (!strcmp(infile,"")) {
      filename = "results/example_combined_GaussExample_model.root";
      bool fileExist = !gSystem->AccessPathName(filename); // note opposite return code
      // if file does not exists generate with histfactory
      if (!fileExist) {
#ifdef _WIN32
         cout << "HistFactory file cannot be generated on Windows - exit" << endl;
         return;
#endif
         // Normally this would be run on the command line
         cout <<"will run standard hist2workspace example"<<endl;
         gROOT->ProcessLine(".! prepareHistFactory .");
         gROOT->ProcessLine(".! hist2workspace config/example.xml");
         cout <<"\n\n---------------------"<<endl;
         cout <<"Done creating example input"<<endl;
         cout <<"---------------------\n\n"<<endl;
      }

   }
   else
      filename = infile;

   // Try to open the file
   TFile *file = TFile::Open(filename);

   // if input file was specified byt not found, quit
   if(!file ){
      cout <<"StandardRooStatsDemoMacro: Input file " << filename << " is not found" << endl;
      return;
   }


  /////////////////////////////////////////////////////////////
  // Tutorial starts here
  ////////////////////////////////////////////////////////////

  // get the workspace out of the file
  RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
  if(!w){
    cout <<"workspace not found" << endl;
    return;
  }
  w->Print();

  // get the modelConfig out of the file
  ModelConfig* sbModel = (ModelConfig*) w->obj(modelSBName);


  // get the modelConfig out of the file
  RooAbsData* data = w->data(dataName);

  // make sure ingredients are found
  if(!data || !sbModel){
    w->Print();
    cout << "data or ModelConfig was not found" <<endl;
    return;
  }
  // make b model
  ModelConfig* bModel = (ModelConfig*) w->obj(modelBName);


   // case of no systematics
   // remove nuisance parameters from model
   if (noSystematics) {
      const RooArgSet * nuisPar = sbModel->GetNuisanceParameters();
      if (nuisPar && nuisPar->getSize() > 0) {
         std::cout << "StandardHypoTestInvDemo" << "  -  Switch off all systematics by setting them constant to their initial values" << std::endl;
         RooStats::SetAllConstant(*nuisPar);
      }
      if (bModel) {
         const RooArgSet * bnuisPar = bModel->GetNuisanceParameters();
         if (bnuisPar)
            RooStats::SetAllConstant(*bnuisPar);
      }
   }


  if (!bModel ) {
      Info("StandardHypoTestInvDemo","The background model %s does not exist",modelBName);
      Info("StandardHypoTestInvDemo","Copy it from ModelConfig %s and set POI to zero",modelSBName);
      bModel = (ModelConfig*) sbModel->Clone();
      bModel->SetName(TString(modelSBName)+TString("B_only"));
      RooRealVar * var = dynamic_cast<RooRealVar*>(bModel->GetParametersOfInterest()->first());
      if (!var) return;
      double oldval = var->getVal();
      var->setVal(0);
      //bModel->SetSnapshot( RooArgSet(*var, *w->var("lumi"))  );
      bModel->SetSnapshot( RooArgSet(*var)  );
      var->setVal(oldval);
  }

   if (!sbModel->GetSnapshot() || poiValue > 0) {
      Info("StandardHypoTestDemo","Model %s has no snapshot  - make one using model poi",modelSBName);
      RooRealVar * var = dynamic_cast<RooRealVar*>(sbModel->GetParametersOfInterest()->first());
      if (!var) return;
      double oldval = var->getVal();
      if (poiValue > 0)  var->setVal(poiValue);
      //sbModel->SetSnapshot( RooArgSet(*var, *w->var("lumi") ) );
      sbModel->SetSnapshot( RooArgSet(*var) );
      if (poiValue > 0) var->setVal(oldval);
      //sbModel->SetSnapshot( *sbModel->GetParametersOfInterest() );
   }





   // part 1, hypothesis testing
   SimpleLikelihoodRatioTestStat * slrts = new SimpleLikelihoodRatioTestStat(*bModel->GetPdf(), *sbModel->GetPdf());
   // null parameters must includes snapshot of poi plus the nuisance values
   RooArgSet nullParams(*bModel->GetSnapshot()); //Obtains parameters of the null Hypothesis
   if (bModel->GetNuisanceParameters()) nullParams.add(*bModel->GetNuisanceParameters()); //Add nuisance parameters to the null hypothesis

   slrts->SetNullParameters(nullParams);
   RooArgSet altParams(*sbModel->GetSnapshot()); //Obtains parameters of the alternate Hypothesis
   if (sbModel->GetNuisanceParameters()) altParams.add(*sbModel->GetNuisanceParameters());//Add nuisance parameters to the alternate    hypothesis
   slrts->SetAltParameters(altParams);


   ProfileLikelihoodTestStat * profll = new ProfileLikelihoodTestStat(*bModel->GetPdf());


   RatioOfProfiledLikelihoodsTestStat *
      ropl = new RatioOfProfiledLikelihoodsTestStat(*bModel->GetPdf(), *sbModel->GetPdf(), sbModel->GetSnapshot());
   ropl->SetSubtractMLE(false);

   if (testStatType == 3) profll->SetOneSidedDiscovery(1);
   profll->SetPrintLevel(printLevel);

   // profll.SetReuseNLL(mOptimize);
   // slrts.SetReuseNLL(mOptimize);
   // ropl.SetReuseNLL(mOptimize);

   AsymptoticCalculator::SetPrintLevel(printLevel);

   HypoTestCalculatorGeneric *  hypoCalc = 0;
   // note here Null is B and Alt is S+B
   if (calcType == 0) hypoCalc = new  FrequentistCalculator(*data, *sbModel, *bModel);
   else if (calcType == 1) hypoCalc= new  HybridCalculator(*data, *sbModel, *bModel);
   else if (calcType == 2) hypoCalc= new  AsymptoticCalculator(*data, *sbModel, *bModel);

   if (calcType == 0)
       ((FrequentistCalculator*)hypoCalc)->SetToys(ntoys, ntoys/nToysRatio);
   if (calcType == 1)
       ((HybridCalculator*)hypoCalc)->SetToys(ntoys, ntoys/nToysRatio);
   if (calcType == 2 ) {
      if (testStatType == 3) ((AsymptoticCalculator*) hypoCalc)->SetOneSidedDiscovery(true);
      if (testStatType != 2 && testStatType != 3)
         Warning("StandardHypoTestDemo","Only the PL test statistic can be used with AsymptoticCalculator - use by default a two-sided PL");


   }


   // check for nuisance prior pdf in case of nuisance parameters
   if (calcType == 1 && (bModel->GetNuisanceParameters() || sbModel->GetNuisanceParameters() )) {
         RooAbsPdf * nuisPdf = 0;
         if (nuisPriorName) nuisPdf = w->pdf(nuisPriorName);
         // use prior defined first in bModel (then in SbModel)
         if (!nuisPdf)  {
            Info("StandardHypoTestDemo","No nuisance pdf given for the HybridCalculator - try to deduce  pdf from the   model");
            if (bModel->GetPdf() && bModel->GetObservables() )
               nuisPdf = RooStats::MakeNuisancePdf(*bModel,"nuisancePdf_bmodel");
            else
               nuisPdf = RooStats::MakeNuisancePdf(*sbModel,"nuisancePdf_sbmodel");
         }
         if (!nuisPdf ) {
            if (bModel->GetPriorPdf())  {
               nuisPdf = bModel->GetPriorPdf();
               Info("StandardHypoTestDemo","No nuisance pdf given - try to use %s that is defined as a prior pdf in the B model",nuisPdf->GetName());
            }
            else {
               Error("StandardHypoTestDemo","Cannnot run Hybrid calculator because no prior on the nuisance parameter is specified or can be derived");
               return;
            }
         }
         assert(nuisPdf);
         Info("StandardHypoTestDemo","Using as nuisance Pdf ... " );
         nuisPdf->Print();

         const RooArgSet * nuisParams = (bModel->GetNuisanceParameters() ) ? bModel->GetNuisanceParameters() : sbModel->GetNuisanceParameters();
         RooArgSet * np = nuisPdf->getObservables(*nuisParams);
         if (np->getSize() == 0) {
            Warning("StandardHypoTestDemo","Prior nuisance does not depend on nuisance parameters. They will be smeared in their full range");
         }
         delete np;

         ((HybridCalculator*)hypoCalc)->ForcePriorNuisanceAlt(*nuisPdf);
         ((HybridCalculator*)hypoCalc)->ForcePriorNuisanceNull(*nuisPdf);
   }

   // hypoCalc->ForcePriorNuisanceAlt(*sbModel->GetPriorPdf());
   // hypoCalc->ForcePriorNuisanceNull(*bModel->GetPriorPdf());

   ToyMCSampler * sampler = (ToyMCSampler *)hypoCalc->GetTestStatSampler();

   if (sampler && (calcType == 0 || calcType == 1) ) {

      // look if pdf is number counting or extended
      if (sbModel->GetPdf()->canBeExtended() ) {
         if (useNC)   Warning("StandardHypoTestDemo","Pdf is extended: but number counting flag is set: ignore it ");
      }
      else {
         // for not extended pdf
         if (!useNC)  {
            int nEvents = data->numEntries();
            Info("StandardHypoTestDemo","Pdf is not extended: number of events to generate taken  from observed data set is %d",nEvents);
            sampler->SetNEventsPerToy(nEvents);
         }
         else {
            Info("StandardHypoTestDemo","using a number counting pdf");
            sampler->SetNEventsPerToy(1);
         }
      }

      if (data->isWeighted() && !generateBinned) {
         Info("StandardHypoTestDemo","Data set is weighted, nentries = %d and sum of weights = %8.1f but toy generation is unbinned - it would be faster to set generateBinned to true\n",data->numEntries(), data->sumEntries());
      }
      if (generateBinned)  sampler->SetGenerateBinned(generateBinned);


      // set the test statistic
      if (testStatType == 0) sampler->SetTestStatistic(slrts);
      if (testStatType == 1) sampler->SetTestStatistic(ropl);
      if (testStatType == 2 || testStatType == 3) sampler->SetTestStatistic(profll);

   }

   HypoTestResult *  htr = hypoCalc->GetHypoTest();
   htr->SetPValueIsRightTail(true);
   htr->SetBackgroundAsAlt(false);
   htr->Print(); // how to get meaningfull CLs at this point?

   delete sampler;
   delete slrts;
   delete ropl;
   delete profll;

   if (calcType != 2) {
      HypoTestPlot * plot = new HypoTestPlot(*htr,100);
      plot->SetLogYaxis(true);
      plot->Draw();
      plot->SamplingDistPlot::DumpToFile(hypoTestGraphFile,"RECREATE");
   }
   else {
      std::cout << "Asymptotic results " << std::endl;

   }

   // look at expected significances
   // found median of S+B distribution
   if (calcType != 2) {

      SamplingDistribution * altDist = htr->GetAltDistribution();
      HypoTestResult htExp("Expected Result");
      htExp.Append(htr);
      // find quantiles in alt (S+B) distribution
      double p[5];
      double q[5];
      for (int i = 0; i < 5; ++i) {
         double sig = -2  + i;
         p[i] = ROOT::Math::normal_cdf(sig,1);
      }
      std::vector<double> values = altDist->GetSamplingDistribution();
      TMath::Quantiles( values.size(), 5, &values[0], q, p, false);

      for (int i = 0; i < 5; ++i) {
         htExp.SetTestStatisticData( q[i] );
         double sig = -2  + i;
         std::cout << " Expected p -value and significance at " << sig << " sigma = "
                   << htExp.NullPValue() << " significance " << htExp.Significance() << " sigma " << std::endl;

      }
   }
   else {
      // case of asymptotic calculator
      for (int i = 0; i < 5; ++i) {
         double sig = -2  + i;
         // sigma is inverted here
         double pval = AsymptoticCalculator::GetExpectedPValues( htr->NullPValue(), htr->AlternatePValue(), -sig, false);
         std::cout << " Expected p -value and significance at " << sig << " sigma = "
                   << pval << " significance " << ROOT::Math::normal_quantile_c(pval,1) << " sigma " << std::endl;

      }
   }
    
    ////////////////////////////////////////////////////////////////////////////////////////////////
    //      FROM HERE ON IT HAS BEEN MODIFIED TO SAVE THE RESULTS IN TREES IN A .ROOT FILE
    
    
    //Declare the variable in which the hypothesis test results will be stored
    Double_t p_value, significance_t, cl_b, cl_sb, cl_s ;

    
    if(newHypoTest){
        
        TNtuple *resultsHypoTest = new TNtuple("resultsHypoTest", "resultsHypoTest", "p_value:significance_t:cl_b:cl_sb:cl_s");
        
        //Store the current results
        resultsHypoTest->Fill(htr->NullPValue(),htr->Significance(),htr->CLb(),htr->CLsplusb(),htr->CLs()) ;
        
        // Save the NTuple  to a .root file
        TFile* f_hypoTestResults = new TFile("resultsHypoTestDisc.root","RECREATE") ;
        resultsHypoTest->Write() ;
        f_hypoTestResults->Close() ;
    }
    else{
        // Open the .root that contains the NTuple and add the newly calculated results
        TFile* f_hypoTestResults = new TFile("resultsHypoTestDisc.root","UPDATE") ;

        //Get the NTuple from the file
        TNtuple *resultsHypoTest = (TNtuple*)f_hypoTestResults->Get("resultsHypoTest");
        
        resultsHypoTest->Fill(htr->NullPValue(),htr->Significance(),htr->CLb(),htr->CLsplusb(),htr->CLs()) ;
        
        //IF YOU WANT A DIFFERENT BRANCH FOR EACH TEST
        resultsHypoTest->Write();
        f_hypoTestResults->Close();
        //*/
        
        /*// IF YOU ONLY WNAT ONE BRANCH WITH ALL VALUES INSIDE IT. keep the latest ntuple header only
        resultsHypoTest->Write("",TObject::kOverwrite);
        f_hypoTestResults->Close();
        //*/
    }
    
}
コード例 #19
0
ファイル: makeTable.C プロジェクト: geonmo/cmg-cmssw
void makeTable(int nbins = 40, const string label = "HFhits", const char * tag = "Preliminary_NoEffCor_AMPT_d1107", const char* dataset = "DATA"){

  bool DATA = false;
  bool SIM = true;
  bool MC = false;
  double EFF = 1;
  double MXS = 1. - EFF;

   // Retrieving data
  int maxEvents = -200;
  vector<int> runnums;
  
  //  const char* infileName = Form("/net/hisrv0001/home/yetkin/hidsk0001/analysis/prod/%s_RECO_391/test.root",dataset);
  const char* infileName = Form("/net/hisrv0001/home/yetkin/hidsk0001/centrality/prod/%s/test.root",dataset);

  //  TFile* infile = new TFile(infileName,"read");
  TChain* t = new TChain("HltTree");
  //  TChain* t = new TChain("hltanalysis/HltTree");

  t->Add(infileName);

  // Creating output table
  TFile* outFile = new TFile("tables_d1108.root","update");
   TDirectory* dir = outFile->mkdir(tag);
   dir->cd();
   TNtuple* nt = new TNtuple("nt","","hf:bin:b:npart:ncoll:nhard");
   CentralityBins* bins = new CentralityBins("noname","Test tag", nbins);
   bins->table_.reserve(nbins);

  TH1D::SetDefaultSumw2();

  int runMC = 1;
  TFile * inputMCfile;
  CentralityBins* inputMCtable;
  
  if(DATA){
    inputMCfile = new TFile("tables_d1103.root","read");
    inputMCtable = (CentralityBins*)inputMCfile->Get("CentralityTable_HFhits40_AMPT2760GeV_v1_mc_MC_38Y_V12/run1");
  }

  // Setting up variables & branches
  double binboundaries[nbinsMax+1];
  vector<float> values;

  float b,npart,ncoll,nhard,hf,hfhit,eb,ee,etmr,parameter;
  int npix,ntrks;
  //  TTree* t = (TTree*)infile->Get("HltTree");
  int run;

  if(SIM){
    t->SetBranchAddress("b",&b);
    t->SetBranchAddress("Npart",&npart);
    t->SetBranchAddress("Ncoll",&ncoll);
    t->SetBranchAddress("Nhard",&nhard);
  }

  t->SetBranchAddress("hiHFhit",&hfhit);
  t->SetBranchAddress("hiHF",&hf);
  t->SetBranchAddress("hiEB",&eb);
  t->SetBranchAddress("hiEE",&ee);
  t->SetBranchAddress("hiET",&etmr);
  t->SetBranchAddress("hiNpix",&npix);
  t->SetBranchAddress("hiNtracks",&ntrks);
  t->SetBranchAddress("Run",&run);

  bool binNpart = label.compare("Npart") == 0;
  bool binNcoll = label.compare("Ncoll") == 0;
  bool binNhard = label.compare("Nhard") == 0;
  bool binB = label.compare("b") == 0;
  bool binHF = label.compare("HFtowers") == 0;
  bool binHFhit = label.compare("HFhits") == 0;
  bool binEB = label.compare("EB") == 0;
  bool binEE = label.compare("EE") == 0;
  bool binETMR = label.compare("ETMR") == 0;
  bool binNpix = label.compare("PixelHits") == 0;
  bool binNtrks = label.compare("Ntracks") == 0;

  // Determining bins of cross section
  // loop over events
  unsigned int events=t->GetEntries();
  for(unsigned int iev = 0; iev < events && (maxEvents < 0 || iev< maxEvents); ++iev){
    if( iev % 100 == 0 ) cout<<"Processing event : "<<iev<<endl;
    t->GetEntry(iev);

    if(binNpart) parameter = npart;
    if(binNcoll) parameter = ncoll;
    if(binNhard) parameter = nhard;
    if(binB) parameter = b;
    if(binHF) parameter = hf;
    if(binHFhit) parameter = hfhit;
    if(binEB) parameter = eb;
    if(binEE) parameter = ee;
    if(binETMR) parameter = etmr;
    if(binNpix) parameter = npix;
    if(binNtrks) parameter = ntrks;
 
    values.push_back(parameter);
    if(runnums.size() == 0 || runnums[runnums.size()-1] != run) runnums.push_back(run);
  }
  
  if(label.compare("b") == 0) sort(values.begin(),values.end(),descend);
  else sort(values.begin(),values.end());

  double max = values[events-1];
  binboundaries[nbins] = max;

  cout<<"-------------------------------------"<<endl;
  cout<<label.data()<<" based cuts are : "<<endl;
  cout<<"(";

  int bin = 0;
  double dev = events;
  for(int i = 0; i< nbins; ++i){
     // Find the boundary 
    int entry = (int)(i*(dev/nbins));
    binboundaries[i] = values[entry];

     cout<<" "<<binboundaries[i];
     if(i < nbins - 1) cout<<",";
     else cout<<")"<<endl;
  }

  cout<<"-------------------------------------"<<endl;

  if(!DATA){

  // Determining Glauber results in various bins
  dir->cd();
  TH2D* hNpart = new TH2D("hNpart","",nbins,binboundaries,500,0,500);
  TH2D* hNcoll = new TH2D("hNcoll","",nbins,binboundaries,2000,0,2000);
  TH2D* hNhard = new TH2D("hNhard","",nbins,binboundaries,250,0,250);
  TH2D* hb = new TH2D("hb","",nbins,binboundaries,300,0,30);

  for(unsigned int iev = 0; iev < events && (maxEvents < 0 || iev< maxEvents); ++iev){
     if( iev % 100 == 0 ) cout<<"Processing event : "<<iev<<endl;
     t->GetEntry(iev);
     if(binNpart) parameter = npart;
     if(binNcoll) parameter = ncoll;
     if(binNhard) parameter = nhard;
     if(binB) parameter = b;
     if(binHF) parameter = hf;
     if(binHFhit) parameter = hfhit;
     if(binEB) parameter = eb;
     if(binEE) parameter = ee;
     if(binETMR) parameter = etmr;
     if(binNpix) parameter = npix;
     if(binNtrks) parameter = ntrks;
    
     hNpart->Fill(parameter,npart);
     hNcoll->Fill(parameter,ncoll);
     hNhard->Fill(parameter,nhard);
     hb->Fill(parameter,b);
     int bin = hNpart->GetXaxis()->FindBin(parameter) - 1;
     if(bin < 0) bin = 0;
     if(bin >= nbins) bin = nbins - 1;
     nt->Fill(hf,bin,b,npart,ncoll,nhard);
  }

  // Fitting Glauber distributions in bins to get mean and sigma values

  dir->cd();
  TF1* fGaus = new TF1("fb","gaus(0)",0,2); 
  fGaus->SetParameter(0,1);
  fGaus->SetParameter(1,0.04);
  fGaus->SetParameter(2,0.02); 
  
  fitSlices(hNpart,fGaus);
  fitSlices(hNcoll,fGaus);
  fitSlices(hNhard,fGaus);
  fitSlices(hb,fGaus);

  TH1D* hNpartMean = (TH1D*)gDirectory->Get("hNpart_1");
  TH1D* hNpartSigma = (TH1D*)gDirectory->Get("hNpart_2");
  TH1D* hNcollMean = (TH1D*)gDirectory->Get("hNcoll_1");
  TH1D* hNcollSigma = (TH1D*)gDirectory->Get("hNcoll_2");
  TH1D* hNhardMean = (TH1D*)gDirectory->Get("hNhard_1");
  TH1D* hNhardSigma = (TH1D*)gDirectory->Get("hNhard_2");
  TH1D* hbMean = (TH1D*)gDirectory->Get("hb_1");
  TH1D* hbSigma = (TH1D*)gDirectory->Get("hb_2");

  cout<<"-------------------------------------"<<endl;
  cout<<"# Bin NpartMean NpartSigma NcollMean NcollSigma bMean bSigma BinEdge"<<endl;

  // Enter values in table
  for(int i = 0; i < nbins; ++i){
     int ii = nbins-i;
     bins->table_[i].n_part_mean = hNpartMean->GetBinContent(ii);
     bins->table_[i].n_part_var = hNpartSigma->GetBinContent(ii);
     bins->table_[i].n_coll_mean = hNcollMean->GetBinContent(ii);
     bins->table_[i].n_coll_var = hNcollSigma->GetBinContent(ii);
     bins->table_[i].b_mean = hbMean->GetBinContent(ii);
     bins->table_[i].b_var = hbSigma->GetBinContent(ii);
     bins->table_[i].n_hard_mean = hNhardMean->GetBinContent(ii);
     bins->table_[i].n_hard_var = hNhardSigma->GetBinContent(ii);
     bins->table_[i].bin_edge = binboundaries[ii-1];

     cout<<i<<" "
	 <<hNpartMean->GetBinContent(ii)<<" "
	 <<hNpartSigma->GetBinContent(ii)<<" "
	 <<hNcollMean->GetBinContent(ii)<<" "
	 <<hNcollSigma->GetBinContent(ii)<<" "
	 <<hbMean->GetBinContent(ii)<<" "
	 <<hbSigma->GetBinContent(ii)<<" "
	 <<binboundaries[ii]<<" "
	 <<endl;
  }
  cout<<"-------------------------------------"<<endl;

  // Save the table in output file
  if(onlySaveTable){

     hNpart->Delete();
     hNpartMean->Delete();
     hNpartSigma->Delete();
     hNcoll->Delete();
     hNcollMean->Delete();
     hNcollSigma->Delete();
     hNhard->Delete();
     hNhardMean->Delete();
     hNhardSigma->Delete();
     hb->Delete();
     hbMean->Delete();
     hbSigma->Delete();
  }
 
  }else{
    cout<<"-------------------------------------"<<endl;
    cout<<"# Bin NpartMean NpartSigma NcollMean NcollSigma bMean bSigma BinEdge"<<endl;

    // Enter values in table
    for(int i = 0; i < nbins; ++i){
      int ii = nbins-i;
      bins->table_[i].n_part_mean = inputMCtable->NpartMeanOfBin(i);
      bins->table_[i].n_part_var = inputMCtable->NpartSigmaOfBin(i);
      bins->table_[i].n_coll_mean = inputMCtable->NcollMeanOfBin(i);
      bins->table_[i].n_coll_var = inputMCtable->NcollSigmaOfBin(i);
      bins->table_[i].b_mean = inputMCtable->bMeanOfBin(i);
      bins->table_[i].b_var = inputMCtable->bSigmaOfBin(i);
      bins->table_[i].n_hard_mean = inputMCtable->NhardMeanOfBin(i);
      bins->table_[i].n_hard_var = inputMCtable->NhardSigmaOfBin(i);
      bins->table_[i].bin_edge = binboundaries[ii-1];

      cout<<i<<" "
	  <<bins->table_[i].n_part_mean<<" "
          <<bins->table_[i].n_part_var<<" "
          <<bins->table_[i].n_coll_mean<<" "
          <<bins->table_[i].n_coll_var<<" "
          <<bins->table_[i].b_mean<<" "
          <<bins->table_[i].b_var<<" "
          <<bins->table_[i].n_hard_mean<<" "
          <<bins->table_[i].n_hard_var<<" "
          <<bins->table_[i].bin_edge<<" "<<endl;

    }
    cout<<"-------------------------------------"<<endl;

  }


  outFile->cd(); 
  dir->cd();

  bins->SetName(Form("run%d",1));
  bins->Write();
  nt->Write();  
  bins->Delete();
  outFile->Write();
  
}
コード例 #20
0
ファイル: makeTable2.C プロジェクト: kurtejung/PurdueForest
void makeTable2(int nbins = 100, const string label = "HFtowersPlusTrunc", const char * tag = "CentralityTable_HFplus100_PA2012B_v538x01_offline", bool isMC = false, int runNum = 1) {

 TH1D::SetDefaultSumw2();

 //Intput files with HiTrees
 const int nTrees = 1;
 //string inFileNames[nTrees] = {"/tmp/azsigmon/HiForest_pPb_Hijing_NEWFIX_v2.root"};
 //string inFileNames[nTrees] = {"/tmp/azsigmon/HiForest_pPb_Epos_336800.root"};
 string inFileNames[nTrees] = {"/tmp/azsigmon/PA2013_HiForest_Express_r0_pilot_minbias_v0.root"};
 TChain * t = new TChain("hiEvtAnalyzer/HiTree");
 for (int i = 0; i<nTrees; i++) {
    t->Add(inFileNames[i].data());
 }

 //Output files and tables
 TFile * outFile = new TFile("out/datatables_Glauber2012B_d20130121_v5.root","recreate");
 //TFile * outFile = new TFile("out/tables_Ampt_d20121115_v3.root","update");
 //TFile * outFile = new TFile("out/tables_Epos_d20121115_v3.root","update");
 //TFile * outFile = new TFile("out/tables_Hijing_d20130119_v4.root","update");
 TDirectory* dir = outFile->mkdir(tag);
 dir->cd();
 TNtuple * nt = new TNtuple("nt","","value:bin:b:npart:ncoll:nhard");
 CentralityBins * bins = new CentralityBins(Form("run%d",runNum), tag, nbins);
 bins->table_.reserve(nbins);

 ofstream txtfile("out/output.txt");
 txtfile << "First input tree: " << inFileNames[0].data() << endl;

 //For data extra inputfile with Glauber centrality table and efficiency file
 TFile * effFile;
 TH1F * hEff; 
 TFile * inputMCfile;
 CentralityBins* inputMCtable;
 if(!isMC){
   //effFile = new TFile("out/efficiencies_Ampt.root","read");
   //effFile = new TFile("out/efficiencies_Hijing.root","read");
   effFile = new TFile("out/efficiencies_EposLHC_v2.root","read");
   hEff = (TH1F*)effFile->Get(Form("%s/hEff",label.data()));
   //inputMCfile = new TFile("out/tables_Glauber2012_AmptResponse_d20121115_v3.root","read");
   //inputMCfile = new TFile("out/tables_Glauber2012_HijingResponse_d20121115_v3.root","read");
   inputMCfile = new TFile("out/tables_Glauber2012B_EposLHCResponse_d20130118_v4.root","read");
   inputMCtable = (CentralityBins*)inputMCfile->Get(Form("CentralityTable_%s_SmearedGlauber_v4/run1",label.data()));
   //txtfile << "Using AMPT efficiency and AMPT smeared Glauber table" << endl << endl;
   txtfile << "Using EPOS efficiency and EPOS smeared Glauber table" << endl << endl;
   //txtfile << "Using HIJING efficiency and HIJING smeared Glauber table" << endl << endl;
 }

 //Setting up variables and branches
 double binboundaries[nbins+1];
 vector<float> values;
 TH1F * hist;
 if(!isMC) hist = new TH1F("hist","",hEff->GetNbinsX(),hEff->GetBinLowEdge(1),hEff->GetBinLowEdge(hEff->GetNbinsX()));

 float vtxZ, b, npart, ncoll, nhard, hf, hfplus, hfpluseta4, hfminuseta4, hfminus, hfhit, ee, eb;
 int run, npix, npixtrks, ntrks;
 t->SetBranchAddress("vz",&vtxZ);
 t->SetBranchAddress("run",&run);
 if(isMC){
    t->SetBranchAddress("b",&b);
    t->SetBranchAddress("Npart",	&npart);
    t->SetBranchAddress("Ncoll",	&ncoll);
    t->SetBranchAddress("Nhard",	&nhard);
 }
 t->SetBranchAddress("hiHF",		&hf);
 t->SetBranchAddress("hiHFplus",	&hfplus);
 t->SetBranchAddress("hiHFplusEta4",	&hfpluseta4);
 t->SetBranchAddress("hiHFminus",	&hfminus);
 t->SetBranchAddress("hiHFminusEta4",	&hfminuseta4);
 t->SetBranchAddress("hiHFhit",		&hfhit);
 t->SetBranchAddress("hiEE",		&ee);
 t->SetBranchAddress("hiEB",		&eb);
 t->SetBranchAddress("hiNpix",		&npix);
 t->SetBranchAddress("hiNpixelTracks",	&npixtrks);
 t->SetBranchAddress("hiNtracks",	&ntrks);
 //t->SetBranchAddress("hiNtracksOffline",	&ntrks);

 bool binB = label.compare("b") == 0;
 bool binNpart = label.compare("Npart") == 0;
 bool binNcoll = label.compare("Ncoll") == 0;
 bool binNhard = label.compare("Nhard") == 0;
 bool binHF = label.compare("HFtowers") == 0;
 bool binHFplus = label.compare("HFtowersPlus") == 0;
 bool binHFminus = label.compare("HFtowersMinus") == 0;
 bool binHFplusTrunc = label.compare("HFtowersPlusTrunc") == 0;
 bool binHFminusTrunc = label.compare("HFtowersMinusTrunc") == 0;
 bool binNpix = label.compare("PixelHits") == 0;
 bool binNpixTrks = label.compare("PixelTracks") == 0;
 bool binNtrks = label.compare("Tracks") == 0;

 //Event loop
 unsigned int Nevents = t->GetEntries();
 txtfile << "Number of events = " << Nevents << endl << endl;
 for(unsigned int iev = 0; iev < Nevents; iev++) {
   if(iev%10000 == 0) cout<<"Processing event: " << iev << endl;
   t->GetEntry(iev);

   //if(run!=runNum) continue;

   float parameter = -1;
   if(binB) parameter = b;
   if(binNpart) parameter = npart;
   if(binNcoll) parameter = ncoll;
   if(binNhard) parameter = nhard;
   if(binHF) parameter = hf;
   if(binHFplus) parameter = hfplus;
   if(binHFminus) parameter = hfminus;
   if(binHFplusTrunc) parameter = hfpluseta4;
   if(binHFminusTrunc) parameter = hfminuseta4;
   if(binNpix) parameter = npix;
   if(binNpixTrks) parameter = npixtrks;
   if(binNtrks) parameter = ntrks;

   values.push_back(parameter);

   if(!isMC) {
     hist->Fill(parameter);
   }

 }

 //Sorting the centrality variable vector
 if(binB) sort(values.begin(),values.end(),descend);
 else sort(values.begin(),values.end());

 //Finding the bin boundaries
 txtfile << "-------------------------------------" << endl;
 txtfile << label.data() << " based cuts are: " << endl;
 txtfile << "(";

 int size = values.size();
 binboundaries[nbins] = values[size-1];

 if(isMC) {
   for(int i = 0; i < nbins; i++) {
      int entry = (int)(i*(size/nbins));
      if(entry < 0 || i == 0) binboundaries[i] = 0;
      else binboundaries[i] = values[entry];
   }
 }
 else {
      TH1F * corr = (TH1F*)hist->Clone("corr");
      //TCanvas *c1 = new TCanvas();
      //c1->SetLogy();
      //corr->DrawCopy("hist");
      for (int j=1; j<corr->GetNbinsX(); j++) {
        if (hEff->GetBinContent(j) != 0) {
          corr->SetBinContent(j,corr->GetBinContent(j)/hEff->GetBinContent(j));
          corr->SetBinError(j,corr->GetBinError(j)/hEff->GetBinContent(j));
        }
      }
      //corr->SetLineColor(2);
      //corr->DrawCopy("hist same");
      //cout << "total integral = " << corr->Integral();
      float prev = 0;
      binboundaries[0] = 0;
      int j = 1;
      for (int i = 1; i < corr->GetNbinsX(); i++) {
        if(j>=nbins) continue;
        float a = corr->Integral(1,i,"");
        a = a/corr->Integral();
	//if(i<100) cout << i << " bin in x fraction of total integral = " << a << " j = " << j << endl;
        if (a > (float)j/nbins && prev < (float)j/nbins) {
		binboundaries[j] = corr->GetBinLowEdge(i+1);
		j++;
	}
        prev = a;
      }
 }
 for(int i = 0; i < nbins; i++) {
  if(binboundaries[i] < 0) binboundaries[i] = 0;
  txtfile << binboundaries[i] << ", ";
 }
 txtfile << binboundaries[nbins] << ")" << endl << "-------------------------------------" << endl;

 //***Determining Glauber results for MC and filling the table***
 if(isMC) {

  dir->cd();
  TH2D* hNpart = new TH2D("hNpart","",nbins,binboundaries,40,0,40);
  TH2D* hNcoll = new TH2D("hNcoll","",nbins,binboundaries,40,0,40);
  TH2D* hNhard = new TH2D("hNhard","",nbins,binboundaries,50,0,50);
  TH2D* hb = new TH2D("hb","",nbins,binboundaries,600,0,30);

  for(unsigned int iev = 0; iev < Nevents; iev++) {
     if( iev % 5000 == 0 ) cout<<"Processing event : " << iev << endl;
     t->GetEntry(iev);

     float parameter = -1;
     if(binB) parameter = b;
     if(binNpart) parameter = npart;
     if(binNcoll) parameter = ncoll;
     if(binNhard) parameter = nhard;
     if(binHF) parameter = hf;
     if(binHFplus) parameter = hfplus;
     if(binHFminus) parameter = hfminus;
     if(binHFplusTrunc) parameter = hfpluseta4;
     if(binHFminusTrunc) parameter = hfminuseta4;
     if(binNpix) parameter = npix;
     if(binNpixTrks) parameter = npixtrks;
     if(binNtrks) parameter = ntrks;

     hNpart->Fill(parameter,npart);
     hNcoll->Fill(parameter,ncoll);
     hNhard->Fill(parameter,nhard);
     hb->Fill(parameter,b);
     int bin = hNpart->GetXaxis()->FindBin(parameter) - 1;
     if(bin < 0) bin = 0;
     if(bin >= nbins) bin = nbins - 1;
     nt->Fill(parameter,bin,b,npart,ncoll,nhard);
  }

  TF1* fGaus = new TF1("fb","gaus(0)",0,2);
  fitSlices(hNpart,fGaus);
  fitSlices(hNcoll,fGaus);
  fitSlices(hNhard,fGaus);
  fitSlices(hb,fGaus);

  TH1D* hNpartMean = (TH1D*)gDirectory->Get("hNpart_1");
  TH1D* hNpartSigma = (TH1D*)gDirectory->Get("hNpart_2");
  TH1D* hNcollMean = (TH1D*)gDirectory->Get("hNcoll_1");
  TH1D* hNcollSigma = (TH1D*)gDirectory->Get("hNcoll_2");
  TH1D* hNhardMean = (TH1D*)gDirectory->Get("hNhard_1");
  TH1D* hNhardSigma = (TH1D*)gDirectory->Get("hNhard_2");
  TH1D* hbMean = (TH1D*)gDirectory->Get("hb_1");
  TH1D* hbSigma = (TH1D*)gDirectory->Get("hb_2");

  txtfile<<"-------------------------------------"<<endl;
  txtfile<<"# Bin NpartMean NpartSigma NcollMean NcollSigma bMean bSigma BinEdge"<<endl;
  for(int i = 0; i < nbins; i++){
     int ii = nbins-i;
     bins->table_[i].n_part_mean = hNpartMean->GetBinContent(ii);
     bins->table_[i].n_part_var = hNpartSigma->GetBinContent(ii);
     bins->table_[i].n_coll_mean = hNcollMean->GetBinContent(ii);
     bins->table_[i].n_coll_var = hNcollSigma->GetBinContent(ii);
     bins->table_[i].b_mean = hbMean->GetBinContent(ii);
     bins->table_[i].b_var = hbSigma->GetBinContent(ii);
     bins->table_[i].n_hard_mean = hNhardMean->GetBinContent(ii);
     bins->table_[i].n_hard_var = hNhardSigma->GetBinContent(ii);
     bins->table_[i].bin_edge = binboundaries[ii-1];

     txtfile << i << " " << hNpartMean->GetBinContent(ii) << " " << hNpartSigma->GetBinContent(ii) << " " << hNcollMean->GetBinContent(ii) << " " << hNcollSigma->GetBinContent(ii) << " " << hbMean->GetBinContent(ii) << " " <<hbSigma->GetBinContent(ii) << " " << binboundaries[ii-1] << " " <<endl;
  }
  txtfile<<"-------------------------------------"<<endl;

 } //***end of MC part***

 else { //***Data table with inputMCtable***

    txtfile<<"-------------------------------------"<<endl;
    txtfile<<"# Bin NpartMean NpartSigma NcollMean NcollSigma bMean bSigma BinEdge"<<endl;
    for(int i = 0; i < nbins; i++){
      int ii = nbins-i;
      bins->table_[i].n_part_mean = inputMCtable->NpartMeanOfBin(i);
      bins->table_[i].n_part_var = inputMCtable->NpartSigmaOfBin(i);
      bins->table_[i].n_coll_mean = inputMCtable->NcollMeanOfBin(i);
      bins->table_[i].n_coll_var = inputMCtable->NcollSigmaOfBin(i);
      bins->table_[i].b_mean = inputMCtable->bMeanOfBin(i);
      bins->table_[i].b_var = inputMCtable->bSigmaOfBin(i);
      bins->table_[i].n_hard_mean = inputMCtable->NhardMeanOfBin(i);
      bins->table_[i].n_hard_var = inputMCtable->NhardSigmaOfBin(i);
      bins->table_[i].ecc2_mean  = inputMCtable->eccentricityMeanOfBin(i);
      bins->table_[i].ecc2_var = inputMCtable->eccentricitySigmaOfBin(i);
      bins->table_[i].bin_edge = binboundaries[ii-1];

      txtfile << i << " " << bins->table_[i].n_part_mean << " " << bins->table_[i].n_part_var << " " << bins->table_[i].n_coll_mean << " " << bins->table_[i].n_coll_var << " " <<bins->table_[i].b_mean << " " << bins->table_[i].b_var << " " << bins->table_[i].n_hard_mean << " " << bins->table_[i].n_hard_var << " " << bins->table_[i].bin_edge << " " << endl;
    }
    txtfile<<"-------------------------------------"<<endl;

 } //***end of Data part***

 outFile->cd();
 dir->cd();
 bins->Write();
 nt->Write();  
 bins->Delete();
 outFile->Write();
 txtfile.close();

}