void selectProbesMuEff(const TString infilename, // input ntuple const TString outputDir, // output directory const Int_t effType, // type of efficiency to compute const Bool_t doGenMatch = kFALSE, // match to generator leptons const Bool_t doWeighted = kFALSE // store events with weights ) { gBenchmark->Start("selectProbesMuEff"); //-------------------------------------------------------------------------------------------------------------- // Settings //============================================================================================================== const Double_t TAG_PT_CUT = 25; //-------------------------------------------------------------------------------------------------------------- // Main analysis code //============================================================================================================== enum {eIDISO, eTrigger}; if(effType > eTrigger) { cout << "Invalid effType option! Exiting..." << endl; return; } Double_t nProbes = 0; // // Set up output ntuple // gSystem->mkdir(outputDir,kTRUE); TFile *outFile = new TFile(outputDir+TString("/probes.root"),"RECREATE"); TTree *outTree = new TTree("Events","Events"); EffData data; outTree->Branch("Events",&data.mass,"mass/F:pt:eta:phi:weight:q/I:npv/i:pass:evtNum"); // // Declare output ntuple variables // Int_t matchGen; Int_t npv; Float_t genVPt, genVPhi, genVy, genVMass; Float_t rawpfmet, rawpfmetPhi; Float_t type1pfmet, type1pfmetPhi; Float_t genmet, genmetPhi, u1, u2; Int_t q1, q2; Float_t pfChIso1, pfChIso2; LorentzVector *dilep=0, *lep1=0, *lep2=0; Int_t isLooseMuon1, isSoftMuon1, isTightMuon1; Int_t isLooseMuon2, isSoftMuon2, isTightMuon2; Int_t passSingleMuTrigger; Int_t matchTrigObj1, matchTrigObj2; // Read input file and get the TTrees cout << "Processing " << infilename << "..." << endl; TFile *infile = new TFile(infilename); assert(infile); TTree *intree = (TTree*)infile->Get("Events"); assert(intree); intree->SetBranchAddress("matchGen", &matchGen); // event has both leptons matched to MC Z->ll intree->SetBranchAddress("npv", &npv); // number of primary vertices intree->SetBranchAddress("genVPt", &genVPt); intree->SetBranchAddress("genVPhi", &genVPhi); intree->SetBranchAddress("genVy", &genVy); intree->SetBranchAddress("genVMass", &genVMass); intree->SetBranchAddress("rawpfmet", &rawpfmet); intree->SetBranchAddress("rawpfmetPhi", &rawpfmetPhi); intree->SetBranchAddress("type1pfmet", &type1pfmet); intree->SetBranchAddress("type1pfmetPhi", &type1pfmetPhi); intree->SetBranchAddress("genmet", &genmet); // MET intree->SetBranchAddress("genmetPhi", &genmetPhi); // phi(MET) intree->SetBranchAddress("u1", &u1); // parallel component of recoil intree->SetBranchAddress("u2", &u2); // perpendicular component of recoil intree->SetBranchAddress("q1", &q1); // charge of tag lepton intree->SetBranchAddress("q2", &q2); // charge of probe lepton intree->SetBranchAddress("pfChIso1", &pfChIso1); intree->SetBranchAddress("pfChIso2", &pfChIso2); intree->SetBranchAddress("dilep", &dilep); // dilepton 4-vector intree->SetBranchAddress("lep1", &lep1); // tag lepton 4-vector intree->SetBranchAddress("lep2", &lep2); // probe lepton 4-vector intree->SetBranchAddress("isLooseMuon1", &isLooseMuon1); intree->SetBranchAddress("isSoftMuon1", &isSoftMuon1); intree->SetBranchAddress("isTightMuon1", &isTightMuon1); intree->SetBranchAddress("isLooseMuon2", &isLooseMuon2); intree->SetBranchAddress("isSoftMuon2", &isSoftMuon2); intree->SetBranchAddress("isTightMuon2", &isTightMuon2); intree->SetBranchAddress("passSingleMuTrigger", &passSingleMuTrigger); intree->SetBranchAddress("matchTrigObj1", &matchTrigObj1); intree->SetBranchAddress("matchTrigObj2", &matchTrigObj2); // // loop over events // for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) { //for(UInt_t ientry=0; ientry<10000; ientry++) { intree->GetEntry(ientry); if(lep1->Pt() < TAG_PT_CUT) continue; // check GEN match if necessary if(doGenMatch && !matchGen) continue; Bool_t pass=kFALSE; Float_t mass=0; if(effType==eIDISO) { // probe = slimmed muon // pass = TightID and Charged Isolation Cut < 0.15 * probe pT if(isTightMuon2 && pfChIso2 < 0.15 * lep2->Pt()) {pass=kTRUE;} else {pass=kFALSE;} mass = dilep->M(); } nProbes += 1; // FIll tree data.mass = mass; data.pt = lep2->Pt(); data.eta = lep2->Eta(); data.phi = lep2->Phi(); data.weight = 1; data.q = q2; data.npv = npv; data.pass = (pass) ? 1 : 0; outTree->Fill(); } delete infile; infile=0, intree=0; //-------------------------------------------------------------------------------------------------------------- // Output //============================================================================================================== cout << "*" << endl; cout << "* SUMMARY" << endl; cout << "*--------------------------------------------------" << endl; cout << endl; cout << " Number of probes selected: " << nProbes << endl; outFile->Write(); outFile->Close(); delete outFile; cout << endl; cout << " <> Output saved in " << outputDir << "/" << endl; cout << endl; gBenchmark->Show("selectProbesMuEff"); }
void mkTreeForPredictedNonZeroACPScan() { float assumedACP[NENTRY] ={ -30, -25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30 }; string assumedACP_s[NENTRY]={ "m30", "m25", "m20", "m15", "m10", "m5", "0", "p5", "p10", "p15", "p20", "p25", "p30"}; TFile* fin = new TFile(fin_s.c_str()); //TH1D *h_sudoAllAsym[NOBS][NCH], *h_sudoSigAsym[NOBS][NCH]; TH1D *h_mcCutFlow[2]; TH1D *h_sigCutFlow[2]; TH1D *h_SigAsym[NOBS][NCH]; TH1D *h_bkg[NOBS][NCH]; TH1D *h_bkgAsym[NOBS][NCH]; h_mcCutFlow[CH_Muon] = (TH1D*)fin->Get("MC__Evt_CutFlow_Mu"); h_mcCutFlow[CH_Electron] = (TH1D*)fin->Get("MC__Evt_CutFlow_El"); h_sigCutFlow[CH_Muon] = (TH1D*)fin->Get("TTJets_SemiLeptMGDecays__Evt_CutFlow_Mu"); h_sigCutFlow[CH_Electron] = (TH1D*)fin->Get("TTJets_SemiLeptMGDecays__Evt_CutFlow_El"); h_SigAsym[OBS_O2][CH_Electron] = (TH1D*)fin->Get("TTJets_SemiLeptMGDecays__Evt_O2Asym_El"); h_SigAsym[OBS_O2][CH_Muon] = (TH1D*)fin->Get("TTJets_SemiLeptMGDecays__Evt_O2Asym_Mu"); h_SigAsym[OBS_O2][CH_Combined] = (TH1D*)fin->Get("TTJets_SemiLeptMGDecays__Evt_O2Asym" ); h_SigAsym[OBS_O3][CH_Electron] = (TH1D*)fin->Get("TTJets_SemiLeptMGDecays__Evt_O3Asym_El"); h_SigAsym[OBS_O3][CH_Muon] = (TH1D*)fin->Get("TTJets_SemiLeptMGDecays__Evt_O3Asym_Mu"); h_SigAsym[OBS_O3][CH_Combined] = (TH1D*)fin->Get("TTJets_SemiLeptMGDecays__Evt_O3Asym" ); h_SigAsym[OBS_O4][CH_Electron] = (TH1D*)fin->Get("TTJets_SemiLeptMGDecays__Evt_O4Asym_El"); h_SigAsym[OBS_O4][CH_Muon] = (TH1D*)fin->Get("TTJets_SemiLeptMGDecays__Evt_O4Asym_Mu"); h_SigAsym[OBS_O4][CH_Combined] = (TH1D*)fin->Get("TTJets_SemiLeptMGDecays__Evt_O4Asym" ); h_SigAsym[OBS_O7][CH_Electron] = (TH1D*)fin->Get("TTJets_SemiLeptMGDecays__Evt_O7Asym_El"); h_SigAsym[OBS_O7][CH_Muon] = (TH1D*)fin->Get("TTJets_SemiLeptMGDecays__Evt_O7Asym_Mu"); h_SigAsym[OBS_O7][CH_Combined] = (TH1D*)fin->Get("TTJets_SemiLeptMGDecays__Evt_O7Asym" ); h_bkgAsym[OBS_O2][CH_Electron] = (TH1D*)fin->Get("BkgMC__Evt_O2Asym_El"); h_bkgAsym[OBS_O2][CH_Muon] = (TH1D*)fin->Get("BkgMC__Evt_O2Asym_Mu"); h_bkgAsym[OBS_O2][CH_Combined] = (TH1D*)fin->Get("BkgMC__Evt_O2Asym" ); h_bkgAsym[OBS_O3][CH_Electron] = (TH1D*)fin->Get("BkgMC__Evt_O3Asym_El"); h_bkgAsym[OBS_O3][CH_Muon] = (TH1D*)fin->Get("BkgMC__Evt_O3Asym_Mu"); h_bkgAsym[OBS_O3][CH_Combined] = (TH1D*)fin->Get("BkgMC__Evt_O3Asym" ); h_bkgAsym[OBS_O4][CH_Electron] = (TH1D*)fin->Get("BkgMC__Evt_O4Asym_El"); h_bkgAsym[OBS_O4][CH_Muon] = (TH1D*)fin->Get("BkgMC__Evt_O4Asym_Mu"); h_bkgAsym[OBS_O4][CH_Combined] = (TH1D*)fin->Get("BkgMC__Evt_O4Asym" ); h_bkgAsym[OBS_O7][CH_Electron] = (TH1D*)fin->Get("BkgMC__Evt_O7Asym_El"); h_bkgAsym[OBS_O7][CH_Muon] = (TH1D*)fin->Get("BkgMC__Evt_O7Asym_Mu"); h_bkgAsym[OBS_O7][CH_Combined] = (TH1D*)fin->Get("BkgMC__Evt_O7Asym" ); TFile* fout = new TFile(fout_s.c_str(), "RECREATE"); TTree* tout = new TTree(tout_s.c_str(), ""); TH1D *h_template[NENTRY][NOBS][NCH]; TH1D *h_sudoExpACPmean[NENTRY][NOBS][NCH]; TH1D *h_sudoExpACPuncs[NENTRY][NOBS][NCH]; TH1D *h_sudoSigACPmean[NENTRY][NOBS][NCH]; TH1D *h_sudoSigACPuncs[NENTRY][NOBS][NCH]; int lastBin = h_sigCutFlow[CH_Electron]->GetXaxis()->GetLast(); float nSig[NCH], eSig[NCH], nMC[NCH]; nSig[CH_Muon] = h_sigCutFlow[CH_Muon] ->GetBinContent(lastBin); nSig[CH_Electron] = h_sigCutFlow[CH_Electron]->GetBinContent(lastBin); nSig[CH_Combined] = nSig[CH_Muon]+nSig[CH_Electron]; eSig[CH_Muon] = h_sigCutFlow[CH_Muon] ->GetBinError(lastBin); eSig[CH_Electron] = h_sigCutFlow[CH_Electron]->GetBinError(lastBin); eSig[CH_Combined] = sqrt( eSig[CH_Muon]*eSig[CH_Muon] + eSig[CH_Electron]*eSig[CH_Electron] ); nMC[CH_Muon] = h_mcCutFlow[CH_Muon]->GetBinContent(lastBin); nMC[CH_Electron] = h_mcCutFlow[CH_Electron]->GetBinContent(lastBin); nMC[CH_Combined] = nMC[CH_Muon] + nMC[CH_Electron]; float assumedACPMean; float assumedACPUncs[NOBS][NCH]; float nSigP[NOBS][NCH]; float nSigM[NOBS][NCH]; float eSigP[NOBS][NCH]; float eSigM[NOBS][NCH]; float nBkgP[NOBS][NCH]; float eBkgP[NOBS][NCH]; float nBkgM[NOBS][NCH]; float eBkgM[NOBS][NCH]; float MC_nEventsPredictedObsP[NOBS][NCH]; float MC_nEventsPredictedObsM[NOBS][NCH]; float MC_eEventsPredictedObsP[NOBS][NCH]; float MC_eEventsPredictedObsM[NOBS][NCH]; float MC_acpMean[NOBS][NCH]; float MC_acpUncs[NOBS][NCH]; float SudoExp_acpMean[NOBS][NCH]; float SudoExp_acpUncs[NOBS][NCH]; float SudoSig_acpMean[NOBS][NCH]; float SudoSig_acpUncs[NOBS][NCH]; tout->Branch("assumedACPMean", &assumedACPMean, "assumedACPMean/F" ); tout->Branch("assumedACPUncs", &assumedACPUncs[0][0], "assumedACPUncs[4][3]/F" ); tout->Branch("nSigP", &nSigP[0][0], "nSigP[4][3]/F" ); tout->Branch("eSigP", &eSigP[0][0], "eSigP[4][3]/F" ); tout->Branch("nSigM", &nSigM[0][0], "nSigM[4][3]/F" ); tout->Branch("eSigM", &eSigM[0][0], "eSigM[4][3]/F" ); tout->Branch("nBkgP", &nBkgP[0][0], "nBkgP[4][3]/F" ); tout->Branch("eBkgP", &eBkgP[0][0], "eBkgP[4][3]/F" ); tout->Branch("nBkgM", &nBkgM[0][0], "nBkgM[4][3]/F" ); tout->Branch("eBkgM", &eBkgM[0][0], "eBkgM[4][3]/F" ); tout->Branch("MC_nEventsPredictedObsP", &MC_nEventsPredictedObsP[0][0], "MC_nEventsPredictedObsP[4][3]/F" ); tout->Branch("MC_nEventsPredictedObsM", &MC_nEventsPredictedObsM[0][0], "MC_nEventsPredictedObsM[4][3]/F" ); tout->Branch("MC_eEventsPredictedObsP", &MC_eEventsPredictedObsP[0][0], "MC_eEventsPredictedObsP[4][3]/F" ); tout->Branch("MC_eEventsPredictedObsM", &MC_eEventsPredictedObsM[0][0], "MC_eEventsPredictedObsM[4][3]/F" ); tout->Branch("MC_acpMean", &MC_acpMean[0][0], "MC_acpMean[4][3]/F" ); tout->Branch("MC_acpUncs", &MC_acpUncs[0][0], "MC_acpUncs[4][3]/F" ); tout->Branch("SudoExp_acpMean", &SudoExp_acpMean[0][0], "SudoExp_acpMean[4][3]/F" ); tout->Branch("SudoExp_acpUncs", &SudoExp_acpUncs[0][0], "SudoExp_acpUncs[4][3]/F" ); tout->Branch("SudoSig_acpMean", &SudoSig_acpMean[0][0], "SudoSig_acpMean[4][3]/F" ); tout->Branch("SudoSig_acpUncs", &SudoSig_acpUncs[0][0], "SudoSig_acpUncs[4][3]/F" ); printf("=============================================================\n"); printf("Total MC Combined %6.2f, Electron %6.2f, Muon %6.2f\n", nMC[CH_Combined], nMC[CH_Electron], nMC[CH_Muon]); for( int entry=0; entry<NENTRY; entry++) { assumedACPMean = assumedACP[entry]/100; // Checking bkg MC effect for( int ich=0; ich<NCH; ich++) { for( int iobs=0; iobs<NOBS; iobs++) { h_sudoExpACPmean[entry][iobs][ich] = new TH1D(("SudoExp_"+assumedACP_s[entry]+"ACPmean_"+obs_s[iobs]+ch_s[ich]).c_str(), "", 2000, -100, 100); h_sudoExpACPuncs[entry][iobs][ich] = new TH1D(("SudoExp_"+assumedACP_s[entry]+"ACPunus_"+obs_s[iobs]+ch_s[ich]).c_str(), "", 1000, 0, 1); h_sudoSigACPmean[entry][iobs][ich] = new TH1D(("SudoSig_"+assumedACP_s[entry]+"ACPmean_"+obs_s[iobs]+ch_s[ich]).c_str(), "", 2000, -100, 100); h_sudoSigACPuncs[entry][iobs][ich] = new TH1D(("SudoSig_"+assumedACP_s[entry]+"ACPunus_"+obs_s[iobs]+ch_s[ich]).c_str(), "", 1000, 0, 1); h_sudoExpACPmean[entry][iobs][ich]->Sumw2(); h_sudoExpACPuncs[entry][iobs][ich]->Sumw2(); h_sudoSigACPmean[entry][iobs][ich]->Sumw2(); h_sudoSigACPuncs[entry][iobs][ich]->Sumw2(); h_template[entry][iobs][ich] = new TH1D(("MC_"+assumedACP_s[entry]+"ACP_"+obs_s[iobs]+"Asym"+ch_s[ich]).c_str(), "", 2, -1, 1); h_template[entry][iobs][ich] ->Sumw2(); // Get signal MC or give assumed signal MC (non-0 acp) if( assumedACPMean == 0. ) { nSigP[iobs][ich] = h_SigAsym[iobs][ich]->GetBinContent(2); nSigM[iobs][ich] = h_SigAsym[iobs][ich]->GetBinContent(1); }else{ nSigP[iobs][ich] = getValue( assumedACPMean, nSig[ich], true ); nSigM[iobs][ich] = getValue( assumedACPMean, nSig[ich], false ); } eSigP[iobs][ich] = sqrt(nSigP[iobs][ich]); eSigM[iobs][ich] = sqrt(nSigM[iobs][ich]); assumedACPUncs[iobs][ich] = getACPUncs( nSigP[iobs][ich], nSigM[iobs][ich] ); // Get background yieds nBkgP[iobs][ich] = h_bkgAsym[iobs][ich]->GetBinContent(2); nBkgM[iobs][ich] = h_bkgAsym[iobs][ich]->GetBinContent(1); eBkgP[iobs][ich] = h_bkgAsym[iobs][ich]->GetBinError(2); eBkgM[iobs][ich] = h_bkgAsym[iobs][ich]->GetBinError(1); // Get assumed signal + background, ACP, and fill template MC_nEventsPredictedObsP[iobs][ich] = nBkgP[iobs][ich] + nSigP[iobs][ich]; MC_nEventsPredictedObsM[iobs][ich] = nBkgM[iobs][ich] + nSigM[iobs][ich]; MC_eEventsPredictedObsP[iobs][ich] = sqrt( eBkgP[iobs][ich]*eBkgP[iobs][ich] + eSigP[iobs][ich]*eSigP[iobs][ich] ); MC_eEventsPredictedObsM[iobs][ich] = sqrt( eBkgM[iobs][ich]*eBkgM[iobs][ich] + eSigM[iobs][ich]*eSigM[iobs][ich] ); MC_acpMean[iobs][ich] = getACPMean( MC_nEventsPredictedObsP[iobs][ich], MC_nEventsPredictedObsM[iobs][ich]); MC_acpUncs[iobs][ich] = getACPUncs( MC_nEventsPredictedObsP[iobs][ich], MC_nEventsPredictedObsM[iobs][ich], MC_eEventsPredictedObsP[iobs][ich], MC_eEventsPredictedObsM[iobs][ich] ); h_template[entry][iobs][ich]->SetBinContent(1, MC_nEventsPredictedObsM[iobs][ich]); h_template[entry][iobs][ich]->SetBinContent(2, MC_nEventsPredictedObsP[iobs][ich]); h_template[entry][iobs][ich]->SetBinError (1, MC_eEventsPredictedObsM[iobs][ich]); h_template[entry][iobs][ich]->SetBinError (2, MC_eEventsPredictedObsP[iobs][ich]); } } // Sudo expriment for( int iexp=0; iexp<NEXP; iexp++) { for( int iobs=0; iobs<NOBS; iobs++ ) { for( int ich=0; ich<NCH; ich++) { float nEvtsSudoExp_M, nEvtsSudoSig_M; float nEvtsSudoExp_P, nEvtsSudoSig_P; float eEvtsSudoExp_M, eEvtsSudoSig_M; float eEvtsSudoExp_P, eEvtsSudoSig_P; // Do toy MC TH1D *h_sudoExp = new TH1D("sudoExp_Asym", "", 2, -1, 1); h_sudoExp->Sumw2(); h_sudoExp->FillRandom( h_template[entry][iobs][ich], int(nMC[ich])); nEvtsSudoExp_M = h_sudoExp->GetBinContent(1); nEvtsSudoExp_P = h_sudoExp->GetBinContent(2); eEvtsSudoExp_M = h_sudoExp->GetBinError(1); eEvtsSudoExp_P = h_sudoExp->GetBinError(2); // Subtract bkg, get toy signal TH1D* h_sudoSig = (TH1D*)h_sudoExp->Clone("sudoSig_Asym"); h_sudoSig->Add( h_bkgAsym[iobs][ich], -1); nEvtsSudoSig_M = h_sudoSig->GetBinContent(1); nEvtsSudoSig_P = h_sudoSig->GetBinContent(2); eEvtsSudoSig_M = h_sudoSig->GetBinError(1); eEvtsSudoSig_P = h_sudoSig->GetBinError(2); // Fill pull h_sudoExpACPmean[entry][iobs][ich]->Fill( getACPMean(nEvtsSudoExp_P, nEvtsSudoExp_M)*100. ); h_sudoSigACPmean[entry][iobs][ich]->Fill( getACPMean(nEvtsSudoSig_P, nEvtsSudoSig_M)*100. ); h_sudoExpACPuncs[entry][iobs][ich]->Fill( getACPUncs(nEvtsSudoExp_P, nEvtsSudoExp_M)*100. ); h_sudoSigACPuncs[entry][iobs][ich]->Fill( getACPUncs(nEvtsSudoSig_P, nEvtsSudoSig_M, eEvtsSudoSig_P, eEvtsSudoSig_M )*100. ); delete h_sudoExp; delete h_sudoSig; } } } for( int ich=0; ich<NCH; ich++) { for( int iobs=0; iobs<NOBS; iobs++ ) { TF1* gaus = new TF1("gaus1_","gaus", assumedACP[entry]-10, assumedACP[entry]+10); gaus->SetLineColor(2); h_sudoExpACPmean[entry][iobs][ich]->Fit( gaus, "WR" ); SudoExp_acpMean[iobs][ich] = gaus->GetParameter(1)/100; SudoExp_acpUncs[iobs][ich] = gaus->GetParameter(2)/100; h_sudoSigACPmean[entry][iobs][ich]->Fit( gaus, "WR" ); SudoSig_acpMean[iobs][ich] = gaus->GetParameter(1)/100; SudoSig_acpUncs[iobs][ich] = gaus->GetParameter(2)/100; delete gaus; } } // Debug printf("=============================================================\n"); printf("Assumed ACP %.0f%s\n", assumedACPMean*100, "%"); printf("O2 Uncs Combined %6.2f, Electron %6.2f, Muon %6.2f\n", assumedACPUncs[OBS_O2][CH_Combined]*100, assumedACPUncs[OBS_O2][CH_Electron]*100, assumedACPUncs[OBS_O2][CH_Muon]*100); printf("O3 Uncs Combined %6.2f, Electron %6.2f, Muon %6.2f\n", assumedACPUncs[OBS_O3][CH_Combined]*100, assumedACPUncs[OBS_O3][CH_Electron]*100, assumedACPUncs[OBS_O3][CH_Muon]*100); printf("O4 Uncs Combined %6.2f, Electron %6.2f, Muon %6.2f\n", assumedACPUncs[OBS_O4][CH_Combined]*100, assumedACPUncs[OBS_O4][CH_Electron]*100, assumedACPUncs[OBS_O4][CH_Muon]*100); printf("O7 Uncs Combined %6.2f, Electron %6.2f, Muon %6.2f\n", assumedACPUncs[OBS_O7][CH_Combined]*100, assumedACPUncs[OBS_O7][CH_Electron]*100, assumedACPUncs[OBS_O7][CH_Muon]*100); printf("O2+ Evt Combined %6.0f, Electron %6.0f, Muon %6.0f\n", nSigP[OBS_O2][CH_Combined], nSigP[OBS_O2][CH_Electron], nSigP[OBS_O2][CH_Muon]); printf("O2- Evt Combined %6.0f, Electron %6.0f, Muon %6.0f\n", nSigM[OBS_O2][CH_Combined], nSigM[OBS_O2][CH_Electron], nSigM[OBS_O2][CH_Muon]); printf("O3+ Evt Combined %6.0f, Electron %6.0f, Muon %6.0f\n", nSigP[OBS_O3][CH_Combined], nSigP[OBS_O3][CH_Electron], nSigP[OBS_O3][CH_Muon]); printf("O3- Evt Combined %6.0f, Electron %6.0f, Muon %6.0f\n", nSigM[OBS_O3][CH_Combined], nSigM[OBS_O3][CH_Electron], nSigM[OBS_O3][CH_Muon]); printf("O4+ Evt Combined %6.0f, Electron %6.0f, Muon %6.0f\n", nSigP[OBS_O4][CH_Combined], nSigP[OBS_O4][CH_Electron], nSigP[OBS_O4][CH_Muon]); printf("O4- Evt Combined %6.0f, Electron %6.0f, Muon %6.0f\n", nSigM[OBS_O4][CH_Combined], nSigM[OBS_O4][CH_Electron], nSigM[OBS_O4][CH_Muon]); printf("O7+ Evt Combined %6.0f, Electron %6.0f, Muon %6.0f\n", nSigP[OBS_O7][CH_Combined], nSigP[OBS_O7][CH_Electron], nSigP[OBS_O7][CH_Muon]); printf("O7- Evt Combined %6.0f, Electron %6.0f, Muon %6.0f\n", nSigM[OBS_O7][CH_Combined], nSigM[OBS_O7][CH_Electron], nSigM[OBS_O7][CH_Muon]); printf("-------------------------------------------------------------\n"); printf("O2+ Bkg Combined %6.0f, Electron %6.0f, Muon %6.0f\n", nBkgP[OBS_O2][CH_Combined], nBkgP[OBS_O2][CH_Electron], nBkgP[OBS_O2][CH_Muon]); printf("O2+ Unc Combined %6.0f, Electron %6.0f, Muon %6.0f\n", eBkgP[OBS_O2][CH_Combined], eBkgP[OBS_O2][CH_Electron], eBkgP[OBS_O2][CH_Muon]); printf("O2- Bkg Combined %6.0f, Electron %6.0f, Muon %6.0f\n", nBkgM[OBS_O2][CH_Combined], nBkgM[OBS_O2][CH_Electron], nBkgM[OBS_O2][CH_Muon]); printf("O2- Unc Combined %6.0f, Electron %6.0f, Muon %6.0f\n", eBkgM[OBS_O2][CH_Combined], eBkgM[OBS_O2][CH_Electron], eBkgM[OBS_O2][CH_Muon]); printf("O3+ Bkg Combined %6.0f, Electron %6.0f, Muon %6.0f\n", nBkgP[OBS_O3][CH_Combined], nBkgP[OBS_O3][CH_Electron], nBkgP[OBS_O3][CH_Muon]); printf("O3+ Unc Combined %6.0f, Electron %6.0f, Muon %6.0f\n", eBkgP[OBS_O3][CH_Combined], eBkgP[OBS_O3][CH_Electron], eBkgP[OBS_O3][CH_Muon]); printf("O3- Bkg Combined %6.0f, Electron %6.0f, Muon %6.0f\n", nBkgM[OBS_O3][CH_Combined], nBkgM[OBS_O3][CH_Electron], nBkgM[OBS_O3][CH_Muon]); printf("O3- Unc Combined %6.0f, Electron %6.0f, Muon %6.0f\n", eBkgM[OBS_O3][CH_Combined], eBkgM[OBS_O3][CH_Electron], eBkgM[OBS_O3][CH_Muon]); printf("O4+ Bkg Combined %6.0f, Electron %6.0f, Muon %6.0f\n", nBkgP[OBS_O4][CH_Combined], nBkgP[OBS_O4][CH_Electron], nBkgP[OBS_O4][CH_Muon]); printf("O4+ Unc Combined %6.0f, Electron %6.0f, Muon %6.0f\n", eBkgP[OBS_O4][CH_Combined], eBkgP[OBS_O4][CH_Electron], eBkgP[OBS_O4][CH_Muon]); printf("O4- Bkg Combined %6.0f, Electron %6.0f, Muon %6.0f\n", nBkgM[OBS_O4][CH_Combined], nBkgM[OBS_O4][CH_Electron], nBkgM[OBS_O4][CH_Muon]); printf("O4- Unc Combined %6.0f, Electron %6.0f, Muon %6.0f\n", eBkgM[OBS_O4][CH_Combined], eBkgM[OBS_O4][CH_Electron], eBkgM[OBS_O4][CH_Muon]); printf("O7+ Bkg Combined %6.0f, Electron %6.0f, Muon %6.0f\n", nBkgP[OBS_O7][CH_Combined], nBkgP[OBS_O7][CH_Electron], nBkgP[OBS_O7][CH_Muon]); printf("O7+ Unc Combined %6.0f, Electron %6.0f, Muon %6.0f\n", eBkgP[OBS_O7][CH_Combined], eBkgP[OBS_O7][CH_Electron], eBkgP[OBS_O7][CH_Muon]); printf("O7- Bkg Combined %6.0f, Electron %6.0f, Muon %6.0f\n", nBkgM[OBS_O7][CH_Combined], nBkgM[OBS_O7][CH_Electron], nBkgM[OBS_O7][CH_Muon]); printf("O7- Unc Combined %6.0f, Electron %6.0f, Muon %6.0f\n", eBkgM[OBS_O7][CH_Combined], eBkgM[OBS_O7][CH_Electron], eBkgM[OBS_O7][CH_Muon]); printf("-------------------------------------------------------------\n"); printf("O2+ All Combined %6.0f, Electron %6.0f, Muon %6.0f\n", MC_nEventsPredictedObsP[OBS_O2][CH_Combined], MC_nEventsPredictedObsP[OBS_O2][CH_Electron], MC_nEventsPredictedObsP[OBS_O2][CH_Muon]); printf("O2+ Unc Combined %6.0f, Electron %6.0f, Muon %6.0f\n", MC_eEventsPredictedObsP[OBS_O2][CH_Combined], MC_eEventsPredictedObsP[OBS_O2][CH_Electron], MC_eEventsPredictedObsP[OBS_O2][CH_Muon]); printf("O2- All Combined %6.0f, Electron %6.0f, Muon %6.0f\n", MC_nEventsPredictedObsM[OBS_O2][CH_Combined], MC_nEventsPredictedObsM[OBS_O2][CH_Electron], MC_nEventsPredictedObsM[OBS_O2][CH_Muon]); printf("O2- Unc Combined %6.0f, Electron %6.0f, Muon %6.0f\n", MC_eEventsPredictedObsM[OBS_O2][CH_Combined], MC_eEventsPredictedObsM[OBS_O2][CH_Electron], MC_eEventsPredictedObsM[OBS_O2][CH_Muon]); printf("O3+ All Combined %6.0f, Electron %6.0f, Muon %6.0f\n", MC_nEventsPredictedObsP[OBS_O3][CH_Combined], MC_nEventsPredictedObsP[OBS_O3][CH_Electron], MC_nEventsPredictedObsP[OBS_O3][CH_Muon]); printf("O3+ Unc Combined %6.0f, Electron %6.0f, Muon %6.0f\n", MC_eEventsPredictedObsP[OBS_O3][CH_Combined], MC_eEventsPredictedObsP[OBS_O3][CH_Electron], MC_eEventsPredictedObsP[OBS_O3][CH_Muon]); printf("O3- All Combined %6.0f, Electron %6.0f, Muon %6.0f\n", MC_nEventsPredictedObsM[OBS_O3][CH_Combined], MC_nEventsPredictedObsM[OBS_O3][CH_Electron], MC_nEventsPredictedObsM[OBS_O3][CH_Muon]); printf("O3- Unc Combined %6.0f, Electron %6.0f, Muon %6.0f\n", MC_eEventsPredictedObsM[OBS_O3][CH_Combined], MC_eEventsPredictedObsM[OBS_O3][CH_Electron], MC_eEventsPredictedObsM[OBS_O3][CH_Muon]); printf("O4+ All Combined %6.0f, Electron %6.0f, Muon %6.0f\n", MC_nEventsPredictedObsP[OBS_O4][CH_Combined], MC_nEventsPredictedObsP[OBS_O4][CH_Electron], MC_nEventsPredictedObsP[OBS_O4][CH_Muon]); printf("O4+ Unc Combined %6.0f, Electron %6.0f, Muon %6.0f\n", MC_eEventsPredictedObsP[OBS_O4][CH_Combined], MC_eEventsPredictedObsP[OBS_O4][CH_Electron], MC_eEventsPredictedObsP[OBS_O4][CH_Muon]); printf("O4- All Combined %6.0f, Electron %6.0f, Muon %6.0f\n", MC_nEventsPredictedObsM[OBS_O4][CH_Combined], MC_nEventsPredictedObsM[OBS_O4][CH_Electron], MC_nEventsPredictedObsM[OBS_O4][CH_Muon]); printf("O4- Unc Combined %6.0f, Electron %6.0f, Muon %6.0f\n", MC_eEventsPredictedObsM[OBS_O4][CH_Combined], MC_eEventsPredictedObsM[OBS_O4][CH_Electron], MC_eEventsPredictedObsM[OBS_O4][CH_Muon]); printf("O7+ All Combined %6.0f, Electron %6.0f, Muon %6.0f\n", MC_nEventsPredictedObsP[OBS_O7][CH_Combined], MC_nEventsPredictedObsP[OBS_O7][CH_Electron], MC_nEventsPredictedObsP[OBS_O7][CH_Muon]); printf("O7+ Unc Combined %6.0f, Electron %6.0f, Muon %6.0f\n", MC_eEventsPredictedObsP[OBS_O7][CH_Combined], MC_eEventsPredictedObsP[OBS_O7][CH_Electron], MC_eEventsPredictedObsP[OBS_O7][CH_Muon]); printf("O7- All Combined %6.0f, Electron %6.0f, Muon %6.0f\n", MC_nEventsPredictedObsM[OBS_O7][CH_Combined], MC_nEventsPredictedObsM[OBS_O7][CH_Electron], MC_nEventsPredictedObsM[OBS_O7][CH_Muon]); printf("O7- Unc Combined %6.0f, Electron %6.0f, Muon %6.0f\n", MC_eEventsPredictedObsM[OBS_O7][CH_Combined], MC_eEventsPredictedObsM[OBS_O7][CH_Electron], MC_eEventsPredictedObsM[OBS_O7][CH_Muon]); printf("-------------------------------------------------------------\n"); printf("O2 Mean Combined %6.2f, Electron %6.2f, Muon %6.2f\n", MC_acpMean[OBS_O2][CH_Combined]*100, MC_acpMean[OBS_O2][CH_Electron]*100, MC_acpMean[OBS_O2][CH_Muon]*100); printf("O2 Uncs Combined %6.2f, Electron %6.2f, Muon %6.2f\n", MC_acpUncs[OBS_O2][CH_Combined]*100, MC_acpUncs[OBS_O2][CH_Electron]*100, MC_acpUncs[OBS_O2][CH_Muon]*100); printf("O3 Mean Combined %6.2f, Electron %6.2f, Muon %6.2f\n", MC_acpMean[OBS_O3][CH_Combined]*100, MC_acpMean[OBS_O3][CH_Electron]*100, MC_acpMean[OBS_O3][CH_Muon]*100); printf("O3 Uncs Combined %6.2f, Electron %6.2f, Muon %6.2f\n", MC_acpUncs[OBS_O3][CH_Combined]*100, MC_acpUncs[OBS_O3][CH_Electron]*100, MC_acpUncs[OBS_O3][CH_Muon]*100); printf("O4 Mean Combined %6.2f, Electron %6.2f, Muon %6.2f\n", MC_acpMean[OBS_O4][CH_Combined]*100, MC_acpMean[OBS_O4][CH_Electron]*100, MC_acpMean[OBS_O4][CH_Muon]*100); printf("O4 Uncs Combined %6.2f, Electron %6.2f, Muon %6.2f\n", MC_acpUncs[OBS_O4][CH_Combined]*100, MC_acpUncs[OBS_O4][CH_Electron]*100, MC_acpUncs[OBS_O4][CH_Muon]*100); printf("O7 Mean Combined %6.2f, Electron %6.2f, Muon %6.2f\n", MC_acpMean[OBS_O7][CH_Combined]*100, MC_acpMean[OBS_O7][CH_Electron]*100, MC_acpMean[OBS_O7][CH_Muon]*100); printf("O7 Uncs Combined %6.2f, Electron %6.2f, Muon %6.2f\n", MC_acpUncs[OBS_O7][CH_Combined]*100, MC_acpUncs[OBS_O7][CH_Electron]*100, MC_acpUncs[OBS_O7][CH_Muon]*100); printf("\n"); tout->Fill(); }//Entry End fout->Write(); fout->Close(); cout<<">> Wrote to file: "<<fout_s.c_str()<<endl; }
void combineAll(const char * rdatfile="rdat_i.root", const char * sumfile="sums.root") { // open trees TFile * rdatfile_tf = new TFile(rdatfile,"READ"); TTree * rdat = (TTree*) rdatfile_tf->Get("rtr"); TFile * sumfile_tf = new TFile(sumfile,"READ"); TTree * sums = (TTree*) sumfile_tf->Get("sum"); // check if trees have same size if(rdat->GetEntries() != sums->GetEntries()) { fprintf(stderr,"ERROR: tree sizes unequal\n"); return; }; Int_t i_rdat,runnum_rdat,fill_rdat; Double_t t_rdat; Float_t RRe[3][10]; // [tbit (bbc,zdc,vpd)] [rellum] Float_t RRw[3][10]; Float_t RRx[3][10]; Float_t RRrsc[3][10]; Float_t RR[3][10]; // mean R Float_t RR_err[3][10]; // error of mean R Float_t RR_rscerr[3][10]; // error of rsc R Float_t R_LL[3]; // systematic uncertainty Float_t scarat[3][4]; // zdc/vpd Int_t i_sums,runnum_sums,fill_sums,fi_sums; // (fi not in rdat tree) Double_t t_sums,tau; Int_t num_runs; Double_t bbce,bbcw,bbcx; Double_t zdce,zdcw,zdcx; Double_t vpde,vpdw,vpdx; Double_t tot_bx; Int_t pattern; Float_t d_vz[3]; // [cbit] Float_t d_xx[3][3]; // [xbit] [tbit] Bool_t isConsistent; // true for a run if diagnostics are "consistent" rdat->SetBranchAddress("i",&i_rdat); rdat->SetBranchAddress("runnum",&runnum_rdat); rdat->SetBranchAddress("fill",&fill_rdat); rdat->SetBranchAddress("t",&t_rdat); rdat->SetBranchAddress("R1_bbce",&(RRe[0][1])); rdat->SetBranchAddress("R2_bbce",&(RRe[0][2])); rdat->SetBranchAddress("R3_bbce",&(RRe[0][3])); rdat->SetBranchAddress("R4_bbce",&(RRe[0][4])); rdat->SetBranchAddress("R5_bbce",&(RRe[0][5])); rdat->SetBranchAddress("R6_bbce",&(RRe[0][6])); rdat->SetBranchAddress("R7_bbce",&(RRe[0][7])); rdat->SetBranchAddress("R8_bbce",&(RRe[0][8])); rdat->SetBranchAddress("R9_bbce",&(RRe[0][9])); rdat->SetBranchAddress("R1_zdce",&(RRe[1][1])); rdat->SetBranchAddress("R2_zdce",&(RRe[1][2])); rdat->SetBranchAddress("R3_zdce",&(RRe[1][3])); rdat->SetBranchAddress("R4_zdce",&(RRe[1][4])); rdat->SetBranchAddress("R5_zdce",&(RRe[1][5])); rdat->SetBranchAddress("R6_zdce",&(RRe[1][6])); rdat->SetBranchAddress("R7_zdce",&(RRe[1][7])); rdat->SetBranchAddress("R8_zdce",&(RRe[1][8])); rdat->SetBranchAddress("R9_zdce",&(RRe[1][9])); rdat->SetBranchAddress("R1_vpde",&(RRe[2][1])); rdat->SetBranchAddress("R2_vpde",&(RRe[2][2])); rdat->SetBranchAddress("R3_vpde",&(RRe[2][3])); rdat->SetBranchAddress("R4_vpde",&(RRe[2][4])); rdat->SetBranchAddress("R5_vpde",&(RRe[2][5])); rdat->SetBranchAddress("R6_vpde",&(RRe[2][6])); rdat->SetBranchAddress("R7_vpde",&(RRe[2][7])); rdat->SetBranchAddress("R8_vpde",&(RRe[2][8])); rdat->SetBranchAddress("R9_vpde",&(RRe[2][9])); rdat->SetBranchAddress("R1_bbcw",&(RRw[0][1])); rdat->SetBranchAddress("R2_bbcw",&(RRw[0][2])); rdat->SetBranchAddress("R3_bbcw",&(RRw[0][3])); rdat->SetBranchAddress("R4_bbcw",&(RRw[0][4])); rdat->SetBranchAddress("R5_bbcw",&(RRw[0][5])); rdat->SetBranchAddress("R6_bbcw",&(RRw[0][6])); rdat->SetBranchAddress("R7_bbcw",&(RRw[0][7])); rdat->SetBranchAddress("R8_bbcw",&(RRw[0][8])); rdat->SetBranchAddress("R9_bbcw",&(RRw[0][9])); rdat->SetBranchAddress("R1_zdcw",&(RRw[1][1])); rdat->SetBranchAddress("R2_zdcw",&(RRw[1][2])); rdat->SetBranchAddress("R3_zdcw",&(RRw[1][3])); rdat->SetBranchAddress("R4_zdcw",&(RRw[1][4])); rdat->SetBranchAddress("R5_zdcw",&(RRw[1][5])); rdat->SetBranchAddress("R6_zdcw",&(RRw[1][6])); rdat->SetBranchAddress("R7_zdcw",&(RRw[1][7])); rdat->SetBranchAddress("R8_zdcw",&(RRw[1][8])); rdat->SetBranchAddress("R9_zdcw",&(RRw[1][9])); rdat->SetBranchAddress("R1_vpdw",&(RRw[2][1])); rdat->SetBranchAddress("R2_vpdw",&(RRw[2][2])); rdat->SetBranchAddress("R3_vpdw",&(RRw[2][3])); rdat->SetBranchAddress("R4_vpdw",&(RRw[2][4])); rdat->SetBranchAddress("R5_vpdw",&(RRw[2][5])); rdat->SetBranchAddress("R6_vpdw",&(RRw[2][6])); rdat->SetBranchAddress("R7_vpdw",&(RRw[2][7])); rdat->SetBranchAddress("R8_vpdw",&(RRw[2][8])); rdat->SetBranchAddress("R9_vpdw",&(RRw[2][9])); rdat->SetBranchAddress("R1_bbcx",&(RRx[0][1])); rdat->SetBranchAddress("R2_bbcx",&(RRx[0][2])); rdat->SetBranchAddress("R3_bbcx",&(RRx[0][3])); rdat->SetBranchAddress("R4_bbcx",&(RRx[0][4])); rdat->SetBranchAddress("R5_bbcx",&(RRx[0][5])); rdat->SetBranchAddress("R6_bbcx",&(RRx[0][6])); rdat->SetBranchAddress("R7_bbcx",&(RRx[0][7])); rdat->SetBranchAddress("R8_bbcx",&(RRx[0][8])); rdat->SetBranchAddress("R9_bbcx",&(RRx[0][9])); rdat->SetBranchAddress("R1_zdcx",&(RRx[1][1])); rdat->SetBranchAddress("R2_zdcx",&(RRx[1][2])); rdat->SetBranchAddress("R3_zdcx",&(RRx[1][3])); rdat->SetBranchAddress("R4_zdcx",&(RRx[1][4])); rdat->SetBranchAddress("R5_zdcx",&(RRx[1][5])); rdat->SetBranchAddress("R6_zdcx",&(RRx[1][6])); rdat->SetBranchAddress("R7_zdcx",&(RRx[1][7])); rdat->SetBranchAddress("R8_zdcx",&(RRx[1][8])); rdat->SetBranchAddress("R9_zdcx",&(RRx[1][9])); rdat->SetBranchAddress("R1_vpdx",&(RRx[2][1])); rdat->SetBranchAddress("R2_vpdx",&(RRx[2][2])); rdat->SetBranchAddress("R3_vpdx",&(RRx[2][3])); rdat->SetBranchAddress("R4_vpdx",&(RRx[2][4])); rdat->SetBranchAddress("R5_vpdx",&(RRx[2][5])); rdat->SetBranchAddress("R6_vpdx",&(RRx[2][6])); rdat->SetBranchAddress("R7_vpdx",&(RRx[2][7])); rdat->SetBranchAddress("R8_vpdx",&(RRx[2][8])); rdat->SetBranchAddress("R9_vpdx",&(RRx[2][9])); rdat->SetBranchAddress("R1_bbcrsc",&(RRrsc[0][1])); rdat->SetBranchAddress("R2_bbcrsc",&(RRrsc[0][2])); rdat->SetBranchAddress("R3_bbcrsc",&(RRrsc[0][3])); rdat->SetBranchAddress("R4_bbcrsc",&(RRrsc[0][4])); rdat->SetBranchAddress("R5_bbcrsc",&(RRrsc[0][5])); rdat->SetBranchAddress("R6_bbcrsc",&(RRrsc[0][6])); rdat->SetBranchAddress("R7_bbcrsc",&(RRrsc[0][7])); rdat->SetBranchAddress("R8_bbcrsc",&(RRrsc[0][8])); rdat->SetBranchAddress("R9_bbcrsc",&(RRrsc[0][9])); rdat->SetBranchAddress("R1_zdcrsc",&(RRrsc[1][1])); rdat->SetBranchAddress("R2_zdcrsc",&(RRrsc[1][2])); rdat->SetBranchAddress("R3_zdcrsc",&(RRrsc[1][3])); rdat->SetBranchAddress("R4_zdcrsc",&(RRrsc[1][4])); rdat->SetBranchAddress("R5_zdcrsc",&(RRrsc[1][5])); rdat->SetBranchAddress("R6_zdcrsc",&(RRrsc[1][6])); rdat->SetBranchAddress("R7_zdcrsc",&(RRrsc[1][7])); rdat->SetBranchAddress("R8_zdcrsc",&(RRrsc[1][8])); rdat->SetBranchAddress("R9_zdcrsc",&(RRrsc[1][9])); rdat->SetBranchAddress("R1_vpdrsc",&(RRrsc[2][1])); rdat->SetBranchAddress("R2_vpdrsc",&(RRrsc[2][2])); rdat->SetBranchAddress("R3_vpdrsc",&(RRrsc[2][3])); rdat->SetBranchAddress("R4_vpdrsc",&(RRrsc[2][4])); rdat->SetBranchAddress("R5_vpdrsc",&(RRrsc[2][5])); rdat->SetBranchAddress("R6_vpdrsc",&(RRrsc[2][6])); rdat->SetBranchAddress("R7_vpdrsc",&(RRrsc[2][7])); rdat->SetBranchAddress("R8_vpdrsc",&(RRrsc[2][8])); rdat->SetBranchAddress("R9_vpdrsc",&(RRrsc[2][9])); rdat->SetBranchAddress("R1_bbc_mean",&(RR[0][1])); rdat->SetBranchAddress("R2_bbc_mean",&(RR[0][2])); rdat->SetBranchAddress("R3_bbc_mean",&(RR[0][3])); rdat->SetBranchAddress("R4_bbc_mean",&(RR[0][4])); rdat->SetBranchAddress("R5_bbc_mean",&(RR[0][5])); rdat->SetBranchAddress("R6_bbc_mean",&(RR[0][6])); rdat->SetBranchAddress("R7_bbc_mean",&(RR[0][7])); rdat->SetBranchAddress("R8_bbc_mean",&(RR[0][8])); rdat->SetBranchAddress("R9_bbc_mean",&(RR[0][9])); rdat->SetBranchAddress("R1_zdc_mean",&(RR[1][1])); rdat->SetBranchAddress("R2_zdc_mean",&(RR[1][2])); rdat->SetBranchAddress("R3_zdc_mean",&(RR[1][3])); rdat->SetBranchAddress("R4_zdc_mean",&(RR[1][4])); rdat->SetBranchAddress("R5_zdc_mean",&(RR[1][5])); rdat->SetBranchAddress("R6_zdc_mean",&(RR[1][6])); rdat->SetBranchAddress("R7_zdc_mean",&(RR[1][7])); rdat->SetBranchAddress("R8_zdc_mean",&(RR[1][8])); rdat->SetBranchAddress("R9_zdc_mean",&(RR[1][9])); rdat->SetBranchAddress("R1_vpd_mean",&(RR[2][1])); rdat->SetBranchAddress("R2_vpd_mean",&(RR[2][2])); rdat->SetBranchAddress("R3_vpd_mean",&(RR[2][3])); rdat->SetBranchAddress("R4_vpd_mean",&(RR[2][4])); rdat->SetBranchAddress("R5_vpd_mean",&(RR[2][5])); rdat->SetBranchAddress("R6_vpd_mean",&(RR[2][6])); rdat->SetBranchAddress("R7_vpd_mean",&(RR[2][7])); rdat->SetBranchAddress("R8_vpd_mean",&(RR[2][8])); rdat->SetBranchAddress("R9_vpd_mean",&(RR[2][9])); rdat->SetBranchAddress("R1_bbc_mean_err",&(RR_err[0][1])); rdat->SetBranchAddress("R2_bbc_mean_err",&(RR_err[0][2])); rdat->SetBranchAddress("R3_bbc_mean_err",&(RR_err[0][3])); rdat->SetBranchAddress("R4_bbc_mean_err",&(RR_err[0][4])); rdat->SetBranchAddress("R5_bbc_mean_err",&(RR_err[0][5])); rdat->SetBranchAddress("R6_bbc_mean_err",&(RR_err[0][6])); rdat->SetBranchAddress("R7_bbc_mean_err",&(RR_err[0][7])); rdat->SetBranchAddress("R8_bbc_mean_err",&(RR_err[0][8])); rdat->SetBranchAddress("R9_bbc_mean_err",&(RR_err[0][9])); rdat->SetBranchAddress("R1_zdc_mean_err",&(RR_err[1][1])); rdat->SetBranchAddress("R2_zdc_mean_err",&(RR_err[1][2])); rdat->SetBranchAddress("R3_zdc_mean_err",&(RR_err[1][3])); rdat->SetBranchAddress("R4_zdc_mean_err",&(RR_err[1][4])); rdat->SetBranchAddress("R5_zdc_mean_err",&(RR_err[1][5])); rdat->SetBranchAddress("R6_zdc_mean_err",&(RR_err[1][6])); rdat->SetBranchAddress("R7_zdc_mean_err",&(RR_err[1][7])); rdat->SetBranchAddress("R8_zdc_mean_err",&(RR_err[1][8])); rdat->SetBranchAddress("R9_zdc_mean_err",&(RR_err[1][9])); rdat->SetBranchAddress("R1_vpd_mean_err",&(RR_err[2][1])); rdat->SetBranchAddress("R2_vpd_mean_err",&(RR_err[2][2])); rdat->SetBranchAddress("R3_vpd_mean_err",&(RR_err[2][3])); rdat->SetBranchAddress("R4_vpd_mean_err",&(RR_err[2][4])); rdat->SetBranchAddress("R5_vpd_mean_err",&(RR_err[2][5])); rdat->SetBranchAddress("R6_vpd_mean_err",&(RR_err[2][6])); rdat->SetBranchAddress("R7_vpd_mean_err",&(RR_err[2][7])); rdat->SetBranchAddress("R8_vpd_mean_err",&(RR_err[2][8])); rdat->SetBranchAddress("R9_vpd_mean_err",&(RR_err[2][9])); rdat->SetBranchAddress("R1_bbc_rsc_err",&(RR_rscerr[0][1])); rdat->SetBranchAddress("R2_bbc_rsc_err",&(RR_rscerr[0][2])); rdat->SetBranchAddress("R3_bbc_rsc_err",&(RR_rscerr[0][3])); rdat->SetBranchAddress("R4_bbc_rsc_err",&(RR_rscerr[0][4])); rdat->SetBranchAddress("R5_bbc_rsc_err",&(RR_rscerr[0][5])); rdat->SetBranchAddress("R6_bbc_rsc_err",&(RR_rscerr[0][6])); rdat->SetBranchAddress("R7_bbc_rsc_err",&(RR_rscerr[0][7])); rdat->SetBranchAddress("R8_bbc_rsc_err",&(RR_rscerr[0][8])); rdat->SetBranchAddress("R9_bbc_rsc_err",&(RR_rscerr[0][9])); rdat->SetBranchAddress("R1_zdc_rsc_err",&(RR_rscerr[1][1])); rdat->SetBranchAddress("R2_zdc_rsc_err",&(RR_rscerr[1][2])); rdat->SetBranchAddress("R3_zdc_rsc_err",&(RR_rscerr[1][3])); rdat->SetBranchAddress("R4_zdc_rsc_err",&(RR_rscerr[1][4])); rdat->SetBranchAddress("R5_zdc_rsc_err",&(RR_rscerr[1][5])); rdat->SetBranchAddress("R6_zdc_rsc_err",&(RR_rscerr[1][6])); rdat->SetBranchAddress("R7_zdc_rsc_err",&(RR_rscerr[1][7])); rdat->SetBranchAddress("R8_zdc_rsc_err",&(RR_rscerr[1][8])); rdat->SetBranchAddress("R9_zdc_rsc_err",&(RR_rscerr[1][9])); rdat->SetBranchAddress("R1_vpd_rsc_err",&(RR_rscerr[2][1])); rdat->SetBranchAddress("R2_vpd_rsc_err",&(RR_rscerr[2][2])); rdat->SetBranchAddress("R3_vpd_rsc_err",&(RR_rscerr[2][3])); rdat->SetBranchAddress("R4_vpd_rsc_err",&(RR_rscerr[2][4])); rdat->SetBranchAddress("R5_vpd_rsc_err",&(RR_rscerr[2][5])); rdat->SetBranchAddress("R6_vpd_rsc_err",&(RR_rscerr[2][6])); rdat->SetBranchAddress("R7_vpd_rsc_err",&(RR_rscerr[2][7])); rdat->SetBranchAddress("R8_vpd_rsc_err",&(RR_rscerr[2][8])); rdat->SetBranchAddress("R9_vpd_rsc_err",&(RR_rscerr[2][9])); rdat->SetBranchAddress("d_vz_e",&(d_vz[0])); rdat->SetBranchAddress("d_vz_w",&(d_vz[1])); rdat->SetBranchAddress("d_vz_x",&(d_vz[2])); rdat->SetBranchAddress("d_ew_bbc",&(d_xx[0][0])); rdat->SetBranchAddress("d_ew_zdc",&(d_xx[0][1])); rdat->SetBranchAddress("d_ew_vpd",&(d_xx[0][2])); rdat->SetBranchAddress("d_ex_bbc",&(d_xx[1][0])); rdat->SetBranchAddress("d_ex_zdc",&(d_xx[1][1])); rdat->SetBranchAddress("d_ex_vpd",&(d_xx[1][2])); rdat->SetBranchAddress("d_wx_bbc",&(d_xx[2][0])); rdat->SetBranchAddress("d_wx_zdc",&(d_xx[2][1])); rdat->SetBranchAddress("d_wx_vpd",&(d_xx[2][2])); //rdat->SetBranchAddress("R_LL_e",&(R_LL[0])); //rdat->SetBranchAddress("R_LL_w",&(R_LL[1])); //rdat->SetBranchAddress("R_LL_x",&(R_LL[2])); //rdat->SetBranchAddress("scarat",scarat); sums->SetBranchAddress("i",&i_sums); sums->SetBranchAddress("runnum",&runnum_sums); sums->SetBranchAddress("fi",&fi_sums); sums->SetBranchAddress("fill",&fill_sums); sums->SetBranchAddress("t",&t_sums); sums->SetBranchAddress("tau",&tau); sums->SetBranchAddress("num_runs",&num_runs); sums->SetBranchAddress("bbce",&bbce); sums->SetBranchAddress("bbcw",&bbcw); sums->SetBranchAddress("bbcx",&bbcx); sums->SetBranchAddress("zdce",&zdce); sums->SetBranchAddress("zdcw",&zdcw); sums->SetBranchAddress("zdcx",&zdcx); sums->SetBranchAddress("vpde",&vpde); sums->SetBranchAddress("vpdw",&vpdw); sums->SetBranchAddress("vpdx",&vpdx); sums->SetBranchAddress("tot_bx",&tot_bx); sums->SetBranchAddress("pattern",&pattern); TFile * outfile = new TFile("rtree.root","RECREATE"); TTree * rellum = new TTree("rellum","rellum"); rellum->Branch("i",&i_sums,"i/I"); // run index rellum->Branch("runnum",&runnum_sums,"runnum/I"); // run number rellum->Branch("fi",&fi_sums,"fi/I"); // fill index rellum->Branch("fill",&fill_sums,"fill/I"); // fill number rellum->Branch("t",&t_sums,"t/D"); // run time (seconds) rellum->Branch("tau",&tau,"tau/D"); // total bXings / bXing rate (nominally == run time) rellum->Branch("num_runs",&num_runs,"num_runs/I"); // total no. runs in a fill rellum->Branch("bbce",&bbce,"bbce/D"); // multiples & accidentals corrected scaler counts rellum->Branch("bbcw",&bbcw,"bbcw/D"); rellum->Branch("bbcx",&bbcx,"bbcx/D"); rellum->Branch("zdce",&zdce,"zdce/D"); rellum->Branch("zdcw",&zdcw,"zdcw/D"); rellum->Branch("zdcx",&zdcx,"zdcx/D"); rellum->Branch("vpde",&vpde,"vpde/D"); rellum->Branch("vpdw",&vpdw,"vpdw/D"); rellum->Branch("vpdx",&vpdx,"vpdx/D"); rellum->Branch("tot_bx",&tot_bx,"tot_bx/D"); // total no. bXings rellum->Branch("R1_bbce",&(RRe[0][1]),"R1_bbce/F"); // bbce relative luminosity rellum->Branch("R2_bbce",&(RRe[0][2]),"R2_bbce/F"); rellum->Branch("R3_bbce",&(RRe[0][3]),"R3_bbce/F"); rellum->Branch("R4_bbce",&(RRe[0][4]),"R4_bbce/F"); rellum->Branch("R5_bbce",&(RRe[0][5]),"R5_bbce/F"); rellum->Branch("R6_bbce",&(RRe[0][6]),"R6_bbce/F"); rellum->Branch("R7_bbce",&(RRe[0][7]),"R7_bbce/F"); rellum->Branch("R8_bbce",&(RRe[0][8]),"R8_bbce/F"); rellum->Branch("R9_bbce",&(RRe[0][9]),"R9_bbce/F"); rellum->Branch("R1_zdce",&(RRe[1][1]),"R1_zdce/F"); // zdce relative luminosity rellum->Branch("R2_zdce",&(RRe[1][2]),"R2_zdce/F"); rellum->Branch("R3_zdce",&(RRe[1][3]),"R3_zdce/F"); rellum->Branch("R4_zdce",&(RRe[1][4]),"R4_zdce/F"); rellum->Branch("R5_zdce",&(RRe[1][5]),"R5_zdce/F"); rellum->Branch("R6_zdce",&(RRe[1][6]),"R6_zdce/F"); rellum->Branch("R7_zdce",&(RRe[1][7]),"R7_zdce/F"); rellum->Branch("R8_zdce",&(RRe[1][8]),"R8_zdce/F"); rellum->Branch("R9_zdce",&(RRe[1][9]),"R9_zdce/F"); rellum->Branch("R1_vpde",&(RRe[2][1]),"R1_vpde/F"); // vpde relative luminosity rellum->Branch("R2_vpde",&(RRe[2][2]),"R2_vpde/F"); rellum->Branch("R3_vpde",&(RRe[2][3]),"R3_vpde/F"); rellum->Branch("R4_vpde",&(RRe[2][4]),"R4_vpde/F"); rellum->Branch("R5_vpde",&(RRe[2][5]),"R5_vpde/F"); rellum->Branch("R6_vpde",&(RRe[2][6]),"R6_vpde/F"); rellum->Branch("R7_vpde",&(RRe[2][7]),"R7_vpde/F"); rellum->Branch("R8_vpde",&(RRe[2][8]),"R8_vpde/F"); rellum->Branch("R9_vpde",&(RRe[2][9]),"R9_vpde/F"); rellum->Branch("R1_bbcw",&(RRw[0][1]),"R1_bbcw/F"); // bbcw relative luminosity rellum->Branch("R2_bbcw",&(RRw[0][2]),"R2_bbcw/F"); rellum->Branch("R3_bbcw",&(RRw[0][3]),"R3_bbcw/F"); rellum->Branch("R4_bbcw",&(RRw[0][4]),"R4_bbcw/F"); rellum->Branch("R5_bbcw",&(RRw[0][5]),"R5_bbcw/F"); rellum->Branch("R6_bbcw",&(RRw[0][6]),"R6_bbcw/F"); rellum->Branch("R7_bbcw",&(RRw[0][7]),"R7_bbcw/F"); rellum->Branch("R8_bbcw",&(RRw[0][8]),"R8_bbcw/F"); rellum->Branch("R9_bbcw",&(RRw[0][9]),"R9_bbcw/F"); rellum->Branch("R1_zdcw",&(RRw[1][1]),"R1_zdcw/F"); // zdcw relative luminosity rellum->Branch("R2_zdcw",&(RRw[1][2]),"R2_zdcw/F"); rellum->Branch("R3_zdcw",&(RRw[1][3]),"R3_zdcw/F"); rellum->Branch("R4_zdcw",&(RRw[1][4]),"R4_zdcw/F"); rellum->Branch("R5_zdcw",&(RRw[1][5]),"R5_zdcw/F"); rellum->Branch("R6_zdcw",&(RRw[1][6]),"R6_zdcw/F"); rellum->Branch("R7_zdcw",&(RRw[1][7]),"R7_zdcw/F"); rellum->Branch("R8_zdcw",&(RRw[1][8]),"R8_zdcw/F"); rellum->Branch("R9_zdcw",&(RRw[1][9]),"R9_zdcw/F"); rellum->Branch("R1_vpdw",&(RRw[2][1]),"R1_vpdw/F"); // vpdw relative luminosity rellum->Branch("R2_vpdw",&(RRw[2][2]),"R2_vpdw/F"); rellum->Branch("R3_vpdw",&(RRw[2][3]),"R3_vpdw/F"); rellum->Branch("R4_vpdw",&(RRw[2][4]),"R4_vpdw/F"); rellum->Branch("R5_vpdw",&(RRw[2][5]),"R5_vpdw/F"); rellum->Branch("R6_vpdw",&(RRw[2][6]),"R6_vpdw/F"); rellum->Branch("R7_vpdw",&(RRw[2][7]),"R7_vpdw/F"); rellum->Branch("R8_vpdw",&(RRw[2][8]),"R8_vpdw/F"); rellum->Branch("R9_vpdw",&(RRw[2][9]),"R9_vpdw/F"); rellum->Branch("R1_bbcx",&(RRx[0][1]),"R1_bbcx/F"); // bbcx relative luminosity rellum->Branch("R2_bbcx",&(RRx[0][2]),"R2_bbcx/F"); rellum->Branch("R3_bbcx",&(RRx[0][3]),"R3_bbcx/F"); rellum->Branch("R4_bbcx",&(RRx[0][4]),"R4_bbcx/F"); rellum->Branch("R5_bbcx",&(RRx[0][5]),"R5_bbcx/F"); rellum->Branch("R6_bbcx",&(RRx[0][6]),"R6_bbcx/F"); rellum->Branch("R7_bbcx",&(RRx[0][7]),"R7_bbcx/F"); rellum->Branch("R8_bbcx",&(RRx[0][8]),"R8_bbcx/F"); rellum->Branch("R9_bbcx",&(RRx[0][9]),"R9_bbcx/F"); rellum->Branch("R1_zdcx",&(RRx[1][1]),"R1_zdcx/F"); // zdcx relative luminosity rellum->Branch("R2_zdcx",&(RRx[1][2]),"R2_zdcx/F"); rellum->Branch("R3_zdcx",&(RRx[1][3]),"R3_zdcx/F"); rellum->Branch("R4_zdcx",&(RRx[1][4]),"R4_zdcx/F"); rellum->Branch("R5_zdcx",&(RRx[1][5]),"R5_zdcx/F"); rellum->Branch("R6_zdcx",&(RRx[1][6]),"R6_zdcx/F"); rellum->Branch("R7_zdcx",&(RRx[1][7]),"R7_zdcx/F"); rellum->Branch("R8_zdcx",&(RRx[1][8]),"R8_zdcx/F"); rellum->Branch("R9_zdcx",&(RRx[1][9]),"R9_zdcx/F"); rellum->Branch("R1_vpdx",&(RRx[2][1]),"R1_vpdx/F"); // vpdx relative luminosity rellum->Branch("R2_vpdx",&(RRx[2][2]),"R2_vpdx/F"); rellum->Branch("R3_vpdx",&(RRx[2][3]),"R3_vpdx/F"); rellum->Branch("R4_vpdx",&(RRx[2][4]),"R4_vpdx/F"); rellum->Branch("R5_vpdx",&(RRx[2][5]),"R5_vpdx/F"); rellum->Branch("R6_vpdx",&(RRx[2][6]),"R6_vpdx/F"); rellum->Branch("R7_vpdx",&(RRx[2][7]),"R7_vpdx/F"); rellum->Branch("R8_vpdx",&(RRx[2][8]),"R8_vpdx/F"); rellum->Branch("R9_vpdx",&(RRx[2][9]),"R9_vpdx/F"); rellum->Branch("R1_bbcrsc",&(RRrsc[0][1]),"R1_bbcrsc/F"); // bbcrsc relative luminosity rellum->Branch("R2_bbcrsc",&(RRrsc[0][2]),"R2_bbcrsc/F"); rellum->Branch("R3_bbcrsc",&(RRrsc[0][3]),"R3_bbcrsc/F"); rellum->Branch("R4_bbcrsc",&(RRrsc[0][4]),"R4_bbcrsc/F"); rellum->Branch("R5_bbcrsc",&(RRrsc[0][5]),"R5_bbcrsc/F"); rellum->Branch("R6_bbcrsc",&(RRrsc[0][6]),"R6_bbcrsc/F"); rellum->Branch("R7_bbcrsc",&(RRrsc[0][7]),"R7_bbcrsc/F"); rellum->Branch("R8_bbcrsc",&(RRrsc[0][8]),"R8_bbcrsc/F"); rellum->Branch("R9_bbcrsc",&(RRrsc[0][9]),"R9_bbcrsc/F"); rellum->Branch("R1_zdcrsc",&(RRrsc[1][1]),"R1_zdcrsc/F"); // zdcrsc relative luminosity rellum->Branch("R2_zdcrsc",&(RRrsc[1][2]),"R2_zdcrsc/F"); rellum->Branch("R3_zdcrsc",&(RRrsc[1][3]),"R3_zdcrsc/F"); rellum->Branch("R4_zdcrsc",&(RRrsc[1][4]),"R4_zdcrsc/F"); rellum->Branch("R5_zdcrsc",&(RRrsc[1][5]),"R5_zdcrsc/F"); rellum->Branch("R6_zdcrsc",&(RRrsc[1][6]),"R6_zdcrsc/F"); rellum->Branch("R7_zdcrsc",&(RRrsc[1][7]),"R7_zdcrsc/F"); rellum->Branch("R8_zdcrsc",&(RRrsc[1][8]),"R8_zdcrsc/F"); rellum->Branch("R9_zdcrsc",&(RRrsc[1][9]),"R9_zdcrsc/F"); rellum->Branch("R1_vpdrsc",&(RRrsc[2][1]),"R1_vpdrsc/F"); // vpdrsc relative luminosity rellum->Branch("R2_vpdrsc",&(RRrsc[2][2]),"R2_vpdrsc/F"); rellum->Branch("R3_vpdrsc",&(RRrsc[2][3]),"R3_vpdrsc/F"); rellum->Branch("R4_vpdrsc",&(RRrsc[2][4]),"R4_vpdrsc/F"); rellum->Branch("R5_vpdrsc",&(RRrsc[2][5]),"R5_vpdrsc/F"); rellum->Branch("R6_vpdrsc",&(RRrsc[2][6]),"R6_vpdrsc/F"); rellum->Branch("R7_vpdrsc",&(RRrsc[2][7]),"R7_vpdrsc/F"); rellum->Branch("R8_vpdrsc",&(RRrsc[2][8]),"R8_vpdrsc/F"); rellum->Branch("R9_vpdrsc",&(RRrsc[2][9]),"R9_vpdrsc/F"); rellum->Branch("R1_bbc_mean",&(RR[0][1]),"R1_bbc_mean/F"); // mean bbc relative luminosity rellum->Branch("R2_bbc_mean",&(RR[0][2]),"R2_bbc_mean/F"); rellum->Branch("R3_bbc_mean",&(RR[0][3]),"R3_bbc_mean/F"); rellum->Branch("R4_bbc_mean",&(RR[0][4]),"R4_bbc_mean/F"); rellum->Branch("R5_bbc_mean",&(RR[0][5]),"R5_bbc_mean/F"); rellum->Branch("R6_bbc_mean",&(RR[0][6]),"R6_bbc_mean/F"); rellum->Branch("R7_bbc_mean",&(RR[0][7]),"R7_bbc_mean/F"); rellum->Branch("R8_bbc_mean",&(RR[0][8]),"R8_bbc_mean/F"); rellum->Branch("R9_bbc_mean",&(RR[0][9]),"R9_bbc_mean/F"); rellum->Branch("R1_zdc_mean",&(RR[1][1]),"R1_zdc_mean/F"); // mean zdc relative luminosity rellum->Branch("R2_zdc_mean",&(RR[1][2]),"R2_zdc_mean/F"); rellum->Branch("R3_zdc_mean",&(RR[1][3]),"R3_zdc_mean/F"); rellum->Branch("R4_zdc_mean",&(RR[1][4]),"R4_zdc_mean/F"); rellum->Branch("R5_zdc_mean",&(RR[1][5]),"R5_zdc_mean/F"); rellum->Branch("R6_zdc_mean",&(RR[1][6]),"R6_zdc_mean/F"); rellum->Branch("R7_zdc_mean",&(RR[1][7]),"R7_zdc_mean/F"); rellum->Branch("R8_zdc_mean",&(RR[1][8]),"R8_zdc_mean/F"); rellum->Branch("R9_zdc_mean",&(RR[1][9]),"R9_zdc_mean/F"); rellum->Branch("R1_vpd_mean",&(RR[2][1]),"R1_vpd_mean/F"); // mean vpd relative luminosity rellum->Branch("R2_vpd_mean",&(RR[2][2]),"R2_vpd_mean/F"); rellum->Branch("R3_vpd_mean",&(RR[2][3]),"R3_vpd_mean/F"); rellum->Branch("R4_vpd_mean",&(RR[2][4]),"R4_vpd_mean/F"); rellum->Branch("R5_vpd_mean",&(RR[2][5]),"R5_vpd_mean/F"); rellum->Branch("R6_vpd_mean",&(RR[2][6]),"R6_vpd_mean/F"); rellum->Branch("R7_vpd_mean",&(RR[2][7]),"R7_vpd_mean/F"); rellum->Branch("R8_vpd_mean",&(RR[2][8]),"R8_vpd_mean/F"); rellum->Branch("R9_vpd_mean",&(RR[2][9]),"R9_vpd_mean/F"); rellum->Branch("R1_bbc_mean_err",&(RR_err[0][1]),"R1_bbc_mean_err/F"); // mean bbc{e,w,x} rellum err rellum->Branch("R2_bbc_mean_err",&(RR_err[0][2]),"R2_bbc_mean_err/F"); rellum->Branch("R3_bbc_mean_err",&(RR_err[0][3]),"R3_bbc_mean_err/F"); rellum->Branch("R4_bbc_mean_err",&(RR_err[0][4]),"R4_bbc_mean_err/F"); rellum->Branch("R5_bbc_mean_err",&(RR_err[0][5]),"R5_bbc_mean_err/F"); rellum->Branch("R6_bbc_mean_err",&(RR_err[0][6]),"R6_bbc_mean_err/F"); rellum->Branch("R7_bbc_mean_err",&(RR_err[0][7]),"R7_bbc_mean_err/F"); rellum->Branch("R8_bbc_mean_err",&(RR_err[0][8]),"R8_bbc_mean_err/F"); rellum->Branch("R9_bbc_mean_err",&(RR_err[0][9]),"R9_bbc_mean_err/F"); rellum->Branch("R1_zdc_mean_err",&(RR_err[1][1]),"R1_zdc_mean_err/F"); // mean zdc{e,w,x} rellum err rellum->Branch("R2_zdc_mean_err",&(RR_err[1][2]),"R2_zdc_mean_err/F"); rellum->Branch("R3_zdc_mean_err",&(RR_err[1][3]),"R3_zdc_mean_err/F"); rellum->Branch("R4_zdc_mean_err",&(RR_err[1][4]),"R4_zdc_mean_err/F"); rellum->Branch("R5_zdc_mean_err",&(RR_err[1][5]),"R5_zdc_mean_err/F"); rellum->Branch("R6_zdc_mean_err",&(RR_err[1][6]),"R6_zdc_mean_err/F"); rellum->Branch("R7_zdc_mean_err",&(RR_err[1][7]),"R7_zdc_mean_err/F"); rellum->Branch("R8_zdc_mean_err",&(RR_err[1][8]),"R8_zdc_mean_err/F"); rellum->Branch("R9_zdc_mean_err",&(RR_err[1][9]),"R9_zdc_mean_err/F"); rellum->Branch("R1_vpd_mean_err",&(RR_err[2][1]),"R1_vpd_mean_err/F"); // mean vpd{e,w,x} rellum err rellum->Branch("R2_vpd_mean_err",&(RR_err[2][2]),"R2_vpd_mean_err/F"); rellum->Branch("R3_vpd_mean_err",&(RR_err[2][3]),"R3_vpd_mean_err/F"); rellum->Branch("R4_vpd_mean_err",&(RR_err[2][4]),"R4_vpd_mean_err/F"); rellum->Branch("R5_vpd_mean_err",&(RR_err[2][5]),"R5_vpd_mean_err/F"); rellum->Branch("R6_vpd_mean_err",&(RR_err[2][6]),"R6_vpd_mean_err/F"); rellum->Branch("R7_vpd_mean_err",&(RR_err[2][7]),"R7_vpd_mean_err/F"); rellum->Branch("R8_vpd_mean_err",&(RR_err[2][8]),"R8_vpd_mean_err/F"); rellum->Branch("R9_vpd_mean_err",&(RR_err[2][9]),"R9_vpd_mean_err/F"); rellum->Branch("R1_bbc_rsc_err",&(RR_rscerr[0][1]),"R1_bbc_rsc_err/F"); // bbc_rsc rellum err rellum->Branch("R2_bbc_rsc_err",&(RR_rscerr[0][2]),"R2_bbc_rsc_err/F"); rellum->Branch("R3_bbc_rsc_err",&(RR_rscerr[0][3]),"R3_bbc_rsc_err/F"); rellum->Branch("R4_bbc_rsc_err",&(RR_rscerr[0][4]),"R4_bbc_rsc_err/F"); rellum->Branch("R5_bbc_rsc_err",&(RR_rscerr[0][5]),"R5_bbc_rsc_err/F"); rellum->Branch("R6_bbc_rsc_err",&(RR_rscerr[0][6]),"R6_bbc_rsc_err/F"); rellum->Branch("R7_bbc_rsc_err",&(RR_rscerr[0][7]),"R7_bbc_rsc_err/F"); rellum->Branch("R8_bbc_rsc_err",&(RR_rscerr[0][8]),"R8_bbc_rsc_err/F"); rellum->Branch("R9_bbc_rsc_err",&(RR_rscerr[0][9]),"R9_bbc_rsc_err/F"); rellum->Branch("R1_zdc_rsc_err",&(RR_rscerr[1][1]),"R1_zdc_rsc_err/F"); // zdc_rsc rellum err rellum->Branch("R2_zdc_rsc_err",&(RR_rscerr[1][2]),"R2_zdc_rsc_err/F"); rellum->Branch("R3_zdc_rsc_err",&(RR_rscerr[1][3]),"R3_zdc_rsc_err/F"); rellum->Branch("R4_zdc_rsc_err",&(RR_rscerr[1][4]),"R4_zdc_rsc_err/F"); rellum->Branch("R5_zdc_rsc_err",&(RR_rscerr[1][5]),"R5_zdc_rsc_err/F"); rellum->Branch("R6_zdc_rsc_err",&(RR_rscerr[1][6]),"R6_zdc_rsc_err/F"); rellum->Branch("R7_zdc_rsc_err",&(RR_rscerr[1][7]),"R7_zdc_rsc_err/F"); rellum->Branch("R8_zdc_rsc_err",&(RR_rscerr[1][8]),"R8_zdc_rsc_err/F"); rellum->Branch("R9_zdc_rsc_err",&(RR_rscerr[1][9]),"R9_zdc_rsc_err/F"); rellum->Branch("R1_vpd_rsc_err",&(RR_rscerr[2][1]),"R1_vpd_rsc_err/F"); // vpd_rsc rellum err rellum->Branch("R2_vpd_rsc_err",&(RR_rscerr[2][2]),"R2_vpd_rsc_err/F"); rellum->Branch("R3_vpd_rsc_err",&(RR_rscerr[2][3]),"R3_vpd_rsc_err/F"); rellum->Branch("R4_vpd_rsc_err",&(RR_rscerr[2][4]),"R4_vpd_rsc_err/F"); rellum->Branch("R5_vpd_rsc_err",&(RR_rscerr[2][5]),"R5_vpd_rsc_err/F"); rellum->Branch("R6_vpd_rsc_err",&(RR_rscerr[2][6]),"R6_vpd_rsc_err/F"); rellum->Branch("R7_vpd_rsc_err",&(RR_rscerr[2][7]),"R7_vpd_rsc_err/F"); rellum->Branch("R8_vpd_rsc_err",&(RR_rscerr[2][8]),"R8_vpd_rsc_err/F"); rellum->Branch("R9_vpd_rsc_err",&(RR_rscerr[2][9]),"R9_vpd_rsc_err/F"); rellum->Branch("d_vz_e",&(d_vz[0]),"d_vz_e/F"); // zdc-vpd diagnostic rellum->Branch("d_vz_w",&(d_vz[1]),"d_vz_w/F"); rellum->Branch("d_vz_x",&(d_vz[2]),"d_vz_x/F"); rellum->Branch("d_ew_bbc",&(d_xx[0][0]),"d_ew_bbc/F"); // east-west diagnostic rellum->Branch("d_ew_zdc",&(d_xx[0][1]),"d_ew_zdc/F"); rellum->Branch("d_ew_vpd",&(d_xx[0][2]),"d_ew_vpd/F"); rellum->Branch("d_ex_bbc",&(d_xx[1][0]),"d_ex_bbc/F"); // east-coin diagnostic rellum->Branch("d_ex_zdc",&(d_xx[1][1]),"d_ex_zdc/F"); rellum->Branch("d_ex_vpd",&(d_xx[1][2]),"d_ex_vpd/F"); rellum->Branch("d_wx_bbc",&(d_xx[2][0]),"d_wx_bbc/F"); // west-coin diagnostic rellum->Branch("d_wx_zdc",&(d_xx[2][1]),"d_wx_zdc/F"); rellum->Branch("d_wx_vpd",&(d_xx[2][2]),"d_wx_vpd/F"); rellum->Branch("isConsistent",&isConsistent,"isConsistent/O"); // true if diagnostics passed rellum->Branch("pattern",&pattern,"pattern/I"); // spin pattern no. (see sumTree.C) // diagnostic consistency bounds (see if statement in tree for loop below) // -- these bounds were determined by eye // -- these are so far only done using cdf acc+mul corrections; but not rate-safe corrections; // this can be modified later, but I so far see no reason that it's needed Float_t d_vz_cc[3]; Float_t d_xx_cc[3][3]; Float_t t_tau; d_vz_cc[0] = 0.002; // VPDE - ZDCE d_vz_cc[1] = 0.002; // VPDW - ZDCW d_vz_cc[2] = 0.003; // VPDX - ZDCX d_xx_cc[0][1] = 0.0015; // ZDCE - ZDCW d_xx_cc[0][2] = 0.002; // VPDE - VPDW d_xx_cc[1][1] = 0.004; // ZDCE - ZDCX d_xx_cc[1][2] = 0.015; // VPDE - VPDX d_xx_cc[2][1] = 0.004; // ZDCW - ZDCX d_xx_cc[2][2] = 0.003; // VPDW - VPDX t_tau = 1.1; printf("\ndiagnostic cuts\n"); printf("| VPDE - ZDCE | < %f\n",d_vz_cc[0]); printf("| VPDW - ZDCW | < %f\n",d_vz_cc[1]); printf("| VPDX - ZDCX | < %f\n",d_vz_cc[2]); printf("| ZDCE - ZDCW | < %f\n",d_xx_cc[0][1]); printf("| VPDE - VPDW | < %f\n",d_xx_cc[0][2]); printf("| ZDCE - ZDCX | < %f\n",d_xx_cc[1][1]); printf("| VPDE - VPDX | < %f\n",d_xx_cc[1][2]); printf("| ZDCW - ZDCX | < %f\n",d_xx_cc[2][1]); printf("| VPDW - VPDX | < %f\n",d_xx_cc[2][2]); printf("t / tau < %f\n",t_tau); // fill tree Int_t ent = rdat->GetEntries(); for(Int_t e=0; e<ent; e++) { rdat->GetEntry(e); sums->GetEntry(e); // diagnostic pass check if( fabs(d_vz[0]) < d_vz_cc[0] && fabs(d_vz[1]) < d_vz_cc[1] && fabs(d_vz[2]) < d_vz_cc[2] && fabs(d_xx[0][1]) < d_xx_cc[0][1] && fabs(d_xx[0][2]) < d_xx_cc[0][2] && fabs(d_xx[1][1]) < d_xx_cc[1][1] && fabs(d_xx[1][2]) < d_xx_cc[1][2] && fabs(d_xx[2][1]) < d_xx_cc[2][1] && fabs(d_xx[2][2]) < d_xx_cc[2][2] && t_sums/tau < t_tau ) { isConsistent=1; } else isConsistent=0; /////////////////////////////////////////////////////////////////// //if(pattern!=13) isConsistent=0; //if(pattern!=14) isConsistent=0; //if(pattern!=23) isConsistent=0; //if(pattern!=24) isConsistent=0; //if(pattern!=31) isConsistent=0; //if(pattern!=32) isConsistent=0; //if(pattern!=41) isConsistent=0; //if(pattern!=42) isConsistent=0; //if(pattern!=13 && pattern!=24 && pattern!=31 && pattern!=42) isConsistent=0; // A //if(pattern!=14 && pattern!=23 && pattern!=32 && pattern!=41) isConsistent=0; // B /////////////////////////////////////////////////////////////////// // rdat and sum tree consistency check if( (i_rdat != i_sums) || (runnum_rdat != runnum_sums) || (fill_rdat != fill_sums) || (t_rdat != t_sums)) { fprintf(stderr,"ERROR: trees not consistent (either i,runnum,fill,t"); return; } else rellum->Fill(); }; rellum->Write(); printf("\nrellum tree written to rtree.root\n"); printf("%d / %d rellum tree entries pass consistency check\n", rellum->GetEntries("isConsistent"), rellum->GetEntries()); };
TFile *cernbuild(Int_t getFile=0, Int_t print=1) { Int_t Category; UInt_t Flag; Int_t Age; Int_t Service; Int_t Children; Int_t Grade; Int_t Step; Int_t Hrweek; Int_t Cost; Char_t Division[4]; Char_t Nation[3]; //The input file cern.dat is a copy of the CERN staff data base //from 1988 TString filename = "cernstaff.root"; TString dir = gROOT->GetTutorialDir(); dir.Append("/tree/"); dir.ReplaceAll("/./","/"); FILE *fp = fopen(Form("%scernstaff.dat",dir.Data()),"r"); TFile *hfile = 0; if (getFile) { // if the argument getFile =1 return the file "cernstaff.root" // if the file does not exist, it is created if (!gSystem->AccessPathName(dir+"cernstaff.root",kFileExists)) { hfile = TFile::Open(dir+"cernstaff.root"); //in $ROOTSYS/tutorials/tree if (hfile) return hfile; } //otherwise try $PWD/cernstaff.root if (!gSystem->AccessPathName("cernstaff.root",kFileExists)) { hfile = TFile::Open("cernstaff.root"); //in current dir if (hfile) return hfile; } } //no cernstaff.root file found. Must generate it ! //generate cernstaff.root in $ROOTSYS/tutorials/tree if we have write access if (gSystem->AccessPathName(".",kWritePermission)) { printf("you must run the script in a directory with write access\n"); return 0; } hfile = TFile::Open(filename,"RECREATE"); TTree *tree = new TTree("T","CERN 1988 staff data"); tree->Branch("Category",&Category,"Category/I"); tree->Branch("Flag",&Flag,"Flag/i"); tree->Branch("Age",&Age,"Age/I"); tree->Branch("Service",&Service,"Service/I"); tree->Branch("Children",&Children,"Children/I"); tree->Branch("Grade",&Grade,"Grade/I"); tree->Branch("Step",&Step,"Step/I"); tree->Branch("Hrweek",&Hrweek,"Hrweek/I"); tree->Branch("Cost",&Cost,"Cost/I"); tree->Branch("Division",Division,"Division/C"); tree->Branch("Nation",Nation,"Nation/C"); char line[80]; while (fgets(line,80,fp)) { sscanf(&line[0],"%d %d %d %d %d %d %d %d %d %s %s", &Category,&Flag,&Age,&Service,&Children,&Grade,&Step,&Hrweek,&Cost,Division,Nation); tree->Fill(); } if (print) tree->Print(); tree->Write(); fclose(fp); delete hfile; if (getFile) { //we come here when the script is executed outside $ROOTSYS/tutorials/tree hfile = TFile::Open(filename); return hfile; } return 0; }
TTree* ParseForHeaderData(ifstream *myFile, FASTFRAME_HEADER *UserHeaderData, string cUserColSep, Bool_t bIsGermanDecimal){ if(myFile->tellg()>0){ myFile->clear(); // clear eof-bit myFile->seekg(0, ios::beg); // reset stream to beginning } // create TTree for storing results static FASTFRAME_HEADER myHeaderData = {-1,-1.0,-1,0.0,0.0,-1}; TTree *tUserHeaderData = new TTree(HEADER_TREE_NAME,"Tektronix Fast Frame Header Data"); // split header data into separate branches! tUserHeaderData->Branch(HEADER_BRANCH_NAME_RECORD_LENGTH,&myHeaderData.nRecordLength,"nRecordLength/I"); tUserHeaderData->Branch(HEADER_BRANCH_NAME_SAMPLE_INTERVAL,&myHeaderData.fSampleInterval,"fSampleInterval/D"); tUserHeaderData->Branch(HEADER_BRANCH_NAME_TRIGGER_POINT,&myHeaderData.nTriggerPoint,"nTriggerPoint/I"); tUserHeaderData->Branch(HEADER_BRANCH_NAME_TRIGGER_TIME,&myHeaderData.fTriggerTime,"fTriggerTime/D"); tUserHeaderData->Branch(HEADER_BRANCH_NAME_HOR_OFFSET,&myHeaderData.fHorizontalOffset,"fHorizontalOffset/D"); tUserHeaderData->Branch(HEADER_BRANCH_NAME_FRAME_COUNT,&myHeaderData.nFastFrameCount,"nFastFrameCount/I"); // header format information (fixed) const int nHeaderLines = N_HEADER_LINES; string HeaderKeywords[nHeaderLines]; // replace this by a STL map HeaderKeywords[0] = "Record Length"; HeaderKeywords[1] = "Sample Interval"; HeaderKeywords[2] = "Trigger Point"; HeaderKeywords[3] = "Trigger Time"; HeaderKeywords[4] = "Horizontal Offset"; HeaderKeywords[5] = "FastFrame Count"; // start parsing file if(myFile == NULL){ cerr << "Data file pointer is invalid!" << endl; exit(1); } // use stl:bitset here!! bitset<6> bpDecodedHeaderWords; std::vector<string> cHeaderTokens; Int_t nDecodedHeaderWords = 0; Int_t nLinesFound = 0; while(myFile->good() && bpDecodedHeaderWords.count()!= N_HEADER_LINES){ // loop over data file until all header lines are decoded or end of file is reached nLinesFound++; // increment number of lines in file //cout << nLinesFound << endl; string CurrentHeaderLine; size_t CurrentHeaderInfoPos[2]; getline(*myFile,CurrentHeaderLine,'\n'); if(CurrentHeaderLine[0] == '\"') // all header lines begin with ", so only attempt to parse if this is true cHeaderTokens = LineParser(CurrentHeaderLine,*cUserColSep.c_str()); if(cHeaderTokens.size()>0){ for(Int_t i=0; i<N_HEADER_LINES; i++){ // begin loop over header keywords if(cHeaderTokens[0].find(HeaderKeywords[i])!= string::npos){ //cout << cHeaderTokens[0] << " " << HeaderKeywords[i] << " : " << cHeaderTokens[1] << endl; switch (i) { // all header data decoded corresponds to 0x3F case 0: myHeaderData.nRecordLength = atoi(cHeaderTokens[1].c_str()); bpDecodedHeaderWords.set(0); break; case 1: if(bIsGermanDecimal){ cHeaderTokens.at(1) += "." + cHeaderTokens.at(2); //cout << cHeaderTokens.at(1) << endl; } myHeaderData.fSampleInterval = atof(cHeaderTokens[1].c_str()); bpDecodedHeaderWords.set(1); break; case 2: myHeaderData.nTriggerPoint = atoi(cHeaderTokens[1].c_str()); bpDecodedHeaderWords.set(2); break; case 3: if(bIsGermanDecimal){ cHeaderTokens.at(1) += "." + cHeaderTokens.at(2); //cout << cHeaderTokens.at(1) << endl; } myHeaderData.fTriggerTime = atof(cHeaderTokens[1].c_str()); bpDecodedHeaderWords.set(3); break; case 4: if(bIsGermanDecimal){ cHeaderTokens.at(1) += "." + cHeaderTokens.at(2); //cout << cHeaderTokens.at(1) << endl; } myHeaderData.fHorizontalOffset = atof(cHeaderTokens[1].c_str()); bpDecodedHeaderWords.set(4); break; case 5: myHeaderData.nFastFrameCount = atoi(cHeaderTokens[1].c_str()); bpDecodedHeaderWords.set(5); break; } break; } //clog << nDecodedHeaderWords << ", " << CurrentHeaderLine << endl; } // end of loop over header key words } cHeaderTokens.clear(); } // end of loop over data file //cout << bpDecodedHeaderWords.to_string<char,char_traits<char>,allocator<char> >() << endl; if(myFile->eof() || bpDecodedHeaderWords.count() != N_HEADER_LINES){ // not all header data available if(!bpDecodedHeaderWords.test(0)){ // record length was not decoded cout << "Header decoding incomplete!" << endl; delete tUserHeaderData; delete UserHeaderData; return (NULL); } if(!bpDecodedHeaderWords.test(5)){ // number of frames not in header information, so reconstruct it myHeaderData.nFastFrameCount = (nLinesFound-1)/myHeaderData.nRecordLength; // change this check to see if there is a reminder after the division! if(myHeaderData.nFastFrameCount*myHeaderData.nRecordLength != (nLinesFound-1)){ cout << "Error reconstructing number of frames in file!" << endl; delete tUserHeaderData; delete UserHeaderData; return (NULL); } } } myFile->clear(); // clear eof-bit myFile->seekg(0, ios::beg); // reset stream to beginning tUserHeaderData->Fill(); if(UserHeaderData!=NULL){ // copy header data UserHeaderData->nRecordLength = myHeaderData.nRecordLength; UserHeaderData->fSampleInterval = myHeaderData.fSampleInterval; UserHeaderData->nTriggerPoint = myHeaderData.nTriggerPoint; UserHeaderData->fTriggerTime = myHeaderData.fTriggerTime; UserHeaderData->fHorizontalOffset = myHeaderData.fHorizontalOffset; UserHeaderData->nFastFrameCount = myHeaderData.nFastFrameCount; } return (tUserHeaderData); }
//__________________________________________________________ int main(int argc, char **argv) { if (argc != 4) { std::cout << "Invalid arguments..." << endl; return 1; } double timeCutLow = atof(argv[1]); double timeCutHigh = atof(argv[2]); //Create the add back table CreateAddBackTable(atof(argv[3])); TFile *rootfile = new TFile(Form("%s_p3p_%d_%d_%d.root",outname,(int)timeCutLow,(int)timeCutHigh,(int)atof(argv[3])), "RECREATE"); // Create interactive interface //TRint *theApp = new TRint("ROOT example", &argc, argv, NULL, 0); double PI = TMath::Pi(); // Parameters for the MINOS ANALYSIS && Reading of ConfigFileSetup.txt for beta values double Test; double DALIOffset; double TargetLength; // in mm int BeamA, BeamZ; string ConfigBeam; double BeamEnergy; double betaLISE_before, betaLISE_middle, betaLISE_after, beta_vertex; double x_vertex, y_vertex, z_vertex; double x_vertexPPAC, y_vertexPPAC, z_vertexPPAC; double x_vertexDSSSD, y_vertexDSSSD, z_vertexDSSSD; double beta1, beta2; //beta from BR/ZD data given event by event double Angle_CD[NUMBEROFDALICRYSTALS]; //--Beta Measured(b57 & b811)--// double beta1_average;// = 0.6377; //From input file double beta2_average;// = 0.5524; //These values are intended for the beta before and after the target double boffset_before = 0.0; // not used currently double boffset_after = 0.0; // double LH2Offset = 13.0; // 13 = 11 + 2 (target length = 102 mm) double z_vertexH = 0.; int reconstructminos =0; // RT ifstream ConfigFile; //ConfigFile.open("./../ConfigFileSetup.txt"); // Be careful, please change the symbolic link for each settings. ConfigFile.open("./ConfigFileSetup.txt"); string Header; ConfigFile >> ConfigBeam; ConfigFile >> Header >> Test; ConfigFile >> Header >> Test; ConfigFile >> Header >> Test; ConfigFile >> Header >> Test; ConfigFile >> Header >> Test; ConfigFile >> Header >> DALIOffset; // Offset between beginning of TPC & DALI2 zero position ConfigFile >> Header >> TargetLength; ConfigFile >> Header >> BeamA; ConfigFile >> Header >> BeamZ; ConfigFile >> Header >> BeamEnergy; ConfigFile >> Header >> betaLISE_before; ConfigFile >> Header >> betaLISE_middle; ConfigFile >> Header >> betaLISE_after; ConfigFile >> Header >> beta1_average; //RT add ConfigFile >> Header >> beta2_average; ConfigFile.close(); cout << "The beta values are: Before target=" << betaLISE_before << ", Middle of target=" << betaLISE_middle << ", End of target=" << betaLISE_after << endl; EventCut *TreeCut = new EventCut(); Long64_t nentries = TreeCut->fChainCut->GetEntriesFast(); cout << "nentries = " << nentries << endl; TTree *tree = new TTree("tree", "analyzed tree"); rootfile->cd(); //Specific variables; int daliMult; int daliTimeTrueMult; int daliFold; int daliTimeTrueFold; Double_t DopplerAngle, costheta, DopplerAnglePieter; //________________________________________________________________________ //Spectra: char name[100]; //Define spectra: int minBin = 0; int maxBin = 4000; int binning = 10; int numBin = (maxBin - minBin) / binning; double maxE = 8000.; double minE = 0.; double binE = 50.; double numbinE = (maxE - minE) / binE; TH1F *h_beta_vertex = new TH1F("h_beta_vertex", "h_beta_vertex",300, 0.5, 0.7); TH1F *h_Zvertex = new TH1F("h_Zvertex", "h_Zvertex", 200, -50, 150); TH1F *h_betaBR = new TH1F("h_betaBR", "h_betaBR", 600, 0.4, 0.7); TH1F *h_betaZD = new TH1F("h_betaZD", "h_betaZD", 600, 0.4, 0.7); TH2F* h_XminosPPAC = new TH2F("h_XminosPPAC", "h_XminosPPAC", 200, -100, 100, 200, -100, 100); TH2F* h_YminosPPAC = new TH2F("h_YminosPPAC", "h_YminosPPAC", 200, -100, 100, 200, -100, 100); TH2F* h_ZminosPPAC = new TH2F("h_ZminosPPAC", "h_ZminosPPAC", 200, -50, 150, 200, -50, 150); TH2F * h_XminosDSSSD = new TH2F("h_XminosDSSSD", "h_XminosDSSSD", 200, -100, 100, 200, -100, 100); TH2F * h_YminosDSSSD = new TH2F("h_YminosDSSSD", "h_YminosDSSSD", 200, -100, 100, 200, -100, 100); TH2F* h_ZminosDSSSD = new TH2F("h_ZminosDSSSD", "h_ZminosDSSSD", 200, -50, 150, 200, -50, 150); TH2F* h_XPPACDSSSD = new TH2F("h_XPPACDSSSD", "h_XPPACDSSSD", 200, -100, 100, 200, -100, 100); TH2F* h_YPPACDSSSD = new TH2F("h_YPPACDSSSD", "h_YPPACDSSSD", 200, -100, 100, 200, -100, 100); TH2F* h_ZPPACDSSSD = new TH2F("h_ZPPACDSSSD", "h_ZPPACDSSSD", 200, -50, 150, 200, -50, 150); TH2F *hdifftheta = new TH2F("hdifftheta", "hdifftheta", 100, 0, 3, 100, 0, 3); TH2F *hEnergyZ = new TH2F("hEnergyZ", "hEnergyZ", 100, -30, 130, numBin, minBin, maxBin); TH2F *hEnergyZnovertex = new TH2F("hEnergyZnovertex", "hEnergyZnovertex", 100, -30, 130, numBin, minBin, maxBin); TH1F *hEnergy_forward = new TH1F("hEnergy_forward", "hEnergy_forward", numBin, minBin, maxBin); TH1F *hEnergy_backward = new TH1F("hEnergy_backward", "hEnergy_backward", numBin, minBin, maxBin); TH2F *hEnergyZ_forward = new TH2F("hEnergyZ_forward", "hEnergyZ_forward", 200, -100, 100, numBin, minBin, maxBin); TH2F *hEnergyZ_backward = new TH2F("hEnergyZ_backward", "hEnergyZ_backward", 200, -100, 100, numBin, minBin, maxBin); TH1F *hEnergyZ20_forward = new TH1F("hEnergyZ20_forward", "hEnergyZ20_forward", numBin / 2., minBin, maxBin); TH1F *hEnergyZ80_forward = new TH1F("hEnergyZ80_forward", "hEnergyZ80_forward", numBin / 2., minBin, maxBin); TH1F *hEnergyZ20_backward = new TH1F("hEnergyZ20_backward", "hEnergyZ20_backward", numBin / 2., minBin, maxBin); TH1F *hEnergyZ80_backward = new TH1F("hEnergyZ80_backward", "hEnergyZ80_backward", numBin / 2., minBin, maxBin); TH2F *hEnergyBeta1 = new TH2F("hEnergyBeta1", "hEnergyBeta1", 200, 0.54, 0.66, numBin, minBin, maxBin); TH2F *hEnergyBeta2 = new TH2F("hEnergyBeta2", "hEnergyBeta2", 200, 0.54, 0.66, numBin, minBin, maxBin); TH2F *hEnergyBeta = new TH2F("hEnergyBeta", "hEnergyBeta", 400, 0.54, 0.66, numBin, minBin, maxBin); TH2F *h_ECD_angle = new TH2F("hAngle_ECD", "hAngle_ECD", 180, 0, 180, numBin, minBin, maxBin); TH2F *hEnergyID = new TH2F("hEnergyID", "hEnergyID", 188, 0, 188, numBin, minBin, maxBin); TH2F *hEnergyID_novertex = new TH2F("hEnergyID_novertex", "hEnergyID_novertex", 188, 0, 188, numBin, minBin, maxBin); TH2F *hEnergyID_lab = new TH2F("hEnergyID_lab", "hEnergyID_lab", 188, 0, 188, numBin, minBin, maxBin); //RT TH1F *h_SpectrumDALI = new TH1F("h_SpectrumDALI", "h_SpectrumDALI", numbinE, minE, maxE); TH1F *h_SpectrumMINOS = new TH1F("h_SpectrumMINOS", "h_SpectrumMINOS", numbinE, minE, maxE); TH1F *h_SpectrumDALI_wAdBk = new TH1F("h_SpectrumDALI_wAdBk", "h_SpectrumDALI_wAdBk", numbinE, minE, maxE); TH1F *h_SpectrumMINOS_wAdBk = new TH1F("h_SpectrumMINOS_wAdBk", "h_SpectrumMINOS_wAdBk", numbinE, minE, maxE); TH1F *h_SpectrumMINOS_wAdBk_1p = new TH1F("h_SpectrumMINOS_wAdBk_1p", "h_SpectrumMINOS_wAdBk_1p", numbinE, minE, maxE); TH1F *h_SpectrumMINOS_wAdBk_2p = new TH1F("h_SpectrumMINOS_wAdBk_2p", "h_SpectrumMINOS_wAdBk_2p", numbinE, minE, maxE); TH2F *h_EEcoinc_allMult = new TH2F("h_EEcoinc_allMult", "h_EEcoinc_allMult", 400, 0, 4000, 400, 0, 4000); TH2F *h_EEcoinc_MultInf4 = new TH2F("h_EEcoinc_MultInf4", "h_EEcoinc_MultInf4", 400, 0, 4000, 400, 0, 4000); TH2F *h_EEcoinc_MultSup2 = new TH2F("h_EEcoinc_MultSup2", "h_EEcoinc_MultSup2", 400, 0, 4000, 400, 0, 4000); TH1F *h_mult[8]; TH1F *h_multINF[8]; TH1F *h_multSUP[8]; for (int i = 0; i < 8; i++) { sprintf(name, "h_multEq%i", i + 1); h_mult[i] = new TH1F(name, name, numbinE, minE, maxE); sprintf(name, "h_multInf%i", i + 1); h_multINF[i] = new TH1F(name, name, numbinE, minE, maxE); sprintf(name, "h_multSup%i", i + 1); h_multSUP[i] = new TH1F(name, name, numbinE, minE, maxE); } vector<double> DALINaI_Time; vector<double> EnergyRaw; vector<double> EnergyMINOS; vector<double> EnergyDALI; vector<double> EnergyMINOS_wAdBk; vector<double> EnergyDALI_wAdBk; vector<int> IDMult_wAdBk; int Mult_wAdBk; tree->Branch("DALINaI_Time", "vector<double>", &DALINaI_Time); tree->Branch("EnergyRaw", "vector<double>", &EnergyRaw); tree->Branch("EnergyMINOS", "vector<double>", &EnergyMINOS); tree->Branch("EnergyMINOS_wAdBk", "vector<double>", &EnergyMINOS_wAdBk); tree->Branch("EnergyDALI", "vector<double>", &EnergyDALI); tree->Branch("EnergyDALI_wAdBk", "vector<double>", &EnergyDALI_wAdBk); tree->Branch("IDMult_wAdBk", "vector<int>", &IDMult_wAdBk); tree->Branch("Mult_wAdBk", &Mult_wAdBk, "Mult_wAdBk/I"); //vector<int> detCoinc1, detCoinc2, detCoinc3, detCoinc0; vector<int> detCoinc0, detCoinc1, detCoinc2, detCoinc3, detCoinc4, detCoinc5; vector<double> EnergyCoinc0, EnergyCoinc1, EnergyCoinc2, EnergyCoinc3, EnergyCoinc4, EnergyCoinc5; tree->Branch("EnergyCoinc0", "vector<double>", &EnergyCoinc0); tree->Branch("EnergyCoinc1", "vector<double>", &EnergyCoinc1); tree->Branch("EnergyCoinc2", "vector<double>", &EnergyCoinc2); tree->Branch("EnergyCoinc3", "vector<double>", &EnergyCoinc3); tree->Branch("EnergyCoinc4", "vector<double>", &EnergyCoinc4); tree->Branch("EnergyCoinc5", "vector<double>", &EnergyCoinc5); //RT int trackNbr_FINAL = TreeCut->trackNbr_FINAL; tree->Branch("trackNbr_FINAL", &trackNbr_FINAL , "trackNbr_FINAL/I");//RT double aoq[6], aoqc[6], zet[6]; tree->Branch("aoq", aoq, "aoq[6]/D"); tree->Branch("aoqc", aoqc, "aoqc[6]/D"); tree->Branch("zet", zet, "zet[6]/D"); vector<double> MINOSSpectrumAdBk; tree->Branch("MINOSSpectrumAdBk", "vector<double>", &MINOSSpectrumAdBk); //RT //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //Start looping through data; Long64_t i = 0; for (Long64_t jentry = 0; jentry < nentries; jentry++) { if (jentry % 500 == 0) cout << jentry << "/" << nentries << " Events DONE!" << endl; TreeCut->fChainCut->GetEvent(jentry); DALINaI_Time.clear(); EnergyRaw.clear(); EnergyMINOS.clear(); EnergyMINOS_wAdBk.clear(); EnergyDALI.clear(); EnergyDALI_wAdBk.clear(); IDMult_wAdBk.clear(); Mult_wAdBk = 0; detCoinc0.clear(); detCoinc1.clear(); detCoinc2.clear(); detCoinc3.clear(); detCoinc4.clear();// detCoinc5.clear();// EnergyCoinc0.clear(); EnergyCoinc1.clear(); EnergyCoinc2.clear(); EnergyCoinc3.clear(); EnergyCoinc4.clear();// EnergyCoinc5.clear();// MINOSSpectrumAdBk.clear();//RT // Calculate beta from the z_vertex found with MINOS offline software // (estimated beam track parallel to the z axis) x_vertex = TreeCut->x_vertex; y_vertex = TreeCut->y_vertex; z_vertex = TreeCut->z_vertex; //if(TreeCut->trackNbr_FINAL!=2) continue; x_vertexDSSSD = TreeCut->x_vertexDSSSD; y_vertexDSSSD = TreeCut->y_vertexDSSSD; z_vertexDSSSD = TreeCut->z_vertexDSSSD; x_vertexPPAC = TreeCut->x_vertexPPAC; y_vertexPPAC = TreeCut->y_vertexPPAC; z_vertexPPAC = TreeCut->z_vertexPPAC; /*beta1 = TreeCut->BigRIPSBeam_beta[1]-0.01; beta2 = TreeCut->BigRIPSBeam_beta[2]-0.01; */ // //beta1 = TreeCut->BigRIPSBeam_beta[3]*TreeCut->BigRIPSBeam_aoq[3]/(74./28.) - beta1_average + betaLISE_before; //beta2 = TreeCut->BigRIPSBeam_beta[3]*TreeCut->BigRIPSBeam_aoq[3]/(74./28.) - beta2_average + betaLISE_after; //From TOF information beta1 = TreeCut->BigRIPSBeam_beta[3] - beta1_average + betaLISE_before; // beta2 = TreeCut->BigRIPSBeam_beta[3] - beta2_average + betaLISE_after; //beta[3] <-> Beam 89 (ave tof ZDS) //RT for (int i=0; i<6; i++){ aoq[i] = TreeCut->aoq[i]; aoqc[i] = TreeCut->aoqc[i]; zet[i] = TreeCut->zet[i]; } //RT z_vertexH = z_vertex + LH2Offset; if (TreeCut->trackNbr_FINAL>=1){ if (z_vertexH >= 0. && z_vertexH <= TargetLength){ beta_vertex = beta1 - z_vertexH * (beta1 - beta2) / TargetLength; } else if (z_vertexH < 0. && z_vertexH >= -10.) { beta_vertex = beta1; } else if (z_vertexH > TargetLength && z_vertexH <= (TargetLength + 10.)) { beta_vertex = beta2; //if (z_vertexH < -10. || z_vertexH > (TargetLength + 10.)) //continue; // pull out wrong z vertex reconstructions } else { //if ( z_vertexH < -10. || z_vertexH > (TargetLength+10.)) { z_vertexH = z_vertexDSSSD + LH2Offset; if (z_vertexH >= 0. && z_vertexH <= TargetLength) { beta_vertex = beta1 - z_vertexH * (beta1 - beta2) / TargetLength; } else if (z_vertexH < 0. && z_vertexH >= -10.) { beta_vertex = beta1; } else if (z_vertexH > TargetLength && z_vertexH <= (TargetLength + 10.)) { beta_vertex = beta2; } else { z_vertexH = z_vertexPPAC + LH2Offset; if (z_vertexH >= 0. && z_vertexH <= TargetLength) { beta_vertex = beta1 - z_vertexH * (beta1 - beta2) / TargetLength; } else if (z_vertexH < 0. && z_vertexH >= -10.) { beta_vertex = beta1; } else if (z_vertexH > TargetLength && z_vertexH <= (TargetLength + 10.)) { beta_vertex = beta2; } else { continue; // Sep7 beta_vertex = betaLISE_middle; // pull out wrong z vertex reconstructions z_vertex = 50. - LH2Offset; x_vertex =0.; y_vertex =0.; } } }//RT JUN5 }else{ continue; //continue; //for inera channel do not continue beta_vertex = betaLISE_middle; // pull out wrong z vertex reconstructions z_vertex = 50. - LH2Offset; x_vertex =0.; y_vertex =0.; } //Fill in histograms BEFORE going to the DALI2 referential h_beta_vertex->Fill(beta_vertex); h_Zvertex->Fill(z_vertex); h_betaBR->Fill(TreeCut->BigRIPSBeam_beta[0]); //h_betaZD->Fill(TreeCut->BigRIPSBeam_beta[2]); h_betaZD->Fill(TreeCut->BigRIPSBeam_beta[3]); if (TreeCut->trackNbr_FINAL == 2) { h_XminosPPAC->Fill(x_vertex, x_vertexPPAC); h_YminosPPAC->Fill(y_vertex, y_vertexPPAC); h_ZminosPPAC->Fill(z_vertex, z_vertexPPAC); h_XminosDSSSD->Fill(x_vertex, x_vertexDSSSD); h_YminosDSSSD->Fill(y_vertex, y_vertexDSSSD); h_ZminosDSSSD->Fill(z_vertex, z_vertexDSSSD); h_XPPACDSSSD->Fill(x_vertexPPAC, x_vertexDSSSD); h_YPPACDSSSD->Fill(y_vertexPPAC, y_vertexDSSSD); h_ZPPACDSSSD->Fill(z_vertexPPAC, z_vertexDSSSD); } //if(z_vertex<-900) continue; //Convert x,y,z in the DALI2 referential (in cm) z_vertex = (z_vertex - DALIOffset - 7.) / 10.; //Offset -7 mm from beta optimization _ 20140909 x_vertex = x_vertex / 10.; y_vertex = y_vertex / 10.; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //Sorting the DALI2 data fDaliFold = 0;//Fold fDaliFoldTa = 0;//Fold fDaliMultTa = 0;//multiplicity for (int j = 0; j < NUMBEROFDALICRYSTALS; j++) { crystalUsedForAddback[j] = false; } //cout<<"DALINaI: "<<TreeCut->DALINaI_<<endl; for (int j = 0; j < TreeCut->DALINaI_; j++) { fDali[j].id = TreeCut->DALINaI_id[j] - 1; fDali[j].layer = TreeCut->DALINaI_layer[j]; fDali[j].theta = fTheta[fDali[j].id]; fDali[j].x = fPosX[fDali[j].id]; fDali[j].y = fPosY[fDali[j].id]; fDali[j].z = fPosZ[fDali[j].id]; fDali[j].e = TreeCut->DALINaI_fEnergy[j]; fDali[j].t = TreeCut->DALINaI_fTimeOffseted[j]; DALINaI_Time.push_back(fDali[j].t); EnergyRaw.push_back(fDali[j].e); //cout<<"j= "<<j<<" E="<<fDali[j].e<<" t="<<fDali[j].t <<endl; if (fDali[j].e > 0) { DopplerAngle = CalculateTheta(fDali[j].x, fDali[j].y, fDali[j].z, x_vertex, y_vertex, z_vertex); Angle_CD[fDali[j].id] = DopplerAngle * 180. / PI; DopplerAnglePieter = CalculateTheta(fDali[j].x, fDali[j].y, fDali[j].z, 0, 0, 0); //cout << " Theta : DALI=" << fDali[j].theta << ", w/MINOS=" << DopplerAngle << endl; hdifftheta->Fill(fDali[j].theta, DopplerAngle); fDali[j].dopp = DopplerCorrect(beta_vertex, DopplerAngle, fDali[j].e); fDali[j].doppPieter = DopplerCorrect(betaLISE_middle, DopplerAnglePieter, fDali[j].e); //if(fDali[j].t>timeCutLow-2000&&fDali[j].t<timeCutHigh+2000)fDaliFold++; fDaliFold++; if (fDali[j].t > timeCutLow && fDali[j].t < timeCutHigh) { fDali[j].ttrue = true; fDaliFoldTa++; } else fDali[j].ttrue = false; } else { fDali[j].dopp = -999.; fDali[j].ttrue = false; } } for (int j = TreeCut->DALINaI_; j < NUMBEROFDALICRYSTALS; j++) { fDali[j].id = -1; fDali[j].layer = -1; fDali[j].theta = -1; fDali[j].x = -999; fDali[j].y = -999; fDali[j].z = -999; fDali[j].e = -999; fDali[j].t = -999; fDali[j].ttrue = false; fDali[j].dopp = -999; } SortData(TreeCut->DALINaI_, fDali); //Sort DALI2 crystals by decreasing energies, the detectors with e=-999 will have i>fDaliFold //Going to the add-back: float dummyEnergy[NUMBEROFDALICRYSTALS] = { 0. }; float dummyEnergyPieter[NUMBEROFDALICRYSTALS] = { 0. }; //Making add-back and true multiplicity: //The Energy must be sorted already according to the highest detected one. //cout<<"Starting addback"<<endl; //for (int i = fDaliFold; i>=0; i--) { //From lower energy to higher energy for (int i = 0; i < fDaliFold; i++) { if (crystalUsedForAddback[fDali[i].id] == true || fDali[i].ttrue == false) continue; double labenergy=fDali[i].e;//RT DopplerAngle = CalculateTheta(fDali[i].x, fDali[i].y, fDali[i].z, x_vertex, y_vertex, z_vertex); dummyEnergy[fDaliMultTa] = DopplerCorrect(beta_vertex, DopplerAngle, fDali[i].e); DopplerAnglePieter = CalculateTheta(fDali[i].x, fDali[i].y, fDali[i].z, 0, 0, 0); dummyEnergyPieter[fDaliMultTa] = DopplerCorrect(betaLISE_middle, DopplerAnglePieter, fDali[i].e); crystalUsedForAddback[fDali[i].id] = true; fDali[fDaliMultTa].idwa = fDali[i].id; for (int j = i + 1; j < fDaliFold; j++) { if (crystalUsedForAddback[fDali[j].id] == false && fDali[j].ttrue == true) { for (int k = 0; k < fNumberOfAddbackPartners[fDali[i].id]; k++) { if (fDali[j].id == fAddbackTable[fDali[i].id][k + 1]) { crystalUsedForAddback[fDali[j].id] = true; dummyEnergy[fDaliMultTa] += DopplerCorrect(beta_vertex, DopplerAngle, fDali[j].e); dummyEnergyPieter[fDaliMultTa] += DopplerCorrect(betaLISE_middle, DopplerAnglePieter, fDali[j].e); labenergy+= fDali[j].e;//RT Jun5 //RT 2nd AdBk /*for (int l = i + 2; l < fDaliFold; l++) { // l == j event can be eliminated by crystalUsedForAddback ==true if (crystalUsedForAddback[fDali[l].id] == false && fDali[l].ttrue == true) { for (int m = 0; m < fNumberOfAddbackPartners[fDali[j].id]; m++) { if (fDali[l].id == fAddbackTable[fDali[j].id][m + 1]) { crystalUsedForAddback[fDali[l].id] = true; dummyEnergy[fDaliMultTa] += DopplerCorrect(beta_vertex, DopplerAngle, fDali[l].e); dummyEnergyPieter[fDaliMultTa] += DopplerCorrect(betaLISE_middle, DopplerAnglePieter, fDali[l].e); } } } }*/ //RT 2nd AdBk } } } } /*if (labenergy > 1200. ){//Reconstruction for the pair creation for (int j = i + 1; j < fDaliFold; j++) { if (crystalUsedForAddback[fDali[j].id] == false && fDali[j].ttrue== true && abs(fDali[j].e-511.)<30.) { //cout<<" 511keVhit "<<labenergy; labenergy+=fDali[j].e; dummyEnergy[fDaliMultTa]= DopplerCorrect(beta_vertex, DopplerAngle, labenergy); dummyEnergyPieter[fDaliMultTa]= DopplerCorrect(betaLISE_middle, DopplerAnglePieter, labenergy); //cout<<" after "<<labenergy; } } }*/ fDaliMultTa++; } for (int i = 0; i < fDaliMultTa; i++) { fDali[i].doppwa = dummyEnergy[i]; fDali[i].doppPieterwa = dummyEnergyPieter[i]; } for (int i = fDaliMultTa; i < NUMBEROFDALICRYSTALS; i++) { fDali[i].doppwa = -999; fDali[i].idwa = -999; } // w/o addback for (int j = 0; j < fDaliFold; j++) { if (fDali[j].ttrue) { h_SpectrumMINOS->Fill(fDali[j].dopp); h_SpectrumDALI->Fill(fDali[j].doppPieter); EnergyMINOS.push_back(fDali[j].dopp); EnergyDALI.push_back(fDali[j].doppPieter); /* hEnergyBeta->Fill(beta_vertex, fDali[j].dopp); hEnergyBeta1->Fill(beta1, fDali[j].dopp); hEnergyBeta2->Fill(beta2, fDali[j].dopp); */ hEnergyID_lab->Fill(fDali[j].id, fDali[j].e); // RT if (fDaliFoldTa <= 3) { hEnergyZnovertex->Fill(z_vertexH, fDali[j].doppPieter); hEnergyZ->Fill(z_vertexH, fDali[j].dopp); hEnergyID->Fill(fDali[j].id, fDali[j].dopp); hEnergyID_novertex->Fill(fDali[j].id, fDali[j].doppPieter); } } } // w/ addback Mult_wAdBk = fDaliMultTa; for (int j = 0; j < fDaliMultTa; j++) { // All mult h_SpectrumDALI_wAdBk->Fill(fDali[j].doppPieterwa); h_SpectrumMINOS_wAdBk->Fill(fDali[j].doppwa); EnergyMINOS_wAdBk.push_back(fDali[j].doppwa); EnergyDALI_wAdBk.push_back(fDali[j].doppPieterwa); IDMult_wAdBk.push_back(j); //RT ADD MINOSSpectrumAdBk.push_back(fDali[j].doppwa); //RT if (fDaliMultTa >= 2) { if (fDali[j].doppwa >= Coinc0_min && fDali[j].doppwa <= Coinc0_max) detCoinc0.push_back(j); if (fDali[j].doppwa >= Coinc1_min && fDali[j].doppwa <= Coinc1_max) detCoinc1.push_back(j); if (fDali[j].doppwa >= Coinc2_min && fDali[j].doppwa <= Coinc2_max) detCoinc2.push_back(j); if (fDali[j].doppwa >= Coinc3_min && fDali[j].doppwa <= Coinc3_max) detCoinc3.push_back(j); //Oct 15, add below if (fDali[j].doppwa >= Coinc4_min && fDali[j].doppwa <= Coinc4_max) detCoinc4.push_back(j); if (fDali[j].doppwa >= Coinc5_min && fDali[j].doppwa <= Coinc5_max) detCoinc5.push_back(j); } if (TreeCut->trackNbr_FINAL == 1) h_SpectrumMINOS_wAdBk_1p->Fill(fDali[j].doppwa); if (TreeCut->trackNbr_FINAL == 2) { h_SpectrumMINOS_wAdBk_2p->Fill(fDali[j].doppwa); } if(fDaliMultTa<3&&TreeCut->trackNbr_FINAL == 2){//Sep 14 RT add h_ECD_angle->Fill(Angle_CD[fDali[j].id], fDali[j].doppwa); //hEnergyID->Fill(fDali[j].id,fDali[j].doppwa); //hEnergyZnovertex->Fill(z_vertex*10.,fDali[j].doppPieterwa); //hEnergyZ->Fill(z_vertex*10.,fDali[j].doppwa); // Forward/backward angles && beginning/end of target if (fDali[j].id > 120) { hEnergy_forward->Fill(fDali[j].doppwa); hEnergyZ_forward->Fill(z_vertex * 10., fDali[j].doppwa); if (z_vertexH >= 0. && z_vertexH <= 20) hEnergyZ20_forward->Fill(fDali[j].doppwa); else if (z_vertexH >= 80. && z_vertexH <= 100) hEnergyZ80_forward->Fill(fDali[j].doppwa); } if (fDali[j].id < 30) { //<60 original hEnergy_backward->Fill(fDali[j].doppwa); hEnergyZ_backward->Fill(z_vertex * 10., fDali[j].doppwa); if (z_vertexH >= 0. && z_vertexH <= 20) hEnergyZ20_backward->Fill(fDali[j].doppwa); else if (z_vertexH >= 80. && z_vertexH <= 100) hEnergyZ80_backward->Fill(fDali[j].doppwa); } hEnergyBeta->Fill(beta_vertex, fDali[j].doppwa);// moved from above hEnergyBeta1->Fill(beta1, fDali[j].doppwa);// hEnergyBeta2->Fill(beta2, fDali[j].doppwa);// }//RT // Multiplicities == if (fDaliMultTa == 1) { h_mult[0]->Fill(fDali[j].doppwa); // mult==1 h_multINF[0]->Fill(fDali[j].doppwa); // mult==1 } if (fDaliMultTa == 2) h_mult[1]->Fill(fDali[j].doppwa); // mult==2 if (fDaliMultTa == 3) h_mult[2]->Fill(fDali[j].doppwa); // mult==3 if (fDaliMultTa == 4) h_mult[3]->Fill(fDali[j].doppwa); // mult==4 if (fDaliMultTa == 5) h_mult[4]->Fill(fDali[j].doppwa); // mult==5 if (fDaliMultTa == 6) h_mult[5]->Fill(fDali[j].doppwa); // mult==6 if (fDaliMultTa == 7) h_mult[6]->Fill(fDali[j].doppwa); // mult==7 if (fDaliMultTa == 8) h_mult[7]->Fill(fDali[j].doppwa); // mult==8 // Multiplicities <= if (fDaliMultTa <= 2) h_multINF[1]->Fill(fDali[j].doppwa); // mult<=2 if (fDaliMultTa <= 3) { //h_SpectrumDALI_wAdBk->Fill(fDali[j].doppPieterwa); //h_SpectrumMINOS_wAdBk->Fill(fDali[j].doppwa); h_multINF[2]->Fill(fDali[j].doppwa); //mult<=3 } if (fDaliMultTa <= 4) h_multINF[3]->Fill(fDali[j].doppwa); // mult<=4 if (fDaliMultTa <= 5) h_multINF[4]->Fill(fDali[j].doppwa); // mult<=5 if (fDaliMultTa <= 6) h_multINF[5]->Fill(fDali[j].doppwa); // mult<=6 if (fDaliMultTa <= 7) h_multINF[6]->Fill(fDali[j].doppwa); // mult<=7 if (fDaliMultTa <= 8) h_multINF[7]->Fill(fDali[j].doppwa); // mult<=8 // Multiplicities == if (fDaliMultTa > 1) h_multSUP[0]->Fill(fDali[j].doppwa); // mult>1 if (fDaliMultTa > 2) h_multSUP[1]->Fill(fDali[j].doppwa); // mult>2 if (fDaliMultTa > 3) h_multSUP[2]->Fill(fDali[j].doppwa); // mult>3 if (fDaliMultTa > 4) h_multSUP[3]->Fill(fDali[j].doppwa); // mult>4 if (fDaliMultTa > 5) h_multSUP[4]->Fill(fDali[j].doppwa); // mult>5 if (fDaliMultTa > 6) h_multSUP[5]->Fill(fDali[j].doppwa); // mult>6 if (fDaliMultTa > 7) h_multSUP[6]->Fill(fDali[j].doppwa); // mult>7 if (fDaliMultTa > 8) h_multSUP[7]->Fill(fDali[j].doppwa); // mult>8 } //cerr << "Coinc1: " << detCoinc1.size() << "; Coinc2: " << detCoinc2.size() << "; Coinc3: " << detCoinc3.size() << "; Coinc0: " << detCoinc0.size() << endl; for (int j = 0; j < fDaliMultTa; j++) { for (int fj = 0; fj < detCoinc0.size(); fj++) { if (j != detCoinc0[fj]) EnergyCoinc0.push_back(fDali[j].doppwa); } for (int fj = 0; fj < detCoinc1.size(); fj++) { if (j != detCoinc1[fj]) EnergyCoinc1.push_back(fDali[j].doppwa); } for (int fj = 0; fj < detCoinc2.size(); fj++) { if (j != detCoinc2[fj]) EnergyCoinc2.push_back(fDali[j].doppwa); } for (int fj = 0; fj < detCoinc3.size(); fj++) { if (j != detCoinc3[fj]) EnergyCoinc3.push_back(fDali[j].doppwa); } //Oct 15 for (int fj = 0; fj < detCoinc4.size(); fj++) { if (j != detCoinc4[fj]) EnergyCoinc4.push_back(fDali[j].doppwa); } for (int fj = 0; fj < detCoinc5.size(); fj++) { if (j != detCoinc5[fj]) EnergyCoinc5.push_back(fDali[j].doppwa); } for (int fj = 0; fj < fDaliMultTa; fj++) { if (j != fj) h_EEcoinc_allMult->Fill(fDali[j].doppwa, fDali[fj].doppwa); if (fDaliMultTa <= 4 && j != fj) h_EEcoinc_MultInf4->Fill(fDali[j].doppwa, fDali[fj].doppwa); if (fDaliMultTa > 2 && j != fj) h_EEcoinc_MultSup2->Fill(fDali[j].doppwa, fDali[fj].doppwa); } } //cout << EnergyMINOS_wAdBk.size() << " " << EnergyMINOS_wAdBk.back() << endl; tree->Fill(); } for (int i = 0; i < 8; i++) h_mult[i]->Write(); for (int i = 0; i < 8; i++) h_multINF[i]->Write(); for (int i = 0; i < 8; i++) h_multSUP[i]->Write(); h_SpectrumMINOS->Write(); h_SpectrumDALI->Write(); h_SpectrumMINOS_wAdBk->Write(); h_SpectrumMINOS_wAdBk_1p->Write(); h_SpectrumMINOS_wAdBk_2p->Write(); h_SpectrumDALI_wAdBk->Write(); h_beta_vertex->Write(); hdifftheta->Write(); hEnergyZnovertex->Write(); hEnergyZ->Write(); hEnergyID->Write(); h_Zvertex->Write(); h_betaBR->Write(); h_betaZD->Write(); h_XminosPPAC->Write(); h_YminosPPAC->Write(); h_ZminosPPAC->Write(); h_XminosDSSSD->Write(); h_YminosDSSSD->Write(); h_ZminosDSSSD->Write(); h_XPPACDSSSD->Write(); h_YPPACDSSSD->Write(); h_ZPPACDSSSD->Write(); h_EEcoinc_allMult->Write(); h_EEcoinc_MultInf4->Write(); h_EEcoinc_MultSup2->Write(); //theApp->Run(); rootfile->Write(); rootfile->Close(); return 0; }
void results2tree( const char* workDirName, bool isMC=false, const char* thePoiNames="RFrac2Svs1S,N_Jpsi,f_Jpsi,m_Jpsi,sigma1_Jpsi,alpha_Jpsi,n_Jpsi,sigma2_Jpsi,MassRatio,rSigma21_Jpsi,lambda1_Bkg,lambda2_Bkg,lambda3_Bkg,lambda4_Bkg,lambda5__Bkg,N_Bkg" ) { // workDirName: usual tag where to look for files in Output // thePoiNames: comma-separated list of parameters to store ("par1,par2,par3"). Default: all TFile *f = new TFile(treeFileName(workDirName,isMC),"RECREATE"); TTree *tr = new TTree("fitresults","fit results"); // bin edges float ptmin, ptmax, ymin, ymax, centmin, centmax; // model names Char_t jpsiName[128], psipName[128], bkgName[128]; // collision system Char_t collSystem[8]; // goodness of fit float nll, chi2, normchi2; int npar, ndof; // parameters to store: make it a vector vector<poi> thePois; TString thePoiNamesStr(thePoiNames); TString t; Int_t from = 0; while (thePoiNamesStr.Tokenize(t, from , ",")) { poi p; strcpy(p.name, t.Data()); cout << p.name << endl; thePois.push_back(p); } // create tree branches tr->Branch("ptmin",&ptmin,"ptmin/F"); tr->Branch("ptmax",&ptmax,"ptmax/F"); tr->Branch("ymin",&ymin,"ymin/F"); tr->Branch("ymax",&ymax,"ymax/F"); tr->Branch("centmin",¢min,"centmin/F"); tr->Branch("centmax",¢max,"centmax/F"); tr->Branch("jpsiName",jpsiName,"jpsiName/C"); tr->Branch("psipName",psipName,"psipName/C"); tr->Branch("bkgName",bkgName,"bkgName/C"); tr->Branch("collSystem",collSystem,"collSystem/C"); tr->Branch("nll",&nll,"nll/F"); tr->Branch("chi2",&chi2,"chi2/F"); tr->Branch("normchi2",&normchi2,"normchi2/F"); tr->Branch("npar",&npar,"npar/I"); tr->Branch("ndof",&ndof,"ndof/I"); for (vector<poi>::iterator it=thePois.begin(); it!=thePois.end(); it++) { tr->Branch(Form("%s_val",it->name),&(it->val),Form("%s_val/F",it->name)); tr->Branch(Form("%s_err",it->name),&(it->err),Form("%s_err/F",it->name)); } // list of files vector<TString> theFiles = fileList(workDirName,"",isMC); int cnt=0; for (vector<TString>::const_iterator it=theFiles.begin(); it!=theFiles.end(); it++) { cout << "Parsing file " << cnt << " / " << theFiles.size() << ": " << *it << endl; // parse the file name to get info anabin thebin = binFromFile(*it); ptmin = thebin.ptbin().low(); ptmax = thebin.ptbin().high(); ymin = thebin.rapbin().low(); ymax = thebin.rapbin().high(); centmin = thebin.centbin().low(); centmax = thebin.centbin().high(); strcpy(collSystem, (it->Index("PbPb")>0) ? "PbPb" : "PP"); // get the model names from = 0; bool catchjpsi=false, catchpsip=false, catchbkg=false; while (it->Tokenize(t, from, "_")) { if (catchjpsi) {strcpy(jpsiName, t.Data()); catchjpsi=false;} if (catchpsip) {strcpy(psipName, t.Data()); catchpsip=false;} if (catchbkg) {strcpy(bkgName, t.Data()); catchbkg=false;} if (t=="Jpsi") catchjpsi=true; if (t=="Psi2S") catchpsip=true; if (t=="Bkg") catchbkg=true; } TFile *f = new TFile(*it); RooWorkspace *ws = NULL; if (!f) { cout << "Error, file " << *it << " does not exist." << endl; } else { ws = (RooWorkspace*) f->Get("workspace"); if (!ws) { cout << "Error, workspace not found in " << *it << "." << endl; } } nll=0; chi2=0; npar=0; ndof=0; if (f && ws) { // get the model for nll and npar RooAbsPdf *model = pdfFromWS(ws, Form("_%s",collSystem), "pdfMASS_Tot"); if (model) { RooAbsData *dat = dataFromWS(ws, Form("_%s",collSystem), "dOS_DATA"); if (dat) { RooAbsReal *NLL = model->createNLL(*dat); if (NLL) nll = NLL->getVal(); npar = model->getParameters(dat)->selectByAttrib("Constant",kFALSE)->getSize(); // compute the chi2 and the ndof RooPlot* frame = ws->var("invMass")->frame(Bins(nBins)); dat->plotOn(frame); model->plotOn(frame); TH1 *hdatact = dat->createHistogram("hdatact", *(ws->var("invMass")), Binning(nBins)); RooHist *hpull = frame->pullHist(0,0, true); double* ypulls = hpull->GetY(); unsigned int nFullBins = 0; for (int i = 0; i < nBins; i++) { if (hdatact->GetBinContent(i+1) > 0.0) { chi2 += ypulls[i]*ypulls[i]; nFullBins++; } } ndof = nFullBins - npar; normchi2 = chi2/ndof; } } // get the POIs for (vector<poi>::iterator itpoi=thePois.begin(); itpoi!=thePois.end(); itpoi++) { RooRealVar *thevar = poiFromWS(ws, Form("_%s",collSystem), itpoi->name); itpoi->val = thevar ? thevar->getVal() : 0; itpoi->err = thevar ? thevar->getError() : 0; } f->Close(); delete f; } else { for (vector<poi>::iterator itpoi=thePois.begin(); itpoi!=thePois.end(); itpoi++) { itpoi->val = 0; itpoi->err = 0; } } // fill the tree tr->Fill(); cnt++; } // loop on the files f->Write(); f->Close(); }
void revCalSimulation (Int_t runNumber, string b, string A) { int numFiles = 180;//(b==std::string("inf")?200:(A==std::string("-1")?200:20)); bool allEvtsTrigg = false; //This just removes the use of the trigger function for an initial calibration. // Once a calibration is established (or if running on Betas), you can keep this false bool simProperStatistics = false; // If True, this uses the actual data run to determine the number of Type 0s to simulate cout << "Running reverse calibration for run " << runNumber << endl; UInt_t BetaEvents = 0; //Holds the number of electron like Type 0 events to process Char_t temp[500],tempE[500],tempW[500]; //First get the number of total electron events around the source position from the data file and also the length of the run //sprintf(temp,"%s/replay_pass4_%i.root",getenv("REPLAY_PASS4"),runNumber); sprintf(temp,"%s/replay_pass3_%i.root",getenv("REPLAY_PASS3"),runNumber); TFile *dataFile = new TFile(temp,"READ"); TTree *data = (TTree*)(dataFile->Get("pass3")); sprintf(tempE,"Type<4 && Type>=0 && PID==1 && Side==0 && (xE.center*xE.center+yE.center*yE.center)<2500. && (xW.center*xW.center+yW.center*yW.center)<2500."); sprintf(tempW,"Type<4 && Type>=0 && PID==1 && Side==1 && (xW.center*xW.center+yW.center*yW.center)<2500. && (xE.center*xE.center+yE.center*yE.center)<2500."); BetaEvents = data->GetEntries(tempE) + data->GetEntries(tempW); cout << "Electron Events in Data file: " << BetaEvents << endl; cout << "East: " << data->GetEntries(tempE) << "\tWest: " << data->GetEntries(tempW) << endl; delete data; dataFile->Close(); //If we have a Beta run and we don't want exact statistics, simulate 16 times the number of events if ( !simProperStatistics ) { BetaEvents = 100*BetaEvents; } std::cout << "Processing " << BetaEvents << " events...\n"; ///////////////////////// SETTING GAIN OF FIRST and second DYNYODE Double_t g_d = 16.; Double_t g_rest = 12500.; /////// Loading other run dependent quantities vector <Int_t> pmtQuality = getEreconPMTQuality(runNumber); // Get the quality of the PMTs for that run UInt_t calibrationPeriod = getSrcRunPeriod(runNumber); // retrieve the calibration period for this run UInt_t XePeriod = getXeRunPeriod(runNumber); // Get the proper Xe run period for the Trigger functions //GetPositionMap(XePeriod); PositionMap posmap(5.0,50.); //Load position map with 5 mm bins posmap.readPositionMap(XePeriod,"endpoint"); vector <Double_t> alpha = GetAlphaValues(calibrationPeriod); // fill vector with the alpha (nPE/keV) values for this run period /////////////// Load trigger functions ////////////////// TriggerFunctions trigger(runNumber); std::vector < std::vector <Double_t> > pedestals = loadPMTpedestals(runNumber); std::vector < Double_t > PMTgain = loadGainFactors(runNumber); //Load the simulated relationship between EQ and Etrue EreconParameterization eRecon(runNumber); // Int_t pol = source=="Beta" ? getPolarization(runNumber) : 1; LinearityCurve linCurve(calibrationPeriod,false); std::cout << "Loaded Linearity Curves\n"; //Decide which simulation to use... TChain *chain = new TChain("anaTree"); std::string geom; if (runNumber<20000) geom = "2011-2012_geom"; else if (runNumber>=21087 && runNumber<21679) geom = "2012-2013_isobutane_geom"; else geom = "2012-2013_geom"; TString fileLocation = TString::Format("/extern/mabrow05/ucna/xuan_stuff/AbFit_Fierz_2011-2013/%s/A_%s_b_%s/", geom.c_str(),A.c_str(),b.c_str()); std::cout << "Using simulation from " << fileLocation << "...\n"; //Read in simulated data and put in a TChain TRandom3 *randFile = new TRandom3(runNumber*2); int fileNum = (int)(randFile->Rndm()*numFiles); delete randFile; for (int i=0; i<numFiles; i++) { if (fileNum==numFiles) fileNum=0; chain->AddFile(TString::Format("%s/xuan_analyzed_%i.root",fileLocation.Data(),fileNum)); fileNum++; } // Set the addresses of the information read in from the simulation file /*chain->SetBranchAddress("MWPCEnergy",&mwpcE); x chain->SetBranchAddress("time",&Time); x chain->SetBranchAddress("Edep",&edep); x chain->SetBranchAddress("EdepQ",&edepQ); x chain->SetBranchAddress("MWPCPos",&mwpc_pos); x chain->SetBranchAddress("ScintPos",&scint_pos); x chain->SetBranchAddress("primKE",&primKE); x chain->SetBranchAddress("primTheta",&primTheta); chain->SetBranchAddress("Cath_EX",Cath_EX); chain->SetBranchAddress("Cath_EY",Cath_EY); chain->SetBranchAddress("Cath_WX",Cath_WX); chain->SetBranchAddress("Cath_WY",Cath_WY); chain->SetBranchAddress("hitCountSD",hitCountSD);*/ //These are for feeding in Xuan's simulations... this needs to be updated so that I can pass a flag and change these on the fly chain->SetBranchAddress("primaryParticleSpecies",&primaryID); chain->SetBranchAddress("mwpcEnergy",&mwpcE); chain->SetBranchAddress("scintTimeToHit",&Time); chain->SetBranchAddress("scintillatorEdep",&edep); chain->SetBranchAddress("scintillatorEdepQuenched",&edepQ); chain->SetBranchAddress("MWPCPos",&mwpc_pos); chain->SetBranchAddress("ScintPos",&scint_pos); chain->SetBranchAddress("primaryKE",&primKE); chain->SetBranchAddress("primaryMomentum",primMom); //Set random number generator TRandom3 *seed = new TRandom3( 3*runNumber ); // seed generator TRandom3 *rand0 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) ); TRandom3 *rand1 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) ); TRandom3 *rand2 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) ); TRandom3 *rand3 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) ); //Initialize random numbers for 8 pmt trigger probabilities TRandom3 *randPMTE1 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) ); TRandom3 *randPMTE2 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) ); TRandom3 *randPMTE3 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) ); TRandom3 *randPMTE4 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) ); TRandom3 *randPMTW1 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) ); TRandom3 *randPMTW2 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) ); TRandom3 *randPMTW3 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) ); TRandom3 *randPMTW4 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) ); std::vector <Double_t> triggRandVec(4,0.); // Wirechamber information bool EastScintTrigger, WestScintTrigger, EMWPCTrigger, WMWPCTrigger; //Trigger booleans Double_t MWPCAnodeThreshold=0.; // keV dep in the wirechamber.. //Get total number of events in TChain UInt_t nevents = chain->GetEntries(); cout << "events = " << nevents << endl; //Start from random position in evt sequence if we aren't simulating veryHighStatistics UInt_t evtStart = seed->Rndm()*nevents; UInt_t evtTally = 0; //To keep track of the number of events UInt_t evt = evtStart; //current event number vector < vector <Int_t> > gridPoint; //Create simulation output file TFile *outfile = new TFile(TString::Format("%s/revCalSim_%i.root",fileLocation.Data(),runNumber), "RECREATE"); //Setup the output tree TTree *tree = new TTree("revCalSim", "revCalSim"); SetUpTree(tree); //Setup the output tree and branches //Histograms of event types for quick checks vector <TH1D*> finalEn (6,NULL); finalEn[0] = new TH1D("finalE0", "Simulated Weighted Sum East Type 0", 400, 0., 1200.); finalEn[1] = new TH1D("finalW0", "Simulated Weighted Sum West Type 0", 400, 0., 1200.); finalEn[2] = new TH1D("finalE1", "Simulated Weighted Sum East Type 1", 400, 0., 1200.); finalEn[3] = new TH1D("finalW1", "Simulated Weighted Sum West Type 1", 400, 0., 1200.); finalEn[4] = new TH1D("finalE23", "Simulated Weighted Sum East Type 2/3", 400, 0., 1200.); finalEn[5] = new TH1D("finalW23", "Simulated Weighted Sum West Type 2/3", 400, 0., 1200.); //Read in events and determine evt type based on triggers while (evtTally<=BetaEvents) { if (evt>=nevents) evt=0; //Wrapping the events back to the beginning EastScintTrigger = WestScintTrigger = EMWPCTrigger = WMWPCTrigger = false; //Resetting triggers each event chain->GetEvent(evt); //Checking that the event occurs within the fiducial volume in the simulation to minimize // contamination from edge effects and interactions with detector walls // This is also the fiducial cut used in extracting asymmetries and doing calibrations Double_t fidCut = 50.; /////////////// Do position and Wirechamber stuff /////////////////// // Following negative sign is to turn x-coordinate into global coordinate on East scint_pos_adj.ScintPosAdjE[0] = scint_pos.ScintPosE[0]*sqrt(0.6)*1000.; scint_pos_adj.ScintPosAdjE[1] = scint_pos.ScintPosE[1]*sqrt(0.6)*1000.; scint_pos_adj.ScintPosAdjW[0] = scint_pos.ScintPosW[0]*sqrt(0.6)*1000.;//sqrt(0.6)*10.*scint_pos.ScintPosW[0]+displacementX; scint_pos_adj.ScintPosAdjW[1] = scint_pos.ScintPosW[1]*sqrt(0.6)*1000.;//sqrt(0.6)*10.*scint_pos.ScintPosW[1]+displacementY; scint_pos_adj.ScintPosAdjE[2] = scint_pos.ScintPosE[2]*1000.; scint_pos_adj.ScintPosAdjW[2] = scint_pos.ScintPosW[2]*1000.; Double_t mwpcAdjE[3] = {0.,0.,0.}; Double_t mwpcAdjW[3] = {0.,0.,0.}; mwpcAdjE[0] = mwpc_pos.MWPCPosE[0] * sqrt(0.6) * 1000.; mwpcAdjE[1] = mwpc_pos.MWPCPosE[1] * sqrt(0.6) * 1000.; mwpcAdjW[0] = mwpc_pos.MWPCPosW[0] * sqrt(0.6) * 1000. ; mwpcAdjW[1] = mwpc_pos.MWPCPosW[1] * sqrt(0.6) * 1000. ; mwpcAdjE[2] = mwpc_pos.MWPCPosE[2] * 1000. ; mwpcAdjW[2] = mwpc_pos.MWPCPosW[2] * 1000. ; //std::cout << mwpcAdjE[0] << "\t" << mwpcAdjW[0] << std::endl; //if (evtTally==5) exit(0); ///////////////////////////////////////////////////////////////////// // Creating all extra structs to hold the alternate position reconstruction // crap before writing it all out ///////////////////////////////////////////////////////////////////// std::vector <Double_t> eta; std::vector <Double_t> trueEta; // This is the position map value of the actual event position, not the position as determined // by cathode reconstruction trueEta = posmap.getInterpolatedEta(scint_pos_adj.ScintPosAdjE[0], scint_pos_adj.ScintPosAdjE[1], scint_pos_adj.ScintPosAdjW[0], scint_pos_adj.ScintPosAdjW[1]); eta = posmap.getInterpolatedEta(scint_pos_adj.ScintPosAdjE[0], scint_pos_adj.ScintPosAdjE[1], scint_pos_adj.ScintPosAdjW[0], scint_pos_adj.ScintPosAdjW[1]); //MWPC triggers if (mwpcE.MWPCEnergyE>MWPCAnodeThreshold) EMWPCTrigger=true; if (mwpcE.MWPCEnergyW>MWPCAnodeThreshold) WMWPCTrigger=true; std::vector<Double_t> ADCvecE(4,0.); std::vector<Double_t> ADCvecW(4,0.); //East Side smeared PMT energies for (UInt_t p=0; p<4; p++) { if ( edep.EdepE>0. ) { //Check to make sure that there is light to see in the scintillator if (eta[p]>0.) { pmt.etaEvis[p] = (1./(alpha[p]*g_d*g_rest)) * (rand3->Poisson(g_rest*rand2->Poisson(g_d*rand1->Poisson(alpha[p]*trueEta[p]*edepQ.EdepQE)))); Double_t ADC = linCurve.applyInverseLinCurve(p, pmt.etaEvis[p]) + rand0->Gaus(0.,pedestals[p][1]); //Take into account non-zero width of the pedestal ADCvecE[p] = ADC; pmt.etaEvis[p] = linCurve.applyLinCurve(p, ADC); pmt.Evis[p] = pmt.etaEvis[p]/eta[p]; } else { //To avoid dividing by zero.. these events won't be used in analysis since they are outside the fiducial cut pmt.etaEvis[p] = (1./(alpha[p]*g_d*g_rest)) * (rand3->Poisson(g_rest*rand2->Poisson(g_d*rand1->Poisson(alpha[p]*edepQ.EdepQE)))); Double_t ADC = linCurve.applyInverseLinCurve(p, pmt.etaEvis[p]);// + rand0->Gaus(0.,pedestals[p][1]); //Take into account non-zero width of the pedestal ADCvecE[p] = ADC; pmt.etaEvis[p] = linCurve.applyLinCurve(p, ADC); pmt.Evis[p] = pmt.etaEvis[p]; } pmt.nPE[p] = alpha[p]*pmt.etaEvis[p] ; } // If eQ is 0... else { pmt.etaEvis[p] = 0.; pmt.Evis[p] = 0.; pmt.nPE[p] = 0.; } } Double_t numer=0., denom=0.; for (UInt_t p=0;p<4;p++) { numer += ( pmtQuality[p] ) ? pmt.nPE[p] : 0.; denom += ( pmtQuality[p] ) ? eta[p]*alpha[p] : 0.; //numer += ( pmtQuality[p] && pmt.etaEvis[p]>0. ) ? pmt.nPE[p] : 0.; //denom += ( pmtQuality[p] && pmt.etaEvis[p]>0. ) ? eta[p]*alpha[p] : 0.; } Double_t totalEnE = denom>0. ? numer/denom : 0.; evis.EvisE = totalEnE; //Now we apply the trigger probability triggRandVec[0] = randPMTE1->Rndm(); triggRandVec[1] = randPMTE2->Rndm(); triggRandVec[2] = randPMTE3->Rndm(); triggRandVec[3] = randPMTE4->Rndm(); if ( (allEvtsTrigg && totalEnE>0.) || ( trigger.decideEastTrigger(ADCvecE,triggRandVec) ) ) EastScintTrigger = true; //West Side for (UInt_t p=4; p<8; p++) { if ( !(p==5 && runNumber>16983 && runNumber<17249) && edep.EdepW>0. ) { //Check to make sure that there is light to see in the scintillator and that run isn't one where PMTW2 was dead if (eta[p]>0.) { pmt.etaEvis[p] = (1./(alpha[p]*g_d*g_rest)) * (rand3->Poisson(g_rest*rand2->Poisson(g_d*rand1->Poisson(alpha[p]*trueEta[p]*edepQ.EdepQW)))); Double_t ADC = linCurve.applyInverseLinCurve(p, pmt.etaEvis[p]) + rand0->Gaus(0.,pedestals[p][1]); //Take into account non-zero width of the pedestal ADCvecW[p-4] = ADC; //cout << ADCvecW[p-4] << endl; pmt.etaEvis[p] = linCurve.applyLinCurve(p, ADC); pmt.Evis[p] = pmt.etaEvis[p]/eta[p]; } else { //To avoid dividing by zero.. these events won't be used in analysis since they are outside the fiducial cut pmt.etaEvis[p] = (1./(alpha[p]*g_d*g_rest)) * (rand3->Poisson(g_rest*rand2->Poisson(g_d*rand1->Poisson(alpha[p]*edepQ.EdepQW)))); Double_t ADC = linCurve.applyInverseLinCurve(p, pmt.etaEvis[p]);// + rand0->Gaus(0.,pedestals[p][1]); //Take into account non-zero width of the pedestal ADCvecW[p-4] = ADC; pmt.etaEvis[p] = linCurve.applyLinCurve(p, ADC); pmt.Evis[p] = pmt.etaEvis[p]; } pmt.nPE[p] = alpha[p]*pmt.etaEvis[p]; } // If PMT is dead and EQ=0... else { pmt.etaEvis[p] = 0.; pmt.Evis[p] = 0.; pmt.nPE[p] = 0.; } } //Calculate the total weighted energy numer=denom=0.; for (UInt_t p=4;p<8;p++) { numer += ( pmtQuality[p] ) ? pmt.nPE[p] : 0.; denom += ( pmtQuality[p] ) ? eta[p]*alpha[p] : 0.; //numer += ( pmtQuality[p] && pmt.etaEvis[p]>0. ) ? pmt.nPE[p] : 0.; //denom += ( pmtQuality[p] && pmt.etaEvis[p]>0. ) ? eta[p]*alpha[p] : 0.; } //Now we apply the trigger probability Double_t totalEnW = denom>0. ? numer/denom : 0.; evis.EvisW = totalEnW; triggRandVec[0] = randPMTW1->Rndm(); triggRandVec[1] = randPMTW2->Rndm(); triggRandVec[2] = randPMTW3->Rndm(); triggRandVec[3] = randPMTW4->Rndm(); if ( (allEvtsTrigg && totalEnW>0.) || ( trigger.decideWestTrigger(ADCvecW,triggRandVec) ) ) WestScintTrigger = true; //if (totalEnW<25.) std::cout << totalEnW << " " << WestScintTrigger << "\n"; //Fill proper total event histogram based on event type PID=6; //This is an unidentified particle type=4; //this is a lost event side=2; //This means there are no scintillator triggers //Type 0 East if (EastScintTrigger && EMWPCTrigger && !WestScintTrigger && !WMWPCTrigger) { PID=1; type=0; side=0; //finalEn[0]->Fill(evis.EvisE); //cout << "Type 0 East E = " << totalEnE << endl; } //Type 0 West else if (WestScintTrigger && WMWPCTrigger && !EastScintTrigger && !EMWPCTrigger) { PID=1; type=0; side=1; //finalEn[1]->Fill(totalEnW); } //Type 1 else if (EastScintTrigger && EMWPCTrigger && WestScintTrigger && WMWPCTrigger) { PID=1; type=1; //East if (Time.timeE<Time.timeW) { //finalEn[2]->Fill(totalEnE); side=0; } //West else if (Time.timeE>Time.timeW) { //finalEn[3]->Fill(totalEnW); side=1; } } //Type 2/3 East else if (EastScintTrigger && EMWPCTrigger && !WestScintTrigger && WMWPCTrigger) { PID=1; type=2; side=0; //finalEn[4]->Fill(totalEnE); //cout << "Type 2/3 East E = " << totalEnE << endl; } //Type 2/3 West else if (!EastScintTrigger && EMWPCTrigger && WestScintTrigger && WMWPCTrigger) { PID=1; type=2; side=1; //finalEn[5]->Fill(totalEnW); //cout << "Type 2/3 East W = " << totalEnW << endl; } //Gamma events and missed events (Type 4) else { if (!WMWPCTrigger && !EMWPCTrigger) { if (EastScintTrigger && !WestScintTrigger) { PID=0; type=0; side=0; } else if (!EastScintTrigger && WestScintTrigger) { PID=0; type=0; side=1; } else if (EastScintTrigger && WestScintTrigger) { PID=0; type=1; if (Time.timeE<Time.timeW) { side=0; } else { side=1; } } else { PID=6; type=4; side=2; } } else { PID=1; type=4; side = (WMWPCTrigger && EMWPCTrigger) ? 2 : (WMWPCTrigger ? 1 : 0); //Side==2 means the event triggered both wirechambers, but neither scint } } //Calculate Erecon Erecon = -1.; Int_t typeIndex = (type==0 || type==4) ? 0:(type==1 ? 1:2); //for retrieving the parameters from EQ2Etrue if (side==0) { Double_t totalEvis = type==1 ? (evis.EvisE+evis.EvisW):evis.EvisE; if (evis.EvisE>0. && totalEvis>0.) { Erecon = eRecon.getErecon(0,typeIndex,totalEvis); if (type==0) finalEn[0]->Fill(Erecon); else if (type==1) finalEn[2]->Fill(Erecon); else if(type==2 ||type==3) finalEn[4]->Fill(Erecon); } else Erecon=-1.; } if (side==1) { Double_t totalEvis = type==1 ? (evis.EvisE+evis.EvisW):evis.EvisW; if (evis.EvisW>0. && totalEvis>0.) { Erecon = eRecon.getErecon(1,typeIndex,totalEvis); if (type==0) finalEn[1]->Fill(Erecon); else if (type==1) finalEn[3]->Fill(Erecon); else if(type==2 ||type==3) finalEn[5]->Fill(Erecon); } else Erecon=-1.; } if ( PID==1 && Erecon>0. && sqrt( scint_pos_adj.ScintPosAdjE[0]*scint_pos_adj.ScintPosAdjE[0] + scint_pos_adj.ScintPosAdjE[1]*scint_pos_adj.ScintPosAdjE[1] )<fidCut && sqrt( scint_pos_adj.ScintPosAdjW[0]*scint_pos_adj.ScintPosAdjW[0] + scint_pos_adj.ScintPosAdjW[1]*scint_pos_adj.ScintPosAdjW[1] )<fidCut ) evtTally++; evt++; tree->Fill(); if (evtTally%10000==0) {std::cout << evtTally << " PID=" << PID << " Erecon=" << Erecon << std::endl;}//cout << "filled event " << evt << endl; } cout << endl; delete chain; delete seed; delete rand0; delete rand1; delete rand2; delete rand3; delete randPMTE1; delete randPMTE2; delete randPMTE3; delete randPMTE4; delete randPMTW1; delete randPMTW2; delete randPMTW3; delete randPMTW4; outfile->Write(); outfile->Close(); }
void makeTemplatesWe() { gBenchmark->Start("makeTemplatesWe"); //-------------------------------------------------------------------------------------------------------------- // Settings //============================================================================================================== const Double_t PT_CUT = 25; const Double_t ETA_CUT = 2.5; // input W signal file TString infilename("/data/blue/Bacon/Run2/wz_flat_07_23/Wenu/ntuples/we_select.root"); // file name with Zll data TString datafname("ZeeData/fits_mva.root"); // file name with Zl MC TString zllMCfname("ZeeMC/fits.root"); // file name with Wp MC TString wpMCfname("WepMC/fits.root"); // file name with Wm MC TString wmMCfname("WemMC/fits.root"); // output file name TString outfilename("./testWe.root"); //-------------------------------------------------------------------------------------------------------------- // Main analysis code //============================================================================================================== // Access recoil corrections //RecoilCorrector recoilCorr(datafname,zllMCfname,wpMCfname,wmMCfname); RecoilCorrector recoilCorr(datafname); // // Declare variables to read in ntuple // UInt_t runNum, lumiSec, evtNum; UInt_t npv, npu; Float_t genVPt, genVPhi; Float_t weight, scale1fb, puWeight; Float_t met, metPhi, sumEt, mt, u1, u2; Int_t q; TLorentzVector *lep=0; TLorentzVector *sc=0; // // Set up output TTrees // Float_t out_met; TFile *outFile = new TFile(outfilename,"RECREATE"); TTree *rawWeTree = new TTree("RawWe","RawWe"); rawWeTree->Branch("weight", &weight, "weight/F"); rawWeTree->Branch("out_met", &out_met, "out_met/F"); TTree *rawWepTree = new TTree("RawWep","RawWep"); rawWepTree->Branch("weight", &weight, "weight/F"); rawWepTree->Branch("out_met", &out_met, "out_met/F"); TTree *rawWemTree = new TTree("RawWem","RawWem"); rawWemTree->Branch("weight", &weight, "weight/F"); rawWemTree->Branch("out_met", &out_met, "out_met/F"); TTree *corrWeTree = new TTree("CorrWe","corrWe"); corrWeTree->Branch("weight", &weight, "weight/F"); corrWeTree->Branch("out_met", &out_met, "out_met/F"); TTree *corrWepTree = new TTree("CorrWep","corrWep"); corrWepTree->Branch("weight", &weight, "weight/F"); corrWepTree->Branch("out_met", &out_met, "out_met/F"); TTree *corrWemTree = new TTree("CorrWem","corrWem"); corrWemTree->Branch("weight", &weight, "weight/F"); corrWemTree->Branch("out_met", &out_met, "out_met/F"); TTree *corrUpWeTree = new TTree("CorrUpWe","corrUpWe"); corrUpWeTree->Branch("weight", &weight, "weight/F"); corrUpWeTree->Branch("out_met", &out_met, "out_met/F"); TTree *corrUpWepTree = new TTree("CorrUpWep","corrUpWep"); corrUpWepTree->Branch("weight", &weight, "weight/F"); corrUpWepTree->Branch("out_met", &out_met, "out_met/F"); TTree *corrUpWemTree = new TTree("CorrUpWem","corrUpWem"); corrUpWemTree->Branch("weight", &weight, "weight/F"); corrUpWemTree->Branch("out_met", &out_met, "out_met/F"); TTree *corrDownWeTree = new TTree("CorrDownWe","corrDownWe"); corrDownWeTree->Branch("weight", &weight, "weight/F"); corrDownWeTree->Branch("out_met", &out_met, "out_met/F"); TTree *corrDownWepTree = new TTree("CorrDownWep","corrDownWep"); corrDownWepTree->Branch("weight", &weight, "weight/F"); corrDownWepTree->Branch("out_met", &out_met, "out_met/F"); TTree *corrDownWemTree = new TTree("CorrDownWem","corrDownWem"); corrDownWemTree->Branch("weight", &weight, "weight/F"); corrDownWemTree->Branch("out_met", &out_met, "out_met/F"); TTree *lepScaleUpWeTree = new TTree("LepScaleUpWe","lepScaleUpWe"); lepScaleUpWeTree->Branch("weight", &weight, "weight/F"); lepScaleUpWeTree->Branch("out_met", &out_met, "out_met/F"); TTree *lepScaleUpWepTree = new TTree("LepScaleUpWep","lepScaleUpWep"); lepScaleUpWepTree->Branch("weight", &weight, "weight/F"); lepScaleUpWepTree->Branch("out_met", &out_met, "out_met/F"); TTree *lepScaleUpWemTree = new TTree("LepScaleUpWem","lepScaleUpWem"); lepScaleUpWemTree->Branch("weight", &weight, "weight/F"); lepScaleUpWemTree->Branch("out_met", &out_met, "out_met/F"); TTree *lepScaleDownWeTree = new TTree("LepScaleDownWe","lepScaleDownWe"); lepScaleDownWeTree->Branch("weight", &weight, "weight/F"); lepScaleDownWeTree->Branch("out_met", &out_met, "out_met/F"); TTree *lepScaleDownWepTree = new TTree("LepScaleDownWep","lepScaleDownWep"); lepScaleDownWepTree->Branch("weight", &weight, "weight/F"); lepScaleDownWepTree->Branch("out_met", &out_met, "out_met/F"); TTree *lepScaleDownWemTree = new TTree("LepScaleDownWem","lepScaleDownWem"); lepScaleDownWemTree->Branch("weight", &weight, "weight/F"); lepScaleDownWemTree->Branch("out_met", &out_met, "out_met/F"); TTree *lepResUpWeTree = new TTree("LepResUpWe","lepResUpWe"); lepResUpWeTree->Branch("weight", &weight, "weight/F"); lepResUpWeTree->Branch("out_met", &out_met, "out_met/F"); TTree *lepResUpWepTree = new TTree("LepResUpWep","lepResUpWep"); lepResUpWepTree->Branch("weight", &weight, "weight/F"); lepResUpWepTree->Branch("out_met", &out_met, "out_met/F"); TTree *lepResUpWemTree = new TTree("LepResUpWem","lepResUpWem"); lepResUpWemTree->Branch("weight", &weight, "weight/F"); lepResUpWemTree->Branch("out_met", &out_met, "out_met/F"); TTree *lepResDownWeTree = new TTree("LepResDownWe","lepResDownWe"); lepResDownWeTree->Branch("weight", &weight, "weight/F"); lepResDownWeTree->Branch("out_met", &out_met, "out_met/F"); TTree *lepResDownWepTree = new TTree("LepResDownWep","lepResDownWep"); lepResDownWepTree->Branch("weight", &weight, "weight/F"); lepResDownWepTree->Branch("out_met", &out_met, "out_met/F"); TTree *lepResDownWemTree = new TTree("LepResDownWem","lepResDownWem"); lepResDownWemTree->Branch("weight", &weight, "weight/F"); lepResDownWemTree->Branch("out_met", &out_met, "out_met/F"); TFile *infile=0; TTree *intree=0; // Read input file and get the TTrees cout << "Processing " << infilename << "..." << endl; infile = TFile::Open(infilename); assert(infile); intree = (TTree*)infile->Get("Events"); assert(intree); intree->SetBranchAddress("runNum", &runNum); // event run number intree->SetBranchAddress("lumiSec", &lumiSec); // event lumi section intree->SetBranchAddress("evtNum", &evtNum); // event number intree->SetBranchAddress("npv", &npv); // number of primary vertices intree->SetBranchAddress("npu", &npu); // number of in-time PU events (MC) intree->SetBranchAddress("genVPt", &genVPt); // GEN W boson pT (signal MC) intree->SetBranchAddress("genVPhi", &genVPhi); // GEN W boson phi (signal MC) intree->SetBranchAddress("scale1fb", &scale1fb); // event weight per 1/fb (MC) intree->SetBranchAddress("puWeight", &puWeight); // pileup reweighting intree->SetBranchAddress("mvaMet", &met); // MET intree->SetBranchAddress("mvaMetPhi",&metPhi); // phi(MET) intree->SetBranchAddress("mvaSumEt", &sumEt); // Sum ET intree->SetBranchAddress("mvaMt", &mt); // transverse mass intree->SetBranchAddress("mvaU1", &u1); // parallel component of recoil intree->SetBranchAddress("mvaU2", &u2); // perpendicular component of recoil intree->SetBranchAddress("q", &q); // lepton charge intree->SetBranchAddress("lep", &lep); // lepton 4-vector intree->SetBranchAddress("sc", &sc); // electron Supercluster 4-vector // // loop over events // for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) { intree->GetEntry(ientry); weight=scale1fb*puWeight; if(sc->Pt() < PT_CUT) continue; if(fabs(sc->Eta()) > ETA_CUT) continue; // uncorrected MET out_met = met; rawWeTree->Fill(); if(q>0) rawWepTree->Fill(); else rawWemTree->Fill(); Double_t corrMet=met, corrMetPhi=metPhi; Double_t lepPt=lep->Pt(), lepPhi=lep->Phi(); // apply recoil corrections with nominal lepton scale and resolution corrections lepPt = gRandom->Gaus(lep->Pt()*getEleScaleCorr(lep->Eta(),0), getEleResCorr(lep->Eta(),0)); recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lepPhi,0,0); out_met = corrMet; corrWeTree->Fill(); if(q>0) corrWepTree->Fill(); else corrWemTree->Fill(); // recoil corrections "up" recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lepPhi,1,0); out_met = corrMet; corrUpWeTree->Fill(); if(q>0) corrUpWepTree->Fill(); else corrUpWemTree->Fill(); // recoil corrections "down" recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lepPhi,-1,0); out_met = corrMet; corrDownWeTree->Fill(); if(q>0) corrDownWepTree->Fill(); else corrDownWemTree->Fill(); // lepton scale "up" lepPt = gRandom->Gaus(lep->Pt()*getEleScaleCorr(lep->Eta(),1), getEleResCorr(lep->Eta(),0)); recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lepPhi,0,0); out_met = corrMet; lepScaleUpWeTree->Fill(); if(q>0) lepScaleUpWepTree->Fill(); else lepScaleUpWemTree->Fill(); // lepton scale "down" lepPt = gRandom->Gaus(lep->Pt()*getEleScaleCorr(lep->Eta(),-1), getEleResCorr(lep->Eta(),0)); recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lepPhi,0,0); out_met = corrMet; lepScaleDownWeTree->Fill(); if(q>0) lepScaleDownWepTree->Fill(); else lepScaleDownWemTree->Fill(); // lepton resolution "up" lepPt = gRandom->Gaus(lep->Pt()*getEleScaleCorr(lep->Eta(),0), getEleResCorr(lep->Eta(),1)); recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lepPhi,0,0); out_met = corrMet; lepResUpWeTree->Fill(); if(q>0) lepResUpWepTree->Fill(); else lepResUpWemTree->Fill(); // lepton resolution "down" lepPt = gRandom->Gaus(lep->Pt()*getEleScaleCorr(lep->Eta(),0), TMath::Max(getEleResCorr(lep->Eta(),-1),0.0)); recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lepPhi,0,0); out_met = corrMet; lepResDownWeTree->Fill(); if(q>0) lepResDownWepTree->Fill(); else lepResDownWemTree->Fill(); } delete infile; infile=0, intree=0; //-------------------------------------------------------------------------------------------------------------- // Output //============================================================================================================== cout << "*" << endl; cout << "* SUMMARY" << endl; cout << "*--------------------------------------------------" << endl; outFile->Write(); outFile->Close(); delete outFile; cout << endl; cout << " <> Output: " << outfilename << endl; cout << endl; gBenchmark->Show("makeTemplatesWe"); }
void skimTree1::Loop() { if (fChain == 0) return; std::string remword=".root"; size_t pos = inputFile_.find(remword); std::string forOutput = inputFile_; if(pos!= std::string::npos) forOutput.swap(forOutput.erase(pos,remword.length())); std::string endfix = "_filtered.root"; std::string outputFile = forOutput + endfix; // now open new root file TFile* newfile_data = new TFile(outputFile.data(),"recreate"); // clone tree TTree* newtree = fChain->CloneTree(0); newtree->SetMaxTreeSize(5000000000); cout << "Saving " << outputFile << " tree" << endl; ofstream fout; fout.open("wrong.dat"); Long64_t nentries = fChain->GetEntriesFast(); Long64_t nPassEvt=0; Long64_t nbytes = 0, nb = 0; for (Long64_t jentry=0; jentry<nentries;jentry++) { Long64_t ientry = LoadTree(jentry); if (ientry < 0) break; nb = fChain->GetEntry(jentry); nbytes += nb; if (jentry%100==0) printf("%4.1f%% done.\r",(float)jentry/(float)nentries*100.); // require events have CA8jet pt >200 bool hasCA8jet=false; for(int i=0; i < CA8nJet; i++){ double jet_pt = CA8jetPt->at(i); if(jet_pt >200) { hasCA8jet=true; cout<<"ev: "<< jentry << " jet pt: "<<jet_pt<<endl; break; } } // end of loop over ca8 jet /* // require events have two electrons or two muons // with mass = 60-120 GeV, pt > 60 GeV if(nEle < 2 && nMu < 2)continue; bool hasDoubleEle=false; for(int i=0; i < nEle; i++){ TLorentzVector i_l4(0,0,0,0); i_l4.SetPtEtaPhiM( elePt->at(i), eleEta->at(i), elePhi->at(i), eleM->at(i) ); for(int j=0; j< i; j++){ TLorentzVector j_l4(0,0,0,0); j_l4.SetPtEtaPhiM( elePt->at(j), eleEta->at(j), elePhi->at(j), eleM->at(j) ); double Zpt = (i_l4+j_l4).Pt(); double ZM = (i_l4+j_l4).M(); if(Zpt > 60 && ZM > 60 && ZM < 120) { hasDoubleEle=true; break; } } } // end of double loop over electrons bool hasDoubleMuo=false; for(int i=0; i < nMu; i++){ TLorentzVector i_l4(0,0,0,0); i_l4.SetPtEtaPhiM( muPt->at(i), muEta->at(i), muPhi->at(i), muM->at(i) ); for(int j=0; j< i; j++){ TLorentzVector j_l4(0,0,0,0); j_l4.SetPtEtaPhiM( muPt->at(j), muEta->at(j), muPhi->at(j), muM->at(j) ); double Zpt = (i_l4+j_l4).Pt(); double ZM = (i_l4+j_l4).M(); if(Zpt > 60 && ZM > 60 && ZM < 120) { hasDoubleMuo=true; break; } } } // end of double loop over double muons if(!hasDoubleEle && !hasDoubleMuo)continue; */ if(!hasCA8jet)continue; newtree->Fill(); nPassEvt++; } // newtree->Print(); newtree->AutoSave(); delete newfile_data; fout.close(); cout << "nentries = " << nentries << endl; cout << "Number of passed events = " << nPassEvt << endl; cout << "Reduction rate = " << (double)nPassEvt/(double)nentries << endl; }
// Main macro function //-------------------------------------------------------------------------------------------------- void SkimTightPlusRecoPerFile(string inputFilename, string outputFilename) { gBenchmark->Start("SkimNtuples"); TTree::SetMaxTreeSize(kMaxLong64); mithep::MuonIDMVA *muonIDMVA = new mithep::MuonIDMVA(); muonIDMVA->Initialize("BDTG method", "/home/sixie/CMSSW_analysis/src/MitPhysics/data/MuonMVAWeights/BarrelPtBin0_IDIsoCombined_BDTG.weights.xml", "/home/sixie/CMSSW_analysis/src/MitPhysics/data/MuonMVAWeights/EndcapPtBin0_IDIsoCombined_BDTG.weights.xml", "/home/sixie/CMSSW_analysis/src/MitPhysics/data/MuonMVAWeights/BarrelPtBin1_IDIsoCombined_BDTG.weights.xml", "/home/sixie/CMSSW_analysis/src/MitPhysics/data/MuonMVAWeights/EndcapPtBin1_IDIsoCombined_BDTG.weights.xml", "/home/sixie/CMSSW_analysis/src/MitPhysics/data/MuonMVAWeights/BarrelPtBin2_IDIsoCombined_BDTG.weights.xml", "/home/sixie/CMSSW_analysis/src/MitPhysics/data/MuonMVAWeights/EndcapPtBin2_IDIsoCombined_BDTG.weights.xml", mithep::MuonIDMVA::kIDIsoCombinedDetIso); mithep::ElectronIDMVA *electronIDMVA = new mithep::ElectronIDMVA(); electronIDMVA->Initialize("BDTG method", "MitPhysics/data/ElectronMVAWeights/Subdet0LowPt_IDIsoCombined_BDTG.weights.xml", "MitPhysics/data/ElectronMVAWeights/Subdet1LowPt_IDIsoCombined_BDTG.weights.xml", "MitPhysics/data/ElectronMVAWeights/Subdet2LowPt_IDIsoCombined_BDTG.weights.xml", "MitPhysics/data/ElectronMVAWeights/Subdet0HighPt_IDIsoCombined_BDTG.weights.xml", "MitPhysics/data/ElectronMVAWeights/Subdet1HighPt_IDIsoCombined_BDTG.weights.xml", "MitPhysics/data/ElectronMVAWeights/Subdet2HighPt_IDIsoCombined_BDTG.weights.xml", mithep::ElectronIDMVA::kIDIsoCombined); // Don't write TObject part of the objects mithep::TEventInfo::Class()->IgnoreTObjectStreamer(); mithep::TMuon::Class()->IgnoreTObjectStreamer(); mithep::TElectron::Class()->IgnoreTObjectStreamer(); mithep::TJet::Class()->IgnoreTObjectStreamer(); mithep::TPhoton::Class()->IgnoreTObjectStreamer(); // Data structures to store info from TTrees mithep::TEventInfo *info = new mithep::TEventInfo(); TClonesArray *muonArr = new TClonesArray("mithep::TMuon"); TClonesArray *electronArr = new TClonesArray("mithep::TElectron"); TClonesArray *jetArr = new TClonesArray("mithep::TJet"); TClonesArray *photonArr = new TClonesArray("mithep::TPhoton"); UInt_t nInputEvts = 0; UInt_t nPassEvts = 0; UInt_t nEventsTotal = 0; TFile* outfile = new TFile(outputFilename.c_str(), "RECREATE"); // // Initialize data trees and structs // TTree *outEventTree = new TTree("Events","Events"); outEventTree->Branch("Info", &info); outEventTree->Branch("Muon", &muonArr); outEventTree->Branch("Electron", &electronArr); outEventTree->Branch("PFJet", &jetArr); outEventTree->Branch("Photon", &photonArr); cout << "Skimming " << inputFilename << "..." << endl; TTree *eventTree = getTreeFromFile(inputFilename.c_str(),"Events"); nEventsTotal += getNEvents(inputFilename.c_str()); assert(eventTree); // Set branch address to structures that will store the info eventTree->SetBranchAddress("Info", &info); TBranch *infoBr = eventTree->GetBranch("Info"); eventTree->SetBranchAddress("Muon", &muonArr); TBranch *muonBr = eventTree->GetBranch("Muon"); eventTree->SetBranchAddress("Electron", &electronArr); TBranch *electronBr = eventTree->GetBranch("Electron"); eventTree->SetBranchAddress("PFJet", &jetArr); TBranch *jetBr = eventTree->GetBranch("PFJet"); eventTree->SetBranchAddress("Photon", &photonArr); TBranch *photonBr = eventTree->GetBranch("Photon"); for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) { infoBr->GetEntry(ientry); muonArr->Clear(); muonBr->GetEntry(ientry); electronArr->Clear(); electronBr->GetEntry(ientry); jetArr->Clear(); jetBr->GetEntry(ientry); photonArr->Clear(); photonBr->GetEntry(ientry); if (ientry % 100000 == 0) cout << "Events: " << ientry << endl; nInputEvts++; Bool_t keep = kTRUE; Double_t rho = 0; if (!(TMath::IsNaN(info->PileupEnergyDensity) || isinf(info->PileupEnergyDensity))) rho = info->PileupEnergyDensity; Int_t NTightMuons = 0; Int_t NRecoMuons = 0; for(Int_t i=0; i<muonArr->GetEntries(); i++) { const mithep::TMuon *mu = (mithep::TMuon*)((*muonArr)[i]); if ( fabs(mu->eta) < 2.4 && mu->pt > 10.0 ) { NRecoMuons++; // if ( passMuonCuts(mu)) NTightMuons++; if ( passMuonMVAIDIsoCombined(mu, muonIDMVA->MVAValue( mu->pt, mu->eta, mu->tkNchi2, mu->muNchi2, mu->nValidHits, mu->nTkHits, mu->nPixHits, mu->nMatch, mu->d0, mu->ip3d, mu->ip3dSig, mu->TrkKink, mu->SegmentCompatibility, mu->CaloCompatilibity, (mu->HadEnergy - rho*MuonEffectiveArea(kMuHadEnergy,mu->eta))/mu->pt, (mu->HoEnergy - rho*MuonEffectiveArea(kMuHoEnergy,mu->eta))/mu->pt, (mu->EmEnergy - rho*MuonEffectiveArea(kMuEmEnergy,mu->eta))/mu->pt, (mu->HadS9Energy - rho*MuonEffectiveArea(kMuHadS9Energy,mu->eta))/mu->pt, (mu->HoS9Energy - rho*MuonEffectiveArea(kMuHoS9Energy,mu->eta))/mu->pt, (mu->EmS9Energy - rho*MuonEffectiveArea(kMuEmS9Energy,mu->eta))/mu->pt, (mu->trkIso03 - rho*MuonEffectiveArea(kMuTrkIso03,mu->eta))/mu->pt, (mu->emIso03 - rho*MuonEffectiveArea(kMuEMIso03,mu->eta))/mu->pt, (mu->hadIso03 - rho*MuonEffectiveArea(kMuHadIso03,mu->eta))/mu->pt, (mu->trkIso05 - rho*MuonEffectiveArea(kMuTrkIso05,mu->eta))/mu->pt, (mu->emIso05 - rho*MuonEffectiveArea(kMuEMIso05,mu->eta))/mu->pt, (mu->hadIso05 - rho*MuonEffectiveArea(kMuHadIso05,mu->eta))/mu->pt ), rho)) NTightMuons++; } } Int_t NTightElectrons = 0; Int_t NRecoElectrons = 0; for(Int_t i=0; i<electronArr->GetEntries(); i++) { const mithep::TElectron *ele = (mithep::TElectron*)((*electronArr)[i]); if ( fabs(ele->eta) < 2.5 && ele->pt > 10.0 ) { NRecoElectrons++; // if (passElectronCuts(ele)) NTightElectrons++; if (passElectronMVAIDIsoCombined(ele, electronIDMVA->MVAValue( ele->pt,ele->scEta,rho, ele->sigiEtaiEta, ele->deltaEtaIn, ele->deltaPhiIn, ele->HoverE, ele->d0, ele->dz, ele->fBrem, ele->EOverP, ele->ESeedClusterOverPout, TMath::Sqrt(ele->sigiPhiiPhi), ele->nBrem, (1.0/(ele->scEt * TMath::CosH(ele->scEta)) - 1/ele->p), ele->ESeedClusterOverPIn, ele->ip3d, ele->ip3dSig, ele->GsfTrackChi2OverNdof, ele->dEtaCalo, ele->dPhiCalo, ele->R9, ele->SCEtaWidth, ele->SCPhiWidth, ele->CovIEtaIPhi, ele->PreShowerOverRaw, ele->ChargedIso03, (ele->NeutralHadronIso03_05Threshold - ele->NeutralHadronIso007_05Threshold), (ele->GammaIso03_05Threshold - ele->GammaIsoVetoEtaStrip03_05Threshold), ele->ChargedIso04 , (ele->NeutralHadronIso04_05Threshold - ele->NeutralHadronIso007_05Threshold), (ele->GammaIso04_05Threshold - ele->GammaIsoVetoEtaStrip04_05Threshold) ), 0)) NTightElectrons++; } } //One Tight AND Two Loose if (!( NTightElectrons + NTightMuons >= 1 && NRecoElectrons + NRecoMuons >= 2 ) ) { keep = kFALSE; } if(keep) { outEventTree->Fill(); nPassEvts++; } } outfile->Write(); outfile->Close(); delete info; delete muonArr; delete electronArr; delete jetArr; std::cout << outputFilename << " created!" << std::endl; std::cout << " >>> Total Number of Events: " << nEventsTotal << std::endl; std::cout << " >>> Events processed: " << nInputEvts << std::endl; std::cout << " >>> Events passing: " << nPassEvts << std::endl; gBenchmark->Show("SkimNtuples"); }
// fills event data into correct mass bin bool writeEvent(vector<TTree*>& pwaTrees, const TLorentzVector& beamLv, // !!! <channel-dependent part> !!! const TLorentzVector& piZero0, const TLorentzVector& piZero1, const TLorentzVector& piMinus, // !!! </channel-dependent part> !!! const double XMass, // [GeV/c^2] const unsigned int nmbMassBins = 50, const double massBinWidth = 50, // [MeV/c^2] const double massRangeMin = 500, // [MeV/c^2] const string& prodKinMomentaLeafName = "prodKinMomenta", const string& decayKinMomentaLeafName = "decayKinMomenta", const bool debug = false) { const double mass = 1000 * XMass; // convert from GeV/c^2 to MeV/c^2 // make sure that mass is in range if ((mass < massRangeMin) or (mass > (massRangeMin + nmbMassBins * massBinWidth))) return false; const unsigned int bin = (unsigned int) ((mass - massRangeMin) / massBinWidth); if (not pwaTrees[bin]) { printWarn << "null pointer for tree for mass bin [" << massRangeMin + bin * massBinWidth << ", " << massRangeMin + (bin + 1) * massBinWidth << "]" << endl; return false; } // fill tree if (debug) printDebug << "filling tree for bin " << bin << " = [" << massRangeMin + bin * massBinWidth << ", " << massRangeMin + (bin + 1) * massBinWidth << "] MeV/c^2" << endl; // create tree leafs static TClonesArray* prodKinMomenta = new TClonesArray("TVector3"); static TClonesArray* decayKinMomenta = new TClonesArray("TVector3"); // connect leaf variables to tree branches or create branches, if they don't exist yet TTree* outTree = pwaTrees[bin]; if (outTree->SetBranchAddress(prodKinMomentaLeafName.c_str(), &prodKinMomenta) < 0) { printWarn << "could not connect variable to branch '" << prodKinMomentaLeafName << "'. " << "skipping." << endl; return false; } if (outTree->SetBranchAddress(decayKinMomentaLeafName.c_str(), &decayKinMomenta) < 0) { printWarn << "could not connect variable to branch '" << prodKinMomentaLeafName << "'. " << "skipping." << endl; return false; } // clear arrays prodKinMomenta->Clear (); decayKinMomenta->Clear(); // set leaf variables // beam particle new ((*prodKinMomenta)[0]) TVector3(beamLv.Vect()); // !!! <channel-dependent part> !!! // for target particle elastic scattering is assumed // outgoing hadrons new ((*decayKinMomenta)[0]) TVector3(piZero0.Vect()); new ((*decayKinMomenta)[1]) TVector3(piZero1.Vect()); new ((*decayKinMomenta)[2]) TVector3(piMinus.Vect()); // !!! </channel-dependent part> !!! // fill tree outTree->Fill(); return true; }
TTree* execute() { // q is simply a prefix for values which are a branch on the TTree TTree * dataTree = new TTree("treeData", "treeData"); float qChargeValues[7]; float qTotalCharge; float qMeasurementTimes[7]; float qCurrentValues[7]; float qVoltageValuesPreNoise[7]; float qVoltageValuesPostNoise[7]; int qDigitalReadoutValues[7]; float qFitShiftingTime; float qFitScalingFactor; int qTotalDigitalReadoutValue; int qDifferenceDigitalReadoutValue; float qIntegralReadoutValue; dataTree->Branch("qChargeValues", qChargeValues, "qChargeValues[7]/F"); dataTree->Branch("qTotalCharge", &qTotalCharge, "qTotalCharge/F"); dataTree->Branch("qMeasurementTimes", qMeasurementTimes, "qMeasurementTimes[7]/F"); dataTree->Branch("qCurrentValues", qCurrentValues, "qCurrentValues[7]/F"); dataTree->Branch("qVoltageValuesPreNoise", qVoltageValuesPreNoise, "qVoltageValuesPreNoise[7]/F"); dataTree->Branch("qVoltageValuesPostNoise", qVoltageValuesPostNoise, "qVoltageValuesPostNoise[7]/F"); dataTree->Branch("qDigitalReadoutValues", qDigitalReadoutValues, "qDigitalReadoutValues[7]/I"); dataTree->Branch("qFitShiftingTime", &qFitShiftingTime, "qFitShiftingTime/F"); dataTree->Branch("qFitScalingFactor", &qFitScalingFactor, "qFitScalingFactor/F"); dataTree->Branch("qTotalDigitalReadoutValue", &qTotalDigitalReadoutValue, "qTotalDigitalReadoutValue/I"); dataTree->Branch("qDifferenceDigitalReadoutValue", &qDifferenceDigitalReadoutValue, "qDifferenceDigitalReadoutValue/I"); dataTree->Branch("qIntegralReadoutValue", &qIntegralReadoutValue, "qIntegralReadoutValue/F"); const int numTrials = 10000; // Set number of trials const float shapingTime = 40.0; const float shapingPower = 1.0; ElectronSimulation * eSim = new ElectronSimulation(); for (int i = 0; i < numTrials; ++i) { TrialDataSet eSimData; eSim->simulate(eSimData, shapingTime, shapingPower); qTotalCharge = sumArray(eSimData.chargeValues, 7); qTotalDigitalReadoutValue = sumArray(eSimData.digitalReadoutValues, 7); qDifferenceDigitalReadoutValue = maxArray(eSimData.digitalReadoutValues, 7) - eSimData.digitalReadoutValues[0]; TF1 * fittedFunction = eSim->computeFunctionFit(eSimData); qFitShiftingTime = fittedFunction->GetParameter(0); qFitScalingFactor = fittedFunction->GetParameter(1); qIntegralReadoutValue = eSim->integrateFunc(qFitScalingFactor); fittedFunction->Draw(); for (int j = 0; j<7; ++j) { qChargeValues[j] = eSimData.chargeValues[j]; qMeasurementTimes[j] = eSimData.measurementTimes[j]; qCurrentValues[j] = eSimData.currentValues[j]; qVoltageValuesPreNoise[j] = eSimData.voltageValuesPreNoise[j]; qVoltageValuesPostNoise[j] = eSimData.voltageValuesPostNoise[j]; qDigitalReadoutValues[j] = eSimData.digitalReadoutValues[j]; } dataTree->Fill(); } return dataTree; }
void L1JetEmulator(TString forest_input = "/mnt/hadoop/cms/store/user/luck/L1Emulator/HydjetMB_502TeV_740pre8_MCHI2_74_V3_HiForestAndEmulator_v5.root", TString outFileName = "Hydjet502_JetResults.root") { std::cout << "Processing file: " << forest_input << std::endl; std::cout << "Saving to: " << outFileName << std::endl; L1EmulatorSimulator::cand regions[396]; // ************ this block makes regions out of towers const int nEta = 22; const int nPhi = 18; TChain *fTowerTree = new TChain("rechitanalyzer/tower","fTowerTree"); TChain *fEvtTree = new TChain("hiEvtAnalyzer/HiTree","fEvtTree"); fTowerTree->Add(forest_input); fEvtTree->Add(forest_input); TChain *l1Tree = new TChain("L1UpgradeAnalyzer/L1UpgradeTree","l1Tree"); l1Tree->Add(forest_input); TChain *fSkimTree = new TChain("skimanalysis/HltTree"); fSkimTree->Add(forest_input); Int_t l1_event, l1_run, l1_lumi; Int_t region_hwPtOriginal[396], region_hwEtaOriginal[396], region_hwPhiOriginal[396]; l1Tree->SetBranchAddress("event",&l1_event); l1Tree->SetBranchAddress("lumi",&l1_lumi); l1Tree->SetBranchAddress("run",&l1_run); l1Tree->SetBranchAddress("region_hwPt", region_hwPtOriginal); l1Tree->SetBranchAddress("region_hwEta", region_hwEtaOriginal); l1Tree->SetBranchAddress("region_hwPhi", region_hwPhiOriginal); Int_t f_evt, f_run, f_lumi,f_pcollisionEventSelection,f_pHBHENoiseFilter; fEvtTree->SetBranchAddress("evt",&f_evt); fEvtTree->SetBranchAddress("run",&f_run); fEvtTree->SetBranchAddress("lumi",&f_lumi); fSkimTree->SetBranchAddress("pcollisionEventSelection",&f_pcollisionEventSelection); fSkimTree->SetBranchAddress("pHBHENoiseFilter",&f_pHBHENoiseFilter); Int_t f_nTow = -1; Float_t f_eta[10000]; Float_t f_phi[10000]; Float_t f_et[10000]; fTowerTree->SetBranchAddress("eta" , &f_eta); fTowerTree->SetBranchAddress("phi" , &f_phi); fTowerTree->SetBranchAddress("et" , &f_et); fTowerTree->SetBranchAddress("n" , &f_nTow); Double_t rctEtaMap[23] = {-5.100, -4.500, -4.000, -3.500, -3.000, -2.172, -1.740, -1.392, -1.044, -0.696, -0.348, 0.000, 0.348, 0.696, 1.044, 1.392, 1.740, 2.172, 3.000, 3.500, 4.000, 4.500, 5.10}; Double_t rctPhiMap[20] = {-1*TMath::Pi(), -2.967060, -2.617990, -2.268930, -1.919860, -1.570800, -1.221730, -0.872665, -0.523599, -0.174533, 0.174533, 0.523599, 0.872665, 1.221730, 1.570800, 1.919860, 2.268930, 2.617990, 2.96706, TMath::Pi()}; TH2F* hFtmp = new TH2F("Ftmp", "F_tmp" , nEta , rctEtaMap, nPhi+1, rctPhiMap); TH2F* hFtmpReb = new TH2F("FtmpReb", "F_tmpReb", nEta , 0, nEta , nPhi , 0, nPhi); // ********************************************** TFile *outFile = TFile::Open(outFileName,"RECREATE"); TTree *outTree = new TTree("L1UpgradeTree","L1UpgradeTree"); Int_t run, lumi, evt,pcollisionEventSelection,pHBHENoiseFilter; Int_t region_hwPt_[396], region_hwPhi_[396], region_hwEta_[396]; Int_t region_hwPtOriginal_[396], region_hwPhiOriginal_[396], region_hwEtaOriginal_[396]; outTree->Branch("run",&run,"run/I"); outTree->Branch("lumi",&lumi,"lumi/I"); outTree->Branch("event",&evt,"event/I"); outTree->Branch("pcollisionEventSelection",&pcollisionEventSelection,"pcollisionEventSelection/I"); outTree->Branch("pHBHENoiseFilter",&pHBHENoiseFilter,"pHBHENoiseFilter/I"); outTree->Branch("region_hwPt",region_hwPt_,"region_hwPt[396]/I"); outTree->Branch("region_hwPhi",region_hwPhi_,"region_hwPhi[396]/I"); outTree->Branch("region_hwEta",region_hwEta_,"region_hwEta[396]/I"); outTree->Branch("region_hwPtOriginal",region_hwPtOriginal_,"region_hwPtOriginal[396]/I"); outTree->Branch("region_hwPhiOriginal",region_hwPhiOriginal_,"region_hwPhiOriginal[396]/I"); outTree->Branch("region_hwEtaOriginal",region_hwEtaOriginal_,"region_hwEtaOriginal[396]/I"); Long64_t l_entries = fTowerTree->GetEntries(); for(Long64_t j = 0; j < l_entries; ++j) { fTowerTree->GetEntry(j); fEvtTree->GetEntry(j); l1Tree->GetEntry(j); for (int i=0;i<396;i++){ region_hwPtOriginal_[i]=region_hwPtOriginal[i]; region_hwPhiOriginal_[i]=region_hwPhiOriginal[i]; region_hwEtaOriginal_[i]=region_hwEtaOriginal[i]; } run = f_run; evt = f_evt; lumi = f_lumi; pcollisionEventSelection=(int)(f_pcollisionEventSelection); pHBHENoiseFilter=(int)(f_pHBHENoiseFilter); for(int itow = 0; itow < f_nTow; ++itow) { hFtmp->Fill(f_eta[itow], f_phi[itow], f_et[itow]); } for(int ieta = 0; ieta < nEta; ++ieta) { double content = 0.; for(int iphi = 0; iphi < nPhi; ++iphi) { if(iphi == 0 ) content = hFtmp->GetBinContent(ieta+1,1) + hFtmp->GetBinContent(ieta+1,19); else content = hFtmp->GetBinContent(ieta+1,iphi+1); if(iphi < 9) hFtmpReb->SetBinContent(ieta+1, iphi+10, content); else if(iphi >= 9 && iphi < 18) hFtmpReb->SetBinContent(ieta+1, iphi-8, content); } } int nReg = 0; for(int ieta = 0; ieta < nEta; ++ieta) { for(int iphi = 0; iphi < nPhi; ++iphi) { regions[nReg].pt = hFtmpReb->GetBinContent(ieta+1, iphi+1) * 2.0; regions[nReg].eta = ieta; regions[nReg].phi = iphi; region_hwPt_[nReg] = regions[nReg].pt; region_hwEta_[nReg] = regions[nReg].eta; region_hwPhi_[nReg] = regions[nReg].phi; nReg++; } } hFtmpReb->Reset(); hFtmp->Reset(); outTree->Fill(); } outTree->Write(); //lFile->Close(); outFile->Close(); }
int Proto2ShowerCalib::process_event(PHCompositeNode *topNode) { if (verbosity > 2) cout << "Proto2ShowerCalib::process_event() entered" << endl; // init eval objects _eval_run.reset(); _shower.reset(); Fun4AllHistoManager *hm = get_HistoManager(); assert(hm); PdbParameterMap *info = findNode::getClass<PdbParameterMap>(topNode, "RUN_INFO"); //if(!_is_sim) assert(info); if(info) { PHParameters run_info_copy("RunInfo"); run_info_copy.FillFrom(info); _eval_run.beam_mom = run_info_copy.get_double_param("beam_MTNRG_GeV"); TH1F * hBeam_Mom = dynamic_cast<TH1F *>(hm->getHisto("hBeam_Mom")); assert(hBeam_Mom); hBeam_Mom->Fill(_eval_run.beam_mom); } EventHeader* eventheader = findNode::getClass<EventHeader>(topNode, "EventHeader"); //if(!_is_sim) assert(eventheader); if( eventheader ) { _eval_run.run = eventheader->get_RunNumber(); if (verbosity > 4) cout << __PRETTY_FUNCTION__ << _eval_run.run << endl; _eval_run.event = eventheader->get_EvtSequence(); } // normalization TH1F * hNormalization = dynamic_cast<TH1F *>(hm->getHisto("hNormalization")); assert(hNormalization); hNormalization->Fill("ALL", 1); // other nodes RawTowerContainer* TOWER_CALIB_TRIGGER_VETO = findNode::getClass< RawTowerContainer>(topNode, "TOWER_CALIB_TRIGGER_VETO"); //if(!_is_sim) assert(TOWER_CALIB_TRIGGER_VETO); RawTowerContainer* TOWER_CALIB_HODO_HORIZONTAL = findNode::getClass< RawTowerContainer>(topNode, "TOWER_CALIB_HODO_HORIZONTAL"); //if(!_is_sim) assert(TOWER_CALIB_HODO_HORIZONTAL); RawTowerContainer* TOWER_CALIB_HODO_VERTICAL = findNode::getClass< RawTowerContainer>(topNode, "TOWER_CALIB_HODO_VERTICAL"); //if(!_is_sim) assert(TOWER_CALIB_HODO_VERTICAL); RawTowerContainer* TOWER_RAW_CEMC; if(!_is_sim) { TOWER_RAW_CEMC = findNode::getClass<RawTowerContainer>( topNode, "TOWER_RAW_CEMC"); }else{ TOWER_RAW_CEMC = findNode::getClass<RawTowerContainer>( topNode, "TOWER_RAW_LG_CEMC"); } assert(TOWER_RAW_CEMC); RawTowerContainer* TOWER_CALIB_CEMC; if(!_is_sim) { TOWER_CALIB_CEMC = findNode::getClass<RawTowerContainer>( topNode, "TOWER_CALIB_CEMC"); } else { TOWER_CALIB_CEMC = findNode::getClass<RawTowerContainer>( topNode, "TOWER_CALIB_LG_CEMC"); } assert(TOWER_CALIB_CEMC); RawTowerContainer* TOWER_RAW_LG_HCALIN = 0; RawTowerContainer* TOWER_RAW_HG_HCALIN = 0; if(!_is_sim) { TOWER_RAW_LG_HCALIN = findNode::getClass<RawTowerContainer>( topNode, "TOWER_RAW_LG_HCALIN"); TOWER_RAW_HG_HCALIN= findNode::getClass<RawTowerContainer>( topNode, "TOWER_RAW_HG_HCALIN"); assert(TOWER_RAW_LG_HCALIN); assert(TOWER_RAW_HG_HCALIN); } RawTowerContainer* TOWER_CALIB_HCALIN; if(!_is_sim) { TOWER_CALIB_HCALIN = findNode::getClass<RawTowerContainer>( topNode, "TOWER_CALIB_LG_HCALIN"); } else { TOWER_CALIB_HCALIN = findNode::getClass<RawTowerContainer>( topNode, "TOWER_CALIB_LG_HCALIN"); } assert(TOWER_CALIB_HCALIN); RawTowerContainer* TOWER_RAW_LG_HCALOUT = 0; RawTowerContainer* TOWER_RAW_HG_HCALOUT = 0; if(!_is_sim) { TOWER_RAW_LG_HCALOUT = findNode::getClass<RawTowerContainer>( topNode, "TOWER_RAW_LG_HCALOUT"); TOWER_RAW_HG_HCALOUT = findNode::getClass<RawTowerContainer>( topNode, "TOWER_RAW_HG_HCALOUT"); assert(TOWER_RAW_LG_HCALOUT); assert(TOWER_RAW_HG_HCALOUT); } RawTowerContainer* TOWER_CALIB_HCALOUT = findNode::getClass<RawTowerContainer>( topNode, "TOWER_CALIB_LG_HCALOUT"); assert(TOWER_CALIB_HCALOUT); RawTowerContainer* TOWER_TEMPERATURE_EMCAL = findNode::getClass< RawTowerContainer>(topNode, "TOWER_TEMPERATURE_EMCAL"); if(!_is_sim) assert(TOWER_TEMPERATURE_EMCAL); RawTowerContainer* TOWER_CALIB_C1 = findNode::getClass<RawTowerContainer>( topNode, "TOWER_CALIB_C1"); //if(!_is_sim) assert(TOWER_CALIB_C1); RawTowerContainer* TOWER_CALIB_C2 = findNode::getClass<RawTowerContainer>( topNode, "TOWER_CALIB_C2"); //if(!_is_sim) assert(TOWER_CALIB_C2); if(!_is_sim && TOWER_CALIB_C2 && TOWER_CALIB_C1 && eventheader) { // Cherenkov RawTower * t_c2_in = NULL; RawTower * t_c2_out = NULL; if (eventheader->get_RunNumber() >= 2105) { t_c2_in = TOWER_CALIB_C2->getTower(10); t_c2_out = TOWER_CALIB_C2->getTower(11); } else { t_c2_in = TOWER_CALIB_C2->getTower(0); t_c2_out = TOWER_CALIB_C2->getTower(1); } assert(t_c2_in); assert(t_c2_out); const double c2_in = t_c2_in->get_energy(); const double c2_out = t_c2_out->get_energy(); const double c1 = TOWER_CALIB_C1->getTower(0)->get_energy(); _eval_run.C2_sum = c2_in + c2_out; _eval_run.C1 = c1; bool cherekov_e = (_eval_run.C2_sum) > 100; hNormalization->Fill("C2-e", cherekov_e); bool cherekov_h = (_eval_run.C2_sum) < 20; hNormalization->Fill("C2-h", cherekov_h); TH2F * hCheck_Cherenkov = dynamic_cast<TH2F *>(hm->getHisto( "hCheck_Cherenkov")); assert(hCheck_Cherenkov); hCheck_Cherenkov->Fill(c1, "C1", 1); hCheck_Cherenkov->Fill(c2_in, "C2 in", 1); hCheck_Cherenkov->Fill(c2_out, "C2 out", 1); hCheck_Cherenkov->Fill(c2_in + c2_out, "C2 sum", 1); // veto TH1F * hCheck_Veto = dynamic_cast<TH1F *>(hm->getHisto("hCheck_Veto")); assert(hCheck_Veto); bool trigger_veto_pass = true; { auto range = TOWER_CALIB_TRIGGER_VETO->getTowers(); for (auto it = range.first; it != range.second; ++it) { RawTower* tower = it->second; assert(tower); hCheck_Veto->Fill(tower->get_energy()); if (abs(tower->get_energy()) > 15) trigger_veto_pass = false; } } hNormalization->Fill("trigger_veto_pass", trigger_veto_pass); _eval_run.trigger_veto_pass = trigger_veto_pass; // hodoscope TH1F * hCheck_Hodo_H = dynamic_cast<TH1F *>(hm->getHisto("hCheck_Hodo_H")); assert(hCheck_Hodo_H); int hodo_h_count = 0; { auto range = TOWER_CALIB_HODO_HORIZONTAL->getTowers(); for (auto it = range.first; it != range.second; ++it) { RawTower* tower = it->second; assert(tower); hCheck_Hodo_H->Fill(tower->get_energy()); if (abs(tower->get_energy()) > 30) { hodo_h_count++; _eval_run.hodo_h = tower->get_id(); } } } const bool valid_hodo_h = hodo_h_count == 1; hNormalization->Fill("valid_hodo_h", valid_hodo_h); _eval_run.valid_hodo_h = valid_hodo_h; TH1F * hCheck_Hodo_V = dynamic_cast<TH1F *>(hm->getHisto("hCheck_Hodo_V")); assert(hCheck_Hodo_V); int hodo_v_count = 0; { auto range = TOWER_CALIB_HODO_VERTICAL->getTowers(); for (auto it = range.first; it != range.second; ++it) { RawTower* tower = it->second; assert(tower); hCheck_Hodo_V->Fill(tower->get_energy()); if (abs(tower->get_energy()) > 30) { hodo_v_count++; _eval_run.hodo_v = tower->get_id(); } } } const bool valid_hodo_v = hodo_v_count == 1; _eval_run.valid_hodo_v = valid_hodo_v; hNormalization->Fill("valid_hodo_v", valid_hodo_v); const bool good_e = valid_hodo_v and valid_hodo_h and cherekov_e and trigger_veto_pass; const bool good_h = valid_hodo_v and valid_hodo_h and cherekov_h and trigger_veto_pass; hNormalization->Fill("good_e", good_e); hNormalization->Fill("good_h", good_h); _eval_run.good_temp = 1; _eval_run.good_e = good_e; _eval_run.good_h = good_h; } // tower double emcal_sum_energy_calib = 0; double emcal_sum_energy_recalib = 0; double hcalin_sum_energy_calib = 0; double hcalin_sum_energy_recalib = 0; double hcalout_sum_energy_calib = 0; double hcalout_sum_energy_recalib = 0; stringstream sdata; //EMCAL towers { auto range = TOWER_CALIB_CEMC->getTowers(); for (auto it = range.first; it != range.second; ++it) { //RawTowerDefs::keytype key = it->first; RawTower* tower = it->second; assert(tower); const double energy_calib = tower->get_energy(); emcal_sum_energy_calib += energy_calib; if(_is_sim) continue; const int col = tower->get_column(); const int row = tower->get_row(); // recalibration assert( _emcal_recalib_const.find(make_pair(col, row)) != _emcal_recalib_const.end()); const double energy_recalib = energy_calib * _emcal_recalib_const[make_pair(col, row)]; // energy sums emcal_sum_energy_recalib += energy_recalib; } } //HCALIN towers { auto range = TOWER_CALIB_HCALIN->getTowers(); for (auto it = range.first; it != range.second; ++it) { RawTower* tower = it->second; assert(tower); const double energy_calib = tower->get_energy(); hcalin_sum_energy_calib += energy_calib; if(_is_sim) continue; const int col = tower->get_column(); const int row = tower->get_row(); assert( _hcalin_recalib_const.find(make_pair(col, row)) != _hcalin_recalib_const.end()); const double energy_recalib = energy_calib * _hcalin_recalib_const[make_pair(col, row)]; hcalin_sum_energy_recalib += energy_recalib; } } //HCALOUT towers { auto range = TOWER_CALIB_HCALOUT->getTowers(); for (auto it = range.first; it != range.second; ++it) { RawTower* tower = it->second; assert(tower); const double energy_calib = tower->get_energy(); hcalout_sum_energy_calib += energy_calib; if(_is_sim) continue; const int col = tower->get_column(); const int row = tower->get_row(); assert( _hcalout_recalib_const.find(make_pair(col, row)) != _hcalout_recalib_const.end()); const double energy_recalib = energy_calib * _hcalout_recalib_const[make_pair(col, row)]; hcalout_sum_energy_recalib += energy_recalib; } } const double EoP = emcal_sum_energy_recalib / abs(_eval_run.beam_mom); _eval_run.EoP = EoP; // E/p if (_eval_run.good_e) { if (verbosity >= 3) cout << __PRETTY_FUNCTION__ << " sum_energy_calib = " << emcal_sum_energy_calib << " sum_energy_recalib = " << emcal_sum_energy_recalib << " _eval_run.beam_mom = " << _eval_run.beam_mom << endl; TH2F * hEoP = dynamic_cast<TH2F *>(hm->getHisto("hEoP")); assert(hEoP); hEoP->Fill(EoP, abs(_eval_run.beam_mom)); } // calibration file assert(fdata.is_open()); fdata << sdata.str(); fdata << endl; _shower.emcal_e = emcal_sum_energy_calib; _shower.hcalin_e = hcalin_sum_energy_calib; _shower.hcalout_e = hcalout_sum_energy_calib; _shower.sum_e = emcal_sum_energy_calib + hcalin_sum_energy_calib + hcalout_sum_energy_calib ; _shower.hcal_asym = (hcalin_sum_energy_calib - hcalout_sum_energy_calib)/(hcalin_sum_energy_calib + hcalout_sum_energy_calib); _shower.emcal_e_recal = emcal_sum_energy_recalib; _shower.hcalin_e_recal = hcalin_sum_energy_recalib; _shower.hcalout_e_recal = hcalout_sum_energy_recalib; _shower.sum_e_recal = emcal_sum_energy_recalib + hcalin_sum_energy_recalib + hcalout_sum_energy_recalib ; if(_fill_time_samples && !_is_sim) { //HCALIN { auto range = TOWER_RAW_LG_HCALIN->getTowers(); for (auto it = range.first; it != range.second; ++it) { RawTower_Prototype2* tower = dynamic_cast<RawTower_Prototype2 *>(it->second); assert(tower); int col = tower->get_column(); int row = tower->get_row(); int towerid = row + 4*col; for(int isample=0; isample<24; isample++) _time_samples.hcalin_time_samples[towerid][isample] = tower->get_signal_samples(isample); } } //HCALOUT { auto range = TOWER_RAW_LG_HCALOUT->getTowers(); for (auto it = range.first; it != range.second; ++it) { RawTower_Prototype2* tower = dynamic_cast<RawTower_Prototype2 *>(it->second); assert(tower); int col = tower->get_column(); int row = tower->get_row(); int towerid = row + 4*col; for(int isample=0; isample<24; isample++) _time_samples.hcalout_time_samples[towerid][isample] = tower->get_signal_samples(isample); } } //EMCAL { auto range = TOWER_RAW_CEMC->getTowers(); for (auto it = range.first; it != range.second; ++it) { RawTower_Prototype2* tower = dynamic_cast<RawTower_Prototype2 *>(it->second); assert(tower); int col = tower->get_column(); int row = tower->get_row(); int towerid = row + 8*col; for(int isample=0; isample<24; isample++) _time_samples.emcal_time_samples[towerid][isample] = tower->get_signal_samples(isample); } } } TTree * T = dynamic_cast<TTree *>(hm->getHisto("T")); assert(T); T->Fill(); return Fun4AllReturnCodes::EVENT_OK; }
int getSimulatedDigits(TString digitdir) { AliRunLoader *rl = AliRunLoader::Open(digitdir+TString("/galice.root")); AliPHOSLoader *prl = (AliPHOSLoader*)rl->GetDetectorLoader("PHOS"); prl->LoadSDigits(); prl->LoadDigits(); Int_t nSimEvents = rl->GetNumberOfEvents(); TFile *mydigitsFile = new TFile("mydigits.root", "RECREATE"); TTree *mydigitTree = new TTree("mydigitTree", "mydigitTree"); TClonesArray * mydigits = new TClonesArray(AliPHOSDigit::Class()); mydigitTree->Branch("Digits", &mydigits); for (Int_t ev = 0; ev < nSimEvents; ev++) { rl->GetEvent(ev); Int_t nPhosDigits = prl->SDigits()->GetEntries(); Int_t nDigsFound = 0; for (Int_t iDig = 0; iDig < nPhosDigits; iDig++) { const AliPHOSDigit *digit = prl->SDigit(iDig); Int_t id = digit->GetId(); if (id > 3*geom->GetNPhi()*geom->GetNZ()) continue; for (Int_t n = 0; n < nDigsFound; n++) { AliPHOSDigit *tmpDig = (AliPHOSDigit*)mydigits->At(n); if (id == tmpDig->GetId()) { *tmpDig += *digit; digit = 0; break; } } if (digit) { AliPHOSDigit *newDig = new((*mydigits)[nDigsFound]) AliPHOSDigit(-1, id, (float)0.0, (float)0.0); *newDig += *digit; nDigsFound++; } } for(int i = 0; i <nDigsFound; i++) { AliPHOSDigit *tmpDig = (AliPHOSDigit*)mydigits->At(i); Int_t relId[4]; geom->AbsToRelNumbering(tmpDig->GetId(), relId); // Some necessary ugly hacks needed at the moment, need to get these numbers from OCDB tmpDig->SetEnergy((float)((int)(tmpDig->GetEnergy()/phosCalibData->GetADCchannelEmc(relId[0], relId[3], relId[2])))); //std::cout << "Sample time step: " << phosCalibData->GetSampleTimeStep() << " " << phosCalibData->GetTimeShiftEmc(relId[0], relId[3], relId[2]) << geom << std::endl; tmpDig->SetTime(1.5e-8); tmpDig->SetTimeR(1.5e-8); } mydigitTree->Fill(); mydigits->Clear("C"); } mydigitsFile->Write(); simTree = mydigitTree; //mydigit //mydigitsFile->Close(); return 0; }
void testZeeMCSmearWithScale(string datareco = "jan16 or nov30",int phtcorr = 231, int test_fitdet= 1, string test_smearmethod = "corrSmear or uncorrSmear",string test_fitmethod = "lh or lhpoisson",int fixscale = 0,int fitstra = 1, int testpaircat=0, double test_fitlow = 70, double test_fithigh = 110, double test_binwidth = 1.0){ int phtcorr_test = phtcorr; if( phtcorr_test == 486){ phtcorr = 485; } fitdet = test_fitdet; smearMethod = test_smearmethod ; testOnlyCat = testpaircat; fitrangeLow = test_fitlow; fitrangeHigh = test_fithigh; binwidth = test_binwidth; fitmethod = test_fitmethod; gStyle->SetOptStat(0); gStyle->SetNdivisions(508,"X"); gStyle->SetNdivisions(512,"Y"); int mc = 1; fillMapIndex(); TString filename; fChainMC = new TChain("Analysis"); fChainData = new TChain("Analysis"); string dataset; int iflag = 2; if( datareco == "nov30"){ iflag = 1; dataset = "DoubleElectronRun2011AB30Nov2011v1AOD"; }else if( datareco == "jan16"){ iflag = 2; dataset = "DoubleElectronRun2011AB16Jan2012v1AOD"; }else{ cout<<"dataset ? " << datareco.c_str()<<endl; return; } ///MC filename = TString(Form("/home/raid2/yangyong/data/CMSSW/v1/CMSSW_4_2_8/src/zSelector/dielectrontree/makeDiElectronTree.v3.DYJetsToLL_TuneZ2_M50_7TeVmadgraphtauolaFall11PU_S6_START42_V14Bv1AODSIMallstat.etcut20.corr%d.eleid1.datapu6.mcpu1.r1to92.scale0.root",phtcorr)); cout<<filename<<endl; fChainMC->Add(filename); //fChainMC->SetBranchAddress("isRealData", &isRealData); fChainMC->SetBranchAddress("elescr9", elescr9); fChainMC->SetBranchAddress("elesceta", elesceta); fChainMC->SetBranchAddress("eleen", eleen); //fChainMC->SetBranchAddress("eleen0", eleen0); fChainMC->SetBranchAddress("mpair", &mpair); // fChainMC->SetBranchAddress("mpair0", &mpair0); fChainMC->SetBranchAddress("eleeta", eleeta); fChainMC->SetBranchAddress("eleieta", eleieta); fChainMC->SetBranchAddress("eleiphi", eleiphi); fChainMC->SetBranchAddress("runNumber", &runNumber); fChainMC->SetBranchAddress("evtNumber", &evtNumber); fChainMC->SetBranchAddress("lumiBlock", &lumiBlock); fChainMC->SetBranchAddress("eleetrue", eleetrue); // fChainMC->SetBranchAddress("eleetruenofsr", eleetruenofsr); // fChainMC->SetBranchAddress("eleetrueplusfsrdrbc003", eleetrueplusfsrdrbc003); // fChainMC->SetBranchAddress("eleetrueplusfsrdrbc004", eleetrueplusfsrdrbc004); fChainMC->SetBranchAddress("eleetrueplusfsrdrbc005", eleetrueplusfsrdrbc005); // fChainMC->SetBranchAddress("eleetrueplusfsrdrbc006", eleetrueplusfsrdrbc006); // fChainMC->SetBranchAddress("eleetrueplusfsrdrbc007", eleetrueplusfsrdrbc007); // fChainMC->SetBranchAddress("eleetrueplusfsrdrbc008", eleetrueplusfsrdrbc008); // fChainMC->SetBranchAddress("eleetrueplusfsrdrbc009", eleetrueplusfsrdrbc009); fChainMC->SetBranchAddress("eleetrueplusfsrdrbc01", eleetrueplusfsrdrbc01); // fChainMC->SetBranchAddress("eletrueelematched", eletrueelematched); // fChainMC->SetBranchAddress("eletrueelematchednofsr", eletrueelematchednofsr); fChainMC->SetBranchAddress("weight", &weight); //Data filename = TString(Form("/home/raid2/yangyong/data/CMSSW/v1/CMSSW_4_2_8/src/zSelector/dielectrontree/makeDiElectronTree.v3.%s.etcut20.corr%d.eleid1.datapu0.mcpu0.r1to131.scale0.root",dataset.c_str(),phtcorr)); cout<<filename<<endl; fChainData->Add(filename); fChainData->SetBranchAddress("isRealData", &isRealData); fChainData->SetBranchAddress("elescr9", elescr9); fChainData->SetBranchAddress("elesceta", elesceta); fChainData->SetBranchAddress("eleen", eleen); fChainData->SetBranchAddress("eleen0", eleen0); fChainData->SetBranchAddress("mpair", &mpair); fChainData->SetBranchAddress("mpair0", &mpair0); fChainData->SetBranchAddress("eleeta", eleeta); fChainData->SetBranchAddress("eleieta", eleieta); fChainData->SetBranchAddress("eleiphi", eleiphi); fChainData->SetBranchAddress("runNumber", &runNumber); fChainData->SetBranchAddress("evtNumber", &evtNumber); fChainData->SetBranchAddress("lumiBlock", &lumiBlock); NMC = fChainMC->GetEntries(); NData = fChainData->GetEntries(); cout<<"nMC " << NMC <<" "<< NData <<endl; filename = TString(Form("testZeeMCSmearWithScale.%s.%s.%s.testpair%d.fitrange%dto%d.binwidth%2.2f.fitdet%d.corr%d.fitstra%d.fixscale%d.etcut%d.root",datareco.c_str(),test_smearmethod.c_str(),test_fitmethod.c_str(),testpaircat,int(fitrangeLow+0.1),int(fitrangeHigh+0.1),binwidth,fitdet,phtcorr_test,fitstra,fixscale,etcut)); TFile *fnew = new TFile(filename,"recreate"); //filename = TString(Form("testZeeMCSmearWithScale.%s.%s.%s.testpair%d.fitrange%dto%d.binwidth%2.2f.fitdet%d.corr%d.fitstra%d.fixscale%d.etcut%d.txt",datareco.c_str(),test_smearmethod.c_str(),test_fitmethod.c_str(),testpaircat,int(fitrangeLow+0.1),int(fitrangeHigh+0.1),binwidth,fitdet,phtcorr,fitstra,fixscale,etcut)); //txtout.open(filename,ios::out); TTree *mytree = new TTree("Analysis",""); float mcfitpar[8] = {0}; float mcfitparErr[8] = {0}; int mcfitStatus; float fAmin; mytree->Branch("mcfitpar",mcfitpar,"mcfitpar[8]/F"); mytree->Branch("mcfitparErr",mcfitparErr,"mcfitparErr[8]/F"); mytree->Branch("mcfitStatus",&mcfitStatus,"mcfitStatus/I"); mytree->Branch("fAmin",&fAmin,"fAmin/F"); rv_mass = new RooRealVar("rv_mass","mass",100,0,1E6); rv_weight = new RooRealVar("rv_weight","weight",1.0,0,1E6); for(int j=0;j<20;j++){ string sname = string(Form("mpairmc_indscpair%d",j)); makeRootDataSetAndTH1F(sname,int( (fitrangeHigh-fitrangeLow)/binwidth+0.1),fitrangeLow,fitrangeHigh); sname = string(Form("mpairdata_indscpair%d",j)); makeRootDataSetAndTH1F(sname,int( (fitrangeHigh-fitrangeLow)/binwidth+0.1),fitrangeLow,fitrangeHigh); } int sc1cat; int sc2cat; cout<<" nMC " <<NMC <<endl; for(int n=0; n< NMC; n++){ fChainMC->GetEntry(n); if(phtcorr==94){ if(evtNumber%2==0) continue; } ///same as 485, for test purpose only if(phtcorr_test==486){ if(evtNumber%2==0) continue; } if(n%500000==0) cout<<"n " << n <<endl; if(fitdet==1){ if( fabs(elesceta[0])>1.48 || fabs(elesceta[1])>1.48) continue; }else if( fitdet==2){ if( fabs(elesceta[0])<1.48 || fabs(elesceta[1])<1.48) continue; } ///scale r9 in MC for(int j=0; j<2; j++){ if(fabs(elesceta[j])<1.48) elescr9[j] *= 1.004; else elescr9[j] *= 1.006; } ///get pair index sc1cat = scCategoryEight(elesceta[0],elescr9[0]); sc2cat = scCategoryEight(elesceta[1],elescr9[1]); if(sc2cat < sc1cat){ exChangeTwoNumber(sc1cat,sc2cat); } int indpair; if(fitdet==1){ indpair = map_indscpairBarrel[sc1cat][sc2cat]; }else{ indpair = map_indscpairEndcap[sc1cat][sc2cat]; } //test one category if(testOnlyCat >=0 && indpair != testOnlyCat) continue; float e1true; if( fabs(elesceta[0])<1.48){ e1true = eleetrueplusfsrdrbc005[0]; }else{ e1true = eleetrueplusfsrdrbc01[0]; } float e2true; if( fabs(elesceta[1])<1.48){ e2true = eleetrueplusfsrdrbc005[1]; }else{ e2true = eleetrueplusfsrdrbc01[1]; } if(e1true <1 || e2true<1) continue; vindpair.push_back(indpair); sc1cat = scCategoryEight(elesceta[0],elescr9[0]); sc2cat = scCategoryEight(elesceta[1],elescr9[1]); if(fitdet==2){ //Endcap, starting with 4,5,6,7 sc1cat -=4; sc2cat -=4; } vsc1cat.push_back(sc1cat); vsc2cat.push_back(sc2cat); vele1eta.push_back(eleeta[0]); vele1ieta.push_back(eleieta[0]); vele1iphi.push_back(eleiphi[0]); vele2eta.push_back(eleeta[1]); vele2ieta.push_back(eleieta[1]); vele2iphi.push_back(eleiphi[1]); vele1en.push_back(eleen[0]); vele2en.push_back(eleen[1]); vmpair.push_back(mpair); vweight.push_back(weight); vele1etrue.push_back(e1true); vele2etrue.push_back(e2true); if( eleen[0]* sin(2*atan(exp(-eleeta[0]))) < etcut) continue; if( eleen[1]* sin(2*atan(exp(-eleeta[1]))) < etcut) continue; string sname = string(Form("mpairmc_indscpair%d",indpair)); fillRootDataSetAndTH1F(sname,mpair,weight); } setMap_cat_runbin(); loadRunbyRunScaleCorrectionNoR9(iflag,phtcorr); loadScaleCorrectionR9(iflag,phtcorr); for(int n=0; n< NData; n++){ fChainData->GetEntry(n); if(n%500000==0) cout<<"n " << n <<endl; if(fitdet==1){ if( fabs(elesceta[0])>1.48 || fabs(elesceta[1])>1.48) continue; }else if( fitdet==2){ if( fabs(elesceta[0])<1.48 || fabs(elesceta[1])<1.48) continue; } float scorr = 1.0; for(int j=0; j<2; j++){ float dEoE = energyScaleRunNoR9(elesceta[j]); float dEoE1 = energyScaleR9(elesceta[j],elescr9[j]); eleen[j] *= 1.0/(1+dEoE) * 1.0/(1+dEoE1); scorr *= 1.0/(1+dEoE) * 1.0/(1+dEoE1); } mpair *= sqrt(scorr); if( eleen[0]*sin(2*atan(exp(-eleeta[0]))) < etcut) continue; if( eleen[1]*sin(2*atan(exp(-eleeta[1]))) < etcut) continue; sc1cat = scCategoryEight(elesceta[0],elescr9[0]); sc2cat = scCategoryEight(elesceta[1],elescr9[1]); if(sc2cat < sc1cat){ exChangeTwoNumber(sc1cat,sc2cat); } int indpair; if(fitdet==1){ indpair = map_indscpairBarrel[sc1cat][sc2cat]; }else{ indpair = map_indscpairEndcap[sc1cat][sc2cat]; } string sname = string(Form("mpairdata_indscpair%d",indpair)); fillRootDataSetAndTH1F(sname,mpair,1); } for(int j=0;j<10;j++){ string sname = string(Form("mpairmc_indscpair%d",j)); string snamed = string(Form("mpairdata_indscpair%d",j)); cout<<"mpair catpair " << th1f_map[sname]->GetEntries()<<" "<< th1f_map[snamed]->GetEntries()<<endl; } generateGaussRandom(); //return; TMinuit *minuit; int npar = 8; minuit = new TMinuit(npar); //minuit->SetFCN(function); //minuit->SetFCN(function1); minuit->SetFCN(function2); //settings Double_t arglist[1]; Int_t ierflg = 0; //double STEPMN = 0.01; double STEPMN = 0.0001; // 1 for Chi square // 0.5 for negative log likelihood if(fitmethod== "lh" || fitmethod == "lhpoisson"){ minuit->SetErrorDef(0.5); }else{ minuit->SetErrorDef(1); } double fitpar[10]; double fitparErr[10]; double smearcat[4] = {1.1,1.1,1.1,1.1}; double smearcatMax[4] = {3,3,3,3}; double deltaEcat[4] = {0,0,0,0}; if(smearMethod=="uncorrSmear"){ smearcatMax[0] = 0.05; smearcatMax[1] = 0.05; smearcatMax[2] = 0.05; smearcatMax[3] = 0.05; smearcat[0] = 0.007; smearcat[1] = 0.01; smearcat[2] = 0.015; smearcat[3] = 0.02; if(fitdet==2){ smearcat[0] = 0.02; smearcat[1] = 0.02; smearcat[2] = 0.02; smearcat[3] = 0.02; } } for(int j=0; j<4; j++){ TString parname = TString (Form("smearcat%d",j)); if(smearMethod=="corrSmear"){ minuit->mnparm(j, parname, smearcat[j], STEPMN, 0.5,smearcatMax[j],ierflg); }else if(smearMethod=="uncorrSmear"){ minuit->mnparm(j, parname, smearcat[j], STEPMN, 0,smearcatMax[j],ierflg); } fitpar[j] = smearcat[j]; //initialized values } for(int j=4; j<npar; j++){ TString parname = TString (Form("scalecat%d",j-4)); minuit->mnparm(j, parname, deltaEcat[j-4], STEPMN, -0.03,0.03,ierflg); fitpar[j] = deltaEcat[j-4]; //initialized values } if(fixscale==1){ for(int j=4; j<npar; j++){ minuit->FixParameter(j); } } if(testpaircat==1){ minuit->FixParameter(0); minuit->FixParameter(2); minuit->FixParameter(3); minuit->FixParameter(4); minuit->FixParameter(6); minuit->FixParameter(7); }else if( testpaircat==0){ minuit->FixParameter(1); minuit->FixParameter(2); minuit->FixParameter(3); minuit->FixParameter(5); minuit->FixParameter(6); minuit->FixParameter(7); } else if( testpaircat==2){ minuit->FixParameter(0); minuit->FixParameter(1); minuit->FixParameter(3); minuit->FixParameter(4); minuit->FixParameter(5); minuit->FixParameter(7); } else if( testpaircat==3){ minuit->FixParameter(0); minuit->FixParameter(1); minuit->FixParameter(2); minuit->FixParameter(4); minuit->FixParameter(5); minuit->FixParameter(6); } arglist[0] = 0.0001; minuit->mnexcm("SET EPS",arglist,1,ierflg); //minuit->mnsimp(); ////arglist[0] = 1; ///minuit->mnexcm("SET STR",arglist,1,ierflg); //minuit->mnexcm("MIGRAD", arglist ,1,ierflg); arglist[0] = fitstra; minuit->mnexcm("SET STR",arglist,1,ierflg); bool dofit = true; if( dofit){ minuit->Migrad(); if (!minuit->fCstatu.Contains("CONVERGED")) { mcfitStatus = 1; //first try not converged. minuit->Migrad(); }else{ mcfitStatus = 0; } } double ftest[1000]; double atest[1000]; //minuit->GetParameter(0,fitpar[0],fitparErr[0]); if (!minuit->fCstatu.Contains("CONVERGED")) { printf("No convergence at fitting, routine Fit \n"); printf("Minuit return string: %s \n",minuit->fCstatu.Data()); mcfitStatus = 2; //2nd try not converged. }else{ mcfitStatus = -1; } fAmin = minuit->fAmin; for(int j=0; j<npar; j++){ minuit->GetParameter(j,fitpar[j],fitparErr[j]); mcfitpar[j] = fitpar[j]; mcfitparErr[j] = fitparErr[j]; } double par[10]; for(int j=0;j<npar;j++){ par[j] = fitpar[j]; } bool printScan = false; //bool printScan = true; par[0] = 0.0076; if(printScan && testpaircat>=0){ double fmin = function2(par,true); float x1 = fitpar[testpaircat] - 0.1; float x2 = fitpar[testpaircat] + 0.1; float teststep = 0.01; if(smearMethod=="uncorrSmear"){ x1 = fitpar[testpaircat] - 0.005 >0 ? fitpar[testpaircat] - 0.005: 0; x2 = fitpar[testpaircat] +0.005; teststep = 0.001; } double dmin1 = 1; double dmin2 = 1; double fitparErrLow[10]; double fitparErrHigh[10]; int ntest = 0; for(float x = x1; x <= x2; x += teststep){ cout<<"x " << x <<endl; par[testpaircat] = x ; //double f = function2(par,false); double f = function2(par,true); if(fabs(f-fmin-1)< dmin1 && x < fitpar[testpaircat]){ dmin1 = fabs(f-fmin-0.5); fitparErrLow[testpaircat] = fitpar[testpaircat] -x; } if(fabs(f-fmin-1)< dmin2 && x > fitpar[testpaircat]){ dmin2 = fabs(f-fmin-0.5); fitparErrHigh[testpaircat] = x-fitpar[testpaircat]; } atest[ntest] = x; ftest[ntest] = f; ntest ++; } cout<<"fitpar[testpaircat]" << fitpar[testpaircat]<<" +/- "<<fitparErr[testpaircat]<<" - "<< fitparErrLow[testpaircat]<<" + "<< fitparErrHigh[testpaircat]<<endl; TCanvas *can0 = new TCanvas("can0","c000",200,10,550,500); setTCanvasNice(can0); TGraph *gr = new TGraph(ntest,atest,ftest); gr->Draw("ap"); //TF1 *ff = new TF1("ff","[0]+[1]*x+[2]*x*x",0,0.0); //gr->Fit(ff,"r"); can0->Print("testconverge1.pdf"); can0->Print("testconverge1.C"); } mytree->Fill(); mytree->Write(); fnew->Write(); fnew->Close(); }
int main (int argc, char** argv) { // load framework libraries gSystem->Load( "libFWCoreFWLite" ); //gSystem->Load("libNtupleMakerBEANmaker.so"); AutoLibraryLoader::enable(); int debug = 0; // levels of debug, 10 is large JobParameters myConfig = parseJobOptions(argc, argv); TFile * outputFile = new TFile (myConfig.outputFileName.c_str(), "RECREATE"); outputFile->cd(); TTree * summaryTree = new TTree("summaryTree", "Summary Event Values"); fwlite::ChainEvent ev(myConfig.inputFileNames); HelperLeptonCore lepHelper; // setup the analysis // it comes from the lepHelper BEANhelper * beanHelper = lepHelper.setupAnalysisParameters("2012_53x", myConfig.sampleName); // --------------------------------------------- // Note for future development: should these be // saved inside the lepHelper somewhere? // For now they are ok here // --------------------------------------------- // when the selections are the same, then everything should be tight not loose muonID::muonID muonTightID = muonID::muonSideTightMVA; muonID::muonID muonLooseID = muonID::muonSideLooseMVA; muonID::muonID muonPreselectedID = muonID::muonSide; electronID::electronID electronTightID = electronID::electronSideTightMVA; electronID::electronID electronLooseID = electronID::electronSideLooseMVA; electronID::electronID electronPreselectedID = electronID::electronSide; // declare your kinematic variables that you want // to be written out into the tree vector<ArbitraryVariable*> kinVars; vector<ArbitraryVariable*> cutVars; // NumJets myNjets; // myNjets.setCut(2); // parameter is keep events with jets >= num // kinVars.push_back(&myNjets); //save it in the tree // cutVars.push_back(&myNjets); //also cut on it // NumLeptons myNlep; // kinVars.push_back(&myNlep); // CSV weights don't exist for jets // with a pt < 30 // // CSVWeights myCSV(&lepHelper); // kinVars.push_back(&myCSV); PUWeights myPU(&lepHelper); kinVars.push_back(&myPU); TopPtWeights myTopPt(&lepHelper); kinVars.push_back(&myTopPt); // do these definitions work? // yes, it it tight and everything else is loose LeptonIDAndIsoScaleFactors myLepIDAndIsoSF(&lepHelper, muonTightID, muonLooseID, electronTightID, electronLooseID); kinVars.push_back(&myLepIDAndIsoSF); LeptonTriggerScaleFactors myLepTrig( &lepHelper); kinVars.push_back(&myLepTrig); CleanEventVars myClean (&lepHelper); kinVars.push_back(&myClean); CheckTwoLepTrigger checkTrig (&lepHelper); kinVars.push_back(&checkTrig); //MassLepLep mll; //kinVars.push_back(&mll); // GenericMuonCollectionMember<double, BNmuonCollection> allMuonPt(Reflex::Type::ByName("BNmuon"), "pt", "muons_by_pt", KinematicVariableConstants::FLOAT_INIT, 2); // kinVars.push_back(&allMuonPt); // GenericMuonCollectionMember<double, BNmuonCollection> allMuonEta(Reflex::Type::ByName("BNmuon"), "eta", "muons_by_pt", KinematicVariableConstants::FLOAT_INIT, 2); // kinVars.push_back(&allMuonEta); // GenericJetCollectionMember<double, BNjetCollection> allJetPt(Reflex::Type::ByName("BNjet"), "pt", "jet_by_pt", KinematicVariableConstants::FLOAT_INIT, 6); // kinVars.push_back(&allJetPt); // GenericJetCollectionMember<double, BNjetCollection> allJetEta(Reflex::Type::ByName("BNjet"), "eta", "jet_by_pt", KinematicVariableConstants::FLOAT_INIT, 6); // kinVars.push_back(&allJetEta); int numExtraPartons = -99; summaryTree->Branch("numExtraPartons", &numExtraPartons); // GenericEventCollectionMember<unsigned, BNeventCollection> runNumber(Reflex::Type::ByName("BNevent"), "run", "eventInfo", KinematicVariableConstants::UINT_INIT, 1); // kinVars.push_back(&runNumber); // GenericEventCollectionMember<unsigned, BNeventCollection> lumiBlock(Reflex::Type::ByName("BNevent"), "lumi", "eventInfo", KinematicVariableConstants::UINT_INIT, 1); // kinVars.push_back(&lumiBlock); // this is a long inside BNevent // just using keyword long won't work // needs to be Long64_t // GenericEventCollectionMember<Long64_t, BNeventCollection> eventNumber(Reflex::Type::ByName("BNevent"), "evt", "eventInfo", KinematicVariableConstants::INT_INIT, 1); // kinVars.push_back(&eventNumber); // hook up the variables if (debug > 9) { cout << "Hooking variables to tree" << endl;} for (vector<ArbitraryVariable*>::iterator iVar = kinVars.begin(); iVar != kinVars.end(); iVar++) { (*iVar)->attachToTree (summaryTree); } int numEvents = 0; int numEventsFailCuts = 0; int numEventsPassCuts = 0; int printEvery = 1000; BEANFileInterface selectedCollections; for (ev.toBegin(); !ev.atEnd(); ++ev){ numEvents++; if (numEvents > myConfig.maxEvents) break; if (numEvents == 1 || numEvents % printEvery == 0 ) cout << "Processing event.... " << numEvents << endl; if (debug > 9) cout << "---------->>>>>> Event " << numEvents << endl; lepHelper.initializeInputCollections(ev, true, selectedCollections); ///////////////////////////////////////////////////////////// // // Apply object ids // ////////////////////////////////////////////////////////////// //------------ Jets if (debug > 9) cout << "Getting jets " << endl; lepHelper.getTightCorrectedJets(25.0, 2.4, jetID::jetLoose, &selectedCollections); //------------ Electrons if (debug > 9) cout << "Getting electrons " << endl; lepHelper.getTightLoosePreselectedElectrons(electronTightID, electronLooseID, electronPreselectedID, &selectedCollections); //----------- Muons if (debug > 9) cout << "Getting muons " << endl; lepHelper.getTightLoosePreselectedMuons(muonTightID, muonLooseID, muonPreselectedID, &selectedCollections); //---------- MET if (debug > 9) cout << "Getting met " << endl; lepHelper.getCorrectedMet(&selectedCollections); //--------- fill up the lepton collections if (debug >9) cout << "Filling lepton collections" << endl; lepHelper.fillLepCollectionWithSelectedLeptons(&selectedCollections); // reset all the vars if (debug > 9) cout << "Resetting " << endl; for (vector<ArbitraryVariable*>::iterator iVar = kinVars.begin(); iVar != kinVars.end(); iVar++) { (*iVar)->reset(); (*iVar)->assignCollections(&selectedCollections); } bool passAllCuts = true; if (debug > 9) cout << "Checking cuts " << endl; for (vector<ArbitraryVariable*>::iterator iCut = cutVars.begin(); iCut != cutVars.end(); iCut++ ) { (*iCut)->evaluate(); passAllCuts = passAllCuts && (*iCut)->passCut(); } // do the lepton cut passAllCuts = passAllCuts && LeptonCutThisAnalysis(&selectedCollections); if (!passAllCuts) { numEventsFailCuts++; //!!!! Skip The event /////////////// continue; } else { numEventsPassCuts++; } // Now evaluate the vars if (debug > 9) cout << "Evaluating vars " << endl; for (vector<ArbitraryVariable*>::iterator iVar = kinVars.begin(); iVar != kinVars.end(); iVar++) { (*iVar)->evaluate(); } if (debug > 9) { for (vector<ArbitraryVariable*>::iterator iVar = kinVars.begin(); iVar != kinVars.end(); iVar++) { (*iVar)->print(); cout << endl; } } //LeptonVarsThisAnalysis(&selectedCollections, LeptonCutThisAnalysis(&selectedCollections), TwoMuon, TwoElectron, MuonElectron); getNumExtraPartons(beanHelper, selectedCollections, numExtraPartons); if (myConfig.sampleName.find("_0p") != std::string::npos) { //0 parton samples //Cut to require 0 partons if (numExtraPartons != 0) { numEventsFailCuts++; numEventsPassCuts--; continue; } } if (debug > 9) cout << "Filling tree " << endl; summaryTree->Fill(); if (debug > 9) cout << "Done with event " << numEvents << endl; }// end for each event cout << "Num Events processed " << numEvents << endl << "Passed cuts " << numEventsPassCuts << endl << "Failed cuts " << numEventsFailCuts << endl ; outputFile->Write(); outputFile->Close(); }
void ZeeGammaMassFitSystematicStudy(string workspaceFile, const Int_t seed = 1234, Int_t Option = 0, Int_t NToys = 1) { //-------------------------------------------------------------------------------------------------------------- // Settings //============================================================================================================== TRandom3 *randomnumber = new TRandom3(seed); // RooRealVar m("m","mass",60,130); RooCategory sample("sample",""); sample.defineType("Pass",1); sample.defineType("Fail",2); //-------------------------------------------------------------------------------------------------------------- //Load Workspace //============================================================================================================== TFile *f = new TFile (workspaceFile.c_str(), "READ"); RooWorkspace *w = (RooWorkspace*)f->Get("MassFitWorkspace"); //-------------------------------------------------------------------------------------------------------------- //Setup output tree //============================================================================================================== TFile *outputfile = new TFile (Form("EffToyResults_Option%d_Seed%d.root",Option, seed), "RECREATE"); float varEff = 0; float varEffErrL = 0; float varEffErrH = 0; TTree *outTree = new TTree("eff","eff"); outTree->Branch("eff",&varEff, "eff/F"); outTree->Branch("efferrl",&varEffErrL, "efferrl/F"); outTree->Branch("efferrh",&varEffErrH, "efferrh/F"); //-------------------------------------------------------------------------------------------------------------- //Load Model //============================================================================================================== RooSimultaneous *totalPdf = (RooSimultaneous*)w->pdf("totalPdf"); RooRealVar *m_default = (RooRealVar*)w->var("m"); m_default->setRange("signalRange",85, 95); //get default models RooAddPdf *modelPass_default = (RooAddPdf*)w->pdf("modelPass"); RooAddPdf *modelFail_default = (RooAddPdf*)w->pdf("modelFail"); //get variables RooRealVar *Nsig = (RooRealVar*)w->var("Nsig"); RooRealVar *eff = (RooRealVar*)w->var("eff"); RooRealVar *NbkgFail = (RooRealVar*)w->var("NbkgFail"); RooFormulaVar NsigPass("NsigPass","eff*Nsig",RooArgList(*eff,*Nsig)); RooFormulaVar NsigFail("NsigFail","(1.0-eff)*Nsig",RooArgList(*eff,*Nsig)); //get number of expected events Double_t npass = 100; Double_t nfail = 169; //************************************************************************************* //make alternative model //************************************************************************************* RooRealVar *tFail_default = (RooRealVar*)w->var("tFail"); RooRealVar *fracFail_default = (RooRealVar*)w->var("fracFail"); RooRealVar *meanFail_default = (RooRealVar*)w->var("meanFail"); RooRealVar *sigmaFail_default = (RooRealVar*)w->var("sigmaFail"); RooHistPdf *bkgFailTemplate_default = (RooHistPdf*)w->pdf("bkgHistPdfFail"); RooFFTConvPdf *sigFail_default = (RooFFTConvPdf*)w->pdf("signalFail"); RooFFTConvPdf *bkgFail_default = (RooFFTConvPdf*)w->pdf("bkgConvPdfFail"); RooExtendPdf *esignalFail_default = (RooExtendPdf *)w->pdf("esignalFail"); RooExtendPdf *ebackgroundFail_default = (RooExtendPdf *)w->pdf("ebackgroundFail"); RooExponential *bkgexpFail_default = (RooExponential*)w->pdf("bkgexpFail"); RooAddPdf *backgroundFail_default = (RooAddPdf*)w->pdf("backgroundFail"); RooGaussian *bkggausFail_default = (RooGaussian*)w->pdf("bkggausFail"); //shifted mean RooRealVar *meanFail_shifted = new RooRealVar("meanFail_shifted","meanFail_shifted", 0, -5, 5); meanFail_shifted->setVal(meanFail_default->getVal()); if (Option == 1) meanFail_shifted->setVal(meanFail_default->getVal()-1.0); else if (Option == 2) meanFail_shifted->setVal(meanFail_default->getVal()+1.0); else if (Option == 11) meanFail_shifted->setVal(meanFail_default->getVal()-2.0); else if (Option == 12) meanFail_shifted->setVal(meanFail_default->getVal()+2.0); RooRealVar *sigmaFail_shifted = new RooRealVar("sigmaFail_shifted","sigmaFail_shifted", 0, -5, 5); sigmaFail_shifted->setVal(sigmaFail_default->getVal()); if (Option == 3) sigmaFail_shifted->setVal(sigmaFail_default->getVal()*1.2); else if (Option == 4) sigmaFail_shifted->setVal(sigmaFail_default->getVal()*0.8); CMCBkgTemplateConvGaussianPlusExp *bkgFailModel = new CMCBkgTemplateConvGaussianPlusExp(*m_default,bkgFailTemplate_default,false,meanFail_shifted,sigmaFail_shifted, "shifted"); bkgFailModel->t->setVal(tFail_default->getVal()); bkgFailModel->frac->setVal(fracFail_default->getVal()); cout << "mean : " << meanFail_default->getVal() << " - " << meanFail_shifted->getVal() << endl; cout << "sigma : " << sigmaFail_default->getVal() << " - " << sigmaFail_shifted->getVal() << endl; cout << "t: " << tFail_default->getVal() << " - " << bkgFailModel->t->getVal() << endl; cout << "frac: " << fracFail_default->getVal() << " - " << bkgFailModel->frac->getVal() << endl; cout << "eff: " << eff->getVal() << " : " << NsigPass.getVal() << " / " << (NsigPass.getVal() + NsigFail.getVal()) << endl; cout << "NbkgFail: " << NbkgFail->getVal() << endl; //make alternative fail model RooAddPdf *modelFail=0; RooExtendPdf *esignalFail=0, *ebackgroundFail=0; ebackgroundFail = new RooExtendPdf("ebackgroundFail_shifted","ebackgroundFail_shifted",*(bkgFailModel->model),*NbkgFail,"signalRange"); modelFail = new RooAddPdf("modelFail","Model for FAIL sample", RooArgList(*esignalFail_default,*ebackgroundFail)); cout << "*************************************\n"; ebackgroundFail->Print(); cout << "*************************************\n"; ebackgroundFail_default->Print(); cout << "*************************************\n"; modelFail->Print(); cout << "*************************************\n"; modelFail_default->Print(); cout << "*************************************\n"; TCanvas *cv = new TCanvas("cv","cv",800,600); RooPlot *mframeFail_default = m_default->frame(Bins(Int_t(130-60)/2)); modelFail_default->plotOn(mframeFail_default); modelFail_default->plotOn(mframeFail_default,Components("ebackgroundFail"),LineStyle(kDashed),LineColor(kRed)); modelFail_default->plotOn(mframeFail_default,Components("bkgexpFail"),LineStyle(kDashed),LineColor(kGreen+2)); mframeFail_default->GetYaxis()->SetTitle(""); mframeFail_default->GetYaxis()->SetTitleOffset(1.2); mframeFail_default->GetXaxis()->SetTitle("m_{ee#gamma} [GeV/c^{2}]"); mframeFail_default->GetXaxis()->SetTitleOffset(1.05); mframeFail_default->SetTitle(""); mframeFail_default->Draw(); cv->SaveAs("DefaultModel.gif"); RooPlot *mframeFail = m_default->frame(Bins(Int_t(130-60)/2)); modelFail->plotOn(mframeFail); modelFail->plotOn(mframeFail,Components("ebackgroundFail_shifted"),LineStyle(kDashed),LineColor(kRed)); modelFail->plotOn(mframeFail,Components("bkgexpFail_shifted"),LineStyle(kDashed),LineColor(kGreen+2)); mframeFail->GetYaxis()->SetTitle(""); mframeFail->GetYaxis()->SetTitleOffset(1.2); mframeFail->GetXaxis()->SetTitle("m_{ee#gamma} [GeV/c^{2}]"); mframeFail->GetXaxis()->SetTitleOffset(1.05); mframeFail->SetTitle(""); mframeFail->Draw(); cv->SaveAs(Form("ShiftedModel_%d.gif",Option)); //************************************************************************************* //Do Toys //************************************************************************************* for(uint t=0; t < NToys; ++t) { RooDataSet *pseudoData_pass = modelPass_default->generate(*m_default, randomnumber->Poisson(npass)); RooDataSet *pseudoData_fail = 0; pseudoData_fail = modelFail->generate(*m_default, randomnumber->Poisson(nfail)); RooDataSet *pseudoDataCombined = new RooDataSet("pseudoDataCombined","pseudoDataCombined",RooArgList(*m_default), RooFit::Index(sample), RooFit::Import("Pass",*pseudoData_pass), RooFit::Import("Fail",*pseudoData_fail)); pseudoDataCombined->write(Form("toy%d.txt",t)); RooFitResult *fitResult=0; fitResult = totalPdf->fitTo(*pseudoDataCombined, RooFit::Extended(), RooFit::Strategy(2), //RooFit::Minos(RooArgSet(eff)), RooFit::Save()); cout << "\n\n"; cout << "Eff Fit: " << eff->getVal() << " -" << fabs(eff->getErrorLo()) << " +" << eff->getErrorHi() << endl; //Fill Tree varEff = eff->getVal(); varEffErrL = fabs(eff->getErrorLo()); varEffErrH = eff->getErrorHi(); outTree->Fill(); // //************************************************************************************* // //Plot Toys // //************************************************************************************* // TCanvas *cv = new TCanvas("cv","cv",800,600); // char pname[50]; // char binlabelx[100]; // char binlabely[100]; // char yield[50]; // char effstr[100]; // char nsigstr[100]; // char nbkgstr[100]; // char chi2str[100]; // // // // Plot passing probes // // // RooPlot *mframeFail_default = m.frame(Bins(Int_t(130-60)/2)); // modelFail_default->plotOn(mframeFail_default); // modelFail_default->plotOn(mframeFail_default,Components("ebackgroundFail"),LineStyle(kDashed),LineColor(kRed)); // modelFail_default->plotOn(mframeFail_default,Components("bkgexpFail"),LineStyle(kDashed),LineColor(kGreen+2)); // mframeFail_default->Draw(); // cv->SaveAs("DefaultModel.gif"); // RooPlot *mframeFail = m.frame(Bins(Int_t(130-60)/2)); // modelFail->plotOn(mframeFail); // modelFail->plotOn(mframeFail,Components("ebackgroundFail_shifted"),LineStyle(kDashed),LineColor(kRed)); // modelFail->plotOn(mframeFail,Components("bkgexpFail_shifted"),LineStyle(kDashed),LineColor(kGreen+2)); // sprintf(yield,"%u Events",(Int_t)passTree->GetEntries()); // sprintf(nsigstr,"N_{sig} = %.1f #pm %.1f",NsigPass.getVal(),NsigPass.getPropagatedError(*fitResult)); // plotPass.AddTextBox(yield,0.21,0.76,0.51,0.80,0,kBlack,-1); // plotPass.AddTextBox(effstr,0.70,0.85,0.94,0.90,0,kBlack,-1); // plotPass.AddTextBox(0.70,0.73,0.94,0.83,0,kBlack,-1,1,nsigstr);//,chi2str); // mframeFail->Draw(); // cv->SaveAs(Form("ShiftedModel_%d.gif",Option)); // // // // Plot failing probes // // // sprintf(pname,"fail%s_%i",name.Data(),ibin); // sprintf(yield,"%u Events",(Int_t)failTree->GetEntries()); // sprintf(nsigstr,"N_{sig} = %.1f #pm %.1f",NsigFail.getVal(),NsigFail.getPropagatedError(*fitResult)); // sprintf(nbkgstr,"N_{bkg} = %.1f #pm %.1f",NbkgFail.getVal(),NbkgFail.getPropagatedError(*fitResult)); // sprintf(chi2str,"#chi^{2}/DOF = %.3f",mframePass->chiSquare(nflfail)); // CPlot plotFail(pname,mframeFail,"Failing probes","tag-probe mass [GeV/c^{2}]","Events / 2.0 GeV/c^{2}"); // plotFail.AddTextBox(binlabelx,0.21,0.85,0.51,0.90,0,kBlack,-1); // if((name.CompareTo("etapt")==0) || (name.CompareTo("etaphi")==0)) { // plotFail.AddTextBox(binlabely,0.21,0.80,0.51,0.85,0,kBlack,-1); // plotFail.AddTextBox(yield,0.21,0.76,0.51,0.80,0,kBlack,-1); // } else { // plotFail.AddTextBox(yield,0.21,0.81,0.51,0.85,0,kBlack,-1); // } // plotFail.AddTextBox(effstr,0.70,0.85,0.94,0.90,0,kBlack,-1); // plotFail.AddTextBox(0.70,0.68,0.94,0.83,0,kBlack,-1,2,nsigstr,nbkgstr);//,chi2str); // plotFail.Draw(cfail,kTRUE,format); } //for loop over all toys //************************************************************************************* //Save To File //************************************************************************************* outputfile->WriteTObject(outTree, outTree->GetName(), "WriteDelete"); }
void NormalizeVGammaSample(TString InputFilename0 = "/data/smurf/data/Run2012_Summer12_SmurfV9_53X/mitf-alljets/wgamma.root", TString InputFilename1 = "/data/smurf/data/Run2012_Summer12_SmurfV9_53X/mitf-alljets/wgammafo.root", bool applyCorrection = true ) { Double_t eventCount0 = 0; TH1D *hDRatioPhotonElectron = new TH1D("hDRatioPhotonElectron","hDRatioPhotonElectron",10,0.0,2.5); hDRatioPhotonElectron->Sumw2(); TH1D *hDLepSel[10]; hDLepSel[0] = new TH1D("hDLepSel_0","hDLepSel_0",20,0.0,100.0); hDLepSel[1] = new TH1D("hDLepSel_1","hDLepSel_1",20,0.0,100.0); hDLepSel[2] = new TH1D("hDLepSel_2","hDLepSel_2",10,0.0,2.5); hDLepSel[3] = new TH1D("hDLepSel_3","hDLepSel_3",10,0.0,2.5); hDLepSel[4] = new TH1D("hDLepSel_4","hDLepSel_4",20,0.0,100.0); hDLepSel[5] = new TH1D("hDLepSel_5","hDLepSel_5",20,0.0,100.0); hDLepSel[6] = new TH1D("hDLepSel_6","hDLepSel_6",10,0.0,2.5); hDLepSel[7] = new TH1D("hDLepSel_7","hDLepSel_7",10,0.0,2.5); for(int i=0; i<8; i++) hDLepSel[i]->Sumw2(); TH1D *hDpSel[20]; hDpSel[0] = new TH1D("hDpSel_0" ,"hDpSel_0" ,20,0.0,100.0); hDpSel[1] = new TH1D("hDpSel_1" ,"hDpSel_1" ,20,0.0,100.0); hDpSel[2] = new TH1D("hDpSel_2" ,"hDpSel_2" ,10,0.0,2.5); hDpSel[3] = new TH1D("hDpSel_3" ,"hDpSel_3" ,10,0.0,2.5); hDpSel[4] = new TH1D("hDpSel_4" ,"hDpSel_4" ,40,0.0,200.0); hDpSel[5] = new TH1D("hDpSel_5" ,"hDpSel_5" ,40,0.0,200.0); hDpSel[6] = new TH1D("hDpSel_6" ,"hDpSel_6" ,40,0.0,200.0); hDpSel[7] = new TH1D("hDpSel_7" ,"hDpSel_7" ,36,0.0,160.0); hDpSel[8] = new TH1D("hDpSel_8" ,"hDpSel_8" ,40,0.0,200.0); hDpSel[9] = new TH1D("hDpSel_9" ,"hDpSel_9" ,40,0.0,200.0); hDpSel[10] = new TH1D("hDpSel_10","hDpSel_10",20,0.0,100.0); hDpSel[11] = new TH1D("hDpSel_11","hDpSel_11",20,0.0,100.0); hDpSel[12] = new TH1D("hDpSel_12","hDpSel_12",10,0.0,2.5); hDpSel[13] = new TH1D("hDpSel_13","hDpSel_13",10,0.0,2.5); hDpSel[14] = new TH1D("hDpSel_14","hDpSel_14",40,0.0,200.0); hDpSel[15] = new TH1D("hDpSel_15","hDpSel_15",40,0.0,200.0); hDpSel[16] = new TH1D("hDpSel_16","hDpSel_16",40,0.0,200.0); hDpSel[17] = new TH1D("hDpSel_17","hDpSel_17",36,0.0,160.0); hDpSel[18] = new TH1D("hDpSel_18","hDpSel_18",40,0.0,200.0); hDpSel[19] = new TH1D("hDpSel_19","hDpSel_19",40,0.0,200.0); for(int i=0; i<20; i++) hDpSel[i]->Sumw2(); SmurfTree vgammaEvent; vgammaEvent.LoadTree(InputFilename0.Data()); vgammaEvent.InitTree(0); vgammaEvent.tree_->SetName("tree"); TFile *fRatioPhotonElectron = TFile::Open("/data/smurf/data/Run2012_Summer12_SmurfV9_53X/auxiliar/ratio_photon_electron.root"); TH1D *fhDRatioPhotonElectron = (TH1D*)(fRatioPhotonElectron->Get("hDRatioPhotonElectron")); assert(fhDRatioPhotonElectron); fhDRatioPhotonElectron->SetDirectory(0); fRatioPhotonElectron->Close(); delete fRatioPhotonElectron; for (int n=0;n<vgammaEvent.tree_->GetEntries();n++) { vgammaEvent.tree_->GetEntry(n); bool lid = (vgammaEvent.cuts_ & SmurfTree::Lep1FullSelection) == SmurfTree::Lep1FullSelection && (vgammaEvent.cuts_ & SmurfTree::Lep2FullSelection) == SmurfTree::Lep2FullSelection; if (!lid) continue; if( vgammaEvent.lep1_.pt() <= 20 ) continue; // cut on leading lepton pt if( vgammaEvent.lep2_.pt() <= 10 ) continue; // cut on trailing lepton pt if( vgammaEvent.dilep_.M() <= 12 ) continue; // cut on minimum dilepton mass Double_t add = vgammaEvent.sfWeightPU_*vgammaEvent.sfWeightEff_*vgammaEvent.sfWeightTrig_; Double_t myWeight = vgammaEvent.scale1fb_*add; if(!(TMath::Abs(vgammaEvent.lep1McId_) == 11 || TMath::Abs(vgammaEvent.lep1McId_) == 13)) hDLepSel[0]->Fill(TMath::Min(vgammaEvent.lep1_.pt(),99.999),myWeight); if(!(TMath::Abs(vgammaEvent.lep2McId_) == 11 || TMath::Abs(vgammaEvent.lep2McId_) == 13)) hDLepSel[0]->Fill(TMath::Min(vgammaEvent.lep2_.pt(),99.999),myWeight); if(!(TMath::Abs(vgammaEvent.lep1McId_) == 11 || TMath::Abs(vgammaEvent.lep1McId_) == 13)) hDLepSel[2]->Fill(TMath::Min(TMath::Abs(vgammaEvent.lep1_.eta()),2.499),myWeight); if(!(TMath::Abs(vgammaEvent.lep2McId_) == 11 || TMath::Abs(vgammaEvent.lep2McId_) == 13)) hDLepSel[2]->Fill(TMath::Min(TMath::Abs(vgammaEvent.lep2_.eta()),2.499),myWeight); if((TMath::Abs(vgammaEvent.lep1McId_) == 11 || TMath::Abs(vgammaEvent.lep1McId_) == 13)) hDLepSel[4]->Fill(TMath::Min(vgammaEvent.lep1_.pt(),99.999),myWeight); if((TMath::Abs(vgammaEvent.lep2McId_) == 11 || TMath::Abs(vgammaEvent.lep2McId_) == 13)) hDLepSel[4]->Fill(TMath::Min(vgammaEvent.lep2_.pt(),99.999),myWeight); if((TMath::Abs(vgammaEvent.lep1McId_) == 11 || TMath::Abs(vgammaEvent.lep1McId_) == 13)) hDLepSel[6]->Fill(TMath::Min(TMath::Abs(vgammaEvent.lep1_.eta()),2.499),myWeight); if((TMath::Abs(vgammaEvent.lep2McId_) == 11 || TMath::Abs(vgammaEvent.lep2McId_) == 13)) hDLepSel[6]->Fill(TMath::Min(TMath::Abs(vgammaEvent.lep2_.eta()),2.499),myWeight); eventCount0 += myWeight; } cout << "eventCount0 Event Count 1fb^-1 : " << eventCount0 << endl; Double_t eventCount1 = 0; SmurfTree vgammafoEvent; vgammafoEvent.LoadTree(InputFilename1.Data()); vgammafoEvent.InitTree(0); vgammafoEvent.tree_->SetName("tree"); for (int n=0;n<vgammafoEvent.tree_->GetEntries();n++) { vgammafoEvent.tree_->GetEntry(n); bool lid = ((vgammafoEvent.cuts_ & SmurfTree::Lep1FullSelection) == SmurfTree::Lep1FullSelection && (vgammafoEvent.cuts_ & SmurfTree::Lep2LooseEleV2) == SmurfTree::Lep2LooseEleV2) || ((vgammafoEvent.cuts_ & SmurfTree::Lep1LooseEleV2) == SmurfTree::Lep1LooseEleV2 && (vgammafoEvent.cuts_ & SmurfTree::Lep2FullSelection) == SmurfTree::Lep2FullSelection); if (!lid) continue; if( vgammafoEvent.lep1_.pt() <= 20 ) continue; // cut on leading lepton pt if( vgammafoEvent.lep2_.pt() <= 10 ) continue; // cut on trailing lepton pt if( TMath::Abs(vgammafoEvent.lep1_.eta()) >= 2.5 ) continue; // cut on leading lepton pt if( TMath::Abs(vgammafoEvent.lep2_.eta()) >= 2.5 ) continue; // cut on trailing lepton pt if( vgammafoEvent.dilep_.M() <= 12 ) continue; // cut on minimum dilepton mass Double_t add = vgammafoEvent.sfWeightPU_*vgammafoEvent.sfWeightEff_*vgammafoEvent.sfWeightTrig_; Double_t myWeight = vgammafoEvent.scale1fb_*add; hDpSel[0]->Fill(TMath::Min(vgammafoEvent.lep1_.pt(),99.999),myWeight); hDpSel[1]->Fill(TMath::Min(vgammafoEvent.lep2_.pt(),99.999),myWeight); hDpSel[2]->Fill(TMath::Min(TMath::Abs(vgammafoEvent.lep1_.eta()),2.499),myWeight); hDpSel[3]->Fill(TMath::Min(TMath::Abs(vgammafoEvent.lep2_.eta()),2.499),myWeight); hDpSel[4]->Fill(TMath::Min((double)vgammafoEvent.mt_,199.999),myWeight); hDpSel[5]->Fill(TMath::Min((double)vgammafoEvent.dilep_.M(),199.999),myWeight); hDpSel[6]->Fill(TMath::Min((double)vgammafoEvent.met_,199.999),myWeight); hDpSel[7]->Fill(TMath::Min((double)vgammafoEvent.dPhi_*180/TMath::Pi(),179.999),myWeight); hDpSel[8]->Fill(TMath::Min((double)vgammafoEvent.mt1_,199.999),myWeight); hDpSel[9]->Fill(TMath::Min((double)vgammafoEvent.mt2_,199.999),myWeight); if(!(TMath::Abs(vgammafoEvent.lep1McId_) == 11 || TMath::Abs(vgammafoEvent.lep1McId_) == 13) && applyCorrection == true) myWeight = myWeight * ratioPhotonElectron(fhDRatioPhotonElectron,TMath::Abs(vgammafoEvent.lep1_.eta())); if(!(TMath::Abs(vgammafoEvent.lep2McId_) == 11 || TMath::Abs(vgammafoEvent.lep2McId_) == 13) && applyCorrection == true) myWeight = myWeight * ratioPhotonElectron(fhDRatioPhotonElectron,TMath::Abs(vgammafoEvent.lep2_.eta())); hDpSel[10]->Fill(TMath::Min(vgammafoEvent.lep1_.pt(),99.999),myWeight); hDpSel[11]->Fill(TMath::Min(vgammafoEvent.lep2_.pt(),99.999),myWeight); hDpSel[12]->Fill(TMath::Min(TMath::Abs(vgammafoEvent.lep1_.eta()),2.499),myWeight); hDpSel[13]->Fill(TMath::Min(TMath::Abs(vgammafoEvent.lep2_.eta()),2.499),myWeight); hDpSel[14]->Fill(TMath::Min((double)vgammafoEvent.mt_,199.999),myWeight); hDpSel[15]->Fill(TMath::Min((double)vgammafoEvent.dilep_.M(),199.999),myWeight); hDpSel[16]->Fill(TMath::Min((double)vgammafoEvent.met_,199.999),myWeight); hDpSel[17]->Fill(TMath::Min((double)vgammafoEvent.dPhi_*180/TMath::Pi(),179.999),myWeight); hDpSel[18]->Fill(TMath::Min((double)vgammafoEvent.mt1_,199.999),myWeight); hDpSel[19]->Fill(TMath::Min((double)vgammafoEvent.mt2_,199.999),myWeight); if(!(TMath::Abs(vgammafoEvent.lep1McId_) == 11 || TMath::Abs(vgammafoEvent.lep1McId_) == 13)) hDLepSel[1]->Fill(TMath::Min(vgammafoEvent.lep1_.pt(),99.999),myWeight); if(!(TMath::Abs(vgammafoEvent.lep2McId_) == 11 || TMath::Abs(vgammafoEvent.lep2McId_) == 13)) hDLepSel[1]->Fill(TMath::Min(vgammafoEvent.lep2_.pt(),99.999),myWeight); if(!(TMath::Abs(vgammafoEvent.lep1McId_) == 11 || TMath::Abs(vgammafoEvent.lep1McId_) == 13)) hDLepSel[3]->Fill(TMath::Min(TMath::Abs(vgammafoEvent.lep1_.eta()),2.499),myWeight); if(!(TMath::Abs(vgammafoEvent.lep2McId_) == 11 || TMath::Abs(vgammafoEvent.lep2McId_) == 13)) hDLepSel[3]->Fill(TMath::Min(TMath::Abs(vgammafoEvent.lep2_.eta()),2.499),myWeight); if((TMath::Abs(vgammafoEvent.lep1McId_) == 11 || TMath::Abs(vgammafoEvent.lep1McId_) == 13)) hDLepSel[5]->Fill(TMath::Min(vgammafoEvent.lep1_.pt(),99.999),myWeight); if((TMath::Abs(vgammafoEvent.lep2McId_) == 11 || TMath::Abs(vgammafoEvent.lep2McId_) == 13)) hDLepSel[5]->Fill(TMath::Min(vgammafoEvent.lep2_.pt(),99.999),myWeight); if((TMath::Abs(vgammafoEvent.lep1McId_) == 11 || TMath::Abs(vgammafoEvent.lep1McId_) == 13)) hDLepSel[7]->Fill(TMath::Min(TMath::Abs(vgammafoEvent.lep1_.eta()),2.499),myWeight); if((TMath::Abs(vgammafoEvent.lep2McId_) == 11 || TMath::Abs(vgammafoEvent.lep2McId_) == 13)) hDLepSel[7]->Fill(TMath::Min(TMath::Abs(vgammafoEvent.lep2_.eta()),2.499),myWeight); eventCount1 += myWeight; } cout << "eventCount1 Event Count 1fb^-1 : " << eventCount1 << endl; double NormalizationWeight = eventCount0/eventCount1; cout << "Normalized Event Count 1fb^-1 : " << NormalizationWeight << endl; hDLepSel[0]->Divide(hDLepSel[1]); hDLepSel[2]->Divide(hDLepSel[3]); hDLepSel[4]->Divide(hDLepSel[5]); hDLepSel[6]->Divide(hDLepSel[7]); hDRatioPhotonElectron->Add(hDLepSel[2]); TFile *weightPE = new TFile("ratio_photon_electron.root", "RECREATE"); weightPE->cd(); hDRatioPhotonElectron->Write(); weightPE->Close(); //************************************************************************************************* // Create new normalized tree //************************************************************************************************* SmurfTree newEvent; newEvent.LoadTree(InputFilename1.Data()); newEvent.InitTree(0); newEvent.tree_->SetName("tree"); TString OutputFilename = InputFilename1; OutputFilename.ReplaceAll(".root","_newweight.root"); cout << "creating new root file: " << OutputFilename << endl; TFile *outputFile = new TFile(OutputFilename.Data(), "RECREATE"); outputFile->cd(); for(int i=0; i<8; i++) hDLepSel[i]->Write(); for(int i=0; i<20; i++) hDpSel[i]->Scale(1./hDpSel[i]->GetSumOfWeights()); for(int i=0; i<20; i++) hDpSel[i]->Write(); TTree *normalizedTree = newEvent.tree_->CloneTree(0); for (int n=0;n<newEvent.tree_->GetEntries();n++) { newEvent.tree_->GetEntry(n); newEvent.scale1fb_ = newEvent.scale1fb_*NormalizationWeight; if((vgammafoEvent.cuts_ & SmurfTree::Lep1LooseEleV2) == SmurfTree::Lep1LooseEleV2) newEvent.cuts_ |= SmurfTree::Lep1FullSelection; if((vgammafoEvent.cuts_ & SmurfTree::Lep2LooseEleV2) == SmurfTree::Lep2LooseEleV2) newEvent.cuts_ |= SmurfTree::Lep2FullSelection; if((vgammafoEvent.cuts_ & SmurfTree::Lep3LooseEleV2) == SmurfTree::Lep3LooseEleV2) newEvent.cuts_ |= SmurfTree::Lep3FullSelection; normalizedTree->Fill(); } normalizedTree->Write(); outputFile->Close(); }
int main(){ int nhit1, nhit2, evt, nVox[2500], nhit3; double x1[5000], y1[5000], z1[5000]; double xR[7000], yR[7000], zR[7000]; double x2[5000], y2[5000], z2[5000], xRes[5000], yRes[5000], vE[5000], xVe[2][5000], rawE[5000],nvoxX[5000], nvoxY[5000]; TFile *f1 = new TFile("mubarPlots.root","recreate"); TTree *tree = new TTree("h1","stuff"); tree->Branch("Event", &evt,"evtno/I"); tree->Branch("G4Hit", &nhit3,"nhit3/I"); tree->Branch("G4X",&xR,"xR[nhit3]/D"); tree->Branch("G4Y",&yR,"yR[nhit3]/D"); tree->Branch("G4Z",&zR,"zR[nhit3]/D"); tree->Branch("bhepHit",&nhit1,"nhit1/I"); tree->Branch("recHit",&nhit2,"nhit2/I"); tree->Branch("bhepX",&x1,"x1[nhit1]/D"); tree->Branch("bhepY",&y1,"y1[nhit1]/D"); tree->Branch("bhepZ",&z1,"z1[nhit1]/D"); tree->Branch("voxE", &vE,"vE[nhit1]/D"); tree->Branch("endXE",&xVe[0],"xVE[nhit1]/D"); tree->Branch("endYE",&xVe[1],"yVE[nhit1]/D"); tree->Branch("RawVoxE", &rawE,"rawE[nhit1]/D"); tree->Branch("recX",&x2,"x2[nhit2]/D"); tree->Branch("recY",&y2,"y2[nhit2]/D"); tree->Branch("recZ",&z2,"z2[nhit2]/D"); tree->Branch("xResolution",&xRes,"xRes[nhit2]/D"); tree->Branch("yResolution",&yRes,"yRes[nhit2]/D"); tree->Branch("nVox",&nVox,"nvox[nhit2]/I"); tree->Branch("nVoxX",&nvoxX,"nvoxX[nhit2]/D"); tree->Branch("nVoxY",&nvoxY,"nvoxY[nhit2]/D"); TH1F *voxXres = new TH1F("resX","Difference in voxel X and contained deposit Xs",200,-20,20); TH1F *voxYres = new TH1F("resY","Difference in voxel Y and contained deposit Ys",200,-20,20); int nevents=40000; string param_file = "examples/param/mubarCC_0.param"; bhep::gstore store; bhep::sreader reader(store); reader.file(param_file); reader.group("RUN"); reader.read(); hit_clusterer* hct = new hit_clusterer( store ); bhep::reader_root inDst; inDst.open("../digi_out/muCC/muCC_0_digi.dst.root"); //measurement_vector meas; std::vector<cluster*> meas; size_t countification; for (int i=0;i<nevents;i++){ cout << "Event: " << i << endl; bhep::event& e = inDst.read_event( i ); std::vector<bhep::particle*> parts = e.digi_particles(); for (size_t j=0;j < parts.size();j++){ countification = 0; std::vector<bhep::hit*> hits = parts[j]->hits("tracking"); if ( hits.size() == 0) continue; nhit1 = (int)hits.size(); nhit3 = 0; //std::cout << "Voxels before: " << nhit1 << std::endl; for (int k=0;k<nhit1;k++){ x1[k] = hits[k]->x()[0]; y1[k] = hits[k]->x()[1]; vdouble dX = hits[k]->vddata("Xpoint"); vdouble dY = hits[k]->vddata("Ypoint"); vdouble dZ = hits[k]->vddata("Zpoint"); vdouble dE = hits[k]->vddata("Epoint"); //nhit3 += (int)dX.size(); rawE[k] = 0; for (int vdiff=0;vdiff<(int)dX.size();vdiff++){ voxXres->Fill( x1[k]-dX[vdiff] ); voxYres->Fill( y1[k]-dY[vdiff] ); xR[nhit3] = dX[vdiff]; yR[nhit3] = dY[vdiff]; zR[nhit3] = dZ[vdiff]; nhit3++; rawE[k] += dE[vdiff]; } z1[k] = hits[k]->x()[2]; vE[k] = hits[k]->ddata("TotalEng"); xVe[0][k] = hits[k]->ddata("XEng"); xVe[1][k] = hits[k]->ddata("YEng"); } hct->execute(hits, meas); nhit2 = (int)meas.size(); for (int l=0;l<nhit2;l++){ x2[l] = meas[l]->position()[0]; y2[l] = meas[l]->position()[1]; z2[l] = meas[l]->position()[2]; vector<bhep::hit*> vs = meas[l]->get_hits(); double xx=0, yy=0,QQ=0,Q1; nVox[l] = (int)meas[l]->get_nVox(); nvoxX[l] = meas[l]->get_VoxX(); cout << meas[l]->get_VoxX() << endl; nvoxY[l] = meas[l]->get_VoxY(); for (size_t ll=0;ll<vs.size();ll++){ vdouble XX = vs[ll]->vddata("Xpoint"); vdouble YY = vs[ll]->vddata("Ypoint"); vdouble EE = vs[ll]->vddata("Epoint"); for (size_t lll=0;lll<XX.size();lll++){ Q1 = EE[lll];//vs[ll]->ddata( "truEng" ); QQ += Q1; xx += XX[lll]*Q1;//vs[ll]->x()[0]*Q1; yy += YY[lll]*Q1;//vs[ll]->x()[1]*Q1; } XX.clear(); YY.clear(); EE.clear(); } //cout << "Weight mean: " << xx/QQ << endl; xRes[l] = x2[l] - xx/QQ; yRes[l] = y2[l] - yy/QQ; } // for (int ii=0;ii<nhit2;ii++){ // countification += meas[ii]->get_nVox(); // std::cout << "MuProp meas["<<ii<<"] = " << meas[ii]->get_mu_prop() << std::endl; // } evt = i; tree->Fill(); } stc_tools::destroy(meas); parts.clear(); e.clear(); } inDst.close(); f1->Write(); f1->Close(); delete hct; return 0; }
int main (int argc, char *argv[]) { cout << endl; cout << " ,-----------------------," << endl; cout << " | Starting analysis |" << endl; cout << " `-----------------------`" << endl; cout << endl; // ################################## // # Some parameters for the user # // ################################## bool doHistoManager = false; // False will not produce histos bool doLatexOutput = true; // False will not produce latex table bool doPileUpReweigthing = false; // False will not use pileup reweighting // (can be overwritten by argv[1]) string defaultConfiguration("../../config/TTbarMETAnalysis.xml"); // (can be overwritten by argv[2]) string defaultLatexTableName("CutflowTable"); // (can be overwritten by argv[3]) string defaultRootOutputName("TTbarMETanalysis.root"); // ############################ // # Initializing variables # // ############################ INFO1_MSG << "Initializing variables..." << endl; vector < Dataset > datasets; TTbarMetSelection sel; float Luminosity = 0; float LumiError = 0.; int DataType = 0; // DataType : 0: MC - 1: Data - 2 Data & MC int verbosity = -1; reweight::LumiReWeighting *LumiWeights; IPHCTree::NTEvent * event = 0; std::vector<std::string> dileptonCol; dileptonCol.push_back("l+jets"); dileptonCol.push_back("ll"); dileptonCol.push_back("llHadrTau"); dileptonCol.push_back("llHadrTau3+"); std::vector<std::string> dileptonRow; dileptonRow.push_back("baseline"); dileptonRow.push_back("MET"); dileptonRow.push_back("stdVeto"); dileptonRow.push_back("stdVetoEff"); dileptonRow.push_back("vetoTest0"); dileptonRow.push_back("vetoTest0Eff"); dileptonRow.push_back("vetoTest1"); dileptonRow.push_back("vetoTest1Eff"); dileptonRow.push_back("vetoTest2"); dileptonRow.push_back("vetoTest2Eff"); dileptonRow.push_back("vetoTest3"); dileptonRow.push_back("vetoTest3Eff"); // Reading parameters from argv // -> configuration file string xmlFileName; if (argc > 1) xmlFileName = string(argv[1]); else xmlFileName = defaultConfiguration; // -> root output name string rootOutputName; if (argc > 2) rootOutputName = string(argv[2]); else rootOutputName = defaultRootOutputName; // -> latex table name string latexTableName; if (argc > 3) latexTableName = string(argv[3]); else latexTableName = defaultLatexTableName; // ############################# // # Loading configuration # // ############################# cout << endl; INFO1_MSG << "Loading configuration..." << endl; cout << " (config : " << xmlFileName << ")" << endl; AnalysisEnvironmentLoader anaEL (xmlFileName); anaEL.LoadSamples (datasets); // now the list of datasets written in the xml file is known anaEL.LoadSelection (sel); // now the parameters for the selection are given to the selection // no specific TTbarMET parameters anaEL.LoadGeneralInfo (DataType, Luminosity, LumiError, verbosity); // ######################################### // # Creating tables and histomanagers # // ######################################### cout << endl; INFO1_MSG << "Creating tables and histomanagers..." << endl; // Stuff TFile dileptonTreeFile("dileptonTree.root","RECREATE","Tree for Dilepton background study"); TTree *dileptonTree = new TTree("dileptonTree","Tree for Dilepton background study"); dileptonTree->Branch("dileptonData",&dileptonDataForTree,"iso_02:iso_03:iso_03_pT1GeV:iso_04:iso_05:iso_05_no01:iso_05_no015:iso_05_no015_pT1GeV:iso_05_no02:iso_045_no015:iso_055_no015:iso_05_no015_pTEqualIso02:hadronicMC_dRmeanDecay:hadronicMC_dRmaxDecay:hadronicMC_dRmeanChargedDecay:hadronicMC_dRmaxChargedDecay:hadronicMC_pTminChargedDecay:hadronicMC_pTmeanChargedDecay:hadronicMC_pTmaxChargedDecay:bestIso03_iso_03:bestIso03_iso_05_no015:bestIso03_iso_05_no01:bestIso03_iso_05_ntrk_01:bestIso03_iso_05_ntrk_015:bestIso03_iso_05_ntrk_015_pT1GeV:bestIso05no015_iso_03:bestIso05no015_iso_05_no015:bestIso05no015_iso_05_no01:bestIso05no015_iso_05_ntrk_01:bestIso05no015_iso_05_ntrk_015:bestIso05no015_iso_05_ntrk_015_pT1GeV:bestIso05no01_iso_03:bestIso05no01_iso_05_no015:bestIso05no01_iso_05_no01:bestIso05no01_iso_05_ntrk_01:bestIso05no01_iso_05_ntrk_015:bestIso05no01_iso_05_ntrk_015_pT1GeV:eventInfo_isSemilep:eventInfo_isDilep:eventInfo_haveTau:eventInfo_haveHadronicTau:eventInfo_haveHadronicTau3"); TableScrewdriver dileptonTable(dileptonCol,dileptonRow); dileptonTable.PrintTable(); // Tables SelectionTable selTable_e (sel.GetCutList (), datasets, string ("e")); SelectionTable selTable_mu (sel.GetCutList (), datasets, string ("µ")); SelectionTable selTable_l (sel.GetCutList (), datasets, string ("lepton")); // Histomanagers TTbarMetHistoManager histoManager; if(doHistoManager) { histoManager.LoadDatasets(datasets); histoManager.LoadSelectionSteps(sel.GetCutList ()); histoManager.LoadChannels(sel.GetChannelList ()); histoManager.CreateHistos(); } // HistoManager specific to Dilepton background analysis DileptonBkgAnaHistoManager histoManagerDileptonBkg; if(doHistoManager) { histoManagerDileptonBkg.LoadDatasets (datasets); histoManagerDileptonBkg.LoadSelectionSteps (sel.GetCutList ()); histoManagerDileptonBkg.LoadChannels (sel.GetChannelList ()); histoManagerDileptonBkg.CreateHistos (); } // ############################## // # Printing general infos # // ############################## cout << endl; cout << " -----------------------------" << endl; cout << " Verbosity mode : " << verbosity << endl; cout << " Luminosity : " << Luminosity << endl; cout << " DataType (whole config) : "; switch (DataType) { case 0: { cout << "MC" << endl; break; } case 1: { cout << "Data" << endl; break; } case 2: { cout << "Data & MC" << endl; break; } default: { cout << "Unknwon" << endl; break; } } cout << " -----------------------------" << endl; // ######################################### // # Start loop over the dataset infos # // ######################################### if (verbosity > 0) { cout << endl; cout << " ,---------------------------------," << endl; cout << " | Starting loop over datasets |" << endl; cout << " `---------------------------------`" << endl; cout << endl; } int nEvents_tot; for (unsigned int datasetId = 0; datasetId < datasets.size (); datasetId++) { // ######################## // # Load the dataset # // ######################## INFO1_MSG << "Loading next dataset..." << endl; datasets[datasetId].eventTree()->SetBranchAddress ("NTEvent", &event); unsigned int nEvents = static_cast<unsigned int>(datasets[datasetId].eventTree()->GetEntries ()); nEvents_tot = nEvents; if (verbosity > 2) { cout << endl; cout << " [ Dataset n°" << datasetId+1 << " ]" << endl; cout << " " << datasets[datasetId].Name() << endl; cout << endl; INFO1_MSG << " NEvents total : " << nEvents << endl; INFO1_MSG << "NEvents to run over : " << datasets[datasetId].NofEvtsToRunOver() << endl; cout << endl; } // ######################## // # Load the pile-up # // ######################## INFO1_MSG << "Loading pile-up informations..." << endl; // PU from JL's code if (datasets[datasetId].isData() == false) { // if(datasets[datasetId].Name() == "DY1" || datasets[datasetId].Name() == "signal" ){ // string datafile = "/opt/sbg/data/data1/cms/ccollard/CMSSW/CMSSW_4_2_8_patch7/src/NTuple/NTupleAnalysis/macros/data/PUdata.root"; // string mcfile = "/opt/sbg/data/data1/cms/ccollard/CMSSW/CMSSW_4_2_8_patch7/src/NTuple/NTupleAnalysis/macros/data/PU3DMC_Fall11.root"; // // LumiWeights = new reweight::LumiReWeighting(mcfile, datafile, "histoMCPU", "pileup" ); // } // else{ string datafile = "/opt/sbg/data/data1/cms/ccollard/CMSSW/CMSSW_4_2_8_patch7/src/NTuple/NTupleAnalysis/macros/data/default73.5mb.root"; string mcfile = "/opt/sbg/data/data1/cms/ccollard/CMSSW/CMSSW_4_2_8_patch7/src/NTuple/NTupleAnalysis/macros/data/PU3DMC.root"; LumiWeights = new reweight::LumiReWeighting(mcfile, datafile, "histoMCPU", "pileup" ); LumiWeights->weight3D_init( 1. ); // } } // ############################ // # Loop over the events # // ############################ if (verbosity > 0) { cout << endl; cout << " ,-------------------------------," << endl; cout << " | Starting loop over events |" << endl; cout << " `-------------------------------`" << endl; cout << endl; } for (unsigned int ievt = 0; ievt < datasets[datasetId].NofEvtsToRunOver(); ievt++) { // Display some information if (verbosity > 3) { INFO1_MSG << "run: " << event->general.runNb; std::cout << " lumi: " << event->general.lumiblock; std::cout << " event: " << event->general.eventNb; std::cout << std::endl; } if (ievt % 100000 == 0) printProgressBar(ievt,datasets[datasetId].NofEvtsToRunOver()); // Load the event datasets[datasetId].eventTree()->GetEntry(ievt); IPHCTree::NTTransient::InitializeAfterReading(event); int eventId = event->general.eventNb; sel.LoadEvent(event); // Get the weight for pile-up reweighting float weight = 1.; if (doPileUpReweigthing) { if(datasets[datasetId].isData() == false) weight = datasets[datasetId].NormFactor()*Luminosity; //if Data , weight = 1 float weightpu=1.; if(datasets[datasetId].isData() == false) { // MC // if( datasets[datasetId].Name() == "DY1" || datasets[datasetId].Name() == "signal") // { // double ave_npu = (event->pileup.before_npu+event->pileup.intime_npu+event->pileup.after_npu)/3.; // weightpu = LumiWeights->ITweight3BX(ave_npu); // } // else // { weightpu = LumiWeights->weight3D(event->pileup.before_npu, event->pileup.intime_npu, event->pileup.after_npu); // } // weight *= weightpu; //if Data , weight = 1 } // else // { // // DATA // JEC_L2L3Residuals.ApplyCorrections(event); // n'appliquer la correction que pour les donnees // } } // Apply full selection int triggerME = 0; int selLastStep = sel.doFullSelection (&(datasets[datasetId]), string("all"),&triggerME); // Get trigger info from selection bool trigger_e = false; bool trigger_mu = false; if (triggerME % 1 == 1) trigger_e = true; if (triggerME >= 10) trigger_mu = true; // Also get the lepton type int lep = sel.GetLeptonType(); // Fill the table // 1. No Selection selTable_e.Fill( datasetId, 0, weight); selTable_mu.Fill(datasetId, 0, weight); selTable_l.Fill( datasetId, 0, weight); // 2. Trigger if (selLastStep > 0) { selTable_l.Fill( datasetId, 1, weight); if (trigger_e) selTable_e.Fill( datasetId, 1, weight); if (trigger_mu) selTable_mu.Fill(datasetId, 1, weight); } // 3. Rest of the table for (unsigned int i = 2; i < (sel.GetCutList()).size() ; i++) { if (selLastStep >= (int) i && lep==0) selTable_e.Fill( datasetId, i, weight); if (selLastStep >= (int) i && lep==1) selTable_mu.Fill(datasetId, i, weight); if (selLastStep >= (int) i) selTable_l.Fill( datasetId, i, weight); } // Fill the histo int selLastStep_e = 0; int selLastStep_mu = 0; if (trigger_e) { selLastStep_e = 1; if (lep == 0) selLastStep_e=selLastStep; } if (trigger_mu) { selLastStep_mu = 1; if (lep == 1) selLastStep_mu=selLastStep; } histoManager.Fill(sel, event, sel.GetMuonsForAna(), sel.GetElectronsForAna(), selLastStep_e, 0, datasetId, weight); histoManager.Fill(sel, event, sel.GetMuonsForAna(), sel.GetElectronsForAna(), selLastStep_mu, 1, datasetId, weight); //histoManager.Fill(sel, event, sel.GetMuonsForAna(), sel.GetElectronsForAna(), selLastStep, 2, datasetId, weight); //dileptonBackgroundStudy(&sel,trigger_e,trigger_mu,lep,selLastStep,&histoManagerDileptonBkg,datasetId,weight); // Calculate efficiency for semi-leptonic and di-leptonic { const IPHCTree::NTMonteCarlo mcInfo = *(sel.GetPointer2MC()); int TMEME = mcInfo.TMEME; int MEME = TMEME % 10000; int EME = MEME % 1000; int ME = EME % 100; int E = ME % 10; int nTau = TMEME / 10000; int nMuFromTau = MEME / 1000; int nElFromTau = EME / 100; int nMuon = ME / 10; int nElec = E / 1; bool foundVeto0 = false; bool foundVeto1 = false; bool foundVeto2 = false; bool foundVeto3 = false; resetDileptonData(&dileptonDataForTree); if (selLastStep >= 5) { TLorentzVector lepton_p; // Get selected muon for the check if (sel.GetMuonsForAna().size()==1) lepton_p = (sel.GetMuonsForAna()[0]).p4; else lepton_p = (sel.GetElectronsForAna()[0]).p4; if (nTau > 0) { DEBUG_MSG << " NTauMC = " << nTau; if (nMuFromTau + nElFromTau == 0) cout << " hadr "; std::vector<IPHCTree::NTTau> localTaus = *(sel.GetPointer2Taus()); for(unsigned int i=0;i<localTaus.size();i++) { if ( lepton_p.DeltaR(localTaus[i].p4) < 0.1) continue; //DEBUG_MSG << "tipi 0" << endl; if (localTaus[i].leadTrackPt <= 5) continue; //DEBUG_MSG << "tipi 1" << endl; if ((localTaus[i].ID["byLooseIsolation"] != 1) && (localTaus[i].ID["byMediumIsolation"] != 1) && (localTaus[i].ID["byTightIsolation"] != 1) && (localTaus[i].ID["byLooseCombinedIsolationDeltaBetaCorr"] != 1) && (localTaus[i].ID["byMediumCombinedIsolationDeltaBetaCorr"] != 1) && (localTaus[i].ID["byTightCombinedIsolationDeltaBetaCorr"] != 1)) continue; if(fabs(localTaus[i].p4.Eta()) >= 2.5) continue; if(fabs(localTaus[i].p4.Eta())<1.566 && fabs(localTaus[i].p4.Eta())>1.4442) continue; if(localTaus[i].p4.Pt() < 5) continue; //if ( fabs( localTaus[i].vertex.Z() - sel.GetSelectedVertex()[0].p3.Z() ) > cfg.TauVertexMatchThr_ ) continue; if ( fabs( localTaus[i].D0) >= 0.04 ) continue; cout << " ; found"; } cout << endl; } // Output vector std::vector<IPHCTree::NTPFCandidate> vetotracks = sel.GetPFCandidates(); // Loop over pfcandidates tracks for(unsigned int i=0 ; i < vetotracks.size() ; i++) { if ((vetotracks[i].p4.Pt() > 10) && (fabs(vetotracks[i].dz_firstGoodVertex) < 0.05)) { TLorentzVector vetoTrack_p = vetotracks[i].p4; // Check pfcandidate doesnt match the selected lepton if (lepton_p.DeltaR(vetoTrack_p) > 0.1) { float thePt = vetotracks[i].p4.Pt(); if (dileptonDataForTree.iso_03 > vetotracks[i].others["iso_03"]/thePt) { dileptonDataForTree.iso_03 = vetotracks[i].others["iso_03"]/thePt; dileptonDataForTree.bestIso03_iso_03 = vetotracks[i].others["iso_03"]/thePt; dileptonDataForTree.bestIso03_iso_05_no015 = vetotracks[i].others["iso_05_no015"]/thePt; dileptonDataForTree.bestIso03_iso_05_no01 = vetotracks[i].others["iso_05_no01"]/thePt; dileptonDataForTree.bestIso03_iso_05_ntrk_01 = (float) vetotracks[i].others["ntrk_01"]; dileptonDataForTree.bestIso03_iso_05_ntrk_015 = (float) vetotracks[i].others["ntrk_015"]; dileptonDataForTree.bestIso03_iso_05_ntrk_015_pT1GeV = (float) vetotracks[i].others["ntrk_015_pT1GeV"]; } if (dileptonDataForTree.iso_05_no01 > vetotracks[i].others["iso_05_no01"]/thePt) { dileptonDataForTree.iso_05_no01 = vetotracks[i].others["iso_05_no01"]/thePt; dileptonDataForTree.bestIso05no01_iso_03 = vetotracks[i].others["iso_03"]/thePt; dileptonDataForTree.bestIso05no01_iso_05_no015 = vetotracks[i].others["iso_05_no015"]/thePt; dileptonDataForTree.bestIso05no01_iso_05_no01 = vetotracks[i].others["iso_05_no01"]/thePt; dileptonDataForTree.bestIso05no01_iso_05_ntrk_01 = (float) vetotracks[i].others["ntrk_01"]; dileptonDataForTree.bestIso05no01_iso_05_ntrk_015 = (float) vetotracks[i].others["ntrk_015"]; dileptonDataForTree.bestIso05no01_iso_05_ntrk_015_pT1GeV = (float) vetotracks[i].others["ntrk_015_pT1GeV"]; } if (dileptonDataForTree.iso_05_no015 > vetotracks[i].others["iso_05_no015"]/thePt) { dileptonDataForTree.iso_05_no015 = vetotracks[i].others["iso_05_no015"]/thePt; dileptonDataForTree.bestIso05no015_iso_03 = vetotracks[i].others["iso_03"]/thePt; dileptonDataForTree.bestIso05no015_iso_05_no015 = vetotracks[i].others["iso_05_no015"]/thePt; dileptonDataForTree.bestIso05no015_iso_05_no01 = vetotracks[i].others["iso_05_no01"]/thePt; dileptonDataForTree.bestIso05no015_iso_05_ntrk_01 = (float) vetotracks[i].others["ntrk_01"]; dileptonDataForTree.bestIso05no015_iso_05_ntrk_015 = (float) vetotracks[i].others["ntrk_015"]; dileptonDataForTree.bestIso05no015_iso_05_ntrk_015_pT1GeV = (float) vetotracks[i].others["ntrk_015_pT1GeV"]; } if (dileptonDataForTree.iso_02 > vetotracks[i].others["iso_02"]/thePt) dileptonDataForTree.iso_02 = vetotracks[i].others["iso_02"]/thePt; if (dileptonDataForTree.iso_04 > vetotracks[i].others["iso_04"]/thePt) dileptonDataForTree.iso_04 = vetotracks[i].others["iso_04"]/thePt; if (dileptonDataForTree.iso_05 > vetotracks[i].others["iso_05"]/thePt) dileptonDataForTree.iso_05 = vetotracks[i].others["iso_05"]/thePt; if (dileptonDataForTree.iso_03_pT1GeV > vetotracks[i].others["iso_03_pT1GeV"]/thePt) dileptonDataForTree.iso_03_pT1GeV = vetotracks[i].others["iso_03_pT1GeV"]/thePt; if (dileptonDataForTree.iso_05_no015_pT1GeV > vetotracks[i].others["iso_05_no015_pT1GeV"]/thePt) dileptonDataForTree.iso_05_no015_pT1GeV = vetotracks[i].others["iso_05_no015_pT1GeV"]/thePt; if (dileptonDataForTree.iso_05_no02 > vetotracks[i].others["iso_05_no02"]/thePt) dileptonDataForTree.iso_05_no02 = vetotracks[i].others["iso_05_no02"]/thePt; if (dileptonDataForTree.iso_045_no015 > vetotracks[i].others["iso_045_no015"]/thePt) dileptonDataForTree.iso_045_no015 = vetotracks[i].others["iso_045_no015"]/thePt; if (dileptonDataForTree.iso_055_no015 > vetotracks[i].others["iso_055_no015"]/thePt) dileptonDataForTree.iso_055_no015 = vetotracks[i].others["iso_055_no015"]/thePt; } } } // Loop over pfcandidates tracks for(unsigned int i=0 ; i < vetotracks.size() ; i++) { if ((vetotracks[i].p4.Pt() + vetotracks[i].others["iso_02"] > 10) && (fabs(vetotracks[i].dz_firstGoodVertex) < 0.05)) { TLorentzVector vetoTrack_p = vetotracks[i].p4; float thePt = vetotracks[i].p4.Pt() + vetotracks[i].others["iso_02"]; // Check pfcandidate doesnt match the selected lepton if (lepton_p.DeltaR(vetoTrack_p) > 0.1) { if (dileptonDataForTree.iso_05_no015_pTEqualIso02 > vetotracks[i].others["iso_05_no015"]/thePt) dileptonDataForTree.iso_05_no015_pTEqualIso02 = vetotracks[i].others["iso_05_no015"]/thePt; } } } string channelType(""); // Semi-leptonic case if (nTau + nMuon + nElec == 1) { dileptonDataForTree.eventInfo_isSemilep = 1.0; channelType = string("l+jets"); if (nTau >= 1) dileptonDataForTree.eventInfo_haveTau = 1.0; } // Di-leptonic case else if (nTau + nMuon + nElec >= 2) { dileptonDataForTree.eventInfo_isDilep = 1.0; channelType = string("ll"); if (nTau >= 1) { // Di-leptonic with a tau dileptonDataForTree.eventInfo_haveTau = 1.0; if (nMuFromTau + nElFromTau <= 0) { // Di-leptonic with a hadronic tau dileptonDataForTree.eventInfo_haveHadronicTau = 1.0; std::vector<IPHCTree::NTGenParticle> genParticles = mcInfo.genParticles; IPHCTree::NTGenParticle theGenTau; int genTauIndex = -1; bool foundTau = false; for (int i = 0 ; i < genParticles.size() ; i++) { IPHCTree::NTGenParticle particle = genParticles[i]; if (fabs(particle.id) != 15) continue; if (!foundTau) { theGenTau = particle; genTauIndex = i; } else { DEBUG_MSG << "Warning : second tau found in the event" << endl; } } int PKKPPL_ = theGenTau.decayMode; int KKPPL_ = PKKPPL_ % 100000; int KPPL_ = KKPPL_ % 10000; int PPL_ = KPPL_ % 1000; int PL_ = PPL_ % 100; int L_ = PL_ % 10; int numberOfPhotons = PKKPPL_ / 100000; int numberOfKCharged = KKPPL_ / 10000; int numberOfKZero = KPPL_ / 1000; int numberOfPiCharged = PPL_ / 100; int numberOfPiZero = PL_ / 10; int leptonFlavor = L_ / 1; int numberOfCharged = numberOfKCharged + numberOfPiCharged; if (numberOfCharged >= 3) dileptonDataForTree.eventInfo_haveHadronicTau3 = 1.0; // Compute dR mean between decays products // first we find the highest pt charged decay int maxPt = -1.0; IPHCTree::NTGenParticle maxPtChargedDecay; for (int i = 0 ; i < genParticles.size() ; i++) { IPHCTree::NTGenParticle particle = genParticles[i]; if (particle.motherIndex_ == genTauIndex) if (((abs(particle.id) == 211) || (abs(particle.id) == 321)) && (particle.p4.Pt() > maxPt)) { maxPt = particle.p4.Pt(); maxPtChargedDecay = particle; } } // then compute the sumDr float sumDr = 0.0; float DrMax = -1.0; int nDecay = 1; float sumDrCharged = 0.0; float DrMaxCharged = -1.0; float sumPtCharged = maxPtChargedDecay.p4.Pt(); float pTminCharged = maxPtChargedDecay.p4.Pt(); float pTmaxCharged = maxPtChargedDecay.p4.Pt(); int nDecayCharged = 1; for (int i = 0 ; i < genParticles.size() ; i++) { IPHCTree::NTGenParticle particle = genParticles[i]; if (particle.p4 == maxPtChargedDecay.p4) continue; if ((particle.motherIndex_ == genTauIndex) && (abs(particle.id) != 16)) { nDecay++; // For all decays sumDr += maxPtChargedDecay.p4.DeltaR(particle.p4); if (maxPtChargedDecay.p4.DeltaR(particle.p4) > DrMax) DrMax = maxPtChargedDecay.p4.DeltaR(particle.p4); // ChargedDecay if (((abs(particle.id) == 211) || (abs(particle.id) == 321))) { nDecayCharged++; sumPtCharged += particle.p4.Pt(); sumDrCharged += maxPtChargedDecay.p4.DeltaR(particle.p4); if (particle.p4.Pt() > pTmaxCharged) pTmaxCharged = particle.p4.Pt(); if (particle.p4.Pt() < pTminCharged) pTminCharged = particle.p4.Pt(); if (maxPtChargedDecay.p4.DeltaR(particle.p4) > DrMaxCharged) DrMaxCharged = maxPtChargedDecay.p4.DeltaR(particle.p4); } } } // Fill tree info dileptonDataForTree.hadronicMC_dRmeanDecay = sumDr / nDecay; dileptonDataForTree.hadronicMC_dRmaxDecay = DrMax; dileptonDataForTree.hadronicMC_dRmeanChargedDecay = sumDrCharged / nDecayCharged; dileptonDataForTree.hadronicMC_dRmaxChargedDecay = DrMaxCharged; dileptonDataForTree.hadronicMC_pTminChargedDecay = pTminCharged; dileptonDataForTree.hadronicMC_pTmeanChargedDecay = sumPtCharged / nDecayCharged; dileptonDataForTree.hadronicMC_pTmaxChargedDecay = pTmaxCharged; } } } if (channelType != string("")) { dileptonTable.Fill(channelType,"baseline",1.0); if (selLastStep >= 5) { dileptonTable.Fill(channelType,"MET" ,1.0); dileptonTable.Fill(channelType,"vetoTest0",(int) foundVeto0); dileptonTable.Fill(channelType,"vetoTest1",(int) foundVeto1); dileptonTable.Fill(channelType,"vetoTest2",(int) foundVeto2); dileptonTable.Fill(channelType,"vetoTest3",(int) foundVeto3); } if (selLastStep >= 6) dileptonTable.Fill(channelType,"stdVeto",1.0); } dileptonTree->Fill(); } } } // end of loop over evts } // end of loop over datasets dileptonTree->Print(); dileptonTreeFile.Write(); dileptonTreeFile.Close(); dileptonTable.PrintTable(); // ################################ // # Computations after loops # // ################################ cout << endl; cout << " ,-------------------------------," << endl; cout << " | Compute histos and tables |" << endl; cout << " `-------------------------------`" << endl; cout << endl; // Compute and save histograms if(!doHistoManager) INFO1_MSG << "HistoManagers [skipped]" << endl; else { INFO1_MSG << "HistoManagers ..." << endl; // Standard histograms histoManager.Compute (); string orootfilename = rootOutputName; TFile *fout = new TFile (orootfilename.c_str(), "RECREATE"); histoManager.Write (fout); fout->Close (); // DileptonBkg histograms histoManagerDileptonBkg.MergeChannels(); histoManagerDileptonBkg.DoMCStack(); histoManagerDileptonBkg.MergeMCDatasets(); histoManagerDileptonBkg.PlotsCutByCut(); string orootfilenameDileptonBkg; orootfilenameDileptonBkg = string("TTbarMETanalysis_DileptonBkgAna.root"); TFile *fout2 = new TFile (orootfilenameDileptonBkg.c_str(), "RECREATE"); histoManagerDileptonBkg.Write (fout2); fout2->Close(); string orootfilenameDileptonBkg2D; orootfilenameDileptonBkg2D = string("TTbarMETanalysis_DileptonBkgAna2D.root"); TFile *fout3 = new TFile (orootfilenameDileptonBkg2D.c_str(), "RECREATE"); histoManagerDileptonBkg.Write2D (fout3); fout3->Close(); // Clear histoManager.Clear (); histoManagerDileptonBkg.Clear (); delete fout; delete fout2; delete fout3; } // Write and compile tables if (!doLatexOutput) INFO1_MSG << "Tables [skipped]" << endl; { INFO1_MSG << "Tables ..." << endl; selTable_e.TableCalculator(); selTable_mu.TableCalculator(); selTable_l.TableCalculator(); makeSelectionTable(latexTableName,selTable_e,selTable_mu,selTable_l); } cout << endl; cout << " ,-----------------------," << endl; cout << " | Program completed |" << endl; cout << " `-----------------------`" << endl; cout << endl; return (0); }
TTree* ParseForTimestampData(ifstream *myFile, Int_t nRecordLength, string cUserColSep, Bool_t bIsGermanDecimal){ // +++ reset file reading position marker +++ if(myFile->tellg()>0){ myFile->clear(); // clear eof-bit myFile->seekg(0, ios::beg); // reset stream to beginning } // +++ decode time base information +++ if(nRecordLength<1){ cout << "Illegal record length: " << nRecordLength << endl; return (NULL); } //Double_t *fTimestamps = new Double_t[nRecordLength]; std::vector<Double_t> fTimestamps; fTimestamps.reserve(nRecordLength); // +++ extract first timestamp +++ Double_t fFirstTimestamp; string cCurrentLine; std::vector<string> cTimestampTokens; getline(*myFile, cCurrentLine, '\n'); // extract one line of data from file cTimestampTokens = LineParser(cCurrentLine,*cUserColSep.c_str()); // last column is amplitude (last two in case of German decimal identifier) if(cTimestampTokens.size()<2){ // check if enough columns have been found return (NULL); } string cTempDatum; if(bIsGermanDecimal){ cTempDatum = cTimestampTokens.at(cTimestampTokens.size()-4) + "." + cTimestampTokens.at(cTimestampTokens.size()-3); } else{ cTempDatum = cTimestampTokens.at(cTimestampTokens.size()-2); } fFirstTimestamp = atof(cTempDatum.c_str()); fTimestamps.push_back(fFirstTimestamp); while(myFile->good()){ // begin of loop over data file getline(*myFile, cCurrentLine, '\n'); // extract one line of data from file cTimestampTokens = LineParser(cCurrentLine,*cUserColSep.c_str()); // last column is amplitude (last two in case of German decimal identifier) if(cTimestampTokens.size()<2){ // check if enough columns have been found return (NULL); } string cTempDatum; if(bIsGermanDecimal){ cTempDatum = cTimestampTokens.at(cTimestampTokens.size()-4) + "." + cTimestampTokens.at(cTimestampTokens.size()-3); } else{ cTempDatum = cTimestampTokens.at(cTimestampTokens.size()-2); } if(fFirstTimestamp==atof(cTempDatum.c_str())) break; fTimestamps.push_back(atof(cTempDatum.c_str())); cTimestampTokens.clear(); cCurrentLine.clear(); } // end of loop over data file cout << fTimestamps.size() << " : " << nRecordLength << endl; if(fTimestamps.size()!=nRecordLength){ return (NULL); } // +++ create TTree for storing timestamp data +++ TTree *tUserTimestampData = new TTree(TIMESTAMPS_TREE_NAME,"Tektronix Fast Frame Timestamp Data"); std::stringstream cTimestampTreeEntry; cTimestampTreeEntry << "fTimestamps[" << nRecordLength << "]/D"; tUserTimestampData->Branch(TIMESTAMPS_BRANCH_NAME,&fTimestamps[0],cTimestampTreeEntry.str().c_str()); // +++ fill TTree +++ tUserTimestampData->Fill(); // +++ reset file input stream status +++ myFile->clear(); // clear eof-bit myFile->seekg(0, ios::beg); // reset stream to beginning //delete[] fTimestamps; fTimestamps.clear(); return (tUserTimestampData); }
void conv2CaloGeoView(const Char_t *input, const Char_t *output) { TChain *rootChain = new TChain("CollectionTree"); rootChain->Add(input); const Int_t nevent = rootChain->GetEntries(); cout << "Formating " << nevent << " events..." << endl; //Input vectors. UInt_t nClusters; vector<UInt_t> *rootNCells = new vector<UInt_t>; vector<UChar_t> *rootLayers = new vector<UChar_t>; vector<Float_t> *rootEnergy = new vector<Float_t>; vector<Float_t> *rootEta = new vector<Float_t>; vector<Float_t> *rootPhi = new vector<Float_t>; vector<UInt_t> *rootLVL1Id = new vector<UInt_t>; vector<UInt_t> *rootRoIId = new vector<UInt_t>; vector<Float_t> *rootLVL1Eta = new vector<Float_t>; vector<Float_t> *rootLVL1Phi = new vector<Float_t>; vector<Float_t> *rootLVL2Eta = new vector<Float_t>; vector<Float_t> *rootLVL2Phi = new vector<Float_t>; vector<Float_t> *rootLVL2Et = new vector<Float_t>; // Output vectors. UInt_t nCellsEM; vector<UChar_t> *layersEM = new vector<UChar_t>; vector<Float_t> *energyEM = new vector<Float_t>; vector<Float_t> *etaEM = new vector<Float_t>; vector<Float_t> *phiEM = new vector<Float_t>; UInt_t nCellsHAD; vector<UChar_t> *layersHAD = new vector<UChar_t>; vector<Float_t> *energyHAD = new vector<Float_t>; vector<Float_t> *etaHAD = new vector<Float_t>; vector<Float_t> *phiHAD = new vector<Float_t>; UInt_t lvl1Id; UInt_t roiId; Float_t lvl1Eta; Float_t lvl1Phi; Float_t lvl2Eta; Float_t lvl2Phi; Float_t lvl2Et; //Creating the output tree. TTree *outTree = new TTree("CollectionTree", "RoI for CaloGeoView."); outTree->Branch("NCellsLRoI", &nCellsEM, "NCellsLRoI/i"); outTree->Branch("DetCellsLRoI", &layersEM); outTree->Branch("ECellsLRoI", &energyEM); outTree->Branch("EtaCellsLRoI", &etaEM); outTree->Branch("PhiCellsLRoI", &phiEM); outTree->Branch("NCellsTRoI", &nCellsHAD, "NCellsTRoI/i"); outTree->Branch("DetCellsTRoI", &layersHAD); outTree->Branch("ECellsTRoI", &energyHAD); outTree->Branch("EtaCellsTRoI", &etaHAD); outTree->Branch("PhiCellsTRoI", &phiHAD); outTree->Branch("LVL1_Id", &lvl1Id, "LVL1_Id/i"); outTree->Branch("RoI_Id", &roiId, "RoI_Id/i"); outTree->Branch("LVL1_Eta", &lvl1Eta, "LVL1_Eta/f"); outTree->Branch("LVL1_Phi", &lvl1Phi, "LVL1_Phi/f"); outTree->Branch("LVL2_Eta", &lvl2Eta, "LVL2_Eta/f"); outTree->Branch("LVL2_Phi", &lvl2Phi, "LVL2_Phi/f"); outTree->Branch("LVL2_Et", &lvl2Et, "LVL2_Et/f"); //Selecting the branches we want to read. rootChain->SetBranchStatus("*",0); // disable all branches rootChain->SetBranchStatus("Ringer_NClusters",1); rootChain->SetBranchStatus("Ringer_NCells",1); rootChain->SetBranchStatus("Ringer_DetCells",1); rootChain->SetBranchStatus("Ringer_ECells",1); rootChain->SetBranchStatus("Ringer_EtaCells",1); rootChain->SetBranchStatus("Ringer_PhiCells",1); rootChain->SetBranchStatus("Ringer_LVL1_Id",1); rootChain->SetBranchStatus("Ringer_Roi_Id",1); rootChain->SetBranchStatus("Ringer_LVL1_Eta",1); rootChain->SetBranchStatus("Ringer_LVL1_Phi",1); rootChain->SetBranchStatus("Ringer_LVL2_Eta",1); rootChain->SetBranchStatus("Ringer_LVL2_Phi",1); rootChain->SetBranchStatus("Ringer_LVL2_Et",1); // Associating branches with the input vectors. rootChain->SetBranchAddress("Ringer_NClusters", &nClusters); rootChain->SetBranchAddress("Ringer_NCells", &rootNCells); rootChain->SetBranchAddress("Ringer_DetCells", &rootLayers); rootChain->SetBranchAddress("Ringer_ECells", &rootEnergy); rootChain->SetBranchAddress("Ringer_EtaCells", &rootEta); rootChain->SetBranchAddress("Ringer_PhiCells", &rootPhi); rootChain->SetBranchAddress("Ringer_LVL1_Id", &rootLVL1Id); rootChain->SetBranchAddress("Ringer_Roi_Id", &rootRoIId); rootChain->SetBranchAddress("Ringer_LVL1_Eta", &rootLVL1Eta); rootChain->SetBranchAddress("Ringer_LVL1_Phi", &rootLVL1Phi); rootChain->SetBranchAddress("Ringer_LVL2_Eta", &rootLVL2Eta); rootChain->SetBranchAddress("Ringer_LVL2_Phi", &rootLVL2Phi); rootChain->SetBranchAddress("Ringer_LVL2_Et", &rootLVL2Et); for (Int_t ev=0; ev<nevent; ev++) { rootChain->GetEntry(ev); if (!nClusters) continue; UInt_t roiCellBegin = 0; nCellsEM = nCellsHAD = 0; for (UInt_t roi=0; roi<nClusters; roi++) { //Copying RoI header values. lvl1Id = rootLVL1Id->at(roi); roiId = rootRoIId->at(roi); lvl1Eta = rootLVL1Eta->at(roi); lvl1Phi = rootLVL1Phi->at(roi); lvl2Eta = rootLVL2Eta->at(roi); lvl2Phi = rootLVL2Phi->at(roi); lvl2Et = rootLVL2Et->at(roi); //Copying the RoI elements. for (UInt_t c = roiCellBegin; c < (roiCellBegin+rootNCells->at(roi)); c++) { if (rootLayers->at(c) < 8) // If it is EM... { layersEM->push_back(rootLayers->at(c)); energyEM->push_back(rootEnergy->at(c)); etaEM->push_back(rootEta->at(c)); phiEM->push_back(rootPhi->at(c)); nCellsEM++; } else // If it is Hadronic... { layersHAD->push_back(rootLayers->at(c)); energyHAD->push_back(rootEnergy->at(c)); etaHAD->push_back(rootEta->at(c)); phiHAD->push_back(rootPhi->at(c)); nCellsHAD++; } } //Pointing to the next RoI. roiCellBegin += rootNCells->at(roi); //Saving to the output ntuple. outTree->Fill(); //Clearing the vectors for the next cycle. layersEM->clear(); energyEM->clear(); etaEM->clear(); phiEM->clear(); layersHAD->clear(); energyHAD->clear(); etaHAD->clear(); phiHAD->clear(); } } //Saving the NTuple file. TFile outFile(output, "RECREATE"); outTree->Write(); outFile.Close(); delete rootChain; delete outTree; delete rootNCells; delete rootLayers; delete rootEnergy; delete rootEta; delete rootPhi; delete layersEM; delete energyEM; delete etaEM; delete phiEM; delete layersHAD; delete energyHAD; delete etaHAD; delete phiHAD; }
void TestIdealGeometry::analyze( const edm::Event& iEvent, const edm::EventSetup& iSetup ) { //Retrieve tracker topology from geometry edm::ESHandle<TrackerTopology> tTopoHandle; iSetup.get<IdealGeometryRecord>().get(tTopoHandle); const TrackerTopology* const tTopo = tTopoHandle.product(); edm::LogInfo("TrackerAlignment") << "Starting!"; // // Read in the survey information from the text files // edm::ParameterSet textFiles = theParameterSet.getParameter<edm::ParameterSet>( "textFileNames" ); std::string textFileNames[NFILES]; std::string fileType[NFILES]; textFileNames[0] = textFiles.getUntrackedParameter<std::string>("forTIB","NONE"); fileType[0] = "TIB"; textFileNames[1] = textFiles.getUntrackedParameter<std::string>("forTID","NONE"); fileType[1] = "TID"; SurveyDataReader dataReader; for (int ii=0 ; ii<NFILES ;ii++) { if ( textFileNames[ii] == "NONE" ) throw cms::Exception("BadConfig") << fileType[ii] << " input file not found in configuration"; dataReader.readFile( textFileNames[ii], fileType[ii], tTopo ); } edm::LogInfo("TrackerAlignment") << "Files read"; const MapTypeOr& theSurveyMap = dataReader.surveyMap(); edm::LogInfo("TrackerAlignment") << "Map written"; // // Retrieve tracker geometry from event setup // edm::ESHandle<TrackerGeometry> trackerGeometry; iSetup.get<TrackerDigiGeometryRecord>().get( trackerGeometry ); // Retrieve alignment[Error]s from DBase // edm::ESHandle<Alignments> alignments; // iSetup.get<TrackerAlignmentRcd>().get( alignments ); // edm::ESHandle<AlignmentErrors> alignmentErrors; // iSetup.get<TrackerAlignmentErrorRcd>().get( alignmentErrors ); int countDet = 0; // Now loop on detector units, and store difference position and orientation w.r.t. survey for ( auto iGeomDet = trackerGeometry->dets().begin(); iGeomDet != trackerGeometry->dets().end(); iGeomDet++ ) // for (auto iGeomDet = alignments->m_align.begin(); // iGeomDet != alignments->m_align.end(); iGeomDet++ ) { if (countDet == 0) { // Enter only once for double-sided dets countDet++; unsigned int comparisonVect[6] = {0,0,0,0,0,0}; if (((*iGeomDet)->geographicalId()).subdetId() == int(StripSubdetector::TIB)) { comparisonVect[0] = int(StripSubdetector::TIB); comparisonVect[1] = tTopo->tibLayer((*iGeomDet)->geographicalId()); if (comparisonVect[1] < 3) countDet = countDet + 2; std::vector<unsigned int> theString = tTopo->tibStringInfo((*iGeomDet)->geographicalId()); comparisonVect[2] = theString[0]; comparisonVect[3] = theString[1]; comparisonVect[4] = theString[2]; comparisonVect[5] = tTopo->tibModule((*iGeomDet)->geographicalId()); } else if (((*iGeomDet)->geographicalId()).subdetId() == int(StripSubdetector::TID)) { comparisonVect[0] = int(StripSubdetector::TID); comparisonVect[1] = tTopo->tidSide((*iGeomDet)->geographicalId()); comparisonVect[2] = tTopo->tidWheel((*iGeomDet)->geographicalId()); comparisonVect[3] = tTopo->tidRing((*iGeomDet)->geographicalId()); if (comparisonVect[3] < 3) countDet = countDet + 2; std::vector<unsigned int> theModule = tTopo->tidModuleInfo((*iGeomDet)->geographicalId()); comparisonVect[4] = theModule[0]; comparisonVect[5] = theModule[1]; } for ( MapTypeOr::const_iterator it = theSurveyMap.begin(); it != theSurveyMap.end(); it++ ) { std::vector<int> locPos = (it)->first; align::Scalars align_params = (it)->second; if (locPos[0] == int(comparisonVect[0]) && locPos[1] == int(comparisonVect[1]) && locPos[2] == int(comparisonVect[2]) && locPos[3] == int(comparisonVect[3]) && locPos[4] == int(comparisonVect[4]) && locPos[5] == int(comparisonVect[5]) ) { Id_ = (*iGeomDet)->geographicalId().rawId(); cout << "DetId = " << Id_ << " " << endl; cout << "DetId decodified = " << comparisonVect[0] << " " << comparisonVect[1] << " " << comparisonVect[2] << " " << comparisonVect[3] << " " << comparisonVect[4] << " " << comparisonVect[5] << endl; dx_ = (*iGeomDet)->position().x() - align_params[0]; cout << "X pos : TRACKER_GEOM = " << std::fixed << std::setprecision(2) << (*iGeomDet)->position().x() << " / IDEAL RICCARDO = " << align_params[0] << endl; dy_ = (*iGeomDet)->position().y() - align_params[1]; cout << "Y pos : TRACKER_GEOM = " << std::fixed << std::setprecision(2) << (*iGeomDet)->position().y() << " / IDEAL RICCARDO = " << align_params[1] << endl; dz_ = (*iGeomDet)->position().z() - align_params[2]; cout << "Z pos : TRACKER_GEOM = " << std::fixed << std::setprecision(2) << (*iGeomDet)->position().z() << " / IDEAL RICCARDO = " << align_params[2] << endl; dtx_ = (*iGeomDet)->rotation().xx() - align_params[6]; cout << "Trans vect X : TRACKER_GEOM = " << std::fixed << std::setprecision(3) << (*iGeomDet)->rotation().xx() << " / IDEAL RICCARDO = " << align_params[6] << endl; dty_ = (*iGeomDet)->rotation().xy() - align_params[7]; cout << "Trans vect Y : TRACKER_GEOM = " << std::fixed << std::setprecision(3) << (*iGeomDet)->rotation().xy() << " / IDEAL RICCARDO = " << align_params[7] << endl; dtz_ = (*iGeomDet)->rotation().xz() - align_params[8]; cout << "Trans vect Z : TRACKER_GEOM = " << std::fixed << std::setprecision(3) << (*iGeomDet)->rotation().xz() << " / IDEAL RICCARDO = " << align_params[8] << endl; dkx_ = (*iGeomDet)->rotation().yx() - align_params[9]; cout << "Long vect X : TRACKER_GEOM = " << std::fixed << std::setprecision(3) << (*iGeomDet)->rotation().yx() << " / IDEAL RICCARDO = " << align_params[9] << endl; dky_ = (*iGeomDet)->rotation().yy() - align_params[10]; cout << "Long vect Y : TRACKER_GEOM = " << std::fixed << std::setprecision(3) << (*iGeomDet)->rotation().yy() << " / IDEAL RICCARDO = " << align_params[10] << endl; dkz_ = (*iGeomDet)->rotation().yz() - align_params[11]; cout << "Long vect Z : TRACKER_GEOM = " << std::fixed << std::setprecision(3) << (*iGeomDet)->rotation().yz() << " / IDEAL RICCARDO = " << align_params[11] << endl; dnx_ = (*iGeomDet)->rotation().zx() - align_params[3]; cout << "Norm vect X : TRACKER_GEOM = " << std::fixed << std::setprecision(3) << (*iGeomDet)->rotation().zx() << " / IDEAL RICCARDO = " << align_params[3] << endl; dny_ = (*iGeomDet)->rotation().zy() - align_params[4]; cout << "Norm vect Y : TRACKER_GEOM = " << std::fixed << std::setprecision(3) << (*iGeomDet)->rotation().zy() << " / IDEAL RICCARDO = " << align_params[4] << endl; dnz_ = (*iGeomDet)->rotation().zz() - align_params[5]; cout << "Norm vect Z : TRACKER_GEOM = " << std::fixed << std::setprecision(3) << (*iGeomDet)->rotation().zz() << " / IDEAL RICCARDO = " << align_params[5] << endl; theTree->Fill(); } } } countDet--; } edm::LogInfo("TrackerAlignment") << "Done!"; }
void applyenergy() { ROOT::Cintex::Cintex::Enable(); //printf("include: %s\n",gSystem->GetIncludePath()); //return; Long64_t maxentries = -1; //TFile *fmc = new TFile("/home/bendavid/cms/hist/hgg-v0-Sept1/local/filefi/merged/hgg-v0_s11-h120gg-gf-v11-pu_noskim.root","READ"); //TFile *fmc = new TFile("/scratch/bendavid/cms/hist/hgg-v0/merged/hgg-v0_f11--h121gg-gf-v14b-pu_noskim.root","READ"); TFile *fmc = new TFile("/scratch/bendavid/cms/hist/hgg-v0/merged/hgg-v0_f11-zjets-v14b-pu_noskim.root","READ"); //TFile *fmc = new TFile("/scratch/bendavid/cms/hist/hgg-v0/t2mit/filefi/025/f11--h121gg-gf-v14b-pu/hgg-v0_f11--h121gg-gf-v14b-pu_noskim_0000.root","READ"); TDirectory *dir = (TDirectory*)fmc->FindObjectAny("PhotonTreeWriterPresel"); TTree *hmcph = (TTree*)dir->Get("hPhotonTree"); TDirectory *dirsingle = (TDirectory*)fmc->FindObjectAny("PhotonTreeWriterSingle"); TTree *hmcsingleph = (TTree*)dirsingle->Get("hPhotonTree"); TFile *fmcele = new TFile("/scratch/bendavid/cms/hist/hgg-v0/merged/hgg-v0_f11-zjets-v14b-pu_noskim.root","READ"); TDirectory *direle = (TDirectory*)fmcele->FindObjectAny("PhotonTreeWriterE"); TTree *hmcele = (TTree*)direle->Get("hPhotonTree"); TDirectory *direlesingle = (TDirectory*)fmcele->FindObjectAny("PhotonTreeWriterE"); TTree *hmcelesingle = (TTree*)direlesingle->Get("hPhotonTreeSingle"); TFile *fdele = new TFile("/scratch/bendavid/cms/hist/hgg-v0/MergedDel2011J16.root","READ"); TDirectory *dirdele = (TDirectory*)fdele->FindObjectAny("PhotonTreeWriterE"); TTree *hdele = (TTree*)dirdele->Get("hPhotonTree"); TDirectory *dirdelesingle = (TDirectory*)fdele->FindObjectAny("PhotonTreeWriterE"); TTree *hdelesingle = (TTree*)dirdelesingle->Get("hPhotonTreeSingle"); TFile *fgbropt = new TFile("fgbrtraintest.root","READ"); const GBRForest *gbropt = (GBRForest*)fgbropt->Get("gbrtrain"); std::vector<std::string> *varlist = (std::vector<std::string>*)fgbropt->Get("varlist"); std::vector<std::string> *varlisteb = varlist; std::vector<std::string> *varlistee = varlist; const GBRForest *gbr = 0; const GBRForest *gbreb = gbropt; const GBRForest *gbree = gbropt; UInt_t nvarseb = varlisteb->size(); UInt_t nvarsee = varlistee->size(); Float_t *vals = 0; Float_t *valseb = new Float_t[nvarseb]; Float_t *valsee = new Float_t[nvarsee]; TFile *fmvacor = new TFile("fmvacor.root","RECREATE"); TTree *hmvacorph = new TTree("hmvacorph",""); TTree *hmvacorele = new TTree("hmvacorele",""); TTree *hmvacorelesingle = new TTree("hmvacorelesingle",""); TTree *hmvacordele = new TTree("hmvacordele",""); TTree *hmvacordelesingle = new TTree("hmvacordelesingle",""); TTree *hmvacorqcdsingle = new TTree("hmvacorqcdsingle",""); hmvacorele->SetAutoFlush(-1000000000); hmvacorelesingle->SetAutoFlush(-1000000000); hmvacordele->SetAutoFlush(-1000000000); hmvacordelesingle->SetAutoFlush(-1000000000); Float_t massmvacor=0.; Float_t massmvacorerr=0.; Float_t massmvacorerrlo=0.; Float_t massmvacorerrhi=0.; Float_t ph1emvacor=0.; Float_t ph1emvacorerr=0.; Float_t ph1emvacorerrlo=0.; Float_t ph1emvacorerrhi=0.; Float_t ph1bdt = 0.; Float_t ph1bdtvar = 0.; Int_t ph1dcoridx=0; Float_t ph1emvadcor=0.; Float_t ph2emvacor=0.; Float_t ph2emvacorerr=0.; Float_t ph2emvacorerrlo=0.; Float_t ph2emvacorerrhi=0.; Float_t ph2bdt = 0.; Float_t ph2bdtvar = 0.; Int_t ph2dcoridx=0; Float_t ph2emvadcor=0.; Float_t phemvacor=0.; Float_t phemvacorerr=0.; Float_t phbdt=0.; Float_t phbdtvar=0.; Int_t phdcoridx = 0; Float_t phemvadcor=0; Float_t phregtarget = 0.; for (UInt_t isample=1; isample<3; ++isample) { TTree *hmc = 0; TTree *hmvacor = 0; TTree *hmcsingle = 0; TTree *hmvacorsingle = 0; if (isample==0) { hmc = hmcph; hmvacor = hmvacorph; //hmcsingle = hmcqcdsingle; //hmvacorsingle = hmvacorqcdsingle; } else if (isample==1) { hmc = hmcele; hmvacor = hmvacorele; hmcsingle = hmcelesingle; hmvacorsingle = hmvacorelesingle; } else if (isample==2) { hmc = hdele; hmvacor = hmvacordele; hmcsingle = hdelesingle; hmvacorsingle = hmvacordelesingle; } // std::vector<TTreeFormula*> forms1; // std::vector<TTreeFormula*> forms2; // std::vector<TTreeFormula*> formssingle; TTreeFormula **formseb1 = new TTreeFormula*[nvarseb]; TTreeFormula **formseb2 = new TTreeFormula*[nvarseb]; TTreeFormula **formsebsingle = new TTreeFormula*[nvarseb]; for (UInt_t ivar=0; ivar<varlisteb->size(); ++ivar) { TString expression = varlisteb->at(ivar); expression.ReplaceAll("ph.genz","vtxZ"); TString expr1(expression); expr1.ReplaceAll("ph.","ph1."); TString expr2(expression); expr2.ReplaceAll("ph.","ph2."); printf("expr = %s, expr1 = %s, expr2 = %s\n",expression.Data(),expr1.Data(),expr2.Data()); formseb1[ivar] = new TTreeFormula(expr1,expr1,hmc); formseb2[ivar] = new TTreeFormula(expr2,expr2,hmc); if (hmcsingle) formsebsingle[ivar] = new TTreeFormula(expression,expression,hmcsingle); } TTreeFormula **formsee1 = new TTreeFormula*[nvarsee]; TTreeFormula **formsee2 = new TTreeFormula*[nvarsee]; TTreeFormula **formseesingle = new TTreeFormula*[nvarsee]; for (UInt_t ivar=0; ivar<varlistee->size(); ++ivar) { TString expression = varlistee->at(ivar); expression.ReplaceAll("ph.genz","vtxZ"); if (expression=="(1.0-(!ismc)*0.072)*ph.scpse/ph.scrawe") expression = "ph.scpse/ph.scrawe"; TString expr1(expression); expr1.ReplaceAll("ph.","ph1."); TString expr2(expression); expr2.ReplaceAll("ph.","ph2."); printf("expr = %s, expr1 = %s, expr2 = %s\n",expression.Data(),expr1.Data(),expr2.Data()); formsee1[ivar] = new TTreeFormula(expr1,expr1,hmc); formsee2[ivar] = new TTreeFormula(expr2,expr2,hmc); if (hmcsingle) formseesingle[ivar] = new TTreeFormula(expression,expression,hmcsingle); } TString denebexpr1 = "ph1.scrawe"; TString denebexpr2 = "ph2.scrawe"; TString denebexprsingle = "ph.scrawe"; TTreeFormula *denebform1 = new TTreeFormula(denebexpr1,denebexpr1,hmc); TTreeFormula *denebform2 = new TTreeFormula(denebexpr2,denebexpr2,hmc); TTreeFormula *denebformsingle = 0; if (hmcsingle) denebformsingle = new TTreeFormula(denebexprsingle,denebexprsingle,hmcsingle); // TString deneeexpr1 = "ph1.scrawe + (1.0-(!ismc)*0.072)*ph1.scpse"; // TString deneeexpr2 = "ph2.scrawe + (1.0-(!ismc)*0.072)*ph2.scpse"; TString deneeexpr1 = "ph1.scrawe + ph1.scpse"; TString deneeexpr2 = "ph2.scrawe + ph2.scpse"; TString deneeexprsingle = "ph.scrawe + ph.scpse"; TTreeFormula *deneeform1 = new TTreeFormula(deneeexpr1,deneeexpr1,hmc); TTreeFormula *deneeform2 = new TTreeFormula(deneeexpr2,deneeexpr2,hmc); TTreeFormula *deneeformsingle = 0; if (hmcsingle) deneeformsingle = new TTreeFormula(deneeexprsingle,deneeexprsingle,hmcsingle); TTreeFormula *costhetaform = new TTreeFormula("costheta","costheta",hmc); TString isbexpr1 = "ph1.isbarrel"; TString isbexpr2 = "ph2.isbarrel"; TString isbexprsingle = "ph.isbarrel"; TTreeFormula *isbform1 = new TTreeFormula(isbexpr1,isbexpr1,hmc); TTreeFormula *isbform2 = new TTreeFormula(isbexpr2,isbexpr2,hmc); TTreeFormula *isbformsingle = 0; if (hmcsingle) isbformsingle = new TTreeFormula(isbexprsingle,isbexprsingle,hmcsingle); hmvacor->Branch("massmvacor",&massmvacor,"massmvacor/F"); hmvacor->Branch("massmvacorerr",&massmvacorerr,"massmvacorerr/F"); //hmvacor->Branch("massmvacorerrlo",&massmvacorerrlo,"massmvacorerrlo/F"); //hmvacor->Branch("massmvacorerrhi",&massmvacorerrhi,"massmvacorerrhi/F"); hmvacor->Branch("ph1.emvacor",&ph1emvacor,"ph1.emvacor/F"); hmvacor->Branch("ph1.emvacorerr",&ph1emvacorerr,"ph1.emvacorerr/F"); hmvacor->Branch("ph1.bdt",&ph1bdt,"ph1.bdt/F"); hmvacor->Branch("ph1.bdtvar",&ph1bdtvar,"ph1.bdtvar/F"); hmvacor->Branch("ph1.dcoridx",&ph1dcoridx,"ph1.dcoridx/I"); hmvacor->Branch("ph1.emvadcor",&ph1emvadcor,"ph1.emvadcor/F"); //hmvacor->Branch("ph1.emvacorerrlo",&ph1emvacorerrlo,"ph1.emvacorerrlo/F"); //hmvacor->Branch("ph1.emvacorerrhi",&ph1emvacorerrhi,"ph1.emvacorerrhi/F"); hmvacor->Branch("ph2.emvacor",&ph2emvacor,"ph2.emvacor/F"); hmvacor->Branch("ph2.emvacorerr",&ph2emvacorerr,"ph2.emvacorerr/F"); hmvacor->Branch("ph2.bdt",&ph2bdt,"ph2.bdt/F"); hmvacor->Branch("ph2.bdtvar",&ph2bdtvar,"ph2.bdtvar/F"); hmvacor->Branch("ph2.dcoridx",&ph2dcoridx,"ph2.dcoridx/I"); hmvacor->Branch("ph2.emvadcor",&ph2emvadcor,"ph2.emvadcor/F"); //hmvacor->Branch("ph2.emvacorerrlo",&ph2emvacorerrlo,"ph2.emvacorerrlo/F"); //hmvacor->Branch("ph2.emvacorerrhi",&ph2emvacorerrhi,"ph2.emvacorerrhi/F"); if (hmvacorsingle) { hmvacorsingle->Branch("ph.emvacor",&phemvacor,"ph.emvacor/F"); hmvacorsingle->Branch("ph.emvacorerr",&phemvacorerr,"ph.emvacorerr/F"); hmvacorsingle->Branch("ph.dcoridx",&phdcoridx,"ph.dcoridx/I"); hmvacorsingle->Branch("ph.emvadcor",&phemvadcor,"ph.emvadcor/F"); //hmvacor->Branch("ph.bdt",&ph1bdt,"ph.bdt/F"); //hmvacor->Branch("ph.bdtvar",&ph1bdtvar,"ph.bdtvar/F"); } //TString method = "MLP method"; //TString method = "BDT method"; TString method = "BDTG method"; //TString method = "PDEFoam method"; for (Long64_t i=0; i<hmc->GetEntries(); ++i) { hmc->LoadTree(i); float den1, den2; bool isb1 = isbform1->EvalInstance(); bool isb2 = isbform2->EvalInstance(); if (isb1) { gbr = gbreb; //gbrvar = gbrvareb; //gbrdcor = gbrdcoreb; vals = valseb; den1 = denebform1->EvalInstance(); for (UInt_t ivar=0; ivar<nvarseb; ++ivar) { valseb[ivar] = formseb1[ivar]->EvalInstance(); } } else { gbr = gbree; //gbrvar = gbrvaree; //gbrdcor = gbrdcoree; vals = valsee; den1 = deneeform1->EvalInstance(); for (UInt_t ivar=0; ivar<nvarsee; ++ivar) { valsee[ivar] = formsee1[ivar]->EvalInstance(); } } phregtarget = gbr->GetResponse(vals); ph1emvacor = phregtarget*den1; //printf("phregtarget = %5f, ph1emvacor = %5f\n",phregtarget,ph1emvacor); if (isb2) { gbr = gbreb; vals = valseb; den2 = denebform2->EvalInstance(); for (UInt_t ivar=0; ivar<nvarseb; ++ivar) { valseb[ivar] = formseb2[ivar]->EvalInstance(); } } else { gbr = gbree; vals = valsee; den2 = deneeform2->EvalInstance(); for (UInt_t ivar=0; ivar<nvarsee; ++ivar) { valsee[ivar] = formsee2[ivar]->EvalInstance(); } } phregtarget = gbr->GetResponse(vals); ph2emvacor = phregtarget*den2; massmvacor = TMath::Sqrt(2.0*ph1emvacor*ph2emvacor*(1.0-costhetaform->EvalInstance())); //massmvacorerr = 0.5*massmvacor*TMath::Sqrt(ph1emvacorerr*ph1emvacorerr/ph1emvacor/ph1emvacor + ph2emvacorerr*ph2emvacorerr/ph2emvacor/ph2emvacor); //massmvacorerrlo = 0.5*massmvacor*TMath::Sqrt(ph1emvacorerrlo*ph1emvacorerrlo/ph1emvacor/ph1emvacor + ph2emvacorerrlo*ph2emvacorerrlo/ph2emvacor/ph2emvacor); //massmvacorerrhi = 0.5*massmvacor*TMath::Sqrt(ph1emvacorerrhi*ph1emvacorerrhi/ph1emvacor/ph1emvacor + ph2emvacorerrhi*ph2emvacorerrhi/ph2emvacor/ph2emvacor); hmvacor->Fill(); } hmc->AddFriend(hmvacor); hmvacor->Write(); if (hmcsingle) { for (Long64_t i=0; i<hmcsingle->GetEntries(); ++i) { hmcsingle->LoadTree(i); float den; bool isbsingle = isbformsingle->EvalInstance(); if (isbsingle) { gbr = gbreb; vals = valseb; den = denebformsingle->EvalInstance(); for (UInt_t ivar=0; ivar<nvarseb; ++ivar) { valseb[ivar] = formsebsingle[ivar]->EvalInstance(); } } else { gbr = gbree; vals = valsee; den = deneeformsingle->EvalInstance(); for (UInt_t ivar=0; ivar<nvarsee; ++ivar) { valsee[ivar] = formseesingle[ivar]->EvalInstance(); } } phregtarget = gbr->GetResponse(vals); phemvacor = phregtarget*den; hmvacorsingle->Fill(); } hmcsingle->AddFriend(hmvacorsingle); hmvacorsingle->Write(); } } // }
template <class HolderClass> void write(const char *testname, int nEntry = 3) { bool testingTopLevelVectors = true; TString dirname = gROOT->GetVersion(); dirname.ReplaceAll(".","-"); dirname.ReplaceAll("/","-"); gSystem->mkdir(dirname); gSystem->Unlink("latest"); gSystem->Symlink(dirname,"latest"); TString filename = gSystem->ConcatFileName(dirname, testname ); filename += ".root"; TFile *file = new TFile(filename,"RECREATE","stl test file",0); HolderClass *holder = new HolderClass( 0 ); // Write(file,"scalar",holder->fScalar) // Write(file,"object",holder->fObject) // Write(file,"nested",holder->fNested) holder->Write("holder"); TString classname = holder->IsA()->GetName(); TTree *tree = new TTree("stltree","testing stl containers"); tree->Branch("split_2.",classname,&holder,32000,-2); tree->Branch("split_1.",classname,&holder,32000,-1); tree->Branch("split0.",classname,&holder,32000,0); tree->Branch("split1.",classname,&holder,32000,1); tree->Branch("split2.",classname,&holder,32000,2); tree->Branch("split99.",classname,&holder,32000,99); if (testingTopLevelVectors) { TClass *cls = gROOT->GetClass(typeid(holder->fScalar)); if (!cls) { TestError("TreeBuilding", Form("Writing holder class: Missing class for %s", typeid(holder->fScalar).name())); } else { tree->Branch("scalar0.",&(holder->fScalarPtr),32000,0); tree->Branch("scalar1.",&(holder->fScalarPtr),32000,1); tree->Branch("scalar2.",&(holder->fScalarPtr),32000,2); tree->Branch("scalar99.",&(holder->fScalarPtr),32000,99); } TClass *clo = gROOT->GetClass(typeid(holder->fObject)); if (!clo) { TestError("TreeBuilding", Form("Writing holder class: Missing class for %s", typeid(holder->fObject).name())); } else { tree->Branch("object0." ,&(holder->fObjectPtr),32000,0); tree->Branch("object1." ,&(holder->fObjectPtr),32000,1); tree->Branch("object2." ,&(holder->fObjectPtr),32000,2); tree->Branch("object99.",&(holder->fObjectPtr),32000,99); } TClass *cln = gROOT->GetClass(typeid(holder->fNested)); if (!cln) { TestError("TreeBuilding", Form("Writing holder class: Missing class for %s", typeid(holder->fNested).name())); } else { tree->Branch("nested0." ,&(holder->fNestedPtr),32000,0); tree->Branch("nested1." ,&(holder->fNestedPtr),32000,1); tree->Branch("nested2." ,&(holder->fNestedPtr),32000,2); tree->Branch("nested99.",&(holder->fNestedPtr),32000,99); } } for(int i=0; i<nEntry; i++) { holder->Reset(i); tree->Fill(); } file->Write(); delete file; }
void ConvertLUTdata(){ TFile *f = new TFile(fileout, "RECREATE"); int ADC; int board; //float Voltage[numChannelsPerBoard*numBoardsforLUT][psecSampleCells][4096]; /* put on heap memory so compiling works */ float*** Voltage; Voltage = new float**[numChannelsPerBoard*numBoardsforLUT]; for(int j=0; j<numBoardsforLUT; j++){ for(int chan=0; chan<numChannelsPerBoard; chan++){ Voltage[chan+j*numChannelsPerBoard] = new float*[psecSampleCells]; for(int samp=0; samp<psecSampleCells; samp++) Voltage[chan+j*numChannelsPerBoard][samp] = new float[4096]; } } float V[numChannelsPerBoard*numBoardsforLUT][psecSampleCells]; char Voltage_leaf[200]; char* filein; sprintf(Voltage_leaf, "Voltage[%i][256]/F",numChannelsPerBoard*numBoardsforLUT); TTree *Tlut = new TTree("Tlut", "Tlut"); TBranch *_ADC = Tlut->Branch("ADC", &ADC, "ADC/I"); //TBranch *_numBoardsForLUT =Tlut->Branch("numBoardsforLUT", &numBoardsforLUT, "numBoardsforLUT/I"); TBranch *_Voltage =Tlut->Branch("Voltage", &V, Voltage_leaf); /* open cal data .txt file */ for(int fileNum = 0; fileNum < numBoardsforLUT; fileNum++){ ifstream ifs; if(fileNum == 0) filein = lut_file_0; if(fileNum == 1) filein = lut_file_1; if(fileNum == 2) filein = lut_file_2; /*...etc..*/ ifs.open(filein, ios::in); if(!ifs) cout << "error opening file" << endl; /* go through data file */ board = 0; int row = 0, tmp; float temp = 0.; while(ifs){ int channel, sample; ifs >> tmp; //cout << row << ":" << ADC[row] << ":" << numChannelsPerBoard*fileNum << endl; for(int i=0; i<numChannelsPerBoard; i++){ for(int j=0; j<psecSampleCells; j++){ ifs >> temp; channel = i; sample = j; Voltage[channel+numChannelsPerBoard*fileNum][sample][row] = temp; } } row++; if(row > 4095) break; } ifs.close(); cout << "finished processing file " << fileNum+1 << " of " << numBoardsforLUT << endl; } cout << "Now, organize and save to ROOT Tree.." << endl; /* this is a messy way to go about this.. */ for(int i=0; i<4096; i++){ ADC = i; for(int fileNum = 0; fileNum < numBoardsforLUT; fileNum++) for(int channel=0; channel<numChannelsPerBoard; channel++) for(int sample=0; sample<psecSampleCells; sample++) V[channel+numChannelsPerBoard*fileNum][sample] = Voltage[channel+numChannelsPerBoard*fileNum][sample][i]; Tlut->Fill(); } Tlut->Write(); f->Close(); cout << "Done" << endl; return; }
int loop(TString infile="/store/group/phys_heavyions/velicanu/forest/Run2015E/ExpressPhysics/Merged/HiForestExpress_baobab.root", TString outfile="/data/wangj/Data2015/Bntuple/ntB_20151130_HiForestExpress_baobab.root", Bool_t REAL=true, Bool_t isPbPb=false, Int_t startEntries=0, Bool_t skim=false, Bool_t gskim=true, Bool_t checkMatching=false) { void fillTree(TVector3* bP, TVector3* bVtx, TLorentzVector* b4P, Int_t j, Int_t typesize, Double_t track_mass1, Double_t track_mass2, Bool_t REAL); bool signalGen(Int_t Btype, Int_t j); cout<<endl; if(REAL) cout<<"--- Processing - REAL DATA"<<endl; else cout<<"--- Processing - MC"<<endl; TString ifname; if(iseos) ifname = Form("root://eoscms.cern.ch//eos/cms%s",infile.Data()); else ifname = infile; TFile* f = TFile::Open(ifname); TTree* root = (TTree*)f->Get("Bfinder/root"); TTree* hltroot = (TTree*)f->Get("hltanalysis/HltTree"); TTree* hiroot = (TTree*)f->Get("hiEvtAnalyzer/HiTree"); TFile* outf = new TFile(outfile,"recreate"); setBBranch(root); setHltBranch(hltroot); if(isPbPb) setHiTreeBranch(hiroot); int ifchannel[7]; ifchannel[0] = 1; //jpsi+Kp ifchannel[1] = 1; //jpsi+pi ifchannel[2] = 1; //jpsi+Ks(pi+,pi-) ifchannel[3] = 1; //jpsi+K*(K+,pi-) ifchannel[4] = 1; //jpsi+K*(K-,pi+) ifchannel[5] = 1; //jpsi+phi(K+,K-) ifchannel[6] = 1; //jpsi+pi pi <= psi', X(3872), Bs->J/psi f0 cout<<"--- Building trees"<<endl; TTree* nt0 = new TTree("ntKp",""); buildBranch(nt0); TTree* nt1 = new TTree("ntpi",""); buildBranch(nt1); TTree* nt2 = new TTree("ntKs",""); buildBranch(nt2); TTree* nt3 = new TTree("ntKstar",""); buildBranch(nt3); TTree* nt5 = new TTree("ntphi",""); buildBranch(nt5); TTree* nt6 = new TTree("ntmix",""); buildBranch(nt6); TTree* ntGen = new TTree("ntGen",""); buildGenBranch(ntGen); TTree* ntHlt = hltroot->CloneTree(0); TTree* ntHi = hiroot->CloneTree(0); cout<<"--- Building trees finished"<<endl; Long64_t nentries = root->GetEntries(); TVector3* bP = new TVector3; TVector3* bVtx = new TVector3; TLorentzVector* b4P = new TLorentzVector; TLorentzVector* b4Pout = new TLorentzVector; TLorentzVector* bGen = new TLorentzVector; cout<<"--- Check the number of events for two trees"<<endl; cout<<root->GetEntries()<<" "<<hltroot->GetEntries(); if(isPbPb) cout<<" "<<hiroot->GetEntries(); cout<<endl; cout<<"--- Processing events"<<endl; //nentries=1000; for(Int_t i=startEntries;i<nentries;i++) { root->GetEntry(i); hltroot->GetEntry(i); if(isPbPb) hiroot->GetEntry(i); if(i%100000==0) cout<<setw(8)<<i<<" / "<<nentries<<endl; if(checkMatching) { if((Int_t)Bf_HLT_Event!=EvtInfo_EvtNo||Bf_HLT_Run!=EvtInfo_RunNo||Bf_HLT_LumiBlock!=EvtInfo_LumiNo || (isPbPb&&(Bf_HiTree_Evt!=EvtInfo_EvtNo||Bf_HiTree_Run!=EvtInfo_RunNo||Bf_HiTree_Lumi!=EvtInfo_LumiNo))) { cout<<"Error: not matched "<<i<<" | "; cout<<"EvtNo("<<Bf_HLT_Event<<","<<EvtInfo_EvtNo<<") RunNo("<<Bf_HLT_Run<<","<<EvtInfo_RunNo<<") LumiNo("<<Bf_HLT_LumiBlock<<","<<EvtInfo_LumiNo<<") | EvtNo("<<Bf_HiTree_Evt<<","<<EvtInfo_EvtNo<<") RunNo("<<Bf_HiTree_Run<<","<<EvtInfo_RunNo<<") LumiNo("<<Bf_HiTree_Lumi<<","<<EvtInfo_LumiNo<<")"<<endl; continue; } } Int_t Btypesize[7]={0,0,0,0,0,0,0}; Int_t ptflag=-1,ptMatchedflag=-1,probflag=-1,probMatchedflag=-1,tktkflag=-1,tktkMatchedflag=-1; Double_t pttem=0,ptMatchedtem=0,probtem=0,probMatchedtem=0,tktktem=0,tktkMatchedtem=0; for(Int_t t=0;t<7;t++) { Int_t tidx = t-1; if(t!=4) { tidx = t; Bsize = 0; ptflag = -1; pttem = 0; ptMatchedflag = -1; ptMatchedtem = 0; probflag = -1; probtem = 0; probMatchedflag = -1; probMatchedtem = 0; tktkflag = -1; tktktem = 1000000.; tktkMatchedflag = -1; tktkMatchedtem = 1000000.; } if(ifchannel[t]==1) { for(int j=0;j<BInfo_size;j++) { if(BInfo_type[j]==(t+1)) { fillTree(bP,bVtx,b4P,j,Btypesize[tidx],tk1mass[t],tk2mass[t],REAL); if(BInfo_pt[j]>pttem) { ptflag = Btypesize[tidx]; pttem = BInfo_pt[j]; } if(TMath::Prob(BInfo_vtxchi2[j],BInfo_vtxdof[j])>probtem) { probflag = Btypesize[tidx]; probtem = TMath::Prob(BInfo_vtxchi2[j],BInfo_vtxdof[j]); } if(BInfo_type[j]>2&&BInfo_type[j]<7) { if(TMath::Abs(BInfo_tktk_mass[j]-midmass[t])<tktktem) { tktkflag = Btypesize[tidx]; tktktem = TMath::Abs(BInfo_tktk_mass[j]-midmass[t]); } } if((!REAL&&(Bgen[Btypesize[tidx]]==23333||Bgen[Btypesize[tidx]]==41000))||REAL)////////////////////////////// { if(BInfo_pt[j]>ptMatchedtem) { ptMatchedflag = Btypesize[tidx]; ptMatchedtem = BInfo_pt[j]; } if(TMath::Prob(BInfo_vtxchi2[j],BInfo_vtxdof[j])>probMatchedtem) { probMatchedflag = Btypesize[tidx]; probMatchedtem = TMath::Prob(BInfo_vtxchi2[j],BInfo_vtxdof[j]); } if(BInfo_type[j]>2&&BInfo_type[j]<7) { if(TMath::Abs(BInfo_tktk_mass[j]-midmass[t])<tktkMatchedtem) { tktkMatchedflag = Btypesize[tidx]; tktkMatchedtem = TMath::Abs(BInfo_tktk_mass[j]-midmass[t]); } } } Btypesize[tidx]++; } } if(t!=3) { if(ptflag>=0) Bmaxpt[ptflag] = true; if(probflag>=0) Bmaxprob[probflag] = true; if(tktkflag>=0) Bbesttktkmass[tktkflag] = true; if(ptMatchedflag>=0) BmaxptMatched[ptMatchedflag] = true; if(probMatchedflag>=0) BmaxprobMatched[probMatchedflag] = true; if(tktkMatchedflag>=0) BbesttktkmassMatched[tktkMatchedflag] = true; } if(t==0) nt0->Fill(); else if(t==1) nt1->Fill(); else if(t==2) nt2->Fill(); else if(t==4) nt3->Fill(); else if(t==5) nt5->Fill(); else if(t==6) nt6->Fill(); } } ntHlt->Fill(); if(isPbPb) ntHi->Fill(); if(!REAL) { Int_t gt=0,sigtype=0; Int_t gsize=0; Gsize = 0; for(int j=0;j<GenInfo_size;j++) { if((TMath::Abs(GenInfo_pdgId[j])!=BPLUS_PDGID&&TMath::Abs(GenInfo_pdgId[j])!=BZERO_PDGID&&TMath::Abs(GenInfo_pdgId[j])!=BSUBS_PDGID) && gskim) continue; Gsize = gsize+1; Gpt[gsize] = GenInfo_pt[j]; Geta[gsize] = GenInfo_eta[j]; Gphi[gsize] = GenInfo_phi[j]; GpdgId[gsize] = GenInfo_pdgId[j]; bGen->SetPtEtaPhiM(GenInfo_pt[j],GenInfo_eta[j],GenInfo_phi[j],GenInfo_mass[j]); Gy[gsize] = bGen->Rapidity(); sigtype=0; for(gt=1;gt<8;gt++) { if(signalGen(gt,j)) { sigtype=gt; break; } } GisSignal[gsize] = sigtype; Gmu1pt[gsize] = -1; Gmu1eta[gsize] = -20; Gmu1phi[gsize] = -20; Gmu1p[gsize] = -1; Gmu2pt[gsize] = -1; Gmu2eta[gsize] = -20; Gmu2phi[gsize] = -20; Gmu2p[gsize] = -1; Gtk1pt[gsize] = -1; Gtk1eta[gsize] = -20; Gtk1phi[gsize] = -20; Gtk2pt[gsize] = -1; Gtk2eta[gsize] = -20; Gtk2phi[gsize] = -20; if(sigtype!=0) { Gmu1pt[gsize] = GenInfo_pt[GenInfo_da1[GenInfo_da1[j]]]; Gmu1eta[gsize] = GenInfo_eta[GenInfo_da1[GenInfo_da1[j]]]; Gmu1phi[gsize] = GenInfo_phi[GenInfo_da1[GenInfo_da1[j]]]; Gmu1p[gsize] = Gmu1pt[gsize]*cosh(Gmu1eta[gsize]); Gmu2pt[gsize] = GenInfo_pt[GenInfo_da2[GenInfo_da1[j]]]; Gmu2eta[gsize] = GenInfo_eta[GenInfo_da2[GenInfo_da1[j]]]; Gmu2phi[gsize] = GenInfo_phi[GenInfo_da2[GenInfo_da1[j]]]; Gmu2p[gsize] = Gmu2pt[gsize]*cosh(Gmu2eta[gsize]); if(sigtype==1||sigtype==2) { Gtk1pt[gsize] = GenInfo_pt[GenInfo_da2[j]]; Gtk1eta[gsize] = GenInfo_eta[GenInfo_da2[j]]; Gtk1phi[gsize] = GenInfo_phi[GenInfo_da2[j]]; } else { Gtk1pt[gsize] = GenInfo_pt[GenInfo_da1[GenInfo_da2[j]]]; Gtk1eta[gsize] = GenInfo_eta[GenInfo_da1[GenInfo_da2[j]]]; Gtk1phi[gsize] = GenInfo_phi[GenInfo_da1[GenInfo_da2[j]]]; Gtk2pt[gsize] = GenInfo_pt[GenInfo_da2[GenInfo_da2[j]]]; Gtk2eta[gsize] = GenInfo_eta[GenInfo_da2[GenInfo_da2[j]]]; Gtk2phi[gsize] = GenInfo_phi[GenInfo_da2[GenInfo_da2[j]]]; } } gsize++; } ntGen->Fill(); } } outf->Write(); outf->Close(); return 1; }
int main (int argc, char** argv) { // load framework libraries gSystem->Load( "libFWCoreFWLite" ); //gSystem->Load("libNtupleMakerBEANmaker.so"); AutoLibraryLoader::enable(); int debug = 0; // levels of debug, 10 is large JobParameters myConfig = parseJobOptions(argc, argv); TFile * outputFile = new TFile (myConfig.outputFileName.c_str(), "RECREATE"); outputFile->cd(); TTree * summaryTree = new TTree("summaryTree", "Summary Event Values"); fwlite::ChainEvent ev(myConfig.inputFileNames); HelperLeptonCore lepHelper; // setup the analysis // it comes from the lepHelper BEANhelper * beanHelper = lepHelper.setupAnalysisParameters("2012_53x", myConfig.sampleName); sysType::sysType jetSyst = sysType::NA; if (myConfig.jetSyst == "NA") jetSyst = sysType::NA; else if (myConfig.jetSyst == "JESUp") jetSyst = sysType::JESup; else if (myConfig.jetSyst == "JESDown") jetSyst = sysType::JESdown; else std::cout << "No valid JES corrections specified - using nominal" << std::endl; // --------------------------------------------- // Note for future development: should these be // saved inside the lepHelper somewhere? // For now they are ok here // --------------------------------------------- muonID::muonID muonTightID = muonID::muonTight; muonID::muonID muonLooseID = muonID::muonLoose; muonID::muonID muonPreselectedID = muonID::muonRaw; electronID::electronID electronTightID = electronID::electronTight; electronID::electronID electronLooseID = electronID::electronLoose; electronID::electronID electronPreselectedID = electronID::electronRaw; tauID::tauID tauTightID = tauID::tauMedium; // tauID::tauID tauLooseID = tauID::tauVLoose; tauID::tauID tauPreselectedID = tauID::tauNonIso; // collections GenericCollection<BNelectronCollection> tightElectrons(beanHelper); // GenericCollection<BNelectronCollection> looseElectrons(beanHelper); // GenericCollection<BNelectronCollection> preselectedElectrons(beanHelper); GenericCollection<BNelectronCollection> tightLooseElectrons(beanHelper); // GenericCollection<BNelectronCollection> loosePreselectedElectrons(beanHelper); GenericCollection<BNelectronCollection> tightLoosePreselectedElectrons(beanHelper); GenericCollection<BNmuonCollection> tightMuons(beanHelper); // GenericCollection<BNmuonCollection> looseMuons(beanHelper); // GenericCollection<BNmuonCollection> preselectedMuons(beanHelper); GenericCollection<BNmuonCollection> tightLooseMuons(beanHelper); GenericCollection<BNmuonCollection> tightLoosePreselectedMuons(beanHelper); // GenericCollection<BNleptonCollection> tightLeptons(beanHelper); // GenericCollection<BNleptonCollection> looseLeptons(beanHelper); // GenericCollection<BNleptonCollection> preselectedLeptons(beanHelper); // GenericCollection<BNleptonCollection> tightLooseLeptons(beanHelper); // GenericCollection<BNleptonCollection> tightLoosePreselectedLeptons(beanHelper); // // GenericCollection<BNleptonCollection> tightLooseLeptons_fromHiggs(beanHelper); //failed to get working // GenericCollection<BNtauCollection> tightTaus(beanHelper); // GenericCollection<BNtauCollection> tightLooseTaus(beanHelper); // GenericCollection<BNtauCollection> tightLoosePreselectedTaus(beanHelper); // GenericCollection<BNjetCollection> jets(beanHelper); // GenericCollection<BNjetCollection> jets_30(beanHelper); // GenericCollection<BNjetCollection> jetsByCSV(beanHelper); // GenericCollection<BNjetCollection> looseCSVJets(beanHelper); // GenericCollection<BNjetCollection> mediumCSVJets(beanHelper); // GenericCollection<BNjetCollection> notMediumCSVJets(beanHelper); // GenericCollection<BNjetCollection> jets_fromHiggs(beanHelper); // GenericCollection<BNjetCollection> jets_fromHiggs_30(beanHelper); // GenericCollection<BNmetCollection> met(beanHelper); // GenericCollection<BNprimaryvertexCollection> primaryVertexes(beanHelper); // GenericCollection<BNtriggerCollection> hltCollection(beanHelper); // GenericCollection<BNeventCollection> events(beanHelper); // GenericCollection<BNmcparticleCollection> mcParticles(beanHelper); // GenericCollection<BNmcparticleCollection> genHiggsParticles(beanHelper); // GenericCollection<BNmcparticleCollection> genTopParticles(beanHelper); // GenericCollection<BNmcparticleCollection> genAntiTopParticles(beanHelper); // declare your kinematic variables that you want // to be written out into the tree vector<ArbitraryVariable*> kinVars; vector<ArbitraryVariable*> cutVars; // GenericCollectionSizeVariable<BNjetCollection> // numJets(&(jets.ptrToItems), "numJets"); // kinVars.push_back(&numJets); // numJets.setCutMin(2); // cutVars.push_back(&numJets); // GenericCollectionSizeVariable<BNjetCollection> // numJets_30(&(jets_30.ptrToItems), "numJets_30"); // kinVars.push_back(&numJets_30); // GenericCollectionSizeVariable<BNjetCollection> // numJets_fromHiggs(&(jets_fromHiggs.ptrToItems), "numJets_fromHiggs"); // kinVars.push_back(&numJets_fromHiggs); // GenericCollectionSizeVariable<BNjetCollection> // numJets_fromHiggs_30(&(jets_fromHiggs_30.ptrToItems), "numJets_fromHiggs_30"); // kinVars.push_back(&numJets_fromHiggs_30); // GenericCollectionSizeVariable<BNjetCollection> // numMediumBJets(&(mediumCSVJets.ptrToItems), "numMediumBJets"); // kinVars.push_back(&numMediumBJets); // GenericCollectionSizeVariable<BNjetCollection> // numLooseBJets(&(looseCSVJets.ptrToItems), "numLooseBJets"); // kinVars.push_back(&numLooseBJets); // GenericCollectionSizeVariable<BNleptonCollection> // numTightLooseLeptons(&(tightLooseLeptons.ptrToItems), "numTightLooseLeptons"); // kinVars.push_back(&numTightLooseLeptons); // numTightLooseLeptons.setCutMin(2); // cutVars.push_back(&numTightLooseLeptons); // GenericCollectionSizeVariable<BNleptonCollection> // numAllLeptons(&(tightLoosePreselectedLeptons.ptrToItems), "numAllLeptons"); // kinVars.push_back(&numAllLeptons); // GenericCollectionSizeVariable<BNleptonCollection> // numTightLeptons(&(tightLeptons.ptrToItems), "numTightLeptons"); // kinVars.push_back(&numTightLeptons); // numTightLeptons.setCutMin(1); // cutVars.push_back(&numTightLeptons); // GenericCollectionSizeVariable<BNmuonCollection> // numTightMuons(&(tightMuons.ptrToItems), "numTightMuons"); // kinVars.push_back(&numTightMuons); // GenericCollectionSizeVariable<BNelectronCollection> // numTightElectrons(&(tightElectrons.ptrToItems), "numTightElectrons"); // kinVars.push_back(&numTightElectrons); // CSVWeights // myCSV(beanHelper, &(jets.ptrToItems), jetSyst); // kinVars.push_back(&myCSV); // PUWeights // myPU(&lepHelper, &(events.ptrToItems)); // kinVars.push_back(&myPU); // TopPtWeights // myTopPt(&lepHelper, &(mcParticles.ptrToItems)); // kinVars.push_back(&myTopPt); // LeptonIDAndIsoScaleFactors // myLepIDAndIsoSF(&lepHelper, muonTightID, muonLooseID, electronTightID, electronLooseID, // &(tightMuons.ptrToItems), &(looseMuons.ptrToItems), // &(tightElectrons.ptrToItems), &(looseElectrons.ptrToItems)); // kinVars.push_back(&myLepIDAndIsoSF); // LeptonTriggerScaleFactors // myLepTrig(&lepHelper, &(tightMuons.ptrToItems), &(looseMuons.ptrToItems), &(preselectedMuons.ptrToItems), // &(tightElectrons.ptrToItems), &(looseElectrons.ptrToItems), &(preselectedElectrons.ptrToItems)); // kinVars.push_back(&myLepTrig); // CleanEventVars // myClean(&lepHelper, &(events.ptrToItems), &(primaryVertexes.ptrToItems)); // kinVars.push_back(&myClean); // CheckTwoLepTrigger // checkTrig(&lepHelper, &(hltCollection.ptrToItems)); // kinVars.push_back(&checkTrig); // //DBCorrectedRelIsoDR04s myDBCorrectedRelIsoDR04s(&lepHelper, 2); // //kinVars.push_back(&myDBCorrectedRelIsoDR04s); // HiggsDecayType // myHiggsDecayType(&lepHelper, &(mcParticles.ptrToItems)); // kinVars.push_back(&myHiggsDecayType); // TwoObjectKinematic<BNleptonCollection,BNleptonCollection> // myMassLepLep("mass", "min", "mass_leplep", // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99, // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99); // kinVars.push_back(&myMassLepLep); // TwoObjectKinematic<BNleptonCollection,BNleptonCollection> // myZmass("mass", "closest_to", "Zmass", // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99, // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99, // 91.2, "same_flavour"); // kinVars.push_back(&myZmass); // TwoObjectKinematic<BNleptonCollection,BNleptonCollection> // myDeltaRLepLep("deltaR", "min", "dR_leplep", // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99, // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99); // kinVars.push_back(&myDeltaRLepLep); // TwoObjectKinematic<BNleptonCollection,BNleptonCollection> // myDeltaPhiLepLep("deltaPhi", "min", "dPhi_leplep", // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99, // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99); // kinVars.push_back(&myDeltaPhiLepLep); // TwoObjectKinematic<BNleptonCollection,BNjetCollection> // myMHT("pt", "vector_sum", "mht", // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99, // &(jets.ptrToItems), "jets_by_pt", 1, 99); // kinVars.push_back(&myMHT); // ////////// Variables for BDT ////////// // TwoObjectKinematic<BNjetCollection,BNjetCollection> // myMinDrJets("deltaR", "min", "min_dr_jets", // &(jets.ptrToItems), "jets_by_pt", 1, 99, // &(jets.ptrToItems), "jets_by_pt", 1, 99); // kinVars.push_back(&myMinDrJets); // TwoObjectKinematic<BNleptonCollection,BNjetCollection> // mySumPt("pt", "sum", "sum_pt", // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99, // &(jets.ptrToItems), "jets_by_pt", 1, 99); // kinVars.push_back(&mySumPt); // TwoObjectKinematic<BNjetCollection,BNjetCollection> // mySumJetPt("pt", "sum", "sum_jet_pt", // &(jets.ptrToItems), "jets_by_pt", 1, 99, // &(jets.ptrToItems), "jets_by_pt", 1, 99); // kinVars.push_back(&mySumJetPt); // TwoObjectKinematic<BNjetCollection,BNjetCollection> // mySumJetMass("mass", "vector_sum", "sum_jet_mass", // &(jets.ptrToItems), "jets_by_pt", 1, 99, // &(jets.ptrToItems), "jets_by_pt", 1, 99); // kinVars.push_back(&mySumJetMass); // TwoObjectKinematic<BNjetCollection,BNjetCollection> // mySumNonTaggedJetMass("mass", "vector_sum", "sum_non_tagged_jet_mass", // &(notMediumCSVJets.ptrToItems), "untagged_jets_by_pt", 1, 99, // &(notMediumCSVJets.ptrToItems), "untagged_jets_by_pt", 1, 99); // kinVars.push_back(&mySumNonTaggedJetMass); // TwoObjectKinematic<BNjetCollection,BNjetCollection> // myWLikeDijetMass81("mass", "closest_to", "WLike_dijet_mass", // &(notMediumCSVJets.ptrToItems), "untagged_jets_by_pt", 1, 99, // &(notMediumCSVJets.ptrToItems), "untagged_jets_by_pt", 1, 99, // 81); // kinVars.push_back(&myWLikeDijetMass81); // TwoObjectKinematic<BNjetCollection,BNjetCollection> // myDeltaPhiJets_FromHiggs("deltaPhi", "min", "dPhi_jets_fromHiggs", // &(jets_fromHiggs.ptrToItems), "jets_fromHiggs_by_pt", 1, 99, // &(jets_fromHiggs.ptrToItems), "jets_fromHiggs_by_pt", 1, 99); // kinVars.push_back(&myDeltaPhiJets_FromHiggs); // TwoObjectKinematic<BNjetCollection,BNjetCollection> // myDeltaRJets_FromHiggs("deltaR", "min", "dR_jets_fromHiggs", // &(jets_fromHiggs.ptrToItems), "jets_fromHiggs_by_pt", 1, 99, // &(jets_fromHiggs.ptrToItems), "jets_fromHiggs_by_pt", 1, 99); // kinVars.push_back(&myDeltaRJets_FromHiggs); // TwoObjectKinematic<BNmetCollection,BNleptonCollection> // myDeltaPhiMetLep1("deltaPhi", "min", "dPhi_met_lep1", // &(met.ptrToItems), "met", 1, 1, // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 1); // kinVars.push_back(&myDeltaPhiMetLep1); // TwoObjectKinematic<BNmetCollection,BNleptonCollection> // myDeltaPhiMetLep2("deltaPhi", "min", "dPhi_met_lep2", // &(met.ptrToItems), "met", 1, 1, // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 2, 2); // kinVars.push_back(&myDeltaPhiMetLep2); // TwoObjectKinematic<BNmetCollection,BNjetCollection> // myMinDeltaPhiMetJet("deltaPhi", "min", "min_dPhi_metjet", // &(met.ptrToItems), "met", 1, 99, // &(jets.ptrToItems), "jets_by_pt", 1, 99); // kinVars.push_back(&myMinDeltaPhiMetJet); // TwoObjectKinematic<BNmetCollection,BNjetCollection> // myMaxDeltaPhiMetJet("deltaPhi", "max", "max_dPhi_metjet", // &(met.ptrToItems), "met", 1, 99, // &(jets.ptrToItems), "jets_by_pt", 1, 99); // kinVars.push_back(&myMaxDeltaPhiMetJet); // TwoObjectKinematic<BNmetCollection,BNjetCollection> // myMinDeltaPhiMetJet_fromHiggs("deltaPhi", "min", "min_dPhi_metjet_fromHiggs", // &(met.ptrToItems), "met", 1, 99, // &(jets_fromHiggs.ptrToItems), "jets_fromHiggs_by_pt", 1, 99); // kinVars.push_back(&myMinDeltaPhiMetJet_fromHiggs); // TwoObjectKinematic<BNmetCollection,BNjetCollection> // myMaxDeltaPhiMetJet_fromHiggs("deltaPhi", "max", "max_dPhi_metjet_fromHiggs", // &(met.ptrToItems), "met", 1, 99, // &(jets_fromHiggs.ptrToItems), "jets_by_pt", 1, 99); // kinVars.push_back(&myMaxDeltaPhiMetJet_fromHiggs); // ThreeObjectKinematic<BNleptonCollection, BNleptonCollection, BNmetCollection> // myMassMetLepLep("mass", "min", "mass_met_leplep", // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 1, // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 2, 2, // &(met.ptrToItems), "met", 1, 1); // kinVars.push_back(&myMassMetLepLep); // ThreeObjectKinematic<BNleptonCollection, BNleptonCollection, BNmetCollection> // myMTMetLepLep("MT", "min", "MT_met_leplep", // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 1, // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 2, 2, // &(met.ptrToItems), "met", 1, 1); // kinVars.push_back(&myMTMetLepLep); // ThreeObjectKinematic<BNleptonCollection, BNleptonCollection, BNmetCollection> // myDeltaRMetLepLep("deltaR", "min", "dR_met_leplep", // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 1, // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 2, 2, // &(met.ptrToItems), "met", 1, 1); // kinVars.push_back(&myDeltaRMetLepLep); // ThreeObjectKinematic<BNleptonCollection, BNleptonCollection, BNmetCollection> // myDeltaPhiMetLepLep("deltaPhi", "min", "dPhi_met_leplep", // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 1, // &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 2, 2, // &(met.ptrToItems), "met", 1, 1); // kinVars.push_back(&myDeltaPhiMetLepLep); // TwoObjectKinematic<BNjetCollection,BNjetCollection> // myGenHiggsDijetMass("mass", "min", "genHiggs_dijet_mass", // &(jets_fromHiggs.ptrToItems), "jets_by_pt", 1, 1, // &(jets_fromHiggs.ptrToItems), "jets_by_pt", 2, 2); // kinVars.push_back(&myGenHiggsDijetMass); // TwoObjectKinematic<BNjetCollection,BNjetCollection> // myHiggsLikeDijetMass("mass", "closest_to", "higgsLike_dijet_mass", // &(jets.ptrToItems), "jets_by_pt", 1, 99, // &(jets.ptrToItems), "jets_by_pt", 1, 99, // 115.0); // kinVars.push_back(&myHiggsLikeDijetMass); // TwoObjectKinematic<BNjetCollection,BNjetCollection> // myHiggsLikeDijetMass2("mass", "second_closest_to", "higgsLike_dijet_mass2", // &(jets.ptrToItems), "jets_by_pt", 1, 99, // &(jets.ptrToItems), "jets_by_pt", 1, 99, // 115.0); // kinVars.push_back(&myHiggsLikeDijetMass2); // TwoObjectKinematic<BNjetCollection,BNjetCollection> // myNumJetsFloat("eta", "num_within", "numJets_float", // &(jets.ptrToItems), "jets_by_pt", 1, 99, // &(jets.ptrToItems), "jets_by_pt", 1, 99, // 0.0, "", "", 5.0); // kinVars.push_back(&myNumJetsFloat); // TwoObjectKinematic<BNjetCollection,BNjetCollection> // myNumHiggsLikeDijet15("mass", "num_within", "numHiggsLike_dijet_15_float", // &(jets.ptrToItems), "jets_by_pt", 1, 99, // &(jets.ptrToItems), "jets_by_pt", 1, 99, // 115.0, "", "", 15.0); // kinVars.push_back(&myNumHiggsLikeDijet15); // TwoJetVariables // myAvgBtagDiscBtags("CSV", "avg", "avg_btag_disc_btags", // &(mediumCSVJets.ptrToItems), "medium_bjets_by_pt", 1, 99, // &(mediumCSVJets.ptrToItems), "medium_bjets_by_pt", 1, 99); // kinVars.push_back(&myAvgBtagDiscBtags); // TwoJetVariables // myAvgBtagDiscNonBtags("CSV", "avg", "avg_btag_disc_non_btags", // &(notMediumCSVJets.ptrToItems), "not_medium_bjets_by_pt", 1, 99, // &(notMediumCSVJets.ptrToItems), "not_medium_bjets_by_pt", 1, 99); // kinVars.push_back(&myAvgBtagDiscNonBtags); // ////////// all leptons ////////// // GenericCollectionMember<double, BNleptonCollection> // allLeptonPt(Reflex::Type::ByName("BNlepton"), &(tightLooseLeptons.ptrToItems), // "pt", "leptons_by_pt", KinematicVariableConstants::FLOAT_INIT, 2); // kinVars.push_back(&allLeptonPt); // GenericCollectionMember<double, BNleptonCollection> // allLeptonEta(Reflex::Type::ByName("BNlepton"), &(tightLooseLeptons.ptrToItems), // "eta", "leptons_by_pt", KinematicVariableConstants::FLOAT_INIT, 2); // kinVars.push_back(&allLeptonEta); // GenericCollectionMember<int, BNleptonCollection> // allLeptonTkCharge(Reflex::Type::ByName("BNlepton"), &(tightLooseLeptons.ptrToItems), // "tkCharge", "leptons_by_pt", KinematicVariableConstants::INT_INIT, 2); // kinVars.push_back(&allLeptonTkCharge); // GenericCollectionMember<int, BNleptonCollection> // allLeptonGenMotherId(Reflex::Type::ByName("BNlepton"), &(tightLooseLeptons.ptrToItems), // "genMotherId", "leptons_by_pt", KinematicVariableConstants::INT_INIT, 2); // kinVars.push_back(&allLeptonGenMotherId); // GenericCollectionMember<int, BNleptonCollection> // allLeptonGenGrandMotherId(Reflex::Type::ByName("BNlepton"), &(tightLooseLeptons.ptrToItems), // "genGrandMother00Id", "leptons_by_pt", KinematicVariableConstants::INT_INIT, 2); // kinVars.push_back(&allLeptonGenGrandMotherId); // NECESSARY TO FILL LEPTON VALUES - DO NOT COMMENT OUT // GenericCollectionMember<double, BNmuonCollection> allMuonPt(Reflex::Type::ByName("BNmuon"), &(tightLooseMuons.ptrToItems), "pt", "muons_by_pt", KinematicVariableConstants::FLOAT_INIT, 2); kinVars.push_back(&allMuonPt); GenericCollectionMember<double, BNelectronCollection> allElectronPt(Reflex::Type::ByName("BNelectron"), &(tightLooseElectrons.ptrToItems), "pt", "electrons_by_pt", KinematicVariableConstants::FLOAT_INIT, 2); kinVars.push_back(&allElectronPt); ////////// all jets ////////// // GenericCollectionMember<double, BNjetCollection> // allJetPt(Reflex::Type::ByName("BNjet"), &(jets.ptrToItems), // "pt", "jets_by_pt", KinematicVariableConstants::FLOAT_INIT, 4); // kinVars.push_back(&allJetPt); // GenericCollectionMember<double, BNjetCollection> // allJetEta(Reflex::Type::ByName("BNjet"), &(jets.ptrToItems), // "eta", "jets_by_pt", KinematicVariableConstants::FLOAT_INIT, 4); // kinVars.push_back(&allJetEta); // GenericCollectionMember<double, BNjetCollection> // allJetCSV(Reflex::Type::ByName("BNjet"), &(jets.ptrToItems), // "btagCombinedSecVertex", "jets_by_pt", KinematicVariableConstants::FLOAT_INIT, 4); // kinVars.push_back(&allJetCSV); // ////////// met ////////// // GenericCollectionMember<double, BNmetCollection> // metPt(Reflex::Type::ByName("BNmet"), &(met.ptrToItems), // "pt", "met", KinematicVariableConstants::FLOAT_INIT, 1); // kinVars.push_back(&metPt); ////////// manual variables ////////// // int TwoMuon = 0; // int TwoElectron = 0; // int MuonElectron = 0; // int PassTwoLepton = 0; // Char_t *dataset = (Char_t *)lepHelper.dataset.c_str(); // int sampleNumber = (int)lepHelper.sampleNumber; // double weight_Xsec = (double)lepHelper.weight_Xsec; // int nGen = (int)lepHelper.nGen; // double Xsec = (double)lepHelper.Xsec; // summaryTree->Branch("sampleNumber", &sampleNumber); // summaryTree->Branch("weight_Xsec", &weight_Xsec); // summaryTree->Branch("nGen", &nGen); // summaryTree->Branch("Xsec", &Xsec); // summaryTree->Branch("TwoMuon", &TwoMuon); // summaryTree->Branch("TwoElectron", &TwoElectron); // summaryTree->Branch("MuonElectron", &MuonElectron); // summaryTree->Branch("PassTwoLepton", &PassTwoLepton); // summaryTree->Branch("dataset", (void*)dataset, "dataset/C"); // int numExtraPartons = -99; // summaryTree->Branch("numExtraPartons", &numExtraPartons); bool ttPlusHFKeepEventBool = false; ////////// event info ////////// // GenericCollectionMember<unsigned, BNeventCollection> // runNumber(Reflex::Type::ByName("BNevent"), &(events.ptrToItems), // "run", "eventInfo", KinematicVariableConstants::UINT_INIT, 1); // kinVars.push_back(&runNumber); // GenericCollectionMember<unsigned, BNeventCollection> // lumiBlock(Reflex::Type::ByName("BNevent"), &(events.ptrToItems), // "lumi", "eventInfo", KinematicVariableConstants::UINT_INIT, 1); // kinVars.push_back(&lumiBlock); // this is a long inside BNevent // just using keyword long won't work // needs to be Long64_t // GenericCollectionMember<Long64_t, BNeventCollection> // eventNumber(Reflex::Type::ByName("BNevent"), &(events.ptrToItems), // "evt", "eventInfo", KinematicVariableConstants::INT_INIT, 1); // kinVars.push_back(&eventNumber); ////////// variables from functions ////////// // PassZmask myPassZmask(&myZmass, &myMHT, &metPt); // kinVars.push_back(&myPassZmask); // myPassZmask.setCut("PassZmask_mht"); // cutVars.push_back(&myPassZmask); // FinalBDT_OS_2012 myFinalBDT_OS_2012(&myMinDrJets, &mySumPt, &myAvgBtagDiscBtags, &myAvgBtagDiscNonBtags, // &myHiggsLikeDijetMass, &myHiggsLikeDijetMass2, &myNumJetsFloat, &myNumHiggsLikeDijet15); // kinVars.push_back(&myFinalBDT_OS_2012); if (debug > 9) { cout << "Hooking variables to tree" << endl;} for (vector<ArbitraryVariable*>::iterator iVar = kinVars.begin(); iVar != kinVars.end(); iVar++) { (*iVar)->attachToTree (summaryTree); } int numEvents = 0; int numEventsFailCuts = 0; int numEventsPassCuts = 0; int printEvery = 1000; for (ev.toBegin(); !ev.atEnd(); ++ev){ numEvents++; if ((numEvents > myConfig.maxEvents) && myConfig.maxEvents != -1) break; if (numEvents == 1 || numEvents % printEvery == 0 ) cout << "Processing event.... " << numEvents << endl; if (debug > 9) cout << "---------->>>>>> Event " << numEvents << endl; ///////////////////////////////////////////////////////////// // // Initialize collections and apply object ids // ////////////////////////////////////////////////////////////// tightLoosePreselectedElectrons.initializeRawItemsSortedByPt(ev, "BNproducer","selectedPatElectronsPFlow"); tightLoosePreselectedMuons.initializeRawItemsSortedByPt(ev, "BNproducer","selectedPatMuonsPFlow"); tightLoosePreselectedElectrons.keepSelectedParticles(electronPreselectedID); // tightElectrons.initializeRawItems(tightLoosePreselectedElectrons.rawItems); // tightElectrons.keepSelectedParticles(electronTightID); tightLooseElectrons.initializeRawItems(tightLoosePreselectedElectrons.rawItems); tightLooseElectrons.keepSelectedParticles(electronLooseID); // looseElectrons.initializeRawItems(tightLoosePreselectedElectrons.rawItems); // looseElectrons.keepSelectedDifference(electronLooseID, electronTightID); // preselectedElectrons.initializeRawItems(tightLoosePreselectedElectrons.rawItems); // preselectedElectrons.keepSelectedDifference(electronPreselectedID, electronLooseID); // loosePreselectedElectrons.initializeRawItems(tightLoosePreselectedElectrons.rawItems); // loosePreselectedElectrons.addUnion({looseElectrons.items, preselectedElectrons.items}); tightLoosePreselectedMuons.keepSelectedParticles(muonPreselectedID); // tightMuons.initializeRawItems(tightLoosePreselectedMuons.rawItems); // tightMuons.keepSelectedParticles(muonTightID); // looseMuons.initializeRawItems(tightLoosePreselectedMuons.rawItems); // looseMuons.keepSelectedDifference(muonLooseID, muonTightID); // preselectedMuons.initializeRawItems(tightLoosePreselectedMuons.rawItems); // preselectedMuons.keepSelectedDifference(muonPreselectedID, muonLooseID); tightLooseMuons.initializeRawItems(tightLoosePreselectedMuons.rawItems); tightLooseMuons.keepSelectedParticles(muonLooseID); // // Require reset before first pushback to avoid keeping leptons from previous event // tightLeptons.resetAndPushBack(tightElectrons.items); // tightLeptons.pushBackAndSort(tightMuons.items); // looseLeptons.resetAndPushBack(looseElectrons.items); // looseLeptons.pushBackAndSort(looseMuons.items); // preselectedLeptons.resetAndPushBack(preselectedElectrons.items); // preselectedLeptons.pushBackAndSort(preselectedMuons.items); // tightLooseLeptons.resetAndPushBack(tightLooseElectrons.items); // tightLooseLeptons.pushBackAndSort(tightLooseMuons.items); // tightLoosePreselectedLeptons.resetAndPushBack(tightLoosePreselectedElectrons.items); // tightLoosePreselectedLeptons.pushBackAndSort(tightLoosePreselectedMuons.items); // tightTaus.initializeRawItemsSortedByPt(ev, "BNproducer","selectedPatTaus"); // tightTaus.keepSelectedParticles(tauTightID); // tightLooseTaus.initializeRawItems(tightTaus.rawItems); // tightLooseTaus.keepSelectedParticles(tauTightID); // tightLoosePreselectedTaus.initializeRawItems(tightTaus.rawItems); // tightLoosePreselectedTaus.keepSelectedParticles(tauPreselectedID); // jets.initializeRawItemsSortedByPt(ev, "BNproducer","selectedPatJetsPFlow"); // jets.cleanJets(tightLoosePreselectedLeptons.items); // jets.correctRawJets(jetSyst); // jets.keepSelectedJets(25.0, 2.4, jetID::jetLoose, '-'); // jetsByCSV.initializeRawItemsSortedByCSV(jets.items); // looseCSVJets.initializeRawItems(jets.rawItems); // looseCSVJets.keepSelectedJets(25.0, 2.4, jetID::jetLoose, 'L'); // mediumCSVJets.initializeRawItems(jets.rawItems); // mediumCSVJets.keepSelectedJets(25.0, 2.4, jetID::jetLoose, 'M'); // notMediumCSVJets.initializeRawItems(beanHelper->GetDifference(jets.items, mediumCSVJets.items)); // jets_30.initializeRawItems(jets.items); // jets_30.keepSelectedJets(30.0, 2.4, jetID::jetLoose, '-'); // jets_fromHiggs.initializeRawItems(jets.items); // auto jetGenPartonMotherId = [] (BNjet j) { return (j.genPartonMotherId == 25); }; // jets_fromHiggs.keepSelectedParticles(jetGenPartonMotherId); // jets_fromHiggs_30.initializeRawItems(jets_30.items); // jets_fromHiggs_30.keepSelectedParticles(jetGenPartonMotherId); // met.initializeRawItems(ev, "BNproducer","patMETsPFlow"); // met.getCorrectedMet(jets); // events.initializeRawItems(ev, "BNproducer", ""); // mcParticles.initializeRawItems(ev, "BNproducer", "MCstatus3"); // primaryVertexes.initializeRawItems(ev, "BNproducer","offlinePrimaryVertices"); // hltCollection.initializeRawItems(ev, "BNproducer", "HLT"); // genHiggsParticles.initializeRawItems(mcParticles.rawItems); // auto higgsPDGID = [] (BNmcparticle p) { return (p.id == 25); }; // genHiggsParticles.keepSelectedParticles(higgsPDGID); // genTopParticles.initializeRawItems(mcParticles.rawItems); // auto topPDGID = [] (BNmcparticle p) { return (p.id == 6); }; // genTopParticles.keepSelectedParticles(topPDGID); // genAntiTopParticles.initializeRawItems(mcParticles.rawItems); // auto antitopPDGID = [] (BNmcparticle p) { return (p.id == -6); }; // reset all the vars if (debug > 9) cout << "Resetting " << endl; for (vector<ArbitraryVariable*>::iterator iVar = kinVars.begin(); iVar != kinVars.end(); iVar++) { (*iVar)->reset(); } bool passAllCuts = true; if (debug > 9) cout << "Checking cuts " << endl; for (vector<ArbitraryVariable*>::iterator iCut = cutVars.begin(); iCut != cutVars.end(); iCut++ ) { (*iCut)->evaluate(); passAllCuts = passAllCuts && (*iCut)->passCut(); } if (!passAllCuts) { numEventsFailCuts++; continue; //!!!! Skip The event /////////////// } else { numEventsPassCuts++; } // Now evaluate the vars if (debug > 9) cout << "Evaluating vars " << endl; for (vector<ArbitraryVariable*>::iterator iVar = kinVars.begin(); iVar != kinVars.end(); iVar++) { (*iVar)->evaluate(); } if (debug > 9) { for (vector<ArbitraryVariable*>::iterator iVar = kinVars.begin(); iVar != kinVars.end(); iVar++) { (*iVar)->print(); cout << endl; } } // Get manual variables // LeptonVarsThisAnalysis(tightMuons.items, tightLooseMuons.items, tightElectrons.items, tightLooseElectrons.items, // TwoMuon, TwoElectron, MuonElectron, PassTwoLepton); // getNumExtraPartons(beanHelper, mcParticles.items, numExtraPartons); // if (myConfig.sampleName.find("_0p") != std::string::npos) { //0 parton samples //Cut to require 0 partons // if (numExtraPartons != 0) { // numEventsFailCuts++; // numEventsPassCuts--; // continue; //Don't go on to fill tree with this event // } // } if (myConfig.sampleName == "ttbar" || myConfig.sampleName.find("ttbar_") != std::string::npos ) { //ttbar samples //ttPlusHFKeepEventFunction(beanHelper, mcParticles.items, jets.items, ttPlusHFKeepEventBool); if (!ttPlusHFKeepEventBool) { numEventsFailCuts++; numEventsPassCuts--; continue; //Don't go on to fill tree with this event } } // Fill the trees if (debug > 9) cout << "Filling tree " << endl; summaryTree->Fill(); if (debug > 9) cout << "Done with event " << numEvents << endl; }// end for each event cout << "Num Events processed " << numEvents << endl << "Passed cuts " << numEventsPassCuts << endl << "Failed cuts " << numEventsFailCuts << endl ; outputFile->Write(); outputFile->Close(); }