diff --git a/app/DumpGiBUUEvents.cxx b/app/DumpGiBUUEvents.cxx index d8c456f..e3e571f 100644 --- a/app/DumpGiBUUEvents.cxx +++ b/app/DumpGiBUUEvents.cxx @@ -1,49 +1,49 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include #include "FitLogger.h" #include "StdHepEvt.h" int main(int argv, char const *argc[]) { if (argv != 2) { - QTHROW("[ERROR]: expected a single input GiBUU rootracker file."); + NUIS_ABORT("[ERROR]: expected a single input GiBUU rootracker file."); } std::string inpf(argc[1]); if (!inpf.length()) { - QTHROW("[ERROR]: expected an input GiBUU rootracker file."); + NUIS_ABORT("[ERROR]: expected an input GiBUU rootracker file."); } TChain tn("giRooTracker"); tn.AddFile(inpf.c_str()); GiBUUStdHepReader giRead; bool ok = giRead.SetBranchAddresses(&tn); if (!ok) { - QTHROW("[ERROR]: Could not correctly set branch address for input file."); + NUIS_ABORT("[ERROR]: Could not correctly set branch address for input file."); } for (Long64_t ievt = 0; ievt < tn.GetEntries(); ++ievt) { tn.GetEntry(ievt); - QLOG(EVT, WriteGiBUUEvent(giRead)); + NUIS_LOG(EVT, WriteGiBUUEvent(giRead)); } } diff --git a/app/PrepareGENIE.cxx b/app/PrepareGENIE.cxx index 06030f0..8196e5e 100644 --- a/app/PrepareGENIE.cxx +++ b/app/PrepareGENIE.cxx @@ -1,938 +1,938 @@ #include "FitLogger.h" #include "PlotUtils.h" #include "TFile.h" #include "TH1D.h" #include "TTree.h" #include #include #ifdef __GENIE_ENABLED__ #ifdef GENIE_PRE_R3 #include "Conventions/Units.h" #include "GHEP/GHepParticle.h" #include "PDG/PDGUtils.h" #else #include "Framework/Conventions/Units.h" #include "Framework/GHEP/GHepParticle.h" #include "Framework/ParticleData/PDGUtils.h" #endif #endif std::string gInputFiles = ""; std::string gOutputFile = ""; std::string gFluxFile = ""; std::string gTarget = ""; double MonoEnergy; int gNEvents = -999; bool IsMonoE = false; void PrintOptions(); void ParseOptions(int argc, char *argv[]); void RunGENIEPrepareMono(std::string input, std::string target, std::string output); void RunGENIEPrepare(std::string input, std::string flux, std::string target, std::string output); int main(int argc, char *argv[]) { ParseOptions(argc, argv); if (IsMonoE) { RunGENIEPrepareMono(gInputFiles, gTarget, gOutputFile); } else { RunGENIEPrepare(gInputFiles, gFluxFile, gTarget, gOutputFile); } } void RunGENIEPrepareMono(std::string input, std::string target, std::string output) { - QLOG(FIT, "Running GENIE Prepare in mono energetic with E = " << MonoEnergy + NUIS_LOG(FIT, "Running GENIE Prepare in mono energetic with E = " << MonoEnergy << " GeV"); // Setup TTree TChain *tn = new TChain("gtree"); tn->AddFile(input.c_str()); if (tn->GetFile() == NULL) { tn->Print(); - QERROR(FTL, "gtree not located in GENIE file: " << input); - QTHROW("Check your inputs, they may need to be completely regenerated!"); + NUIS_ERR(FTL, "gtree not located in GENIE file: " << input); + NUIS_ABORT("Check your inputs, they may need to be completely regenerated!"); throw; } int nevt = tn->GetEntries(); if (gNEvents != -999) { - QLOG(FIT, "Overriding number of events by user from " << nevt << " to " + NUIS_LOG(FIT, "Overriding number of events by user from " << nevt << " to " << gNEvents); nevt = gNEvents; } NtpMCEventRecord *genientpl = NULL; tn->SetBranchAddress("gmcrec", &genientpl); // Have the TH1D go from MonoEnergy/2 to MonoEnergy/2 TH1D *fluxhist = new TH1D("flux", "flux", 1000, MonoEnergy / 2., MonoEnergy * 2.); fluxhist->Fill(MonoEnergy); fluxhist->Scale(1, "width"); // Make Event Hist TH1D *eventhist = (TH1D *)fluxhist->Clone(); eventhist->Reset(); TH1D *xsechist = (TH1D *)eventhist->Clone(); // Create maps std::map modexsec; std::map modecount; std::vector genieids; std::vector targetids; std::vector interids; // Loop over all events for (int i = 0; i < nevt; i++) { tn->GetEntry(i); StopTalking(); EventRecord &event = *(genientpl->event); GHepParticle *neu = event.Probe(); StartTalking(); // Get XSec From Spline GHepRecord genie_record = static_cast(event); double xsec = (genie_record.XSec() / (1E-38 * genie::units::cm2)); // Parse Interaction String std::string mode = genie_record.Summary()->AsString(); std::vector modevec = GeneralUtils::ParseToStr(mode, ";"); std::string targ = (modevec[0] + ";" + modevec[1]); std::string inter = mode; // Fill lists of Unique IDS if (std::find(targetids.begin(), targetids.end(), targ) == targetids.end()) { targetids.push_back(targ); } if (std::find(interids.begin(), interids.end(), inter) == interids.end()) { interids.push_back(inter); } // Create entries Mode Maps if (modexsec.find(mode) == modexsec.end()) { genieids.push_back(mode); modexsec[mode] = (TH1D *)xsechist->Clone(); modecount[mode] = (TH1D *)xsechist->Clone(); modexsec[mode]->GetYaxis()->SetTitle( "d#sigma/dE_{#nu} #times 10^{-38} (events weighted by #sigma)"); modecount[mode]->GetYaxis()->SetTitle("Number of events in file"); } // Fill XSec Histograms modexsec[mode]->Fill(neu->E(), xsec); modecount[mode]->Fill(neu->E()); // Fill total event hist eventhist->Fill(neu->E()); // Clear Event genientpl->Clear(); size_t freq = nevt / 20; if (freq && !(i % freq)) { - QLOG(FIT, "Processed " + NUIS_LOG(FIT, "Processed " << i << "/" << nevt << " GENIE events (E: " << neu->E() << " GeV, xsec: " << xsec << " E-38 cm^2/nucleon)"); } } - QLOG(FIT, "Processed all events"); + NUIS_LOG(FIT, "Processed all events"); TFile *outputfile; // If no output is specified just append to the file if (!gOutputFile.length()) { tn->GetEntry(0); outputfile = tn->GetFile(); outputfile->cd(); } else { outputfile = new TFile(gOutputFile.c_str(), "RECREATE"); outputfile->cd(); - QLOG(FIT, "Cloning input vector to output file: " << gOutputFile); + NUIS_LOG(FIT, "Cloning input vector to output file: " << gOutputFile); TTree *cloneTree = tn->CloneTree(-1, "fast"); cloneTree->SetDirectory(outputfile); cloneTree->Write(); - QLOG(FIT, "Cloning input nova_wgts to output file: " << gOutputFile); + NUIS_LOG(FIT, "Cloning input nova_wgts to output file: " << gOutputFile); // *********************************** // *********************************** // FUDGE FOR NOVA MINERVA WORKSHOP // Also check for the nova_wgts tree from Jeremy TChain *nova_chain = new TChain("nova_wgts"); nova_chain->AddFile(input.c_str()); TTree *nova_tree = nova_chain->GetTree(); if (!nova_tree) { - QLOG(FIT, "Could not find nova_wgts tree in " << gOutputFile); + NUIS_LOG(FIT, "Could not find nova_wgts tree in " << gOutputFile); } else { - QLOG(FIT, "Found nova_wgts tree in " << gOutputFile); + NUIS_LOG(FIT, "Found nova_wgts tree in " << gOutputFile); } if (nova_tree) { nova_tree->SetDirectory(outputfile); nova_tree->Write(); } - QLOG(FIT, "Done cloning tree."); + NUIS_LOG(FIT, "Done cloning tree."); } - QLOG(FIT, "Getting splines in mono-energetic..."); + NUIS_LOG(FIT, "Getting splines in mono-energetic..."); // Save each of the reconstructed splines to file std::map modeavg; TDirectory *inddir = (TDirectory *)outputfile->Get("IndividualGENIESplines"); if (!inddir) inddir = (TDirectory *)outputfile->mkdir("IndividualGENIESplines"); inddir->cd(); // Loop over GENIE ID's and get MEC count int MECcount = 0; bool MECcorrect = FitPar::Config().GetParB("CorrectGENIEMECNorm"); for (UInt_t i = 0; i < genieids.size(); i++) { if (genieids[i].find("MEC") != std::string::npos) { MECcount++; } } - QLOG(FIT, "Found " << MECcount << " repeated MEC instances."); + NUIS_LOG(FIT, "Found " << MECcount << " repeated MEC instances."); for (UInt_t i = 0; i < genieids.size(); i++) { std::string mode = genieids[i]; modexsec[mode]->Write((mode + "_summed_xsec").c_str(), TObject::kOverwrite); modecount[mode]->Write((mode + "_summed_evt").c_str(), TObject::kOverwrite); // Form extra avg xsec map -> Reconstructed spline modeavg[mode] = (TH1D *)modexsec[mode]->Clone(); modeavg[mode]->GetYaxis()->SetTitle( "#sigma (E_{#nu}) #times 10^{-38} (cm^{2}/target)"); modeavg[mode]->Divide(modecount[mode]); if (MECcorrect && (mode.find("MEC") != std::string::npos)) { modeavg[mode]->Scale(1.0 / double(MECcount)); } modeavg[mode]->Write((mode + "_rec_spline").c_str(), TObject::kOverwrite); } TDirectory *targdir = (TDirectory *)outputfile->Get("TargetGENIESplines"); if (!targdir) targdir = (TDirectory *)outputfile->mkdir("TargetGENIESplines"); targdir->cd(); - QLOG(FIT, "Getting Target Splines"); + NUIS_LOG(FIT, "Getting Target Splines"); // For each target save a total spline std::map targetsplines; for (uint i = 0; i < targetids.size(); i++) { std::string targ = targetids[i]; - QLOG(FIT, "Getting target " << i << ": " << targ); + NUIS_LOG(FIT, "Getting target " << i << ": " << targ); targetsplines[targ] = (TH1D *)xsechist->Clone(); targetsplines[targ]->GetYaxis()->SetTitle( "#sigma (E_{#nu}) #times 10^{-38} (cm^{2}/target)"); - QLOG(FIT, "Created target spline for " << targ); + NUIS_LOG(FIT, "Created target spline for " << targ); for (uint j = 0; j < genieids.size(); j++) { std::string mode = genieids[j]; if (mode.find(targ) != std::string::npos) { - QLOG(FIT, " Mode " << mode << " contains " << targ << " target"); + NUIS_LOG(FIT, " Mode " << mode << " contains " << targ << " target"); targetsplines[targ]->Add(modeavg[mode]); - QLOG(FIT, + NUIS_LOG(FIT, "Finished with Mode " << mode << " " << modeavg[mode]->Integral()); } } - QLOG(FIT, "Saving target spline:" << targ); + NUIS_LOG(FIT, "Saving target spline:" << targ); targetsplines[targ]->Write(("Total_" + targ).c_str(), TObject::kOverwrite); } - QLOG(FIT, "Getting total splines"); + NUIS_LOG(FIT, "Getting total splines"); // Now we have each of the targets we need to create a total cross-section. int totalnucl = 0; // Get the targets specified by the user, separated by commas // This has structure target1[fraction1], target2[fraction2] std::vector targprs = GeneralUtils::ParseToStr(target, ","); std::vector targ_list; std::vector frac_list; // Chop up the target string which has format // TARGET1[fraction1],TARGET2[fraction2] // std::cout << "Targets: " << std::endl; // Loop over the vector of strings "TARGET1[fraction1]" "TARGET2[fraction2]" for (std::vector::iterator it = targprs.begin(); it != targprs.end(); ++it) { // Cut into "TARGET1" and "fraction1]" std::vector targind = GeneralUtils::ParseToStr(*it, "["); // std::cout << " " << *it << std::endl; // Cut into "TARGET1" and "fraction1" for (std::vector::iterator jt = targind.begin(); jt != targind.end(); ++jt) { if ((*jt).find("]") != std::string::npos) { (*jt) = (*jt).substr(0, (*jt).find("]")); //*jt = "hello"; frac_list.push_back(*jt); // Won't find bracket for target } else { targ_list.push_back(*jt); } } } targprs = targ_list; std::vector targ_fractions; double minimum = 1.0; for (std::vector::iterator it = frac_list.begin(); it != frac_list.end(); it++) { // std::cout << " " << *it << std::endl; double frac = std::atof((*it).c_str()); targ_fractions.push_back(frac); if (frac < minimum) minimum = frac; } std::vector::iterator it = targ_fractions.begin(); std::vector::iterator jt = targ_list.begin(); double scaling = 0; for (; it != targ_fractions.end(); it++, jt++) { // First get the mass number from the targ_list int nucl = atoi((*jt).c_str()); nucl = (nucl % 10000) / 10; // Gets the relative portions right *it = (*it) / minimum; // Scale relative the atomic mass //(*it) *= (double(nucl)/(*it)); double tempscaling = double(nucl) / (*it); if (tempscaling > scaling) scaling = tempscaling; } it = targ_fractions.begin(); for (; it != targ_fractions.end(); it++) { // Round the scaling to nearest integer and multiply *it *= int(scaling + 0.5); // Round to nearest integer *it = int(*it + 0.5); totalnucl += *it; } if (totalnucl == 0) { - QTHROW("Didn't find any nucleons in input file. Did you really specify the " + NUIS_ABORT("Didn't find any nucleons in input file. Did you really specify the " "target ratios?\ne.g. TARGET1[fraction1],TARGET2[fraction2]"); } TH1D *totalxsec = (TH1D *)xsechist->Clone(); for (uint i = 0; i < targprs.size(); i++) { std::string targpdg = targprs[i]; // Check that we found the user requested target in GENIE bool FoundTarget = false; for (std::map::iterator iter = targetsplines.begin(); iter != targetsplines.end(); iter++) { std::string targstr = iter->first; TH1D *xsec = iter->second; // Match the user targets to the targets found in GENIE if (targstr.find(targpdg) != std::string::npos) { FoundTarget = true; - QLOG(FIT, "Adding target spline " + NUIS_LOG(FIT, "Adding target spline " << targstr << " Integral = " << xsec->Integral("width")); totalxsec->Add(xsec); // int nucl = atoi(targpdg.c_str()); // totalnucl += int((nucl % 10000) / 10); } } // Check that targets were all found if (!FoundTarget) { - QERROR(WRN, "Didn't find target " + NUIS_ERR(WRN, "Didn't find target " << targpdg << " in the list of targets recorded by GENIE"); - QERROR(WRN, " The list of targets you requested is: "); + NUIS_ERR(WRN, " The list of targets you requested is: "); for (uint i = 0; i < targprs.size(); ++i) - QERROR(WRN, " " << targprs[i]); - QERROR(WRN, " The list of targets found in GENIE is: "); + NUIS_ERR(WRN, " " << targprs[i]); + NUIS_ERR(WRN, " The list of targets found in GENIE is: "); for (std::map::iterator iter = targetsplines.begin(); iter != targetsplines.end(); iter++) - QERROR(WRN, " " << iter->first); + NUIS_ERR(WRN, " " << iter->first); } } outputfile->cd(); totalxsec->GetYaxis()->SetTitle( "#sigma (E_{#nu}) #times 10^{-38} (cm^{2}/nucleon)"); totalxsec->Write("nuisance_xsec", TObject::kOverwrite); eventhist = (TH1D *)fluxhist->Clone(); eventhist->Multiply(totalxsec); eventhist->GetYaxis()->SetTitle( (std::string("Event rate (N = #sigma #times #Phi) #times 10^{-38} " "(cm^{2}/nucleon) #times ") + eventhist->GetYaxis()->GetTitle()) .c_str()); - QLOG(FIT, "Dividing by Total Nucl = " << totalnucl); + NUIS_LOG(FIT, "Dividing by Total Nucl = " << totalnucl); eventhist->Scale(1.0 / double(totalnucl)); eventhist->Write("nuisance_events", TObject::kOverwrite); fluxhist->Write("nuisance_flux", TObject::kOverwrite); - QLOG(FIT, "Inclusive XSec Per Nucleon = " << eventhist->Integral("width") * + NUIS_LOG(FIT, "Inclusive XSec Per Nucleon = " << eventhist->Integral("width") * 1E-38 / fluxhist->Integral("width")); - QLOG(FIT, "XSec Hist Integral = " << totalxsec->Integral("width")); + NUIS_LOG(FIT, "XSec Hist Integral = " << totalxsec->Integral("width")); outputfile->Close(); return; } void RunGENIEPrepare(std::string input, std::string flux, std::string target, std::string output) { - QLOG(FIT, "Running GENIE Prepare with flux..."); + NUIS_LOG(FIT, "Running GENIE Prepare with flux..."); // Get Flux Hist std::vector fluxvect = GeneralUtils::ParseToStr(flux, ","); TH1 *fluxhist = NULL; if (fluxvect.size() == 3) { double from = GeneralUtils::StrToDbl(fluxvect[0]); double to = GeneralUtils::StrToDbl(fluxvect[1]); double step = GeneralUtils::StrToDbl(fluxvect[2]); int nstep = ceil((to - from) / step); to = from + step * nstep; - QLOG(FIT, "Generating flat flux histogram from " + NUIS_LOG(FIT, "Generating flat flux histogram from " << from << " to " << to << " with bins " << step << " wide (NBins = " << nstep << ")."); fluxhist = new TH1D("spectrum", ";E_{#nu} (GeV);Count (A.U.)", nstep, from, to); for (Int_t bi_it = 1; bi_it < fluxhist->GetXaxis()->GetNbins(); ++bi_it) { fluxhist->SetBinContent(bi_it, 1.0 / double(step * nstep)); } fluxhist->SetDirectory(0); } else if (fluxvect.size() == 2) { TFile *fluxfile = new TFile(fluxvect[0].c_str(), "READ"); if (!fluxfile->IsZombie()) { fluxhist = dynamic_cast(fluxfile->Get(fluxvect[1].c_str())); if (!fluxhist) { - QERROR(FTL, "Couldn't find histogram named: \"" + NUIS_ERR(FTL, "Couldn't find histogram named: \"" << fluxvect[1] << "\" in file: \"" << fluxvect[0]); throw; } fluxhist->SetDirectory(0); } } else if (fluxvect.size() == 1) { MonoEnergy = GeneralUtils::StrToDbl(fluxvect[0]); RunGENIEPrepareMono(input, target, output); return; } else { - QLOG(FTL, "Bad flux specification: \"" << flux << "\"."); + NUIS_LOG(FTL, "Bad flux specification: \"" << flux << "\"."); throw; } // Setup TTree TChain *tn = new TChain("gtree"); std::string first_file = ""; if (input.find_first_of(',') != std::string::npos) { std::vector inputvect = GeneralUtils::ParseToStr(input, ","); for (size_t iv_it = 0; iv_it < inputvect.size(); ++iv_it) { tn->AddFile(inputvect[iv_it].c_str()); - QLOG(FIT, "Added input file: " << inputvect[iv_it]); + NUIS_LOG(FIT, "Added input file: " << inputvect[iv_it]); if (!first_file.length()) { first_file = inputvect[iv_it]; } } } else { // The Add form can accept wildcards. tn->Add(input.c_str()); first_file = input; } if (tn->GetFile() == NULL) { tn->Print(); - QERROR(FTL, "gtree not located in GENIE file: " << input); - QTHROW("Check your inputs, they may need to be completely regenerated!"); + NUIS_ERR(FTL, "gtree not located in GENIE file: " << input); + NUIS_ABORT("Check your inputs, they may need to be completely regenerated!"); throw; } int nevt = tn->GetEntries(); if (gNEvents != -999) { - QLOG(FIT, "Overriding number of events by user from " << nevt << " to " + NUIS_LOG(FIT, "Overriding number of events by user from " << nevt << " to " << gNEvents); nevt = gNEvents; } if (!nevt) { - QTHROW("Couldn't load any events from input specification: \"" + NUIS_ABORT("Couldn't load any events from input specification: \"" << input.c_str() << "\""); } else { - QLOG(FIT, "Found " << nevt << " input entries in " << input); + NUIS_LOG(FIT, "Found " << nevt << " input entries in " << input); } NtpMCEventRecord *genientpl = NULL; tn->SetBranchAddress("gmcrec", &genientpl); // Make Event and xsec Hist TH1D *eventhist = (TH1D *)fluxhist->Clone(); eventhist->SetDirectory(NULL); eventhist->Reset(); TH1D *xsechist = (TH1D *)eventhist->Clone(); xsechist->SetDirectory(NULL); // Create maps std::map modexsec; std::map modecount; std::vector genieids; std::vector targetids; std::vector interids; // Loop over all events for (int i = 0; i < nevt; i++) { tn->GetEntry(i); // Hussssch GENIE StopTalking(); // Get the event EventRecord &event = *(genientpl->event); // Get the neutrino GHepParticle *neu = event.Probe(); StartTalking(); // Get XSec From Spline // Get the GHepRecord GHepRecord genie_record = static_cast(event); double xsec = (genie_record.XSec() / (1E-38 * genie::units::cm2)); // Parse Interaction String std::string mode = genie_record.Summary()->AsString(); std::vector modevec = GeneralUtils::ParseToStr(mode, ";"); std::string targ = (modevec[0] + ";" + modevec[1]); std::string inter = mode; // Get target nucleus // Alternative ways of getting the summaries // GHepParticle *target = genie_record.TargetNucleus(); // int pdg = target->Pdg(); // Fill lists of Unique IDS (neutrino and target) if (std::find(targetids.begin(), targetids.end(), targ) == targetids.end()) { targetids.push_back(targ); } // The full interaction list if (std::find(interids.begin(), interids.end(), inter) == interids.end()) { interids.push_back(inter); } // Create entries Mode Maps if (modexsec.find(mode) == modexsec.end()) { genieids.push_back(mode); modexsec[mode] = (TH1D *)xsechist->Clone(); modecount[mode] = (TH1D *)xsechist->Clone(); modexsec[mode]->SetDirectory(NULL); modecount[mode]->SetDirectory(NULL); modexsec[mode]->GetYaxis()->SetTitle( "d#sigma/dE_{#nu} #times 10^{-38} (events weighted by #sigma)"); modecount[mode]->GetYaxis()->SetTitle("Number of events in file"); } // Fill XSec Histograms modexsec[mode]->Fill(neu->E(), xsec); modecount[mode]->Fill(neu->E()); // Fill total event hist eventhist->Fill(neu->E()); if (i % (nevt / 20) == 0) { - QLOG(FIT, "Processed " + NUIS_LOG(FIT, "Processed " << i << "/" << nevt << " GENIE events (E: " << neu->E() << " GeV, xsec: " << xsec << " E-38 cm^2/nucleon)"); } // Clear Event genientpl->Clear(); } - QLOG(FIT, "Processed all events"); + NUIS_LOG(FIT, "Processed all events"); // Once event loop is done we can start saving stuff into the file TFile *outputfile; if (!gOutputFile.length()) { // Shut the chain; delete tn; outputfile = new TFile(first_file.c_str(), "UPDATE"); } else { outputfile = new TFile(gOutputFile.c_str(), "RECREATE"); outputfile->cd(); - QLOG(FIT, "Cloning input vector to output file: " << gOutputFile); + NUIS_LOG(FIT, "Cloning input vector to output file: " << gOutputFile); TTree *cloneTree = tn->CloneTree(-1, "fast"); cloneTree->SetDirectory(outputfile); cloneTree->Write(); // ******************************** // CLUDGE KLUDGE KLUDGE FOR NOVA - QLOG(FIT, "Cloning input nova_wgts to output file: " << gOutputFile); + NUIS_LOG(FIT, "Cloning input nova_wgts to output file: " << gOutputFile); // Also check for the nova_wgts tree from Jeremy TChain *nova_chain = new TChain("nova_wgts"); nova_chain->AddFile(input.c_str()); TTree *nova_tree = nova_chain->CloneTree(-1, "fast"); if (!nova_tree) { - QLOG(FIT, "Could not find nova_wgts tree in " << input); + NUIS_LOG(FIT, "Could not find nova_wgts tree in " << input); } else { - QLOG(FIT, "Found nova_wgts tree in " << input); + NUIS_LOG(FIT, "Found nova_wgts tree in " << input); nova_tree->SetDirectory(outputfile); nova_tree->Write(); } - QLOG(FIT, "Done cloning tree."); + NUIS_LOG(FIT, "Done cloning tree."); } - QLOG(FIT, "Getting splines..."); + NUIS_LOG(FIT, "Getting splines..."); // Save each of the reconstructed splines to file std::map modeavg; TDirectory *inddir = (TDirectory *)outputfile->Get("IndividualGENIESplines"); if (!inddir) inddir = (TDirectory *)outputfile->mkdir("IndividualGENIESplines"); inddir->cd(); // Loop over GENIE ID's and get MEC count int MECcount = 0; bool MECcorrect = FitPar::Config().GetParB("CorrectGENIEMECNorm"); for (UInt_t i = 0; i < genieids.size(); i++) { if (genieids[i].find("MEC") != std::string::npos) { MECcount++; } } - QLOG(FIT, "Found " << MECcount << " repeated MEC instances."); + NUIS_LOG(FIT, "Found " << MECcount << " repeated MEC instances."); for (UInt_t i = 0; i < genieids.size(); i++) { std::string mode = genieids[i]; modexsec[mode]->Write((mode + "_summed_xsec").c_str(), TObject::kOverwrite); modecount[mode]->Write((mode + "_summed_evt").c_str(), TObject::kOverwrite); // Form extra avg xsec map -> Reconstructed spline modeavg[mode] = (TH1D *)modexsec[mode]->Clone(); modeavg[mode]->GetYaxis()->SetTitle( "#sigma (E_{#nu}) #times 10^{-38} (cm^{2}/target)"); modeavg[mode]->Divide(modecount[mode]); if (MECcorrect && (mode.find("MEC") != std::string::npos)) { modeavg[mode]->Scale(1.0 / double(MECcount)); } modeavg[mode]->Write((mode + "_rec_spline").c_str(), TObject::kOverwrite); } TDirectory *targdir = (TDirectory *)outputfile->Get("TargetGENIESplines"); if (!targdir) targdir = (TDirectory *)outputfile->mkdir("TargetGENIESplines"); targdir->cd(); - QLOG(FIT, "Getting Target Splines"); + NUIS_LOG(FIT, "Getting Target Splines"); // For each target save a total spline std::map targetsplines; for (uint i = 0; i < targetids.size(); i++) { std::string targ = targetids[i]; - QLOG(FIT, "Getting target " << i << ": " << targ); + NUIS_LOG(FIT, "Getting target " << i << ": " << targ); targetsplines[targ] = (TH1D *)xsechist->Clone(); targetsplines[targ]->GetYaxis()->SetTitle( "#sigma (E_{#nu}) #times 10^{-38} (cm^{2}/target)"); - QLOG(FIT, "Created target spline for " << targ); + NUIS_LOG(FIT, "Created target spline for " << targ); for (uint j = 0; j < genieids.size(); j++) { std::string mode = genieids[j]; // Look at all matching modes/targets if (mode.find(targ) != std::string::npos) { - QLOG(FIT, " Mode " << mode << " contains " << targ << " target"); + NUIS_LOG(FIT, " Mode " << mode << " contains " << targ << " target"); targetsplines[targ]->Add(modeavg[mode]); - QLOG(FIT, + NUIS_LOG(FIT, "Finished with Mode " << mode << " " << modeavg[mode]->Integral()); } } - QLOG(FIT, "Saving target spline: " << targ); + NUIS_LOG(FIT, "Saving target spline: " << targ); targetsplines[targ]->Write(("Total_" + targ).c_str(), TObject::kOverwrite); } - QLOG(FIT, "Getting total splines"); + NUIS_LOG(FIT, "Getting total splines"); // Now we have each of the targets we need to create a total cross-section. int totalnucl = 0; // This has structure target1[fraction1], target2[fraction2] std::vector targprs = GeneralUtils::ParseToStr(target, ","); std::vector targ_list; std::vector frac_list; // Chop up the target string which has format // TARGET1[fraction1],TARGET2[fraction2] // std::cout << "Targets: " << std::endl; // Loop over the vector of strings "TARGET1[fraction1]" "TARGET2[fraction2]" for (std::vector::iterator it = targprs.begin(); it != targprs.end(); ++it) { // Cut into "TARGET1" and "fraction1]" std::vector targind = GeneralUtils::ParseToStr(*it, "["); // std::cout << " " << *it << std::endl; // Cut into "TARGET1" and "fraction1" for (std::vector::iterator jt = targind.begin(); jt != targind.end(); ++jt) { if ((*jt).find("]") != std::string::npos) { (*jt) = (*jt).substr(0, (*jt).find("]")); //*jt = "hello"; frac_list.push_back(*jt); // Won't find bracket for target } else { targ_list.push_back(*jt); } } } targprs = targ_list; std::vector targ_fractions; double minimum = 1.0; for (std::vector::iterator it = frac_list.begin(); it != frac_list.end(); it++) { // std::cout << " " << *it << std::endl; double frac = std::atof((*it).c_str()); targ_fractions.push_back(frac); if (frac < minimum) minimum = frac; } std::vector::iterator it = targ_fractions.begin(); std::vector::iterator jt = targ_list.begin(); double scaling = 0; for (; it != targ_fractions.end(); it++, jt++) { // First get the mass number from the targ_list int nucl = atoi((*jt).c_str()); nucl = (nucl % 10000) / 10; // Gets the relative portions right *it = (*it) / minimum; // Scale relative the atomic mass //(*it) *= (double(nucl)/(*it)); double tempscaling = double(nucl) / (*it); if (tempscaling > scaling) scaling = tempscaling; } it = targ_fractions.begin(); for (; it != targ_fractions.end(); it++) { // Round the scaling to nearest integer and multiply *it *= int(scaling + 0.5); // Round to nearest integer *it = int(*it + 0.5); totalnucl += *it; } if (totalnucl == 0) { - QTHROW("Didn't find any nucleons in input file. Did you really specify the " + NUIS_ABORT("Didn't find any nucleons in input file. Did you really specify the " "target ratios?\ne.g. TARGET1[fraction1],TARGET2[fraction2]"); } TH1D *totalxsec = (TH1D *)xsechist->Clone(); // Loop over the specified targets by the user for (uint i = 0; i < targprs.size(); i++) { std::string targpdg = targprs[i]; // Check that we found the user requested target in GENIE bool FoundTarget = false; for (std::map::iterator iter = targetsplines.begin(); iter != targetsplines.end(); iter++) { std::string targstr = iter->first; TH1D *xsec = iter->second; // Match the user targets to the targets found in GENIE if (targstr.find(targpdg) != std::string::npos) { FoundTarget = true; - QLOG(FIT, "Adding target spline " + NUIS_LOG(FIT, "Adding target spline " << targstr << " Integral = " << xsec->Integral("width")); totalxsec->Add(xsec); // int nucl = atoi(targpdg.c_str()); // totalnucl += int((nucl % 10000) / 10); } } // Looped over target splines // Check that targets were all found if (!FoundTarget) { - QERROR(WRN, "Didn't find target " + NUIS_ERR(WRN, "Didn't find target " << targpdg << " in the list of targets recorded by GENIE"); - QERROR(WRN, " The list of targets you requested is: "); + NUIS_ERR(WRN, " The list of targets you requested is: "); for (uint i = 0; i < targprs.size(); ++i) - QERROR(WRN, " " << targprs[i]); - QERROR(WRN, " The list of targets found in GENIE is: "); + NUIS_ERR(WRN, " " << targprs[i]); + NUIS_ERR(WRN, " The list of targets found in GENIE is: "); for (std::map::iterator iter = targetsplines.begin(); iter != targetsplines.end(); iter++) - QERROR(WRN, " " << iter->first); + NUIS_ERR(WRN, " " << iter->first); } } outputfile->cd(); totalxsec->GetYaxis()->SetTitle( "#sigma (E_{#nu}) #times 10^{-38} (cm^{2}/nucleon)"); totalxsec->Write("nuisance_xsec", TObject::kOverwrite); eventhist = (TH1D *)fluxhist->Clone(); eventhist->Multiply(totalxsec); eventhist->GetYaxis()->SetTitle( (std::string("Event rate (N = #sigma #times #Phi) #times 10^{-38} " "(cm^{2}/nucleon) #times ") + eventhist->GetYaxis()->GetTitle()) .c_str()); - QLOG(FIT, "Dividing by Total Nucl = " << totalnucl); + NUIS_LOG(FIT, "Dividing by Total Nucl = " << totalnucl); eventhist->Scale(1.0 / double(totalnucl)); eventhist->Write("nuisance_events", TObject::kOverwrite); fluxhist->Write("nuisance_flux", TObject::kOverwrite); - QLOG(FIT, "Inclusive XSec Per Nucleon = " << eventhist->Integral("width") * + NUIS_LOG(FIT, "Inclusive XSec Per Nucleon = " << eventhist->Integral("width") * 1E-38 / fluxhist->Integral("width")); - QLOG(FIT, "XSec Hist Integral = " << totalxsec->Integral()); + NUIS_LOG(FIT, "XSec Hist Integral = " << totalxsec->Integral()); outputfile->Close(); return; }; void PrintOptions() { std::cout << "PrepareGENIEEvents NUISANCE app. " << std::endl << "Takes GHep Outputs and prepares events for NUISANCE." << std::endl << std::endl << "PrepareGENIE [-h,-help,--h,--help] [-i " "inputfile1.root,inputfile2.root,inputfile3.root,...] " << "[-f flux_root_file.root,flux_hist_name] [-t " "target1[frac1],target2[frac2],...]" << "[-n number_of_events (experimental)]" << std::endl << std::endl; std::cout << "Prepare Mode [Default] : Takes a single GHep file, " "reconstructs the original GENIE splines, " << " and creates a duplicate file that also contains the flux, " "event rate, and xsec predictions that NUISANCE needs. " << std::endl; std::cout << "Following options are required for Prepare Mode:" << std::endl; std::cout << " [ -i inputfile.root ] : Reads in a single GHep input file " "that needs the xsec calculation ran on it. " << std::endl; std::cout << " [ -f flux_file.root,hist_name ] : Path to root file " "containing the flux histogram the GHep records were generated " "with." << " A simple method is to point this to the flux histogram genie " "generatrs '-f /path/to/events/input-flux.root,spectrum'. " << std::endl; std::cout << " [ -f elow,ehigh,estep ] : Energy range specification when no " "flux file was used." << std::endl; std::cout << " [ -t target ] : Target that GHepRecords were generated with. " "Comma seperated list. E.g. for CH2 " "target=1000060120,1000010010,1000010010" << std::endl; std::cout << " [ -o outputfile.root ] : File to write prepared input file to." << std::endl; std::cout << " [ -m Mono_E_nu_GeV ] : Run in mono-energetic mode with m GeV " "neutrino energy." << std::endl; std::cout << " [ -n number_of_evt ] : Run with a reduced number of events " "for debugging purposes" << std::endl; } void ParseOptions(int argc, char *argv[]) { bool flagopt = false; // If No Arguments print commands for (int i = 1; i < argc; ++i) { if (!std::strcmp(argv[i], "-h")) { flagopt = true; break; } if (i + 1 != argc) { // Cardfile if (!std::strcmp(argv[i], "-h")) { flagopt = true; break; } else if (!std::strcmp(argv[i], "-i")) { gInputFiles = argv[i + 1]; ++i; } else if (!std::strcmp(argv[i], "-o")) { gOutputFile = argv[i + 1]; ++i; } else if (!std::strcmp(argv[i], "-f")) { gFluxFile = argv[i + 1]; ++i; } else if (!std::strcmp(argv[i], "-t")) { gTarget = argv[i + 1]; ++i; } else if (!std::strcmp(argv[i], "-n")) { gNEvents = GeneralUtils::StrToInt(argv[i + 1]); ++i; } else if (!std::strcmp(argv[i], "-m")) { MonoEnergy = GeneralUtils::StrToDbl(argv[i + 1]); IsMonoE = true; ++i; } else { - QERROR(FTL, "ERROR: unknown command line option given! - '" + NUIS_ERR(FTL, "ERROR: unknown command line option given! - '" << argv[i] << " " << argv[i + 1] << "'"); PrintOptions(); break; } } } if (gInputFiles == "" && !flagopt) { - QERROR(FTL, "No input file(s) specified!"); + NUIS_ERR(FTL, "No input file(s) specified!"); flagopt = true; } if (gFluxFile == "" && !flagopt && !IsMonoE) { - QERROR(FTL, "No flux input specified for Prepare Mode"); + NUIS_ERR(FTL, "No flux input specified for Prepare Mode"); flagopt = true; } if (gTarget == "" && !flagopt) { - QERROR(FTL, "No target specified for Prepare Mode"); + NUIS_ERR(FTL, "No target specified for Prepare Mode"); flagopt = true; } if (gTarget.find("[") == std::string::npos || gTarget.find("]") == std::string::npos) { - QERROR(FTL, "Didn't specify target ratios in Prepare Mode"); - QERROR(FTL, "Are you sure you gave it as -t " + NUIS_ERR(FTL, "Didn't specify target ratios in Prepare Mode"); + NUIS_ERR(FTL, "Are you sure you gave it as -t " "\"TARGET1[fraction1],TARGET2[fraction]\"?"); flagopt = true; } if (argc < 1 || flagopt) { PrintOptions(); exit(-1); } return; } diff --git a/app/PrepareNEUT.cxx b/app/PrepareNEUT.cxx index 0d929f6..d95d069 100644 --- a/app/PrepareNEUT.cxx +++ b/app/PrepareNEUT.cxx @@ -1,416 +1,416 @@ #include "FitLogger.h" #include "PlotUtils.h" #include "StatUtils.h" #include "TFile.h" #include "TH1D.h" #include "TTree.h" #include #include // If you don't have NEUT enabled, you shouldn't compile this... #include "neutpart.h" #include "neutvect.h" std::string fInputFiles = ""; std::string fOutputFile = ""; std::string fFluxFile = ""; bool fFluxInGeV = false; bool fIsMonoEFlux = false; double fMonoEEnergy = 0xdeadbeef; void PrintOptions(); void ParseOptions(int argc, char *argv[]); void AddMonoRateHistogram(std::string inputList, double MonoE, std::string output); void CreateRateHistogram(std::string inputList, std::string flux, std::string output); //******************************* int main(int argc, char *argv[]) { //******************************* LOG_VERB(FitPar::Config().GetParI("VERBOSITY")); ERR_VERB(FitPar::Config().GetParI("ERROR")); ParseOptions(argc, argv); - QLOG(FIT, "Running PrepareNEUT"); + NUIS_LOG(FIT, "Running PrepareNEUT"); if (fIsMonoEFlux) { AddMonoRateHistogram(fInputFiles, fMonoEEnergy, fOutputFile); } else { CreateRateHistogram(fInputFiles, fFluxFile, fOutputFile); } }; void AddMonoRateHistogram(std::string inputList, double MonoE, std::string output) { // Need to allow for more than one file... will do soon TChain *tn = new TChain("neuttree"); std::vector inputs = GeneralUtils::ParseToStr(inputList, ","); for (std::vector::iterator it = inputs.begin(); it != inputs.end(); ++it) { - QLOG(FIT, "Adding " << *it << " to the output"); + NUIS_LOG(FIT, "Adding " << *it << " to the output"); tn->AddFile((*it).c_str()); } if (inputs.size() > 1 && output.empty()) { - QTHROW("You must provide a new output file name if you want to have " + NUIS_ABORT("You must provide a new output file name if you want to have " "more than 1 input file!"); } int nevts = tn->GetEntries(); if (!nevts) { - QTHROW("Either the input file is not from NEUT, or it's empty..."); + NUIS_ABORT("Either the input file is not from NEUT, or it's empty..."); } NeutVect *fNeutVect = NULL; tn->SetBranchAddress("vectorbranch", &fNeutVect); TH1D *fluxHist = new TH1D("flux", "flux", 1000, 0, fFluxInGeV ? 10 : 10000); fluxHist->Fill(MonoE); fluxHist->Scale(1, "width"); // Make Event Hist TH1D *xsecHist = (TH1D *)fluxHist->Clone(); xsecHist->Reset(); // Make a total cross section hist for shits and giggles TH1D *entryHist = (TH1D *)xsecHist->Clone(); double MeanE = 0; for (int i = 0; i < nevts; ++i) { tn->GetEntry(i); NeutPart *part = fNeutVect->PartInfo(0); double E = part->fP.E(); double xsec = fNeutVect->Totcrs; // Unit conversion if (fFluxInGeV) E *= 1E-3; xsecHist->Fill(E, xsec); entryHist->Fill(E); MeanE += E; if (i % (nevts / 20) == 0) { - QLOG(FIT, "Processed " << i << "/" << nevts << " NEUT events."); + NUIS_LOG(FIT, "Processed " << i << "/" << nevts << " NEUT events."); } } MeanE /= double(nevts); - QLOG(FIT, "Processed all events"); + NUIS_LOG(FIT, "Processed all events"); xsecHist->Divide(entryHist); // This will be the evtrt histogram TH1D *evtHist = (TH1D *)xsecHist->Clone(); evtHist->Multiply(fluxHist); // Check whether the overflow is empty. If not, advise that either the wrong // flux histogram or units were used... // If the events were generated with a limited range of the flux histogram, // this may be benign if (evtHist->Integral(0, -1) != evtHist->Integral() || evtHist->Integral(0, -1) == 0) { - QERROR(WRN, "The input file(" + NUIS_ERR(WRN, "The input file(" << evtHist->Integral(0, -1) << ") and flux histogram provided do not match... "); - QERROR(WRN, "Are the units correct (MeanE = " + NUIS_ERR(WRN, "Are the units correct (MeanE = " << MeanE << ", FluxHistoUpperLim: " << fluxHist->GetXaxis()->GetBinUpEdge(1000) << ")? Did you provide the correct flux file?"); - QERROR(WRN, "Use output with caution..."); + NUIS_ERR(WRN, "Use output with caution..."); } // Pick where the output should go TFile *outFile = NULL; if (!output.empty()) { - QLOG(FIT, "Saving histograms in " << output); + NUIS_LOG(FIT, "Saving histograms in " << output); outFile = new TFile(output.c_str(), "RECREATE"); } else { - QLOG(FIT, "Saving histograms in " << inputs[0]); + NUIS_LOG(FIT, "Saving histograms in " << inputs[0]); outFile = new TFile(inputs[0].c_str(), "UPDATE"); } outFile->cd(); std::string xsec_name = "xsec_PrepareNeut"; std::string flux_name = "flux_PrepareNeut"; std::string rate_name = "evtrt_PrepareNeut"; if (output.empty()) { // Check whether we should overwrite existing histograms std::string input_xsec = PlotUtils::GetObjectWithName(outFile, "xsec"); std::string input_flux = PlotUtils::GetObjectWithName(outFile, "flux"); std::string input_rate = PlotUtils::GetObjectWithName(outFile, "evtrt"); if (!input_xsec.empty()) { - QLOG(FIT, "Updating histogram: " << input_xsec); + NUIS_LOG(FIT, "Updating histogram: " << input_xsec); xsec_name = input_xsec; } if (!input_flux.empty()) { - QLOG(FIT, "Updating histogram: " << input_flux); + NUIS_LOG(FIT, "Updating histogram: " << input_flux); flux_name = input_flux; } if (!input_rate.empty()) { - QLOG(FIT, "Updating histogram: " << input_rate); + NUIS_LOG(FIT, "Updating histogram: " << input_rate); rate_name = input_rate; } } else { - QLOG(FIT, "Cloning neuttree into output file."); + NUIS_LOG(FIT, "Cloning neuttree into output file."); StopTalking(); TTree *newtree = (TTree *)tn->CloneTree(-1, "fast"); StartTalking(); newtree->Write(); } xsecHist->Write(xsec_name.c_str(), TObject::kOverwrite); fluxHist->Write(flux_name.c_str(), TObject::kOverwrite); evtHist->Write(rate_name.c_str(), TObject::kOverwrite); outFile->Close(); } //******************************* void CreateRateHistogram(std::string inputList, std::string flux, std::string output) { //******************************* // Need to allow for more than one file... will do soon TChain *tn = new TChain("neuttree"); std::vector inputs = GeneralUtils::ParseToStr(inputList, ","); for (std::vector::iterator it = inputs.begin(); it != inputs.end(); ++it) { - QLOG(FIT, "Adding " << *it << " to the output"); + NUIS_LOG(FIT, "Adding " << *it << " to the output"); tn->AddFile((*it).c_str()); } if (inputs.size() > 1 && output.empty()) { - QTHROW("You must provide a new output file name if you want to have " + NUIS_ABORT("You must provide a new output file name if you want to have " "more than 1 input file!"); } int nevts = tn->GetEntries(); if (!nevts) { - QTHROW("Either the input file is not from NEUT, or it's empty..."); + NUIS_ABORT("Either the input file is not from NEUT, or it's empty..."); } NeutVect *fNeutVect = NULL; tn->SetBranchAddress("vectorbranch", &fNeutVect); // Get Flux Hist std::vector fluxvect = GeneralUtils::ParseToStr(flux, ","); TH1D *fluxHist = NULL; if (fluxvect.size() > 1) { TFile *fluxfile = new TFile(fluxvect[0].c_str(), "READ"); fluxHist = (TH1D *)fluxfile->Get(fluxvect[1].c_str()); fluxHist->SetDirectory(0); } else { - QTHROW("NO FLUX SPECIFIED"); + NUIS_ABORT("NO FLUX SPECIFIED"); } // Decide what type of flux was given if (fFluxInGeV) { - QLOG(FIT, "Assuming flux histogram is in GeV"); + NUIS_LOG(FIT, "Assuming flux histogram is in GeV"); } else { - QLOG(FIT, "Assuming flux histogram is in MeV"); + NUIS_LOG(FIT, "Assuming flux histogram is in MeV"); } // Make Event Hist TH1D *xsecHist = (TH1D *)fluxHist->Clone(); xsecHist->Reset(); // Make a total cross section hist for shits and giggles TH1D *entryHist = (TH1D *)xsecHist->Clone(); for (int i = 0; i < nevts; ++i) { tn->GetEntry(i); NeutPart *part = fNeutVect->PartInfo(0); double E = part->fP.E(); double xsec = fNeutVect->Totcrs; // Unit conversion if (fFluxInGeV) E *= 1E-3; xsecHist->Fill(E, xsec); entryHist->Fill(E); if (i % (nevts / 20) == 0) { - QLOG(FIT, "Processed " << i << "/" << nevts << " NEUT events." + NUIS_LOG(FIT, "Processed " << i << "/" << nevts << " NEUT events." << "(Enu = " << E << ", xsec = " << xsec << ") "); } } - QLOG(FIT, "Processed all events"); + NUIS_LOG(FIT, "Processed all events"); xsecHist->Divide(entryHist); // This will be the evtrt histogram TH1D *evtHist = NULL; // If the integral of xsecHist is 0 the input file used a really old version // of NEUT without Totcrs if (!xsecHist->Integral(0, -1)) { - QERROR(WRN, "Old NEUT input file: events will not be correctly normalized"); + NUIS_ERR(WRN, "Old NEUT input file: events will not be correctly normalized"); evtHist = (TH1D *)entryHist->Clone(); if (evtHist->Integral() != 0) evtHist->Scale(fluxHist->Integral() / float(evtHist->Integral())); } else { evtHist = (TH1D *)xsecHist->Clone(); evtHist->Multiply(fluxHist); } // Check whether the overflow is empty. If not, advise that either the wrong // flux histogram or units were used... // If the events were generated with a limited range of the flux histogram, // this may be benign if (evtHist->Integral(0, -1) != evtHist->Integral() || evtHist->Integral(0, -1) == 0) { - QERROR(WRN, "The input file(" + NUIS_ERR(WRN, "The input file(" << evtHist->Integral(0, -1) << ") and flux histogram provided do not match... "); - QERROR(WRN, + NUIS_ERR(WRN, "Are the units correct? Did you provide the correct flux file?"); - QERROR(WRN, "Use output with caution..."); + NUIS_ERR(WRN, "Use output with caution..."); } // Pick where the output should go TFile *outFile = NULL; if (!output.empty()) { - QLOG(FIT, "Saving histograms in " << output); + NUIS_LOG(FIT, "Saving histograms in " << output); outFile = new TFile(output.c_str(), "RECREATE"); } else { - QLOG(FIT, "Saving histograms in " << inputs[0]); + NUIS_LOG(FIT, "Saving histograms in " << inputs[0]); outFile = new TFile(inputs[0].c_str(), "UPDATE"); } outFile->cd(); std::string xsec_name = "xsec_PrepareNeut"; std::string flux_name = "flux_PrepareNeut"; std::string rate_name = "evtrt_PrepareNeut"; if (output.empty()) { // Check whether we should overwrite existing histograms std::string input_xsec = PlotUtils::GetObjectWithName(outFile, "xsec"); std::string input_flux = PlotUtils::GetObjectWithName(outFile, "flux"); std::string input_rate = PlotUtils::GetObjectWithName(outFile, "evtrt"); if (!input_xsec.empty()) { - QLOG(FIT, "Updating histogram: " << input_xsec); + NUIS_LOG(FIT, "Updating histogram: " << input_xsec); xsec_name = input_xsec; } if (!input_flux.empty()) { - QLOG(FIT, "Updating histogram: " << input_flux); + NUIS_LOG(FIT, "Updating histogram: " << input_flux); flux_name = input_flux; } if (!input_rate.empty()) { - QLOG(FIT, "Updating histogram: " << input_rate); + NUIS_LOG(FIT, "Updating histogram: " << input_rate); rate_name = input_rate; } } else { - QLOG(FIT, "Cloning neuttree into output file."); + NUIS_LOG(FIT, "Cloning neuttree into output file."); StopTalking(); TTree *newtree = (TTree *)tn->CloneTree(-1, "fast"); StartTalking(); newtree->Write(); } xsecHist->Write(xsec_name.c_str(), TObject::kOverwrite); fluxHist->Write(flux_name.c_str(), TObject::kOverwrite); evtHist->Write(rate_name.c_str(), TObject::kOverwrite); outFile->Close(); return; } void PrintOptions() { std::cout << "PrepareNEUT NUISANCE app. " << std::endl << "Produces or recalculates evtrt and flux histograms necessary " "for NUISANCE normalization." << std::endl; std::cout << "PrepareNEUT: " << std::endl; std::cout << " [-h,-help,--h,--help]" << std::endl; std::cout << " -i inputfile1.root,inputfile2.root,inputfile3.root,..." << std::endl; std::cout << " Takes any number of files, but assumes all are " "produced with a single flux" << std::endl; std::cout << " -f flux_root_file.root,flux_hist_name" << std::endl; std::cout << " Path to root file containing the flux histogram used " "when generating the NEUT files" << std::endl; std::cout << " [-o outputfile.root] " << std::endl; std::cout << " If an output file is not given, the input file will be used" << std::endl; std::cout << " If more than one input file is given, an output file " "must be given" << std::endl; std::cout << " [-G]" << std::endl; std::cout << " Flux is assumed to be in MeV. This switch indicates " "the input flux is in GeV" << std::endl; std::cout << " [-m E_nu]" << std::endl; std::cout << " Used to add dummy flux and evt rate histograms to " "mono-energetic vectors. Adheres to the -G flag." << std::endl; } void ParseOptions(int argc, char *argv[]) { bool flagopt = false; // If No Arguments print commands for (int i = 1; i < argc; ++i) { if (!std::strcmp(argv[i], "-h")) { flagopt = true; break; } else if (!std::strcmp(argv[i], "-G")) { fFluxInGeV = true; continue; } if (i + 1 != argc) { // Cardfile if (!std::strcmp(argv[i], "-h")) { flagopt = true; break; } else if (!std::strcmp(argv[i], "-i")) { fInputFiles = argv[i + 1]; ++i; } else if (!std::strcmp(argv[i], "-o")) { fOutputFile = argv[i + 1]; ++i; } else if (!std::strcmp(argv[i], "-f")) { fFluxFile = argv[i + 1]; ++i; } else if (!std::strcmp(argv[i], "-m")) { fIsMonoEFlux = true; fMonoEEnergy = GeneralUtils::StrToDbl(argv[i + 1]); ++i; } else { - QERROR(FTL, "ERROR: unknown command line option given! - '" + NUIS_ERR(FTL, "ERROR: unknown command line option given! - '" << argv[i] << " " << argv[i + 1] << "'"); PrintOptions(); break; } } } if (fInputFiles == "" && !flagopt) { - QERROR(FTL, "No input file(s) specified!"); + NUIS_ERR(FTL, "No input file(s) specified!"); flagopt = true; } if (fFluxFile == "" && (!flagopt) && (!fIsMonoEFlux)) { - QERROR(FTL, "No flux input specified!"); + NUIS_ERR(FTL, "No flux input specified!"); flagopt = true; } if (argc < 1 || flagopt) { PrintOptions(); exit(-1); } return; } diff --git a/app/PrepareNuwroEvents.cxx b/app/PrepareNuwroEvents.cxx index ba52a84..c6daed4 100644 --- a/app/PrepareNuwroEvents.cxx +++ b/app/PrepareNuwroEvents.cxx @@ -1,492 +1,492 @@ #include "event1.h" #include #include // Hopefully we don't need these as they're included above. // #include "params_all.h" // #include "params.h" #include "FitLogger.h" #include "PlotUtils.h" #include "TFile.h" #include "TH1D.h" #include "TTree.h" void printInputCommands(char *argv[]) { std::cout << "[USAGE]: " << argv[0] << " [-h] [-f] [-F ,] [-o output.root] " "inputfile.root [file2.root ...]" << std::endl << "\t-h : Print this message." << std::endl << "\t-f : Pass -f argument to '$ hadd' invocation." << std::endl << "\t-F : Read input flux from input descriptor." << std::endl << "\t-o : Write full output to a new file." << std::endl << std::endl; }; void CreateRateHistograms(std::string inputs, bool force_out); void HaddNuwroFiles(std::vector &inputs, bool force_out); bool outputNewFile = false; std::string ofile = ""; bool haveFluxInputs = false; struct FluxInputBlob { FluxInputBlob(std::string _File, std::string _Hist, int _PDG, double _Fraction) : File(_File), Hist(_Hist), PDG(_PDG), Fraction(_Fraction) {} std::string File; std::string Hist; int PDG; double Fraction; }; std::vector FluxInputs; bool haddedFiles = false; TH1D *F2D(TH1F *f) { Double_t *bins = new Double_t[f->GetXaxis()->GetNbins() + 1]; for (Int_t bi_it = 0; bi_it < f->GetXaxis()->GetNbins(); ++bi_it) { bins[bi_it] = f->GetXaxis()->GetBinLowEdge(bi_it + 1); } bins[f->GetXaxis()->GetNbins()] = f->GetXaxis()->GetBinUpEdge(f->GetXaxis()->GetNbins()); TH1D *d = new TH1D((std::string(f->GetName()) + "_f").c_str(), f->GetTitle(), f->GetXaxis()->GetNbins(), bins); std::cout << "Converted TH1F with " << f->GetXaxis()->GetXbins() << " bins : " << std::endl; for (Int_t bi_it = 0; bi_it < f->GetXaxis()->GetNbins() + 2; ++bi_it) { d->SetBinContent(bi_it, f->GetBinContent(bi_it)); d->SetBinError(bi_it, f->GetBinError(bi_it)); std::cout << "\tF " << f->GetXaxis()->GetBinLowEdge(bi_it) << "--[" << bi_it << "]--" << f->GetXaxis()->GetBinUpEdge(bi_it) << ": " << f->GetBinContent(bi_it) << " D " << d->GetXaxis()->GetBinLowEdge(bi_it) << "--[" << bi_it << "]--" << d->GetXaxis()->GetBinUpEdge(bi_it) << ": " << d->GetBinContent(bi_it) << std::endl; } delete bins; return d; } TH1D *GetTH1DFromFile(std::string const &rootFile, std::string const &histName) { TFile *inpFile = new TFile(rootFile.c_str(), "READ"); if (!inpFile || !inpFile->IsOpen()) { - QTHROW("Cannot open input root file: " << rootFile + NUIS_ABORT("Cannot open input root file: " << rootFile << " to read input histo."); } TH1D *histD = dynamic_cast(inpFile->Get(histName.c_str())); if (!histD) { TH1F *histF = dynamic_cast(inpFile->Get(histName.c_str())); if (!histF) { - QTHROW("Cannot find TH1D/F: " << histName << " in root file: " << rootFile + NUIS_ABORT("Cannot find TH1D/F: " << histName << " in root file: " << rootFile << "."); } histD = F2D(histF); } else { histD = static_cast(histD->Clone()); } histD->SetDirectory(NULL); inpFile->Close(); return histD; } //******************************* int main(int argc, char *argv[]) { //******************************* // If No Arguments print commands if (argc == 1) { printInputCommands(argv); return 0; } std::vector inputfiles; bool force_output = false; // Get Inputs for (int i = 1; i < argc; ++i) { if (!std::strcmp(argv[i], "-h")) { printInputCommands(argv); return 0; } else if (!std::strcmp(argv[i], "-f")) { force_output = true; } else if (!std::strcmp(argv[i], "-o")) { outputNewFile = true; ofile = argv[++i]; } else if (!std::strcmp(argv[i], "-F")) { std::string inpLine = argv[++i]; std::vector fluxInputDescriptor = GeneralUtils::ParseToStr(inpLine, ","); if ((fluxInputDescriptor.size() != 2) && (fluxInputDescriptor.size() != 3) && (fluxInputDescriptor.size() != 4)) { - QTHROW("Received -F argument with option: \"" + NUIS_ABORT("Received -F argument with option: \"" << inpLine << "\", was expecting " ",[,PDG[,speciesFraction]]."); } haveFluxInputs = true; FluxInputs.push_back( FluxInputBlob(fluxInputDescriptor[0], fluxInputDescriptor[1], (fluxInputDescriptor.size() > 2) ? GeneralUtils::StrToInt(fluxInputDescriptor[2]) : 14, (fluxInputDescriptor.size() > 3) ? GeneralUtils::StrToDbl(fluxInputDescriptor[3]) : 1)); if (!FluxInputs.back().File.length() || !FluxInputs.back().Hist.length()) { - QTHROW("Received -F argument with option: \"" + NUIS_ABORT("Received -F argument with option: \"" << inpLine << "\", was expecting " ",[,PDG[,speciesFraction]]."); } } else { inputfiles.push_back(std::string(argv[i])); } } // If one input file just create flux histograms if (inputfiles.size() > (UInt_t)1) { HaddNuwroFiles(inputfiles, force_output); } else if (inputfiles.size() < (UInt_t)1) { printInputCommands(argv); } CreateRateHistograms(inputfiles[0], force_output); - QLOG(FIT, "Finished NUWRO Prep."); + NUIS_LOG(FIT, "Finished NUWRO Prep."); }; //******************************* void CreateRateHistograms(std::string inputs, bool force_out) { //******************************* // Open root file TFile *outRootFile = 0; TTree *nuwrotree = 0; if (!haddedFiles && outputNewFile) { // we need to make the new file and clone the tree. TFile *inpFile = new TFile(inputs.c_str(), "READ"); if (!inpFile || !inpFile->IsOpen()) { - QTHROW("Cannot open input root file: " << inputs); + NUIS_ABORT("Cannot open input root file: " << inputs); } TTree *inpTree = dynamic_cast(inpFile->Get("treeout")); if (!inpTree) { - QTHROW("Cannot find TTree \"treeout\" in input root file: " + NUIS_ABORT("Cannot find TTree \"treeout\" in input root file: " << inputs.c_str()); } outRootFile = new TFile(ofile.c_str(), force_out ? "RECREATE" : "CREATE"); if (!outRootFile || !outRootFile->IsOpen()) { - QTHROW("Couldn't open root file: " + NUIS_ABORT("Couldn't open root file: " << ofile << " for writing, does it already exist?"); } nuwrotree = inpTree->CloneTree(-1, "fast"); nuwrotree->SetDirectory(outRootFile); nuwrotree->Write(nuwrotree->GetName()); } else { outRootFile = new TFile(inputs.c_str(), "UPDATE"); if (!outRootFile || !outRootFile->IsOpen()) { - QTHROW("Cannot open input root file: " << inputs); + NUIS_ABORT("Cannot open input root file: " << inputs); } nuwrotree = dynamic_cast(outRootFile->Get("treeout")); if (!nuwrotree) { - QTHROW("Cannot find TTree \"treeout\" in input root file: " + NUIS_ABORT("Cannot find TTree \"treeout\" in input root file: " << inputs.c_str()); } } // Get Flux Histogram event *evt = new event(); nuwrotree->SetBranchAddress("e", &evt); nuwrotree->GetEntry(0); int fluxtype = evt->par.beam_type; std::map fluxlist; std::map eventlist; std::vector allpdg; std::map nevtlist; std::map intxseclist; // Did the input file have a mono-energetic flux? bool isMono = false; nevtlist[0] = 0.0; intxseclist[0] = 0.0; allpdg.push_back(0); - QLOG(FIT, "Nuwro fluxtype = " << fluxtype); + NUIS_LOG(FIT, "Nuwro fluxtype = " << fluxtype); if (haveFluxInputs) { double totalFraction = 0; for (size_t flux_it = 0; flux_it < FluxInputs.size(); ++flux_it) { FluxInputBlob &fb = FluxInputs[flux_it]; int pdg = fb.PDG; TH1D *fluxHist = GetTH1DFromFile(fb.File, fb.Hist); double pctg = fb.Fraction; totalFraction += pctg; double Elow = fluxHist->GetXaxis()->GetBinLowEdge(1); double Ehigh = fluxHist->GetXaxis()->GetBinLowEdge( fluxHist->GetXaxis()->GetNbins() + 1); - QLOG(FIT, "Adding new nuwro flux " + NUIS_LOG(FIT, "Adding new nuwro flux " << "pdg: " << pdg << " pctg: " << pctg << " Elow: " << Elow << " Ehigh: " << Ehigh); // Sort total flux plot if (!fluxlist[0]) { // Setup total flux fluxlist[0] = (TH1D *)fluxHist->Clone(); fluxlist[0]->SetNameTitle("FluxHist", "FluxHist"); // Prep empty total events eventlist[0] = (TH1D *)fluxHist->Clone(); eventlist[0]->SetNameTitle("EvtHist", "EvtHist"); eventlist[0]->Reset(); } else { // Add up each new plot fluxlist[0]->Add(fluxHist); } fluxHist->SetNameTitle(Form("nuwro_pdg%i_pct%f_Flux", pdg, pctg), Form("nuwro_pdg%i_pct%f_Flux", pdg, pctg)); TH1D *eventplot = (TH1D *)fluxHist->Clone(); eventplot->SetNameTitle(Form("nuwro_pdg%i_pct%f_Evt", pdg, pctg), Form("nuwro_pdg%i_pct%f_Evt", pdg, pctg)); eventplot->Reset(); fluxlist[pdg] = (TH1D *)fluxHist->Clone(); eventlist[pdg] = eventplot; nevtlist[pdg] = 0; intxseclist[pdg] = 0.0; allpdg.push_back(pdg); delete fluxHist; } if (fabs(totalFraction - 1) > 1E-5) { - QTHROW(FTL, "Total species fraction for input flux histos = " + NUIS_ABORT(FTL, "Total species fraction for input flux histos = " << totalFraction << ", expected to sum to 1."); } } else if (fluxtype == 0) { std::string fluxstring = evt->par.beam_energy; std::vector fluxvals = GeneralUtils::ParseToDbl(fluxstring, " "); int pdg = evt->par.beam_particle; double Elow = double(fluxvals[0]) / 1000.0; double Ehigh = double(fluxvals[1]) / 1000.0; TH1D *fluxplot = NULL; if (Elow > Ehigh) isMono = true; // For files produced with a flux distribution if (!isMono) { - QLOG(FIT, "Adding new nuwro flux " + NUIS_LOG(FIT, "Adding new nuwro flux " << "pdg: " << pdg << " Elow: " << Elow << " Ehigh: " << Ehigh); fluxplot = new TH1D("fluxplot", "fluxplot", fluxvals.size() - 4, Elow, Ehigh); for (uint j = 2; j < fluxvals.size(); j++) { - QLOG(DEB, j << " " << fluxvals[j]); + NUIS_LOG(DEB, j << " " << fluxvals[j]); fluxplot->SetBinContent(j - 1, fluxvals[j]); } } else { // For monoenergetic fluxes - QLOG(FIT, "Adding mono-energetic nuwro flux " + NUIS_LOG(FIT, "Adding mono-energetic nuwro flux " << "pdg: " << pdg << " E: " << Elow); fluxplot = new TH1D("fluxplot", "fluxplot", 100, 0, Elow * 2); fluxplot->SetBinContent(fluxplot->FindBin(Elow), 1); } // Setup total flux fluxlist[0] = (TH1D *)fluxplot->Clone(); fluxlist[0]->SetNameTitle("FluxHist", "FluxHist"); // Prep empty total events eventlist[0] = (TH1D *)fluxplot->Clone(); eventlist[0]->SetNameTitle("EvtHist", "EvtHist"); eventlist[0]->Reset(); fluxplot->SetNameTitle(Form("nuwro_pdg%i_Flux", pdg), Form("nuwro_pdg%i_Flux", pdg)); TH1D *eventplot = (TH1D *)fluxplot->Clone(); eventplot->SetNameTitle(Form("nuwro_pdg%i_Evt", pdg), Form("nuwro_pdg%i_Evt", pdg)); eventplot->Reset(); fluxlist[pdg] = fluxplot; eventlist[pdg] = eventplot; nevtlist[pdg] = 0; intxseclist[pdg] = 0.0; allpdg.push_back(pdg); } else if (fluxtype == 1) { std::string fluxstring = evt->par.beam_content; std::vector fluxlines = GeneralUtils::ParseToStr(fluxstring, "\n"); for (uint i = 0; i < fluxlines.size(); i++) { std::vector fluxvals = GeneralUtils::ParseToDbl(fluxlines[i], " "); int pdg = int(fluxvals[0]); double pctg = double(fluxvals[1]) / 100.0; double Elow = double(fluxvals[2]) / 1000.0; double Ehigh = double(fluxvals[3]) / 1000.0; - QLOG(FIT, "Adding new nuwro flux " + NUIS_LOG(FIT, "Adding new nuwro flux " << "pdg: " << pdg << " pctg: " << pctg << " Elow: " << Elow << " Ehigh: " << Ehigh); TH1D *fluxplot = new TH1D("fluxplot", "fluxplot", fluxvals.size() - 4, Elow, Ehigh); for (uint j = 4; j < fluxvals.size(); j++) { fluxplot->SetBinContent(j + 1, fluxvals[j]); } // Sort total flux plot if (!fluxlist[0]) { // Setup total flux fluxlist[0] = (TH1D *)fluxplot->Clone(); fluxlist[0]->SetNameTitle("FluxHist", "FluxHist"); // Prep empty total events eventlist[0] = (TH1D *)fluxplot->Clone(); eventlist[0]->SetNameTitle("EvtHist", "EvtHist"); eventlist[0]->Reset(); } else { // Add up each new plot fluxlist[0]->Add(fluxplot); } fluxplot->SetNameTitle(Form("nuwro_pdg%i_pct%f_Flux", pdg, pctg), Form("nuwro_pdg%i_pct%f_Flux", pdg, pctg)); TH1D *eventplot = (TH1D *)fluxplot->Clone(); eventplot->SetNameTitle(Form("nuwro_pdg%i_pct%f_Evt", pdg, pctg), Form("nuwro_pdg%i_pct%f_Evt", pdg, pctg)); eventplot->Reset(); fluxlist[pdg] = fluxplot; eventlist[pdg] = eventplot; nevtlist[pdg] = 0; intxseclist[pdg] = 0.0; allpdg.push_back(pdg); } } // Start main event loop to fill plots int nevents = nuwrotree->GetEntries(); double Enu = 0.0; double TotXSec = 0.0; // double totaleventmode = 0.0; // double totalevents = 0.0; int pdg = 0; int countwidth = nevents / 50.0; countwidth = countwidth ? countwidth : 1; for (int i = 0; i < nevents; i++) { nuwrotree->GetEntry(i); // Get Variables Enu = evt->in[0].t / 1000.0; TotXSec = evt->weight; pdg = evt->in[0].pdg; eventlist[0]->Fill(Enu); eventlist[pdg]->Fill(Enu); nevtlist[0] += 1; nevtlist[pdg] += 1; intxseclist[0] += TotXSec; intxseclist[pdg] += TotXSec; if (i % countwidth == 0) { - QLOG(FIT, "Processed " << i << " events " + NUIS_LOG(FIT, "Processed " << i << " events " << " (" << int(i * 100.0 / nevents) << "%)" << " : E, W, PDG = " << Enu << ", " << TotXSec << ", " << pdg) } } TH1D *zeroevents = (TH1D *)eventlist[0]->Clone(); outRootFile->cd(); // Loop over eventlist for (uint i = 0; i < allpdg.size(); i++) { int pdg = allpdg[i]; double AvgXSec = intxseclist[0] * 1E38 / double(nevtlist[0]); - QLOG(FIT, pdg << " Avg XSec = " << AvgXSec); - QLOG(FIT, pdg << " nevents = " << double(nevtlist[pdg])); + NUIS_LOG(FIT, pdg << " Avg XSec = " << AvgXSec); + NUIS_LOG(FIT, pdg << " nevents = " << double(nevtlist[pdg])); if (!isMono) { // Convert events to PDF eventlist[pdg]->Scale(1.0 / zeroevents->Integral("width")); // Multiply by total predicted event rate eventlist[pdg]->Scale(fluxlist[0]->Integral("width") * AvgXSec); } else { // If a mono-energetic flux was used, width should not be used // The output is (now) forced to be flux = 1, evtrt = xsec (in 1E38 * nb // cm^2) eventlist[pdg]->Scale(1.0 / zeroevents->Integral()); eventlist[pdg]->Scale(fluxlist[0]->Integral() * AvgXSec); } // Save everything fluxlist[pdg]->Write("", TObject::kOverwrite); eventlist[pdg]->Write("", TObject::kOverwrite); } // Tidy up outRootFile->Close(); fluxlist.clear(); eventlist.clear(); // Exit Program return; } //******************************* void HaddNuwroFiles(std::vector &inputs, bool force_out) { //******************************* // Get output file name std::string outputname = inputs[0]; // Make command line string std::string cmd = "hadd "; if (outputNewFile) { cmd += ofile + " "; outputname = ofile; } else if (force_out) { cmd += "-f "; } for (UInt_t i = 0; i < inputs.size(); i++) { cmd += inputs[i] + " "; } - QLOG(FIT, " Running HADD from PrepareNuwro: " << cmd); + NUIS_LOG(FIT, " Running HADD from PrepareNuwro: " << cmd); // Start HADD system(cmd.c_str()); // Return name of output file inputs.clear(); inputs.push_back(outputname); haddedFiles = true; return; } diff --git a/app/neut_NUISANCE.cxx b/app/neut_NUISANCE.cxx index b216a81..c3d0a39 100644 --- a/app/neut_NUISANCE.cxx +++ b/app/neut_NUISANCE.cxx @@ -1,911 +1,911 @@ #ifdef __NEUT_ENABLED__ #include "ComparisonRoutines.h" #include "ParserUtils.h" #include "TargetUtils.h" #ifdef WINDOWS #include #define GetCurrentDir _getcwd #else #include #define GetCurrentDir getcwd #endif // All possible inputs std::string gOptEnergyDef; std::vector gOptEnergyRange; int gOptNumberEvents = -1; int gOptNumberTestEvents = 5E6; std::string gOptGeneratorList = "Default"; std::string gOptCrossSections = "Default"; // If default this will look in // $NUISANCE/data/neut/Default_params.txt int gOptSeed = time(NULL); std::string gOptTargetDef = ""; std::string gOptFluxDef = ""; std::string gOptOutputFile = ""; int gOptRunNumber = -1; using namespace TargetUtils; void GetCommandLineArgs(int argc, char **argv); void PrintSyntax(void); std::string GETCWD() { char cCurrentPath[FILENAME_MAX]; if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath))) { - QTHROW("CANT FIND CURRENT DIRECTORY!"); + NUIS_ABORT("CANT FIND CURRENT DIRECTORY!"); } std::string curdir = std::string(cCurrentPath); return curdir; } std::string ExpandPath(std::string name) { // Get Current char cCurrentPath[FILENAME_MAX]; if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath))) { - QTHROW("CANT FIND CURRENT DIRECTORY!"); + NUIS_ABORT("CANT FIND CURRENT DIRECTORY!"); } std::string curdir = std::string(cCurrentPath); // If first entry is not / then add the current working directory if (!name.empty() and name.at(0) != '/') { name = curdir + "/" + name; } return name; } std::string GetBaseName(std::string name) { std::vector splitfile = GeneralUtils::ParseToStr(name, "/"); std::string filename = ""; if (splitfile.size() == 1) { filename = splitfile[0]; } else if (splitfile.size() > 1) { filename = splitfile[splitfile.size() - 1]; } else { - QTHROW("Cannot split filename: " << name); + NUIS_ABORT("Cannot split filename: " << name); } return filename; } std::string GetDynamicModes(std::string list, bool neutrino) { - QLOG(FIT, "Using " << list << " to define interaction modes for Neutrino=" + NUIS_LOG(FIT, "Using " << list << " to define interaction modes for Neutrino=" << neutrino); std::map modes; std::vector ids; // Create vector of ids for the print out and future reference /* C C nu nub C 1: CC Q.E. CC Q.E.( Free ) C 2-4: CC 1pi CC 1pi C 5: CC DIS 1320 CC DIS 1.3 < W < 2.0 C 6-9: NC 1pi NC 1pi C 10: NC DIS 1320 NC DIS 1.3 < W < 2.0 C 11: NC els CC Q.E.( Bound ) C 12: NC els NC els C 13: NC els NC els C 14: coherent NC els C 15: coherent coherent C 16: CC eta coherent C 17 NC eta CC eta C 18: NC eta NC eta C 19: CC K NC eta C 20 NC K CC K C 21: NC K NC K C 22: N/A NC K C 23: CC DIS CC DIS (W > 2.0) C 24: NC DIS NC DIS (W > 2.0) C 25: CC 1 gamma CC 1 gamma C 26: NC 1 gamma NC 1 gamma C 27: NC 1 gamma NC 1 gamma C 28: 2p2h 2p2h */ ids.push_back("crsmode_CCQE"); ids.push_back("crsmode_CC2P2H"); ids.push_back("crsmode_CC1pi"); ids.push_back("crsmode_CCDIS_lowW"); ids.push_back("crsmode_NC1pi"); ids.push_back("crsmode_NCDIS_lowW"); ids.push_back("crsmode_NCEL"); ids.push_back("crsmode_CCCOH"); ids.push_back("crsmode_NCCOH"); ids.push_back("crsmode_CCETA"); ids.push_back("crsmode_NCETA"); ids.push_back("crsmode_CCKAON"); ids.push_back("crsmode_NCKAON"); ids.push_back("crsmode_CCDIS_highW"); ids.push_back("crsmode_NCDIS_highW"); ids.push_back("crsmode_CCGAMMA"); ids.push_back("crsmode_NCGAMMA"); // Now define possible models if (!list.compare("Default")) { // Everything but MEC modes["crsmode_CCQE"] = 1; modes["crsmode_CC2P2H"] = 0; modes["crsmode_CC1pi"] = 1; modes["crsmode_CCDIS_lowW"] = 1; modes["crsmode_CCCOH"] = 1; modes["crsmode_CCETA"] = 1; modes["crsmode_CCKAON"] = 1; modes["crsmode_CCDIS_highW"] = 1; modes["crsmode_CCGAMMA"] = 1; modes["crsmode_NC1pi"] = 1; modes["crsmode_NCDIS_lowW"] = 1; modes["crsmode_NCEL"] = 1; modes["crsmode_NCCOH"] = 1; modes["crsmode_NCETA"] = 1; modes["crsmode_NCKAON"] = 1; modes["crsmode_NCDIS_highW"] = 1; modes["crsmode_NCGAMMA"] = 1; } else if (!list.compare("DefaultFree")) { modes["crsmode_CCQE"] = 1; modes["crsmode_CC2P2H"] = 0; modes["crsmode_CC1pi"] = 1; modes["crsmode_CCDIS_lowW"] = 1; modes["crsmode_CCCOH"] = 0; modes["crsmode_CCETA"] = 1; modes["crsmode_CCKAON"] = 1; modes["crsmode_CCDIS_highW"] = 1; modes["crsmode_CCGAMMA"] = 1; modes["crsmode_NC1pi"] = 1; modes["crsmode_NCDIS_lowW"] = 1; modes["crsmode_NCEL"] = 1; modes["crsmode_NCCOH"] = 0; modes["crsmode_NCETA"] = 1; modes["crsmode_NCKAON"] = 1; modes["crsmode_NCDIS_highW"] = 1; modes["crsmode_NCGAMMA"] = 1; } else if (!list.compare("Default+MEC")) { modes["crsmode_CCQE"] = 1; modes["crsmode_CC2P2H"] = 1; modes["crsmode_CC1pi"] = 1; modes["crsmode_CCDIS_lowW"] = 1; modes["crsmode_CCCOH"] = 1; modes["crsmode_CCETA"] = 1; modes["crsmode_CCKAON"] = 1; modes["crsmode_CCDIS_highW"] = 1; modes["crsmode_CCGAMMA"] = 1; modes["crsmode_NC1pi"] = 1; modes["crsmode_NCDIS_lowW"] = 1; modes["crsmode_NCEL"] = 1; modes["crsmode_NCCOH"] = 1; modes["crsmode_NCETA"] = 1; modes["crsmode_NCKAON"] = 1; modes["crsmode_NCDIS_highW"] = 1; modes["crsmode_NCGAMMA"] = 1; } else { - QTHROW("Event generator list " << list << " not found!"); + NUIS_ABORT("Event generator list " << list << " not found!"); } // Now we actually have to make the conversion because NEUTS modes // organisation are a mess. /* C C nu nub C 1: CC Q.E. CC Q.E.( Free ) C 2-4: CC 1pi CC 1pi C 5: CC DIS 1320 CC DIS 1.3 < W < 2.0 C 6-9: NC 1pi NC 1pi C 10: NC DIS 1320 NC DIS 1.3 < W < 2.0 C 11: NC els CC Q.E.( Bound ) C 12: NC els NC els C 13: NC els NC els C 14: coherent NC els C 15: coherent coherent C 16: CC eta coherent C 17 NC eta CC eta C 18: NC eta NC eta C 19: CC K NC eta C 20 NC K CC K C 21: NC K NC K C 22: N/A NC K C 23: CC DIS CC DIS (W > 2.0) C 24: NC DIS NC DIS (W > 2.0) C 25: CC 1 gamma CC 1 gamma C 26,27: NC 1 gamma NC 1 gamma */ std::string modestring_neutrino = "NEUT-CRS "; std::string modestring_antineutrino = "NEUT-CRSB "; // Neutrino First if (neutrino) { // Fill empty NEUT-CRSB for (size_t i = 0; i < 27; i++) { modestring_antineutrino += " 0"; } modestring_neutrino += (modes["crsmode_CCQE"] ? " 1" : " 0"); modestring_neutrino += (modes["crsmode_CC1pi"] ? " 1 1 1" : " 0 0 0"); modestring_neutrino += (modes["crsmode_CCDIS_lowW"] ? " 1" : " 0"); modestring_neutrino += (modes["crsmode_NC1pi"] ? " 1 1 1 1" : " 0 0 0 0"); modestring_neutrino += (modes["crsmode_NCDIS_lowW"] ? " 1" : " 0"); modestring_neutrino += (modes["crsmode_NCEL"] ? " 1 1 1" : " 0 0 0"); modestring_neutrino += (modes["crsmode_CCCOH"] ? " 1" : " 0"); modestring_neutrino += (modes["crsmode_NCCOH"] ? " 1" : " 0"); modestring_neutrino += (modes["crsmode_CCETA"] ? " 1" : " 0"); modestring_neutrino += (modes["crsmode_NCETA"] ? " 1 1" : " 0 0"); modestring_neutrino += (modes["crsmode_CCKAON"] ? " 1" : " 0"); modestring_neutrino += (modes["crsmode_NCKAON"] ? " 1 1" : " 0 0"); modestring_neutrino += " 1"; // /NA modestring_neutrino += (modes["crsmode_CCDIS_highW"] ? " 1" : " 0"); modestring_neutrino += (modes["crsmode_NCDIS_highW"] ? " 1" : " 0"); modestring_neutrino += (modes["crsmode_CCGAMMA"] ? " 1" : " 0"); modestring_neutrino += (modes["crsmode_NCGAMMA"] ? " 1" : " 0"); modestring_neutrino += (modes["crsmode_CC2P2H"] ? " 1" : " 0"); } else { // Fill Empty NEUT CRS for (size_t i = 0; i < 27; i++) { modestring_neutrino += " 0"; } modestring_antineutrino += (modes["crsmode_CCQE"] ? " 1" : " 0"); modestring_antineutrino += (modes["crsmode_CC1pi"] ? " 1 1 1" : " 0 0 0"); modestring_antineutrino += (modes["crsmode_CCDIS_lowW"] ? " 1" : " 0"); modestring_antineutrino += (modes["crsmode_NC1pi"] ? " 1 1 1 1" : " 0 0 0 0"); modestring_antineutrino += (modes["crsmode_NCDIS_lowW"] ? " 1" : " 0"); modestring_antineutrino += (modes["crsmode_CCQE"] ? " 1" : " 0"); modestring_antineutrino += (modes["crsmode_NCEL"] ? " 1 1 1" : " 0 0 0"); modestring_antineutrino += (modes["crsmode_CCCOH"] ? " 1" : " 0"); modestring_antineutrino += (modes["crsmode_NCCOH"] ? " 1" : " 0"); modestring_antineutrino += (modes["crsmode_CCETA"] ? " 1" : " 0"); modestring_antineutrino += (modes["crsmode_NCETA"] ? " 1 1" : " 0 0"); modestring_antineutrino += (modes["crsmode_CCKAON"] ? " 1" : " 0"); modestring_antineutrino += (modes["crsmode_NCKAON"] ? " 1 1" : " 0 0"); modestring_antineutrino += (modes["crsmode_CCDIS_highW"] ? " 1" : " 0"); modestring_antineutrino += (modes["crsmode_NCDIS_highW"] ? " 1" : " 0"); modestring_antineutrino += (modes["crsmode_CCGAMMA"] ? " 1" : " 0"); modestring_antineutrino += (modes["crsmode_NCGAMMA"] ? " 1" : " 0"); modestring_antineutrino += (modes["crsmode_CC2P2H"] ? " 1" : " 0"); } return "NEUT-MODE -1 \n" + modestring_neutrino + "\n" + modestring_antineutrino; } std::map MakeNewFluxFile(std::string flux, std::string out) { - QLOG(FIT, "Using " << flux << " to define NEUT beam."); + NUIS_LOG(FIT, "Using " << flux << " to define NEUT beam."); std::vector fluxargs = GeneralUtils::ParseToStr(flux, ","); if (fluxargs.size() < 2) { - QTHROW("Expected flux in the format: file.root,hist_name1[pdg1],... : " + NUIS_ABORT("Expected flux in the format: file.root,hist_name1[pdg1],... : " "reveived : " << flux); } // Build Map std::map fluxmap; fluxmap["beam_type"] = "6"; fluxmap["beam_inputroot"] = fluxargs[0]; fluxmap["beam_inputroot_nue"] = ""; fluxmap["beam_inputroot_nueb"] = ""; fluxmap["beam_inputroot_numu"] = ""; fluxmap["beam_inputroot_numub"] = ""; fluxmap["beam_inputroot_nutau"] = ""; fluxmap["beam_inputroot_nutaub"] = ""; // Split by beam bdgs for (uint i = 1; i < fluxargs.size(); i++) { std::string histdef = fluxargs[i]; string::size_type open_bracket = histdef.find("["); string::size_type close_bracket = histdef.find("]"); string::size_type ibeg = 0; string::size_type iend = open_bracket; string::size_type jbeg = open_bracket + 1; string::size_type jend = close_bracket - 1; std::string name = std::string(histdef.substr(ibeg, iend).c_str()); int pdg = atoi(histdef.substr(jbeg, jend).c_str()); if (pdg == 12) fluxmap["beam_inputroot_nue"] = name; else if (pdg == -12) fluxmap["beam_inputroot_nueb"] = name; else if (pdg == 14) fluxmap["beam_inputroot_numu"] = name; else if (pdg == -14) fluxmap["beam_inputroot_numub"] = name; else if (pdg == 16) fluxmap["beam_inputroot_tau"] = name; else if (pdg == -16) fluxmap["beam_inputroot_taub"] = name; } // Now create a new flux file matching the output file std::cout << " -> Moving flux from '" + fluxmap["beam_inputroot"] + "' to current directory to keep everything organised." << std::endl; TFile *fluxread = new TFile(fluxmap["beam_inputroot"].c_str(), "READ"); TFile *fluxwrite = new TFile((out + ".flux.root").c_str(), "RECREATE"); for (std::map::iterator iter = fluxmap.begin(); iter != fluxmap.end(); iter++) { TH1 *temp = (TH1 *)fluxread->Get(iter->second.c_str()); if (!temp) continue; TH1D *cuthist = (TH1D *)temp->Clone(); // Restrict energy range if required if (gOptEnergyRange.size() == 2) { for (int i = 0; i < cuthist->GetNbinsX(); i++) { if (cuthist->GetXaxis()->GetBinCenter(i + 1) < gOptEnergyRange[0] or cuthist->GetXaxis()->GetBinCenter(i + 1) > gOptEnergyRange[1]) { cuthist->SetBinContent(i + 1, 0.0); } } } // Check Flux if (cuthist->Integral() <= 0.0) { - QTHROW("Flux histogram " << iter->second << " has integral <= 0.0"); + NUIS_ABORT("Flux histogram " << iter->second << " has integral <= 0.0"); } // Save fluxwrite->cd(); cuthist->Write(); } std::cout << " ->-> Saved to : " << (out + ".flux.root") << std::endl; fluxmap["beam_inputroot"] = (out + ".flux.root"); fluxwrite->Close(); return fluxmap; } std::string GetFluxDefinition(std::string fluxfile, std::string fluxhist, std::string fluxid) { // Get base name of flux file as its being copied to NEUT Run Directory std::vector splitfluxfile = GeneralUtils::ParseToStr(fluxfile, "/"); std::string filename = ""; if (splitfluxfile.size() == 1) { filename = splitfluxfile[0]; } else if (splitfluxfile.size() > 1) { filename = splitfluxfile[splitfluxfile.size() - 1]; } else { - QTHROW("NO FILENAME FOR FLUX DEFINITION FOUND!"); + NUIS_ABORT("NO FILENAME FOR FLUX DEFINITION FOUND!"); } // Build string std::string fluxparams = ""; fluxparams += "EVCT-FILENM \'" + filename + "\' \n"; fluxparams += "EVCT-HISTNM \'" + fluxhist + "\' \n"; fluxparams += "EVCT-INMEV 0 \n"; fluxparams += "EVCT-MPV 3 \n"; // Set PDG Code if (!fluxid.compare("nue")) fluxparams += "EVCT-IDPT 12"; else if (!fluxid.compare("nueb")) fluxparams += "EVCT-IDPT -12"; else if (!fluxid.compare("numu")) fluxparams += "EVCT-IDPT 14"; else if (!fluxid.compare("numub")) fluxparams += "EVCT-IDPT -14"; else if (!fluxid.compare("nutau")) fluxparams += "EVCT-IDPT 16"; else if (!fluxid.compare("nutaub")) fluxparams += "EVCT-IDPT -16"; else { - QTHROW("UNKNOWN FLUX ID GIVEN!"); + NUIS_ABORT("UNKNOWN FLUX ID GIVEN!"); } return fluxparams; } std::string GetTargetDefinition(std::string target) { - QLOG(FIT, "Defining NEUT Target from : " << target); + NUIS_LOG(FIT, "Defining NEUT Target from : " << target); // Target is given as either a single PDG, or a combo with the total number of // nucleons std::vector trgts = GeneralUtils::ParseToStr(target, ","); std::string targetstring = ""; // NEUT only lets us pass C and CH type inputs. // Single Target if (trgts.size() == 1) { int PDG = GeneralUtils::StrToInt(trgts[0]); int Z = TargetUtils::GetTargetZFromPDG(PDG); int N = TargetUtils::GetTargetAFromPDG(PDG) - Z; targetstring += "NEUT-NUMBNDP " + GeneralUtils::IntToStr(Z) + "\n"; targetstring += "NEUT-NUMBNDN " + GeneralUtils::IntToStr(N) + "\n"; targetstring += "NEUT-NUMFREP 0\n"; targetstring += "NEUT-NUMATOM " + GeneralUtils::IntToStr(Z + N) + "\n"; // Combined target } else if (trgts.size() == 3) { int NUCLEONS = GeneralUtils::StrToInt(trgts[0]); std::string target1 = trgts[1]; std::string target2 = trgts[2]; // Parse target strings string::size_type open_bracket = target1.find("["); string::size_type close_bracket = target1.find("]"); string::size_type ibeg = 0; string::size_type iend = open_bracket; string::size_type jbeg = open_bracket + 1; string::size_type jend = close_bracket - 1; int PDG1 = atoi(target1.substr(ibeg, iend).c_str()); double W1 = atof(target1.substr(jbeg, jend).c_str()); open_bracket = target2.find("["); close_bracket = target2.find("]"); ibeg = 0; iend = open_bracket; jbeg = open_bracket + 1; jend = close_bracket - 1; int PDG2 = atoi(target2.substr(ibeg, iend).c_str()); double W2 = atof(target2.substr(jbeg, jend).c_str()); // Can only have H as a secondary target! if (PDG1 != 1000010010 && PDG2 != 1000010010) { - QTHROW( + NUIS_ABORT( "NEUT Doesn't support composite targets apart fromn Target+H. E.g. " "CH"); } // Switch so H is PDG2 if given if (PDG1 == 1000010010 && PDG2 != 1000010010) { PDG1 = PDG2; PDG2 = 1000010010; double temp1 = W1; W1 = W2; W2 = temp1; } // Now build string int Z = TargetUtils::GetTargetZFromPDG(PDG1); int N = TargetUtils::GetTargetAFromPDG(PDG1) - Z; int NHydrogen = int(W2 * double(NUCLEONS)); if (double(W2 * double(NUCLEONS)) - (double(NHydrogen)) > 0.5) { NHydrogen++; // awkward rounding bug fix } targetstring += "NEUT-NUMBNDP " + GeneralUtils::IntToStr(Z) + "\n"; targetstring += "NEUT-NUMBNDN " + GeneralUtils::IntToStr(N) + "\n"; targetstring += "NEUT-NUMFREP " + GeneralUtils::IntToStr(NHydrogen) + "\n"; targetstring += "NEUT-NUMATOM " + GeneralUtils::IntToStr(Z + N) + "\n"; } else { - QTHROW("NEUT only supports single targets or ones with a secondary H!"); + NUIS_ABORT("NEUT only supports single targets or ones with a secondary H!"); } return targetstring; } std::string GetEventAndSeedDefinition(int nevents, int seed) { std::string eventdef = ""; eventdef += "EVCT-NEVT " + GeneralUtils::IntToStr(nevents) + "\n"; - QLOG(FIT, "Event Definition: "); + NUIS_LOG(FIT, "Event Definition: "); std::cout << " -> EVCT-NEVT : " << nevents << std::endl; return eventdef; } //____________________________________________________________________________ int main(int argc, char **argv) { - QLOG(FIT, "==== RUNNING neut_nuisance Event Generator ====="); + NUIS_LOG(FIT, "==== RUNNING neut_nuisance Event Generator ====="); GetCommandLineArgs(argc, argv); std::string neutroot = std::string(getenv("NEUT_ROOT")) + "/src/neutsmpl/"; // Calculate the dynamic modes definition // Read Target string std::string targetparamsdef = GetTargetDefinition(gOptTargetDef); //____________________________ // NEUT doesn't let us do combined flux inputs so have to loop over each flux. std::map newfluxdef = MakeNewFluxFile(gOptFluxDef, gOptOutputFile); // Quick fix to make flux also save to pid_time.root.flux.root std::stringstream ss; ss << getpid() << "_" << time(NULL) << ".root"; newfluxdef = MakeNewFluxFile(gOptFluxDef, ss.str()); // Copy this file to the NEUT working directory - QLOG(FIT, "Copying flux to NEUT working directory"); + NUIS_LOG(FIT, "Copying flux to NEUT working directory"); system( ("cp -v " + newfluxdef["beam_inputroot"] + " " + neutroot + "/").c_str()); TFile *fluxrootfile = new TFile(newfluxdef["beam_inputroot"].c_str(), "READ"); // Setup possible beams and get relative fractions std::vector possiblefluxids; std::vector fluxfractions; possiblefluxids.push_back("nue"); possiblefluxids.push_back("nueb"); possiblefluxids.push_back("numu"); possiblefluxids.push_back("numub"); possiblefluxids.push_back("tau"); possiblefluxids.push_back("taub"); // Total up integrals double totintflux = 0.0; for (size_t i = 0; i < possiblefluxids.size(); i++) { if (newfluxdef["beam_inputroot_" + possiblefluxids[i]].empty()) { fluxfractions.push_back(0.0); } else { TH1D *fluxhist = (TH1D *)fluxrootfile->Get( newfluxdef["beam_inputroot_" + possiblefluxids[i]].c_str()); if (!fluxhist) { - QTHROW("FLUX HIST : " + NUIS_ABORT("FLUX HIST : " << newfluxdef["beam_inputroot_" + possiblefluxids[i]] << " not found!"); } fluxfractions.push_back(fluxhist->Integral()); totintflux += fluxhist->Integral(); } } fluxrootfile->Close(); // Now loop over and actually generate jobs! for (size_t i = 0; i < possiblefluxids.size(); i++) { if (fluxfractions[i] == 0.0) continue; // Get number of events for this subbeam int nevents = int(double(gOptNumberEvents) * fluxfractions[i] / totintflux); std::cout << "NEVENTS = " << gOptNumberEvents << " " << fluxfractions[i] << " " << totintflux << " " << nevents << std::endl; std::string eventparamsdef = GetEventAndSeedDefinition(nevents, gOptSeed); bool neutrino = true; if (possiblefluxids[i].find("b") != std::string::npos) neutrino = false; std::string dynparamsdef = GetDynamicModes(gOptGeneratorList, neutrino); std::string fluxparamsdef = GetFluxDefinition( newfluxdef["beam_inputroot"], newfluxdef["beam_inputroot_" + possiblefluxids[i]], possiblefluxids[i]); - QLOG(FIT,"==== Generating CardFiles NEUT! ==="); + NUIS_LOG(FIT,"==== Generating CardFiles NEUT! ==="); std::cout << dynparamsdef << std::endl; std::cout << targetparamsdef << std::endl; std::cout << eventparamsdef << std::endl; std::cout << fluxparamsdef << std::endl; // Create card file std::ifstream incardfile; std::ofstream outcardfile; std::string line; incardfile.open(gOptCrossSections.c_str(), ios::in); outcardfile.open( (gOptOutputFile + "." + possiblefluxids[i] + ".par").c_str(), ios::out); // Copy base card file if (incardfile.is_open()) { while (getline(incardfile, line)) { outcardfile << line << '\n'; } } else { - QTHROW("Cannot find card file : " << gOptCrossSections); + NUIS_ABORT("Cannot find card file : " << gOptCrossSections); } // Now copy our strings outcardfile << eventparamsdef << '\n'; outcardfile << dynparamsdef << '\n'; outcardfile << targetparamsdef << '\n'; outcardfile << fluxparamsdef << '\n'; // Close card and keep name for future use. outcardfile.close(); } - QLOG(FIT, "GENERATING"); + NUIS_LOG(FIT, "GENERATING"); for (size_t i = 0; i < possiblefluxids.size(); i++) { if (fluxfractions[i] == 0.0) continue; int nevents = int(double(gOptNumberEvents) * fluxfractions[i] / totintflux); if (nevents <= 0) continue; std::string cardfile = ExpandPath(gOptOutputFile + "." + possiblefluxids[i] + ".par"); std::string outputfile = ExpandPath(gOptOutputFile + "." + possiblefluxids[i] + ".root"); std::string basecardfile = GetBaseName(cardfile); std::string baseoutputfile = ss.str(); std::cout << "CARDFILE = " << cardfile << " : " << basecardfile << std::endl; std::cout << "OUTPUTFILE = " << outputfile << " : " << baseoutputfile << std::endl; system(("cp " + cardfile + " " + neutroot).c_str()); std::string cwd = GETCWD(); chdir(neutroot.c_str()); // int attempts = 0; // while(true){ // Break if too many attempts // attempts++; // if (attempts > 20) continue; // Actually run neutroot2 system(("./neutroot2 " + basecardfile + " " + baseoutputfile).c_str()); // Check the output is valid, sometimes NEUT aborts mid run. // TFile* f = new TFile(baseoutputfile.c_str(),"READ"); // if (!f or f->IsZombie()) continue; // Check neutttree is there and filled correctly. // TTree* tn = (TTree*) f->Get("neuttree"); // if (!tn) continue; // if (tn->GetEntries() < nevents * 0.9) continue; // break; // } // Move the finished file back and clean this directory of card files system(("mv -v " + baseoutputfile + " " + outputfile).c_str()); system(("rm -v " + basecardfile).c_str()); chdir(cwd.c_str()); } return 0; } //____________________________________________________________________________ void GetCommandLineArgs(int argc, char **argv) { // Check for -h flag. for (int i = 0; i < argc; i++) { if (!std::string(argv[i]).compare("-h")) PrintSyntax(); } // Format is neut -r run_number -n n events std::vector args = GeneralUtils::LoadCharToVectStr(argc, argv); ParserUtils::ParseArgument(args, "-n", gOptNumberEvents, false); if (gOptNumberEvents == -1) { - QTHROW("No event count passed to neut_NUISANCE!"); + NUIS_ABORT("No event count passed to neut_NUISANCE!"); } // Flux/Energy Specs ParserUtils::ParseArgument(args, "-e", gOptEnergyDef, false); gOptEnergyRange = GeneralUtils::ParseToDbl(gOptEnergyDef, ","); ParserUtils::ParseArgument(args, "-f", gOptFluxDef, false); if (gOptFluxDef.empty() and gOptEnergyRange.size() < 1) { - QTHROW("No flux or energy range given to neut_nuisance!"); + NUIS_ABORT("No flux or energy range given to neut_nuisance!"); } else if (gOptFluxDef.empty() and gOptEnergyRange.size() == 1) { // Fixed energy, make sure -p is given - QTHROW("neut_NUISANCE cannot yet do fixed energy!"); + NUIS_ABORT("neut_NUISANCE cannot yet do fixed energy!"); } else if (gOptFluxDef.empty() and gOptEnergyRange.size() == 2) { // Uniform energy range - QTHROW("neut_NUISANCE cannot yet do a uniform energy range!"); + NUIS_ABORT("neut_NUISANCE cannot yet do a uniform energy range!"); } else if (!gOptFluxDef.empty()) { // Try to convert the flux definition if possible. std::string convflux = BeamUtils::ConvertFluxIDs(gOptFluxDef); if (!convflux.empty()) gOptFluxDef = convflux; } else { - QTHROW("Unknown flux energy range combination!"); + NUIS_ABORT("Unknown flux energy range combination!"); } ParserUtils::ParseArgument(args, "-t", gOptTargetDef, false); if (gOptTargetDef.empty()) { - QTHROW("No Target passed to neut_nuisance! use the '-t' argument."); + NUIS_ABORT("No Target passed to neut_nuisance! use the '-t' argument."); } else { std::string convtarget = TargetUtils::ConvertTargetIDs(gOptTargetDef); if (!convtarget.empty()) gOptTargetDef = convtarget; } ParserUtils::ParseArgument(args, "-r", gOptRunNumber, false); ParserUtils::ParseArgument(args, "-o", gOptOutputFile, false); if (gOptOutputFile.empty()) { if (gOptRunNumber == -1) gOptRunNumber = 1; - QLOG(FIT, "No output file given! Saving file to : neutgen." + NUIS_LOG(FIT, "No output file given! Saving file to : neutgen." << gOptRunNumber << ".neutvect.root"); gOptOutputFile = "neutgen." + GeneralUtils::IntToStr(gOptRunNumber) + ".neutvect.root"; } else { // if no run number given leave as is, else add run number. if (gOptRunNumber != -1) { gOptOutputFile += "." + GeneralUtils::IntToStr(gOptRunNumber) + ".root"; } else { gOptRunNumber = 0; } } ParserUtils::ParseArgument(args, "--cross-section", gOptCrossSections, false); if (!gOptCrossSections.compare("Default")) { - QLOG(FIT, "No Parameters File passed. Using default neut one."); + NUIS_LOG(FIT, "No Parameters File passed. Using default neut one."); char *const var = getenv("NUISANCE"); if (!var) { std::cout << "Cannot find top level directory! Set the NUISANCE " "environmental variable" << std::endl; exit(-1); } std::string topnuisancedir = string(var); gOptCrossSections = topnuisancedir + "/neut/Default_params.txt"; } ParserUtils::ParseArgument(args, "--event-generator-list", gOptGeneratorList, false); // Final Check and output if (args.size() > 0) { PrintSyntax(); ParserUtils::CheckBadArguments(args); } - QLOG(FIT, "Generating Neut Events with the following properties:" + NUIS_LOG(FIT, "Generating Neut Events with the following properties:" << std::endl << " -> Energy : " << gOptEnergyDef << " (" << gOptEnergyRange.size() << ")" << std::endl << " -> NEvents : " << gOptNumberEvents << std::endl << " -> Generators : " << gOptGeneratorList << std::endl << " -> XSecPars : " << gOptCrossSections << std::endl << " -> Target : " << gOptTargetDef << std::endl << " -> Flux : " << gOptFluxDef << std::endl << " -> Output : " << gOptOutputFile << std::endl << " -> Run : " << gOptRunNumber); return; } //____________________________________________________________________________ void PrintSyntax(void) { - QLOG(FIT, "\n\n" + NUIS_LOG(FIT, "\n\n" << "Syntax:" << "\n" << "\n neut_nuisance [-h]" << "\n -n nev" << "\n -f flux_description" << "\n -t target_description" << "\n [ -r run_number ]" << "\n [ -o output_file ]" << "\n [ --cross-section /path/to/params.txt ]" << "\n [ --event-generator-list mode_definition ]" << "\n \n"); - QLOG( + NUIS_LOG( FIT, "\n\n Arguments:" << "\n" << "\n -n nev" << "\n -> Total number of events to generate (e.g. 2500000)" << "\n" << "\n -f flux_description" << "\n Definition of the flux to be read in from a ROOT file." << "\n" << "\n Multiple histograms can be read in from the same file using" << "\n the format '-f file.root,hist1[pdg1],hist2[pdg2]" << "\n e.g. \'-f " "./flux/myfluxfile.root,numu_flux[14],numubar_flux[-14]\'" << "\n" << "\n A flux can also be given according to any of the flux IDs " "shown" << "\n at the end of this help message." << "\n e.g. \' -f MINERvA_fhc_numu\' " << "\n" << "\n WARNING: NEUT can't actually generate combined fluxes yet" << "\n if you want a composite flux, pass them in as normal, but " "the " "app" << "\n will generate you the files seperately, with reduced " "nevents " "in each" << "\n so that the statistics are roughly okay." << "\n" << "\n -t target_description" << "\n Definition of the target to be used. Multiple targets can " "be " "given." << "\n" << "\n To pass a single target just provide the target PDG" << "\n e.g. \' -t 1000060120 \'" << "\n" << "\n To pass a combined target provide a list containing the " "following" << "\n \' -t TotalNucleons,Target1[Weight1],Target2[Weight2],.. " "where " "the " << "\n TotalNucleons is the total nucleons combined, Target1 is " "the " "PDG " << "\n of the first target, and Weight1 is the fractional weight " "of " "the " << "\n first target." << "\n e.g. \' -t 13,1000060120[0.9231],1000010010[0.0769] \'" << "\n" << "\n Target can also be specified by the target IDs given at " "the " "end of" << "\n this help message." << "\n e.g. \' -t CH2 \'" << "\n" << "\n WARNING: NEUT can only generate A+H targets. E.g. CH or " "CH2 " "will work, but " << "\n Fe+Pb will not. You will have to generate each seperately " "if " "you want" << "\n something other than A+NH." << "\n" << "\n -r run_number" << "\n run number ID that can be used when generating large " "samples " "in small " << "\n jobs. Must be an integer. When given neut_nuisance will " "update " "the " << "\n output file from 'output.root' to " "'output.root.run_number.root'" << "\n" << "\n -o output_file" << "\n Path to the output_file you want to save events to." << "\n" << "\n If this is not given but '-r' is then events will be saved " "to " << "\n the file 'neutgen.run_number.neutvect.root'" << "\n" << "\n If a run number is given alongside '-o' then events will " "be " "saved " << "\n to 'output.root.run_number.root'" << "\n" << "\n --cross-section /path/to/params.txt" << "\n Path to the neut model definition. If this is not given, " "then " "this " << "\n will default to $NUISANCE/data/neut/Default_params.txt" << "\n" << "\n Look in $NUISANCE/data/neut/Default_params.txt for " "examples " "when " << "\n writing your own card files." << "\n" << "\n --event-generator-list mode_definition" << "\n Name of modes to run. This sets the CRS and CRSB values in " "NEUT." << "\n e.g. --event-generator-list Default+MEC" << "\n" << "\n Allowed mode_definitions are given at the end of this help " "message." << "\n" << "\n\n"); std::cout << "-----------------" << std::endl; TargetUtils::ListTargetIDs(); std::cout << "-----------------" << std::endl; BeamUtils::ListFluxIDs(); std::cout << "-----------------" << std::endl; - QLOG(FIT) << "Allowed Mode Definitions:" << std::endl + NUIS_LOG(FIT) << "Allowed Mode Definitions:" << std::endl << " - Default : Default CC+NC modes, no MEC" << std::endl << " - Default+MEC : Default CC+NC modes + 2p2h MEC " << std::endl << " - DefaultFree : Default CC+NC modes, no Coherent or MEC "); std::cout << "----------------" << std::endl; exit(0); } //____________________________________________________________________________ #endif diff --git a/app/nuisbayes.cxx b/app/nuisbayes.cxx index 7a5ca21..98c9c3f 100644 --- a/app/nuisbayes.cxx +++ b/app/nuisbayes.cxx @@ -1,68 +1,68 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ // Author: Patrick Stowell 09/2016 /* Usage: ./nuissyst -c card file -o output file, where the results of the throws are stored where: */ #include "BayesianRoutines.h" //******************************* void printInputCommands(){ //******************************* exit(-1); }; //******************************* int main(int argc, char* argv[]){ //******************************* // Program status; int status = 0; // If No Arguments print commands if (argc == 1) printInputCommands(); for (int i = 1; i< argc; ++i){ // Cardfile if (!std::strcmp(argv[i], "-h")) printInputCommands(); else break; } // Read input arguments such as card file, parameter arguments, and fit routines - QLOG(FIT,"Starting nuissyst"); + NUIS_LOG(FIT,"Starting nuissyst"); // Make systematic class and run fit BayesianRoutines* min = new BayesianRoutines(argc, argv); min->Run(); // Show Final Status - QLOG(FIT,"-------------------------------------"); - QLOG(FIT,"FINISHED"); - QLOG(FIT,"-------------------------------------"); + NUIS_LOG(FIT,"-------------------------------------"); + NUIS_LOG(FIT,"FINISHED"); + NUIS_LOG(FIT,"-------------------------------------"); return status; } diff --git a/app/nuiscomp.cxx b/app/nuiscomp.cxx index d21ff6d..b04cef7 100644 --- a/app/nuiscomp.cxx +++ b/app/nuiscomp.cxx @@ -1,293 +1,293 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "ComparisonRoutines.h" //******************************* void printInputCommands() { //******************************* std::cout << "nuiscomp : NUISANCE Data Comparison App \n" << std::endl; std::cout << "# Running nuiscomp with a card file #\n" << "######################################\n" << "nuiscomp -c cardfile.xml [ -o outputfile.root ] [ -f routines ] [ " "-n maxevents ] \n" << " [ -i 'cardstructure' ] [ -d fakedata ] [ -q config=val ] [ " "+e/-e ] [ +v/-v ] \n" << "\n" << "# Running nuiscomp with structures at cmd line #\n" << "################################################\n" << "nuiscomp -i 'cardstructure' -o outputfile.root [ -c cardfile.xml [ " "-f routines ] [ -n maxevents ] \n" << " [ -d fakedata ] [ -q config=val ] [ +e/-e ] [ +v/-v ] \n" << std::endl; sleep(4); std::cout << "" << "\n" << " \n" << " -c cardfile.xml : NUISANCE format card file defining " "comparisons. \n" << " \n" << " -o outputfile.root : Output file that histograms will be " "saved in. If a card file is \n" << " given but no output file this will " "default to cardfile.xml.root \n" << " \n" << " -f routines : Comma separated list of comparison " "routines to run in order. \n" << " Allowed Routines : " " \n" << " Compare : Fixed comparison at " "nominal dial values. \n" << " \n" << " -n maxevents : Set limit on the number of event " "entries to process. \n" << " \n" << " -i \'cardstructure\' : Define card structure like those " "available in the standard NUISANCE \n" << " card format, but on the command line " "at runtime. MUST be enclosed \n" << " in single quotation marks. See " "examples below for usage. \n" << " \n" << " It is possible to entirely define " "the comparison using \' -i\' commands \n" << " without the need to write a card " "file explicitly. If you do this, \n" << " make sure to also use the \' -o\' " "flag to tell it where to go. \n" << " \n" << " -d fakedata : Define a fake data set to be used. " "All data in NUISANCE will be set \n" << " to the values defined in this fake " "data before comparisons are made. \n" << " \n" << " There are two possible methods. Fake " "data from MC or a previous file.\n" << " fakedata = \'MC\' : Sets the MC to " "the values defined by \'fake_parameters\' \n" << " shown in the " "examples below, and then sets the data \n" << " to be equal to " "this MC prediction. \n" << " fakedata = \'file.root\' : Reads in " "the ROOT file at the specified path \n" << " assuming " "its a standard NUISANCE file. Takes \n" << " MC " "predictions in this file and uses them as \n" << " fake data. " "\n" << " \n" << " -q config=val : Overrides default configurations " "provided in the cardfile and in \n" << " '$NUISANCE/parameters/config.xml\'. " "Any config parameter can be set. \n" << " Examples : \n" << " \'-q VERBOSITY=4\' \n" << " \'-q EventManager=1\' \n" << " \'-q drawOpts=DATA/MC\' \n" << " \n" << " +e/-e : Increase/Decrease the default error " "verbosity by 1. \n" << " \n" << " +v/-v : Increase/Decrease the default " "logging verbosity by 1.\n" << " \n\n" << std::endl; sleep(4); std::cout << "# nuiscomp Running Examples #" << "############################# \n" << " \n" << " 1. Generate cardfile comparisons with increased verbosity and only " "50000 events \n\n" << " nuiscomp -c cardfile.card -o mycomp.root -n 50000 +v +v \n" << " \n\n" << " 2. Generate a comparison to MiniBooNE data using simple structure, " "saving it to outfile.root \n\n" << " nuiscomp -o outfile.root -i \'sample " "MiniBooNE_CCQE_XSec_1DQ2_nu NEUT:neutevents.root\' \n" << " \n\n" << " 3. Generate a comparison to MiniBooNE data using xml structure, " "reweight MaCCQE, and save the prediction to outfile.root \n\n" << " nuiscomp -o outfile.root -i \'sample " "name=\"MiniBooNE_CCQE_XSec_1DQ2_nu\" " "input=\"NEUT:neutevents.root\"\' \\ \n" << " -i \'sample " "name=\"MiniBooNE_CC1pip_XSec_1DQ2_nu\" " "input=\"NEUT:neutevents.root\"\' \\ \n" << " -i \'parameter name=\"MaCCQE\" " "nominal=\"1.0\" type=\"neut_parameter\"\' \n " << " \n\n" << " 4. Generate a comparison, using fake data from the MC predictions " "inside the fakedata.root \n\n" << " nuiscomp -c cardfile.card -o myfakecomp.root -d fakedata.root " "\n" << " \n\n" << " 5. Generate a comparison using fake data defined on the command " "line use fake parameters \n\n" << " nuiscomp -c cardfile.card -d MC -i \'fakeparameter " "name=\"MaCCQE\" nominal=\"1.0\"\' \n " << " -i \'parameter name=\"MaCCQE\" " "nominal=\"1.0\" type=\"neut_parameter\"' " << " \n\n" << std::endl; sleep(4); std::cout << "# NUISANCE Card Format Structure Examples # \n" << "########################################### \n" << "\n" << "The NUISANCE card can be defined as a simple text file, or an " "xml file. \n" << "Examples for both with relevant structures are given below. \n" << std::endl; std::cout << "# XML Card File Example # \n" << "cardfile.xml: \n" << "" << "\n" << " \n" << " \n" << " \n" << "\n" << " \n" << " " "\n" << " \n" << " \n" << " \n" << " \n" << " \n" << "\n" << " \n" << " \n" << "\n" << "\n" << " \n" << " \n" << " \n" << " \n" << " \n" << "\n" << " \n" << "\n" << " \n" << " \n" << " \n" << " \n" << " \n" << "\n" << " \n" << "\n" << " \n\n" << std::endl; std::cout << "# Simple Card File Example # \n" << "cardfile.card: \n" << "\n" << "# CONFIG STRUCTURE \n" << "# config name val \n" << "config VERBOSITY 4 \n" << "\n" << "# Sample Structure \n" << "# ID Corresponds to names given in src/FCN/SampleList.cxx \n" << "# TYPE is the generator type (NEUT,NUWRO,GENIE,GIBUU). \n" << "# FILE is the input generator events file. \n" << "# TYPE is optional and used to define options for a class. e.g. FREE " " \n" << "# NORM is optional and sets sample normalisations. \n" << "# sample ID TYPE:FILE TYPE 1.0 \n" << "\n" << "sample MiniBooNE_CCQE_XSec_1DQ2_nu GENIE:genieevents.root \n" << "sample MiniBooNE_CC1pip_XSec_1DQ2_nu GENIE:genieevents.root SHAPE \n" << "\n" << "\n" << "# Parameter Structure \n" << "# ID is the name of the dial in each generator RW engine \n" << "# TYPE is the dial type (neut,newer,genie,niwg,t2k,custom,norm) \n" << "# VAL is the nominal value in 1-sigma variation for the comparison \n" << "# TYPE_parameter ID VAL \n" << "\n" << "neut_parameter MaCCQE 0.5 \n" << "\n" << "# Fake Parameter Structure \n" << "# Sets values for fake data defined using the ‘MC’ flag. \n" << "# ID is the dial name, it MUST be specified before hand using a " "normal parameter structure \n" << "# VAL is the value to use for the fake data \n" << "# fake_parameter ID VAL \n" << "\n" << "fake_parameter MaCCQE 1.0 \n" << "\n" << std::endl; exit(-1); }; //******************************* int main(int argc, char *argv[]) { //******************************* // Program status; int status = 0; // If No Arguments print commands if (argc == 1) printInputCommands(); for (int i = 1; i < argc; ++i) { // Cardfile if (!std::strcmp(argv[i], "-h")) printInputCommands(); else break; } // Read input arguments such as card file, parameter arguments, and fit // routines - QLOG(FIT, "Starting nuiscomp.exe"); + NUIS_LOG(FIT, "Starting nuiscomp.exe"); // Make minimizer class and run fit ComparisonRoutines *comp = new ComparisonRoutines(argc, argv); comp->Run(); delete comp; // Show Final Status - QLOG(FIT, "------------------------------------ -"); - QLOG(FIT, "Comparison Complete."); - QLOG(FIT, "------------------------------------ -"); + NUIS_LOG(FIT, "------------------------------------ -"); + NUIS_LOG(FIT, "Comparison Complete."); + NUIS_LOG(FIT, "------------------------------------ -"); return status; } diff --git a/app/nuisflat.cxx b/app/nuisflat.cxx index a15e9b5..25fa4ed 100644 --- a/app/nuisflat.cxx +++ b/app/nuisflat.cxx @@ -1,391 +1,391 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "ComparisonRoutines.h" #include "GenericFlux_Tester.h" #include "GenericFlux_Vectors.h" #include "InputUtils.h" #include "MeasurementBase.h" #include "Smearceptance_Tester.h" // Global Arguments std::string gOptInputFile = ""; std::string gOptFormat = ""; std::string gOptOutputFile = ""; std::string gOptType = "DEFAULT"; std::string gOptNumberEvents = "NULL"; std::string gOptCardInput = ""; std::string gOptOptions = ""; // Input Dial Vals std::vector fParams; ///< Vector of dial names. std::map fStateVals; ///< Map of dial states std::map fCurVals; ///< Map of dial values std::map fTypeVals; ///< Map of dial type enums. // Fake Dial Vals std::map fFakeVals; ///< Map of fake data settings. void SetupComparisonsFromXML(); void SetupRWEngine(); //******************************* void PrintSyntax() { //******************************* std::cout << "nuisflat -i input [-f format] [-o outfile] [-n nevents] [-t " "options] [-q con=val] \n"; std::cout << "\n Arguments : " << "\n\t -i input : Path to input vector of events to flatten" << "\n\t" << "\n\t This should be given in the same format a normal " "input file" << "\n\t is given to NUISANCE. {e.g. NUWRO:eventsout.root}." << "\n\t" << "\n\t -f format : FlatTree format to output. If none given " "GenericVectors used." << "\n\t\t GenericFlux : Flat event summary format." << "\n\t\t GenericVectors : Standard event summary format with " "particle vectors." << "\n\t " << "\n\t[-c crd.xml]: Input card file to override configs or set dial " "values." << "\n\t " << "\n\t[-o outfile]: Optional output file path. " << "\n\t " << "\n\t If none given, input.format.root is chosen." << "\n\t" << "\n\t[-n nevents]: Optional choice of Nevents to run over. Default is " "all." << "\n\t" << "\n\t[-t options]: Pass OPTION to the FlatTree sample. " << "\n\t Similar to type field in comparison xml configs." << "\n\t" << "\n\t[-q con=val]: Configuration overrides." << std::endl; exit(-1); }; //____________________________________________________________________________ void GetCommandLineArgs(int argc, char **argv) { // Check for -h flag. for (int i = 0; i < argc; i++) { if ((!std::string(argv[i]).compare("-h")) || (!std::string(argv[i]).compare("-?")) || (!std::string(argv[i]).compare("--help"))) PrintSyntax(); } // Format is nuwro -r run_number -n n events std::vector args = GeneralUtils::LoadCharToVectStr(argc, argv); // Parse input file ParserUtils::ParseArgument(args, "-i", gOptInputFile, false); if (gOptInputFile == "") { - QTHROW("Need to provide a valid input file to nuisflat using -i flag!"); + NUIS_ABORT("Need to provide a valid input file to nuisflat using -i flag!"); } else { - QLOG(FIT, "Reading Input File = " << gOptInputFile); + NUIS_LOG(FIT, "Reading Input File = " << gOptInputFile); } // Get Output Format ParserUtils::ParseArgument(args, "-f", gOptFormat, false); if (gOptFormat == "") { gOptFormat = "GenericVectors"; - QLOG(FIT, "Saving flattree in default format = " << gOptFormat); + NUIS_LOG(FIT, "Saving flattree in default format = " << gOptFormat); } else { - QLOG(FIT, "Saving flattree in format = " << gOptFormat); + NUIS_LOG(FIT, "Saving flattree in format = " << gOptFormat); } // Get Output File ParserUtils::ParseArgument(args, "-o", gOptOutputFile, false); if (gOptOutputFile == "") { gOptOutputFile = gOptInputFile + "." + gOptFormat + ".root"; - QLOG(FIT, "No output file given so saving nuisflat output to:" + NUIS_LOG(FIT, "No output file given so saving nuisflat output to:" << gOptOutputFile); } else { - QLOG(FIT, "Saving nuisflat output to " << gOptOutputFile); + NUIS_LOG(FIT, "Saving nuisflat output to " << gOptOutputFile); } // Get N Events and Configs nuisconfig configuration = Config::Get(); ParserUtils::ParseArgument(args, "-n", gOptNumberEvents, false); if (gOptNumberEvents.compare("NULL")) { configuration.OverrideConfig("MAXEVENTS=" + gOptNumberEvents); } std::vector configargs; ParserUtils::ParseArgument(args, "-q", configargs); for (size_t i = 0; i < configargs.size(); i++) { configuration.OverrideConfig(configargs[i]); } ParserUtils::ParseArgument(args, "-c", gOptCardInput, false); if (gOptCardInput != "") { - QLOG(FIT, "Reading cardfile: " << gOptCardInput); + NUIS_LOG(FIT, "Reading cardfile: " << gOptCardInput); configuration.LoadSettings(gOptCardInput, ""); } ParserUtils::ParseArgument(args, "-t", gOptOptions, false); if (gOptOptions != "") { - QLOG(FIT, "Read options: \"" << gOptOptions << "\'"); + NUIS_LOG(FIT, "Read options: \"" << gOptOptions << "\'"); } return; } //******************************* int main(int argc, char *argv[]) { //******************************* // Parse GetCommandLineArgs(argc, argv); // Make output file TFile *f = new TFile(gOptOutputFile.c_str(), "RECREATE"); if (f->IsZombie()) { - QTHROW("Cannot create output file!"); + NUIS_ABORT("Cannot create output file!"); } f->cd(); FitPar::Config().out = f; // Create a new measurementbase class depending on the Format MeasurementBase *flattreecreator = NULL; SetupComparisonsFromXML(); SetupRWEngine(); // SetupFCN(); // Make a new sample key for the format of interest. nuiskey samplekey = Config::CreateKey("sample"); if (!gOptFormat.compare("GenericFlux")) { samplekey.Set("name", "FlatTree"); samplekey.Set("input", gOptInputFile); samplekey.Set("type", gOptType); flattreecreator = new GenericFlux_Tester("FlatTree", gOptInputFile, FitBase::GetRW(), gOptType, ""); } else if (!gOptFormat.compare("GenericVectors")) { samplekey.Set("name", "FlatTree"); samplekey.Set("input", gOptInputFile); samplekey.Set("type", gOptType); flattreecreator = new GenericFlux_Vectors("FlatTree", gOptInputFile, FitBase::GetRW(), gOptType, ""); } else { - QERROR(FTL, "Unknown FlatTree format!"); + NUIS_ERR(FTL, "Unknown FlatTree format!"); } // Make the FlatTree reconfigure flattreecreator->Reconfigure(); f->cd(); flattreecreator->Write(); f->Close(); // Show Final Status - QLOG(FIT, "-------------------------------------"); - QLOG(FIT, "Flattree Generation Complete."); - QLOG(FIT, "-------------------------------------"); + NUIS_LOG(FIT, "-------------------------------------"); + NUIS_LOG(FIT, "Flattree Generation Complete."); + NUIS_LOG(FIT, "-------------------------------------"); return 0; } //************************************* void SetupComparisonsFromXML() { //************************************* - QLOG(FIT, "Setting up nuiscomp"); + NUIS_LOG(FIT, "Setting up nuiscomp"); // Setup Parameters ------------------------------------------ std::vector parkeys = Config::QueryKeys("parameter"); if (!parkeys.empty()) { - QLOG(FIT, "Number of parameters : " << parkeys.size()); + NUIS_LOG(FIT, "Number of parameters : " << parkeys.size()); } for (size_t i = 0; i < parkeys.size(); i++) { nuiskey key = parkeys.at(i); // Check for type,name,nom if (!key.Has("type")) { - QERROR(FTL, "No type given for parameter " << i); - QERROR(FTL, "type='PARAMETER_TYPE'"); + NUIS_ERR(FTL, "No type given for parameter " << i); + NUIS_ERR(FTL, "type='PARAMETER_TYPE'"); throw; } else if (!key.Has("name")) { - QERROR(FTL, "No name given for parameter " << i); - QERROR(FTL, "name='SAMPLE_NAME'"); + NUIS_ERR(FTL, "No name given for parameter " << i); + NUIS_ERR(FTL, "name='SAMPLE_NAME'"); throw; } else if (!key.Has("nominal")) { - QERROR(FTL, "No nominal given for parameter " << i); - QERROR(FTL, "nominal='NOMINAL_VALUE'"); + NUIS_ERR(FTL, "No nominal given for parameter " << i); + NUIS_ERR(FTL, "nominal='NOMINAL_VALUE'"); throw; } // Get Inputs std::string partype = key.GetS("type"); std::string parname = key.GetS("name"); double parnom = key.GetD("nominal"); double parlow = parnom - 1; double parhigh = parnom + 1; double parstep = 1; // override if state not given if (!key.Has("state")) { key.SetS("state", "FIX"); } std::string parstate = key.GetS("state"); // Check for incomplete limtis int limdef = ((int)key.Has("low") + (int)key.Has("high") + (int)key.Has("step")); if (limdef > 0 and limdef < 3) { - QERROR(FTL, "Incomplete limit set given for parameter : " << parname); - QERROR( + NUIS_ERR(FTL, "Incomplete limit set given for parameter : " << parname); + NUIS_ERR( FTL, "Requires: low='LOWER_LIMIT' high='UPPER_LIMIT' step='STEP_SIZE' "); throw; } // Extra limits if (key.Has("low")) { parlow = key.GetD("low"); parhigh = key.GetD("high"); parstep = key.GetD("step"); - QLOG(FIT, "Read " << partype << " : " << parname << " = " << parnom + NUIS_LOG(FIT, "Read " << partype << " : " << parname << " = " << parnom << " : " << parlow << " < p < " << parhigh << " : " << parstate); } else { - QLOG(FIT, "Read " << partype << " : " << parname << " = " << parnom + NUIS_LOG(FIT, "Read " << partype << " : " << parname << " = " << parnom << " : " << parstate); } // Convert if required if (parstate.find("ABS") != std::string::npos) { parnom = FitBase::RWAbsToSigma(partype, parname, parnom); parlow = FitBase::RWAbsToSigma(partype, parname, parlow); parhigh = FitBase::RWAbsToSigma(partype, parname, parhigh); parstep = FitBase::RWAbsToSigma(partype, parname, parstep); } else if (parstate.find("FRAC") != std::string::npos) { parnom = FitBase::RWFracToSigma(partype, parname, parnom); parlow = FitBase::RWFracToSigma(partype, parname, parlow); parhigh = FitBase::RWFracToSigma(partype, parname, parhigh); parstep = FitBase::RWFracToSigma(partype, parname, parstep); } // Push into vectors fParams.push_back(parname); fTypeVals[parname] = FitBase::ConvDialType(partype); ; fCurVals[parname] = parnom; fStateVals[parname] = parstate; } // Setup Samples ---------------------------------------------- std::vector samplekeys = Config::QueryKeys("sample"); if (!samplekeys.empty()) { - QLOG(FIT,"Number of samples : " << samplekeys.size()); + NUIS_LOG(FIT,"Number of samples : " << samplekeys.size()); } for (size_t i = 0; i < samplekeys.size(); i++) { nuiskey key = samplekeys.at(i); // Get Sample Options std::string samplename = key.GetS("name"); std::string samplefile = key.GetS("input"); std::string sampletype = key.Has("type") ? key.GetS("type") : "DEFAULT"; double samplenorm = key.Has("norm") ? key.GetD("norm") : 1.0; // Print out - QLOG(FIT, "Read Sample " << i << ". : " << samplename << " (" + NUIS_LOG(FIT, "Read Sample " << i << ". : " << samplename << " (" << sampletype << ") [Norm=" << samplenorm << "]" << std::endl << " -> input='" << samplefile << "'"); // If FREE add to parameters otherwise continue if (sampletype.find("FREE") == std::string::npos) { continue; } // Form norm dial from samplename + sampletype + "_norm"; std::string normname = samplename + "_norm"; // Check normname not already present if (fTypeVals.find("normname") != fTypeVals.end()) { continue; } // Add new norm dial to list if its passed above checks fParams.push_back(normname); fTypeVals[normname] = kNORM; fStateVals[normname] = sampletype; fCurVals[normname] = samplenorm; } // Setup Fake Parameters ----------------------------- std::vector fakekeys = Config::QueryKeys("fakeparameter"); if (!fakekeys.empty()) { - QLOG(FIT,"Number of fake parameters : " << fakekeys.size()); + NUIS_LOG(FIT,"Number of fake parameters : " << fakekeys.size()); } for (size_t i = 0; i < fakekeys.size(); i++) { nuiskey key = fakekeys.at(i); // Check for type,name,nom if (!key.Has("name")) { - QERROR(FTL, "No name given for fakeparameter " << i); + NUIS_ERR(FTL, "No name given for fakeparameter " << i); throw; } else if (!key.Has("nominal")) { - QERROR(FTL, "No nominal given for fakeparameter " << i); + NUIS_ERR(FTL, "No nominal given for fakeparameter " << i); throw; } // Get Inputs std::string parname = key.GetS("name"); double parnom = key.GetD("nominal"); // Push into vectors fFakeVals[parname] = parnom; } } //************************************* void SetupRWEngine() { //************************************* - QLOG(FIT,"Setting up FitWeight Engine"); + NUIS_LOG(FIT,"Setting up FitWeight Engine"); for (UInt_t i = 0; i < fParams.size(); i++) { std::string name = fParams[i]; FitBase::GetRW()->IncludeDial(name, fTypeVals.at(name)); } for (UInt_t i = 0; i < fParams.size(); i++) { std::string name = fParams[i]; if (fCurVals.find(name) == fCurVals.end()) continue; FitBase::GetRW()->SetDialValue(name, fCurVals.at(name)); } FitBase::GetRW()->Reconfigure(); return; } diff --git a/app/nuismin.cxx b/app/nuismin.cxx index c8175ab..7b965d5 100644 --- a/app/nuismin.cxx +++ b/app/nuismin.cxx @@ -1,141 +1,141 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ // Author: Callum Wilkinson 01/2014 // Patrick Stowell 09/2015 /** Usage: ./GSLminimizerWithReWeight.exe -c card file, where samples and parameters are defined -o output file, where the results of the fit are stored where: */ #include "MinimizerRoutines.h" //******************************* void printInputCommands() { //******************************* std::cout << "ExtFit_minimizer.exe -c cardFile -o outFile [-f fitStategy] [-d " "fakeDataFile] [-i inputFile] [-q config_name=config_val] \n"; std::cout << std::endl; std::cout << "Arguments:" << std::endl; std::cout << " -c cardFile: Path to card file that defines fit " "samples, free parameters, and config overrides \n"; std::cout << " -o outFile: Path to root file that will be created to " "save output file.\n"; std::cout << " To turn automatically overwrite outFile if " "one exists turn off use 'config overwrite_output 1'\n"; std::cout << " To automatically use previous outFile as " "an inputFile if it exists so that the fit can be continued\n"; std::cout << " use the flag 'config use_previous_output " "1'. (A warning will be printed when doing this). \n"; std::cout << " -f fitStategy: Pass a comma seperated list of fit " "routines to run in order. Default is Migrad,FixAtLim \n"; std::cout << " Possible Options: \n"; std::cout << " 1. Migrad - Minuit2 Migrad Minimizer \n"; std::cout << " 2. Simplex - Simplex Minimizer \n"; std::cout << " 3. Scan - Brute force scan of parameter " "space \n"; std::cout << " 4. FixAtLim - Takes any free parameters " "close to a limit and fixes them \n"; std::cout << " 5. Scan1D - Make 1D Scans and save them " "in a folder \n"; std::cout << " 6. Contours - Make Contour Scans \n"; std::cout << " 7. Save - Will save the state of the " "fitter (Always done by default at the end) \n"; std::cout << " Extra option LowStatFit will perform " "each of these options with a lower number \n"; std::cout << " of fit events (config lowstat). Example: " "LowStatMigrad, LowStatScan \n"; std::cout << " -d fakeDataFile: Uses the MC generated from a previous " "fit as a fake data set for these fits \n"; std::cout << " Can also specify MC to set the fake-data " "to the Monte-Carlo prediction\n"; std::cout << " In this case, you can specify " "fake_parameter PARAM_NAME PARAM_VALUE in the card\n"; std::cout << " to reweight the MC parameter " "PARAM_NAME to some PARAM_VALUE. The minimiser will start\n"; std::cout << " at whatever neut_parameter or " "genie_parameter is set to in the cardfile.\n"; std::cout << " -i inputFile: Uses the results from a previous fit file " "as starting input for these fits \n"; std::cout << " -q config_name=config_val : Allows any config parameter " "to be overridden from the command line.\n"; std::cout << " This will take priority over " "those given in the default, or cardFile. \n"; std::cout << " example: -q verbosity=6 -q " "maxevents=10000 \n"; exit(-1); }; //******************************* int main(int argc, char *argv[]) { //******************************* // Program status; int status = 0; // If No Arguments print commands if (argc == 1) printInputCommands(); for (int i = 1; i < argc; ++i) { // Cardfile if (!std::strcmp(argv[i], "-h")) printInputCommands(); else break; } // Read input arguments such as card file, parameter arguments, and fit // routines - QLOG(FIT, "Starting ExtFit_minimizer.exe"); + NUIS_LOG(FIT, "Starting ExtFit_minimizer.exe"); // Make minimizer class and run fit MinimizerRoutines *min = new MinimizerRoutines(argc, argv); // Save Starting States if (FitPar::Config().GetParB("savenominal")) min->SaveNominal(); if (FitPar::Config().GetParB("saveprefit")) min->SavePrefit(); // Run the fit routines min->Run(); // Save by default min->SaveResults(); // Get Status status = min->GetStatus(); // Show Final Status - QLOG(FIT, "-------------------------------------"); + NUIS_LOG(FIT, "-------------------------------------"); if (status == 0) { - QLOG(FIT, "Minimizer Complete."); + NUIS_LOG(FIT, "Minimizer Complete."); } else { - QERROR(WRN, "Minimizer Failed (error state = " << status << ")"); + NUIS_ERR(WRN, "Minimizer Failed (error state = " << status << ")"); } - QLOG(FIT, "-------------------------------------"); + NUIS_LOG(FIT, "-------------------------------------"); return status; } diff --git a/app/nuissmear.cxx b/app/nuissmear.cxx index a649139..d085fbe 100644 --- a/app/nuissmear.cxx +++ b/app/nuissmear.cxx @@ -1,218 +1,218 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "ComparisonRoutines.h" #include "InputUtils.h" #include "Smearceptance_Tester.h" // Global Arguments std::string gOptInputFile = ""; std::string gOptOutputFile = ""; std::string gOptType = "DEFAULT"; std::string gOptNumberEvents = "NULL"; std::string gOptCardInput = ""; std::string gOptOptions = ""; //******************************* void PrintSyntax() { //******************************* std::cout << "nuisflat -i input [-o outfile] [-n nevents] [-t " "options] [-q con=val] \n"; std::cout << "\n Arguments : " << "\n\t -i input : Path to input vector of events to flatten" << "\n\t" << "\n\t This should be given in the same format a normal " "input file" << "\n\t is given to NUISANCE. {e.g. NUWRO:eventsout.root}." << "\n\t" << "\n\t[-c crd.xml]: Input card file to override configs or define " "smearcepters." << "\n\t " << "\n\t[-o outfile]: Optional output file path. " << "\n\t " << "\n\t If none given, input.smear.root is chosen." << "\n\t" << "\n\t[-n nevents]: Optional choice of Nevents to run over. Default is " "all." << "\n\t" << "\n\t[-t options]: Pass OPTION to the smearception sample. " << "\n\t Similar to type field in comparison xml configs." << "\n\t" << "\n\t[-q con=val]: Configuration overrides." << std::endl; exit(-1); }; //____________________________________________________________________________ void GetCommandLineArgs(int argc, char **argv) { // Check for -h flag. for (int i = 0; i < argc; i++) { if ((!std::string(argv[i]).compare("-h")) || (!std::string(argv[i]).compare("-?")) || (!std::string(argv[i]).compare("--help"))) PrintSyntax(); } // Format is nuwro -r run_number -n n events std::vector args = GeneralUtils::LoadCharToVectStr(argc, argv); // Parse input file ParserUtils::ParseArgument(args, "-i", gOptInputFile, false); if (gOptInputFile == "") { - QTHROW("Need to provide a valid input file to nuisflat using -i flag!"); + NUIS_ABORT("Need to provide a valid input file to nuisflat using -i flag!"); } else { - QLOG(FIT, "Reading Input File = " << gOptInputFile); + NUIS_LOG(FIT, "Reading Input File = " << gOptInputFile); gOptInputFile = InputUtils::PrependGuessedInputTypeToName(gOptInputFile); } // Get Output File ParserUtils::ParseArgument(args, "-o", gOptOutputFile, false); if (gOptOutputFile == "") { gOptOutputFile = gOptInputFile + ".smear.root"; - QLOG(FIT, "No output file given so saving nuisflat output to:" + NUIS_LOG(FIT, "No output file given so saving nuisflat output to:" << gOptOutputFile); } else { - QLOG(FIT, "Saving nuisflat output to " << gOptOutputFile); + NUIS_LOG(FIT, "Saving nuisflat output to " << gOptOutputFile); } // Get N Events and Configs nuisconfig configuration = Config::Get(); ParserUtils::ParseArgument(args, "-n", gOptNumberEvents, false); if (gOptNumberEvents.compare("NULL")) { configuration.OverrideConfig("MAXEVENTS=" + gOptNumberEvents); } std::vector configargs; ParserUtils::ParseArgument(args, "-q", configargs); for (size_t i = 0; i < configargs.size(); i++) { configuration.OverrideConfig(configargs[i]); } ParserUtils::ParseArgument(args, "-c", gOptCardInput, false); if (gOptCardInput != "") { - QLOG(FIT, "Reading cardfile: " << gOptCardInput); + NUIS_LOG(FIT, "Reading cardfile: " << gOptCardInput); configuration.LoadSettings(gOptCardInput, ""); } ParserUtils::ParseArgument(args, "-t", gOptOptions, false); if (gOptOptions != "") { - QLOG(FIT, "Read options: \"" << gOptOptions << "\'"); + NUIS_LOG(FIT, "Read options: \"" << gOptOptions << "\'"); } return; } void SetupRW() { std::vector parkeys = Config::QueryKeys("parameter"); if (!parkeys.empty()) { - QLOG(FIT, "Number of parameters : " << parkeys.size()); + NUIS_LOG(FIT, "Number of parameters : " << parkeys.size()); } std::vector Params; std::map TypeVals; std::map CurrVals; for (size_t i = 0; i < parkeys.size(); i++) { nuiskey key = parkeys.at(i); // Check for type,name,nom if (!key.Has("type")) { - QERROR(FTL, "No type given for parameter " << i); - QTHROW("type='PARAMETER_TYPE'"); + NUIS_ERR(FTL, "No type given for parameter " << i); + NUIS_ABORT("type='PARAMETER_TYPE'"); } else if (!key.Has("name")) { - QERROR(FTL, "No name given for parameter " << i); - QTHROW("name='SAMPLE_NAME'"); + NUIS_ERR(FTL, "No name given for parameter " << i); + NUIS_ABORT("name='SAMPLE_NAME'"); } else if (!key.Has("nominal")) { - QERROR(FTL, "No nominal given for parameter " << i); - QTHROW("nominal='NOMINAL_VALUE'"); + NUIS_ERR(FTL, "No nominal given for parameter " << i); + NUIS_ABORT("nominal='NOMINAL_VALUE'"); } // Get Inputs std::string partype = key.GetS("type"); std::string parname = key.GetS("name"); double parnom = key.GetD("nominal"); // Push into vectors Params.push_back(parname); TypeVals[parname] = FitBase::ConvDialType(partype); CurrVals[parname] = parnom; } for (UInt_t i = 0; i < Params.size(); i++) { FitBase::GetRW()->IncludeDial(Params[i], TypeVals[Params[i]]); FitBase::GetRW()->SetDialValue(Params[i], CurrVals[Params[i]]); } FitBase::GetRW()->Reconfigure(); } //******************************* int main(int argc, char *argv[]) { //******************************* // Parse GetCommandLineArgs(argc, argv); // Make output file TFile *f = new TFile(gOptOutputFile.c_str(), "RECREATE"); if (f->IsZombie()) { - QTHROW("Cannot create output file!"); + NUIS_ABORT("Cannot create output file!"); } f->cd(); Config::Get().out = f; // Create a new measurementbase class depending on the Format MeasurementBase *flattreecreator = NULL; // Make a new sample key for the format of interest. nuiskey samplekey = Config::CreateKey("sample"); samplekey.Set("name", "FlatTree"); samplekey.Set("smearceptor", gOptOptions); samplekey.Set("input", gOptInputFile); samplekey.Set("type", gOptType); if (gOptOptions == "") { - QTHROW("Attempting to flatten with Smearceptor, but no Smearceptor given. " + NUIS_ABORT("Attempting to flatten with Smearceptor, but no Smearceptor given. " "Please supply a -t option."); } if (gOptCardInput == "") { - QTHROW("Attempting to flatten with Smearceptor, but no card passed with " + NUIS_ABORT("Attempting to flatten with Smearceptor, but no card passed with " "Smearceptors configured. Please supply a -c option."); } SetupRW(); flattreecreator = new Smearceptance_Tester(samplekey); // Make the FlatTree reconfigure flattreecreator->Reconfigure(); f->cd(); flattreecreator->Write(); f->Close(); // Show Final Status - QLOG(FIT, "-------------------------------------"); - QLOG(FIT, "Flattree Generation Complete."); - QLOG(FIT, "-------------------------------------"); + NUIS_LOG(FIT, "-------------------------------------"); + NUIS_LOG(FIT, "Flattree Generation Complete."); + NUIS_LOG(FIT, "-------------------------------------"); return 0; } diff --git a/app/nuissplines.cxx b/app/nuissplines.cxx index e66685b..2ab79eb 100644 --- a/app/nuissplines.cxx +++ b/app/nuissplines.cxx @@ -1,105 +1,105 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ // Author: Callum Wilkinson 01/2014 // Patrick Stowell 09/2015 /** Usage: ./GSLminimizerWithReWeight.exe -c card file, where samples and parameters are defined -o output file, where the results of the fit are stored where: */ #include "SplineRoutines.h" //******************************* void printInputCommands(){ //******************************* /* std::cout<<"ExtFit_splines.exe -c cardFile -f [spline_routines] [-q config_name=config_val] \n"; std::cout<Run(); // Show Final Status - QLOG(FIT, "-------------------------------------"); - QLOG(FIT, "Spline Generation/Validation Finished."); - QLOG(FIT, "-------------------------------------"); + NUIS_LOG(FIT, "-------------------------------------"); + NUIS_LOG(FIT, "Spline Generation/Validation Finished."); + NUIS_LOG(FIT, "-------------------------------------"); return 0; } diff --git a/app/nuissyst.cxx b/app/nuissyst.cxx index cdc1746..5e66265 100644 --- a/app/nuissyst.cxx +++ b/app/nuissyst.cxx @@ -1,83 +1,83 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ // Author: Patrick Stowell 09/2016 /* Usage: ./nuissyst -c card file -o output file, where the results of the throws are stored where: */ #include "SystematicRoutines.h" //******************************* void printInputCommands() { //******************************* std::cout << "nuissyst.exe -c cardFile -o outFile [-f fitStategy] [-d " "fakeDataFile] [-i inputFile] [-q config_name=config_val] \n"; std::cout << std::endl; std::cout << "Arguments:" << std::endl; std::cout << " -c cardFile: Path to card file that defines fit " "samples, free parameters, and config overrides \n"; std::cout << " -o outFile: Path to root file that will be created to " "save output file.\n"; std::cout << " -f Strategy: ErrorBands (default) or PlotLimits\n" << std::endl; exit(-1); }; //******************************* int main(int argc, char *argv[]) { //******************************* // Program status; int status = 0; // If No Arguments print commands if (argc == 1) printInputCommands(); for (int i = 1; i < argc; ++i) { // Cardfile if (!std::strcmp(argv[i], "-h")) printInputCommands(); else break; } // Read input arguments such as card file, parameter arguments, and fit // routines - QLOG(FIT, "Starting nuissyst"); + NUIS_LOG(FIT, "Starting nuissyst"); // Make systematic class and run fit SystematicRoutines *min = new SystematicRoutines(argc, argv); min->Run(); // Show Final Status - QLOG(FIT, "-------------------------------------"); + NUIS_LOG(FIT, "-------------------------------------"); if (status == 0) { - QLOG(FIT, "Systematic Complete."); + NUIS_LOG(FIT, "Systematic Complete."); } else { - QERROR(FTL, "Systematic Failed (error state = " << status << ")"); + NUIS_ERR(FTL, "Systematic Failed (error state = " << status << ")"); } - QLOG(FIT, "-------------------------------------"); + NUIS_LOG(FIT, "-------------------------------------"); return status; } diff --git a/app/nuwro_NUISANCE.cxx b/app/nuwro_NUISANCE.cxx index 6d54cb4..5501730 100644 --- a/app/nuwro_NUISANCE.cxx +++ b/app/nuwro_NUISANCE.cxx @@ -1,535 +1,535 @@ #ifdef __NUWRO_ENABLED__ #include "ComparisonRoutines.h" #include "ParserUtils.h" #include "TargetUtils.h" // All possible inputs std::string gOptEnergyDef; std::vector gOptEnergyRange; int gOptNumberEvents = -1; int gOptNumberTestEvents = 5E6; std::string gOptGeneratorList = "Default"; std::string gOptCrossSections = "Default"; // If default this will look in // $NUISANCE/data/nuwro/default_params.txt int gOptSeed = time(NULL); std::string gOptTargetDef = ""; std::string gOptFluxDef = ""; std::string gOptOutputFile = ""; int gOptRunNumber = -1; void GetCommandLineArgs(int argc, char **argv); void PrintSyntax(void); std::string GetDynamicModes(std::string list) { - QLOG(FIT, "Using " << list << " to define interaction modes."); + NUIS_LOG(FIT, "Using " << list << " to define interaction modes."); std::map modes; if (!list.compare("Default")) { modes["dyn_qel_cc"] = 1; // Quasi elastic charged current modes["dyn_qel_nc"] = 1; // Quasi elastic neutral current modes["dyn_res_cc"] = 1; // Resonant charged current modes["dyn_res_nc"] = 1; // Resonant neutral current modes["dyn_dis_cc"] = 1; // Deep inelastic charged current modes["dyn_dis_nc"] = 1; // Deep inelastic neutral current modes["dyn_coh_cc"] = 1; // Coherent charged current modes["dyn_coh_nc"] = 1; // Coherent neutral current modes["dyn_mec_cc"] = 0; // Meson exchange charged current modes["dyn_mec_nc"] = 0; // Meson exchange neutral current } else if (!list.compare("DefaultFree")) { modes["dyn_qel_cc"] = 1; // Quasi elastic charged current modes["dyn_qel_nc"] = 1; // Quasi elastic neutral current modes["dyn_res_cc"] = 1; // Resonant charged current modes["dyn_res_nc"] = 1; // Resonant neutral current modes["dyn_dis_cc"] = 1; // Deep inelastic charged current modes["dyn_dis_nc"] = 1; // Deep inelastic neutral current modes["dyn_coh_cc"] = 0; // Coherent charged current modes["dyn_coh_nc"] = 0; // Coherent neutral current modes["dyn_mec_cc"] = 0; // Meson exchange charged current modes["dyn_mec_nc"] = 0; // Meson exchange neutral current } else if (!list.compare("Default+MEC")) { modes["dyn_qel_cc"] = 1; // Quasi elastic charged current modes["dyn_qel_nc"] = 1; // Quasi elastic neutral current modes["dyn_res_cc"] = 1; // Resonant charged current modes["dyn_res_nc"] = 1; // Resonant neutral current modes["dyn_dis_cc"] = 1; // Deep inelastic charged current modes["dyn_dis_nc"] = 1; // Deep inelastic neutral current modes["dyn_coh_cc"] = 1; // Coherent charged current modes["dyn_coh_nc"] = 1; // Coherent neutral current modes["dyn_mec_cc"] = 1; // Meson exchange charged current modes["dyn_mec_nc"] = 1; // Meson exchange neutral current } else { - QTHROW("Event generator list " << list << " not found!"); + NUIS_ABORT("Event generator list " << list << " not found!"); } std::string modestring = ""; for (std::map::iterator iter = modes.begin(); iter != modes.end(); iter++) { std::cout << " -> " << iter->first << " : " << iter->second << std::endl; modestring += " -p \"" + iter->first + "=" + GeneralUtils::IntToStr(iter->second) + "\""; } return modestring; } std::string GetFluxDefinition(std::string flux, std::string out) { - QLOG(FIT, "Using " << flux << " to define NuWro beam."); + NUIS_LOG(FIT, "Using " << flux << " to define NuWro beam."); // By default the flux is type 6 with a root file std::vector fluxargs = GeneralUtils::ParseToStr(flux, ","); if (fluxargs.size() < 2) { - QTHROW("Expected flux in the format: file.root,hist_name1[pdg1],... : " + NUIS_ABORT("Expected flux in the format: file.root,hist_name1[pdg1],... : " "reveived : " << flux); } // Build Map std::map fluxmap; fluxmap["beam_type"] = "6"; fluxmap["beam_inputroot"] = fluxargs[0]; fluxmap["beam_inputroot_nue"] = ""; fluxmap["beam_inputroot_nueb"] = ""; fluxmap["beam_inputroot_numu"] = ""; fluxmap["beam_inputroot_numub"] = ""; fluxmap["beam_inputroot_nutau"] = ""; fluxmap["beam_inputroot_nutaub"] = ""; // Split by beam bdgs for (int i = 1; i < fluxargs.size(); i++) { std::string histdef = fluxargs[i]; string::size_type open_bracket = histdef.find("["); string::size_type close_bracket = histdef.find("]"); string::size_type ibeg = 0; string::size_type iend = open_bracket; string::size_type jbeg = open_bracket + 1; string::size_type jend = close_bracket - 1; std::string name = std::string(histdef.substr(ibeg, iend).c_str()); int pdg = atoi(histdef.substr(jbeg, jend).c_str()); if (pdg == 12) fluxmap["beam_inputroot_nue"] = name; else if (pdg == -12) fluxmap["beam_inputroot_nueb"] = name; else if (pdg == 14) fluxmap["beam_inputroot_numu"] = name; else if (pdg == -14) fluxmap["beam_inputroot_numub"] = name; else if (pdg == 16) fluxmap["beam_inputroot_nutau"] = name; else if (pdg == -16) fluxmap["beam_inputroot_nutaub"] = name; } // Now create a new flux file matching the output file std::cout << " -> Moving flux from '" + fluxmap["beam_inputroot"] + "' to current directory to keep everything organised." << std::endl; TFile *fluxread = new TFile(fluxmap["beam_inputroot"].c_str(), "READ"); TFile *fluxwrite = new TFile((out + ".flux.root").c_str(), "RECREATE"); for (std::map::iterator iter = fluxmap.begin(); iter != fluxmap.end(); iter++) { TH1 *temp = (TH1 *)fluxread->Get(iter->second.c_str()); if (!temp) continue; TH1D *cuthist = (TH1D *)temp->Clone(); // Restrict energy range if required if (gOptEnergyRange.size() == 2) { for (int i = 0; i < cuthist->GetNbinsX(); i++) { if (cuthist->GetXaxis()->GetBinCenter(i + 1) < gOptEnergyRange[0] or cuthist->GetXaxis()->GetBinCenter(i + 1) > gOptEnergyRange[1]) { cuthist->SetBinContent(i + 1, 0.0); } } } // Check Flux if (cuthist->Integral() <= 0.0) { - QTHROW("Flux histogram " << iter->second << " has integral <= 0.0"); + NUIS_ABORT("Flux histogram " << iter->second << " has integral <= 0.0"); } // Save fluxwrite->cd(); cuthist->Write(); } std::cout << " ->-> Saved to : " << (out + ".flux.root") << std::endl; fluxmap["beam_inputroot"] = (out + ".flux.root"); fluxwrite->Close(); // Return a parameters string std::string fluxstring = ""; for (std::map::iterator iter = fluxmap.begin(); iter != fluxmap.end(); iter++) { std::cout << " -> " << iter->first << " : " << iter->second << std::endl; fluxstring += " -p \"" + iter->first + "=" + iter->second + "\""; } return fluxstring; } std::string GetTargetDefinition(std::string target) { - QLOG(FIT, "Defining NuWro Target from : " << target); + NUIS_LOG(FIT, "Defining NuWro Target from : " << target); // Target is given as either a single PDG, or a combo with the total number of // nucleons std::vector trgts = GeneralUtils::ParseToStr(target, ","); std::string targetstring = ""; // Single Target if (trgts.size() == 1) { int PDG = GeneralUtils::StrToInt(trgts[0]); int Z = TargetUtils::GetTargetZFromPDG(PDG); int N = TargetUtils::GetTargetAFromPDG(PDG) - Z; int TOTAL = 1; targetstring += (" -p \"target_content=" + GeneralUtils::IntToStr(Z) + " " + GeneralUtils::IntToStr(N) + " " + GeneralUtils::IntToStr(TOTAL) + "x" + "\""); // Combined target } else if (trgts.size() > 1) { int NUCLEONS = GeneralUtils::StrToInt(trgts[0]); // Loop over all targets for (size_t i = 1; i < trgts.size(); i++) { // Extra PDG and W std::string tgtdef = trgts[i]; string::size_type open_bracket = tgtdef.find("["); string::size_type close_bracket = tgtdef.find("]"); string::size_type ibeg = 0; string::size_type iend = open_bracket; string::size_type jbeg = open_bracket + 1; string::size_type jend = close_bracket - 1; int PDG = atoi(tgtdef.substr(ibeg, iend).c_str()); double W = atof(tgtdef.substr(jbeg, jend).c_str()); // extract Z N int Z = TargetUtils::GetTargetZFromPDG(PDG); int A = TargetUtils::GetTargetAFromPDG(PDG); int N = TargetUtils::GetTargetAFromPDG(PDG) - Z; std::cout << "Target " << PDG << " Z" << Z << " N" << N << std::endl; // extract weight int TOTAL = round(double(NUCLEONS) * W / A); if (i == 1) { targetstring += (" -p \"target_content=" + GeneralUtils::IntToStr(Z) + " " + GeneralUtils::IntToStr(N) + " " + GeneralUtils::IntToStr(TOTAL) + "x" + "\""); } else { targetstring += (" -p \"target_content+=" + GeneralUtils::IntToStr(Z) + " " + GeneralUtils::IntToStr(N) + " " + GeneralUtils::IntToStr(TOTAL) + "x" + "\""); } } // No target given! } else { - QTHROW("No target given : " << target); + NUIS_ABORT("No target given : " << target); } std::cout << " -> " << targetstring << std::endl; return targetstring; } std::string GetEventAndSeedDefinition(int nevents, int ntestevents, int seed) { std::string eventdef = ""; eventdef += " -p \"number_of_events=" + GeneralUtils::IntToStr(nevents) + "\""; eventdef += " -p \"number_of_test_events=" + GeneralUtils::IntToStr(ntestevents) + "\""; eventdef += " -p \"random_seed=" + GeneralUtils::IntToStr(seed) + "\""; - QLOG(FIT, "Event Definition: "); - QLOG(FIT, " -> number_of_events : " << nevents); - QLOG(FIT, " -> number_of_test_events : " << ntestevents); - QLOG(FIT, " -> seed : " << seed); + NUIS_LOG(FIT, "Event Definition: "); + NUIS_LOG(FIT, " -> number_of_events : " << nevents); + NUIS_LOG(FIT, " -> number_of_test_events : " << ntestevents); + NUIS_LOG(FIT, " -> seed : " << seed); return eventdef; } //____________________________________________________________________________ int main(int argc, char **argv) { - QLOG(FIT, "==== RUNNING nuwro_nuisance Event Generator ====="); + NUIS_LOG(FIT, "==== RUNNING nuwro_nuisance Event Generator ====="); GetCommandLineArgs(argc, argv); // Calculate the dynamic modes definition std::string dynparamsdef = GetDynamicModes(gOptGeneratorList); // Get Flux and Target definition std::string fluxparamsdef = GetFluxDefinition(gOptFluxDef, gOptOutputFile); std::string targetparamsdef = GetTargetDefinition(gOptTargetDef); // Get Run Definition std::string eventparamsdef = GetEventAndSeedDefinition( gOptNumberEvents, gOptNumberTestEvents, gOptSeed); // Run NuWro Externally! - QLOG(FIT, "==== Actually running nuwro! ==="); + NUIS_LOG(FIT, "==== Actually running nuwro! ==="); std::string nuwrocommand = "nuwro"; nuwrocommand += " -i " + gOptCrossSections; nuwrocommand += " -o " + gOptOutputFile; nuwrocommand += " " + fluxparamsdef; nuwrocommand += " " + dynparamsdef; nuwrocommand += " " + eventparamsdef; nuwrocommand += " " + targetparamsdef; std::cout << nuwrocommand << std::endl; sleep(10); system((nuwrocommand).c_str()); return 0; } //____________________________________________________________________________ void GetCommandLineArgs(int argc, char **argv) { // Check for -h flag. for (int i = 0; i < argc; i++) { if (!std::string(argv[i]).compare("-h")) PrintSyntax(); } // Format is nuwro -r run_number -n n events std::vector args = GeneralUtils::LoadCharToVectStr(argc, argv); ParserUtils::ParseArgument(args, "-n", gOptNumberEvents, false); if (gOptNumberEvents == -1) { - QTHROW("No event count passed to nuwro_NUISANCE!"); + NUIS_ABORT("No event count passed to nuwro_NUISANCE!"); } // Flux/Energy Specs ParserUtils::ParseArgument(args, "-e", gOptEnergyDef, false); gOptEnergyRange = GeneralUtils::ParseToDbl(gOptEnergyDef, ","); ParserUtils::ParseArgument(args, "-f", gOptFluxDef, false); if (gOptFluxDef.empty() and gOptEnergyRange.size() < 1) { - QTHROW("No flux or energy range given to nuwro_nuisance!"); + NUIS_ABORT("No flux or energy range given to nuwro_nuisance!"); } else if (gOptFluxDef.empty() and gOptEnergyRange.size() == 1) { // Fixed energy, make sure -p is given - QTHROW("nuwro_NUISANCE cannot yet do fixed energy!"); + NUIS_ABORT("nuwro_NUISANCE cannot yet do fixed energy!"); } else if (gOptFluxDef.empty() and gOptEnergyRange.size() == 2) { // Uniform energy range - QTHROW("nuwro_NUISANCE cannot yet do a uniform energy range!"); + NUIS_ABORT("nuwro_NUISANCE cannot yet do a uniform energy range!"); } else if (!gOptFluxDef.empty()) { // Try to convert the flux definition if possible. std::string convflux = BeamUtils::ConvertFluxIDs(gOptFluxDef); if (!convflux.empty()) gOptFluxDef = convflux; } else { - QTHROW("Unknown flux energy range combination!"); + NUIS_ABORT("Unknown flux energy range combination!"); } ParserUtils::ParseArgument(args, "-t", gOptTargetDef, false); if (gOptTargetDef.empty()) { - QTHROW("No Target passed to nuwro_nuisance! use the '-t' argument."); + NUIS_ABORT("No Target passed to nuwro_nuisance! use the '-t' argument."); } else { std::string convtarget = TargetUtils::ConvertTargetIDs(gOptTargetDef); if (!convtarget.empty()) gOptTargetDef = convtarget; } ParserUtils::ParseArgument(args, "-r", gOptRunNumber, false); ParserUtils::ParseArgument(args, "-o", gOptOutputFile, false); if (gOptOutputFile.empty()) { if (gOptRunNumber == -1) gOptRunNumber = 1; - QLOG(FIT, "No output file given! Saving file to : nuwrogen." + NUIS_LOG(FIT, "No output file given! Saving file to : nuwrogen." << gOptRunNumber << ".event.root"); gOptOutputFile = "nuwrogen." + GeneralUtils::IntToStr(gOptRunNumber) + ".event.root"; } else { // if no run number given leave as is, else add run number. if (gOptRunNumber != -1) { gOptOutputFile += "." + GeneralUtils::IntToStr(gOptRunNumber) + ".root"; } else { gOptRunNumber = 0; } } ParserUtils::ParseArgument(args, "--cross-section", gOptCrossSections, false); if (!gOptCrossSections.compare("Default")) { - QLOG(FIT, "No Parameters File passed. Using default NuWro one."); + NUIS_LOG(FIT, "No Parameters File passed. Using default NuWro one."); char *const var = getenv("NUISANCE"); if (!var) { std::cout << "Cannot find top level directory! Set the NUISANCE " "environmental variable" << std::endl; exit(-1); } std::string topnuisancedir = string(var); gOptCrossSections = topnuisancedir + "/nuwro/Default_params.txt"; } ParserUtils::ParseArgument(args, "--event-generator-list", gOptGeneratorList, false); ParserUtils::ParseArgument(args, "--seed", gOptSeed, false); ParserUtils::ParseArgument(args, "--test-events", gOptNumberTestEvents, false); // Final Check and output if (args.size() > 0) { PrintSyntax(); ParserUtils::CheckBadArguments(args); } - QLOG(FIT, "Generating NuWro Events with the following properties:" + NUIS_LOG(FIT, "Generating NuWro Events with the following properties:" << std::endl << " -> Energy : " << gOptEnergyDef << " (" << gOptEnergyRange.size() << ")" << std::endl << " -> NEvents : " << gOptNumberEvents << std::endl << " -> NTestEvents : " << gOptNumberTestEvents << std::endl << " -> Generators : " << gOptGeneratorList << std::endl << " -> XSecPars : " << gOptCrossSections << std::endl << " -> Seed : " << gOptSeed << std::endl << " -> Target : " << gOptTargetDef << std::endl << " -> Flux : " << gOptFluxDef << std::endl << " -> Output : " << gOptOutputFile << std::endl << " -> Run : " << gOptRunNumber); return; } //____________________________________________________________________________ void PrintSyntax(void) { - QLOG(FIT, "\n\n" + NUIS_LOG(FIT, "\n\n" << "Syntax:" << "\n" << "\n nuwro_nuisance [-h]" << "\n -n nev" << "\n -f flux_description" << "\n -t target_description" << "\n [ -r run_number ]" << "\n [ -o output_file ]" << "\n [ --cross-section /path/to/params.txt ]" << "\n [ --event-generator-list mode_definition ]" << "\n [ --seed seed_value ]" << "\n [ --test-events ntest ]" << "\n \n"); - QLOG( + NUIS_LOG( FIT, "\n\n Arguments:" << "\n" << "\n -n nev" << "\n -> Total number of events to generate (e.g. 2500000)" << "\n" << "\n -f flux_description" << "\n Definition of the flux to be read in from a ROOT file." << "\n" << "\n Multiple histograms can be read in from the same file using" << "\n the format '-f file.root,hist1[pdg1],hist2[pdg2]" << "\n e.g. \'-f " "./flux/myfluxfile.root,numu_flux[14],numubar_flux[-14]\'" << "\n" << "\n When passing in multiple histograms, the nuwro_nuisance " "will" << "\n generate a single file containing both sets of events with " "the" << "\n correct ratios for each set." << "\n" << "\n A flux can also be given according to any of the flux IDs " "shown" << "\n at the end of this help message." << "\n e.g. \' -f MINERvA_fhc_numu\' " << "\n" << "\n -t target_description" << "\n Definition of the target to be used. Multiple targets can " "be " "given." << "\n" << "\n To pass a single target just provide the target PDG" << "\n e.g. \' -t 1000060120 \'" << "\n" << "\n To pass a combined target provide a list containing the " "following" << "\n \' -t TotalNucleons,Target1[Weight1],Target2[Weight2],.. " "where " "the " << "\n TotalNucleons is the total nucleons combined, Target1 is " "the " "PDG " << "\n of the first target, and Weight1 is the fractional weight " "of " "the " << "\n first target." << "\n e.g. \' -t 13,1000060120[0.9231],1000010010[0.0769] \'" << "\n" << "\n Target can also be specified by the target IDs given at " "the " "end of" << "\n this help message." << "\n e.g. \' -t CH2 \'" << "\n" << "\n -r run_number" << "\n run number ID that can be used when generating large " "samples " "in small " << "\n jobs. Must be an integer. When given nuwro_nuisance will " "update the " << "\n output file from 'output.root' to " "'output.root.run_number.root'" << "\n" << "\n -o output_file" << "\n Path to the output_file you want to save events to." << "\n" << "\n If this is not given but '-r' is then events will be saved " "to " << "\n the file 'nuwrogen.run_number.events.root'" << "\n" << "\n If a run number is given alongside '-o' then events will " "be " "saved " << "\n to 'output.root.run_number.root'" << "\n" << "\n --cross-section /path/to/params.txt" << "\n Path to the nuwro model definition. If this is not given, " "then " "this " << "\n will default to $NUISANCE/data/nuwro/Default_params.txt" << "\n" << "\n Look in $NUISANCE/data/nuwro/Default_params.txt for " "examples " "when " << "\n writing your own card files." << "\n" << "\n --event-generator-list mode_definition" << "\n Name of modes to run. This sets the dynamic mode settings " "in " "nuwro." << "\n e.g. --event-generator-list Default+MEC" << "\n" << "\n Allowed mode_definitions are given at the end of this help " "message." << "\n" << "\n --seed seed_value " << "\n Value to use as the seed. If seed isn't given, time(NULL) " "is " "used." << "\n" << "\n --test-events ntest " << "\n Sets the number of test events for Nuwro to use. If this " "option " << "\n isn't given then we assume 5E6 test events by default." << "\n\n"); std::cout << "-----------------" << std::endl; TargetUtils::ListTargetIDs(); std::cout << "-----------------" << std::endl; BeamUtils::ListFluxIDs(); std::cout << "-----------------" << std::endl; - QLOG(FIT, "Allowed Mode Definitions:" + NUIS_LOG(FIT, "Allowed Mode Definitions:" << std::endl << " - Default : Default CC+NC modes, no MEC" << std::endl << " - Default+MEC : Default CC+NC modes + 2p2h MEC " << std::endl << " - DefaultFree : Default CC+NC modes, no Coherent or MEC " << std::endl << "----------------"); exit(0); } //____________________________________________________________________________ #endif diff --git a/cmake/pythia6Setup.cmake b/cmake/pythia6Setup.cmake index 1a89b0c..3a496e6 100644 --- a/cmake/pythia6Setup.cmake +++ b/cmake/pythia6Setup.cmake @@ -1,29 +1,36 @@ # Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret ################################################################################ # This file is part of NUISANCE. # # NUISANCE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # NUISANCE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NUISANCE. If not, see . ################################################################################ if(NEED_PYTHIA6) + + if(DEFINED ENV{PYTHIA6_LIBRARY} AND PYTHIA6 STREQUAL "") + SET(PYTHIA6 $ENV{PYTHIA6_LIBRARY} CACHE PATH + "Path to directory containing libPythia6.so. Overrides environment variable \$PYTHIA6 <>" + FORCE) + endif() + if(PYTHIA6 STREQUAL "") cmessage(FATAL_ERROR "Variable PYTHIA6 is not defined. This must be set to point to a prebuilt PYTHIA6 instance, please set the \$PYTHIA6 environment variable or configure with -DPYTHIA6=/path/to/pythia6.") endif() LIST(APPEND EXTRA_LINK_DIRS ${PYTHIA6}) LIST(APPEND EXTRA_LIBS Pythia6 gfortran) endif() diff --git a/src/ANL/ANL_CC1npip_XSec_1DEnu_nu.cxx b/src/ANL/ANL_CC1npip_XSec_1DEnu_nu.cxx index e81e3fa..070d4dc 100644 --- a/src/ANL/ANL_CC1npip_XSec_1DEnu_nu.cxx +++ b/src/ANL/ANL_CC1npip_XSec_1DEnu_nu.cxx @@ -1,142 +1,142 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ /** * Radecky et al. Phys Rev D, 3rd series, volume 25, number 5, 1 March 1982, p * 1161-1173 */ #include "ANL_CC1npip_XSec_1DEnu_nu.h" //******************************************************************** ANL_CC1npip_XSec_1DEnu_nu::ANL_CC1npip_XSec_1DEnu_nu(nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "ANL CC1npip Event Rate 1DQ2 nu sample. \n" "Target: D2 \n" "Flux: \n" "Signal: \n"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("E_{#nu} (GeV)"); fSettings.SetYTitle("#sigma (cm^{2}/nucleon)"); fSettings.SetAllowedTypes("FIX/DIAG", "FIX,FREE,SHAPE/DIAG"); fSettings.SetEnuRange(0.0, 1.5); fSettings.SetS("norm_error", "0.20"); fSettings.DefineAllowedTargets("D,H"); // plot information fSettings.SetTitle("ANL #nu_mu CC1n#pi^{+}"); fSettings.DefineAllowedSpecies("numu"); // User can specifiy to use uncorrected data UseCorrectedData = !fSettings.Found("name", "Uncorr"); // User can specify "W14" for W < 1.4 GeV cut // "W16" for W < 1.6 GeV cut // The default is W < 2.0 if (fSettings.Found("name", "W14Cut")) wTrueCut = 1.4; else if (fSettings.Found("name", "W16Cut")) wTrueCut = 1.6; else wTrueCut = 10.0; // Flag for bad combo if (UseCorrectedData && wTrueCut == 1.6) { - QERROR(WRN, "Can not run ANL CC1pi+1n W < 1.6 GeV with CORRECTION, because " + NUIS_ERR(WRN, "Can not run ANL CC1pi+1n W < 1.6 GeV with CORRECTION, because " "the data DOES NOT EXIST"); - QERROR(WRN, "Correction exists for W < 1.4 GeV and no W cut data ONLY"); - QERROR(WRN, "Reverting to using uncorrected data!"); + NUIS_ERR(WRN, "Correction exists for W < 1.4 GeV and no W cut data ONLY"); + NUIS_ERR(WRN, "Reverting to using uncorrected data!"); UseCorrectedData = false; } // Now read in different data depending on what the user has specified std::string DataLocation = GeneralUtils::GetTopLevelDir() + "/data/ANL/CC1pip_on_n/"; // If we're using corrected data if (UseCorrectedData) { if (wTrueCut == 1.4) { DataLocation += "anl82corr-numu-n-to-mu-n-piplus-lowW_edges.txt"; // No W cut } else { DataLocation += "anl82corr-numu-n-to-mu-n-piplus-noW_edges.txt"; } // If we're using raw uncorrected data } else { if (wTrueCut == 1.4) { DataLocation += "anl82-numu-cc1npip-14Wcut.txt"; } else if (wTrueCut == 1.6) { DataLocation += "anl82-numu-cc1npip-16Wcut.txt"; } else if (wTrueCut == 10.0) { DataLocation += "anl82-numu-cc1npip-noWcut.txt"; } } fSettings.SetDataInput(DataLocation); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = (GetEventHistogram()->Integral("width") * 1E-38 * 2.0 / 1.0 / (fNEvents + 0.)); // Plot Setup ------------------------------------------------------- SetDataFromTextFile(fSettings.GetDataInput()); SetCovarFromDiagonal(); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; void ANL_CC1npip_XSec_1DEnu_nu::FillEventVariables(FitEvent *event) { if (event->NumFSParticle(2112) == 0 || event->NumFSParticle(211) == 0 || event->NumFSParticle(13) == 0) { return; } TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Pn = event->GetHMFSParticle(2112)->fP; TLorentzVector Ppip = event->GetHMFSParticle(211)->fP; TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; double hadMass = FitUtils::MpPi(Pn, Ppip); double Enu = -1.0; // ANL has a W cuts at 1.4, 1.6 and no w cut // This is set by user, or defaults to 2.0 if (hadMass < wTrueCut * 1000.) { Enu = Pnu.E() / 1.E3; } fXVar = Enu; return; }; bool ANL_CC1npip_XSec_1DEnu_nu::isSignal(FitEvent *event) { return SignalDef::isCC1pi3Prong(event, 14, 211, 2112, EnuMin, EnuMax); } diff --git a/src/ANL/ANL_CC1pi0_XSec_1DEnu_nu.cxx b/src/ANL/ANL_CC1pi0_XSec_1DEnu_nu.cxx index 19ef7a7..fe39e89 100644 --- a/src/ANL/ANL_CC1pi0_XSec_1DEnu_nu.cxx +++ b/src/ANL/ANL_CC1pi0_XSec_1DEnu_nu.cxx @@ -1,137 +1,137 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ /** * Radecky et al. Phys Rev D, 3rd series, volume 25, number 5, 1 March 1982, p 1161-1173 */ #include "ANL_CC1pi0_XSec_1DEnu_nu.h" //******************************************************************** ANL_CC1pi0_XSec_1DEnu_nu::ANL_CC1pi0_XSec_1DEnu_nu(nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "ANL CC1pi0 Event Rate 1DQ2 nu sample. \n" \ "Target: D2 \n" \ "Flux: \n" \ "Signal: \n"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("E_{#nu} (GeV)"); fSettings.SetYTitle("#sigma (cm^{2}/neutron)"); fSettings.SetAllowedTypes("FIX/DIAG", "FIX,FREE,SHAPE/DIAG"); fSettings.SetEnuRange(0.0, 1.5); fSettings.SetS("norm_error", "0.20"); fSettings.DefineAllowedTargets("D,H"); // plot information fSettings.SetTitle("ANL #nu_mu CC1#pi^{0}"); fSettings.DefineAllowedSpecies("numu"); // User can specifiy to use uncorrected data UseCorrectedData = !fSettings.Found("name", "Uncorr"); // User can specify "W14" for W < 1.4 GeV cut // "W16" for W < 1.6 GeV cut // The default is W < 2.0 if (fSettings.Found("name", "W14Cut")) wTrueCut = 1.4; else if (fSettings.Found("name", "W16Cut")) wTrueCut = 1.6; else wTrueCut = 10.0; // Flag for bad combo if (UseCorrectedData && wTrueCut == 1.6) { - QERROR(WRN, "Can not run ANL CC1pi0 W < 1.6 GeV with CORRECTION, because " + NUIS_ERR(WRN, "Can not run ANL CC1pi0 W < 1.6 GeV with CORRECTION, because " "the data DOES NOT EXIST"); - QERROR(WRN, "Correction exists for W < 1.4 GeV and no W cut data ONLY"); - QERROR(WRN, "Reverting to using uncorrected data!"); + NUIS_ERR(WRN, "Correction exists for W < 1.4 GeV and no W cut data ONLY"); + NUIS_ERR(WRN, "Reverting to using uncorrected data!"); UseCorrectedData = false; } // Now read in different data depending on what the user has specified std::string DataLocation = GeneralUtils::GetTopLevelDir() + "/data/ANL/CC1pi0_on_n/"; // If we're using corrected data if (UseCorrectedData) { if (wTrueCut == 1.4) { DataLocation += "anl82corr-numu-n-to-mu-p-pi0-lowW_edges.txt"; } else if (wTrueCut == 10.0) { DataLocation += "anl82corr-numu-n-to-mu-p-pi0-noW_edges.txt"; } // If we're using raw uncorrected data } else { if (wTrueCut == 1.4) { DataLocation += "anl82-numu-cc1pi0-14Wcut.txt"; } else if (wTrueCut == 1.6) { DataLocation += "anl82-numu-cc1pi0-16Wcut.txt"; } else if (wTrueCut == 10.0) { DataLocation += "anl82-numu-cc1pi0-noWcut.txt"; } } fSettings.SetDataInput(DataLocation); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = (GetEventHistogram()->Integral("width") * 1E-38 * 2.0 / 1.0 / (fNEvents + 0.)); // Plot Setup ------------------------------------------------------- SetDataFromTextFile( fSettings.GetDataInput() ); SetCovarFromDiagonal(); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; void ANL_CC1pi0_XSec_1DEnu_nu::FillEventVariables(FitEvent *event) { if (event->NumFSParticle(2212) == 0 || event->NumFSParticle(111) == 0 || event->NumFSParticle(13) == 0) { return; } TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Pp = event->GetHMFSParticle(2212)->fP; TLorentzVector Ppi0 = event->GetHMFSParticle(111)->fP; TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; double hadMass = FitUtils::MpPi(Pp, Ppi0); double Enu = -1.0; if (hadMass/1000. < wTrueCut) { Enu = Pnu.E()/1.E3; } fXVar = Enu; return; }; bool ANL_CC1pi0_XSec_1DEnu_nu::isSignal(FitEvent *event) { return SignalDef::isCC1pi3Prong(event, 14, 111, 2212, EnuMin, EnuMax); } diff --git a/src/ANL/ANL_CC1ppip_XSec_1DEnu_nu.cxx b/src/ANL/ANL_CC1ppip_XSec_1DEnu_nu.cxx index cb15beb..fa5af57 100644 --- a/src/ANL/ANL_CC1ppip_XSec_1DEnu_nu.cxx +++ b/src/ANL/ANL_CC1ppip_XSec_1DEnu_nu.cxx @@ -1,139 +1,139 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ /** * Radecky et al. Phys Rev D, 3rd series, volume 25, number 5, 1 March 1982, p 1161-1173 */ #include "ANL_CC1ppip_XSec_1DEnu_nu.h" //******************************************************************** ANL_CC1ppip_XSec_1DEnu_nu::ANL_CC1ppip_XSec_1DEnu_nu(nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "ANL CC1pip XSec Enu nu sample. \n" \ "Target: D2 \n" \ "Flux: \n" \ "Signal: \n"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("E_{#nu} (GeV)"); fSettings.SetYTitle("#sigma (cm^{2}/nucleon)"); fSettings.SetAllowedTypes("FIX/DIAG", "FIX,FREE,SHAPE/DIAG"); fSettings.SetEnuRange(0.0, 6.0); fSettings.SetS("norm_error", "0.20"); fSettings.DefineAllowedTargets("D,H"); // plot information fSettings.SetTitle("ANL #nu_mu CC1#pi^{0}"); fSettings.DefineAllowedSpecies("numu"); // User can specifiy to use uncorrected data UseCorrectedData = !fSettings.Found("name", "Uncorr"); // User can specify "W14" for W < 1.4 GeV cut // "W16" for W < 1.6 GeV cut // The default is no W cut if (fSettings.Found("name", "W14Cut")) wTrueCut = 1.4; else if (fSettings.Found("name", "W16Cut")) wTrueCut = 1.6; else wTrueCut = 10.0; // Flag for bad combo if (UseCorrectedData && wTrueCut == 1.6) { - QERROR(WRN, "Can not run ANL CC1pi+1p W < 1.6 GeV with CORRECTION, because " + NUIS_ERR(WRN, "Can not run ANL CC1pi+1p W < 1.6 GeV with CORRECTION, because " "the data DOES NOT EXIST"); - QERROR(WRN, "Correction exists for W < 1.4 GeV and no W cut data ONLY"); - QERROR(WRN, "Reverting to using uncorrected data!"); + NUIS_ERR(WRN, "Correction exists for W < 1.4 GeV and no W cut data ONLY"); + NUIS_ERR(WRN, "Reverting to using uncorrected data!"); UseCorrectedData = false; } // Now read in different data depending on what the user has specified std::string DataLocation = GeneralUtils::GetTopLevelDir() + "/data/ANL/CC1pip_on_p/"; // If we're using corrected data if (UseCorrectedData) { if (wTrueCut == 1.4) { DataLocation += "anl82corr-numu-p-to-mu-p-piplus-lowW_edges.txt"; } else if (wTrueCut == 10.0) { DataLocation += "anl82corr-numu-p-to-mu-p-piplus-noW_edges.txt"; } // If we're using raw uncorrected data } else { if (wTrueCut == 1.4) { DataLocation += "anl82-numu-cc1ppip-14Wcut.txt"; } else if (wTrueCut == 1.6) { DataLocation += "anl82-numu-cc1ppip-16Wcut.txt"; } else if (wTrueCut == 10.0) { DataLocation += "anl82-numu-cc1ppip-noWcut.txt"; } } fSettings.SetDataInput(DataLocation); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = (GetEventHistogram()->Integral("width") * 1E-38 * 2.0 / 1.0 / (fNEvents + 0.)); // Plot Setup ------------------------------------------------------- SetDataFromTextFile( fSettings.GetDataInput() ); SetCovarFromDiagonal(); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; void ANL_CC1ppip_XSec_1DEnu_nu::FillEventVariables(FitEvent *event) { if (event->NumFSParticle(2212) == 0 || event->NumFSParticle(211) == 0 || event->NumFSParticle(13) == 0) { return; } TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Pp = event->GetHMFSParticle(2212)->fP; TLorentzVector Ppip = event->GetHMFSParticle(211)->fP; TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; double hadMass = FitUtils::MpPi(Pp, Ppip); double Enu = -1.0; // ANL has a W cuts at 1.4, 1.6 and no w cut // This is set by user, or defaults to 2.0 if (hadMass/1000. < wTrueCut) { Enu = Pnu.E()/1.E3; } fXVar = Enu; return; } bool ANL_CC1ppip_XSec_1DEnu_nu::isSignal(FitEvent *event) { return SignalDef::isCC1pi3Prong(event, 14, 211, 2212, EnuMin, EnuMax); } diff --git a/src/Config/NuisConfig.cxx b/src/Config/NuisConfig.cxx index ba6db79..c1d3915 100644 --- a/src/Config/NuisConfig.cxx +++ b/src/Config/NuisConfig.cxx @@ -1,817 +1,817 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "NuisConfig.h" #include "FitLogger.h" #include "GeneralUtils.h" #include "TXMLEngine.h" namespace Config { nuisconfig &Get() { return nuisconfig::GetConfig(); }; std::string GetPar(std::string const &name) { return Get().GetConfig(name); } bool HasPar(std::string const &name) { return Get().HasConfig(name); } std::string GetParS(std::string const &name) { return Get().GetConfigS(name); } int GetParI(std::string const &name) { return Get().GetConfigI(name); } bool GetParB(std::string const &name) { return Get().GetConfigB(name); } float GetParF(std::string const &name) { return Get().GetConfigF(name); } double GetParD(std::string const &name) { return Get().GetConfigD(name); } void SetPar(std::string const &name, std::string const &val) { Get().SetConfig(name, val); } void SetPar(std::string const &name, char const *val) { Get().SetConfig(name, val); } void SetPar(std::string const &name, bool val) { Get().SetConfig(name, val); } void SetPar(std::string const &name, int val) { Get().SetConfig(name, val); } void SetPar(std::string const &name, float val) { Get().SetConfig(name, val); } void SetPar(std::string const &name, double val) { Get().SetConfig(name, val); } } namespace FitPar { std::string GetDataBase() { return GeneralUtils::GetTopLevelDir() + "/data/"; }; nuisconfig &Config() { return Config::Get(); }; } nuisconfig *nuisconfig::m_nuisconfigInstance = NULL; nuisconfig &nuisconfig::GetConfig(void) { if (!m_nuisconfigInstance) m_nuisconfigInstance = new nuisconfig; return *m_nuisconfigInstance; }; // Main Class Definition nuisconfig::nuisconfig() { // Load default Parameters std::string filename = (GeneralUtils::GetTopLevelDir() + "/parameters/config.xml"); std::cout << "[ NUISANCE ]: Loading DEFAULT settings from : " << filename; // Create XML Engine fXML = new TXMLEngine; fXML->SetSkipComments(true); // Load in documents fXMLDocs.push_back(fXML->ParseFile(filename.c_str(), 1000000)); if (!fXMLDocs[0]) { - QTHROW("Cannot Read Parameters File!"); + NUIS_ABORT("Cannot Read Parameters File!"); } // Setup Main XML Node to be the first file read fMainNode = fXML->DocGetRootElement(fXMLDocs[0]); // Print result std::cout << " -> DONE." << std::endl; } nuisconfig::~nuisconfig() { // Should really delete XML objects here but we don't } void nuisconfig::LoadSettings(std::string const &filename, std::string const &state) { // Open file and see if its XML std::cout << "[ NUISANCE ]: Trying to parse file : " << filename; StopTalking(); XMLDocPointer_t readdoc = fXML->ParseFile(filename.c_str(), 1000000); StartTalking(); // If it is parse it as a nice XML config file if (readdoc) { std::cout << " -> Found XML file." << std::endl; LoadXMLSettings(filename, state); // Otherwise its an old simple card file } else { std::cout << " -> Assuming its a simple card file." << std::endl; LoadCardSettings(filename, state); } } void nuisconfig::LoadXMLSettings(std::string const &filename, std::string const &state) { std::cout << "[ NUISANCE ]: Loading XML settings from : " << filename << std::endl; // Add new file to xml docs list fXMLDocs.push_back(fXML->ParseFile(filename.c_str(), 1000000)); if (!fXMLDocs.back()) { - QTHROW("Failed to read: " << filename); + NUIS_ABORT("Failed to read: " << filename); } // Loop over children and add XMLNodePointer_t child = fXML->GetChild(fXML->DocGetRootElement(fXMLDocs.back())); // // Here we manually load all the children from the card file into our root // node if (!child) { - QTHROW("CANNOT Find child inside settings file!"); + NUIS_ABORT("CANNOT Find child inside settings file!"); } while (child) { // SPECIAL CONFIG CASE // If its a config node, then remove previous attributes, overriding old // value if (!std::string(fXML->GetNodeName(child)).compare("config")) { // Loop over attribues XMLAttrPointer_t attr1 = fXML->GetFirstAttr(child); while (attr1) { // If a valid attribute name is given then compare if (!GetConfigS(fXML->GetAttrName(attr1)).empty()) { // Get full list of present configs std::vector confignodes = GetNodes("config"); // Loop over present configs and compare for (size_t i = 0; i < confignodes.size(); i++) { // If we already have this config, free the old attribute if (fXML->HasAttr(confignodes[i], fXML->GetAttrName(attr1))) { fXML->FreeAttr(confignodes[i], fXML->GetAttrName(attr1)); break; } } } // Move onto next config attribute attr1 = fXML->GetNextAttr(attr1); } } TString nodeStr; fXML->SaveSingleNode(child, &nodeStr); XMLNodePointer_t copyNode = fXML->ReadSingleNode(nodeStr.Data()); // std::cout << "copying node..." << std::endl; // PrintXML(copyNode); // Add this child to the main config list fXML->AddChild(fMainNode, copyNode); // std::cout << "Done, was it added?" << std::endl; // PrintXML(fMainNode); // Get Next Child child = fXML->GetNext(child); } std::cout << " -> DONE." << std::endl; } void nuisconfig::LoadCardSettings(std::string const &filename, std::string const &state) { std::cout << "[ NUISANCE ]: Loading simple config from : " << filename; // Build XML Config from the card file by parsing each line std::vector cardlines = GeneralUtils::ParseFileToStr(filename, "\n"); int linecount = 0; // Loop over all input lines for (std::vector::iterator iter = cardlines.begin(); iter != cardlines.end(); iter++) { std::string line = (*iter); linecount++; // Skip Comments if (line.empty()) continue; if (line.c_str()[0] == '#') continue; // Parse whitespace std::vector strvct = GeneralUtils::ParseToStr(line, " "); if (strvct.empty()) continue; // Get Identifier std::string id = strvct[0]; // Build backwards compatible xml configs // Sample structure if (!id.compare("sample")) { CreateSampleNodeFromLine(line); } // Any parameter structure if (id.find("_parameter") != std::string::npos) { CreateParameterNodeFromLine(line); } // Any covar structure if (!id.compare("covar") || !id.compare("pull") || !id.compare("throw")) { CreatePullNodeFromLine(line); } // Any config structure if (!id.compare("config")) { CreateOldConfigNodeFromLine(line); } } std::cout << " -> DONE." << std::endl; } XMLNodePointer_t nuisconfig::CreateSampleNodeFromLine(std::string const &line) { // Create new node entry XMLNodePointer_t samplenode = CreateNode("sample"); // Parse line std::vector strvct = GeneralUtils::ParseToStr(line, " "); // Add line elements to the node // name input type norm if (strvct.size() > 1) Set(samplenode, "name", strvct[1]); if (strvct.size() > 2) Set(samplenode, "input", strvct[2]); if (strvct.size() > 3) Set(samplenode, "type", strvct[3]); if (strvct.size() > 4) Set(samplenode, "norm", strvct[4]); return samplenode; } XMLNodePointer_t nuisconfig::CreateParameterNodeFromLine( std::string const &line) { // Create new node entry XMLNodePointer_t parnode = CreateNode("parameter"); // Parse line std::vector strvct = GeneralUtils::ParseToStr(line, " "); // Add line elements to the node // type name nominal [low] [high] [step] state if (strvct.size() > 0) Set(parnode, "type", strvct[0]); if (strvct.size() > 1) Set(parnode, "name", strvct[1]); if (strvct.size() > 2) Set(parnode, "nominal", strvct[2]); // If free structure if (strvct.size() == 7) { Set(parnode, "low", strvct[3]); Set(parnode, "high", strvct[4]); Set(parnode, "step", strvct[5]); Set(parnode, "state", strvct[6]); // Fixed param structure } else if (strvct.size() == 3) { Set(parnode, "state", "FIX"); } else if (strvct.size() == 4) { Set(parnode, "state", strvct[3]); } return parnode; } XMLNodePointer_t nuisconfig::CreatePullNodeFromLine(std::string const &line) { // Create new node entry XMLNodePointer_t parnode = CreateNode("covar"); // Parse line std::vector strvct = GeneralUtils::ParseToStr(line, " "); // Add line elements to the node // name input type if (strvct.size() > 1) Set(parnode, "name", strvct[1]); if (strvct.size() > 2) Set(parnode, "input", strvct[2]); if (strvct.size() > 3) Set(parnode, "type", strvct[3]); return parnode; } XMLNodePointer_t nuisconfig::CreateOldConfigNodeFromLine( std::string const &line) { // Create new node entry XMLNodePointer_t confignode = CreateNode("config"); // Parse line std::vector strvct = GeneralUtils::ParseToStr(line, " "); // Add line elements to the node // name value if (strvct.size() > 2) Set(confignode, strvct[1], strvct[2]); return confignode; } void nuisconfig::FinaliseSettings(std::string const &name) { std::cout << "[ NUISANCE ]: Finalising run settings"; WriteSettings(name); // Save full config to file RemoveEmptyNodes(); RemoveIdenticalNodes(); std::cout << " -> DONE." << std::endl; } void nuisconfig::WriteSettings(std::string const &outputname) { // Create a New XML Doc XMLDocPointer_t newxmldoc = fXML->NewDoc(); fXML->DocSetRootElement(newxmldoc, fMainNode); // Save document to file if (GetConfigB("SaveParsedXMLFile")) { fXML->SaveDoc(newxmldoc, outputname.c_str()); } } void nuisconfig::PrintXML(XMLNodePointer_t node, int indent) { if (!node) { node = fMainNode; } std::stringstream ss(""); for (int i = 0; i < indent; ++i) { ss << " "; } std::cout << ss.str() << "<" << fXML->GetNodeName(node) << std::flush; XMLAttrPointer_t attr = fXML->GetFirstAttr(node); while (attr) { std::cout << " " << fXML->GetAttrName(attr) << "=\"" << fXML->GetAttrValue(attr) << "\"" << std::flush; attr = fXML->GetNextAttr(attr); } if (!fXML->GetChild(node)) { std::cout << " />" << std::endl; return; } std::cout << " >" << std::endl; XMLNodePointer_t child = fXML->GetChild(node); while (child) { PrintXML(child, indent + 1); child = fXML->GetNext(child); } std::cout << ss.str() << "GetNodeName(node) << ">" << std::endl; } XMLNodePointer_t nuisconfig::CreateNode(std::string const &name) { return fXML->NewChild(fMainNode, 0, name.c_str()); } XMLNodePointer_t nuisconfig::CreateNode(XMLNodePointer_t node, std::string const &name) { return fXML->NewChild(node, 0, name.c_str()); } XMLNodePointer_t nuisconfig::GetNode(XMLNodePointer_t node, std::string const &type) { /// Loop over all children XMLNodePointer_t child = fXML->GetChild(node); while (child != 0) { /// Get nodes for given type (if type empty return all) if (std::string(fXML->GetNodeName(child)) == type.c_str() or type.empty()) { return child; } // Next child child = fXML->GetNext(child); } // Child not found return 0; } void nuisconfig::RemoveEmptyNodes() { std::vector nodelist = Config::Get().GetNodes(); for (size_t i = 0; i < nodelist.size(); i++) { if (fXML->IsEmptyNode(nodelist[i])) { std::cout << "Removing empty node: " << fXML->GetNodeName(nodelist[i]) << ", with child ?" << bool(fXML->GetChild(nodelist[i])) << std::endl; RemoveNode(nodelist[i]); } } } void nuisconfig::RemoveIdenticalNodes() { std::vector removed; // Loop over all nodes and check for identical nodes std::vector nodelist = Config::Get().GetNodes(); for (size_t i = 0; i < nodelist.size(); i++) { for (size_t j = 0; j < nodelist.size(); j++) { if (i == j) continue; XMLNodePointer_t node1 = nodelist[i]; XMLNodePointer_t node2 = nodelist[j]; // Check node already removed. if (std::find(removed.begin(), removed.end(), node1) != removed.end()) { continue; } if (std::find(removed.begin(), removed.end(), node2) != removed.end()) { continue; } // Check matching if (!MatchingNodes(node1, node2)) { continue; } if (std::string(fXML->GetNodeName(node1)).compare("config") and fXML->IsEmptyNode(node1)) { // Matching so print out warning std::cout << "Matching nodes given! Removing node1!" << std::endl << "Node 1" << std::endl; PrintNode(node1); std::cout << "Node 2" << std::endl; PrintNode(node2); } // Remove node removed.push_back(node1); } } // Now go through and remove this node. for (size_t i = 0; i < removed.size(); i++) { RemoveNode(removed.at(i)); } return; } void nuisconfig::RemoveNode(XMLNodePointer_t node) { std::cout << "[INFO]: Removing node: " << fXML->GetNodeName(node) << std::endl; fXML->FreeAllAttr(node); fXML->CleanNode(node); fXML->FreeNode(node); fXML->UnlinkNode(node); } void nuisconfig::PrintNode(XMLNodePointer_t node) { // Print Node Name std::cout << fXML->GetNodeName(node) << std::endl; // Loop and print all attributes XMLAttrPointer_t attr = fXML->GetFirstAttr(node); while (attr != 0) { std::cout << " -> " << fXML->GetAttrName(attr) << " : " << fXML->GetAttrValue(attr) << std::endl; attr = fXML->GetNextAttr(attr); } } bool nuisconfig::MatchingNodes(XMLNodePointer_t node1, XMLNodePointer_t node2) { bool matching = true; XMLAttrPointer_t attr = fXML->GetFirstAttr(node1); while (attr != 0) { if (GetS(node2, fXML->GetAttrName(attr)) != fXML->GetAttrValue(attr)) matching = false; attr = fXML->GetNextAttr(attr); } return matching; } XMLNodePointer_t nuisconfig::GetNode(std::string const &type) { return GetNode(fMainNode, type); } std::vector nuisconfig::GetNodes(XMLNodePointer_t node, std::string const &type) { // Create new vector for nodes std::vector nodelist; /// Loop over all children XMLNodePointer_t child = fXML->GetChild(node); while (child != 0) { /// Get nodes for given type (if type empty return all) if (std::string(fXML->GetNodeName(child)) == type.c_str() or type.empty()) { nodelist.push_back(child); } // Next child child = fXML->GetNext(child); } // return list return nodelist; } std::vector nuisconfig::GetNodes(std::string const &type) { return GetNodes(fMainNode, type); } void nuisconfig::Set(XMLNodePointer_t node, std::string const &name, std::string const &val) { // Remove and re-add attribute if (fXML->HasAttr(node, name.c_str())) { fXML->FreeAttr(node, name.c_str()); } fXML->NewAttr(node, 0, name.c_str(), val.c_str()); } void nuisconfig::Set(XMLNodePointer_t node, std::string const &name, char const *val) { Set(node, name, std::string(val)); } void nuisconfig::Set(XMLNodePointer_t node, std::string const &name, bool val) { Set(node, name, GeneralUtils::BoolToStr(val)); } void nuisconfig::Set(XMLNodePointer_t node, std::string const &name, int val) { Set(node, name, GeneralUtils::IntToStr(val)); } void nuisconfig::Set(XMLNodePointer_t node, std::string const &name, float val) { Set(node, name, GeneralUtils::DblToStr(val)); } void nuisconfig::Set(XMLNodePointer_t node, std::string const &name, double val) { Set(node, name, GeneralUtils::DblToStr(val)); } void nuisconfig::SetS(XMLNodePointer_t node, std::string const &name, std::string const &val) { Set(node, name, val); } void nuisconfig::SetB(XMLNodePointer_t node, std::string const &name, bool val) { Set(node, name, GeneralUtils::BoolToStr(val)); } void nuisconfig::SetI(XMLNodePointer_t node, std::string const &name, int val) { Set(node, name, GeneralUtils::IntToStr(val)); } void nuisconfig::SetF(XMLNodePointer_t node, std::string const &name, float val) { Set(node, name, GeneralUtils::DblToStr(val)); } void nuisconfig::SetD(XMLNodePointer_t node, std::string const &name, double val) { Set(node, name, GeneralUtils::DblToStr(val)); } bool nuisconfig::Has(XMLNodePointer_t node, std::string const &name) { // If node empty return empty if (node == 0) return false; // Search attributes XMLAttrPointer_t attr = fXML->GetFirstAttr(node); bool found = false; // Loop over all attributes while (attr != 0) { // Find value of correct name if (std::string(fXML->GetAttrName(attr)) == name.c_str()) { found = true; break; } // Next Attribute attr = fXML->GetNextAttr(attr); } return found; } std::string nuisconfig::Get(XMLNodePointer_t node, std::string const &name) { // If node empty return empty if (node == 0) return ""; // Get Attribute from child with name XMLAttrPointer_t attr = fXML->GetFirstAttr(node); std::string temp = ""; // Loop over all attributes while (attr != 0) { // If valid match then save if (std::string(fXML->GetAttrName(attr)) == name.c_str()) { temp = fXML->GetAttrValue(attr); } // Next Attribute attr = fXML->GetNextAttr(attr); } return temp; } std::string nuisconfig::GetS(XMLNodePointer_t node, std::string const &name) { return Get(node, name); } bool nuisconfig::GetB(XMLNodePointer_t node, std::string const &name) { std::string tempattr = Get(node, name); return GeneralUtils::StrToBool(tempattr); } int nuisconfig::GetI(XMLNodePointer_t node, std::string const &name) { std::string tempattr = Get(node, name); return GeneralUtils::StrToInt(tempattr); } float nuisconfig::GetF(XMLNodePointer_t node, std::string const &name) { std::string tempattr = Get(node, name); return GeneralUtils::StrToDbl(tempattr); } double nuisconfig::GetD(XMLNodePointer_t node, std::string const &name) { std::string tempattr = Get(node, name); return GeneralUtils::StrToDbl(tempattr); } std::vector nuisconfig::GetVS(XMLNodePointer_t node, std::string const &name, const char *del) { std::string tempattr = Get(node, name); return GeneralUtils::ParseToStr(tempattr, del); } // std::vector nuisconfig::GetVB(XMLNodePointer_t node, // std::string name, // const char* del) { // std::string tempattr = Get(node, name); // return GeneralUtils::ParseToBool(tempattr, del); // } std::vector nuisconfig::GetVI(XMLNodePointer_t node, std::string const &name, const char *del) { std::string tempattr = Get(node, name); return GeneralUtils::ParseToInt(tempattr, del); } // std::vector nuisconfig::GetVF(XMLNodePointer_t node, // std::string name, // const char* del) { // std::string tempattr = Get(node, name); // return GeneralUtils::ParseToDouble(tempattr, del); // } std::vector nuisconfig::GetVD(XMLNodePointer_t node, std::string const &name, char const *del) { std::string tempattr = Get(node, name); return GeneralUtils::ParseToDbl(tempattr, del); } std::vector nuisconfig::GetAllKeysForNode(XMLNodePointer_t node) { //bool matching = true; XMLAttrPointer_t attr = fXML->GetFirstAttr(node); std::vector keys; while (attr != 0) { if (!std::string(fXML->GetAttrName(attr)).empty()) { keys.push_back(std::string(fXML->GetAttrName(attr))); } attr = fXML->GetNextAttr(attr); } return keys; } XMLNodePointer_t nuisconfig::GetConfigNode(std::string const &name) { // Loop over children and look for name XMLNodePointer_t child = fXML->GetChild(fMainNode); while (child != 0) { // Select only config parameters if (!std::string(fXML->GetNodeName(child)).compare("config")) { // Loop over config attributes and search for name XMLAttrPointer_t attr = fXML->GetFirstAttr(child); while (attr != 0) { // Save name value if (std::string(fXML->GetAttrName(attr)) == name.c_str()) { return child; } // Get Next Attribute attr = fXML->GetNextAttr(attr); } } // Next Child child = fXML->GetNext(child); } return 0; } void nuisconfig::SetConfig(std::string const &name, std::string const &val) { XMLNodePointer_t node = GetConfigNode(name); if (!node) node = CreateNode("config"); Set(node, name, val); } void nuisconfig::SetConfig(std::string const &name, char const *val) { SetConfig(name, std::string(val)); } void nuisconfig::SetConfig(std::string const &name, bool val) { XMLNodePointer_t node = GetConfigNode(name); if (!node) node = CreateNode("config"); Set(node, name, val); } void nuisconfig::SetConfig(std::string const &name, int val) { XMLNodePointer_t node = GetConfigNode(name); if (!node) node = CreateNode("config"); Set(node, name, val); } void nuisconfig::SetConfig(std::string const &name, float val) { XMLNodePointer_t node = GetConfigNode(name); if (!node) node = CreateNode("config"); Set(node, name, val); } void nuisconfig::SetConfig(std::string const &name, double val) { XMLNodePointer_t node = GetConfigNode(name); if (!node) node = CreateNode("config"); Set(node, name, val); } void nuisconfig::OverrideConfig(std::string const &conf) { std::vector opts = GeneralUtils::ParseToStr(conf, "="); SetConfig(opts[0], opts[1]); } std::string nuisconfig::GetConfig(std::string const &name) { XMLNodePointer_t node = GetConfigNode(name); if (!node) return ""; XMLAttrPointer_t attr = fXML->GetFirstAttr(node); std::string temp = ""; // Loop config attributes while (attr != 0) { // Find match if (std::string(fXML->GetAttrName(attr)) == name.c_str()) { temp = fXML->GetAttrValue(attr); } // Get Next Attribute attr = fXML->GetNextAttr(attr); } return temp; } bool nuisconfig::HasConfig(std::string const &name) { return bool(GetConfigNode(name)); } std::string nuisconfig::GetConfigS(std::string const &name) { return GetConfig(name); } bool nuisconfig::GetConfigB(std::string const &name) { std::string pars = GetConfig(name); return GeneralUtils::StrToBool(pars); } int nuisconfig::GetConfigI(std::string const &name) { std::string pars = GetConfig(name); return GeneralUtils::StrToInt(pars); } float nuisconfig::GetConfigF(std::string const &name) { std::string pars = GetConfig(name); return GeneralUtils::StrToDbl(pars); } double nuisconfig::GetConfigD(std::string const &name) { std::string pars = GetConfig(name); return GeneralUtils::StrToDbl(pars); } std::string nuisconfig::GetParDIR(std::string const &parName) { std::string outstr = this->GetParS(parName); // Make replacements in the string const int nfiletypes = 2; const std::string filetypes[nfiletypes] = {"@data", "@nuisance"}; std::string filerepl[nfiletypes] = {FitPar::GetDataBase(), FitPar::GetDataBase() + "/../"}; for (int i = 0; i < nfiletypes; i++) { std::string findstring = filetypes[i]; std::string replstring = filerepl[i]; if (outstr.find(findstring) != std::string::npos) { outstr.replace(outstr.find(findstring), findstring.size(), filerepl[i]); break; } } return outstr; }; diff --git a/src/Electron/ElectronScattering_DurhamData.cxx b/src/Electron/ElectronScattering_DurhamData.cxx index 11d575b..7d8cf8c 100644 --- a/src/Electron/ElectronScattering_DurhamData.cxx +++ b/src/Electron/ElectronScattering_DurhamData.cxx @@ -1,483 +1,483 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "ElectronScattering_DurhamData.h" //******************************************************************** ElectronScattering_DurhamData::ElectronScattering_DurhamData( nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "Electron Scattering Durham Data sample. \n" "Target: Multiple \n" "Flux: Energy should match data being handled \n" "Signal: Any event with an electron in the final state \n"; fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.DefineAllowedSpecies("electron"); fSettings.SetTitle("Electron"); fSettings.SetAllowedTypes("FIX/DIAG", "FIX,FREE,SHAPE/DIAG/NORM/MASK"); fSettings.SetXTitle("q0"); fSettings.SetYTitle("#sigma"); fIsNoWidth = true; FinaliseSampleSettings(); // Plot Setup ------------------------------------------------------- SetDataFromName(fSettings.GetS("originalname")); SetCovarFromDiagonal(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon // fScaleFactor = ((GetEventHistogram()->Integral("width") * 1E-38 / (fNEvents // + 0.)) / TotalIntegratedFlux()); EnuMin = fZLowLim; EnuMax = fZHighLim; double sigscale = GetEventHistogram()->Integral() * 1E-38 / double(fNEvents) / TotalIntegratedFlux(); // double dangle = 2 * M_PI * fabs((1. - cos(fYLowLim * M_PI / 180.)) - (1. - // cos(fYHighLim * M_PI / 180.))); // fScaleFactor = sigscale / dangle / fZCenter; fScaleFactor = sigscale; std::cout << "Event Integral = " << GetEventHistogram()->Integral() << std::endl; std::cout << "Flux Integral = " << TotalIntegratedFlux() << std::endl; std::cout << "FNEvents = " << fNEvents << std::endl; std::cout << "Z Limits = " << fZLowLim << " " << fZHighLim << std::endl; std::cout << "sigscale = " << sigscale << std::endl; std::cout << "fZCenter = " << fZCenter << std::endl; std::cout << "ScaleFactor = " << fScaleFactor << std::endl; // Finish up FinaliseMeasurement(); }; //******************************************************************** void ElectronScattering_DurhamData::SetDataFromName(std::string name) { //******************************************************************** // Data Should be given in the format // Electron_Z_A_Energy_Theta_Source std::vector splitstring = GeneralUtils::ParseToStr(name, "_"); std::string zstring = splitstring[1]; std::string astring = splitstring[2]; std::string estring = splitstring[3]; std::string tstring = splitstring[4]; std::string sstring = splitstring[5]; fYCenter = GeneralUtils::StrToDbl(tstring); fZCenter = GeneralUtils::StrToDbl(estring); // Create effective E and Theta bin Edges std::vector thetabinedges; std::vector ebinedges; int nthetabins = FitPar::Config().GetParI("Electron_NThetaBins"); int nebins = FitPar::Config().GetParI("Electron_NEnergyBins"); double thetawidth = FitPar::Config().GetParD("Electron_ThetaWidth"); double ewidth = FitPar::Config().GetParD("Electron_EnergyWidth"); for (int i = -nthetabins; i <= nthetabins; i++) { thetabinedges.push_back(fYCenter + thetawidth * (double(i))); } for (int i = -nebins; i <= nebins; i++) { double newval = fZCenter + ewidth * (double(i)); if (newval < 0.0) newval = 0.0; if (newval < GetEventHistogram()->GetXaxis()->GetXmin()) newval = GetEventHistogram()->GetXaxis()->GetXmin(); if (newval > GetEventHistogram()->GetXaxis()->GetXmax()) newval = GetEventHistogram()->GetXaxis()->GetXmax(); if (std::find(ebinedges.begin(), ebinedges.end(), newval) != ebinedges.end()) continue; ebinedges.push_back(newval); } // Determine target std::string target = ""; if (!zstring.compare("6") && !astring.compare("12")) target = "12C.dat"; else if (!zstring.compare("8") && !astring.compare("16")) target = "16O.dat"; else { - QTHROW("Target not supported in electron scattering module!" + NUIS_ABORT("Target not supported in electron scattering module!" ); } // Fill Data Points std::string line; std::ifstream mask((FitPar::GetDataBase() + "/Electron/" + target).c_str(), std::ifstream::in); if (!mask.good()) { - QTHROW("Failed to open e-scattering database file: " + NUIS_ABORT("Failed to open e-scattering database file: " << (FitPar::GetDataBase() + "/Electron/" + target)); } int i = 0; std::vector pointx; std::vector errorx; std::vector pointy; std::vector errory; double scalef = 1.E-38 * 1.E5; while (std::getline(mask >> std::ws, line, '\n')) { // std::cout << "Line = " << line << std::endl; if (line.empty()) continue; std::vector lineentries = GeneralUtils::ParseToStr(line, " "); // std::cout << "Checking : " << line << std::endl; if (zstring.compare(lineentries[0])) continue; if (astring.compare(lineentries[1])) continue; if (estring.compare(lineentries[2])) continue; if (tstring.compare(lineentries[3])) continue; if (sstring.compare(lineentries[7])) continue; // std::cout << "Registering data point : " << line << std::endl; // std::cout << "Adding Graph Point : " << // GeneralUtils::StrToDbl(lineentries[4]) << " " << // GeneralUtils::StrToDbl(lineentries[5]) << std::endl; // Loop through x and y points and find a place to insert if (pointx.empty()) { pointx.push_back(GeneralUtils::StrToDbl(lineentries[4])); errorx.push_back(0.0); pointy.push_back(GeneralUtils::StrToDbl(lineentries[5]) * scalef); errory.push_back(GeneralUtils::StrToDbl(lineentries[6]) * scalef); } else { for (size_t j = 0; j < pointx.size(); j++) { if (GeneralUtils::StrToDbl(lineentries[4]) < pointx[j] && j == 0) { // std::cout << "Inserting at start point iterator " << std::endl; pointx.insert(pointx.begin() + j, GeneralUtils::StrToDbl(lineentries[4])); errorx.insert(errorx.begin() + j, 0.0); pointy.insert(pointy.begin() + j, GeneralUtils::StrToDbl(lineentries[5]) * scalef); errory.insert(errory.begin() + j, GeneralUtils::StrToDbl(lineentries[6]) * scalef); break; } else if (GeneralUtils::StrToDbl(lineentries[4]) > pointx[j] && j == pointx.size() - 1) { // std::cout << "Pushing back data point " << std::endl; pointx.push_back(GeneralUtils::StrToDbl(lineentries[4])); errorx.push_back(0.0); pointy.push_back(GeneralUtils::StrToDbl(lineentries[5]) * scalef); errory.push_back(GeneralUtils::StrToDbl(lineentries[6]) * scalef); break; } else if (GeneralUtils::StrToDbl(lineentries[4]) > pointx[j - 1] && GeneralUtils::StrToDbl(lineentries[4]) < pointx[j]) { // std::cout << "Inserting at point iterator = " << j << std::endl; pointx.insert(pointx.begin() + j, GeneralUtils::StrToDbl(lineentries[4])); errorx.insert(errorx.begin() + j, 0.0); pointy.insert(pointy.begin() + j, GeneralUtils::StrToDbl(lineentries[5]) * scalef); errory.insert(errory.begin() + j, GeneralUtils::StrToDbl(lineentries[6]) * scalef); break; } } } // pointx.push_back(GeneralUtils::StrToDbl(lineentries[4])); // errorx.push_back(0.0); // pointy.push_back(GeneralUtils::StrToDbl(lineentries[5])); // errory.push_back(GeneralUtils::StrToDbl(lineentries[6])); i++; } if (!pointx.size() || (pointx.size() != errorx.size()) || !pointy.size() || (pointy.size() != errory.size())) { - QTHROW("Failed to find dataset: " << name << "{" + NUIS_ABORT("Failed to find dataset: " << name << "{" << "Z: " << zstring << ", A: " << astring << ", E: " << estring << ", CTheta: " << tstring << ", PubID: " << sstring << " } in file: " << (FitPar::GetDataBase() + "/Electron/" + target)); } // for (uint i = 0; i < pointx.size(); i++) { // std::cout << "Q0 Point " << i << " = " << pointx[i] << std::endl; // } fDataGraph = new TGraphErrors(pointx.size(), &pointx[0], &pointy[0], &errorx[0], &errory[0]); fDataGraph->SetNameTitle((fName + "_data_GRAPH").c_str(), (fName + "_data_GRAPH").c_str()); // Now form an effective data and mc histogram std::vector q0binedges; const double* x = fDataGraph->GetX(); // Loop over graph and get mid way point between each data point. for (int i = 0; i < fDataGraph->GetN(); i++) { // std::cout << "X Point = " << x[i] << std::endl; if (i == 0) { // First point set lower width as half distance to point above q0binedges.push_back(x[0] - ((x[1] - x[0]) / 2.0)); } else if (i == fDataGraph->GetN() - 1) { // Last point set upper width as half distance to point above. q0binedges.push_back(x[i] - ((x[i] - x[i - 1]) / 2.0)); q0binedges.push_back(x[i] + ((x[i] - x[i - 1]) / 2.0)); } else { // Set half distance to point below q0binedges.push_back(x[i] - ((x[i] - x[i - 1]) / 2.0)); } } // Bubble Sort // for (uint i = 0; i < q0binedges.size(); i++) { // std::cout << "Q0 Edge " << i << " = " << q0binedges[i] << std::endl; // } // for (uint i = 0; i < ebinedges.size(); i++) { // std::cout << "e Edge " << i << " = " << ebinedges[i] << std::endl; // } // for (uint i = 0; i < thetabinedges.size(); i++) { // std::cout << "theta Edge " << i << " = " << thetabinedges[i] << // std::endl; // } // Form the data hist, mchist, etc fDataHist = new TH1D((fName + "_data").c_str(), (fName + "_data").c_str(), q0binedges.size() - 1, &q0binedges[0]); fMCHist = (TH1D*)fDataHist->Clone("MC"); const double* y = fDataGraph->GetY(); const double* ey = fDataGraph->GetEY(); for (int i = 0; i < fDataGraph->GetN(); i++) { // std::cout << "Setting Data Bin " << i + 1 << " to " << y[i] << " +- " << // ey[i] << std::endl; fDataHist->SetBinContent(i + 1, y[i]); fDataHist->SetBinError(i + 1, ey[i]); fMCHist->SetBinContent(i + 1, 0.0); fMCHist->SetBinError(i + 1, 0.0); } fMCScan_Q0vsThetavsE = new TH3D((fName + "_MC_q0vsthetavse").c_str(), "MC_q0vsthetavse", q0binedges.size() - 1, &q0binedges[0], thetabinedges.size() - 1, &thetabinedges[0], ebinedges.size() - 1, &ebinedges[0]); fMCScan_Q0vsThetavsE->Reset(); fMCScan_Q0vsTheta = new TH2D( (fName + "_MC_q0vstheta").c_str(), "MC_q0vstheta", q0binedges.size() - 1, &q0binedges[0], thetabinedges.size() - 1, &thetabinedges[0]); fMCScan_Q0vsTheta->Reset(); fMCScan_Q0vsE = new TH2D((fName + "_MC_q0vse").c_str(), "MC_q0vse", q0binedges.size() - 1, &q0binedges[0], ebinedges.size() - 1, &ebinedges[0]); fMCScan_Q0vsE->Reset(); fXLowLim = fMCScan_Q0vsThetavsE->GetXaxis()->GetBinLowEdge(1); fXHighLim = fMCScan_Q0vsThetavsE->GetXaxis()->GetBinLowEdge( fMCScan_Q0vsThetavsE->GetNbinsX() + 2); fYLowLim = fMCScan_Q0vsThetavsE->GetYaxis()->GetBinLowEdge(1); fYHighLim = fMCScan_Q0vsThetavsE->GetYaxis()->GetBinLowEdge( fMCScan_Q0vsThetavsE->GetNbinsY() + 2); fZLowLim = fMCScan_Q0vsThetavsE->GetZaxis()->GetBinLowEdge(1); fZHighLim = fMCScan_Q0vsThetavsE->GetZaxis()->GetBinLowEdge( fMCScan_Q0vsThetavsE->GetNbinsZ() + 2); std::cout << "Sample " << name << "initialised: " << "{" << fXLowLim << "--" << fXHighLim << ", " << fYLowLim << "--" << fYHighLim << ", " << fZLowLim << "--" << fZHighLim << "}" << std::endl; } //******************************************************************** void ElectronScattering_DurhamData::FillEventVariables(FitEvent* event) { //******************************************************************** if (event->NumFSParticle(11) == 0) return; FitParticle* ein = event->PartInfo(0); FitParticle* eout = event->GetHMFSParticle(11); double q0 = fabs(ein->fP.E() - eout->fP.E()) / 1000.0; double E = ein->fP.E() / 1000.0; double theta = ein->fP.Vect().Angle(eout->fP.Vect()) * 180. / M_PI; fXVar = q0; fYVar = theta; fZVar = E; return; }; //******************************************************************** bool ElectronScattering_DurhamData::isSignal(FitEvent* event) { //******************************************************************** if (event->NumFSParticle(11) == 0) { std::cout << "Ev Cut due to no FS electron." << std::endl; return false; } // std::cout << "fXVar = " << fXVar << " " << fXLowLim << " " << fXHighLim << // std::endl; // std::cout << "fYVar = " << fYVar << " " << fYLowLim << " " << fYHighLim << // std::endl; // std::cout << "fZVar = " << fZVar << " " << fZLowLim << " " << fZHighLim << // std::endl; // std::cout << "iWeight: " << event->InputWeight << std::endl; if (fXVar < fXLowLim or fXVar > fXHighLim) { // std::cout << "Ev Cut due to X lims: " << fXLowLim << " -- " << fXHighLim // << " !<> " << fXVar << std::endl; return false; } if (fYVar < fYLowLim or fYVar > fYHighLim) { // std::cout << "Ev Cut due to Y lims: " << fYLowLim << " -- " << fYHighLim // << " !<> " << fXVar << std::endl; return false; } if (fZVar < fZLowLim or fZVar > fZHighLim) { // std::cout << "Ev Cut due to Z lims: " << fZLowLim << " -- " << fZHighLim // << " !<> " << fXVar << std::endl; return false; } return true; }; //******************************************************************** void ElectronScattering_DurhamData::FillHistograms() { //******************************************************************** Measurement1D::FillHistograms(); if (Signal) { fMCScan_Q0vsThetavsE->Fill(fXVar, fYVar, fZVar); fMCScan_Q0vsTheta->Fill(fXVar, fYVar); fMCScan_Q0vsE->Fill(fXVar, fZVar); } } // Weight = 1.0; // if (Signal) { // fMCHist->Fill(fXVar, Weight); // fMCFine->Fill(fXVar, Weight); // fMCStat->Fill(fXVar, 1.0); // if (fMCHist_Modes) fMCHist_Modes->Fill(Mode, fXVar, Weight); // } // } void ElectronScattering_DurhamData::ResetAll() { Measurement1D::ResetAll(); fMCScan_Q0vsThetavsE->Reset(); fMCScan_Q0vsTheta->Reset(); fMCScan_Q0vsE->Reset(); } void ElectronScattering_DurhamData::ApplyNormScale(double norm) { Measurement1D::ApplyNormScale(norm); fMCScan_Q0vsThetavsE->Scale(1.0 / norm); fMCScan_Q0vsTheta->Scale(1.0 / norm); fMCScan_Q0vsE->Scale(1.0 / norm); } //******************************************************************** void ElectronScattering_DurhamData::ScaleEvents() { //******************************************************************** Measurement1D::ScaleEvents(); /* fMCScan_Q0vsThetavsE->Scale(fScaleFactor, "width"); // Project into fMCScan_Q0vsTheta for (int x = 0; x < fMCScan_Q0vsThetavsE->GetNbinsX(); x++) { for (int y = 0; y < fMCScan_Q0vsThetavsE->GetNbinsY(); y++) { double total = 0.; for (int z = 0; z < fMCScan_Q0vsThetavsE->GetNbinsZ(); z++) { double zwidth = fMCScan_Q0vsThetavsE->GetZaxis()->GetBinWidth(z + 1); total += fMCScan_Q0vsThetavsE->GetBinContent(x + 1, y + 1, z + 1) * zwidth; } fMCScan_Q0vsTheta->SetBinContent(x + 1, y + 1, total); } } // Project into fMCScan_Q0vsE for (int x = 0; x < fMCScan_Q0vsThetavsE->GetNbinsX(); x++) { for (int z = 0; z < fMCScan_Q0vsThetavsE->GetNbinsZ(); z++) { double total = 0.; for (int y = 0; y < fMCScan_Q0vsThetavsE->GetNbinsY(); y++) { double ywidth = fMCScan_Q0vsThetavsE->GetYaxis()->GetBinWidth(y + 1); total += fMCScan_Q0vsThetavsE->GetBinContent(x + 1, y + 1, z + 1) * ywidth; } fMCScan_Q0vsE->SetBinContent(x + 1, z + 1, total); } } // Project fMCScan_Q0vsTheta into MC Hist for (int x = 0; x < fMCScan_Q0vsTheta->GetNbinsX(); x++) { double total = 0.; for (int y = 0; y < fMCScan_Q0vsTheta->GetNbinsY(); y++) { double ywidth = fMCScan_Q0vsTheta->GetYaxis()->GetBinWidth(y + 1); total += fMCScan_Q0vsTheta->GetBinContent(x + 1, y + 1); } double xwidth = fMCScan_Q0vsTheta->GetXaxis()->GetBinWidth(x + 1); fMCHist->SetBinContent(x + 1, total * xwidth); } fMCHist->Scale(fDataHist->Integral() / fMCHist->Integral()); */ } //******************************************************************** int ElectronScattering_DurhamData::GetNDOF() { //******************************************************************** return fDataGraph->GetN(); } void ElectronScattering_DurhamData::Write(std::string drawOpts) { Measurement1D::Write(drawOpts); fMCScan_Q0vsThetavsE->Write(); fMCScan_Q0vsTheta->Write(); fMCScan_Q0vsE->Write(); fDataGraph->Write(); } double ElectronScattering_DurhamData::GetLikelihood() { return 0.0; } void ElectronScattering_DurhamData::SetFitOptions(std::string opt) { return; } TH1D* ElectronScattering_DurhamData::GetMCHistogram(void) { return fMCHist; } TH1D* ElectronScattering_DurhamData::GetDataHistogram(void) { return fDataHist; } diff --git a/src/FCN/JointFCN.cxx b/src/FCN/JointFCN.cxx index a19273c..64d00b6 100755 --- a/src/FCN/JointFCN.cxx +++ b/src/FCN/JointFCN.cxx @@ -1,1123 +1,1123 @@ #include "JointFCN.h" #include "FitUtils.h" #include //*************************************************** JointFCN::JointFCN(TFile *outfile) { //*************************************************** fOutputDir = gDirectory; if (outfile) Config::Get().out = outfile; std::vector samplekeys = Config::QueryKeys("sample"); LoadSamples(samplekeys); std::vector covarkeys = Config::QueryKeys("covar"); LoadPulls(covarkeys); fCurIter = 0; fMCFilled = false; fIterationTree = false; fDialVals = NULL; fNDials = 0; fUsingEventManager = FitPar::Config().GetParB("EventManager"); fOutputDir->cd(); } //*************************************************** JointFCN::JointFCN(std::vector samplekeys, TFile *outfile) { //*************************************************** fOutputDir = gDirectory; if (outfile) Config::Get().out = outfile; LoadSamples(samplekeys); fCurIter = 0; fMCFilled = false; fOutputDir->cd(); fIterationTree = false; fDialVals = NULL; fNDials = 0; fUsingEventManager = FitPar::Config().GetParB("EventManager"); fOutputDir->cd(); } //*************************************************** JointFCN::~JointFCN() { //*************************************************** // Delete Samples for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end(); iter++) { MeasurementBase *exp = *iter; delete exp; } for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) { ParamPull *pull = *iter; delete pull; } // Sort Tree if (fIterationTree) DestroyIterationTree(); if (fDialVals) delete fDialVals; if (fSampleLikes) delete fSampleLikes; }; //*************************************************** void JointFCN::CreateIterationTree(std::string name, FitWeight *rw) { //*************************************************** - QLOG(FIT, " Creating new iteration container! "); + NUIS_LOG(FIT, " Creating new iteration container! "); DestroyIterationTree(); fIterationTreeName = name; // Add sample likelihoods and ndof for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end(); iter++) { MeasurementBase *exp = *iter; std::string name = exp->GetName(); std::string liketag = name + "_likelihood"; fNameValues.push_back(liketag); fCurrentValues.push_back(0.0); std::string ndoftag = name + "_ndof"; fNameValues.push_back(ndoftag); fCurrentValues.push_back(0.0); } // Add Pull terms for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) { ParamPull *pull = *iter; std::string name = pull->GetName(); std::string liketag = name + "_likelihood"; fNameValues.push_back(liketag); fCurrentValues.push_back(0.0); std::string ndoftag = name + "_ndof"; fNameValues.push_back(ndoftag); fCurrentValues.push_back(0.0); } // Add Likelihoods fNameValues.push_back("total_likelihood"); fCurrentValues.push_back(0.0); fNameValues.push_back("total_ndof"); fCurrentValues.push_back(0.0); // Setup Containers fSampleN = fSamples.size() + fPulls.size(); fSampleLikes = new double[fSampleN]; fSampleNDOF = new int[fSampleN]; // Add Dials std::vector dials = rw->GetDialNames(); for (size_t i = 0; i < dials.size(); i++) { fNameValues.push_back(dials[i]); fCurrentValues.push_back(0.0); } fNDials = dials.size(); fDialVals = new double[fNDials]; // Set IterationTree Flag fIterationTree = true; } //*************************************************** void JointFCN::DestroyIterationTree() { //*************************************************** fIterationCount.clear(); fCurrentValues.clear(); fNameValues.clear(); fIterationValues.clear(); } //*************************************************** void JointFCN::WriteIterationTree() { //*************************************************** - QLOG(FIT, "Writing iteration tree"); + NUIS_LOG(FIT, "Writing iteration tree"); // Make a new TTree TTree *itree = new TTree(fIterationTreeName.c_str(), fIterationTreeName.c_str()); double *vals = new double[fNameValues.size()]; int count = 0; itree->Branch("iteration", &count, "Iteration/I"); for (size_t i = 0; i < fNameValues.size(); i++) { itree->Branch(fNameValues[i].c_str(), &vals[i], (fNameValues[i] + "/D").c_str()); } // Fill Iterations for (size_t i = 0; i < fIterationValues.size(); i++) { std::vector itervals = fIterationValues[i]; // Fill iteration state count = fIterationCount[i]; for (size_t j = 0; j < itervals.size(); j++) { vals[j] = itervals[j]; } // Save to TTree itree->Fill(); } // Write to file itree->Write(); } //*************************************************** void JointFCN::FillIterationTree(FitWeight *rw) { //*************************************************** // Loop over samples count int count = 0; for (int i = 0; i < fSampleN; i++) { fCurrentValues[count++] = fSampleLikes[i]; fCurrentValues[count++] = double(fSampleNDOF[i]); } // Fill Totals fCurrentValues[count++] = fLikelihood; fCurrentValues[count++] = double(fNDOF); // Loop Over Parameter Counts rw->GetAllDials(fDialVals, fNDials); for (int i = 0; i < fNDials; i++) { fCurrentValues[count++] = double(fDialVals[i]); } // Push Back Into Container fIterationCount.push_back(fCurIter); fIterationValues.push_back(fCurrentValues); } //*************************************************** double JointFCN::DoEval(const double *x) { //*************************************************** // WEIGHT ENGINE fDialChanged = FitBase::GetRW()->HasRWDialChanged(x); FitBase::GetRW()->UpdateWeightEngine(x); if (fDialChanged) { FitBase::GetRW()->Reconfigure(); FitBase::EvtManager().ResetWeightFlags(); } if (LOG_LEVEL(REC)) { FitBase::GetRW()->Print(); } // SORT SAMPLES ReconfigureSamples(); // GET TEST STAT fLikelihood = GetLikelihood(); fNDOF = GetNDOF(); // PRINT PROGRESS - QLOG(FIT, "Current Stat (iter. " << this->fCurIter << ") = " << fLikelihood); + NUIS_LOG(FIT, "Current Stat (iter. " << this->fCurIter << ") = " << fLikelihood); // UPDATE TREE if (fIterationTree) FillIterationTree(FitBase::GetRW()); return fLikelihood; } //*************************************************** int JointFCN::GetNDOF() { //*************************************************** int totaldof = 0; int count = 0; // Total number of Free bins in each MC prediction for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end(); iter++) { MeasurementBase *exp = *iter; int dof = exp->GetNDOF(); // Save Seperate DOF if (fIterationTree) { fSampleNDOF[count] = dof; } // Add to total totaldof += dof; count++; } // Loop over pulls for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) { ParamPull *pull = *iter; double dof = pull->GetLikelihood(); // Save seperate DOF if (fIterationTree) { fSampleNDOF[count] = dof; } // Add to total totaldof += dof; count++; } // Set Data Variable if (fIterationTree) { fSampleNDOF[count] = totaldof; } return totaldof; } //*************************************************** double JointFCN::GetLikelihood() { //*************************************************** - QLOG(MIN, std::left << std::setw(43) << "Getting likelihoods..." + NUIS_LOG(MIN, std::left << std::setw(43) << "Getting likelihoods..." << " : " << "-2logL"); // Loop and add up likelihoods in an uncorrelated way double like = 0.0; int count = 0; for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end(); iter++) { MeasurementBase *exp = *iter; double newlike = exp->GetLikelihood(); int ndof = exp->GetNDOF(); // Save seperate likelihoods if (fIterationTree) { fSampleLikes[count] = newlike; } - QLOG(MIN, "-> " << std::left << std::setw(40) << exp->GetName() << " : " + NUIS_LOG(MIN, "-> " << std::left << std::setw(40) << exp->GetName() << " : " << newlike << "/" << ndof); // Add Weight Scaling // like *= FitBase::GetRW()->GetSampleLikelihoodWeight(exp->GetName()); // Add to total like += newlike; count++; } // Loop over pulls for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) { ParamPull *pull = *iter; double newlike = pull->GetLikelihood(); // Save seperate likelihoods if (fIterationTree) { fSampleLikes[count] = newlike; } // Add to total like += newlike; count++; } // Set Data Variable fLikelihood = like; if (fIterationTree) { fSampleLikes[count] = fLikelihood; } return like; }; void JointFCN::LoadSamples(std::vector samplekeys) { - QLOG(MIN, "Loading Samples : " << samplekeys.size()); + NUIS_LOG(MIN, "Loading Samples : " << samplekeys.size()); for (size_t i = 0; i < samplekeys.size(); i++) { nuiskey key = samplekeys[i]; // Get Sample Options std::string samplename = key.GetS("name"); std::string samplefile = key.GetS("input"); std::string sampletype = key.GetS("type"); std::string fakeData = ""; - QLOG(MIN, "Loading Sample : " << samplename); + NUIS_LOG(MIN, "Loading Sample : " << samplename); fOutputDir->cd(); MeasurementBase *NewLoadedSample = SampleUtils::CreateSample(key); if (!NewLoadedSample) { - QERROR(FTL, "Could not load sample provided: " << samplename); - QERROR(FTL, "Check spelling with that in src/FCN/SampleList.cxx"); + NUIS_ERR(FTL, "Could not load sample provided: " << samplename); + NUIS_ERR(FTL, "Check spelling with that in src/FCN/SampleList.cxx"); throw; } else { fSamples.push_back(NewLoadedSample); } } } //*************************************************** void JointFCN::LoadPulls(std::vector pullkeys) { //*************************************************** for (size_t i = 0; i < pullkeys.size(); i++) { nuiskey key = pullkeys[i]; std::string pullname = key.GetS("name"); std::string pullfile = key.GetS("input"); std::string pulltype = key.GetS("type"); fOutputDir->cd(); fPulls.push_back(new ParamPull(pullname, pullfile, pulltype)); } } //*************************************************** void JointFCN::ReconfigureSamples(bool fullconfig) { //*************************************************** int starttime = time(NULL); - QLOG(REC, "Starting Reconfigure iter. " << this->fCurIter); + NUIS_LOG(REC, "Starting Reconfigure iter. " << this->fCurIter); // std::cout << fUsingEventManager << " " << fullconfig << " " << fMCFilled << // std::endl; // Event Manager Reconf if (fUsingEventManager) { if (!fullconfig && fMCFilled) ReconfigureFastUsingManager(); else ReconfigureUsingManager(); } else { // Loop over all Measurement Classes for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end(); iter++) { MeasurementBase *exp = *iter; // If RW Either do signal or full reconfigure. if (fDialChanged or !fMCFilled or fullconfig) { if (!fullconfig and fMCFilled) exp->ReconfigureFast(); else exp->Reconfigure(); // If RW Not needed just do normalisation } else { exp->Renormalise(); } } } // Loop over pulls and update for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) { ParamPull *pull = *iter; pull->Reconfigure(); } fMCFilled = true; - QLOG(MIN, "Finished Reconfigure iter. " << fCurIter << " in " + NUIS_LOG(MIN, "Finished Reconfigure iter. " << fCurIter << " in " << time(NULL) - starttime << "s"); fCurIter++; } //*************************************************** void JointFCN::ReconfigureSignal() { //*************************************************** ReconfigureSamples(false); } //*************************************************** void JointFCN::ReconfigureAllEvents() { //*************************************************** FitBase::GetRW()->Reconfigure(); FitBase::EvtManager().ResetWeightFlags(); ReconfigureSamples(true); } std::vector JointFCN::GetInputList() { std::vector InputList; fIsAllSplines = true; MeasListConstIter iterSam = fSamples.begin(); for (; iterSam != fSamples.end(); iterSam++) { MeasurementBase *exp = (*iterSam); std::vector subsamples = exp->GetSubSamples(); for (size_t i = 0; i < subsamples.size(); i++) { InputHandlerBase *inp = subsamples[i]->GetInput(); if (std::find(InputList.begin(), InputList.end(), inp) == InputList.end()) { if (subsamples[i]->GetInput()->GetType() != kSPLINEPARAMETER) fIsAllSplines = false; InputList.push_back(subsamples[i]->GetInput()); } } } return InputList; } std::vector JointFCN::GetSubSampleList() { std::vector SampleList; MeasListConstIter iterSam = fSamples.begin(); for (; iterSam != fSamples.end(); iterSam++) { MeasurementBase *exp = (*iterSam); std::vector subsamples = exp->GetSubSamples(); for (size_t i = 0; i < subsamples.size(); i++) { SampleList.push_back(subsamples[i]); } } return SampleList; } //*************************************************** void JointFCN::ReconfigureUsingManager() { //*************************************************** // 'Slow' Event Manager Reconfigure - QLOG(REC, "Event Manager Reconfigure"); + NUIS_LOG(REC, "Event Manager Reconfigure"); int timestart = time(NULL); // Reset all samples MeasListConstIter iterSam = fSamples.begin(); for (; iterSam != fSamples.end(); iterSam++) { MeasurementBase *exp = (*iterSam); exp->ResetAll(); } // If we are siving signal, reset all containers. bool savesignal = (FitPar::Config().GetParB("SignalReconfigures")); if (savesignal) { // Reset all of our event signal vectors fSignalEventBoxes.clear(); fSignalEventFlags.clear(); fSampleSignalFlags.clear(); fSignalEventSplines.clear(); } // Make sure we have a list of inputs if (fInputList.empty()) { fInputList = GetInputList(); fSubSampleList = GetSubSampleList(); } // If all inputs are splines make sure the readers are told // they need to be reconfigured. std::vector::iterator inp_iter = fInputList.begin(); if (fIsAllSplines) { for (; inp_iter != fInputList.end(); inp_iter++) { InputHandlerBase *curinput = (*inp_iter); // Tell reader in each BaseEvent it needs a Reconfigure next weight calc. BaseFitEvt *curevent = curinput->FirstBaseEvent(); if (curevent->fSplineRead) { curevent->fSplineRead->SetNeedsReconfigure(true); } } } // MAIN INPUT LOOP ==================== int fillcount = 0; int inputcount = 0; inp_iter = fInputList.begin(); // Loop over each input in manager for (; inp_iter != fInputList.end(); inp_iter++) { InputHandlerBase *curinput = (*inp_iter); // Get event information FitEvent *curevent = curinput->FirstNuisanceEvent(); curinput->CreateCache(); int i = 0; int nevents = curinput->GetNEvents(); int countwidth = nevents / 10; // Start event loop iterating until we get a NULL pointer. while (curevent) { // Get Event Weight // The reweighting weight curevent->RWWeight = FitBase::GetRW()->CalcWeight(curevent); // The Custom weight and reweight curevent->Weight = curevent->RWWeight * curevent->InputWeight * curevent->CustomWeight; if (LOGGING(REC)) { if (countwidth && (i % countwidth == 0)) { - QLOG(REC, curinput->GetName() + NUIS_LOG(REC, curinput->GetName() << " : Processed " << i << " events. [M, W] = [" << curevent->Mode << ", " << curevent->Weight << "]"); } } // Setup flag for if signal found in at least one sample bool foundsignal = false; // Create a new signal bitset for this event std::vector signalbitset(fSubSampleList.size()); // Create a new signal box vector for this event std::vector signalboxes; // Start measurement iterator size_t measitercount = 0; std::vector::iterator meas_iter = fSubSampleList.begin(); // Loop over all subsamples (sub in JointMeas) for (; meas_iter != fSubSampleList.end(); meas_iter++) { MeasurementBase *curmeas = (*meas_iter); // Compare input pointers, to current input, skip if not. // Pointer tells us if it matches without doing ID checks. if (curinput != curmeas->GetInput()) { if (savesignal) { // Set bit to 0 as definitely not signal signalbitset[measitercount] = 0; } // Count up what measurement we are on. measitercount++; // Skip sample as input not signal. continue; } // Fill events for matching inputs. MeasurementVariableBox *box = curmeas->FillVariableBox(curevent); bool signal = curmeas->isSignal(curevent); curmeas->SetSignal(signal); curmeas->FillHistograms(curevent->Weight); // If its Signal tally up fills if (signal) { fillcount++; } // If we are saving signal/splines fill the bitset if (savesignal) { signalbitset[measitercount] = signal; } // If signal save a clone of the event box for use later. if (savesignal and signal) { foundsignal = true; signalboxes.push_back(box->CloneSignalBox()); } // Keep track of Measurement we are on. measitercount++; } // Once we've filled the measurements, if saving signal // push back if any sample flagged this event as signal if (savesignal) { fSignalEventFlags.push_back(foundsignal); } // Save the vector of signal boxes for this event if (savesignal && foundsignal) { fSignalEventBoxes.push_back(signalboxes); fSampleSignalFlags.push_back(signalbitset); } // If all inputs are splines we can save the spline coefficients // for fast in memory reconfigures later. if (fIsAllSplines && savesignal && foundsignal) { // Make temp vector to push back with std::vector coeff; for (size_t l = 0; l < (UInt_t)curevent->fSplineRead->GetNPar(); l++) { coeff.push_back(curevent->fSplineCoeff[l]); } // Push back to signal event splines. Kept in sync with // fSignalEventBoxes size. // int splinecount = fSignalEventSplines.size(); fSignalEventSplines.push_back(coeff); // if (splinecount % 1000 == 0) { // std::cout << "Pushed Back Coeff " << splinecount << " : "; // for (size_t l = 0; l < fSignalEventSplines[splinecount].size(); l++) // { // std::cout << " " << fSignalEventSplines[splinecount][l]; // } // std::cout << std::endl; // } } // Clean up vectors once done with this event signalboxes.clear(); signalbitset.clear(); // Iterate to the next event. curevent = curinput->NextNuisanceEvent(); i++; } // curinput->RemoveCache(); // Keep track of what input we are on. inputcount++; } // End of Event Loop =============================== // Now event loop is finished loop over all Measurements // Converting Binned events to XSec Distributions iterSam = fSamples.begin(); for (; iterSam != fSamples.end(); iterSam++) { MeasurementBase *exp = (*iterSam); exp->ConvertEventRates(); } // Print out statements on approximate memory usage for profiling. - QLOG(REC, "Filled " << fillcount << " signal events."); + NUIS_LOG(REC, "Filled " << fillcount << " signal events."); if (savesignal) { int mem = ( // sizeof(fSignalEventBoxes) + // fSignalEventBoxes.size() * sizeof(fSignalEventBoxes.at(0)) + sizeof(MeasurementVariableBox1D) * fillcount) * 1E-6; - QLOG(REC, " -> Saved " << fillcount << " signal boxes for faster access. (~" + NUIS_LOG(REC, " -> Saved " << fillcount << " signal boxes for faster access. (~" << mem << " MB)"); if (fIsAllSplines and !fSignalEventSplines.empty()) { int splmem = sizeof(float) * fSignalEventSplines.size() * fSignalEventSplines[0].size() * 1E-6; - QLOG(REC, " -> Saved " << fillcount << " " << fSignalEventSplines.size() + NUIS_LOG(REC, " -> Saved " << fillcount << " " << fSignalEventSplines.size() << " spline sets into memory. (~" << splmem << " MB)"); } } - QLOG(REC, + NUIS_LOG(REC, "Time taken ReconfigureUsingManager() : " << time(NULL) - timestart); // Check SignalReconfigures works for all samples if (savesignal) { double likefull = GetLikelihood(); ReconfigureFastUsingManager(); double likefast = GetLikelihood(); if (fabs(likefull - likefast) > 0.0001) { - QERROR(FTL, "Fast and Full Likelihoods DIFFER! : " << likefull << " : " + NUIS_ERR(FTL, "Fast and Full Likelihoods DIFFER! : " << likefull << " : " << likefast); - QERROR(FTL, "This means some samples you are using are not setup to use " + NUIS_ERR(FTL, "This means some samples you are using are not setup to use " "SignalReconfigures=1"); - QERROR(FTL, "Please turn OFF signal reconfigures."); + NUIS_ERR(FTL, "Please turn OFF signal reconfigures."); throw; } else { - QLOG(FIT, + NUIS_LOG(FIT, "Likelihoods for FULL and FAST match. Will use FAST next time."); } } }; //*************************************************** void JointFCN::ReconfigureFastUsingManager() { //*************************************************** - QLOG(FIT, " -> Doing FAST using manager"); + NUIS_LOG(FIT, " -> Doing FAST using manager"); // Get Start time for profilling int timestart = time(NULL); // Reset all samples MeasListConstIter iterSam = fSamples.begin(); for (; iterSam != fSamples.end(); iterSam++) { MeasurementBase *exp = (*iterSam); exp->ResetAll(); } // Check for saved variables if not do a full reconfigure. if (fSignalEventFlags.empty()) { - QERROR(WRN, "Signal Flags Empty! Using normal manager."); + NUIS_ERR(WRN, "Signal Flags Empty! Using normal manager."); ReconfigureUsingManager(); return; } bool fFillNuisanceEvent = FitPar::Config().GetParB("FullEventOnSignalReconfigure"); // Setup fast vector iterators. std::vector::iterator inpsig_iter = fSignalEventFlags.begin(); std::vector>::iterator box_iter = fSignalEventBoxes.begin(); std::vector>::iterator spline_iter = fSignalEventSplines.begin(); std::vector>::iterator samsig_iter = fSampleSignalFlags.begin(); int splinecount = 0; // Setup stuff for logging int fillcount = 0; // This is just the total number of events // int nevents = fSignalEventFlags.size(); // This is the number of events that are signal int nevents = fSignalEventBoxes.size(); int countwidth = nevents / 10; // If All Splines tell splines they need a reconfigure. std::vector::iterator inp_iter = fInputList.begin(); if (fIsAllSplines) { - QLOG(REC, "All Spline Inputs so using fast spline loop."); + NUIS_LOG(REC, "All Spline Inputs so using fast spline loop."); for (; inp_iter != fInputList.end(); inp_iter++) { InputHandlerBase *curinput = (*inp_iter); // Tell each fSplineRead in BaseFitEvent to reconf next weight calc BaseFitEvt *curevent = curinput->FirstBaseEvent(); if (curevent->fSplineRead) curevent->fSplineRead->SetNeedsReconfigure(true); } } // Loop over all possible spline inputs double *coreeventweights = new double[fSignalEventBoxes.size()]; splinecount = 0; inp_iter = fInputList.begin(); inpsig_iter = fSignalEventFlags.begin(); spline_iter = fSignalEventSplines.begin(); // Loop over all signal flags // For each valid signal flag add one to splinecount // Get Splines from that count and add to weight // Add splinecount int sigcount = 0; // #pragma omp parallel for shared(splinecount,sigcount) for (uint iinput = 0; iinput < fInputList.size(); iinput++) { InputHandlerBase *curinput = fInputList[iinput]; BaseFitEvt *curevent = curinput->FirstBaseEvent(); // Loop over the events in each input for (int i = 0; i < curinput->GetNEvents(); i++) { double rwweight = 0.0; // If the event is a signal event if (fSignalEventFlags[sigcount]) { // Get Event Info if (!fIsAllSplines) { if (fFillNuisanceEvent) { curevent = curinput->GetNuisanceEvent(i); } else { curevent = curinput->GetBaseEvent(i); } } else { curevent->fSplineCoeff = &fSignalEventSplines[splinecount][0]; } curevent->RWWeight = FitBase::GetRW()->CalcWeight(curevent); curevent->Weight = curevent->RWWeight * curevent->InputWeight * curevent->CustomWeight; rwweight = curevent->Weight; coreeventweights[splinecount] = rwweight; if (countwidth && ((splinecount % countwidth) == 0)) { - QLOG(REC, curinput->GetName() + NUIS_LOG(REC, curinput->GetName() << " : Processed " << i << " events. W = " << curevent->Weight << std::endl); } // #pragma omp atomic splinecount++; } // #pragma omp atomic sigcount++; } } - QLOG(SAM, "Processed event weights."); + NUIS_LOG(SAM, "Processed event weights."); // #pragma omp barrier // Reset Iterators inpsig_iter = fSignalEventFlags.begin(); spline_iter = fSignalEventSplines.begin(); box_iter = fSignalEventBoxes.begin(); samsig_iter = fSampleSignalFlags.begin(); int nsplineweights = splinecount; splinecount = 0; // Start of Fast Event Loop ============================ // Start input iterators // Loop over number of inputs for (int ispline = 0; ispline < nsplineweights; ispline++) { double rwweight = coreeventweights[ispline]; // Get iterators for this event std::vector::iterator subsamsig_iter = (*samsig_iter).begin(); std::vector::iterator subbox_iter = (*box_iter).begin(); // Loop over all sub measurements. std::vector::iterator meas_iter = fSubSampleList.begin(); for (; meas_iter != fSubSampleList.end(); meas_iter++, subsamsig_iter++) { MeasurementBase *curmeas = (*meas_iter); // If event flagged as signal for this sample fill from the box. if (*subsamsig_iter) { curmeas->SetSignal(true); curmeas->FillHistogramsFromBox((*subbox_iter), rwweight); // Move onto next box if there is one. subbox_iter++; fillcount++; } } if (ispline % countwidth == 0) { - QLOG(REC, "Filled " << ispline << " sample weights."); + NUIS_LOG(REC, "Filled " << ispline << " sample weights."); } // Iterate over the main signal event containers. samsig_iter++; box_iter++; spline_iter++; splinecount++; } // End of Fast Event Loop =================== - QLOG(SAM, "Filled sample distributions."); + NUIS_LOG(SAM, "Filled sample distributions."); // Now loop over all Measurements // Convert Binned events iterSam = fSamples.begin(); for (; iterSam != fSamples.end(); iterSam++) { MeasurementBase *exp = (*iterSam); exp->ConvertEventRates(); } // Cleanup coreeventweights delete coreeventweights; // Print some reconfigure profiling. - QLOG(REC, "Filled " << fillcount << " signal events."); - QLOG(REC, + NUIS_LOG(REC, "Filled " << fillcount << " signal events."); + NUIS_LOG(REC, "Time taken ReconfigureFastUsingManager() : " << time(NULL) - timestart); } //*************************************************** void JointFCN::Write() { //*************************************************** // Save a likelihood/ndof plot - QLOG(MIN, "Writing likelihood plot..."); + NUIS_LOG(MIN, "Writing likelihood plot..."); std::vector likes; std::vector ndofs; std::vector names; for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end(); iter++) { MeasurementBase *exp = *iter; double like = exp->GetLikelihood(); double ndof = exp->GetNDOF(); std::string name = exp->GetName(); likes.push_back(like); ndofs.push_back(ndof); names.push_back(name); } if (likes.size()) { TH1D likehist = TH1D("likelihood_hist", "likelihood_hist", likes.size(), 0.0, double(likes.size())); TH1D ndofhist = TH1D("ndof_hist", "ndof_hist", ndofs.size(), 0.0, double(ndofs.size())); TH1D divhist = TH1D("likedivndof_hist", "likedivndof_hist", likes.size(), 0.0, double(likes.size())); for (int i = 0; i < likehist.GetNbinsX(); i++) { likehist.SetBinContent(i + 1, likes[i]); ndofhist.SetBinContent(i + 1, ndofs[i]); if (ndofs[i] != 0.0) { divhist.SetBinContent(i + 1, likes[i] / ndofs[i]); } likehist.GetXaxis()->SetBinLabel(i + 1, names[i].c_str()); ndofhist.GetXaxis()->SetBinLabel(i + 1, names[i].c_str()); divhist.GetXaxis()->SetBinLabel(i + 1, names[i].c_str()); } likehist.Write(); ndofhist.Write(); divhist.Write(); } // Loop over individual experiments and call Write - QLOG(MIN, "Writing each of the data classes..."); + NUIS_LOG(MIN, "Writing each of the data classes..."); for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end(); iter++) { MeasurementBase *exp = *iter; exp->Write(); } // Save Pull Terms for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) { ParamPull *pull = *iter; pull->Write(); } if (FitPar::Config().GetParB("EventManager")) { // Get list of inputs std::map fInputs = FitBase::EvtManager().GetInputs(); std::map::const_iterator iterInp; for (iterInp = fInputs.begin(); iterInp != fInputs.end(); iterInp++) { InputHandlerBase *input = (iterInp->second); input->GetFluxHistogram()->Write(); input->GetXSecHistogram()->Write(); input->GetEventHistogram()->Write(); } } }; //*************************************************** void JointFCN::SetFakeData(std::string fakeinput) { //*************************************************** - QLOG(MIN, "Setting fake data from " << fakeinput); + NUIS_LOG(MIN, "Setting fake data from " << fakeinput); for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end(); iter++) { MeasurementBase *exp = *iter; exp->SetFakeDataValues(fakeinput); } return; } //*************************************************** void JointFCN::ThrowDataToy() { //*************************************************** for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end(); iter++) { MeasurementBase *exp = *iter; exp->ThrowDataToy(); } return; } //*************************************************** std::vector JointFCN::GetAllNames() { //*************************************************** // Vect of all likelihoods and total std::vector namevect; // Loop over samples first for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end(); iter++) { MeasurementBase *exp = *iter; // Get Likelihoods and push to vector namevect.push_back(exp->GetName()); } // Loop over pulls second for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) { ParamPull *pull = *iter; // Push back to vector namevect.push_back(pull->GetName()); } // Finally add the total namevect.push_back("total"); return namevect; } //*************************************************** std::vector JointFCN::GetAllLikelihoods() { //*************************************************** // Vect of all likelihoods and total std::vector likevect; double total_likelihood = 0.0; - QLOG(MIN, "Likelihoods : "); + NUIS_LOG(MIN, "Likelihoods : "); // Loop over samples first for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end(); iter++) { MeasurementBase *exp = *iter; // Get Likelihoods and push to vector double singlelike = exp->GetLikelihood(); likevect.push_back(singlelike); total_likelihood += singlelike; // Print Out - QLOG(MIN, "-> " << std::left << std::setw(40) << exp->GetName() << " : " + NUIS_LOG(MIN, "-> " << std::left << std::setw(40) << exp->GetName() << " : " << singlelike); } // Loop over pulls second for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) { ParamPull *pull = *iter; // Push back to vector double singlelike = pull->GetLikelihood(); likevect.push_back(singlelike); total_likelihood += singlelike; // Print Out - QLOG(MIN, "-> " << std::left << std::setw(40) << pull->GetName() << " : " + NUIS_LOG(MIN, "-> " << std::left << std::setw(40) << pull->GetName() << " : " << singlelike); } // Finally add the total likelihood likevect.push_back(total_likelihood); return likevect; } //*************************************************** std::vector JointFCN::GetAllNDOF() { //*************************************************** // Vect of all ndof and total std::vector ndofvect; int total_ndof = 0; // Loop over samples first for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end(); iter++) { MeasurementBase *exp = *iter; // Get Likelihoods and push to vector int singlendof = exp->GetNDOF(); ndofvect.push_back(singlendof); total_ndof += singlendof; } // Loop over pulls second for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) { ParamPull *pull = *iter; // Push back to vector int singlendof = pull->GetNDOF(); ndofvect.push_back(singlendof); total_ndof += singlendof; } // Finally add the total ndof ndofvect.push_back(total_ndof); return ndofvect; } diff --git a/src/FCN/MinimizerFCN.h b/src/FCN/MinimizerFCN.h index 0114fec..c86fa75 100755 --- a/src/FCN/MinimizerFCN.h +++ b/src/FCN/MinimizerFCN.h @@ -1,81 +1,81 @@ #ifndef _MINIMIZER_FCN_H_ #define _MINIMIZER_FCN_H_ /*! * \addtogroup FCN * @{ */ #include #include #include "FitLogger.h" #include "JointFCN.h" //! Wrapper for JointFCN to make ROOT minimization behave sensibly. class MinimizerFCN{ public: // Empty Construction MinimizerFCN(){ fFCN = NULL; } // Construct from function MinimizerFCN(JointFCN* f){ SetFCN(f); }; // Destroy (Doesn't delete FCN) ~MinimizerFCN(){ }; /* inline double Up() const { return 1.; } */ // Set FCN inline void SetFCN(JointFCN* f) { fFCN = f; }; // Get FCN inline JointFCN* GetFCN() const { return fFCN; }; // Wrapper for jointFCN Eval inline double DoEval(const double *x) const { if (!fFCN){ - QERROR(FTL,"No FCN Found in MinimizerFCN!"); - QTHROW("Exiting!"); + NUIS_ERR(FTL,"No FCN Found in MinimizerFCN!"); + NUIS_ABORT("Exiting!"); } return fFCN->DoEval(x); }; // Func Operator for vectors inline double operator() (const std::vector & x) const { double* x_array = new double[x.size()]; return this->DoEval(x_array); }; // Func Operator for arrays inline double operator() (const double *x) const { return this->DoEval(x); }; private: JointFCN* fFCN; }; /*! @} */ #endif // _MINIMIZER_FCN_H_ diff --git a/src/FCN/SampleList.cxx b/src/FCN/SampleList.cxx index 176f692..ff323b7 100644 --- a/src/FCN/SampleList.cxx +++ b/src/FCN/SampleList.cxx @@ -1,1440 +1,1440 @@ #include "SampleList.h" #ifndef __NO_ANL__ #include "ANL_CCQE_Evt_1DQ2_nu.h" #include "ANL_CCQE_XSec_1DEnu_nu.h" // ANL CC1ppip #include "ANL_CC1ppip_Evt_1DQ2_nu.h" #include "ANL_CC1ppip_Evt_1DcosmuStar_nu.h" #include "ANL_CC1ppip_Evt_1DcosmuStar_nu.h" #include "ANL_CC1ppip_Evt_1DcosthAdler_nu.h" #include "ANL_CC1ppip_Evt_1Dphi_nu.h" #include "ANL_CC1ppip_Evt_1Dppi_nu.h" #include "ANL_CC1ppip_Evt_1Dthpr_nu.h" #include "ANL_CC1ppip_XSec_1DEnu_nu.h" #include "ANL_CC1ppip_XSec_1DQ2_nu.h" // ANL CC1npip #include "ANL_CC1npip_Evt_1DQ2_nu.h" #include "ANL_CC1npip_Evt_1DcosmuStar_nu.h" #include "ANL_CC1npip_Evt_1Dppi_nu.h" #include "ANL_CC1npip_XSec_1DEnu_nu.h" // ANL CC1pi0 #include "ANL_CC1pi0_Evt_1DQ2_nu.h" #include "ANL_CC1pi0_Evt_1DcosmuStar_nu.h" #include "ANL_CC1pi0_XSec_1DEnu_nu.h" // ANL NC1npip (mm, exotic!) #include "ANL_NC1npip_Evt_1Dppi_nu.h" // ANL NC1ppim (mm, exotic!) #include "ANL_NC1ppim_Evt_1DcosmuStar_nu.h" #include "ANL_NC1ppim_XSec_1DEnu_nu.h" // ANL CC2pi 1pim1pip (mm, even more exotic!) #include "ANL_CC2pi_1pim1pip_Evt_1Dpmu_nu.h" #include "ANL_CC2pi_1pim1pip_Evt_1Dppim_nu.h" #include "ANL_CC2pi_1pim1pip_Evt_1Dppip_nu.h" #include "ANL_CC2pi_1pim1pip_Evt_1Dpprot_nu.h" #include "ANL_CC2pi_1pim1pip_XSec_1DEnu_nu.h" // ANL CC2pi 1pip1pip (mm, even more exotic!) #include "ANL_CC2pi_1pip1pip_Evt_1Dpmu_nu.h" #include "ANL_CC2pi_1pip1pip_Evt_1Dpneut_nu.h" #include "ANL_CC2pi_1pip1pip_Evt_1DppipHigh_nu.h" #include "ANL_CC2pi_1pip1pip_Evt_1DppipLow_nu.h" #include "ANL_CC2pi_1pip1pip_XSec_1DEnu_nu.h" // ANL CC2pi 1pip1pi0 (mm, even more exotic!) #include "ANL_CC2pi_1pip1pi0_Evt_1Dpmu_nu.h" #include "ANL_CC2pi_1pip1pi0_Evt_1Dppi0_nu.h" #include "ANL_CC2pi_1pip1pi0_Evt_1Dppip_nu.h" #include "ANL_CC2pi_1pip1pi0_Evt_1Dpprot_nu.h" #include "ANL_CC2pi_1pip1pi0_XSec_1DEnu_nu.h" #endif #ifndef __NO_ArgoNeuT__ // ArgoNeuT CC1Pi #include "ArgoNeuT_CC1Pi_XSec_1Dpmu_nu.h" #include "ArgoNeuT_CC1Pi_XSec_1Dthetamu_nu.h" #include "ArgoNeuT_CC1Pi_XSec_1Dthetapi_nu.h" #include "ArgoNeuT_CC1Pi_XSec_1Dthetamupi_nu.h" #include "ArgoNeuT_CC1Pi_XSec_1Dpmu_antinu.h" #include "ArgoNeuT_CC1Pi_XSec_1Dthetamu_antinu.h" #include "ArgoNeuT_CC1Pi_XSec_1Dthetapi_antinu.h" #include "ArgoNeuT_CC1Pi_XSec_1Dthetamupi_antinu.h" // ArgoNeuT CC-inclusive #include "ArgoNeuT_CCInc_XSec_1Dpmu_antinu.h" #include "ArgoNeuT_CCInc_XSec_1Dpmu_nu.h" #include "ArgoNeuT_CCInc_XSec_1Dthetamu_antinu.h" #include "ArgoNeuT_CCInc_XSec_1Dthetamu_nu.h" #endif #ifndef __NO_BNL__ // BNL CCQE #include "BNL_CCQE_Evt_1DQ2_nu.h" #include "BNL_CCQE_XSec_1DEnu_nu.h" // BNL CC1ppip #include "BNL_CC1ppip_Evt_1DQ2_nu.h" #include "BNL_CC1ppip_Evt_1DQ2_nu.h" #include "BNL_CC1ppip_Evt_1DcosthAdler_nu.h" #include "BNL_CC1ppip_Evt_1Dphi_nu.h" #include "BNL_CC1ppip_XSec_1DEnu_nu.h" // BNL CC1npip #include "BNL_CC1npip_Evt_1DQ2_nu.h" #include "BNL_CC1npip_XSec_1DEnu_nu.h" // BNL CC1pi0 #include "BNL_CC1pi0_Evt_1DQ2_nu.h" #include "BNL_CC1pi0_XSec_1DEnu_nu.h" #endif #ifndef __NO_FNAL__ // FNAL CCQE #include "FNAL_CCQE_Evt_1DQ2_nu.h" // FNAL CC1ppip #include "FNAL_CC1ppip_Evt_1DQ2_nu.h" #include "FNAL_CC1ppip_XSec_1DEnu_nu.h" #include "FNAL_CC1ppip_XSec_1DQ2_nu.h" // FNAL CC1ppim #include "FNAL_CC1ppim_XSec_1DEnu_antinu.h" #endif #ifndef __NO_BEBC__ // BEBC CCQE #include "BEBC_CCQE_XSec_1DQ2_nu.h" // BEBC CC1ppip #include "BEBC_CC1ppip_XSec_1DEnu_nu.h" #include "BEBC_CC1ppip_XSec_1DQ2_nu.h" // BEBC CC1npip #include "BEBC_CC1npip_XSec_1DEnu_nu.h" #include "BEBC_CC1npip_XSec_1DQ2_nu.h" // BEBC CC1pi0 #include "BEBC_CC1pi0_XSec_1DEnu_nu.h" #include "BEBC_CC1pi0_XSec_1DQ2_nu.h" // BEBC CC1npim #include "BEBC_CC1npim_XSec_1DEnu_antinu.h" #include "BEBC_CC1npim_XSec_1DQ2_antinu.h" // BEBC CC1ppim #include "BEBC_CC1ppim_XSec_1DEnu_antinu.h" #include "BEBC_CC1ppim_XSec_1DQ2_antinu.h" #endif #ifndef __NO_GGM__ // GGM CC1ppip #include "GGM_CC1ppip_Evt_1DQ2_nu.h" #include "GGM_CC1ppip_XSec_1DEnu_nu.h" #endif #ifndef __NO_MiniBooNE__ // MiniBooNE CCQE #include "MiniBooNE_CCQE_XSec_1DQ2_antinu.h" #include "MiniBooNE_CCQE_XSec_1DQ2_nu.h" #include "MiniBooNE_CCQE_XSec_2DTcos_antinu.h" #include "MiniBooNE_CCQE_XSec_2DTcos_antinu.h" #include "MiniBooNE_CCQE_XSec_2DTcos_nu.h" // MiniBooNE CC1pi+ 1D #include "MiniBooNE_CC1pip_XSec_1DEnu_nu.h" #include "MiniBooNE_CC1pip_XSec_1DQ2_nu.h" #include "MiniBooNE_CC1pip_XSec_1DTpi_nu.h" #include "MiniBooNE_CC1pip_XSec_1DTu_nu.h" // MiniBooNE CC1pi+ 2D #include "MiniBooNE_CC1pip_XSec_2DQ2Enu_nu.h" #include "MiniBooNE_CC1pip_XSec_2DTpiCospi_nu.h" #include "MiniBooNE_CC1pip_XSec_2DTpiEnu_nu.h" #include "MiniBooNE_CC1pip_XSec_2DTuCosmu_nu.h" #include "MiniBooNE_CC1pip_XSec_2DTuEnu_nu.h" // MiniBooNE CC1pi0 #include "MiniBooNE_CC1pi0_XSec_1DEnu_nu.h" #include "MiniBooNE_CC1pi0_XSec_1DQ2_nu.h" #include "MiniBooNE_CC1pi0_XSec_1DTu_nu.h" #include "MiniBooNE_CC1pi0_XSec_1Dcosmu_nu.h" #include "MiniBooNE_CC1pi0_XSec_1Dcospi0_nu.h" #include "MiniBooNE_CC1pi0_XSec_1Dppi0_nu.h" #include "MiniBooNE_NC1pi0_XSec_1Dcospi0_antinu.h" #include "MiniBooNE_NC1pi0_XSec_1Dcospi0_nu.h" #include "MiniBooNE_NC1pi0_XSec_1Dppi0_antinu.h" #include "MiniBooNE_NC1pi0_XSec_1Dppi0_nu.h" // MiniBooNE NC1pi0 //#include "MiniBooNE_NCpi0_XSec_1Dppi0_nu.h" // MiniBooNE NCEL #include "MiniBooNE_NCEL_XSec_Treco_nu.h" #endif #ifndef __NO_MicroBooNE__ #include "MicroBooNE_CCInc_XSec_2DPcos_nu.h" #endif #ifndef __NO_MINERvA__ // MINERvA CCQE #include "MINERvA_CCQE_XSec_1DQ2_antinu.h" #include "MINERvA_CCQE_XSec_1DQ2_joint.h" #include "MINERvA_CCQE_XSec_1DQ2_nu.h" // MINERvA CC0pi #include "MINERvA_CC0pi_XSec_1DEe_nue.h" #include "MINERvA_CC0pi_XSec_1DQ2_nu_proton.h" #include "MINERvA_CC0pi_XSec_1DQ2_nue.h" #include "MINERvA_CC0pi_XSec_1DThetae_nue.h" // 2018 MINERvA CC0pi STV #include "MINERvA_CC0pinp_STV_XSec_1D_nu.h" // 2018 MINERvA CC0pi 2D #include "MINERvA_CC0pi_XSec_2D_nu.h" #include "MINERvA_CC0pi_XSec_1D_2018_nu.h" // 2018 MINERvA CC0pi 2D antinu #include "MINERvA_CC0pi_XSec_2D_antinu.h" // MINERvA CC1pi+ #include "MINERvA_CC1pip_XSec_1DTpi_20deg_nu.h" #include "MINERvA_CC1pip_XSec_1DTpi_nu.h" #include "MINERvA_CC1pip_XSec_1Dth_20deg_nu.h" #include "MINERvA_CC1pip_XSec_1Dth_nu.h" // 2017 data update #include "MINERvA_CC1pip_XSec_1D_2017Update.h" // MINERvA CCNpi+ #include "MINERvA_CCNpip_XSec_1DEnu_nu.h" #include "MINERvA_CCNpip_XSec_1DQ2_nu.h" #include "MINERvA_CCNpip_XSec_1DTpi_nu.h" #include "MINERvA_CCNpip_XSec_1Dpmu_nu.h" #include "MINERvA_CCNpip_XSec_1Dth_nu.h" #include "MINERvA_CCNpip_XSec_1Dthmu_nu.h" // MINERvA CC1pi0 #include "MINERvA_CC1pi0_XSec_1DEnu_antinu.h" #include "MINERvA_CC1pi0_XSec_1DQ2_antinu.h" #include "MINERvA_CC1pi0_XSec_1DTpi0_antinu.h" #include "MINERvA_CC1pi0_XSec_1Dpmu_antinu.h" #include "MINERvA_CC1pi0_XSec_1Dppi0_antinu.h" #include "MINERvA_CC1pi0_XSec_1Dth_antinu.h" #include "MINERvA_CC1pi0_XSec_1Dthmu_antinu.h" // MINERvA CC1pi0 neutrino #include "MINERvA_CC1pi0_XSec_1D_nu.h" // MINERvA CCINC #include "MINERvA_CCinc_XSec_1DEnu_ratio.h" #include "MINERvA_CCinc_XSec_1Dx_ratio.h" #include "MINERvA_CCinc_XSec_2DEavq3_nu.h" // MINERvA CCDIS #include "MINERvA_CCDIS_XSec_1DEnu_ratio.h" #include "MINERvA_CCDIS_XSec_1Dx_ratio.h" // MINERvA CCCOH pion #include "MINERvA_CCCOHPI_XSec_1DEnu_antinu.h" #include "MINERvA_CCCOHPI_XSec_1DEnu_antinu.h" #include "MINERvA_CCCOHPI_XSec_1DEpi_antinu.h" #include "MINERvA_CCCOHPI_XSec_1DQ2_antinu.h" #include "MINERvA_CCCOHPI_XSec_1DEpi_nu.h" #include "MINERvA_CCCOHPI_XSec_1DQ2_nu.h" #include "MINERvA_CCCOHPI_XSec_1Dth_nu.h" #include "MINERvA_CCCOHPI_XSec_1Dth_nu.h" #include "MINERvA_CCCOHPI_XSec_joint.h" #include "MINERvA_CC0pi_XSec_1DQ2_TgtRatio_nu.h" #include "MINERvA_CC0pi_XSec_1DQ2_Tgt_nu.h" #endif #ifndef __NO_T2K__ // T2K CC0pi 2016 #include "T2K_CC0pi_XSec_2DPcos_nu.h" // T2K CC-inclusive with full acceptance 2018 #include "T2K_CCinc_XSec_2DPcos_nu_nonuniform.h" // T2K STV CC0pi 2018 #include "T2K_CC0pi_XSec_2DPcos_nu_nonuniform.h" #include "T2K_CC0pinp_STV_XSec_1Ddpt_nu.h" #include "T2K_CC0pinp_STV_XSec_1Ddphit_nu.h" #include "T2K_CC0pinp_STV_XSec_1Ddat_nu.h" #include "T2K_CC0pi1p_XSec_3DPcoscos_nu_nonuniform.h" #include "T2K_CC0pinp_ifk_XSec_3Dinfp_nu.h" #include "T2K_CC0pinp_ifk_XSec_3Dinfa_nu.h" #include "T2K_CC0pinp_ifk_XSec_3Dinfip_nu.h" // T2K CC1pi+ on CH #include "T2K_CC1pip_CH_XSec_2Dpmucosmu_nu.h" #include "T2K_CC1pip_CH_XSec_1Dppi_nu.h" #include "T2K_CC1pip_CH_XSec_1Dthpi_nu.h" #include "T2K_CC1pip_CH_XSec_1Dthmupi_nu.h" #include "T2K_CC1pip_CH_XSec_1DQ2_nu.h" #include "T2K_CC1pip_CH_XSec_1DAdlerPhi_nu.h" #include "T2K_CC1pip_CH_XSec_1DCosThAdler_nu.h" //#include "T2K_CC1pip_CH_XSec_1Dthq3pi_nu.h" //#include "T2K_CC1pip_CH_XSec_1DWrec_nu.h" //#include "T2K_CC1pip_CH_XSec_1Dq3_nu.h" // T2K CC1pi+ on H2O #include "T2K_CC1pip_H2O_XSec_1DEnuDelta_nu.h" #include "T2K_CC1pip_H2O_XSec_1DEnuMB_nu.h" #include "T2K_CC1pip_H2O_XSec_1Dcosmu_nu.h" #include "T2K_CC1pip_H2O_XSec_1Dcosmupi_nu.h" #include "T2K_CC1pip_H2O_XSec_1Dcospi_nu.h" #include "T2K_CC1pip_H2O_XSec_1Dpmu_nu.h" #include "T2K_CC1pip_H2O_XSec_1Dppi_nu.h" #endif #ifndef __NO_SciBooNE__ // SciBooNE COH studies #include "SciBooNE_CCCOH_1TRK_1DQ2_nu.h" #include "SciBooNE_CCCOH_1TRK_1Dpmu_nu.h" #include "SciBooNE_CCCOH_1TRK_1Dthetamu_nu.h" #include "SciBooNE_CCCOH_MuPiNoVA_1DQ2_nu.h" #include "SciBooNE_CCCOH_MuPiNoVA_1Dthetapi_nu.h" #include "SciBooNE_CCCOH_MuPiNoVA_1Dthetapr_nu.h" #include "SciBooNE_CCCOH_MuPiNoVA_1Dthetamu_nu.h" #include "SciBooNE_CCCOH_MuPiNoVA_1Dpmu_nu.h" #include "SciBooNE_CCCOH_MuPiVA_1DQ2_nu.h" #include "SciBooNE_CCCOH_MuPiVA_1Dpmu_nu.h" #include "SciBooNE_CCCOH_MuPiVA_1Dthetamu_nu.h" #include "SciBooNE_CCCOH_MuPr_1DQ2_nu.h" #include "SciBooNE_CCCOH_MuPr_1Dpmu_nu.h" #include "SciBooNE_CCCOH_MuPr_1Dthetamu_nu.h" #include "SciBooNE_CCCOH_STOPFINAL_1DQ2_nu.h" #include "SciBooNE_CCCOH_STOP_NTrks_nu.h" #endif #ifndef __NO_K2K__ // K2K NC1pi0 #include "K2K_NC1pi0_Evt_1Dppi0_nu.h" #endif // MC Studies #include "ExpMultDist_CCQE_XSec_1DVar_FakeStudy.h" #include "ExpMultDist_CCQE_XSec_2DVar_FakeStudy.h" #include "MCStudy_CCQEHistograms.h" #include "GenericFlux_Tester.h" #include "GenericFlux_Vectors.h" #include "ElectronFlux_FlatTree.h" #include "ElectronScattering_DurhamData.h" #include "MCStudy_KaonPreSelection.h" #include "MCStudy_MuonValidation.h" #include "OfficialNIWGPlots.h" #include "T2K2017_FakeData.h" #include "Simple_Osc.h" #include "Smear_SVDUnfold_Propagation_Osc.h" #include "FitWeight.h" #include "NuisConfig.h" #include "NuisKey.h" #ifdef __USE_DYNSAMPLES__ #include "TRegexp.h" #include // linux #include DynamicSampleFactory::DynamicSampleFactory() : NSamples(0), NManifests(0) { LoadPlugins(); - QLOG(FIT, "Loaded " << NSamples << " from " << NManifests + NUIS_LOG(FIT, "Loaded " << NSamples << " from " << NManifests << " shared object libraries."); } DynamicSampleFactory* DynamicSampleFactory::glblDSF = NULL; DynamicSampleFactory::PluginManifest::~PluginManifest() { for (size_t i_it = 0; i_it < Instances.size(); ++i_it) { (*(DSF_DestroySample))(Instances[i_it]); } } std::string EnsureTrailingSlash(std::string const& inp) { if (!inp.length()) { return "/"; } if (inp[inp.length() - 1] == '/') { return inp; } return inp + "/"; } void DynamicSampleFactory::LoadPlugins() { std::vector SearchDirectories; if (Config::HasPar("dynamic_sample.path")) { SearchDirectories = GeneralUtils::ParseToStr(Config::GetParS("dynamic_sample.path"), ":"); } char const* envPath = getenv("NUISANCE_DS_PATH"); if (envPath) { std::vector envPaths = GeneralUtils::ParseToStr(envPath, ":"); for (size_t ep_it = 0; ep_it < envPaths.size(); ++ep_it) { SearchDirectories.push_back(envPaths[ep_it]); } } if (!SearchDirectories.size()) { char const* pwdPath = getenv("PWD"); if (pwdPath) { SearchDirectories.push_back(pwdPath); } } for (size_t sp_it = 0; sp_it < SearchDirectories.size(); ++sp_it) { std::string dirpath = EnsureTrailingSlash(SearchDirectories[sp_it]); - QLOG(FIT, "Searching for dynamic sample manifests in: " << dirpath); + NUIS_LOG(FIT, "Searching for dynamic sample manifests in: " << dirpath); Ssiz_t len = 0; DIR* dir; struct dirent* ent; dir = opendir(dirpath.c_str()); if (dir != NULL) { TRegexp matchExp("*.so", true); while ((ent = readdir(dir)) != NULL) { if (matchExp.Index(TString(ent->d_name), &len) != Ssiz_t(-1)) { - QLOG(FIT, "\tFound shared object: " + NUIS_LOG(FIT, "\tFound shared object: " << ent->d_name << " checking for relevant methods..."); void* dlobj = dlopen((dirpath + ent->d_name).c_str(), RTLD_NOW | RTLD_GLOBAL); char const* dlerr_cstr = dlerror(); std::string dlerr; if (dlerr_cstr) { dlerr = dlerr_cstr; } if (dlerr.length()) { - QERROR(WRN, "\tDL Load Error: " << dlerr); + NUIS_ERR(WRN, "\tDL Load Error: " << dlerr); continue; } PluginManifest plgManif; plgManif.dllib = dlobj; plgManif.soloc = (dirpath + ent->d_name); plgManif.DSF_NSamples = reinterpret_cast(dlsym(dlobj, "DSF_NSamples")); dlerr = ""; dlerr_cstr = dlerror(); if (dlerr_cstr) { dlerr = dlerr_cstr; } if (dlerr.length()) { - QERROR(WRN, "\tFailed to load symbol \"DSF_NSamples\" from " + NUIS_ERR(WRN, "\tFailed to load symbol \"DSF_NSamples\" from " << (dirpath + ent->d_name) << ": " << dlerr); dlclose(dlobj); continue; } plgManif.DSF_GetSampleName = reinterpret_cast( dlsym(dlobj, "DSF_GetSampleName")); dlerr = ""; dlerr_cstr = dlerror(); if (dlerr_cstr) { dlerr = dlerr_cstr; } if (dlerr.length()) { - QERROR(WRN, "\tFailed to load symbol \"DSF_GetSampleName\" from " + NUIS_ERR(WRN, "\tFailed to load symbol \"DSF_GetSampleName\" from " << (dirpath + ent->d_name) << ": " << dlerr); dlclose(dlobj); continue; } plgManif.DSF_GetSample = reinterpret_cast( dlsym(dlobj, "DSF_GetSample")); dlerr = ""; dlerr_cstr = dlerror(); if (dlerr_cstr) { dlerr = dlerr_cstr; } if (dlerr.length()) { - QERROR(WRN, "\tFailed to load symbol \"DSF_GetSample\" from " + NUIS_ERR(WRN, "\tFailed to load symbol \"DSF_GetSample\" from " << (dirpath + ent->d_name) << ": " << dlerr); dlclose(dlobj); continue; } plgManif.DSF_DestroySample = reinterpret_cast( dlsym(dlobj, "DSF_DestroySample")); dlerr = ""; dlerr_cstr = dlerror(); if (dlerr_cstr) { dlerr = dlerr_cstr; } if (dlerr.length()) { - QERROR(WRN, "Failed to load symbol \"DSF_DestroySample\" from " + NUIS_ERR(WRN, "Failed to load symbol \"DSF_DestroySample\" from " << (dirpath + ent->d_name) << ": " << dlerr); dlclose(dlobj); continue; } plgManif.NSamples = (*(plgManif.DSF_NSamples))(); - QLOG(FIT, "\tSuccessfully loaded dynamic sample manifest: " + NUIS_LOG(FIT, "\tSuccessfully loaded dynamic sample manifest: " << plgManif.soloc << ". Contains " << plgManif.NSamples << " samples."); for (size_t smp_it = 0; smp_it < plgManif.NSamples; ++smp_it) { char const* smp_name = (*(plgManif.DSF_GetSampleName))(smp_it); if (!smp_name) { - QTHROW("Could not load sample " << smp_it << " / " + NUIS_ABORT("Could not load sample " << smp_it << " / " << plgManif.NSamples << " from " << plgManif.soloc); } if (Samples.count(smp_name)) { - QERROR(WRN, "Already loaded a sample named: \"" + NUIS_ERR(WRN, "Already loaded a sample named: \"" << smp_name << "\". cannot load duplciates. This " "sample will be skipped."); continue; } plgManif.SamplesProvided.push_back(smp_name); Samples[smp_name] = std::make_pair(plgManif.soloc, smp_it); - QLOG(FIT, "\t\t" << smp_name); + NUIS_LOG(FIT, "\t\t" << smp_name); } if (plgManif.SamplesProvided.size()) { Manifests[plgManif.soloc] = plgManif; NSamples += plgManif.SamplesProvided.size(); NManifests++; } else { dlclose(dlobj); } } } closedir(dir); } else { - QERROR(WRN, "Tried to open non-existant directory."); + NUIS_ERR(WRN, "Tried to open non-existant directory."); } } } DynamicSampleFactory& DynamicSampleFactory::Get() { if (!glblDSF) { glblDSF = new DynamicSampleFactory(); } return *glblDSF; } void DynamicSampleFactory::Print() { std::map > ManifestSamples; for (std::map >::iterator smp_it = Samples.begin(); smp_it != Samples.end(); ++smp_it) { if (!ManifestSamples.count(smp_it->second.first)) { ManifestSamples[smp_it->second.first] = std::vector(); } ManifestSamples[smp_it->second.first].push_back(smp_it->first); } - QLOG(FIT, "Dynamic sample manifest: "); + NUIS_LOG(FIT, "Dynamic sample manifest: "); for (std::map >::iterator m_it = ManifestSamples.begin(); m_it != ManifestSamples.end(); ++m_it) { - QLOG(FIT, "\tLibrary " << m_it->first << " contains: "); + NUIS_LOG(FIT, "\tLibrary " << m_it->first << " contains: "); for (size_t s_it = 0; s_it < m_it->second.size(); ++s_it) { - QLOG(FIT, "\t\t" << m_it->second[s_it]); + NUIS_LOG(FIT, "\t\t" << m_it->second[s_it]); } } } bool DynamicSampleFactory::HasSample(std::string const& name) { return Samples.count(name); } bool DynamicSampleFactory::HasSample(nuiskey& samplekey) { return HasSample(samplekey.GetS("name")); } MeasurementBase* DynamicSampleFactory::CreateSample(nuiskey& samplekey) { if (!HasSample(samplekey)) { - QERROR(WRN, "Asked to load unknown sample: \"" << samplekey.GetS("name") + NUIS_ERR(WRN, "Asked to load unknown sample: \"" << samplekey.GetS("name") << "\"."); return NULL; } std::pair sample = Samples[samplekey.GetS("name")]; - QLOG(SAM, "\tLoading sample " << sample.second << " from " << sample.first); + NUIS_LOG(SAM, "\tLoading sample " << sample.second << " from " << sample.first); return (*(Manifests[sample.first].DSF_GetSample))(sample.second, &samplekey); } DynamicSampleFactory::~DynamicSampleFactory() { Manifests.clear(); } #endif //! Functions to make it easier for samples to be created and handled. namespace SampleUtils { //! Create a given sample given its name, file, type, fakdata(fkdt) file and the //! current rw engine and push it back into the list fChain. MeasurementBase* CreateSample(std::string name, std::string file, std::string type, std::string fkdt, FitWeight* rw) { nuiskey samplekey = Config::CreateKey("sample"); samplekey.Set("name", name); samplekey.Set("input", file); samplekey.Set("type", type); return CreateSample(samplekey); } MeasurementBase* CreateSample(nuiskey samplekey) { #ifdef __USE_DYNSAMPLES__ if (DynamicSampleFactory::Get().HasSample(samplekey)) { - QLOG(SAM, "Instantiating dynamic sample..."); + NUIS_LOG(SAM, "Instantiating dynamic sample..."); MeasurementBase* ds = DynamicSampleFactory::Get().CreateSample(samplekey); if (ds) { - QLOG(SAM, "Done."); + NUIS_LOG(SAM, "Done."); return ds; } - QTHROW("Failed to instantiate dynamic sample."); + NUIS_ABORT("Failed to instantiate dynamic sample."); } #endif FitWeight* rw = FitBase::GetRW(); std::string name = samplekey.GetS("name"); std::string file = samplekey.GetS("input"); std::string type = samplekey.GetS("type"); std::string fkdt = ""; /* ANL CCQE Samples */ #ifndef __NO_ANL__ if (!name.compare("ANL_CCQE_XSec_1DEnu_nu") || !name.compare("ANL_CCQE_XSec_1DEnu_nu_PRD26") || !name.compare("ANL_CCQE_XSec_1DEnu_nu_PRL31") || !name.compare("ANL_CCQE_XSec_1DEnu_nu_PRD16")) { return (new ANL_CCQE_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("ANL_CCQE_Evt_1DQ2_nu") || !name.compare("ANL_CCQE_Evt_1DQ2_nu_PRL31") || !name.compare("ANL_CCQE_Evt_1DQ2_nu_PRD26") || !name.compare("ANL_CCQE_Evt_1DQ2_nu_PRD16")) { return (new ANL_CCQE_Evt_1DQ2_nu(samplekey)); /* ANL CC1ppip samples */ } else if (!name.compare("ANL_CC1ppip_XSec_1DEnu_nu") || !name.compare("ANL_CC1ppip_XSec_1DEnu_nu_W14Cut") || !name.compare("ANL_CC1ppip_XSec_1DEnu_nu_Uncorr") || !name.compare("ANL_CC1ppip_XSec_1DEnu_nu_W14Cut_Uncorr") || !name.compare("ANL_CC1ppip_XSec_1DEnu_nu_W16Cut_Uncorr")) { return (new ANL_CC1ppip_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("ANL_CC1ppip_XSec_1DQ2_nu")) { return (new ANL_CC1ppip_XSec_1DQ2_nu(samplekey)); } else if (!name.compare("ANL_CC1ppip_Evt_1DQ2_nu") || !name.compare("ANL_CC1ppip_Evt_1DQ2_nu_W14Cut")) { return (new ANL_CC1ppip_Evt_1DQ2_nu(samplekey)); } else if (!name.compare("ANL_CC1ppip_Evt_1Dppi_nu")) { return (new ANL_CC1ppip_Evt_1Dppi_nu(samplekey)); } else if (!name.compare("ANL_CC1ppip_Evt_1Dthpr_nu")) { return (new ANL_CC1ppip_Evt_1Dthpr_nu(samplekey)); } else if (!name.compare("ANL_CC1ppip_Evt_1DcosmuStar_nu")) { return (new ANL_CC1ppip_Evt_1DcosmuStar_nu(samplekey)); } else if (!name.compare("ANL_CC1ppip_Evt_1DcosthAdler_nu")) { return (new ANL_CC1ppip_Evt_1DcosthAdler_nu(samplekey)); } else if (!name.compare("ANL_CC1ppip_Evt_1Dphi_nu")) { return (new ANL_CC1ppip_Evt_1Dphi_nu(samplekey)); /* ANL CC1npip sample */ } else if (!name.compare("ANL_CC1npip_XSec_1DEnu_nu") || !name.compare("ANL_CC1npip_XSec_1DEnu_nu_W14Cut") || !name.compare("ANL_CC1npip_XSec_1DEnu_nu_Uncorr") || !name.compare("ANL_CC1npip_XSec_1DEnu_nu_W14Cut_Uncorr") || !name.compare("ANL_CC1npip_XSec_1DEnu_nu_W16Cut_Uncorr")) { return (new ANL_CC1npip_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("ANL_CC1npip_Evt_1DQ2_nu") || !name.compare("ANL_CC1npip_Evt_1DQ2_nu_W14Cut")) { return (new ANL_CC1npip_Evt_1DQ2_nu(samplekey)); } else if (!name.compare("ANL_CC1npip_Evt_1Dppi_nu")) { return (new ANL_CC1npip_Evt_1Dppi_nu(samplekey)); } else if (!name.compare("ANL_CC1npip_Evt_1DcosmuStar_nu")) { return (new ANL_CC1npip_Evt_1DcosmuStar_nu(samplekey)); /* ANL CC1pi0 sample */ } else if (!name.compare("ANL_CC1pi0_XSec_1DEnu_nu") || !name.compare("ANL_CC1pi0_XSec_1DEnu_nu_W14Cut") || !name.compare("ANL_CC1pi0_XSec_1DEnu_nu_Uncorr") || !name.compare("ANL_CC1pi0_XSec_1DEnu_nu_W14Cut_Uncorr") || !name.compare("ANL_CC1pi0_XSec_1DEnu_nu_W16Cut_Uncorr")) { return (new ANL_CC1pi0_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("ANL_CC1pi0_Evt_1DQ2_nu") || !name.compare("ANL_CC1pi0_Evt_1DQ2_nu_W14Cut")) { return (new ANL_CC1pi0_Evt_1DQ2_nu(samplekey)); } else if (!name.compare("ANL_CC1pi0_Evt_1DcosmuStar_nu")) { return (new ANL_CC1pi0_Evt_1DcosmuStar_nu(samplekey)); /* ANL NC1npip sample */ } else if (!name.compare("ANL_NC1npip_Evt_1Dppi_nu")) { return (new ANL_NC1npip_Evt_1Dppi_nu(samplekey)); /* ANL NC1ppim sample */ } else if (!name.compare("ANL_NC1ppim_XSec_1DEnu_nu")) { return (new ANL_NC1ppim_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("ANL_NC1ppim_Evt_1DcosmuStar_nu")) { return (new ANL_NC1ppim_Evt_1DcosmuStar_nu(samplekey)); /* ANL CC2pi sample */ } else if (!name.compare("ANL_CC2pi_1pim1pip_XSec_1DEnu_nu")) { return (new ANL_CC2pi_1pim1pip_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("ANL_CC2pi_1pim1pip_Evt_1Dpmu_nu")) { return (new ANL_CC2pi_1pim1pip_Evt_1Dpmu_nu(samplekey)); } else if (!name.compare("ANL_CC2pi_1pim1pip_Evt_1Dppip_nu")) { return (new ANL_CC2pi_1pim1pip_Evt_1Dppip_nu(samplekey)); } else if (!name.compare("ANL_CC2pi_1pim1pip_Evt_1Dppim_nu")) { return (new ANL_CC2pi_1pim1pip_Evt_1Dppim_nu(samplekey)); } else if (!name.compare("ANL_CC2pi_1pim1pip_Evt_1Dpprot_nu")) { return (new ANL_CC2pi_1pim1pip_Evt_1Dpprot_nu(samplekey)); } else if (!name.compare("ANL_CC2pi_1pip1pip_XSec_1DEnu_nu")) { return (new ANL_CC2pi_1pip1pip_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("ANL_CC2pi_1pip1pip_Evt_1Dpmu_nu")) { return (new ANL_CC2pi_1pip1pip_Evt_1Dpmu_nu(samplekey)); } else if (!name.compare("ANL_CC2pi_1pip1pip_Evt_1Dpneut_nu")) { return (new ANL_CC2pi_1pip1pip_Evt_1Dpneut_nu(samplekey)); } else if (!name.compare("ANL_CC2pi_1pip1pip_Evt_1DppipHigh_nu")) { return (new ANL_CC2pi_1pip1pip_Evt_1DppipHigh_nu(samplekey)); } else if (!name.compare("ANL_CC2pi_1pip1pip_Evt_1DppipLow_nu")) { return (new ANL_CC2pi_1pip1pip_Evt_1DppipLow_nu(samplekey)); } else if (!name.compare("ANL_CC2pi_1pip1pi0_XSec_1DEnu_nu")) { return (new ANL_CC2pi_1pip1pi0_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("ANL_CC2pi_1pip1pi0_Evt_1Dpmu_nu")) { return (new ANL_CC2pi_1pip1pi0_Evt_1Dpmu_nu(samplekey)); } else if (!name.compare("ANL_CC2pi_1pip1pi0_Evt_1Dppip_nu")) { return (new ANL_CC2pi_1pip1pi0_Evt_1Dppip_nu(samplekey)); } else if (!name.compare("ANL_CC2pi_1pip1pi0_Evt_1Dppi0_nu")) { return (new ANL_CC2pi_1pip1pi0_Evt_1Dppi0_nu(samplekey)); } else if (!name.compare("ANL_CC2pi_1pip1pi0_Evt_1Dpprot_nu")) { return (new ANL_CC2pi_1pip1pi0_Evt_1Dpprot_nu(samplekey)); /* ArgoNeut Samples */ } else #endif #ifndef __NO_ArgoNeuT__ if (!name.compare("ArgoNeuT_CCInc_XSec_1Dpmu_antinu")) { return (new ArgoNeuT_CCInc_XSec_1Dpmu_antinu(samplekey)); } else if (!name.compare("ArgoNeuT_CCInc_XSec_1Dpmu_nu")) { return (new ArgoNeuT_CCInc_XSec_1Dpmu_nu(samplekey)); } else if (!name.compare("ArgoNeuT_CCInc_XSec_1Dthetamu_antinu")) { return (new ArgoNeuT_CCInc_XSec_1Dthetamu_antinu(samplekey)); } else if (!name.compare("ArgoNeuT_CCInc_XSec_1Dthetamu_nu")) { return (new ArgoNeuT_CCInc_XSec_1Dthetamu_nu(samplekey)); } else if (!name.compare("ArgoNeuT_CC1Pi_XSec_1Dpmu_nu")) { return (new ArgoNeuT_CC1Pi_XSec_1Dpmu_nu(samplekey)); } else if (!name.compare("ArgoNeuT_CC1Pi_XSec_1Dthetamu_nu")) { return (new ArgoNeuT_CC1Pi_XSec_1Dthetamu_nu(samplekey)); } else if (!name.compare("ArgoNeuT_CC1Pi_XSec_1Dthetapi_nu")) { return (new ArgoNeuT_CC1Pi_XSec_1Dthetapi_nu(samplekey)); } else if (!name.compare("ArgoNeuT_CC1Pi_XSec_1Dthetamupi_nu")) { return (new ArgoNeuT_CC1Pi_XSec_1Dthetamupi_nu(samplekey)); } else if (!name.compare("ArgoNeuT_CC1Pi_XSec_1Dpmu_antinu")) { return (new ArgoNeuT_CC1Pi_XSec_1Dpmu_antinu(samplekey)); } else if (!name.compare("ArgoNeuT_CC1Pi_XSec_1Dthetamu_antinu")) { return (new ArgoNeuT_CC1Pi_XSec_1Dthetamu_antinu(samplekey)); } else if (!name.compare("ArgoNeuT_CC1Pi_XSec_1Dthetapi_antinu")) { return (new ArgoNeuT_CC1Pi_XSec_1Dthetapi_antinu(samplekey)); } else if (!name.compare("ArgoNeuT_CC1Pi_XSec_1Dthetamupi_antinu")) { return (new ArgoNeuT_CC1Pi_XSec_1Dthetamupi_antinu(samplekey)); /* BNL Samples */ } else #endif #ifndef __NO_BNL__ if (!name.compare("BNL_CCQE_XSec_1DEnu_nu")) { return (new BNL_CCQE_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("BNL_CCQE_Evt_1DQ2_nu")) { return (new BNL_CCQE_Evt_1DQ2_nu(samplekey)); /* BNL CC1ppip samples */ } else if (!name.compare("BNL_CC1ppip_XSec_1DEnu_nu") || !name.compare("BNL_CC1ppip_XSec_1DEnu_nu_Uncorr") || !name.compare("BNL_CC1ppip_XSec_1DEnu_nu_W14Cut") || !name.compare("BNL_CC1ppip_XSec_1DEnu_nu_W14Cut_Uncorr")) { return (new BNL_CC1ppip_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("BNL_CC1ppip_Evt_1DQ2_nu") || !name.compare("BNL_CC1ppip_Evt_1DQ2_nu_W14Cut")) { return (new BNL_CC1ppip_Evt_1DQ2_nu(samplekey)); } else if (!name.compare("BNL_CC1ppip_Evt_1DcosthAdler_nu")) { return (new BNL_CC1ppip_Evt_1DcosthAdler_nu(samplekey)); } else if (!name.compare("BNL_CC1ppip_Evt_1Dphi_nu")) { return (new BNL_CC1ppip_Evt_1Dphi_nu(samplekey)); /* BNL CC1npip samples */ } else if (!name.compare("BNL_CC1npip_XSec_1DEnu_nu") || !name.compare("BNL_CC1npip_XSec_1DEnu_nu_Uncorr")) { return (new BNL_CC1npip_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("BNL_CC1npip_Evt_1DQ2_nu")) { return (new BNL_CC1npip_Evt_1DQ2_nu(samplekey)); /* BNL CC1pi0 samples */ } else if (!name.compare("BNL_CC1pi0_XSec_1DEnu_nu")) { return (new BNL_CC1pi0_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("BNL_CC1pi0_Evt_1DQ2_nu")) { return (new BNL_CC1pi0_Evt_1DQ2_nu(samplekey)); /* FNAL Samples */ } else #endif #ifndef __NO_FNAL__ if (!name.compare("FNAL_CCQE_Evt_1DQ2_nu")) { return (new FNAL_CCQE_Evt_1DQ2_nu(samplekey)); /* FNAL CC1ppip */ } else if (!name.compare("FNAL_CC1ppip_XSec_1DEnu_nu")) { return (new FNAL_CC1ppip_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("FNAL_CC1ppip_XSec_1DQ2_nu")) { return (new FNAL_CC1ppip_XSec_1DQ2_nu(samplekey)); } else if (!name.compare("FNAL_CC1ppip_Evt_1DQ2_nu")) { return (new FNAL_CC1ppip_Evt_1DQ2_nu(samplekey)); /* FNAL CC1ppim */ } else if (!name.compare("FNAL_CC1ppim_XSec_1DEnu_antinu")) { return (new FNAL_CC1ppim_XSec_1DEnu_antinu(samplekey)); /* BEBC Samples */ } else #endif #ifndef __NO_BEBC__ if (!name.compare("BEBC_CCQE_XSec_1DQ2_nu")) { return (new BEBC_CCQE_XSec_1DQ2_nu(samplekey)); /* BEBC CC1ppip samples */ } else if (!name.compare("BEBC_CC1ppip_XSec_1DEnu_nu")) { return (new BEBC_CC1ppip_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("BEBC_CC1ppip_XSec_1DQ2_nu")) { return (new BEBC_CC1ppip_XSec_1DQ2_nu(samplekey)); /* BEBC CC1npip samples */ } else if (!name.compare("BEBC_CC1npip_XSec_1DEnu_nu")) { return (new BEBC_CC1npip_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("BEBC_CC1npip_XSec_1DQ2_nu")) { return (new BEBC_CC1npip_XSec_1DQ2_nu(samplekey)); /* BEBC CC1pi0 samples */ } else if (!name.compare("BEBC_CC1pi0_XSec_1DEnu_nu")) { return (new BEBC_CC1pi0_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("BEBC_CC1pi0_XSec_1DQ2_nu")) { return (new BEBC_CC1pi0_XSec_1DQ2_nu(samplekey)); /* BEBC CC1npim samples */ } else if (!name.compare("BEBC_CC1npim_XSec_1DEnu_antinu")) { return (new BEBC_CC1npim_XSec_1DEnu_antinu(samplekey)); } else if (!name.compare("BEBC_CC1npim_XSec_1DQ2_antinu")) { return (new BEBC_CC1npim_XSec_1DQ2_antinu(samplekey)); /* BEBC CC1ppim samples */ } else if (!name.compare("BEBC_CC1ppim_XSec_1DEnu_antinu")) { return (new BEBC_CC1ppim_XSec_1DEnu_antinu(samplekey)); } else if (!name.compare("BEBC_CC1ppim_XSec_1DQ2_antinu")) { return (new BEBC_CC1ppim_XSec_1DQ2_antinu(samplekey)); /* GGM CC1ppip samples */ } else #endif #ifndef __NO_GGM__ if (!name.compare("GGM_CC1ppip_XSec_1DEnu_nu")) { return (new GGM_CC1ppip_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("GGM_CC1ppip_Evt_1DQ2_nu")) { return (new GGM_CC1ppip_Evt_1DQ2_nu(samplekey)); /* MiniBooNE Samples */ /* CCQE */ } else #endif #ifndef __NO_MiniBooNE__ if (!name.compare("MiniBooNE_CCQE_XSec_1DQ2_nu") || !name.compare("MiniBooNE_CCQELike_XSec_1DQ2_nu")) { return (new MiniBooNE_CCQE_XSec_1DQ2_nu(samplekey)); } else if (!name.compare("MiniBooNE_CCQE_XSec_1DQ2_antinu") || !name.compare("MiniBooNE_CCQELike_XSec_1DQ2_antinu") || !name.compare("MiniBooNE_CCQE_CTarg_XSec_1DQ2_antinu")) { return (new MiniBooNE_CCQE_XSec_1DQ2_antinu(samplekey)); } else if (!name.compare("MiniBooNE_CCQE_XSec_2DTcos_nu") || !name.compare("MiniBooNE_CCQELike_XSec_2DTcos_nu")) { return (new MiniBooNE_CCQE_XSec_2DTcos_nu(samplekey)); } else if (!name.compare("MiniBooNE_CCQE_XSec_2DTcos_antinu") || !name.compare("MiniBooNE_CCQELike_XSec_2DTcos_antinu")) { return (new MiniBooNE_CCQE_XSec_2DTcos_antinu(samplekey)); /* MiniBooNE CC1pi+ */ // 1D } else if (!name.compare("MiniBooNE_CC1pip_XSec_1DEnu_nu")) { return (new MiniBooNE_CC1pip_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("MiniBooNE_CC1pip_XSec_1DQ2_nu")) { return (new MiniBooNE_CC1pip_XSec_1DQ2_nu(samplekey)); } else if (!name.compare("MiniBooNE_CC1pip_XSec_1DTpi_nu")) { return (new MiniBooNE_CC1pip_XSec_1DTpi_nu(samplekey)); } else if (!name.compare("MiniBooNE_CC1pip_XSec_1DTu_nu")) { return (new MiniBooNE_CC1pip_XSec_1DTu_nu(samplekey)); // 2D } else if (!name.compare("MiniBooNE_CC1pip_XSec_2DQ2Enu_nu")) { return (new MiniBooNE_CC1pip_XSec_2DQ2Enu_nu(samplekey)); } else if (!name.compare("MiniBooNE_CC1pip_XSec_2DTpiCospi_nu")) { return (new MiniBooNE_CC1pip_XSec_2DTpiCospi_nu(samplekey)); } else if (!name.compare("MiniBooNE_CC1pip_XSec_2DTpiEnu_nu")) { return (new MiniBooNE_CC1pip_XSec_2DTpiEnu_nu(samplekey)); } else if (!name.compare("MiniBooNE_CC1pip_XSec_2DTuCosmu_nu")) { return (new MiniBooNE_CC1pip_XSec_2DTuCosmu_nu(samplekey)); } else if (!name.compare("MiniBooNE_CC1pip_XSec_2DTuEnu_nu")) { return (new MiniBooNE_CC1pip_XSec_2DTuEnu_nu(samplekey)); /* MiniBooNE CC1pi0 */ } else if (!name.compare("MiniBooNE_CC1pi0_XSec_1DEnu_nu")) { return (new MiniBooNE_CC1pi0_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("MiniBooNE_CC1pi0_XSec_1DQ2_nu")) { return (new MiniBooNE_CC1pi0_XSec_1DQ2_nu(samplekey)); } else if (!name.compare("MiniBooNE_CC1pi0_XSec_1DTu_nu")) { return (new MiniBooNE_CC1pi0_XSec_1DTu_nu(samplekey)); } else if (!name.compare("MiniBooNE_CC1pi0_XSec_1Dcosmu_nu")) { return (new MiniBooNE_CC1pi0_XSec_1Dcosmu_nu(samplekey)); } else if (!name.compare("MiniBooNE_CC1pi0_XSec_1Dcospi0_nu")) { return (new MiniBooNE_CC1pi0_XSec_1Dcospi0_nu(samplekey)); } else if (!name.compare("MiniBooNE_CC1pi0_XSec_1Dppi0_nu")) { return (new MiniBooNE_CC1pi0_XSec_1Dppi0_nu(samplekey)); } else if (!name.compare("MiniBooNE_NC1pi0_XSec_1Dcospi0_antinu") || !name.compare("MiniBooNE_NC1pi0_XSec_1Dcospi0_rhc")) { return (new MiniBooNE_NC1pi0_XSec_1Dcospi0_antinu(samplekey)); } else if (!name.compare("MiniBooNE_NC1pi0_XSec_1Dcospi0_nu") || !name.compare("MiniBooNE_NC1pi0_XSec_1Dcospi0_fhc")) { return (new MiniBooNE_NC1pi0_XSec_1Dcospi0_nu(samplekey)); } else if (!name.compare("MiniBooNE_NC1pi0_XSec_1Dppi0_antinu") || !name.compare("MiniBooNE_NC1pi0_XSec_1Dppi0_rhc")) { return (new MiniBooNE_NC1pi0_XSec_1Dppi0_antinu(samplekey)); } else if (!name.compare("MiniBooNE_NC1pi0_XSec_1Dppi0_nu") || !name.compare("MiniBooNE_NC1pi0_XSec_1Dppi0_fhc")) { return (new MiniBooNE_NC1pi0_XSec_1Dppi0_nu(samplekey)); /* MiniBooNE NCEL */ } else if (!name.compare("MiniBooNE_NCEL_XSec_Treco_nu")) { return (new MiniBooNE_NCEL_XSec_Treco_nu(samplekey)); } else #endif #ifndef __NO_MicroBooNE__ /* MicroBooNE Samples */ /* MicroBooNE CCinclusive */ if (!name.compare("MicroBooNE_CCInc_XSec_2DPcos_nu")) { return (new MicroBooNE_CCInc_XSec_2DPcos_nu(samplekey)); } else #endif #ifndef __NO_MINERvA__ /* MINERvA Samples */ if (!name.compare("MINERvA_CCQE_XSec_1DQ2_nu") || !name.compare("MINERvA_CCQE_XSec_1DQ2_nu_20deg") || !name.compare("MINERvA_CCQE_XSec_1DQ2_nu_oldflux") || !name.compare("MINERvA_CCQE_XSec_1DQ2_nu_20deg_oldflux")) { return (new MINERvA_CCQE_XSec_1DQ2_nu(samplekey)); } else if (!name.compare("MINERvA_CCQE_XSec_1DQ2_antinu") || !name.compare("MINERvA_CCQE_XSec_1DQ2_antinu_20deg") || !name.compare("MINERvA_CCQE_XSec_1DQ2_antinu_oldflux") || !name.compare("MINERvA_CCQE_XSec_1DQ2_antinu_20deg_oldflux")) { return (new MINERvA_CCQE_XSec_1DQ2_antinu(samplekey)); } else if (!name.compare("MINERvA_CCQE_XSec_1DQ2_joint_oldflux") || !name.compare("MINERvA_CCQE_XSec_1DQ2_joint_20deg_oldflux") || !name.compare("MINERvA_CCQE_XSec_1DQ2_joint") || !name.compare("MINERvA_CCQE_XSec_1DQ2_joint_20deg")) { return (new MINERvA_CCQE_XSec_1DQ2_joint(samplekey)); } else if (!name.compare("MINERvA_CC0pi_XSec_1DEe_nue")) { return (new MINERvA_CC0pi_XSec_1DEe_nue(samplekey)); } else if (!name.compare("MINERvA_CC0pi_XSec_1DQ2_nue")) { return (new MINERvA_CC0pi_XSec_1DQ2_nue(samplekey)); } else if (!name.compare("MINERvA_CC0pi_XSec_1DThetae_nue")) { return (new MINERvA_CC0pi_XSec_1DThetae_nue(samplekey)); } else if (!name.compare("MINERvA_CC0pinp_STV_XSec_1Dpmu_nu") || !name.compare("MINERvA_CC0pinp_STV_XSec_1Dthmu_nu") || !name.compare("MINERvA_CC0pinp_STV_XSec_1Dpprot_nu") || !name.compare("MINERvA_CC0pinp_STV_XSec_1Dthprot_nu") || !name.compare("MINERvA_CC0pinp_STV_XSec_1Dpnreco_nu") || !name.compare("MINERvA_CC0pinp_STV_XSec_1Ddalphat_nu") || !name.compare("MINERvA_CC0pinp_STV_XSec_1Ddpt_nu") || !name.compare("MINERvA_CC0pinp_STV_XSec_1Ddphit_nu")) { return (new MINERvA_CC0pinp_STV_XSec_1D_nu(samplekey)); } else if (!name.compare("MINERvA_CC0pi_XSec_1DQ2_nu_proton")) { return (new MINERvA_CC0pi_XSec_1DQ2_nu_proton(samplekey)); } else if (!name.compare("MINERvA_CC0pi_XSec_1DQ2_TgtC_nu") || !name.compare("MINERvA_CC0pi_XSec_1DQ2_TgtCH_nu") || !name.compare("MINERvA_CC0pi_XSec_1DQ2_TgtFe_nu") || !name.compare("MINERvA_CC0pi_XSec_1DQ2_TgtPb_nu")) { return (new MINERvA_CC0pi_XSec_1DQ2_Tgt_nu(samplekey)); } else if (!name.compare("MINERvA_CC0pi_XSec_1DQ2_TgtRatioC_nu") || !name.compare("MINERvA_CC0pi_XSec_1DQ2_TgtRatioFe_nu") || !name.compare("MINERvA_CC0pi_XSec_1DQ2_TgtRatioPb_nu")) { return (new MINERvA_CC0pi_XSec_1DQ2_TgtRatio_nu(samplekey)); // Dan Ruterbories measurements of late 2018 } else if ( !name.compare("MINERvA_CC0pi_XSec_2Dptpz_nu")) { return (new MINERvA_CC0pi_XSec_2D_nu(samplekey)); } else if ( !name.compare("MINERvA_CC0pi_XSec_1Dpt_nu") || !name.compare("MINERvA_CC0pi_XSec_1Dpz_nu") || !name.compare("MINERvA_CC0pi_XSec_1DQ2QE_nu") || !name.compare("MINERvA_CC0pi_XSec_1DEnuQE_nu")) { return (new MINERvA_CC0pi_XSec_1D_2018_nu(samplekey)); // C. Patrick's early 2018 measurements } else if ( !name.compare("MINERvA_CC0pi_XSec_2Dptpz_antinu") || !name.compare("MINERvA_CC0pi_XSec_2DQ2QEEnuQE_antinu") || !name.compare("MINERvA_CC0pi_XSec_2DQ2QEEnuTrue_antinu")) { return (new MINERvA_CC0pi_XSec_2D_antinu(samplekey)); /* CC1pi+ */ // DONE } else if (!name.compare("MINERvA_CC1pip_XSec_1DTpi_nu") || !name.compare("MINERvA_CC1pip_XSec_1DTpi_nu_20deg") || !name.compare("MINERvA_CC1pip_XSec_1DTpi_nu_fluxcorr") || !name.compare("MINERvA_CC1pip_XSec_1DTpi_nu_20deg_fluxcorr")) { return (new MINERvA_CC1pip_XSec_1DTpi_nu(samplekey)); // DONE } else if (!name.compare("MINERvA_CC1pip_XSec_1Dth_nu") || !name.compare("MINERvA_CC1pip_XSec_1Dth_nu_20deg") || !name.compare("MINERvA_CC1pip_XSec_1Dth_nu_fluxcorr") || !name.compare("MINERvA_CC1pip_XSec_1Dth_nu_20deg_fluxcorr")) { return (new MINERvA_CC1pip_XSec_1Dth_nu(samplekey)); } else if (!name.compare("MINERvA_CC1pip_XSec_1DTpi_nu_2017") || !name.compare("MINERvA_CC1pip_XSec_1Dth_nu_2017") || !name.compare("MINERvA_CC1pip_XSec_1Dpmu_nu_2017") || !name.compare("MINERvA_CC1pip_XSec_1Dthmu_nu_2017") || !name.compare("MINERvA_CC1pip_XSec_1DQ2_nu_2017") || !name.compare("MINERvA_CC1pip_XSec_1DEnu_nu_2017")) { return (new MINERvA_CC1pip_XSec_1D_2017Update(samplekey)); /* CCNpi+ */ } else if (!name.compare("MINERvA_CCNpip_XSec_1Dth_nu") || !name.compare("MINERvA_CCNpip_XSec_1Dth_nu_2015") || !name.compare("MINERvA_CCNpip_XSec_1Dth_nu_2016") || !name.compare("MINERvA_CCNpip_XSec_1Dth_nu_2015_20deg") || !name.compare("MINERvA_CCNpip_XSec_1Dth_nu_2015_fluxcorr") || !name.compare("MINERvA_CCNpip_XSec_1Dth_nu_2015_20deg_fluxcorr")) { return (new MINERvA_CCNpip_XSec_1Dth_nu(samplekey)); } else if (!name.compare("MINERvA_CCNpip_XSec_1DTpi_nu") || !name.compare("MINERvA_CCNpip_XSec_1DTpi_nu_2015") || !name.compare("MINERvA_CCNpip_XSec_1DTpi_nu_2016") || !name.compare("MINERvA_CCNpip_XSec_1DTpi_nu_2015_20deg") || !name.compare("MINERvA_CCNpip_XSec_1DTpi_nu_2015_fluxcorr") || !name.compare( "MINERvA_CCNpip_XSec_1DTpi_nu_2015_20deg_fluxcorr")) { return (new MINERvA_CCNpip_XSec_1DTpi_nu(samplekey)); } else if (!name.compare("MINERvA_CCNpip_XSec_1Dthmu_nu")) { return (new MINERvA_CCNpip_XSec_1Dthmu_nu(samplekey)); } else if (!name.compare("MINERvA_CCNpip_XSec_1Dpmu_nu")) { return (new MINERvA_CCNpip_XSec_1Dpmu_nu(samplekey)); } else if (!name.compare("MINERvA_CCNpip_XSec_1DQ2_nu")) { return (new MINERvA_CCNpip_XSec_1DQ2_nu(samplekey)); } else if (!name.compare("MINERvA_CCNpip_XSec_1DEnu_nu")) { return (new MINERvA_CCNpip_XSec_1DEnu_nu(samplekey)); /* MINERvA CC1pi0 anti-nu */ // Done } else if (!name.compare("MINERvA_CC1pi0_XSec_1Dth_antinu") || !name.compare("MINERvA_CC1pi0_XSec_1Dth_antinu_2015") || !name.compare("MINERvA_CC1pi0_XSec_1Dth_antinu_2016") || !name.compare("MINERvA_CC1pi0_XSec_1Dth_antinu_fluxcorr") || !name.compare("MINERvA_CC1pi0_XSec_1Dth_antinu_2015_fluxcorr") || !name.compare("MINERvA_CC1pi0_XSec_1Dth_antinu_2016_fluxcorr")) { return (new MINERvA_CC1pi0_XSec_1Dth_antinu(samplekey)); } else if (!name.compare("MINERvA_CC1pi0_XSec_1Dppi0_antinu") || !name.compare("MINERvA_CC1pi0_XSec_1Dppi0_antinu_fluxcorr")) { return (new MINERvA_CC1pi0_XSec_1Dppi0_antinu(samplekey)); } else if (!name.compare("MINERvA_CC1pi0_XSec_1DTpi0_antinu")) { return (new MINERvA_CC1pi0_XSec_1DTpi0_antinu(samplekey)); // Done } else if (!name.compare("MINERvA_CC1pi0_XSec_1DQ2_antinu")) { return (new MINERvA_CC1pi0_XSec_1DQ2_antinu(samplekey)); // Done } else if (!name.compare("MINERvA_CC1pi0_XSec_1Dthmu_antinu")) { return (new MINERvA_CC1pi0_XSec_1Dthmu_antinu(samplekey)); // Done } else if (!name.compare("MINERvA_CC1pi0_XSec_1Dpmu_antinu")) { return (new MINERvA_CC1pi0_XSec_1Dpmu_antinu(samplekey)); // Done } else if (!name.compare("MINERvA_CC1pi0_XSec_1DEnu_antinu")) { return (new MINERvA_CC1pi0_XSec_1DEnu_antinu(samplekey)); // MINERvA CC1pi0 nu } else if (!name.compare("MINERvA_CC1pi0_XSec_1DTpi_nu") || !name.compare("MINERvA_CC1pi0_XSec_1Dth_nu") || !name.compare("MINERvA_CC1pi0_XSec_1Dpmu_nu") || !name.compare("MINERvA_CC1pi0_XSec_1Dthmu_nu") || !name.compare("MINERvA_CC1pi0_XSec_1DQ2_nu") || !name.compare("MINERvA_CC1pi0_XSec_1DEnu_nu") || !name.compare("MINERvA_CC1pi0_XSec_1DWexp_nu") || !name.compare("MINERvA_CC1pi0_XSec_1DPPi0Mass_nu") || !name.compare("MINERvA_CC1pi0_XSec_1DPPi0MassDelta_nu") || !name.compare("MINERvA_CC1pi0_XSec_1DCosAdler_nu") || !name.compare("MINERvA_CC1pi0_XSec_1DPhiAdler_nu")) { return (new MINERvA_CC1pi0_XSec_1D_nu(samplekey)); /* CCINC */ } else if (!name.compare("MINERvA_CCinc_XSec_2DEavq3_nu")) { return (new MINERvA_CCinc_XSec_2DEavq3_nu(samplekey)); } else if (!name.compare("MINERvA_CCinc_XSec_1Dx_ratio_C12_CH") || !name.compare("MINERvA_CCinc_XSec_1Dx_ratio_Fe56_CH") || !name.compare("MINERvA_CCinc_XSec_1Dx_ratio_Pb208_CH")) { return (new MINERvA_CCinc_XSec_1Dx_ratio(samplekey)); } else if (!name.compare("MINERvA_CCinc_XSec_1DEnu_ratio_C12_CH") || !name.compare("MINERvA_CCinc_XSec_1DEnu_ratio_Fe56_CH") || !name.compare("MINERvA_CCinc_XSec_1DEnu_ratio_Pb208_CH")) { return (new MINERvA_CCinc_XSec_1DEnu_ratio(samplekey)); /* CCDIS */ } else if (!name.compare("MINERvA_CCDIS_XSec_1Dx_ratio_C12_CH") || !name.compare("MINERvA_CCDIS_XSec_1Dx_ratio_Fe56_CH") || !name.compare("MINERvA_CCDIS_XSec_1Dx_ratio_Pb208_CH")) { return (new MINERvA_CCDIS_XSec_1Dx_ratio(samplekey)); } else if (!name.compare("MINERvA_CCDIS_XSec_1DEnu_ratio_C12_CH") || !name.compare("MINERvA_CCDIS_XSec_1DEnu_ratio_Fe56_CH") || !name.compare("MINERvA_CCDIS_XSec_1DEnu_ratio_Pb208_CH")) { return (new MINERvA_CCDIS_XSec_1DEnu_ratio(samplekey)); /* CC-COH */ } else if (!name.compare("MINERvA_CCCOHPI_XSec_1DEnu_nu")) { return (new MINERvA_CCCOHPI_XSec_1DEnu_nu(samplekey)); } else if (!name.compare("MINERvA_CCCOHPI_XSec_1DEpi_nu")) { return (new MINERvA_CCCOHPI_XSec_1DEpi_nu(samplekey)); } else if (!name.compare("MINERvA_CCCOHPI_XSec_1Dth_nu")) { return (new MINERvA_CCCOHPI_XSec_1Dth_nu(samplekey)); } else if (!name.compare("MINERvA_CCCOHPI_XSec_1DQ2_nu")) { return (new MINERvA_CCCOHPI_XSec_1DQ2_nu(samplekey)); } else if (!name.compare("MINERvA_CCCOHPI_XSec_1DEnu_antinu")) { return (new MINERvA_CCCOHPI_XSec_1DEnu_antinu(samplekey)); } else if (!name.compare("MINERvA_CCCOHPI_XSec_1DEpi_antinu")) { return (new MINERvA_CCCOHPI_XSec_1DEpi_antinu(samplekey)); } else if (!name.compare("MINERvA_CCCOHPI_XSec_1Dth_antinu")) { return (new MINERvA_CCCOHPI_XSec_1Dth_antinu(samplekey)); } else if (!name.compare("MINERvA_CCCOHPI_XSec_1DQ2_antinu")) { return (new MINERvA_CCCOHPI_XSec_1DQ2_antinu(samplekey)); } else if (!name.compare("MINERvA_CCCOHPI_XSec_1DEnu_joint")) { return (new MINERvA_CCCOHPI_XSec_joint(samplekey)); } else if (!name.compare("MINERvA_CCCOHPI_XSec_1DEpi_joint")) { return (new MINERvA_CCCOHPI_XSec_joint(samplekey)); } else if (!name.compare("MINERvA_CCCOHPI_XSec_1Dth_joint")) { return (new MINERvA_CCCOHPI_XSec_joint(samplekey)); } else if (!name.compare("MINERvA_CCCOHPI_XSec_1DQ2_joint")) { return (new MINERvA_CCCOHPI_XSec_joint(samplekey)); /* T2K Samples */ } else #endif #ifndef __NO_T2K__ if (!name.compare("T2K_CC0pi_XSec_2DPcos_nu") || !name.compare("T2K_CC0pi_XSec_2DPcos_nu_I") || !name.compare("T2K_CC0pi_XSec_2DPcos_nu_II")) { return (new T2K_CC0pi_XSec_2DPcos_nu(samplekey)); } else if (!name.compare("T2K_CC0pi_XSec_2DPcos_nu_nonuniform")) { return (new T2K_CC0pi_XSec_2DPcos_nu_nonuniform(samplekey)); } else if (!name.compare("T2K_CCinc_XSec_2DPcos_nu_nonuniform")) { return (new T2K_CCinc_XSec_2DPcos_nu_nonuniform(samplekey)); /* T2K CC1pi+ CH samples */ // Comment these out for now because we don't have the proper data } else if (!name.compare("T2K_CC1pip_CH_XSec_2Dpmucosmu_nu")) { return (new T2K_CC1pip_CH_XSec_2Dpmucosmu_nu(samplekey)); } else if (!name.compare("T2K_CC1pip_CH_XSec_1Dppi_nu")) { return (new T2K_CC1pip_CH_XSec_1Dppi_nu(samplekey)); } else if (!name.compare("T2K_CC1pip_CH_XSec_1Dthpi_nu")) { return (new T2K_CC1pip_CH_XSec_1Dthpi_nu(samplekey)); } else if (!name.compare("T2K_CC1pip_CH_XSec_1Dthmupi_nu")) { return (new T2K_CC1pip_CH_XSec_1Dthmupi_nu(samplekey)); } else if (!name.compare("T2K_CC1pip_CH_XSec_1DQ2_nu")) { return (new T2K_CC1pip_CH_XSec_1DQ2_nu(samplekey)); } else if (!name.compare("T2K_CC1pip_CH_XSec_1DAdlerPhi_nu")) { return (new T2K_CC1pip_CH_XSec_1DAdlerPhi_nu(samplekey)); } else if (!name.compare("T2K_CC1pip_CH_XSec_1DCosThAdler_nu")) { return (new T2K_CC1pip_CH_XSec_1DCosThAdler_nu(samplekey)); // Maybe something for the future: were in Raquel's thesis //} else if (!name.compare("T2K_CC1pip_CH_XSec_1Dq3_nu")) { //return (new T2K_CC1pip_CH_XSec_1Dq3_nu(file, rw, type, fkdt)); //} else if (!name.compare("T2K_CC1pip_CH_XSec_1Dthq3pi_nu")) { //return (new T2K_CC1pip_CH_XSec_1Dthq3pi_nu(file, rw, type, fkdt)); //} else if (!name.compare("T2K_CC1pip_CH_XSec_1DWrec_nu")) { //return (new T2K_CC1pip_CH_XSec_1DWrec_nu(file, rw, type, fkdt)); /* T2K CC1pi+ H2O samples */ } else if (!name.compare("T2K_CC1pip_H2O_XSec_1DEnuDelta_nu")) { return (new T2K_CC1pip_H2O_XSec_1DEnuDelta_nu(samplekey)); } else if (!name.compare("T2K_CC1pip_H2O_XSec_1DEnuMB_nu")) { return (new T2K_CC1pip_H2O_XSec_1DEnuMB_nu(samplekey)); } else if (!name.compare("T2K_CC1pip_H2O_XSec_1Dcosmu_nu")) { return (new T2K_CC1pip_H2O_XSec_1Dcosmu_nu(samplekey)); } else if (!name.compare("T2K_CC1pip_H2O_XSec_1Dcosmupi_nu")) { return (new T2K_CC1pip_H2O_XSec_1Dcosmupi_nu(samplekey)); } else if (!name.compare("T2K_CC1pip_H2O_XSec_1Dcospi_nu")) { return (new T2K_CC1pip_H2O_XSec_1Dcospi_nu(samplekey)); } else if (!name.compare("T2K_CC1pip_H2O_XSec_1Dpmu_nu")) { return (new T2K_CC1pip_H2O_XSec_1Dpmu_nu(samplekey)); } else if (!name.compare("T2K_CC1pip_H2O_XSec_1Dppi_nu")) { return (new T2K_CC1pip_H2O_XSec_1Dppi_nu(samplekey)); /* T2K CC0pi + np CH samples */ } else if (!name.compare("T2K_CC0pinp_STV_XSec_1Ddpt_nu")) { return (new T2K_CC0pinp_STV_XSec_1Ddpt_nu(samplekey)); } else if (!name.compare("T2K_CC0pinp_STV_XSec_1Ddphit_nu")) { return (new T2K_CC0pinp_STV_XSec_1Ddphit_nu(samplekey)); } else if (!name.compare("T2K_CC0pinp_STV_XSec_1Ddat_nu")) { return (new T2K_CC0pinp_STV_XSec_1Ddat_nu(samplekey)); } else if (!name.compare("T2K_CC0pi1p_XSec_3DPcoscos_nu_nonuniform")) { return (new T2K_CC0pi1p_XSec_3DPcoscos_nu_nonuniform(samplekey)); } else if (!name.compare("T2K_CC0pinp_ifk_XSec_3Dinfp_nu")) { return (new T2K_CC0pinp_ifk_XSec_3Dinfp_nu(samplekey)); } else if (!name.compare("T2K_CC0pinp_ifk_XSec_3Dinfa_nu")) { return (new T2K_CC0pinp_ifk_XSec_3Dinfa_nu(samplekey)); } else if (!name.compare("T2K_CC0pinp_ifk_XSec_3Dinfip_nu")) { return (new T2K_CC0pinp_ifk_XSec_3Dinfip_nu(samplekey)); // SciBooNE COH studies } else #endif #ifndef __NO_SciBooNE__ if (!name.compare("SciBooNE_CCCOH_STOP_NTrks_nu")) { return (new SciBooNE_CCCOH_STOP_NTrks_nu(samplekey)); } else if (!name.compare("SciBooNE_CCCOH_1TRK_1DQ2_nu")) { return (new SciBooNE_CCCOH_1TRK_1DQ2_nu(samplekey)); } else if (!name.compare("SciBooNE_CCCOH_1TRK_1Dpmu_nu")) { return (new SciBooNE_CCCOH_1TRK_1Dpmu_nu(samplekey)); } else if (!name.compare("SciBooNE_CCCOH_1TRK_1Dthetamu_nu")) { return (new SciBooNE_CCCOH_1TRK_1Dthetamu_nu(samplekey)); } else if (!name.compare("SciBooNE_CCCOH_MuPr_1DQ2_nu")) { return (new SciBooNE_CCCOH_MuPr_1DQ2_nu(samplekey)); } else if (!name.compare("SciBooNE_CCCOH_MuPr_1Dpmu_nu")) { return (new SciBooNE_CCCOH_MuPr_1Dpmu_nu(samplekey)); } else if (!name.compare("SciBooNE_CCCOH_MuPr_1Dthetamu_nu")) { return (new SciBooNE_CCCOH_MuPr_1Dthetamu_nu(samplekey)); } else if (!name.compare("SciBooNE_CCCOH_MuPiVA_1DQ2_nu")) { return (new SciBooNE_CCCOH_MuPiVA_1DQ2_nu(samplekey)); } else if (!name.compare("SciBooNE_CCCOH_MuPiVA_1Dpmu_nu")) { return (new SciBooNE_CCCOH_MuPiVA_1Dpmu_nu(samplekey)); } else if (!name.compare("SciBooNE_CCCOH_MuPiVA_1Dthetamu_nu")) { return (new SciBooNE_CCCOH_MuPiVA_1Dthetamu_nu(samplekey)); } else if (!name.compare("SciBooNE_CCCOH_MuPiNoVA_1DQ2_nu")) { return (new SciBooNE_CCCOH_MuPiNoVA_1DQ2_nu(samplekey)); } else if (!name.compare("SciBooNE_CCCOH_MuPiNoVA_1Dthetapr_nu")) { return (new SciBooNE_CCCOH_MuPiNoVA_1Dthetapr_nu(samplekey)); } else if (!name.compare("SciBooNE_CCCOH_MuPiNoVA_1Dthetapi_nu")) { return (new SciBooNE_CCCOH_MuPiNoVA_1Dthetapi_nu(samplekey)); } else if (!name.compare("SciBooNE_CCCOH_MuPiNoVA_1Dthetamu_nu")) { return (new SciBooNE_CCCOH_MuPiNoVA_1Dthetamu_nu(samplekey)); } else if (!name.compare("SciBooNE_CCCOH_MuPiNoVA_1Dpmu_nu")) { return (new SciBooNE_CCCOH_MuPiNoVA_1Dpmu_nu(samplekey)); } else if (!name.compare("SciBooNE_CCCOH_STOPFINAL_1DQ2_nu")) { return (new SciBooNE_CCCOH_STOPFINAL_1DQ2_nu(samplekey)); /* K2K Samples */ /* NC1pi0 */ } else #endif #ifndef __NO_K2K__ if (!name.compare("K2K_NC1pi0_Evt_1Dppi0_nu")) { return (new K2K_NC1pi0_Evt_1Dppi0_nu(samplekey)); /* Fake Studies */ } else #endif if (name.find("ExpMultDist_CCQE_XSec_1D") != std::string::npos && name.find("_FakeStudy") != std::string::npos) { return ( new ExpMultDist_CCQE_XSec_1DVar_FakeStudy(name, file, rw, type, fkdt)); } else if (name.find("ExpMultDist_CCQE_XSec_2D") != std::string::npos && name.find("_FakeStudy") != std::string::npos) { return ( new ExpMultDist_CCQE_XSec_2DVar_FakeStudy(name, file, rw, type, fkdt)); } else if (name.find("GenericFlux_") != std::string::npos) { return (new GenericFlux_Tester(name, file, rw, type, fkdt)); } else if (name.find("GenericVectors_") != std::string::npos) { return (new GenericFlux_Vectors(name, file, rw, type, fkdt)); } else if (!name.compare("T2K2017_FakeData")) { return (new T2K2017_FakeData(samplekey)); } else if (!name.compare("MCStudy_CCQE")) { return (new MCStudy_CCQEHistograms(name, file, rw, type, fkdt)); } else if (!name.compare("ElectronFlux_FlatTree")) { return (new ElectronFlux_FlatTree(name, file, rw, type, fkdt)); } else if (name.find("ElectronData_") != std::string::npos) { return new ElectronScattering_DurhamData(samplekey); } else if (name.find("MuonValidation_") != std::string::npos) { return (new MCStudy_MuonValidation(name, file, rw, type, fkdt)); } else if (!name.compare("NIWGOfficialPlots")) { return (new OfficialNIWGPlots(samplekey)); } else if (!name.compare("Simple_Osc")) { return (new Simple_Osc(samplekey)); } else if (!name.compare("Smear_SVDUnfold_Propagation_Osc")) { return (new Smear_SVDUnfold_Propagation_Osc(samplekey)); } else { - QTHROW("Error: No such sample: " << name << std::endl); + NUIS_ABORT("Error: No such sample: " << name << std::endl); } // Return NULL if no sample loaded. return NULL; } } diff --git a/src/FitBase/EventManager.cxx b/src/FitBase/EventManager.cxx index d92ffd6..771a4ba 100644 --- a/src/FitBase/EventManager.cxx +++ b/src/FitBase/EventManager.cxx @@ -1,140 +1,140 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "EventManager.h" EventManager* EventManager::m_evtmgrInstance = NULL; EventManager& EventManager::Get(void) { if (!m_evtmgrInstance) { m_evtmgrInstance = new EventManager; } return *m_evtmgrInstance; } FitWeight* EventManager::GetRW() { return fRW; }; InputHandlerBase* EventManager::GetInput(int infile) { return finputs[infile]; }; FitEvent* EventManager::GetEvent(int infile, int i) { /* finputs[infile]->ReadEvent(i); FitEvent* evtpt = finputs[infile]->GetEventPointer(); // If we don't need a full reweight if (!frwneeded[infile][i]) { evtpt->Weight = calc_rw[infile][i]; // if we do need a full reweight } else { evtpt->RWWeight = fRW->CalcWeight(evtpt); evtpt->Weight = evtpt->RWWeight * evtpt->InputWeight; calc_rw[infile][i] = evtpt->Weight; frwneeded[infile][i] = false; } */ return NULL; } double EventManager::GetEventWeight(int infile, int i) { /* if (!frwneeded[infile][i]) { return calc_rw[infile][i]; } finputs[infile]->GetTreeEntry(i); FitEvent* evtpt = finputs[infile]->GetEventPointer(); double Weight = fRW->CalcWeight(evtpt) * evtpt->InputWeight; calc_rw[infile][i] = Weight; frwneeded[infile][i] = false; */ double Weight = 1.0; return Weight; } std::map EventManager::GetInputs() { return finputs; } InputHandlerBase* EventManager::AddInput(std::string handle, std::string infile) { // Expect INPUTTYPE:FileLocation(s) std::vector file_descriptor = GeneralUtils::ParseToStr(infile, ":"); if (file_descriptor.size() != 2) { - QTHROW("File descriptor had no filetype declaration: \"" << infile + NUIS_ABORT("File descriptor had no filetype declaration: \"" << infile << "\". expected \"FILETYPE:file.root\""); } InputUtils::InputType inpType = InputUtils::ParseInputType(file_descriptor[0]); int id = GetInputID(file_descriptor[1]); if ((uint)id != fid.size()) { - QLOG(SAM,"Event manager already contains " << file_descriptor[1]); + NUIS_LOG(SAM,"Event manager already contains " << file_descriptor[1]); return finputs[id]; } fid[file_descriptor[1]] = id; finputs[id] = InputUtils::CreateInputHandler(handle, inpType, file_descriptor[1]); frwneeded[id] = std::vector(finputs[id]->GetNEvents(), true); calc_rw[id] = std::vector(finputs[id]->GetNEvents(), 0.0); - QLOG(SAM,"Registered " << handle << " with EventManager."); + NUIS_LOG(SAM,"Registered " << handle << " with EventManager."); return finputs[id]; } // Reset the weight flags // Should be called for every succesful event loop void EventManager::ResetWeightFlags() { /* // Loop over the inpts for (std::map::iterator iter = finputs.begin(); iter != finputs.end(); iter++) { int id = iter->first; frwneeded[id].clear(); // Reset so that all events need the reweight frwneeded[id] = std::vector(finputs[id]->GetNEvents(), true); } */ } EventManager::EventManager() { fRW = new FitWeight("FitWeight"); finputs.clear(); }; EventManager::~EventManager() { delete fRW; finputs.clear(); }; int EventManager::GetInputID(std::string infile) { if (fid.find(infile) == fid.end()) { return fid.size(); } return fid[infile]; } void EventManager::SetRW(FitWeight* rw){ fRW = rw; } diff --git a/src/FitBase/JointMeas1D.cxx b/src/FitBase/JointMeas1D.cxx index 6dc1138..7d7afec 100644 --- a/src/FitBase/JointMeas1D.cxx +++ b/src/FitBase/JointMeas1D.cxx @@ -1,2222 +1,2222 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This ile is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "JointMeas1D.h" //******************************************************************** JointMeas1D::JointMeas1D(void) { //******************************************************************** // XSec Scalings fScaleFactor = -1.0; fCurrentNorm = 1.0; // Histograms fDataHist = NULL; fDataTrue = NULL; fMCHist = NULL; fMCFine = NULL; fMCWeighted = NULL; fMaskHist = NULL; // Covar covar = NULL; fFullCovar = NULL; fCovar = NULL; fInvert = NULL; fDecomp = NULL; // Fake Data fFakeDataInput = ""; fFakeDataFile = NULL; // Options fDefaultTypes = "FIX/FULL/CHI2"; fAllowedTypes = "FIX,FREE,SHAPE/FULL,DIAG/CHI2/NORM/ENUCORR/Q2CORR/ENU1D/MASK"; fIsFix = false; fIsShape = false; fIsFree = false; fIsDiag = false; fIsFull = false; fAddNormPen = false; fIsMask = false; fIsChi2SVD = false; fIsRawEvents = false; fIsDifXSec = false; fIsEnu1D = false; // Inputs fInput = NULL; fRW = NULL; // Extra Histograms fMCHist_Modes = NULL; for (std::vector::const_iterator iter = fSubChain.begin(); iter != fSubChain.end(); iter++) { MeasurementBase *exp = *iter; if (exp) delete exp; } fSubChain.clear(); // Flags for Joint Measurements fIsRatio = false; fIsSummed = false; fSaveSubMeas = false; fIsJoint = true; } //******************************************************************** void JointMeas1D::SetupDefaultHist() { //******************************************************************** // Setup fMCHist fMCHist = (TH1D *)fDataHist->Clone(); fMCHist->SetNameTitle((fName + "_MC").c_str(), (fName + "_MC" + fPlotTitles).c_str()); // Setup fMCFine Int_t nBins = fMCHist->GetNbinsX(); fMCFine = new TH1D( (fName + "_MC_FINE").c_str(), (fName + "_MC_FINE" + fPlotTitles).c_str(), nBins * 6, fMCHist->GetBinLowEdge(1), fMCHist->GetBinLowEdge(nBins + 1)); fMCStat = (TH1D *)fMCHist->Clone(); fMCStat->Reset(); fMCHist->Reset(); fMCFine->Reset(); // Setup the NEUT Mode Array PlotUtils::CreateNeutModeArray((TH1D *)fMCHist, (TH1 **)fMCHist_PDG); PlotUtils::ResetNeutModeArray((TH1 **)fMCHist_PDG); // Setup bin masks using sample name if (fIsMask) { std::string maskloc = FitPar::Config().GetParDIR(fName + ".mask"); if (maskloc.empty()) { maskloc = FitPar::GetDataBase() + "/masks/" + fName + ".mask"; } SetBinMask(maskloc); } fMCHist_Modes = new TrueModeStack((fName + "_MODES").c_str(), ("True Channels"), fMCHist); SetAutoProcessTH1(fMCHist_Modes); return; } //******************************************************************** JointMeas1D::~JointMeas1D(void) { //******************************************************************** if (fDataHist) delete fDataHist; if (fDataTrue) delete fDataTrue; if (fMCHist) delete fMCHist; if (fMCFine) delete fMCFine; if (fMCWeighted) delete fMCWeighted; if (fMaskHist) delete fMaskHist; if (covar) delete covar; if (fFullCovar) delete fFullCovar; if (fCovar) delete fCovar; if (fInvert) delete fInvert; if (fDecomp) delete fDecomp; for (std::vector::const_iterator iter = fSubChain.begin(); iter != fSubChain.end(); iter++) { MeasurementBase *exp = *iter; if (exp) delete exp; } fSubChain.clear(); } //******************************************************************** SampleSettings JointMeas1D::LoadSampleSettings(nuiskey samplekey) { //******************************************************************** SampleSettings s = MeasurementBase::LoadSampleSettings(samplekey); // Parse Inputs fSubInFiles.clear(); std::vector entries = GeneralUtils::ParseToStr(s.GetS("input"), ";"); if (entries.size() < 2) { - QTHROW("Joint measurement expected to recieve at least two semi-colon " + NUIS_ABORT("Joint measurement expected to recieve at least two semi-colon " "separated input files, but recieved: \"" << s.GetS("input") << "\""); } std::vector first_file_descriptor = GeneralUtils::ParseToStr(entries.front(), ":"); if (first_file_descriptor.size() != 2) { - QTHROW("Found Joint measurement where the input file had no type: \"" + NUIS_ABORT("Found Joint measurement where the input file had no type: \"" << s.GetS("input") << "\", expected \"INPUTTYPE:File.root;File2.root\"."); } std::string inpType = first_file_descriptor[0]; for (std::vector::iterator iter = entries.begin(); iter != entries.end(); iter++) { if (GeneralUtils::ParseToStr(*iter, ":").size() != 2) { std::stringstream ss(""); ss << inpType << ":" << (*iter); fSubInFiles.push_back(ss.str()); } else { fSubInFiles.push_back(*iter); } } return s; } //******************************************************************** void JointMeas1D::FinaliseSampleSettings() { //******************************************************************** // Setup naming + renaming fName = fSettings.GetName(); fSettings.SetS("originalname", fName); if (fSettings.Has("rename")) { fName = fSettings.GetS("rename"); fSettings.SetS("name", fName); } // Setup all other options - QLOG(SAM, "Finalising Sample Settings: " << fName); + NUIS_LOG(SAM, "Finalising Sample Settings: " << fName); if ((fSettings.GetS("originalname").find("Evt") != std::string::npos)) { fIsRawEvents = true; - QLOG(SAM, "Found event rate measurement but using poisson likelihoods."); + NUIS_LOG(SAM, "Found event rate measurement but using poisson likelihoods."); } if (fSettings.GetS("originalname").find("XSec_1DEnu") != std::string::npos) { fIsEnu1D = true; - QLOG(SAM, "::" << fName << "::"); - QLOG(SAM, "Found XSec Enu measurement, applying flux integrated scaling, " + NUIS_LOG(SAM, "::" << fName << "::"); + NUIS_LOG(SAM, "Found XSec Enu measurement, applying flux integrated scaling, " << "not flux averaged!"); } if (fIsEnu1D && fIsRawEvents) { - QLOG(SAM, "Found 1D Enu XSec distribution AND fIsRawEvents, is this " + NUIS_LOG(SAM, "Found 1D Enu XSec distribution AND fIsRawEvents, is this " "really correct?!"); - QLOG(SAM, + NUIS_LOG(SAM, "Check experiment constructor for " << fName << " and correct this!"); - QLOG(SAM, "I live in " << __FILE__ << ":" << __LINE__); + NUIS_LOG(SAM, "I live in " << __FILE__ << ":" << __LINE__); exit(-1); } // Parse Inputs fSubInFiles.clear(); std::vector entries = GeneralUtils::ParseToStr(fSettings.GetS("input"), ";"); if (entries.size() < 2) { - QTHROW("Joint measurement expected to recieve at least two semi-colon " + NUIS_ABORT("Joint measurement expected to recieve at least two semi-colon " "separated input files, but recieved: \"" << fSettings.GetS("input") << "\""); } std::vector first_file_descriptor = GeneralUtils::ParseToStr(entries.front(), ":"); if (first_file_descriptor.size() != 2) { - QTHROW("Found Joint measurement where the input file had no type: \"" + NUIS_ABORT("Found Joint measurement where the input file had no type: \"" << fSettings.GetS("input") << "\", expected \"INPUTTYPE:File.root;File2.root\"."); } std::string inpType = first_file_descriptor[0]; for (std::vector::iterator iter = entries.begin(); iter != entries.end(); iter++) { if (GeneralUtils::ParseToStr(*iter, ":").size() != 2) { std::stringstream ss(""); ss << inpType << ":" << (*iter); fSubInFiles.push_back(ss.str()); } else { fSubInFiles.push_back(*iter); } } // Setup options SetFitOptions(fDefaultTypes); // defaults SetFitOptions(fSettings.GetS("type")); // user specified EnuMin = GeneralUtils::StrToDbl(fSettings.GetS("enu_min")); EnuMax = GeneralUtils::StrToDbl(fSettings.GetS("enu_max")); if (fAddNormPen) { if (fNormError <= 0.0) { - QERROR(FTL, "Norm error for class " << fName << " is 0.0!"); - QERROR(FTL, "If you want to use it please add fNormError=VAL"); + NUIS_ERR(FTL, "Norm error for class " << fName << " is 0.0!"); + NUIS_ERR(FTL, "If you want to use it please add fNormError=VAL"); throw; } } if (!fRW) fRW = FitBase::GetRW(); - QLOG(SAM, "Finalised Sample Settings"); + NUIS_LOG(SAM, "Finalised Sample Settings"); } //******************************************************************** void JointMeas1D::SetDataFromTextFile(std::string datafile) { //******************************************************************** - QLOG(SAM, "Reading data from text file: " << datafile); + NUIS_LOG(SAM, "Reading data from text file: " << datafile); fDataHist = PlotUtils::GetTH1DFromFile( datafile, fSettings.GetName() + "_data", fSettings.GetFullTitles()); } //******************************************************************** void JointMeas1D::SetDataFromRootFile(std::string datafile, std::string histname) { //******************************************************************** - QLOG(SAM, "Reading data from root file: " << datafile << ";" << histname); + NUIS_LOG(SAM, "Reading data from root file: " << datafile << ";" << histname); fDataHist = PlotUtils::GetTH1DFromRootFile(datafile, histname); fDataHist->SetNameTitle((fSettings.GetName() + "_data").c_str(), (fSettings.GetFullTitles()).c_str()); return; }; //******************************************************************** void JointMeas1D::SetPoissonErrors() { //******************************************************************** if (!fDataHist) { - QERROR(FTL, "Need a data hist to setup possion errors! "); - QTHROW("Setup Data First!"); + NUIS_ERR(FTL, "Need a data hist to setup possion errors! "); + NUIS_ABORT("Setup Data First!"); } for (int i = 0; i < fDataHist->GetNbinsX() + 1; i++) { fDataHist->SetBinError(i + 1, sqrt(fDataHist->GetBinContent(i + 1))); } } //******************************************************************** void JointMeas1D::SetCovarFromDiagonal(TH1D *data) { //******************************************************************** if (!data and fDataHist) { data = fDataHist; } if (data) { - QLOG(SAM, "Setting diagonal covariance for: " << data->GetName()); + NUIS_LOG(SAM, "Setting diagonal covariance for: " << data->GetName()); fFullCovar = StatUtils::MakeDiagonalCovarMatrix(data); covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); } else { - QERROR(FTL, "No data input provided to set diagonal covar from!"); + NUIS_ERR(FTL, "No data input provided to set diagonal covar from!"); } if (!fIsDiag) { - QERROR(FTL, "SetCovarMatrixFromDiag called for measurement " + NUIS_ERR(FTL, "SetCovarMatrixFromDiag called for measurement " << "that is not set as diagonal."); throw; } } //******************************************************************** void JointMeas1D::SetCovarFromTextFile(std::string covfile, int dim) { //******************************************************************** - QLOG(SAM, "Reading covariance from text file: " << covfile); + NUIS_LOG(SAM, "Reading covariance from text file: " << covfile); fFullCovar = StatUtils::GetCovarFromTextFile(covfile, dim); covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); } //******************************************************************** void JointMeas1D::SetCovarFromMultipleTextFiles(std::string covfiles, int dim) { //******************************************************************** if (dim == -1) { dim = fDataHist->GetNbinsX(); } std::vector covList = GeneralUtils::ParseToStr(covfiles, ";"); fFullCovar = new TMatrixDSym(dim); for (uint i = 0; i < covList.size(); ++i) { - QLOG(SAM, "Reading covariance from text file: " << covList[i]); + NUIS_LOG(SAM, "Reading covariance from text file: " << covList[i]); TMatrixDSym *temp_cov = StatUtils::GetCovarFromTextFile(covList[i], dim); (*fFullCovar) += (*temp_cov); delete temp_cov; } covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); } //******************************************************************** void JointMeas1D::SetCovarFromRootFile(std::string covfile, std::string histname) { //******************************************************************** - QLOG(SAM, + NUIS_LOG(SAM, "Reading covariance from text file: " << covfile << ";" << histname); fFullCovar = StatUtils::GetCovarFromRootFile(covfile, histname); covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); } //******************************************************************** void JointMeas1D::SetCovarInvertFromTextFile(std::string covfile, int dim) { //******************************************************************** - QLOG(SAM, "Reading inverted covariance from text file: " << covfile); + NUIS_LOG(SAM, "Reading inverted covariance from text file: " << covfile); covar = StatUtils::GetCovarFromTextFile(covfile, dim); fFullCovar = StatUtils::GetInvert(covar); fDecomp = StatUtils::GetDecomp(fFullCovar); } //******************************************************************** void JointMeas1D::SetCovarInvertFromRootFile(std::string covfile, std::string histname) { //******************************************************************** - QLOG(SAM, "Reading inverted covariance from text file: " << covfile << ";" + NUIS_LOG(SAM, "Reading inverted covariance from text file: " << covfile << ";" << histname); covar = StatUtils::GetCovarFromRootFile(covfile, histname); fFullCovar = StatUtils::GetInvert(covar); fDecomp = StatUtils::GetDecomp(fFullCovar); } //******************************************************************** void JointMeas1D::SetCorrelationFromTextFile(std::string covfile, int dim) { //******************************************************************** if (dim == -1) dim = fDataHist->GetNbinsX(); - QLOG(SAM, + NUIS_LOG(SAM, "Reading data correlations from text file: " << covfile << ";" << dim); TMatrixDSym *correlation = StatUtils::GetCovarFromTextFile(covfile, dim); if (!fDataHist) { - QTHROW("Trying to set correlations from text file but there is no " + NUIS_ABORT("Trying to set correlations from text file but there is no " "data to build it from. \n" << "In constructor make sure data is set before " "SetCorrelationFromTextFile is called. \n"); } // Fill covar from data errors and correlations fFullCovar = new TMatrixDSym(dim); for (int i = 0; i < fDataHist->GetNbinsX(); i++) { for (int j = 0; j < fDataHist->GetNbinsX(); j++) { (*fFullCovar)(i, j) = (*correlation)(i, j) * fDataHist->GetBinError(i + 1) * fDataHist->GetBinError(j + 1) * 1.E76; } } // Fill other covars. covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); delete correlation; } //******************************************************************** void JointMeas1D::SetCorrelationFromMultipleTextFiles(std::string corrfiles, int dim) { //******************************************************************** if (dim == -1) { dim = fDataHist->GetNbinsX(); } std::vector corrList = GeneralUtils::ParseToStr(corrfiles, ";"); fFullCovar = new TMatrixDSym(dim); for (uint i = 0; i < corrList.size(); ++i) { - QLOG(SAM, "Reading covariance from text file: " << corrList[i]); + NUIS_LOG(SAM, "Reading covariance from text file: " << corrList[i]); TMatrixDSym *temp_cov = StatUtils::GetCovarFromTextFile(corrList[i], dim); for (int i = 0; i < fDataHist->GetNbinsX(); i++) { for (int j = 0; j < fDataHist->GetNbinsX(); j++) { // Note that there is a factor of 1E76 here. It is very silly indeed. // However, if you remove it, you also need to fix the factors of 1E38 // added to the chi2 calculations! (*temp_cov)(i, j) = (*temp_cov)(i, j) * fDataHist->GetBinError(i + 1) * fDataHist->GetBinError(j + 1) * 1E76; } } (*fFullCovar) += (*temp_cov); delete temp_cov; } covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); } //******************************************************************** void JointMeas1D::SetCorrelationFromRootFile(std::string covfile, std::string histname) { //******************************************************************** - QLOG(SAM, "Reading data correlations from text file: " << covfile << ";" + NUIS_LOG(SAM, "Reading data correlations from text file: " << covfile << ";" << histname); TMatrixDSym *correlation = StatUtils::GetCovarFromRootFile(covfile, histname); if (!fDataHist) { - QTHROW("Trying to set correlations from text file but there is no " + NUIS_ABORT("Trying to set correlations from text file but there is no " "data to build it from. \n" << "In constructor make sure data is set before " "SetCorrelationFromTextFile is called. \n"); } // Fill covar from data errors and correlations fFullCovar = new TMatrixDSym(fDataHist->GetNbinsX()); for (int i = 0; i < fDataHist->GetNbinsX(); i++) { for (int j = 0; j < fDataHist->GetNbinsX(); j++) { (*fFullCovar)(i, j) = (*correlation)(i, j) * fDataHist->GetBinError(i + 1) * fDataHist->GetBinError(j + 1) * 1.E76; } } // Fill other covars. covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); delete correlation; } void JointMeas1D::SetShapeCovar() { // Return if this is missing any pre-requisites if (!fFullCovar) return; if (!fDataHist) return; // Also return if it's bloody stupid under the circumstances if (fIsDiag) return; fShapeCovar = StatUtils::ExtractShapeOnlyCovar(fFullCovar, fDataHist); return; } //******************************************************************** void JointMeas1D::SetCholDecompFromTextFile(std::string covfile, int dim) { //******************************************************************** - QLOG(SAM, "Reading cholesky from text file: " << covfile); + NUIS_LOG(SAM, "Reading cholesky from text file: " << covfile); TMatrixD *temp = StatUtils::GetMatrixFromTextFile(covfile, dim, dim); TMatrixD *trans = (TMatrixD *)temp->Clone(); trans->T(); (*trans) *= (*temp); fFullCovar = new TMatrixDSym(dim, trans->GetMatrixArray(), ""); covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); delete temp; delete trans; } //******************************************************************** void JointMeas1D::SetCholDecompFromRootFile(std::string covfile, std::string histname) { //******************************************************************** - QLOG(SAM, "Reading cholesky decomp from root file: " << covfile << ";" + NUIS_LOG(SAM, "Reading cholesky decomp from root file: " << covfile << ";" << histname); TMatrixD *temp = StatUtils::GetMatrixFromRootFile(covfile, histname); TMatrixD *trans = (TMatrixD *)temp->Clone(); trans->T(); (*trans) *= (*temp); fFullCovar = new TMatrixDSym(temp->GetNrows(), trans->GetMatrixArray(), ""); covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); delete temp; delete trans; } //******************************************************************** void JointMeas1D::ScaleData(double scale) { //******************************************************************** fDataHist->Scale(scale); } //******************************************************************** void JointMeas1D::ScaleCovar(double scale) { //******************************************************************** (*fFullCovar) *= scale; (*covar) *= 1.0 / scale; (*fDecomp) *= sqrt(scale); } //******************************************************************** void JointMeas1D::SetBinMask(std::string maskfile) { //******************************************************************** if (!fIsMask) return; - QLOG(SAM, "Reading bin mask from file: " << maskfile); + NUIS_LOG(SAM, "Reading bin mask from file: " << maskfile); // Create a mask histogram with dim of data int nbins = fDataHist->GetNbinsX(); fMaskHist = new TH1I((fSettings.GetName() + "_BINMASK").c_str(), (fSettings.GetName() + "_BINMASK; Bin; Mask?").c_str(), nbins, 0, nbins); std::string line; std::ifstream mask(maskfile.c_str(), std::ifstream::in); if (!mask.is_open()) { - QTHROW(" Cannot find mask file: " << maskfile); + NUIS_ABORT(" Cannot find mask file: " << maskfile); } while (std::getline(mask >> std::ws, line, '\n')) { std::vector entries = GeneralUtils::ParseToInt(line, " "); // Skip lines with poorly formatted lines if (entries.size() < 2) { - QLOG(WRN, "JointMeas1D::SetBinMask(), couldn't parse line: " << line); + NUIS_LOG(WRN, "JointMeas1D::SetBinMask(), couldn't parse line: " << line); continue; } // The first index should be the bin number, the second should be the mask // value. int val = 0; if (entries[1] > 0) val = 1; fMaskHist->SetBinContent(entries[0], val); } // Apply masking by setting masked data bins to zero PlotUtils::MaskBins(fDataHist, fMaskHist); return; } //******************************************************************** void JointMeas1D::FinaliseMeasurement() { //******************************************************************** - QLOG(SAM, "Finalising Measurement: " << fName); + NUIS_LOG(SAM, "Finalising Measurement: " << fName); // Make sure data is setup if (!fDataHist) { - QTHROW("No data has been setup inside " << fName << " constructor!"); + NUIS_ABORT("No data has been setup inside " << fName << " constructor!"); } // Make sure covariances are setup if (!fFullCovar) { fIsDiag = true; SetCovarFromDiagonal(fDataHist); } if (!covar) { covar = StatUtils::GetInvert(fFullCovar); } if (!fDecomp) { fDecomp = StatUtils::GetDecomp(fFullCovar); } // Push the diagonals of fFullCovar onto the data histogram // Comment out until scaling is used consistently... StatUtils::SetDataErrorFromCov(fDataHist, fFullCovar, 1E-38); // Setup fMCHist from data fMCHist = (TH1D *)fDataHist->Clone(); fMCHist->SetNameTitle((fSettings.GetName() + "_MC").c_str(), (fSettings.GetFullTitles()).c_str()); fMCHist->Reset(); // Setup fMCFine fMCFine = new TH1D("mcfine", "mcfine", fDataHist->GetNbinsX(), fMCHist->GetBinLowEdge(1), fMCHist->GetBinLowEdge(fDataHist->GetNbinsX() + 1)); fMCFine->SetNameTitle((fSettings.GetName() + "_MC_FINE").c_str(), (fSettings.GetFullTitles()).c_str()); fMCFine->Reset(); // Setup MC Stat fMCStat = (TH1D *)fMCHist->Clone(); fMCStat->Reset(); // Search drawopts for possible types to include by default std::string drawopts = FitPar::Config().GetParS("drawopts"); if (drawopts.find("MODES") != std::string::npos) { fMCHist_Modes = new TrueModeStack((fSettings.GetName() + "_MODES").c_str(), ("True Channels"), fMCHist); SetAutoProcessTH1(fMCHist_Modes); } // Setup bin masks using sample name if (fIsMask) { std::string curname = fName; std::string origname = fSettings.GetS("originalname"); // Check rename.mask std::string maskloc = FitPar::Config().GetParDIR(curname + ".mask"); // Check origname.mask if (maskloc.empty()) maskloc = FitPar::Config().GetParDIR(origname + ".mask"); // Check database if (maskloc.empty()) { maskloc = FitPar::GetDataBase() + "/masks/" + origname + ".mask"; } // Setup Bin Mask SetBinMask(maskloc); } /* if (fScaleFactor < 0) { ERR(FTL) << "I found a negative fScaleFactor in " << __FILE__ << ":" << __LINE__ << std::endl; ERR(FTL) << "fScaleFactor = " << fScaleFactor << std::endl; ERR(FTL) << "EXITING" << std::endl; throw; } */ // Create and fill Weighted Histogram if (!fMCWeighted) { fMCWeighted = (TH1D *)fMCHist->Clone(); fMCWeighted->SetNameTitle((fName + "_MCWGHTS").c_str(), (fName + "_MCWGHTS" + fPlotTitles).c_str()); fMCWeighted->GetYaxis()->SetTitle("Weighted Events"); } } //******************************************************************** void JointMeas1D::SetFitOptions(std::string opt) { //******************************************************************** // Do nothing if default given if (opt == "DEFAULT") return; // CHECK Conflicting Fit Options std::vector fit_option_allow = GeneralUtils::ParseToStr(fAllowedTypes, "/"); for (UInt_t i = 0; i < fit_option_allow.size(); i++) { std::vector fit_option_section = GeneralUtils::ParseToStr(fit_option_allow.at(i), ","); bool found_option = false; for (UInt_t j = 0; j < fit_option_section.size(); j++) { std::string av_opt = fit_option_section.at(j); if (!found_option and opt.find(av_opt) != std::string::npos) { found_option = true; } else if (found_option and opt.find(av_opt) != std::string::npos) { - QTHROW("ERROR: Conflicting fit options provided: " + NUIS_ABORT("ERROR: Conflicting fit options provided: " << opt << std::endl << "Conflicting group = " << fit_option_section.at(i) << std::endl << "You should only supply one of these options in card file."); } } } // Check all options are allowed std::vector fit_options_input = GeneralUtils::ParseToStr(opt, "/"); for (UInt_t i = 0; i < fit_options_input.size(); i++) { if (fAllowedTypes.find(fit_options_input.at(i)) == std::string::npos) { - QERROR(FTL, "ERROR: Fit Option '" + NUIS_ERR(FTL, "ERROR: Fit Option '" << fit_options_input.at(i) << "' Provided is not allowed for this measurement."); - QERROR(FTL, "Fit Options should be provided as a '/' seperated list " + NUIS_ERR(FTL, "Fit Options should be provided as a '/' seperated list " "(e.g. FREE/DIAG/NORM)"); - QERROR(FTL, "Available options for " << fName << " are '" << fAllowedTypes + NUIS_ERR(FTL, "Available options for " << fName << " are '" << fAllowedTypes << "'"); throw; } } // Set TYPE fFitType = opt; // FIX,SHAPE,FREE if (opt.find("FIX") != std::string::npos) { fIsFree = fIsShape = false; fIsFix = true; } else if (opt.find("SHAPE") != std::string::npos) { fIsFree = fIsFix = false; fIsShape = true; } else if (opt.find("FREE") != std::string::npos) { fIsFix = fIsShape = false; fIsFree = true; } // DIAG,FULL (or default to full) if (opt.find("DIAG") != std::string::npos) { fIsDiag = true; fIsFull = false; } else if (opt.find("FULL") != std::string::npos) { fIsDiag = false; fIsFull = true; } // CHI2/LL (OTHERS?) if (opt.find("LOG") != std::string::npos) { fIsChi2 = false; - QERROR(FTL, "No other LIKELIHOODS properly supported!"); - QERROR(FTL, "Try to use a chi2!"); + NUIS_ERR(FTL, "No other LIKELIHOODS properly supported!"); + NUIS_ERR(FTL, "Try to use a chi2!"); throw; } else { fIsChi2 = true; } // EXTRAS if (opt.find("RAW") != std::string::npos) fIsRawEvents = true; if (opt.find("DIF") != std::string::npos) fIsDifXSec = true; if (opt.find("ENU1D") != std::string::npos) fIsEnu1D = true; if (opt.find("NORM") != std::string::npos) fAddNormPen = true; if (opt.find("MASK") != std::string::npos) fIsMask = true; return; }; //******************************************************************** void JointMeas1D::SetSmearingMatrix(std::string smearfile, int truedim, int recodim) { //******************************************************************** // The smearing matrix describes the migration from true bins (rows) to reco // bins (columns) // Counter over the true bins! int row = 0; std::string line; std::ifstream smear(smearfile.c_str(), std::ifstream::in); // Note that the smearing matrix may be rectangular. fSmearMatrix = new TMatrixD(truedim, recodim); if (smear.is_open()) { - QLOG(SAM, "Reading smearing matrix from file: " << smearfile); + NUIS_LOG(SAM, "Reading smearing matrix from file: " << smearfile); } else { - QTHROW("Smearing matrix provided is incorrect: " << smearfile); + NUIS_ABORT("Smearing matrix provided is incorrect: " << smearfile); } while (std::getline(smear >> std::ws, line, '\n')) { int column = 0; std::vector entries = GeneralUtils::ParseToDbl(line, " "); for (std::vector::iterator iter = entries.begin(); iter != entries.end(); iter++) { (*fSmearMatrix)(row, column) = (*iter) / 100.; // Convert to fraction from // percentage (this may not be // general enough) column++; } row++; } return; } //******************************************************************** void JointMeas1D::ApplySmearingMatrix() { //******************************************************************** if (!fSmearMatrix) { - QERROR(WRN, + NUIS_ERR(WRN, fName << ": attempted to apply smearing matrix, but none was set"); return; } TH1D *unsmeared = (TH1D *)fMCHist->Clone(); TH1D *smeared = (TH1D *)fMCHist->Clone(); smeared->Reset(); // Loop over reconstructed bins // true = row; reco = column for (int rbin = 0; rbin < fSmearMatrix->GetNcols(); ++rbin) { // Sum up the constributions from all true bins double rBinVal = 0; // Loop over true bins for (int tbin = 0; tbin < fSmearMatrix->GetNrows(); ++tbin) { rBinVal += (*fSmearMatrix)(tbin, rbin) * unsmeared->GetBinContent(tbin + 1); } smeared->SetBinContent(rbin + 1, rBinVal); } fMCHist = (TH1D *)smeared->Clone(); return; } /* Reconfigure LOOP */ //******************************************************************** void JointMeas1D::ResetAll() { //******************************************************************** fMCHist->Reset(); fMCFine->Reset(); fMCStat->Reset(); return; }; //******************************************************************** void JointMeas1D::FillHistograms() { //******************************************************************** if (Signal) { fMCHist->Fill(fXVar, Weight); fMCFine->Fill(fXVar, Weight); fMCStat->Fill(fXVar, 1.0); if (fMCHist_Modes) fMCHist_Modes->Fill(Mode, fXVar, Weight); } return; }; //******************************************************************** void JointMeas1D::ScaleEvents() { //******************************************************************** - QLOG(FIT, "Scaling JointMeas1D"); + NUIS_LOG(FIT, "Scaling JointMeas1D"); // Fill MCWeighted; for (int i = 0; i < fMCHist->GetNbinsX(); i++) { fMCWeighted->SetBinContent(i + 1, fMCHist->GetBinContent(i + 1)); fMCWeighted->SetBinError(i + 1, fMCHist->GetBinError(i + 1)); } // Setup Stat ratios for MC and MC Fine double *statratio = new double[fMCHist->GetNbinsX()]; for (int i = 0; i < fMCHist->GetNbinsX(); i++) { if (fMCHist->GetBinContent(i + 1) != 0) { statratio[i] = fMCHist->GetBinError(i + 1) / fMCHist->GetBinContent(i + 1); } else { statratio[i] = 0.0; } } double *statratiofine = new double[fMCFine->GetNbinsX()]; for (int i = 0; i < fMCFine->GetNbinsX(); i++) { if (fMCFine->GetBinContent(i + 1) != 0) { statratiofine[i] = fMCFine->GetBinError(i + 1) / fMCFine->GetBinContent(i + 1); } else { statratiofine[i] = 0.0; } } // Scaling for raw event rates if (fIsRawEvents) { double datamcratio = fDataHist->Integral() / fMCHist->Integral(); fMCHist->Scale(datamcratio); fMCFine->Scale(datamcratio); if (fMCHist_Modes) fMCHist_Modes->Scale(datamcratio); // Scaling for XSec as function of Enu } else if (fIsEnu1D) { PlotUtils::FluxUnfoldedScaling(fMCHist, GetFluxHistogram(), GetEventHistogram(), fScaleFactor, fNEvents); PlotUtils::FluxUnfoldedScaling(fMCFine, GetFluxHistogram(), GetEventHistogram(), fScaleFactor, fNEvents); // if (fMCHist_Modes) { // PlotUtils::FluxUnfoldedScaling(fMCHist_Modes, GetFluxHistogram(), // GetEventHistogram(), fScaleFactor, // fNEvents); // } // Any other differential scaling } else { fMCHist->Scale(fScaleFactor, "width"); fMCFine->Scale(fScaleFactor, "width"); if (fMCHist_Modes) { fMCHist_Modes->Scale(fScaleFactor, "width"); } } // Proper error scaling - ROOT Freaks out with xsec weights sometimes for (int i = 0; i < fMCStat->GetNbinsX(); i++) { fMCHist->SetBinError(i + 1, fMCHist->GetBinContent(i + 1) * statratio[i]); } for (int i = 0; i < fMCFine->GetNbinsX(); i++) { fMCFine->SetBinError(i + 1, fMCFine->GetBinContent(i + 1) * statratiofine[i]); } // Clean up delete statratio; delete statratiofine; return; }; //******************************************************************** void JointMeas1D::ApplyNormScale(double norm) { //******************************************************************** fCurrentNorm = norm; fMCHist->Scale(1.0 / norm); fMCFine->Scale(1.0 / norm); return; }; /* Statistic Functions - Outsources to StatUtils */ //******************************************************************** int JointMeas1D::GetNDOF() { //******************************************************************** int ndof = fDataHist->GetNbinsX(); if (fMaskHist) ndof -= fMaskHist->Integral(); return ndof; } //******************************************************************** double JointMeas1D::GetLikelihood() { //******************************************************************** // If this is for a ratio, there is no data histogram to compare to! if (fNoData || !fDataHist) return 0.; // Apply Masking to MC if Required. if (fIsMask and fMaskHist) { PlotUtils::MaskBins(fMCHist, fMaskHist); } // Sort Shape Scaling double scaleF = 0.0; if (fIsShape) { if (fMCHist->Integral(1, fMCHist->GetNbinsX(), "width")) { scaleF = fDataHist->Integral(1, fDataHist->GetNbinsX(), "width") / fMCHist->Integral(1, fMCHist->GetNbinsX(), "width"); fMCHist->Scale(scaleF); fMCFine->Scale(scaleF); } } // Likelihood Calculation double stat = 0.; if (fIsChi2) { if (fIsRawEvents) { stat = StatUtils::GetChi2FromEventRate(fDataHist, fMCHist, fMaskHist); } else if (fIsDiag) { stat = StatUtils::GetChi2FromDiag(fDataHist, fMCHist, fMaskHist); } else if (!fIsDiag and !fIsRawEvents) { stat = StatUtils::GetChi2FromCov(fDataHist, fMCHist, covar, fMaskHist); } } // Sort Penalty Terms if (fAddNormPen) { double penalty = (1. - fCurrentNorm) * (1. - fCurrentNorm) / (fNormError * fNormError); stat += penalty; } // Return to normal scaling if (fIsShape and !FitPar::Config().GetParB("saveshapescaling")) { fMCHist->Scale(1. / scaleF); fMCFine->Scale(1. / scaleF); } fLikelihood = stat; return stat; } /* Fake Data Functions */ //******************************************************************** void JointMeas1D::SetFakeDataValues(std::string fakeOption) { //******************************************************************** // Setup original/datatrue TH1D *tempdata = (TH1D *)fDataHist->Clone(); if (!fIsFakeData) { fIsFakeData = true; // Make a copy of the original data histogram. if (!fDataOrig) fDataOrig = (TH1D *)fDataHist->Clone((fName + "_data_original").c_str()); } else { ResetFakeData(); } // Setup Inputs fFakeDataInput = fakeOption; - QLOG(SAM, "Setting fake data from : " << fFakeDataInput); + NUIS_LOG(SAM, "Setting fake data from : " << fFakeDataInput); // From MC if (fFakeDataInput.compare("MC") == 0) { fDataHist = (TH1D *)fMCHist->Clone((fName + "_MC").c_str()); // Fake File } else { if (!fFakeDataFile) fFakeDataFile = new TFile(fFakeDataInput.c_str(), "READ"); fDataHist = (TH1D *)fFakeDataFile->Get((fName + "_MC").c_str()); } // Setup Data Hist fDataHist->SetNameTitle((fName + "_FAKE").c_str(), (fName + fPlotTitles).c_str()); // Replace Data True if (fDataTrue) delete fDataTrue; fDataTrue = (TH1D *)fDataHist->Clone(); fDataTrue->SetNameTitle((fName + "_FAKE_TRUE").c_str(), (fName + fPlotTitles).c_str()); // Make a new covariance for fake data hist. int nbins = fDataHist->GetNbinsX(); double alpha_i = 0.0; double alpha_j = 0.0; for (int i = 0; i < nbins; i++) { for (int j = 0; j < nbins; j++) { alpha_i = fDataHist->GetBinContent(i + 1) / tempdata->GetBinContent(i + 1); alpha_j = fDataHist->GetBinContent(j + 1) / tempdata->GetBinContent(j + 1); (*fFullCovar)(i, j) = alpha_i * alpha_j * (*fFullCovar)(i, j); } } // Setup Covariances if (covar) delete covar; covar = StatUtils::GetInvert(fFullCovar); if (fDecomp) delete fDecomp; fDecomp = StatUtils::GetInvert(fFullCovar); delete tempdata; return; }; //******************************************************************** void JointMeas1D::ResetFakeData() { //******************************************************************** if (fIsFakeData) { if (fDataHist) delete fDataHist; fDataHist = (TH1D *)fDataTrue->Clone((fSettings.GetName() + "_FKDAT").c_str()); } } //******************************************************************** void JointMeas1D::ResetData() { //******************************************************************** if (fIsFakeData) { if (fDataHist) delete fDataHist; fDataHist = (TH1D *)fDataOrig->Clone((fSettings.GetName() + "_data").c_str()); } fIsFakeData = false; } //******************************************************************** void JointMeas1D::ThrowCovariance() { //******************************************************************** // Take a fDecomposition and use it to throw the current dataset. // Requires fDataTrue also be set incase used repeatedly. if (fDataHist) delete fDataHist; fDataHist = StatUtils::ThrowHistogram(fDataTrue, fFullCovar); return; }; //******************************************************************** void JointMeas1D::ThrowDataToy() { //******************************************************************** if (!fDataTrue) fDataTrue = (TH1D *)fDataHist->Clone(); if (fMCHist) delete fMCHist; fMCHist = StatUtils::ThrowHistogram(fDataTrue, fFullCovar); } /* Access Functions */ //******************************************************************** TH1D *JointMeas1D::GetMCHistogram() { //******************************************************************** if (!fMCHist) return fMCHist; std::ostringstream chi2; chi2 << "#chi^{2}=" << std::setprecision(5) << this->GetLikelihood(); int linecolor = kRed; int linestyle = 1; int linewidth = 1; int fillcolor = 0; int fillstyle = 1001; if (fSettings.Has("linecolor")) linecolor = fSettings.GetI("linecolor"); if (fSettings.Has("linestyle")) linestyle = fSettings.GetI("linestyle"); if (fSettings.Has("linewidth")) linewidth = fSettings.GetI("linewidth"); if (fSettings.Has("fillcolor")) fillcolor = fSettings.GetI("fillcolor"); if (fSettings.Has("fillstyle")) fillstyle = fSettings.GetI("fillstyle"); fMCHist->SetTitle(chi2.str().c_str()); fMCHist->SetLineColor(linecolor); fMCHist->SetLineStyle(linestyle); fMCHist->SetLineWidth(linewidth); fMCHist->SetFillColor(fillcolor); fMCHist->SetFillStyle(fillstyle); return fMCHist; }; //******************************************************************** TH1D *JointMeas1D::GetDataHistogram() { //******************************************************************** if (!fDataHist) return fDataHist; int datacolor = kBlack; int datastyle = 1; int datawidth = 1; if (fSettings.Has("datacolor")) datacolor = fSettings.GetI("datacolor"); if (fSettings.Has("datastyle")) datastyle = fSettings.GetI("datastyle"); if (fSettings.Has("datawidth")) datawidth = fSettings.GetI("datawidth"); fDataHist->SetLineColor(datacolor); fDataHist->SetLineWidth(datawidth); fDataHist->SetMarkerStyle(datastyle); return fDataHist; }; /* Write Functions */ // Save all the histograms at once //******************************************************************** void JointMeas1D::Write(std::string drawOpt) { //******************************************************************** // Get Draw Options drawOpt = FitPar::Config().GetParS("drawopts"); // Write Settigns if (drawOpt.find("SETTINGS") != std::string::npos) { fSettings.Set("#chi^{2}", fLikelihood); fSettings.Set("NDOF", this->GetNDOF()); fSettings.Set("#chi^{2}/NDOF", fLikelihood / this->GetNDOF()); fSettings.Write(); } // Write Data/MC GetDataHistogram()->Write(); GetMCHistogram()->Write(); // Write Fine Histogram if (drawOpt.find("FINE") != std::string::npos) GetFineList().at(0)->Write(); // Write Weighted Histogram if (drawOpt.find("WEIGHTS") != std::string::npos && fMCWeighted) fMCWeighted->Write(); // Save Flux/Evt if no event manager if (!FitPar::Config().GetParB("EventManager")) { if (drawOpt.find("FLUX") != std::string::npos && GetFluxHistogram()) GetFluxHistogram()->Write(); if (drawOpt.find("EVT") != std::string::npos && GetEventHistogram()) GetEventHistogram()->Write(); if (drawOpt.find("XSEC") != std::string::npos && GetEventHistogram()) GetEventHistogram()->Write(); } // Write Mask if (fIsMask && (drawOpt.find("MASK") != std::string::npos)) { fMaskHist->Write(); } // Write Covariances if (drawOpt.find("COV") != std::string::npos && fFullCovar) { PlotUtils::GetFullCovarPlot(fFullCovar, fSettings.GetName()); } if (drawOpt.find("INVCOV") != std::string::npos && covar) { PlotUtils::GetInvCovarPlot(covar, fSettings.GetName()); } if (drawOpt.find("DECOMP") != std::string::npos && fDecomp) { PlotUtils::GetDecompCovarPlot(fDecomp, fSettings.GetName()); } // // Likelihood residual plots // if (drawOpt.find("RESIDUAL") != std::string::npos) { // WriteResidualPlots(); // } // Ratio and Shape Plots if (drawOpt.find("RATIO") != std::string::npos) { WriteRatioPlot(); } if (drawOpt.find("SHAPE") != std::string::npos) { WriteShapePlot(); if (drawOpt.find("RATIO") != std::string::npos) WriteShapeRatioPlot(); } // // RATIO // if (drawOpt.find("CANVMC") != std::string::npos) { // TCanvas* c1 = WriteMCCanvas(fDataHist, fMCHist); // c1->Write(); // delete c1; // } // // PDG // if (drawOpt.find("CANVPDG") != std::string::npos && fMCHist_Modes) { // TCanvas* c2 = WritePDGCanvas(fDataHist, fMCHist, fMCHist_Modes); // c2->Write(); // delete c2; // } // Write Extra Histograms AutoWriteExtraTH1(); WriteExtraHistograms(); if (fSaveSubMeas) { for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { MeasurementBase *exp = *expIter; exp->Write(drawOpt); } } // Returning - QLOG(SAM, "Written Histograms: " << fName); + NUIS_LOG(SAM, "Written Histograms: " << fName); return; } //******************************************************************** void JointMeas1D::WriteRatioPlot() { //******************************************************************** // Setup mc data ratios TH1D *dataRatio = (TH1D *)fDataHist->Clone((fName + "_data_RATIO").c_str()); TH1D *mcRatio = (TH1D *)fMCHist->Clone((fName + "_MC_RATIO").c_str()); // Extra MC Data Ratios for (int i = 0; i < mcRatio->GetNbinsX(); i++) { dataRatio->SetBinContent(i + 1, fDataHist->GetBinContent(i + 1) / fMCHist->GetBinContent(i + 1)); dataRatio->SetBinError(i + 1, fDataHist->GetBinError(i + 1) / fMCHist->GetBinContent(i + 1)); mcRatio->SetBinContent(i + 1, fMCHist->GetBinContent(i + 1) / fMCHist->GetBinContent(i + 1)); mcRatio->SetBinError(i + 1, fMCHist->GetBinError(i + 1) / fMCHist->GetBinContent(i + 1)); } // Write ratios mcRatio->Write(); dataRatio->Write(); delete mcRatio; delete dataRatio; } //******************************************************************** void JointMeas1D::WriteShapePlot() { //******************************************************************** TH1D *mcShape = (TH1D *)fMCHist->Clone((fName + "_MC_SHAPE").c_str()); double shapeScale = 1.0; if (fIsRawEvents) { shapeScale = fDataHist->Integral() / fMCHist->Integral(); } else { shapeScale = fDataHist->Integral("width") / fMCHist->Integral("width"); } mcShape->Scale(shapeScale); std::stringstream ss; ss << "Scale=" << shapeScale; mcShape->SetTitle(ss.str().c_str()); mcShape->SetLineWidth(3); mcShape->SetLineStyle(7); mcShape->Write(); delete mcShape; } //******************************************************************** void JointMeas1D::WriteShapeRatioPlot() { //******************************************************************** // Get a mcshape histogram TH1D *mcShape = (TH1D *)fMCHist->Clone((fName + "_MC_SHAPE").c_str()); double shapeScale = 1.0; if (fIsRawEvents) { shapeScale = fDataHist->Integral() / fMCHist->Integral(); } else { shapeScale = fDataHist->Integral("width") / fMCHist->Integral("width"); } mcShape->Scale(shapeScale); // Create shape ratio histograms TH1D *mcShapeRatio = (TH1D *)mcShape->Clone((fName + "_MC_SHAPE_RATIO").c_str()); TH1D *dataShapeRatio = (TH1D *)fDataHist->Clone((fName + "_data_SHAPE_RATIO").c_str()); // Divide the histograms mcShapeRatio->Divide(mcShape); dataShapeRatio->Divide(mcShape); // Colour the shape ratio plots mcShapeRatio->SetLineWidth(3); mcShapeRatio->SetLineStyle(7); mcShapeRatio->Write(); dataShapeRatio->Write(); delete mcShapeRatio; delete dataShapeRatio; } /* Setup Functions */ //******************************************************************** void JointMeas1D::SetupMeasurement(std::string input, std::string type, FitWeight *rw, std::string fkdt) { //******************************************************************** // For joint samples, input files are given as a semi-colon seperated list. // Parse this list and save it for later, and set up the types etc. if (FitPar::Config().GetParB("EventManager")) { - QERROR(FTL, "Event Manager does not yet work with JointMeas1D Samples"); - QERROR(FTL, "If you want good predictions for " + NUIS_ERR(FTL, "Event Manager does not yet work with JointMeas1D Samples"); + NUIS_ERR(FTL, "If you want good predictions for " << fName << " then run with it turned off! (-q EventManager=0)"); } fSubInFiles.clear(); std::vector entries = GeneralUtils::ParseToStr(input, ";"); if (entries.size() < 2) { - QTHROW("Joint measurement expected to recieve at least two semi-colon " + NUIS_ABORT("Joint measurement expected to recieve at least two semi-colon " "separated input files, but recieved: \"" << input << "\""); } std::vector first_file_descriptor = GeneralUtils::ParseToStr(entries.front(), ":"); if (first_file_descriptor.size() != 2) { - QTHROW("Found Joint measurement where the input file had no type: \"" + NUIS_ABORT("Found Joint measurement where the input file had no type: \"" << input << "\", expected \"INPUTTYPE:File.root;File2.root\"."); } std::string inpType = first_file_descriptor[0]; for (std::vector::iterator iter = entries.begin(); iter != entries.end(); iter++) { if (GeneralUtils::ParseToStr(*iter, ":").size() != 2) { std::stringstream ss(""); ss << inpType << ":" << (*iter); fSubInFiles.push_back(ss.str()); } else { fSubInFiles.push_back(*iter); } } // Set Engine and Fake Data fRW = rw; fFakeDataInput = fkdt; // Set Fit Options SetFitOptions(type); return; } /* XSec Functions */ //******************************************************************** double JointMeas1D::TotalIntegratedFlux(std::string intOpt, double low, double high) { //******************************************************************** double totalflux = 0.0; // Destroy the job for sub samples for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { MeasurementBase *exp = *expIter; double expflux = exp->TotalIntegratedFlux(intOpt, low, high); // Fill flux options if (fIsRatio) { totalflux = expflux; break; } if (fIsSummed) { totalflux += expflux; } } return totalflux; } /* Reconfigure Functions */ //******************************************************************** void JointMeas1D::Reconfigure() { //******************************************************************** for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { MeasurementBase *exp = *expIter; exp->Reconfigure(); } ConvertEventRates(); return; } //******************************************************************** void JointMeas1D::ConvertEventRates() { //******************************************************************** // Apply Event Scaling for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { MeasurementBase *exp = static_cast(*expIter); exp->ScaleEvents(); } // Joint function called by top level class MakePlots(); // Do Final Normalisation ApplyNormScale(fRW->GetSampleNorm(this->fName)); } //******************************************************************** void JointMeas1D::MakePlots() { //******************************************************************** // Reset the 1D histograms but not the subClasses ResetAll(); // If Summed if (fIsSummed) { for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { MeasurementBase *exp = static_cast(*expIter); this->fMCHist->Add(exp->GetMCList().at(0)); this->fMCFine->Add(exp->GetFineList().at(0)); } return; } // If Ratio if (fIsRatio) { int sample = 0; for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { MeasurementBase *exp = *expIter; if (sample == 0) { this->fMCHist->Add(exp->GetMCList().at(0)); this->fMCFine->Add(exp->GetFineList().at(0)); } else if (sample == 1) { this->fMCHist->Divide(exp->GetMCList().at(0)); this->fMCFine->Divide(exp->GetFineList().at(0)); } else { break; } sample++; } return; } return; } /* Access Functions */ //******************************************************************** std::vector JointMeas1D::GetMCList() { //******************************************************************** // Make Default Vector std::vector tempVect; tempVect.push_back(this->fMCHist); // Return vector from all sub samples for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { MeasurementBase *exp = *expIter; std::vector subTempVect = exp->GetMCList(); for (UInt_t i = 0; i < subTempVect.size(); i++) { tempVect.push_back(subTempVect.at(i)); } } return tempVect; } //******************************************************************** std::vector JointMeas1D::GetDataList() { //******************************************************************** // Make Default Vector std::vector tempVect; tempVect.push_back(this->fDataHist); // Return vector from all sub samples for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { MeasurementBase *exp = *expIter; std::vector subTempVect = exp->GetDataList(); for (UInt_t i = 0; i < subTempVect.size(); i++) { tempVect.push_back(subTempVect.at(i)); } } return tempVect; } //******************************************************************** std::vector JointMeas1D::GetFineList() { //******************************************************************** // Make Default Vector std::vector tempVect; tempVect.push_back(this->fMCFine); // Return vector from all sub samples for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { MeasurementBase *exp = *expIter; std::vector subTempVect = exp->GetFineList(); for (UInt_t i = 0; i < subTempVect.size(); i++) { tempVect.push_back(subTempVect.at(i)); } } return tempVect; } //******************************************************************** std::vector JointMeas1D::GetMaskList() { //******************************************************************** // Make Default Vector std::vector tempVect; tempVect.push_back(this->fMaskHist); // Return vector from all sub samples for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { MeasurementBase *exp = *expIter; std::vector subTempVect = exp->GetMaskList(); for (UInt_t i = 0; i < subTempVect.size(); i++) { tempVect.push_back(subTempVect.at(i)); } } return tempVect; } //******************************************************************** std::vector JointMeas1D::GetFluxList() { //******************************************************************** // Make Default Vector std::vector tempVect; tempVect.push_back(MeasurementBase::GetFluxHistogram()); // Return vector from all sub samples for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { MeasurementBase *exp = *expIter; std::vector subTempVect = exp->GetFluxList(); for (UInt_t i = 0; i < subTempVect.size(); i++) { tempVect.push_back(subTempVect.at(i)); } } return tempVect; } //******************************************************************** std::vector JointMeas1D::GetEventRateList() { //******************************************************************** // Make Default Vector std::vector tempVect; tempVect.push_back(MeasurementBase::GetEventHistogram()); // Return vector from all sub samples for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { MeasurementBase *exp = *expIter; std::vector subTempVect = exp->GetEventRateList(); for (UInt_t i = 0; i < subTempVect.size(); i++) { tempVect.push_back(subTempVect.at(i)); } } return tempVect; } //******************************************************************** std::vector JointMeas1D::GetXSecList() { //******************************************************************** // Make Default Vector std::vector tempVect; tempVect.push_back(MeasurementBase::GetXSecHistogram()); // Return vector from all sub samples for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { MeasurementBase *exp = *expIter; std::vector subTempVect = exp->GetXSecList(); for (UInt_t i = 0; i < subTempVect.size(); i++) { tempVect.push_back(subTempVect.at(i)); } } return tempVect; } //******************************************************************** TH1D *JointMeas1D::GetCombinedFlux() { //******************************************************************** TH1D *newflux = NULL; int sample = 0; for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { MeasurementBase *exp = *expIter; // Get flux from experiment std::vector fluxVect = exp->GetFluxList(); // Setup newflux if (sample == 0) { newflux = (TH1D *)fluxVect.at(0); newflux->Reset(); } // Add all fluxes for (UInt_t i = 0; i < fluxVect.size(); i++) { newflux->Add((TH1D *)fluxVect.at(i)); sample++; } } if (!newflux) { - QTHROW("No combined flux setup in JointMeas1D"); + NUIS_ABORT("No combined flux setup in JointMeas1D"); } return newflux; } //******************************************************************** TH1D *JointMeas1D::GetCombinedEventRate() { //******************************************************************** TH1D *newflux = NULL; int sample = 0; for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { MeasurementBase *exp = *expIter; // Get flux from experiment std::vector fluxVect = exp->GetFluxList(); // Setup newflux if (sample == 0) { newflux = (TH1D *)fluxVect.at(0); newflux->Reset(); } // Add all fluxes for (UInt_t i = 0; i < fluxVect.size(); i++) { newflux->Add(fluxVect.at(i)); sample++; } } if (!newflux) { - QTHROW("No combined event rate setup in JointMeas1D"); + NUIS_ABORT("No combined event rate setup in JointMeas1D"); } return newflux; } //******************************************************************** std::vector JointMeas1D::GetSubSamples() { //******************************************************************** std::vector exps; for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { exps.push_back(*expIter); } return exps; } //// CRAP TO BE REMOVED //******************************************************************** void JointMeas1D::SetDataValues(std::string dataFile) { //******************************************************************** // Override this function if the input file isn't in a suitable format - QLOG(SAM, "Reading data from: " << dataFile.c_str()); + NUIS_LOG(SAM, "Reading data from: " << dataFile.c_str()); fDataHist = PlotUtils::GetTH1DFromFile(dataFile, (fName + "_data"), fPlotTitles); fDataTrue = (TH1D *)fDataHist->Clone(); // Number of data points is number of bins fNDataPointsX = fDataHist->GetXaxis()->GetNbins(); return; }; //******************************************************************** void JointMeas1D::SetDataFromDatabase(std::string inhistfile, std::string histname) { //******************************************************************** - QLOG(SAM, "Filling histogram from " << inhistfile << "->" << histname); + NUIS_LOG(SAM, "Filling histogram from " << inhistfile << "->" << histname); fDataHist = PlotUtils::GetTH1DFromRootFile( (GeneralUtils::GetTopLevelDir() + "/data/" + inhistfile), histname); fDataHist->SetNameTitle((fName + "_data").c_str(), (fName + "_data").c_str()); return; }; //******************************************************************** void JointMeas1D::SetDataFromFile(std::string inhistfile, std::string histname) { //******************************************************************** - QLOG(SAM, "Filling histogram from " << inhistfile << "->" << histname); + NUIS_LOG(SAM, "Filling histogram from " << inhistfile << "->" << histname); fDataHist = PlotUtils::GetTH1DFromRootFile((inhistfile), histname); fDataHist->SetNameTitle((fName + "_data").c_str(), (fName + "_data").c_str()); return; }; //******************************************************************** void JointMeas1D::SetCovarMatrix(std::string covarFile) { //******************************************************************** // Covariance function, only really used when reading in the MB Covariances. TFile *tempFile = new TFile(covarFile.c_str(), "READ"); TH2D *covarPlot = new TH2D(); TH2D *fFullCovarPlot = new TH2D(); std::string covName = ""; std::string covOption = FitPar::Config().GetParS("thrown_covariance"); if (fIsShape || fIsFree) covName = "shp_"; if (fIsDiag) covName += "diag"; else covName += "full"; covarPlot = (TH2D *)tempFile->Get((covName + "cov").c_str()); if (!covOption.compare("SUB")) fFullCovarPlot = (TH2D *)tempFile->Get((covName + "cov").c_str()); else if (!covOption.compare("FULL")) fFullCovarPlot = (TH2D *)tempFile->Get("fullcov"); else { - QERROR(WRN, "Incorrect thrown_covariance option in parameters."); + NUIS_ERR(WRN, "Incorrect thrown_covariance option in parameters."); } int dim = int(fDataHist->GetNbinsX()); //-this->masked->Integral()); int covdim = int(fDataHist->GetNbinsX()); this->covar = new TMatrixDSym(dim); fFullCovar = new TMatrixDSym(dim); fDecomp = new TMatrixDSym(dim); int row, column = 0; row = 0; column = 0; for (Int_t i = 0; i < covdim; i++) { // if (this->masked->GetBinContent(i+1) > 0) continue; for (Int_t j = 0; j < covdim; j++) { // if (this->masked->GetBinContent(j+1) > 0) continue; (*this->covar)(row, column) = covarPlot->GetBinContent(i + 1, j + 1); (*fFullCovar)(row, column) = fFullCovarPlot->GetBinContent(i + 1, j + 1); column++; } column = 0; row++; } // Set bin errors on data if (!fIsDiag) { StatUtils::SetDataErrorFromCov(fDataHist, fFullCovar); } // Get Deteriminant and inverse matrix // fCovDet = this->covar->Determinant(); TDecompSVD LU = TDecompSVD(*this->covar); this->covar = new TMatrixDSym(dim, LU.Invert().GetMatrixArray(), ""); return; }; //******************************************************************** // Sets the covariance matrix from a provided file in a text format // scale is a multiplicative pre-factor to apply in the case where the // covariance is given in some unit (e.g. 1E-38) void JointMeas1D::SetCovarMatrixFromText(std::string covarFile, int dim, double scale) { //******************************************************************** // Make a counter to track the line number int row = 0; std::string line; std::ifstream covarread(covarFile.c_str(), std::ifstream::in); this->covar = new TMatrixDSym(dim); fFullCovar = new TMatrixDSym(dim); if (covarread.is_open()) { - QLOG(SAM, "Reading covariance matrix from file: " << covarFile); + NUIS_LOG(SAM, "Reading covariance matrix from file: " << covarFile); } else { - QERROR(FTL, "Covariance matrix provided is incorrect: " << covarFile); + NUIS_ERR(FTL, "Covariance matrix provided is incorrect: " << covarFile); } // Loop over the lines in the file while (std::getline(covarread >> std::ws, line, '\n')) { int column = 0; // Loop over entries and insert them into matrix std::vector entries = GeneralUtils::ParseToDbl(line, " "); if (entries.size() <= 1) { - QERROR(WRN, "SetCovarMatrixFromText -> Covariance matrix only has <= 1 " + NUIS_ERR(WRN, "SetCovarMatrixFromText -> Covariance matrix only has <= 1 " "entries on this line: " << row); } for (std::vector::iterator iter = entries.begin(); iter != entries.end(); iter++) { (*covar)(row, column) = *iter; (*fFullCovar)(row, column) = *iter; column++; } row++; } covarread.close(); // Scale the actualy covariance matrix by some multiplicative factor (*fFullCovar) *= scale; // Robust matrix inversion method TDecompSVD LU = TDecompSVD(*this->covar); // THIS IS ACTUALLY THE INVERSE COVARIANCE MATRIXA AAAAARGH delete this->covar; this->covar = new TMatrixDSym(dim, LU.Invert().GetMatrixArray(), ""); // Now need to multiply by the scaling factor // If the covariance (*this->covar) *= 1. / (scale); return; }; //******************************************************************** void JointMeas1D::SetCovarMatrixFromCorrText(std::string corrFile, int dim) { //******************************************************************** // Make a counter to track the line number int row = 0; std::string line; std::ifstream corr(corrFile.c_str(), std::ifstream::in); this->covar = new TMatrixDSym(dim); this->fFullCovar = new TMatrixDSym(dim); if (corr.is_open()) { - QLOG(SAM, + NUIS_LOG(SAM, "Reading and converting correlation matrix from file: " << corrFile); } else { - QERROR(FTL, "Correlation matrix provided is incorrect: " << corrFile); + NUIS_ERR(FTL, "Correlation matrix provided is incorrect: " << corrFile); exit(-1); } while (std::getline(corr >> std::ws, line, '\n')) { int column = 0; // Loop over entries and insert them into matrix // Multiply by the errors to get the covariance, rather than the correlation // matrix std::vector entries = GeneralUtils::ParseToDbl(line, " "); for (std::vector::iterator iter = entries.begin(); iter != entries.end(); iter++) { double val = (*iter) * this->fDataHist->GetBinError(row + 1) * 1E38 * this->fDataHist->GetBinError(column + 1) * 1E38; if (val == 0) { - QERROR(FTL, "Found a zero value in the covariance matrix, assuming " + NUIS_ERR(FTL, "Found a zero value in the covariance matrix, assuming " "this is an error!"); exit(-1); } (*this->covar)(row, column) = val; (*this->fFullCovar)(row, column) = val; column++; } row++; } // Robust matrix inversion method TDecompSVD LU = TDecompSVD(*this->covar); delete this->covar; this->covar = new TMatrixDSym(dim, LU.Invert().GetMatrixArray(), ""); return; }; //******************************************************************** // FullUnits refers to if we have "real" unscaled units in the covariance // matrix, e.g. 1E-76. If this is the case we need to scale it so that the chi2 // contribution is correct NUISANCE internally assumes the covariance matrix has // units of 1E76 void JointMeas1D::SetCovarFromDataFile(std::string covarFile, std::string covName, bool FullUnits) { //******************************************************************** - QLOG(SAM, "Getting covariance from " << covarFile << "->" << covName); + NUIS_LOG(SAM, "Getting covariance from " << covarFile << "->" << covName); TFile *tempFile = new TFile(covarFile.c_str(), "READ"); TH2D *covPlot = (TH2D *)tempFile->Get(covName.c_str()); covPlot->SetDirectory(0); // Scale the covariance matrix if it comes in normal units if (FullUnits) { covPlot->Scale(1.E76); } int dim = covPlot->GetNbinsX(); fFullCovar = new TMatrixDSym(dim); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { (*fFullCovar)(i, j) = covPlot->GetBinContent(i + 1, j + 1); } } this->covar = (TMatrixDSym *)fFullCovar->Clone(); fDecomp = (TMatrixDSym *)fFullCovar->Clone(); TDecompSVD LU = TDecompSVD(*this->covar); this->covar = new TMatrixDSym(dim, LU.Invert().GetMatrixArray(), ""); TDecompChol LUChol = TDecompChol(*fDecomp); LUChol.Decompose(); fDecomp = new TMatrixDSym(dim, LU.GetU().GetMatrixArray(), ""); return; }; // std::vector JointMeas1D::GetMCList(void){ // std::vector temp; // return temp; // } // std::vector JointMeas1D::GetDataList(void){ // std::vector temp; // return temp; // } // std::vector JointMeas1D::GetMaskList(void){ // std::vector temp; // return temp; // } // std::vector JointMeas1D::GetFineList(void){ // std::vector temp; // return temp; // } diff --git a/src/FitBase/JointMeas1D.h b/src/FitBase/JointMeas1D.h index 0fd2627..dd8c840 100644 --- a/src/FitBase/JointMeas1D.h +++ b/src/FitBase/JointMeas1D.h @@ -1,650 +1,650 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #ifndef JOINTMEASUREMENT_1D_H_SEEN #define JOINTMEASUREMENT_1D_H_SEEN /*! * \addtogroup FitBase * @{ */ #include #include #include #include #include #include #include #include #include // ROOT includes #include "Measurement1D.h" #include #include #include #include #include #include #include #include #include #include #include #include // External data fit includes #include "FitEvent.h" #include "FitUtils.h" #include "MeasurementBase.h" #include "PlotUtils.h" #include "StatUtils.h" //******************************************************************** /// 1D Measurement base class. Histogram handling is done in this base layer. class JointMeas1D : public MeasurementBase { //******************************************************************** public: /* Constructor/Deconstuctor */ JointMeas1D(void); virtual ~JointMeas1D(void); /* Setup Functions */ SampleSettings LoadSampleSettings(nuiskey samplekey); /// \brief Setup all configs once initialised /// /// Should be called after all configs have been setup inside fSettings /// container. Handles the processing of inputs and setting up of types. /// Replaces the old 'SetupMeasurement' function. void FinaliseSampleSettings(); /// \brief Read 1D data inputs from a text file. /// /// Inputfile should have the format: \n /// low_binedge_1 bin_content_1 bin_error_1 \n /// low_binedge_2 bin_content_2 bin_error_2 \n /// .... .... .... \n /// high_bin_edge_N 0.0 0.0 virtual void SetDataFromTextFile(std::string datafile); /// \brief Read 1D data inputs from a root file. /// /// inhistfile specifies the path to the root file /// histname specifies the name of the histogram. /// /// If no histogram name is given the inhistfile value /// is automatically parsed with ';' so that: \n /// 'myhistfile.root;myhistname' \n /// will also work. virtual void SetDataFromRootFile(std::string inhistfile, std::string histname = ""); /// \brief Set data bin errors to sqrt(entries) /// /// \warning REQUIRES DATA HISTOGRAM TO BE SET FIRST /// /// Sets the data errors as the sqrt of the bin contents /// Should be use for counting experiments virtual void SetPoissonErrors(); /// \brief Make diagonal covariance from data /// /// \warning If no histogram passed, data must be setup first! /// Setup the covariance inputs by taking the data histogram /// errors and setting up a diagonal covariance matrix. /// /// If no data is supplied, fDataHist is used if already set. virtual void SetCovarFromDiagonal(TH1D *data = NULL); /// \brief Read the data covariance from a text file. /// /// Inputfile should have the format: \n /// covariance_11 covariance_12 covariance_13 ... \n /// covariance_21 covariance_22 covariance_23 ... \n /// ... ... ... ... \n /// /// If no dimensions are given, it is assumed from the number /// entries in the first line of covfile. virtual void SetCovarFromTextFile(std::string covfile, int dim = -1); virtual void SetCovarFromMultipleTextFiles(std::string covfiles, int dim = -1); /// \brief Read the data covariance from a ROOT file. /// /// - covfile specifies the full path to the file /// - histname specifies the name of the covariance object. Both TMatrixDSym /// and TH2D are supported. /// /// If no histogram name is given the inhistfile value /// is automatically parsed with ; so that: \n /// mycovfile.root;myhistname \n /// will also work. virtual void SetCovarFromRootFile(std::string covfile, std::string histname); /// \brief Read the inverted data covariance from a text file. /// /// Inputfile should have similar format to that shown /// in SetCovarFromTextFile. /// /// If no dimensions are given, it is assumed from the number /// entries in the first line of covfile. virtual void SetCovarInvertFromTextFile(std::string covfile, int dim = -1); /// \brief Read the inverted data covariance from a ROOT file. /// /// Inputfile should have similar format to that shown /// in SetCovarFromRootFile. /// /// If no histogram name is given the inhistfile value /// is automatically parsed with ; so that: \n /// mycovfile.root;myhistname \n /// will also work. virtual void SetCovarInvertFromRootFile(std::string covfile, std::string histname); /// \brief Read the data correlations from a text file. /// /// \warning REQUIRES DATA HISTOGRAM TO BE SET FIRST /// /// Inputfile should have similar format to that shown /// in SetCovarFromTextFile. /// /// If no dimensions are given, it is assumed from the number /// entries in the first line of covfile. virtual void SetCorrelationFromTextFile(std::string covfile, int dim = -1); /// \brief Read the data correlations from multiple text files. /// /// \warning REQUIRES DATA HISTOGRAM TO BE SET FIRST /// /// Inputfile should have similar format to that shown /// in SetCovarFromTextFile. /// /// If no dimensions are given, it is assumed from the number /// entries in the first line of first covfile. virtual void SetCorrelationFromMultipleTextFiles(std::string corrfiles, int dim = -1); /// \brief Read the data correlations from a ROOT file. /// /// \warning REQUIRES DATA TO BE SET FIRST /// /// Inputfile should have similar format to that shown /// in SetCovarFromRootFile. /// /// If no histogram name is given the inhistfile value /// is automatically parsed with ; so that: \n /// mycovfile.root;myhistname \n /// will also work. virtual void SetCorrelationFromRootFile(std::string covfile, std::string histname); /// \brief Try to extract a shape-only matrix from the existing covariance virtual void SetShapeCovar(); /// \brief Read the cholesky decomposed covariance from a text file and turn /// it into a covariance /// /// Inputfile should have similar format to that shown /// in SetCovarFromTextFile. /// /// If no dimensions are given, it is assumed from the number /// entries in the first line of covfile. virtual void SetCholDecompFromTextFile(std::string covfile, int dim = -1); /// \brief Read the cholesky decomposed covariance from a ROOT file and turn /// it into a covariance /// /// Inputfile should have similar format to that shown /// in SetCovarFromRootFile. /// /// If no histogram name is given the inhistfile value /// is automatically parsed with ; so that: \n /// mycovfile.root;myhistname \n /// will also work. virtual void SetCholDecompFromRootFile(std::string covfile, std::string histname); /// \brief Scale the data by some scale factor virtual void ScaleData(double scale); /// \brief Scale the covariaince and its invert/decomp by some scale factor. virtual void ScaleCovar(double scale); /// \brief Setup a bin masking histogram and apply masking to data /// /// \warning REQUIRES DATA HISTOGRAM TO BE SET FIRST /// /// Reads in a list of bins in a text file to be masked. Format is: \n /// bin_index_1 1 \n /// bin_index_2 1 \n /// bin_index_3 1 \n /// /// If 0 is given then a bin entry will NOT be masked. So for example: \n\n /// 1 1 \n /// 2 1 \n /// 3 0 \n /// 4 1 \n\n /// Will mask only the 1st, 2nd, and 4th bins. /// /// Masking can be turned on by specifiying the MASK option when creating a /// sample. When this is passed NUISANCE will look in the following locations /// for the mask file: /// - FitPar::Config().GetParS(fName + ".mask") /// - "data/masks/" + fName + ".mask"; virtual void SetBinMask(std::string maskfile); /// \brief Final constructor setup /// \warning Should be called right at the end of the constructor. /// /// Contains a series of checks to ensure the data and inputs have been setup. /// Also creates the MC histograms needed for fitting. virtual void FinaliseMeasurement(); /// \brief Set the current fit options from a string. /// /// This is called twice for each sample, once to set the default /// and once to set the current setting (if anything other than default given) /// /// For this to work properly it requires the default and allowed types to be /// set correctly. These should be specified as a string listing options. /// /// To split up options so that NUISANCE can automatically detect ones that /// are conflicting. Any options seperated with the '/' symbol are non /// conflicting and can be given together, whereas any seperated with the ',' /// symbol cannot be specified by the end user at the same time. /// /// Default Type Examples: /// - DIAG/FIX = Default option will be a diagonal covariance, with FIXED /// norm. /// - MASK/SHAPE = Default option will be a masked hist, with SHAPE always on. /// /// Allowed Type examples: /// - 'FULL/DIAG/NORM/MASK' = Any of these options can be specified. /// - 'FULL,FREE,SHAPE/MASK/NORM' = User can give either FULL, FREE, or SHAPE /// as on option. MASK and NORM can also be included as options. virtual void SetFitOptions(std::string opt); /* Smearing */ /// \brief Read in smearing matrix from file /// /// Set the smearing matrix from a text file given the size of the matrix virtual void SetSmearingMatrix(std::string smearfile, int truedim, int recodim); /// \brief Apply smearing to MC true to get MC reco /// /// Apply smearing matrix to fMCHist using fSmearingMatrix virtual void ApplySmearingMatrix(void); /* Reconfigure Functions */ /// \brief Create a Measurement1D box /// /// Creates a new 1D variable box containing just fXVar. /// /// This box is the bare minimum required by the JointFCN when /// running fast reconfigures during a routine. /// If for some reason a sample needs extra variables to be saved then /// it should override this function creating its own MeasurementVariableBox /// that contains the extra variables. virtual MeasurementVariableBox *CreateBox() { return new MeasurementVariableBox1D(); }; /// \brief Reset all MC histograms /// /// Resets all standard histograms and those registered to auto /// process to zero. /// /// If extra histograms are not included in auto processing, then they must be /// reset by overriding this function and doing it manually if required. virtual void ResetAll(void); /// \brief Fill MC Histograms from XVar /// /// Fill standard histograms using fXVar, Weight read from the variable box. /// /// WARNING : Any extra MC histograms need to be filled by overriding this /// function, even if they have been set to auto process. virtual void FillHistograms(void); // \brief Convert event rates to final histogram /// /// Apply standard scaling procedure to standard mc histograms to convert from /// raw events to xsec prediction. /// /// If any distributions have been set to auto process /// that is done during this function call, and a differential xsec is /// assumed. If that is not the case this function must be overriden. virtual void ScaleEvents(void); /// \brief Scale MC by a factor=1/norm /// /// Apply a simple normalisation scaling if the option FREE or a /// norm_parameter has been specified in the NUISANCE routine. virtual void ApplyNormScale(double norm); /* Statistical Functions */ /// \brief Get Number of degrees of freedom /// /// Returns the number bins inside the data histogram accounting for /// any bin masking applied. virtual int GetNDOF(void); /// \brief Return Data/MC Likelihood at current state /// /// Returns the likelihood of the data given the current MC prediction. /// Diferent likelihoods definitions are used depending on the FitOptions. virtual double GetLikelihood(void); /* Fake Data */ /// \brief Set the fake data values from either a file, or MC /// /// - Setting from a file "path": \n /// When reading from a file the full path must be given to a standard /// nuisance output. The standard MC histogram should have a name that matches /// this sample for it to be read in. /// \n\n /// - Setting from "MC": \n /// If the MC option is given the current MC prediction is used as fake data. virtual void SetFakeDataValues(std::string fakeOption); /// \brief Reset fake data back to starting fake data /// /// Reset the fake data back to original fake data (Reset back to before /// ThrowCovariance was first called) virtual void ResetFakeData(void); /// \brief Reset fake data back to original data /// /// Reset the data histogram back to the true original dataset for this sample /// before any fake data was defined. virtual void ResetData(void); /// \brief Generate fake data by throwing the covariance. /// /// Can be used on fake MC data or just the original dataset. /// Call ResetFakeData or ResetData to return to values before the throw. virtual void ThrowCovariance(void); /// \brief Throw the data by its assigned errors and assign this to MC /// /// Used when creating data toys by assign the MC to this thrown data /// so that the likelihood is calculated between data and thrown data virtual void ThrowDataToy(void); /* Access Functions */ /// \brief Returns nicely formatted MC Histogram /// /// Format options can also be given in the samplesettings: /// - linecolor /// - linestyle /// - linewidth /// - fillcolor /// - fillstyle /// /// So to have a sample line colored differently in the xml cardfile put: \n /// virtual TH1D *GetMCHistogram(void); /// \brief Returns nicely formatted data Histogram /// /// Format options can also be given in the samplesettings: /// - datacolor /// - datastyle /// - datawidth /// /// So to have a sample data colored differently in the xml cardfile put: \n /// virtual TH1D *GetDataHistogram(void); /// \brief Returns a list of all MC histograms. /// /// Override this if you have extra histograms that need to be /// accessed outside of the Measurement1D class. virtual std::vector GetMCList(void); /// \brief Returns a list of all Data histograms. /// /// Override this if you have extra histograms that need to be /// accessed outside of the Measurement1D class. virtual std::vector GetDataList(void); /// \brief Returns a list of all Mask histograms. /// /// Override this if you have extra histograms that need to be /// accessed outside of the Measurement1D class. virtual std::vector GetMaskList(void); /// \brief Returns a list of all Fine histograms. /// /// Override this if you have extra histograms that need to be /// accessed outside of the Measurement1D class. virtual std::vector GetFineList(void); /* Write Functions */ /// \brief Save the current state to the current TFile directory \n /// /// Data/MC are both saved by default. /// A range of other histograms can be saved by setting the /// config option 'drawopts'. /// /// Possible options: \n /// - FINE = Write Fine Histogram \n /// - WEIGHTS = Write Weighted MC Histogram (before scaling) \n /// - FLUX = Write Flux Histogram from MC Input \n /// - EVT = Write Event Histogram from MC Input \n /// - XSEC = Write XSec Histogram from MC Input \n /// - MASK = Write Mask Histogram \n /// - COV = Write Covariance Histogram \n /// - INVCOV = Write Inverted Covariance Histogram \n /// - DECMOP = Write Decomp. Covariance Histogram \n /// - RESIDUAL= Write Resudial Histograms \n /// - RATIO = Write Data/MC Ratio Histograms \n /// - SHAPE = Write MC Shape Histograms norm. to Data \n /// - CANVMC = Build MC Canvas Showing Data, MC, Shape \n /// - MODES = Write PDG Stack \n /// - CANVPDG = Build MC Canvas Showing Data, PDGStack \n /// /// So to save a range of these in parameters/config.xml set: \n /// virtual void Write(std::string drawOpt); virtual void WriteRatioPlot(); virtual void WriteShapePlot(); virtual void WriteShapeRatioPlot(); double TotalIntegratedFlux(std::string intOpt, double low, double high); //* // OLD DEFUNCTIONS // /// OLD FUNCTION virtual void SetupMeasurement(std::string input, std::string type, FitWeight *rw, std::string fkdt); /// OLD FUNCTION virtual void SetupDefaultHist(void); /// OLD FUNCTION virtual void SetDataValues(std::string dataFile); /// OLD FUNCTION virtual void SetDataFromFile(std::string inhistfile, std::string histname); /// OLD FUNCTION virtual void SetDataFromDatabase(std::string inhistfile, std::string histname); /// OLD FUNCTION virtual void SetCovarMatrix(std::string covarFile); /// OLD FUNCTION virtual void SetCovarMatrixFromText(std::string covarFile, int dim, double scale = 1.0); /// OLD FUNCTION virtual void SetCovarMatrixFromCorrText(std::string covarFile, int dim); /// OLD FUNCTION virtual void SetCovarFromDataFile(std::string covarFile, std::string covName, bool FullUnits = false); ////// JOINT MEAS1D Functions ////// /* Reconfigure Functions */ /// Call reconfigure on every sub sample virtual void Reconfigure(); /// Stitch the sub sample plots together to make a final fMCHist after /// reconfigure has been called virtual void MakePlots(); virtual std::vector GetSubSamples(); virtual void ConvertEventRates(); /* Access Functions */ virtual std::vector GetFluxList(); virtual std::vector GetEventRateList(); virtual std::vector GetXSecList(); //! Return a flux integrated across all sub samples virtual TH1D *GetCombinedFlux(); //! Return an event rate integrated across all sub samples virtual TH1D *GetCombinedEventRate(); virtual TH1D *GetEventHistogram() { return GetCombinedEventRate(); }; virtual TH1D *GetXSecHistogram() { - QERROR(WRN, + NUIS_ERR(WRN, "XSec histogram not properly implemented for joint measurements."); return MeasurementBase::GetXSecHistogram(); }; virtual TH1D *GetFluxHistogram() { return GetCombinedFlux(); }; protected: // Data TH1D *fDataHist; ///< default data histogram TH1D *fDataOrig; ///< histogram to store original data before throws. TH1D *fDataTrue; ///< histogram to store true dataset std::string fPlotTitles; ///< Plot title x and y for the histograms // MC TH1D *fMCHist; ///< default MC Histogram used in the chi2 fits TH1D *fMCFine; ///< finely binned MC histogram TH1D *fMCStat; ///< histogram with unweighted events to properly calculate TH1D *fMCWeighted; ///< Weighted histogram before xsec scaling TH1I *fMaskHist; ///< Mask histogram for neglecting specific bins TMatrixD *fSmearMatrix; ///< Smearing matrix (note, this is not symmetric) TrueModeStack *fMCHist_Modes; ///< Optional True Mode Stack // Statistical TMatrixDSym *covar; ///< Inverted Covariance TMatrixDSym *fFullCovar; ///< Full Covariance TMatrixDSym *fDecomp; ///< Decomposed Covariance TMatrixDSym *fCorrel; ///< Correlation Matrix TMatrixDSym *fShapeCovar; ///< Shape-only covariance TMatrixDSym *fCovar; ///< New FullCovar TMatrixDSym *fInvert; ///< New covar double fNormError; ///< Sample norm error // Fake Data bool fIsFakeData; ///< Flag: is the current data fake from MC std::string fFakeDataInput; ///< Input fake data file path TFile *fFakeDataFile; ///< Input fake data file // Fit specific flags std::string fFitType; ///< Current fit type std::string fAllowedTypes; ///< Fit Types Possible std::string fDefaultTypes; ///< Starting Default Fit Types bool fIsShape; ///< Flag : Perform Shape-only fit bool fIsFree; ///< Flag : Perform normalisation free fit bool fIsDiag; ///< Flag : only include uncorrelated diagonal errors bool fIsMask; ///< Flag : Apply bin masking bool fIsRawEvents; ///< Flag : Are bin contents just event rates bool fIsEnu1D; ///< Flag : Perform Flux Unfolded Scaling bool fIsChi2SVD; ///< Flag : Use alternative Chi2 SVD Method (Do not use) bool fAddNormPen; ///< Flag : Add a normalisation penalty term to the chi2. bool fIsFix; ///< Flag : keeping norm fixed bool fIsFull; ///< Flag : using full covariaince bool fIsDifXSec; ///< Flag : creating a dif xsec bool fIsChi2; ///< Flag : using Chi2 over LL methods bool fIsSmeared; ///< Flag : Apply smearing? /// OLD STUFF TO REMOVE TH1D *fMCHist_PDG[61]; ///< REMOVE OLD MC PDG Plot // Arrays for data entries Double_t *fXBins; ///< REMOVE xBin edges Double_t *fDataValues; ///< REMOVE data bin contents Double_t *fDataErrors; ///< REMOVE data bin errors Int_t fNDataPointsX; ///< REMOVE number of data points //// JOINT MEAS1D OBJECTS //// std::vector fSubChain; //!< Vector of experimental classes //! that are the sub measurements std::vector fSubInFiles; //!< vector of input files for each of the sub measurements. bool fIsRatio; //!< Flag: is this sample a hist1/hist2 ratio sample bool fIsSummed; //!< Flag: is this sample a combination hist1 + hist2 bool fSaveSubMeas; //!< Flag: Save each of the histograms from the sub //! samples as well as this joint samples plots double fLikelihood; }; /*! @} */ #endif diff --git a/src/FitBase/Measurement1D.cxx b/src/FitBase/Measurement1D.cxx index d0c4ea5..a1ebaa7 100644 --- a/src/FitBase/Measurement1D.cxx +++ b/src/FitBase/Measurement1D.cxx @@ -1,1898 +1,1898 @@ // Copyright 2016 L. Pickering, P. Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This ile is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "Measurement1D.h" //******************************************************************** Measurement1D::Measurement1D(void) { //******************************************************************** // XSec Scalings fScaleFactor = -1.0; fCurrentNorm = 1.0; // Histograms fDataHist = NULL; fDataTrue = NULL; fMCHist = NULL; fMCFine = NULL; fMCWeighted = NULL; fMaskHist = NULL; // Covar covar = NULL; fFullCovar = NULL; fShapeCovar = NULL; fCovar = NULL; fInvert = NULL; fDecomp = NULL; // Fake Data fFakeDataInput = ""; fFakeDataFile = NULL; // Options fDefaultTypes = "FIX/FULL/CHI2"; fAllowedTypes = "FIX,FREE,SHAPE/FULL,DIAG/CHI2/NORM/ENUCORR/Q2CORR/ENU1D/MASK/NOWIDTH"; fIsFix = false; fIsShape = false; fIsFree = false; fIsDiag = false; fIsFull = false; fAddNormPen = false; fIsMask = false; fIsChi2SVD = false; fIsRawEvents = false; fIsNoWidth = false; fIsDifXSec = false; fIsEnu1D = false; // Inputs fInput = NULL; fRW = NULL; // Extra Histograms fMCHist_Modes = NULL; } //******************************************************************** Measurement1D::~Measurement1D(void) { //******************************************************************** if (fDataHist) delete fDataHist; if (fDataTrue) delete fDataTrue; if (fMCHist) delete fMCHist; if (fMCFine) delete fMCFine; if (fMCWeighted) delete fMCWeighted; if (fMaskHist) delete fMaskHist; if (covar) delete covar; if (fFullCovar) delete fFullCovar; if (fShapeCovar) delete fShapeCovar; if (fCovar) delete fCovar; if (fInvert) delete fInvert; if (fDecomp) delete fDecomp; } //******************************************************************** void Measurement1D::FinaliseSampleSettings() { //******************************************************************** MeasurementBase::FinaliseSampleSettings(); // Setup naming + renaming fName = fSettings.GetName(); fSettings.SetS("originalname", fName); if (fSettings.Has("rename")) { fName = fSettings.GetS("rename"); fSettings.SetS("name", fName); } // Setup all other options - QLOG(SAM, "Finalising Sample Settings: " << fName); + NUIS_LOG(SAM, "Finalising Sample Settings: " << fName); if ((fSettings.GetS("originalname").find("Evt") != std::string::npos)) { fIsRawEvents = true; - QLOG(SAM, "Found event rate measurement but using poisson likelihoods."); + NUIS_LOG(SAM, "Found event rate measurement but using poisson likelihoods."); } if (fSettings.GetS("originalname").find("XSec_1DEnu") != std::string::npos) { fIsEnu1D = true; - QLOG(SAM, "::" << fName << "::"); - QLOG(SAM, "Found XSec Enu measurement, applying flux integrated scaling, " + NUIS_LOG(SAM, "::" << fName << "::"); + NUIS_LOG(SAM, "Found XSec Enu measurement, applying flux integrated scaling, " << "not flux averaged!"); } if (fIsEnu1D && fIsRawEvents) { - QERROR(FTL, "Found 1D Enu XSec distribution AND fIsRawEvents, is this " + NUIS_ERR(FTL, "Found 1D Enu XSec distribution AND fIsRawEvents, is this " "really correct?!"); - QERROR(FTL, "Check experiment constructor for " << fName + NUIS_ERR(FTL, "Check experiment constructor for " << fName << " and correct this!"); - QERROR(FTL, "I live in " << __FILE__ << ":" << __LINE__); + NUIS_ERR(FTL, "I live in " << __FILE__ << ":" << __LINE__); throw; } if (!fRW) fRW = FitBase::GetRW(); if (!fInput and !fIsJoint) SetupInputs(fSettings.GetS("input")); // Setup options SetFitOptions(fDefaultTypes); // defaults SetFitOptions(fSettings.GetS("type")); // user specified EnuMin = GeneralUtils::StrToDbl(fSettings.GetS("enu_min")); EnuMax = GeneralUtils::StrToDbl(fSettings.GetS("enu_max")); if (fAddNormPen) { if (fNormError <= 0.0) { - QERROR(FTL, "Norm error for class " << fName << " is 0.0!"); - QERROR(FTL, "If you want to use it please add fNormError=VAL"); + NUIS_ERR(FTL, "Norm error for class " << fName << " is 0.0!"); + NUIS_ERR(FTL, "If you want to use it please add fNormError=VAL"); throw; } } } //******************************************************************** void Measurement1D::CreateDataHistogram(int dimx, double *binx) { //******************************************************************** if (fDataHist) delete fDataHist; fDataHist = new TH1D((fSettings.GetName() + "_data").c_str(), (fSettings.GetFullTitles()).c_str(), dimx, binx); } //******************************************************************** void Measurement1D::SetDataFromTextFile(std::string datafile) { //******************************************************************** - QLOG(SAM, "Reading data from text file: " << datafile); + NUIS_LOG(SAM, "Reading data from text file: " << datafile); fDataHist = PlotUtils::GetTH1DFromFile( datafile, fSettings.GetName() + "_data", fSettings.GetFullTitles()); } //******************************************************************** void Measurement1D::SetDataFromRootFile(std::string datafile, std::string histname) { //******************************************************************** - QLOG(SAM, "Reading data from root file: " << datafile << ";" << histname); + NUIS_LOG(SAM, "Reading data from root file: " << datafile << ";" << histname); fDataHist = PlotUtils::GetTH1DFromRootFile(datafile, histname); fDataHist->SetNameTitle((fSettings.GetName() + "_data").c_str(), (fSettings.GetFullTitles()).c_str()); return; }; //******************************************************************** void Measurement1D::SetEmptyData() { //******************************************************************** fDataHist = new TH1D("EMPTY_DATA", "EMPTY_DATA", 1, 0.0, 1.0); } //******************************************************************** void Measurement1D::SetPoissonErrors() { //******************************************************************** if (!fDataHist) { - QERROR(FTL, "Need a data hist to setup possion errors! "); - QERROR(FTL, "Setup Data First!"); + NUIS_ERR(FTL, "Need a data hist to setup possion errors! "); + NUIS_ERR(FTL, "Setup Data First!"); throw; } for (int i = 0; i < fDataHist->GetNbinsX() + 1; i++) { fDataHist->SetBinError(i + 1, sqrt(fDataHist->GetBinContent(i + 1))); } } //******************************************************************** void Measurement1D::SetCovarFromDiagonal(TH1D *data) { //******************************************************************** if (!data and fDataHist) { data = fDataHist; } if (data) { - QLOG(SAM, "Setting diagonal covariance for: " << data->GetName()); + NUIS_LOG(SAM, "Setting diagonal covariance for: " << data->GetName()); fFullCovar = StatUtils::MakeDiagonalCovarMatrix(data); covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); } else { - QTHROW("No data input provided to set diagonal covar from!"); + NUIS_ABORT("No data input provided to set diagonal covar from!"); } // if (!fIsDiag) { // ERR(FTL) << "SetCovarMatrixFromDiag called for measurement " // << "that is not set as diagonal." ); // throw; // } } //******************************************************************** void Measurement1D::SetCovarFromTextFile(std::string covfile, int dim) { //******************************************************************** if (dim == -1) { dim = fDataHist->GetNbinsX(); } - QLOG(SAM, "Reading covariance from text file: " << covfile); + NUIS_LOG(SAM, "Reading covariance from text file: " << covfile); fFullCovar = StatUtils::GetCovarFromTextFile(covfile, dim); covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); } //******************************************************************** void Measurement1D::SetCovarFromMultipleTextFiles(std::string covfiles, int dim) { //******************************************************************** if (dim == -1) { dim = fDataHist->GetNbinsX(); } std::vector covList = GeneralUtils::ParseToStr(covfiles, ";"); fFullCovar = new TMatrixDSym(dim); for (uint i = 0; i < covList.size(); ++i) { - QLOG(SAM, "Reading covariance from text file: " << covList[i]); + NUIS_LOG(SAM, "Reading covariance from text file: " << covList[i]); TMatrixDSym *temp_cov = StatUtils::GetCovarFromTextFile(covList[i], dim); (*fFullCovar) += (*temp_cov); delete temp_cov; } covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); } //******************************************************************** void Measurement1D::SetCovarFromRootFile(std::string covfile, std::string histname) { //******************************************************************** - QLOG(SAM, + NUIS_LOG(SAM, "Reading covariance from text file: " << covfile << ";" << histname); fFullCovar = StatUtils::GetCovarFromRootFile(covfile, histname); covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); } //******************************************************************** void Measurement1D::SetCovarInvertFromTextFile(std::string covfile, int dim) { //******************************************************************** if (dim == -1) { dim = fDataHist->GetNbinsX(); } - QLOG(SAM, "Reading inverted covariance from text file: " << covfile); + NUIS_LOG(SAM, "Reading inverted covariance from text file: " << covfile); covar = StatUtils::GetCovarFromTextFile(covfile, dim); fFullCovar = StatUtils::GetInvert(covar); fDecomp = StatUtils::GetDecomp(fFullCovar); } //******************************************************************** void Measurement1D::SetCovarInvertFromRootFile(std::string covfile, std::string histname) { //******************************************************************** - QLOG(SAM, "Reading inverted covariance from text file: " << covfile << ";" + NUIS_LOG(SAM, "Reading inverted covariance from text file: " << covfile << ";" << histname); covar = StatUtils::GetCovarFromRootFile(covfile, histname); fFullCovar = StatUtils::GetInvert(covar); fDecomp = StatUtils::GetDecomp(fFullCovar); } //******************************************************************** void Measurement1D::SetCorrelationFromTextFile(std::string covfile, int dim) { //******************************************************************** if (dim == -1) dim = fDataHist->GetNbinsX(); - QLOG(SAM, + NUIS_LOG(SAM, "Reading data correlations from text file: " << covfile << ";" << dim); TMatrixDSym *correlation = StatUtils::GetCovarFromTextFile(covfile, dim); if (!fDataHist) { - QTHROW("Trying to set correlations from text file but there is no " + NUIS_ABORT("Trying to set correlations from text file but there is no " "data to build it from. \n" << "In constructor make sure data is set before " "SetCorrelationFromTextFile is called. \n"); } // Fill covar from data errors and correlations fFullCovar = new TMatrixDSym(dim); for (int i = 0; i < fDataHist->GetNbinsX(); i++) { for (int j = 0; j < fDataHist->GetNbinsX(); j++) { (*fFullCovar)(i, j) = (*correlation)(i, j) * fDataHist->GetBinError(i + 1) * fDataHist->GetBinError(j + 1) * 1.E76; } } // Fill other covars. covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); delete correlation; } //******************************************************************** void Measurement1D::SetCorrelationFromMultipleTextFiles(std::string corrfiles, int dim) { //******************************************************************** if (dim == -1) { dim = fDataHist->GetNbinsX(); } std::vector corrList = GeneralUtils::ParseToStr(corrfiles, ";"); fFullCovar = new TMatrixDSym(dim); for (uint i = 0; i < corrList.size(); ++i) { - QLOG(SAM, "Reading covariance from text file: " << corrList[i]); + NUIS_LOG(SAM, "Reading covariance from text file: " << corrList[i]); TMatrixDSym *temp_cov = StatUtils::GetCovarFromTextFile(corrList[i], dim); for (int i = 0; i < fDataHist->GetNbinsX(); i++) { for (int j = 0; j < fDataHist->GetNbinsX(); j++) { (*temp_cov)(i, j) = (*temp_cov)(i, j) * fDataHist->GetBinError(i + 1) * fDataHist->GetBinError(j + 1) * 1.E76; } } (*fFullCovar) += (*temp_cov); delete temp_cov; } covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); } //******************************************************************** void Measurement1D::SetCorrelationFromRootFile(std::string covfile, std::string histname) { //******************************************************************** - QLOG(SAM, "Reading data correlations from text file: " << covfile << ";" + NUIS_LOG(SAM, "Reading data correlations from text file: " << covfile << ";" << histname); TMatrixDSym *correlation = StatUtils::GetCovarFromRootFile(covfile, histname); if (!fDataHist) { - QTHROW("Trying to set correlations from text file but there is no " + NUIS_ABORT("Trying to set correlations from text file but there is no " "data to build it from. \n" << "In constructor make sure data is set before " "SetCorrelationFromTextFile is called. \n"); } // Fill covar from data errors and correlations fFullCovar = new TMatrixDSym(fDataHist->GetNbinsX()); for (int i = 0; i < fDataHist->GetNbinsX(); i++) { for (int j = 0; j < fDataHist->GetNbinsX(); j++) { (*fFullCovar)(i, j) = (*correlation)(i, j) * fDataHist->GetBinError(i + 1) * fDataHist->GetBinError(j + 1) * 1.E76; } } // Fill other covars. covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); delete correlation; } //******************************************************************** void Measurement1D::SetCholDecompFromTextFile(std::string covfile, int dim) { //******************************************************************** if (dim == -1) { dim = fDataHist->GetNbinsX(); } - QLOG(SAM, "Reading cholesky from text file: " << covfile); + NUIS_LOG(SAM, "Reading cholesky from text file: " << covfile); TMatrixD *temp = StatUtils::GetMatrixFromTextFile(covfile, dim, dim); TMatrixD *trans = (TMatrixD *)temp->Clone(); trans->T(); (*trans) *= (*temp); fFullCovar = new TMatrixDSym(dim, trans->GetMatrixArray(), ""); covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); delete temp; delete trans; } //******************************************************************** void Measurement1D::SetCholDecompFromRootFile(std::string covfile, std::string histname) { //******************************************************************** - QLOG(SAM, "Reading cholesky decomp from root file: " << covfile << ";" + NUIS_LOG(SAM, "Reading cholesky decomp from root file: " << covfile << ";" << histname); TMatrixD *temp = StatUtils::GetMatrixFromRootFile(covfile, histname); TMatrixD *trans = (TMatrixD *)temp->Clone(); trans->T(); (*trans) *= (*temp); fFullCovar = new TMatrixDSym(temp->GetNrows(), trans->GetMatrixArray(), ""); covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); delete temp; delete trans; } void Measurement1D::SetShapeCovar() { // Return if this is missing any pre-requisites if (!fFullCovar) return; if (!fDataHist) return; // Also return if it's bloody stupid under the circumstances if (fIsDiag) return; fShapeCovar = StatUtils::ExtractShapeOnlyCovar(fFullCovar, fDataHist); return; } //******************************************************************** void Measurement1D::ScaleData(double scale) { //******************************************************************** fDataHist->Scale(scale); } //******************************************************************** void Measurement1D::ScaleDataErrors(double scale) { //******************************************************************** for (int i = 0; i < fDataHist->GetNbinsX(); i++) { fDataHist->SetBinError(i + 1, fDataHist->GetBinError(i + 1) * scale); } } //******************************************************************** void Measurement1D::ScaleCovar(double scale) { //******************************************************************** (*fFullCovar) *= scale; (*covar) *= 1.0 / scale; (*fDecomp) *= sqrt(scale); } //******************************************************************** void Measurement1D::SetBinMask(std::string maskfile) { //******************************************************************** if (!fIsMask) return; - QLOG(SAM, "Reading bin mask from file: " << maskfile); + NUIS_LOG(SAM, "Reading bin mask from file: " << maskfile); // Create a mask histogram with dim of data int nbins = fDataHist->GetNbinsX(); fMaskHist = new TH1I((fSettings.GetName() + "_BINMASK").c_str(), (fSettings.GetName() + "_BINMASK; Bin; Mask?").c_str(), nbins, 0, nbins); std::string line; std::ifstream mask(maskfile.c_str(), std::ifstream::in); if (!mask.is_open()) { - QTHROW("Cannot find mask file."); + NUIS_ABORT("Cannot find mask file."); } while (std::getline(mask >> std::ws, line, '\n')) { std::vector entries = GeneralUtils::ParseToInt(line, " "); // Skip lines with poorly formatted lines if (entries.size() < 2) { - QLOG(WRN, "Measurement1D::SetBinMask(), couldn't parse line: " << line); + NUIS_LOG(WRN, "Measurement1D::SetBinMask(), couldn't parse line: " << line); continue; } // The first index should be the bin number, the second should be the mask // value. int val = 0; if (entries[1] > 0) val = 1; fMaskHist->SetBinContent(entries[0], val); } // Apply masking by setting masked data bins to zero PlotUtils::MaskBins(fDataHist, fMaskHist); return; } //******************************************************************** void Measurement1D::FinaliseMeasurement() { //******************************************************************** - QLOG(SAM, "Finalising Measurement: " << fName); + NUIS_LOG(SAM, "Finalising Measurement: " << fName); if (fSettings.GetB("onlymc")) { if (fDataHist) delete fDataHist; fDataHist = new TH1D("empty_data", "empty_data", 1, 0.0, 1.0); } // Make sure data is setup if (!fDataHist) { - QTHROW("No data has been setup inside " << fName << " constructor!"); + NUIS_ABORT("No data has been setup inside " << fName << " constructor!"); } // Make sure covariances are setup if (!fFullCovar) { fIsDiag = true; SetCovarFromDiagonal(fDataHist); } if (!covar) { covar = StatUtils::GetInvert(fFullCovar); } if (!fDecomp) { fDecomp = StatUtils::GetDecomp(fFullCovar); } // Push the diagonals of fFullCovar onto the data histogram // Comment this out until the covariance/data scaling is consistent! StatUtils::SetDataErrorFromCov(fDataHist, fFullCovar, 1E-38); // If shape only, set covar and fDecomp using the shape-only matrix (if set) if (fIsShape && fShapeCovar && FitPar::Config().GetParB("UseShapeCovar")) { if (covar) delete covar; covar = StatUtils::GetInvert(fShapeCovar); if (fDecomp) delete fDecomp; fDecomp = StatUtils::GetDecomp(fFullCovar); } // Setup fMCHist from data fMCHist = (TH1D *)fDataHist->Clone(); fMCHist->SetNameTitle((fSettings.GetName() + "_MC").c_str(), (fSettings.GetFullTitles()).c_str()); fMCHist->Reset(); // Setup fMCFine fMCFine = new TH1D("mcfine", "mcfine", fDataHist->GetNbinsX() * 8, fMCHist->GetBinLowEdge(1), fMCHist->GetBinLowEdge(fDataHist->GetNbinsX() + 1)); fMCFine->SetNameTitle((fSettings.GetName() + "_MC_FINE").c_str(), (fSettings.GetFullTitles()).c_str()); fMCFine->Reset(); // Setup MC Stat fMCStat = (TH1D *)fMCHist->Clone(); fMCStat->Reset(); // Search drawopts for possible types to include by default std::string drawopts = FitPar::Config().GetParS("drawopts"); if (drawopts.find("MODES") != std::string::npos) { fMCHist_Modes = new TrueModeStack((fSettings.GetName() + "_MODES").c_str(), ("True Channels"), fMCHist); SetAutoProcessTH1(fMCHist_Modes, kCMD_Reset, kCMD_Norm, kCMD_Write); } // Setup bin masks using sample name if (fIsMask) { std::string curname = fName; std::string origname = fSettings.GetS("originalname"); // Check rename.mask std::string maskloc = FitPar::Config().GetParDIR(curname + ".mask"); // Check origname.mask if (maskloc.empty()) maskloc = FitPar::Config().GetParDIR(origname + ".mask"); // Check database if (maskloc.empty()) { maskloc = FitPar::GetDataBase() + "/masks/" + origname + ".mask"; } // Setup Bin Mask SetBinMask(maskloc); } if (fScaleFactor < 0) { - QERROR(FTL, "I found a negative fScaleFactor in " << __FILE__ << ":" + NUIS_ERR(FTL, "I found a negative fScaleFactor in " << __FILE__ << ":" << __LINE__); - QERROR(FTL, "fScaleFactor = " << fScaleFactor); - QERROR(FTL, "EXITING"); + NUIS_ERR(FTL, "fScaleFactor = " << fScaleFactor); + NUIS_ERR(FTL, "EXITING"); throw; } // Create and fill Weighted Histogram if (!fMCWeighted) { fMCWeighted = (TH1D *)fMCHist->Clone(); fMCWeighted->SetNameTitle((fName + "_MCWGHTS").c_str(), (fName + "_MCWGHTS" + fPlotTitles).c_str()); fMCWeighted->GetYaxis()->SetTitle("Weighted Events"); } } //******************************************************************** void Measurement1D::SetFitOptions(std::string opt) { //******************************************************************** // Do nothing if default given if (opt == "DEFAULT") return; // CHECK Conflicting Fit Options std::vector fit_option_allow = GeneralUtils::ParseToStr(fAllowedTypes, "/"); for (UInt_t i = 0; i < fit_option_allow.size(); i++) { std::vector fit_option_section = GeneralUtils::ParseToStr(fit_option_allow.at(i), ","); bool found_option = false; for (UInt_t j = 0; j < fit_option_section.size(); j++) { std::string av_opt = fit_option_section.at(j); if (!found_option and opt.find(av_opt) != std::string::npos) { found_option = true; } else if (found_option and opt.find(av_opt) != std::string::npos) { - QTHROW("ERROR: Conflicting fit options provided: " + NUIS_ABORT("ERROR: Conflicting fit options provided: " << opt << std::endl << "Conflicting group = " << fit_option_section.at(i) << std::endl << "You should only supply one of these options in card file."); } } } // Check all options are allowed std::vector fit_options_input = GeneralUtils::ParseToStr(opt, "/"); for (UInt_t i = 0; i < fit_options_input.size(); i++) { if (fAllowedTypes.find(fit_options_input.at(i)) == std::string::npos) { - QERROR(WRN, "ERROR: Fit Option '" + NUIS_ERR(WRN, "ERROR: Fit Option '" << fit_options_input.at(i) << "' Provided is not allowed for this measurement."); - QERROR(WRN, "Fit Options should be provided as a '/' seperated list " + NUIS_ERR(WRN, "Fit Options should be provided as a '/' seperated list " "(e.g. FREE/DIAG/NORM)"); - QTHROW("Available options for " << fName << " are '" << fAllowedTypes + NUIS_ABORT("Available options for " << fName << " are '" << fAllowedTypes << "'"); } } // Set TYPE fFitType = opt; // FIX,SHAPE,FREE if (opt.find("FIX") != std::string::npos) { fIsFree = fIsShape = false; fIsFix = true; } else if (opt.find("SHAPE") != std::string::npos) { fIsFree = fIsFix = false; fIsShape = true; } else if (opt.find("FREE") != std::string::npos) { fIsFix = fIsShape = false; fIsFree = true; } // DIAG,FULL (or default to full) if (opt.find("DIAG") != std::string::npos) { fIsDiag = true; fIsFull = false; } else if (opt.find("FULL") != std::string::npos) { fIsDiag = false; fIsFull = true; } // CHI2/LL (OTHERS?) if (opt.find("LOG") != std::string::npos) { fIsChi2 = false; - QERROR(FTL, "No other LIKELIHOODS properly supported!"); - QERROR(FTL, "Try to use a chi2!"); + NUIS_ERR(FTL, "No other LIKELIHOODS properly supported!"); + NUIS_ERR(FTL, "Try to use a chi2!"); throw; } else { fIsChi2 = true; } // EXTRAS if (opt.find("RAW") != std::string::npos) fIsRawEvents = true; if (opt.find("NOWIDTH") != std::string::npos) fIsNoWidth = true; if (opt.find("DIF") != std::string::npos) fIsDifXSec = true; if (opt.find("ENU1D") != std::string::npos) fIsEnu1D = true; if (opt.find("NORM") != std::string::npos) fAddNormPen = true; if (opt.find("MASK") != std::string::npos) fIsMask = true; return; }; //******************************************************************** void Measurement1D::SetSmearingMatrix(std::string smearfile, int truedim, int recodim) { //******************************************************************** // The smearing matrix describes the migration from true bins (rows) to reco // bins (columns) // Counter over the true bins! int row = 0; std::string line; std::ifstream smear(smearfile.c_str(), std::ifstream::in); // Note that the smearing matrix may be rectangular. fSmearMatrix = new TMatrixD(truedim, recodim); if (smear.is_open()) { - QLOG(SAM, "Reading smearing matrix from file: " << smearfile); + NUIS_LOG(SAM, "Reading smearing matrix from file: " << smearfile); } else { - QTHROW("Smearing matrix provided is incorrect: " << smearfile); + NUIS_ABORT("Smearing matrix provided is incorrect: " << smearfile); } while (std::getline(smear >> std::ws, line, '\n')) { int column = 0; std::vector entries = GeneralUtils::ParseToDbl(line, " "); for (std::vector::iterator iter = entries.begin(); iter != entries.end(); iter++) { (*fSmearMatrix)(row, column) = (*iter) / 100.; // Convert to fraction from // percentage (this may not be // general enough) column++; } row++; } return; } //******************************************************************** void Measurement1D::ApplySmearingMatrix() { //******************************************************************** if (!fSmearMatrix) { - QERROR(WRN, + NUIS_ERR(WRN, fName << ": attempted to apply smearing matrix, but none was set"); return; } TH1D *unsmeared = (TH1D *)fMCHist->Clone(); TH1D *smeared = (TH1D *)fMCHist->Clone(); smeared->Reset(); // Loop over reconstructed bins // true = row; reco = column for (int rbin = 0; rbin < fSmearMatrix->GetNcols(); ++rbin) { // Sum up the constributions from all true bins double rBinVal = 0; // Loop over true bins for (int tbin = 0; tbin < fSmearMatrix->GetNrows(); ++tbin) { rBinVal += (*fSmearMatrix)(tbin, rbin) * unsmeared->GetBinContent(tbin + 1); } smeared->SetBinContent(rbin + 1, rBinVal); } fMCHist = (TH1D *)smeared->Clone(); return; } /* Reconfigure LOOP */ //******************************************************************** void Measurement1D::ResetAll() { //******************************************************************** fMCHist->Reset(); fMCFine->Reset(); fMCStat->Reset(); return; }; //******************************************************************** void Measurement1D::FillHistograms() { //******************************************************************** if (Signal) { - QLOG(DEB, "Fill MCHist: " << fXVar << ", " << Weight); + NUIS_LOG(DEB, "Fill MCHist: " << fXVar << ", " << Weight); fMCHist->Fill(fXVar, Weight); fMCFine->Fill(fXVar, Weight); fMCStat->Fill(fXVar, 1.0); if (fMCHist_Modes) fMCHist_Modes->Fill(Mode, fXVar, Weight); } return; }; //******************************************************************** void Measurement1D::ScaleEvents() { //******************************************************************** // Fill MCWeighted; // for (int i = 0; i < fMCHist->GetNbinsX(); i++) { // fMCWeighted->SetBinContent(i + 1, fMCHist->GetBinContent(i + 1)); // fMCWeighted->SetBinError(i + 1, fMCHist->GetBinError(i + 1)); // } // Setup Stat ratios for MC and MC Fine double *statratio = new double[fMCHist->GetNbinsX()]; for (int i = 0; i < fMCHist->GetNbinsX(); i++) { if (fMCHist->GetBinContent(i + 1) != 0) { statratio[i] = fMCHist->GetBinError(i + 1) / fMCHist->GetBinContent(i + 1); } else { statratio[i] = 0.0; } } double *statratiofine = new double[fMCFine->GetNbinsX()]; for (int i = 0; i < fMCFine->GetNbinsX(); i++) { if (fMCFine->GetBinContent(i + 1) != 0) { statratiofine[i] = fMCFine->GetBinError(i + 1) / fMCFine->GetBinContent(i + 1); } else { statratiofine[i] = 0.0; } } // Scaling for raw event rates if (fIsRawEvents) { double datamcratio = fDataHist->Integral() / fMCHist->Integral(); fMCHist->Scale(datamcratio); fMCFine->Scale(datamcratio); if (fMCHist_Modes) fMCHist_Modes->Scale(datamcratio); // Scaling for XSec as function of Enu } else if (fIsEnu1D) { PlotUtils::FluxUnfoldedScaling(fMCHist, GetFluxHistogram(), GetEventHistogram(), fScaleFactor, fNEvents); PlotUtils::FluxUnfoldedScaling(fMCFine, GetFluxHistogram(), GetEventHistogram(), fScaleFactor, fNEvents); if (fMCHist_Modes) { // Loop over the modes fMCHist_Modes->FluxUnfold(GetFluxHistogram(), GetEventHistogram(), fScaleFactor, fNEvents); // PlotUtils::FluxUnfoldedScaling(fMCHist_Modes, GetFluxHistogram(), // GetEventHistogram(), fScaleFactor, // fNEvents); } } else if (fIsNoWidth) { fMCHist->Scale(fScaleFactor); fMCFine->Scale(fScaleFactor); if (fMCHist_Modes) fMCHist_Modes->Scale(fScaleFactor); // Any other differential scaling } else { fMCHist->Scale(fScaleFactor, "width"); fMCFine->Scale(fScaleFactor, "width"); if (fMCHist_Modes) fMCHist_Modes->Scale(fScaleFactor, "width"); } // Proper error scaling - ROOT Freaks out with xsec weights sometimes for (int i = 0; i < fMCStat->GetNbinsX(); i++) { fMCHist->SetBinError(i + 1, fMCHist->GetBinContent(i + 1) * statratio[i]); } for (int i = 0; i < fMCFine->GetNbinsX(); i++) { fMCFine->SetBinError(i + 1, fMCFine->GetBinContent(i + 1) * statratiofine[i]); } // Clean up delete[] statratio; delete[] statratiofine; return; }; //******************************************************************** void Measurement1D::ApplyNormScale(double norm) { //******************************************************************** fCurrentNorm = norm; fMCHist->Scale(1.0 / norm); fMCFine->Scale(1.0 / norm); return; }; /* Statistic Functions - Outsources to StatUtils */ //******************************************************************** int Measurement1D::GetNDOF() { //******************************************************************** int ndof = fDataHist->GetNbinsX(); if (fMaskHist and fIsMask) ndof -= fMaskHist->Integral(); return ndof; } //******************************************************************** double Measurement1D::GetLikelihood() { //******************************************************************** // If this is for a ratio, there is no data histogram to compare to! if (fNoData || !fDataHist) return 0.; // Apply Masking to MC if Required. if (fIsMask and fMaskHist) { PlotUtils::MaskBins(fMCHist, fMaskHist); } // Sort Shape Scaling double scaleF = 0.0; // TODO Include !fIsRawEvents if (fIsShape) { if (fMCHist->Integral(1, fMCHist->GetNbinsX(), "width")) { scaleF = fDataHist->Integral(1, fDataHist->GetNbinsX(), "width") / fMCHist->Integral(1, fMCHist->GetNbinsX(), "width"); fMCHist->Scale(scaleF); fMCFine->Scale(scaleF); } } // Likelihood Calculation double stat = 0.; if (fIsChi2) { if (fIsRawEvents) { stat = StatUtils::GetChi2FromEventRate(fDataHist, fMCHist, fMaskHist); } else if (fIsDiag) { stat = StatUtils::GetChi2FromDiag(fDataHist, fMCHist, fMaskHist); } else if (!fIsDiag and !fIsRawEvents) { stat = StatUtils::GetChi2FromCov(fDataHist, fMCHist, covar, fMaskHist); } } // Sort Penalty Terms if (fAddNormPen) { double penalty = (1. - fCurrentNorm) * (1. - fCurrentNorm) / (fNormError * fNormError); stat += penalty; } // Return to normal scaling if (fIsShape) { // and !FitPar::Config().GetParB("saveshapescaling")) { fMCHist->Scale(1. / scaleF); fMCFine->Scale(1. / scaleF); } fLikelihood = stat; return stat; } /* Fake Data Functions */ //******************************************************************** void Measurement1D::SetFakeDataValues(std::string fakeOption) { //******************************************************************** // Setup original/datatrue TH1D *tempdata = (TH1D *)fDataHist->Clone(); if (!fIsFakeData) { fIsFakeData = true; // Make a copy of the original data histogram. if (!fDataOrig) fDataOrig = (TH1D *)fDataHist->Clone((fName + "_data_original").c_str()); } else { ResetFakeData(); } // Setup Inputs fFakeDataInput = fakeOption; - QLOG(SAM, "Setting fake data from : " << fFakeDataInput); + NUIS_LOG(SAM, "Setting fake data from : " << fFakeDataInput); // From MC if (fFakeDataInput.compare("MC") == 0) { fDataHist = (TH1D *)fMCHist->Clone((fName + "_MC").c_str()); // Fake File } else { if (!fFakeDataFile) fFakeDataFile = new TFile(fFakeDataInput.c_str(), "READ"); fDataHist = (TH1D *)fFakeDataFile->Get((fName + "_MC").c_str()); } // Setup Data Hist fDataHist->SetNameTitle((fName + "_FAKE").c_str(), (fName + fPlotTitles).c_str()); // Replace Data True if (fDataTrue) delete fDataTrue; fDataTrue = (TH1D *)fDataHist->Clone(); fDataTrue->SetNameTitle((fName + "_FAKE_TRUE").c_str(), (fName + fPlotTitles).c_str()); // Make a new covariance for fake data hist. int nbins = fDataHist->GetNbinsX(); double alpha_i = 0.0; double alpha_j = 0.0; for (int i = 0; i < nbins; i++) { for (int j = 0; j < nbins; j++) { alpha_i = fDataHist->GetBinContent(i + 1) / tempdata->GetBinContent(i + 1); alpha_j = fDataHist->GetBinContent(j + 1) / tempdata->GetBinContent(j + 1); (*fFullCovar)(i, j) = alpha_i * alpha_j * (*fFullCovar)(i, j); } } // Setup Covariances if (covar) delete covar; covar = StatUtils::GetInvert(fFullCovar); if (fDecomp) delete fDecomp; fDecomp = StatUtils::GetInvert(fFullCovar); delete tempdata; return; }; //******************************************************************** void Measurement1D::ResetFakeData() { //******************************************************************** if (fIsFakeData) { if (fDataHist) delete fDataHist; fDataHist = (TH1D *)fDataTrue->Clone((fSettings.GetName() + "_FKDAT").c_str()); } } //******************************************************************** void Measurement1D::ResetData() { //******************************************************************** if (fIsFakeData) { if (fDataHist) delete fDataHist; fDataHist = (TH1D *)fDataOrig->Clone((fSettings.GetName() + "_data").c_str()); } fIsFakeData = false; } //******************************************************************** void Measurement1D::ThrowCovariance() { //******************************************************************** // Take a fDecomposition and use it to throw the current dataset. // Requires fDataTrue also be set incase used repeatedly. if (!fDataTrue) fDataTrue = (TH1D *)fDataHist->Clone(); if (fDataHist) delete fDataHist; fDataHist = StatUtils::ThrowHistogram(fDataTrue, fFullCovar); return; }; //******************************************************************** void Measurement1D::ThrowDataToy() { //******************************************************************** if (!fDataTrue) fDataTrue = (TH1D *)fDataHist->Clone(); if (fMCHist) delete fMCHist; fMCHist = StatUtils::ThrowHistogram(fDataTrue, fFullCovar); } /* Access Functions */ //******************************************************************** TH1D *Measurement1D::GetMCHistogram() { //******************************************************************** if (!fMCHist) return fMCHist; std::ostringstream chi2; chi2 << std::setprecision(5) << this->GetLikelihood(); int linecolor = kRed; int linestyle = 1; int linewidth = 1; int fillcolor = 0; int fillstyle = 1001; // if (fSettings.Has("linecolor")) linecolor = fSettings.GetI("linecolor"); // if (fSettings.Has("linestyle")) linestyle = fSettings.GetI("linestyle"); // if (fSettings.Has("linewidth")) linewidth = fSettings.GetI("linewidth"); // if (fSettings.Has("fillcolor")) fillcolor = fSettings.GetI("fillcolor"); // if (fSettings.Has("fillstyle")) fillstyle = fSettings.GetI("fillstyle"); fMCHist->SetTitle(chi2.str().c_str()); fMCHist->SetLineColor(linecolor); fMCHist->SetLineStyle(linestyle); fMCHist->SetLineWidth(linewidth); fMCHist->SetFillColor(fillcolor); fMCHist->SetFillStyle(fillstyle); return fMCHist; }; //******************************************************************** TH1D *Measurement1D::GetDataHistogram() { //******************************************************************** if (!fDataHist) return fDataHist; int datacolor = kBlack; int datastyle = 1; int datawidth = 1; // if (fSettings.Has("datacolor")) datacolor = fSettings.GetI("datacolor"); // if (fSettings.Has("datastyle")) datastyle = fSettings.GetI("datastyle"); // if (fSettings.Has("datawidth")) datawidth = fSettings.GetI("datawidth"); fDataHist->SetLineColor(datacolor); fDataHist->SetLineWidth(datawidth); fDataHist->SetMarkerStyle(datastyle); return fDataHist; }; /* Write Functions */ // Save all the histograms at once //******************************************************************** void Measurement1D::Write(std::string drawOpt) { //******************************************************************** // Get Draw Options drawOpt = FitPar::Config().GetParS("drawopts"); // Write Settigns if (drawOpt.find("SETTINGS") != std::string::npos) { fSettings.Set("#chi^{2}", fLikelihood); fSettings.Set("NDOF", this->GetNDOF()); fSettings.Set("#chi^{2}/NDOF", fLikelihood / this->GetNDOF()); fSettings.Write(); } // Write Data/MC if (drawOpt.find("DATA") != std::string::npos) GetDataList().at(0)->Write(); if (drawOpt.find("MC") != std::string::npos) { GetMCList().at(0)->Write(); if ((fEvtRateScaleFactor != 0xdeadbeef) && GetMCList().at(0)) { TH1D *PredictedEvtRate = static_cast(GetMCList().at(0)->Clone()); PredictedEvtRate->Scale(fEvtRateScaleFactor); PredictedEvtRate->GetYaxis()->SetTitle("Predicted event rate"); PredictedEvtRate->Write(); } } // Write Fine Histogram if (drawOpt.find("FINE") != std::string::npos) GetFineList().at(0)->Write(); // Write Weighted Histogram if (drawOpt.find("WEIGHTS") != std::string::npos && fMCWeighted) fMCWeighted->Write(); // Save Flux/Evt if no event manager if (!FitPar::Config().GetParB("EventManager")) { if (drawOpt.find("FLUX") != std::string::npos && GetFluxHistogram()) GetFluxHistogram()->Write(); if (drawOpt.find("EVT") != std::string::npos && GetEventHistogram()) GetEventHistogram()->Write(); if (drawOpt.find("XSEC") != std::string::npos && GetEventHistogram()) GetXSecHistogram()->Write(); } // Write Mask if (fIsMask && (drawOpt.find("MASK") != std::string::npos)) { fMaskHist->Write(); } // Write Covariances if (drawOpt.find("COV") != std::string::npos && fFullCovar) { PlotUtils::GetFullCovarPlot(fFullCovar, fSettings.GetName())->Write(); } if (drawOpt.find("INVCOV") != std::string::npos && covar) { PlotUtils::GetInvCovarPlot(covar, fSettings.GetName())->Write(); } if (drawOpt.find("DECOMP") != std::string::npos && fDecomp) { PlotUtils::GetDecompCovarPlot(fDecomp, fSettings.GetName())->Write(); } // // Likelihood residual plots // if (drawOpt.find("RESIDUAL") != std::string::npos) { // WriteResidualPlots(); // } // Ratio and Shape Plots if (drawOpt.find("RATIO") != std::string::npos) { WriteRatioPlot(); } if (drawOpt.find("SHAPE") != std::string::npos) { WriteShapePlot(); if (drawOpt.find("RATIO") != std::string::npos) WriteShapeRatioPlot(); } // // RATIO // if (drawOpt.find("CANVMC") != std::string::npos) { // TCanvas* c1 = WriteMCCanvas(fDataHist, fMCHist); // c1->Write(); // delete c1; // } // // PDG // if (drawOpt.find("CANVPDG") != std::string::npos && fMCHist_Modes) { // TCanvas* c2 = WritePDGCanvas(fDataHist, fMCHist, fMCHist_Modes); // c2->Write(); // delete c2; // } // Write Extra Histograms AutoWriteExtraTH1(); WriteExtraHistograms(); // Returning - QLOG(SAM, "Written Histograms: " << fName); + NUIS_LOG(SAM, "Written Histograms: " << fName); return; } //******************************************************************** void Measurement1D::WriteRatioPlot() { //******************************************************************** // Setup mc data ratios TH1D *dataRatio = (TH1D *)fDataHist->Clone((fName + "_data_RATIO").c_str()); TH1D *mcRatio = (TH1D *)fMCHist->Clone((fName + "_MC_RATIO").c_str()); // Extra MC Data Ratios for (int i = 0; i < mcRatio->GetNbinsX(); i++) { dataRatio->SetBinContent(i + 1, fDataHist->GetBinContent(i + 1) / fMCHist->GetBinContent(i + 1)); dataRatio->SetBinError(i + 1, fDataHist->GetBinError(i + 1) / fMCHist->GetBinContent(i + 1)); mcRatio->SetBinContent(i + 1, fMCHist->GetBinContent(i + 1) / fMCHist->GetBinContent(i + 1)); mcRatio->SetBinError(i + 1, fMCHist->GetBinError(i + 1) / fMCHist->GetBinContent(i + 1)); } // Write ratios mcRatio->Write(); dataRatio->Write(); delete mcRatio; delete dataRatio; } //******************************************************************** void Measurement1D::WriteShapePlot() { //******************************************************************** TH1D *mcShape = (TH1D *)fMCHist->Clone((fName + "_MC_SHAPE").c_str()); TH1D *dataShape = (TH1D *)fDataHist->Clone((fName + "_data_SHAPE").c_str()); // Don't check error if (fShapeCovar) StatUtils::SetDataErrorFromCov(dataShape, fShapeCovar, 1E-38, false); double shapeScale = 1.0; if (fIsRawEvents) { shapeScale = fDataHist->Integral() / fMCHist->Integral(); } else { shapeScale = fDataHist->Integral("width") / fMCHist->Integral("width"); } mcShape->Scale(shapeScale); std::stringstream ss; ss << shapeScale; mcShape->SetTitle(ss.str().c_str()); mcShape->SetLineWidth(3); mcShape->SetLineStyle(7); mcShape->Write(); dataShape->Write(); delete mcShape; } //******************************************************************** void Measurement1D::WriteShapeRatioPlot() { //******************************************************************** // Get a mcshape histogram TH1D *mcShape = (TH1D *)fMCHist->Clone((fName + "_MC_SHAPE").c_str()); double shapeScale = 1.0; if (fIsRawEvents) { shapeScale = fDataHist->Integral() / fMCHist->Integral(); } else { shapeScale = fDataHist->Integral("width") / fMCHist->Integral("width"); } mcShape->Scale(shapeScale); // Create shape ratio histograms TH1D *mcShapeRatio = (TH1D *)mcShape->Clone((fName + "_MC_SHAPE_RATIO").c_str()); TH1D *dataShapeRatio = (TH1D *)fDataHist->Clone((fName + "_data_SHAPE_RATIO").c_str()); // Divide the histograms mcShapeRatio->Divide(mcShape); dataShapeRatio->Divide(mcShape); // Colour the shape ratio plots mcShapeRatio->SetLineWidth(3); mcShapeRatio->SetLineStyle(7); mcShapeRatio->Write(); dataShapeRatio->Write(); delete mcShapeRatio; delete dataShapeRatio; } //// CRAP TO BE REMOVED //******************************************************************** void Measurement1D::SetupMeasurement(std::string inputfile, std::string type, FitWeight *rw, std::string fkdt) { //******************************************************************** nuiskey samplekey = Config::CreateKey("sample"); samplekey.Set("name", fName); samplekey.Set("type", type); samplekey.Set("input", inputfile); fSettings = LoadSampleSettings(samplekey); // Reset everything to NULL // Init(); // Check if name contains Evt, indicating that it is a raw number of events // measurements and should thus be treated as once fIsRawEvents = false; if ((fName.find("Evt") != std::string::npos) && fIsRawEvents == false) { fIsRawEvents = true; - QLOG(SAM, "Found event rate measurement but fIsRawEvents == false!"); - QLOG(SAM, "Overriding this and setting fIsRawEvents == true!"); + NUIS_LOG(SAM, "Found event rate measurement but fIsRawEvents == false!"); + NUIS_LOG(SAM, "Overriding this and setting fIsRawEvents == true!"); } fIsEnu1D = false; if (fName.find("XSec_1DEnu") != std::string::npos) { fIsEnu1D = true; - QLOG(SAM, "::" << fName << "::"); - QLOG(SAM, "Found XSec Enu measurement, applying flux integrated scaling, " + NUIS_LOG(SAM, "::" << fName << "::"); + NUIS_LOG(SAM, "Found XSec Enu measurement, applying flux integrated scaling, " "not flux averaged!"); } if (fIsEnu1D && fIsRawEvents) { - QERROR(FTL, "Found 1D Enu XSec distribution AND fIsRawEvents, is this " + NUIS_ERR(FTL, "Found 1D Enu XSec distribution AND fIsRawEvents, is this " "really correct?!"); - QERROR(FTL, "Check experiment constructor for " << fName + NUIS_ERR(FTL, "Check experiment constructor for " << fName << " and correct this!"); - QERROR(FTL, "I live in " << __FILE__ << ":" << __LINE__); + NUIS_ERR(FTL, "I live in " << __FILE__ << ":" << __LINE__); throw; } fRW = rw; if (!fInput and !fIsJoint) SetupInputs(inputfile); // Set Default Options SetFitOptions(fDefaultTypes); // Set Passed Options SetFitOptions(type); // Still adding support for flat flux inputs // // Set Enu Flux Scaling // if (isFlatFluxFolding) this->Input()->ApplyFluxFolding( // this->defaultFluxHist ); // FinaliseMeasurement(); } //******************************************************************** void Measurement1D::SetupDefaultHist() { //******************************************************************** // Setup fMCHist fMCHist = (TH1D *)fDataHist->Clone(); fMCHist->SetNameTitle((fName + "_MC").c_str(), (fName + "_MC" + fPlotTitles).c_str()); // Setup fMCFine Int_t nBins = fMCHist->GetNbinsX(); fMCFine = new TH1D( (fName + "_MC_FINE").c_str(), (fName + "_MC_FINE" + fPlotTitles).c_str(), nBins * 6, fMCHist->GetBinLowEdge(1), fMCHist->GetBinLowEdge(nBins + 1)); fMCStat = (TH1D *)fMCHist->Clone(); fMCStat->Reset(); fMCHist->Reset(); fMCFine->Reset(); // Setup the NEUT Mode Array PlotUtils::CreateNeutModeArray((TH1D *)fMCHist, (TH1 **)fMCHist_PDG); PlotUtils::ResetNeutModeArray((TH1 **)fMCHist_PDG); // Setup bin masks using sample name if (fIsMask) { std::string maskloc = FitPar::Config().GetParDIR(fName + ".mask"); if (maskloc.empty()) { maskloc = FitPar::GetDataBase() + "/masks/" + fName + ".mask"; } SetBinMask(maskloc); } fMCHist_Modes = new TrueModeStack((fName + "_MODES").c_str(), ("True Channels"), fMCHist); SetAutoProcessTH1(fMCHist_Modes, kCMD_Reset, kCMD_Norm, kCMD_Write); return; } //******************************************************************** void Measurement1D::SetDataValues(std::string dataFile) { //******************************************************************** // Override this function if the input file isn't in a suitable format - QLOG(SAM, "Reading data from: " << dataFile.c_str()); + NUIS_LOG(SAM, "Reading data from: " << dataFile.c_str()); fDataHist = PlotUtils::GetTH1DFromFile(dataFile, (fName + "_data"), fPlotTitles); fDataTrue = (TH1D *)fDataHist->Clone(); // Number of data points is number of bins fNDataPointsX = fDataHist->GetXaxis()->GetNbins(); return; }; //******************************************************************** void Measurement1D::SetDataFromDatabase(std::string inhistfile, std::string histname) { //******************************************************************** - QLOG(SAM, "Filling histogram from " << inhistfile << "->" << histname); + NUIS_LOG(SAM, "Filling histogram from " << inhistfile << "->" << histname); fDataHist = PlotUtils::GetTH1DFromRootFile( (GeneralUtils::GetTopLevelDir() + "/data/" + inhistfile), histname); fDataHist->SetNameTitle((fName + "_data").c_str(), (fName + "_data").c_str()); return; }; //******************************************************************** void Measurement1D::SetDataFromFile(std::string inhistfile, std::string histname) { //******************************************************************** - QLOG(SAM, "Filling histogram from " << inhistfile << "->" << histname); + NUIS_LOG(SAM, "Filling histogram from " << inhistfile << "->" << histname); fDataHist = PlotUtils::GetTH1DFromRootFile((inhistfile), histname); fDataHist->SetNameTitle((fName + "_data").c_str(), (fName + "_data").c_str()); return; }; //******************************************************************** void Measurement1D::SetCovarMatrix(std::string covarFile) { //******************************************************************** // Covariance function, only really used when reading in the MB Covariances. TFile *tempFile = new TFile(covarFile.c_str(), "READ"); TH2D *covarPlot = new TH2D(); TH2D *fFullCovarPlot = new TH2D(); std::string covName = ""; std::string covOption = FitPar::Config().GetParS("thrown_covariance"); if (fIsShape || fIsFree) covName = "shp_"; if (fIsDiag) covName += "diag"; else covName += "full"; covarPlot = (TH2D *)tempFile->Get((covName + "cov").c_str()); if (!covOption.compare("SUB")) fFullCovarPlot = (TH2D *)tempFile->Get((covName + "cov").c_str()); else if (!covOption.compare("FULL")) fFullCovarPlot = (TH2D *)tempFile->Get("fullcov"); else { - QERROR(WRN, "Incorrect thrown_covariance option in parameters."); + NUIS_ERR(WRN, "Incorrect thrown_covariance option in parameters."); } int dim = int(fDataHist->GetNbinsX()); //-this->masked->Integral()); int covdim = int(fDataHist->GetNbinsX()); this->covar = new TMatrixDSym(dim); fFullCovar = new TMatrixDSym(dim); fDecomp = new TMatrixDSym(dim); int row, column = 0; row = 0; column = 0; for (Int_t i = 0; i < covdim; i++) { // if (this->masked->GetBinContent(i+1) > 0) continue; for (Int_t j = 0; j < covdim; j++) { // if (this->masked->GetBinContent(j+1) > 0) continue; (*this->covar)(row, column) = covarPlot->GetBinContent(i + 1, j + 1); (*fFullCovar)(row, column) = fFullCovarPlot->GetBinContent(i + 1, j + 1); column++; } column = 0; row++; } // Set bin errors on data if (!fIsDiag) { StatUtils::SetDataErrorFromCov(fDataHist, fFullCovar); } // Get Deteriminant and inverse matrix // fCovDet = this->covar->Determinant(); TDecompSVD LU = TDecompSVD(*this->covar); this->covar = new TMatrixDSym(dim, LU.Invert().GetMatrixArray(), ""); return; }; //******************************************************************** // Sets the covariance matrix from a provided file in a text format // scale is a multiplicative pre-factor to apply in the case where the // covariance is given in some unit (e.g. 1E-38) void Measurement1D::SetCovarMatrixFromText(std::string covarFile, int dim, double scale) { //******************************************************************** // Make a counter to track the line number int row = 0; std::string line; std::ifstream covarread(covarFile.c_str(), std::ifstream::in); this->covar = new TMatrixDSym(dim); fFullCovar = new TMatrixDSym(dim); if (covarread.is_open()) { - QLOG(SAM, "Reading covariance matrix from file: " << covarFile); + NUIS_LOG(SAM, "Reading covariance matrix from file: " << covarFile); } else { - QTHROW("Covariance matrix provided is incorrect: " << covarFile); + NUIS_ABORT("Covariance matrix provided is incorrect: " << covarFile); } // Loop over the lines in the file while (std::getline(covarread >> std::ws, line, '\n')) { int column = 0; // Loop over entries and insert them into matrix std::vector entries = GeneralUtils::ParseToDbl(line, " "); if (entries.size() <= 1) { - QERROR(WRN, "SetCovarMatrixFromText -> Covariance matrix only has <= 1 " + NUIS_ERR(WRN, "SetCovarMatrixFromText -> Covariance matrix only has <= 1 " "entries on this line: " << row); } for (std::vector::iterator iter = entries.begin(); iter != entries.end(); iter++) { (*covar)(row, column) = *iter; (*fFullCovar)(row, column) = *iter; column++; } row++; } covarread.close(); // Scale the actualy covariance matrix by some multiplicative factor (*fFullCovar) *= scale; // Robust matrix inversion method TDecompSVD LU = TDecompSVD(*this->covar); // THIS IS ACTUALLY THE INVERSE COVARIANCE MATRIXA AAAAARGH delete this->covar; this->covar = new TMatrixDSym(dim, LU.Invert().GetMatrixArray(), ""); // Now need to multiply by the scaling factor // If the covariance (*this->covar) *= 1. / (scale); return; }; //******************************************************************** void Measurement1D::SetCovarMatrixFromCorrText(std::string corrFile, int dim) { //******************************************************************** // Make a counter to track the line number int row = 0; std::string line; std::ifstream corr(corrFile.c_str(), std::ifstream::in); this->covar = new TMatrixDSym(dim); this->fFullCovar = new TMatrixDSym(dim); if (corr.is_open()) { - QLOG(SAM, + NUIS_LOG(SAM, "Reading and converting correlation matrix from file: " << corrFile); } else { - QTHROW("Correlation matrix provided is incorrect: " << corrFile); + NUIS_ABORT("Correlation matrix provided is incorrect: " << corrFile); } while (std::getline(corr >> std::ws, line, '\n')) { int column = 0; // Loop over entries and insert them into matrix // Multiply by the errors to get the covariance, rather than the correlation // matrix std::vector entries = GeneralUtils::ParseToDbl(line, " "); for (std::vector::iterator iter = entries.begin(); iter != entries.end(); iter++) { double val = (*iter) * this->fDataHist->GetBinError(row + 1) * 1E38 * this->fDataHist->GetBinError(column + 1) * 1E38; if (val == 0) { - QTHROW("Found a zero value in the covariance matrix, assuming " + NUIS_ABORT("Found a zero value in the covariance matrix, assuming " "this is an error!"); } (*this->covar)(row, column) = val; (*this->fFullCovar)(row, column) = val; column++; } row++; } // Robust matrix inversion method TDecompSVD LU = TDecompSVD(*this->covar); delete this->covar; this->covar = new TMatrixDSym(dim, LU.Invert().GetMatrixArray(), ""); return; }; //******************************************************************** // FullUnits refers to if we have "real" unscaled units in the covariance // matrix, e.g. 1E-76. If this is the case we need to scale it so that the chi2 // contribution is correct NUISANCE internally assumes the covariance matrix has // units of 1E76 void Measurement1D::SetCovarFromDataFile(std::string covarFile, std::string covName, bool FullUnits) { //******************************************************************** - QLOG(SAM, "Getting covariance from " << covarFile << "->" << covName); + NUIS_LOG(SAM, "Getting covariance from " << covarFile << "->" << covName); TFile *tempFile = new TFile(covarFile.c_str(), "READ"); TH2D *covPlot = (TH2D *)tempFile->Get(covName.c_str()); covPlot->SetDirectory(0); // Scale the covariance matrix if it comes in normal units if (FullUnits) { covPlot->Scale(1.E76); } int dim = covPlot->GetNbinsX(); fFullCovar = new TMatrixDSym(dim); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { (*fFullCovar)(i, j) = covPlot->GetBinContent(i + 1, j + 1); } } this->covar = (TMatrixDSym *)fFullCovar->Clone(); fDecomp = (TMatrixDSym *)fFullCovar->Clone(); TDecompSVD LU = TDecompSVD(*this->covar); this->covar = new TMatrixDSym(dim, LU.Invert().GetMatrixArray(), ""); TDecompChol LUChol = TDecompChol(*fDecomp); LUChol.Decompose(); fDecomp = new TMatrixDSym(dim, LU.GetU().GetMatrixArray(), ""); return; }; // //******************************************************************** // void Measurement1D::SetBinMask(std::string maskFile) { // //******************************************************************** // // Create a mask histogram. // int nbins = fDataHist->GetNbinsX(); // fMaskHist = // new TH1I((fName + "_fMaskHist").c_str(), // (fName + "_fMaskHist; Bin; Mask?").c_str(), nbins, 0, nbins); // std::string line; // std::ifstream mask(maskFile.c_str(), std::ifstream::in); // if (mask.is_open()) // LOG(SAM) << "Reading bin mask from file: " << maskFile << std::endl; // else // LOG(FTL) << " Cannot find mask file." << std::endl; // while (std::getline(mask >> std::ws, line, '\n')) { // std::vector entries = GeneralUtils::ParseToInt(line, " "); // // Skip lines with poorly formatted lines // if (entries.size() < 2) { // LOG(WRN) << "Measurement1D::SetBinMask(), couldn't parse line: " << // line // << std::endl; // continue; // } // // The first index should be the bin number, the second should be the // mask // // value. // fMaskHist->SetBinContent(entries[0], entries[1]); // } // // Set masked data bins to zero // PlotUtils::MaskBins(fDataHist, fMaskHist); // return; // } // //******************************************************************** // void Measurement1D::GetBinContents(std::vector& cont, // std::vector& err) { // //******************************************************************** // // Return a vector of the main bin contents // for (int i = 0; i < fMCHist->GetNbinsX(); i++) { // cont.push_back(fMCHist->GetBinContent(i + 1)); // err.push_back(fMCHist->GetBinError(i + 1)); // } // return; // }; /* XSec Functions */ // //******************************************************************** // void Measurement1D::SetFluxHistogram(std::string fluxFile, int minE, int // maxE, // double fluxNorm) { // //******************************************************************** // // Note this expects the flux bins to be given in terms of MeV // LOG(SAM) << "Reading flux from file: " << fluxFile << std::endl; // TGraph f(fluxFile.c_str(), "%lg %lg"); // fFluxHist = // new TH1D((fName + "_flux").c_str(), (fName + "; E_{#nu} (GeV)").c_str(), // f.GetN() - 1, minE, maxE); // Double_t* yVal = f.GetY(); // for (int i = 0; i < fFluxHist->GetNbinsX(); ++i) // fFluxHist->SetBinContent(i + 1, yVal[i] * fluxNorm); // }; // //******************************************************************** // double Measurement1D::TotalIntegratedFlux(std::string intOpt, double low, // double high) { // //******************************************************************** // if (fInput->GetType() == kGiBUU) { // return 1.0; // } // // The default case of low = -9999.9 and high = -9999.9 // if (low == -9999.9) low = this->EnuMin; // if (high == -9999.9) high = this->EnuMax; // int minBin = fFluxHist->GetXaxis()->FindBin(low); // int maxBin = fFluxHist->GetXaxis()->FindBin(high); // // Get integral over custom range // double integral = fFluxHist->Integral(minBin, maxBin + 1, intOpt.c_str()); // return integral; // }; diff --git a/src/FitBase/Measurement2D.cxx b/src/FitBase/Measurement2D.cxx index d017428..37316bc 100644 --- a/src/FitBase/Measurement2D.cxx +++ b/src/FitBase/Measurement2D.cxx @@ -1,1982 +1,1982 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "Measurement2D.h" #include "TDecompChol.h" //******************************************************************** Measurement2D::Measurement2D(void) { //******************************************************************** covar = NULL; fDecomp = NULL; fFullCovar = NULL; fMCHist = NULL; fMCFine = NULL; fDataHist = NULL; fMCHist_X = NULL; fMCHist_Y = NULL; fDataHist_X = NULL; fDataHist_Y = NULL; fMaskHist = NULL; fMapHist = NULL; fDataOrig = NULL; fDataTrue = NULL; fMCWeighted = NULL; fDefaultTypes = "FIX/FULL/CHI2"; fAllowedTypes = "FIX,FREE,SHAPE/FULL,DIAG/CHI2/NORM/ENUCORR/Q2CORR/ENU1D/FITPROJX/" "FITPROJY"; fIsFix = false; fIsShape = false; fIsFree = false; fIsDiag = false; fIsFull = false; fAddNormPen = false; fIsMask = false; fIsChi2SVD = false; fIsRawEvents = false; fIsDifXSec = false; fIsEnu = false; // XSec Scalings fScaleFactor = -1.0; fCurrentNorm = 1.0; // Histograms fDataHist = NULL; fDataTrue = NULL; fMCHist = NULL; fMCFine = NULL; fMCWeighted = NULL; fMaskHist = NULL; // Covar covar = NULL; fFullCovar = NULL; fCovar = NULL; fInvert = NULL; fDecomp = NULL; // Fake Data fFakeDataInput = ""; fFakeDataFile = NULL; // Options fDefaultTypes = "FIX/FULL/CHI2"; fAllowedTypes = "FIX,FREE,SHAPE/FULL,DIAG/CHI2/NORM/ENUCORR/Q2CORR/ENU1D/MASK"; fIsFix = false; fIsShape = false; fIsFree = false; fIsDiag = false; fIsFull = false; fAddNormPen = false; fIsMask = false; fIsChi2SVD = false; fIsRawEvents = false; fIsDifXSec = false; fIsEnu1D = false; // Inputs fInput = NULL; fRW = NULL; // Extra Histograms fMCHist_Modes = NULL; } //******************************************************************** Measurement2D::~Measurement2D(void) { //******************************************************************** if (fDataHist) delete fDataHist; if (fDataTrue) delete fDataTrue; if (fMCHist) delete fMCHist; if (fMCFine) delete fMCFine; if (fMCWeighted) delete fMCWeighted; if (fMaskHist) delete fMaskHist; if (covar) delete covar; if (fFullCovar) delete fFullCovar; if (fCovar) delete fCovar; if (fInvert) delete fInvert; if (fDecomp) delete fDecomp; } //******************************************************************** void Measurement2D::FinaliseSampleSettings() { //******************************************************************** MeasurementBase::FinaliseSampleSettings(); // Setup naming + renaming fName = fSettings.GetName(); fSettings.SetS("originalname", fName); if (fSettings.Has("rename")) { fName = fSettings.GetS("rename"); fSettings.SetS("name", fName); } // Setup all other options - QLOG(SAM, "Finalising Sample Settings: " << fName); + NUIS_LOG(SAM, "Finalising Sample Settings: " << fName); if ((fSettings.GetS("originalname").find("Evt") != std::string::npos)) { fIsRawEvents = true; - QLOG(SAM, "Found event rate measurement but using poisson likelihoods."); + NUIS_LOG(SAM, "Found event rate measurement but using poisson likelihoods."); } if (fSettings.GetS("originalname").find("Enu") != std::string::npos) { fIsEnu1D = true; - QLOG(SAM, "::" << fName << "::"); - QLOG(SAM, "Found XSec Enu measurement, applying flux integrated scaling, " + NUIS_LOG(SAM, "::" << fName << "::"); + NUIS_LOG(SAM, "Found XSec Enu measurement, applying flux integrated scaling, " << "not flux averaged!"); } if (fIsEnu1D && fIsRawEvents) { - QERROR(FTL, "Found 2D Enu XSec distribution AND fIsRawEvents, is this " + NUIS_ERR(FTL, "Found 2D Enu XSec distribution AND fIsRawEvents, is this " "really correct?!"); - QERROR(FTL, "Check experiment constructor for " << fName + NUIS_ERR(FTL, "Check experiment constructor for " << fName << " and correct this!"); - QTHROW("I live in " << __FILE__ << ":" << __LINE__); + NUIS_ABORT("I live in " << __FILE__ << ":" << __LINE__); } if (!fRW) fRW = FitBase::GetRW(); if (!fInput) SetupInputs(fSettings.GetS("input")); // Setup options SetFitOptions(fDefaultTypes); // defaults SetFitOptions(fSettings.GetS("type")); // user specified EnuMin = GeneralUtils::StrToDbl(fSettings.GetS("enu_min")); EnuMax = GeneralUtils::StrToDbl(fSettings.GetS("enu_max")); if (fAddNormPen) { fNormError = fSettings.GetNormError(); if (fNormError <= 0.0) { - QERROR(FTL, "Norm error for class " << fName << " is 0.0!"); - QTHROW("If you want to use it please add fNormError=VAL"); + NUIS_ERR(FTL, "Norm error for class " << fName << " is 0.0!"); + NUIS_ABORT("If you want to use it please add fNormError=VAL"); } } } void Measurement2D::CreateDataHistogram(int dimx, double *binx, int dimy, double *biny) { if (fDataHist) delete fDataHist; - QLOG(SAM, "Creating Data Histogram dim : " << dimx << " " << dimy); + NUIS_LOG(SAM, "Creating Data Histogram dim : " << dimx << " " << dimy); fDataHist = new TH2D((fSettings.GetName() + "_data").c_str(), (fSettings.GetFullTitles()).c_str(), dimx - 1, binx, dimy - 1, biny); } void Measurement2D::SetDataFromTextFile(std::string data, std::string binx, std::string biny) { // Get the data hist fDataHist = PlotUtils::GetTH2DFromTextFile(data, binx, biny); // Set the name properly fDataHist->SetName((fSettings.GetName() + "_data").c_str()); fDataHist->SetTitle(fSettings.GetFullTitles().c_str()); } void Measurement2D::SetDataFromRootFile(std::string datfile, std::string histname) { - QLOG(SAM, "Reading data from root file: " << datfile << ";" << histname); + NUIS_LOG(SAM, "Reading data from root file: " << datfile << ";" << histname); fDataHist = PlotUtils::GetTH2DFromRootFile(datfile, histname); fDataHist->SetNameTitle((fSettings.GetName() + "_data").c_str(), (fSettings.GetFullTitles()).c_str()); } void Measurement2D::SetDataValuesFromTextFile(std::string datfile, TH2D *hist) { - QLOG(SAM, "Setting data values from text file"); + NUIS_LOG(SAM, "Setting data values from text file"); if (!hist) hist = fDataHist; // Read TH2D From textfile TH2D *valhist = (TH2D *)hist->Clone(); valhist->Reset(); PlotUtils::Set2DHistFromText(datfile, valhist, 1.0, true); - QLOG(SAM, " -> Filling values from read hist."); + NUIS_LOG(SAM, " -> Filling values from read hist."); for (int i = 0; i < valhist->GetNbinsX(); i++) { for (int j = 0; j < valhist->GetNbinsY(); j++) { hist->SetBinContent(i + 1, j + 1, valhist->GetBinContent(i + 1, j + 1)); } } - QLOG(SAM, " --> Done"); + NUIS_LOG(SAM, " --> Done"); } void Measurement2D::SetDataErrorsFromTextFile(std::string datfile, TH2D *hist) { - QLOG(SAM, "Setting data errors from text file"); + NUIS_LOG(SAM, "Setting data errors from text file"); if (!hist) hist = fDataHist; // Read TH2D From textfile TH2D *valhist = (TH2D *)hist->Clone(); valhist->Reset(); PlotUtils::Set2DHistFromText(datfile, valhist, 1.0); // Fill Errors - QLOG(SAM, " -> Filling errors from read hist."); + NUIS_LOG(SAM, " -> Filling errors from read hist."); for (int i = 0; i < valhist->GetNbinsX(); i++) { for (int j = 0; j < valhist->GetNbinsY(); j++) { hist->SetBinError(i + 1, j + 1, valhist->GetBinContent(i + 1, j + 1)); } } - QLOG(SAM, " --> Done"); + NUIS_LOG(SAM, " --> Done"); } void Measurement2D::SetMapValuesFromText(std::string dataFile) { TH2D *hist = fDataHist; std::vector edgex; std::vector edgey; for (int i = 0; i <= hist->GetNbinsX(); i++) edgex.push_back(hist->GetXaxis()->GetBinLowEdge(i + 1)); for (int i = 0; i <= hist->GetNbinsY(); i++) edgey.push_back(hist->GetYaxis()->GetBinLowEdge(i + 1)); fMapHist = new TH2I((fName + "_map").c_str(), (fName + fPlotTitles).c_str(), edgex.size() - 1, &edgex[0], edgey.size() - 1, &edgey[0]); - QLOG(SAM, "Reading map from: " << dataFile); + NUIS_LOG(SAM, "Reading map from: " << dataFile); PlotUtils::Set2DHistFromText(dataFile, fMapHist, 1.0); } //******************************************************************** void Measurement2D::SetPoissonErrors() { //******************************************************************** if (!fDataHist) { - QERROR(FTL, "Need a data hist to setup possion errors! "); - QTHROW("Setup Data First!"); + NUIS_ERR(FTL, "Need a data hist to setup possion errors! "); + NUIS_ABORT("Setup Data First!"); } for (int i = 0; i < fDataHist->GetNbinsX() + 1; i++) { fDataHist->SetBinError(i + 1, sqrt(fDataHist->GetBinContent(i + 1))); } } //******************************************************************** void Measurement2D::SetCovarFromDiagonal(TH2D *data) { //******************************************************************** if (!data and fDataHist) { data = fDataHist; } if (data) { - QLOG(SAM, "Setting diagonal covariance for: " << data->GetName()); + NUIS_LOG(SAM, "Setting diagonal covariance for: " << data->GetName()); fFullCovar = StatUtils::MakeDiagonalCovarMatrix(data); covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); } else { - QTHROW("No data input provided to set diagonal covar from!"); + NUIS_ABORT("No data input provided to set diagonal covar from!"); } // if (!fIsDiag) { // ERR(FTL) << "SetCovarMatrixFromDiag called for measurement " // << "that is not set as diagonal." << std::endl; // throw; // } } //******************************************************************** void Measurement2D::SetCovarFromTextFile(std::string covfile, int dim) { //******************************************************************** if (dim == -1) { dim = this->GetNDOF(); } - QLOG(SAM, "Reading covariance from text file: " << covfile << " " << dim); + NUIS_LOG(SAM, "Reading covariance from text file: " << covfile << " " << dim); fFullCovar = StatUtils::GetCovarFromTextFile(covfile, dim); covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); } //******************************************************************** void Measurement2D::SetCovarFromRootFile(std::string covfile, std::string histname) { //******************************************************************** - QLOG(SAM, + NUIS_LOG(SAM, "Reading covariance from text file: " << covfile << ";" << histname); fFullCovar = StatUtils::GetCovarFromRootFile(covfile, histname); covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); } //******************************************************************** void Measurement2D::SetCovarInvertFromTextFile(std::string covfile, int dim) { //******************************************************************** if (dim == -1) { dim = this->GetNDOF(); } - QLOG(SAM, "Reading inverted covariance from text file: " << covfile); + NUIS_LOG(SAM, "Reading inverted covariance from text file: " << covfile); covar = StatUtils::GetCovarFromTextFile(covfile, dim); fFullCovar = StatUtils::GetInvert(covar); fDecomp = StatUtils::GetDecomp(fFullCovar); } //******************************************************************** void Measurement2D::SetCovarInvertFromRootFile(std::string covfile, std::string histname) { //******************************************************************** - QLOG(SAM, "Reading inverted covariance from text file: " << covfile << ";" + NUIS_LOG(SAM, "Reading inverted covariance from text file: " << covfile << ";" << histname); covar = StatUtils::GetCovarFromRootFile(covfile, histname); fFullCovar = StatUtils::GetInvert(covar); fDecomp = StatUtils::GetDecomp(fFullCovar); } //******************************************************************** void Measurement2D::SetCorrelationFromTextFile(std::string covfile, int dim) { //******************************************************************** if (dim == -1) dim = this->GetNDOF(); - QLOG(SAM, + NUIS_LOG(SAM, "Reading data correlations from text file: " << covfile << ";" << dim); TMatrixDSym *correlation = StatUtils::GetCovarFromTextFile(covfile, dim); if (!fDataHist) { - QTHROW("Trying to set correlations from text file but there is no " + NUIS_ABORT("Trying to set correlations from text file but there is no " "data to build it from. \n" << "In constructor make sure data is set before " "SetCorrelationFromTextFile is called. \n"); } // Fill covar from data errors and correlations fFullCovar = new TMatrixDSym(dim); for (int i = 0; i < fDataHist->GetNbinsX(); i++) { for (int j = 0; j < fDataHist->GetNbinsX(); j++) { (*fFullCovar)(i, j) = (*correlation)(i, j) * fDataHist->GetBinError(i + 1) * fDataHist->GetBinError(j + 1) * 1.E76; } } // Fill other covars. covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); delete correlation; } //******************************************************************** void Measurement2D::SetCorrelationFromRootFile(std::string covfile, std::string histname) { //******************************************************************** - QLOG(SAM, "Reading data correlations from text file: " << covfile << ";" + NUIS_LOG(SAM, "Reading data correlations from text file: " << covfile << ";" << histname); TMatrixDSym *correlation = StatUtils::GetCovarFromRootFile(covfile, histname); if (!fDataHist) { - QTHROW("Trying to set correlations from text file but there is no " + NUIS_ABORT("Trying to set correlations from text file but there is no " "data to build it from. \n" << "In constructor make sure data is set before " "SetCorrelationFromTextFile is called. \n"); } // Fill covar from data errors and correlations fFullCovar = new TMatrixDSym(fDataHist->GetNbinsX()); for (int i = 0; i < fDataHist->GetNbinsX(); i++) { for (int j = 0; j < fDataHist->GetNbinsX(); j++) { (*fFullCovar)(i, j) = (*correlation)(i, j) * fDataHist->GetBinError(i + 1) * fDataHist->GetBinError(j + 1) * 1.E76; } } // Fill other covars. covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); delete correlation; } //******************************************************************** void Measurement2D::SetCholDecompFromTextFile(std::string covfile, int dim) { //******************************************************************** if (dim == -1) { dim = this->GetNDOF(); } - QLOG(SAM, "Reading cholesky from text file: " << covfile << " " << dim); + NUIS_LOG(SAM, "Reading cholesky from text file: " << covfile << " " << dim); TMatrixD *temp = StatUtils::GetMatrixFromTextFile(covfile, dim, dim); TMatrixD *trans = (TMatrixD *)temp->Clone(); trans->T(); (*trans) *= (*temp); fFullCovar = new TMatrixDSym(dim, trans->GetMatrixArray(), ""); covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); delete temp; delete trans; } //******************************************************************** void Measurement2D::SetCholDecompFromRootFile(std::string covfile, std::string histname) { //******************************************************************** - QLOG(SAM, "Reading cholesky decomp from root file: " << covfile << ";" + NUIS_LOG(SAM, "Reading cholesky decomp from root file: " << covfile << ";" << histname); TMatrixD *temp = StatUtils::GetMatrixFromRootFile(covfile, histname); TMatrixD *trans = (TMatrixD *)temp->Clone(); trans->T(); (*trans) *= (*temp); fFullCovar = new TMatrixDSym(temp->GetNrows(), trans->GetMatrixArray(), ""); covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); delete temp; delete trans; } //******************************************************************** void Measurement2D::ScaleData(double scale) { //******************************************************************** fDataHist->Scale(scale); } //******************************************************************** void Measurement2D::ScaleDataErrors(double scale) { //******************************************************************** for (int i = 0; i < fDataHist->GetNbinsX(); i++) { for (int j = 0; j < fDataHist->GetNbinsY(); j++) { fDataHist->SetBinError(i + 1, j + 1, fDataHist->GetBinError(i + 1, j + 1) * scale); } } } //******************************************************************** void Measurement2D::ScaleCovar(double scale) { //******************************************************************** (*fFullCovar) *= scale; (*covar) *= 1.0 / scale; (*fDecomp) *= sqrt(scale); } //******************************************************************** void Measurement2D::SetBinMask(std::string maskfile) { //******************************************************************** if (!fIsMask) return; - QLOG(SAM, "Reading bin mask from file: " << maskfile); + NUIS_LOG(SAM, "Reading bin mask from file: " << maskfile); // Create a mask histogram with dim of data int nbinsx = fDataHist->GetNbinsX(); int nbinxy = fDataHist->GetNbinsY(); fMaskHist = new TH2I((fSettings.GetName() + "_BINMASK").c_str(), (fSettings.GetName() + "_BINMASK; Bin; Mask?").c_str(), nbinsx, 0, nbinsx, nbinxy, 0, nbinxy); std::string line; std::ifstream mask(maskfile.c_str(), std::ifstream::in); if (!mask.is_open()) { - QLOG(FTL, " Cannot find mask file."); + NUIS_LOG(FTL, " Cannot find mask file."); throw; } while (std::getline(mask >> std::ws, line, '\n')) { std::vector entries = GeneralUtils::ParseToInt(line, " "); // Skip lines with poorly formatted lines if (entries.size() < 2) { - QLOG(WRN, "Measurement2D::SetBinMask(), couldn't parse line: " << line); + NUIS_LOG(WRN, "Measurement2D::SetBinMask(), couldn't parse line: " << line); continue; } // The first index should be the bin number, the second should be the mask // value. int val = 0; if (entries[2] > 0) val = 1; fMaskHist->SetBinContent(entries[0], entries[1], val); } // Apply masking by setting masked data bins to zero PlotUtils::MaskBins(fDataHist, fMaskHist); return; } //******************************************************************** void Measurement2D::FinaliseMeasurement() { //******************************************************************** - QLOG(SAM, "Finalising Measurement: " << fName); + NUIS_LOG(SAM, "Finalising Measurement: " << fName); if (fSettings.GetB("onlymc")) { if (fDataHist) delete fDataHist; fDataHist = new TH2D("empty_data", "empty_data", 1, 0.0, 1.0, 1, 0.0, 1.0); } // Make sure data is setup if (!fDataHist) { - QTHROW("No data has been setup inside " << fName << " constructor!"); + NUIS_ABORT("No data has been setup inside " << fName << " constructor!"); } // Make sure covariances are setup if (!fFullCovar) { fIsDiag = true; SetCovarFromDiagonal(fDataHist); } if (!covar) { covar = StatUtils::GetInvert(fFullCovar); } if (!fDecomp) { fDecomp = StatUtils::GetDecomp(fFullCovar); } // Setup fMCHist from data fMCHist = (TH2D *)fDataHist->Clone(); fMCHist->SetNameTitle((fSettings.GetName() + "_MC").c_str(), (fSettings.GetFullTitles()).c_str()); fMCHist->Reset(); // Setup fMCFine fMCFine = new TH2D( "mcfine", "mcfine", fDataHist->GetNbinsX() * 6, fMCHist->GetXaxis()->GetBinLowEdge(1), fMCHist->GetXaxis()->GetBinLowEdge(fDataHist->GetNbinsX() + 1), fDataHist->GetNbinsY() * 6, fMCHist->GetYaxis()->GetBinLowEdge(1), fMCHist->GetYaxis()->GetBinLowEdge(fDataHist->GetNbinsY() + 1)); fMCFine->SetNameTitle((fSettings.GetName() + "_MC_FINE").c_str(), (fSettings.GetFullTitles()).c_str()); fMCFine->Reset(); // Setup MC Stat fMCStat = (TH2D *)fMCHist->Clone(); fMCStat->Reset(); // Search drawopts for possible types to include by default std::string drawopts = FitPar::Config().GetParS("drawopts"); if (drawopts.find("MODES") != std::string::npos) { fMCHist_Modes = new TrueModeStack((fSettings.GetName() + "_MODES").c_str(), ("True Channels"), fMCHist); SetAutoProcessTH1(fMCHist_Modes); } // Setup bin masks using sample name if (fIsMask) { std::string curname = fName; std::string origname = fSettings.GetS("originalname"); // Check rename.mask std::string maskloc = FitPar::Config().GetParDIR(curname + ".mask"); // Check origname.mask if (maskloc.empty()) maskloc = FitPar::Config().GetParDIR(origname + ".mask"); // Check database if (maskloc.empty()) { maskloc = FitPar::GetDataBase() + "/masks/" + origname + ".mask"; } // Setup Bin Mask SetBinMask(maskloc); } if (fScaleFactor < 0) { - QERROR(FTL, "I found a negative fScaleFactor in " << __FILE__ << ":" + NUIS_ERR(FTL, "I found a negative fScaleFactor in " << __FILE__ << ":" << __LINE__); - QERROR(FTL, "fScaleFactor = " << fScaleFactor); - QTHROW("EXITING"); + NUIS_ERR(FTL, "fScaleFactor = " << fScaleFactor); + NUIS_ABORT("EXITING"); } // Create and fill Weighted Histogram if (!fMCWeighted) { fMCWeighted = (TH2D *)fMCHist->Clone(); fMCWeighted->SetNameTitle((fName + "_MCWGHTS").c_str(), (fName + "_MCWGHTS" + fPlotTitles).c_str()); fMCWeighted->GetYaxis()->SetTitle("Weighted Events"); } if (!fMapHist) fMapHist = StatUtils::GenerateMap(fDataHist); } //******************************************************************** void Measurement2D::SetFitOptions(std::string opt) { //******************************************************************** // Do nothing if default given if (opt == "DEFAULT") return; // CHECK Conflicting Fit Options std::vector fit_option_allow = GeneralUtils::ParseToStr(fAllowedTypes, "/"); for (UInt_t i = 0; i < fit_option_allow.size(); i++) { std::vector fit_option_section = GeneralUtils::ParseToStr(fit_option_allow.at(i), ","); bool found_option = false; for (UInt_t j = 0; j < fit_option_section.size(); j++) { std::string av_opt = fit_option_section.at(j); if (!found_option and opt.find(av_opt) != std::string::npos) { found_option = true; } else if (found_option and opt.find(av_opt) != std::string::npos) { - QTHROW("ERROR: Conflicting fit options provided: " + NUIS_ABORT("ERROR: Conflicting fit options provided: " << opt << std::endl << "Conflicting group = " << fit_option_section.at(i) << std::endl << "You should only supply one of these options in card file."); } } } // Check all options are allowed std::vector fit_options_input = GeneralUtils::ParseToStr(opt, "/"); for (UInt_t i = 0; i < fit_options_input.size(); i++) { if (fAllowedTypes.find(fit_options_input.at(i)) == std::string::npos) { - QERROR(FTL, "ERROR: Fit Option '" + NUIS_ERR(FTL, "ERROR: Fit Option '" << fit_options_input.at(i) << "' Provided is not allowed for this measurement."); - QERROR(FTL, "Fit Options should be provided as a '/' seperated list " + NUIS_ERR(FTL, "Fit Options should be provided as a '/' seperated list " "(e.g. FREE/DIAG/NORM)"); - QTHROW("Available options for " << fName << " are '" << fAllowedTypes + NUIS_ABORT("Available options for " << fName << " are '" << fAllowedTypes << "'"); } } // Set TYPE fFitType = opt; // FIX,SHAPE,FREE if (opt.find("FIX") != std::string::npos) { fIsFree = fIsShape = false; fIsFix = true; } else if (opt.find("SHAPE") != std::string::npos) { fIsFree = fIsFix = false; fIsShape = true; } else if (opt.find("FREE") != std::string::npos) { fIsFix = fIsShape = false; fIsFree = true; } // DIAG,FULL (or default to full) if (opt.find("DIAG") != std::string::npos) { fIsDiag = true; fIsFull = false; } else if (opt.find("FULL") != std::string::npos) { fIsDiag = false; fIsFull = true; } // CHI2/LL (OTHERS?) if (opt.find("LOG") != std::string::npos) { fIsChi2 = false; - QERROR(FTL, "No other LIKELIHOODS properly supported!"); - QTHROW("Try to use a chi2!"); + NUIS_ERR(FTL, "No other LIKELIHOODS properly supported!"); + NUIS_ABORT("Try to use a chi2!"); } else { fIsChi2 = true; } // EXTRAS if (opt.find("RAW") != std::string::npos) fIsRawEvents = true; if (opt.find("DIF") != std::string::npos) fIsDifXSec = true; if (opt.find("ENU1D") != std::string::npos) fIsEnu1D = true; if (opt.find("NORM") != std::string::npos) fAddNormPen = true; if (opt.find("MASK") != std::string::npos) fIsMask = true; // Set TYPE fFitType = opt; // FIX,SHAPE,FREE if (opt.find("FIX") != std::string::npos) { fIsFree = fIsShape = false; fIsFix = true; } else if (opt.find("SHAPE") != std::string::npos) { fIsFree = fIsFix = false; fIsShape = true; } else if (opt.find("FREE") != std::string::npos) { fIsFix = fIsShape = false; fIsFree = true; } // DIAG,FULL (or default to full) if (opt.find("DIAG") != std::string::npos) { fIsDiag = true; fIsFull = false; } else if (opt.find("FULL") != std::string::npos) { fIsDiag = false; fIsFull = true; } // CHI2/LL (OTHERS?) if (opt.find("LOG") != std::string::npos) fIsChi2 = false; else fIsChi2 = true; // EXTRAS if (opt.find("RAW") != std::string::npos) fIsRawEvents = true; if (opt.find("DIF") != std::string::npos) fIsDifXSec = true; if (opt.find("ENU1D") != std::string::npos) fIsEnu = true; if (opt.find("NORM") != std::string::npos) fAddNormPen = true; if (opt.find("MASK") != std::string::npos) fIsMask = true; fIsProjFitX = (opt.find("FITPROJX") != std::string::npos); fIsProjFitY = (opt.find("FITPROJY") != std::string::npos); return; }; /* Reconfigure LOOP */ //******************************************************************** void Measurement2D::ResetAll() { //******************************************************************** fMCHist->Reset(); fMCFine->Reset(); fMCStat->Reset(); return; }; //******************************************************************** void Measurement2D::FillHistograms() { //******************************************************************** if (Signal) { fMCHist->Fill(fXVar, fYVar, Weight); fMCFine->Fill(fXVar, fYVar, Weight); fMCStat->Fill(fXVar, fYVar, 1.0); if (fMCHist_Modes) fMCHist_Modes->Fill(Mode, fXVar, fYVar, Weight); } return; }; //******************************************************************** void Measurement2D::ScaleEvents() { //******************************************************************** // Fill MCWeighted; // for (int i = 0; i < fMCHist->GetNbinsX(); i++) { // fMCWeighted->SetBinContent(i + 1, fMCHist->GetBinContent(i + 1)); // fMCWeighted->SetBinError(i + 1, fMCHist->GetBinError(i + 1)); // } // Setup Stat ratios for MC and MC Fine double *statratio = new double[fMCHist->GetNbinsX()]; for (int i = 0; i < fMCHist->GetNbinsX(); i++) { if (fMCHist->GetBinContent(i + 1) != 0) { statratio[i] = fMCHist->GetBinError(i + 1) / fMCHist->GetBinContent(i + 1); } else { statratio[i] = 0.0; } } double *statratiofine = new double[fMCFine->GetNbinsX()]; for (int i = 0; i < fMCFine->GetNbinsX(); i++) { if (fMCFine->GetBinContent(i + 1) != 0) { statratiofine[i] = fMCFine->GetBinError(i + 1) / fMCFine->GetBinContent(i + 1); } else { statratiofine[i] = 0.0; } } // Scaling for raw event rates if (fIsRawEvents) { double datamcratio = fDataHist->Integral() / fMCHist->Integral(); fMCHist->Scale(datamcratio); fMCFine->Scale(datamcratio); if (fMCHist_Modes) fMCHist_Modes->Scale(datamcratio); // Scaling for XSec as function of Enu } else if (fIsEnu1D) { PlotUtils::FluxUnfoldedScaling(fMCHist, GetFluxHistogram(), GetEventHistogram(), fScaleFactor); PlotUtils::FluxUnfoldedScaling(fMCFine, GetFluxHistogram(), GetEventHistogram(), fScaleFactor); // if (fMCHist_Modes) { // PlotUtils::FluxUnfoldedScaling(fMCHist_Modes, GetFluxHistogram(), // GetEventHistogram(), fScaleFactor, // fNEvents); // } // Any other differential scaling } else { fMCHist->Scale(fScaleFactor, "width"); fMCFine->Scale(fScaleFactor, "width"); // if (fMCHist_Modes) fMCHist_Modes->Scale(fScaleFactor, "width"); } // Proper error scaling - ROOT Freaks out with xsec weights sometimes for (int i = 0; i < fMCStat->GetNbinsX(); i++) { fMCHist->SetBinError(i + 1, fMCHist->GetBinContent(i + 1) * statratio[i]); } for (int i = 0; i < fMCFine->GetNbinsX(); i++) { fMCFine->SetBinError(i + 1, fMCFine->GetBinContent(i + 1) * statratiofine[i]); } // Clean up delete statratio; delete statratiofine; return; }; //******************************************************************** void Measurement2D::ApplyNormScale(double norm) { //******************************************************************** fCurrentNorm = norm; fMCHist->Scale(1.0 / norm); fMCFine->Scale(1.0 / norm); return; }; /* Statistic Functions - Outsources to StatUtils */ //******************************************************************** int Measurement2D::GetNDOF() { //******************************************************************** // Just incase it has gone... if (!fDataHist) return -1; int nDOF = 0; // If datahist has no errors make sure we don't include those bins as they are // not data points for (int xBin = 0; xBin < fDataHist->GetNbinsX(); ++xBin) { for (int yBin = 0; yBin < fDataHist->GetNbinsY(); ++yBin) { if (fDataHist->GetBinError(xBin + 1, yBin + 1) != 0) ++nDOF; } } // Account for possible bin masking int nMasked = 0; if (fMaskHist and fIsMask) if (fMaskHist->Integral() > 0) for (int xBin = 0; xBin < fMaskHist->GetNbinsX() + 1; ++xBin) for (int yBin = 0; yBin < fMaskHist->GetNbinsY() + 1; ++yBin) if (fMaskHist->GetBinContent(xBin, yBin) > 0.5) ++nMasked; // Take away those masked DOF if (fIsMask) { nDOF -= nMasked; } return nDOF; } //******************************************************************** double Measurement2D::GetLikelihood() { //******************************************************************** // If this is for a ratio, there is no data histogram to compare to! if (fNoData || !fDataHist) return 0.; // Fix weird masking bug if (!fIsMask) { if (fMaskHist) { fMaskHist = NULL; } } else { if (fMaskHist) { PlotUtils::MaskBins(fMCHist, fMaskHist); } } // if (fIsProjFitX or fIsProjFitY) return GetProjectedChi2(); // Scale up the results to match each other (Not using width might be // inconsistent with Meas1D) double scaleF = fDataHist->Integral() / fMCHist->Integral(); if (fIsShape) { fMCHist->Scale(scaleF); fMCFine->Scale(scaleF); // PlotUtils::ScaleNeutModeArray((TH1**)fMCHist_PDG, scaleF); } if (!fMapHist) fMapHist = StatUtils::GenerateMap(fDataHist); // Get the chi2 from either covar or diagonals double chi2 = 0.0; if (fIsChi2) { if (fIsDiag) { chi2 = StatUtils::GetChi2FromDiag(fDataHist, fMCHist, fMapHist, fMaskHist); } else { chi2 = StatUtils::GetChi2FromCov(fDataHist, fMCHist, covar, fMapHist, fMaskHist); } } // Add a normal penalty term if (fAddNormPen) { chi2 += (1 - (fCurrentNorm)) * (1 - (fCurrentNorm)) / (fNormError * fNormError); - QLOG(REC, "Norm penalty = " << (1 - (fCurrentNorm)) * (1 - (fCurrentNorm)) / + NUIS_LOG(REC, "Norm penalty = " << (1 - (fCurrentNorm)) * (1 - (fCurrentNorm)) / (fNormError * fNormError)); } // Adjust the shape back to where it was. if (fIsShape and !FitPar::Config().GetParB("saveshapescaling")) { fMCHist->Scale(1. / scaleF); fMCFine->Scale(1. / scaleF); } fLikelihood = chi2; return chi2; } /* Fake Data Functions */ //******************************************************************** void Measurement2D::SetFakeDataValues(std::string fakeOption) { //******************************************************************** // Setup original/datatrue TH2D *tempdata = (TH2D *)fDataHist->Clone(); if (!fIsFakeData) { fIsFakeData = true; // Make a copy of the original data histogram. if (!fDataOrig) fDataOrig = (TH2D *)fDataHist->Clone((fName + "_data_original").c_str()); } else { ResetFakeData(); } // Setup Inputs fFakeDataInput = fakeOption; - QLOG(SAM, "Setting fake data from : " << fFakeDataInput); + NUIS_LOG(SAM, "Setting fake data from : " << fFakeDataInput); // From MC if (fFakeDataInput.compare("MC") == 0) { fDataHist = (TH2D *)fMCHist->Clone((fName + "_MC").c_str()); // Fake File } else { if (!fFakeDataFile) fFakeDataFile = new TFile(fFakeDataInput.c_str(), "READ"); fDataHist = (TH2D *)fFakeDataFile->Get((fName + "_MC").c_str()); } // Setup Data Hist fDataHist->SetNameTitle((fName + "_FAKE").c_str(), (fName + fPlotTitles).c_str()); // Replace Data True if (fDataTrue) delete fDataTrue; fDataTrue = (TH2D *)fDataHist->Clone(); fDataTrue->SetNameTitle((fName + "_FAKE_TRUE").c_str(), (fName + fPlotTitles).c_str()); // Make a new covariance for fake data hist. int nbins = fDataHist->GetNbinsX() * fDataHist->GetNbinsY(); double alpha_i = 0.0; double alpha_j = 0.0; for (int i = 0; i < nbins; i++) { for (int j = 0; j < nbins; j++) { if (tempdata->GetBinContent(i + 1) && tempdata->GetBinContent(j + 1)) { alpha_i = fDataHist->GetBinContent(i + 1) / tempdata->GetBinContent(i + 1); alpha_j = fDataHist->GetBinContent(j + 1) / tempdata->GetBinContent(j + 1); } else { alpha_i = 0.0; alpha_j = 0.0; } (*fFullCovar)(i, j) = alpha_i * alpha_j * (*fFullCovar)(i, j); } } // Setup Covariances if (covar) delete covar; covar = StatUtils::GetInvert(fFullCovar); if (fDecomp) delete fDecomp; fDecomp = StatUtils::GetInvert(fFullCovar); delete tempdata; return; }; //******************************************************************** void Measurement2D::ResetFakeData() { //******************************************************************** if (fIsFakeData) { if (fDataHist) delete fDataHist; fDataHist = (TH2D *)fDataTrue->Clone((fSettings.GetName() + "_FKDAT").c_str()); } } //******************************************************************** void Measurement2D::ResetData() { //******************************************************************** if (fIsFakeData) { if (fDataHist) delete fDataHist; fDataHist = (TH2D *)fDataOrig->Clone((fSettings.GetName() + "_data").c_str()); } fIsFakeData = false; } //******************************************************************** void Measurement2D::ThrowCovariance() { //******************************************************************** // Take a fDecomposition and use it to throw the current dataset. // Requires fDataTrue also be set incase used repeatedly. if (fDataHist) delete fDataHist; fDataHist = StatUtils::ThrowHistogram(fDataTrue, fFullCovar); return; }; //******************************************************************** void Measurement2D::ThrowDataToy() { //******************************************************************** if (!fDataTrue) fDataTrue = (TH2D *)fDataHist->Clone(); if (fMCHist) delete fMCHist; fMCHist = StatUtils::ThrowHistogram(fDataTrue, fFullCovar); } /* Access Functions */ //******************************************************************** TH2D *Measurement2D::GetMCHistogram() { //******************************************************************** if (!fMCHist) return fMCHist; std::ostringstream chi2; chi2 << std::setprecision(5) << this->GetLikelihood(); int linecolor = kRed; int linestyle = 1; int linewidth = 1; int fillcolor = 0; int fillstyle = 1001; if (fSettings.Has("linecolor")) linecolor = fSettings.GetI("linecolor"); if (fSettings.Has("linestyle")) linestyle = fSettings.GetI("linestyle"); if (fSettings.Has("linewidth")) linewidth = fSettings.GetI("linewidth"); if (fSettings.Has("fillcolor")) fillcolor = fSettings.GetI("fillcolor"); if (fSettings.Has("fillstyle")) fillstyle = fSettings.GetI("fillstyle"); fMCHist->SetTitle(chi2.str().c_str()); fMCHist->SetLineColor(linecolor); fMCHist->SetLineStyle(linestyle); fMCHist->SetLineWidth(linewidth); fMCHist->SetFillColor(fillcolor); fMCHist->SetFillStyle(fillstyle); return fMCHist; }; //******************************************************************** TH2D *Measurement2D::GetDataHistogram() { //******************************************************************** if (!fDataHist) return fDataHist; int datacolor = kBlack; int datastyle = 1; int datawidth = 1; if (fSettings.Has("datacolor")) datacolor = fSettings.GetI("datacolor"); if (fSettings.Has("datastyle")) datastyle = fSettings.GetI("datastyle"); if (fSettings.Has("datawidth")) datawidth = fSettings.GetI("datawidth"); fDataHist->SetLineColor(datacolor); fDataHist->SetLineWidth(datawidth); fDataHist->SetMarkerStyle(datastyle); return fDataHist; }; /* Write Functions */ // Save all the histograms at once //******************************************************************** void Measurement2D::Write(std::string drawOpt) { //******************************************************************** // Get Draw Options drawOpt = FitPar::Config().GetParS("drawopts"); // Write Settigns if (drawOpt.find("SETTINGS") != std::string::npos) { fSettings.Set("#chi^{2}", fLikelihood); fSettings.Set("NDOF", this->GetNDOF()); fSettings.Set("#chi^{2}/NDOF", fLikelihood / this->GetNDOF()); fSettings.Write(); } // // Likelihood residual plots // if (drawOpt.find("RESIDUAL") != std::string::npos) { // WriteResidualPlots(); //} // // RATIO // if (drawOpt.find("CANVMC") != std::string::npos) { // TCanvas* c1 = WriteMCCanvas(fDataHist, fMCHist); // c1->Write(); // delete c1; // } // // PDG // if (drawOpt.find("CANVPDG") != std::string::npos && fMCHist_Modes) { // TCanvas* c2 = WritePDGCanvas(fDataHist, fMCHist, fMCHist_Modes); // c2->Write(); // delete c2; // } /// 2D VERSION // If null pointer return if (!fMCHist and !fDataHist) { - QLOG(SAM, fName << "Incomplete histogram set!"); + NUIS_LOG(SAM, fName << "Incomplete histogram set!"); return; } // Config::Get().out->cd(); // Get Draw Options drawOpt = FitPar::Config().GetParS("drawopts"); bool drawData = (drawOpt.find("DATA") != std::string::npos); bool drawNormal = (drawOpt.find("MC") != std::string::npos); bool drawEvents = (drawOpt.find("EVT") != std::string::npos); bool drawFine = (drawOpt.find("FINE") != std::string::npos); bool drawRatio = (drawOpt.find("RATIO") != std::string::npos); // bool drawModes = (drawOpt.find("MODES") != std::string::npos); bool drawShape = (drawOpt.find("SHAPE") != std::string::npos); bool residual = (drawOpt.find("RESIDUAL") != std::string::npos); bool drawMatrix = (drawOpt.find("MATRIX") != std::string::npos); bool drawFlux = (drawOpt.find("FLUX") != std::string::npos); bool drawMask = (drawOpt.find("MASK") != std::string::npos); bool drawMap = (drawOpt.find("MAP") != std::string::npos); bool drawProj = (drawOpt.find("PROJ") != std::string::npos); // bool drawCanvPDG = (drawOpt.find("CANVPDG") != std::string::npos); bool drawCov = (drawOpt.find("COV") != std::string::npos); bool drawSliceMC = (drawOpt.find("CANVSLICEMC") != std::string::npos); bool drawWeighted = (drawOpt.find("WEIGHTS") != std::string::npos && fMCWeighted); if (FitPar::Config().GetParB("EventManager")) { drawFlux = false; drawEvents = false; } // Save standard plots if (drawData) { GetDataList().at(0)->Write(); // Generate a simple map if (!fMapHist) fMapHist = StatUtils::GenerateMap(fDataHist); // Convert to 1D Lists TH1D *data_1D = StatUtils::MapToTH1D(fDataHist, fMapHist); data_1D->Write(); delete data_1D; } if (drawNormal) { GetMCList().at(0)->Write(); if (!fMapHist) fMapHist = StatUtils::GenerateMap(fDataHist); TH1D *mc_1D = StatUtils::MapToTH1D(fMCHist, fMapHist); mc_1D->SetLineColor(kRed); mc_1D->Write(); delete mc_1D; } // Write Weighted Histogram if (drawWeighted) fMCWeighted->Write(); if (drawCov) { TH2D(*fFullCovar).Write((fName + "_COV").c_str()); } if (drawOpt.find("INVCOV") != std::string::npos) { TH2D(*covar).Write((fName + "_INVCOV").c_str()); } // Save only mc and data if splines if (fEventType == 4 or fEventType == 3) { return; } // Draw Extra plots if (drawFine) this->GetFineList().at(0)->Write(); if (drawFlux and GetFluxHistogram()) { GetFluxHistogram()->Write(); } if (drawEvents and GetEventHistogram()) { GetEventHistogram()->Write(); } if (fIsMask and drawMask) { fMaskHist->Write((fName + "_MSK").c_str()); //< save mask TH1I *mask_1D = StatUtils::MapToMask(fMaskHist, fMapHist); if (mask_1D) { mask_1D->Write(); TMatrixDSym *calc_cov = StatUtils::ApplyInvertedMatrixMasking(covar, mask_1D); TH1D *data_1D = StatUtils::MapToTH1D(fDataHist, fMapHist); TH1D *mc_1D = StatUtils::MapToTH1D(fMCHist, fMapHist); TH1D *calc_data = StatUtils::ApplyHistogramMasking(data_1D, mask_1D); TH1D *calc_mc = StatUtils::ApplyHistogramMasking(mc_1D, mask_1D); TH2D *bin_cov = new TH2D(*calc_cov); bin_cov->Write(); calc_data->Write(); calc_mc->Write(); delete mask_1D; delete calc_cov; delete calc_data; delete calc_mc; delete bin_cov; delete data_1D; delete mc_1D; } } if (drawMap) fMapHist->Write((fName + "_MAP").c_str()); //< save map // // Save neut stack // if (drawModes) { // THStack combo_fMCHist_PDG = PlotUtils::GetNeutModeStack( // (fName + "_MC_PDG").c_str(), // (TH1**)fMCHist_PDG, 0); // combo_fMCHist_PDG.Write(); // } // Save Matrix plots if (drawMatrix and fFullCovar and covar and fDecomp) { TH2D cov = TH2D((*fFullCovar)); cov.SetNameTitle((fName + "_cov").c_str(), (fName + "_cov;Bins; Bins;").c_str()); cov.Write(); TH2D covinv = TH2D((*this->covar)); covinv.SetNameTitle((fName + "_covinv").c_str(), (fName + "_cov;Bins; Bins;").c_str()); covinv.Write(); TH2D covdec = TH2D((*fDecomp)); covdec.SetNameTitle((fName + "_covdec").c_str(), (fName + "_cov;Bins; Bins;").c_str()); covdec.Write(); } // Save ratio plots if required if (drawRatio) { // Needed for error bars for (int i = 0; i < fMCHist->GetNbinsX() * fMCHist->GetNbinsY(); i++) fMCHist->SetBinError(i + 1, 0.0); fDataHist->GetSumw2(); fMCHist->GetSumw2(); // Create Ratio Histograms TH2D *dataRatio = (TH2D *)fDataHist->Clone((fName + "_data_RATIO").c_str()); TH2D *mcRatio = (TH2D *)fMCHist->Clone((fName + "_MC_RATIO").c_str()); mcRatio->Divide(fMCHist); dataRatio->Divide(fMCHist); // Cancel bin errors on MC for (int i = 0; i < mcRatio->GetNbinsX() * mcRatio->GetNbinsY(); i++) { mcRatio->SetBinError(i + 1, fMCHist->GetBinError(i + 1) / fMCHist->GetBinContent(i + 1)); } mcRatio->SetMinimum(0); mcRatio->SetMaximum(2); dataRatio->SetMinimum(0); dataRatio->SetMaximum(2); mcRatio->Write(); dataRatio->Write(); delete mcRatio; delete dataRatio; } // Save Shape Plots if required if (drawShape) { // Create Shape Histogram TH2D *mcShape = (TH2D *)fMCHist->Clone((fName + "_MC_SHAPE").c_str()); double shapeScale = 1.0; if (fIsRawEvents) { shapeScale = fDataHist->Integral() / fMCHist->Integral(); } else { shapeScale = fDataHist->Integral("width") / fMCHist->Integral("width"); } mcShape->Scale(shapeScale); mcShape->SetLineWidth(3); mcShape->SetLineStyle(7); // dashes mcShape->Write(); // Save shape ratios if (drawRatio) { // Needed for error bars mcShape->GetSumw2(); // Create shape ratio histograms TH2D *mcShapeRatio = (TH2D *)mcShape->Clone((fName + "_MC_SHAPE_RATIO").c_str()); TH2D *dataShapeRatio = (TH2D *)fDataHist->Clone((fName + "_data_SHAPE_RATIO").c_str()); // Divide the histograms mcShapeRatio->Divide(mcShape); dataShapeRatio->Divide(mcShape); // Colour the shape ratio plots mcShapeRatio->SetLineWidth(3); mcShapeRatio->SetLineStyle(7); // dashes mcShapeRatio->Write(); dataShapeRatio->Write(); delete mcShapeRatio; delete dataShapeRatio; } delete mcShape; } // Save residual calculations of what contributed to the chi2 values. if (residual) { } if (fIsProjFitX || fIsProjFitY || drawProj) { // If not already made, make the projections if (!fMCHist_X) { PlotUtils::MatchEmptyBins(fDataHist, fMCHist); fMCHist_X = PlotUtils::GetProjectionX(fMCHist, fMaskHist); fMCHist_Y = PlotUtils::GetProjectionY(fMCHist, fMaskHist); fDataHist_X = PlotUtils::GetProjectionX(fDataHist, fMaskHist); fDataHist_Y = PlotUtils::GetProjectionY(fDataHist, fMaskHist); // This is not the correct way of doing it // double chi2X = StatUtils::GetChi2FromDiag(fDataHist_X, fMCHist_X); // double chi2Y = StatUtils::GetChi2FromDiag(fDataHist_Y, fMCHist_Y); // fMCHist_X->SetTitle(Form("%f", chi2X)); // fMCHist_Y->SetTitle(Form("%f", chi2Y)); } // Save the histograms fDataHist_X->Write(); fMCHist_X->Write(); fDataHist_Y->Write(); fMCHist_Y->Write(); } if (drawSliceMC) { TCanvas *c1 = new TCanvas((fName + "_MC_CANV_Y").c_str(), (fName + "_MC_CANV_Y").c_str(), 1024, 1024); c1->Divide(2, int(fDataHist->GetNbinsY() / 3. + 1)); TH2D *mcShape = (TH2D *)fMCHist->Clone((fName + "_MC_SHAPE").c_str()); double shapeScale = fDataHist->Integral("width") / fMCHist->Integral("width"); mcShape->Scale(shapeScale); mcShape->SetLineStyle(7); c1->cd(1); TLegend *leg = new TLegend(0.0, 0.0, 1.0, 1.0); leg->AddEntry(fDataHist, (fName + " Data").c_str(), "lep"); leg->AddEntry(fMCHist, (fName + " MC").c_str(), "l"); leg->AddEntry(mcShape, (fName + " Shape").c_str(), "l"); leg->SetLineColor(0); leg->SetLineStyle(0); leg->SetFillColor(0); leg->SetLineStyle(0); leg->Draw("SAME"); // Make Y slices for (int i = 1; i < fDataHist->GetNbinsY() + 1; i++) { c1->cd(i + 1); TH1D *fDataHist_SliceY = PlotUtils::GetSliceY(fDataHist, i); fDataHist_SliceY->Draw("E1"); TH1D *fMCHist_SliceY = PlotUtils::GetSliceY(fMCHist, i); fMCHist_SliceY->Draw("SAME"); TH1D *mcShape_SliceY = PlotUtils::GetSliceY(mcShape, i); mcShape_SliceY->Draw("SAME"); mcShape_SliceY->SetLineStyle(mcShape->GetLineStyle()); } c1->Write(); delete c1; delete leg; TCanvas *c2 = new TCanvas((fName + "_MC_CANV_X").c_str(), (fName + "_MC_CANV_X").c_str(), 1024, 1024); c2->Divide(2, int(fDataHist->GetNbinsX() / 3. + 1)); mcShape = (TH2D *)fMCHist->Clone((fName + "_MC_SHAPE").c_str()); shapeScale = fDataHist->Integral("width") / fMCHist->Integral("width"); mcShape->Scale(shapeScale); mcShape->SetLineStyle(7); c2->cd(1); TLegend *leg2 = new TLegend(0.0, 0.0, 1.0, 1.0); leg2->AddEntry(fDataHist, (fName + " Data").c_str(), "lep"); leg2->AddEntry(fMCHist, (fName + " MC").c_str(), "l"); leg2->AddEntry(mcShape, (fName + " Shape").c_str(), "l"); leg2->SetLineColor(0); leg2->SetLineStyle(0); leg2->SetFillColor(0); leg2->SetLineStyle(0); leg2->Draw("SAME"); // Make Y slices for (int i = 1; i < fDataHist->GetNbinsX() + 1; i++) { c2->cd(i + 1); TH1D *fDataHist_SliceX = PlotUtils::GetSliceX(fDataHist, i); fDataHist_SliceX->Draw("E1"); TH1D *fMCHist_SliceX = PlotUtils::GetSliceX(fMCHist, i); fMCHist_SliceX->Draw("SAME"); TH1D *mcShape_SliceX = PlotUtils::GetSliceX(mcShape, i); mcShape_SliceX->Draw("SAME"); mcShape_SliceX->SetLineStyle(mcShape->GetLineStyle()); } c2->Write(); delete c2; delete leg2; } // Write Extra Histograms AutoWriteExtraTH1(); WriteExtraHistograms(); // Returning - QLOG(SAM, "Written Histograms: " << fName); + NUIS_LOG(SAM, "Written Histograms: " << fName); return; } /* Setup Functions */ //******************************************************************** void Measurement2D::SetupMeasurement(std::string inputfile, std::string type, FitWeight *rw, std::string fkdt) { //******************************************************************** // Check if name contains Evt, indicating that it is a raw number of events // measurements and should thus be treated as once fIsRawEvents = false; if ((fName.find("Evt") != std::string::npos) && fIsRawEvents == false) { fIsRawEvents = true; - QLOG(SAM, "Found event rate measurement but fIsRawEvents == false!"); - QLOG(SAM, "Overriding this and setting fIsRawEvents == true!"); + NUIS_LOG(SAM, "Found event rate measurement but fIsRawEvents == false!"); + NUIS_LOG(SAM, "Overriding this and setting fIsRawEvents == true!"); } fIsEnu = false; if ((fName.find("XSec") != std::string::npos) && (fName.find("Enu") != std::string::npos)) { fIsEnu = true; - QLOG(SAM, "::" << fName << "::"); - QLOG(SAM, "Found XSec Enu measurement, applying flux integrated scaling, " + NUIS_LOG(SAM, "::" << fName << "::"); + NUIS_LOG(SAM, "Found XSec Enu measurement, applying flux integrated scaling, " "not flux averaged!"); if (FitPar::Config().GetParB("EventManager")) { - QERROR(FTL, "Enu Measurements do not yet work with the Event Manager!"); - QERROR(FTL, "If you want decent flux unfolded results please run in " + NUIS_ERR(FTL, "Enu Measurements do not yet work with the Event Manager!"); + NUIS_ERR(FTL, "If you want decent flux unfolded results please run in " "series mode (-q EventManager=0)"); sleep(2); throw; } } if (fIsEnu && fIsRawEvents) { - QERROR(FTL, "Found 1D Enu XSec distribution AND fIsRawEvents, is this " + NUIS_ERR(FTL, "Found 1D Enu XSec distribution AND fIsRawEvents, is this " "really correct?!"); - QERROR(FTL, "Check experiment constructor for " << fName + NUIS_ERR(FTL, "Check experiment constructor for " << fName << " and correct this!"); - QTHROW("I live in " << __FILE__ << ":" << __LINE__); + NUIS_ABORT("I live in " << __FILE__ << ":" << __LINE__); } // Reset everything to NULL fRW = rw; // Setting up 2D Inputs this->SetupInputs(inputfile); // Set Default Options SetFitOptions(fDefaultTypes); // Set Passed Options SetFitOptions(type); } //******************************************************************** void Measurement2D::SetupDefaultHist() { //******************************************************************** // Setup fMCHist fMCHist = (TH2D *)fDataHist->Clone(); fMCHist->SetNameTitle((fName + "_MC").c_str(), (fName + "_MC" + fPlotTitles).c_str()); // Setup fMCFine Int_t nBinsX = fMCHist->GetNbinsX(); Int_t nBinsY = fMCHist->GetNbinsY(); fMCFine = new TH2D((fName + "_MC_FINE").c_str(), (fName + "_MC_FINE" + fPlotTitles).c_str(), nBinsX * 3, fMCHist->GetXaxis()->GetBinLowEdge(1), fMCHist->GetXaxis()->GetBinLowEdge(nBinsX + 1), nBinsY * 3, fMCHist->GetYaxis()->GetBinLowEdge(1), fMCHist->GetYaxis()->GetBinLowEdge(nBinsY + 1)); // Setup MC Stat fMCStat = (TH2D *)fMCHist->Clone(); fMCStat->Reset(); // Setup the NEUT Mode Array // PlotUtils::CreateNeutModeArray(fMCHist, (TH1**)fMCHist_PDG); // Setup bin masks using sample name if (fIsMask) { std::string maskloc = FitPar::Config().GetParDIR(fName + ".mask"); if (maskloc.empty()) { maskloc = FitPar::GetDataBase() + "/masks/" + fName + ".mask"; } SetBinMask(maskloc); } return; } //******************************************************************** void Measurement2D::SetDataValues(std::string dataFile, std::string TH2Dname) { //******************************************************************** if (dataFile.find(".root") == std::string::npos) { - QERROR(FTL, "Error! " << dataFile << " is not a .root file"); - QERROR(FTL, "Currently only .root file reading is supported (MiniBooNE " + NUIS_ERR(FTL, "Error! " << dataFile << " is not a .root file"); + NUIS_ERR(FTL, "Currently only .root file reading is supported (MiniBooNE " "CC1pi+ 2D), but implementing .txt should be dirt easy"); - QTHROW("See me at " << __FILE__ << ":" << __LINE__); + NUIS_ABORT("See me at " << __FILE__ << ":" << __LINE__); } else { TFile *inFile = new TFile(dataFile.c_str(), "READ"); fDataHist = (TH2D *)(inFile->Get(TH2Dname.c_str())->Clone()); fDataHist->SetDirectory(0); fDataHist->SetNameTitle((fName + "_data").c_str(), (fName + "_MC" + fPlotTitles).c_str()); delete inFile; } return; } //******************************************************************** void Measurement2D::SetDataValues(std::string dataFile, double dataNorm, std::string errorFile, double errorNorm) { //******************************************************************** // Make a counter to track the line number int yBin = 0; std::string line; std::ifstream data(dataFile.c_str(), std::ifstream::in); fDataHist = new TH2D((fName + "_data").c_str(), (fName + fPlotTitles).c_str(), fNDataPointsX - 1, fXBins, fNDataPointsY - 1, fYBins); if (data.is_open()) { - QLOG(SAM, "Reading data from: " << dataFile.c_str()); + NUIS_LOG(SAM, "Reading data from: " << dataFile.c_str()); } while (std::getline(data >> std::ws, line, '\n')) { int xBin = 0; // Loop over entries and insert them into the histogram std::vector entries = GeneralUtils::ParseToDbl(line, " "); for (std::vector::iterator iter = entries.begin(); iter != entries.end(); iter++) { fDataHist->SetBinContent(xBin + 1, yBin + 1, (*iter) * dataNorm); xBin++; } yBin++; } yBin = 0; std::ifstream error(errorFile.c_str(), std::ifstream::in); if (error.is_open()) { - QLOG(SAM, "Reading errors from: " << errorFile.c_str()); + NUIS_LOG(SAM, "Reading errors from: " << errorFile.c_str()); } while (std::getline(error >> std::ws, line, '\n')) { int xBin = 0; // Loop over entries and insert them into the histogram std::vector entries = GeneralUtils::ParseToDbl(line, " "); for (std::vector::iterator iter = entries.begin(); iter != entries.end(); iter++) { fDataHist->SetBinError(xBin + 1, yBin + 1, (*iter) * errorNorm); xBin++; } yBin++; } return; }; //******************************************************************** void Measurement2D::SetDataValuesFromText(std::string dataFile, double dataNorm) { //******************************************************************** fDataHist = new TH2D((fName + "_data").c_str(), (fName + fPlotTitles).c_str(), fNDataPointsX - 1, fXBins, fNDataPointsY - 1, fYBins); - QLOG(SAM, "Reading data from: " << dataFile); + NUIS_LOG(SAM, "Reading data from: " << dataFile); PlotUtils::Set2DHistFromText(dataFile, fDataHist, dataNorm, true); return; }; //******************************************************************** void Measurement2D::SetCovarMatrix(std::string covarFile) { //******************************************************************** // Used to read a covariance matrix from a root file TFile *tempFile = new TFile(covarFile.c_str(), "READ"); // Make plots that we want TH2D *covarPlot = new TH2D(); TH2D *fFullCovarPlot = new TH2D(); // Get covariance options for fake data studies std::string covName = ""; std::string covOption = FitPar::Config().GetParS("throw_covariance"); // Which matrix to get? if (fIsShape || fIsFree) covName = "shp_"; if (fIsDiag) covName += "diag"; else covName += "full"; covarPlot = (TH2D *)tempFile->Get((covName + "cov").c_str()); // Throw either the sub matrix or the full matrix if (!covOption.compare("SUB")) fFullCovarPlot = (TH2D *)tempFile->Get((covName + "cov").c_str()); else if (!covOption.compare("FULL")) fFullCovarPlot = (TH2D *)tempFile->Get("fullcov"); else { - QERROR(WRN, " Incorrect thrown_covariance option in parameters."); + NUIS_ERR(WRN, " Incorrect thrown_covariance option in parameters."); } // Bin masking? int dim = int(fDataHist->GetNbinsX()); //-this->masked->Integral()); int covdim = int(fDataHist->GetNbinsX()); // Make new covars this->covar = new TMatrixDSym(dim); fFullCovar = new TMatrixDSym(dim); fDecomp = new TMatrixDSym(dim); // Full covariance values int row, column = 0; row = 0; column = 0; for (Int_t i = 0; i < covdim; i++) { // masking can be dodgy // if (this->masked->GetBinContent(i+1) > 0) continue; for (Int_t j = 0; j < covdim; j++) { // if (this->masked->GetBinContent(j+1) > 0) continue; (*this->covar)(row, column) = covarPlot->GetBinContent(i + 1, j + 1); (*fFullCovar)(row, column) = fFullCovarPlot->GetBinContent(i + 1, j + 1); column++; } column = 0; row++; } // Set bin errors on data if (!fIsDiag) { for (Int_t i = 0; i < fDataHist->GetNbinsX(); i++) { fDataHist->SetBinError( i + 1, sqrt((covarPlot->GetBinContent(i + 1, i + 1))) * 1E-38); } } TDecompSVD LU = TDecompSVD(*this->covar); this->covar = new TMatrixDSym(dim, LU.Invert().GetMatrixArray(), ""); tempFile->Close(); delete tempFile; return; }; //******************************************************************** void Measurement2D::SetCovarMatrixFromText(std::string covarFile, int dim) { //******************************************************************** // Make a counter to track the line number int row = 0; std::string line; std::ifstream covar(covarFile.c_str(), std::ifstream::in); this->covar = new TMatrixDSym(dim); fFullCovar = new TMatrixDSym(dim); if (covar.is_open()) { - QLOG(SAM, "Reading covariance matrix from file: " << covarFile); + NUIS_LOG(SAM, "Reading covariance matrix from file: " << covarFile); } while (std::getline(covar >> std::ws, line, '\n')) { int column = 0; // Loop over entries and insert them into matrix // Multiply by the errors to get the covariance, rather than the correlation // matrix std::vector entries = GeneralUtils::ParseToDbl(line, " "); for (std::vector::iterator iter = entries.begin(); iter != entries.end(); iter++) { double val = (*iter) * fDataHist->GetBinError(row + 1) * 1E38 * fDataHist->GetBinError(column + 1) * 1E38; (*this->covar)(row, column) = val; (*fFullCovar)(row, column) = val; column++; } row++; } // Robust matrix inversion method TDecompSVD LU = TDecompSVD(*this->covar); this->covar = new TMatrixDSym(dim, LU.Invert().GetMatrixArray(), ""); return; }; //******************************************************************** void Measurement2D::SetCovarMatrixFromChol(std::string covarFile, int dim) { //******************************************************************** // Make a counter to track the line number int row = 0; std::string line; std::ifstream covarread(covarFile.c_str(), std::ifstream::in); TMatrixD *newcov = new TMatrixD(dim, dim); if (covarread.is_open()) { - QLOG(SAM, "Reading covariance matrix from file: " << covarFile); + NUIS_LOG(SAM, "Reading covariance matrix from file: " << covarFile); } while (std::getline(covarread >> std::ws, line, '\n')) { int column = 0; // Loop over entries and insert them into matrix // Multiply by the errors to get the covariance, rather than the correlation // matrix std::vector entries = GeneralUtils::ParseToDbl(line, " "); for (std::vector::iterator iter = entries.begin(); iter != entries.end(); iter++) { (*newcov)(row, column) = *iter; column++; } row++; } covarread.close(); // Form full covariance TMatrixD *trans = (TMatrixD *)(newcov)->Clone(); trans->T(); (*trans) *= (*newcov); fFullCovar = new TMatrixDSym(dim, trans->GetMatrixArray(), ""); delete newcov; delete trans; // Robust matrix inversion method TDecompChol LU = TDecompChol(*this->fFullCovar); this->covar = new TMatrixDSym(dim, LU.Invert().GetMatrixArray(), ""); return; }; // //******************************************************************** // void Measurement2D::SetMapValuesFromText(std::string dataFile) { // //******************************************************************** // fMapHist = new TH2I((fName + "_map").c_str(), (fName + // fPlotTitles).c_str(), // fNDataPointsX - 1, fXBins, fNDataPointsY - 1, fYBins); // LOG(SAM) << "Reading map from: " << dataFile << std::endl; // PlotUtils::Set2DHistFromText(dataFile, fMapHist, 1.0); // return; // }; diff --git a/src/FitBase/MeasurementBase.cxx b/src/FitBase/MeasurementBase.cxx index 369fa3a..66e0d9d 100644 --- a/src/FitBase/MeasurementBase.cxx +++ b/src/FitBase/MeasurementBase.cxx @@ -1,597 +1,597 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MeasurementBase.h" /* Constructor/Destructors */ //******************************************************************** // 2nd Level Constructor (Inherits From MeasurementBase.h) MeasurementBase::MeasurementBase(void) { //******************************************************************** fScaleFactor = 1.0; fMCFilled = false; fNoData = false; fInput = NULL; NSignal = 0; // Set the default values // After-wards this gets set in SetupMeasurement EnuMin = 0.; EnuMax = 1.E5; fMeasurementSpeciesType = kSingleSpeciesMeasurement; fEventVariables = NULL; fIsJoint = false; fNPOT = 0xdeadbeef; fFluxIntegralOverride = 0xdeadbeef; fTargetVolume = 0xdeadbeef; fTargetMaterialDensity = 0xdeadbeef; fEvtRateScaleFactor = 0xdeadbeef; }; void MeasurementBase::FinaliseMeasurement() { // Used to setup default data hists, covars, etc. } //******************************************************************** // 2nd Level Destructor (Inherits From MeasurementBase.h) MeasurementBase::~MeasurementBase(){ //******************************************************************** }; //******************************************************************** double MeasurementBase::TotalIntegratedFlux(std::string intOpt, double low, double high) { //******************************************************************** // Set Energy Limits if (low == -9999.9) low = this->EnuMin; if (high == -9999.9) high = this->EnuMax; return GetInput()->TotalIntegratedFlux(low, high, intOpt); }; //******************************************************************** double MeasurementBase::PredictedEventRate(std::string intOpt, double low, double high) { //******************************************************************** // Set Energy Limits if (low == -9999.9) low = this->EnuMin; if (high == -9999.9) high = this->EnuMax; return GetInput()->PredictedEventRate(low, high, intOpt) * 1E-38; }; //******************************************************************** void MeasurementBase::SetupInputs(std::string inputfile) { //******************************************************************** // Add this infile to the global manager if (FitPar::Config().GetParB("EventManager")) { fInput = FitBase::AddInput(fName, inputfile); } else { std::vector file_descriptor = GeneralUtils::ParseToStr(inputfile, ":"); if (file_descriptor.size() != 2) { - QTHROW("File descriptor had no filetype declaration: \"" + NUIS_ABORT("File descriptor had no filetype declaration: \"" << inputfile << "\". expected \"FILETYPE:file.root\""); } InputUtils::InputType inpType = InputUtils::ParseInputType(file_descriptor[0]); fInput = InputUtils::CreateInputHandler(fName, inpType, file_descriptor[1]); } fNEvents = fInput->GetNEvents(); // Expect INPUTTYPE:FileLocation(s) std::vector file_descriptor = GeneralUtils::ParseToStr(inputfile, ":"); if (file_descriptor.size() != 2) { - QTHROW("File descriptor had no filetype declaration: \"" + NUIS_ABORT("File descriptor had no filetype declaration: \"" << inputfile << "\". expected \"FILETYPE:file.root\""); } fInputType = InputUtils::ParseInputType(file_descriptor[0]); fInputFileName = file_descriptor[1]; if (EnuMin == 0 && EnuMax == 1.E5) { EnuMin = fInput->GetFluxHistogram()->GetBinLowEdge(1); EnuMax = fInput->GetFluxHistogram()->GetBinLowEdge( fInput->GetFluxHistogram()->GetNbinsX() + 1); } fFluxHist = fInput->GetFluxHistogram(); fEventHist = fInput->GetEventHistogram(); } //*********************************************** int MeasurementBase::GetInputID() { //*********************************************** return FitBase::GetInputID(fInputFileName); } //*********************************************** SampleSettings MeasurementBase::LoadSampleSettings(nuiskey samplekey) { //*********************************************** SampleSettings setting = SampleSettings(samplekey); fName = setting.GetS("name"); // Used as an initial setup function incase we need to do anything here. - QLOG(SAM, "Loading Sample : " << setting.GetName()); + NUIS_LOG(SAM, "Loading Sample : " << setting.GetName()); fEvtRateScaleFactor = 0xdeadbeef; if (!fIsJoint) { SetupInputs(setting.GetS("input")); fNPOT = samplekey.Has("NPOT") ? samplekey.GetD("NPOT") : 1; fFluxIntegralOverride = samplekey.Has("FluxIntegralOverride") ? samplekey.GetD("FluxIntegralOverride") : 0xdeadbeef; fTargetVolume = samplekey.Has("TargetVolume") ? samplekey.GetD("TargetVolume") : 0xdeadbeef; fTargetMaterialDensity = samplekey.Has("TargetMaterialDensity") ? samplekey.GetD("TargetMaterialDensity") : 0xdeadbeef; if ((fTargetVolume != 0xdeadbeef) && (fTargetMaterialDensity != 0xdeadbeef)) { double TargetMass_kg = fTargetVolume * fTargetMaterialDensity; double NNucleons = TargetMass_kg / PhysConst::mass_nucleon_kg; double NNeutrinos = ((fFluxIntegralOverride == 0xdeadbeef) ? TotalIntegratedFlux() : fFluxIntegralOverride) * fNPOT; fEvtRateScaleFactor = NNeutrinos * NNucleons; - QLOG(SAM, "\tEvent rate prediction : "); - QLOG(SAM, "\t\tTarget volume : " << fTargetVolume << " m^3"); - QLOG(SAM, "\t\tTarget density : " << fTargetMaterialDensity << " kg/m^3"); - QLOG(SAM, "\t\tTarget mass : " << TargetMass_kg << " kg"); - QLOG(SAM, "\t\tNTarget Nucleons : " << NNucleons); + NUIS_LOG(SAM, "\tEvent rate prediction : "); + NUIS_LOG(SAM, "\t\tTarget volume : " << fTargetVolume << " m^3"); + NUIS_LOG(SAM, "\t\tTarget density : " << fTargetMaterialDensity << " kg/m^3"); + NUIS_LOG(SAM, "\t\tTarget mass : " << TargetMass_kg << " kg"); + NUIS_LOG(SAM, "\t\tNTarget Nucleons : " << NNucleons); if ((fNPOT != 1)) { - QLOG(SAM, "\t\tTotal POT : " << fNPOT); + NUIS_LOG(SAM, "\t\tTotal POT : " << fNPOT); } - QLOG(SAM, "\t\tNNeutrinos : " + NUIS_LOG(SAM, "\t\tNNeutrinos : " << NNeutrinos << ((fNPOT != 1) ? " /cm^2" : " /POT /cm^2")); - QLOG(SAM, "\t\tXSec -> EvtRate scale factor : " << fEvtRateScaleFactor); + NUIS_LOG(SAM, "\t\tXSec -> EvtRate scale factor : " << fEvtRateScaleFactor); } } return setting; } //*********************************************** SampleSettings MeasurementBase::LoadSampleSettings(std::string name, std::string input, std::string type) { //*********************************************** nuiskey samplekey = Config::CreateKey("sample"); samplekey.SetS("name", name); samplekey.SetS("input", input); samplekey.SetS("type", type); return LoadSampleSettings(samplekey); } void MeasurementBase::FinaliseSampleSettings() { EnuMin = fSettings.GetD("enu_min"); EnuMax = fSettings.GetD("enu_max"); } //*********************************************** void MeasurementBase::Reconfigure() { //*********************************************** - QLOG(REC, " Reconfiguring sample " << fName); + NUIS_LOG(REC, " Reconfiguring sample " << fName); // Reset Histograms ResetExtraHistograms(); AutoResetExtraTH1(); this->ResetAll(); // FitEvent* cust_event = fInput->GetEventPointer(); int fNEvents = fInput->GetNEvents(); int countwidth = (fNEvents / 5); // MAIN EVENT LOOP FitEvent *cust_event = fInput->FirstNuisanceEvent(); int i = 0; int npassed = 0; while (cust_event) { cust_event->RWWeight = fRW->CalcWeight(cust_event); cust_event->Weight = cust_event->RWWeight * cust_event->InputWeight; Weight = cust_event->Weight; // Initialize fXVar = -999.9; fYVar = -999.9; fZVar = -999.9; Signal = false; Mode = cust_event->Mode; // Extract Measurement Variables this->FillEventVariables(cust_event); Signal = this->isSignal(cust_event); if (Signal) npassed++; GetBox()->SetX(fXVar); GetBox()->SetY(fYVar); GetBox()->SetZ(fZVar); GetBox()->SetMode(Mode); // GetBox()->fSignal = Signal; // Fill Histogram Values GetBox()->FillBoxFromEvent(cust_event); // this->FillExtraHistograms(GetBox(), Weight); this->FillHistogramsFromBox(GetBox(), Weight); // Print Out if (LOG_LEVEL(REC) && countwidth > 0 && !(i % countwidth)) { std::stringstream ss(""); ss.unsetf(std::ios_base::fixed); ss << std::setw(7) << std::right << i << "/" << fNEvents << " events (" << std::setw(2) << int(double(i) / double(fNEvents) * 100.) + 1 << std::left << std::setw(5) << "%) " << "[S,X,Y,Z,M,W] = [" << std::fixed << std::setprecision(2) << std::right << Signal << ", " << std::setw(5) << fXVar << ", " << std::setw(5) << fYVar << ", " << std::setw(5) << fYVar << ", " << std::setw(3) << (int)Mode << ", " << std::setw(5) << Weight << "] " << std::endl; - QLOG(SAM, ss.str()); + NUIS_LOG(SAM, ss.str()); } // iterate cust_event = fInput->NextNuisanceEvent(); i++; } - QLOG(SAM, npassed << "/" << fNEvents << " passed selection "); + NUIS_LOG(SAM, npassed << "/" << fNEvents << " passed selection "); if (npassed == 0) { - QLOG(SAM, "WARNING: NO EVENTS PASSED SELECTION!"); + NUIS_LOG(SAM, "WARNING: NO EVENTS PASSED SELECTION!"); } - QLOG(REC, + NUIS_LOG(REC, std::setw(10) << std::right << NSignal << "/" << fNEvents << " events passed selection + binning after reweight"); // Finalise Histograms fMCFilled = true; this->ConvertEventRates(); } void MeasurementBase::FillHistogramsFromBox(MeasurementVariableBox *var, double weight) { fXVar = var->GetX(); fYVar = var->GetY(); fZVar = var->GetZ(); Weight = weight; fEventVariables = var; FillHistograms(); FillExtraHistograms(var, weight); } void MeasurementBase::FillHistograms(double weight) { Weight = weight * GetBox()->GetSampleWeight(); FillHistograms(); FillExtraHistograms(GetBox(), Weight); } MeasurementVariableBox *MeasurementBase::FillVariableBox(FitEvent *event) { GetBox()->Reset(); Mode = event->Mode; Weight = 1.0; // event->Weight; this->FillEventVariables(event); Signal = this->isSignal(event); GetBox()->FillBoxFromEvent(event); GetBox()->SetX(fXVar); GetBox()->SetY(fYVar); GetBox()->SetZ(fZVar); GetBox()->SetMode(event->Mode); GetBox()->SetSampleWeight(Weight); // GetBox()->fSignal = Signal; return GetBox(); } MeasurementVariableBox *MeasurementBase::GetBox() { if (!fEventVariables) fEventVariables = CreateBox(); return fEventVariables; } //*********************************************** void MeasurementBase::ReconfigureFast() { //*********************************************** this->Reconfigure(); } //*********************************************** void MeasurementBase::ConvertEventRates() { //*********************************************** AutoScaleExtraTH1(); ScaleExtraHistograms(GetBox()); this->ScaleEvents(); double normval = fRW->GetSampleNorm(this->fName); if (normval < 0.01 or normval > 10.0) { - QERROR(WRN, + NUIS_ERR(WRN, "Norm Value inside MeasurementBase::ConvertEventRates() looks off!"); - QERROR(WRN, + NUIS_ERR(WRN, "It could have become out of sync with the minimizer norm list."); - QERROR(WRN, "Setting it to 1.0"); + NUIS_ERR(WRN, "Setting it to 1.0"); normval = 1.0; } AutoNormExtraTH1(normval); NormExtraHistograms(GetBox(), normval); this->ApplyNormScale(normval); } //*********************************************** InputHandlerBase *MeasurementBase::GetInput() { //*********************************************** if (!fInput) { - QTHROW("MeasurementBase::fInput not set. Please submit your command " + NUIS_ABORT("MeasurementBase::fInput not set. Please submit your command " "line options and input cardfile with a bug report to: " "nuisance@projects.hepforge.org"); } return fInput; }; //*********************************************** void MeasurementBase::Renormalise() { //*********************************************** // Called when the fitter has changed a measurements normalisation but not any // reweight dials // Means we don't have to call the time consuming reconfigure when this // happens. double norm = fRW->GetDialValue(this->fName + "_norm"); if ((this->fCurrentNorm == 0.0 and norm != 0.0) or not fMCFilled) { this->ReconfigureFast(); return; } if (this->fCurrentNorm == norm) return; this->ApplyNormScale(1.0 / this->fCurrentNorm); this->ApplyNormScale(norm); return; }; //*********************************************** void MeasurementBase::SetSignal(bool sig) { //*********************************************** Signal = sig; } //*********************************************** void MeasurementBase::SetSignal(FitEvent *evt) { //*********************************************** Signal = this->isSignal(evt); } //*********************************************** void MeasurementBase::SetWeight(double wght) { //*********************************************** Weight = wght; } //*********************************************** void MeasurementBase::SetMode(int md) { //*********************************************** Mode = md; } //*********************************************** std::vector MeasurementBase::GetFluxList() { //*********************************************** return GetInput()->GetFluxList(); } //*********************************************** std::vector MeasurementBase::GetEventRateList() { //*********************************************** return GetInput()->GetEventList(); } //*********************************************** std::vector MeasurementBase::GetXSecList() { //*********************************************** return GetInput()->GetXSecList(); } void MeasurementBase::ProcessExtraHistograms(int cmd, MeasurementVariableBox *vars, double weight) { // This should be overriden if we have extra histograms!!! // Add a flag to tell user this... return; } void MeasurementBase::FillExtraHistograms(MeasurementVariableBox *vars, double weight) { ProcessExtraHistograms(kCMD_Fill, vars, weight); } void MeasurementBase::ScaleExtraHistograms(MeasurementVariableBox *vars) { ProcessExtraHistograms(kCMD_Scale, vars, 1.0); } void MeasurementBase::ResetExtraHistograms() { ProcessExtraHistograms(kCMD_Reset, NULL, 1.0); } void MeasurementBase::NormExtraHistograms(MeasurementVariableBox *vars, double norm) { ProcessExtraHistograms(kCMD_Norm, vars, norm); } void MeasurementBase::WriteExtraHistograms() { ProcessExtraHistograms(kCMD_Write, NULL, 1.00); } void MeasurementBase::SetAutoProcessTH1(TH1 *hist, int c1, int c2, int c3, int c4, int c5) { FakeStack *fake = new FakeStack(hist); SetAutoProcessTH1(fake, c1, c2, c3, c4, c5); // Need to add a destroy command! } void MeasurementBase::SetAutoProcess(TH1 *hist, int c1, int c2, int c3, int c4, int c5) { FakeStack *fake = new FakeStack(hist); SetAutoProcessTH1(fake, c1, c2, c3, c4, c5); // Need to add a destroy command! } void MeasurementBase::SetAutoProcess(TGraph *g, int c1, int c2, int c3, int c4, int c5) { FakeStack *fake = new FakeStack(g); SetAutoProcessTH1(fake, c1, c2, c3, c4, c5); // Need to add a destroy command! } void MeasurementBase::SetAutoProcess(TF1 *f, int c1, int c2, int c3, int c4, int c5) { FakeStack *fake = new FakeStack(f); SetAutoProcessTH1(fake, c1, c2, c3, c4, c5); // Need to add a destroy command! } void MeasurementBase::SetAutoProcess(StackBase *hist, int c1, int c2, int c3, int c4, int c5) { SetAutoProcessTH1(hist, c1, c2, c3, c4, c5); } void MeasurementBase::SetAutoProcessTH1(StackBase *hist, int c1, int c2, int c3, int c4, int c5) { // Set Defaults // int ncommands = kCMD_extraplotflags; int givenflags[5]; givenflags[0] = c1; givenflags[1] = c2; givenflags[2] = c3; givenflags[3] = c4; givenflags[4] = c5; fExtraTH1s[hist] = std::vector(5, 0); // Setup a default one. if (c1 == -1 && c2 == -1 && c3 == -1 && c4 == -1 && c5 == -1) { fExtraTH1s[hist][kCMD_Reset] = 1; fExtraTH1s[hist][kCMD_Scale] = 1; fExtraTH1s[hist][kCMD_Norm] = 1; fExtraTH1s[hist][kCMD_Write] = 1; } for (int i = 0; i < 5; i++) { switch (givenflags[i]) { // Skip over... case -1: break; case kCMD_Reset: case kCMD_Scale: case kCMD_Norm: case kCMD_Write: fExtraTH1s[hist][givenflags[i]] = 1; break; case kCMD_Fill: { - QERROR(FTL, "Can't auto fill yet!"); + NUIS_ERR(FTL, "Can't auto fill yet!"); break; } default: break; } } } void MeasurementBase::AutoFillExtraTH1() { - QTHROW("Can't auto fill yet! it's too inefficent!"); + NUIS_ABORT("Can't auto fill yet! it's too inefficent!"); return; } void MeasurementBase::AutoResetExtraTH1() { for (std::map>::iterator iter = fExtraTH1s.begin(); iter != fExtraTH1s.end(); iter++) { if (!((*iter).second)[kCMD_Reset]) continue; (*iter).first->Reset(); } }; void MeasurementBase::AutoScaleExtraTH1() { for (std::map>::iterator iter = fExtraTH1s.begin(); iter != fExtraTH1s.end(); iter++) { if (!((*iter).second)[kCMD_Scale]) continue; if (fIsNoWidth) { (*iter).first->Scale(fScaleFactor); } else { (*iter).first->Scale(fScaleFactor, "width"); } } }; void MeasurementBase::AutoNormExtraTH1(double norm) { double sfactor = 0.0; if (norm != 0.0) sfactor = 1.0 / norm; for (std::map>::iterator iter = fExtraTH1s.begin(); iter != fExtraTH1s.end(); iter++) { if (!((*iter).second)[kCMD_Norm]) continue; (*iter).first->Scale(sfactor); } }; void MeasurementBase::AutoWriteExtraTH1() { for (std::map>::iterator iter = fExtraTH1s.begin(); iter != fExtraTH1s.end(); iter++) { if (!(((*iter).second)[kCMD_Write])) continue; (*iter).first->Write(); } }; diff --git a/src/FitBase/ParamPull.cxx b/src/FitBase/ParamPull.cxx index 75c75bb..0464a7a 100644 --- a/src/FitBase/ParamPull.cxx +++ b/src/FitBase/ParamPull.cxx @@ -1,867 +1,867 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "ParamPull.h" //******************************************************************************* ParamPull::ParamPull(std::string name, std::string inputfile, std::string type, std::string dials) { //******************************************************************************* fMinHist = NULL; fMaxHist = NULL; fTypeHist = NULL; fDialSelection = dials; fLimitHist = NULL; fName = name; fInput = inputfile; fType = type; // Set the pull type SetType(fType); // Setup Histograms from input file SetupHistograms(fInput); }; //******************************************************************************* void ParamPull::SetType(std::string type) { //******************************************************************************* fType = type; // Assume Default if empty if (type.empty() || type == "DEFAULT") { - QERROR(WRN, "No type specified for ParmPull class " << fName); - QERROR(WRN, "Assuming GAUSTHROW/GAUSPULL"); + NUIS_ERR(WRN, "No type specified for ParmPull class " << fName); + NUIS_ERR(WRN, "Assuming GAUSTHROW/GAUSPULL"); type = "GAUSTHROW/GAUSPULL"; } // Set Dial options if (type.find("FRAC") != std::string::npos) { fDialOptions = "FRAC"; fPlotTitles = ";; Fractional RW Value"; } else if (type.find("ABS") != std::string::npos) { fDialOptions = "ABS"; fPlotTitles = ";; ABS RW Value"; } else { fDialOptions = ""; fPlotTitles = ";; RW Value"; } // Parse throw types if (type.find("GAUSPULL") != std::string::npos) fCalcType = kGausPull; else fCalcType = kNoPull; if (type.find("GAUSTHROW") != std::string::npos) fThrowType = kGausThrow; else if (type.find("FLATTHROW") != std::string::npos) fThrowType = kFlatThrow; else fThrowType = kNoThrow; // Extra check to see if throws or pulls are turned off if (type.find("NOPULL") != std::string::npos) fCalcType = kNoPull; if (type.find("NOTHROW") != std::string::npos) fThrowType = kNoThrow; } //******************************************************************************* void ParamPull::SetupHistograms(std::string input) { //******************************************************************************* // Extract Types from Input fFileType = ""; const int nfiletypes = 4; const std::string filetypes[nfiletypes] = {"FIT", "ROOT", "TXT", "DIAL"}; for (int i = 0; i < nfiletypes; i++) { std::string tempTypes = filetypes[i] + ":"; if (input.find(tempTypes) != std::string::npos) { fFileType = filetypes[i]; input.replace(input.find(tempTypes), tempTypes.size(), ""); break; } } // Read Files if (!fFileType.compare("FIT")) ReadFitFile(input); else if (!fFileType.compare("ROOT")) ReadRootFile(input); else if (!fFileType.compare("VECT")) ReadVectFile(input); else if (!fFileType.compare("DIAL")) ReadDialInput(input); else { - QERROR(FTL, "Unknown ParamPull Type: " << input); - QTHROW("Need FIT, ROOT, VECT or DIAL"); + NUIS_ERR(FTL, "Unknown ParamPull Type: " << input); + NUIS_ABORT("Need FIT, ROOT, VECT or DIAL"); } // Check Dials are all good if (!CheckDialsValid()) { - QTHROW("DIALS NOT VALID"); + NUIS_ABORT("DIALS NOT VALID"); } // Setup MC Histogram fMCHist = (TH1D *)fDataHist->Clone(); fMCHist->Reset(); fMCHist->SetNameTitle((fName + "_MC").c_str(), (fName + " MC" + fPlotTitles).c_str()); // If no Covar input make an uncorrelated one if (!fCovar) { fCovar = StatUtils::MakeDiagonalCovarMatrix(fDataHist, 1.0); } // If no types or limits are provided give them a default option if (!fMinHist) { - QLOG(FIT, "No minimum histogram found for pull parameters, setting to be " + NUIS_LOG(FIT, "No minimum histogram found for pull parameters, setting to be " "content - 1E6..."); fMinHist = (TH1D *)fDataHist->Clone(); fMinHist->SetNameTitle((fName + "_min").c_str(), (fName + " min" + fPlotTitles).c_str()); for (int i = 0; i < fMinHist->GetNbinsX(); i++) { // TODO (P.Stowell) Change this to a NULL system where limits are actually // free! fMinHist->SetBinContent(i + 1, fDataHist->GetBinContent(i + 1) - 1E6); } } if (!fMaxHist) { - QLOG(FIT, "No maximum histogram found for pull parameters, setting to be " + NUIS_LOG(FIT, "No maximum histogram found for pull parameters, setting to be " "content - 1E6..."); fMaxHist = (TH1D *)fDataHist->Clone(); fMaxHist->SetNameTitle((fName + "_min").c_str(), (fName + " min" + fPlotTitles).c_str()); for (int i = 0; i < fMaxHist->GetNbinsX(); i++) { fMaxHist->SetBinContent(i + 1, fDataHist->GetBinContent(i + 1) - 1E6); } } // Set types from state, or to unknown // Not really sure when or if this is ever used if (!fTypeHist) { int deftype = -1; if (fType.find("T2K") != std::string::npos) { deftype = kT2K; } else if (fType.find("NEUT") != std::string::npos) { deftype = kNEUT; } else if (fType.find("NIWG") != std::string::npos) { deftype = kNIWG; } else if (fType.find("GENIE") != std::string::npos) { deftype = kGENIE; } else if (fType.find("NORM") != std::string::npos) { deftype = kNORM; } else if (fType.find("NUWRO") != std::string::npos) { deftype = kNUWRO; } fTypeHist = new TH1I((fName + "_type").c_str(), (fName + " type" + fPlotTitles).c_str(), fDataHist->GetNbinsX(), 0, fDataHist->GetNbinsX()); for (int i = 0; i < fTypeHist->GetNbinsX(); i++) { fTypeHist->SetBinContent(i + 1, deftype); } } // Sort Covariances fInvCovar = StatUtils::GetInvert(fCovar); fDecomp = StatUtils::GetDecomp(fCovar); // Create DataTrue for Throws fDataTrue = (TH1D *)fDataHist->Clone(); fDataTrue->SetNameTitle((fName + "_truedata").c_str(), (fName + " truedata" + fPlotTitles).c_str()); fDataOrig = (TH1D *)fDataHist->Clone(); fDataOrig->SetNameTitle((fName + "_origdata").c_str(), (fName + " origdata" + fPlotTitles).c_str()); // Select only dials we want if (!fDialSelection.empty()) { (*fDataHist) = RemoveBinsNotInString(*fDataHist, fDialSelection); } } //******************************************************************************* TH1D ParamPull::RemoveBinsNotInString(TH1D hist, std::string mystr) { //******************************************************************************* // Make list of allowed bins std::vector allowedbins; for (int i = 0; i < hist.GetNbinsX(); i++) { std::string syst = std::string(hist.GetXaxis()->GetBinLabel(i + 1)); if (mystr.find(syst) != std::string::npos) { allowedbins.push_back(syst); } } // Make new histogram UInt_t nbins = allowedbins.size(); TH1D newhist = TH1D(hist.GetName(), hist.GetTitle(), (Int_t)nbins, 0.0, (Double_t)nbins); // Setup bins for (UInt_t i = 0; i < nbins; i++) { // Set Labels newhist.GetXaxis()->SetBinLabel(i + 1, allowedbins[i].c_str()); // Copy Values for (Int_t j = 0; j < hist.GetNbinsX(); j++) { if (!allowedbins[i].compare(hist.GetXaxis()->GetBinLabel(j + 1))) { newhist.SetBinContent(i + 1, hist.GetBinContent(j + 1)); newhist.SetBinError(i + 1, hist.GetBinError(j + 1)); } } } return newhist; } //******************************************************************************* TH1I ParamPull::RemoveBinsNotInString(TH1I hist, std::string mystr) { //******************************************************************************* // Make list of allowed bins std::vector allowedbins; for (int i = 0; i < hist.GetNbinsX(); i++) { std::string syst = std::string(hist.GetXaxis()->GetBinLabel(i + 1)); if (mystr.find(syst) != std::string::npos) { allowedbins.push_back(syst); } } // Make new histogram UInt_t nbins = allowedbins.size(); TH1I newhist = TH1I(hist.GetName(), hist.GetTitle(), (Int_t)nbins, 0.0, (Int_t)nbins); // Setup bins for (UInt_t i = 0; i < nbins; i++) { // Set Labels newhist.GetXaxis()->SetBinLabel(i + 1, allowedbins[i].c_str()); // Copy Values for (Int_t j = 0; j < hist.GetNbinsX(); j++) { if (!allowedbins[i].compare(hist.GetXaxis()->GetBinLabel(j + 1))) { newhist.SetBinContent(i + 1, hist.GetBinContent(j + 1)); newhist.SetBinError(i + 1, hist.GetBinError(j + 1)); } } } return newhist; } //******************************************************************************* void ParamPull::ReadFitFile(std::string input) { //******************************************************************************* TFile *tempfile = new TFile(input.c_str(), "READ"); // Read Data fDataHist = (TH1D *)tempfile->Get("fit_dials_free"); CheckHist(fDataHist); fDataHist->SetDirectory(0); fDataHist->SetNameTitle((fName + "_data").c_str(), (fName + " data" + fPlotTitles).c_str()); fMinHist = (TH1D *)tempfile->Get("min_dials_free"); CheckHist(fMinHist); fMinHist->SetDirectory(0); fMinHist->SetNameTitle((fName + "_min").c_str(), (fName + " min" + fPlotTitles).c_str()); fMaxHist = (TH1D *)tempfile->Get("max_dials_free"); CheckHist(fMaxHist); fMaxHist->SetDirectory(0); fMaxHist->SetNameTitle((fName + "_max").c_str(), (fName + " max" + fPlotTitles).c_str()); // Read Covar TH2D *tempcov = (TH2D *)tempfile->Get("covariance_free"); if (!tempcov) { - QERROR(FTL, "Can't find TH2D covariance_free in " << fName); - QERROR(FTL, "File Entries:"); + NUIS_ERR(FTL, "Can't find TH2D covariance_free in " << fName); + NUIS_ERR(FTL, "File Entries:"); tempfile->ls(); throw; } // Setup Covar int nbins = fDataHist->GetNbinsX(); fCovar = new TMatrixDSym(nbins); for (int i = 0; i < nbins; i++) { for (int j = 0; j < nbins; j++) { (*fCovar)(i, j) = tempcov->GetBinContent(i + 1, j + 1); } } return; } //******************************************************************************* void ParamPull::ReadRootFile(std::string input) { //******************************************************************************* std::vector inputlist = GeneralUtils::ParseToStr(input, ";"); // Check all given if (inputlist.size() < 2) { - QERROR(FTL, "Covar supplied in 'ROOT' format should have 3 semi-colon " + NUIS_ERR(FTL, "Covar supplied in 'ROOT' format should have 3 semi-colon " "seperated entries!" << std::endl << "ROOT:filename;histname[;covarname]"); - QTHROW("histname = TH1D, covarname = TH2D"); + NUIS_ABORT("histname = TH1D, covarname = TH2D"); } // Get Entries std::string filename = inputlist[0]; std::string histname = inputlist[1]; // Read File TFile *tempfile = new TFile(filename.c_str(), "READ"); if (tempfile->IsZombie()) { - QLOG(FIT, "Looking for ParamPull input inside database"); + NUIS_LOG(FIT, "Looking for ParamPull input inside database"); filename = FitPar::GetDataBase() + "/" + filename; tempfile = new TFile(filename.c_str(), "READ"); } if (tempfile->IsZombie()) { - QERROR(FTL, "Can't find file in " << fName); - QTHROW("location = " << filename); + NUIS_ERR(FTL, "Can't find file in " << fName); + NUIS_ABORT("location = " << filename); } // Read Hist fDataHist = (TH1D *)tempfile->Get(histname.c_str()); if (!fDataHist) { - QERROR(FTL, "Can't find TH1D hist " << histname << " in " << fName); - QERROR(FTL, "File Entries:"); + NUIS_ERR(FTL, "Can't find TH1D hist " << histname << " in " << fName); + NUIS_ERR(FTL, "File Entries:"); tempfile->ls(); throw; } fDataHist->SetDirectory(0); fDataHist->SetNameTitle((fName + "_data").c_str(), (fName + " data" + fPlotTitles).c_str()); - QLOG(DEB, "READING COVAR"); + NUIS_LOG(DEB, "READING COVAR"); // Read Covar if (inputlist.size() > 2) { std::string covarname = inputlist[2]; - QLOG(DEB, "COVARNAME = " << covarname); + NUIS_LOG(DEB, "COVARNAME = " << covarname); TH2D *tempcov = (TH2D *)tempfile->Get(covarname.c_str()); if (!tempcov) { - QERROR(FTL, "Can't find TH2D covar " << covarname << " in " << fName); - QERROR(FTL, "File Entries:"); + NUIS_ERR(FTL, "Can't find TH2D covar " << covarname << " in " << fName); + NUIS_ERR(FTL, "File Entries:"); tempfile->ls(); throw; } // Setup Covar int nbins = fDataHist->GetNbinsX(); fCovar = new TMatrixDSym(nbins); for (int i = 0; i < nbins; i++) { for (int j = 0; j < nbins; j++) { (*fCovar)(i, j) = tempcov->GetBinContent(i + 1, j + 1); } } // Uncorrelated } else { - QLOG(SAM, "No Covar provided so using diagonal errors for " << fName); + NUIS_LOG(SAM, "No Covar provided so using diagonal errors for " << fName); fCovar = NULL; } } //******************************************************************************* void ParamPull::ReadVectFile(std::string input) { //******************************************************************************* std::vector inputlist = GeneralUtils::ParseToStr(input, ";"); if (inputlist.size() < 4) { - QERROR(FTL, "Need 3 inputs for vector input in " << fName); - QTHROW("Inputs: " << input); + NUIS_ERR(FTL, "Need 3 inputs for vector input in " << fName); + NUIS_ABORT("Inputs: " << input); } // Open File std::string rootname = inputlist[0]; TFile *tempfile = new TFile(rootname.c_str(), "READ"); if (tempfile->IsZombie()) { - QERROR(FTL, "Can't find file in " << fName); - QTHROW("location = " << rootname); + NUIS_ERR(FTL, "Can't find file in " << fName); + NUIS_ABORT("location = " << rootname); } // Get Name std::string tagname = inputlist[1]; // TVector dialtags = tempfile->Get(tagname.c_str()); // if (!dialtags){ // ERR(FTL) << "Can't find list of dial names!" << std::endl; // } // Get Values std::string valuename = inputlist[2]; TVectorD *dialvals = (TVectorD *)tempfile->Get(valuename.c_str()); if (!dialvals) { - QERROR(FTL, "Can't find dial values"); + NUIS_ERR(FTL, "Can't find dial values"); } // Get Matrix std::string matrixname = inputlist[3]; TMatrixD *matrixvals = (TMatrixD *)tempfile->Get(matrixname.c_str()); if (!matrixvals) { - QERROR(FTL, "Can't find matirx values"); + NUIS_ERR(FTL, "Can't find matirx values"); } // Get Types if (inputlist.size() > 4) { std::string typesname = inputlist[3]; } // Get Minimum if (inputlist.size() > 5) { std::string minname = inputlist[4]; } // Get Maximum if (inputlist.size() > 6) { std::string maxname = inputlist[5]; } } //******************************************************************************* void ParamPull::ReadDialInput(std::string input) { //******************************************************************************* std::vector inputlist = GeneralUtils::ParseToStr(input, ";"); if (inputlist.size() < 3) { - QERROR(FTL, "Need 3 inputs for dial input in " << fName); - QTHROW("Inputs: " << input); + NUIS_ERR(FTL, "Need 3 inputs for dial input in " << fName); + NUIS_ABORT("Inputs: " << input); } std::vector inputvals = GeneralUtils::ParseToDbl(input, ";"); std::string dialname = inputlist[0]; double val = inputvals[1]; double err = inputvals[2]; fDataHist = new TH1D((fName + "_data").c_str(), (fName + "_data" + fPlotTitles).c_str(), 1, 0, 1); fDataHist->SetBinContent(1, val); fDataHist->SetBinError(1, err); fDataHist->GetXaxis()->SetBinLabel(1, dialname.c_str()); fLimitHist = new TH1D((fName + "_limits").c_str(), (fName + "_limits" + fPlotTitles).c_str(), 1, 0, 1); fLimitHist->Reset(); if (inputvals.size() > 4) { fLimitHist->SetBinContent(1, (inputvals[3] + inputvals[4]) / 2.0); fLimitHist->SetBinError(1, (inputvals[4] - inputvals[3]) / 2.0); } fCovar = NULL; } //******************************************************************************* std::map ParamPull::GetAllDials() { //******************************************************************************* std::map dialtypemap; for (int i = 0; i < fDataHist->GetNbinsX(); i++) { std::string name = fDataHist->GetXaxis()->GetBinLabel(i + 1); int type = fTypeHist->GetBinContent(i + 1); dialtypemap[name] = type; } return dialtypemap; } //******************************************************************************* bool ParamPull::CheckDialsValid() { //******************************************************************************* std::string helpstring = ""; for (int i = 0; i < fDataHist->GetNbinsX(); i++) { std::string name = std::string(fDataHist->GetXaxis()->GetBinLabel(i + 1)); // If dial exists its all good if (FitBase::GetRW()->DialIncluded(name)) { - QLOG(DEB, "Found dial " << name << " in covariance " << fInput + NUIS_LOG(DEB, "Found dial " << name << " in covariance " << fInput << " and matched to reweight engine "); continue; } // If it doesn't but its a sample norm also continue if (name.find("_norm") != std::string::npos) { - QERROR(WRN, "Norm dial included in covar but not set in FitWeight."); - QERROR(WRN, "Assuming its a sample norm and skipping..."); + NUIS_ERR(WRN, "Norm dial included in covar but not set in FitWeight."); + NUIS_ERR(WRN, "Assuming its a sample norm and skipping..."); } // Dial unknown so print a help statement std::ostringstream tempstr; tempstr << "unknown_parameter " << name << " " << fDataHist->GetBinContent(i + 1) << " " << fDataHist->GetBinContent(i + 1) - fDataHist->GetBinError(i + 1) << " " << fDataHist->GetBinContent(i + 1) + fDataHist->GetBinError(i + 1) << " " << fDataHist->GetBinError(i + 1) << " "; if (!fType.empty()) tempstr << fType << std::endl; else tempstr << "FREE" << std::endl; helpstring += tempstr.str(); } // Show statement before failing if (!helpstring.empty()) { - QERROR(FTL, "Dial(s) included in covar but not set in FitWeight."); - QERROR(FTL, "ParamPulls needs to know how you want it to be treated."); - QTHROW("Include the following lines into your card to throw UNCORRELATED:" + NUIS_ERR(FTL, "Dial(s) included in covar but not set in FitWeight."); + NUIS_ERR(FTL, "ParamPulls needs to know how you want it to be treated."); + NUIS_ABORT("Include the following lines into your card to throw UNCORRELATED:" << std::endl << helpstring); } else { return true; } return false; } //******************************************************************************* void ParamPull::Reconfigure() { //******************************************************************************* FitWeight *rw = FitBase::GetRW(); // Get Dial Names that are valid std::vector namevec = rw->GetDialNames(); std::vector valuevec = rw->GetDialValues(); // Set Bin Values from RW for (UInt_t i = 0; i < namevec.size(); i++) { // Loop over bins and check name matches std::string syst = namevec.at(i); double systval = valuevec.at(i); std::vector allsyst = GeneralUtils::ParseToStr(syst, ","); // Proper Reconf using RW for (int j = 0; j < fMCHist->GetNbinsX(); j++) { // Search for the name of this bin in the corrent dial std::string binname = std::string(fMCHist->GetXaxis()->GetBinLabel(j + 1)); // Check Full Name if (!syst.compare(binname.c_str())) { fMCHist->SetBinContent(j + 1, systval); break; } std::vector splitbinname = GeneralUtils::ParseToStr(binname, ","); for (size_t l = 0; l < splitbinname.size(); l++) { std::string singlebinname = splitbinname[l]; for (size_t k = 0; k < allsyst.size(); k++) { if (!allsyst[k].compare(singlebinname.c_str())) { fMCHist->SetBinContent(j + 1, systval); } } } } } return; }; //******************************************************************************* void ParamPull::ResetToy(void) { //******************************************************************************* if (fDataHist) delete fDataHist; - QLOG(DEB, "Resetting toy"); - QLOG(DEB, fDataTrue); + NUIS_LOG(DEB, "Resetting toy"); + NUIS_LOG(DEB, fDataTrue); fDataHist = (TH1D *)fDataTrue->Clone(); - QLOG(DEB, "Setting name"); + NUIS_LOG(DEB, "Setting name"); fDataHist->SetNameTitle((fName + "_data").c_str(), (fName + " data" + fPlotTitles).c_str()); } //******************************************************************************* void ParamPull::SetFakeData(std::string fakeinput) { //******************************************************************************* // Set from MC Setting if (!fakeinput.compare("MC")) { // Copy MC into data if (fDataHist) delete fDataHist; fDataHist = (TH1D *)fMCHist->Clone(); fDataHist->SetNameTitle((fName + "_data").c_str(), (fName + " fakedata" + fPlotTitles).c_str()); // Copy original data errors for (int i = 0; i < fDataOrig->GetNbinsX(); i++) { fDataHist->SetBinError(i + 1, fDataOrig->GetBinError(i + 1)); } // Make True Toy Central Value Hist fDataTrue = (TH1D *)fDataHist->Clone(); fDataTrue->SetNameTitle((fName + "_truedata").c_str(), (fName + " truedata" + fPlotTitles).c_str()); } else { - QERROR(FTL, "Trying to set fake data for ParamPulls not from MC!"); - QTHROW("Not currently implemented.."); + NUIS_ERR(FTL, "Trying to set fake data for ParamPulls not from MC!"); + NUIS_ABORT("Not currently implemented.."); } } //******************************************************************************* void ParamPull::RemoveFakeData() { //******************************************************************************* delete fDataHist; fDataHist = (TH1D *)fDataOrig->Clone(); fDataHist->SetNameTitle((fName + "_data").c_str(), (fName + " data" + fPlotTitles).c_str()); fDataTrue = (TH1D *)fDataHist->Clone(); fDataTrue->SetNameTitle((fName + "_truedata").c_str(), (fName + " truedata" + fPlotTitles).c_str()); } //******************************************************************************* double ParamPull::GetLikelihood() { //******************************************************************************* double like = 0.0; switch (fCalcType) { // Gaussian Calculation with correlations case kGausPull: like = StatUtils::GetChi2FromCov(fDataHist, fMCHist, fInvCovar, NULL); like *= 1E-76; break; // Default says this has no pull case kNoThrow: default: like = 0.0; break; } - QLOG(DEB, "Likelihood = " << like << " " << fCalcType); + NUIS_LOG(DEB, "Likelihood = " << like << " " << fCalcType); return like; }; //******************************************************************************* int ParamPull::GetNDOF() { //******************************************************************************* int ndof = 0; if (fCalcType != kNoThrow) { ndof = fDataHist->GetNbinsX(); } return ndof; }; //******************************************************************************* void ParamPull::ThrowCovariance() { //******************************************************************************* // Reset toy for throw ResetToy(); - QLOG(FIT, "Creating new toy dataset"); + NUIS_LOG(FIT, "Creating new toy dataset"); // Generate random Gaussian throws std::vector randthrows; for (int i = 0; i < fDataHist->GetNbinsX(); i++) { double randtemp = 0.0; switch (fThrowType) { // Gaussian Throws case kGausThrow: randtemp = gRandom->Gaus(0.0, 1.0); break; // Uniform Throws case kFlatThrow: randtemp = gRandom->Uniform(0.0, 1.0); if (fLimitHist) { randtemp = fLimitHist->GetBinContent(i + 1) + fLimitHist->GetBinError(i + 1) * (randtemp * 2 - 1); } break; // No Throws (DEFAULT) default: break; } randthrows.push_back(randtemp); } // Create Bin Modifications double totalres = 0.0; for (int i = 0; i < fDataHist->GetNbinsX(); i++) { // Calc Bin Mod double binmod = 0.0; if (fThrowType == kGausThrow) { for (int j = 0; j < fDataHist->GetNbinsX(); j++) { binmod += (*fDecomp)(j, i) * randthrows.at(j); } } else if (fThrowType == kFlatThrow) { binmod = randthrows.at(i) - fDataHist->GetBinContent(i + 1); } // Add up fraction dif totalres += binmod; // Add to current data fDataHist->SetBinContent(i + 1, fDataHist->GetBinContent(i + 1) + binmod); } // Rename fDataHist->SetNameTitle((fName + "_data").c_str(), (fName + " toydata" + fPlotTitles).c_str()); // Check Limits if (fLimitHist) { for (int i = 0; i < fLimitHist->GetNbinsX(); i++) { if (fLimitHist->GetBinError(i + 1) == 0.0) continue; if (fDataHist->GetBinContent(i + 1) > fLimitHist->GetBinContent(i + 1) + fLimitHist->GetBinError(i + 1) || fDataHist->GetBinContent(i + 1) < fLimitHist->GetBinContent(i + 1) - fLimitHist->GetBinError(i + 1)) { - QLOG(FIT, "Threw outside allowed region, rethrowing..."); + NUIS_LOG(FIT, "Threw outside allowed region, rethrowing..."); ThrowCovariance(); } } } }; //******************************************************************************* TH2D ParamPull::GetCovar() { //******************************************************************************* TH2D tempCov = TH2D(*fInvCovar); for (int i = 0; i < tempCov.GetNbinsX(); i++) { tempCov.GetXaxis()->SetBinLabel(i + 1, fDataHist->GetXaxis()->GetBinLabel(i + 1)); tempCov.GetYaxis()->SetBinLabel(i + 1, fDataHist->GetXaxis()->GetBinLabel(i + 1)); } tempCov.SetNameTitle((fName + "_INVCOV").c_str(), (fName + " InvertedCovariance;Dials;Dials").c_str()); return tempCov; } //******************************************************************************* TH2D ParamPull::GetFullCovar() { //******************************************************************************* TH2D tempCov = TH2D(*fCovar); for (int i = 0; i < tempCov.GetNbinsX(); i++) { tempCov.GetXaxis()->SetBinLabel(i + 1, fDataHist->GetXaxis()->GetBinLabel(i + 1)); tempCov.GetYaxis()->SetBinLabel(i + 1, fDataHist->GetXaxis()->GetBinLabel(i + 1)); } tempCov.SetNameTitle((fName + "_COV").c_str(), (fName + " Covariance;Dials;Dials").c_str()); return tempCov; } //******************************************************************************* TH2D ParamPull::GetDecompCovar() { //******************************************************************************* TH2D tempCov = TH2D(*fDecomp); for (int i = 0; i < tempCov.GetNbinsX(); i++) { tempCov.GetXaxis()->SetBinLabel(i + 1, fDataHist->GetXaxis()->GetBinLabel(i + 1)); tempCov.GetYaxis()->SetBinLabel(i + 1, fDataHist->GetXaxis()->GetBinLabel(i + 1)); } tempCov.SetNameTitle((fName + "_DEC").c_str(), (fName + " Decomposition;Dials;Dials").c_str()); return tempCov; } //******************************************************************************* void ParamPull::Write(std::string writeoptt) { //******************************************************************************* fDataHist->Write(); fMCHist->Write(); if (fLimitHist) { fLimitHist->Write(); } GetCovar().Write(); GetFullCovar().Write(); GetDecompCovar().Write(); return; }; void ParamPull::CheckHist(TH1D *hist) { if (!hist) { - QERROR(FTL, "Can't find TH1D hist fit_dials in " << fName); - QERROR(FTL, "File Entries:"); + NUIS_ERR(FTL, "Can't find TH1D hist fit_dials in " << fName); + NUIS_ERR(FTL, "File Entries:"); TFile *temp = new TFile(fInput.c_str(), "open"); temp->ls(); throw; } } diff --git a/src/FitBase/StackBase.cxx b/src/FitBase/StackBase.cxx index 4c83bbe..1a721a1 100644 --- a/src/FitBase/StackBase.cxx +++ b/src/FitBase/StackBase.cxx @@ -1,216 +1,216 @@ #include "StackBase.h" void StackBase::AddMode(std::string name, std::string title, int linecolor, int linewidth, int fillstyle) { // int ncur = fAllLabels.size(); fAllLabels.push_back(name); fAllTitles.push_back(title); std::vector temp; temp.push_back(linecolor); temp.push_back(linewidth); temp.push_back(fillstyle); fAllStyles.push_back(temp); } void StackBase::FluxUnfold(TH1D *flux, TH1D *events, double scalefactor, int nevents) { for (size_t i = 0; i < fAllLabels.size(); i++) { if (fNDim == 1) { PlotUtils::FluxUnfoldedScaling((TH1D *)fAllHists[i], flux, events, scalefactor, nevents); } else if (fNDim == 2) { PlotUtils::FluxUnfoldedScaling((TH2D *)fAllHists[i], flux, events, scalefactor); } } } void StackBase::AddMode(int index, std::string name, std::string title, int linecolor, int linewidth, int fillstyle) { while (fAllLabels.size() <= (UInt_t)index) { fAllLabels.push_back(""); fAllTitles.push_back(""); fAllStyles.push_back(std::vector(1, 1)); } fAllLabels[index] = (name); fAllTitles[index] = (title); std::vector temp; temp.push_back(linecolor); temp.push_back(linewidth); temp.push_back(fillstyle); fAllStyles[index] = temp; } bool StackBase::IncludeInStack(TH1 *hist) { if (!FitPar::Config().GetParB("includeemptystackhists") and hist->Integral() == 0.0) return false; return true; } bool StackBase::IncludeInStack(int index) { return true; } void StackBase::SetupStack(TH1 *hist) { fTemplate = (TH1 *)hist->Clone(fName.c_str()); fTemplate->Reset(); // Determine template dim fNDim = fTemplate->GetDimension(); for (size_t i = 0; i < fAllLabels.size(); i++) { fAllHists.push_back( (TH1 *)fTemplate->Clone((fName + "_" + fAllLabels[i]).c_str())); } }; void StackBase::Scale(double sf, std::string opt) { for (size_t i = 0; i < fAllLabels.size(); i++) { // std::cout << "Scaling Stack Hist " << i << " by " << sf << std::endl; fAllHists[i]->Scale(sf, opt.c_str()); } }; void StackBase::Reset() { for (size_t i = 0; i < fAllLabels.size(); i++) { fAllHists[i]->Reset(); } }; void StackBase::FillStack(int index, double x, double y, double z, double weight) { if (index < 0 or (UInt_t) index >= fAllLabels.size()) { - QERROR(WRN, "Returning Stack Fill Because Range = " << index << " " + NUIS_ERR(WRN, "Returning Stack Fill Because Range = " << index << " " << fAllLabels.size()); return; } if (fNDim == 1) fAllHists[index]->Fill(x, y); else if (fNDim == 2) { // std::cout << "Filling 2D Stack " << index << " " << x << " " << y << " " // << z << std::endl; ((TH2 *)fAllHists[index])->Fill(x, y, z); } else if (fNDim == 3) ((TH3 *)fAllHists[index])->Fill(x, y, z, weight); } void StackBase::Write() { THStack *st = new THStack(); // Loop and add all histograms bool saveseperate = FitPar::Config().GetParB("WriteSeperateStacks"); for (size_t i = 0; i < fAllLabels.size(); i++) { if (!IncludeInStack(fAllHists[i])) continue; if (!IncludeInStack(i)) continue; fAllHists[i]->SetTitle(fAllTitles[i].c_str()); fAllHists[i]->GetXaxis()->SetTitle(fXTitle.c_str()); fAllHists[i]->GetYaxis()->SetTitle(fYTitle.c_str()); fAllHists[i]->GetZaxis()->SetTitle(fZTitle.c_str()); fAllHists[i]->SetLineColor(fAllStyles[i][0]); fAllHists[i]->SetLineWidth(fAllStyles[i][1]); fAllHists[i]->SetFillStyle(fAllStyles[i][2]); fAllHists[i]->SetFillColor(fAllStyles[i][0]); if (saveseperate) fAllHists[i]->Write(); st->Add(fAllHists[i]); } st->SetTitle(fTitle.c_str()); st->SetName(fName.c_str()); st->Write(); delete st; }; void StackBase::Multiply(TH1 *hist) { for (size_t i = 0; i < fAllLabels.size(); i++) { fAllHists[i]->Multiply(hist); } } void StackBase::Divide(TH1 *hist) { for (size_t i = 0; i < fAllLabels.size(); i++) { fAllHists[i]->Divide(hist); } } void StackBase::Add(TH1 *hist, double scale) { for (size_t i = 0; i < fAllLabels.size(); i++) { fAllHists[i]->Add(hist, scale); } } void StackBase::Add(StackBase *hist, double scale) { if (hist->GetType() != fType) { - QERROR(WRN, "Trying to add two StackBases of different types!"); - QERROR(WRN, fType << " + " << hist->GetType() << " = Undefined."); - QERROR(WRN, "Doing nothing..."); + NUIS_ERR(WRN, "Trying to add two StackBases of different types!"); + NUIS_ERR(WRN, fType << " + " << hist->GetType() << " = Undefined."); + NUIS_ERR(WRN, "Doing nothing..."); return; } for (size_t i = 0; i < fAllLabels.size(); i++) { fAllHists[i]->Add(hist->GetHist(i)); } } TH1 *StackBase::GetHist(int entry) { return fAllHists[entry]; } TH1 *StackBase::GetHist(std::string label) { TH1 *hist = NULL; std::vector splitlabels = GeneralUtils::ParseToStr(label, "+"); for (size_t j = 0; j < splitlabels.size(); j++) { std::string newlabel = splitlabels[j]; for (size_t i = 0; i < fAllLabels.size(); i++) { if (newlabel == fAllLabels[i]) { if (!hist) hist = (TH1 *)fAllHists[i]->Clone(); else hist->Add(fAllHists[i]); } } } return hist; } THStack StackBase::GetStack() { THStack st = THStack(); for (size_t i = 0; i < fAllLabels.size(); i++) { st.Add(fAllHists[i]); } return st; } void StackBase::AddNewHist(std::string name, TH1 *hist) { AddMode(fAllLabels.size(), name, hist->GetTitle(), hist->GetLineColor()); fAllHists.push_back((TH1 *)hist->Clone()); } void StackBase::AddToCategory(std::string name, TH1 *hist) { for (size_t i = 0; i < fAllLabels.size(); i++) { if (name == fAllLabels[i]) { fAllHists[i]->Add(hist); break; } } } void StackBase::AddToCategory(int index, TH1 *hist) { fAllHists[index]->Add(hist); } diff --git a/src/InputHandler/FitEvent.cxx b/src/InputHandler/FitEvent.cxx index 05db85b..0150633 100644 --- a/src/InputHandler/FitEvent.cxx +++ b/src/InputHandler/FitEvent.cxx @@ -1,465 +1,465 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is pddrt of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "FitEvent.h" #include "TObjArray.h" #include FitEvent::FitEvent() { fGenInfo = NULL; kRemoveFSIParticles = true; kRemoveUndefParticles = true; AllocateParticleStack(400); }; void FitEvent::AddGeneratorInfo(GeneratorInfoBase *gen) { fGenInfo = gen; gen->AllocateParticleStack(kMaxParticles); } void FitEvent::AllocateParticleStack(int stacksize) { - QLOG(DEB, "Allocating particle stack of size: " << stacksize); + NUIS_LOG(DEB, "Allocating particle stack of size: " << stacksize); kMaxParticles = stacksize; fParticleList = new FitParticle *[kMaxParticles]; fParticleMom = new double *[kMaxParticles]; fParticleState = new UInt_t[kMaxParticles]; fParticlePDG = new int[kMaxParticles]; fPrimaryVertex = new bool[kMaxParticles]; fOrigParticleMom = new double *[kMaxParticles]; fOrigParticleState = new UInt_t[kMaxParticles]; fOrigParticlePDG = new int[kMaxParticles]; fOrigPrimaryVertex = new bool[kMaxParticles]; for (size_t i = 0; i < kMaxParticles; i++) { fParticleList[i] = NULL; fParticleMom[i] = new double[4]; fOrigParticleMom[i] = new double[4]; } if (fGenInfo) fGenInfo->AllocateParticleStack(kMaxParticles); } void FitEvent::ExpandParticleStack(int stacksize) { DeallocateParticleStack(); AllocateParticleStack(stacksize); } void FitEvent::DeallocateParticleStack() { for (size_t i = 0; i < kMaxParticles; i++) { if (fParticleList[i]) delete fParticleList[i]; delete fParticleMom[i]; delete fOrigParticleMom[i]; } delete fParticleMom; delete fOrigParticleMom; delete fParticleList; delete fParticleState; delete fParticlePDG; delete fPrimaryVertex; delete fOrigParticleState; delete fOrigParticlePDG; delete fOrigPrimaryVertex; if (fGenInfo) fGenInfo->DeallocateParticleStack(); kMaxParticles = 0; } void FitEvent::ClearFitParticles() { for (size_t i = 0; i < kMaxParticles; i++) { fParticleList[i] = NULL; } } void FitEvent::FreeFitParticles() { for (size_t i = 0; i < kMaxParticles; i++) { FitParticle *fp = fParticleList[i]; if (fp) delete fp; fParticleList[i] = NULL; } } void FitEvent::ResetParticleList() { for (unsigned int i = 0; i < kMaxParticles; i++) { FitParticle *fp = fParticleList[i]; if (fp) delete fp; fParticleList[i] = NULL; } } void FitEvent::HardReset() { for (unsigned int i = 0; i < kMaxParticles; i++) { fParticleList[i] = NULL; } } void FitEvent::ResetEvent() { Mode = 9999; fEventNo = -1; fTotCrs = -1.0; fTargetA = -1; fTargetZ = -1; fTargetH = -1; fBound = false; fNParticles = 0; if (fGenInfo) fGenInfo->Reset(); for (unsigned int i = 0; i < kMaxParticles; i++) { if (fParticleList[i]) delete fParticleList[i]; fParticleList[i] = NULL; continue; fParticlePDG[i] = 0; fParticleState[i] = kUndefinedState; fParticleMom[i][0] = 0.0; fParticleMom[i][1] = 0.0; fParticleMom[i][2] = 0.0; fParticleMom[i][3] = 0.0; fPrimaryVertex[i] = false; fOrigParticlePDG[i] = 0; fOrigParticleState[i] = kUndefinedState; fOrigParticleMom[i][0] = 0.0; fOrigParticleMom[i][1] = 0.0; fOrigParticleMom[i][2] = 0.0; fOrigParticleMom[i][3] = 0.0; fOrigPrimaryVertex[i] = false; } } void FitEvent::OrderStack() { // Copy current stack int npart = fNParticles; for (int i = 0; i < npart; i++) { fOrigParticlePDG[i] = fParticlePDG[i]; fOrigParticleState[i] = fParticleState[i]; fOrigParticleMom[i][0] = fParticleMom[i][0]; fOrigParticleMom[i][1] = fParticleMom[i][1]; fOrigParticleMom[i][2] = fParticleMom[i][2]; fOrigParticleMom[i][3] = fParticleMom[i][3]; fOrigPrimaryVertex[i] = fPrimaryVertex[i]; } // Now run loops for each particle fNParticles = 0; int stateorder[6] = {kInitialState, kFinalState, kFSIState, kNuclearInitial, kNuclearRemnant, kUndefinedState}; for (int s = 0; s < 6; s++) { for (int i = 0; i < npart; i++) { if ((UInt_t)fOrigParticleState[i] != (UInt_t)stateorder[s]) continue; fParticlePDG[fNParticles] = fOrigParticlePDG[i]; fParticleState[fNParticles] = fOrigParticleState[i]; fParticleMom[fNParticles][0] = fOrigParticleMom[i][0]; fParticleMom[fNParticles][1] = fOrigParticleMom[i][1]; fParticleMom[fNParticles][2] = fOrigParticleMom[i][2]; fParticleMom[fNParticles][3] = fOrigParticleMom[i][3]; fPrimaryVertex[fNParticles] = fOrigPrimaryVertex[i]; fNParticles++; } } if (LOG_LEVEL(DEB)) { - QLOG(DEB, "Ordered stack"); + NUIS_LOG(DEB, "Ordered stack"); for (int i = 0; i < fNParticles; i++) { - QLOG(DEB, "Particle " << i << ". " << fParticlePDG[i] << " " + NUIS_LOG(DEB, "Particle " << i << ". " << fParticlePDG[i] << " " << fParticleMom[i][0] << " " << fParticleMom[i][1] << " " << fParticleMom[i][2] << " " << fParticleMom[i][3] << " " << fParticleState[i]); } } if (fNParticles != npart) { - QTHROW("Dropped some particles when ordering the stack!"); + NUIS_ABORT("Dropped some particles when ordering the stack!"); } return; } void FitEvent::Print() { if (LOG_LEVEL(FIT)) { - QLOG(FIT, "FITEvent print"); - QLOG(FIT, "Mode: " << Mode << ", Weight: " << InputWeight); - QLOG(FIT, "Particles: " << fNParticles); - QLOG(FIT, " -> Particle Stack "); + NUIS_LOG(FIT, "FITEvent print"); + NUIS_LOG(FIT, "Mode: " << Mode << ", Weight: " << InputWeight); + NUIS_LOG(FIT, "Particles: " << fNParticles); + NUIS_LOG(FIT, " -> Particle Stack "); for (int i = 0; i < fNParticles; i++) { - QLOG(FIT, " -> -> " << i << ". " << fParticlePDG[i] << " " + NUIS_LOG(FIT, " -> -> " << i << ". " << fParticlePDG[i] << " " << fParticleState[i] << " " << " Mom(" << fParticleMom[i][0] << ", " << fParticleMom[i][1] << ", " << fParticleMom[i][2] << ", " << fParticleMom[i][3] << ")."); } } return; } /* Read/Write own event class */ void FitEvent::SetBranchAddress(TChain *tn) { tn->SetBranchAddress("Mode", &Mode); tn->SetBranchAddress("EventNo", &fEventNo); tn->SetBranchAddress("TotCrs", &fTotCrs); tn->SetBranchAddress("TargetA", &fTargetA); tn->SetBranchAddress("TargetH", &fTargetH); tn->SetBranchAddress("Bound", &fBound); tn->SetBranchAddress("RWWeight", &SavedRWWeight); tn->SetBranchAddress("InputWeight", &InputWeight); } void FitEvent::AddBranchesToTree(TTree *tn) { tn->Branch("Mode", &Mode, "Mode/I"); tn->Branch("EventNo", &fEventNo, "EventNo/i"); tn->Branch("TotCrs", &fTotCrs, "TotCrs/D"); tn->Branch("TargetA", &fTargetA, "TargetA/I"); tn->Branch("TargetH", &fTargetH, "TargetH/I"); tn->Branch("Bound", &fBound, "Bound/O"); tn->Branch("RWWeight", &RWWeight, "RWWeight/D"); tn->Branch("InputWeight", &InputWeight, "InputWeight/D"); tn->Branch("NParticles", &fNParticles, "NParticles/I"); tn->Branch("ParticleState", fOrigParticleState, "ParticleState[NParticles]/i"); tn->Branch("ParticlePDG", fOrigParticlePDG, "ParticlePDG[NParticles]/I"); tn->Branch("ParticleMom", fOrigParticleMom, "ParticleMom[NParticles][4]/D"); } // ------- EVENT ACCESS FUNCTION --------- // TLorentzVector FitEvent::GetParticleP4(int index) const { if (index == -1 or index >= fNParticles) return TLorentzVector(); return TLorentzVector(fParticleMom[index][0], fParticleMom[index][1], fParticleMom[index][2], fParticleMom[index][3]); } TVector3 FitEvent::GetParticleP3(int index) const { if (index == -1 or index >= fNParticles) return TVector3(); return TVector3(fParticleMom[index][0], fParticleMom[index][1], fParticleMom[index][2]); } double FitEvent::GetParticleMom(int index) const { if (index == -1 or index >= fNParticles) return 0.0; return sqrt(fParticleMom[index][0] * fParticleMom[index][0] + fParticleMom[index][1] * fParticleMom[index][1] + fParticleMom[index][2] * fParticleMom[index][2]); } double FitEvent::GetParticleMom2(int index) const { if (index == -1 or index >= fNParticles) return 0.0; return fabs((fParticleMom[index][0] * fParticleMom[index][0] + fParticleMom[index][1] * fParticleMom[index][1] + fParticleMom[index][2] * fParticleMom[index][2])); } double FitEvent::GetParticleE(int index) const { if (index == -1 or index >= fNParticles) return 0.0; return fParticleMom[index][3]; } int FitEvent::GetParticleState(int index) const { if (index == -1 or index >= fNParticles) return kUndefinedState; return (fParticleState[index]); } int FitEvent::GetParticlePDG(int index) const { if (index == -1 or index >= fNParticles) return 0; return (fParticlePDG[index]); } FitParticle *FitEvent::GetParticle(int const i) { // Check Valid Index if (i == -1) { return NULL; } // Check Valid if (i > fNParticles) { - QTHROW("Requesting particle beyond stack!" + NUIS_ABORT("Requesting particle beyond stack!" << std::endl << "i = " << i << " N = " << fNParticles << std::endl << "Mode = " << Mode); } if (!fParticleList[i]) { /* std::cout << "Creating particle with values i " << i << " "; std::cout << fParticleMom[i][0] << " " << fParticleMom[i][1] << " " << fParticleMom[i][2] << " " << fParticleMom[i][3] << " "; std::cout << fParticlePDG[i] << " " << fParticleState[i] << std::endl; */ fParticleList[i] = new FitParticle(fParticleMom[i][0], fParticleMom[i][1], fParticleMom[i][2], fParticleMom[i][3], fParticlePDG[i], fParticleState[i]); } else { /* std::cout << "Filling particle with values i " << i << " "; std::cout << fParticleMom[i][0] << " " << fParticleMom[i][1] << " " << fParticleMom[i][2] << " " << fParticleMom[i][3] << " "; std::cout << fParticlePDG[i] << " "<< fParticleState[i] <SetValues(fParticleMom[i][0], fParticleMom[i][1], fParticleMom[i][2], fParticleMom[i][3], fParticlePDG[i], fParticleState[i]); } return fParticleList[i]; } bool FitEvent::HasParticle(int const pdg, int const state) const { bool found = false; for (int i = 0; i < fNParticles; i++) { if (state != -1 && fParticleState[i] != (uint)state) continue; if (fParticlePDG[i] == pdg) found = true; } return found; } int FitEvent::NumParticle(int const pdg, int const state) const { int nfound = 0; for (int i = 0; i < fNParticles; i++) { if (state != -1 and fParticleState[i] != (uint)state) continue; if (pdg == 0 or fParticlePDG[i] == pdg) nfound += 1; } return nfound; } std::vector FitEvent::GetAllParticleIndices(int const pdg, int const state) const { std::vector indexlist; for (int i = 0; i < fNParticles; i++) { if (state != -1 and fParticleState[i] != (uint)state) continue; if (pdg == 0 or fParticlePDG[i] == pdg) { indexlist.push_back(i); } } return indexlist; } std::vector FitEvent::GetAllParticle(int const pdg, int const state) { std::vector indexlist = GetAllParticleIndices(pdg, state); std::vector plist; for (std::vector::iterator iter = indexlist.begin(); iter != indexlist.end(); iter++) { plist.push_back(GetParticle((*iter))); } return plist; } int FitEvent::GetHMParticleIndex(int const pdg, int const state) const { double maxmom2 = -9999999.9; int maxind = -1; for (int i = 0; i < fNParticles; i++) { if (state != -1 and fParticleState[i] != (uint)state) continue; if (pdg == 0 or fParticlePDG[i] == pdg) { double newmom2 = GetParticleMom2(i); if (newmom2 > maxmom2) { maxind = i; maxmom2 = newmom2; } } } return maxind; } int FitEvent::GetBeamNeutrinoIndex(void) const { for (int i = 0; i < fNParticles; i++) { if (fParticleState[i] != kInitialState) continue; int pdg = abs(fParticlePDG[i]); if (pdg == 12 or pdg == 14 or pdg == 16) { return i; } } return 0; } int FitEvent::GetBeamElectronIndex(void) const { return GetHMISParticleIndex(11); } int FitEvent::GetBeamPionIndex(void) const { return GetHMISParticleIndex(PhysConst::pdg_pions); } int FitEvent::GetBeamPartIndex(void) const { return GetHMISParticleIndex(this->probe_pdg); } int FitEvent::NumFSMesons() { int nMesons = 0; for (int i = 0; i < fNParticles; i++) { if (fParticleState[i] != kFinalState) continue; if (abs(fParticlePDG[i]) >= 111 && abs(fParticlePDG[i]) <= 557) nMesons += 1; } return nMesons; } int FitEvent::NumFSLeptons(void) const { int nLeptons = 0; for (int i = 0; i < fNParticles; i++) { if (fParticleState[i] != kFinalState) continue; if (abs(fParticlePDG[i]) == 11 || abs(fParticlePDG[i]) == 13 || abs(fParticlePDG[i]) == 15) nLeptons += 1; } return nLeptons; } diff --git a/src/InputHandler/FitEventInputHandler.cxx b/src/InputHandler/FitEventInputHandler.cxx index c40b0ed..a30350f 100644 --- a/src/InputHandler/FitEventInputHandler.cxx +++ b/src/InputHandler/FitEventInputHandler.cxx @@ -1,141 +1,141 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "FitEventInputHandler.h" #include "InputUtils.h" FitEventInputHandler::FitEventInputHandler(std::string const &handle, std::string const &rawinputs) { - QLOG(SAM, "Creating FitEventInputHandler : " << handle); + NUIS_LOG(SAM, "Creating FitEventInputHandler : " << handle); // Run a joint input handling fName = handle; fFitEventTree = new TChain("nuisance_events"); fCacheSize = FitPar::Config().GetParI("CacheSize"); std::vector inputs = InputUtils::ParseInputFileList(rawinputs); for (size_t inp_it = 0; inp_it < inputs.size(); ++inp_it) { // Open File for histogram access TFile *inp_file = new TFile(inputs[inp_it].c_str(), "READ"); if (!inp_file or inp_file->IsZombie()) { - QTHROW("FitEvent File IsZombie() at " << inputs[inp_it]); + NUIS_ABORT("FitEvent File IsZombie() at " << inputs[inp_it]); } // Get Flux/Event hist TH1D *fluxhist = (TH1D *)inp_file->Get("nuisance_fluxhist"); TH1D *eventhist = (TH1D *)inp_file->Get("nuisance_eventhist"); if (!fluxhist or !eventhist) { - QTHROW("FitEvent FILE doesn't contain flux/xsec info"); + NUIS_ABORT("FitEvent FILE doesn't contain flux/xsec info"); } // Get N Events TTree *eventtree = (TTree *)inp_file->Get("nuisance_events"); if (!eventtree) { - QTHROW("nuisance_events not located in GENIE file! " << inputs[inp_it]); + NUIS_ABORT("nuisance_events not located in GENIE file! " << inputs[inp_it]); } int nevents = eventtree->GetEntries(); // Register input to form flux/event rate hists RegisterJointInput(inputs[inp_it], nevents, fluxhist, eventhist); // Add to TChain fFitEventTree->Add(inputs[inp_it].c_str()); } // Registor all our file inputs SetupJointInputs(); // Assign to tree fEventType = kINPUTFITEVENT; // Create Fit Event fNUISANCEEvent = new FitEvent(); fNUISANCEEvent->HardReset(); fNUISANCEEvent->SetBranchAddress(fFitEventTree); fFitEventTree->SetBranchAddress("NParticles", &fReadNParticles); fFitEventTree->SetBranchAddress("ParticleState", &fReadParticleState); fFitEventTree->SetBranchAddress("ParticlePDG", &fReadParticlePDG); fFitEventTree->SetBranchAddress("ParticleMom", &fReadParticleMom); fFitEventTree->Show(0); fNUISANCEEvent = GetNuisanceEvent(0); std::cout << "NParticles = " << fNUISANCEEvent->Npart() << std::endl; std::cout << "Event Info " << fNUISANCEEvent->PartInfo(0)->fPID << std::endl; } FitEventInputHandler::~FitEventInputHandler() { if (fFitEventTree) delete fFitEventTree; } void FitEventInputHandler::CreateCache() { // fFitEventTree->SetCacheEntryRange(0, fNEvents); // fFitEventTree->AddBranchToCache("*", 1); // fFitEventTree->SetCacheSize(fCacheSize); } void FitEventInputHandler::RemoveCache() { // fFitEventTree->SetCacheEntryRange(0, fNEvents); // fFitEventTree->AddBranchToCache("*", 0); // fFitEventTree->SetCacheSize(0); } FitEvent *FitEventInputHandler::GetNuisanceEvent(const UInt_t entry, const bool lightweight) { // Return NULL if out of bounds if (entry >= (UInt_t)fNEvents) return NULL; // Reset all variables before tree read fNUISANCEEvent->ResetEvent(); // Read NUISANCE Tree fFitEventTree->GetEntry(entry); // Fill Stack fNUISANCEEvent->fNParticles = 0; for (int i = 0; i < fReadNParticles; i++) { size_t curpart = fNUISANCEEvent->fNParticles; fNUISANCEEvent->fParticleState[curpart] = fReadParticleState[i]; // Mom fNUISANCEEvent->fParticleMom[curpart][0] = fReadParticleMom[i][0]; fNUISANCEEvent->fParticleMom[curpart][1] = fReadParticleMom[i][1]; fNUISANCEEvent->fParticleMom[curpart][2] = fReadParticleMom[i][2]; fNUISANCEEvent->fParticleMom[curpart][3] = fReadParticleMom[i][3]; // PDG fNUISANCEEvent->fParticlePDG[curpart] = fReadParticlePDG[i]; // Add to N particle count fNUISANCEEvent->fNParticles++; } // Setup Input scaling for joint inputs fNUISANCEEvent->InputWeight = GetInputWeight(entry); return fNUISANCEEvent; } double FitEventInputHandler::GetInputWeight(int entry) { double w = InputHandlerBase::GetInputWeight(entry); return w * fNUISANCEEvent->SavedRWWeight; } void FitEventInputHandler::Print() {} diff --git a/src/InputHandler/GENIEInputHandler.cxx b/src/InputHandler/GENIEInputHandler.cxx index 86d89c4..5a38a97 100644 --- a/src/InputHandler/GENIEInputHandler.cxx +++ b/src/InputHandler/GENIEInputHandler.cxx @@ -1,594 +1,594 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #ifdef __GENIE_ENABLED__ #include "GENIEInputHandler.h" #ifdef GENIE_PRE_R3 #include "Messenger/Messenger.h" #else #include "Framework/Messenger/Messenger.h" #endif #include "InputUtils.h" GENIEGeneratorInfo::~GENIEGeneratorInfo() { DeallocateParticleStack(); } void GENIEGeneratorInfo::AddBranchesToTree(TTree *tn) { tn->Branch("GenieParticlePDGs", &fGenieParticlePDGs, "GenieParticlePDGs/I"); } void GENIEGeneratorInfo::SetBranchesFromTree(TTree *tn) { tn->SetBranchAddress("GenieParticlePDGs", &fGenieParticlePDGs); } void GENIEGeneratorInfo::AllocateParticleStack(int stacksize) { fGenieParticlePDGs = new int[stacksize]; } void GENIEGeneratorInfo::DeallocateParticleStack() { delete fGenieParticlePDGs; } void GENIEGeneratorInfo::FillGeneratorInfo(NtpMCEventRecord *ntpl) { Reset(); // Check for GENIE Event if (!ntpl) return; if (!ntpl->event) return; // Cast Event Record GHepRecord *ghep = static_cast(ntpl->event); if (!ghep) return; // Fill Particle Stack GHepParticle *p = 0; TObjArrayIter iter(ghep); // Loop over all particles int i = 0; while ((p = (dynamic_cast((iter).Next())))) { if (!p) continue; // Get PDG fGenieParticlePDGs[i] = p->Pdg(); i++; } } void GENIEGeneratorInfo::Reset() { for (int i = 0; i < kMaxParticles; i++) { fGenieParticlePDGs[i] = 0; } } GENIEInputHandler::GENIEInputHandler(std::string const &handle, std::string const &rawinputs) { - QLOG(SAM, "Creating GENIEInputHandler : " << handle); + NUIS_LOG(SAM, "Creating GENIEInputHandler : " << handle); genie::Messenger::Instance()->SetPriorityLevel("GHepUtils", pFATAL); // Run a joint input handling fName = handle; // Setup the TChain fGENIETree = new TChain("gtree"); fSaveExtra = FitPar::Config().GetParB("SaveExtraGenie"); fCacheSize = FitPar::Config().GetParI("CacheSize"); fMaxEvents = FitPar::Config().GetParI("MAXEVENTS"); // Are we running with NOvA weights fNOvAWeights = FitPar::Config().GetParB("NOvA_Weights"); MAQEw = 1.0; NonResw = 1.0; RPAQEw = 1.0; RPARESw = 1.0; MECw = 1.0; DISw = 1.0; NOVAw = 1.0; // Loop over all inputs and grab flux, eventhist, and nevents std::vector inputs = InputUtils::ParseInputFileList(rawinputs); for (size_t inp_it = 0; inp_it < inputs.size(); ++inp_it) { // Open File for histogram access TFile *inp_file = new TFile( InputUtils::ExpandInputDirectories(inputs[inp_it]).c_str(), "READ"); if (!inp_file or inp_file->IsZombie()) { - QTHROW("GENIE File IsZombie() at : '" + NUIS_ABORT("GENIE File IsZombie() at : '" << inputs[inp_it] << "'" << std::endl << "Check that your file paths are correct and the file exists!" << std::endl << "$ ls -lh " << inputs[inp_it]); } // Get Flux/Event hist TH1D *fluxhist = (TH1D *)inp_file->Get("nuisance_flux"); TH1D *eventhist = (TH1D *)inp_file->Get("nuisance_events"); if (!fluxhist or !eventhist) { - QERROR(FTL, "Input File Contents: " << inputs[inp_it]); + NUIS_ERR(FTL, "Input File Contents: " << inputs[inp_it]); inp_file->ls(); - QTHROW("GENIE FILE doesn't contain flux/xsec info." + NUIS_ABORT("GENIE FILE doesn't contain flux/xsec info." << std::endl << "Try running the app PrepareGENIE first on :" << inputs[inp_it] << std::endl << "$ PrepareGENIE -h"); } // Get N Events TTree *genietree = (TTree *)inp_file->Get("gtree"); if (!genietree) { - QERROR(FTL, "gtree not located in GENIE file: " << inputs[inp_it]); - QTHROW("Check your inputs, they may need to be completely regenerated!"); + NUIS_ERR(FTL, "gtree not located in GENIE file: " << inputs[inp_it]); + NUIS_ABORT("Check your inputs, they may need to be completely regenerated!"); } int nevents = genietree->GetEntries(); if (nevents <= 0) { - QTHROW("Trying to a TTree with " + NUIS_ABORT("Trying to a TTree with " << nevents << " to TChain from : " << inputs[inp_it]); } // Check for precomputed weights TTree *weighttree = (TTree *)inp_file->Get("nova_wgts"); if (fNOvAWeights) { if (!weighttree) { - QTHROW("Did not find nova_wgts tree in file " + NUIS_ABORT("Did not find nova_wgts tree in file " << inputs[inp_it] << " but you specified it" << std::endl); } else { - QLOG(FIT, "Found nova_wgts tree in file " << inputs[inp_it]); + NUIS_LOG(FIT, "Found nova_wgts tree in file " << inputs[inp_it]); } } // Register input to form flux/event rate hists RegisterJointInput(inputs[inp_it], nevents, fluxhist, eventhist); // Add To TChain fGENIETree->AddFile(inputs[inp_it].c_str()); if (weighttree != NULL) fGENIETree->AddFriend(weighttree); } // Registor all our file inputs SetupJointInputs(); // Assign to tree fEventType = kGENIE; fGenieNtpl = NULL; fGENIETree->SetBranchAddress("gmcrec", &fGenieNtpl); // Set up the custom weights if (fNOvAWeights) { fGENIETree->SetBranchAddress("MAQEwgt", &MAQEw); fGENIETree->SetBranchAddress("nonResNormWgt", &NonResw); fGENIETree->SetBranchAddress("RPAQEWgt", &RPAQEw); fGENIETree->SetBranchAddress("RPARESWgt", &RPARESw); fGENIETree->SetBranchAddress("MECWgt", &MECw); fGENIETree->SetBranchAddress("DISWgt", &DISw); fGENIETree->SetBranchAddress("nova2018CVWgt", &NOVAw); } // Libraries should be seen but not heard... StopTalking(); fGENIETree->GetEntry(0); StartTalking(); // Create Fit Event fNUISANCEEvent = new FitEvent(); fNUISANCEEvent->SetGenieEvent(fGenieNtpl); if (fSaveExtra) { fGenieInfo = new GENIEGeneratorInfo(); fNUISANCEEvent->AddGeneratorInfo(fGenieInfo); } fNUISANCEEvent->HardReset(); }; GENIEInputHandler::~GENIEInputHandler() { // if (fGenieGHep) delete fGenieGHep; // if (fGenieNtpl) delete fGenieNtpl; // if (fGENIETree) delete fGENIETree; // if (fGenieInfo) delete fGenieInfo; } void GENIEInputHandler::CreateCache() { if (fCacheSize > 0) { // fGENIETree->SetCacheEntryRange(0, fNEvents); fGENIETree->AddBranchToCache("*", 1); fGENIETree->SetCacheSize(fCacheSize); } } void GENIEInputHandler::RemoveCache() { // fGENIETree->SetCacheEntryRange(0, fNEvents); fGENIETree->AddBranchToCache("*", 0); fGENIETree->SetCacheSize(0); } FitEvent *GENIEInputHandler::GetNuisanceEvent(const UInt_t entry, const bool lightweight) { if (entry >= (UInt_t)fNEvents) return NULL; // Clear the previous event (See Note 1 in ROOT TClonesArray documentation) if (fGenieNtpl) { fGenieNtpl->Clear(); } // Read Entry from TTree to fill NEUT Vect in BaseFitEvt; fGENIETree->GetEntry(entry); // Run NUISANCE Vector Filler if (!lightweight) { CalcNUISANCEKinematics(); } #ifdef __PROB3PP_ENABLED__ else { // Check for GENIE Event if (!fGenieNtpl) return NULL; if (!fGenieNtpl->event) return NULL; // Cast Event Record fGenieGHep = static_cast(fGenieNtpl->event); if (!fGenieGHep) return NULL; TObjArrayIter iter(fGenieGHep); genie::GHepParticle *p; while ((p = (dynamic_cast((iter).Next())))) { if (!p) { continue; } // Get Status int state = GetGENIEParticleStatus(p, fNUISANCEEvent->Mode); if (state != genie::kIStInitialState) { continue; } fNUISANCEEvent->probe_E = p->E() * 1.E3; fNUISANCEEvent->probe_pdg = p->Pdg(); break; } } #endif // Setup Input scaling for joint inputs fNUISANCEEvent->InputWeight = GetInputWeight(entry); return fNUISANCEEvent; } int GENIEInputHandler::GetGENIEParticleStatus(genie::GHepParticle *p, int mode) { /* kIStUndefined = -1, kIStInitialState = 0, / generator-level initial state / kIStStableFinalState = 1, / generator-level final state: particles to be tracked by detector-level MC / kIStIntermediateState = 2, kIStDecayedState = 3, kIStCorrelatedNucleon = 10, kIStNucleonTarget = 11, kIStDISPreFragmHadronicState = 12, kIStPreDecayResonantState = 13, kIStHadronInTheNucleus = 14, / hadrons inside the nucleus: marked for hadron transport modules to act on / kIStFinalStateNuclearRemnant = 15, / low energy nuclear fragments entering the record collectively as a 'hadronic blob' pseudo-particle / kIStNucleonClusterTarget = 16, // for composite nucleons before phase space decay */ int state = kUndefinedState; switch (p->Status()) { case genie::kIStNucleonTarget: case genie::kIStInitialState: case genie::kIStCorrelatedNucleon: case genie::kIStNucleonClusterTarget: state = kInitialState; break; case genie::kIStStableFinalState: state = kFinalState; break; case genie::kIStHadronInTheNucleus: if (abs(mode) == 2) state = kInitialState; else state = kFSIState; break; case genie::kIStPreDecayResonantState: case genie::kIStDISPreFragmHadronicState: case genie::kIStIntermediateState: state = kFSIState; break; case genie::kIStFinalStateNuclearRemnant: case genie::kIStUndefined: case genie::kIStDecayedState: default: break; } // Flag to remove nuclear part in genie if (p->Pdg() > 1000000) { if (state == kInitialState) state = kNuclearInitial; else if (state == kFinalState) state = kNuclearRemnant; } return state; } #endif #ifdef __GENIE_ENABLED__ int GENIEInputHandler::ConvertGENIEReactionCode(GHepRecord *gheprec) { // Electron Scattering if (gheprec->Summary()->ProcInfo().IsEM()) { if (gheprec->Summary()->InitState().ProbePdg() == 11) { if (gheprec->Summary()->ProcInfo().IsQuasiElastic()) return 1; else if (gheprec->Summary()->ProcInfo().IsMEC()) return 2; else if (gheprec->Summary()->ProcInfo().IsResonant()) return 13; else if (gheprec->Summary()->ProcInfo().IsDeepInelastic()) return 26; else { - QERROR(WRN, + NUIS_ERR(WRN, "Unknown GENIE Electron Scattering Mode!" << std::endl << "ScatteringTypeId = " << gheprec->Summary()->ProcInfo().ScatteringTypeId() << " " << "InteractionTypeId = " << gheprec->Summary()->ProcInfo().InteractionTypeId() << std::endl << genie::ScatteringType::AsString( gheprec->Summary()->ProcInfo().ScatteringTypeId()) << " " << genie::InteractionType::AsString( gheprec->Summary()->ProcInfo().InteractionTypeId()) << " " << gheprec->Summary()->ProcInfo().IsMEC()); return 0; } } // Weak CC } else if (gheprec->Summary()->ProcInfo().IsWeakCC()) { // CC MEC if (gheprec->Summary()->ProcInfo().IsMEC()) { if (pdg::IsNeutrino(gheprec->Summary()->InitState().ProbePdg())) return 2; else if (pdg::IsAntiNeutrino(gheprec->Summary()->InitState().ProbePdg())) return -2; // CC OTHER } else { return utils::ghep::NeutReactionCode(gheprec); } // Weak NC } else if (gheprec->Summary()->ProcInfo().IsWeakNC()) { // NC MEC if (gheprec->Summary()->ProcInfo().IsMEC()) { if (pdg::IsNeutrino(gheprec->Summary()->InitState().ProbePdg())) return 32; else if (pdg::IsAntiNeutrino(gheprec->Summary()->InitState().ProbePdg())) return -32; // NC OTHER } else { return utils::ghep::NeutReactionCode(gheprec); } } return 0; } void GENIEInputHandler::CalcNUISANCEKinematics() { // Reset all variables fNUISANCEEvent->ResetEvent(); // Check for GENIE Event if (!fGenieNtpl) return; if (!fGenieNtpl->event) return; // Cast Event Record fGenieGHep = static_cast(fGenieNtpl->event); if (!fGenieGHep) return; // Convert GENIE Reaction Code fNUISANCEEvent->Mode = ConvertGENIEReactionCode(fGenieGHep); // Set Event Info fNUISANCEEvent->fEventNo = 0.0; fNUISANCEEvent->fTotCrs = fGenieGHep->XSec(); // Have a bool storing if interaction happened on free or bound nucleon bool IsFree = false; // Set the TargetPDG if (fGenieGHep->TargetNucleus() != NULL) { fNUISANCEEvent->fTargetPDG = fGenieGHep->TargetNucleus()->Pdg(); IsFree = false; // Sometimes GENIE scatters off free nucleons, electrons, photons // In which TargetNucleus is NULL and we need to find the initial state // particle } else { // Check the particle is an initial state particle // Follows GHepRecord::TargetNucleusPosition but doesn't do check on // pdg::IsIon GHepParticle *p = fGenieGHep->Particle(1); // Check that particle 1 actually exists if (!p) { - QTHROW("Can't find particle 1 for GHepRecord"); + NUIS_ABORT("Can't find particle 1 for GHepRecord"); } // If not an ion but is an initial state particle if (!pdg::IsIon(p->Pdg()) && p->Status() == kIStInitialState) { IsFree = true; fNUISANCEEvent->fTargetPDG = p->Pdg(); // Catch if something strange happens: // Here particle 1 is not an initial state particle OR // particle 1 is an ion OR // both } else { if (pdg::IsIon(p->Pdg())) { - QTHROW("Particle 1 in GHepRecord stack is an ion but isn't an initial " + NUIS_ABORT("Particle 1 in GHepRecord stack is an ion but isn't an initial " "state particle"); } else { - QTHROW("Particle 1 in GHepRecord stack is not an ion but is an initial " + NUIS_ABORT("Particle 1 in GHepRecord stack is not an ion but is an initial " "state particle"); } } } // Set the A and Z and H from the target PDG // Depends on if we scattered off a free or bound nucleon if (!IsFree) { fNUISANCEEvent->fTargetA = TargetUtils::GetTargetAFromPDG(fNUISANCEEvent->fTargetPDG); fNUISANCEEvent->fTargetZ = TargetUtils::GetTargetZFromPDG(fNUISANCEEvent->fTargetPDG); fNUISANCEEvent->fTargetH = 0; } else { // If free proton scattering if (fNUISANCEEvent->fTargetPDG == 2212) { fNUISANCEEvent->fTargetA = 1; fNUISANCEEvent->fTargetZ = 1; fNUISANCEEvent->fTargetH = 1; // If free neutron scattering } else if (fNUISANCEEvent->fTargetPDG == 2112) { fNUISANCEEvent->fTargetA = 0; fNUISANCEEvent->fTargetZ = 1; fNUISANCEEvent->fTargetH = 0; // If neither } else { fNUISANCEEvent->fTargetA = 0; fNUISANCEEvent->fTargetZ = 0; fNUISANCEEvent->fTargetH = 0; } } fNUISANCEEvent->fBound = !IsFree; fNUISANCEEvent->InputWeight = 1.0; //(1E+38 / genie::units::cm2) * fGenieGHep->XSec(); // And the custom weights if (fNOvAWeights) { fNUISANCEEvent->CustomWeight = NOVAw; fNUISANCEEvent->CustomWeightArray[0] = MAQEw; fNUISANCEEvent->CustomWeightArray[1] = NonResw; fNUISANCEEvent->CustomWeightArray[2] = RPAQEw; fNUISANCEEvent->CustomWeightArray[3] = RPARESw; fNUISANCEEvent->CustomWeightArray[4] = MECw; fNUISANCEEvent->CustomWeightArray[5] = NOVAw; } else { fNUISANCEEvent->CustomWeight = 1.0; fNUISANCEEvent->CustomWeightArray[0] = 1.0; fNUISANCEEvent->CustomWeightArray[1] = 1.0; fNUISANCEEvent->CustomWeightArray[2] = 1.0; fNUISANCEEvent->CustomWeightArray[3] = 1.0; fNUISANCEEvent->CustomWeightArray[4] = 1.0; fNUISANCEEvent->CustomWeightArray[5] = 1.0; } // Get N Particle Stack unsigned int npart = fGenieGHep->GetEntries(); unsigned int kmax = fNUISANCEEvent->kMaxParticles; if (npart > kmax) { - QERROR(WRN, "GENIE has too many particles, expanding stack."); + NUIS_ERR(WRN, "GENIE has too many particles, expanding stack."); fNUISANCEEvent->ExpandParticleStack(npart); } // Fill Particle Stack GHepParticle *p = 0; TObjArrayIter iter(fGenieGHep); fNUISANCEEvent->fNParticles = 0; // Loop over all particles while ((p = (dynamic_cast((iter).Next())))) { if (!p) continue; // Get Status int state = GetGENIEParticleStatus(p, fNUISANCEEvent->Mode); // Remove Undefined if (kRemoveUndefParticles && state == kUndefinedState) continue; // Remove FSI if (kRemoveFSIParticles && state == kFSIState) continue; if (kRemoveNuclearParticles && (state == kNuclearInitial || state == kNuclearRemnant)) continue; // Fill Vectors int curpart = fNUISANCEEvent->fNParticles; fNUISANCEEvent->fParticleState[curpart] = state; // Mom fNUISANCEEvent->fParticleMom[curpart][0] = p->Px() * 1.E3; fNUISANCEEvent->fParticleMom[curpart][1] = p->Py() * 1.E3; fNUISANCEEvent->fParticleMom[curpart][2] = p->Pz() * 1.E3; fNUISANCEEvent->fParticleMom[curpart][3] = p->E() * 1.E3; // PDG fNUISANCEEvent->fParticlePDG[curpart] = p->Pdg(); // Set if the particle was on the fundamental vertex fNUISANCEEvent->fPrimaryVertex[curpart] = (p->FirstMother() < 2); // Add to N particle count fNUISANCEEvent->fNParticles++; // Extra Check incase GENIE fails. if ((UInt_t)fNUISANCEEvent->fNParticles == kmax) { - QERROR(WRN, "Number of GENIE Particles exceeds maximum!"); - QERROR(WRN, "Extend kMax, or run without including FSI particles!"); + NUIS_ERR(WRN, "Number of GENIE Particles exceeds maximum!"); + NUIS_ERR(WRN, "Extend kMax, or run without including FSI particles!"); break; } } // Fill Extra Stack if (fSaveExtra) fGenieInfo->FillGeneratorInfo(fGenieNtpl); // Run Initial, FSI, Final, Other ordering. fNUISANCEEvent->OrderStack(); FitParticle *ISAnyLepton = fNUISANCEEvent->GetHMISAnyLeptons(); if (ISAnyLepton) { fNUISANCEEvent->probe_E = ISAnyLepton->E(); fNUISANCEEvent->probe_pdg = ISAnyLepton->PDG(); } return; } void GENIEInputHandler::Print() {} #endif diff --git a/src/InputHandler/GIBUUInputHandler.cxx b/src/InputHandler/GIBUUInputHandler.cxx index fe912dc..ce90bb8 100644 --- a/src/InputHandler/GIBUUInputHandler.cxx +++ b/src/InputHandler/GIBUUInputHandler.cxx @@ -1,300 +1,300 @@ #ifdef __GiBUU_ENABLED__ #include "GIBUUInputHandler.h" #include "InputUtils.h" GIBUUGeneratorInfo::~GIBUUGeneratorInfo() { DeallocateParticleStack(); } void GIBUUGeneratorInfo::AddBranchesToTree(TTree *tn) { // tn->Branch("NEUTParticleN", fNEUTParticleN, "NEUTParticleN/I"); // tn->Branch("NEUTParticleStatusCode", fNEUTParticleStatusCode, // "NEUTParticleStatusCode[NEUTParticleN]/I"); // tn->Branch("NEUTParticleAliveCode", fNEUTParticleAliveCode, // "NEUTParticleAliveCode[NEUTParticleN]/I"); } void GIBUUGeneratorInfo::SetBranchesFromTree(TTree *tn) { // tn->SetBranchAddress("NEUTParticleN", &fNEUTParticleN ); // tn->SetBranchAddress("NEUTParticleStatusCode", &fNEUTParticleStatusCode ); // tn->SetBranchAddress("NEUTParticleAliveCode", &fNEUTParticleAliveCode ); } void GIBUUGeneratorInfo::AllocateParticleStack(int stacksize) { // fNEUTParticleN = 0; // fNEUTParticleStatusCode = new int[stacksize]; // fNEUTParticleStatusCode = new int[stacksize]; } void GIBUUGeneratorInfo::DeallocateParticleStack() { // delete fNEUTParticleStatusCode; // delete fNEUTParticleAliveCode; } void GIBUUGeneratorInfo::FillGeneratorInfo(GiBUUStdHepReader *nevent) { Reset(); // for (int i = 0; i < nevent->Npart(); i++) { // fNEUTParticleStatusCode[i] = nevent->PartInfo(i)->fStatus; // fNEUTParticleAliveCode[i] = nevent->PartInfo(i)->fIsAlive; // fNEUTParticleN++; // } } void GIBUUGeneratorInfo::Reset() { // for (int i = 0; i < fNEUTParticleN; i++) { // fNEUTParticleStatusCode[i] = -1; // fNEUTParticleAliveCode[i] = 9; // } // fNEUTParticleN = 0; } GIBUUInputHandler::GIBUUInputHandler(std::string const &handle, std::string const &rawinputs) { - QLOG(SAM, "Creating GiBUUInputHandler : " << handle); + NUIS_LOG(SAM, "Creating GiBUUInputHandler : " << handle); // Run a joint input handling fName = handle; fEventType = kGiBUU; fGIBUUTree = new TChain("giRooTracker"); // Loop over all inputs and grab flux, eventhist, and nevents std::vector inputs = InputUtils::ParseInputFileList(rawinputs); for (size_t inp_it = 0; inp_it < inputs.size(); ++inp_it) { // Open File for histogram access - QLOG(SAM, "Opening event file " << inputs[inp_it]); + NUIS_LOG(SAM, "Opening event file " << inputs[inp_it]); TFile *inp_file = new TFile(inputs[inp_it].c_str(), "READ"); if ((!inp_file) || (!inp_file->IsOpen())) { - QTHROW("GiBUU file !IsOpen() at : '" + NUIS_ABORT("GiBUU file !IsOpen() at : '" << inputs[inp_it] << "'" << std::endl << "Check that your file paths are correct and the file exists!"); } int NFluxes = bool(dynamic_cast(inp_file->Get("numu_flux"))) + bool(dynamic_cast(inp_file->Get("numub_flux"))) + bool(dynamic_cast(inp_file->Get("nue_flux"))) + bool(dynamic_cast(inp_file->Get("nueb_flux"))) + bool(dynamic_cast(inp_file->Get("e_flux"))); if (NFluxes != 1) { - QTHROW("Found " << NFluxes << " input fluxes in " << inputs[inp_it] + NUIS_ABORT("Found " << NFluxes << " input fluxes in " << inputs[inp_it] << ". The NUISANCE GiBUU interface expects to be " "passed multiple species vectors as separate " "input files like: " "\"GiBUU:(MINERVA_FHC_numu_evts.root,MINERVA_FHC_" "numubar_evts.root,[...])\""); } // Get Flux/Event hist TH1D *fluxhist = dynamic_cast(inp_file->Get("flux")); TH1D *eventhist = dynamic_cast(inp_file->Get("evt")); if (!fluxhist || !eventhist) { - QERROR(FTL, "Input File Contents: " << inputs[inp_it]); + NUIS_ERR(FTL, "Input File Contents: " << inputs[inp_it]); inp_file->ls(); - QTHROW("GiBUU FILE doesn't contain flux/xsec info. You may have to " + NUIS_ABORT("GiBUU FILE doesn't contain flux/xsec info. You may have to " "regenerate your MC!"); } // Get N Events TTree *giRooTracker = dynamic_cast(inp_file->Get("giRooTracker")); if (!giRooTracker) { - QERROR(FTL, + NUIS_ERR(FTL, "giRooTracker Tree not located in NEUT file: " << inputs[inp_it]); - QTHROW("Check your inputs, they may need to be completely regenerated!"); + NUIS_ABORT("Check your inputs, they may need to be completely regenerated!"); throw; } int nevents = giRooTracker->GetEntries(); if (nevents <= 0) { - QTHROW("Trying to a TTree with " + NUIS_ABORT("Trying to a TTree with " << nevents << " to TChain from : " << inputs[inp_it]); } // Register input to form flux/event rate hists RegisterJointInput(inputs[inp_it], nevents, fluxhist, eventhist); // Add To TChain fGIBUUTree->AddFile(inputs[inp_it].c_str()); } // Registor all our file inputs SetupJointInputs(); // Create Fit Event fNUISANCEEvent = new FitEvent(); fGiReader = new GiBUUStdHepReader(); fGiReader->SetBranchAddresses(fGIBUUTree); fNUISANCEEvent->HardReset(); }; FitEvent *GIBUUInputHandler::GetNuisanceEvent(const UInt_t entry, const bool lightweight) { // Check out of bounds if (entry >= (UInt_t)fNEvents) return NULL; // Read Entry from TTree to fill NEUT Vect in BaseFitEvt; fGIBUUTree->GetEntry(entry); // Run NUISANCE Vector Filler if (!lightweight) { CalcNUISANCEKinematics(); } #ifdef __PROB3PP_ENABLED__ else { for (int i = 0; i < fGiReader->StdHepN; i++) { int state = GetGIBUUParticleStatus(fGiReader->StdHepStatus[i], fGiReader->StdHepPdg[i]); if (state != kInitialState) { continue; } if (std::count(PhysConst::pdg_neutrinos, PhysConst::pdg_neutrinos + 4, fGiReader->StdHepPdg[i])) { fNUISANCEEvent->probe_E = fGiReader->StdHepP4[i][3] * 1.E3; fNUISANCEEvent->probe_pdg = fGiReader->StdHepPdg[i]; break; } } } #endif fNUISANCEEvent->InputWeight *= GetInputWeight(entry); fNUISANCEEvent->GiRead = fGiReader; return fNUISANCEEvent; } int GetGIBUUParticleStatus(int status, int pdg) { int state = kUndefinedState; switch (status) { case 0: // Incoming case 11: // Struck nucleon state = kInitialState; break; case 1: // Good Final State state = kFinalState; break; default: // Other break; } // Set Nuclear States Flag if (pdg > 1000000) { if (state == kInitialState) state = kNuclearInitial; else if (state == kFinalState) state = kNuclearRemnant; else state = kUndefinedState; } return state; } void GIBUUInputHandler::CalcNUISANCEKinematics() { // Reset all variables fNUISANCEEvent->ResetEvent(); FitEvent *evt = fNUISANCEEvent; evt->Mode = fGiReader->GiBUU2NeutCode; evt->fEventNo = 0.0; evt->fTotCrs = 0; evt->fTargetA = 0.0; // Change to get these from nuclear remnant. evt->fTargetZ = 0.0; evt->fTargetH = 0; evt->fBound = 0.0; // Extra GiBUU Input Weight evt->InputWeight = fGiReader->EvtWght; // Check Stack N int npart = fGiReader->StdHepN; int kmax = evt->kMaxParticles; if ((UInt_t)npart > (UInt_t)kmax) { - QERROR(WRN, "GiBUU has too many particles. Expanding Stack."); + NUIS_ERR(WRN, "GiBUU has too many particles. Expanding Stack."); fNUISANCEEvent->ExpandParticleStack(npart); } // Create Stack evt->fNParticles = 0; for (int i = 0; i < npart; i++) { // State int state = GetGIBUUParticleStatus(fGiReader->StdHepStatus[i], fGiReader->StdHepPdg[i]); int curpart = evt->fNParticles; // Set State evt->fParticleState[evt->fNParticles] = state; // Mom evt->fParticleMom[curpart][0] = fGiReader->StdHepP4[i][0] * 1.E3; evt->fParticleMom[curpart][1] = fGiReader->StdHepP4[i][1] * 1.E3; evt->fParticleMom[curpart][2] = fGiReader->StdHepP4[i][2] * 1.E3; evt->fParticleMom[curpart][3] = fGiReader->StdHepP4[i][3] * 1.E3; // PDG evt->fParticlePDG[curpart] = fGiReader->StdHepPdg[i]; // Add to total particles evt->fNParticles++; } // Run Initial, FSI, Final, Other ordering. fNUISANCEEvent->OrderStack(); FitParticle *ISAnyLepton = fNUISANCEEvent->GetHMISAnyLeptons(); if (ISAnyLepton) { fNUISANCEEvent->probe_E = ISAnyLepton->E(); fNUISANCEEvent->probe_pdg = ISAnyLepton->PDG(); } return; } void GIBUUInputHandler::Print() {} void GIBUUInputHandler::SetupJointInputs() { if (jointeventinputs.size() <= 1) { jointinput = false; } else if (jointeventinputs.size() > 1) { jointinput = true; jointindexswitch = 0; } fMaxEvents = FitPar::Config().GetParI("MAXEVENTS"); if (fMaxEvents != -1 and jointeventinputs.size() > 1) { - QTHROW("Can only handle joint inputs when config MAXEVENTS = -1!"); + NUIS_ABORT("Can only handle joint inputs when config MAXEVENTS = -1!"); } for (size_t i = 0; i < jointeventinputs.size(); i++) { double scale = double(fNEvents) / fEventHist->Integral("width"); scale *= jointfluxinputs.at(i)->Integral("width"); jointindexscale.push_back(scale); } fEventHist->SetNameTitle((fName + "_EVT").c_str(), (fName + "_EVT").c_str()); fFluxHist->SetNameTitle((fName + "_FLUX").c_str(), (fName + "_FLUX").c_str()); // Setup Max Events if (fMaxEvents > 1 && fMaxEvents < fNEvents) { if (LOG_LEVEL(SAM)) { std::cout << "\t\t|-> Read Max Entries : " << fMaxEvents << std::endl; } fNEvents = fMaxEvents; } // Print out Status if (LOG_LEVEL(SAM)) { std::cout << "\t\t|-> Total Entries : " << fNEvents << std::endl << "\t\t|-> Event Integral : " << fEventHist->Integral("width") * 1.E-38 << " events/nucleon" << std::endl << "\t\t|-> Flux Integral : " << fFluxHist->Integral("width") << " /cm2" << std::endl << "\t\t|-> Event/Flux : " << fEventHist->Integral("width") * 1.E-38 / fFluxHist->Integral("width") << " cm2/nucleon" << std::endl; } } #endif diff --git a/src/InputHandler/HepMCTextInputHandler.cxx b/src/InputHandler/HepMCTextInputHandler.cxx index d358544..b5cf5db 100644 --- a/src/InputHandler/HepMCTextInputHandler.cxx +++ b/src/InputHandler/HepMCTextInputHandler.cxx @@ -1,171 +1,171 @@ #ifdef __HEPMC_ENABLED__ #include "HepMCTextInputHandler.h" HepMCTextInputHandler::~HepMCTextInputHandler(){ }; HepMCTextInputHandler::HepMCTextInputHandler(std::string const& handle, std::string const& rawinputs) { - QLOG(SAM, "Creating HepMCTextInputHandler : " << handle ); + NUIS_LOG(SAM, "Creating HepMCTextInputHandler : " << handle ); // Run a joint input handling fName = handle; jointinput = false; jointindexswitch = 0; // Get initial flags fMaxEvents = FitPar::Config().GetParI("MAXEVENTS"); // Form list of all inputs, remove brackets if required. std::vector inputs = GeneralUtils::ParseToStr(rawinputs, ","); if (inputs.front()[0] == '(') { inputs.front() = inputs.front().substr(1); } if (inputs.back()[inputs.back().size() - 1] == ')') { inputs.back() = inputs.back().substr(0, inputs.back().size() - 1); } for (size_t inp_it = 0; inp_it < inputs.size(); ++inp_it) { if (LOG_LEVEL(SAM)) { std::cout << "\t\t|-> Input File " << inp_it << " : " << inputs[inp_it] << std::endl; } } fEventType = kHEPMC; fASCIIStream = std::ifstream(inputs[0].c_str()); fHepMCEvent = HepMC::GenEvent(); // Loop through events and get N fNEvents = 0; while (fASCIIStream){ fHepMCEvent.read(fASCIIStream); fNEvents++; } fASCIIStream.seekg(0); fEventHist = new TH1D("eventhist","eventhist",10,0.0,1.0); fFluxHist = new TH1D("eventhist","eventhist",10,0.0,1.0); fNUISANCEEvent = new FitEvent(kHEPMC); fNUISANCEEvent->HardReset(); fBaseEvent = static_cast(fNUISANCEEvent); }; FitEvent* HepMCTextInputHandler::GetNuisanceEvent(const UInt_t entry) { // Catch too large entries if (entry >= (UInt_t)fNEvents){ fASCIIStream.seekg(0); return NULL; } // If no event get the first one if (!fHepMCEvent.is_valid()){ fHepMCEvent.read(fASCIIStream); } // Read Entry from TTree to fill NEUT Vect in BaseFitEvt; if (fHepMCEvent.event_number() != entry){ // If have to read backwords skip to start of ifstream if (fHepMCEvent.event_number() > entry){ fASCIIStream.seekg(0); fHepMCEvent.read(fASCIIStream); } // Loop to event before if reading forwards while (fHepMCEvent.event_number() < entry - 1 and fASCIIStream){ fHepMCEvent.read(fASCIIStream); } fHepMCEvent.read(fASCIIStream); } // Setup Input scaling for joint inputs if (jointinput) { fNUISANCEEvent->InputWeight = GetInputWeight(entry); } else { fNUISANCEEvent->InputWeight = 1.0; } // Run NUISANCE Vector Filler CalcNUISANCEKinematics(); // Return event pointer return fNUISANCEEvent; } int HepMCTextInputHandler::ConvertHepMCStatus() { // Status for HepMC convertor return 0; } void HepMCTextInputHandler::CalcNUISANCEKinematics() { // Reset all variables fNUISANCEEvent->ResetEvent(); // Read all particles from fHepMCEvent std::vector allstateparticles; for ( HepMC::GenEvent::particle_iterator p = fHepMCEvent.particles_begin(); p != fHepMCEvent.particles_end(); ++p ){ allstateparticles.push_back(*p); int pdg = (*p)->pdg_id(); int status = (*p)->status(); // FourVector vect = (*p)->momentum(); int state = ConvertHepMCStatus(status); int curpart = fNUISANCEEvent->fNParticles; fNUISANCEEvent->fParticleState[curpart] = state; // Mom // fNUISANCEEvent->fParticleMom[curpart][0] = vect.px(); // fNUISANCEEvent->fParticleMom[curpart][1] = vect.py(); // fNUISANCEEvent->fParticleMom[curpart][2] = vect.pz(); // fNUISANCEEvent->fParticleMom[curpart][3] = vect.e(); // PDG fNUISANCEEvent->fParticlePDG[curpart] = pdg; // Add up particle count fNUISANCEEvent->fNParticles++; } // Run Initial, FSI, Final, Other ordering. fNUISANCEEvent-> OrderStack(); return; } double HepMCTextInputHandler::GetInputWeight(const UInt_t entry) { // Find Switch Scale while ( entry < (UInt_t)jointindexlow[jointindexswitch] || entry >= (UInt_t)jointindexhigh[jointindexswitch] ) { jointindexswitch++; // Loop Around if (jointindexswitch == jointindexlow.size()) { jointindexswitch = 0; } } return jointindexscale[jointindexswitch]; }; BaseFitEvt* HepMCTextInputHandler::GetBaseEvent(const UInt_t entry) { // Read entry from TTree to fill NEUT Vect in BaseFitEvt; if (entry >= (UInt_t)fNEvents) return NULL; return (BaseFitEvent*)GetNuisanceEvent(entry); } #endif diff --git a/src/InputHandler/HistogramInputHandler.cxx b/src/InputHandler/HistogramInputHandler.cxx index 552e678..e1a97aa 100644 --- a/src/InputHandler/HistogramInputHandler.cxx +++ b/src/InputHandler/HistogramInputHandler.cxx @@ -1,57 +1,57 @@ #include "HistogramInputHandler.h" #include "InputUtils.h" TH1 *HistoInputHandler::GetHistogram(int i) { if (size_t(i) >= fHistos.size()) { - QTHROW("Requested histogram, index " << i << ", but only specified " + NUIS_ABORT("Requested histogram, index " << i << ", but only specified " << fHistos.size() << " input histos."); } return fHistos[i]; } std::vector HistoInputHandler::GetHistograms(int i, int j) { size_t from = (i < 0) ? 0 : i; size_t to = (j < 0) ? fHistos.size() : j; if (j <= i) { - QTHROW("Lower bound of GetHistograms range is larger than or equal to the " + NUIS_ABORT("Lower bound of GetHistograms range is larger than or equal to the " "upper bound: [" << i << ", " << j << "]."); } std::vector rtnv; for (size_t it = from; it < to; ++it) { rtnv.push_back(GetHistogram(it)); } return rtnv; } HistoInputHandler::HistoInputHandler(std::string const &handle, std::string const &rawinputs) { - QLOG(SAM, "Creating HistoInputHandler : " << handle); + NUIS_LOG(SAM, "Creating HistoInputHandler : " << handle); // Run a joint input handling fName = handle; fNEvents = 1; fEventType = kHISTO; fFluxHist = new TH1D("flux", "dummy", 1, 1, 2); fFluxHist->SetBinContent(1, 1); fEventHist = new TH1D("event", "dummy", 1, 1, 2); fEventHist->SetBinContent(1, 1); // Loop over all inputs and grab flux, eventhist, and nevents std::vector inputs = InputUtils::ParseInputFileList(rawinputs); for (size_t inp_it = 0; inp_it < inputs.size(); ++inp_it) { // Open File for histogram access - QLOG(SAM, "Reading histograms from descriptor " << inputs[inp_it]); + NUIS_LOG(SAM, "Reading histograms from descriptor " << inputs[inp_it]); std::vector histos = PlotUtils::GetTH1sFromRootFile(inputs[inp_it]); for (size_t h_it = 0; h_it < histos.size(); ++h_it) { - QLOG(SAM, "Read " << histos[h_it]->GetName()); + NUIS_LOG(SAM, "Read " << histos[h_it]->GetName()); fHistos.push_back(histos[h_it]); } } }; void HistoInputHandler::Print() {} diff --git a/src/InputHandler/InputFactory.cxx b/src/InputHandler/InputFactory.cxx index d1d9d35..794edf6 100644 --- a/src/InputHandler/InputFactory.cxx +++ b/src/InputHandler/InputFactory.cxx @@ -1,122 +1,122 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "FitEventInputHandler.h" #include "GENIEInputHandler.h" #include "GIBUUInputHandler.h" #include "HistogramInputHandler.h" #include "NEUTInputHandler.h" #include "NUANCEInputHandler.h" #include "NuWroInputHandler.h" #include "SigmaQ0HistogramInputHandler.h" #include "SplineInputHandler.h" #include "InputFactory.h" #include "TFile.h" namespace InputUtils { InputHandlerBase *CreateInputHandler(std::string const &handle, InputUtils::InputType inpType, std::string const &inputs) { InputHandlerBase *input = NULL; std::string newinputs = InputUtils::ExpandInputDirectories(inputs); switch (inpType) { case (kNEUT_Input): #ifdef __NEUT_ENABLED__ input = new NEUTInputHandler(handle, newinputs); #else - QERROR(FTL, "Tried to create NEUTInputHandler : " << handle << " " << inpType + NUIS_ERR(FTL, "Tried to create NEUTInputHandler : " << handle << " " << inpType << " " << inputs); - QTHROW("NEUT is not enabled!"); + NUIS_ABORT("NEUT is not enabled!"); #endif break; case (kGENIE_Input): #ifdef __GENIE_ENABLED__ input = new GENIEInputHandler(handle, newinputs); #else - QERROR(FTL, "Tried to create GENIEInputHandler : " + NUIS_ERR(FTL, "Tried to create GENIEInputHandler : " << handle << " " << inpType << " " << inputs); - QTHROW("GENIE is not enabled!"); + NUIS_ABORT("GENIE is not enabled!"); #endif break; case (kNUWRO_Input): #ifdef __NUWRO_ENABLED__ input = new NuWroInputHandler(handle, newinputs); #else - QERROR(FTL, "Tried to create NuWroInputHandler : " + NUIS_ERR(FTL, "Tried to create NuWroInputHandler : " << handle << " " << inpType << " " << inputs); - QTHROW("NuWro is not enabled!"); + NUIS_ABORT("NuWro is not enabled!"); #endif break; case (kGiBUU_Input): #ifdef __GiBUU_ENABLED__ input = new GIBUUInputHandler(handle, newinputs); #else - QERROR(FTL, "Tried to create GiBUUInputHandler : " + NUIS_ERR(FTL, "Tried to create GiBUUInputHandler : " << handle << " " << inpType << " " << inputs); - QTHROW("GiBUU is not enabled!"); + NUIS_ABORT("GiBUU is not enabled!"); #endif break; case (kNUANCE_Input): #ifdef __NUANCE_ENABLED__ input = new NUANCEInputHandler(handle, newinputs); #else - QERROR(FTL, "Tried to create NUANCEInputHandler : " + NUIS_ERR(FTL, "Tried to create NUANCEInputHandler : " << handle << " " << inpType << " " << inputs); - QTHROW("NUANCE is not enabled!"); + NUIS_ABORT("NUANCE is not enabled!"); #endif break; case (kFEVENT_Input): input = new FitEventInputHandler(handle, newinputs); break; case (kEVSPLN_Input): input = new SplineInputHandler(handle, newinputs); break; case (kSIGMAQ0HIST_Input): input = new SigmaQ0HistogramInputHandler(handle, newinputs); break; case (kHISTO_Input): input = new HistoInputHandler(handle, newinputs); break; default: break; } /// Input failed if (!input) { - QTHROW("Input handler creation failed!" << std::endl + NUIS_ABORT("Input handler creation failed!" << std::endl << "Generator Type " << inpType << " not enabled!"); } return input; }; } // namespace InputUtils diff --git a/src/InputHandler/InputHandler.cxx b/src/InputHandler/InputHandler.cxx index 35480d7..7ef8800 100644 --- a/src/InputHandler/InputHandler.cxx +++ b/src/InputHandler/InputHandler.cxx @@ -1,299 +1,299 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "InputHandler.h" #include "InputUtils.h" InputHandlerBase::InputHandlerBase() { fName = ""; fFluxHist = NULL; fEventHist = NULL; fNEvents = 0; fNUISANCEEvent = NULL; fBaseEvent = NULL; kRemoveUndefParticles = FitPar::Config().GetParB("RemoveUndefParticles"); kRemoveFSIParticles = FitPar::Config().GetParB("RemoveFSIParticles"); kRemoveNuclearParticles = FitPar::Config().GetParB("RemoveNuclearParticles"); fMaxEvents = FitPar::Config().GetParI("MAXEVENTS"); fTTreePerformance = NULL; }; InputHandlerBase::~InputHandlerBase() { if (fFluxHist) delete fFluxHist; if (fEventHist) delete fEventHist; // if (fXSecHist) delete fXSecHist; // if (fNUISANCEEvent) delete fNUISANCEEvent; jointfluxinputs.clear(); jointeventinputs.clear(); jointindexlow.clear(); jointindexhigh.clear(); jointindexallowed.clear(); jointindexscale.clear(); // if (fTTreePerformance) { // fTTreePerformance->SaveAs(("ttreeperfstats_" + fName + // ".root").c_str()); // } } void InputHandlerBase::Print(){}; TH1D* InputHandlerBase::GetXSecHistogram(void) { fXSecHist = (TH1D*)fFluxHist->Clone(); fXSecHist->Divide(fEventHist); return fXSecHist; }; double InputHandlerBase::PredictedEventRate(double low, double high, std::string intOpt) { Int_t minBin = fEventHist->GetXaxis()->FindFixBin(low); Int_t maxBin = fEventHist->GetXaxis()->FindFixBin(high); if ((fEventHist->IsBinOverflow(minBin) && (low != -9999.9))) { minBin = 1; } if ((fEventHist->IsBinOverflow(maxBin) && (high != -9999.9))) { maxBin = fEventHist->GetXaxis()->GetNbins() + 1; } // If we are within a single bin if (minBin == maxBin) { // Get the contained fraction of the single bin's width return ((high - low) / fEventHist->GetXaxis()->GetBinWidth(minBin)) * fEventHist->Integral(minBin, minBin, intOpt.c_str()); } double lowBinUpEdge = fEventHist->GetXaxis()->GetBinUpEdge(minBin); double highBinLowEdge = fEventHist->GetXaxis()->GetBinLowEdge(maxBin); double lowBinfracIntegral = ((lowBinUpEdge - low) / fEventHist->GetXaxis()->GetBinWidth(minBin)) * fEventHist->Integral(minBin, minBin, intOpt.c_str()); double highBinfracIntegral = ((high - highBinLowEdge) / fEventHist->GetXaxis()->GetBinWidth(maxBin)) * fEventHist->Integral(maxBin, maxBin, intOpt.c_str()); // If they are neighbouring bins if ((minBin + 1) == maxBin) { std::cout << "Get lowfrac + highfrac" << std::endl; // Get the contained fraction of the two bin's width return lowBinfracIntegral + highBinfracIntegral; } double ContainedIntegral = fEventHist->Integral(minBin + 1, maxBin - 1, intOpt.c_str()); // If there are filled bins between them return lowBinfracIntegral + highBinfracIntegral + ContainedIntegral; }; double InputHandlerBase::TotalIntegratedFlux(double low, double high, std::string intOpt) { Int_t minBin = fFluxHist->GetXaxis()->FindFixBin(low); Int_t maxBin = fFluxHist->GetXaxis()->FindFixBin(high); if ((fFluxHist->IsBinOverflow(minBin) && (low != -9999.9))) { minBin = 1; } if ((fFluxHist->IsBinOverflow(maxBin) && (high != -9999.9))) { maxBin = fFluxHist->GetXaxis()->GetNbins(); high = fFluxHist->GetXaxis()->GetBinLowEdge(maxBin+1); } // If we are within a single bin if (minBin == maxBin) { // Get the contained fraction of the single bin's width return ((high - low) / fFluxHist->GetXaxis()->GetBinWidth(minBin)) * fFluxHist->Integral(minBin, minBin, intOpt.c_str()); } double lowBinUpEdge = fFluxHist->GetXaxis()->GetBinUpEdge(minBin); double highBinLowEdge = fFluxHist->GetXaxis()->GetBinLowEdge(maxBin); double lowBinfracIntegral = ((lowBinUpEdge - low) / fFluxHist->GetXaxis()->GetBinWidth(minBin)) * fFluxHist->Integral(minBin, minBin, intOpt.c_str()); double highBinfracIntegral = ((high - highBinLowEdge) / fFluxHist->GetXaxis()->GetBinWidth(maxBin)) * fFluxHist->Integral(maxBin, maxBin, intOpt.c_str()); // If they are neighbouring bins if ((minBin + 1) == maxBin) { std::cout << "Get lowfrac + highfrac" << std::endl; // Get the contained fraction of the two bin's width return lowBinfracIntegral + highBinfracIntegral; } double ContainedIntegral = fFluxHist->Integral(minBin + 1, maxBin - 1, intOpt.c_str()); // If there are filled bins between them return lowBinfracIntegral + highBinfracIntegral + ContainedIntegral; } std::vector InputHandlerBase::GetFluxList(void) { return std::vector(1, fFluxHist); }; std::vector InputHandlerBase::GetEventList(void) { return std::vector(1, fEventHist); }; std::vector InputHandlerBase::GetXSecList(void) { return std::vector(1, GetXSecHistogram()); }; FitEvent* InputHandlerBase::FirstNuisanceEvent() { fCurrentIndex = 0; return GetNuisanceEvent(fCurrentIndex); }; FitEvent* InputHandlerBase::NextNuisanceEvent() { fCurrentIndex++; if ((fMaxEvents != -1) && (fCurrentIndex > fMaxEvents)) { return NULL; } return GetNuisanceEvent(fCurrentIndex); }; BaseFitEvt* InputHandlerBase::FirstBaseEvent() { fCurrentIndex = 0; return GetBaseEvent(fCurrentIndex); }; BaseFitEvt* InputHandlerBase::NextBaseEvent() { fCurrentIndex++; if (jointinput and fMaxEvents != -1) { while (fCurrentIndex < jointindexlow[jointindexswitch] || fCurrentIndex >= jointindexhigh[jointindexswitch]) { jointindexswitch++; // Loop Around if (jointindexswitch == jointindexlow.size()) { jointindexswitch = 0; } } if (fCurrentIndex > jointindexlow[jointindexswitch] + jointindexallowed[jointindexswitch]) { fCurrentIndex = jointindexlow[jointindexswitch]; } } return GetBaseEvent(fCurrentIndex); }; void InputHandlerBase::RegisterJointInput(std::string input, int n, TH1D* f, TH1D* e) { if (jointfluxinputs.size() == 0) { jointindexswitch = 0; fNEvents = 0; } // Push into individual input vectors jointfluxinputs.push_back((TH1D*)f->Clone()); jointeventinputs.push_back((TH1D*)e->Clone()); jointindexlow.push_back(fNEvents); jointindexhigh.push_back(fNEvents + n); fNEvents += n; // Add to the total flux/event hist if (!fFluxHist) fFluxHist = (TH1D*)f->Clone(); else fFluxHist->Add(f); if (!fEventHist) fEventHist = (TH1D*)e->Clone(); else fEventHist->Add(e); } void InputHandlerBase::SetupJointInputs() { if (jointeventinputs.size() <= 1) { jointinput = false; } else if (jointeventinputs.size() > 1) { jointinput = true; jointindexswitch = 0; } fMaxEvents = FitPar::Config().GetParI("MAXEVENTS"); if (fMaxEvents != -1 and jointeventinputs.size() > 1) { - QTHROW("Can only handle joint inputs when config MAXEVENTS = -1!"); + NUIS_ABORT("Can only handle joint inputs when config MAXEVENTS = -1!"); } if (jointeventinputs.size() > 1) { - QERROR(WRN, + NUIS_ERR(WRN, "GiBUU sample contains multiple inputs. This will only work for " "samples that expect multi-species inputs. If this sample does, you " "can ignore this warning."); } for (size_t i = 0; i < jointeventinputs.size(); i++) { double scale = double(fNEvents) / fEventHist->Integral("width"); scale *= jointeventinputs.at(i)->Integral("width"); scale /= double(jointindexhigh[i] - jointindexlow[i]); jointindexscale.push_back(scale); } fEventHist->SetNameTitle((fName + "_EVT").c_str(), (fName + "_EVT").c_str()); fFluxHist->SetNameTitle((fName + "_FLUX").c_str(), (fName + "_FLUX").c_str()); // Setup Max Events if (fMaxEvents > 1 && fMaxEvents < fNEvents) { if (LOG_LEVEL(SAM)) { std::cout << "\t\t|-> Read Max Entries : " << fMaxEvents << std::endl; } fNEvents = fMaxEvents; } // Print out Status if (LOG_LEVEL(SAM)) { std::cout << "\t\t|-> Total Entries : " << fNEvents << std::endl << "\t\t|-> Event Integral : " << fEventHist->Integral("width") * 1.E-38 << " events/nucleon" << std::endl << "\t\t|-> Flux Integral : " << fFluxHist->Integral("width") << " /cm2" << std::endl << "\t\t|-> Event/Flux : " << fEventHist->Integral("width") * 1.E-38 / fFluxHist->Integral("width") << " cm2/nucleon" << std::endl; } } BaseFitEvt* InputHandlerBase::GetBaseEvent(const UInt_t entry) { // Do some light processing: don't calculate the kinematics return static_cast(GetNuisanceEvent(entry, true)); } double InputHandlerBase::GetInputWeight(int entry) { if (!jointinput) return 1.0; // Find Switch Scale while (entry < jointindexlow[jointindexswitch] || entry >= jointindexhigh[jointindexswitch]) { jointindexswitch++; // Loop Around if (jointindexswitch >= jointindexlow.size()) { jointindexswitch = 0; } } return jointindexscale[jointindexswitch]; }; diff --git a/src/InputHandler/InputUtils.cxx b/src/InputHandler/InputUtils.cxx index 88484fd..ebbe6c7 100644 --- a/src/InputHandler/InputUtils.cxx +++ b/src/InputHandler/InputUtils.cxx @@ -1,171 +1,171 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "GeneralUtils.h" #include "InputHandler.h" #include "InputUtils.h" namespace InputUtils { std::vector ParseInputFileList(std::string const &inpFile) { std::vector inputs = GeneralUtils::ParseToStr(inpFile, ","); if (inputs.front()[0] == '(') { inputs.front() = inputs.front().substr(1); } if (inputs.back()[inputs.back().size() - 1] == ')') { inputs.back() = inputs.back().substr(0, inputs.back().size() - 1); } return inputs; } InputType ParseInputType(std::string const &inp) { // The hard-coded list of supported input generators const static std::string filetypes[] = { "NEUT", "NUWRO", "GENIE", "GiBUU", "NUANCE", "EVSPLN", "EMPTY", "FEVENT", "JOINT", "SIGMAQ0HIST", "HISTO"}; size_t nInputTypes = GeneralUtils::GetArraySize(filetypes); for (size_t i = 0; i < nInputTypes; i++) { if (inp == filetypes[i]) { return InputType(i); } } return kInvalid_Input; } bool IsJointInput(std::string const &inputs) { bool isJoint = (inputs[0] == '('); if (isJoint && (inputs[inputs.length() - 1] != ')')) { - QTHROW("Inputs specifier: \"" + NUIS_ABORT("Inputs specifier: \"" << inputs << "\" looks like a composite input specifier -- " "(filea.root,fileb.root), however, it did not end in a \')\', " "it ended in a \'" << inputs[inputs.length() - 1] << "\'"); } return isJoint; } std::string ExpandInputDirectories(std::string const &inputs) { // Parse the "environement" flags in the fitter config // Can specify NEUT_DIR = "" and others in parameters/fitter.config.dat const static std::string filedir[] = {"NEUT_DIR", "NUWRO_DIR", "GENIE_DIR", "NUANCE_DIR", "EVSPLN_DIR", "GIBUU_DIR"}; size_t nfiledir = GeneralUtils::GetArraySize(filedir); std::string expandedInputs = inputs; for (size_t i = 0; i < nfiledir; i++) { std::string tempdir = "@" + filedir[i]; bool didRpl; do { size_t torpl = expandedInputs.find(tempdir); if (torpl != std::string::npos) { std::string event_folder = FitPar::Config().GetParS(filedir[i]); expandedInputs.replace(torpl, tempdir.size(), event_folder); didRpl = true; } else { didRpl = false; } } while (didRpl); } bool didRpl; do { size_t torpl = expandedInputs.find("//"); if (torpl != std::string::npos) { expandedInputs.replace(torpl, 2, "/"); didRpl = true; } else { didRpl = false; } } while (didRpl); return expandedInputs; } InputType GuessInputTypeFromFile(TFile *inpF) { const std::string NEUT_TreeName = "neuttree"; const std::string NuWro_TreeName = "treeout"; const std::string GENIE_TreeName = "gtree"; const std::string GiBUU_TreeName = "giRooTracker"; if (!inpF) { return kInvalid_Input; } TTree *NEUT_Input = dynamic_cast(inpF->Get(NEUT_TreeName.c_str())); if (NEUT_Input) { return kNEUT_Input; } TTree *NUWRO_Input = dynamic_cast(inpF->Get(NuWro_TreeName.c_str())); if (NUWRO_Input) { return kNUWRO_Input; } TTree *GENIE_Input = dynamic_cast(inpF->Get(GENIE_TreeName.c_str())); if (GENIE_Input) { return kGENIE_Input; } TTree *GiBUU_Input = dynamic_cast(inpF->Get(GiBUU_TreeName.c_str())); if (GiBUU_Input) { return kGiBUU_Input; } return kInvalid_Input; } std::string PrependGuessedInputTypeToName(std::string const &inpFName) { // If it already has a name. if (inpFName.find(":") != std::string::npos) { return inpFName; } TFile *inpF = TFile::Open(inpFName.c_str(), "READ"); if (!inpF || !inpF->IsOpen()) { - QTHROW("Couldn't open \"" << inpFName << "\" for reading."); + NUIS_ABORT("Couldn't open \"" << inpFName << "\" for reading."); } InputType iType = GuessInputTypeFromFile(inpF); if (iType == kInvalid_Input) { - QTHROW("Couldn't determine input type from file: " << inpFName << "."); + NUIS_ABORT("Couldn't determine input type from file: " << inpFName << "."); } inpF->Close(); delete inpF; switch (iType) { case kNEUT_Input: { return "NEUT:" + inpFName; } case kNUWRO_Input: { return "NUWRO:" + inpFName; } case kGENIE_Input: { return "GENIE:" + inpFName; } case kGiBUU_Input: { return "GiBUU:" + inpFName; } default: { - QTHROW("Input type from file: " << inpFName << " was invalid."); + NUIS_ABORT("Input type from file: " << inpFName << " was invalid."); throw; } } } } // namespace InputUtils diff --git a/src/InputHandler/NEUTInputHandler.cxx b/src/InputHandler/NEUTInputHandler.cxx index 94a616a..e086bb0 100644 --- a/src/InputHandler/NEUTInputHandler.cxx +++ b/src/InputHandler/NEUTInputHandler.cxx @@ -1,516 +1,516 @@ #ifdef __NEUT_ENABLED__ #include "NEUTInputHandler.h" #include "InputUtils.h" NEUTGeneratorInfo::~NEUTGeneratorInfo() { DeallocateParticleStack(); } void NEUTGeneratorInfo::AddBranchesToTree(TTree *tn) { tn->Branch("NEUTParticleN", fNEUTParticleN, "NEUTParticleN/I"); tn->Branch("NEUTParticleStatusCode", fNEUTParticleStatusCode, "NEUTParticleStatusCode[NEUTParticleN]/I"); tn->Branch("NEUTParticleAliveCode", fNEUTParticleAliveCode, "NEUTParticleAliveCode[NEUTParticleN]/I"); } void NEUTGeneratorInfo::SetBranchesFromTree(TTree *tn) { tn->SetBranchAddress("NEUTParticleN", &fNEUTParticleN); tn->SetBranchAddress("NEUTParticleStatusCode", &fNEUTParticleStatusCode); tn->SetBranchAddress("NEUTParticleAliveCode", &fNEUTParticleAliveCode); } void NEUTGeneratorInfo::AllocateParticleStack(int stacksize) { fNEUTParticleN = 0; fNEUTParticleStatusCode = new int[stacksize]; fNEUTParticleStatusCode = new int[stacksize]; } void NEUTGeneratorInfo::DeallocateParticleStack() { delete fNEUTParticleStatusCode; delete fNEUTParticleAliveCode; } void NEUTGeneratorInfo::FillGeneratorInfo(NeutVect *nevent) { Reset(); for (int i = 0; i < nevent->Npart(); i++) { fNEUTParticleStatusCode[i] = nevent->PartInfo(i)->fStatus; fNEUTParticleAliveCode[i] = nevent->PartInfo(i)->fIsAlive; fNEUTParticleN++; } } void NEUTGeneratorInfo::Reset() { for (int i = 0; i < fNEUTParticleN; i++) { fNEUTParticleStatusCode[i] = -1; fNEUTParticleAliveCode[i] = 9; } fNEUTParticleN = 0; } NEUTInputHandler::NEUTInputHandler(std::string const &handle, std::string const &rawinputs) { - QLOG(SAM, "Creating NEUTInputHandler : " << handle); + NUIS_LOG(SAM, "Creating NEUTInputHandler : " << handle); // Run a joint input handling fName = handle; // Setup the TChain fNEUTTree = new TChain("neuttree"); fSaveExtra = FitPar::Config().GetParB("SaveExtraNEUT"); fCacheSize = FitPar::Config().GetParI("CacheSize"); fMaxEvents = FitPar::Config().GetParI("MAXEVENTS"); // Loop over all inputs and grab flux, eventhist, and nevents std::vector inputs = InputUtils::ParseInputFileList(rawinputs); for (size_t inp_it = 0; inp_it < inputs.size(); ++inp_it) { // Open File for histogram access TFile *inp_file = new TFile(inputs[inp_it].c_str(), "READ"); if (!inp_file or inp_file->IsZombie()) { - QTHROW("NEUT File IsZombie() at : '" + NUIS_ABORT("NEUT File IsZombie() at : '" << inputs[inp_it] << "'" << std::endl << "Check that your file paths are correct and the file exists!" << std::endl << "$ ls -lh " << inputs[inp_it]); } // Get Flux/Event hist TH1D *fluxhist = (TH1D *)inp_file->Get( (PlotUtils::GetObjectWithName(inp_file, "flux")).c_str()); TH1D *eventhist = (TH1D *)inp_file->Get( (PlotUtils::GetObjectWithName(inp_file, "evt")).c_str()); if (!fluxhist or !eventhist) { - QERROR(FTL, "Input File Contents: " << inputs[inp_it]); + NUIS_ERR(FTL, "Input File Contents: " << inputs[inp_it]); inp_file->ls(); - QTHROW("NEUT FILE doesn't contain flux/xsec info. You may have to " + NUIS_ABORT("NEUT FILE doesn't contain flux/xsec info. You may have to " "regenerate your MC!"); } // Get N Events TTree *neuttree = (TTree *)inp_file->Get("neuttree"); if (!neuttree) { - QERROR(FTL, "neuttree not located in NEUT file: " << inputs[inp_it]); - QTHROW("Check your inputs, they may need to be completely regenerated!"); + NUIS_ERR(FTL, "neuttree not located in NEUT file: " << inputs[inp_it]); + NUIS_ABORT("Check your inputs, they may need to be completely regenerated!"); throw; } int nevents = neuttree->GetEntries(); if (nevents <= 0) { - QTHROW("Trying to a TTree with " + NUIS_ABORT("Trying to a TTree with " << nevents << " to TChain from : " << inputs[inp_it]); } // Register input to form flux/event rate hists RegisterJointInput(inputs[inp_it], nevents, fluxhist, eventhist); // Add To TChain fNEUTTree->AddFile(inputs[inp_it].c_str()); } // Registor all our file inputs SetupJointInputs(); // Assign to tree fEventType = kNEUT; fNeutVect = NULL; fNEUTTree->SetBranchAddress("vectorbranch", &fNeutVect); fNEUTTree->GetEntry(0); // Create Fit Event fNUISANCEEvent = new FitEvent(); fNUISANCEEvent->SetNeutVect(fNeutVect); if (fSaveExtra) { fNeutInfo = new NEUTGeneratorInfo(); fNUISANCEEvent->AddGeneratorInfo(fNeutInfo); } fNUISANCEEvent->HardReset(); }; NEUTInputHandler::~NEUTInputHandler(){ // if (fNEUTTree) delete fNEUTTree; // if (fNeutVect) delete fNeutVect; // if (fNeutInfo) delete fNeutInfo; }; void NEUTInputHandler::CreateCache() { if (fCacheSize > 0) { // fNEUTTree->SetCacheEntryRange(0, fNEvents); fNEUTTree->AddBranchToCache("vectorbranch", 1); fNEUTTree->SetCacheSize(fCacheSize); } } void NEUTInputHandler::RemoveCache() { // fNEUTTree->SetCacheEntryRange(0, fNEvents); fNEUTTree->AddBranchToCache("vectorbranch", 0); fNEUTTree->SetCacheSize(0); } FitEvent *NEUTInputHandler::GetNuisanceEvent(const UInt_t entry, const bool lightweight) { // Catch too large entries if (entry >= (UInt_t)fNEvents) return NULL; // Read Entry from TTree to fill NEUT Vect in BaseFitEvt; fNEUTTree->GetEntry(entry); // Run NUISANCE Vector Filler if (!lightweight) { CalcNUISANCEKinematics(); } #ifdef __PROB3PP_ENABLED__ else { UInt_t npart = fNeutVect->Npart(); for (size_t i = 0; i < npart; i++) { NeutPart *part = fNUISANCEEvent->fNeutVect->PartInfo(i); if ((part->fIsAlive == false) && (part->fStatus == -1) && std::count(PhysConst::pdg_neutrinos, PhysConst::pdg_neutrinos + 4, part->fPID)) { fNUISANCEEvent->probe_E = part->fP.T(); fNUISANCEEvent->probe_pdg = part->fPID; break; } else { continue; } } } #endif // Setup Input scaling for joint inputs fNUISANCEEvent->InputWeight = GetInputWeight(entry); // Return event pointer return fNUISANCEEvent; } // From NEUT neutclass/neutpart.h // Bool_t fIsAlive; // Particle should be tracked or not // ( in the detector simulator ) // // Int_t fStatus; // Status flag of this particle // -2: Non existing particle // -1: Initial state particle // 0: Normal // 1: Decayed to the other particle // 2: Escaped from the detector // 3: Absorped // 4: Charge exchanged // 5: Pauli blocked // 6: N/A // 7: Produced child particles // 8: Inelastically scattered // int NEUTInputHandler::GetNeutParticleStatus(NeutPart *part) { // State int state = kUndefinedState; // Remove Pauli blocked events, probably just single pion events if (part->fStatus == 5) { state = kFSIState; // fStatus == -1 means initial state } else if (part->fIsAlive == false && part->fStatus == -1) { state = kInitialState; // NEUT has a bit of a strange convention for fIsAlive and fStatus // combinations // for NC and neutrino particle isAlive true/false and status 2 means // final state particle // for other particles in NC status 2 means it's an FSI particle // for CC it means it was an FSI particle } else if (part->fStatus == 2) { // NC case is a little strange... The outgoing neutrino might be alive or // not alive. Remaining particles with status 2 are FSI particles that // reinteracted if (abs(fNeutVect->Mode) > 30 && (abs(part->fPID) == 16 || abs(part->fPID) == 14 || abs(part->fPID) == 12)) { state = kFinalState; // The usual CC case } else if (part->fIsAlive == true) { state = kFSIState; } } else if (part->fIsAlive == true && part->fStatus == 2 && (abs(part->fPID) == 16 || abs(part->fPID) == 14 || abs(part->fPID) == 12)) { state = kFinalState; } else if (part->fIsAlive == true && part->fStatus == 0) { state = kFinalState; } else if (!part->fIsAlive && (part->fStatus == 1 || part->fStatus == 3 || part->fStatus == 4 || part->fStatus == 7 || part->fStatus == 8)) { state = kFSIState; // There's one hyper weird case where fStatus = -3. This apparently // corresponds to a nucleon being ejected via pion FSI when there is "data // available" } else if (!part->fIsAlive && (part->fStatus == -3)) { state = kUndefinedState; // NC neutrino outgoing } else if (!part->fIsAlive && part->fStatus == 0 && (abs(part->fPID) == 16 || abs(part->fPID) == 14 || abs(part->fPID) == 12)) { state = kFinalState; // Warn if we still find alive particles without classifying them } else if (part->fIsAlive == true) { - QTHROW("Undefined NEUT state " + NUIS_ABORT("Undefined NEUT state " << " Alive: " << part->fIsAlive << " Status: " << part->fStatus << " PDG: " << part->fPID); // Warn if we find dead particles that we haven't classified } else { - QTHROW("Undefined NEUT state " + NUIS_ABORT("Undefined NEUT state " << " Alive: " << part->fIsAlive << " Status: " << part->fStatus << " PDG: " << part->fPID); } return state; } void NEUTInputHandler::CalcNUISANCEKinematics() { // Reset all variables fNUISANCEEvent->ResetEvent(); // Fill Globals fNUISANCEEvent->Mode = fNeutVect->Mode; fNUISANCEEvent->fEventNo = fNeutVect->EventNo; fNUISANCEEvent->fTargetA = fNeutVect->TargetA; fNUISANCEEvent->fTargetZ = fNeutVect->TargetZ; fNUISANCEEvent->fTargetH = fNeutVect->TargetH; fNUISANCEEvent->fBound = bool(fNeutVect->Ibound); if (fNUISANCEEvent->fBound) { fNUISANCEEvent->fTargetPDG = TargetUtils::GetTargetPDGFromZA( fNUISANCEEvent->fTargetZ, fNUISANCEEvent->fTargetA); } else { fNUISANCEEvent->fTargetPDG = 1000010010; } // Check Particle Stack UInt_t npart = fNeutVect->Npart(); UInt_t kmax = fNUISANCEEvent->kMaxParticles; if (npart > kmax) { - QERROR(WRN,"NEUT has too many particles. Expanding stack."); + NUIS_ERR(WRN,"NEUT has too many particles. Expanding stack."); fNUISANCEEvent->ExpandParticleStack(npart); } int nprimary = fNeutVect->Nprimary(); // Fill Particle Stack for (size_t i = 0; i < npart; i++) { // Get Current Count int curpart = fNUISANCEEvent->fNParticles; // Get NEUT Particle NeutPart *part = fNeutVect->PartInfo(i); // State int state = GetNeutParticleStatus(part); // Remove Undefined if (kRemoveUndefParticles && state == kUndefinedState) continue; // Remove FSI if (kRemoveFSIParticles && state == kFSIState) continue; // Remove Nuclear if (kRemoveNuclearParticles && (state == kNuclearInitial || state == kNuclearRemnant)) continue; // State fNUISANCEEvent->fParticleState[curpart] = state; // Is the paricle associated with the primary vertex? bool primary = false; // NEUT events are just popped onto the stack as primary, then continues to // be non-primary if (i < nprimary) primary = true; fNUISANCEEvent->fPrimaryVertex[curpart] = primary; // Mom fNUISANCEEvent->fParticleMom[curpart][0] = part->fP.X(); fNUISANCEEvent->fParticleMom[curpart][1] = part->fP.Y(); fNUISANCEEvent->fParticleMom[curpart][2] = part->fP.Z(); fNUISANCEEvent->fParticleMom[curpart][3] = part->fP.T(); // PDG fNUISANCEEvent->fParticlePDG[curpart] = part->fPID; // Add up particle count fNUISANCEEvent->fNParticles++; } // Save Extra Generator Info if (fSaveExtra) { fNeutInfo->FillGeneratorInfo(fNeutVect); } // Run Initial, FSI, Final, Other ordering. fNUISANCEEvent->OrderStack(); FitParticle *ISAnyLepton = fNUISANCEEvent->GetHMISAnyLeptons(); if (ISAnyLepton) { fNUISANCEEvent->probe_E = ISAnyLepton->E(); fNUISANCEEvent->probe_pdg = ISAnyLepton->PDG(); } return; } void NEUTUtils::FillNeutCommons(NeutVect *nvect) { // WARNING: This has only been implemented for a neuttree and not GENIE // This should be kept in sync with T2KNIWGUtils::GetNIWGEvent(TTree) // NEUT version info. Can't get it to compile properly with this yet // neutversion_.corev = nvect->COREVer; // neutversion_.nucev = nvect->NUCEVer; // neutversion_.nuccv = nvect->NUCCVer; // Documentation: See nework.h nework_.modene = nvect->Mode; nework_.numne = nvect->Npart(); #ifdef NEUT_COMMON_QEAV nemdls_.mdlqeaf = nvect->QEAVForm; #else nemdls_.mdlqeaf = nvect->QEVForm; #endif nemdls_.mdlqe = nvect->QEModel; nemdls_.mdlspi = nvect->SPIModel; nemdls_.mdldis = nvect->DISModel; nemdls_.mdlcoh = nvect->COHModel; neutcoh_.necohepi = nvect->COHModel; nemdls_.xmaqe = nvect->QEMA; nemdls_.xmvqe = nvect->QEMV; nemdls_.kapp = nvect->KAPPA; // nemdls_.sccfv = SCCFVdef; // nemdls_.sccfa = SCCFAdef; // nemdls_.fpqe = FPQEdef; nemdls_.xmaspi = nvect->SPIMA; nemdls_.xmvspi = nvect->SPIMV; nemdls_.xmares = nvect->RESMA; nemdls_.xmvres = nvect->RESMV; neut1pi_.xmanffres = nvect->SPIMA; neut1pi_.xmvnffres = nvect->SPIMV; neut1pi_.xmarsres = nvect->RESMA; neut1pi_.xmvrsres = nvect->RESMV; neut1pi_.neiff = nvect->SPIForm; neut1pi_.nenrtype = nvect->SPINRType; neut1pi_.rneca5i = nvect->SPICA5I; neut1pi_.rnebgscl = nvect->SPIBGScale; nemdls_.xmacoh = nvect->COHMA; nemdls_.rad0nu = nvect->COHR0; // nemdls_.fa1coh = nvect->COHA1err; // nemdls_.fb1coh = nvect->COHb1err; // neutdis_.nepdf = NEPDFdef; // neutdis_.nebodek = NEBODEKdef; neutcard_.nefrmflg = nvect->FrmFlg; neutcard_.nepauflg = nvect->PauFlg; neutcard_.nenefo16 = nvect->NefO16; neutcard_.nemodflg = nvect->ModFlg; // neutcard_.nenefmodl = 1; // neutcard_.nenefmodh = 1; // neutcard_.nenefkinh = 1; // neutpiabs_.neabspiemit = 1; nenupr_.iformlen = nvect->FormLen; neutpiless_.ipilessdcy = nvect->IPilessDcy; neutpiless_.rpilessdcy = nvect->RPilessDcy; neutpiless_.ipilessdcy = nvect->IPilessDcy; neutpiless_.rpilessdcy = nvect->RPilessDcy; neffpr_.fefqe = nvect->NuceffFactorPIQE; neffpr_.fefqeh = nvect->NuceffFactorPIQEH; neffpr_.fefinel = nvect->NuceffFactorPIInel; neffpr_.fefabs = nvect->NuceffFactorPIAbs; neffpr_.fefcx = nvect->NuceffFactorPICX; neffpr_.fefcxh = nvect->NuceffFactorPICXH; neffpr_.fefcoh = nvect->NuceffFactorPICoh; neffpr_.fefqehf = nvect->NuceffFactorPIQEHKin; neffpr_.fefcxhf = nvect->NuceffFactorPICXKin; neffpr_.fefcohf = nvect->NuceffFactorPIQELKin; for (int i = 0; i < nework_.numne; i++) { nework_.ipne[i] = nvect->PartInfo(i)->fPID; nework_.pne[i][0] = (float)nvect->PartInfo(i)->fP.X() / 1000; // VC(NE)WORK in M(G)eV nework_.pne[i][1] = (float)nvect->PartInfo(i)->fP.Y() / 1000; // VC(NE)WORK in M(G)eV nework_.pne[i][2] = (float)nvect->PartInfo(i)->fP.Z() / 1000; // VC(NE)WORK in M(G)eV } // fsihist.h // neutroot fills a dummy object for events with no FSI to prevent memory leak // when // reading the TTree, so check for it here if ((int)nvect->NfsiVert() == 1) { // An event with FSI must have at least two vertices // if (nvect->NfsiPart()!=1 || nvect->Fsiprob!=-1) // ERR(WRN) << "T2KNeutUtils::fill_neut_commons(TTree) NfsiPart!=1 or // Fsiprob!=-1 when NfsiVert==1" << std::endl; fsihist_.nvert = 0; fsihist_.nvcvert = 0; fsihist_.fsiprob = 1; } else { // Real FSI event fsihist_.nvert = (int)nvect->NfsiVert(); for (int ivert = 0; ivert < fsihist_.nvert; ivert++) { fsihist_.iflgvert[ivert] = nvect->FsiVertInfo(ivert)->fVertID; fsihist_.posvert[ivert][0] = (float)nvect->FsiVertInfo(ivert)->fPos.X(); fsihist_.posvert[ivert][1] = (float)nvect->FsiVertInfo(ivert)->fPos.Y(); fsihist_.posvert[ivert][2] = (float)nvect->FsiVertInfo(ivert)->fPos.Z(); } fsihist_.nvcvert = nvect->NfsiPart(); for (int ip = 0; ip < fsihist_.nvcvert; ip++) { fsihist_.abspvert[ip] = (float)nvect->FsiPartInfo(ip)->fMomLab; fsihist_.abstpvert[ip] = (float)nvect->FsiPartInfo(ip)->fMomNuc; fsihist_.ipvert[ip] = nvect->FsiPartInfo(ip)->fPID; fsihist_.iverti[ip] = nvect->FsiPartInfo(ip)->fVertStart; fsihist_.ivertf[ip] = nvect->FsiPartInfo(ip)->fVertEnd; fsihist_.dirvert[ip][0] = (float)nvect->FsiPartInfo(ip)->fDir.X(); fsihist_.dirvert[ip][1] = (float)nvect->FsiPartInfo(ip)->fDir.Y(); fsihist_.dirvert[ip][2] = (float)nvect->FsiPartInfo(ip)->fDir.Z(); } fsihist_.fsiprob = nvect->Fsiprob; } neutcrscom_.crsx = nvect->Crsx; neutcrscom_.crsy = nvect->Crsy; neutcrscom_.crsz = nvect->Crsz; neutcrscom_.crsphi = nvect->Crsphi; neutcrscom_.crsq2 = nvect->Crsq2; neuttarget_.numbndn = nvect->TargetA - nvect->TargetZ; neuttarget_.numbndp = nvect->TargetZ; neuttarget_.numfrep = nvect->TargetH; neuttarget_.numatom = nvect->TargetA; posinnuc_.ibound = nvect->Ibound; // put empty nucleon FSI history (since it is not saved in the NeutVect // format) // Comment out as NEUT does not have the necessary proton FSI information yet // nucleonfsihist_.nfnvert = 0; // nucleonfsihist_.nfnstep = 0; } #endif diff --git a/src/InputHandler/NUANCEInputHandler.cxx b/src/InputHandler/NUANCEInputHandler.cxx index c11fd23..b2a8668 100644 --- a/src/InputHandler/NUANCEInputHandler.cxx +++ b/src/InputHandler/NUANCEInputHandler.cxx @@ -1,937 +1,937 @@ #ifdef __NUANCE_ENABLED__ #include "NUANCEInputHandler.h" #include "InputUtils.h" NUANCEGeneratorInfo::~NUANCEGeneratorInfo() { DeallocateParticleStack(); } void NUANCEGeneratorInfo::AddBranchesToTree(TTree *tn) { // tn->Branch("NEUTParticleN", fNEUTParticleN, "NEUTParticleN/I"); // tn->Branch("NEUTParticleStatusCode", fNEUTParticleStatusCode, // "NEUTParticleStatusCode[NEUTParticleN]/I"); // tn->Branch("NEUTParticleAliveCode", fNEUTParticleAliveCode, // "NEUTParticleAliveCode[NEUTParticleN]/I"); } void NUANCEGeneratorInfo::SetBranchesFromTree(TTree *tn) { // tn->SetBranchAddress("NEUTParticleN", &fNEUTParticleN ); // tn->SetBranchAddress("NEUTParticleStatusCode", &fNEUTParticleStatusCode ); // tn->SetBranchAddress("NEUTParticleAliveCode", &fNEUTParticleAliveCode ); } void NUANCEGeneratorInfo::AllocateParticleStack(int stacksize) { // fNEUTParticleN = 0; // fNEUTParticleStatusCode = new int[stacksize]; // fNEUTParticleStatusCode = new int[stacksize]; } void NUANCEGeneratorInfo::DeallocateParticleStack() { // delete fNEUTParticleStatusCode; // delete fNEUTParticleAliveCode; } void NUANCEGeneratorInfo::FillGeneratorInfo(NuanceEvent *nevent) { Reset(); // for (int i = 0; i < nevent->Npart(); i++) { // fNEUTParticleStatusCode[i] = nevent->PartInfo(i)->fStatus; // fNEUTParticleAliveCode[i] = nevent->PartInfo(i)->fIsAlive; // fNEUTParticleN++; // } } void NUANCEGeneratorInfo::Reset() { // for (int i = 0; i < fNEUTParticleN; i++) { // fNEUTParticleStatusCode[i] = -1; // fNEUTParticleAliveCode[i] = 9; // } // fNEUTParticleN = 0; } NUANCEInputHandler::NUANCEInputHandler(std::string const &handle, std::string const &rawinputs) { - QLOG(SAM, "Creating NUANCEInputHandler : " << handle); + NUIS_LOG(SAM, "Creating NUANCEInputHandler : " << handle); // Run a joint input handling fName = handle; fSaveExtra = FitPar::Config().GetParB("SaveExtraNUANCE"); fCacheSize = FitPar::Config().GetParI("CacheSize"); fMaxEvents = FitPar::Config().GetParI("MAXEVENTS"); // Parse Inputs std::vector inputs = InputUtils::ParseInputFileList(rawinputs); if (inputs.size() > 1) { - QTHROW("NUANCE is not currently setup to handle joint inputs sorry!" + NUIS_ABORT("NUANCE is not currently setup to handle joint inputs sorry!" << std::endl << "If you know how to correctly normalise the events for this" << " please let us know!"); } // Read in NUANCE Tree fNUANCETree = new TChain("h3"); fNUANCETree->AddFile(rawinputs.c_str()); // Get entries and fNuwroEvent int nevents = fNUANCETree->GetEntries(); double EnuMin = 0.0; double EnuMax = 1000.0; TH1D *fluxhist = new TH1D((fName + "_FLUX").c_str(), (fName + "_FLUX").c_str(), 100, EnuMin, EnuMax); for (int i = 0; i < fluxhist->GetNbinsX(); i++) { fluxhist->SetBinContent(i + 1, 1.0); } fluxhist->Scale(1.0 / fluxhist->Integral()); TH1D *eventhist = new TH1D((fName + "_EVT").c_str(), (fName + "_EVT").c_str(), 100, EnuMin, EnuMax); for (int i = 0; i < fluxhist->GetNbinsX(); i++) { eventhist->SetBinContent(i + 1, 1.0); } eventhist->Scale(1.0 / eventhist->Integral()); RegisterJointInput(rawinputs, nevents, fluxhist, eventhist); SetupJointInputs(); // Setup Reader fNuanceEvent = new NuanceEvent(); fNuanceEvent->SetBranchAddresses(fNUANCETree); fNUANCETree->GetEntry(0); // Setup Event in FitEvent fNUISANCEEvent = new FitEvent(); fNUISANCEEvent->SetNuanceEvent(fNuanceEvent); // Setup extra if needed if (fSaveExtra) { - QTHROW("NO SAVEExtra Implemented for NUANCE YET!"); + NUIS_ABORT("NO SAVEExtra Implemented for NUANCE YET!"); // fNuanceInfo = new NUANCEGeneratorInfo(); // fNUISANCEEvent->AddGeneratorInfo(fNuanceInfo); } }; NUANCEInputHandler::~NUANCEInputHandler() { if (fNuanceEvent) delete fNuanceEvent; if (fNUANCETree) delete fNUANCETree; // if (fNuanceInfo) delete fNuanceInfo; } void NUANCEInputHandler::CreateCache() { if (fCacheSize > 0) { fNUANCETree->SetCacheEntryRange(0, fNEvents); fNUANCETree->AddBranchToCache("h3", 1); fNUANCETree->SetCacheSize(fCacheSize); } } void NUANCEInputHandler::RemoveCache() { fNUANCETree->SetCacheEntryRange(0, fNEvents); fNUANCETree->AddBranchToCache("h3", 0); fNUANCETree->SetCacheSize(0); } FitEvent *NUANCEInputHandler::GetNuisanceEvent(const UInt_t entry, const bool lightweight) { // Check out of bounds if (entry >= (UInt_t)fNEvents) return NULL; // Read Entry from TTree to fill NEUT Vect in BaseFitEvt; fNUANCETree->GetEntry(entry); // Setup Input scaling for joint inputs fNUISANCEEvent->InputWeight = GetInputWeight(entry); // Run NUISANCE Vector Filler if (!lightweight) { CalcNUISANCEKinematics(); } return fNUISANCEEvent; } void NUANCEInputHandler::CalcNUISANCEKinematics() { // Reset all variables fNUISANCEEvent->ResetEvent(); // Get shortened pointer FitEvent *evt = fNUISANCEEvent; // Fill Global evt->Mode = ConvertNuanceMode(fNuanceEvent); evt->fEventNo = 0.0; evt->fTotCrs = 1.0; evt->fTargetA = 0.0; evt->fTargetZ = 0.0; evt->fTargetH = 0; evt->fBound = 0.0; // Fill particle Stack evt->fNParticles = 0; // Check Particle Stack UInt_t npart = 2 + fNuanceEvent->n_leptons + fNuanceEvent->n_hadrons; UInt_t kmax = evt->kMaxParticles; if (npart > kmax) { - QERROR(FTL, "NUANCE has too many particles"); - QERROR(FTL, "npart=" << npart << " kMax=" << kmax); + NUIS_ERR(FTL, "NUANCE has too many particles"); + NUIS_ERR(FTL, "npart=" << npart << " kMax=" << kmax); throw; } // Fill Neutrino evt->fParticleState[0] = kInitialState; evt->fParticleMom[0][0] = fNuanceEvent->p_neutrino[0]; evt->fParticleMom[0][1] = fNuanceEvent->p_neutrino[1]; evt->fParticleMom[0][2] = fNuanceEvent->p_neutrino[2]; evt->fParticleMom[0][3] = fNuanceEvent->p_neutrino[3]; evt->fParticlePDG[0] = fNuanceEvent->neutrino; // Fill Target Nucleon evt->fParticleState[1] = kInitialState; evt->fParticleMom[1][0] = fNuanceEvent->p_targ[0]; evt->fParticleMom[1][1] = fNuanceEvent->p_targ[1]; evt->fParticleMom[1][2] = fNuanceEvent->p_targ[2]; evt->fParticleMom[1][3] = fNuanceEvent->p_targ[3]; evt->fParticlePDG[1] = fNuanceEvent->target; evt->fNParticles = 2; // Fill Outgoing Leptons for (int i = 0; i < fNuanceEvent->n_leptons; i++) { evt->fParticleState[evt->fNParticles] = kFinalState; evt->fParticleMom[evt->fNParticles][0] = fNuanceEvent->p_lepton[i][0]; evt->fParticleMom[evt->fNParticles][1] = fNuanceEvent->p_lepton[i][1]; evt->fParticleMom[evt->fNParticles][2] = fNuanceEvent->p_lepton[i][2]; evt->fParticleMom[evt->fNParticles][3] = fNuanceEvent->p_lepton[i][3]; evt->fParticlePDG[evt->fNParticles] = fNuanceEvent->lepton[i]; evt->fNParticles++; } // Fill Outgoing Hadrons for (int i = 0; i < fNuanceEvent->n_hadrons; i++) { evt->fParticleState[evt->fNParticles] = kFinalState; evt->fParticleMom[evt->fNParticles][0] = fNuanceEvent->p_hadron[i][0]; evt->fParticleMom[evt->fNParticles][1] = fNuanceEvent->p_hadron[i][1]; evt->fParticleMom[evt->fNParticles][2] = fNuanceEvent->p_hadron[i][2]; evt->fParticleMom[evt->fNParticles][3] = fNuanceEvent->p_hadron[i][3]; evt->fParticlePDG[evt->fNParticles] = fNuanceEvent->hadron[i]; evt->fNParticles++; } // Save Extra info if (fSaveExtra) { // fNuanceInfo->FillGeneratorInfo(fNuanceEvent); } // Run Initial, FSI, Final, Other ordering. fNUISANCEEvent->OrderStack(); return; } void NUANCEInputHandler::Print() {} int NUANCEInputHandler::ConvertNuanceMode(NuanceEvent *evt) { int ch = evt->channel; int sg = 1; if (evt->neutrino < 0) sg = -1; switch (ch) { // 1 NUANCE CCQE -> NEUT CCQE 1 case 1: return sg * 1; // 2 NUANCE NCEL -> NEUT NCEL 51,52 -> Set from whether target is p or n case 2: if (evt->target == 2212) return sg * 51; else return sg * 52; // 3 NUANCE CCPIP -> NEUT CCPIP 11 case 3: return sg * 11; // 4 NUANCE CCPI0 -> NEUT CCPI0 = 12 case 4: return sg * 12; // 5 NUANCE CCPIPn -> NEUT CCPIPn 13 case 5: return sg * 13; // 6 NUANCE NCpPI0 -> NEUT NCpPI0 32 case 6: return sg * 32; // 7 NUANCE NCpPI+ -> NEUT NCpPI+ 34 case 7: return sg * 34; // 8 NUANCE NCnPI0 -> NEUT NCnPI0 31 case 8: return sg * 31; // 9 NUANCE NCnPIM -> NEUT NCnPIM 33 case 9: return sg * 33; // 10 NUANCE CCPIP -> NEUT CCPIP -11 case 10: return sg * 11; // 11 NUANCE CCPI0 -> NEUT CCPI0 -12 case 11: return sg * 12; // 12 NUANCE CCPIPn -> NEUT CCPIPn 13 case 12: return sg * 13; // 13 NUANCE NCpPI0 -> NEUT NCnPI0 -32 case 13: return sg * 32; // 14 NUANCE NCpPI+ -> NEUT NCpPI+ -34 case 14: return sg * 34; // 15 NUANCE NCnPI0 -> NEUT NCnPI0 -31 case 15: return sg * 31; // 16 NUANCE NCnPIM -> NEUT NCnPIM -33 case 16: return sg * 33; // 17 NUANCE -> NEUT 21 CC MULTIPI case 17: return sg * 21; // 18 NUANCE -> NEUT 21 CC MULTIPI case 18: return sg * 21; // 19 NUANCE -> NEUT 21 CC MULTIPI case 19: return sg * 21; // 20 NUANCE -> NEUT 21 CC MULTIPI case 20: return sg * 21; // 21 NUANCE -> NEUT 21 CC MULTIPI case 21: return sg * 21; // 22 NUANCE -> NEUT 41 NC MULTIPI case 22: return sg * 41; // 23 NUANCE -> NEUT 41 NC MULTIPI case 23: return sg * 41; // 24 NUANCE -> NEUT 41 NC MULTIPI case 24: return sg * 41; // 25 NUANCE -> NEUT 41 NC MULTIPI case 25: return sg * 41; // 26 NUANCE -> NEUT 41 NC MULTIPI case 26: return sg * 41; // 27 NUANCE -> NEUT -41 "NC (1.3 < W < 2 GeV) case 27: return sg * 41; // 28 NUANCE -> NEUT -21 CC (1.3 < W < 2 GeV) case 28: return sg * 21; // 29 NUANCE -> NEUT -21 CC (1.3 < W < 2 GeV) case 29: return sg * 21; // 30 NUANCE -> NEUT -21 CC (1.3 < W < 2 GeV) case 30: return sg * 21; // 31 NUANCE -> NEUT -21 CC (1.3 < W < 2 GeV) case 31: return sg * 21; // 32 NUANCE -> NEUT -21 CC (1.3 < W < 2 GeV) case 32: return sg * 21; // 33 NUANCE -> NEUT -41 "NC (1.3 < W < 2 GeV) case 33: return sg * 41; // 34 NUANCE -> NEUT -41 "NC (1.3 < W < 2 GeV) case 34: return sg * 41; // 35 NUANCE -> NEUT -41 "NC (1.3 < W < 2 GeV) case 35: return sg * 41; // 36 NUANCE -> NEUT -41 "NC (1.3 < W < 2 GeV) case 36: return sg * 41; // 37 NUANCE -> NEUT -41 "NC (1.3 < W < 2 GeV) case 37: return sg * 41; // 38 NUANCE -> NEUT -41 "NC (1.3 < W < 2 GeV) case 38: return sg * 41; // 39 NUANCE -> NEUT 22 case 39: return sg * 22; // 40 NUANCE -> NEUT 22 case 40: return sg * 22; // 41 NUANCE -> NEUT 22 case 41: return sg * 22; // 42 NUANCE -> NEUT 43 case 42: return sg * 43; // 43 NUANCE -> NEUT 43 case 43: return sg * 43; // 44 NUANCE -> NUET 42 case 44: return sg * 42; // 45 NUANCE -> NEUT -42 case 45: return sg * 42; // 46 NUANCE -> NEUT -22 case 46: return sg * 22; // 47 NUANCE -> NEUT -22 case 47: return sg * 22; // 48 NUANCE -> NEUT -22 case 48: return sg * 22; // 49 NUANCE -> NEUT -43 case 49: return sg * 43; // 50 NUANCE -> NEUT -43 case 50: return sg * 43; // 51 NUANCE -> NEUT -42 case 51: return sg * 42; // 52 NUANCE -> NEUT -42 case 52: return sg * 42; // 53 NUANCE -> NEUT 23 CC 1K case 53: return sg * 23; // 54 NUANCE -> NEUT 23 CC 1K case 54: return sg * 23; // 55 NUANCE -> NEUT 23 CC 1K case 55: return sg * 23; // 56 NUANCE -> NEUT 45 NC 1K case 56: return sg * 45; // 57 NUANCE -> NEUT 44 NC 1K case 57: return sg * 44; // 58 NUANCE -> NEUT 44 NC 1K case 58: return sg * 44; // 59 NUANCE -> NEUT 44 NC 1K case 59: return sg * 44; // 60 NUANCE -> NEUT -23 CC 1K case 60: return sg * 23; // 61 NUANCE -> NEUT -23 CC 1K case 61: return sg * 23; // 62 NUANCE -> NEUT -23 CC 1K case 62: return sg * 23; // 63 NUANCE -> NEUT -23 CC 1K case 63: return sg * 23; // 64 NUANCE -> NEUT -44 NC 1K case 64: return sg * 44; // 65 NUANCE -> NEUT -44 NC 1K case 65: return sg * 44; // 66 NUANCE -> NEUT -45 NC 1K case 66: return sg * 45; // 67 NUANCE -> NEUT 22 CC1eta case 67: return sg * 22; // 68 NUANCE -> NEUT 43 NC p eta case 68: return sg * 43; // 69 NUANCE -> NEUT 43 NC n eta case 69: return sg * 43; // 70 NUANCE -> NEUT -22 CC1eta case 70: return sg * 22; // 71 NUANCE -> NEUT -43 NC p eta case 71: return sg * 43; // 72 NUANCE -> NEUT 42 NC n eta case 72: return sg * 42; // 73 NUANCE -> NEUT 21 CC Multi Pi case 73: return sg * 21; // 74 NUANCE -> NEUT 41 NC Multi Pi case 74: return sg * 41; // 75 NUANCE -> NEUT 41 NC Multi Pi case 75: return sg * 41; // 76 NUANCE -> NEUT -21 CC Multi Pi case 76: return sg * 21; // 77 NUANCE -> NEUT -41 NC Multi Pi case 77: return sg * 41; // 78 NUANCE -> NEUT -41 NC Multi Pi case 78: return sg * 41; // 79 NUANCE -> NEUT 21 CC Multi Pi case 79: return sg * 21; // 80 NUANCE -> NEUT 21 CC Multi Pi case 80: return sg * 21; // 81 NUANCE -> NEUT 41 NC Multi Pi case 81: return sg * 41; // 82 NUANCE -> NEUT 41 NC Multi Pi case 82: return sg * 41; // 83 NUANCE -> NEUT 41 NC Multi Pi case 83: return sg * 41; // 84 NUANCE -> NEUT 41 NC Multi Pi case 84: return sg * 84; // 85 NUANCE -> NEUT -21 CC Multi Pi case 85: return sg * 21; // 86 NUANCE -> NEUT -21 CC Multi Pi case 86: return sg * 21; // 87 NUANCE -> NEUT -41 CC Multi Pi case 87: return sg * 41; // 88 NUANCE -> NEUT -41 case 88: return sg * 41; // 89 NUANCE -> NEUT -41 case 89: return sg * 41; // 90 NUANCE -> NEUT -41 case 90: return sg * 41; // 91 NUANCE -> NEUT 26 CC DIS case 91: return sg * 26; // 92 NUANCE -> NEUT 46 NC DIS case 92: return sg * 46; // 93 NUANCE -> NEUT 17 1#gamma from #Delta case 93: return sg * 17; // 94 NUANCE -> NEUT 39 1#gamma from #Delta case 94: return sg * 39; // 95 -> UNKOWN NEUT MODE case 95: return sg * 0; // 96 NUANCE -> NEUT 36 NC COH case 96: return sg * 36; // 97 NUANCE -> NEUT 16 case 97: return sg * 16; // 98 -> UNKNOWN NEUT MODE case 98: return sg * 0; // 99 -> UNKNOWN NEUT MODE case 99: return sg * 0; default: - QTHROW("Unknown Nuance Channel ID = " << ch); + NUIS_ABORT("Unknown Nuance Channel ID = " << ch); return 0; } return 0; } /* // Notes copied from NuanceChannels.pdf 1 NUANCE CCQE -> NEUT CCQE 1 CC, numu n --> mu- p Cabibbo-allowed quasi-elastic scattering from nucleons 2 NUANCE NCEL -> NEUT NCEL 51,52 -> Set from whether target is p or n NC, numu N --> num N, (N=n,p) (quasi)-elastic scattering from nucleons 3 NUANCE CCPIP -> NEUT CCPIP 11 CC, numu p --> mu- p pi+ resonant single pion production 4 NUANCE CCPI0 -> NEUT CCPI0 = 12 CC, numu n --> mu- p pi0 resonant single pion production 5 NUANCE CCPIPn -> NEUT CCPIPn 13 CC, numu n --> mu- n pi+ resonant single pion production 6 NUANCE NCpPI0 -> NEUT NCpPI0 32 NC, numu p --> numu p pi0 resonant single pion production 7 NUANCE NCpPI+ -> NEUT NCpPI+ 34 NC, numu p --> numu n pi+ resonant single pion production 8 NUANCE NCnPI0 -> NEUT NCnPI0 31 NC, numu n --> numu n pi0 resonant single pion production 9 NUANCE NCnPIM -> NEUT NCnPIM 33 NC, numu n --> numu p pi- resonant single pion production 10 NUANCE CCPIP -> NEUT CCPIP -11 CC, numubar p --> mu- p pi+ resonant single pion production 11 NUANCE CCPI0 -> NEUT CCPI0 -12 CC, numubar n --> mu- p pi0 resonant single pion production 12 NUANCE CCPIPn -> NEUT CCPIPn -13 CC, numubar n --> mu- n pi+ resonant single pion production 13 NUANCE NCpPI0 -> NEUT NCnPI0 -32 NC, numubar p --> numubar p pi0 resonant single pion production 14 NUANCE NCpPI+ -> NEUT NCpPI+ -34 NC, numubar p --> numubar n pi+ resonant single pion production 15 NUANCE NCnPI0 -> NEUT NCnPI0 -31 NC, numubar n --> numubar n pi0 resonant single pion production 16 NUANCE NCnPIM -> NEUT NCnPIM -33 NC, numubar n --> numubar p pi- resonant single pion production 17 NUANCE -> NEUT 21 CC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow l^{-} N' multi-#pi CC, numu p --> mu- Delta+ pi+ resonant processes involving more than a single pion 18 NUANCE -> NEUT 21 CC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow l^{-} N' multi-#pi CC, numu p --> mu- Delta++ pi0 resonant processes involving more than a single pion 19 NUANCE -> NEUT 21 CC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow l^{-} N' multi-#pi CC, numu n --> mu- Delta+ pi0 resonant processes involving more than a single pion 20 NUANCE -> NEUT 21 CC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow l^{-} N' multi-#pi CC, numu n --> mu- Delta0 pi+ resonant processes involving more than a single pion 21 NUANCE -> NEUT 21 CC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow l^{-} N' multi-#pi CC, numu n --> mu- Delta++ pi- resonant processes involving more than a single pion 22 NUANCE -> NEUT 41 "NC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow #nu_{l} N multi-#pi" NC, numu p+ --> numu Delta+ pi0 resonant processes involving more than a single pion 23 NUANCE -> NEUT 41 "NC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow #nu_{l} N multi-#pi" NC,numu p --> numu Delta0 pi+ resonant processes involving more than a single pion 24 NUANCE -> NEUT 41 "NC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow #nu_{l} N multi-#pi" NC, numu p --> numu Delta++ pi- resonant processes involving more than a single pion 25 NUANCE -> NEUT 41 "NC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow #nu_{l} N multi-#pi" NC, numu n --> numu Delta+ pi- resonant processes involving more than a single pion 26 NUANCE -> NEUT 41 "NC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow #nu_{l} N multi-#pi" NC, numu n --> numu Delta0 pi0 resonant processes involving more than a single pion 27 NUANCE -> NEUT -41 "NC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow #nu_{l} N multi-#pi" NC, numubar n --> numubar Delta- pi+ resonant processes involving more than a single pion 28 NUANCE -> NEUT -21 CC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow l^{-} N' multi-#pi CC, numubar p --> mu- Delta+ pi+ resonant processes involving more than a single pion 29 UANCE -> NEUT -21 CC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow l^{-} N' multi-#pi CC, numubar p --> mu- Delta++ pi0 resonant processes involving more than a single pion 30 NUANCE -> NEUT -21 CC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow l^{-} N' multi-#pi CC, numubar n --> mu- Delta+ pi0 resonant processes involving more than a single pion 31 NUANCE -> NEUT -21 CC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow l^{-} N' multi-#pi CC, numubar n --> mu- Delta0 pi+ resonant processes involving more than a single pion 32 NUANCE -> NEUT -21 CC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow l^{-} N' multi-#pi CC, numubar n --> mu- Delta++ pi- resonant processes involving more than a single pion 33 NUANCE -> NEUT -41 "NC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow #nu_{l} N multi-#pi" NC, numubar p+ --> numubar Delta+ pi0 resonant processes involving more than a single pion 34 NUANCE -> NEUT -41 "NC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow #nu_{l} N multi-#pi" NC,numubar p --> numubar Delta0 pi+ resonant processes involving more than a single pion 35 NUANCE -> NEUT -41 "NC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow #nu_{l} N multi-#pi" NC, numubar p --> numubar Delta++ pi- resonant processes involving more than a single pion 36 NUANCE -> NEUT -41 "NC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow #nu_{l} N multi-#pi" NC, numubar n --> numubar Delta+ pi- resonant processes involving more than a single pion 37 NUANCE -> NEUT -41 "NC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow #nu_{l} N multi-#pi" NC, numubar n --> numubar Delta0 pi0 resonant processes involving more than a single pion 38 NUANCE -> NEUT -41 "NC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow #nu_{l} N multi-#pi" NC, numubar n --> numubar Delta- pi+ resonant processes involving more than a single pion // RHO Production lumped in with eta production 22 CCeta 43 NCeta on p 42 NCeta on n 39 NUANCE -> NEUT 22 CC, numu p --> mu- p rho+(770) resonant processes involving more than a single pion 40 NUANCE -> NEUT 22 CC, numu n --> mu- p rho0(770) resonant processes involving more than a single pion 41 NUANCE -> NEUT 22 CC, numu n --> mu- n rho+(770) resonant processes involving more than a single pion 42 NUANCE -> NEUT 43 NC, numu p --> numu p rho0(770) resonant processes involving more than a single pion 43 NUANCE -> NEUT 43 NC, numu p --> numu n rho+(770) resonant processes involving more than a single pion 44 NUANCE -> NUET 42 NC, numu n --> numu n rho0(770) resonant processes involving more than a single pion 45 NUANCE -> NEUT -42 NC, numubar n --> numubar p rho-(770) resonant processes involving more than a single pion 46 NUANCE -> NEUT -22 CC, numubar p --> mu- p rho+(770) resonant processes involving more than a single pion 47 NUANCE -> NEUT -22 CC, numubar n --> mu- p rho0(770) resonant processes involving more than a single pion 48 NUANCE -> NEUT -22 CC, numubar n --> mu- n rho+(770) resonant processes involving more than a single pion 49 NUANCE -> NEUT -43 NC, numubar p --> numubar p rho0(770) resonant processes involving more than a single pion 50 NUANCE -> NEUT -43 NC, numubar p --> numubar n rho+(770) resonant processes involving more than a single pion 51 NUANCE -> NEUT -42 NC, numubar n --> numubar n rho0(770) resonant processes involving more than a single pion 52 NUANCE -> NEUT -42 NC, numubar n --> numubar p rho-(770) resonant processes involving more than a single pion 53 NUANCE -> NEUT 23 CC 1K: #nu_{l} n #rightarrow l^{-} #Lambda K^{+} CC, numu p --> mu- Sigma+ K+ resonant processes involving more than a single pion 54 NUANCE -> NEUT 23 CC 1K: #nu_{l} n #rightarrow l^{-} #Lambda K^{+} CC, numu n --> mu- Sigma0 K+ resonant processes involving more than a single pion 55 NUANCE -> NEUT 23 CC 1K: #nu_{l} n #rightarrow l^{-} #Lambda K^{+} CC, numu n --> mu- Sigma+ K0 resonant processes involving more than a single pion 56 NUANCE -> NEUT 45 NC 1K: #nu_{l} n #rightarrow #nu_{l} #Lambda K^{+} NC, numu p --> numu Sigma0 K+ resonant processes involving more than a single pion 57 NUANCE -> NEUT 44 NC 1K: #nu_{l} n #rightarrow #nu_{l} #Lambda K^{0} NC, numu p --> numu Sigma+ K0 resonant processes involving more than a single pion 58 NUANCE -> NEUT 44 NC 1K: #nu_{l} n #rightarrow #nu_{l} #Lambda K^{0} NC, numu n --> numu Sigma0 K0 resonant processes involving more than a single pion 59 NUANCE -> NEUT 45 NC 1K: #nu_{l} n #rightarrow #nu_{l} #Lambda K^{+} NC, numu n --> numu Sigma- K+ resonant processes involving more than a single pion 60 NUANCE -> NEUT -23 CC 1K: #nu_{l} n #rightarrow l^{-} #Lambda K^{+} CC, numubar p --> mu- Sigma+ K+ resonant processes involving more than a single pion 61 NUANCE -> NEUT -23 CC 1K: #nu_{l} n #rightarrow l^{-} #Lambda K^{+} CC, numubar n --> mu- Sigma0 K+ resonant processes involving more than a single pion 62 NUANCE -> NEUT -23 CC 1K: #nu_{l} n #rightarrow l^{-} #Lambda K^{+} CC, numubar n --> mu- Sigma+ K0 resonant processes involving more than a single pion 63 NUANCE -> NEUT -45 NC 1K: #nu_{l} n #rightarrow #nu_{l} #Lambda K^{+} NC, numubar p --> numubar Sigma0 K+ resonant processes involving more than a single pion 64 NUANCE -> NEUT -44 NC 1K: #nu_{l} n #rightarrow #nu_{l} #Lambda K^{0} NC, numubar p --> numubar Sigma+ K0 resonant processes involving more than a single pion 65 NUANCE -> NEUT -44 NC 1K: #nu_{l} n #rightarrow #nu_{l} #Lambda K^{0} NC, numubar n --> numubar Sigma0 K0 resonant processes involving more than a single pion 66 NUANCE -> NEUT -45 NC 1K: #nu_{l} n #rightarrow #nu_{l} #Lambda K^{+} NC, numubar n --> numubar Sigma- K+ resonant processes involving more than a single pion 67 NUANCE -> NEUT 22 ModeStack[22]->SetTitle("CC1#eta^{0} on n"); CC, numu n --> mu- p eta resonant processes involving more than a single pion 68 NUANCE -> NEUT 43 NC, numu p --> numu p eta resonant processes involving more than a single pion 69 NUANCE -> NEUT 42 NC, numu n --> numu n eta resonant processes involving more than a single pion 70 NUANCE -> NEUT -22 ModeStack[22]->SetTitle("CC1#eta^{0} on n"); CC, numubar n --> mu- p eta resonant processes involving more than a single pion 71 NUANCE -> NEUT -43 ModeStack[43]->SetTitle("NC1#eta^{0} on p"); NC, numubar p --> numubar p eta resonant processes involving more than a single pion 72 NUANCE -> NEUT -42 ModeStack[42]->SetTitle("NC1#eta^{0} on n"); NC, numubar n --> numubar n eta resonant processes involving more than a single pion 73 NUANCE -> NEUT 21 ModeStack[21]->SetTitle("Multi #pi (1.3 < W < 2.0)"); CC, numu n --> mu- K+ Lambda resonant processes involving more than a single pion 74 NUANCE -> NEUT 41 ModeStack[41]->SetTitle("Multi #pi (1.3 < W < 2.0)"); NC, numu p --> numu K+ Lambda resonant processes involving more than a single pion 75 NUANCE -> NEUT 41 ModeStack[41]->SetTitle("Multi #pi (1.3 < W < 2.0)"); NC, numu n --> numu K0 Lambda resonant processes involving more than a single pion 76 NUANCE -> NEUT -21 ModeStack[21]->SetTitle("Multi #pi (1.3 < W < 2.0)"); CC, numubar n --> mu- K+ Lambda resonant processes involving more than a single pion 77 NUANCE -> NEUT -41 ModeStack[41]->SetTitle("Multi #pi (1.3 < W < 2.0)"); NC, numubar p --> numubar K+ Lambda resonant processes involving more than a single pion 78 NUANCE -> NEUT -41 ModeStack[41]->SetTitle("Multi #pi (1.3 < W < 2.0)"); NC, numubar n --> numubar K0 Lambda resonant processes involving more than a single pion CC Multipi ModeStack[21]->SetTitle("Multi #pi (1.3 < W < 2.0)"); NC Multipi ModeStack[41]->SetTitle("Multi #pi (1.3 < W < 2.0)"); 79 NUANCE -> NEUT 21 CC, numu n --> mu- p pi+ pi- two pion production 80 NUANCE -> NEUT 21 CC, numu n --> mu- p pi0 pi0 two pion production 81 NUANCE -> NEUT 41 NC, numu p --> numu p pi+ pi- two pion production 82 NUANCE -> NEUT 41 NC, numu p --> numu p pi0 pi0 two pion production 83 NUANCE -> NEUT 41 NC, numu n --> numu n pi+ pi- two pion production 84 NUANCE -> NEUT 41 NC, numu n --> numu n pi0 pi0 two pion production 85 NUANCE -> NEUT -21 CC, numubar n --> mu- p pi+ pi- two pion production 86 NUANCE -> NEUT -21 CC, numubar n --> mu- p pi0 pi0 two pion production 87 NUANCE -> NEUT -41 ModeStack[41]->SetTitle("Multi #pi (1.3 < W < 2.0)"); NC, numubar p --> numubar p pi+ pi- two pion production 88 NUANCE -> NEUT -41 ModeStack[41]->SetTitle("Multi #pi (1.3 < W < 2.0)"); NC, numubar p --> numubar p pi0 pi0 two pion production 89 NUANCE -> NEUT -41 ModeStack[41]->SetTitle("Multi #pi (1.3 < W < 2.0)"); NC, numubar n --> numubar n pi+ pi- two pion production 90 NUANCE -> NEUT -41 ModeStack[41]->SetTitle("Multi #pi (1.3 < W < 2.0)"); NC, numubar n --> numubar n pi0 pi0 two pion production 91 NUANCE -> NEUT 26 ModeStack[26]->SetTitle("DIS (W > 2.0)"); CC, numu N --> mu- X (where N=n,p) deep inelastic scattering (nu or nubar) 92 NUANCE -> NEUT 46 ModeStack[46]->SetTitle("DIS (W > 2.0)"); NC, numu N --> numu X (where N=n,p) deep inelastic scattering (nu or nubar) 93 NUANCE -> NEUT 17 1#gamma from #Delta: #nu_{l} n #rightarrow l^{-} p #gamma CC, numu n --> mu- p gamma Delta radiative decay, Delta --> N gamma (only in NUANCE versions v3 and and higher) 94 NUANCE -> NEUT 39 1#gamma from #Delta: #nu_{l} p #rightarrow #nu_{l} p #gamma neutModeID[15] = 38; neutModeName[15] = "ncngam"; neutModeTitle[15] = "1#gamma from #Delta: #nu_{l} n #rightarrow #nu_{l} n #gamma"; neutModeID[16] = 39; neutModeName[16] = "ncpgam"; neutModeTitle[16] = "1#gamma from #Delta: #nu_{l} p #rightarrow #nu_{l} p #gamma"; NC, numu N --> numu N gamma Delta radiative decay, Delta --> N gamma (only in NUANCE versions v3 and and higher) 95 -> UNKOWN NEUT MODE CC, numubar p --> mu+ Lambda, numubar n -- > mu+ Sigma-, numubar p --> mu+ Sigma0 Cabibbo-suppressed QE hyperon production from nucleons 96 NUANCE -> NEUT 36 neutModeID[14] = 36; neutModeName[14] = "nccoh"; neutModeTitle[14] = "NC coherent-#pi: #nu_{l} ^{16}O #rightarrow #nu_{l} ^{16}O #pi^{0}"; NC, numu A --> numu pi0 A coherent or diffractive pi0 production 97 NUANCE -> NEUT 16 neutModeID[4] = 16; neutModeName[4] = "cccoh"; neutModeTitle[4] = "CC coherent-#pi: #nu_{l} ^{16}O #rightarrow l^{-} ^{16}O #pi^{+}"; CC, numu A --> mu- pi+ A (or numubar A --> coherent or diffractive pi0 production 98 -> UNKNOWN NEUT MODE NC, numu e- --> numu e- (or numubar e- --> neutrino + electron elastic scattering 99 -> UNKNOWN NEUT MODE CC, numu e- --> mu- nue neutrino + electron inverse muon decay NEUT Modes: // CC Modes neutModeID[0] = 1; neutModeName[0] = "ccqe"; neutModeTitle[0] = "CCQE: #nu_{l} n #rightarrow l^{-} p"; neutModeID[1] = 11; neutModeName[1] = "ccppip"; neutModeTitle[1] = "CC 1#pi: #nu_{l} p #rightarrow l^{-} p #pi^{+}"; neutModeID[2] = 12; neutModeName[2] = "ccppi0"; neutModeTitle[2] = "CC 1#pi: #nu_{l} n #rightarrow l^{-} p #pi^{0}"; neutModeID[3] = 13; neutModeName[3] = "ccnpip"; neutModeTitle[3] = "CC 1#pi: #nu_{l} n #rightarrow l^{-} n #pi^{+}"; neutModeID[4] = 16; neutModeName[4] = "cccoh"; neutModeTitle[4] = "CC coherent-#pi: #nu_{l} ^{16}O #rightarrow l^{-} ^{16}O #pi^{+}"; neutModeID[5] = 17; neutModeName[5] = "ccgam"; neutModeTitle[5] = "1#gamma from #Delta: #nu_{l} n #rightarrow l^{-} p #gamma"; neutModeID[6] = 21; neutModeName[6] = "ccmpi"; neutModeTitle[6] = "CC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow l^{-} N' multi-#pi"; neutModeID[7] = 22; neutModeName[7] = "cceta"; neutModeTitle[7] = "CC 1#eta: #nu_{l} n #rightarrow l^{-} p #eta"; neutModeID[8] = 23; neutModeName[8] = "cck"; neutModeTitle[8] = "CC 1K: #nu_{l} n #rightarrow l^{-} #Lambda K^{+}"; neutModeID[9] = 26; neutModeName[9] = "ccdis"; neutModeTitle[9] = "CC DIS (2 GeV < W): #nu_{l} N #rightarrow l^{-} N' mesons"; neutModeID[10] = 31; neutModeName[10] = "ncnpi0"; neutModeTitle[10] = "NC 1#pi: #nu_{l} n #rightarrow #nu_{l} n #pi^{0}"; neutModeID[11] = 32; neutModeName[11] = "ncppi0"; neutModeTitle[11] = "NC 1#pi: #nu_{l} p #rightarrow #nu_{l} p #pi^{0}"; neutModeID[12] = 33; neutModeName[12] = "ncppim"; neutModeTitle[12] = "NC 1#pi: #nu_{l} n #rightarrow #nu_{l} p #pi^{-}"; neutModeID[13] = 34; neutModeName[13] = "ncnpip"; neutModeTitle[13] = "NC 1#pi: #nu_{l} p #rightarrow #nu_{l} n #pi^{+}"; neutModeID[14] = 36; neutModeName[14] = "nccoh"; neutModeTitle[14] = "NC coherent-#pi: #nu_{l} ^{16}O #rightarrow #nu_{l} ^{16}O #pi^{0}"; neutModeID[15] = 38; neutModeName[15] = "ncngam"; neutModeTitle[15] = "1#gamma from #Delta: #nu_{l} n #rightarrow #nu_{l} n #gamma"; neutModeID[16] = 39; neutModeName[16] = "ncpgam"; neutModeTitle[16] = "1#gamma from #Delta: #nu_{l} p #rightarrow #nu_{l} p #gamma"; neutModeID[17] = 41; neutModeName[17] = "ncmpi"; neutModeTitle[17] = "NC (1.3 < W < 2 GeV): #nu_{l} N #rightarrow #nu_{l} N multi-#pi"; neutModeID[18] = 42; neutModeName[18] = "ncneta"; neutModeTitle[18] = "NC 1#eta: #nu_{l} n #rightarrow #nu_{l} n #eta"; neutModeID[19] = 43; neutModeName[19] = "ncpeta"; neutModeTitle[19] = "NC 1#eta: #nu_{l} p #rightarrow #nu_{l} p #eta"; neutModeID[20] = 44; neutModeName[20] = "nck0"; neutModeTitle[20] = "NC 1K: #nu_{l} n #rightarrow #nu_{l} #Lambda K^{0}"; neutModeID[21] = 45; neutModeName[21] = "nckp"; neutModeTitle[21] = "NC 1K: #nu_{l} n #rightarrow #nu_{l} #Lambda K^{+}"; neutModeID[22] = 46; neutModeName[22] = "ncdis"; neutModeTitle[22] = "NC DIS (2 GeV < W): #nu_{l} N #rightarrow #nu_{l} N' mesons"; neutModeID[23] = 51; neutModeName[23] = "ncqep"; neutModeTitle[23] = "NC elastic: #nu_{l} p #rightarrow #nu_{l} p"; neutModeID[24] = 52; neutModeName[24] = "ncqen"; neutModeTitle[24] = "NC elastic: #nu_{l} n #rightarrow #nu_{l} n"; */ #endif diff --git a/src/InputHandler/NuWroInputHandler.cxx b/src/InputHandler/NuWroInputHandler.cxx index 739e060..b6c2096 100644 --- a/src/InputHandler/NuWroInputHandler.cxx +++ b/src/InputHandler/NuWroInputHandler.cxx @@ -1,518 +1,518 @@ #ifdef __NUWRO_ENABLED__ #include "NuWroInputHandler.h" #include "InputUtils.h" NuWroGeneratorInfo::~NuWroGeneratorInfo() { delete fNuWroParticlePDGs; } void NuWroGeneratorInfo::AddBranchesToTree(TTree *tn) { tn->Branch("NuWroParticlePDGs", &fNuWroParticlePDGs, "NuWroParticlePDGs/I"); } void NuWroGeneratorInfo::SetBranchesFromTree(TTree *tn) { tn->SetBranchAddress("NuWroParticlePDGs", &fNuWroParticlePDGs); } void NuWroGeneratorInfo::AllocateParticleStack(int stacksize) { fNuWroParticlePDGs = new int[stacksize]; } void NuWroGeneratorInfo::DeallocateParticleStack() { delete fNuWroParticlePDGs; } void NuWroGeneratorInfo::FillGeneratorInfo(event *e) { Reset(); } void NuWroGeneratorInfo::Reset() { for (int i = 0; i < kMaxParticles; i++) { fNuWroParticlePDGs[i] = 0; } } int event1_nof(event *e, int pdg) { int c = 0; for (size_t i = 0; i < e->out.size(); i++) if (e->out[i].pdg == pdg) c++; return c; } NuWroInputHandler::NuWroInputHandler(std::string const &handle, std::string const &rawinputs) { - QLOG(SAM, "Creating NuWroInputHandler : " << handle); + NUIS_LOG(SAM, "Creating NuWroInputHandler : " << handle); // Run a joint input handling fName = handle; fMaxEvents = FitPar::Config().GetParI("MAXEVENTS"); fSaveExtra = false; // FitPar::Config().GetParB("NuWroSaveExtra"); // Setup the TChain fNuWroTree = new TChain("treeout"); // Loop over all inputs and grab flux, eventhist, and nevents std::vector inputs = InputUtils::ParseInputFileList(rawinputs); for (size_t inp_it = 0; inp_it < inputs.size(); ++inp_it) { // Open File for histogram access TFile *inp_file = new TFile(inputs[inp_it].c_str(), "READ"); if (!inp_file or inp_file->IsZombie()) { - QTHROW("nuwro File IsZombie() at " << inputs[inp_it]); + NUIS_ABORT("nuwro File IsZombie() at " << inputs[inp_it]); } // Get Flux/Event hist TH1D *fluxhist = (TH1D *)inp_file->Get( (PlotUtils::GetObjectWithName(inp_file, "FluxHist")).c_str()); TH1D *eventhist = (TH1D *)inp_file->Get( (PlotUtils::GetObjectWithName(inp_file, "EvtHist")).c_str()); if (!fluxhist or !eventhist) { - QERROR(FTL, "nuwro FILE doesn't contain flux/xsec info"); + NUIS_ERR(FTL, "nuwro FILE doesn't contain flux/xsec info"); if (FitPar::Config().GetParB("regennuwro")) { - QERROR(FTL, + NUIS_ERR(FTL, "Regen NuWro has not been added yet. Email the developers!"); // ProcessNuWroInputFlux(inputs[inp_it]); throw; } else { - QTHROW("If you would like NUISANCE to generate these for you " + NUIS_ABORT("If you would like NUISANCE to generate these for you " << "please set parameter regennuwro=1 and re-run."); } } // Get N Events TTree *nuwrotree = (TTree *)inp_file->Get("treeout"); if (!nuwrotree) { - QTHROW("treeout not located in nuwro file! " << inputs[inp_it]); + NUIS_ABORT("treeout not located in nuwro file! " << inputs[inp_it]); } int nevents = nuwrotree->GetEntries(); // Register input to form flux/event rate hists RegisterJointInput(inputs[inp_it], nevents, fluxhist, eventhist); // Add to TChain fNuWroTree->Add(inputs[inp_it].c_str()); } // Registor all our file inputs SetupJointInputs(); // Setup Events fNuWroEvent = NULL; fNuWroTree->SetBranchAddress("e", &fNuWroEvent); fNuWroTree->GetEntry(0); fNUISANCEEvent = new FitEvent(); fNUISANCEEvent->fType = kNUWRO; fNUISANCEEvent->fNuwroEvent = fNuWroEvent; fNUISANCEEvent->HardReset(); if (fSaveExtra) { fNuWroInfo = new NuWroGeneratorInfo(); fNUISANCEEvent->AddGeneratorInfo(fNuWroInfo); } }; NuWroInputHandler::~NuWroInputHandler() { if (fNuWroTree) delete fNuWroTree; } void NuWroInputHandler::CreateCache() { // fNuWroTree->SetCacheEntryRange(0, fNEvents); // fNuWroTree->AddBranchToCache("*", 1); // fNuWroTree->SetCacheSize(fCacheSize); } void NuWroInputHandler::RemoveCache() { // fNuWroTree->SetCacheEntryRange(0, fNEvents); // fNuWroTree->AddBranchToCache("*", 0); // fNuWroTree->SetCacheSize(0); } void NuWroInputHandler::ProcessNuWroInputFlux(const std::string file) {} FitEvent *NuWroInputHandler::GetNuisanceEvent(const UInt_t entry, const bool lightweight) { // Catch too large entries if (entry >= (UInt_t)fNEvents) return NULL; // Read Entry from TTree to fill NEUT Vect in BaseFitEvt; fNuWroTree->GetEntry(entry); // Run NUISANCE Vector Filler if (!lightweight) { CalcNUISANCEKinematics(); } #ifdef __PROB3PP_ENABLED__ for (size_t i = 0; i < fNUISANCEEvent->fNuwroEvent->in.size(); i++) { if (std::count(PhysConst::pdg_neutrinos, PhysConst::pdg_neutrinos + 4, fNUISANCEEvent->fNuwroEvent->in[i].pdg)) { fNUISANCEEvent->probe_E = fNUISANCEEvent->fNuwroEvent->in[i].t; fNUISANCEEvent->probe_pdg = fNUISANCEEvent->fNuwroEvent->in[i].pdg; break; } } #endif // Setup Input scaling for joint inputs fNUISANCEEvent->InputWeight = GetInputWeight(entry); #ifdef __USE_NUWRO_SRW_EVENTS__ if (!rwEvs.size()) { fNuwroParams = fNuWroEvent->par; } if (entry >= rwEvs.size()) { rwEvs.push_back(BaseFitEvt()); rwEvs.back().fType = kNUWRO; rwEvs.back().Mode = fNUISANCEEvent->Mode; rwEvs.back().fNuwroSRWEvent = SRW::SRWEvent(*fNuWroEvent); rwEvs.back().fNuwroEvent = NULL; rwEvs.back().fNuwroParams = &fNuwroParams; rwEvs.back().probe_E = rwEvs.back().fNuwroSRWEvent.NeutrinoEnergy; rwEvs.back().probe_pdg = rwEvs.back().fNuwroSRWEvent.NeutrinoPDG; } fNUISANCEEvent->fNuwroSRWEvent = SRW::SRWEvent(*fNuWroEvent); fNUISANCEEvent->fNuwroParams = &fNuwroParams; fNUISANCEEvent->probe_E = fNUISANCEEvent->fNuwroSRWEvent.NeutrinoEnergy; fNUISANCEEvent->probe_pdg = fNUISANCEEvent->fNuwroSRWEvent.NeutrinoPDG; #endif return fNUISANCEEvent; } int NuWroInputHandler::ConvertNuwroMode(event *e) { Int_t proton_pdg, neutron_pdg, pion_pdg, pion_plus_pdg, pion_minus_pdg, lambda_pdg, eta_pdg, kaon_pdg, kaon_plus_pdg; proton_pdg = 2212; eta_pdg = 221; neutron_pdg = 2112; pion_pdg = 111; pion_plus_pdg = 211; pion_minus_pdg = -211; // O_16_pdg = 100069; // oznacznie z Neuta lambda_pdg = 3122; kaon_pdg = 311; kaon_plus_pdg = 321; if (e->flag.qel) // kwiazielastyczne oddziaływanie { if (e->flag.anty) // jeśli jest to oddziaływanie z antyneutrinem { if (e->flag.cc) return -1; else { if (event1_nof(e, proton_pdg)) return -51; else if (event1_nof(e, neutron_pdg)) return -52; // sprawdzam dodatkowo ? } } else // oddziaływanie z neutrinem { if (e->flag.cc) return 1; else { if (event1_nof(e, proton_pdg)) return 51; else if (event1_nof(e, neutron_pdg)) return 52; } } } if (e->flag.mec) { if (e->flag.anty) return -2; else return 2; } if (e->flag.res) // rezonansowa produkcja: pojedynczy pion, pojed.eta, kaon, // multipiony { Int_t liczba_pionow, liczba_kaonow; liczba_pionow = event1_nof(e, pion_pdg) + event1_nof(e, pion_plus_pdg) + event1_nof(e, pion_minus_pdg); liczba_kaonow = event1_nof(e, kaon_pdg) + event1_nof(e, kaon_pdg); if (liczba_pionow > 1 || liczba_pionow == 0) // multipiony { if (e->flag.anty) { if (e->flag.cc) return -21; else return -41; } else { if (e->flag.cc) return 21; else return 41; } } if (liczba_pionow == 1) { if (e->flag.anty) // jeśli jest to oddziaływanie z antyneutrinem { if (e->flag.cc) { if (event1_nof(e, neutron_pdg) && event1_nof(e, pion_minus_pdg)) return -11; if (event1_nof(e, neutron_pdg) && event1_nof(e, pion_pdg)) return -12; if (event1_nof(e, proton_pdg) && event1_nof(e, pion_minus_pdg)) return -13; } else { if (event1_nof(e, proton_pdg)) { if (event1_nof(e, pion_minus_pdg)) return -33; else if (event1_nof(e, pion_pdg)) return -32; } else if (event1_nof(e, neutron_pdg)) { if (event1_nof(e, pion_plus_pdg)) return -34; else if (event1_nof(e, pion_pdg)) return -31; } } } else // oddziaływanie z neutrinem { if (e->flag.cc) { if (event1_nof(e, proton_pdg) && event1_nof(e, pion_plus_pdg)) return 11; if (event1_nof(e, proton_pdg) && event1_nof(e, pion_pdg)) return 12; if (event1_nof(e, neutron_pdg) && event1_nof(e, pion_plus_pdg)) return 13; } else { if (event1_nof(e, proton_pdg)) { if (event1_nof(e, pion_minus_pdg)) return 33; else if (event1_nof(e, pion_pdg)) return 32; } else if (event1_nof(e, neutron_pdg)) { if (event1_nof(e, pion_plus_pdg)) return 34; else if (event1_nof(e, pion_pdg)) return 31; } } } } if (event1_nof(e, eta_pdg)) // produkcja rezonansowa ety { if (e->flag.anty) // jeśli jest to oddziaływanie z antyneutrinem { if (e->flag.cc) return -22; else { if (event1_nof(e, neutron_pdg)) return -42; else if (event1_nof(e, proton_pdg)) return -43; // sprawdzam dodatkowo ? } } else // oddziaływanie z neutrinem { if (e->flag.cc) return 22; else { if (event1_nof(e, neutron_pdg)) return 42; else if (event1_nof(e, proton_pdg)) return 43; } } } if (event1_nof(e, lambda_pdg) == 1 && liczba_kaonow == 1) // produkcja rezonansowa kaonu { if (e->flag.anty) // jeśli jest to oddziaływanie z antyneutrinem { if (e->flag.cc && event1_nof(e, kaon_pdg)) return -23; else { if (event1_nof(e, kaon_pdg)) return -44; else if (event1_nof(e, kaon_plus_pdg)) return -45; } } else // oddziaływanie z neutrinem { if (e->flag.cc && event1_nof(e, kaon_plus_pdg)) return 23; else { if (event1_nof(e, kaon_pdg)) return 44; else if (event1_nof(e, kaon_plus_pdg)) return 45; } } } } if (e->flag.coh) // koherentne oddziaływanie tylko na O(16) { Int_t _target; _target = e->par.nucleus_p + e->par.nucleus_n; // liczba masowa O(16) if (_target == 16) { if (e->flag.anty) // jeśli jest to oddziaływanie z antyneutrinem { if (e->flag.cc && event1_nof(e, pion_minus_pdg)) return -16; else if (event1_nof(e, pion_pdg)) return -36; } else // oddziaływanie z neutrinem { if (e->flag.cc && event1_nof(e, pion_plus_pdg)) return 16; else if (event1_nof(e, pion_pdg)) return 36; } } } // gleboko nieelastyczne rozpraszanie if (e->flag.dis) { if (e->flag.anty) { if (e->flag.cc) return -26; else return -46; } else { if (e->flag.cc) return 26; else return 46; } } return 9999; } void NuWroInputHandler::CalcNUISANCEKinematics() { // std::cout << "NuWro Event Address " << fNuWroEvent << std::endl; // Reset all variables fNUISANCEEvent->ResetEvent(); FitEvent *evt = fNUISANCEEvent; // Sort Event Info evt->Mode = ConvertNuwroMode(fNuWroEvent); if (abs(evt->Mode) > 60) { evt->Mode = 0; } evt->fEventNo = 0.0; evt->fTotCrs = 0.0; evt->fTargetA = fNuWroEvent->par.nucleus_p + fNuWroEvent->par.nucleus_n; evt->fTargetZ = fNuWroEvent->par.nucleus_p; evt->fTargetPDG = TargetUtils::GetTargetPDGFromZA(evt->fTargetZ, evt->fTargetA); evt->fTargetH = 0; evt->fBound = (evt->fTargetA != 1); // Check Particle Stack UInt_t npart_in = fNuWroEvent->in.size(); UInt_t npart_out = fNuWroEvent->out.size(); UInt_t npart_post = fNuWroEvent->post.size(); UInt_t npart = npart_in + npart_out + npart_post; UInt_t kmax = evt->kMaxParticles; if (npart > kmax) { - QERROR(WRN, "NUWRO has too many particles. Expanding stack."); + NUIS_ERR(WRN, "NUWRO has too many particles. Expanding stack."); fNUISANCEEvent->ExpandParticleStack(npart); } evt->fNParticles = 0; std::vector::iterator p_iter; // Get the Initial State for (p_iter = fNuWroEvent->in.begin(); p_iter != fNuWroEvent->in.end(); p_iter++) { AddNuWroParticle(fNUISANCEEvent, (*p_iter), kInitialState, true); } // Try to find the FSI state particles // Loop over the primary vertex particles // If they match the post-FSI they haven't undergone FSI. // If they don't match post-FSI they have undergone FSI. for (p_iter = fNuWroEvent->out.begin(); p_iter != fNuWroEvent->out.end(); p_iter++) { // Get the particle particle p = (*p_iter); // Check against all the post particles, match them std::vector::iterator p2_iter; bool match = false; for (p2_iter = fNuWroEvent->post.begin(); p2_iter != fNuWroEvent->post.end(); p2_iter++) { particle p2 = (*p2_iter); // Check energy and pdg // A very small cascade which changes the energy by 1E-5 MeV should be // matched match = (fabs(p2.E() - p.E()) < 1E-5 && p2.pdg == p.pdg); // If we match p to p2 break the loop if (match) break; } // If we've looped through the whole particle stack of post-FSI and haven't // found a match it's a primary particle that has been FSIed if (!match) AddNuWroParticle(fNUISANCEEvent, (*p_iter), kFSIState, true); } // Loop over the final state particles for (p_iter = fNuWroEvent->post.begin(); p_iter != fNuWroEvent->post.end(); p_iter++) { particle p = (*p_iter); // To find if it's primary or not we have to loop through the primary ones // and match, just like above bool match = false; std::vector::iterator p2_iter; for (p2_iter = fNuWroEvent->out.begin(); p2_iter != fNuWroEvent->out.end(); p2_iter++) { particle p2 = (*p2_iter); match = (fabs(p2.E() - p.E()) < 1E-5 && p2.pdg == p.pdg); if (match) break; } AddNuWroParticle(fNUISANCEEvent, (*p_iter), kFinalState, match); } // Fill Generator Info if (fSaveExtra) fNuWroInfo->FillGeneratorInfo(fNuWroEvent); // Run Initial, FSI, Final, Other ordering. fNUISANCEEvent->OrderStack(); FitParticle *ISAnyLepton = fNUISANCEEvent->GetHMISAnyLeptons(); if (ISAnyLepton) { fNUISANCEEvent->probe_E = ISAnyLepton->E(); fNUISANCEEvent->probe_pdg = ISAnyLepton->PDG(); } return; } void NuWroInputHandler::AddNuWroParticle(FitEvent *evt, particle &p, int state, bool primary = false) { // Add Mom evt->fParticleMom[evt->fNParticles][0] = static_cast(p).x; evt->fParticleMom[evt->fNParticles][1] = static_cast(p).y; evt->fParticleMom[evt->fNParticles][2] = static_cast(p).z; evt->fParticleMom[evt->fNParticles][3] = static_cast(p).t; // For NuWro a particle that we've given a FSI state is a pre-FSI particle // An initial state particle is also a primary vertex praticle evt->fPrimaryVertex[evt->fNParticles] = primary; // Status/PDG evt->fParticleState[evt->fNParticles] = state; evt->fParticlePDG[evt->fNParticles] = p.pdg; // Add to particle count evt->fNParticles++; } void NuWroInputHandler::Print() {} #endif diff --git a/src/InputHandler/NuWroInputHandler.h b/src/InputHandler/NuWroInputHandler.h index 699bce6..21844a3 100644 --- a/src/InputHandler/NuWroInputHandler.h +++ b/src/InputHandler/NuWroInputHandler.h @@ -1,95 +1,95 @@ #ifndef NuWroINPUTHANDLER_H #define NuWroINPUTHANDLER_H #ifdef __NUWRO_ENABLED__ #include "GeneratorUtils.h" #include "InputHandler.h" #include "PlotUtils.h" /// NuWro Generator Container to save extra particle status codes. class NuWroGeneratorInfo : public GeneratorInfoBase { public: NuWroGeneratorInfo(){}; virtual ~NuWroGeneratorInfo(); /// Assigns information to branches void AddBranchesToTree(TTree* tn); /// Setup reading information from branches void SetBranchesFromTree(TTree* tn); /// Allocate any dynamic arrays for a new particle stack size void AllocateParticleStack(int stacksize); /// Clear any dynamic arrays void DeallocateParticleStack(); /// Read extra genie information from the event void FillGeneratorInfo(event* e); /// Reset extra information to default/empty values void Reset(); int kMaxParticles; ///< Number of particles in stack int* fNuWroParticlePDGs; ///< NuWro Particle PDGs (example) }; /// Main NuWro Input Reader. Requires events have flux and xsec TH1Ds saved into /// them. class NuWroInputHandler : public InputHandlerBase { #ifdef __USE_NUWRO_SRW_EVENTS__ params fNuwroParams; std::vector rwEvs; #endif public: /// Constructor. Can handle single and joint inputs. NuWroInputHandler(std::string const& handle, std::string const& rawinputs); ~NuWroInputHandler(); /// Create a TTree Cache to speed up file read void CreateCache(); /// Remove TTree Cache to save memory void RemoveCache(); /// Returns filled NUISANCEEvent for given entry. FitEvent* GetNuisanceEvent(const UInt_t entry, const bool lightweight = false); #ifdef __USE_NUWRO_SRW_EVENTS__ // Returns filled BaseFitEvent for a given entry; BaseFitEvt* GetBaseEvent(const UInt_t entry) { if (rwEvs.size() <= entry) { - QTHROW("Tried to get cached BaseFitEv[" << entry << "], but only have " + NUIS_ABORT("Tried to get cached BaseFitEv[" << entry << "], but only have " << rwEvs.size() << " in the cache."); } return &rwEvs[entry]; } #endif /// Fills fNUISANCEEvent from fNuWroEvent void CalcNUISANCEKinematics(); /// (LEGACY) Automatically creates nuwro flux/event histograms that /// nuisance needs to normalise events. void ProcessNuWroInputFlux(const std::string file); /// Calculates a True Interaction code for NuWro events int ConvertNuwroMode(event* e); /// Adds a new particle to NUISANCE stack for given NuWro particle void AddNuWroParticle(FitEvent* evt, particle& p, int state, bool primary); event* fNuWroEvent; ///< Pointer to NuWro Format Events /// Print Event Information void Print(); TChain* fNuWroTree; ///< TTree for reading NuWro event vectors bool fSaveExtra; ///< Save Extra NuWro info into Nuisance Event NuWroGeneratorInfo* fNuWroInfo; ///< Extra NuWro Generator Info }; /*! @} */ #endif #endif diff --git a/src/InputHandler/SigmaQ0HistogramInputHandler.cxx b/src/InputHandler/SigmaQ0HistogramInputHandler.cxx index 4103a24..4a16536 100644 --- a/src/InputHandler/SigmaQ0HistogramInputHandler.cxx +++ b/src/InputHandler/SigmaQ0HistogramInputHandler.cxx @@ -1,267 +1,267 @@ #include "SigmaQ0HistogramInputHandler.h" SigmaQ0HistogramInputHandler::SigmaQ0HistogramInputHandler( std::string const &handle, std::string const &rawinputs) { - QLOG(SAM, "Creating SigmaQ0HistogramInputHandler : " << handle); + NUIS_LOG(SAM, "Creating SigmaQ0HistogramInputHandler : " << handle); // Run a joint input handling fName = handle; // Assign to hist event format fEventType = kSIGMAQ0HIST; // Parse our input file // SIGMAQ0HIST:path.txt,ENERGY=0.25,THETA=0.34,Q0COL=1,XSCOL=2,SCL=10 std::vector parsedinputs = GeneralUtils::ParseToStr(rawinputs, ","); fFilePath = parsedinputs[0]; // Setup Defaults incase none given fEnergy = -1.0; fTheta = -1.0; fQ0Column = 0; fSigmaColumn = 1; fBeamPDG = -1; // Assume electron by default fDelim = " "; fScaling = 1.E38; // Now Loop through and parse possible inputs for (uint i = 1; i < parsedinputs.size(); i++) { std::vector parsedspec = GeneralUtils::ParseToStr(parsedinputs[i], "="); if (parsedspec.size() < 2) { - QTHROW("NO VALUE GIVEN TO SPECIFIER : " << parsedinputs[0]); + NUIS_ABORT("NO VALUE GIVEN TO SPECIFIER : " << parsedinputs[0]); } std::string spec = parsedspec[0]; std::string value = parsedspec[1]; // Read Energy if (!spec.compare("ENERGY") or !spec.compare("E")) { fEnergy = GeneralUtils::StrToDbl(value); // Read Theta } else if (!spec.compare("THETA") or !spec.compare("T")) { fTheta = GeneralUtils::StrToDbl(value); // Set Q0 Column } else if (!spec.compare("Q0") or !spec.compare("Q0COL")) { fQ0Column = GeneralUtils::StrToInt(value); // Set XSec Column } else if (!spec.compare("XSCOL") or !spec.compare("XS") or !spec.compare("X") or !spec.compare("SIG") or !spec.compare("SIGMA")) { fSigmaColumn = GeneralUtils::StrToInt(value); } else if (!spec.compare("BEAM") or !spec.compare("P") or !spec.compare("PDG")) { fBeamPDG = GeneralUtils::StrToInt(value); } else if (!spec.compare("SCL") or !spec.compare("SC") or !spec.compare("S")) { fScaling = GeneralUtils::StrToDbl(value); // Throw } else { - QTHROW("Unknown argument given to SigmaQ0 InputHandler!"); + NUIS_ABORT("Unknown argument given to SigmaQ0 InputHandler!"); } } // Check we got everything if (fEnergy == -1 or fEnergy < 0) { - QTHROW("Energy for SigmaQ0 Handler either invalid or not given! Specify " + NUIS_ABORT("Energy for SigmaQ0 Handler either invalid or not given! Specify " "with ',E=ENERGY' in the input spec."); } // Default to Electron if (fBeamPDG == -1) { - QERROR(WRN, + NUIS_ERR(WRN, "No Beam PDG Given in SigmaQ0 Handler so assuming electron. " << "If input is not electron scattering please specify using : " "PDG=PDGCODE"); } // Convert Theta fTheta = fTheta * M_PI / 180.0; - QLOG(FIT, "Set Theta to = " << fTheta); + NUIS_LOG(FIT, "Set Theta to = " << fTheta); // Have to create a dummy flux and event rate histogram :( fFluxHist = new TH1D("fluxhist", "fluxhist", 100.0, 0.0, 2.0 * fEnergy); fFluxHist->SetBinContent(fFluxHist->FindBin(fEnergy), 1.0); fEventHist = new TH1D("eventhist", "eventhist", 100.0, 0.0, 2.0 * fEnergy); fEventHist->SetBinContent(fEventHist->FindBin(fEnergy), 1.0); fEnergy = fEnergy * 1.E3; - QLOG(FIT, "Set E energy"); + NUIS_LOG(FIT, "Set E energy"); // Now parse the lines in our input file. fApplyInterpolation = FitPar::Config().GetParB("InterpolateSigmaQ0Histogram"); double interpolation_res = FitPar::Config().GetParD("InterpolateSigmaQ0HistogramRes"); fMaxValue = 0.0; fMaxX = 0.0; fMinX = 1.E10; // Create a TGraph of Points TGraph *gr = new TGraph(); std::vector inputlines = GeneralUtils::ParseFileToStr(fFilePath, "\n"); for (uint i = 0; i < inputlines.size(); i++) { std::vector splitline = GeneralUtils::ParseToDbl(inputlines[i], fDelim.c_str()); double q0 = splitline[fQ0Column]; double sig = splitline[fSigmaColumn]; gr->SetPoint(gr->GetN(), q0, sig); if (sig > fMaxValue) fMaxValue = sig; if (q0 > fMaxX) fMaxX = q0; if (q0 < fMinX) fMinX = q0; } fInputGraph = new TGraph(); for (int i = 0; i < gr->GetN(); i++) { fInputGraph->SetPoint(fInputGraph->GetN(), gr->GetX()[i], gr->GetY()[i]); fNEvents++; if (fApplyInterpolation) { // If not last point create extra events if (i != gr->GetN() - 1) { double xlow = gr->GetX()[i]; double xhigh = gr->GetX()[i + 1]; for (int j = 1; j < int(interpolation_res); j++) { double x = xlow + double(j) * (xhigh - xlow) / interpolation_res; fInputGraph->SetPoint(fInputGraph->GetN(), x, gr->Eval(x)); fNEvents++; } } } } delete gr; fFluxHist->Scale(1.0 / fFluxHist->Integral("width")); fEventHist->Scale(fScaling * double(fNEvents) / fEventHist->Integral()); if (fApplyInterpolation) { fEventHist->Scale(1.0 / interpolation_res); } fUseAcceptReject = FitPar::Config().GetParB("InterpolateSigmaQ0HistogramThrow"); if (fUseAcceptReject) { std::cout << "USING ACCEPT REJECT" << std::endl; fEventHist->Scale(fMaxValue / double(fNEvents)); fNEvents = FitPar::Config().GetParI("InterpolateSigmaQ0HistogramNTHROWS"); std::cout << "NEvents = " << fNEvents << std::endl; sleep(1); } fNUISANCEEvent = new FitEvent(); }; SigmaQ0HistogramInputHandler::~SigmaQ0HistogramInputHandler(){}; FitEvent * SigmaQ0HistogramInputHandler::GetNuisanceEvent(const UInt_t entry, const bool lightweight) { // Catch too large entries if (entry >= (UInt_t)fNEvents) return NULL; // Evaluate Graph to Create an Event if (!fUseAcceptReject) { double q0 = fInputGraph->GetX()[entry]; double sig = fInputGraph->GetY()[entry]; FillNuisanceEvent(q0, sig); } else { double q0 = ThrowQ0(); FillNuisanceEvent(q0, 1.0); } // Return event pointer return fNUISANCEEvent; } double SigmaQ0HistogramInputHandler::ThrowQ0() { // Use input graph to Throw Q0. int count = 0; while (count < 1E7) { double x = fRandom.Uniform(fMinX, fMaxX); if (fRandom.Uniform(0.0, 1.0) <= fInputGraph->Eval(x) / fMaxValue) { return x; }; std::cout << "THROW " << count << " : " << x << std::endl; } return 0.0; } void SigmaQ0HistogramInputHandler::FillNuisanceEvent(double q0, double sig) { // Reset all variables fNUISANCEEvent->ResetEvent(); // Fill Globals fNUISANCEEvent->Mode = 1; fNUISANCEEvent->fEventNo = 0; fNUISANCEEvent->fTargetA = 0; // Should the User Specify these? fNUISANCEEvent->fTargetZ = 0; // Should the User Specify these? fNUISANCEEvent->fTargetH = 0; // Should the User Specify these? fNUISANCEEvent->fBound = 1; // Should the User Specify these? fNUISANCEEvent->InputWeight = sig; // Add incoming beam particle along Z with energy E and outgoing with theta if (fBeamPDG == 11) { // Initial Beam fNUISANCEEvent->fParticleState[0] = kInitialState; fNUISANCEEvent->fParticlePDG[0] = 11; double mass = 0.511; // Get Momentum of Electron moving along Z fNUISANCEEvent->fParticleMom[0][0] = 0.0; fNUISANCEEvent->fParticleMom[0][1] = 0.0; - QLOG(FIT, "Setting Energy = " << fEnergy); + NUIS_LOG(FIT, "Setting Energy = " << fEnergy); fNUISANCEEvent->fParticleMom[0][2] = sqrt(fEnergy * fEnergy - mass * mass); fNUISANCEEvent->fParticleMom[0][3] = fEnergy; // Outgoing particle fNUISANCEEvent->fParticleState[1] = kFinalState; fNUISANCEEvent->fParticlePDG[1] = 11; // Get Momentum of Electron outgoing minus q0 double oute = fEnergy - q0; double outp = sqrt(oute * oute - mass * mass); fNUISANCEEvent->fParticleMom[1][0] = 0.0; fNUISANCEEvent->fParticleMom[1][1] = sin(fTheta) * outp; fNUISANCEEvent->fParticleMom[1][2] = cos(fTheta) * outp; fNUISANCEEvent->fParticleMom[1][3] = oute; } // Update Particles fNUISANCEEvent->fNParticles = 2; // Run Initial, FSI, Final, Other ordering. fNUISANCEEvent->OrderStack(); // Check Q0 // FitParticle* ein = fNUISANCEEvent->PartInfo(0); // FitParticle* eout = fNUISANCEEvent->GetHMFSParticle(11); // double newq0 = fabs(ein->fP.E() - eout->fP.E()) / 1000.0; // double E = ein->fP.E() / 1000.0; // double theta = ein->fP.Vect().Angle(eout->fP.Vect()) * 180. / M_PI; // LOG(FIT) << "Extracted event from line: theirs-" << q0/1.E3 << " ours-" //<< newq0 << " E-" << fEnergy << " T-" << theta << " X-" << sig << std::endl; return; } diff --git a/src/InputHandler/SplineInputHandler.cxx b/src/InputHandler/SplineInputHandler.cxx index dfc0165..43b3675 100644 --- a/src/InputHandler/SplineInputHandler.cxx +++ b/src/InputHandler/SplineInputHandler.cxx @@ -1,132 +1,132 @@ #include "SplineInputHandler.h" SplineInputHandler::SplineInputHandler(std::string const &handle, std::string const &rawinputs) { - QLOG(SAM, "Creating SplineInputHandler : " << handle); + NUIS_LOG(SAM, "Creating SplineInputHandler : " << handle); // Run a joint input handling fName = handle; fCacheSize = FitPar::Config().GetParI("CacheSize"); fMaxEvents = FitPar::Config().GetParI("MAXEVENTS"); // Setup the TChain fFitEventTree = new TChain("nuisance_events"); // Open File for histogram access TFile *inp_file = new TFile(rawinputs.c_str(), "READ"); if (!inp_file or inp_file->IsZombie()) { - QTHROW("FitEvent File IsZombie() at " << rawinputs); + NUIS_ABORT("FitEvent File IsZombie() at " << rawinputs); } // Get Flux/Event hist TH1D *fluxhist = (TH1D *)inp_file->Get("nuisance_fluxhist"); TH1D *eventhist = (TH1D *)inp_file->Get("nuisance_eventhist"); if (!fluxhist or !eventhist) { - QTHROW("FitEvent FILE doesn't contain flux/xsec info"); + NUIS_ABORT("FitEvent FILE doesn't contain flux/xsec info"); } // Get N Events TTree *eventtree = (TTree *)inp_file->Get("nuisance_events"); if (!eventtree) { - QTHROW("nuisance_events not located in FitSpline file! " << rawinputs); + NUIS_ABORT("nuisance_events not located in FitSpline file! " << rawinputs); } int nevents = eventtree->GetEntries(); // Register input to form flux/event rate hists RegisterJointInput(rawinputs, nevents, fluxhist, eventhist); SetupJointInputs(); // Add to TChain fFitEventTree->Add(rawinputs.c_str()); // Setup NEvents and the FitEvent fNEvents = fFitEventTree->GetEntries(); fEventType = kSPLINEPARAMETER; fNUISANCEEvent = new FitEvent(); fNUISANCEEvent->SetBranchAddress(fFitEventTree); // Setup Spline Reader - QLOG(SAM, "Loading Spline Reader."); + NUIS_LOG(SAM, "Loading Spline Reader."); fSplRead = new SplineReader(); fSplRead->Read((TTree *)inp_file->Get("spline_reader")); fNUISANCEEvent->fSplineRead = this->fSplRead; // Setup Matching Spline TTree fSplTree = (TTree *)inp_file->Get("spline_tree"); fSplTree->SetBranchAddress("SplineCoeff", fSplineCoeff); fNUISANCEEvent->fSplineCoeff = this->fSplineCoeff; // Load into memory for (int j = 0; j < fNEvents; j++) { std::vector tempval; fFitEventTree->GetEntry(j); fStartingWeights.push_back(GetInputWeight(j)); } }; SplineInputHandler::~SplineInputHandler() { if (fFitEventTree) delete fFitEventTree; if (fSplTree) delete fSplTree; if (fSplRead) delete fSplRead; fStartingWeights.clear(); } void SplineInputHandler::CreateCache() { if (fCacheSize > 0) { fFitEventTree->SetCacheEntryRange(0, fNEvents); fFitEventTree->AddBranchToCache("*", 1); fFitEventTree->SetCacheSize(fCacheSize); fSplTree->SetCacheEntryRange(0, fNEvents); fSplTree->AddBranchToCache("*", 1); fSplTree->SetCacheSize(fCacheSize); } } void SplineInputHandler::RemoveCache() { fFitEventTree->SetCacheEntryRange(0, fNEvents); fFitEventTree->AddBranchToCache("*", 0); fFitEventTree->SetCacheSize(0); fSplTree->SetCacheEntryRange(0, fNEvents); fSplTree->AddBranchToCache("*", 0); fSplTree->SetCacheSize(0); } FitEvent *SplineInputHandler::GetNuisanceEvent(const UInt_t entry, const bool lightweight) { // Make sure events setup if (entry >= (UInt_t)fNEvents) return NULL; // Reset all variables before tree read fNUISANCEEvent->ResetEvent(); // Read NUISANCE Tree if (!lightweight) fFitEventTree->GetEntry(entry); // Get Spline Coefficients fSplTree->GetEntry(entry); fNUISANCEEvent->fSplineCoeff = fSplineCoeff; // Setup Input scaling for joint inputs fNUISANCEEvent->InputWeight = fStartingWeights[entry]; // Run Initial, FSI, Final, Other ordering. fNUISANCEEvent->OrderStack(); return fNUISANCEEvent; } double SplineInputHandler::GetInputWeight(int entry) { double w = InputHandlerBase::GetInputWeight(entry); return w * fNUISANCEEvent->SavedRWWeight; } void SplineInputHandler::Print() {} diff --git a/src/InputHandler/StdHepEvt.cxx b/src/InputHandler/StdHepEvt.cxx index 2ee5fc6..17b7622 100644 --- a/src/InputHandler/StdHepEvt.cxx +++ b/src/InputHandler/StdHepEvt.cxx @@ -1,136 +1,136 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include #include #include #include "StdHepEvt.h" // Include logging #include "FitLogger.h" StdHepReader::StdHepReader(){}; bool StdHepReader::SetBranchAddresses(TChain *chain) { bool ok = true; int SBAStatus = 0; SBAStatus = chain->SetBranchAddress("StdHepN", &StdHepN); ok = ok && (SBAStatus || SBAStatus == 5); if (!(!SBAStatus || SBAStatus == 5)) { - QERROR(WRN, "Failed to set branch address for \"StdHepN\": " << SBAStatus); + NUIS_ERR(WRN, "Failed to set branch address for \"StdHepN\": " << SBAStatus); } SBAStatus = chain->SetBranchAddress("StdHepPdg", StdHepPdg); ok = ok && (SBAStatus || SBAStatus == 5); if (!(!SBAStatus || SBAStatus == 5)) { - QERROR(WRN, + NUIS_ERR(WRN, "Failed to set branch address for \"StdHepPdg\": " << SBAStatus); } SBAStatus = chain->SetBranchAddress("StdHepStatus", StdHepStatus); ok = ok && (SBAStatus || SBAStatus == 5); if (!(!SBAStatus || SBAStatus == 5)) { - QERROR(WRN, + NUIS_ERR(WRN, "Failed to set branch address for \"StdHepStatus\": " << SBAStatus); } SBAStatus = chain->SetBranchAddress("StdHepP4", StdHepP4); ok = ok && (SBAStatus || SBAStatus == 5); if (!(!SBAStatus || SBAStatus == 5)) { - QERROR(WRN, "Failed to set branch address for \"StdHepP4\": " << SBAStatus); + NUIS_ERR(WRN, "Failed to set branch address for \"StdHepP4\": " << SBAStatus); } return ok; } bool GiBUUStdHepReader::SetBranchAddresses(TChain *chain) { bool ok = true; int SBAStatus = 0; ok = ok && StdHepReader::SetBranchAddresses(chain); SBAStatus = chain->SetBranchAddress("GiBUU2NeutCode", &GiBUU2NeutCode); ok = ok && (SBAStatus || SBAStatus == 5); if (!(!SBAStatus || SBAStatus == 5)) { - QERROR(WRN, "Failed to set branch address for \"GiBUU2NeutCode\": " + NUIS_ERR(WRN, "Failed to set branch address for \"GiBUU2NeutCode\": " << SBAStatus); } SBAStatus = chain->SetBranchAddress("GiBUUReactionCode", &GiBUUReactionCode); ok = ok && (SBAStatus || SBAStatus == 5); if (!(!SBAStatus || SBAStatus == 5)) { - QERROR(WRN, "Failed to set branch address for \"GiBUUReactionCode\": " + NUIS_ERR(WRN, "Failed to set branch address for \"GiBUUReactionCode\": " << SBAStatus); } SBAStatus = chain->SetBranchAddress("EvtWght", &EvtWght); ok = ok && (SBAStatus || SBAStatus == 5); if (!(!SBAStatus || SBAStatus == 5)) { - QERROR(WRN, "Failed to set branch address for \"EvtWght\": " << SBAStatus); + NUIS_ERR(WRN, "Failed to set branch address for \"EvtWght\": " << SBAStatus); } return ok; } std::string NegSpacer(double const &num) { return (num >= 0) ? " " : ""; } std::ostream &operator<<(std::ostream &os, TLorentzVector const &tlv) { std::streamsize prec = os.precision(); std::ios_base::fmtflags flags = os.flags(); os.precision(2); os.flags(std::ios::scientific); os << "[" << NegSpacer(tlv[0]) << tlv[0] << "," << NegSpacer(tlv[1]) << tlv[1] << "," << NegSpacer(tlv[2]) << tlv[2] << "," << NegSpacer(tlv[3]) << tlv[3] << ":M(" << tlv.M() << ")]"; os.precision(prec); os.flags(flags); return os; } std::string WriteGiBUUEvent(GiBUUStdHepReader const &gi) { std::stringstream ss(""); ss << "[INFO]: contained " << gi.StdHepN << ", Event Weight: " << std::setprecision(3) << gi.EvtWght << ", NeutConventionReactionCode: " << gi.GiBUU2NeutCode << "\n\t[Lep In](" << std::setw(3) << gi.StdHepPdg[0] << ") " << TLorentzVector(gi.StdHepP4[0][StdHepReader::kStdHepIdxPx], gi.StdHepP4[0][StdHepReader::kStdHepIdxPy], gi.StdHepP4[0][StdHepReader::kStdHepIdxPz], gi.StdHepP4[0][StdHepReader::kStdHepIdxE]) << std::endl; ss << "\t[Target] : " << gi.StdHepPdg[1] << std::endl; ss << "\t[Nuc In] : " << TLorentzVector(gi.StdHepP4[3][StdHepReader::kStdHepIdxPx], gi.StdHepP4[3][StdHepReader::kStdHepIdxPy], gi.StdHepP4[3][StdHepReader::kStdHepIdxPz], gi.StdHepP4[3][StdHepReader::kStdHepIdxE]) << " (" << std::setw(4) << gi.StdHepPdg[3] << ")" << std::endl; for (Int_t stdHepInd = 4; stdHepInd < gi.StdHepN; ++stdHepInd) { ss << "\t[" << std::setw(2) << (stdHepInd - (4)) << "](" << std::setw(5) << gi.StdHepPdg[stdHepInd] << ") " << TLorentzVector(gi.StdHepP4[stdHepInd][StdHepReader::kStdHepIdxPx], gi.StdHepP4[stdHepInd][StdHepReader::kStdHepIdxPy], gi.StdHepP4[stdHepInd][StdHepReader::kStdHepIdxPz], gi.StdHepP4[stdHepInd][StdHepReader::kStdHepIdxE]) << std::endl; } ss << "\t[Lep Out](" << std::setw(3) << gi.StdHepPdg[2] << ") " << TLorentzVector(gi.StdHepP4[2][StdHepReader::kStdHepIdxPx], gi.StdHepP4[2][StdHepReader::kStdHepIdxPy], gi.StdHepP4[2][StdHepReader::kStdHepIdxPz], gi.StdHepP4[2][StdHepReader::kStdHepIdxE]) << std::endl; return ss.str(); } diff --git a/src/Logger/FitLogger.h b/src/Logger/FitLogger.h index 9fa8868..f406298 100644 --- a/src/Logger/FitLogger.h +++ b/src/Logger/FitLogger.h @@ -1,196 +1,196 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #ifndef FITLOGGER_HPP #define FITLOGGER_HPP /*! * \addtogroup FitBase * @{ */ #include #include #include #include #include "TRandom3.h" #include "Initialiser.h" #include "NuisConfig.h" #define RESET "\033[0m" #define BLACK "\033[30m" /* Black */ #define RED "\033[31m" /* Red */ #define GREEN "\033[32m" /* Green */ #define YELLOW "\033[33m" /* Yellow */ #define BLUE "\033[34m" /* Blue */ #define MAGENTA "\033[35m" /* Magenta */ #define CYAN "\033[36m" /* Cyan */ #define WHITE "\033[37m" /* White */ #define BOLDBLACK "\033[1m\033[30m" /* Bold Black */ #define BOLDRED "\033[1m\033[31m" /* Bold Red */ #define BOLDGREEN "\033[1m\033[32m" /* Bold Green */ #define BOLDYELLOW "\033[1m\033[33m" /* Bold Yellow */ #define BOLDBLUE "\033[1m\033[34m" /* Bold Blue */ #define BOLDMAGENTA "\033[1m\033[35m" /* Bold Magenta */ #define BOLDCYAN "\033[1m\033[36m" /* Bold Cyan */ #define BOLDWHITE "\033[1m\033[37m" /* Bold White */ namespace Logger { extern int log_verb; //!< Current VERBOSITY extern int err_verb; //!< Current ERROR VERBOSITY extern bool external_verb; extern bool use_colors; //!< Use BASH Terminal Colors Flag extern bool super_rainbow_mode; //!< For when fitting gets boring. extern unsigned int super_rainbow_mode_colour; extern bool showtrace; // Quick Tracing for debugging extern int nloggercalls; extern int timelastlog; extern std::streambuf *default_cout; //!< Where the STDOUT stream is currently directed extern std::streambuf *default_cerr; //!< Where the STDERR stream is currently directed extern std::ofstream redirect_stream; //!< Where should unwanted messages be thrown } // namespace Logger /// Returns full path to file currently in #define __FILENAME__ \ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__) // ------ LOGGER FUNCTIONS ------------ // namespace Logger { /// NULL Output Stream extern std::ofstream __LOG_nullstream; /// Logging Stream extern std::ostream *__LOG_outstream; } // namespace Logger /// Fitter VERBOSITY Enumerations /// These go through the different depths of the fitter. /// /// 0 QUIET - Little output. /// 1 FIT - Top Level Minimizer Status /// 2 MIN - Output from the FCN Minimizer Functions /// 3 SAM - Output from each of the samples during setup etc /// 4 REC - Output during each reconfigure. Percentage progress etc. /// 5 SIG - Output during every signal event that is found. /// 6 EVT - Output during every event. -/// -1 DEB - Will print only debugging info wherever a QLOG(DEB) statement was +/// -1 DEB - Will print only debugging info wherever a NUIS_LOG(DEB) statement was /// made enum __LOG_levels { QUIET = 0, FIT, MIN, SAM, REC, SIG, EVT, DEB }; /// Returns log level for a given file/function int __GETLOG_LEVEL(int level, const char *filename, const char *funct); bool LOG_LEVEL(int level); /// Actually runs the logger std::ostream &__OUTLOG(int level, const char *filename, const char *funct, int line); /// Global Logging Definitions -#define QLOGN(level, stream) \ +#define NUIS_LOGN(level, stream) \ { \ if (LOG_LEVEL(level)) { \ __OUTLOG(level, __FILENAME__, __FUNCTION__, __LINE__) << stream; \ } \ }; /// Global Logging Definitions -#define QLOG(level, stream) QLOGN(level, stream << std::endl) +#define NUIS_LOG(level, stream) NUIS_LOGN(level, stream << std::endl) #define BREAK(level) \ { \ \ if (LOG_LEVEL(level)) { \ __OUTLOG(level, __FILENAME__, __FUNCTION__, __LINE__) << std::endl; \ } \ }; /// Return whether logging level is valid bool LOGGING(int level); /// Set Global Verbosity void SETVERBOSITY(int level); /// Set Global Verbosity from String void SETVERBOSITY(std::string verb); /// Set Trace Option void SETTRACE(bool val); // ----------- ERROR FUNCTIONS ---------- // /// Error Stream extern std::ostream *__ERR_outstream; /// Fitter ERROR VERBOSITY Enumerations /// /// 0 QUIET - No Error Output /// 1 FTL - Show errors only if fatal /// 2 WRN - Show Warning messages enum __ERR_levels { ERRQUIET = 0, FTL, WRN }; /// Actually runs the error messager std::ostream &__OUTERR(int level, const char *filename, const char *funct, int line); /// Error Logging Function -#define QERROR(level, stream) \ +#define NUIS_ERR(level, stream) \ { \ __OUTERR(level, __FILENAME__, __FUNCTION__, __LINE__) \ << stream << std::endl; \ }; // ----------- ERROR HANDLING ------------- // /// Exit the program with given error message stream -#define QTHROW(stream) \ +#define NUIS_ABORT(stream) \ { \ __OUTERR(FTL, __FILENAME__, __FUNCTION__, __LINE__) \ << stream << std::endl; \ __OUTERR(FTL, __FILENAME__, __FUNCTION__, __LINE__) \ << "Attempting to save output file." << std::endl; \ if (Config::Get().out && Config::Get().out->IsOpen()) { \ Config::Get().out->Write(); \ Config::Get().out->Close(); \ __OUTERR(FTL, __FILENAME__, __FUNCTION__, __LINE__) \ << "Done." << std::endl; \ } else { \ __OUTERR(FTL, __FILENAME__, __FUNCTION__, __LINE__) \ << "No output file set." << std::endl; \ } \ __OUTERR(FTL, __FILENAME__, __FUNCTION__, __LINE__) \ << "Exiting!" << std::endl; \ std::abort(); \ } // ----------- External Logging ----------- // void SETEXTERNALVERBOSITY(int level); void StopTalking(); void StartTalking(); extern "C" { void shhnuisancepythiaitokay_(void); void canihaznuisancepythia_(void); } #endif diff --git a/src/MCStudies/ElectronFlux_FlatTree.cxx b/src/MCStudies/ElectronFlux_FlatTree.cxx index 81d2341..7411811 100644 --- a/src/MCStudies/ElectronFlux_FlatTree.cxx +++ b/src/MCStudies/ElectronFlux_FlatTree.cxx @@ -1,559 +1,559 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "ElectronFlux_FlatTree.h" //******************************************************************** /// @brief Class to perform MC Studies on a custom measurement ElectronFlux_FlatTree::ElectronFlux_FlatTree(std::string name, std::string inputfile, FitWeight *rw, std::string type, std::string fakeDataFile) { //******************************************************************** // Measurement Details fName = name; eventVariables = NULL; // Define our energy range for flux calcs EnuMin = 0.; EnuMax = 100.; // Arbritrarily high energy limit // Set default fitter flags fIsDiag = true; fIsShape = false; fIsRawEvents = false; nu_4mom = new TLorentzVector(0, 0, 0, 0); pmu = new TLorentzVector(0, 0, 0, 0); ppip = new TLorentzVector(0, 0, 0, 0); ppim = new TLorentzVector(0, 0, 0, 0); ppi0 = new TLorentzVector(0, 0, 0, 0); pprot = new TLorentzVector(0, 0, 0, 0); pneut = new TLorentzVector(0, 0, 0, 0); // This function will sort out the input files automatically and parse all the // inputs,flags,etc. // There may be complex cases where you have to do this by hand, but usually // this will do. Measurement1D::SetupMeasurement(inputfile, type, rw, fakeDataFile); eventVariables = NULL; liteMode = FitPar::Config().GetParB("isLiteMode"); // Setup fDataHist as a placeholder this->fDataHist = new TH1D(("empty_data"), ("empty-data"), 1, 0, 1); this->SetupDefaultHist(); fFullCovar = StatUtils::MakeDiagonalCovarMatrix(fDataHist); covar = StatUtils::GetInvert(fFullCovar); // 1. The generator is organised in SetupMeasurement so it gives the // cross-section in "per nucleon" units. // So some extra scaling for a specific measurement may be required. For // Example to get a "per neutron" measurement on carbon // which we do here, we have to multiple by the number of nucleons 12 and // divide by the number of neutrons 6. this->fScaleFactor = (GetEventHistogram()->Integral("width") * 1E-38 / (fNEvents + 0.)) / this->TotalIntegratedFlux(); - QLOG(SAM," Generic Flux Scaling Factor = " << fScaleFactor); + NUIS_LOG(SAM," Generic Flux Scaling Factor = " << fScaleFactor); if (fScaleFactor <= 0.0) { - QERROR(WRN,"SCALE FACTOR TOO LOW "); + NUIS_ERR(WRN,"SCALE FACTOR TOO LOW "); sleep(20); } // Setup our TTrees this->AddEventVariablesToTree(); this->AddSignalFlagsToTree(); } void ElectronFlux_FlatTree::AddEventVariablesToTree() { // Setup the TTree to save everything if (!eventVariables) { Config::Get().out->cd(); eventVariables = new TTree((this->fName + "_VARS").c_str(), (this->fName + "_VARS").c_str()); } - QLOG(SAM, "Adding Event Variables"); + NUIS_LOG(SAM, "Adding Event Variables"); eventVariables->Branch("Mode", &Mode, "Mode/I"); eventVariables->Branch("PDGnu", &PDGnu, "PDGnu/I"); eventVariables->Branch("Enu_true", &Enu_true, "Enu_true/F"); eventVariables->Branch("Nleptons", &Nleptons, "Nleptons/I"); eventVariables->Branch("MLep", &MLep, "MLep/F"); eventVariables->Branch("ELep", &ELep, "ELep/F"); eventVariables->Branch("TLep", &TLep, "TLep/F"); eventVariables->Branch("CosLep", &CosLep, "CosLep/F"); eventVariables->Branch("CosPmuPpip", &CosPmuPpip, "CosPmuPpip/F"); eventVariables->Branch("CosPmuPpim", &CosPmuPpim, "CosPmuPpim/F"); eventVariables->Branch("CosPmuPpi0", &CosPmuPpi0, "CosPmuPpi0/F"); eventVariables->Branch("CosPmuPprot", &CosPmuPprot, "CosPmuPprot/F"); eventVariables->Branch("CosPmuPneut", &CosPmuPneut, "CosPmuPneut/F"); eventVariables->Branch("Nprotons", &Nprotons, "Nprotons/I"); eventVariables->Branch("MPr", &MPr, "MPr/F"); eventVariables->Branch("EPr", &EPr, "EPr/F"); eventVariables->Branch("TPr", &TPr, "TPr/F"); eventVariables->Branch("CosPr", &CosPr, "CosPr/F"); eventVariables->Branch("CosPprotPneut", &CosPprotPneut, "CosPprotPneut/F"); eventVariables->Branch("Nneutrons", &Nneutrons, "Nneutrons/I"); eventVariables->Branch("MNe", &MNe, "MNe/F"); eventVariables->Branch("ENe", &ENe, "ENe/F"); eventVariables->Branch("TNe", &TNe, "TNe/F"); eventVariables->Branch("CosNe", &CosNe, "CosNe/F"); eventVariables->Branch("Npiplus", &Npiplus, "Npiplus/I"); eventVariables->Branch("MPiP", &MPiP, "MPiP/F"); eventVariables->Branch("EPiP", &EPiP, "EPiP/F"); eventVariables->Branch("TPiP", &TPiP, "TPiP/F"); eventVariables->Branch("CosPiP", &CosPiP, "CosPiP/F"); eventVariables->Branch("CosPpipPprot", &CosPpipPprot, "CosPpipProt/F"); eventVariables->Branch("CosPpipPneut", &CosPpipPneut, "CosPpipPneut/F"); eventVariables->Branch("CosPpipPpim", &CosPpipPpim, "CosPpipPpim/F"); eventVariables->Branch("CosPpipPpi0", &CosPpipPpi0, "CosPpipPpi0/F"); eventVariables->Branch("Npineg", &Npineg, "Npineg/I"); eventVariables->Branch("MPiN", &MPiN, "MPiN/F"); eventVariables->Branch("EPiN", &EPiN, "EPiN/F"); eventVariables->Branch("TPiN", &TPiN, "TPiN/F"); eventVariables->Branch("CosPiN", &CosPiN, "CosPiN/F"); eventVariables->Branch("CosPpimPprot", &CosPpimPprot, "CosPpimPprot/F"); eventVariables->Branch("CosPpimPneut", &CosPpimPneut, "CosPpimPneut/F"); eventVariables->Branch("CosPpimPpi0", &CosPpimPpi0, "CosPpimPpi0/F"); eventVariables->Branch("Npi0", &Npi0, "Npi0/I"); eventVariables->Branch("MPi0", &MPi0, "MPi0/F"); eventVariables->Branch("EPi0", &EPi0, "EPi0/F"); eventVariables->Branch("TPi0", &TPi0, "TPi0/F"); eventVariables->Branch("CosPi0", &CosPi0, "CosPi0/F"); eventVariables->Branch("CosPi0Pprot", &CosPi0Pprot, "CosPi0Pprot/F"); eventVariables->Branch("CosPi0Pneut", &CosPi0Pneut, "CosPi0Pneut/F"); eventVariables->Branch("Nother", &Nother, "Nother/I"); eventVariables->Branch("Q2_true", &Q2_true, "Q2_true/F"); eventVariables->Branch("q0_true", &q0_true, "q0_true/F"); eventVariables->Branch("q3_true", &q3_true, "q3_true/F"); eventVariables->Branch("Enu_QE", &Enu_QE, "Enu_QE/F"); eventVariables->Branch("Q2_QE", &Q2_QE, "Q2_QE/F"); eventVariables->Branch("W_nuc_rest", &W_nuc_rest, "W_nuc_rest/F"); eventVariables->Branch("bjorken_x", &bjorken_x, "bjorken_x/F"); eventVariables->Branch("bjorken_y", &bjorken_y, "bjorken_y/F"); eventVariables->Branch("Erecoil_true", &Erecoil_true, "Erecoil_true/F"); eventVariables->Branch("Erecoil_charged", &Erecoil_charged, "Erecoil_charged/F"); eventVariables->Branch("Erecoil_minerva", &Erecoil_minerva, "Erecoil_minerva/F"); if (!liteMode) { eventVariables->Branch("nu_4mom", &nu_4mom); eventVariables->Branch("pmu_4mom", &pmu); eventVariables->Branch("hm_ppip_4mom", &ppip); eventVariables->Branch("hm_ppim_4mom", &ppim); eventVariables->Branch("hm_ppi0_4mom", &ppi0); eventVariables->Branch("hm_pprot_4mom", &pprot); eventVariables->Branch("hm_pneut_4mom", &pneut); } // Event Scaling Information eventVariables->Branch("Weight", &Weight, "Weight/F"); eventVariables->Branch("InputWeight", &InputWeight, "InputWeight/F"); eventVariables->Branch("RWWeight", &RWWeight, "RWWeight/F"); eventVariables->Branch("FluxWeight", &FluxWeight, "FluxWeight/F"); eventVariables->Branch("fScaleFactor", &fScaleFactor, "fScaleFactor/D"); return; } void ElectronFlux_FlatTree::AddSignalFlagsToTree() { if (!eventVariables) { Config::Get().out->cd(); eventVariables = new TTree((this->fName + "_VARS").c_str(), (this->fName + "_VARS").c_str()); } - QLOG(SAM, "Adding Samples" ); + NUIS_LOG(SAM, "Adding Samples" ); // Signal Definitions from SignalDef.cxx eventVariables->Branch("flagCCINC", &flagCCINC, "flagCCINC/O"); eventVariables->Branch("flagNCINC", &flagNCINC, "flagNCINC/O"); eventVariables->Branch("flagCCQE", &flagCCQE, "flagCCQE/O"); eventVariables->Branch("flagCC0pi", &flagCC0pi, "flagCC0pi/O"); eventVariables->Branch("flagCCQELike", &flagCCQELike, "flagCCQELike/O"); eventVariables->Branch("flagNCEL", &flagNCEL, "flagNCEL/O"); eventVariables->Branch("flagNC0pi", &flagNC0pi, "flagNC0pi/O"); eventVariables->Branch("flagCCcoh", &flagCCcoh, "flagCCcoh/O"); eventVariables->Branch("flagNCcoh", &flagNCcoh, "flagNCcoh/O"); eventVariables->Branch("flagCC1pip", &flagCC1pip, "flagCC1pip/O"); eventVariables->Branch("flagNC1pip", &flagNC1pip, "flagNC1pip/O"); eventVariables->Branch("flagCC1pim", &flagCC1pim, "flagCC1pim/O"); eventVariables->Branch("flagNC1pim", &flagNC1pim, "flagNC1pim/O"); eventVariables->Branch("flagCC1pi0", &flagCC1pi0, "flagCC1pi0/O"); eventVariables->Branch("flagNC1pi0", &flagNC1pi0, "flagNC1pi0/O"); }; //******************************************************************** void ElectronFlux_FlatTree::FillEventVariables(FitEvent *event) { //******************************************************************** // Fill Signal Variables FillSignalFlags(event); - QLOG(DEB, "Filling signal"); + NUIS_LOG(DEB, "Filling signal"); // Function used to extract any variables of interest to the event Mode = event->Mode; Nleptons = 0; Nparticles = 0; PDGnu = 0; PDGLep = 0; Enu_true = Enu_QE = Q2_true = Q2_QE = TLep = TPr = TNe = TPiP = TPiN = TPi0 = -999.9; Nprotons = 0; PPr = EPr = MPr = CosPr = -999.9; Nneutrons = 0; PNe = ENe = MNe = CosNe = -999.9; Npiplus = 0; PPiP = EPiP = MPiP = CosPiP = -999.9; Npineg = 0; PPiN = EPiN = MPiN = CosPiN = -999.9; Npi0 = 0; PPi0 = EPi0 = MPi0 = CosPi0 = -999.9; // All of the angles Clarence added CosPmuPpip = CosPmuPpim = CosPmuPpi0 = CosPmuPprot = CosPmuPneut = CosPpipPprot = CosPpipPneut = CosPpipPpim = CosPpipPpi0 = CosPpimPprot = CosPpimPneut = CosPpimPpi0 = CosPi0Pprot = CosPi0Pneut = CosPprotPneut = -999.9; float proton_highmom = -999.9; float neutron_highmom = -999.9; float piplus_highmom = -999.9; float pineg_highmom = -999.9; float pi0_highmom = -999.9; (*nu_4mom) = event->PartInfo(0)->fP; if (!liteMode) { (*pmu) = TLorentzVector(0, 0, 0, 0); (*ppip) = TLorentzVector(0, 0, 0, 0); (*ppim) = TLorentzVector(0, 0, 0, 0); (*ppi0) = TLorentzVector(0, 0, 0, 0); (*pprot) = TLorentzVector(0, 0, 0, 0); (*pneut) = TLorentzVector(0, 0, 0, 0); } Enu_true = nu_4mom->E(); PDGnu = event->PartInfo(0)->fPID; bool cc = (abs(event->Mode) < 30); (void)cc; // Add all pion distributions for the event. // Add classifier for CC0pi or CC1pi or CCOther // Save Modes Properly // Save low recoil measurements // Start Particle Loop UInt_t npart = event->Npart(); for (UInt_t i = 0; i < npart; i++) { // Skip particles that weren't in the final state bool part_alive = event->PartInfo(i)->fIsAlive and event->PartInfo(i)->Status() == kFinalState; if (!part_alive) continue; // PDG Particle int PDGpart = event->PartInfo(i)->fPID; TLorentzVector part_4mom = event->PartInfo(i)->fP; Nparticles++; // Get Charged Lepton if (PDGpart == 11){ Nleptons++; PDGLep = PDGpart; TLep = FitUtils::T(part_4mom) * 1000.0; PLep = (part_4mom.Vect().Mag()); ELep = (part_4mom.E()); MLep = (part_4mom.Mag()); CosLep = cos(part_4mom.Vect().Angle(nu_4mom->Vect())); pmu = &part_4mom; Q2_true = -1 * (part_4mom - (*nu_4mom)).Mag2(); float ThetaLep = (event->PartInfo(0)) ->fP.Vect() .Angle((event->PartInfo(i))->fP.Vect()); q0_true = (part_4mom - (*nu_4mom)).E(); q3_true = (part_4mom - (*nu_4mom)).Vect().Mag(); // Get W_true with assumption of initial state nucleon at rest float m_n = (float)PhysConst::mass_proton * 1000.; W_nuc_rest = sqrt(-Q2_true + 2 * m_n * (Enu_true - ELep) + m_n * m_n); // Get the Bjorken x and y variables // Assume that E_had = Enu - Emu as in MINERvA bjorken_x = Q2_true / (2 * m_n * (Enu_true - ELep)); bjorken_y = 1 - ELep / Enu_true; // Quasi-elastic ---------------------- // ------------------------------------ // Q2 QE Assuming Carbon Input. Should change this to be dynamic soon. Q2_QE = FitUtils::Q2QErec(part_4mom, cos(ThetaLep), 34., true) * 1000000.0; Enu_QE = FitUtils::EnuQErec(part_4mom, cos(ThetaLep), 34., true) * 1000.0; // Pion Production ---------------------- // -------------------------------------- } else if (PDGpart == 2212) { Nprotons++; if (part_4mom.Vect().Mag() > proton_highmom) { proton_highmom = part_4mom.Vect().Mag(); PPr = (part_4mom.Vect().Mag()); EPr = (part_4mom.E()); TPr = FitUtils::T(part_4mom) * 1000.; MPr = (part_4mom.Mag()); CosPr = cos(part_4mom.Vect().Angle(nu_4mom->Vect())); (*pprot) = part_4mom; } } else if (PDGpart == 2112) { Nneutrons++; if (part_4mom.Vect().Mag() > neutron_highmom) { neutron_highmom = part_4mom.Vect().Mag(); PNe = (part_4mom.Vect().Mag()); ENe = (part_4mom.E()); TNe = FitUtils::T(part_4mom) * 1000.; MNe = (part_4mom.Mag()); CosNe = cos(part_4mom.Vect().Angle(nu_4mom->Vect())); (*pneut) = part_4mom; } } else if (PDGpart == 211) { Npiplus++; if (part_4mom.Vect().Mag() > piplus_highmom) { piplus_highmom = part_4mom.Vect().Mag(); PPiP = (part_4mom.Vect().Mag()); EPiP = (part_4mom.E()); TPiP = FitUtils::T(part_4mom) * 1000.; MPiP = (part_4mom.Mag()); CosPiP = cos(part_4mom.Vect().Angle(nu_4mom->Vect())); (*ppip) = part_4mom; } } else if (PDGpart == -211) { Npineg++; if (part_4mom.Vect().Mag() > pineg_highmom) { pineg_highmom = part_4mom.Vect().Mag(); PPiN = (part_4mom.Vect().Mag()); EPiN = (part_4mom.E()); TPiN = FitUtils::T(part_4mom) * 1000.; MPiN = (part_4mom.Mag()); CosPiN = cos(part_4mom.Vect().Angle(nu_4mom->Vect())); (*ppim) = part_4mom; } } else if (PDGpart == 111) { Npi0++; if (part_4mom.Vect().Mag() > pi0_highmom) { pi0_highmom = part_4mom.Vect().Mag(); PPi0 = (part_4mom.Vect().Mag()); EPi0 = (part_4mom.E()); TPi0 = FitUtils::T(part_4mom) * 1000.; MPi0 = (part_4mom.Mag()); CosPi0 = cos(part_4mom.Vect().Angle(nu_4mom->Vect())); (*ppi0) = part_4mom; } } else { Nother++; } } // Get Recoil Definitions ------ // ----------------------------- Erecoil_true = FitUtils::GetErecoil_TRUE(event); Erecoil_charged = FitUtils::GetErecoil_CHARGED(event); Erecoil_minerva = FitUtils::GetErecoil_MINERvA_LowRecoil(event); // Do the angles between final state particles if (Nleptons > 0 && Npiplus > 0) CosPmuPpip = cos(pmu->Vect().Angle(ppip->Vect())); if (Nleptons > 0 && Npineg > 0) CosPmuPpim = cos(pmu->Vect().Angle(ppim->Vect())); if (Nleptons > 0 && Npi0 > 0) CosPmuPpi0 = cos(pmu->Vect().Angle(ppi0->Vect())); if (Nleptons > 0 && Nprotons > 0) CosPmuPprot = cos(pmu->Vect().Angle(pprot->Vect())); if (Nleptons > 0 && Nneutrons > 0) CosPmuPneut = cos(pmu->Vect().Angle(pneut->Vect())); if (Npiplus > 0 && Nprotons > 0) CosPpipPprot = cos(ppip->Vect().Angle(pprot->Vect())); if (Npiplus > 0 && Nneutrons > 0) CosPpipPneut = cos(ppip->Vect().Angle(pneut->Vect())); if (Npiplus > 0 && Npineg > 0) CosPpipPpim = cos(ppip->Vect().Angle(ppim->Vect())); if (Npiplus > 0 && Npi0 > 0) CosPpipPpi0 = cos(ppip->Vect().Angle(ppi0->Vect())); if (Npineg > 0 && Nprotons > 0) CosPpimPprot = cos(ppim->Vect().Angle(pprot->Vect())); if (Npineg > 0 && Nneutrons > 0) CosPpimPneut = cos(ppim->Vect().Angle(pneut->Vect())); if (Npineg > 0 && Npi0 > 0) CosPpimPpi0 = cos(ppim->Vect().Angle(ppi0->Vect())); if (Npi0 > 0 && Nprotons > 0) CosPi0Pprot = cos(ppi0->Vect().Angle(pprot->Vect())); if (Npi0 > 0 && Nneutrons > 0) CosPi0Pneut = cos(ppi0->Vect().Angle(pneut->Vect())); if (Nprotons > 0 && Nneutrons > 0) CosPprotPneut = cos(pprot->Vect().Angle(pneut->Vect())); // Event Weights ---- // ------------------ Weight = event->RWWeight * event->InputWeight; RWWeight = event->RWWeight; InputWeight = event->InputWeight; FluxWeight = GetFluxHistogram()->GetBinContent(GetFluxHistogram()->FindBin(Enu)) / GetFluxHistogram()->Integral(); xsecScaling = fScaleFactor; if (fScaleFactor <= 0.0) { - QERROR(WRN, "SCALE FACTOR TOO LOW "); + NUIS_ERR(WRN, "SCALE FACTOR TOO LOW "); sleep(20); } // Fill the eventVariables Tree eventVariables->Fill(); return; }; //******************************************************************** void ElectronFlux_FlatTree::Write(std::string drawOpt) { //******************************************************************** // First save the TTree eventVariables->Write(); // Save Flux and Event Histograms too GetInput()->GetFluxHistogram()->Write(); GetInput()->GetEventHistogram()->Write(); return; } //******************************************************************** void ElectronFlux_FlatTree::FillSignalFlags(FitEvent *event) { //******************************************************************** // Some example flags are given from SignalDef. // See src/Utils/SignalDef.cxx for more. int nuPDG = event->PartInfo(0)->fPID; // Generic signal flags flagCCINC = SignalDef::isCCINC(event, nuPDG); flagNCINC = SignalDef::isNCINC(event, nuPDG); flagCCQE = SignalDef::isCCQE(event, nuPDG); flagCCQELike = SignalDef::isCCQELike(event, nuPDG); flagCC0pi = SignalDef::isCC0pi(event, nuPDG); flagNCEL = SignalDef::isNCEL(event, nuPDG); flagNC0pi = SignalDef::isNC0pi(event, nuPDG); flagCCcoh = SignalDef::isCCCOH(event, nuPDG, 211); flagNCcoh = SignalDef::isNCCOH(event, nuPDG, 111); flagCC1pip = SignalDef::isCC1pi(event, nuPDG, 211); flagNC1pip = SignalDef::isNC1pi(event, nuPDG, 211); flagCC1pim = SignalDef::isCC1pi(event, nuPDG, -211); flagNC1pim = SignalDef::isNC1pi(event, nuPDG, -211); flagCC1pi0 = SignalDef::isCC1pi(event, nuPDG, 111); flagNC1pi0 = SignalDef::isNC1pi(event, nuPDG, 111); } // ------------------------------------------------------------------- // Purely MC Plot // Following functions are just overrides to handle this // ------------------------------------------------------------------- //******************************************************************** /// Everything is classed as signal... bool ElectronFlux_FlatTree::isSignal(FitEvent *event) { //******************************************************************** (void)event; return true; }; //******************************************************************** void ElectronFlux_FlatTree::ScaleEvents() { //******************************************************************** // Saving everything to a TTree so no scaling required return; } //******************************************************************** void ElectronFlux_FlatTree::ApplyNormScale(float norm) { //******************************************************************** // Saving everything to a TTree so no scaling required this->fCurrentNorm = norm; return; } //******************************************************************** void ElectronFlux_FlatTree::FillHistograms() { //******************************************************************** // No Histograms need filling........ return; } //******************************************************************** void ElectronFlux_FlatTree::ResetAll() { //******************************************************************** eventVariables->Reset(); return; } //******************************************************************** float ElectronFlux_FlatTree::GetChi2() { //******************************************************************** // No Likelihood to test, purely MC return 0.0; } diff --git a/src/MCStudies/GenericFlux_Tester.cxx b/src/MCStudies/GenericFlux_Tester.cxx index dd778e1..959a1bd 100644 --- a/src/MCStudies/GenericFlux_Tester.cxx +++ b/src/MCStudies/GenericFlux_Tester.cxx @@ -1,591 +1,591 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "GenericFlux_Tester.h" //******************************************************************** /// @brief Class to perform MC Studies on a custom measurement GenericFlux_Tester::GenericFlux_Tester(std::string name, std::string inputfile, FitWeight *rw, std::string type, std::string fakeDataFile) { //******************************************************************** // Measurement Details fName = name; eventVariables = NULL; // Define our energy range for flux calcs EnuMin = 0.; EnuMax = 1E10; // Arbritrarily high energy limit // Set default fitter flags fIsDiag = true; fIsShape = false; fIsRawEvents = false; nu_4mom = new TLorentzVector(0, 0, 0, 0); pmu = new TLorentzVector(0, 0, 0, 0); ppip = new TLorentzVector(0, 0, 0, 0); ppim = new TLorentzVector(0, 0, 0, 0); ppi0 = new TLorentzVector(0, 0, 0, 0); pprot = new TLorentzVector(0, 0, 0, 0); pneut = new TLorentzVector(0, 0, 0, 0); // This function will sort out the input files automatically and parse all the // inputs,flags,etc. // There may be complex cases where you have to do this by hand, but usually // this will do. Measurement1D::SetupMeasurement(inputfile, type, rw, fakeDataFile); eventVariables = NULL; liteMode = Config::Get().GetParB("isLiteMode"); if (Config::HasPar("EnuMin")) { EnuMin = Config::GetParD("EnuMin"); } if (Config::HasPar("EnuMax")) { EnuMax = Config::GetParD("EnuMax"); } // Setup fDataHist as a placeholder this->fDataHist = new TH1D(("empty_data"), ("empty-data"), 1, 0, 1); this->SetupDefaultHist(); fFullCovar = StatUtils::MakeDiagonalCovarMatrix(fDataHist); covar = StatUtils::GetInvert(fFullCovar); // 1. The generator is organised in SetupMeasurement so it gives the // cross-section in "per nucleon" units. // So some extra scaling for a specific measurement may be required. For // Example to get a "per neutron" measurement on carbon // which we do here, we have to multiple by the number of nucleons 12 and // divide by the number of neutrons 6. // N.B. MeasurementBase::PredictedEventRate includes the 1E-38 factor that is // often included here in other classes that directly integrate the event // histogram. This method is used here as it now respects EnuMin and EnuMax // correctly. this->fScaleFactor = (this->PredictedEventRate("width", 0, 1000) / double(fNEvents)) / this->TotalIntegratedFlux(); if (fScaleFactor <= 0.0) { - QTHROW("SCALE FACTOR TOO LOW "); + NUIS_ABORT("SCALE FACTOR TOO LOW "); } - QLOG(SAM, " Generic Flux Scaling Factor = " + NUIS_LOG(SAM, " Generic Flux Scaling Factor = " << fScaleFactor << " [= " << (GetEventHistogram()->Integral("width") * 1E-38) << "/(" << (fNEvents + 0.) << "*" << this->TotalIntegratedFlux() << ")]"); // Setup our TTrees this->AddEventVariablesToTree(); this->AddSignalFlagsToTree(); } void GenericFlux_Tester::AddEventVariablesToTree() { // Setup the TTree to save everything if (!eventVariables) { Config::Get().out->cd(); eventVariables = new TTree((this->fName + "_VARS").c_str(), (this->fName + "_VARS").c_str()); } - QLOG(SAM, "Adding Event Variables"); + NUIS_LOG(SAM, "Adding Event Variables"); eventVariables->Branch("Mode", &Mode, "Mode/I"); eventVariables->Branch("PDGnu", &PDGnu, "PDGnu/I"); eventVariables->Branch("Enu_true", &Enu_true, "Enu_true/F"); eventVariables->Branch("Nleptons", &Nleptons, "Nleptons/I"); // all sensible eventVariables->Branch("MLep", &MLep, "MLep/F"); eventVariables->Branch("ELep", &ELep, "ELep/F"); // negative -999 eventVariables->Branch("TLep", &TLep, "TLep/F"); eventVariables->Branch("CosLep", &CosLep, "CosLep/F"); eventVariables->Branch("CosPmuPpip", &CosPmuPpip, "CosPmuPpip/F"); eventVariables->Branch("CosPmuPpim", &CosPmuPpim, "CosPmuPpim/F"); eventVariables->Branch("CosPmuPpi0", &CosPmuPpi0, "CosPmuPpi0/F"); eventVariables->Branch("CosPmuPprot", &CosPmuPprot, "CosPmuPprot/F"); eventVariables->Branch("CosPmuPneut", &CosPmuPneut, "CosPmuPneut/F"); eventVariables->Branch("Nprotons", &Nprotons, "Nprotons/I"); eventVariables->Branch("MPr", &MPr, "MPr/F"); eventVariables->Branch("EPr", &EPr, "EPr/F"); eventVariables->Branch("TPr", &TPr, "TPr/F"); eventVariables->Branch("CosPr", &CosPr, "CosPr/F"); eventVariables->Branch("CosPprotPneut", &CosPprotPneut, "CosPprotPneut/F"); eventVariables->Branch("Nneutrons", &Nneutrons, "Nneutrons/I"); eventVariables->Branch("MNe", &MNe, "MNe/F"); eventVariables->Branch("ENe", &ENe, "ENe/F"); eventVariables->Branch("TNe", &TNe, "TNe/F"); eventVariables->Branch("CosNe", &CosNe, "CosNe/F"); eventVariables->Branch("Npiplus", &Npiplus, "Npiplus/I"); eventVariables->Branch("MPiP", &MPiP, "MPiP/F"); eventVariables->Branch("EPiP", &EPiP, "EPiP/F"); eventVariables->Branch("TPiP", &TPiP, "TPiP/F"); eventVariables->Branch("CosPiP", &CosPiP, "CosPiP/F"); eventVariables->Branch("CosPpipPprot", &CosPpipPprot, "CosPpipProt/F"); eventVariables->Branch("CosPpipPneut", &CosPpipPneut, "CosPpipPneut/F"); eventVariables->Branch("CosPpipPpim", &CosPpipPpim, "CosPpipPpim/F"); eventVariables->Branch("CosPpipPpi0", &CosPpipPpi0, "CosPpipPpi0/F"); eventVariables->Branch("Npineg", &Npineg, "Npineg/I"); eventVariables->Branch("MPiN", &MPiN, "MPiN/F"); eventVariables->Branch("EPiN", &EPiN, "EPiN/F"); eventVariables->Branch("TPiN", &TPiN, "TPiN/F"); eventVariables->Branch("CosPiN", &CosPiN, "CosPiN/F"); eventVariables->Branch("CosPpimPprot", &CosPpimPprot, "CosPpimPprot/F"); eventVariables->Branch("CosPpimPneut", &CosPpimPneut, "CosPpimPneut/F"); eventVariables->Branch("CosPpimPpi0", &CosPpimPpi0, "CosPpimPpi0/F"); eventVariables->Branch("Npi0", &Npi0, "Npi0/I"); eventVariables->Branch("MPi0", &MPi0, "MPi0/F"); eventVariables->Branch("EPi0", &EPi0, "EPi0/F"); eventVariables->Branch("TPi0", &TPi0, "TPi0/F"); eventVariables->Branch("CosPi0", &CosPi0, "CosPi0/F"); eventVariables->Branch("CosPi0Pprot", &CosPi0Pprot, "CosPi0Pprot/F"); eventVariables->Branch("CosPi0Pneut", &CosPi0Pneut, "CosPi0Pneut/F"); eventVariables->Branch("Nother", &Nother, "Nother/I"); eventVariables->Branch("Q2_true", &Q2_true, "Q2_true/F"); eventVariables->Branch("q0_true", &q0_true, "q0_true/F"); eventVariables->Branch("q3_true", &q3_true, "q3_true/F"); eventVariables->Branch("Enu_QE", &Enu_QE, "Enu_QE/F"); eventVariables->Branch("Q2_QE", &Q2_QE, "Q2_QE/F"); eventVariables->Branch("W_nuc_rest", &W_nuc_rest, "W_nuc_rest/F"); eventVariables->Branch("bjorken_x", &bjorken_x, "bjorken_x/F"); eventVariables->Branch("bjorken_y", &bjorken_y, "bjorken_y/F"); eventVariables->Branch("Erecoil_true", &Erecoil_true, "Erecoil_true/F"); eventVariables->Branch("Erecoil_charged", &Erecoil_charged, "Erecoil_charged/F"); eventVariables->Branch("Erecoil_minerva", &Erecoil_minerva, "Erecoil_minerva/F"); if (!liteMode) { eventVariables->Branch("nu_4mom", &nu_4mom); eventVariables->Branch("pmu_4mom", &pmu); eventVariables->Branch("hm_ppip_4mom", &ppip); eventVariables->Branch("hm_ppim_4mom", &ppim); eventVariables->Branch("hm_ppi0_4mom", &ppi0); eventVariables->Branch("hm_pprot_4mom", &pprot); eventVariables->Branch("hm_pneut_4mom", &pneut); } // Event Scaling Information eventVariables->Branch("Weight", &Weight, "Weight/F"); eventVariables->Branch("InputWeight", &InputWeight, "InputWeight/F"); eventVariables->Branch("RWWeight", &RWWeight, "RWWeight/F"); eventVariables->Branch("FluxWeight", &FluxWeight, "FluxWeight/F"); eventVariables->Branch("fScaleFactor", &fScaleFactor, "fScaleFactor/D"); return; } void GenericFlux_Tester::AddSignalFlagsToTree() { if (!eventVariables) { Config::Get().out->cd(); eventVariables = new TTree((this->fName + "_VARS").c_str(), (this->fName + "_VARS").c_str()); } - QLOG(SAM, "Adding signal flags"); + NUIS_LOG(SAM, "Adding signal flags"); // Signal Definitions from SignalDef.cxx eventVariables->Branch("flagCCINC", &flagCCINC, "flagCCINC/O"); eventVariables->Branch("flagNCINC", &flagNCINC, "flagNCINC/O"); eventVariables->Branch("flagCCQE", &flagCCQE, "flagCCQE/O"); eventVariables->Branch("flagCC0pi", &flagCC0pi, "flagCC0pi/O"); eventVariables->Branch("flagCCQELike", &flagCCQELike, "flagCCQELike/O"); eventVariables->Branch("flagNCEL", &flagNCEL, "flagNCEL/O"); eventVariables->Branch("flagNC0pi", &flagNC0pi, "flagNC0pi/O"); eventVariables->Branch("flagCCcoh", &flagCCcoh, "flagCCcoh/O"); eventVariables->Branch("flagNCcoh", &flagNCcoh, "flagNCcoh/O"); eventVariables->Branch("flagCC1pip", &flagCC1pip, "flagCC1pip/O"); eventVariables->Branch("flagNC1pip", &flagNC1pip, "flagNC1pip/O"); eventVariables->Branch("flagCC1pim", &flagCC1pim, "flagCC1pim/O"); eventVariables->Branch("flagNC1pim", &flagNC1pim, "flagNC1pim/O"); eventVariables->Branch("flagCC1pi0", &flagCC1pi0, "flagCC1pi0/O"); eventVariables->Branch("flagNC1pi0", &flagNC1pi0, "flagNC1pi0/O"); }; //******************************************************************** void GenericFlux_Tester::ResetVariables() { //******************************************************************** // Reset neutrino PDG PDGnu = 0; // Reset energies Enu_true = Enu_QE = __BAD_FLOAT__; // Reset auxillaries Q2_true = Q2_QE = W_nuc_rest = bjorken_x = bjorken_y = q0_true = q3_true = Erecoil_true = Erecoil_charged = Erecoil_minerva = __BAD_FLOAT__; // Reset particle counters Nparticles = Nleptons = Nother = Nprotons = Nneutrons = Npiplus = Npineg = Npi0 = 0; // Reset Lepton PDG PDGLep = 0; // Reset Lepton variables TLep = CosLep = ELep = PLep = MLep = __BAD_FLOAT__; // Rset proton variables PPr = CosPr = EPr = TPr = MPr = __BAD_FLOAT__; // Reset neutron variables PNe = CosNe = ENe = TNe = MNe = __BAD_FLOAT__; // Reset pi+ variables PPiP = CosPiP = EPiP = TPiP = MPiP = __BAD_FLOAT__; // Reset pi- variables PPiN = CosPiN = EPiN = TPiN = MPiN = __BAD_FLOAT__; // Reset pi0 variables PPi0 = CosPi0 = EPi0 = TPi0 = MPi0 = __BAD_FLOAT__; // Reset the cos angles CosPmuPpip = CosPmuPpim = CosPmuPpi0 = CosPmuPprot = CosPmuPneut = CosPpipPprot = CosPpipPneut = CosPpipPpim = CosPpipPpi0 = CosPpimPprot = CosPpimPneut = CosPpimPpi0 = CosPi0Pprot = CosPi0Pneut = CosPprotPneut = __BAD_FLOAT__; } //******************************************************************** void GenericFlux_Tester::FillEventVariables(FitEvent *event) { //******************************************************************** // Fill Signal Variables FillSignalFlags(event); - QLOG(DEB, "Filling signal"); + NUIS_LOG(DEB, "Filling signal"); // Reset the private variables (see header) ResetVariables(); // Function used to extract any variables of interest to the event Mode = event->Mode; // Reset the highest momentum variables float proton_highmom = __BAD_FLOAT__; float neutron_highmom = __BAD_FLOAT__; float piplus_highmom = __BAD_FLOAT__; float pineg_highmom = __BAD_FLOAT__; float pi0_highmom = __BAD_FLOAT__; (*nu_4mom) = event->PartInfo(0)->fP; if (!liteMode) { (*pmu) = TLorentzVector(0, 0, 0, 0); (*ppip) = TLorentzVector(0, 0, 0, 0); (*ppim) = TLorentzVector(0, 0, 0, 0); (*ppi0) = TLorentzVector(0, 0, 0, 0); (*pprot) = TLorentzVector(0, 0, 0, 0); (*pneut) = TLorentzVector(0, 0, 0, 0); } Enu_true = nu_4mom->E(); PDGnu = event->PartInfo(0)->fPID; bool cc = (abs(event->Mode) < 30); (void)cc; // Add all pion distributions for the event. // Add classifier for CC0pi or CC1pi or CCOther // Save Modes Properly // Save low recoil measurements // Start Particle Loop UInt_t npart = event->Npart(); for (UInt_t i = 0; i < npart; i++) { // Skip particles that weren't in the final state bool part_alive = event->PartInfo(i)->fIsAlive and event->PartInfo(i)->Status() == kFinalState; if (!part_alive) continue; // PDG Particle int PDGpart = event->PartInfo(i)->fPID; TLorentzVector part_4mom = event->PartInfo(i)->fP; Nparticles++; // Get Charged Lepton if (abs(PDGpart) == abs(PDGnu) - 1) { Nleptons++; PDGLep = PDGpart; TLep = FitUtils::T(part_4mom) * 1000.0; PLep = (part_4mom.Vect().Mag()); ELep = (part_4mom.E()); MLep = (part_4mom.Mag()); CosLep = cos(part_4mom.Vect().Angle(nu_4mom->Vect())); (*pmu) = part_4mom; Q2_true = -1 * (part_4mom - (*nu_4mom)).Mag2(); float ThetaLep = (event->PartInfo(0)) ->fP.Vect() .Angle((event->PartInfo(i))->fP.Vect()); q0_true = (part_4mom - (*nu_4mom)).E(); q3_true = (part_4mom - (*nu_4mom)).Vect().Mag(); // Get W_true with assumption of initial state nucleon at rest float m_n = (float)PhysConst::mass_proton * 1000.; W_nuc_rest = sqrt(-Q2_true + 2 * m_n * (Enu_true - ELep) + m_n * m_n); // Get the Bjorken x and y variables // Assume that E_had = Enu - Emu as in MINERvA bjorken_x = Q2_true / (2 * m_n * (Enu_true - ELep)); bjorken_y = 1 - ELep / Enu_true; // Quasi-elastic ---------------------- // ------------------------------------ // Q2 QE Assuming Carbon Input. Should change this to be dynamic soon. Q2_QE = FitUtils::Q2QErec(part_4mom, cos(ThetaLep), 34., true) * 1000000.0; Enu_QE = FitUtils::EnuQErec(part_4mom, cos(ThetaLep), 34., true) * 1000.0; // Pion Production ---------------------- // -------------------------------------- } else if (PDGpart == 2212) { Nprotons++; if (part_4mom.Vect().Mag() > proton_highmom) { proton_highmom = part_4mom.Vect().Mag(); PPr = (part_4mom.Vect().Mag()); EPr = (part_4mom.E()); TPr = FitUtils::T(part_4mom) * 1000.; MPr = (part_4mom.Mag()); CosPr = cos(part_4mom.Vect().Angle(nu_4mom->Vect())); (*pprot) = part_4mom; } } else if (PDGpart == 2112) { Nneutrons++; if (part_4mom.Vect().Mag() > neutron_highmom) { neutron_highmom = part_4mom.Vect().Mag(); PNe = (part_4mom.Vect().Mag()); ENe = (part_4mom.E()); TNe = FitUtils::T(part_4mom) * 1000.; MNe = (part_4mom.Mag()); CosNe = cos(part_4mom.Vect().Angle(nu_4mom->Vect())); (*pneut) = part_4mom; } } else if (PDGpart == 211) { Npiplus++; if (part_4mom.Vect().Mag() > piplus_highmom) { piplus_highmom = part_4mom.Vect().Mag(); PPiP = (part_4mom.Vect().Mag()); EPiP = (part_4mom.E()); TPiP = FitUtils::T(part_4mom) * 1000.; MPiP = (part_4mom.Mag()); CosPiP = cos(part_4mom.Vect().Angle(nu_4mom->Vect())); (*ppip) = part_4mom; } } else if (PDGpart == -211) { Npineg++; if (part_4mom.Vect().Mag() > pineg_highmom) { pineg_highmom = part_4mom.Vect().Mag(); PPiN = (part_4mom.Vect().Mag()); EPiN = (part_4mom.E()); TPiN = FitUtils::T(part_4mom) * 1000.; MPiN = (part_4mom.Mag()); CosPiN = cos(part_4mom.Vect().Angle(nu_4mom->Vect())); (*ppim) = part_4mom; } } else if (PDGpart == 111) { Npi0++; if (part_4mom.Vect().Mag() > pi0_highmom) { pi0_highmom = part_4mom.Vect().Mag(); PPi0 = (part_4mom.Vect().Mag()); EPi0 = (part_4mom.E()); TPi0 = FitUtils::T(part_4mom) * 1000.; MPi0 = (part_4mom.Mag()); CosPi0 = cos(part_4mom.Vect().Angle(nu_4mom->Vect())); (*ppi0) = part_4mom; } } else { Nother++; } } // Get Recoil Definitions ------ // ----------------------------- Erecoil_true = FitUtils::GetErecoil_TRUE(event); Erecoil_charged = FitUtils::GetErecoil_CHARGED(event); Erecoil_minerva = FitUtils::GetErecoil_MINERvA_LowRecoil(event); // Do the angles between final state particles if (Nleptons > 0 && Npiplus > 0) CosPmuPpip = cos(pmu->Vect().Angle(ppip->Vect())); if (Nleptons > 0 && Npineg > 0) CosPmuPpim = cos(pmu->Vect().Angle(ppim->Vect())); if (Nleptons > 0 && Npi0 > 0) CosPmuPpi0 = cos(pmu->Vect().Angle(ppi0->Vect())); if (Nleptons > 0 && Nprotons > 0) CosPmuPprot = cos(pmu->Vect().Angle(pprot->Vect())); if (Nleptons > 0 && Nneutrons > 0) CosPmuPneut = cos(pmu->Vect().Angle(pneut->Vect())); if (Npiplus > 0 && Nprotons > 0) CosPpipPprot = cos(ppip->Vect().Angle(pprot->Vect())); if (Npiplus > 0 && Nneutrons > 0) CosPpipPneut = cos(ppip->Vect().Angle(pneut->Vect())); if (Npiplus > 0 && Npineg > 0) CosPpipPpim = cos(ppip->Vect().Angle(ppim->Vect())); if (Npiplus > 0 && Npi0 > 0) CosPpipPpi0 = cos(ppip->Vect().Angle(ppi0->Vect())); if (Npineg > 0 && Nprotons > 0) CosPpimPprot = cos(ppim->Vect().Angle(pprot->Vect())); if (Npineg > 0 && Nneutrons > 0) CosPpimPneut = cos(ppim->Vect().Angle(pneut->Vect())); if (Npineg > 0 && Npi0 > 0) CosPpimPpi0 = cos(ppim->Vect().Angle(ppi0->Vect())); if (Npi0 > 0 && Nprotons > 0) CosPi0Pprot = cos(ppi0->Vect().Angle(pprot->Vect())); if (Npi0 > 0 && Nneutrons > 0) CosPi0Pneut = cos(ppi0->Vect().Angle(pneut->Vect())); if (Nprotons > 0 && Nneutrons > 0) CosPprotPneut = cos(pprot->Vect().Angle(pneut->Vect())); // Event Weights ---- // ------------------ Weight = event->RWWeight * event->InputWeight; RWWeight = event->RWWeight; InputWeight = event->InputWeight; FluxWeight = GetFluxHistogram()->GetBinContent(GetFluxHistogram()->FindBin(Enu)) / GetFluxHistogram()->Integral(); // Fill the eventVariables Tree eventVariables->Fill(); return; }; //******************************************************************** void GenericFlux_Tester::Write(std::string drawOpt) { //******************************************************************** // First save the TTree eventVariables->Write(); // Save Flux and Event Histograms too GetInput()->GetFluxHistogram()->Write(); GetInput()->GetEventHistogram()->Write(); return; } //******************************************************************** void GenericFlux_Tester::FillSignalFlags(FitEvent *event) { //******************************************************************** // Some example flags are given from SignalDef. // See src/Utils/SignalDef.cxx for more. int nuPDG = event->PartInfo(0)->fPID; // Generic signal flags flagCCINC = SignalDef::isCCINC(event, nuPDG); flagNCINC = SignalDef::isNCINC(event, nuPDG); flagCCQE = SignalDef::isCCQE(event, nuPDG); flagCCQELike = SignalDef::isCCQELike(event, nuPDG); flagCC0pi = SignalDef::isCC0pi(event, nuPDG); flagNCEL = SignalDef::isNCEL(event, nuPDG); flagNC0pi = SignalDef::isNC0pi(event, nuPDG); flagCCcoh = SignalDef::isCCCOH(event, nuPDG, 211); flagNCcoh = SignalDef::isNCCOH(event, nuPDG, 111); flagCC1pip = SignalDef::isCC1pi(event, nuPDG, 211); flagNC1pip = SignalDef::isNC1pi(event, nuPDG, 211); flagCC1pim = SignalDef::isCC1pi(event, nuPDG, -211); flagNC1pim = SignalDef::isNC1pi(event, nuPDG, -211); flagCC1pi0 = SignalDef::isCC1pi(event, nuPDG, 111); flagNC1pi0 = SignalDef::isNC1pi(event, nuPDG, 111); } // ------------------------------------------------------------------- // Purely MC Plot // Following functions are just overrides to handle this // ------------------------------------------------------------------- //******************************************************************** /// Everything is classed as signal... bool GenericFlux_Tester::isSignal(FitEvent *event) { //******************************************************************** (void)event; return true; }; //******************************************************************** void GenericFlux_Tester::ScaleEvents() { //******************************************************************** // Saving everything to a TTree so no scaling required return; } //******************************************************************** void GenericFlux_Tester::ApplyNormScale(float norm) { //******************************************************************** // Saving everything to a TTree so no scaling required this->fCurrentNorm = norm; return; } //******************************************************************** void GenericFlux_Tester::FillHistograms() { //******************************************************************** // No Histograms need filling........ return; } //******************************************************************** void GenericFlux_Tester::ResetAll() { //******************************************************************** eventVariables->Reset(); return; } //******************************************************************** float GenericFlux_Tester::GetChi2() { //******************************************************************** // No Likelihood to test, purely MC return 0.0; } diff --git a/src/MCStudies/GenericFlux_Vectors.cxx b/src/MCStudies/GenericFlux_Vectors.cxx index a0ab3af..b55f58c 100644 --- a/src/MCStudies/GenericFlux_Vectors.cxx +++ b/src/MCStudies/GenericFlux_Vectors.cxx @@ -1,441 +1,441 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "GenericFlux_Vectors.h" GenericFlux_Vectors::GenericFlux_Vectors(std::string name, std::string inputfile, FitWeight *rw, std::string type, std::string fakeDataFile) { // Measurement Details fName = name; eventVariables = NULL; // Define our energy range for flux calcs EnuMin = 0.; EnuMax = 1E10; // Arbritrarily high energy limit if (Config::HasPar("EnuMin")) { EnuMin = Config::GetParD("EnuMin"); } if (Config::HasPar("EnuMax")) { EnuMax = Config::GetParD("EnuMax"); } SavePreFSI = Config::Get().GetParB("nuisflat_SavePreFSI"); - QLOG(SAM, + NUIS_LOG(SAM, "Running GenericFlux_Vectors saving pre-FSI particles? " << SavePreFSI); // Set default fitter flags fIsDiag = true; fIsShape = false; fIsRawEvents = false; // This function will sort out the input files automatically and parse all the // inputs,flags,etc. // There may be complex cases where you have to do this by hand, but usually // this will do. Measurement1D::SetupMeasurement(inputfile, type, rw, fakeDataFile); eventVariables = NULL; // Setup fDataHist as a placeholder this->fDataHist = new TH1D(("empty_data"), ("empty-data"), 1, 0, 1); this->SetupDefaultHist(); fFullCovar = StatUtils::MakeDiagonalCovarMatrix(fDataHist); covar = StatUtils::GetInvert(fFullCovar); // 1. The generator is organised in SetupMeasurement so it gives the // cross-section in "per nucleon" units. // So some extra scaling for a specific measurement may be required. For // Example to get a "per neutron" measurement on carbon // which we do here, we have to multiple by the number of nucleons 12 and // divide by the number of neutrons 6. // N.B. MeasurementBase::PredictedEventRate includes the 1E-38 factor that is // often included here in other classes that directly integrate the event // histogram. This method is used here as it now respects EnuMin and EnuMax // correctly. this->fScaleFactor = (this->PredictedEventRate("width", 0, EnuMax) / double(fNEvents)) / this->TotalIntegratedFlux("width"); - QLOG(SAM, " Generic Flux Scaling Factor = " + NUIS_LOG(SAM, " Generic Flux Scaling Factor = " << fScaleFactor << " [= " << (GetEventHistogram()->Integral("width") * 1E-38) << "/(" << (fNEvents + 0.) << "*" << TotalIntegratedFlux("width") << ")]"); if (fScaleFactor <= 0.0) { - QTHROW("SCALE FACTOR TOO LOW"); + NUIS_ABORT("SCALE FACTOR TOO LOW"); } // Setup our TTrees this->AddEventVariablesToTree(); this->AddSignalFlagsToTree(); } void GenericFlux_Vectors::AddEventVariablesToTree() { // Setup the TTree to save everything if (!eventVariables) { Config::Get().out->cd(); eventVariables = new TTree((this->fName + "_VARS").c_str(), (this->fName + "_VARS").c_str()); } - QLOG(SAM, "Adding Event Variables"); + NUIS_LOG(SAM, "Adding Event Variables"); eventVariables->Branch("Mode", &Mode, "Mode/I"); eventVariables->Branch("cc", &cc, "cc/B"); eventVariables->Branch("PDGnu", &PDGnu, "PDGnu/I"); eventVariables->Branch("Enu_true", &Enu_true, "Enu_true/F"); eventVariables->Branch("tgt", &tgt, "tgt/I"); eventVariables->Branch("tgta", &tgta, "tgta/I"); eventVariables->Branch("tgtz", &tgtz, "tgtz/I"); eventVariables->Branch("PDGLep", &PDGLep, "PDGLep/I"); eventVariables->Branch("ELep", &ELep, "ELep/F"); eventVariables->Branch("CosLep", &CosLep, "CosLep/F"); // Basic interaction kinematics eventVariables->Branch("Q2", &Q2, "Q2/F"); eventVariables->Branch("q0", &q0, "q0/F"); eventVariables->Branch("q3", &q3, "q3/F"); eventVariables->Branch("Enu_QE", &Enu_QE, "Enu_QE/F"); eventVariables->Branch("Q2_QE", &Q2_QE, "Q2_QE/F"); eventVariables->Branch("W_nuc_rest", &W_nuc_rest, "W_nuc_rest/F"); eventVariables->Branch("W", &W, "W/F"); eventVariables->Branch("W_genie", &W_genie, "W_genie/F"); eventVariables->Branch("x", &x, "x/F"); eventVariables->Branch("y", &y, "y/F"); eventVariables->Branch("Eav", &Eav, "Eav/F"); eventVariables->Branch("EavAlt", &EavAlt, "EavAlt/F"); eventVariables->Branch("dalphat", &dalphat, "dalphat/F"); eventVariables->Branch("dpt", &dpt, "dpt/F"); eventVariables->Branch("dphit", &dphit, "dphit/F"); eventVariables->Branch("pnreco_C", &pnreco_C, "pnreco_C/F"); // Save outgoing particle vectors eventVariables->Branch("nfsp", &nfsp, "nfsp/I"); eventVariables->Branch("px", px, "px[nfsp]/F"); eventVariables->Branch("py", py, "py[nfsp]/F"); eventVariables->Branch("pz", pz, "pz[nfsp]/F"); eventVariables->Branch("E", E, "E[nfsp]/F"); eventVariables->Branch("pdg", pdg, "pdg[nfsp]/I"); eventVariables->Branch("pdg_rank", pdg_rank, "pdg_rank[nfsp]/I"); // Save init particle vectors eventVariables->Branch("ninitp", &ninitp, "ninitp/I"); eventVariables->Branch("px_init", px_init, "px_init[ninitp]/F"); eventVariables->Branch("py_init", py_init, "py_init[ninitp]/F"); eventVariables->Branch("pz_init", pz_init, "pz_init[ninitp]/F"); eventVariables->Branch("E_init", E_init, "E_init[ninitp]/F"); eventVariables->Branch("pdg_init", pdg_init, "pdg_init[ninitp]/I"); // Save pre-FSI vectors eventVariables->Branch("nvertp", &nvertp, "nvertp/I"); eventVariables->Branch("px_vert", px_vert, "px_vert[nvertp]/F"); eventVariables->Branch("py_vert", py_vert, "py_vert[nvertp]/F"); eventVariables->Branch("pz_vert", pz_vert, "pz_vert[nvertp]/F"); eventVariables->Branch("E_vert", E_vert, "E_vert[nvertp]/F"); eventVariables->Branch("pdg_vert", pdg_vert, "pdg_vert[nvertp]/I"); // Event Scaling Information eventVariables->Branch("Weight", &Weight, "Weight/F"); eventVariables->Branch("InputWeight", &InputWeight, "InputWeight/F"); eventVariables->Branch("RWWeight", &RWWeight, "RWWeight/F"); // Should be a double because may be 1E-39 and less eventVariables->Branch("fScaleFactor", &fScaleFactor, "fScaleFactor/D"); // The customs eventVariables->Branch("CustomWeight", &CustomWeight, "CustomWeight/F"); eventVariables->Branch("CustomWeightArray", CustomWeightArray, "CustomWeightArray[6]/F"); return; } void GenericFlux_Vectors::FillEventVariables(FitEvent *event) { ResetVariables(); // Fill Signal Variables FillSignalFlags(event); - QLOG(DEB, "Filling signal"); + NUIS_LOG(DEB, "Filling signal"); // Now fill the information Mode = event->Mode; cc = event->IsCC(); // Get the incoming neutrino and outgoing lepton FitParticle *nu = event->GetBeamPart(); FitParticle *lep = event->GetHMFSAnyLepton(); PDGnu = nu->fPID; Enu_true = nu->fP.E() / 1E3; tgt = event->fTargetPDG; tgta = event->fTargetA; tgtz = event->fTargetZ; if (lep != NULL) { PDGLep = lep->fPID; ELep = lep->fP.E() / 1E3; CosLep = cos(nu->fP.Vect().Angle(lep->fP.Vect())); // Basic interaction kinematics Q2 = -1 * (nu->fP - lep->fP).Mag2() / 1E6; q0 = (nu->fP - lep->fP).E() / 1E3; q3 = (nu->fP - lep->fP).Vect().Mag() / 1E3; // These assume C12 binding from MINERvA... not ideal Enu_QE = FitUtils::EnuQErec(lep->fP, CosLep, 34., true); Q2_QE = FitUtils::Q2QErec(lep->fP, CosLep, 34., true); Eav = FitUtils::GetErecoil_MINERvA_LowRecoil(event) / 1.E3; EavAlt = FitUtils::Eavailable(event) / 1.E3; // Get W_true with assumption of initial state nucleon at rest float m_n = (float)PhysConst::mass_proton; // Q2 assuming nucleon at rest W_nuc_rest = sqrt(-Q2 + 2 * m_n * q0 + m_n * m_n); // True Q2 W = sqrt(-Q2 + 2 * m_n * q0 + m_n * m_n); x = Q2 / (2 * m_n * q0); y = 1 - ELep / Enu_true; dalphat = FitUtils::Get_STV_dalphat(event, PDGnu, true); dpt = FitUtils::Get_STV_dpt(event, PDGnu, true); dphit = FitUtils::Get_STV_dphit(event, PDGnu, true); pnreco_C = FitUtils::Get_pn_reco_C(event, PDGnu, true); } // Loop over the particles and store all the final state particles in a vector for (UInt_t i = 0; i < event->Npart(); ++i) { if (event->PartInfo(i)->fIsAlive && event->PartInfo(i)->Status() == kFinalState) partList.push_back(event->PartInfo(i)); if (SavePreFSI && event->fPrimaryVertex[i]) vertList.push_back(event->PartInfo(i)); if (SavePreFSI && event->PartInfo(i)->IsInitialState()) initList.push_back(event->PartInfo(i)); } // Save outgoing particle vectors nfsp = (int)partList.size(); std::map>> pdgMap; for (int i = 0; i < nfsp; ++i) { px[i] = partList[i]->fP.X() / 1E3; py[i] = partList[i]->fP.Y() / 1E3; pz[i] = partList[i]->fP.Z() / 1E3; E[i] = partList[i]->fP.E() / 1E3; pdg[i] = partList[i]->fPID; pdgMap[pdg[i]].push_back(std::make_pair(partList[i]->fP.Vect().Mag(), i)); } for (std::map>>::iterator iter = pdgMap.begin(); iter != pdgMap.end(); ++iter) { std::vector> thisVect = iter->second; std::sort(thisVect.begin(), thisVect.end()); // Now save the order... a bit funky to avoid inverting int nPart = (int)thisVect.size() - 1; for (int i = nPart; i >= 0; --i) { pdg_rank[thisVect[i].second] = nPart - i; } } // Save pre-FSI particles nvertp = (int)vertList.size(); for (int i = 0; i < nvertp; ++i) { px_vert[i] = vertList[i]->fP.X() / 1E3; py_vert[i] = vertList[i]->fP.Y() / 1E3; pz_vert[i] = vertList[i]->fP.Z() / 1E3; E_vert[i] = vertList[i]->fP.E() / 1E3; pdg_vert[i] = vertList[i]->fPID; } // Save init particles ninitp = (int)initList.size(); for (int i = 0; i < ninitp; ++i) { px_init[i] = initList[i]->fP.X() / 1E3; py_init[i] = initList[i]->fP.Y() / 1E3; pz_init[i] = initList[i]->fP.Z() / 1E3; E_init[i] = initList[i]->fP.E() / 1E3; pdg_init[i] = initList[i]->fPID; } #ifdef __GENIE_ENABLED__ if (event->fType == kGENIE) { EventRecord *gevent = static_cast(event->genie_event->event); const Interaction *interaction = gevent->Summary(); const Kinematics &kine = interaction->Kine(); double W_genie = kine.W(); } #endif // Fill event weights Weight = event->RWWeight * event->InputWeight; RWWeight = event->RWWeight; InputWeight = event->InputWeight; // And the Customs CustomWeight = event->CustomWeight; for (int i = 0; i < 6; ++i) { CustomWeightArray[i] = event->CustomWeightArray[i]; } // Fill the eventVariables Tree eventVariables->Fill(); return; }; //******************************************************************** void GenericFlux_Vectors::ResetVariables() { //******************************************************************** cc = false; // Reset all Function used to extract any variables of interest to the event Mode = PDGnu = tgt = tgta = tgtz = PDGLep = 0; Enu_true = ELep = CosLep = Q2 = q0 = q3 = Enu_QE = Q2_QE = W_nuc_rest = W = x = y = Eav = EavAlt = -999.9; W_genie = -999; // Other fun variables // MINERvA-like ones dalphat = dpt = dphit = pnreco_C = -999.99; nfsp = ninitp = nvertp = 0; for (int i = 0; i < kMAX; ++i) { px[i] = py[i] = pz[i] = E[i] = -999; pdg[i] = pdg_rank[i] = 0; px_init[i] = py_init[i] = pz_init[i] = E_init[i] = -999; pdg_init[i] = 0; px_vert[i] = py_vert[i] = pz_vert[i] = E_vert[i] = -999; pdg_vert[i] = 0; } Weight = InputWeight = RWWeight = 0.0; CustomWeight = 0.0; for (int i = 0; i < 6; ++i) CustomWeightArray[i] = 0.0; partList.clear(); initList.clear(); vertList.clear(); flagCCINC = flagNCINC = flagCCQE = flagCC0pi = flagCCQELike = flagNCEL = flagNC0pi = flagCCcoh = flagNCcoh = flagCC1pip = flagNC1pip = flagCC1pim = flagNC1pim = flagCC1pi0 = flagNC1pi0 = false; } //******************************************************************** void GenericFlux_Vectors::FillSignalFlags(FitEvent *event) { //******************************************************************** // Some example flags are given from SignalDef. // See src/Utils/SignalDef.cxx for more. int nuPDG = event->PartInfo(0)->fPID; // Generic signal flags flagCCINC = SignalDef::isCCINC(event, nuPDG); flagNCINC = SignalDef::isNCINC(event, nuPDG); flagCCQE = SignalDef::isCCQE(event, nuPDG); flagCCQELike = SignalDef::isCCQELike(event, nuPDG); flagCC0pi = SignalDef::isCC0pi(event, nuPDG); flagNCEL = SignalDef::isNCEL(event, nuPDG); flagNC0pi = SignalDef::isNC0pi(event, nuPDG); flagCCcoh = SignalDef::isCCCOH(event, nuPDG, 211); flagNCcoh = SignalDef::isNCCOH(event, nuPDG, 111); flagCC1pip = SignalDef::isCC1pi(event, nuPDG, 211); flagNC1pip = SignalDef::isNC1pi(event, nuPDG, 211); flagCC1pim = SignalDef::isCC1pi(event, nuPDG, -211); flagNC1pim = SignalDef::isNC1pi(event, nuPDG, -211); flagCC1pi0 = SignalDef::isCC1pi(event, nuPDG, 111); flagNC1pi0 = SignalDef::isNC1pi(event, nuPDG, 111); } void GenericFlux_Vectors::AddSignalFlagsToTree() { if (!eventVariables) { Config::Get().out->cd(); eventVariables = new TTree((this->fName + "_VARS").c_str(), (this->fName + "_VARS").c_str()); } - QLOG(SAM, "Adding signal flags"); + NUIS_LOG(SAM, "Adding signal flags"); // Signal Definitions from SignalDef.cxx eventVariables->Branch("flagCCINC", &flagCCINC, "flagCCINC/O"); eventVariables->Branch("flagNCINC", &flagNCINC, "flagNCINC/O"); eventVariables->Branch("flagCCQE", &flagCCQE, "flagCCQE/O"); eventVariables->Branch("flagCC0pi", &flagCC0pi, "flagCC0pi/O"); eventVariables->Branch("flagCCQELike", &flagCCQELike, "flagCCQELike/O"); eventVariables->Branch("flagNCEL", &flagNCEL, "flagNCEL/O"); eventVariables->Branch("flagNC0pi", &flagNC0pi, "flagNC0pi/O"); eventVariables->Branch("flagCCcoh", &flagCCcoh, "flagCCcoh/O"); eventVariables->Branch("flagNCcoh", &flagNCcoh, "flagNCcoh/O"); eventVariables->Branch("flagCC1pip", &flagCC1pip, "flagCC1pip/O"); eventVariables->Branch("flagNC1pip", &flagNC1pip, "flagNC1pip/O"); eventVariables->Branch("flagCC1pim", &flagCC1pim, "flagCC1pim/O"); eventVariables->Branch("flagNC1pim", &flagNC1pim, "flagNC1pim/O"); eventVariables->Branch("flagCC1pi0", &flagCC1pi0, "flagCC1pi0/O"); eventVariables->Branch("flagNC1pi0", &flagNC1pi0, "flagNC1pi0/O"); }; void GenericFlux_Vectors::Write(std::string drawOpt) { // First save the TTree eventVariables->Write(); // Save Flux and Event Histograms too GetInput()->GetFluxHistogram()->Write(); GetInput()->GetEventHistogram()->Write(); return; } // Override functions which aren't really necessary bool GenericFlux_Vectors::isSignal(FitEvent *event) { (void)event; return true; }; void GenericFlux_Vectors::ScaleEvents() { return; } void GenericFlux_Vectors::ApplyNormScale(float norm) { this->fCurrentNorm = norm; return; } void GenericFlux_Vectors::FillHistograms() { return; } void GenericFlux_Vectors::ResetAll() { eventVariables->Reset(); return; } float GenericFlux_Vectors::GetChi2() { return 0.0; } diff --git a/src/MCStudies/MCStudy_CCQEHistograms.cxx b/src/MCStudies/MCStudy_CCQEHistograms.cxx index b824617..a232b54 100644 --- a/src/MCStudies/MCStudy_CCQEHistograms.cxx +++ b/src/MCStudies/MCStudy_CCQEHistograms.cxx @@ -1,230 +1,230 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MCStudy_CCQEHistograms.h" #include "T2K_SignalDef.h" #include "MINERvA_SignalDef.h" //******************************************************************** /// @brief Class to perform MC Studies on a custom measurement MCStudy_CCQEHistograms::MCStudy_CCQEHistograms(std::string name, std::string inputfile, FitWeight *rw, std::string type, std::string fakeDataFile) { //******************************************************************** // Measurement Details fName = name; fEventTree = NULL; // Define our energy range for flux calcs EnuMin = 0.; EnuMax = 100.; // Arbritrarily high energy limit // Set default fitter flags fIsDiag = true; fIsShape = false; fIsRawEvents = false; // This function will sort out the input files automatically and parse all the // inputs,flags,etc. // There may be complex cases where you have to do this by hand, but usually // this will do. Measurement1D::SetupMeasurement(inputfile, type, rw, fakeDataFile); fEventTree = NULL; // Setup fDataHist as a placeholder this->fDataHist = new TH1D(("approximate_data"), ("kaon_data"), 5, 1.0, 6.0); this->SetupDefaultHist(); fFullCovar = StatUtils::MakeDiagonalCovarMatrix(fDataHist); covar = StatUtils::GetInvert(fFullCovar); // 1. The generator is organised in SetupMeasurement so it gives the // cross-section in "per nucleon" units. // So some extra scaling for a specific measurement may be required. For // Example to get a "per neutron" measurement on carbon // which we do here, we have to multiple by the number of nucleons 12 and // divide by the number of neutrons 6. this->fScaleFactor = (this->fEventHist->Integral("width") * 1E-38 / (fNEvents + 0.)) / this->TotalIntegratedFlux(); hist_Enu = new TH1D("MCStudy_CCQE_Enu","MCStudy_CCQE_Enu",30,0.0,2.0); hist_TLep = new TH1D("MCStudy_CCQE_TLep","MCStudy_CCQE_TLep",30,0.0,4.0); hist_CosLep = new TH1D("MCStudy_CCQE_CosLep","MCStudy_CCQE_CosLep",30,-1.0,1.0); hist_Q2 = new TH1D("MCStudy_CCQE_Q2;Q^{2} (GeV^{2});d#sigma/dQ^{2} (cm^{2}/nucleon/GeV^{2})","MCStudy_CCQE_Q2",30,0.0,3.0); hist_Q2QE = new TH1D("MCStudy_CCQE_Q2QE","MCStudy_CCQE_Q2QE",30,0.0,3.0); hist_EQE = new TH1D("MCStudy_CCQE_EQE","MCStudy_CCQE_EQE",30,0.0,5.0); hist_q0 = new TH1D("MCStudy_CCQE_q0","MCStudy_CCQE_q0",30,0.0,2.0); hist_q3 = new TH1D("MCStudy_CCQE_q3","MCStudy_CCQE_q3",30,0.0,2.0); hist_TLepCosLep = new TH2D("MCStudy_CCQE_TLepCosLep","MCStudy_CCQE_TLepCosLep",15,0.0,5.0,15,-1.0,1.0); hist_Total = new TH1D("MCStudy_CCQE_TotalXSec","MXStudy_CCQE_TotalXSec",1,0.0,1.0); hist_q0q3 = new TH2D("MCStudy_CCQE_q0q3","MCStudy_CCQE_q0q3;q_{3} (GeV); q_{0} (GeV); d#sigma/dq_{0}dq_{3} (cm^{2}/nucleon/GeV^{2})",40,0.0,2.0,40,0.0,2.0); return; } //******************************************************************** void MCStudy_CCQEHistograms::FillEventVariables(FitEvent *event) { //******************************************************************** // std::cout << "Event fBound = " << event->fBound << " " << event->Mode << std::endl; // if (event->fBound > 0) return; if (abs(event->Mode) != 1) return; // std::cout << "Event fBound = " << event->fBound << " " << event->Mode << "-> Signal " << std::endl; FitParticle* muon = NULL; FitParticle* nu = event->GetNeutrinoIn(); bool IsNuMu = event->PDGnu() > 0; if (IsNuMu) muon = event->GetHMFSParticle(13); else muon = event->GetHMFSParticle(-13); // Reset Variables Enu = -999.9; TLep = -999.9; CosLep = -999.9; Q2 = -999.9; Q2QE = -999.9; EQE = -999.9; q0 = -999.9; q3 = -999.9; // Fill Variables if (muon){ Enu = event->Enu() / 1.E3; TLep = (muon->fP.E() - muon->fP.Mag()) / 1.E3; CosLep = cos(muon->fP.Vect().Angle( nu->fP.Vect() )); Q2 = fabs((muon->fP - nu->fP).Mag2() / 1.E6); Q2QE = FitUtils::Q2QErec(muon->fP, CosLep, 34., IsNuMu); EQE = FitUtils::EnuQErec(muon->fP, CosLep, 34., IsNuMu); q0 = fabs((muon->fP - nu->fP).E()) / 1.E3; q3 = fabs((muon->fP - nu->fP).Vect().Mag()) / 1.E3; LocalRWWeight = event->RWWeight; LocalInputWeight = event->InputWeight; } // Fill Tree if (abs(Mode) == 1 and Signal){ hist_Enu->Fill(Enu,event->Weight); hist_TLep->Fill(TLep,event->Weight); hist_CosLep->Fill(CosLep,event->Weight); hist_Q2->Fill(Q2,event->Weight); hist_Q2QE->Fill(Q2QE,event->Weight); hist_EQE->Fill(EQE,event->Weight); hist_q0->Fill(q0,event->Weight); hist_q3->Fill(q3,event->Weight); hist_TLepCosLep->Fill(TLep,CosLep,event->Weight); hist_q0q3->Fill(q3,q0,event->Weight); hist_Total->Fill(0.5,event->Weight); fXVar = Q2; } return; }; //******************************************************************** void MCStudy_CCQEHistograms::Write(std::string drawOpt) { //******************************************************************** // Measurement1D::Write(drawOpt); - QLOG(FIT, "Writing MCStudy_CCQEHistograms "); + NUIS_LOG(FIT, "Writing MCStudy_CCQEHistograms "); // Config::Get().out->cd(); hist_Enu->Write(); hist_TLep->Write(); hist_CosLep->Write(); hist_Q2->Write(); hist_Q2QE->Write(); hist_EQE->Write(); hist_q0->Write(); hist_q3->Write(); hist_TLepCosLep->Write(); hist_q0q3->Write(); hist_Total->Write(); return; } //******************************************************************** void MCStudy_CCQEHistograms::ResetAll(){ //******************************************************************** hist_Enu->Reset(); hist_TLep->Reset(); hist_CosLep->Reset(); hist_Q2->Reset(); hist_Q2QE->Reset(); hist_EQE->Reset(); hist_q0->Reset(); hist_q3->Reset(); hist_q0q3->Reset(); hist_TLepCosLep->Reset(); hist_Total->Reset(); return; } //******************************************************************** void MCStudy_CCQEHistograms::ScaleEvents(){ //******************************************************************** hist_Enu->Scale(fScaleFactor,"width"); hist_TLep->Scale(fScaleFactor,"width"); hist_CosLep->Scale(fScaleFactor,"width"); hist_Q2->Scale(fScaleFactor,"width"); hist_Q2QE->Scale(fScaleFactor,"width"); hist_EQE->Scale(fScaleFactor,"width"); hist_q0->Scale(fScaleFactor,"width"); hist_q3->Scale(fScaleFactor,"width"); hist_q0q3->Scale(fScaleFactor,"width"); hist_TLepCosLep->Scale(fScaleFactor,"width"); hist_Total->Scale(fScaleFactor,"width"); return; } //******************************************************************** /// Select only events with final state Muons bool MCStudy_CCQEHistograms::isSignal(FitEvent *event) { //******************************************************************** if (abs(event->Mode) != 1) return false; //if (event->fBound > 0) return false; // if (!event->HasFSMuon()) return false; // Do we want any other signal? return true; }; diff --git a/src/MCStudies/OfficialNIWGPlots.cxx b/src/MCStudies/OfficialNIWGPlots.cxx index 996540d..1c05bfc 100644 --- a/src/MCStudies/OfficialNIWGPlots.cxx +++ b/src/MCStudies/OfficialNIWGPlots.cxx @@ -1,679 +1,679 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "OfficialNIWGPlots.h" #include "T2K_SignalDef.h" #include "MINERvA_SignalDef.h" //******************************************************************** OfficialNIWGPlots::OfficialNIWGPlots(nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "NIWG Official plots sample. \n" \ "Target: Any \n" \ "Flux: T2K Flux \n" \ "Signal: CC Inclusive \n"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetAllowedTypes("FIX,FREE,SHAPE/DIAG,FULL/NORM/MASK", "FIX/FULL"); fSettings.SetEnuRange(0.0, 30.0); fSettings.DefineAllowedTargets("C,H"); fSettings.DefineAllowedSpecies("numu"); fSettings.SetTitle("NIWG Official Plots 2017"); fSettings.SetOnlyMC(1); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = GetEventHistogram()->Integral("width") * double(1E-38) / double(fNEvents) / TotalIntegratedFlux("width"); fScaleFactorEnuXSec = GetEventHistogram()->Integral("width") * double(1E-38) / double(fNEvents); fScaleFactorDifXSec = GetEventHistogram()->Integral("width") * double(1E-38) / double(fNEvents) / TotalIntegratedFlux("width"); // Plot Setup ------------------------------------------------------- fHist_NuMu_Enu = new TH1D("NuMu_Enu_MC", "NuMu_Enu_MC;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", 45, 0.0, 3.0); fHist_NuMu_Enu_Modes = new MCStudies::OfficialNIWGStack("NuMu_Enu_MC_MODES", "NuMu_Enu_MC_MODES;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", fHist_NuMu_Enu); fHist_NuMu_Enu_Pions = new MCStudies::OfficialPionStack("NuMu_Enu_MC_PIONS", "NuMu_Enu_MC_PIONS;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", fHist_NuMu_Enu); fHist_NuMu_EnuRates = new TH1D("NuMu_EnuRates_MC", "NuMu_EnuRates_MC;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", 45, 0.0, 3.0); fHist_NuMu_EnuRates_Modes = new MCStudies::OfficialNIWGStack("NuMu_EnuRates_MC_MODES", "NuMu_EnuRates_MC_MODES;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", fHist_NuMu_Enu); fHist_NuMu_EnuRates_Pions = new MCStudies::OfficialPionStack("NuMu_EnuRates_MC_PIONS", "NuMu_EnuRates_MC_PIONS;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", fHist_NuMu_Enu); fHist_NuMu_Q2 = new TH1D("NuMu_Q2_MC", "NuMu_Q2_MC;Q^{2} (GeV);d#sigma/dQ^{2} (cm^{2}/nucleon/GeV^{2})", 45, 0.0, 3.0); fHist_NuMu_Q2_Modes = new MCStudies::OfficialNIWGStack("NuMu_Q2_MC_MODES", "NuMu_Q2_MC_MODES;Q^{2} (GeV);#sigma (cm^{2}/nucleon/GeV^{2})", fHist_NuMu_Q2); fHist_NuMu_Q2_Pions = new MCStudies::OfficialPionStack("NuMu_Q2_MC_PIONS", "NuMu_Q2_MC_PIONS;Q^{2} (GeV);#sigma (cm^{2}/nucleon/GeV^{2})", fHist_NuMu_Q2); fHist_NuMu_Pmu = new TH1D("NuMu_Pmu_MC", "NuMu_Pmu_MC;P_{#mu} (GeV);#sigma (cm^{2}/nucleon/GeV)", 45, 0.0, 3.0); fHist_NuMu_Pmu_Modes = new MCStudies::OfficialNIWGStack("NuMu_Pmu_MC_MODES", "NuMu_Pmu_MC_MODES;P_{#mu} (GeV);d#sigma/dP_{#mu} (cm^{2}/nucleon/GeV)", fHist_NuMu_Pmu); fHist_NuMu_Pmu_Pions = new MCStudies::OfficialPionStack("NuMu_Pmu_MC_PIONS", "NuMu_Pmu_MC_PIONS;P_{#mu} (GeV);d#sigma/dP_{#mu} (cm^{2}/nucleon/GeV)", fHist_NuMu_Pmu); fHist_NuMu_Cosmu = new TH1D("NuMu_Cosmu_MC", "NuMu_Cosmu_MC;cos#theta_{#mu};d#sigma/dcos#theta_{#mu} (cm^{2}/nucleon)", 45, -1.0, 1.0); fHist_NuMu_Cosmu_Modes = new MCStudies::OfficialNIWGStack("NuMu_Cosmu_MC_MODES", "NuMu_Cosmu_MC_MODES;cos#theta_{#mu};d#sigma/dcos#theta_{#mu} (cm^{2}/nucleon)", fHist_NuMu_Cosmu); fHist_NuMu_Cosmu_Pions = new MCStudies::OfficialPionStack("NuMu_Cosmu_MC_PIONS", "NuMu_Cosmu_MC_PIONS;cos#theta_{#mu};d#sigma/dcos#theta_{#mu} (cm^{2}/nucleon)", fHist_NuMu_Cosmu); fHist_NuMuBar_Enu = new TH1D("NuMuBar_Enu_MC", "NuMuBar_Enu_MC;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", 45, 0.0, 3.0); fHist_NuMuBar_Enu_Modes = new MCStudies::OfficialNIWGStack("NuMuBar_Enu_MC_MODES", "NuMuBar_Enu_MC_MODES;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", fHist_NuMuBar_Enu); fHist_NuMuBar_Enu_Pions = new MCStudies::OfficialPionStack("NuMuBar_Enu_MC_PIONS", "NuMuBar_Enu_MC_PIONS;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", fHist_NuMuBar_Enu); fHist_NuMuBar_EnuRates = new TH1D("NuMuBar_EnuRates_MC", "NuMuBar_EnuRates_MC;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", 45, 0.0, 3.0); fHist_NuMuBar_EnuRates_Modes = new MCStudies::OfficialNIWGStack("NuMuBar_EnuRates_MC_MODES", "NuMuBar_EnuRates_MC_MODES;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", fHist_NuMuBar_Enu); fHist_NuMuBar_EnuRates_Pions = new MCStudies::OfficialPionStack("NuMuBar_EnuRates_MC_PIONS", "NuMuBar_EnuRates_MC_PIONS;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", fHist_NuMuBar_Enu); fHist_NuMuBar_Q2 = new TH1D("NuMuBar_Q2_MC", "NuMuBar_Q2_MC;Q^{2} (GeV);d#sigma/dQ^{2} (cm^{2}/nucleon/GeV^{2})", 45, 0.0, 3.0); fHist_NuMuBar_Q2_Modes = new MCStudies::OfficialNIWGStack("NuMuBar_Q2_MC_MODES", "NuMuBar_Q2_MC_MODES;Q^{2} (GeV);#sigma (cm^{2}/nucleon/GeV^{2})", fHist_NuMuBar_Q2); fHist_NuMuBar_Q2_Pions = new MCStudies::OfficialPionStack("NuMuBar_Q2_MC_PIONS", "NuMuBar_Q2_MC_PIONS;Q^{2} (GeV);#sigma (cm^{2}/nucleon/GeV^{2})", fHist_NuMuBar_Q2); fHist_NuMuBar_Pmu = new TH1D("NuMuBar_Pmu_MC", "NuMuBar_Pmu_MC;P_{#mu} (GeV);#sigma (cm^{2}/nucleon/GeV)", 45, 0.0, 3.0); fHist_NuMuBar_Pmu_Modes = new MCStudies::OfficialNIWGStack("NuMuBar_Pmu_MC_MODES", "NuMuBar_Pmu_MC_MODES;P_{#mu} (GeV);d#sigma/dP_{#mu} (cm^{2}/nucleon/GeV)", fHist_NuMuBar_Pmu); fHist_NuMuBar_Pmu_Pions = new MCStudies::OfficialPionStack("NuMuBar_Pmu_MC_PIONS", "NuMuBar_Pmu_MC_PIONS;P_{#mu} (GeV);d#sigma/dP_{#mu} (cm^{2}/nucleon/GeV)", fHist_NuMuBar_Pmu); fHist_NuMuBar_Cosmu = new TH1D("NuMuBar_Cosmu_MC", "NuMuBar_Cosmu_MC;cos#theta_{#mu};d#sigma/dcos#theta_{#mu} (cm^{2}/nucleon)", 45, -1.0, 1.0); fHist_NuMuBar_Cosmu_Modes = new MCStudies::OfficialNIWGStack("NuMuBar_Cosmu_MC_MODES", "NuMuBar_Cosmu_MC_MODES;cos#theta_{#mu};d#sigma/dcos#theta_{#mu} (cm^{2}/nucleon)", fHist_NuMuBar_Cosmu); fHist_NuMuBar_Cosmu_Pions = new MCStudies::OfficialPionStack("NuMuBar_Cosmu_MC_PIONS", "NuMuBar_Cosmu_MC_PIONS;cos#theta_{#mu};d#sigma/dcos#theta_{#mu} (cm^{2}/nucleon)", fHist_NuMuBar_Cosmu); fHist_Nue_Enu = new TH1D("Nue_Enu_MC", "Nue_Enu_MC;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", 45, 0.0, 3.0); fHist_Nue_Enu_Modes = new MCStudies::OfficialNIWGStack("Nue_Enu_MC_MODES", "Nue_Enu_MC_MODES;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", fHist_Nue_Enu); fHist_Nue_Enu_Pions = new MCStudies::OfficialPionStack("Nue_Enu_MC_PIONS", "Nue_Enu_MC_PIONS;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", fHist_Nue_Enu); fHist_Nue_EnuRates = new TH1D("Nue_EnuRates_MC", "Nue_EnuRates_MC;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", 45, 0.0, 3.0); fHist_Nue_EnuRates_Modes = new MCStudies::OfficialNIWGStack("Nue_EnuRates_MC_MODES", "Nue_EnuRates_MC_MODES;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", fHist_Nue_Enu); fHist_Nue_EnuRates_Pions = new MCStudies::OfficialPionStack("Nue_EnuRates_MC_PIONS", "Nue_EnuRates_MC_PIONS;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", fHist_Nue_Enu); fHist_Nue_Q2 = new TH1D("Nue_Q2_MC", "Nue_Q2_MC;Q^{2} (GeV);d#sigma/dQ^{2} (cm^{2}/nucleon/GeV^{2})", 45, 0.0, 3.0); fHist_Nue_Q2_Modes = new MCStudies::OfficialNIWGStack("Nue_Q2_MC_MODES", "Nue_Q2_MC_MODES;Q^{2} (GeV);#sigma (cm^{2}/nucleon/GeV^{2})", fHist_Nue_Q2); fHist_Nue_Q2_Pions = new MCStudies::OfficialPionStack("Nue_Q2_MC_PIONS", "Nue_Q2_MC_PIONS;Q^{2} (GeV);#sigma (cm^{2}/nucleon/GeV^{2})", fHist_Nue_Q2); fHist_Nue_Pmu = new TH1D("Nue_Pmu_MC", "Nue_Pmu_MC;P_{#mu} (GeV);#sigma (cm^{2}/nucleon/GeV)", 45, 0.0, 3.0); fHist_Nue_Pmu_Modes = new MCStudies::OfficialNIWGStack("Nue_Pmu_MC_MODES", "Nue_Pmu_MC_MODES;P_{#mu} (GeV);d#sigma/dP_{#mu} (cm^{2}/nucleon/GeV)", fHist_Nue_Pmu); fHist_Nue_Pmu_Pions = new MCStudies::OfficialPionStack("Nue_Pmu_MC_PIONS", "Nue_Pmu_MC_PIONS;P_{#mu} (GeV);d#sigma/dP_{#mu} (cm^{2}/nucleon/GeV)", fHist_Nue_Pmu); fHist_Nue_Cosmu = new TH1D("Nue_Cosmu_MC", "Nue_Cosmu_MC;cos#theta_{#mu};d#sigma/dcos#theta_{#mu} (cm^{2}/nucleon)", 45, -1.0, 1.0); fHist_Nue_Cosmu_Modes = new MCStudies::OfficialNIWGStack("Nue_Cosmu_MC_MODES", "Nue_Cosmu_MC_MODES;cos#theta_{#mu};d#sigma/dcos#theta_{#mu} (cm^{2}/nucleon)", fHist_Nue_Cosmu); fHist_Nue_Cosmu_Pions = new MCStudies::OfficialPionStack("Nue_Cosmu_MC_PIONS", "Nue_Cosmu_MC_PIONS;cos#theta_{#mu};d#sigma/dcos#theta_{#mu} (cm^{2}/nucleon)", fHist_Nue_Cosmu); fHist_NueBar_Enu = new TH1D("NueBar_Enu_MC", "NueBar_Enu_MC;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", 45, 0.0, 3.0); fHist_NueBar_Enu_Modes = new MCStudies::OfficialNIWGStack("NueBar_Enu_MC_MODES", "NueBar_Enu_MC_MODES;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", fHist_NueBar_Enu); fHist_NueBar_Enu_Pions = new MCStudies::OfficialPionStack("NueBar_Enu_MC_PIONS", "NueBar_Enu_MC_PIONS;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", fHist_NueBar_Enu); fHist_NueBar_EnuRates = new TH1D("NueBar_EnuRates_MC", "NueBar_EnuRates_MC;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", 45, 0.0, 3.0); fHist_NueBar_EnuRates_Modes = new MCStudies::OfficialNIWGStack("NueBar_EnuRates_MC_MODES", "NueBar_EnuRates_MC_MODES;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", fHist_NueBar_Enu); fHist_NueBar_EnuRates_Pions = new MCStudies::OfficialPionStack("NueBar_EnuRates_MC_PIONS", "NueBar_EnuRates_MC_PIONS;E_{#nu}^{True} (GeV);#sigma (cm^{2}/nucleon)", fHist_NueBar_Enu); fHist_NueBar_Q2 = new TH1D("NueBar_Q2_MC", "NueBar_Q2_MC;Q^{2} (GeV);d#sigma/dQ^{2} (cm^{2}/nucleon/GeV^{2})", 45, 0.0, 3.0); fHist_NueBar_Q2_Modes = new MCStudies::OfficialNIWGStack("NueBar_Q2_MC_MODES", "NueBar_Q2_MC_MODES;Q^{2} (GeV);#sigma (cm^{2}/nucleon/GeV^{2})", fHist_NueBar_Q2); fHist_NueBar_Q2_Pions = new MCStudies::OfficialPionStack("NueBar_Q2_MC_PIONS", "NueBar_Q2_MC_PIONS;Q^{2} (GeV);#sigma (cm^{2}/nucleon/GeV^{2})", fHist_NueBar_Q2); fHist_NueBar_Pmu = new TH1D("NueBar_Pmu_MC", "NueBar_Pmu_MC;P_{#mu} (GeV);#sigma (cm^{2}/nucleon/GeV)", 45, 0.0, 3.0); fHist_NueBar_Pmu_Modes = new MCStudies::OfficialNIWGStack("NueBar_Pmu_MC_MODES", "NueBar_Pmu_MC_MODES;P_{#mu} (GeV);d#sigma/dP_{#mu} (cm^{2}/nucleon/GeV)", fHist_NueBar_Pmu); fHist_NueBar_Pmu_Pions = new MCStudies::OfficialPionStack("NueBar_Pmu_MC_PIONS", "NueBar_Pmu_MC_PIONS;P_{#mu} (GeV);d#sigma/dP_{#mu} (cm^{2}/nucleon/GeV)", fHist_NueBar_Pmu); fHist_NueBar_Cosmu = new TH1D("NueBar_Cosmu_MC", "NueBar_Cosmu_MC;cos#theta_{#mu};d#sigma/dcos#theta_{#mu} (cm^{2}/nucleon)", 45, -1.0, 1.0); fHist_NueBar_Cosmu_Modes = new MCStudies::OfficialNIWGStack("NueBar_Cosmu_MC_MODES", "NueBar_Cosmu_MC_MODES;cos#theta_{#mu};d#sigma/dcos#theta_{#mu} (cm^{2}/nucleon)", fHist_NueBar_Cosmu); fHist_NueBar_Cosmu_Pions = new MCStudies::OfficialPionStack("NueBar_Cosmu_MC_PIONS", "NueBar_Cosmu_MC_PIONS;cos#theta_{#mu};d#sigma/dcos#theta_{#mu} (cm^{2}/nucleon)", fHist_NueBar_Cosmu); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void OfficialNIWGPlots::FillEventVariables(FitEvent *event) { //******************************************************************** if (!event->GetNeutrinoIn() or abs(event->Mode) > 30) return; TLorentzVector vectnu = event->GetNeutrinoIn()->fP; int leptons[] = {12,-12,14,-14}; if (!event->GetHMFSParticle(leptons))return; TLorentzVector vectlep = event->GetHMFSParticle(leptons)->fP; double Q2 = fabs((vectlep - vectnu).Mag2()) / 1.E6; double Enu = vectnu.E() / 1.E3; double Pmu = vectlep.Vect().Mag() / 1.E3; double Cosmu = cos(vectlep.Vect().Angle(vectnu.Vect())); bool nue = (abs(event->GetNeutrinoIn()->fPID) == 12); bool nubar = (event->GetNeutrinoIn()->fPID > 0); if (OfficialNIWGPlots::isSignal(event)) { if (!nue and !nubar) { fHist_NuMu_Enu->Fill(Enu, Weight); fHist_NuMu_Enu_Modes->Fill(event, Enu, Weight); fHist_NuMu_Enu_Pions->Fill(event, Enu, Weight); fHist_NuMu_EnuRates->Fill(Enu, Weight); fHist_NuMu_EnuRates_Modes->Fill(event, Enu, Weight); fHist_NuMu_EnuRates_Pions->Fill(event, Enu, Weight); fHist_NuMu_Q2->Fill(Q2, Weight); fHist_NuMu_Q2_Modes->Fill(event, Q2, Weight); fHist_NuMu_Q2_Pions->Fill(event, Q2, Weight); fHist_NuMu_Pmu->Fill(Pmu, Weight); fHist_NuMu_Pmu_Modes->Fill(event, Pmu, Weight); fHist_NuMu_Pmu_Pions->Fill(event, Pmu, Weight); fHist_NuMu_Cosmu->Fill(Cosmu, Weight); fHist_NuMu_Cosmu_Modes->Fill(event, Cosmu, Weight); fHist_NuMu_Cosmu_Pions->Fill(event, Cosmu, Weight); } else if (!nue and nubar){ fHist_NuMuBar_Enu->Fill(Enu, Weight); fHist_NuMuBar_Enu_Modes->Fill(event, Enu, Weight); fHist_NuMuBar_Enu_Pions->Fill(event, Enu, Weight); fHist_NuMuBar_EnuRates->Fill(Enu, Weight); fHist_NuMuBar_EnuRates_Modes->Fill(event, Enu, Weight); fHist_NuMuBar_EnuRates_Pions->Fill(event, Enu, Weight); fHist_NuMuBar_Q2->Fill(Q2, Weight); fHist_NuMuBar_Q2_Modes->Fill(event, Q2, Weight); fHist_NuMuBar_Q2_Pions->Fill(event, Q2, Weight); fHist_NuMuBar_Pmu->Fill(Pmu, Weight); fHist_NuMuBar_Pmu_Modes->Fill(event, Pmu, Weight); fHist_NuMuBar_Pmu_Pions->Fill(event, Pmu, Weight); fHist_NuMuBar_Cosmu->Fill(Cosmu, Weight); fHist_NuMuBar_Cosmu_Modes->Fill(event, Cosmu, Weight); fHist_NuMuBar_Cosmu_Pions->Fill(event, Cosmu, Weight); } else if (nue and !nubar){ fHist_Nue_Enu->Fill(Enu, Weight); fHist_Nue_Enu_Modes->Fill(event, Enu, Weight); fHist_Nue_Enu_Pions->Fill(event, Enu, Weight); fHist_Nue_EnuRates->Fill(Enu, Weight); fHist_Nue_EnuRates_Modes->Fill(event, Enu, Weight); fHist_Nue_EnuRates_Pions->Fill(event, Enu, Weight); fHist_Nue_Q2->Fill(Q2, Weight); fHist_Nue_Q2_Modes->Fill(event, Q2, Weight); fHist_Nue_Q2_Pions->Fill(event, Q2, Weight); fHist_Nue_Pmu->Fill(Pmu, Weight); fHist_Nue_Pmu_Modes->Fill(event, Pmu, Weight); fHist_Nue_Pmu_Pions->Fill(event, Pmu, Weight); fHist_Nue_Cosmu->Fill(Cosmu, Weight); fHist_Nue_Cosmu_Modes->Fill(event, Cosmu, Weight); fHist_Nue_Cosmu_Pions->Fill(event, Cosmu, Weight); } else if (nue and nubar){ fHist_NueBar_Enu->Fill(Enu, Weight); fHist_NueBar_Enu_Modes->Fill(event, Enu, Weight); fHist_NueBar_Enu_Pions->Fill(event, Enu, Weight); fHist_NueBar_EnuRates->Fill(Enu, Weight); fHist_NueBar_EnuRates_Modes->Fill(event, Enu, Weight); fHist_NueBar_EnuRates_Pions->Fill(event, Enu, Weight); fHist_NueBar_Q2->Fill(Q2, Weight); fHist_NueBar_Q2_Modes->Fill(event, Q2, Weight); fHist_NueBar_Q2_Pions->Fill(event, Q2, Weight); fHist_NueBar_Pmu->Fill(Pmu, Weight); fHist_NueBar_Pmu_Modes->Fill(event, Pmu, Weight); fHist_NueBar_Pmu_Pions->Fill(event, Pmu, Weight); fHist_NueBar_Cosmu->Fill(Cosmu, Weight); fHist_NueBar_Cosmu_Modes->Fill(event, Cosmu, Weight); fHist_NueBar_Cosmu_Pions->Fill(event, Cosmu, Weight); } } return; }; //******************************************************************** void OfficialNIWGPlots::Write(std::string drawOpt) { //******************************************************************** - QLOG(FIT,"Writing OfficialNIWGPlots "); + NUIS_LOG(FIT,"Writing OfficialNIWGPlots "); fHist_NuMu_Enu->Write(); fHist_NuMu_Enu_Modes->Write(); fHist_NuMu_Enu_Pions->Write(); fHist_NuMu_EnuRates->Write(); fHist_NuMu_EnuRates_Modes->Write(); fHist_NuMu_EnuRates_Pions->Write(); fHist_NuMu_Q2->Write(); fHist_NuMu_Q2_Modes->Write(); fHist_NuMu_Q2_Pions->Write(); fHist_NuMu_Pmu->Write(); fHist_NuMu_Pmu_Modes->Write(); fHist_NuMu_Pmu_Pions->Write(); fHist_NuMu_Cosmu->Write(); fHist_NuMu_Cosmu_Modes->Write(); fHist_NuMu_Cosmu_Pions->Write(); fHist_NuMuBar_Enu->Write(); fHist_NuMuBar_Enu_Modes->Write(); fHist_NuMuBar_Enu_Pions->Write(); fHist_NuMuBar_EnuRates->Write(); fHist_NuMuBar_EnuRates_Modes->Write(); fHist_NuMuBar_EnuRates_Pions->Write(); fHist_NuMuBar_Q2->Write(); fHist_NuMuBar_Q2_Modes->Write(); fHist_NuMuBar_Q2_Pions->Write(); fHist_NuMuBar_Pmu->Write(); fHist_NuMuBar_Pmu_Modes->Write(); fHist_NuMuBar_Pmu_Pions->Write(); fHist_NuMuBar_Cosmu->Write(); fHist_NuMuBar_Cosmu_Modes->Write(); fHist_NuMuBar_Cosmu_Pions->Write(); fHist_Nue_Enu->Write(); fHist_Nue_Enu_Modes->Write(); fHist_Nue_Enu_Pions->Write(); fHist_Nue_EnuRates->Write(); fHist_Nue_EnuRates_Modes->Write(); fHist_Nue_EnuRates_Pions->Write(); fHist_Nue_Q2->Write(); fHist_Nue_Q2_Modes->Write(); fHist_Nue_Q2_Pions->Write(); fHist_Nue_Pmu->Write(); fHist_Nue_Pmu_Modes->Write(); fHist_Nue_Pmu_Pions->Write(); fHist_Nue_Cosmu->Write(); fHist_Nue_Cosmu_Modes->Write(); fHist_Nue_Cosmu_Pions->Write(); fHist_NueBar_Enu->Write(); fHist_NueBar_Enu_Modes->Write(); fHist_NueBar_Enu_Pions->Write(); fHist_NueBar_EnuRates->Write(); fHist_NueBar_EnuRates_Modes->Write(); fHist_NueBar_EnuRates_Pions->Write(); fHist_NueBar_Q2->Write(); fHist_NueBar_Q2_Modes->Write(); fHist_NueBar_Q2_Pions->Write(); fHist_NueBar_Pmu->Write(); fHist_NueBar_Pmu_Modes->Write(); fHist_NueBar_Pmu_Pions->Write(); fHist_NueBar_Cosmu->Write(); fHist_NueBar_Cosmu_Modes->Write(); fHist_NueBar_Cosmu_Pions->Write(); return; } //******************************************************************** void OfficialNIWGPlots::ResetAll() { //******************************************************************** fHist_NuMu_Enu->Reset(); fHist_NuMu_Enu_Modes->Reset(); fHist_NuMu_Enu_Pions->Reset(); fHist_NuMu_EnuRates->Reset(); fHist_NuMu_EnuRates_Modes->Reset(); fHist_NuMu_EnuRates_Pions->Reset(); fHist_NuMu_Q2->Reset(); fHist_NuMu_Q2_Modes->Reset(); fHist_NuMu_Q2_Pions->Reset(); fHist_NuMu_Pmu->Reset(); fHist_NuMu_Pmu_Modes->Reset(); fHist_NuMu_Pmu_Pions->Reset(); fHist_NuMu_Cosmu->Reset(); fHist_NuMu_Cosmu_Modes->Reset(); fHist_NuMu_Cosmu_Pions->Reset(); fHist_NuMuBar_Enu->Reset(); fHist_NuMuBar_Enu_Modes->Reset(); fHist_NuMuBar_Enu_Pions->Reset(); fHist_NuMuBar_EnuRates->Reset(); fHist_NuMuBar_EnuRates_Modes->Reset(); fHist_NuMuBar_EnuRates_Pions->Reset(); fHist_NuMuBar_Q2->Reset(); fHist_NuMuBar_Q2_Modes->Reset(); fHist_NuMuBar_Q2_Pions->Reset(); fHist_NuMuBar_Pmu->Reset(); fHist_NuMuBar_Pmu_Modes->Reset(); fHist_NuMuBar_Pmu_Pions->Reset(); fHist_NuMuBar_Cosmu->Reset(); fHist_NuMuBar_Cosmu_Modes->Reset(); fHist_NuMuBar_Cosmu_Pions->Reset(); fHist_Nue_Enu->Reset(); fHist_Nue_Enu_Modes->Reset(); fHist_Nue_Enu_Pions->Reset(); fHist_Nue_EnuRates->Reset(); fHist_Nue_EnuRates_Modes->Reset(); fHist_Nue_EnuRates_Pions->Reset(); fHist_Nue_Q2->Reset(); fHist_Nue_Q2_Modes->Reset(); fHist_Nue_Q2_Pions->Reset(); fHist_Nue_Pmu->Reset(); fHist_Nue_Pmu_Modes->Reset(); fHist_Nue_Pmu_Pions->Reset(); fHist_Nue_Cosmu->Reset(); fHist_Nue_Cosmu_Modes->Reset(); fHist_Nue_Cosmu_Pions->Reset(); fHist_NueBar_Enu->Reset(); fHist_NueBar_Enu_Modes->Reset(); fHist_NueBar_Enu_Pions->Reset(); fHist_NueBar_EnuRates->Reset(); fHist_NueBar_EnuRates_Modes->Reset(); fHist_NueBar_EnuRates_Pions->Reset(); fHist_NueBar_Q2->Reset(); fHist_NueBar_Q2_Modes->Reset(); fHist_NueBar_Q2_Pions->Reset(); fHist_NueBar_Pmu->Reset(); fHist_NueBar_Pmu_Modes->Reset(); fHist_NueBar_Pmu_Pions->Reset(); fHist_NueBar_Cosmu->Reset(); fHist_NueBar_Cosmu_Modes->Reset(); fHist_NueBar_Cosmu_Pions->Reset(); return; } //******************************************************************** void OfficialNIWGPlots::ScaleEvents() { //******************************************************************** fHist_NuMu_EnuRates->Scale(fScaleFactorEnuXSec); fHist_NuMu_EnuRates_Modes->Scale(fScaleFactorEnuXSec); fHist_NuMu_EnuRates_Pions->Scale(fScaleFactorEnuXSec); PlotUtils::FluxUnfoldedScaling(fHist_NuMu_Enu, GetFluxHistogram(), GetEventHistogram(), fScaleFactorEnuXSec, fNEvents); fHist_NuMu_Enu_Modes->FluxUnfold(GetFluxHistogram(), GetEventHistogram(), fScaleFactorEnuXSec, fNEvents); fHist_NuMu_Enu_Pions->FluxUnfold(GetFluxHistogram(), GetEventHistogram(), fScaleFactorEnuXSec, fNEvents); fHist_NuMu_Q2->Scale(fScaleFactor, "width"); fHist_NuMu_Q2_Modes->Scale(fScaleFactor, "width"); fHist_NuMu_Q2_Pions->Scale(fScaleFactor, "width"); fHist_NuMu_Pmu->Scale(fScaleFactor, "width"); fHist_NuMu_Pmu_Modes->Scale(fScaleFactor, "width"); fHist_NuMu_Pmu_Pions->Scale(fScaleFactor, "width"); fHist_NuMu_Cosmu->Scale(fScaleFactor, "width"); fHist_NuMu_Cosmu_Modes->Scale(fScaleFactor, "width"); fHist_NuMu_Cosmu_Pions->Scale(fScaleFactor, "width"); fHist_NuMu_EnuRates->Scale(fScaleFactorEnuXSec); fHist_NuMu_EnuRates_Modes->Scale(fScaleFactorEnuXSec); fHist_NuMu_EnuRates_Pions->Scale(fScaleFactorEnuXSec); PlotUtils::FluxUnfoldedScaling(fHist_NuMuBar_Enu, GetFluxHistogram(), GetEventHistogram(), fScaleFactorEnuXSec, fNEvents); fHist_NuMuBar_Enu_Modes->FluxUnfold(GetFluxHistogram(), GetEventHistogram(), fScaleFactorEnuXSec, fNEvents); fHist_NuMuBar_Enu_Pions->FluxUnfold(GetFluxHistogram(), GetEventHistogram(), fScaleFactorEnuXSec, fNEvents); fHist_NuMuBar_Q2->Scale(fScaleFactor, "width"); fHist_NuMuBar_Q2_Modes->Scale(fScaleFactor, "width"); fHist_NuMuBar_Q2_Pions->Scale(fScaleFactor, "width"); fHist_NuMuBar_Pmu->Scale(fScaleFactor, "width"); fHist_NuMuBar_Pmu_Modes->Scale(fScaleFactor, "width"); fHist_NuMuBar_Pmu_Pions->Scale(fScaleFactor, "width"); fHist_NuMuBar_Cosmu->Scale(fScaleFactor, "width"); fHist_NuMuBar_Cosmu_Modes->Scale(fScaleFactor, "width"); fHist_NuMuBar_Cosmu_Pions->Scale(fScaleFactor, "width"); fHist_Nue_EnuRates->Scale(fScaleFactorEnuXSec); fHist_Nue_EnuRates_Modes->Scale(fScaleFactorEnuXSec); fHist_Nue_EnuRates_Pions->Scale(fScaleFactorEnuXSec); PlotUtils::FluxUnfoldedScaling(fHist_Nue_Enu, GetFluxHistogram(), GetEventHistogram(), fScaleFactorEnuXSec, fNEvents); fHist_Nue_Enu_Modes->FluxUnfold(GetFluxHistogram(), GetEventHistogram(), fScaleFactorEnuXSec, fNEvents); fHist_Nue_Enu_Pions->FluxUnfold(GetFluxHistogram(), GetEventHistogram(), fScaleFactorEnuXSec, fNEvents); fHist_Nue_Q2->Scale(fScaleFactor, "width"); fHist_Nue_Q2_Modes->Scale(fScaleFactor, "width"); fHist_Nue_Q2_Pions->Scale(fScaleFactor, "width"); fHist_Nue_Pmu->Scale(fScaleFactor, "width"); fHist_Nue_Pmu_Modes->Scale(fScaleFactor, "width"); fHist_Nue_Pmu_Pions->Scale(fScaleFactor, "width"); fHist_Nue_Cosmu->Scale(fScaleFactor, "width"); fHist_Nue_Cosmu_Modes->Scale(fScaleFactor, "width"); fHist_Nue_Cosmu_Pions->Scale(fScaleFactor, "width"); fHist_Nue_EnuRates->Scale(fScaleFactorEnuXSec); fHist_Nue_EnuRates_Modes->Scale(fScaleFactorEnuXSec); fHist_Nue_EnuRates_Pions->Scale(fScaleFactorEnuXSec); PlotUtils::FluxUnfoldedScaling(fHist_NueBar_Enu, GetFluxHistogram(), GetEventHistogram(), fScaleFactorEnuXSec, fNEvents); fHist_NueBar_Enu_Modes->FluxUnfold(GetFluxHistogram(), GetEventHistogram(), fScaleFactorEnuXSec, fNEvents); fHist_NueBar_Enu_Pions->FluxUnfold(GetFluxHistogram(), GetEventHistogram(), fScaleFactorEnuXSec, fNEvents); fHist_NueBar_Q2->Scale(fScaleFactor, "width"); fHist_NueBar_Q2_Modes->Scale(fScaleFactor, "width"); fHist_NueBar_Q2_Pions->Scale(fScaleFactor, "width"); fHist_NueBar_Pmu->Scale(fScaleFactor, "width"); fHist_NueBar_Pmu_Modes->Scale(fScaleFactor, "width"); fHist_NueBar_Pmu_Pions->Scale(fScaleFactor, "width"); fHist_NueBar_Cosmu->Scale(fScaleFactor, "width"); fHist_NueBar_Cosmu_Modes->Scale(fScaleFactor, "width"); fHist_NueBar_Cosmu_Pions->Scale(fScaleFactor, "width"); return; } //******************************************************************** /// Select only events with final state Muons bool OfficialNIWGPlots::isSignal(FitEvent *event) { //******************************************************************** if (abs(event->Mode) > 30) return false; // Do we want any other signal? return true; }; /// Functions to deal with the SB mode stacks MCStudies::OfficialNIWGStack::OfficialNIWGStack(std::string name, std::string title, TH1* hist) { fName = name; fTitle = title; AddMode(0, "CC0PI", "CC-0#pi", kRed, 2, 1001); AddMode(1, "CC1PI", "CC-1#pi", kBlue, 2, 1001); AddMode(2, "CCOther", "CC-Other", kMagenta, 2, 1001); AddMode(3, "CCCOH", "CC-Coherent", kGreen, 2, 1001); AddMode(4, "OTHER", "Other", kYellow, 2, 1001); StackBase::SetupStack(hist); }; int MCStudies::OfficialNIWGStack::ConvertModeToIndex(FitEvent* event) { // Other if (((event->NumFSParticle(13) + event->NumFSParticle(-13)) != 1)) return 4; // CC 0 PI if ((event->NumFSMesons() == 0)) return 0; // CC Coherent if (abs(event->Mode) == 16) return 3; // CC 1 PI if ((event->NumFSParticle(PhysConst::pdg_charged_pions)) == 1) return 1; // CC Other return 2; }; void MCStudies::OfficialNIWGStack::Fill(FitEvent* evt, double x, double y, double z, double weight) { StackBase::FillStack(this->ConvertModeToIndex(evt), x, y, z, weight); }; /// Functions to deal with the SB mode stacks MCStudies::OfficialPionStack::OfficialPionStack(std::string name, std::string title, TH1* hist) { fName = name; fTitle = title; AddMode(0, "CC0PI", "CC-0#pi", kRed, 2, 1001); AddMode(1, "CC1PI", "CC-1#pi", kBlue, 2, 1001); AddMode(2, "CCNPI", "CC-N#pi", kGreen, 2, 1001); AddMode(3, "OTHER", "Other", kYellow, 2, 1001); StackBase::SetupStack(hist); }; int MCStudies::OfficialPionStack::ConvertModeToIndex(FitEvent* event) { // Other if (((event->NumFSParticle(13) + event->NumFSParticle(-13)) != 1)) return 3; // CC 0 PI int npi = (event->NumFSParticle(PhysConst::pdg_charged_pions)); if (npi == 0) return 0; if (npi == 1) return 1; if (npi > 1) return 2; return 3; }; void MCStudies::OfficialPionStack::Fill(FitEvent* evt, double x, double y, double z, double weight) { StackBase::FillStack(this->ConvertModeToIndex(evt), x, y, z, weight); }; diff --git a/src/MCStudies/Smear_SVDUnfold_Propagation_Osc.cxx b/src/MCStudies/Smear_SVDUnfold_Propagation_Osc.cxx index affdd58..60590a7 100644 --- a/src/MCStudies/Smear_SVDUnfold_Propagation_Osc.cxx +++ b/src/MCStudies/Smear_SVDUnfold_Propagation_Osc.cxx @@ -1,924 +1,924 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "Smear_SVDUnfold_Propagation_Osc.h" #include "SmearceptanceUtils.h" #include "OscWeightEngine.h" #include "HistogramInputHandler.h" void Smear_SVDUnfold_Propagation_Osc::AddNDInputs(nuiskey &samplekey) { NDSample nds; // Plot Setup ------------------------------------------------------- // Check that we have the relevant near detector histograms specified. if (!NDSamples.size()) { // If this is the first ND sample, take from the // sample input InputHandlerBase *InputBase = GetInput(); if (InputBase->GetType() != kHISTO) { - QTHROW( + NUIS_ABORT( "Smear_SVDUnfold_Propagation_Osc expects a Histogram input that " "contains the ND observed spectrum."); } HistoInputHandler *HInput = dynamic_cast(InputBase); if (!HInput) { - QTHROW( + NUIS_ABORT( "Smear_SVDUnfold_Propagation_Osc expects a Histogram input that " "contains the ND observed spectrum."); } if (HInput->NHistograms() != 2) { - QTHROW( + NUIS_ABORT( "Input expected to contain 2 histograms. " "HISTO:input.root[NDObs_TH1D,NDSmear_TH2D]"); } nds.NDDataHist = dynamic_cast(HInput->GetHistogram(0)); nds.NDToSpectrumSmearingMatrix = dynamic_cast(HInput->GetHistogram(1)); if (!nds.NDDataHist) { - QTHROW("Expected a valid TH1D input for the ND observed spectrum."); + NUIS_ABORT("Expected a valid TH1D input for the ND observed spectrum."); } if (!nds.NDToSpectrumSmearingMatrix) { - QTHROW("Expected a valid TH2D input for the ND observed smearing."); + NUIS_ABORT("Expected a valid TH2D input for the ND observed smearing."); } } else { std::vector NDObsInputs = PlotUtils::GetTH1sFromRootFile(samplekey.GetS("ObsInput")); if (NDObsInputs.size() < 2) { - QTHROW( + NUIS_ABORT( "Near detector sample must contain the observed ERec spectrum and " "the " "ND ETrue/ERec smearing matrix. e.g. " "ObsInput=\"input.root[NDObs_species,NDSmearing_species]\""); } nds.NDDataHist = dynamic_cast(NDObsInputs[0]); if (!nds.NDDataHist) { - QERROR(FTL, + NUIS_ERR(FTL, "First histogram from ObsInput attribute was not a TH1D containing " "the near detector observed ERec spectrum (" << samplekey.GetS("ObsInput") << ")."); - QTHROW( + NUIS_ABORT( "Near detector sample must contain the observed ERec spectrum and " "the " "ND ETrue/ERec smearing matrix. e.g. " "ObsInput=\"input.root[FDObs_species,FDSmearing_species]\""); } nds.NDToSpectrumSmearingMatrix = dynamic_cast(NDObsInputs[1]); if (!nds.NDToSpectrumSmearingMatrix) { - QERROR( + NUIS_ERR( FTL, "Second histogram from ObsInput attribute was not a TH2D containing " "the near detector ETrue/ERec smearing matrix (" << samplekey.GetS("ObsInput") << ")."); - QTHROW( + NUIS_ABORT( "Near detector sample must contain the observed ERec spectrum and " "the " "ND ETrue/ERec smearing matrix. e.g. " "ObsInput=\"input.root[FDObs_species,FDSmearing_species]\""); } } nds.NDDataHist->Scale(ScalePOT); if (UseRateErrors) { for (Int_t bi_it = 1; bi_it < nds.NDDataHist->GetXaxis()->GetNbins() + 1; ++bi_it) { nds.NDDataHist->SetBinError(bi_it, sqrt(nds.NDDataHist->GetBinContent(bi_it))); } } nds.TruncateStart = 0; if (samplekey.Has("TruncateStart")) { nds.TruncateStart = samplekey.GetI("TruncateStart"); } nds.TruncateUpTo = 0; if (samplekey.Has("TruncateUpTo")) { nds.TruncateUpTo = samplekey.GetI("TruncateUpTo"); - QLOG(SAM, "\tAllowed to truncate unfolding matrix by up to " + NUIS_LOG(SAM, "\tAllowed to truncate unfolding matrix by up to " << nds.TruncateUpTo << " singular values to limit negative ENu spectra."); } nds.NuPDG = 14; if (samplekey.Has("NuPDG")) { nds.NuPDG = samplekey.GetI("NuPDG"); } NDSamples.push_back(nds); } void Smear_SVDUnfold_Propagation_Osc::SetupNDInputs() { for (size_t nd_it = 0; nd_it < NDSamples.size(); ++nd_it) { NDSample &nds = NDSamples[nd_it]; TMatrixD NDToSpectrumResponseMatrix_l = SmearceptanceUtils::GetMatrix( SmearceptanceUtils::SVDGetInverse(nds.NDToSpectrumSmearingMatrix)); nds.NDToSpectrumResponseMatrix.ResizeTo(NDToSpectrumResponseMatrix_l); nds.NDToSpectrumResponseMatrix = NDToSpectrumResponseMatrix_l; if (nds.TruncateStart != 0) { TMatrixD NDToSpectrumResponseMatrix_l = SmearceptanceUtils::GetMatrix(SmearceptanceUtils::SVDGetInverse( nds.NDToSpectrumSmearingMatrix, nds.TruncateStart)); nds.NDToSpectrumResponseMatrix.ResizeTo(NDToSpectrumResponseMatrix_l); nds.NDToSpectrumResponseMatrix = NDToSpectrumResponseMatrix_l; } if (nds.TruncateStart >= nds.TruncateUpTo) { nds.TruncateUpTo = nds.TruncateStart + 1; } UnfoldToNDETrueSpectrum(nd_it); } } void Smear_SVDUnfold_Propagation_Osc::ReadExtraConfig(nuiskey &samplekey) { UseRateErrors = false; if (samplekey.Has("SetErrorsFromRate")) { UseRateErrors = samplekey.GetI("SetErrorsFromRate"); } NDetectorInfo.first = 0xdeadbeef; if (samplekey.Has("DetectorVolume") && samplekey.Has("DetectorDensity")) { NDetectorInfo.first = samplekey.GetD("DetectorVolume"); NDetectorInfo.second = samplekey.GetD("DetectorDensity"); double TargetMass_kg = NDetectorInfo.first * NDetectorInfo.second; - QLOG(SAM, "\tND sample detector mass : "); - QLOG(SAM, "\t\tTarget volume : " << NDetectorInfo.first); - QLOG(SAM, "\t\tTarget density : " << NDetectorInfo.second); - QLOG(SAM, "\t\tTarget mass : " << TargetMass_kg << " kg"); + NUIS_LOG(SAM, "\tND sample detector mass : "); + NUIS_LOG(SAM, "\t\tTarget volume : " << NDetectorInfo.first); + NUIS_LOG(SAM, "\t\tTarget density : " << NDetectorInfo.second); + NUIS_LOG(SAM, "\t\tTarget mass : " << TargetMass_kg << " kg"); } ScalePOT = 1; if (samplekey.Has("ScalePOT")) { ScalePOT = samplekey.GetD("ScalePOT"); } } void Smear_SVDUnfold_Propagation_Osc::AddFDTarget(nuiskey &nk) { FDSample fds; fds.FitRegion_Min = 0xdeadbeef; if (nk.Has("FitRegion_Min")) { fds.FitRegion_Min = nk.GetD("FitRegion_Min"); - QLOG(SAM, "FD Sample [" << FDSamples.size() << "] imposes FitRegion E_nu > " + NUIS_LOG(SAM, "FD Sample [" << FDSamples.size() << "] imposes FitRegion E_nu > " << fds.FitRegion_Min); } if ((FitRegion_Min == 0xdeadbeef) || FitRegion_Min > fds.FitRegion_Min) { FitRegion_Min = fds.FitRegion_Min; } nk.Print(); fds.FitRegion_Max = 0xdeadbeef; if (nk.Has("FitRegion_Max")) { fds.FitRegion_Max = nk.GetD("FitRegion_Max"); - QLOG(SAM, "FD Sample [" << FDSamples.size() << "] imposes FitRegion E_nu < " + NUIS_LOG(SAM, "FD Sample [" << FDSamples.size() << "] imposes FitRegion E_nu < " << fds.FitRegion_Max); } if ((FitRegion_Max == 0xdeadbeef) || FitRegion_Max < fds.FitRegion_Max) { FitRegion_Max = fds.FitRegion_Max; } fds.OscillateToPDG = 0; if (nk.Has("OscillateToPDG")) { fds.OscillateToPDG = nk.GetD("OscillateToPDG"); } std::vector FDNDRatioElements = nk.GetListOfChildNodes("FDNDRatio"); for (size_t fdnd_it = 0; fdnd_it < FDNDRatioElements.size(); ++fdnd_it) { nuiskey &fnr = FDNDRatioElements[fdnd_it]; if (fnr.Has("FromPDG") && fnr.Has("DivergenceFactor")) { fds.FDNDRatios[fnr.GetI("FromPDG")] = fnr.GetD("DivergenceFactor"); - QLOG(SAM, "FDND DivergenceFactor for far detector sample index: " + NUIS_LOG(SAM, "FDND DivergenceFactor for far detector sample index: " << FDSamples.size() << " for PDG: " << fnr.GetI("FromPDG") << " -> " << fds.OscillateToPDG << " = " << fnr.GetD("DivergenceFactor")); } else { - QTHROW( + NUIS_ABORT( "Far detector sample contained FDNDRatio element, but couldn't find " "both FromPDG and Factor attributes."); } } fds.FDNDMassRatio = 1; if (NDetectorInfo.first != 0xdeadbeef) { if ((!nk.Has("DetectorVolume")) || (!nk.Has("DetectorDensity"))) { - QTHROW( + NUIS_ABORT( "Near detector sample has specified volume but FD doesn't. This is " "needed to scale the predicted event rate by the mass ratio."); } fds.DetectorInfo.first = nk.GetD("DetectorVolume"); fds.DetectorInfo.second = nk.GetD("DetectorDensity"); double TargetMass_kg = fds.DetectorInfo.first * fds.DetectorInfo.second; fds.FDNDMassRatio = TargetMass_kg / (NDetectorInfo.first * NDetectorInfo.second); - QLOG(SAM, "\tFD[" << FDSamples.size() << "] Event rate prediction : "); - QLOG(SAM, "\t\tTarget volume : " << fds.DetectorInfo.first); - QLOG(SAM, "\t\tTarget density : " << fds.DetectorInfo.second); - QLOG(SAM, "\t\tFD/ND mass : " << fds.FDNDMassRatio); + NUIS_LOG(SAM, "\tFD[" << FDSamples.size() << "] Event rate prediction : "); + NUIS_LOG(SAM, "\t\tTarget volume : " << fds.DetectorInfo.first); + NUIS_LOG(SAM, "\t\tTarget density : " << fds.DetectorInfo.second); + NUIS_LOG(SAM, "\t\tFD/ND mass : " << fds.FDNDMassRatio); } if (!nk.Has("ObsInput")) { - QTHROW("Far detector sample must specify at least ObsInput."); + NUIS_ABORT("Far detector sample must specify at least ObsInput."); } std::vector FDObsInputs = PlotUtils::GetTH1sFromRootFile(nk.GetS("ObsInput")); if (FDObsInputs.size() < 2) { - QTHROW( + NUIS_ABORT( "Far detector sample must contain the observed ERec spectrum and the " "FD ETrue/ERec smearing matrix. " "ObsInput=\"input.root[FDObs_species,FDSmearing_species]\""); } fds.FDDataHist = NULL; for (size_t hist_it = 0; hist_it < FDObsInputs.size() - 1; ++hist_it) { if (!dynamic_cast(FDObsInputs[hist_it])) { - QERROR(FTL, "Input spectrum index " + NUIS_ERR(FTL, "Input spectrum index " << hist_it << " from ObsInput attribute was not a TH1D containing " "a far detector observed ERec spectrum (" << nk.GetS("ObsInput") << ")."); - QTHROW( + NUIS_ABORT( "Far detector sample must contain the observed ERec spectrum and the " "FD ETrue/ERec smearing matrix. " "ObsInput=\"input.root[FDObs_species,(FDObs_species2),FDSmearing_" "species]\""); } FDObsInputs[hist_it]->Scale(ScalePOT); if (!fds.FDDataHist) { fds.FDDataHist = dynamic_cast(FDObsInputs[hist_it]); } else { fds.FDDataHist->Add(dynamic_cast(FDObsInputs[hist_it])); } - QLOG(SAM, "Added " << (FDObsInputs.size() - 1) + NUIS_LOG(SAM, "Added " << (FDObsInputs.size() - 1) << " far detector component spectra to form Observed " "spectra for sample index " << FDSamples.size() << "."); } fds.SpectrumToFDSmearingMatrix_TH2 = dynamic_cast(FDObsInputs.back()); if (!fds.SpectrumToFDSmearingMatrix_TH2) { - QERROR(FTL, + NUIS_ERR(FTL, "last histogram from ObsInput attribute was not a TH2D containing " "the far detector ETrue/ERec smearing matrix (" << nk.GetS("ObsInput") << ")."); - QTHROW( + NUIS_ABORT( "Far detector sample must contain the observed ERec spectrum and the " "FD ETrue/ERec smearing matrix. " "ObsInput=\"input.root[FDObs_species,FDSmearing_species]\""); } TMatrixD SpectrumToFDSmearingMatrix_l = SmearceptanceUtils::GetMatrix(fds.SpectrumToFDSmearingMatrix_TH2); fds.SpectrumToFDSmearingMatrix.ResizeTo(SpectrumToFDSmearingMatrix_l); fds.SpectrumToFDSmearingMatrix = SpectrumToFDSmearingMatrix_l; FDSamples.push_back(fds); } void Smear_SVDUnfold_Propagation_Osc::FinaliseFDSamples() { std::stringstream ss(""); for (size_t fds_it = 0; fds_it < FDSamples.size(); ++fds_it) { FDSample &fds = FDSamples[fds_it]; // Set up FD histograms. // ============================== for (size_t nd_it = 0; nd_it < NDSamples.size(); ++nd_it) { NDSample &nds = NDSamples[nd_it]; TH1D *sampleHist = static_cast(nds.ND_Unfolded_Spectrum_Hist->Clone()); sampleHist->Reset(); ss.str(""); ss << "FD_Propagated_Spectrum_Hist_" << fds_it << "_NDSample_" << nd_it; sampleHist->SetName(ss.str().c_str()); fds.FD_Propagated_Spectrum_Hist_NDSamples.push_back(sampleHist); } fds.FD_Propagated_Spectrum_Hist = static_cast( fds.FD_Propagated_Spectrum_Hist_NDSamples[0]->Clone()); fds.FD_Propagated_Spectrum_Hist->Reset(); ss.str(""); ss << "FD_Propagated_Spectrum_Hist_" << fds_it; fds.FD_Propagated_Spectrum_Hist->SetName(ss.str().c_str()); for (size_t nd_it = 0; nd_it < NDSamples.size(); ++nd_it) { //NDSample &nds = NDSamples[nd_it]; TH1D *sampleHist = static_cast(fds.FD_Propagated_Spectrum_Hist->Clone()); sampleHist->Reset(); ss.str(""); ss << "NDFD_Corrected_Spectrum_Hist_" << fds_it << "_NDSample_" << nd_it; sampleHist->SetName(ss.str().c_str()); fds.NDFD_Corrected_Spectrum_Hist_NDSamples.push_back(sampleHist); } fds.NDFD_Corrected_Spectrum_Hist = static_cast(fds.FD_Propagated_Spectrum_Hist->Clone()); fds.NDFD_Corrected_Spectrum_Hist->Reset(); ss.str(""); ss << "NDFD_Corrected_Spectrum_Hist_" << fds_it; fds.NDFD_Corrected_Spectrum_Hist->SetName(ss.str().c_str()); fds.FD_Smeared_Spectrum_Hist = new TH1D(*fds.SpectrumToFDSmearingMatrix_TH2->ProjectionX()); fds.FD_Smeared_Spectrum_Hist->SetDirectory(NULL); fds.FD_Smeared_Spectrum_Hist->Reset(); ss.str(""); ss << "FD_Smeared_Spectrum_Hist_" << fds_it; fds.FD_Smeared_Spectrum_Hist->SetName(ss.str().c_str()); for (size_t nd_it = 0; nd_it < NDSamples.size(); ++nd_it) { NDSample &nds = NDSamples[nd_it]; if (!fds.FDNDRatios.count(nds.NuPDG)) { - QERROR(WRN, "Have an ND sample that provides PDG:" + NUIS_ERR(WRN, "Have an ND sample that provides PDG:" << nds.NuPDG << " neutrinos but far detector sample index " << fds_it << " doesn't have an NDFD ratio for this sample. " "Setting to 0 (contribution from sample ignored.)"); fds.FDNDRatios[nds.NuPDG] = 0; } } } } Int_t Smear_SVDUnfold_Propagation_Osc::GetFDSampleNAnalysisBins(size_t fds_it) { if (fds_it >= FDSamples.size()) { - QTHROW("Requested FD sample index " << fds_it << " but only initialised " + NUIS_ABORT("Requested FD sample index " << fds_it << " but only initialised " << FDSamples.size()); } FDSample &fds = FDSamples[fds_it]; Int_t NAnalysisBins = 0; for (Int_t bi_it = 1; bi_it < fds.FDDataHist->GetXaxis()->GetNbins() + 1; ++bi_it) { if ((fds.FitRegion_Min != 0xdeadbeef) && (fds.FDDataHist->GetXaxis()->GetBinUpEdge(bi_it) <= fds.FitRegion_Min)) { continue; } if ((fds.FitRegion_Max != 0xdeadbeef) && (fds.FDDataHist->GetXaxis()->GetBinLowEdge(bi_it) > fds.FitRegion_Max)) { continue; } NAnalysisBins++; } return NAnalysisBins; } void Smear_SVDUnfold_Propagation_Osc::SetupChi2Hists() { fDataHist = new TH1D("SmearSVDUnfold", "", NFDAnalysisBins, 0, NFDAnalysisBins); fDataHist->SetNameTitle((fSettings.GetName() + "_data").c_str(), (fSettings.GetFullTitles()).c_str()); Int_t CurrAnalysisBin = 1; for (size_t fds_it = 0; fds_it < FDSamples.size(); ++fds_it) { FDSample &fds = FDSamples[fds_it]; for (Int_t bi_it = 1; bi_it < fds.FDDataHist->GetXaxis()->GetNbins() + 1; ++bi_it) { if ((fds.FitRegion_Min != 0xdeadbeef) && (fds.FDDataHist->GetXaxis()->GetBinUpEdge(bi_it) <= fds.FitRegion_Min)) { continue; } if ((fds.FitRegion_Max != 0xdeadbeef) && (fds.FDDataHist->GetXaxis()->GetBinLowEdge(bi_it) > fds.FitRegion_Max)) { continue; } fDataHist->SetBinContent(CurrAnalysisBin, fds.FDDataHist->GetBinContent(bi_it)); if (UseRateErrors) { fDataHist->SetBinError(CurrAnalysisBin, sqrt(fds.FDDataHist->GetBinContent(bi_it))); } else { fDataHist->SetBinError(CurrAnalysisBin, fds.FDDataHist->GetBinError(bi_it)); } CurrAnalysisBin++; } } fMCHist = static_cast(fDataHist->Clone()); fMCHist->SetNameTitle((fSettings.GetName() + "_MC").c_str(), (fSettings.GetFullTitles()).c_str()); fMCHist->Reset(); } void Smear_SVDUnfold_Propagation_Osc::UpdateChi2Hists() { Int_t CurrAnalysisBin = 1; for (size_t fds_it = 0; fds_it < FDSamples.size(); ++fds_it) { FDSample &fds = FDSamples[fds_it]; for (Int_t bi_it = 1; bi_it < fds.FD_Smeared_Spectrum_Hist->GetXaxis()->GetNbins() + 1; ++bi_it) { if ((fds.FitRegion_Min != 0xdeadbeef) && (fds.FD_Smeared_Spectrum_Hist->GetXaxis()->GetBinUpEdge(bi_it) <= fds.FitRegion_Min)) { continue; } if ((fds.FitRegion_Max != 0xdeadbeef) && (fds.FD_Smeared_Spectrum_Hist->GetXaxis()->GetBinLowEdge(bi_it) > fds.FitRegion_Max)) { continue; } fMCHist->SetBinContent( CurrAnalysisBin, fds.FD_Smeared_Spectrum_Hist->GetBinContent(bi_it)); fMCHist->SetBinError(CurrAnalysisBin, fds.FD_Smeared_Spectrum_Hist->GetBinError(bi_it)); CurrAnalysisBin++; } } } //******************************************************************** Smear_SVDUnfold_Propagation_Osc::Smear_SVDUnfold_Propagation_Osc( nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "Simple measurement class for doing fake data oscillation studies.\n"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetTitle("Osc Studies"); fSettings.SetDescription(descrip); fSettings.SetXTitle("XXX"); fSettings.SetYTitle("Number of events"); fSettings.SetEnuRange(0.0, 50); fSettings.SetAllowedTypes("EVT/SHAPE/DIAG", "EVT/SHAPE/DIAG"); fSettings.DefineAllowedTargets("*"); fSettings.DefineAllowedSpecies("numu"); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = GetEventHistogram()->Integral("width") / (fNEvents + 0.); fMCHist = NULL; fDataHist = NULL; ReadExtraConfig(samplekey); AddNDInputs(samplekey); std::vector NDTargets = samplekey.GetListOfChildNodes("NDObs"); for (size_t nd_it = 0; nd_it < NDTargets.size(); ++nd_it) { AddNDInputs(NDTargets[nd_it]); } std::vector FDTargets = samplekey.GetListOfChildNodes("FDObs"); NFDAnalysisBins = 0; if (!FDTargets.size()) { // If no child elements, assume that everything is // contained on the sample element AddFDTarget(samplekey); } else { for (size_t fd_it = 0; fd_it < FDTargets.size(); ++fd_it) { AddFDTarget(FDTargets[fd_it]); NFDAnalysisBins += GetFDSampleNAnalysisBins(fd_it); } } if ((FitRegion_Min != 0xdeadbeef) || (FitRegion_Max != 0xdeadbeef)) { - QLOG(SAM, "When unfolding, interested region limited to:"); + NUIS_LOG(SAM, "When unfolding, interested region limited to:"); if (FitRegion_Min != 0xdeadbeef) { - QLOG(SAM, "\tE_nu > " << FitRegion_Min); + NUIS_LOG(SAM, "\tE_nu > " << FitRegion_Min); } if (FitRegion_Max != 0xdeadbeef) { - QLOG(SAM, "\tE_nu < " << FitRegion_Max); + NUIS_LOG(SAM, "\tE_nu < " << FitRegion_Max); } } SetupNDInputs(); FinaliseFDSamples(); - QLOG(SAM, "Set up " << FDSamples.size() + NUIS_LOG(SAM, "Set up " << FDSamples.size() << " samples for oscillation analysis with " << NFDAnalysisBins << " analysis bins."); SetupChi2Hists(); SetCovarFromDiagonal(); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; void Smear_SVDUnfold_Propagation_Osc::FillEventVariables(FitEvent *event){}; bool Smear_SVDUnfold_Propagation_Osc::isSignal(FitEvent *event) { return false; } void DumpUnfoldDebugInfo(Smear_SVDUnfold_Propagation_Osc::NDSample &nds, size_t nd_it, size_t truncations) { TDirectory *ogDir = gDirectory; std::stringstream ss; ss.str(""); ss << "DEBUG_FailedInvert_NDSample_" << nd_it; Config::Get().out->mkdir(ss.str().c_str()); Config::Get().out->cd(ss.str().c_str()); ss.str(""); ss << "ND_Smearing_Matrix_" << nd_it; nds.NDToSpectrumSmearingMatrix->Write(ss.str().c_str(), TObject::kOverwrite); ss.str(""); ss << "ND_Inverse_Smearing_Matrix_" << nd_it; SmearceptanceUtils::SVDGetInverse(nds.NDToSpectrumSmearingMatrix, 0) ->Write(ss.str().c_str(), TObject::kOverwrite); ss.str(""); ss << "ND_Inverse_Smearing_Matrix_" << nd_it << "_Trunc_" << truncations; SmearceptanceUtils::SVDGetInverse(nds.NDToSpectrumSmearingMatrix, truncations) ->Write(ss.str().c_str(), TObject::kOverwrite); ss.str(""); ss << "ND_Obs_" << nd_it; nds.NDDataHist->Write(ss.str().c_str(), TObject::kOverwrite); TMatrixD NDToSpectrumResponseMatrix_notrunc = SmearceptanceUtils::GetMatrix( SmearceptanceUtils::SVDGetInverse(nds.NDToSpectrumSmearingMatrix, 0)); nds.NDToSpectrumResponseMatrix.ResizeTo(NDToSpectrumResponseMatrix_notrunc); nds.NDToSpectrumResponseMatrix = NDToSpectrumResponseMatrix_notrunc; SmearceptanceUtils::PushTH1ThroughMatrixWithErrors( nds.NDDataHist, nds.ND_Unfolded_Spectrum_Hist, nds.NDToSpectrumResponseMatrix, 1000, false); ss.str(""); ss << "ND_Unfolded_" << nd_it; nds.ND_Unfolded_Spectrum_Hist->Write(ss.str().c_str(), TObject::kOverwrite); TMatrixD NDToSpectrumResponseMatrix_trunc = SmearceptanceUtils::GetMatrix(SmearceptanceUtils::SVDGetInverse( nds.NDToSpectrumSmearingMatrix, truncations)); nds.NDToSpectrumResponseMatrix.ResizeTo(NDToSpectrumResponseMatrix_trunc); nds.NDToSpectrumResponseMatrix = NDToSpectrumResponseMatrix_trunc; SmearceptanceUtils::PushTH1ThroughMatrixWithErrors( nds.NDDataHist, nds.ND_Unfolded_Spectrum_Hist, nds.NDToSpectrumResponseMatrix, 1000, false); ss.str(""); ss << "ND_Unfolded_" << nd_it << "_Trunc_" << truncations; nds.ND_Unfolded_Spectrum_Hist->Write(ss.str().c_str(), TObject::kOverwrite); if (ogDir) { ogDir->cd(); } else { Config::Get().out->cd(); } } void Smear_SVDUnfold_Propagation_Osc::UnfoldToNDETrueSpectrum(size_t nd_it) { if (nd_it >= NDSamples.size()) { - QTHROW("Attempting to unfold ND sample index " + NUIS_ABORT("Attempting to unfold ND sample index " << nd_it << " but only have " << NDSamples.size() << " ND samples."); } NDSample &nds = NDSamples[nd_it]; nds.ND_Unfolded_Spectrum_Hist = new TH1D(*nds.NDToSpectrumSmearingMatrix->ProjectionY()); nds.ND_Unfolded_Spectrum_Hist->SetDirectory(NULL); nds.ND_Unfolded_Spectrum_Hist->Clear(); std::stringstream ss(""); ss << "ND_Unfolded_Spectrum_Hist_" << nd_it; nds.ND_Unfolded_Spectrum_Hist->SetName(ss.str().c_str()); bool HasNegValue = false; int truncations = nds.TruncateStart; do { if (truncations >= nds.TruncateUpTo) { DumpUnfoldDebugInfo(nds, nd_it, truncations); - QTHROW("Unfolded enu spectrum had negative values even after " + NUIS_ABORT("Unfolded enu spectrum had negative values even after " << truncations << " SVD singular value truncations."); } // Unfold ND ERec -> Enu spectrum // ------------------------------ SmearceptanceUtils::PushTH1ThroughMatrixWithErrors( nds.NDDataHist, nds.ND_Unfolded_Spectrum_Hist, nds.NDToSpectrumResponseMatrix, 1000, false); HasNegValue = false; for (Int_t bi_it = 1; bi_it < nds.ND_Unfolded_Spectrum_Hist->GetXaxis()->GetNbins() + 1; ++bi_it) { if ((FitRegion_Min != 0xdeadbeef) && (nds.ND_Unfolded_Spectrum_Hist->GetXaxis()->GetBinUpEdge(bi_it) <= FitRegion_Min)) { continue; } if ((FitRegion_Max != 0xdeadbeef) && (nds.ND_Unfolded_Spectrum_Hist->GetXaxis()->GetBinLowEdge(bi_it) > FitRegion_Max)) { continue; } if (nds.ND_Unfolded_Spectrum_Hist->GetBinContent(bi_it) < 0) { HasNegValue = true; - QLOG(SAM, + NUIS_LOG(SAM, "After " << truncations << " truncations, bin " << (bi_it - 1) << " [" << nds.ND_Unfolded_Spectrum_Hist->GetXaxis()->GetBinLowEdge( bi_it) << " -- " << nds.ND_Unfolded_Spectrum_Hist->GetXaxis()->GetBinUpEdge( bi_it) << " ] has value: " << nds.ND_Unfolded_Spectrum_Hist->GetBinContent(bi_it)); break; } } if (HasNegValue) { TMatrixD NDToSpectrumResponseMatrix_l = SmearceptanceUtils::GetMatrix(SmearceptanceUtils::SVDGetInverse( nds.NDToSpectrumSmearingMatrix, truncations)); nds.NDToSpectrumResponseMatrix.ResizeTo(NDToSpectrumResponseMatrix_l); nds.NDToSpectrumResponseMatrix = NDToSpectrumResponseMatrix_l; } truncations++; } while (HasNegValue); } void Smear_SVDUnfold_Propagation_Osc::PropagateFDSample(size_t fds_it) { if (fds_it >= FDSamples.size()) { - QTHROW("Requested FD sample index " << fds_it << " but only initialised " + NUIS_ABORT("Requested FD sample index " << fds_it << " but only initialised " << FDSamples.size()); } FDSample &fds = FDSamples[fds_it]; // Apply Oscillations // ------------------------------ FitWeight *fw = FitBase::GetRW(); OscWeightEngine *oscWE = dynamic_cast(fw->GetRWEngine(kOSCILLATION)); if (!oscWE) { - QTHROW( + NUIS_ABORT( "Couldn't load oscillation weight engine for sample: " "Smear_SVDUnfold_Propagation_Osc."); } for (Int_t bi_it = 1; bi_it < fds.NDFD_Corrected_Spectrum_Hist->GetXaxis()->GetNbins() + 1; ++bi_it) { double content_osc = 0; double error_osc = 0; double content_fdnd = 0; double error_fdnd = 0; // Oscillate each ND sample to FD neutrino for (size_t nd_it = 0; nd_it < NDSamples.size(); ++nd_it) { NDSample &nds = NDSamples[nd_it]; double oscWeight = oscWE->CalcWeight( nds.ND_Unfolded_Spectrum_Hist->GetXaxis()->GetBinCenter(bi_it), nds.NuPDG, fds.OscillateToPDG); double sample_content_osc = nds.ND_Unfolded_Spectrum_Hist->GetBinContent(bi_it) * oscWeight; double sample_error_osc = nds.ND_Unfolded_Spectrum_Hist->GetBinError(bi_it) * oscWeight; fds.FD_Propagated_Spectrum_Hist_NDSamples[nd_it]->SetBinContent( bi_it, sample_content_osc); fds.FD_Propagated_Spectrum_Hist_NDSamples[nd_it]->SetBinError( bi_it, sample_error_osc); double sample_content_fdnd = sample_content_osc * fds.FDNDRatios[nds.NuPDG] * fds.FDNDMassRatio; double sample_error_fdnd = sample_error_osc * fds.FDNDRatios[nds.NuPDG] * fds.FDNDMassRatio; fds.NDFD_Corrected_Spectrum_Hist_NDSamples[nd_it]->SetBinContent( bi_it, sample_content_fdnd); fds.NDFD_Corrected_Spectrum_Hist_NDSamples[nd_it]->SetBinError( bi_it, sample_error_fdnd); content_osc += sample_content_osc; error_osc += sample_error_osc * sample_error_osc; content_fdnd += sample_content_fdnd; error_fdnd += sample_error_fdnd * sample_error_fdnd; } fds.FD_Propagated_Spectrum_Hist->SetBinContent(bi_it, content_osc); fds.FD_Propagated_Spectrum_Hist->SetBinError(bi_it, sqrt(error_osc)); fds.NDFD_Corrected_Spectrum_Hist->SetBinContent(bi_it, content_fdnd); fds.NDFD_Corrected_Spectrum_Hist->SetBinError(bi_it, sqrt(error_fdnd)); } // Forward fold Spectrum -> ERec FD // ------------------------------ SmearceptanceUtils::PushTH1ThroughMatrixWithErrors( fds.NDFD_Corrected_Spectrum_Hist, fds.FD_Smeared_Spectrum_Hist, fds.SpectrumToFDSmearingMatrix, 1000, true); } void Smear_SVDUnfold_Propagation_Osc::ConvertEventRates(void) { /// Get topology weights /// for each ND sample /// /// Build NDSample::NDToSpectrumSmearingMatrix from sum of topology smearing histos scaled by topology weights /// /// SetupNDInputs(); /// /// for each FD sample /// /// Build FDSample::SpectrumToFDSmearingMatrix_TH2 as above. /// /// Convert to TMatrixD, FDSample::SpectrumToFDSmearingMatrix for (size_t fds_it = 0; fds_it < FDSamples.size(); ++fds_it) { PropagateFDSample(fds_it); } UpdateChi2Hists(); } void Smear_SVDUnfold_Propagation_Osc::Write(std::string drawOpt) { TDirectory *ogDir = gDirectory; ConvertEventRates(); FitWeight *fw = FitBase::GetRW(); OscWeightEngine *oscWE = dynamic_cast(fw->GetRWEngine(kOSCILLATION)); if (!oscWE) { - QTHROW( + NUIS_ABORT( "Couldn't load oscillation weight engine for sample: " "Smear_SVDUnfold_Propagation_Osc."); } oscWE->Print(); // Write ND samples //---------------- for (size_t nd_it = 0; nd_it < NDSamples.size(); ++nd_it) { NDSample &nds = NDSamples[nd_it]; std::stringstream ss(""); ss << "Smear_SVDUnfold_Propagation_Osc_NDSample_" << nd_it; if (ogDir) { ogDir->mkdir(ss.str().c_str()); ogDir->cd(ss.str().c_str()); } else { Config::Get().out->mkdir(ss.str().c_str()); Config::Get().out->cd(ss.str().c_str()); } nds.NDToSpectrumSmearingMatrix->Write("SmearingMatrix_ND", TObject::kOverwrite); nds.NDDataHist->Write("Obs_ND", TObject::kOverwrite); nds.ND_Unfolded_Spectrum_Hist->Write( nds.ND_Unfolded_Spectrum_Hist->GetName(), TObject::kOverwrite); if (ogDir) { ogDir->cd(); } else { Config::Get().out->cd(); } } // Write FD samples //---------------- for (size_t fds_it = 0; fds_it < FDSamples.size(); ++fds_it) { FDSample &fds = FDSamples[fds_it]; std::stringstream ss(""); ss << "Smear_SVDUnfold_Propagation_Osc_FDSample_" << fds_it; if (ogDir) { ogDir->mkdir(ss.str().c_str()); ogDir->cd(ss.str().c_str()); } else { Config::Get().out->mkdir(ss.str().c_str()); Config::Get().out->cd(ss.str().c_str()); } // Calc oscillation probability // ------------------------------ FitWeight *fw = FitBase::GetRW(); OscWeightEngine *oscWE = dynamic_cast(fw->GetRWEngine(kOSCILLATION)); if (!oscWE) { - QTHROW( + NUIS_ABORT( "Couldn't load oscillation weight engine for sample: " "Smear_SVDUnfold_Propagation_Osc."); } for (size_t nd_it = 0; nd_it < NDSamples.size(); ++nd_it) { NDSample &nds = NDSamples[nd_it]; ss.str(""); ss << "NDSample_" << nd_it << "_contribution"; fds.FD_Propagated_Spectrum_Hist_NDSamples[nd_it]->Write( ss.str().c_str(), TObject::kOverwrite); ss.str(""); ss << "NDSample_" << nd_it << "_FDNDCorrected_contribution"; fds.NDFD_Corrected_Spectrum_Hist_NDSamples[nd_it]->Write( ss.str().c_str(), TObject::kOverwrite); ss.str(""); ss << "NDSample_" << nd_it << "_OscillationProb"; TGraph POsc; POsc.Set(1E4 - 1); double min = nds.ND_Unfolded_Spectrum_Hist->GetXaxis()->GetBinLowEdge(1); double step = (nds.ND_Unfolded_Spectrum_Hist->GetXaxis()->GetBinUpEdge( nds.ND_Unfolded_Spectrum_Hist->GetXaxis()->GetNbins()) - nds.ND_Unfolded_Spectrum_Hist->GetXaxis()->GetBinLowEdge(1)) / double(1E4); for (size_t i = 1; i < 1E4; ++i) { double enu = min + i * step; double ow = oscWE->CalcWeight(enu, nds.NuPDG, fds.OscillateToPDG); if (ow != ow) { std::cout << "Bad osc weight for ENu: " << enu << std::endl; } POsc.SetPoint(i - 1, enu, ow); } POsc.Write(ss.str().c_str(), TObject::kOverwrite); } fds.FDDataHist->Write("Obs_FD", TObject::kOverwrite); fds.FD_Propagated_Spectrum_Hist->Write( fds.FD_Propagated_Spectrum_Hist->GetName(), TObject::kOverwrite); fds.NDFD_Corrected_Spectrum_Hist->Write( fds.NDFD_Corrected_Spectrum_Hist->GetName(), TObject::kOverwrite); fds.SpectrumToFDSmearingMatrix_TH2->Write("SmearingMatrix_FD", TObject::kOverwrite); fds.FD_Smeared_Spectrum_Hist->Write(fds.FD_Smeared_Spectrum_Hist->GetName(), TObject::kOverwrite); if (ogDir) { ogDir->cd(); } else { Config::Get().out->cd(); } } fMCHist->Write("Pred_FD", TObject::kOverwrite); fDataHist->Write("Obs_FD", TObject::kOverwrite); Measurement1D::Write(drawOpt); } diff --git a/src/MCStudies/Smearceptance_Tester.cxx b/src/MCStudies/Smearceptance_Tester.cxx index 0ef2865..9ec08cd 100644 --- a/src/MCStudies/Smearceptance_Tester.cxx +++ b/src/MCStudies/Smearceptance_Tester.cxx @@ -1,881 +1,881 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "Smearceptance_Tester.h" #include "SmearceptanceUtils.h" #include "Smearcepterton.h" //#define DEBUG_SMEARTESTER //******************************************************************** /// @brief Class to perform smearceptance MC Studies on a custom measurement Smearceptance_Tester::Smearceptance_Tester(nuiskey samplekey) { //******************************************************************** samplekey.Print(); // Sample overview --------------------------------------------------- std::string descrip = "Simple measurement class for producing an event summary tree of smeared " "events.\n"; if (Config::HasPar("NPOT")) { samplekey.SetS("NPOT", Config::GetParS("NPOT")); } if (Config::HasPar("FluxIntegralOverride")) { samplekey.SetS("FluxIntegralOverride", Config::GetParS("FluxIntegralOverride")); } if (Config::HasPar("TargetVolume")) { samplekey.SetS("TargetVolume", Config::GetParS("TargetVolume")); } if (Config::HasPar("TargetMaterialDensity")) { samplekey.SetS("TargetMaterialDensity", Config::GetParS("TargetMaterialDensity")); } OutputSummaryTree = true; if (Config::HasPar("smear.OutputSummaryTree")) { OutputSummaryTree = Config::GetParI("smear.OutputSummaryTree"); } // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetTitle("Smearceptance Studies"); fSettings.SetDescription(descrip); fSettings.SetXTitle("XXX"); fSettings.SetYTitle("Number of events"); fSettings.SetEnuRange(0.0, 1E5); fSettings.SetAllowedTypes("EVT/SHAPE/DIAG", "EVT/SHAPE/DIAG"); fSettings.DefineAllowedTargets("*"); fSettings.DefineAllowedSpecies("*"); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = (GetEventHistogram()->Integral("width") * 1E-38 / (fNEvents + 0.)) / TotalIntegratedFlux(); // Measurement Details std::vector splitName = GeneralUtils::ParseToStr(fName, "_"); //size_t firstUS = fName.find_first_of("_"); std::string smearceptorName = samplekey.GetS("smearceptor"); - QLOG(SAM, "Using smearceptor: " << smearceptorName + NUIS_LOG(SAM, "Using smearceptor: " << smearceptorName << " (parsed from: " << fName << ")."); fDataHist = new TH1D(("empty_data"), ("empty-data"), 1, 0, 1); SetupDefaultHist(); fFullCovar = StatUtils::MakeDiagonalCovarMatrix(fDataHist); covar = StatUtils::GetInvert(fFullCovar); eventVariables = NULL; - QLOG(SAM, "Smearceptance Flux Scaling Factor = " << fScaleFactor); + NUIS_LOG(SAM, "Smearceptance Flux Scaling Factor = " << fScaleFactor); if (fScaleFactor <= 0.0) { - QERROR(WRN, "SCALE FACTOR TOO LOW "); + NUIS_ERR(WRN, "SCALE FACTOR TOO LOW "); sleep(20); } // Setup our TTrees AddEventVariablesToTree(); smearceptor = &Smearcepterton::Get().GetSmearcepter(smearceptorName); Int_t RecNBins = 20, TrueNBins = 20; double RecBinL = 0xdeadbeef, TrueBinL = 0, RecBinH = 10, TrueBinH = 10; if (Config::HasPar("smear.reconstructed.binning")) { std::vector args = GeneralUtils::ParseToStr( Config::GetParS("smear.reconstructed.binning"), ","); RecNBins = GeneralUtils::StrToInt(args[0]); RecBinL = GeneralUtils::StrToDbl(args[1]); RecBinH = GeneralUtils::StrToDbl(args[2]); TrueNBins = RecNBins; TrueBinL = RecBinL; TrueBinH = RecBinH; } if (Config::HasPar("smear.true.binning")) { std::vector args = GeneralUtils::ParseToStr(Config::GetParS("smear.true.binning"), ","); TrueNBins = GeneralUtils::StrToInt(args[0]); TrueBinL = GeneralUtils::StrToDbl(args[1]); TrueBinH = GeneralUtils::StrToDbl(args[2]); } SVDTruncation = 0; if (Config::HasPar("smear.SVD.truncation")) { SVDTruncation = Config::GetParI("smear.SVD.truncation"); - QLOG(SAM, "Applying SVD truncation of: " << SVDTruncation) + NUIS_LOG(SAM, "Applying SVD truncation of: " << SVDTruncation) } ETrueDistrib = NULL; ETrueDistrib_noweight = NULL; ERecDistrib = NULL; RecoSmear = NULL; if (RecBinL != 0xdeadbeef) { - QLOG(SAM, "Using binning True: " << TrueNBins << ", [" << TrueBinL << " -- " + NUIS_LOG(SAM, "Using binning True: " << TrueNBins << ", [" << TrueBinL << " -- " << TrueBinH << "], Rec: " << RecNBins << ", [" << RecBinL << " -- " << RecBinH << "]"); ETrueDistrib = new TH1D("ELep_rate", ";True E_{#nu};Count", TrueNBins, TrueBinL, TrueBinH); ETrueDistrib_noweight = new TH1D("ELep_rate_noweight", ";True E_{#nu};Count", TrueNBins, TrueBinL, TrueBinH); ERecDistrib = new TH1D("ELepRec_rate", ";Rec E_{#nu};Count", RecNBins, RecBinL, RecBinH); ETrueDistrib->Sumw2(); ERecDistrib->Sumw2(); RecoSmear = new TH2D("ELepHadVis_Recon", ";True E_{#nu};Recon. E_{#nu}", RecNBins, RecBinL, RecBinH, TrueNBins, TrueBinL, TrueBinH); RecoSmear->Sumw2(); } // Final setup --------------------------------------------------- FinaliseMeasurement(); } void Smearceptance_Tester::AddEventVariablesToTree() { if (OutputSummaryTree) { // Setup the TTree to save everything if (!eventVariables) { Config::Get().out->cd(); eventVariables = new TTree((fName + "_VARS").c_str(), (fName + "_VARS").c_str()); } - QLOG(SAM, "Adding Event Variables"); + NUIS_LOG(SAM, "Adding Event Variables"); eventVariables->Branch("Omega_true", &Omega_true, "Omega_true/F"); eventVariables->Branch("Q2_true", &Q2_true, "Q2_true/F"); eventVariables->Branch("Mode_true", &Mode_true, "Mode_true/I"); eventVariables->Branch("EISLep_true", &EISLep_true, "EISLep_true/F"); eventVariables->Branch("HMFS_clep_true", &HMFS_clep_true); eventVariables->Branch("HMFS_pip_true", &HMFS_pip_true); eventVariables->Branch("HMFS_pim_true", &HMFS_pim_true); eventVariables->Branch("HMFS_cpi_true", &HMFS_cpi_true); eventVariables->Branch("HMFS_pi0_true", &HMFS_pi0_true); eventVariables->Branch("HMFS_cK_true", &HMFS_cK_true); eventVariables->Branch("HMFS_K0_true", &HMFS_K0_true); eventVariables->Branch("HMFS_p_true", &HMFS_p_true); eventVariables->Branch("KEFSHad_cpip_true", &KEFSHad_cpip_true, "KEFSHad_cpip_true/F"); eventVariables->Branch("KEFSHad_cpim_true", &KEFSHad_cpim_true, "KEFSHad_cpim_true/F"); eventVariables->Branch("KEFSHad_cpi_true", &KEFSHad_cpi_true, "KEFSHad_cpi_true/F"); eventVariables->Branch("TEFSHad_pi0_true", &TEFSHad_pi0_true, "TEFSHad_pi0_true/F"); eventVariables->Branch("KEFSHad_cK_true", &KEFSHad_cK_true, "KEFSHad_cK_true/F"); eventVariables->Branch("KEFSHad_K0_true", &KEFSHad_K0_true, "KEFSHad_K0_true/F"); eventVariables->Branch("KEFSHad_p_true", &KEFSHad_p_true, "KEFSHad_p_true/F"); eventVariables->Branch("KEFSHad_n_true", &KEFSHad_n_true, "KEFSHad_n_true/F"); eventVariables->Branch("EFSHad_true", &EFSHad_true, "EFSHad_true/F"); eventVariables->Branch("EFSChargedEMHad_true", &EFSChargedEMHad_true, "EFSChargedEMHad_true/F"); eventVariables->Branch("EFSLep_true", &EFSLep_true, "EFSLep_true/F"); eventVariables->Branch("EFSgamma_true", &EFSgamma_true, "EFSgamma_true/F"); eventVariables->Branch("PDGISLep_true", &PDGISLep_true, "PDGISLep_true/I"); eventVariables->Branch("PDGFSLep_true", &PDGFSLep_true, "PDGFSLep_true/I"); eventVariables->Branch("Nprotons_true", &Nprotons_true, "Nprotons_true/I"); eventVariables->Branch("Nneutrons_true", &Nneutrons_true, "Nneutrons_true/I"); eventVariables->Branch("Ncpiplus_true", &Ncpiplus_true, "Ncpiplus_true/I"); eventVariables->Branch("Ncpiminus_true", &Ncpiminus_true, "Ncpiminus_true/I"); eventVariables->Branch("Ncpi_true", &Ncpi_true, "Ncpi_true/I"); eventVariables->Branch("Npi0_true", &Npi0_true, "Npi0_true/I"); eventVariables->Branch("NcK_true", &NcK_true, "NcK_true/I"); eventVariables->Branch("NK0_true", &NK0_true, "NK0_true/I"); eventVariables->Branch("HMFS_clep_rec", &HMFS_clep_rec); eventVariables->Branch("HMFS_pip_rec", &HMFS_pip_rec); eventVariables->Branch("HMFS_pim_rec", &HMFS_pim_rec); eventVariables->Branch("HMFS_cpi_rec", &HMFS_cpi_rec); eventVariables->Branch("HMFS_pi0_rec", &HMFS_pi0_rec); eventVariables->Branch("HMFS_cK_rec", &HMFS_cK_rec); eventVariables->Branch("HMFS_K0_rec", &HMFS_K0_rec); eventVariables->Branch("HMFS_p_rec", &HMFS_p_rec); eventVariables->Branch("KEFSHad_cpip_rec", &KEFSHad_cpip_rec, "KEFSHad_cpip_rec/F"); eventVariables->Branch("KEFSHad_cpim_rec", &KEFSHad_cpim_rec, "KEFSHad_cpim_rec/F"); eventVariables->Branch("KEFSHad_cpi_rec", &KEFSHad_cpi_rec, "KEFSHad_cpi_rec/F"); eventVariables->Branch("TEFSHad_pi0_rec", &TEFSHad_pi0_rec, "TEFSHad_pi0_rec/F"); eventVariables->Branch("KEFSHad_cK_rec", &KEFSHad_cK_rec, "KEFSHad_cK_rec/F"); eventVariables->Branch("KEFSHad_K0_rec", &KEFSHad_K0_rec, "KEFSHad_K0_rec/F"); eventVariables->Branch("KEFSHad_p_rec", &KEFSHad_p_rec, "KEFSHad_p_rec/F"); eventVariables->Branch("KEFSHad_n_rec", &KEFSHad_n_rec, "KEFSHad_n_rec/F"); eventVariables->Branch("EFSHad_rec", &EFSHad_rec, "EFSHad_rec/F"); eventVariables->Branch("EFSLep_rec", &EFSLep_rec, "EFSLep_rec/F"); eventVariables->Branch("EFSVis_cpip", &EFSVis_cpip, "EFSVis_cpip/F"); eventVariables->Branch("EFSVis_cpim", &EFSVis_cpim, "EFSVis_cpim/F"); eventVariables->Branch("EFSVis_cpi", &EFSVis_cpi, "EFSVis_cpi/F"); eventVariables->Branch("EFSVis_pi0", &EFSVis_pi0, "EFSVis_pi0/F"); eventVariables->Branch("EFSVis_cK", &EFSVis_cK, "EFSVis_cK/F"); eventVariables->Branch("EFSVis_K0", &EFSVis_K0, "EFSVis_K0/F"); eventVariables->Branch("EFSVis_p", &EFSVis_p, "EFSVis_p/F"); eventVariables->Branch("EFSVis_n", &EFSVis_n, "EFSVis_n/F"); eventVariables->Branch("EFSVis_gamma", &EFSVis_gamma, "EFSVis_gamma/F"); eventVariables->Branch("EFSVis_other", &EFSVis_other, "EFSVis_other/F"); eventVariables->Branch("EFSVis", &EFSVis, "EFSVis/F"); eventVariables->Branch("FSCLep_seen", &FSCLep_seen, "FSCLep_seen/I"); eventVariables->Branch("Nprotons_seen", &Nprotons_seen, "Nprotons_seen/I"); eventVariables->Branch("Nneutrons_seen", &Nneutrons_seen, "Nneutrons_seen/I"); eventVariables->Branch("Ncpip_seen", &Ncpip_seen, "Ncpip_seen/I"); eventVariables->Branch("Ncpim_seen", &Ncpim_seen, "Ncpim_seen/I"); eventVariables->Branch("Ncpi_seen", &Ncpi_seen, "Ncpi_seen/I"); eventVariables->Branch("Npi0_seen", &Npi0_seen, "Npi0_seen/I"); eventVariables->Branch("NcK_seen", &NcK_seen, "NcK_seen/I"); eventVariables->Branch("NK0_seen", &NK0_seen, "NK0_seen/I"); eventVariables->Branch("Nothers_seen", &Nothers_seen, "Nothers_seen/I"); eventVariables->Branch("EISLep_QE_rec", &EISLep_QE_rec, "EISLep_QE_rec/F"); eventVariables->Branch("EISLep_LepHad_rec", &EISLep_LepHad_rec, "EISLep_LepHad_rec/F"); eventVariables->Branch("EISLep_LepHadVis_rec", &EISLep_LepHadVis_rec, "EISLep_LepHadVis_rec/F"); eventVariables->Branch("Nprotons_contributed", &Nprotons_contributed, "Nprotons_contributed/I"); eventVariables->Branch("Nneutrons_contributed", &Nneutrons_contributed, "Nneutrons_contributed/I"); eventVariables->Branch("Ncpip_contributed", &Ncpip_contributed, "Ncpip_contributed/I"); eventVariables->Branch("Ncpim_contributed", &Ncpim_contributed, "Ncpim_contributed/I"); eventVariables->Branch("Ncpi_contributed", &Ncpi_contributed, "Ncpi_contributed/I"); eventVariables->Branch("Npi0_contributed", &Npi0_contributed, "Npi0_contributed/I"); eventVariables->Branch("NcK_contributed", &NcK_contributed, "NcK_contributed/I"); eventVariables->Branch("NK0_contributed", &NK0_contributed, "NK0_contributed/I"); eventVariables->Branch("Ngamma_contributed", &Ngamma_contributed, "Ngamma_contributed/I"); eventVariables->Branch("Nothers_contibuted", &Nothers_contibuted, "Nothers_contibuted/I"); eventVariables->Branch("Weight", &Weight, "Weight/F"); eventVariables->Branch("RWWeight", &RWWeight, "RWWeight/F"); eventVariables->Branch("InputWeight", &InputWeight, "InputWeight/F"); eventVariables->Branch("FluxWeight", &FluxWeight, "FluxWeight/F"); eventVariables->Branch("EffWeight", &EffWeight, "EffWeight/F"); xsecScaling = fScaleFactor; eventVariables->Branch("xsecScaling", &xsecScaling, "xsecScaling/F"); eventVariables->Branch("flagCCINC_true", &flagCCINC_true, "flagCCINC_true/O"); eventVariables->Branch("flagCC0K_true", &flagCC0K_true, "flagCC0K_true/O"); eventVariables->Branch("flagCC0Pi_true", &flagCC0Pi_true, "flagCC0Pi_true/O"); eventVariables->Branch("flagCC1Pi_true", &flagCC1Pi_true, "flagCC1Pi_true/O"); eventVariables->Branch("flagCCINC_rec", &flagCCINC_rec, "flagCCINC_rec/O"); eventVariables->Branch("flagCC0K_rec", &flagCC0K_rec, "flagCC0K_rec/O"); eventVariables->Branch("flagCC0Pi_rec", &flagCC0Pi_rec, "flagCC0Pi_rec/O"); eventVariables->Branch("flagCC1Pi_rec", &flagCC1Pi_rec, "flagCC1Pi_rec/O"); } PredEvtRateWeight = 1; if (fEvtRateScaleFactor != 0xdeadbeef) { if (OutputSummaryTree) { eventVariables->Branch("PredEvtRateWeight", &PredEvtRateWeight, "PredEvtRateWeight/F"); } PredEvtRateWeight = fScaleFactor * fEvtRateScaleFactor; } } template int CountNPdgsSeen(RecoInfo ri, int const (&pdgs)[N]) { int sum = 0; for (size_t pdg_it = 0; pdg_it < N; ++pdg_it) { sum += std::count(ri.RecObjClass.begin(), ri.RecObjClass.end(), pdgs[pdg_it]); } return sum; } template int CountNNotPdgsSeen(RecoInfo ri, int const (&pdgs)[N]) { int sum = 0; for (size_t p_it = 0; p_it < ri.RecObjClass.size(); ++p_it) { if (!std::count(pdgs, pdgs + N, ri.RecObjClass[p_it])) { sum++; } } return sum; } template int CountNPdgsContributed(RecoInfo ri, int const (&pdgs)[N]) { int sum = 0; for (size_t pdg_it = 0; pdg_it < N; ++pdg_it) { sum += std::count(ri.TrueContribPDGs.begin(), ri.TrueContribPDGs.end(), pdgs[pdg_it]); } return sum; } template int CountNNotPdgsContributed(RecoInfo ri, int const (&pdgs)[N]) { int sum = 0; for (size_t p_it = 0; p_it < ri.TrueContribPDGs.size(); ++p_it) { if (!std::count(pdgs, pdgs + N, ri.TrueContribPDGs[p_it])) { sum++; } } return sum; } TLorentzVector GetHMFSRecParticles(RecoInfo ri, int pdg) { TLorentzVector mom(0, 0, 0, 0); for (size_t p_it = 0; p_it < ri.RecObjMom.size(); ++p_it) { if ((ri.RecObjClass[p_it] == pdg) && (mom.Mag() < ri.RecObjMom[p_it].Mag())) { mom.SetXYZM(ri.RecObjMom[p_it].X(), ri.RecObjMom[p_it].Y(), ri.RecObjMom[p_it].Z(), PhysConst::GetMass(ri.RecObjClass[p_it]) * 1.0E3); } } return mom; } template double SumKE_RecoInfo(RecoInfo ri, int const (&pdgs)[N], double mass) { double sum = 0; for (size_t p_it = 0; p_it < ri.RecObjMom.size(); ++p_it) { if (!std::count(pdgs, pdgs + N, ri.RecObjClass[p_it])) { // If we don't care about this // particle type. continue; } sum += sqrt(ri.RecObjMom[p_it].Mag2() + mass * mass) - mass; } return sum; } template double SumTE_RecoInfo(RecoInfo ri, int const (&pdgs)[N], double mass) { double sum = 0; for (size_t p_it = 0; p_it < ri.RecObjMom.size(); ++p_it) { if (!std::count(pdgs, pdgs + N, ri.RecObjClass[p_it])) { // If we don't care about this // particle type. continue; } sum += sqrt(ri.RecObjMom[p_it].Mag2() + mass * mass); } return sum; } template double SumVisE_RecoInfo(RecoInfo ri, int const (&pdgs)[N]) { double sum = 0; for (size_t p_it = 0; p_it < ri.RecVisibleEnergy.size(); ++p_it) { if (!std::count(pdgs, pdgs + N, ri.TrueContribPDGs[p_it])) { // If we don't care about this // particle type. continue; } sum += ri.RecVisibleEnergy[p_it]; } return sum; } template double SumVisE_RecoInfo_NotPdgs(RecoInfo ri, int const (&pdgs)[N]) { double sum = 0; for (size_t p_it = 0; p_it < ri.RecVisibleEnergy.size(); ++p_it) { if (std::count(pdgs, pdgs + N, ri.TrueContribPDGs[p_it])) { // If we know about this // particle type. continue; } sum += ri.RecVisibleEnergy[p_it]; } return sum; } //******************************************************************** void Smearceptance_Tester::FillEventVariables(FitEvent *event) { //******************************************************************** static int const cpipPDG[] = {211}; static int const cpimPDG[] = {-211}; static int const pi0PDG[] = {111}; static int const cKPDG[] = {321, -321}; static int const K0PDG[] = {311, 310, 130}; static int const ProtonPDG[] = {2212}; static int const NeutronPDG[] = {2112}; static int const GammaPDG[] = {22}; static int const CLeptonPDGs[] = {11, 13, 15, -11, -13, -15}; static int const ExplicitPDGs[] = {211, -211, 111, 321, -321, 311, 310, 130, 2212, 2112, 22, 11, 13, 15, 12, 14, 16, -11, -13, -15, -12, -14, -16}; RecoInfo *ri = smearceptor->Smearcept(event); //** START Pions HMFS_clep_true = TLorentzVector(0, 0, 0, 0); HMFS_clep_rec = TLorentzVector(0, 0, 0, 0); FitParticle *fsCLep = event->GetHMFSParticle(CLeptonPDGs); if (fsCLep) { HMFS_clep_true = fsCLep->P4(); HMFS_clep_rec = GetHMFSRecParticles(*ri, fsCLep->PDG()); } //** END Charged leptons //** START Pions HMFS_pip_true = TLorentzVector(0, 0, 0, 0); HMFS_pip_rec = TLorentzVector(0, 0, 0, 0); FitParticle *fsPip = event->GetHMFSPiPlus(); if (fsPip) { HMFS_pip_true = fsPip->P4(); HMFS_pip_rec = GetHMFSRecParticles(*ri, fsPip->PDG()); } HMFS_pim_true = TLorentzVector(0, 0, 0, 0); HMFS_pim_rec = TLorentzVector(0, 0, 0, 0); FitParticle *fsPim = event->GetHMFSPiMinus(); if (fsPim) { HMFS_pim_true = fsPim->P4(); HMFS_pim_rec = GetHMFSRecParticles(*ri, fsPim->PDG()); } HMFS_cpi_true = TLorentzVector(0, 0, 0, 0); HMFS_cpi_rec = TLorentzVector(0, 0, 0, 0); if (fsPip || fsPim) { if (!fsPip) { HMFS_cpi_true = HMFS_pim_true; HMFS_cpi_rec = HMFS_pim_rec; } else if (!fsPim) { HMFS_cpi_true = HMFS_pip_true; HMFS_cpi_rec = HMFS_pip_rec; } else { HMFS_cpi_true = (fsPip->p2() > fsPim->p2()) ? HMFS_pip_true : HMFS_pim_true; HMFS_cpi_rec = (fsPip->p2() > fsPim->p2()) ? HMFS_pip_rec : HMFS_pim_rec; } } HMFS_pi0_true = TLorentzVector(0, 0, 0, 0); HMFS_pi0_rec = TLorentzVector(0, 0, 0, 0); FitParticle *fsPi0 = event->GetHMFSPiZero(); if (fsPi0) { HMFS_pi0_true = fsPi0->P4(); HMFS_pi0_rec = GetHMFSRecParticles(*ri, fsPi0->PDG()); } //** END Pions //** START Kaons HMFS_cK_true = TLorentzVector(0, 0, 0, 0); HMFS_cK_rec = TLorentzVector(0, 0, 0, 0); FitParticle *fscK = event->GetHMFSParticle(cKPDG); if (fscK) { HMFS_cK_true = fscK->P4(); HMFS_cK_rec = GetHMFSRecParticles(*ri, fscK->PDG()); } HMFS_K0_true = TLorentzVector(0, 0, 0, 0); HMFS_K0_rec = TLorentzVector(0, 0, 0, 0); FitParticle *fsK0 = event->GetHMFSParticle(K0PDG); if (fsK0) { HMFS_K0_true = fsK0->P4(); HMFS_K0_rec = GetHMFSRecParticles(*ri, fsK0->PDG()); } //** END Kaons //** START Nucleons HMFS_p_true = TLorentzVector(0, 0, 0, 0); HMFS_p_rec = TLorentzVector(0, 0, 0, 0); FitParticle *fsP = event->GetHMFSProton(); if (fsP) { HMFS_p_true = fsP->P4(); HMFS_p_rec = GetHMFSRecParticles(*ri, fsP->PDG()); } TLorentzVector FourMomentumTransfer = (event->GetHMISAnyLeptons()->P4() - event->GetHMFSAnyLeptons()->P4()); Omega_true = FourMomentumTransfer.E(); Q2_true = -1 * FourMomentumTransfer.Mag2(); Mode_true = event->Mode; EISLep_true = event->GetHMISAnyLeptons()->E(); KEFSHad_cpip_true = FitUtils::SumTE_PartVect(event->GetAllFSPiPlus()); KEFSHad_cpim_true = FitUtils::SumTE_PartVect(event->GetAllFSPiMinus()); KEFSHad_cpi_true = KEFSHad_cpip_true + KEFSHad_cpim_true; TEFSHad_pi0_true = FitUtils::SumTE_PartVect(event->GetAllFSPiZero()); KEFSHad_cK_true = FitUtils::SumTE_PartVect(event->GetAllFSParticle(cKPDG)); KEFSHad_K0_true = FitUtils::SumTE_PartVect(event->GetAllFSParticle(K0PDG)); KEFSHad_p_true = FitUtils::SumKE_PartVect(event->GetAllFSProton()); KEFSHad_n_true = FitUtils::SumKE_PartVect(event->GetAllFSNeutron()); EFSHad_true = KEFSHad_cpi_true + TEFSHad_pi0_true + KEFSHad_p_true + KEFSHad_n_true; EFSChargedEMHad_true = KEFSHad_cpi_true + TEFSHad_pi0_true + KEFSHad_p_true + KEFSHad_cK_true + KEFSHad_K0_true; EFSLep_true = event->GetHMFSAnyLeptons()->E(); EFSgamma_true = FitUtils::SumTE_PartVect(event->GetAllFSPhoton()); PDGISLep_true = event->GetHMISAnyLeptons()->PDG(); PDGFSLep_true = event->GetHMFSAnyLeptons()->PDG(); Nprotons_true = event->GetAllFSProton().size(); Nneutrons_true = event->GetAllFSNeutron().size(); Ncpiplus_true = event->GetAllFSPiPlus().size(); Ncpiminus_true = event->GetAllFSPiMinus().size(); Ncpi_true = Ncpiplus_true + Ncpiminus_true; Npi0_true = event->GetAllFSPiZero().size(); NcK_true = event->GetAllFSParticle(cKPDG).size(); NK0_true = event->GetAllFSParticle(K0PDG).size(); KEFSHad_cpip_rec = SumKE_RecoInfo(*ri, cpipPDG, PhysConst::mass_cpi * PhysConst::mass_MeV); KEFSHad_cpim_rec = SumKE_RecoInfo(*ri, cpimPDG, PhysConst::mass_cpi * PhysConst::mass_MeV); KEFSHad_cpi_rec = KEFSHad_cpip_rec + KEFSHad_cpim_rec; TEFSHad_pi0_rec = SumTE_RecoInfo(*ri, pi0PDG, PhysConst::mass_pi0 * PhysConst::mass_MeV); KEFSHad_cK_rec = SumKE_RecoInfo(*ri, cKPDG, PhysConst::mass_cK * PhysConst::mass_MeV); KEFSHad_K0_rec = SumKE_RecoInfo(*ri, K0PDG, PhysConst::mass_K0 * PhysConst::mass_MeV); KEFSHad_p_rec = SumKE_RecoInfo(*ri, ProtonPDG, PhysConst::mass_proton * PhysConst::mass_MeV); KEFSHad_n_rec = SumKE_RecoInfo(*ri, NeutronPDG, PhysConst::mass_neutron * PhysConst::mass_MeV); EFSHad_rec = KEFSHad_cpi_rec + TEFSHad_pi0_rec + KEFSHad_p_rec + KEFSHad_n_rec; TLorentzVector FSLepMom_rec(0, 0, 0, 0); if (event->GetHMFSAnyLeptons()) { FSLepMom_rec = GetHMFSRecParticles(*ri, event->GetHMFSAnyLeptons()->PDG()); EFSLep_rec = FSLepMom_rec.E(); } else { EFSLep_rec = 0; } EFSVis_cpip = SumVisE_RecoInfo(*ri, cpipPDG); EFSVis_cpim = SumVisE_RecoInfo(*ri, cpimPDG); EFSVis_cpi = EFSVis_cpip + EFSVis_cpim; EFSVis_pi0 = SumVisE_RecoInfo(*ri, pi0PDG); EFSVis_cK = SumVisE_RecoInfo(*ri, cKPDG); EFSVis_K0 = SumVisE_RecoInfo(*ri, K0PDG); EFSVis_p = SumVisE_RecoInfo(*ri, ProtonPDG); EFSVis_n = SumVisE_RecoInfo(*ri, NeutronPDG); EFSVis_gamma = SumVisE_RecoInfo(*ri, GammaPDG); EFSVis_other = SumVisE_RecoInfo_NotPdgs(*ri, ExplicitPDGs); EFSVis = EFSVis_cpi + EFSVis_pi0 + EFSVis_p + EFSVis_n + EFSVis_gamma + EFSVis_cK + EFSVis_K0; FSCLep_seen = CountNPdgsSeen(*ri, CLeptonPDGs); Nprotons_seen = CountNPdgsSeen(*ri, ProtonPDG); Nneutrons_seen = CountNPdgsSeen(*ri, NeutronPDG); Ncpip_seen = CountNPdgsSeen(*ri, cpipPDG); Ncpim_seen = CountNPdgsSeen(*ri, cpimPDG); Ncpi_seen = Ncpip_seen + Ncpim_seen; Npi0_seen = CountNPdgsSeen(*ri, pi0PDG); NcK_seen = CountNPdgsSeen(*ri, cKPDG); NK0_seen = CountNPdgsSeen(*ri, K0PDG); Nothers_seen = CountNNotPdgsSeen(*ri, ExplicitPDGs); if (FSCLep_seen && (FSLepMom_rec.Mag() > 1E-8)) { EISLep_QE_rec = FitUtils::EnuQErec(FSLepMom_rec.Mag() / 1000.0, FSLepMom_rec.CosTheta(), 34, PDGFSLep_true > 0) * 1000.0; } else { EISLep_QE_rec = 0; } EISLep_LepHad_rec = EFSLep_rec + EFSHad_rec; EISLep_LepHadVis_rec = EFSLep_rec + EFSHad_rec + EFSVis; Nprotons_contributed = CountNPdgsContributed(*ri, ProtonPDG); Nneutrons_contributed = CountNPdgsContributed(*ri, NeutronPDG); Ncpip_contributed = CountNPdgsContributed(*ri, cpipPDG); Ncpim_contributed = CountNPdgsContributed(*ri, cpimPDG); Ncpi_contributed = Ncpip_contributed + Ncpim_contributed; Npi0_contributed = CountNPdgsContributed(*ri, pi0PDG); NcK_contributed = CountNPdgsContributed(*ri, cKPDG); NK0_contributed = CountNPdgsContributed(*ri, K0PDG); Ngamma_contributed = CountNPdgsContributed(*ri, GammaPDG); Nothers_contibuted = CountNNotPdgsContributed(*ri, ExplicitPDGs); Weight = event->RWWeight * event->InputWeight; RWWeight = event->RWWeight; InputWeight = event->InputWeight; FluxWeight = GetFluxHistogram()->GetBinContent( GetFluxHistogram()->FindBin(EISLep_true)) / GetFluxHistogram()->Integral(); EffWeight = ri->Weight; flagCCINC_true = PDGFSLep_true & 1; flagCC0K_true = (NcK_true + NK0_true) == 0; flagCC0Pi_true = flagCCINC_true && flagCC0K_true && ((Ncpi_true + Npi0_true) == 0); flagCC1Pi_true = flagCCINC_true && flagCC0K_true && ((Ncpi_true + Npi0_true) == 1); flagCCINC_rec = FSCLep_seen && flagCCINC_true; flagCC0K_rec = (NcK_seen + NK0_seen) == 0; flagCC0Pi_rec = flagCCINC_rec && flagCC0K_rec && ((Ncpi_seen + Npi0_seen) == 0); flagCC1Pi_rec = flagCCINC_rec && flagCC0K_rec && ((Ncpi_seen + Npi0_seen) == 1); if (OutputSummaryTree) { // Fill the eventVariables Tree eventVariables->Fill(); } if (RecoSmear) { RecoSmear->Fill(EISLep_true / 1000.0, flagCCINC_rec ? EISLep_LepHadVis_rec / 1000.0 : -1, Weight); ETrueDistrib_noweight->Fill(EISLep_true / 1000.0, flagCCINC_true ? Weight : 0); ETrueDistrib->Fill(EISLep_true / 1000.0, flagCCINC_true ? Weight * PredEvtRateWeight : 0); ERecDistrib->Fill(EISLep_LepHadVis_rec / 1000.0, flagCCINC_rec ? Weight * PredEvtRateWeight : 0); } }; //******************************************************************** void Smearceptance_Tester::Write(std::string drawOpt) { //******************************************************************** if (OutputSummaryTree) { // First save the TTree eventVariables->Write(); } // Save Flux and Event Histograms too GetInput()->GetFluxHistogram()->Write(); GetInput()->GetEventHistogram()->Write(); if (!RecoSmear) { return; } TH2D *SmearMatrix_ev = static_cast(RecoSmear->Clone("ELepHadVis_Smear_ev")); for (Int_t trueAxis_it = 1; trueAxis_it < RecoSmear->GetXaxis()->GetNbins() + 1; ++trueAxis_it) { double NEISLep = ETrueDistrib_noweight->GetBinContent(trueAxis_it); for (Int_t recoAxis_it = 1; recoAxis_it < RecoSmear->GetYaxis()->GetNbins() + 1; ++recoAxis_it) { if (NEISLep > std::numeric_limits::epsilon()) { SmearMatrix_ev->SetBinContent( trueAxis_it, recoAxis_it, SmearMatrix_ev->GetBinContent(trueAxis_it, recoAxis_it) / NEISLep); } } } ETrueDistrib_noweight->Write(); ETrueDistrib->Write(); ERecDistrib->Write(); RecoSmear->Write(); SmearMatrix_ev->Write(); TH2D *ResponseMatrix_ev = SmearceptanceUtils::SVDGetInverse(SmearMatrix_ev, SVDTruncation); ResponseMatrix_ev->SetName("ResponseMatrix_ev"); ResponseMatrix_ev->Write(); #ifdef DEBUG_SMEARTESTER TMatrixD SmearMatrix_ev_md = SmearceptanceUtils::GetMatrix(SmearMatrix_ev); TH1D *SmearedEvt = static_cast(ERecDistrib->Clone()); SmearedEvt->SetNameTitle("SmearedEvt", ";Rec E_{#nu}; count"); SmearceptanceUtils::PushTH1ThroughMatrixWithErrors( ETrueDistrib, SmearedEvt, SmearMatrix_ev_md, 5000, false); SmearedEvt->Write(); SmearedEvt->Scale(1, "width"); SmearedEvt->SetName("SmearedEvt_bw"); SmearedEvt->Write(); #endif #ifdef __PROB3PP_ENABLED__ FitWeight *fw = FitBase::GetRW(); if (fw->HasRWEngine(kOSCILLATION)) { OscWeightEngine *oscWE = dynamic_cast(fw->GetRWEngine(kOSCILLATION)); TGraph POsc; POsc.Set(1E4 - 1); double min = ETrueDistrib->GetXaxis()->GetBinLowEdge(1); double step = (ETrueDistrib->GetXaxis()->GetBinUpEdge( ETrueDistrib->GetXaxis()->GetNbins()) - ETrueDistrib->GetXaxis()->GetBinLowEdge(1)) / double(1E4); for (size_t i = 1; i < 1E4; ++i) { double enu = min + i * step; double ow = oscWE->CalcWeight(enu, 14); if (ow != ow) { std::cout << "Bad osc weight for ENu: " << enu << std::endl; } POsc.SetPoint(i - 1, enu, ow); } POsc.Write("POsc", TObject::kOverwrite); } #endif TMatrixD ResponseMatrix_evt_md = SmearceptanceUtils::GetMatrix(ResponseMatrix_ev); TH1D *Unfolded_enu_obs = static_cast(ETrueDistrib->Clone()); Unfolded_enu_obs->SetNameTitle("UnfoldedENu_evt", ";True E_{#nu};count"); SmearceptanceUtils::PushTH1ThroughMatrixWithErrors( ERecDistrib, Unfolded_enu_obs, ResponseMatrix_evt_md, 5000, false); Unfolded_enu_obs->Write(); Unfolded_enu_obs->Scale(1, "width"); Unfolded_enu_obs->SetName("UnfoldedENu_evt_bw"); Unfolded_enu_obs->Write(); ETrueDistrib->Scale(1, "width"); ETrueDistrib->SetName("ELep_rate_bw"); ETrueDistrib->Write(); ERecDistrib->Scale(1, "width"); ERecDistrib->SetName("ELepRec_rate_bw"); ERecDistrib->Write(); } // ------------------------------------------------------------------- // Purely MC Plot // Following functions are just overrides to handle this // ------------------------------------------------------------------- //******************************************************************** /// Everything is classed as signal... bool Smearceptance_Tester::isSignal(FitEvent *event) { //******************************************************************** (void)event; return true; }; //******************************************************************** void Smearceptance_Tester::ScaleEvents() { //******************************************************************** // Saving everything to a TTree so no scaling required return; } //******************************************************************** void Smearceptance_Tester::ApplyNormScale(float norm) { //******************************************************************** // Saving everything to a TTree so no scaling required fCurrentNorm = norm; return; } //******************************************************************** void Smearceptance_Tester::FillHistograms() { //******************************************************************** // No Histograms need filling........ return; } //******************************************************************** void Smearceptance_Tester::ResetAll() { //******************************************************************** if (OutputSummaryTree) { eventVariables->Reset(); } return; } //******************************************************************** float Smearceptance_Tester::GetChi2() { //******************************************************************** // No Likelihood to test, purely MC return 0.0; } diff --git a/src/MINERvA/MINERvA_CC0pi_XSec_1DQ2_TgtRatio_nu.cxx b/src/MINERvA/MINERvA_CC0pi_XSec_1DQ2_TgtRatio_nu.cxx index d4fdd48..d37fce6 100644 --- a/src/MINERvA/MINERvA_CC0pi_XSec_1DQ2_TgtRatio_nu.cxx +++ b/src/MINERvA/MINERvA_CC0pi_XSec_1DQ2_TgtRatio_nu.cxx @@ -1,149 +1,149 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_CC0pi_XSec_1DQ2_TgtRatio_nu.h" #include "MINERvA_SignalDef.h" //******************************************************************** MINERvA_CC0pi_XSec_1DQ2_TgtRatio_nu::MINERvA_CC0pi_XSec_1DQ2_TgtRatio_nu( nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "MINERvA_CC0pi_XSec_1DQ2_TgtRatio_nu sample. \n" "Target: Target;CH (2 INPUTS)\n" "Flux: MINERvA Forward Horn Current Numu \n" "Signal: Any event with 1 muon, 1 proton p>450, no pions"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("Q^{2}_{QE} (GeV^{2})"); fSettings.SetYTitle(" d#sigma/dQ^{2}_{QE} (cm^{2}/GeV^{2}/nucleon)"); fSettings.SetAllowedTypes("FIX/DIAG,FULL/MASK", "FIX/FULL"); fSettings.SetEnuRange(0.0, 100.0); // CCQELike plot information fSettings.SetTitle("MINERvA_CC0pi_XSec_1DQ2_TgtRatio_nu"); fIsRatio = true; nBins = 5; target = ""; if (fSettings.Found("name", "TgtRatioFe")) target = "Fe"; else if (fSettings.Found("name", "TgtRatioPb")) target = "Pb"; else if (fSettings.Found("name", "TgtRatioC")) target = "C"; else { - QTHROW("target " << target << " was not found!"); + NUIS_ABORT("target " << target << " was not found!"); } std::string basedir = FitPar::GetDataBase() + "/MINERvA/CC0pi/"; fSettings.SetDataInput(basedir + "Q2_TgtRatio_" + target + "_data.txt"); fSettings.SetCovarInput(basedir + "Q2_TgtRatio_" + target + "_covar.txt"); FinaliseSampleSettings(); // Get parsed input files if (fSubInFiles.size() != 2) { - QTHROW("MINERvA CC0pi ratio requires input files in format: " + NUIS_ABORT("MINERvA CC0pi ratio requires input files in format: " "NUMERATOR;DENOMINATOR"); } std::string inFileNUM = fSubInFiles.at(0); std::string inFileDEN = fSubInFiles.at(1); // Scaling Setup --------------------------------------------------- // Ratio of sub classes so non needed // Plot Setup ------------------------------------------------------- SetDataFromTextFile(fSettings.GetDataInput()); SetCorrelationFromTextFile(fSettings.GetCovarInput()); // Setup Experiments ------------------------------------------------------- std::string type = samplekey.GetS("type"); nuiskey samplekey_num = nuiskey("sample"); samplekey_num.Set("name", "MINERvA_CC0pi_XSec_1DQ2_Tgt" + target + "_nu"); samplekey_num.Set("input", inFileNUM); samplekey_num.Set("type", type); nuiskey samplekey_den = nuiskey("sample"); samplekey_den.Set("name", "MINERvA_CC0pi_XSec_1DQ2_TgtCH_nu"); samplekey_den.Set("input", inFileDEN); samplekey_den.Set("type", type); NUM = new MINERvA_CC0pi_XSec_1DQ2_Tgt_nu(samplekey_num); DEN = new MINERvA_CC0pi_XSec_1DQ2_Tgt_nu(samplekey_den); NUM->SetNoData(); DEN->SetNoData(); // Add to chain for processing this->fSubChain.clear(); this->fSubChain.push_back(NUM); this->fSubChain.push_back(DEN); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CC0pi_XSec_1DQ2_TgtRatio_nu::MakePlots() { //******************************************************************** UInt_t sample = 0; for (std::vector::const_iterator expIter = this->fSubChain.begin(); expIter != this->fSubChain.end(); expIter++) { MeasurementBase *exp = static_cast(*expIter); if (sample == 0) this->NUM = static_cast(exp); else if (sample == 1) this->DEN = static_cast(exp); else break; sample++; } // Now make the ratio histogram TH1D *NUM_MC = (TH1D *)this->NUM->GetMCList().at(0)->Clone(); TH1D *DEN_MC = (TH1D *)this->DEN->GetMCList().at(0)->Clone(); for (int i = 0; i < nBins; ++i) { double binVal = 0; double binErr = 0; if (DEN_MC->GetBinContent(i + 1) && NUM_MC->GetBinContent(i + 1)) { binVal = NUM_MC->GetBinContent(i + 1) / DEN_MC->GetBinContent(i + 1); double fractErrNUM = NUM_MC->GetBinError(i + 1) / NUM_MC->GetBinContent(i + 1); double fractErrDEN = DEN_MC->GetBinError(i + 1) / DEN_MC->GetBinContent(i + 1); binErr = binVal * sqrt(fractErrNUM * fractErrNUM + fractErrDEN * fractErrDEN); } this->fMCHist->SetBinContent(i + 1, binVal); this->fMCHist->SetBinError(i + 1, binErr); } return; } diff --git a/src/MINERvA/MINERvA_CC0pi_XSec_1DQ2_Tgt_nu.cxx b/src/MINERvA/MINERvA_CC0pi_XSec_1DQ2_Tgt_nu.cxx index d2cc079..af840fb 100644 --- a/src/MINERvA/MINERvA_CC0pi_XSec_1DQ2_Tgt_nu.cxx +++ b/src/MINERvA/MINERvA_CC0pi_XSec_1DQ2_Tgt_nu.cxx @@ -1,138 +1,138 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include #include #include "MINERvA_SignalDef.h" #include "MINERvA_CC0pi_XSec_1DQ2_Tgt_nu.h" //******************************************************************** MINERvA_CC0pi_XSec_1DQ2_Tgt_nu::MINERvA_CC0pi_XSec_1DQ2_Tgt_nu(nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "MINERvA_CC0pi_XSec_1DQ2_Tgt_nu sample. \n" \ "Target: Either C, CH, Fe, Pb \n" \ "Flux: MINERvA Forward Horn numu \n" "Signal: Any event with 1 muon, 1 proton p>450, no pions"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("Q^{2}_{QE} (GeV^{2})"); fSettings.SetYTitle("d#sigma/dQ^{2} (cm^{2}/GeV^{2})"); fSettings.SetAllowedTypes("FIX,FREE,SHAPE/DIAG/NORM", "FIX/DIAG"); fSettings.SetEnuRange(0.0, 100.0); fSettings.DefineAllowedTargets("C,H"); // CCQELike plot information fSettings.SetTitle("MINERvA_CC0pi_XSec_1DQ2_Tgt_nu"); fSettings.DefineAllowedSpecies("numu"); // Set Target From name if (fSettings.Found("name","_CH")){ fTarget = 1; // kTargetCH; fSettings.SetDataInput( FitPar::GetDataBase() + "/MINERvA/CC0pi/Q2_Tgt_CH_data.txt"); fSettings.SetCovarInput( FitPar::GetDataBase() + "/MINERvA/CC0pi/Q2_Tgt_CH_covar.txt"); } else if (fSettings.Found("name","TgtC")){ fTarget = 2; //kTargetC; fSettings.SetDataInput( FitPar::GetDataBase() + "/MINERvA/CC0pi/Q2_Tgt_C_data.txt"); fSettings.SetCovarInput( FitPar::GetDataBase() + "/MINERvA/CC0pi/Q2_Tgt_C_covar.txt"); } else if (fSettings.Found("name","TgtFe")){ fTarget = 3; //kTargetFe; fSettings.SetDataInput( FitPar::GetDataBase() + "/MINERvA/CC0pi/Q2_Tgt_Fe_data.txt"); fSettings.SetCovarInput( FitPar::GetDataBase() + "/MINERvA/CC0pi/Q2_Tgt_Fe_covar.txt"); } else if (fSettings.Found("name","TgtPb")){ fTarget = 4; //kTargetPb; fSettings.SetDataInput( FitPar::GetDataBase() + "/MINERvA/CC0pi/Q2_Tgt_Pb_data.txt"); fSettings.SetCovarInput( FitPar::GetDataBase() + "/MINERvA/CC0pi/Q2_Tgt_Pb_covar.txt"); } else { - QTHROW("Target not found in name!"); + NUIS_ABORT("Target not found in name!"); } FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = (GetEventHistogram()->Integral("width")*1E-38/(fNEvents+0.))/TotalIntegratedFlux(); // Plot Setup ------------------------------------------------------- SetDataFromTextFile( fSettings.GetDataInput() ); if (fTarget == 1){ SetCovarFromDiagonal(fDataHist); } else { SetCorrelationFromTextFile(fSettings.GetCovarInput() ); } // Final setup --------------------------------------------------- FinaliseMeasurement(); }; void MINERvA_CC0pi_XSec_1DQ2_Tgt_nu::FillEventVariables(FitEvent *event){ // Has NuMuCC1p if (event->HasISNuMuon() && event->HasFSMuon() && event->HasFSProton()){ TLorentzVector pnu = event->GetHMISNuMuon()->fP; TLorentzVector pprot = event->GetHMFSProton()->fP; TLorentzVector pmu = event->GetHMFSMuon()->fP; // Q2QE rec from leading proton assuming 34 MeV Eb double protmax = pprot.E(); double q2qe = FitUtils::ProtonQ2QErec(protmax, 34.); // Coplanar is angle between muon and proton plane TVector3 plnprotnu = pprot.Vect().Cross(pnu.Vect()); TVector3 plnmunu = pmu.Vect().Cross(pnu.Vect()); double copl = plnprotnu.Angle(plnmunu); // Fill X Variables fXVar = q2qe; // Save Coplanar into spare y variable fYVar = copl; } return; }; bool MINERvA_CC0pi_XSec_1DQ2_Tgt_nu::isSignal(FitEvent *event){ // IS NuMu + FS Muon if (!event->HasISNuMuon()) return false; if (!event->HasFSMuon()) return false; // No Pions if (!SignalDef::isCC0pi(event, 14, EnuMin, EnuMax)) return false; // Proton Threshold if (!SignalDef::HasProtonMomAboveThreshold(event, 450.0)){ return false; } return true; }; diff --git a/src/MINERvA/MINERvA_CC0pi_XSec_1D_2018_nu.cxx b/src/MINERvA/MINERvA_CC0pi_XSec_1D_2018_nu.cxx index d6dd234..1a5ce78 100644 --- a/src/MINERvA/MINERvA_CC0pi_XSec_1D_2018_nu.cxx +++ b/src/MINERvA/MINERvA_CC0pi_XSec_1D_2018_nu.cxx @@ -1,235 +1,235 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ /* Authors: Adrian Orea (v1 2017) Clarence Wret (v2 2018) */ #include "MINERvA_CC0pi_XSec_1D_2018_nu.h" #include "MINERvA_SignalDef.h" //******************************************************************** void MINERvA_CC0pi_XSec_1D_2018_nu::SetupDataSettings() { //******************************************************************** // Set Distribution // See header file for enum and some descriptions std::string name = fSettings.GetS("name"); // Have two distributions as of summer 2018 if (!name.compare("MINERvA_CC0pi_XSec_1Dpt_nu")) fDist = kPt; else if (!name.compare("MINERvA_CC0pi_XSec_1Dpz_nu")) fDist = kPz; else if (!name.compare("MINERvA_CC0pi_XSec_1DQ2QE_nu")) fDist = kQ2QE; else if (!name.compare("MINERvA_CC0pi_XSec_1DEnuQE_nu")) fDist = kEnuQE; // Define what files to use from the dist std::string datafile = ""; std::string corrfile = ""; std::string titles = ""; std::string distdescript = ""; std::string histname = ""; switch (fDist) { case (kPt): datafile = "MINERvA/CC0pi_1D/FixedBinWidthPub/cov_ptmu_qelike.root"; corrfile = "MINERvA/CC0pi_1D/FixedBinWidthPub/cov_ptmu_qelike.root"; titles = "MINERvA CC0#pi #nu_{#mu} p_{t};p_{t} (GeV);d#sigma/dP_{t} " "(cm^{2}/GeV/nucleon)"; distdescript = "MINERvA_CC0pi_XSec_1Dpt_nu sample"; histname = "ptmu_cross_section"; break; case (kPz): datafile = "MINERvA/CC0pi_1D/FixedBinWidthPub/cov_pzmu_qelike.root"; corrfile = "MINERvA/CC0pi_1D/FixedBinWidthPub/cov_pzmu_qelike.root"; titles = "MINERvA CC0#pi #nu_{#mu} p_{z};p_{z} (GeV);d#sigma/dP_{z} " "(cm^{2}/GeV/nucleon)"; distdescript = "MINERvA_CC0pi_XSec_1Dpz_nu sample"; histname = "pzmu_cross_section"; break; case (kQ2QE): datafile = "MINERvA/CC0pi_1D/FixedBinWidthPub/cov_q2qe_qelike.root"; corrfile = "MINERvA/CC0pi_1D/FixedBinWidthPub/cov_q2qe_qelike.root"; titles = "MINERvA CC0#pi #nu_{#mu} Q^{2}_{QE};Q^{2}_{QE} " "(GeV^{2});d#sigma/dQ^{2}_{QE} cm^{2}/GeV^{2}/nucleon)"; distdescript = "MINERvA_CC0pi_XSec_1DQ2QE_nu sample"; histname = "q2qe_cross_section"; break; case (kEnuQE): datafile = "MINERvA/CC0pi_1D/FixedBinWidthPub/cov_enuqe_qelike.root"; corrfile = "MINERvA/CC0pi_1D/FixedBinWidthPub/cov_enuqe_qelike.root"; titles = "MINERvA CC0#pi #nu_{#mu} E_{#nu}^{QE}; E_{#nu}^{QE} " "(GeV);d#sigma/dE_{#nu}^{QE} (cm^{2}/GeV/nucleon)"; distdescript = "MINERvA_CC0pi_XSec_1DEnuQE_nu sample"; histname = "enuqe_cross_section"; break; default: - QTHROW("Unknown Analysis Distribution : " << fDist); + NUIS_ABORT("Unknown Analysis Distribution : " << fDist); } fSettings.SetTitle(GeneralUtils::ParseToStr(titles, ";")[0]); fSettings.SetXTitle(GeneralUtils::ParseToStr(titles, ";")[1]); fSettings.SetYTitle(GeneralUtils::ParseToStr(titles, ";")[2]); // Sample overview --------------------------------------------------- std::string descrip = distdescript + "\n" "Target: CH \n" "Flux: MINERvA Low Energy FHC numu \n" "Signal: CC-0pi \n"; fSettings.SetDescription(descrip); // The input ROOT file fSettings.SetDataInput(FitPar::GetDataBase() + datafile); fSettings.SetCovarInput(FitPar::GetDataBase() + corrfile); // Set the data file SetDataFromRootFile(fSettings.GetDataInput(), histname); }; //******************************************************************** MINERvA_CC0pi_XSec_1D_2018_nu::MINERvA_CC0pi_XSec_1D_2018_nu( nuiskey samplekey) { //******************************************************************** // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetAllowedTypes("FIX,FREE,SHAPE/FULL,DIAG/MASK", "FIX/FULL"); fSettings.SetEnuRange(0.0, 100.0); fSettings.DefineAllowedTargets("C,H"); fSettings.DefineAllowedSpecies("numu"); SetupDataSettings(); FinaliseSampleSettings(); // If EnuQE distribution we apply the bin by bin flux integrated scaling (so // don't divide scalefactor by integrated flux yet) if (fDist == kEnuQE) { fScaleFactor = (GetEventHistogram()->Integral("width") * 1E-38 / (fNEvents + 0.)); } else { fScaleFactor = (GetEventHistogram()->Integral("width") * 1E-38 / (fNEvents + 0.)) / this->TotalIntegratedFlux(); } TMatrixDSym *tempmat = StatUtils::GetCovarFromRootFile( fSettings.GetCovarInput(), "TotalCovariance"); // Scale up up up! (*tempmat) *= 1E38 * 1E38; fFullCovar = tempmat; // Decomposition is stable for entries that aren't E-xxx double ScalingFactor = 1E38; (*fFullCovar) *= ScalingFactor; // Just check that the data error and covariance are the same for (int i = 0; i < fFullCovar->GetNrows(); ++i) { for (int j = 0; j < fFullCovar->GetNcols(); ++j) { // Get the global bin int xbin1, ybin1, zbin1; fDataHist->GetBinXYZ(i, xbin1, ybin1, zbin1); double xlo1 = fDataHist->GetXaxis()->GetBinLowEdge(xbin1); double xhi1 = fDataHist->GetXaxis()->GetBinLowEdge(xbin1 + 1); double ylo1 = fDataHist->GetYaxis()->GetBinLowEdge(ybin1); double yhi1 = fDataHist->GetYaxis()->GetBinLowEdge(ybin1 + 1); if (xlo1 < fDataHist->GetXaxis()->GetBinLowEdge(1) || ylo1 < fDataHist->GetYaxis()->GetBinLowEdge(1) || xhi1 > fDataHist->GetXaxis()->GetBinLowEdge( fDataHist->GetXaxis()->GetNbins() + 1) || yhi1 > fDataHist->GetYaxis()->GetBinLowEdge( fDataHist->GetYaxis()->GetNbins() + 1)) continue; double data_error = fDataHist->GetBinError(xbin1, ybin1); double cov_error = sqrt((*fFullCovar)(i, i) / ScalingFactor); if (fabs(data_error - cov_error) > 1E-5) { std::cerr << "Error on data is different to that of covariance" << std::endl; - QERROR(FTL, "Data error: " << data_error); - QERROR(FTL, "Cov error: " << cov_error); - QERROR(FTL, "Data/Cov: " << data_error / cov_error); - QERROR(FTL, "Data-Cov: " << data_error - cov_error); - QERROR(FTL, "For x: " << xlo1 << "-" << xhi1); - QTHROW("For y: " << ylo1 << "-" << yhi1); + NUIS_ERR(FTL, "Data error: " << data_error); + NUIS_ERR(FTL, "Cov error: " << cov_error); + NUIS_ERR(FTL, "Data/Cov: " << data_error / cov_error); + NUIS_ERR(FTL, "Data-Cov: " << data_error - cov_error); + NUIS_ERR(FTL, "For x: " << xlo1 << "-" << xhi1); + NUIS_ABORT("For y: " << ylo1 << "-" << yhi1); } } } // Now can make the inverted covariance covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); // Now scale back (*fFullCovar) *= 1.0 / ScalingFactor; (*covar) *= ScalingFactor; (*fDecomp) *= ScalingFactor; // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CC0pi_XSec_1D_2018_nu::FillEventVariables(FitEvent *event) { //******************************************************************** // Checking to see if there is a Muon if (event->NumFSParticle(13) == 0) return; // Get the muon kinematics TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; TLorentzVector Pnu = event->GetNeutrinoIn()->fP; // Now we set the x-axis switch (fDist) { case (kPt): { Double_t px = Pmu.X() / 1000.; Double_t py = Pmu.Y() / 1000.; Double_t pt = sqrt(px * px + py * py); fXVar = pt; break; } case (kPz): { Double_t pz = Pmu.Vect().Dot(Pnu.Vect() * (1.0 / Pnu.Vect().Mag())) / 1000.; fXVar = pz; break; } case (kQ2QE): { Double_t q2qe = FitUtils::Q2QErec(Pmu, Pnu, 34.); fXVar = q2qe; break; } case (kEnuQE): { Double_t enuqe = FitUtils::EnuQErec(Pmu, cos(Pnu.Vect().Angle(Pmu.Vect())), 34.); fXVar = enuqe; break; } default: - QTHROW("DIST NOT FOUND : " << fDist); + NUIS_ABORT("DIST NOT FOUND : " << fDist); break; } return; }; //******************************************************************** bool MINERvA_CC0pi_XSec_1D_2018_nu::isSignal(FitEvent *event) { //******************************************************************** return SignalDef::isCC0pi_MINERvAPTPZ(event, 14, EnuMin, EnuMax); }; diff --git a/src/MINERvA/MINERvA_CC0pi_XSec_2D_antinu.cxx b/src/MINERvA/MINERvA_CC0pi_XSec_2D_antinu.cxx index 75b6e8e..2589ec8 100644 --- a/src/MINERvA/MINERvA_CC0pi_XSec_2D_antinu.cxx +++ b/src/MINERvA/MINERvA_CC0pi_XSec_2D_antinu.cxx @@ -1,199 +1,199 @@ // Adrian Orea // I used the file MINERvA_CCinc_XSec_2DEavq3_nu.cxx as a template // Also, I am fully aware of the naming typo (should be ptpz), but Everything is already named the same way so... // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ /* Author : Adrian Orea Clarence Wret Cleanup 2019: Data was missing Signal definition wrong (missing 120 MeV KE cut, missing pz and pt cut) Not fully implemented Assumed generator send neutrinos along z-axis */ #include "MINERvA_SignalDef.h" #include "MINERvA_CC0pi_XSec_2D_antinu.h" //******************************************************************** void MINERvA_CC0pi_XSec_2D_antinu::SetupDataSettings() { //******************************************************************** // Set Distribution // See header file for enum and some descriptions std::string name = fSettings.GetS("name"); // We're lucky to have three different MINERvA CC0pi anti-numu 2D distributions if (!name.compare("MINERvA_CC0pi_XSec_2Dptpz_antinu")) fDist = kPtPz; else if (!name.compare("MINERvA_CC0pi_XSec_2DQ2QEEnuQE_antinu")) fDist = kQ2QEEnuQE; else if (!name.compare("MINERvA_CC0pi_XSec_2DQ2QEEnuTrue_antinu")) fDist = kQ2QEEnuTrue; // Define what files to use from the dist std::string basedir = "MINERvA/CC0pi_2D_antinu/"; std::string datafile = basedir; std::string covfile = basedir; std::string titles = ""; std::string distdescript = ""; std::string histname = ""; std::string xbinning = basedir; std::string ybinning = basedir; // N.B. fScaleFactor also needs to be set dependent on the distribution. The EnuQE and EnuTrue distributions flux integrate in the Enu dimension and flux average in the Q2 dimension switch (fDist) { case (kPtPz): datafile += "cross_sections_muonpz_muonpt_lowangleqelike_minerva_2d.csv"; covfile += "cross_sections_muonpz_muonpt_lowangleqelike_minerva_covariance.csv"; xbinning += "cross_sections_muonpt_lowangleqelike_minerva_intmuonpz_bins_1d.csv"; ybinning += "cross_sections_muonpz_lowangleqelike_minerva_intmuonpt_bins_1d.csv"; titles = "MINERvA CC0#pi #bar{#nu}_{#mu} p_{t} p_{z};p_{t} (GeV);p_{z} (GeV);d^{2}#sigma/dp_{t}dp_{z} (cm^{2}/GeV^{2}/nucleon)"; distdescript = "MINERvA_CC0pi_XSec_2Dptpz_antinu sample"; fScaleFactor = (GetEventHistogram()->Integral("width") * 1E-38 / (fNEvents + 0.)) / this->TotalIntegratedFlux(); break; case (kQ2QEEnuQE): datafile += "cross_sections_enuqe_qsq_lowangleqelike_minerva_2d.csv"; covfile += "cross_sections_enuqe_qsq_lowangleqelike_minerva_covariance.csv"; xbinning += "cross_sections_qsq_lowangleqelike_minerva_intenuqe_bins_1d.csv"; ybinning += "cross_sections_enuqe_lowangleqelike_minerva_intqsq_bins_1d.csv"; titles = "MINERvA CC0#pi #bar{#nu}_{#mu} Q^{2}_{QE} E^{#nu}_{QE};Q^{2}_{QE} (GeV);E^{#nu}_{QE} (GeV);d#sigma/dQ^{2}_{QE} (cm^{2}/GeV^{2}/nucleon)"; distdescript = "MINERvA_CC0pi_XSec_2DQ2QEEnuQE_antinu sample"; fScaleFactor = GetEventHistogram()->Integral("width") * double(1E-38) / double(fNEvents); break; case (kQ2QEEnuTrue): datafile += "cross_sections_enu_qsq_lowangleqelike_minerva_2d.csv"; covfile += "cross_sections_enu_qsq_lowangleqelike_minerva_covariance.csv"; xbinning += "cross_sections_qsq_lowangleqelike_minerva_intenuqe_bins_1d.csv"; ybinning += "cross_sections_enuqe_lowangleqelike_minerva_intqsq_bins_1d.csv"; titles = "MINERvA CC0#pi #bar{#nu}_{#mu} Q^{2}_{QE} E^{#nu}_{True};Q^{2}_{QE} (GeV);E^{#nu}_{True} (GeV);d#sigma/dQ^{2}_{QE} (cm^{2}/GeV^{2}/nucleon)"; distdescript = "MINERvA_CC0pi_XSec_2DQ2QEEnuTrue_antinu sample"; fScaleFactor = GetEventHistogram()->Integral("width") * double(1E-38) / double(fNEvents); break; default: - QTHROW("Unknown Analysis Distribution : " << name); + NUIS_ABORT("Unknown Analysis Distribution : " << name); } fSettings.SetTitle( GeneralUtils::ParseToStr(titles,";")[0] ); fSettings.SetXTitle( GeneralUtils::ParseToStr(titles,";")[1] ); fSettings.SetYTitle( GeneralUtils::ParseToStr(titles,";")[2] ); fSettings.SetZTitle( GeneralUtils::ParseToStr(titles,";")[3] ); // Sample overview --------------------------------------------------- std::string descrip = distdescript + "\n"\ "Target: CH \n" \ "Flux: MINERvA Low Energy RHC anti-numu \n" \ "Signal: CC-0pi \n"; fSettings.SetDescription(descrip); // The input ROOT file in the fSettings fSettings.SetDataInput(FitPar::GetDataBase() + datafile); fSettings.SetCovarInput(FitPar::GetDataBase() + covfile); // Save the binning used in the sample settings fSettings.SetS("xbins", FitPar::GetDataBase() + xbinning); fSettings.SetS("ybins", FitPar::GetDataBase() + ybinning); // Sets up the data from the data file, x binning and y binning SetDataFromTextFile(fSettings.GetDataInput(), fSettings.GetS("xbins"), fSettings.GetS("ybins")); // The data comes in units of 1E-41 fDataHist->Scale(1E-41); // Setup the covariance matrix SetCovarFromTextFile(fSettings.GetCovarInput(), fDataHist->GetNbinsX()*fDataHist->GetNbinsY()); // Set the error on the data from the covariance matrix StatUtils::SetDataErrorFromCov(fDataHist, fFullCovar, (TH2I*)NULL, 1.E-41, true); // In NUISANCE we assume the covar scale is 1E76 (or cross-section in 1E-38) // For this measurement it's actually 1E41*1E41=1E82 so need to multiply 1E82/1E76=1E6 double ScalingFactor = 1E-3*1E-3; (*fFullCovar) *= ScalingFactor; (*covar) *= 1./ScalingFactor; (*fDecomp) *= 1./ScalingFactor; }; //******************************************************************** MINERvA_CC0pi_XSec_2D_antinu::MINERvA_CC0pi_XSec_2D_antinu(nuiskey samplekey) { //******************************************************************** fSettings = LoadSampleSettings(samplekey); fSettings.SetAllowedTypes("FIX,FREE,SHAPE/FULL,DIAG/MASK", "FIX/FULL"); fSettings.SetEnuRange(0.0, 100.0); fSettings.DefineAllowedTargets("C,H"); fSettings.DefineAllowedSpecies("antinumu"); // Set up the data and covariance matrix SetupDataSettings(); FinaliseSampleSettings(); FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CC0pi_XSec_2D_antinu::FillEventVariables(FitEvent *event) { //******************************************************************** // Checking to see if there is a Muon if (event->NumFSParticle(-13) == 0) return; TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Pmu = event->GetHMFSParticle(-13)->fP; switch (fDist) { case (kPtPz): { Double_t px = Pmu.X()/1.E3; Double_t py = Pmu.Y()/1.E3; Double_t pt = sqrt(px*px+py*py); // Don't want to assume the event generators all have neutrino coming along z // pz is muon momentum projected onto the neutrino direction Double_t pz = Pmu.Vect().Dot(Pnu.Vect()*(1.0/Pnu.Vect().Mag()))/1.E3; // Set Hist Variables fYVar = pz; fXVar = pt; break; } case (kQ2QEEnuQE): { double Q2qeRec = FitUtils::Q2QErec(Pmu, Pnu, 30, false); double EnuQErec = FitUtils::EnuQErec(Pmu, Pnu, 30, false); fXVar = Q2qeRec; fYVar = EnuQErec; break; } case (kQ2QEEnuTrue): { double Q2qeRec = FitUtils::Q2QErec(Pmu, Pnu, 30, false); double EnuTrue = Pnu.E()/1.E3; fXVar = Q2qeRec; fYVar = EnuTrue; break; } } }; //******************************************************************** bool MINERvA_CC0pi_XSec_2D_antinu::isSignal(FitEvent *event) { //******************************************************************** return SignalDef::isCC0pi_anti_MINERvAPTPZ(event, -14, EnuMin, EnuMax); }; diff --git a/src/MINERvA/MINERvA_CC0pi_XSec_2D_nu.cxx b/src/MINERvA/MINERvA_CC0pi_XSec_2D_nu.cxx index 28f198d..7990f68 100644 --- a/src/MINERvA/MINERvA_CC0pi_XSec_2D_nu.cxx +++ b/src/MINERvA/MINERvA_CC0pi_XSec_2D_nu.cxx @@ -1,245 +1,245 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ /* Authors: Adrian Orea (v1 2017) Clarence Wret (v2 2018) */ #include "MINERvA_CC0pi_XSec_2D_nu.h" #include "MINERvA_SignalDef.h" //******************************************************************** void MINERvA_CC0pi_XSec_2D_nu::SetupDataSettings() { //******************************************************************** // Set Distribution // See header file for enum and some descriptions std::string name = fSettings.GetS("name"); // Have one distribution as of summer 2018 if (!name.compare("MINERvA_CC0pi_XSec_2Dptpz_nu")) fDist = kPtPz; // Define what files to use from the dist std::string datafile = ""; std::string corrfile = ""; std::string titles = ""; std::string distdescript = ""; std::string histname = ""; switch (fDist) { case (kPtPz): datafile = "MINERvA/CC0pi_2D/cov_ptpl_2D_qelike.root"; corrfile = "MINERvA/CC0pi_2D/cov_ptpl_2D_qelike.root"; titles = "MINERvA CC0#pi #nu_{#mu} p_{t} p_{z};p_{z} (GeV);p_{t} " "(GeV);d^{2}#sigma/dP_{t}dP_{z} (cm^{2}/GeV^{2}/nucleon)"; distdescript = "MINERvA_CC0pi_XSec_2Dptpz_nu sample"; histname = "pt_pl_cross_section"; break; default: - QTHROW("Unknown Analysis Distribution : " << name); + NUIS_ABORT("Unknown Analysis Distribution : " << name); } fSettings.SetTitle(GeneralUtils::ParseToStr(titles, ";")[0]); fSettings.SetXTitle(GeneralUtils::ParseToStr(titles, ";")[1]); fSettings.SetYTitle(GeneralUtils::ParseToStr(titles, ";")[2]); fSettings.SetZTitle(GeneralUtils::ParseToStr(titles, ";")[3]); // Sample overview --------------------------------------------------- std::string descrip = distdescript + "\n" "Target: CH \n" "Flux: MINERvA Low Energy FHC numu \n" "Signal: CC-0pi \n"; fSettings.SetDescription(descrip); // The input ROOT file fSettings.SetDataInput(FitPar::GetDataBase() + datafile); fSettings.SetCovarInput(FitPar::GetDataBase() + corrfile); // Set the data file SetDataValues(fSettings.GetDataInput(), histname); } //******************************************************************** MINERvA_CC0pi_XSec_2D_nu::MINERvA_CC0pi_XSec_2D_nu(nuiskey samplekey) { //******************************************************************** // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetAllowedTypes("FIX,FREE,SHAPE/FULL,DIAG/MASK", "FIX/FULL"); fSettings.SetEnuRange(0.0, 100.0); fSettings.DefineAllowedTargets("C,H"); fSettings.DefineAllowedSpecies("numu"); SetupDataSettings(); FinaliseSampleSettings(); fScaleFactor = (GetEventHistogram()->Integral("width") * 1E-38 / (fNEvents + 0.)) / this->TotalIntegratedFlux(); TMatrixDSym *tempmat = StatUtils::GetCovarFromRootFile( fSettings.GetCovarInput(), "TotalCovariance"); fFullCovar = tempmat; // Decomposition is stable for entries that aren't E-xxx double ScalingFactor = 1E38 * 1E38; (*fFullCovar) *= ScalingFactor; // Just check that the data error and covariance are the same for (int i = 0; i < fFullCovar->GetNrows(); ++i) { for (int j = 0; j < fFullCovar->GetNcols(); ++j) { // Get the global bin int xbin1, ybin1, zbin1; fDataHist->GetBinXYZ(i, xbin1, ybin1, zbin1); double xlo1 = fDataHist->GetXaxis()->GetBinLowEdge(xbin1); double xhi1 = fDataHist->GetXaxis()->GetBinLowEdge(xbin1 + 1); double ylo1 = fDataHist->GetYaxis()->GetBinLowEdge(ybin1); double yhi1 = fDataHist->GetYaxis()->GetBinLowEdge(ybin1 + 1); if (xlo1 < fDataHist->GetXaxis()->GetBinLowEdge(1) || ylo1 < fDataHist->GetYaxis()->GetBinLowEdge(1) || xhi1 > fDataHist->GetXaxis()->GetBinLowEdge( fDataHist->GetXaxis()->GetNbins() + 1) || yhi1 > fDataHist->GetYaxis()->GetBinLowEdge( fDataHist->GetYaxis()->GetNbins() + 1)) continue; double data_error = fDataHist->GetBinError(xbin1, ybin1); double cov_error = sqrt((*fFullCovar)(i, i) / ScalingFactor); if (fabs(data_error - cov_error) > 1E-5) { std::cerr << "Error on data is different to that of covariance" << std::endl; - QERROR(FTL, "Data error: " << data_error); - QERROR(FTL, "Cov error: " << cov_error); - QERROR(FTL, "Data/Cov: " << data_error / cov_error); - QERROR(FTL, "Data-Cov: " << data_error - cov_error); - QERROR(FTL, "For x: " << xlo1 << "-" << xhi1); - QTHROW("For y: " << ylo1 << "-" << yhi1); + NUIS_ERR(FTL, "Data error: " << data_error); + NUIS_ERR(FTL, "Cov error: " << cov_error); + NUIS_ERR(FTL, "Data/Cov: " << data_error / cov_error); + NUIS_ERR(FTL, "Data-Cov: " << data_error - cov_error); + NUIS_ERR(FTL, "For x: " << xlo1 << "-" << xhi1); + NUIS_ABORT("For y: " << ylo1 << "-" << yhi1); } } } // Now can make the inverted covariance covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); // Now scale back (*fFullCovar) *= 1.0 / ScalingFactor; (*covar) *= ScalingFactor; (*fDecomp) *= ScalingFactor; // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CC0pi_XSec_2D_nu::FillEventVariables(FitEvent *event) { //******************************************************************** // Checking to see if there is a Muon if (event->NumFSParticle(13) == 0) return; // Get the muon kinematics TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; TLorentzVector Pnu = event->GetNeutrinoIn()->fP; Double_t px = Pmu.X() / 1000; Double_t py = Pmu.Y() / 1000; Double_t pt = sqrt(px * px + py * py); // y-axis is transverse momentum for both measurements fYVar = pt; // Now we set the x-axis switch (fDist) { case kPtPz: { // Don't want to assume the event generators all have neutrino coming along // z pz is muon momentum projected onto the neutrino direction Double_t pz = Pmu.Vect().Dot(Pnu.Vect() * (1.0 / Pnu.Vect().Mag())) / 1000.; // Set Hist Variables fXVar = pz; break; } default: - QTHROW("DIST NOT FOUND : " << fDist); + NUIS_ABORT("DIST NOT FOUND : " << fDist); break; } }; //******************************************************************** bool MINERvA_CC0pi_XSec_2D_nu::isSignal(FitEvent *event) { //******************************************************************** return SignalDef::isCC0pi_MINERvAPTPZ(event, 14, EnuMin, EnuMax); }; //******************************************************************** // Custom likelihood calculator because binning of covariance matrix double MINERvA_CC0pi_XSec_2D_nu::GetLikelihood() { //******************************************************************** // The calculated chi2 double chi2 = 0.0; // Support shape comparisons double scaleF = fDataHist->Integral() / fMCHist->Integral(); if (fIsShape) { fMCHist->Scale(scaleF); fMCFine->Scale(scaleF); } // Even though this chi2 calculation looks ugly it is _EXACTLY_ what MINERvA // used for their measurement Can be prettified in due time but for now keep int nbinsx = fMCHist->GetNbinsX(); int nbinsy = fMCHist->GetNbinsY(); Int_t Nbins = nbinsx * nbinsy; // Loop over the covariance matrix bins for (int i = 0; i < Nbins; ++i) { int xbin = i % nbinsx + 1; int ybin = i / nbinsx + 1; double datax = fDataHist->GetBinContent(xbin, ybin); double mcx = fMCHist->GetBinContent(xbin, ybin); for (int j = 0; j < Nbins; ++j) { int xbin2 = j % nbinsx + 1; int ybin2 = j / nbinsx + 1; double datay = fDataHist->GetBinContent(xbin2, ybin2); double mcy = fMCHist->GetBinContent(xbin2, ybin2); double chi2_xy = (datax - mcx) * (*covar)(i, j) * (datay - mcy); chi2 += chi2_xy; } } // Normalisation penalty term if included if (fAddNormPen) { chi2 += (1 - (fCurrentNorm)) * (1 - (fCurrentNorm)) / (fNormError * fNormError); - QLOG(REC, "Norm penalty = " << (1 - (fCurrentNorm)) * (1 - (fCurrentNorm)) / + NUIS_LOG(REC, "Norm penalty = " << (1 - (fCurrentNorm)) * (1 - (fCurrentNorm)) / (fNormError * fNormError)); } // Adjust the shape back to where it was. if (fIsShape and !FitPar::Config().GetParB("saveshapescaling")) { fMCHist->Scale(1. / scaleF); fMCFine->Scale(1. / scaleF); } fLikelihood = chi2; return chi2; }; diff --git a/src/MINERvA/MINERvA_CC0pinp_STV_XSec_1D_nu.cxx b/src/MINERvA/MINERvA_CC0pinp_STV_XSec_1D_nu.cxx index 27438cf..58a2413 100644 --- a/src/MINERvA/MINERvA_CC0pinp_STV_XSec_1D_nu.cxx +++ b/src/MINERvA/MINERvA_CC0pinp_STV_XSec_1D_nu.cxx @@ -1,359 +1,359 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ // Implementation of 2018 MINERvA numu CC0pi STV analysis // arxiv 1805.05486.pdf // Clarence Wret // cwret@fnal.gov // Stephen Dolan // Stephen.Dolan@llr.in2p3.fr #include "MINERvA_CC0pinp_STV_XSec_1D_nu.h" #include "MINERvA_SignalDef.h" //******************************************************************** void MINERvA_CC0pinp_STV_XSec_1D_nu::SetupDataSettings() { //******************************************************************** // Set Distribution // See header file for enum and some descriptions std::string name = fSettings.GetS("name"); if (!name.compare("MINERvA_CC0pinp_STV_XSec_1Dpmu_nu")) fDist = kMuonMom; else if (!name.compare("MINERvA_CC0pinp_STV_XSec_1Dthmu_nu")) fDist = kMuonTh; else if (!name.compare("MINERvA_CC0pinp_STV_XSec_1Dpprot_nu")) fDist = kPrMom; else if (!name.compare("MINERvA_CC0pinp_STV_XSec_1Dthprot_nu")) fDist = kPrTh; else if (!name.compare("MINERvA_CC0pinp_STV_XSec_1Dpnreco_nu")) fDist = kNeMom; else if (!name.compare("MINERvA_CC0pinp_STV_XSec_1Ddalphat_nu")) fDist = kDalphaT; else if (!name.compare("MINERvA_CC0pinp_STV_XSec_1Ddpt_nu")) fDist = kDpT; else if (!name.compare("MINERvA_CC0pinp_STV_XSec_1Ddphit_nu")) fDist = kDphiT; // Location of data, correlation matrices and the titles std::string titles = "MINERvA_CC0pinp_STV_XSec_1D"; std::string foldername; std::string distdescript; // Data release is a single file std::string rootfile = "MINERvA_1805.05486.root"; fMin = -999; fMax = 999; switch (fDist) { case (kMuonMom): titles += "pmu"; foldername = "muonmomentum"; distdescript = "Muon momentum in lab frame"; /* fMin = 2.0; fMax = 6.0; */ fMin = 1.5; fMax = 10.0; break; case (kMuonTh): titles += "thmu"; foldername = "muontheta"; distdescript = "Muon angle relative neutrino in lab frame"; fMin = 0.0; fMax = 20.0; break; case (kPrMom): titles += "pprot"; foldername = "protonmomentum"; distdescript = "Proton momentum in lab frame"; // fMin = 0.5; fMin = 0.45; fMax = 1.2; break; case (kPrTh): titles += "thprot"; foldername = "protontheta"; distdescript = "Proton angle relative neutrino in lab frame"; fMin = 0.0; fMax = 70.0; break; case (kNeMom): titles += "pnreco"; foldername = "neutronmomentum"; distdescript = "Neutron momentum in lab frame"; fMin = 0.0; // fMax = 0.9; fMax = 2.0; break; case (kDalphaT): foldername = "dalphat"; titles += foldername; distdescript = "Delta Alpha_T"; fMin = 0.0; // fMax = 170; fMax = 180; break; case (kDpT): foldername = "dpt"; titles += foldername; distdescript = "Delta p_T"; fMin = 0.0; fMax = 2.0; break; case (kDphiT): foldername = "dphit"; titles += foldername; distdescript = "Delta phi_T"; fMin = 0.0; // fMax = 60.0; fMax = 180.0; break; default: - QERROR(FTL, + NUIS_ERR(FTL, "Did not find your specified distribution implemented, exiting"); - QTHROW("You gave " << fName); + NUIS_ABORT("You gave " << fName); } titles += "_nu"; // All have the same name std::string dataname = foldername; // Sample overview --------------------------------------------------- std::string descrip = distdescript + "Target: CH \n" "Flux: MINERvA Forward Horn Current numu ONLY \n" "Signal: Any event with 1 muon, and 0pi0 in FS, no " "mesons, at least one proton with: \n" "1.5GeV < p_mu < 10 GeV\n" "theta_mu < 20 degrees\n" "0.45GeV < p_prot < 1.2 GeV\n" "theta_prot < 70 degrees\n" "arXiv 1805.05486"; fSettings.SetDescription(descrip); std::string filename = GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CC0pi/CC0pi_STV/MINERvA_1805.05486.root"; // Specify the data fSettings.SetDataInput(filename + ";" + dataname); // And the correlations fSettings.SetCovarInput(filename + ";" + dataname); // Set titles fSettings.SetTitle(titles); }; //******************************************************************** MINERvA_CC0pinp_STV_XSec_1D_nu::MINERvA_CC0pinp_STV_XSec_1D_nu( nuiskey samplekey) { //******************************************************************** // A few different distributinos // Muon momentum, muon angle, proton momentum, proton angle, neutron momentum, // dalphat, dpt, dphit // Setup common settings fSettings = LoadSampleSettings(samplekey); // Load up the data paths and sample descriptions SetupDataSettings(); fSettings.SetAllowedTypes("FIX,FREE,SHAPE/DIAG,FULL/NORM/MASK", "FIX/DIAG"); // No Enu cut fSettings.SetEnuRange(0.0, 100.0); fSettings.DefineAllowedTargets("C,H"); fSettings.DefineAllowedSpecies("numu"); // Finalise the settings FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = GetEventHistogram()->Integral("width") * double(1E-38) / (double(fNEvents) * TotalIntegratedFlux("width")); // Set the data and covariance matrix SetDataFromRootFile(fSettings.GetDataInput()); SetCovarianceFromRootFile(fSettings.GetCovarInput()); fSettings.SetXTitle(fDataHist->GetXaxis()->GetTitle()); fSettings.SetYTitle(fDataHist->GetYaxis()->GetTitle()); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** // Data comes in a TList // Some bins need stripping out because of zero bin content. Why oh why void MINERvA_CC0pinp_STV_XSec_1D_nu::SetDataFromRootFile(std::string filename) { //******************************************************************** std::vector tempfile = GeneralUtils::ParseToStr(filename, ";"); TFile *File = new TFile(tempfile[0].c_str(), "READ"); // First object is the data TH1D *temp = (TH1D *)(((TList *)(File->Get(tempfile[1].c_str())))->At(0)); // Garh, some of the data points are zero in the TH1D (WHY?!) so messes with // the covariance entries to data bins check Skim through the data and check // for zero bins std::vector CrossSection; std::vector Error; std::vector BinEdges; int lastbin = 0; startbin = 0; for (int i = 0; i < temp->GetXaxis()->GetNbins() + 2; ++i) { if (temp->GetBinContent(i + 1) > 0 && temp->GetBinLowEdge(i + 1) >= fMin && temp->GetBinLowEdge(i + 1) <= fMax) { if (startbin == 0) startbin = i; lastbin = i; CrossSection.push_back(temp->GetBinContent(i + 1)); BinEdges.push_back(temp->GetXaxis()->GetBinLowEdge(i + 1)); Error.push_back(temp->GetBinError(i + 1)); } } BinEdges.push_back(temp->GetXaxis()->GetBinLowEdge(lastbin + 2)); fDataHist = new TH1D((fSettings.GetName() + "_data").c_str(), (fSettings.GetFullTitles()).c_str(), BinEdges.size() - 1, &BinEdges[0]); fDataHist->SetDirectory(0); for (unsigned int i = 0; i < BinEdges.size() - 1; ++i) { fDataHist->SetBinContent(i + 1, CrossSection[i]); fDataHist->SetBinError(i + 1, Error[i]); } fDataHist->GetXaxis()->SetTitle(temp->GetXaxis()->GetTitle()); fDataHist->GetYaxis()->SetTitle(temp->GetYaxis()->GetTitle()); fDataHist->SetTitle(temp->GetTitle()); File->Close(); } //******************************************************************** // Covariance also needs stripping out // There's padding (two bins...) and overflow (last bin before the two empty // bins) void MINERvA_CC0pinp_STV_XSec_1D_nu::SetCovarianceFromRootFile( std::string filename) { //******************************************************************** std::vector tempfile = GeneralUtils::ParseToStr(filename, ";"); TFile *File = new TFile(tempfile[0].c_str(), "READ"); // First object is the data, second is data with statistical error only, third // is the covariance matrix TMatrixDSym *tempcov = (TMatrixDSym *)((TList *)File->Get(tempfile[1].c_str()))->At(2); // Count the number of zero entries int ngood = 0; int nstart = -1; int nend = -1; // Scan through the middle bin and look for entries int middle = tempcov->GetNrows() / 2; int nbinsdata = fDataHist->GetXaxis()->GetNbins(); for (int j = 0; j < tempcov->GetNrows(); ++j) { if ((*tempcov)(middle, j) > 0 && ngood < nbinsdata) { ngood++; if (nstart == -1) nstart = j; if (j > nend) nend = j; } } fFullCovar = new TMatrixDSym(ngood); for (int i = 0; i < fFullCovar->GetNrows(); ++i) { for (int j = 0; j < fFullCovar->GetNrows(); ++j) { (*fFullCovar)(i, j) = (*tempcov)(i + nstart + startbin - 1, j + nstart + startbin - 1); } } (*fFullCovar) *= 1E38 * 1E38; File->Close(); // Fill other covars. covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); } void MINERvA_CC0pinp_STV_XSec_1D_nu::FillEventVariables(FitEvent *event) { fXVar = -999.99; // Need a proton and a muon if (event->NumFSParticle(2212) == 0 || event->NumFSParticle(13) == 0) { return; } TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; // Find the highest momentum proton in the event between 450 and 1200 MeV with // theta_p < 70 int HMFSProton = 0; double HighestMomentum = 0.0; // Get the stack of protons std::vector Protons = event->GetAllFSProton(); for (size_t i = 0; i < Protons.size(); ++i) { if (Protons[i]->p() > 450 && Protons[i]->p() < 1200 && Protons[i]->P3().Angle(Pnu.Vect()) < (M_PI / 180.0) * 70.0 && Protons[i]->p() > HighestMomentum) { HMFSProton = i; } } // Now get the proton TLorentzVector Pprot = Protons[HMFSProton]->fP; switch (fDist) { case (kMuonMom): fXVar = Pmu.Vect().Mag() / 1000.0; break; case (kMuonTh): fXVar = Pmu.Vect().Angle(Pnu.Vect()) * (180.0 / M_PI); break; case (kPrMom): fXVar = Pprot.Vect().Mag() / 1000.0; break; case (kPrTh): fXVar = Pprot.Vect().Angle(Pnu.Vect()) * (180.0 / M_PI); break; // Use Stephen's validated functions case (kNeMom): fXVar = FitUtils::Get_pn_reco_C(event, 14, true); break; case (kDalphaT): fXVar = FitUtils::Get_STV_dalphat(event, 14, true) * (180.0 / M_PI); break; case (kDpT): fXVar = FitUtils::Get_STV_dpt(event, 14, true) / 1000.0; break; case (kDphiT): fXVar = FitUtils::Get_STV_dphit(event, 14, true) * (180.0 / M_PI); break; } return; }; //******************************************************************** bool MINERvA_CC0pinp_STV_XSec_1D_nu::isSignal(FitEvent *event) //******************************************************************** { return SignalDef::isCC0piNp_MINERvA_STV(event, EnuMin, EnuMax); } diff --git a/src/MINERvA/MINERvA_CC1pi0_XSec_1D_nu.cxx b/src/MINERvA/MINERvA_CC1pi0_XSec_1D_nu.cxx index 68b6579..f186b4b 100644 --- a/src/MINERvA/MINERvA_CC1pi0_XSec_1D_nu.cxx +++ b/src/MINERvA/MINERvA_CC1pi0_XSec_1D_nu.cxx @@ -1,320 +1,320 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_SignalDef.h" #include "MINERvA_CC1pi0_XSec_1D_nu.h" // Implementation of 2017 MINERvA numu CC1pi0 // arxiv:1708.03723v1 hep-ex // c.wret14@imperial.ac.uk //******************************************************************** void MINERvA_CC1pi0_XSec_1D_nu::SetupDataSettings(){ //******************************************************************** // Set Distribution // See header file for enum and some descriptions std::string name = fSettings.GetS("name"); if (!name.compare("MINERvA_CC1pi0_XSec_1DTpi_nu")) fDist = kTpi; else if (!name.compare("MINERvA_CC1pi0_XSec_1Dth_nu")) fDist= kth; else if (!name.compare("MINERvA_CC1pi0_XSec_1Dpmu_nu")) fDist= kpmu; else if (!name.compare("MINERvA_CC1pi0_XSec_1Dthmu_nu")) fDist= kthmu; else if (!name.compare("MINERvA_CC1pi0_XSec_1DQ2_nu")) fDist= kQ2; else if (!name.compare("MINERvA_CC1pi0_XSec_1DEnu_nu")) fDist= kEnu; else if (!name.compare("MINERvA_CC1pi0_XSec_1DWexp_nu")) fDist= kWexp; else if (!name.compare("MINERvA_CC1pi0_XSec_1DPPi0Mass_nu")) fDist= kPPi0Mass; else if (!name.compare("MINERvA_CC1pi0_XSec_1DPPi0MassDelta_nu")) fDist= kPPi0MassDelta; else if (!name.compare("MINERvA_CC1pi0_XSec_1DCosAdler_nu")) fDist= kCosAdler; else if (!name.compare("MINERvA_CC1pi0_XSec_1DPhiAdler_nu")) fDist= kPhiAdler; // Define what files to use from the dist std::string datafile = ""; std::string corrfile = ""; std::string titles = ""; std::string distdescript = ""; // Set the default to essentially not be a cut on proton kinetic energy // The Adler angles and reconstructed p,pi0 invariant mass have cuts on these ProtonCut = 100; // W exp is 1.8 GeV or lower (dealt with below) WexpCut = 1.8; // Load up the data switch (fDist) { case (kTpi): datafile = "data/XSec_Table_pi0_KE_xsec.csv"; corrfile = "corr/Correlation_Table_pi0_KE_xsec.csv"; titles = "CC1#pi^{0};T_{#pi} (GeV);d#sigma/dT_{#pi} (cm^{2}/nucleon/GeV)"; break; case (kth): datafile = "data/XSec_Table_pi0_theta_xsec.csv"; corrfile = "corr/Correlation_Table_pi0_theta_xsec.csv"; titles = "CC1#pi^{0};#theta_{#pi} (degrees); d#sigma/d#theta_{#pi} (cm^{2}/nucleon/degree)"; break; case (kpmu): datafile = "data/XSec_Table_muon_P_xsec.csv"; corrfile = "corr/Correlation_Table_muon_P_xsec.csv"; titles = "CC1#pi^{0};p_{#mu} (GeV);d#sigma/dp_{#mu} (cm^{2}/nucleon/GeV)"; break; case (kthmu): datafile = "data/XSec_Table_muon_theta_xsec.csv"; corrfile = "corr/Correlation_Table_muon_theta_xsec.csv"; titles = "CC1#pi^{0};#theta_{#mu} (degrees);d#sigma/d#theta_{#mu} (cm^{2}/nucleon/degree)"; break; case (kQ2): datafile = "data/XSec_Table_QSq_xsec.csv"; corrfile = "corr/Correlation_Table_QSq_xsec.csv"; titles = "CC1#pi^{0};Q^{2} (GeV^{2});d#sigma/dQ^{2} (cm^{2}/nucleon/GeV^{2})"; break; case (kEnu): datafile = "data/XSec_Table_Enu_xsec.csv"; corrfile = "corr/Correlation_Table_Enu_xsec.csv"; titles = "CC1#pi^{0};E_{#nu} (GeV);#sigma(E_#nu) (cm^{2}/nucleon)"; break; case (kWexp): datafile = "data/XSec_Table_W_xsec.csv"; corrfile = "corr/Correlation_Table_W_xsec.csv"; titles = "CC1#pi^{0};W_{exp} (GeV);d#sigma/dW_{exp} (cm^{2}/nucleon/GeV)"; break; case (kPPi0Mass): datafile = "data/XSec_Table_deltaInvMass_xsec.csv"; corrfile = "corr/Correlation_Table_deltaInvMass_xsec.csv"; titles = "CC1#pi^{0}; M_{p#pi^{0}} (GeV); d#sigma/dM_{p#pi^{0}} (cm^{2}/nucleon/GeV)"; break; case (kPPi0MassDelta): datafile = "data/XSec_Table_deltaInvMass_xsec_DeltaRich.csv"; corrfile = "corr/Correlation_Table_deltaInvMass_xsec_DeltaRich.csv"; titles = "CC1#pi^{0}; M_{p#pi^{0}} W_{exp} < 1.4 (GeV); d#sigma/dM_{p#pi^{0}} (cm^{2}/nucleon/GeV)"; break; case (kCosAdler): datafile = "data/XSec_Table_Delta_pi_theta_xsec.csv"; corrfile = "corr/Correlation_Table_Delta_pi_theta_xsec.csv"; titles = "CC1#pi^{0}; cos#theta_{Adler}; d#sigma/dcos#theta_{Adler} (cm^{2}/nucleon/0.1)"; break; case (kPhiAdler): datafile = "data/XSec_Table_Delta_pi_phi_xsec.csv"; corrfile = "corr/Correlation_Table_Delta_pi_phi_xsec.csv"; titles = "CC1#pi^{0}; #phi_{Adler} (degrees); d#sigma/d#phi_{Adler} (cm^{2}/nucleon/degree)"; break; default: - QTHROW("Unknown Analysis Distribution : " << fDist); + NUIS_ABORT("Unknown Analysis Distribution : " << fDist); } // Set the Wexp and proton kinetic energy cuts depending on sample // for Ppi0Mass distributions and Adler angles we require a proton of at least 100 MeV kinetic energy if (fDist >= kPPi0Mass) { ProtonCut = 0.1; // 0.1 GeV proton kinetic energy cut // Some distributions have a Wexp cut at 1.4 GeV which attempts to isolate delta production if (fDist >= kPPi0MassDelta) { WexpCut = 1.4; } } // Only have xsec covariance (not shape only) // Now setup each data distribution and description. std::string descrip = distdescript + \ "Target: CH \n" \ "Flux: MINERvA Forward Horn Current numu ONLY \n" \ "Signal: Any event with 1 muon with #theta_{#mu,#nu}<25#degree, and 1pi0 in FS, no mesons, any nucleon(s). W < 1.8" \ "Alt Signal: Add in requirement of 1 proton with 100 MeV and sometimes W < 1.4"; fSettings.SetDescription(descrip); // Specify the data fSettings.SetDataInput( GeneralUtils::GetTopLevelDir()+"/data/MINERvA/CC1pi0/2017_nu/" + datafile); // And the correlations fSettings.SetCovarInput(GeneralUtils::GetTopLevelDir()+"/data/MINERvA/CC1pi0/2017_nu/" + corrfile); fSettings.SetTitle( GeneralUtils::ParseToStr(titles,";")[0] ); fSettings.SetXTitle( GeneralUtils::ParseToStr(titles,";")[1] ); fSettings.SetYTitle( GeneralUtils::ParseToStr(titles,";")[2] ); return; } //******************************************************************** MINERvA_CC1pi0_XSec_1D_nu::MINERvA_CC1pi0_XSec_1D_nu(nuiskey samplekey) { //******************************************************************** // Define Sample Settings common to all data distributions fSettings = LoadSampleSettings(samplekey); fSettings.SetAllowedTypes("FIX,FREE,SHAPE/DIAG,FULL/NORM/MASK", "FIX/FULL"); // From 1.5 to 20 GeV Enu fSettings.SetEnuRange(1.5, 20.0); fSettings.DefineAllowedTargets("C,H"); fSettings.DefineAllowedSpecies("numu"); SetupDataSettings(); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // If Enu setup scale factor for Enu Unfolded, otherwise use differential if (fDist == kEnu) fScaleFactor = GetEventHistogram()->Integral("width") * double(1E-38) / double(fNEvents); else fScaleFactor = GetEventHistogram()->Integral("width") * double(1E-38) / double(fNEvents) / TotalIntegratedFlux("width"); // Plot Setup ------------------------------------------------------- SetDataFromTextFile( fSettings.GetDataInput() ); // The errors come as a percent of the cross-section for this measurement so need rescaling // Have set the fDataHist above so just loop over and set new errors for (int i = 0; i < fDataHist->GetNbinsX(); ++i) { fDataHist->SetBinError(i+1, (fDataHist->GetBinError(i+1)/100.0)*fDataHist->GetBinContent(i+1)); } // And finally all the numbers are in units of 1E-40 so scale the histograms as such fDataHist->Scale(1.0E-40); // This measurement gives us a correlation matrix, so should set it up as such SetCorrelationFromTextFile( fSettings.GetCovarInput() ); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CC1pi0_XSec_1D_nu::FillEventVariables(FitEvent *event) { //******************************************************************** fXVar = -999.9; // Need a neutral pion and a muon if (event->NumFSParticle(111) == 0 || event->NumFSParticle(13) == 0) { return; } // Get the TLorentzVectors from the event TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Ppi0 = event->GetHMFSParticle(111)->fP; TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; // Pion kinetic energy double Tpi = (Ppi0.E() - Ppi0.Mag())/1.E3; // Pion-neutrino angle double th = (180./M_PI)*FitUtils::th(Pnu, Ppi0); // Muon momentum double pmu = Pmu.Vect().Mag()/1.E3; // Muon-neutrino angle double thmu = (180.0/M_PI)*FitUtils::th(Pnu, Pmu); // True Q2 double Q2 = fabs((Pmu - Pnu).Mag2()) / 1.E6; // True Enu double Enu = Pnu.E() / 1.E3; // Wexp (derived from "kinematic quantities" but uses EnuTrue) double Wexp = FitUtils::Wrec(Pnu, Pmu)/1.E3; // Wexp cut of 1.8 GeV in signal definition // N.B. the Adler angles and PPi0 mass requires this to be 1400 if (Wexp > WexpCut) return; // There's a theta mu cut of 25 degrees if (thmu > 25) return; // Some distributions require the final state proton: check that it exists if (fDist >= kPPi0Mass && event->NumFSParticle(2212) == 0) return; // Fill the variables depending on the enums switch (fDist) { case kTpi: fXVar = Tpi; break; case kth: fXVar = th; break; case kpmu: // Pmu has a theta_mu < 25degree cut fXVar = pmu; break; case kthmu: // thmu has a theta_mu < 25degree cut fXVar = thmu; break; case kQ2: fXVar = Q2; break; case kEnu: fXVar = Enu; break; case kWexp: fXVar = Wexp; break; // p, pi0 invariant mass with Wexp < 1.8 or Wexp < 1.4: already checked these above case kPPi0Mass: case kPPi0MassDelta: { // Get the proton TLorentzVector Pprot = event->GetHMFSParticle(2212)->fP; double Ppi0Mass = (Ppi0+Pprot).Mag()/1.E3; fXVar = Ppi0Mass; break; } // Cos theta Adler angle case kCosAdler: { TLorentzVector Pprot = event->GetHMFSParticle(2212)->fP; double CosThAdler = FitUtils::CosThAdler(Pnu, Pmu, Ppi0, Pprot); fXVar = CosThAdler; break; } // Phi Adler angle case kPhiAdler: { TLorentzVector Pprot = event->GetHMFSParticle(2212)->fP; double PhiAdler = FitUtils::PhiAdler(Pnu, Pmu, Ppi0, Pprot); fXVar = PhiAdler; break; } default: - QTHROW("DIST NOT FOUND : " << fDist); + NUIS_ABORT("DIST NOT FOUND : " << fDist); break; } }; //******************************************************************** bool MINERvA_CC1pi0_XSec_1D_nu::isSignal(FitEvent *event) { //******************************************************************** // Some of the distributions require a proton with at least 100 MeV KE if (fDist >= kPPi0Mass) { // First of needs a proton in the final state if (event->NumFSParticle(2212) == 0) return false; // Needs to pass CC1pi0 signal definition bool pass_cc1pi0 = SignalDef::isCC1pi0_MINERvA_nu(event, EnuMin, EnuMax); if (!pass_cc1pi0) return false; // And the proton needs at least 100 MeV kinetic energy TLorentzVector Pprot = event->GetHMFSParticle(2212)->fP; double ke = (Pprot.E() - Pprot.Mag())/1.E3; if (pass_cc1pi0 && ke > ProtonCut) { return true; } else { return false; } // The other distributions ahve a more generic "1mu, 1pi0, no mesons, any nucleon(s)" // The W cut is instead made in FillEventVariables } else { return SignalDef::isCC1pi0_MINERvA_nu(event, EnuMin, EnuMax); } } diff --git a/src/MINERvA/MINERvA_CC1pip_XSec_1D_2017Update.cxx b/src/MINERvA/MINERvA_CC1pip_XSec_1D_2017Update.cxx index a013091..63dbdbb 100644 --- a/src/MINERvA/MINERvA_CC1pip_XSec_1D_2017Update.cxx +++ b/src/MINERvA/MINERvA_CC1pip_XSec_1D_2017Update.cxx @@ -1,168 +1,168 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_SignalDef.h" #include "MINERvA_CC1pip_XSec_1D_2017Update.h" //******************************************************************** void MINERvA_CC1pip_XSec_1D_2017Update::SetupDataSettings(){ //******************************************************************** // Set Distribution std::string name = fSettings.GetS("name"); if (!name.compare("MINERvA_CC1pip_XSec_1DTpi_nu_2017")) fDist = kTpi; else if (!name.compare("MINERvA_CC1pip_XSec_1Dth_nu_2017")) fDist= kth; else if (!name.compare("MINERvA_CC1pip_XSec_1Dpmu_nu_2017")) fDist= kpmu; else if (!name.compare("MINERvA_CC1pip_XSec_1Dthmu_nu_2017")) fDist= kthmu; else if (!name.compare("MINERvA_CC1pip_XSec_1DQ2_nu_2017")) fDist= kQ2; else if (!name.compare("MINERvA_CC1pip_XSec_1DEnu_nu_2017")) fDist= kEnu; // Define what files to use from the dist std::string datafile = ""; std::string covarfile = ""; std::string titles = ""; std::string distdescript = ""; switch(fDist){ case (kTpi): datafile = "cc1pip_updated_1DTpi"; covarfile = "cc1pip_updated_1DTpi"; titles = "CC1#pi Updated;T_{#pi} (MeV);d#sigma/dT_{#pi} (cm^{2}/nucleon/MeV)"; break; case (kth): datafile = "cc1pip_updated_1Dth"; covarfile = "cc1pip_updated_1Dth"; titles = "CC1#pi Updated;#theta_{#pi};d#sigma/d#theta_{#pi} (cm^{2}/nucleon)"; break; case (kpmu): datafile = "cc1pip_updated_1Dpmu"; covarfile = "cc1pip_updated_1Dpmu"; titles = "CC1#pi Updated;p_{#mu} (GeV);d#sigma/dp_{#mu} (cm^{2}/nucleon/GeV)"; break; case (kthmu): datafile = "cc1pip_updated_1Dthmu"; covarfile = "cc1pip_updated_1Dthmu"; titles ="CC1#pi Updated;#theta_{#mu};d#sigma/d#theta_{#mu} (cm^{2}/nucleon)"; break; case (kQ2): datafile = "cc1pip_updated_1DQ2"; covarfile = "cc1pip_updated_1DQ2"; titles ="CC1#pi Updated;Q^{2} (GeV^{2});d#sigma/dQ^{2} (cm^{2}/nucleon/GeV^{2})"; break; case (kEnu): datafile = "cc1pip_updated_1DEnu"; covarfile = "cc1pip_updated_1DEnu"; titles ="CC1#pi Updated;E_{#nu} (GeV);#sigma(E_#nu) (cm^{2}/nucleon)"; break; default: - QTHROW("Unknown Analysis Distribution : " << fDist); + NUIS_ABORT("Unknown Analysis Distribution : " << fDist); } // Choose shape or rate covariance fIsShape = fSettings.Found("type","SHAPE"); std::string covid = fIsShape ? "_shapecov.txt" : "_ratecov.txt"; // Now setup each data distribution and description. std::string descrip = distdescript + \ "Target: CH \n" \ "Flux: MINERvA Forward Horn Current numu ONLY \n" \ "Signal: Any event with 1 muon, and 1pi+ or 1pi- in FS. W < 1.8"; fSettings.SetDescription(descrip); fSettings.SetDataInput( GeneralUtils::GetTopLevelDir()+"/data/MINERvA/CC1pip/070717/" + datafile + "_data.txt" ); fSettings.SetCovarInput( GeneralUtils::GetTopLevelDir()+"/data/MINERvA/CC1pip/070717/" + covarfile + covid ); fSettings.SetTitle( GeneralUtils::ParseToStr(titles,";")[0] ); fSettings.SetXTitle( GeneralUtils::ParseToStr(titles,";")[1] ); fSettings.SetYTitle( GeneralUtils::ParseToStr(titles,";")[2] ); return; } //******************************************************************** MINERvA_CC1pip_XSec_1D_2017Update::MINERvA_CC1pip_XSec_1D_2017Update(nuiskey samplekey) { //******************************************************************** // Define Sample Settings common to all data distributions fSettings = LoadSampleSettings(samplekey); fSettings.SetAllowedTypes("FIX,FREE,SHAPE/DIAG,FULL/NORM/MASK", "FIX/FULL"); fSettings.SetEnuRange(1.5, 10.0); fSettings.DefineAllowedTargets("C,H"); fSettings.DefineAllowedSpecies("numu"); SetupDataSettings(); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // If Enu setup scale factor for Enu Unfolded, otherwise use differential if (fDist == kEnu) fScaleFactor = GetEventHistogram()->Integral("width") * double(1E-38) / double(fNEvents); else fScaleFactor = GetEventHistogram()->Integral("width") * double(1E-38) / double(fNEvents) / TotalIntegratedFlux("width"); // Plot Setup ------------------------------------------------------- SetDataFromTextFile( fSettings.GetDataInput() ); SetCorrelationFromTextFile( fSettings.GetCovarInput() ); SetShapeCovar(); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CC1pip_XSec_1D_2017Update::FillEventVariables(FitEvent *event) { //******************************************************************** fXVar = -999.9; if (event->NumFSParticle(PhysConst::pdg_charged_pions) == 0 || event->NumFSParticle(13) == 0) return; TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Ppip = event->GetHMFSParticle(PhysConst::pdg_charged_pions)->fP; TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; double Tpi = Ppip.E() - Ppip.Mag(); double th = (180./M_PI)*FitUtils::th(Pnu, Ppip); double pmu = Pmu.Vect().Mag()/1.E3; // GeV double thmu = (180.0/M_PI)*FitUtils::th(Pnu, Pmu); double Q2 = fabs((Pmu - Pnu).Mag2()) / 1.E6; // Using true here? double Enu = Pnu.E() / 1.E3; switch(fDist){ case kTpi: fXVar = Tpi; break; case kth: fXVar = th; break; case kpmu: fXVar = pmu; break; case kthmu: fXVar = thmu; break; case kQ2: fXVar = Q2; break; case kEnu: fXVar = Enu; break; - default: QTHROW("DIST NOT FOUND : " << fDist); + default: NUIS_ABORT("DIST NOT FOUND : " << fDist); } }; //******************************************************************** bool MINERvA_CC1pip_XSec_1D_2017Update::isSignal(FitEvent *event) { //******************************************************************** // Only seem to release full phase space return SignalDef::isCC1pip_MINERvA_2017(event, EnuMin, EnuMax); } diff --git a/src/MINERvA/MINERvA_CCCOHPI_XSec_joint.cxx b/src/MINERvA/MINERvA_CCCOHPI_XSec_joint.cxx index f56c4ce..23e3191 100644 --- a/src/MINERvA/MINERvA_CCCOHPI_XSec_joint.cxx +++ b/src/MINERvA/MINERvA_CCCOHPI_XSec_joint.cxx @@ -1,210 +1,210 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_CCCOHPI_XSec_joint.h" #include "MINERvA_CCCOHPI_XSec_1DEnu_antinu.h" #include "MINERvA_CCCOHPI_XSec_1DEnu_nu.h" #include "MINERvA_CCCOHPI_XSec_1DEpi_antinu.h" #include "MINERvA_CCCOHPI_XSec_1DEpi_nu.h" #include "MINERvA_CCCOHPI_XSec_1DQ2_antinu.h" #include "MINERvA_CCCOHPI_XSec_1DQ2_nu.h" #include "MINERvA_CCCOHPI_XSec_1Dth_antinu.h" #include "MINERvA_CCCOHPI_XSec_1Dth_nu.h" #include "MINERvA_SignalDef.h" //******************************************************************** void MINERvA_CCCOHPI_XSec_joint::SetupDataSettings() { //******************************************************************** // Set Distribution std::string name = fSettings.GetS("name"); if (!name.compare("MINERvA_CCCOHPI_XSec_1DEpi_joint")) fDist = kEpi; else if (!name.compare("MINERvA_CCCOHPI_XSec_1Dth_joint")) fDist = kth; else if (!name.compare("MINERvA_CCCOHPI_XSec_1DQ2_joint")) fDist = kQ2; else if (!name.compare("MINERvA_CCCOHPI_XSec_1DEnu_joint")) fDist = kEnu; // Define what files to use from the dist std::string datafile = ""; std::string covarfile = ""; std::string titles = ""; std::string distdescript = ""; switch (fDist) { case (kEpi): datafile = "Epi_joint_data.csv"; covarfile = "Epi_joint_cov.csv"; titles = "CC-Coherent #pi;E_{#pi} Bins;d#sigma/dE_{#pi} (cm^{2}/GeV/C12)"; break; case (kth): datafile = "Thpi_joint_data.csv"; covarfile = "Thpi_joint_cov.csv"; titles = "CC-Coherent #pi;#theta_{#pi} Bins;d#sigma/d#theta_{#pi} (cm^{2}/C12)"; break; case (kQ2): datafile = "Q2_joint_data.csv"; covarfile = "Q2_joint_cov.csv"; titles = "CC-Coherent #pi;Q^{2} Bins;d#sigma/dQ^{2} (cm^{2}/GeV^{2}/C12)"; break; case (kEnu): datafile = "Enu_joint_data.csv"; covarfile = "Enu_joint_cov.csv"; titles = "CC-Coherent #pi;E_{#nu} Bins;#sigma(E_{#nu}) (cm^{2}/C12"; break; default: - QTHROW("Unknown Analysis Distribution : " << fDist); + NUIS_ABORT("Unknown Analysis Distribution : " << fDist); } // Now setup each data distribution and description. std::string descrip = distdescript + "Target: CH \n" "Flux: 2 Files, MINERvA FHC numu;MINERvA FHC numubar \n" "Signal: Any event with 1 electron, any nucleons, and " "no other FS particles \n"; fSettings.SetDescription(descrip); fSettings.SetDataInput(GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCcoh/" + datafile); fSettings.SetCovarInput(GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCcoh/" + covarfile); fSettings.SetTitle(GeneralUtils::ParseToStr(titles, ";")[0]); fSettings.SetXTitle(GeneralUtils::ParseToStr(titles, ";")[1]); fSettings.SetYTitle(GeneralUtils::ParseToStr(titles, ";")[2]); return; } //******************************************************************** MINERvA_CCCOHPI_XSec_joint::MINERvA_CCCOHPI_XSec_joint(nuiskey samplekey) { //******************************************************************** // Define Sample Settings common to all data distributions fSettings = LoadSampleSettings(samplekey); fSettings.SetAllowedTypes("FIX,FREE,SHAPE/DIAG,FULL/NORM/MASK", "FIX/FULL"); fSettings.SetEnuRange(0.0, 20.0); fSettings.DefineAllowedTargets("C,H"); fSettings.DefineAllowedSpecies("numu"); SetupDataSettings(); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- fScaleFactor = 0.0; // Plot Setup ------------------------------------------------------- SetDataFromTextFile(fSettings.GetDataInput()); SetCovarFromMultipleTextFiles(fSettings.GetCovarInput()); // Setup Sub Measurements // ------------------------------------------------------- SetupSubMeasurements(); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CCCOHPI_XSec_joint::SetupSubMeasurements() { //******************************************************************** // Get parsed input files if (fSubInFiles.size() != 2) { - QTHROW("MINERvA Joint requires input files in format: nu;antinu"); + NUIS_ABORT("MINERvA Joint requires input files in format: nu;antinu"); } std::string inFileNeutrino = fSubInFiles.at(0); std::string inFileAntineutrino = fSubInFiles.at(1); // Create some config keys nuiskey nukey = Config::CreateKey("sample"); nukey.SetS("input", inFileNeutrino); nukey.SetS("type", fSettings.GetS("type")); nuiskey antinukey = Config::CreateKey("sample"); antinukey.SetS("input", inFileAntineutrino); antinukey.SetS("type", fSettings.GetS("type")); // Create samples for given DIST switch (fDist) { case kEpi: nukey.SetS("name", "MINERvA_CCCOHPI_XSec_1DEpi_nu"); MIN_nu = new MINERvA_CCCOHPI_XSec_1DEpi_nu(nukey); antinukey.SetS("name", "MINERvA_CCCOHPI_XSec_1DEpi_antinu"); MIN_anu = new MINERvA_CCCOHPI_XSec_1DEpi_antinu(antinukey); break; case kth: nukey.SetS("name", "MINERvA_CCCOHPI_XSec_1Dth_nu"); MIN_nu = new MINERvA_CCCOHPI_XSec_1Dth_nu(nukey); antinukey.SetS("name", "MINERvA_CCCOHPI_XSec_1Dth_antinu"); MIN_anu = new MINERvA_CCCOHPI_XSec_1Dth_antinu(antinukey); break; case kEnu: nukey.SetS("name", "MINERvA_CCCOHPI_XSec_1DEnu_nu"); MIN_nu = new MINERvA_CCCOHPI_XSec_1DEnu_nu(nukey); antinukey.SetS("name", "MINERvA_CCCOHPI_XSec_1DEnu_antinu"); MIN_anu = new MINERvA_CCCOHPI_XSec_1DEnu_antinu(antinukey); break; case kQ2: nukey.SetS("name", "MINERvA_CCCOHPI_XSec_1DQ2_nu"); MIN_nu = new MINERvA_CCCOHPI_XSec_1DQ2_nu(nukey); antinukey.SetS("name", "MINERvA_CCCOHPI_XSec_1DQ2_antinu"); MIN_anu = new MINERvA_CCCOHPI_XSec_1DQ2_antinu(antinukey); break; } // Add to chain for processing fSubChain.clear(); fSubChain.push_back(MIN_anu); fSubChain.push_back(MIN_nu); } //******************************************************************** void MINERvA_CCCOHPI_XSec_joint::MakePlots() { //******************************************************************** TH1D *MIN_nu_mc = (TH1D *)MIN_nu->GetMCHistogram(); TH1D *MIN_anu_mc = (TH1D *)MIN_anu->GetMCHistogram(); int count = 0; for (int i = 0; i < MIN_nu_mc->GetNbinsX(); i++) { fMCHist->SetBinContent(count + 1, MIN_nu_mc->GetBinContent(i + 1)); fMCHist->SetBinError(count + 1, MIN_nu_mc->GetBinError(i + 1)); fMCHist->GetXaxis()->SetBinLabel(count + 1, GeneralUtils::IntToStr(count + 1).c_str()); count++; } for (int i = 0; i < MIN_anu_mc->GetNbinsX(); i++) { fMCHist->SetBinContent(count + 1, MIN_anu_mc->GetBinContent(i + 1)); fMCHist->SetBinError(count + 1, MIN_anu_mc->GetBinError(i + 1)); fMCHist->GetXaxis()->SetBinLabel(count + 1, GeneralUtils::IntToStr(count + 1).c_str()); count++; } return; } diff --git a/src/MINERvA/MINERvA_CCDIS_XSec_1DEnu_nu.cxx b/src/MINERvA/MINERvA_CCDIS_XSec_1DEnu_nu.cxx index d22903a..a1605bb 100644 --- a/src/MINERvA/MINERvA_CCDIS_XSec_1DEnu_nu.cxx +++ b/src/MINERvA/MINERvA_CCDIS_XSec_1DEnu_nu.cxx @@ -1,130 +1,130 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_CCDIS_XSec_1DEnu_nu.h" #include "MINERvA_SignalDef.h" //******************************************************************** MINERvA_CCDIS_XSec_1DEnu_nu::MINERvA_CCDIS_XSec_1DEnu_nu(std::string name, std::string inputfile, std::string type) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "MINERvA_CCDIS_XSec_1DEnu_nu sample."; // Setup common settings fSettings = LoadSampleSettings(name, inputfile, type); fSettings.SetDescription(descrip); fSettings.SetXTitle("E_{#nu} (GeV)"); fSettings.SetYTitle("d#sigma/dE_{#nu} (cm^{2}/GeV/nucleon)"); fSettings.SetAllowedTypes("FIX/DIAG/MASK", "FIX/DIAG"); fSettings.SetEnuRange(5.0, 50.0); fSettings.DefineAllowedTargets("Pb,Fe,C,H"); fSettings.DefineAllowedSpecies("numu"); fSettings.SetTitle("MINERvA_CCDIS_XSec_1DEnu_nu"); target = ""; if (name.find("C12") != std::string::npos) target = "C12"; else if (name.find("Fe56") != std::string::npos) target = "Fe56"; else if (name.find("Pb208") != std::string::npos) target = "Pb208"; if (name.find("DEN") != std::string::npos) target = "CH"; if (target == "") { - QERROR(WRN, "target " << target << " was not found!"); + NUIS_ERR(WRN, "target " << target << " was not found!"); } FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = (GetEventHistogram()->Integral("width") * 1E-38 / (fNEvents + 0.)) / this->TotalIntegratedFlux(); // Plot Setup ------------------------------------------------------- double binsx[8] = {5.00, 10.00, 15.00, 20.00, 25.00, 30.00, 40.00, 50.00}; CreateDataHistogram(7, binsx); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CCDIS_XSec_1DEnu_nu::FillEventVariables(FitEvent *event) { //******************************************************************** if (event->NumFSParticle(13) == 0) return; TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; // Need to calculate Q2 and W using the MINERvA method double Enu = Pnu.E() / 1000.; double Emu = Pmu.E() / 1000.; double theta = FitUtils::th(Pnu, Pmu); Q2 = 4 * Enu * Emu * sin(theta / 2.) * sin(theta / 2.); W = sqrt(PhysConst::mass_nucleon * PhysConst::mass_nucleon + 2 * PhysConst::mass_nucleon * (Enu - Emu) - Q2); fXVar = Enu; return; } //******************************************************************** bool MINERvA_CCDIS_XSec_1DEnu_nu::isSignal(FitEvent *event) { //******************************************************************* if (!SignalDef::isCCINC(event, 14, this->EnuMin, this->EnuMax)) return false; // Restrict the phase space to theta < 17 degrees if (!SignalDef::IsRestrictedAngle(event, 14, 13, 17)) return false; if (Q2 < 1.0) return false; if (W < 2.0) return false; return true; }; //******************************************************************** void MINERvA_CCDIS_XSec_1DEnu_nu::ScaleEvents() { //******************************************************************** // Get rid of this because it causes odd behaviour Measurement1D::ScaleEvents(); // this->fMCHist->Scale(this->fScaleFactor, "width"); // // Proper error scaling - ROOT Freaks out with xsec weights sometimes // for(int i=0; ifMCStat->GetNbinsX();i++) { // if (this->fMCStat->GetBinContent(i+1) != 0) // this->fMCHist->SetBinError(i+1, this->fMCHist->GetBinContent(i+1) * // this->fMCStat->GetBinError(i+1) / this->fMCStat->GetBinContent(i+1) ); // else this->fMCHist->SetBinError(i+1, this->fMCHist->Integral()); // } } diff --git a/src/MINERvA/MINERvA_CCDIS_XSec_1DEnu_ratio.cxx b/src/MINERvA/MINERvA_CCDIS_XSec_1DEnu_ratio.cxx index f5476ab..5baa811 100644 --- a/src/MINERvA/MINERvA_CCDIS_XSec_1DEnu_ratio.cxx +++ b/src/MINERvA/MINERvA_CCDIS_XSec_1DEnu_ratio.cxx @@ -1,148 +1,148 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_CCDIS_XSec_1DEnu_ratio.h" #include "MINERvA_SignalDef.h" //******************************************************************** MINERvA_CCDIS_XSec_1DEnu_ratio::MINERvA_CCDIS_XSec_1DEnu_ratio( nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "MINERvA_CCDIS_XSec_1DEnu_ratio sample."; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("E_{#nu} (GeV)"); fSettings.SetYTitle(" d#sigma/dE_{#nu} (cm^{2}/GeV/nucleon)"); fSettings.SetAllowedTypes("FIX/DIAG,FULL/MASK", "FIX/FULL"); fSettings.SetEnuRange(5.0, 50.0); // CCQELike plot information fSettings.SetTitle("MINERvA_CCDIS_XSec_1DEnu_ratio"); fIsRatio = true; nBins = 7; target = ""; if (fSettings.Found("name", "C12")) target = "C12"; else if (fSettings.Found("name", "Fe56")) target = "Fe56"; else if (fSettings.Found("name", "Pb208")) target = "Pb208"; else { - QTHROW("target " << target << " was not found!"); + NUIS_ABORT("target " << target << " was not found!"); } fSettings.SetDataInput(GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCDIS/CCDIS_" + target + "_CH_ratio_Enu_data.csv"); fSettings.SetCovarInput( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCDIS/CCDIS_" + target + "_CH_ratio_Enu_stat.csv;" + GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCDIS/CCDIS_" + target + "_CH_ratio_Enu_syst.csv"); FinaliseSampleSettings(); // Get parsed input files if (fSubInFiles.size() != 2) { - QTHROW("MINERvA CCDIS ratio requires input files in format: " + NUIS_ABORT("MINERvA CCDIS ratio requires input files in format: " "NUMERATOR;DENOMINATOR"); } std::string inFileNUM = fSubInFiles.at(0); std::string inFileDEN = fSubInFiles.at(1); // Scaling Setup --------------------------------------------------- // Ratio of sub classes so non needed // Plot Setup ------------------------------------------------------- SetDataFromTextFile(fSettings.GetDataInput()); SetCovarFromMultipleTextFiles(fSettings.GetCovarInput()); // Need to overlay the sqrt covariance diagonals onto the data histogram StatUtils::SetDataErrorFromCov(fDataHist, fFullCovar); // Need to scale the covariance by 1E-76... this cancels with the factor of // 1E76 introduced in StatUtils::GetChi2FromCov Who says two wrongs don't make // a right ScaleCovar(1E76); // Setup Experiments ------------------------------------------------------- std::string type = samplekey.GetS("type"); NUM = new MINERvA_CCDIS_XSec_1DEnu_nu( "MINERvA_CCDIS_XSec_1DEnu_" + target + "_CH_NUM", inFileNUM, type); DEN = new MINERvA_CCDIS_XSec_1DEnu_nu( "MINERvA_CCDIS_XSec_1DEnu_" + target + "_CH_DEN", inFileDEN, type); NUM->SetNoData(); DEN->SetNoData(); // Add to chain for processing this->fSubChain.clear(); this->fSubChain.push_back(NUM); this->fSubChain.push_back(DEN); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CCDIS_XSec_1DEnu_ratio::MakePlots() { //******************************************************************** UInt_t sample = 0; for (std::vector::const_iterator expIter = this->fSubChain.begin(); expIter != this->fSubChain.end(); expIter++) { MeasurementBase *exp = static_cast(*expIter); if (sample == 0) this->NUM = static_cast(exp); else if (sample == 1) this->DEN = static_cast(exp); else break; sample++; } // Now make the ratio histogram TH1D *NUM_MC = (TH1D *)this->NUM->GetMCList().at(0)->Clone(); TH1D *DEN_MC = (TH1D *)this->DEN->GetMCList().at(0)->Clone(); for (int i = 0; i < nBins; ++i) { double binVal = 0; double binErr = 0; if (DEN_MC->GetBinContent(i + 1) && NUM_MC->GetBinContent(i + 1)) { binVal = NUM_MC->GetBinContent(i + 1) / DEN_MC->GetBinContent(i + 1); double fractErrNUM = NUM_MC->GetBinError(i + 1) / NUM_MC->GetBinContent(i + 1); double fractErrDEN = DEN_MC->GetBinError(i + 1) / DEN_MC->GetBinContent(i + 1); binErr = binVal * sqrt(fractErrNUM * fractErrNUM + fractErrDEN * fractErrDEN); } this->fMCHist->SetBinContent(i + 1, binVal); this->fMCHist->SetBinError(i + 1, binErr); } return; } diff --git a/src/MINERvA/MINERvA_CCDIS_XSec_1Dx_nu.cxx b/src/MINERvA/MINERvA_CCDIS_XSec_1Dx_nu.cxx index 6cca42a..97bf4b5 100644 --- a/src/MINERvA/MINERvA_CCDIS_XSec_1Dx_nu.cxx +++ b/src/MINERvA/MINERvA_CCDIS_XSec_1Dx_nu.cxx @@ -1,130 +1,130 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_CCDIS_XSec_1Dx_nu.h" #include "MINERvA_SignalDef.h" //******************************************************************** MINERvA_CCDIS_XSec_1Dx_nu::MINERvA_CCDIS_XSec_1Dx_nu(std::string name, std::string inputfile, std::string type) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "MINERvA_CCDIS_XSec_1Dx_nu sample."; // Setup common settings fSettings = LoadSampleSettings(name, inputfile, type); fSettings.SetDescription(descrip); fSettings.SetXTitle("Reconstructed Bjorken x"); fSettings.SetYTitle("d#sigma/dx (cm^{2}/nucleon)"); fSettings.SetAllowedTypes("FIX/DIAG/MASK", "FIX/DIAG"); fSettings.SetEnuRange(5.0, 50.0); fSettings.DefineAllowedTargets("Pb,Fe,C,H"); fSettings.DefineAllowedSpecies("numu"); fSettings.SetTitle("MINERvA_CCDIS_XSec_1Dx_nu"); target = ""; if (name.find("C12") != std::string::npos) target = "C12"; else if (name.find("Fe56") != std::string::npos) target = "Fe56"; else if (name.find("Pb208") != std::string::npos) target = "Pb208"; if (name.find("DEN") != std::string::npos) target = "CH"; if (target == "") { - QTHROW("target " << target << " was not found!"); + NUIS_ABORT("target " << target << " was not found!"); } FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = (GetEventHistogram()->Integral("width") * 1E-38 / (fNEvents + 0.)) / this->TotalIntegratedFlux(); // Plot Setup ------------------------------------------------------- double binsx[6] = {0.00, 0.10, 0.20, 0.30, 0.40, 0.75}; CreateDataHistogram(5, binsx); FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CCDIS_XSec_1Dx_nu::FillEventVariables(FitEvent *event) { //******************************************************************** if (event->NumFSParticle(13) == 0) return; TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; // Need to calculate Q2 and W using the MINERvA method double Enu = Pnu.E() / 1000.; double Emu = Pmu.E() / 1000.; double theta = FitUtils::th(Pnu, Pmu); Q2 = 4 * Enu * Emu * sin(theta / 2.) * sin(theta / 2.); W = sqrt(PhysConst::mass_nucleon * PhysConst::mass_nucleon + 2 * PhysConst::mass_nucleon * (Enu - Emu) - Q2); fXVar = Q2 / (2 * PhysConst::mass_nucleon * (Enu - Emu)); return; } //******************************************************************** bool MINERvA_CCDIS_XSec_1Dx_nu::isSignal(FitEvent *event) { //******************************************************************* // Only look at numu events if (!SignalDef::isCCINC(event, 14, EnuMin, EnuMax)) return false; // Restrict the phase space to theta < 17 degrees if (!SignalDef::IsRestrictedAngle(event, 14, 13, 17)) return false; if (Q2 < 1.0) return false; if (W < 2.0) return false; return true; }; //******************************************************************** void MINERvA_CCDIS_XSec_1Dx_nu::ScaleEvents() { //******************************************************************** Measurement1D::ScaleEvents(); // this->fDataHist = (TH1D*)this->GetMCList().at(0)->Clone(); // this->fMCHist->Scale(this->fScaleFactor, "width"); // // Proper error scaling - ROOT Freaks out with xsec weights sometimes // for(int i=0; ifMCStat->GetNbinsX();i++) { // if (this->fMCStat->GetBinContent(i+1) != 0) // this->fMCHist->SetBinError(i+1, this->fMCHist->GetBinContent(i+1) * // this->fMCStat->GetBinError(i+1) / this->fMCStat->GetBinContent(i+1) ); // else this->fMCHist->SetBinError(i+1, this->fMCHist->Integral()); // } } diff --git a/src/MINERvA/MINERvA_CCDIS_XSec_1Dx_ratio.cxx b/src/MINERvA/MINERvA_CCDIS_XSec_1Dx_ratio.cxx index 7236b8f..c3ca9e1 100644 --- a/src/MINERvA/MINERvA_CCDIS_XSec_1Dx_ratio.cxx +++ b/src/MINERvA/MINERvA_CCDIS_XSec_1Dx_ratio.cxx @@ -1,147 +1,147 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_CCDIS_XSec_1Dx_ratio.h" #include "MINERvA_SignalDef.h" //******************************************************************** MINERvA_CCDIS_XSec_1Dx_ratio::MINERvA_CCDIS_XSec_1Dx_ratio(nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "MINERvA_CCDIS_XSec_1Dx_ratio sample."; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("Reconstructed Bjorken x"); fSettings.SetYTitle("d#sigma/dx (cm^{2}/nucleon)"); fSettings.SetAllowedTypes("FIX/DIAG,FULL/MASK", "FIX/FULL"); fSettings.SetEnuRange(5.0, 50.0); // CCQELike plot information fSettings.SetTitle("MINERvA_CCDIS_XSec_1Dx_ratio"); fIsRatio = true; nBins = 5; target = ""; if (fSettings.Found("name", "C12")) target = "C12"; else if (fSettings.Found("name", "Fe56")) target = "Fe56"; else if (fSettings.Found("name", "Pb208")) target = "Pb208"; else { - QTHROW("target " << target << " was not found!"); + NUIS_ABORT("target " << target << " was not found!"); } fSettings.SetDataInput(GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCDIS/CCDIS_" + target + "_CH_ratio_x_data.csv"); fSettings.SetCovarInput( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCDIS/CCDIS_" + target + "_CH_ratio_x_stat.csv;" + GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCDIS/CCDIS_" + target + "_CH_ratio_x_syst.csv"); FinaliseSampleSettings(); // Get parsed input files if (fSubInFiles.size() != 2) { - QTHROW("MINERvA CCDIS ratio requires input files in format: " + NUIS_ABORT("MINERvA CCDIS ratio requires input files in format: " "NUMERATOR;DENOMINATOR"); } std::string inFileNUM = fSubInFiles.at(0); std::string inFileDEN = fSubInFiles.at(1); // Scaling Setup --------------------------------------------------- // Ratio of sub classes so non needed // Plot Setup ------------------------------------------------------- SetDataFromTextFile(fSettings.GetDataInput()); SetCovarFromMultipleTextFiles(fSettings.GetCovarInput()); // Need to overlay the sqrt covariance diagonals (*1E-38) onto the data // histogram StatUtils::SetDataErrorFromCov(fDataHist, fFullCovar); // Need to scale the covariance by 1E-76... this cancels with the factor of // 1E76 introduced in StatUtils::GetChi2FromCov Who says two wrongs don't make // a right ScaleCovar(1E76); // Setup Experiments ------------------------------------------------------- std::string type = samplekey.GetS("type"); NUM = new MINERvA_CCDIS_XSec_1Dx_nu( "MINERvA_CCDIS_XSec_1Dx_" + target + "_CH_NUM", inFileNUM, type); DEN = new MINERvA_CCDIS_XSec_1Dx_nu( "MINERvA_CCDIS_XSec_1Dx_" + target + "_CH_DEN", inFileDEN, type); NUM->SetNoData(); DEN->SetNoData(); // Add to chain for processing this->fSubChain.clear(); this->fSubChain.push_back(NUM); this->fSubChain.push_back(DEN); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CCDIS_XSec_1Dx_ratio::MakePlots() { //******************************************************************** UInt_t sample = 0; for (std::vector::const_iterator expIter = this->fSubChain.begin(); expIter != this->fSubChain.end(); expIter++) { MeasurementBase *exp = static_cast(*expIter); if (sample == 0) this->NUM = static_cast(exp); else if (sample == 1) this->DEN = static_cast(exp); else break; sample++; } // Now make the ratio histogram TH1D *NUM_MC = (TH1D *)this->NUM->GetMCList().at(0)->Clone(); TH1D *DEN_MC = (TH1D *)this->DEN->GetMCList().at(0)->Clone(); for (int i = 0; i < nBins; ++i) { double binVal = 0; double binErr = 0; if (DEN_MC->GetBinContent(i + 1) && NUM_MC->GetBinContent(i + 1)) { binVal = NUM_MC->GetBinContent(i + 1) / DEN_MC->GetBinContent(i + 1); double fractErrNUM = NUM_MC->GetBinError(i + 1) / NUM_MC->GetBinContent(i + 1); double fractErrDEN = DEN_MC->GetBinError(i + 1) / DEN_MC->GetBinContent(i + 1); binErr = binVal * sqrt(fractErrNUM * fractErrNUM + fractErrDEN * fractErrDEN); } this->fMCHist->SetBinContent(i + 1, binVal); this->fMCHist->SetBinError(i + 1, binErr); } return; } diff --git a/src/MINERvA/MINERvA_CCNpip_XSec_1DTpi_nu.cxx b/src/MINERvA/MINERvA_CCNpip_XSec_1DTpi_nu.cxx index 25be198..7346525 100644 --- a/src/MINERvA/MINERvA_CCNpip_XSec_1DTpi_nu.cxx +++ b/src/MINERvA/MINERvA_CCNpip_XSec_1DTpi_nu.cxx @@ -1,296 +1,296 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_CCNpip_XSec_1DTpi_nu.h" #include "MINERvA_SignalDef.h" //******************************************************************** MINERvA_CCNpip_XSec_1DTpi_nu::MINERvA_CCNpip_XSec_1DTpi_nu(nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "MINERvA_CCNpip_XSec_1DTpi_nu sample. \n" "Target: CH \n" "Flux: MINERvA Forward Horn Current nue + nuebar \n" "Signal: Any event with 1 electron, any nucleons, and " "no other FS particles \n"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("T_{#pi} (MeV)"); fSettings.SetYTitle("(1/T#Phi) dN_{#pi}/dT_{#pi} (cm^{2}/MeV/nucleon)"); fSettings.SetAllowedTypes("FIX,FREE,SHAPE/DIAG,FULL/NORM/MASK", "FIX/FULL"); fSettings.SetEnuRange(1.5, 10.0); fSettings.DefineAllowedTargets("C,H"); fSettings.DefineAllowedSpecies("numu"); fFullPhaseSpace = !fSettings.Found("name", "_20deg"); fFluxCorrection = fSettings.Found("name", "fluxcorr"); fUpdatedData = !fSettings.Found("name", "2015"); fSettings.SetTitle("MINERvA_CCNpip_XSec_1DTpi_nu"); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = GetEventHistogram()->Integral("width") * double(1E-38) / double(fNEvents) / TotalIntegratedFlux("width"); // Plot Setup ------------------------------------------------------- // Full Phase Space if (fFullPhaseSpace) { // 2016 release if (fUpdatedData) { SetDataFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2016/nu-ccNpi+-xsec-pion-kinetic-energy.csv"); // MINERvA has the error quoted as a percentage of the cross-section // Need to make this into an absolute error before we go from correlation // matrix -> covariance matrix since it depends on the error in the ith // bin for (int i = 0; i < fDataHist->GetNbinsX() + 1; i++) { fDataHist->SetBinError(i + 1, fDataHist->GetBinContent(i + 1) * (fDataHist->GetBinError(i + 1) / 100.)); } // This is a correlation matrix, not covariance matrix, so needs to be // converted SetCorrelationFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2016/" "nu-ccNpi+-correlation-pion-kinetic-energy.csv"); // 2015 release } else { // If we're doing shape only if (fIsShape) { SetDataFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2015/MINERvA_CCNpi_Tpi_shape.txt"); SetCorrelationFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2015/MINERvA_CCNpi_Tpi_shape_cov.txt"); // If we're doing full cross-section } else { SetDataFromTextFile(GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2015/MINERvA_CCNpi_Tpi.txt"); SetCorrelationFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2015/MINERvA_CCNpi_Tpi_cov.txt"); } } // Restricted Phase Space } else { // Only 2015 data released restricted muon phase space cross-section // unfortunately if (fUpdatedData) { - QTHROW(fName << " has no updated 2016 data for restricted phase space! " + NUIS_ABORT(fName << " has no updated 2016 data for restricted phase space! " "Using 2015 data."); } // If we're using the shape only data if (fIsShape) { SetDataFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2015/MINERvA_CCNpi_Tpi_20deg_shape.txt"); SetCorrelationFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2015/MINERvA_CCNpi_Tpi_20deg_shape_cov.txt"); // Or total cross-section } else { SetDataFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2015/MINERvA_CCNpi_Tpi_20deg.txt"); SetCorrelationFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2015/MINERvA_CCNpi_Tpi_20deg_cov.txt"); } } // Scale the MINERvA data to account for the flux difference // Adjust MINERvA data to flux correction; roughly a 11% normalisation // increase in data Please change when MINERvA releases new data! if (fFluxCorrection) { for (int i = 0; i < fDataHist->GetNbinsX() + 1; i++) { fDataHist->SetBinContent(i + 1, fDataHist->GetBinContent(i + 1) * 1.11); } } // Make some auxillary helper plots onePions = (TH1D *)(fDataHist->Clone()); onePions->SetNameTitle((fName + "_1pions").c_str(), (fName + "_1pions" + fPlotTitles).c_str()); SetAutoProcessTH1(onePions, kCMD_Reset, kCMD_Scale, kCMD_Norm); twoPions = (TH1D *)(fDataHist->Clone()); twoPions->SetNameTitle((fName + "_2pions").c_str(), (fName + "_2pions;" + fPlotTitles).c_str()); SetAutoProcessTH1(twoPions, kCMD_Reset, kCMD_Scale, kCMD_Norm); threePions = (TH1D *)(fDataHist->Clone()); threePions->SetNameTitle((fName + "_3pions").c_str(), (fName + "_3pions" + fPlotTitles).c_str()); SetAutoProcessTH1(threePions, kCMD_Reset, kCMD_Scale, kCMD_Norm); morePions = (TH1D *)(fDataHist->Clone()); morePions->SetNameTitle((fName + "_4pions").c_str(), (fName + "_4pions" + fPlotTitles).c_str()); SetAutoProcessTH1(morePions, kCMD_Reset, kCMD_Scale, kCMD_Norm); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** // Here we have to fill for every pion we find in the event void MINERvA_CCNpip_XSec_1DTpi_nu::FillEventVariables(FitEvent *event) { //******************************************************************** if (event->NumFSParticle(211) == 0 && event->NumFSParticle(-211) == 0) return; if (event->NumFSParticle(13) == 0) return; // Need to make this use event boxes // Clear out the vectors GetPionBox()->Reset(); TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; // Loop over the particle stack for (unsigned int j = 2; j < event->Npart(); ++j) { // Only include alive particles if (event->GetParticleState(j) != kFinalState) continue; int PID = (event->PartInfo(j))->fPID; // Pick up the charged pions in the event if (abs(PID) == 211) { double ppi = FitUtils::T(event->PartInfo(j)->fP) * 1000.; GetPionBox()->fTpiVect.push_back(ppi); } } fXVar = 0; return; }; //******************************************************************** // The last bool refers to if we're using restricted phase space or not bool MINERvA_CCNpip_XSec_1DTpi_nu::isSignal(FitEvent *event) { //******************************************************************** // Last false refers to that this is NOT the restricted MINERvA phase space, // in which only forward-going muons are accepted return SignalDef::isCCNpip_MINERvA(event, EnuMin, EnuMax, !fFullPhaseSpace, !fUpdatedData); } //******************************************************************** // Need to override FillHistograms() here because we fill the histogram N_pion // times void MINERvA_CCNpip_XSec_1DTpi_nu::FillHistograms() { //******************************************************************** if (Signal) { unsigned int nPions = GetPionBox()->fTpiVect.size(); // Need to loop over all the pions in the sample for (size_t k = 0; k < nPions; ++k) { double tpi = GetPionBox()->fTpiVect[k]; this->fMCHist->Fill(tpi, Weight); this->fMCFine->Fill(tpi, Weight); this->fMCStat->Fill(tpi, 1.0); if (nPions == 1) { onePions->Fill(tpi, Weight); } else if (nPions == 2) { twoPions->Fill(tpi, Weight); } else if (nPions == 3) { threePions->Fill(tpi, Weight); } else if (nPions > 3) { morePions->Fill(tpi, Weight); } if (fMCHist_Modes) fMCHist_Modes->Fill(Mode, tpi, Weight); } } } //******************************************************************** void MINERvA_CCNpip_XSec_1DTpi_nu::ScaleEvents() { //******************************************************************** Measurement1D::ScaleEvents(); onePions->Scale(this->fScaleFactor, "width"); twoPions->Scale(this->fScaleFactor, "width"); threePions->Scale(this->fScaleFactor, "width"); morePions->Scale(this->fScaleFactor, "width"); return; } //******************************************************************** void MINERvA_CCNpip_XSec_1DTpi_nu::Write(std::string drawOpts) { //******************************************************************** Measurement1D::Write(drawOpts); // Make an auto processed pion stack // Draw the npions stack onePions->SetTitle("1#pi"); onePions->SetLineColor(kBlack); // onePions->SetFillStyle(0); onePions->SetFillColor(onePions->GetLineColor()); twoPions->SetTitle("2#pi"); twoPions->SetLineColor(kRed); // twoPions->SetFillStyle(0); twoPions->SetFillColor(twoPions->GetLineColor()); threePions->SetTitle("3#pi"); threePions->SetLineColor(kGreen); // threePions->SetFillStyle(0); threePions->SetFillColor(threePions->GetLineColor()); morePions->SetTitle(">3#pi"); morePions->SetLineColor(kBlue); // morePions->SetFillStyle(0); morePions->SetFillColor(morePions->GetLineColor()); THStack pionStack = THStack((fName + "_pionStack").c_str(), (fName + "_pionStack").c_str()); pionStack.Add(onePions); pionStack.Add(twoPions); pionStack.Add(threePions); pionStack.Add(morePions); pionStack.Write(); return; } diff --git a/src/MINERvA/MINERvA_CCNpip_XSec_1Dth_nu.cxx b/src/MINERvA/MINERvA_CCNpip_XSec_1Dth_nu.cxx index 08a05a8..1b219c2 100644 --- a/src/MINERvA/MINERvA_CCNpip_XSec_1Dth_nu.cxx +++ b/src/MINERvA/MINERvA_CCNpip_XSec_1Dth_nu.cxx @@ -1,288 +1,288 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_CCNpip_XSec_1Dth_nu.h" #include "MINERvA_SignalDef.h" //******************************************************************** MINERvA_CCNpip_XSec_1Dth_nu::MINERvA_CCNpip_XSec_1Dth_nu(nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "MINERvA_CCNpip_XSec_1Dth_nu sample. \n" "Target: CH \n" "Flux: MINERvA Forward Horn Current nue + nuebar \n" "Signal: Any event with 1 electron, any nucleons, and " "no other FS particles \n"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("#theta_{#pi} (degrees)"); fSettings.SetYTitle( "(1/T#Phi) dN_{#pi}/d#theta_{#pi} (cm^{2}/degrees/nucleon)"); fSettings.SetAllowedTypes("FIX,FREE,SHAPE/DIAG,FULL/NORM/MASK", "FIX/FULL"); fSettings.SetEnuRange(1.5, 10.0); fSettings.DefineAllowedTargets("C,H"); fSettings.DefineAllowedSpecies("numu"); fFullPhaseSpace = !fSettings.Found("name", "_20deg"); fFluxCorrection = fSettings.Found("name", "fluxcorr"); fUpdatedData = !fSettings.Found("name", "2015"); fSettings.SetTitle("MINERvA_CCNpip_XSec_1Dth_nu"); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = GetEventHistogram()->Integral("width") * double(1E-38) / double(fNEvents) / TotalIntegratedFlux("width"); // Plot Setup ------------------------------------------------------- // Full Phase Space if (fFullPhaseSpace) { // 2016 release data if (fUpdatedData) { SetDataFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2016/nu-ccNpi+-xsec-pion-angle.csv"); // MINERvA has the error quoted as a percentage of the cross-section // Need to make this into an absolute error before we go from correlation // matrix -> covariance matrix since it depends on the error in the ith // bin for (int i = 0; i < fDataHist->GetNbinsX() + 1; i++) { fDataHist->SetBinError(i + 1, fDataHist->GetBinContent(i + 1) * (fDataHist->GetBinError(i + 1) / 100.)); } // This is a correlation matrix! but it's all fixed in // SetCovarMatrixFromText SetCorrelationFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2016/nu-ccNpi+-correlation-pion-angle.csv"); // 2015 release data } else { // 2015 release allows for shape comparisons if (fIsShape) { SetDataFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2015/MINERvA_CCNpi_th_shape.txt"); SetCorrelationFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2015/MINERvA_CCNpi_th_shape_cov.txt"); } else { SetDataFromTextFile(GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2015/MINERvA_CCNpi_th.txt"); SetCorrelationFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2015/MINERvA_CCNpi_th_cov.txt"); } } // Restricted Phase Space Data } else { // 2016 release data unfortunately not released in 20degree forward-going, // revert to 2015 data if (fUpdatedData) { - QTHROW(fName + NUIS_ABORT(fName << " has no updated 2016 data for restricted phase space! Using " "2015 data."); } // Only 2015 20deg data if (fIsShape) { SetDataFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2015/MINERvA_CCNpi_th_20deg_shape.txt"); SetCorrelationFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2015/MINERvA_CCNpi_th_20deg_shape_cov.txt"); } else { SetDataFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2015/MINERvA_CCNpi_th_20deg.txt"); SetCorrelationFromTextFile( GeneralUtils::GetTopLevelDir() + "/data/MINERvA/CCNpip/2015/MINERvA_CCNpi_th_20deg_cov.txt"); } } // Scale the MINERvA data to account for the flux difference // Adjust MINERvA data to flux correction; roughly a 11% normalisation // increase in data Please change when MINERvA releases new data! if (fFluxCorrection) { for (int i = 0; i < fDataHist->GetNbinsX() + 1; i++) { fDataHist->SetBinContent(i + 1, fDataHist->GetBinContent(i + 1) * 1.11); } } // Make some auxillary helper plots onePions = (TH1D *)(fDataHist->Clone()); onePions->SetNameTitle((fName + "_1pions").c_str(), (fName + "_1pions" + fPlotTitles).c_str()); SetAutoProcessTH1(onePions, kCMD_Reset, kCMD_Scale, kCMD_Norm); twoPions = (TH1D *)(fDataHist->Clone()); twoPions->SetNameTitle((fName + "_2pions").c_str(), (fName + "_2pions;" + fPlotTitles).c_str()); SetAutoProcessTH1(twoPions, kCMD_Reset, kCMD_Scale, kCMD_Norm); threePions = (TH1D *)(fDataHist->Clone()); threePions->SetNameTitle((fName + "_3pions").c_str(), (fName + "_3pions" + fPlotTitles).c_str()); SetAutoProcessTH1(threePions, kCMD_Reset, kCMD_Scale, kCMD_Norm); morePions = (TH1D *)(fDataHist->Clone()); morePions->SetNameTitle((fName + "_4pions").c_str(), (fName + "_4pions" + fPlotTitles).c_str()); SetAutoProcessTH1(morePions, kCMD_Reset, kCMD_Scale, kCMD_Norm); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; // ******************************************** // Fill the event variables // Here we want to fill the angle for every pion we can find in the event void MINERvA_CCNpip_XSec_1Dth_nu::FillEventVariables(FitEvent *event) { // ******************************************** if (event->NumFSParticle(211) == 0 && event->NumFSParticle(-211) == 0) return; if (event->NumFSParticle(13) == 0) return; GetBox()->Reset(); TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; TLorentzVector Ppip; // Loop over the particle stack for (unsigned int j = 2; j < event->Npart(); ++j) { // Only include alive particles if ((event->PartInfo(j))->fIsAlive <= 0) continue; if ((event->PartInfo(j))->fNEUTStatusCode != 0) continue; int PID = (event->PartInfo(j))->fPID; // Select highest momentum (energy) charged pion if (abs(PID) == 211) { Ppip = (event->PartInfo(j))->fP; double th = (180. / M_PI) * FitUtils::th(Pnu, Ppip); GetPionBox()->fthpiVect.push_back(th); } } fXVar = 0; return; }; //******************************************************************** // The signal definition for MINERvA CCNpi+ // Last bool refers to if we're selecting on the full phase space or not bool MINERvA_CCNpip_XSec_1Dth_nu::isSignal(FitEvent *event) { //******************************************************************** return SignalDef::isCCNpip_MINERvA(event, EnuMin, EnuMax, !fFullPhaseSpace, !fUpdatedData); } //******************************************************************** // Need to override FillHistograms() here because we fill the histogram N_pion // times void MINERvA_CCNpip_XSec_1Dth_nu::FillHistograms() { //******************************************************************** if (Signal) { unsigned int nPions = GetPionBox()->fthpiVect.size(); // Need to loop over all the pions in the event for (size_t k = 0; k < nPions; ++k) { double th = GetPionBox()->fthpiVect[k]; this->fMCHist->Fill(th, Weight); this->fMCFine->Fill(th, Weight); this->fMCStat->Fill(th, 1.0); if (nPions == 1) { onePions->Fill(th, Weight); } else if (nPions == 2) { twoPions->Fill(th, Weight); } else if (nPions == 3) { threePions->Fill(th, Weight); } else if (nPions > 3) { morePions->Fill(th, Weight); } if (fMCHist_Modes) fMCHist_Modes->Fill(Mode, th, Weight); // PlotUtils::FillNeutModeArray(fMCHist_PDG, Mode, th, Weight); } } return; } //******************************************************************** void MINERvA_CCNpip_XSec_1Dth_nu::Write(std::string drawOpts) { //******************************************************************** Measurement1D::Write(drawOpts); // Draw the npions stack onePions->SetTitle("1#pi"); onePions->SetLineColor(kBlack); // onePions->SetFillStyle(0); onePions->SetFillColor(onePions->GetLineColor()); twoPions->SetTitle("2#pi"); twoPions->SetLineColor(kRed); // twoPions->SetFillStyle(0); twoPions->SetFillColor(twoPions->GetLineColor()); threePions->SetTitle("3#pi"); threePions->SetLineColor(kGreen); // threePions->SetFillStyle(0); threePions->SetFillColor(threePions->GetLineColor()); morePions->SetTitle(">3#pi"); morePions->SetLineColor(kBlue); // morePions->SetFillStyle(0); morePions->SetFillColor(morePions->GetLineColor()); THStack pionStack = THStack((fName + "_pionStack").c_str(), (fName + "_pionStack").c_str()); pionStack.Add(onePions); pionStack.Add(twoPions); pionStack.Add(threePions); pionStack.Add(morePions); pionStack.Write(); return; } diff --git a/src/MINERvA/MINERvA_CCQE_XSec_1DQ2_antinu.cxx b/src/MINERvA/MINERvA_CCQE_XSec_1DQ2_antinu.cxx index 7b9cd83..386907b 100644 --- a/src/MINERvA/MINERvA_CCQE_XSec_1DQ2_antinu.cxx +++ b/src/MINERvA/MINERvA_CCQE_XSec_1DQ2_antinu.cxx @@ -1,209 +1,209 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_SignalDef.h" #include "MINERvA_CCQE_XSec_1DQ2_antinu.h" //******************************************************************** MINERvA_CCQE_XSec_1DQ2_antinu::MINERvA_CCQE_XSec_1DQ2_antinu( nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "MINERvA_CCQE_XSec_1DQ2_antinu sample. \n" "Target: CH \n" "Flux: MINERvA Forward Horn Current Numubar \n" "Signal: True CCQE/2p2h defined at the vertex level \n"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("Q^{2}_{QE} (GeV^{2})"); fSettings.SetYTitle("d#sigma/dQ_{QE}^{2} (cm^{2}/GeV^{2})"); fSettings.SetAllowedTypes("FIX,FREE,SHAPE/DIAG,FULL/NORM/MASK", "FIX/FULL"); fSettings.SetEnuRange(1.5, 10.0); fSettings.DefineAllowedTargets("C,H"); isFluxFix = !fSettings.Found("name", "_oldflux"); fullphasespace = !fSettings.Found("name", "_20deg"); // CCQELike plot information fSettings.SetTitle("MINERvA_CCQE_XSec_1DQ2_antinu"); fSaveExtra = FitPar::Config().GetParB("MINERvASaveExtraCCQE"); std::string basedir = FitPar::GetDataBase() + "/MINERvA/CCQE/"; std::string datafilename = ""; std::string covarfilename = ""; // Full Phase Space if (fullphasespace) { if (isFluxFix) { if (fIsShape) { - QERROR(WRN, + NUIS_ERR(WRN, "SHAPE likelihood comparison not available for MINERvA " << "datasets with fixed flux information. NUISANCE will " "scale MC to match " << "data normalization but full covariance will be used. "); } datafilename = "Q2QE_numubar_data_fluxfix.txt"; covarfilename = "Q2QE_numubar_covar_fluxfix.txt"; // Correlation Matrix } else { if (fIsShape) { datafilename = "Q2QE_numubar_data_SHAPE-extracted.txt"; covarfilename = "Q2QE_numubar_covar_SHAPE-extracted.txt"; // correlation } else { datafilename = "Q2QE_numubar_data.txt"; covarfilename = "Q2QE_numubar_covar.txt"; // Correlation } } // Restricted Phase Space } else { if (isFluxFix) { if (fIsShape) { - QERROR(WRN, + NUIS_ERR(WRN, "SHAPE likelihood comparison not available for MINERvA " << "datasets with fixed flux information. NUISANCE will " "scale MC to match " << "data normalization but full covariance will be used. "); } datafilename = "20deg_Q2QE_numubar_data_fluxfix.txt"; covarfilename = "20deg_Q2QE_numubar_covar_fluxfix.txt"; // Correlation } else { if (fIsShape) { datafilename = "20deg_Q2QE_numubar_data_SHAPE-extracted.txt"; covarfilename = "20deg_Q2QE_numubar_covar_SHAPE-extracted.txt"; // Correlation } else { datafilename = "20deg_Q2QE_numubar_data.txt"; covarfilename = "20deg_Q2QE_numubar_covar.txt"; // Correlation } } } fSettings.SetDataInput(basedir + datafilename); fSettings.SetCovarInput(basedir + covarfilename); fSettings.DefineAllowedSpecies("numu"); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = (GetEventHistogram()->Integral("width") * 1E-38 / (fNEvents + 0.)) * 13. / 7. / TotalIntegratedFlux(); // Plot Setup ------------------------------------------------------- SetDataFromTextFile(fSettings.GetDataInput()); SetCorrelationFromTextFile(fSettings.GetCovarInput()); if (fSaveExtra) { fExtra_Eav = new TH1D((fSettings.GetName() + "Eav").c_str(), "Eav", 30, 0.0, 1.0); fExtra_Eav_MODES = new MINERvAUtils::ModeStack( (fSettings.GetName() + "EavMODES").c_str(), "EavMODES", fExtra_Eav); // fExtra_Eav_MODES->SetReverseStack(); SetAutoProcess(fExtra_Eav); SetAutoProcess(fExtra_Eav_MODES); fExtra_EavQ2 = new TH2D((fSettings.GetName() + "EavQ2").c_str(), "EavQ2", 12, 0.0, 2.0, 50, 0.0, 1.0); fExtra_EavQ2_MODES = new MINERvAUtils::ModeStack( (fSettings.GetName() + "EavQ2MODES").c_str(), "EavQ2MODES", fExtra_EavQ2); // fExtra_EavQ2_MODES->SetReverseStack(); SetAutoProcess(fExtra_EavQ2); SetAutoProcess(fExtra_EavQ2_MODES); fEavQ2Cut = new TF1((fSettings.GetName() + "f1").c_str(), "0.03 + 0.3*x", 0.0, 2.0); SetAutoProcess(fEavQ2Cut); } // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CCQE_XSec_1DQ2_antinu::FillEventVariables(FitEvent *event) { //******************************************************************** if (event->NumFSParticle(-13) == 0) return; TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Pmu = event->GetHMFSParticle(-13)->fP; double ThetaMu = Pnu.Vect().Angle(Pmu.Vect()); double q2qe = FitUtils::Q2QErec(Pmu, cos(ThetaMu), 30., true); fXVar = q2qe; if (fSaveExtra) { double pm = 938.2720813; double pe = pm + 120.0; FitParticle *fakeproton = new FitParticle(0.0, 0.0, sqrt(pe * pe - pm * pm), pe, 2212, kFinalState); double range = MINERvAUtils::RangeInScintillator(fakeproton, 100); pm = 139.57018; pe = pm + 65; // FitParticle* fakepion = new FitParticle(0.0,0.0,sqrt(pe*pe-pm*pm), pe, // 211, kFinalState); double pionrange = // MINERvAUtils::RangeInScintillator(fakepion, 100); double Eav = 0.0; for (uint i = 0; i < event->NParticles(); i++) { if (event->GetParticleState(i) != kFinalState) continue; int pid = event->GetParticlePDG(i); double ParticleEav = 0.0; if (abs(pid) == 13) continue; if (pid != 2112 and pid != 22 and pid != 111) { ParticleEav = MINERvAUtils::GetEDepositOutsideRangeInScintillator( event->GetParticle(i), range) / 1.E3; } else if (pid == 22 or pid == 111) { ParticleEav = event->GetParticle(i)->fP.E() / 1.E3; } Eav += ParticleEav; } fExtra_Eav->Fill(Eav); fExtra_Eav_MODES->Fill(event->Mode, Eav); fExtra_EavQ2->Fill(q2qe, Eav); fExtra_EavQ2_MODES->Fill(event->Mode, q2qe, Eav); } return; } //******************************************************************** bool MINERvA_CCQE_XSec_1DQ2_antinu::isSignal(FitEvent *event) { //******************************************************************* return SignalDef::isCCQEnumubar_MINERvA(event, EnuMin, EnuMax, fullphasespace); } diff --git a/src/MINERvA/MINERvA_CCQE_XSec_1DQ2_joint.cxx b/src/MINERvA/MINERvA_CCQE_XSec_1DQ2_joint.cxx index c569a72..338396d 100644 --- a/src/MINERvA/MINERvA_CCQE_XSec_1DQ2_joint.cxx +++ b/src/MINERvA/MINERvA_CCQE_XSec_1DQ2_joint.cxx @@ -1,202 +1,202 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_CCQE_XSec_1DQ2_joint.h" #include "MINERvA_SignalDef.h" //******************************************************************** MINERvA_CCQE_XSec_1DQ2_joint::MINERvA_CCQE_XSec_1DQ2_joint(nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "MINERvA_CCQE_XSec_1DQ2_joint sample. \n" "Target: CH \n" "Flux: MINERvA Forward Horn Current nue + nuebar \n" "Signal: Any event with 1 electron, any nucleons, and " "no other FS particles \n"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("Q^{2}_{QE} (GeV^{2})"); fSettings.SetYTitle("d#sigma/dQ_{QE}^{2} (cm^{2}/GeV^{2})"); fSettings.SetAllowedTypes("FIX,FREE,SHAPE/DIAG,FULL/NORM/MASK", "FIX/FULL"); fSettings.SetEnuRange(1.5, 10.0); fSettings.DefineAllowedTargets("C,H"); isFluxFix = !fSettings.Found("name", "_oldflux"); fullphasespace = !fSettings.Found("name", "_20deg"); nBins = 16; fIsRatio = false; fIsSummed = false; fSaveSubMeas = true; // CCQELike plot information fSettings.SetTitle("MINERvA_CCQE_XSec_1DQ2_joint"); std::string basedir = FitPar::GetDataBase() + "/MINERvA/CCQE/"; std::string datafilename = ""; std::string covarfilename = ""; std::string neutrinoclass = ""; std::string antineutrinoclass = ""; // Full Phase Space if (fullphasespace) { if (isFluxFix) { if (fIsShape) { - QERROR(WRN, + NUIS_ERR(WRN, "SHAPE likelihood comparison not available for MINERvA " << "datasets with fixed flux information. NUISANCE will " "scale MC to match " << "data normalization but full covariance will be used. "); } datafilename = "Q2QE_joint_data_fluxfix.txt"; covarfilename = "Q2QE_joint_covar_fluxfix.txt"; neutrinoclass = "MINERvA_CCQE_XSec_1DQ2_nu_newflux"; antineutrinoclass = "MINERvA_CCQE_XSec_1DQ2_antinu_newflux"; } else { if (fIsShape) { datafilename = "Q2QE_joint_dataa_SHAPE-extracted.txt"; covarfilename = "Q2QE_joint_covara_SHAPE-extracted.txt"; } else { datafilename = "Q2QE_joint_data.txt"; covarfilename = "Q2QE_joint_covar.txt"; } neutrinoclass = "MINERvA_CCQE_XSec_1DQ2_nu"; antineutrinoclass = "MINERvA_CCQE_XSec_1DQ2_antinu"; } // Restricted Phase Space } else { if (isFluxFix) { if (fIsShape) { - QERROR(WRN, + NUIS_ERR(WRN, "SHAPE likelihood comparison not available for MINERvA " << "datasets with fixed flux information. NUISANCE will " "scale MC to match " << "data normalization but full covariance will be used. "); } datafilename = "20deg_Q2QE_joint_data_fluxfix.txt"; covarfilename = "20deg_Q2QE_joint_covar_fluxfix.txt"; neutrinoclass = "MINERvA_CCQE_XSec_1DQ2_nu_20deg_newflux"; antineutrinoclass = "MINERvA_CCQE_XSec_1DQ2_antinu_20deg_newflux"; } else { if (fIsShape) { datafilename = "20deg_Q2QE_joint_dataa_SHAPE-extracted.txt"; covarfilename = "20deg_Q2QE_joint_covara_SHAPE-extracted.txt"; } else { datafilename = "20deg_Q2QE_joint_data.txt"; covarfilename = "20deg_Q2QE_joint_covar.txt"; } neutrinoclass = "MINERvA_CCQE_XSec_1DQ2_nu_20deg"; antineutrinoclass = "MINERvA_CCQE_XSec_1DQ2_antinu_20deg"; } } fSettings.SetDataInput(basedir + datafilename); fSettings.SetCovarInput(basedir + covarfilename); fSettings.DefineAllowedSpecies("numu,numub"); std::cout << "Finalising sample settings for joint fit = " << fIsJoint << std::endl; FinaliseSampleSettings(); // Get parsed input files if (fSubInFiles.size() != 2) { - QTHROW("MINERvA Joint requires input files in format: antinu;nu"); + NUIS_ABORT("MINERvA Joint requires input files in format: antinu;nu"); } std::string inFileAntineutrino = fSubInFiles.at(0); std::string inFileNeutrino = fSubInFiles.at(1); // Push classes back into list for processing loop fSubChain.push_back(MIN_anu); fSubChain.push_back(MIN_nu); // Plot Setup ------------------------------------------------------- SetDataFromTextFile(fSettings.GetDataInput()); if (fullphasespace and isFluxFix) SetCovarFromTextFile(fSettings.GetCovarInput()); else { SetCorrelationFromTextFile(fSettings.GetCovarInput()); } // Setup Sub classes nuiskey antinukey = Config::CreateKey("sample"); antinukey.SetS("name", antineutrinoclass); antinukey.SetS("input", inFileAntineutrino); antinukey.SetS("type", fSettings.GetS("type")); MIN_anu = new MINERvA_CCQE_XSec_1DQ2_antinu(antinukey); nuiskey nukey = Config::CreateKey("sample"); nukey.SetS("name", neutrinoclass); nukey.SetS("input", inFileNeutrino); nukey.SetS("type", fSettings.GetS("type")); MIN_nu = new MINERvA_CCQE_XSec_1DQ2_nu(nukey); // Add to chain for processing this->fSubChain.clear(); this->fSubChain.push_back(MIN_anu); this->fSubChain.push_back(MIN_nu); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CCQE_XSec_1DQ2_joint::MakePlots() { //******************************************************************** UInt_t sample = 0; for (std::vector::const_iterator expIter = fSubChain.begin(); expIter != fSubChain.end(); expIter++) { MeasurementBase *exp = static_cast(*expIter); if (sample == 0) { MIN_anu = static_cast(exp); TH1D *MIN_anu_mc = (TH1D *)MIN_anu->GetMCList().at(0); for (int i = 0; i < 8; i++) { // std::cout << "Adding MIN_anu_MC " << i + 1 << " : " << i + 1 << " " // << MIN_anu_mc->GetBinContent(i + 1) << std::endl; fMCHist->SetBinContent(i + 1, MIN_anu_mc->GetBinContent(i + 1)); fMCHist->SetBinError(i + 1, MIN_anu_mc->GetBinError(i + 1)); } } else if (sample == 1) { MIN_nu = static_cast(exp); TH1D *MIN_nu_mc = (TH1D *)MIN_nu->GetMCList().at(0); for (int i = 0; i < 8; i++) { // std::cout << "Adding MIN_nu_MC " << i + 1 + 8 << " : " << i + 1 << " // " << MIN_nu_mc->GetBinContent(i + 1) << std::endl; fMCHist->SetBinContent(i + 1 + 8, MIN_nu_mc->GetBinContent(i + 1)); fMCHist->SetBinError(i + 1 + 8, MIN_nu_mc->GetBinError(i + 1)); } } sample++; } return; } diff --git a/src/MINERvA/MINERvA_CCQE_XSec_1DQ2_nu.cxx b/src/MINERvA/MINERvA_CCQE_XSec_1DQ2_nu.cxx index 614f47f..8868df1 100644 --- a/src/MINERvA/MINERvA_CCQE_XSec_1DQ2_nu.cxx +++ b/src/MINERvA/MINERvA_CCQE_XSec_1DQ2_nu.cxx @@ -1,211 +1,211 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_CCQE_XSec_1DQ2_nu.h" #include "MINERvA_SignalDef.h" //******************************************************************** MINERvA_CCQE_XSec_1DQ2_nu::MINERvA_CCQE_XSec_1DQ2_nu(nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "MINERvA_CCQE_XSec_1DQ2_nu sample. \n" "Target: CH \n" "Flux: MINERvA Forward Horn Current Numu \n" "Signal: True CCQE/2p2h defined at the vertex level \n"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("Q^{2}_{QE} (GeV^{2})"); fSettings.SetYTitle("d#sigma/dQ_{QE}^{2} (cm^{2}/GeV^{2})"); fSettings.SetAllowedTypes("FIX,FREE,SHAPE/DIAG,FULL/NORM/MASK", "FIX/FULL"); fSettings.SetEnuRange(1.5, 10.0); fSettings.DefineAllowedTargets("C,H"); isFluxFix = !fSettings.Found("name", "_oldflux"); fullphasespace = !fSettings.Found("name", "_20deg"); fSaveExtra = FitPar::Config().GetParB("MINERvASaveExtraCCQE"); // CCQELike plot information fSettings.SetTitle("MINERvA_CCQE_XSec_1DQ2_nu"); std::string basedir = FitPar::GetDataBase() + "/MINERvA/CCQE/"; std::string datafilename = ""; std::string covarfilename = ""; // Full Phase Space if (fullphasespace) { if (isFluxFix) { if (fIsShape) { - QERROR(WRN, + NUIS_ERR(WRN, "SHAPE likelihood comparison not available for MINERvA " << "datasets with fixed flux information. NUISANCE will " "scale MC to match " << "data normalization but full covariance will be used. "); } datafilename = "Q2QE_numu_data_fluxfix.txt"; covarfilename = "Q2QE_numu_covar_fluxfix.txt"; } else { if (fIsShape) { datafilename = "Q2QE_numu_data_SHAPE-extracted.txt"; covarfilename = "Q2QE_numu_covar_SHAPE-extracted.txt"; } else { datafilename = "Q2QE_numu_data.txt"; covarfilename = "Q2QE_numu_covar.txt"; } } // Restricted Phase Space } else { if (isFluxFix) { if (fIsShape) { - QERROR(WRN, + NUIS_ERR(WRN, "SHAPE likelihood comparison not available for MINERvA " << "datasets with fixed flux information. NUISANCE will " "scale MC to match " << "data normalization but full covariance will be used. "); } datafilename = "20deg_Q2QE_numu_data_fluxfix.txt"; covarfilename = "20deg_Q2QE_numu_covar_fluxfix.txt"; } else { if (fIsShape) { datafilename = "20deg_Q2QE_numu_data_SHAPE-extracted.txt"; covarfilename = "20deg_Q2QE_numu_covar_SHAPE-extracted.txt"; } else { datafilename = "20deg_Q2QE_numu_data.txt"; covarfilename = "20deg_Q2QE_numu_covar.txt"; } } } fSettings.SetDataInput(basedir + datafilename); fSettings.SetCovarInput(basedir + covarfilename); fSettings.DefineAllowedSpecies("numu"); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = (GetEventHistogram()->Integral("width") * 1E-38 * 13.0 / 6.0 / (fNEvents + 0.)) / TotalIntegratedFlux(); // Plot Setup ------------------------------------------------------- SetDataFromTextFile(fSettings.GetDataInput()); if (!isFluxFix or !fullphasespace) { SetCorrelationFromTextFile(fSettings.GetCovarInput()); } else { SetCovarFromTextFile(fSettings.GetCovarInput()); } if (fSaveExtra) { fExtra_Eav = new TH1D((fSettings.GetName() + "Eav").c_str(), "Eav", 30, 0.0, 1.0); fExtra_Eav_MODES = new MINERvAUtils::ModeStack( (fSettings.GetName() + "EavMODES").c_str(), "EavMODES", fExtra_Eav); // fExtra_Eav_MODES->SetReverseStack(); SetAutoProcess(fExtra_Eav); SetAutoProcess(fExtra_Eav_MODES); fExtra_EavQ2 = new TH2D((fSettings.GetName() + "EavQ2").c_str(), "EavQ2", 12, 0.0, 2.0, 50, 0.0, 1.0); fExtra_EavQ2_MODES = new MINERvAUtils::ModeStack( (fSettings.GetName() + "EavQ2MODES").c_str(), "EavQ2MODES", fExtra_EavQ2); // fExtra_EavQ2_MODES->SetReverseStack(); SetAutoProcess(fExtra_EavQ2); SetAutoProcess(fExtra_EavQ2_MODES); fEavQ2Cut = new TF1((fSettings.GetName() + "f1").c_str(), "0.03 + 0.3*x", 0.0, 2.0); SetAutoProcess(fEavQ2Cut); } // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CCQE_XSec_1DQ2_nu::FillEventVariables(FitEvent *event) { //******************************************************************** if (event->NumFSParticle(13) == 0) return; TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; double ThetaMu = Pnu.Vect().Angle(Pmu.Vect()); double q2qe = FitUtils::Q2QErec(Pmu, cos(ThetaMu), 34., true); // Set binning variable fXVar = q2qe; // Calculate from scratch the vertex size if (fSaveExtra) { double pm = 938.2720813; double pe = pm + 120.0; FitParticle *fakeproton = new FitParticle(0.0, 0.0, sqrt(pe * pe - pm * pm), pe, 2212, kFinalState); double range = MINERvAUtils::RangeInScintillator(fakeproton, 100); pm = 139.57018; pe = pm + 65; // FitParticle* fakepion = new FitParticle(0.0,0.0,sqrt(pe*pe-pm*pm), pe, // 211, kFinalState); double pionrange = // MINERvAUtils::RangeInScintillator(fakepion, 100); double Eav = 0.0; for (uint i = 0; i < event->NParticles(); i++) { if (event->GetParticleState(i) != kFinalState) continue; int pid = event->GetParticlePDG(i); double ParticleEav = 0.0; if (pid == 13) continue; if (pid != 2112 and pid != 22 and pid != 111) { ParticleEav = MINERvAUtils::GetEDepositOutsideRangeInScintillator( event->GetParticle(i), range) / 1.E3; } else if (pid == 22 or pid == 111) { ParticleEav = event->GetParticle(i)->fP.E() / 1.E3; } Eav += ParticleEav; } fExtra_Eav->Fill(Eav); fExtra_Eav_MODES->Fill(event->Mode, Eav); fExtra_EavQ2->Fill(q2qe, Eav); fExtra_EavQ2_MODES->Fill(event->Mode, q2qe, Eav); } return; } //******************************************************************** bool MINERvA_CCQE_XSec_1DQ2_nu::isSignal(FitEvent *event) { //******************************************************************* return SignalDef::isCCQEnumu_MINERvA(event, EnuMin, EnuMax, fullphasespace); } diff --git a/src/MINERvA/MINERvA_CCinc_XSec_1DEnu_nu.cxx b/src/MINERvA/MINERvA_CCinc_XSec_1DEnu_nu.cxx index bc4cffe..0b537be 100644 --- a/src/MINERvA/MINERvA_CCinc_XSec_1DEnu_nu.cxx +++ b/src/MINERvA/MINERvA_CCinc_XSec_1DEnu_nu.cxx @@ -1,125 +1,125 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_SignalDef.h" #include "MINERvA_CCinc_XSec_1DEnu_nu.h" //******************************************************************** MINERvA_CCinc_XSec_1DEnu_nu::MINERvA_CCinc_XSec_1DEnu_nu(std::string name, std::string inputfile, std::string type) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "MINERvA_CCinc_XSec_1DEnu_nu sample. \n" "Target: CH \n" "Flux: MiniBooNE Forward Horn Current nue + nuebar \n" "Signal: Any event with 1 muon, any nucleons, and no " "other FS particles \n"; // Setup common settings fSettings = LoadSampleSettings(name, inputfile, type); fSettings.SetDescription(descrip); fSettings.SetXTitle("E_{#nu} (GeV)"); fSettings.SetYTitle("d#sigma/dE_{#nu} (cm^{2}/GeV/nucleon)"); fSettings.SetAllowedTypes("FIX/DIAG/MASK", "FIX/DIAG"); fSettings.SetEnuRange(2.0, 20.0); fSettings.DefineAllowedTargets("C,H"); fSettings.DefineAllowedSpecies("numu"); fSettings.SetTitle("MINERvA_CCinc_XSec_1DEnu_nu"); target = ""; if (name.find("C12") != std::string::npos) target = "C12"; else if (name.find("Fe56") != std::string::npos) target = "Fe56"; else if (name.find("Pb208") != std::string::npos) target = "Pb208"; if (name.find("DEN") != std::string::npos) target = "CH"; if (target == "") { - QTHROW("target " << target << " was not found!"); + NUIS_ABORT("target " << target << " was not found!"); } // fSettings.SetSmearingInput( FitPar::GetDataBase() + // "/MINERvA/CCinc/CCinc_"+target+"_x_smear.csv" ); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = (GetEventHistogram()->Integral("width") * 1E-38 / (fNEvents + 0.)) / this->TotalIntegratedFlux(); // Plot Setup ------------------------------------------------------- double binsx[9] = {2, 3, 4, 5, 6, 8, 10, 15, 20}; CreateDataHistogram(8, binsx); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CCinc_XSec_1DEnu_nu::FillEventVariables(FitEvent *event) { //******************************************************************** if (event->NumFSParticle(13) == 0) return; TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; fXVar = Pnu.E() / 1000.; ThetaMu = Pnu.Vect().Angle(Pmu.Vect()); return; } //******************************************************************** bool MINERvA_CCinc_XSec_1DEnu_nu::isSignal(FitEvent *event) { //******************************************************************* if (!SignalDef::isCCINC(event, 14, this->EnuMin, this->EnuMax)) return false; // Restrict the phase space to theta < 17 degrees if (ThetaMu > 0.296706) return false; return true; }; //******************************************************************** void MINERvA_CCinc_XSec_1DEnu_nu::ScaleEvents() { //******************************************************************** // Get rid of this because it causes odd behaviour Measurement1D::ScaleEvents(); // this->fMCHist->Scale(this->fScaleFactor, "width"); // // Proper error scaling - ROOT Freaks out with xsec weights sometimes // for(int i=0; ifMCStat->GetNbinsX();i++) { // if (this->fMCStat->GetBinContent(i+1) != 0) // this->fMCHist->SetBinError(i+1, this->fMCHist->GetBinContent(i+1) * // this->fMCStat->GetBinError(i+1) / this->fMCStat->GetBinContent(i+1) ); // else this->fMCHist->SetBinError(i+1, this->fMCHist->Integral()); // } } diff --git a/src/MINERvA/MINERvA_CCinc_XSec_1DEnu_ratio.cxx b/src/MINERvA/MINERvA_CCinc_XSec_1DEnu_ratio.cxx index 0cc1151..30009f3 100644 --- a/src/MINERvA/MINERvA_CCinc_XSec_1DEnu_ratio.cxx +++ b/src/MINERvA/MINERvA_CCinc_XSec_1DEnu_ratio.cxx @@ -1,145 +1,145 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_CCinc_XSec_1DEnu_ratio.h" #include "MINERvA_SignalDef.h" //******************************************************************** MINERvA_CCinc_XSec_1DEnu_ratio::MINERvA_CCinc_XSec_1DEnu_ratio( nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "MINERvA_CCinc_XSec_1DEnu_ratio sample. \n" "Target: CH \n" "Flux: MINERvA Forward Horn Current nue + nuebar \n" "Signal: Any event with 1 electron, any nucleons, and " "no other FS particles \n"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("E_{#nu} (GeV)"); fSettings.SetYTitle(" d#sigma/dE_{#nu} (cm^{2}/GeV/nucleon)"); fSettings.SetAllowedTypes("FIX/DIAG,FULL/MASK", "FIX/FULL"); fSettings.SetEnuRange(0.0, 20.0); // CCQELike plot information fSettings.SetTitle("MINERvA_CCinc_XSec_1DEnu_ratio"); fIsRatio = true; nBins = 8; target = ""; if (fSettings.Found("name", "C12")) target = "C12"; else if (fSettings.Found("name", "Fe56")) target = "Fe56"; else if (fSettings.Found("name", "Pb208")) target = "Pb208"; else { - QTHROW("target " << target << " was not found!"); + NUIS_ABORT("target " << target << " was not found!"); } std::string basedir = FitPar::GetDataBase() + "/MINERvA/CCinc/"; fSettings.SetDataInput(basedir + "CCinc_" + target + "_CH_ratio_Enu_data.csv"); fSettings.SetCovarInput(basedir + "CCinc_" + target + "_CH_ratio_Enu_covar.csv"); FinaliseSampleSettings(); // Get parsed input files if (fSubInFiles.size() != 2) { - QTHROW("MINERvA CCinc ratio requires input files in format: " + NUIS_ABORT("MINERvA CCinc ratio requires input files in format: " "NUMERATOR;DENOMINATOR"); } std::string inFileNUM = fSubInFiles.at(0); std::string inFileDEN = fSubInFiles.at(1); // Scaling Setup --------------------------------------------------- // Ratio of sub classes so non needed // Plot Setup ------------------------------------------------------- SetDataFromTextFile(fSettings.GetDataInput()); // This function forces in a factor of 1E76 to the covariance. // This cancels with the factor of 1E38 which is added to the data in the chi2 // calculation... Who said two wrongs don't make a right? SetCorrelationFromTextFile(fSettings.GetCovarInput()); // Setup Experiments ------------------------------------------------------- std::string type = samplekey.GetS("type"); NUM = new MINERvA_CCinc_XSec_1DEnu_nu( "MINERvA_CCinc_XSec_1DEnu_" + target + "_CH_NUM", inFileNUM, type); DEN = new MINERvA_CCinc_XSec_1DEnu_nu( "MINERvA_CCinc_XSec_1DEnu_" + target + "_CH_DEN", inFileDEN, type); NUM->SetNoData(); DEN->SetNoData(); // Add to chain for processing this->fSubChain.clear(); this->fSubChain.push_back(NUM); this->fSubChain.push_back(DEN); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CCinc_XSec_1DEnu_ratio::MakePlots() { //******************************************************************** UInt_t sample = 0; for (std::vector::const_iterator expIter = this->fSubChain.begin(); expIter != this->fSubChain.end(); expIter++) { MeasurementBase *exp = static_cast(*expIter); if (sample == 0) this->NUM = static_cast(exp); else if (sample == 1) this->DEN = static_cast(exp); else break; sample++; } // Now make the ratio histogram TH1D *NUM_MC = (TH1D *)this->NUM->GetMCList().at(0)->Clone(); TH1D *DEN_MC = (TH1D *)this->DEN->GetMCList().at(0)->Clone(); for (int i = 0; i < nBins; ++i) { double binVal = 0; double binErr = 0; if (DEN_MC->GetBinContent(i + 1) && NUM_MC->GetBinContent(i + 1)) { binVal = NUM_MC->GetBinContent(i + 1) / DEN_MC->GetBinContent(i + 1); double fractErrNUM = NUM_MC->GetBinError(i + 1) / NUM_MC->GetBinContent(i + 1); double fractErrDEN = DEN_MC->GetBinError(i + 1) / DEN_MC->GetBinContent(i + 1); binErr = binVal * sqrt(fractErrNUM * fractErrNUM + fractErrDEN * fractErrDEN); } this->fMCHist->SetBinContent(i + 1, binVal); this->fMCHist->SetBinError(i + 1, binErr); } return; } diff --git a/src/MINERvA/MINERvA_CCinc_XSec_1Dx_nu.cxx b/src/MINERvA/MINERvA_CCinc_XSec_1Dx_nu.cxx index 746469c..2175f90 100644 --- a/src/MINERvA/MINERvA_CCinc_XSec_1Dx_nu.cxx +++ b/src/MINERvA/MINERvA_CCinc_XSec_1Dx_nu.cxx @@ -1,124 +1,124 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_CCinc_XSec_1Dx_nu.h" #include "MINERvA_SignalDef.h" //******************************************************************** MINERvA_CCinc_XSec_1Dx_nu::MINERvA_CCinc_XSec_1Dx_nu(std::string name, std::string inputfile, std::string type) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "MINERvA_CCinc_XSec_1Dx_nu sample. \n" "Target: CH \n" "Flux: MiniBooNE Forward Horn Current nue + nuebar \n" "Signal: Any event with 1 muon, any nucleons, and no " "other FS particles \n"; // Setup common settings fSettings = LoadSampleSettings(name, inputfile, type); fSettings.SetDescription(descrip); fSettings.SetXTitle("Reconstructed Bjorken x"); fSettings.SetYTitle("d#sigma/dx (cm^{2}/nucleon)"); fSettings.SetAllowedTypes("FIX/DIAG/MASK", "FIX/DIAG"); fSettings.SetEnuRange(2.0, 20.0); fSettings.DefineAllowedTargets("C,H"); fSettings.DefineAllowedSpecies("numu"); fSettings.SetTitle("MINERvA_CCinc_XSec_1Dx_nu"); target = ""; if (name.find("C12") != std::string::npos) target = "C12"; else if (name.find("Fe56") != std::string::npos) target = "Fe56"; else if (name.find("Pb208") != std::string::npos) target = "Pb208"; if (name.find("DEN") != std::string::npos) target = "CH"; if (target == "") { - QTHROW("target " << target << " was not found!"); + NUIS_ABORT("target " << target << " was not found!"); } FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = (GetEventHistogram()->Integral("width") * 1E-38 / (fNEvents + 0.)) / this->TotalIntegratedFlux(); // Plot Setup ------------------------------------------------------- double binsx[7] = {0, 0.1, 0.3, 0.7, 0.9, 1.1, 1.5}; CreateDataHistogram(6, binsx); std::string basedir = FitPar::GetDataBase() + "/MINERvA/CCinc/"; std::string smearfilename = "CCinc_" + target + "_x_smear.csv"; SetSmearingMatrix(basedir + smearfilename, 6, 7); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CCinc_XSec_1Dx_nu::FillEventVariables(FitEvent *event) { //******************************************************************** if (event->NumFSParticle(13) == 0) return; TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; ThetaMu = Pnu.Vect().Angle(Pmu.Vect()); TLorentzVector q = Pnu - Pmu; double q0 = q.E() / 1000.0; double Emu = (Pmu.E()) / 1000.0; Enu_rec = Emu + q0; double Q2 = 4 * Enu_rec * Emu * sin(ThetaMu / 2) * sin(ThetaMu / 2); bjork_x = Q2 / 2. / q0 / ((PhysConst::mass_proton + PhysConst::mass_neutron) / 2.); // Average nucleon masses fXVar = bjork_x; return; } //******************************************************************** bool MINERvA_CCinc_XSec_1Dx_nu::isSignal(FitEvent *event) { //******************************************************************* // Only look at numu events if (!SignalDef::isCCINC(event, 14, EnuMin, EnuMax)) return false; // Restrict the phase space to theta < 17 degrees if (ThetaMu > 0.296706) return false; return true; }; //******************************************************************** void MINERvA_CCinc_XSec_1Dx_nu::ScaleEvents() { //******************************************************************** this->ApplySmearingMatrix(); Measurement1D::ScaleEvents(); } diff --git a/src/MINERvA/MINERvA_CCinc_XSec_1Dx_ratio.cxx b/src/MINERvA/MINERvA_CCinc_XSec_1Dx_ratio.cxx index aaa2858..f14aaca 100644 --- a/src/MINERvA/MINERvA_CCinc_XSec_1Dx_ratio.cxx +++ b/src/MINERvA/MINERvA_CCinc_XSec_1Dx_ratio.cxx @@ -1,143 +1,143 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MINERvA_CCinc_XSec_1Dx_ratio.h" #include "MINERvA_SignalDef.h" //******************************************************************** MINERvA_CCinc_XSec_1Dx_ratio::MINERvA_CCinc_XSec_1Dx_ratio(nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "MINERvA_CCinc_XSec_1Dx_ratio sample. \n" "Target: CH \n" "Flux: MINERvA Forward Horn Current nue + nuebar \n" "Signal: Any event with 1 electron, any nucleons, and " "no other FS particles \n"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("Reconstructed Bjorken x"); fSettings.SetYTitle("d#sigma/dx (cm^{2}/nucleon)"); fSettings.SetAllowedTypes("FIX/DIAG,FULL/MASK", "FIX/FULL"); fSettings.SetEnuRange(0.0, 20.0); // CCQELike plot information fSettings.SetTitle("MINERvA_CCinc_XSec_1Dx_ratio"); fIsRatio = true; nBins = 8; target = ""; if (fSettings.Found("name", "C12")) target = "C12"; else if (fSettings.Found("name", "Fe56")) target = "Fe56"; else if (fSettings.Found("name", "Pb208")) target = "Pb208"; else { - QTHROW("target " << target << " was not found!"); + NUIS_ABORT("target " << target << " was not found!"); } std::string basedir = FitPar::GetDataBase() + "/MINERvA/CCinc/"; fSettings.SetDataInput(basedir + "CCinc_" + target + "_CH_ratio_x_data.csv"); fSettings.SetCovarInput(basedir + "CCinc_" + target + "_CH_ratio_x_covar.csv"); FinaliseSampleSettings(); // Get parsed input files if (fSubInFiles.size() != 2) { - QTHROW("MINERvA CCinc ratio requires input files in format: " + NUIS_ABORT("MINERvA CCinc ratio requires input files in format: " "NUMERATOR;DENOMINATOR"); } std::string inFileNUM = fSubInFiles.at(0); std::string inFileDEN = fSubInFiles.at(1); // Scaling Setup --------------------------------------------------- // Ratio of sub classes so non needed // Plot Setup ------------------------------------------------------- SetDataFromTextFile(fSettings.GetDataInput()); // This function forces in a factor of 1E76 to the covariance. // This cancels with the factor of 1E38 which is added to the data in the chi2 // calculation... Who said two wrongs don't make a right? SetCorrelationFromTextFile(fSettings.GetCovarInput()); // Setup Experiments ------------------------------------------------------- std::string type = samplekey.GetS("type"); NUM = new MINERvA_CCinc_XSec_1Dx_nu( "MINERvA_CCinc_XSec_1Dx_" + target + "_CH_NUM", inFileNUM, type); DEN = new MINERvA_CCinc_XSec_1Dx_nu( "MINERvA_CCinc_XSec_1Dx_" + target + "_CH_DEN", inFileDEN, type); NUM->SetNoData(); DEN->SetNoData(); // Add to chain for processing this->fSubChain.clear(); this->fSubChain.push_back(NUM); this->fSubChain.push_back(DEN); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; //******************************************************************** void MINERvA_CCinc_XSec_1Dx_ratio::MakePlots() { //******************************************************************** UInt_t sample = 0; for (std::vector::const_iterator expIter = this->fSubChain.begin(); expIter != this->fSubChain.end(); expIter++) { MeasurementBase *exp = static_cast(*expIter); if (sample == 0) this->NUM = static_cast(exp); else if (sample == 1) this->DEN = static_cast(exp); else break; sample++; } // Now make the ratio histogram TH1D *NUM_MC = (TH1D *)this->NUM->GetMCList().at(0)->Clone(); TH1D *DEN_MC = (TH1D *)this->DEN->GetMCList().at(0)->Clone(); for (int i = 0; i < nBins; ++i) { double binVal = 0; double binErr = 0; if (DEN_MC->GetBinContent(i + 1) && NUM_MC->GetBinContent(i + 1)) { binVal = NUM_MC->GetBinContent(i + 1) / DEN_MC->GetBinContent(i + 1); double fractErrNUM = NUM_MC->GetBinError(i + 1) / NUM_MC->GetBinContent(i + 1); double fractErrDEN = DEN_MC->GetBinError(i + 1) / DEN_MC->GetBinContent(i + 1); binErr = binVal * sqrt(fractErrNUM * fractErrNUM + fractErrDEN * fractErrDEN); } this->fMCHist->SetBinContent(i + 1, binVal); this->fMCHist->SetBinError(i + 1, binErr); } return; } diff --git a/src/MiniBooNE/MiniBooNE_CCQE_XSec_1DQ2_antinu.cxx b/src/MiniBooNE/MiniBooNE_CCQE_XSec_1DQ2_antinu.cxx index 24a9f5e..2fe5c02 100644 --- a/src/MiniBooNE/MiniBooNE_CCQE_XSec_1DQ2_antinu.cxx +++ b/src/MiniBooNE/MiniBooNE_CCQE_XSec_1DQ2_antinu.cxx @@ -1,214 +1,214 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MiniBooNE_CCQE_XSec_1DQ2_antinu.h" #include MiniBooNE_CCQE_XSec_1DQ2_antinu::MiniBooNE_CCQE_XSec_1DQ2_antinu( nuiskey samplekey) { // Sample overview std::string descrip = "MiniBooNE CCQE/CC0pi sample. \n" "Target: CH2.08 \n" "Flux: CCQE = Forward Horn Current numu \n" " CC0pi = Forward Horn Current numu+numub \n" "Signal: CCQE = True CCQE + True 2p2h (Mode == 1 or 2) \n" " CC0pi = Events with 1 mu+/mu-, N nucleons, 0 other"; // 1. Initalise sample Settings --------------------------------------- fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("Q^{2}_{QE} (GeV^{2})"); fSettings.SetYTitle("d#sigma/dQ_{QE}^{2} (cm^{2}/GeV^{2})"); fSettings.SetAllowedTypes("FIX,FREE,SHAPE/DIAG/NORM/MASK", "FIX/DIAG"); fSettings.SetEnuRange(0.0, 3.0); fSettings.SetSuggestedFlux(FitPar::GetDataBase() + "/MiniBooNE/ccqe/mb_ccqe_flux.root"); // Define input data information fSettings.FoundFill("name", "CCQELike", fCCQElike, true); fSettings.FoundFill("name", "CTarg", fUseCorrectedCTarget, true); if (fCCQElike && fUseCorrectedCTarget) { - QTHROW("Sample: MiniBooNE_CCQE_XSec_1DQ2_antinu cannot run in both " + NUIS_ABORT("Sample: MiniBooNE_CCQE_XSec_1DQ2_antinu cannot run in both " "QELike and C-Target mode. You're welcome to add the data set."); } if (fCCQElike) { // CCQELike plot information fSettings.SetTitle("MiniBooNE #nu_#mu CCQE on CH"); fSettings.SetDataInput(FitPar::GetDataBase() + "/MiniBooNE/anti-ccqe/asqq_con.txt"); fSettings.SetCovarInput(FitPar::GetDataBase() + "/MiniBooNE/anti-ccqe/asqq_diagcovar"); fSettings.SetDefault("ccqelikebkg_input", FitPar::GetDataBase() + "/MiniBooNE/anti-ccqe/asqq_bkg_ccqe.txt"); fSettings.SetDefault("ccpimbkg_input", FitPar::GetDataBase() + "/MiniBooNE/anti-ccqe/asqq_bkg_ccpim.txt"); fSettings.SetHasExtraHistograms(true); fSettings.DefineAllowedSpecies("numu,numub"); fSettings.DefineAllowedTargets("C,H"); } else if (!fUseCorrectedCTarget) { // CCQE Plot Information fSettings.SetTitle("MiniBooNE #nu_#mu CC0#pi on CH"); fSettings.SetDataInput(FitPar::GetDataBase() + "/MiniBooNE/anti-ccqe/asqq_con.txt"); fSettings.SetCovarInput(FitPar::GetDataBase() + "/MiniBooNE/anti-ccqe/asqq_diagcovar"); fSettings.DefineAllowedSpecies("numu"); fSettings.DefineAllowedTargets("C,H"); } else { // CCQE Corrected Target Plot Information fSettings.SetTitle("MiniBooNE #nu_#mu CC0#pi on C"); fSettings.SetDataInput(FitPar::GetDataBase() + "/MiniBooNE/anti-ccqe/asqq_con_ctarget.txt"); fSettings.SetCovarInput(FitPar::GetDataBase() + "/MiniBooNE/anti-ccqe/asqq_diagcovar"); fSettings.DefineAllowedSpecies("numu"); fSettings.DefineAllowedTargets("C"); } FinaliseSampleSettings(); // 2. Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon // Multiply by 14.08/6.0 to get per neutron double NNucPerNTarg = fUseCorrectedCTarget ? 12.0 / 6.0 : 14.08 / 8.0; fScaleFactor = ((GetEventHistogram()->Integral("width") * 1E-38 / (fNEvents + 0.)) * NNucPerNTarg / TotalIntegratedFlux()); // 3. Plot Setup ------------------------------------------------------- SetDataFromTextFile(fSettings.GetDataInput()); SetCovarFromDiagonal(); /// /// If CCQELike is used an additional the CCQELike BKG is used and a PDG /// Histogram is saved if (fCCQElike) { // CCQELike Data fDataHist_CCQELIKE = PlotUtils::GetTH1DFromFile(fSettings.GetS("ccqelikebkg_input"), fSettings.GetName() + "_CCQELIKE_data"); fDataHist_CCQELIKE->SetNameTitle( (fSettings.Name() + "_CCQELIKE_BKG").c_str(), ("MiniBooNE #nu_#mu CCQE-Like Backgrounds" + fSettings.PlotTitles()) .c_str()); fDataHist->Add(fDataHist_CCQELIKE); SetAutoProcessTH1(fDataHist_CCQELIKE, kCMD_Write); // CCQELike MC fMCHist_CCQELIKE = new NuNuBarTrueModeStack( fSettings.Name() + "_CCQELIKE_MC", "CCQE-like MC" + fSettings.PlotTitles(), fDataHist_CCQELIKE); SetAutoProcessTH1(fMCHist_CCQELIKE); // Data CCRES fDataHist_CCPIM = PlotUtils::GetTH1DFromFile(fSettings.GetS("ccpimbkg_input"), fSettings.GetName() + "_CCPIM_BKG_data"); fDataHist_CCPIM->SetNameTitle( (fSettings.Name() + "_CCPIM_data").c_str(), ("MiniBooNE #nu_#mu CCQE-Like Backgrounds" + fSettings.PlotTitles()) .c_str()); SetAutoProcessTH1(fDataHist_CCQELIKE, kCMD_Write); // MC CCRES fMCHist_CCPIM = new NuNuBarTrueModeStack( fSettings.Name() + "_CCPIM_BKG_MC", "CCQE-like BKG CC-RES" + fSettings.PlotTitles(), fDataHist_CCPIM); SetAutoProcessTH1(fMCHist_CCPIM); // Make NON CCPIM fDataHist_NONCCPIM = (TH1D *)fDataHist_CCQELIKE->Clone(); fDataHist_NONCCPIM->SetNameTitle((fName + "_data_NONCCPIM").c_str(), (fName + "_data_NONCCPIM").c_str()); fDataHist_NONCCPIM->Add(fDataHist_CCPIM, -1.0); SetAutoProcessTH1(fDataHist_NONCCPIM, kCMD_Write); fMCHist_NONCCPIM = new NuNuBarTrueModeStack( fSettings.Name() + "_NONCCPIM_BKG", "CCQE-like BKG CC-NonRES" + fSettings.PlotTitles(), fDataHist_NONCCPIM); SetAutoProcessTH1(fMCHist_NONCCPIM); } FinaliseMeasurement(); }; void MiniBooNE_CCQE_XSec_1DQ2_antinu::FillEventVariables(FitEvent *event) { if (event->NumFSParticle(PhysConst::pdg_muons) == 0) return; TLorentzVector Pnu = event->GetNeutrinoIn()->fP; // The highest momentum mu+/mu-. The isSignal definition should make sure we // only // accept events we want, so no need to do an additional check here. TLorentzVector Pmu = event->GetHMFSParticle(PhysConst::pdg_muons)->fP; // Set X Variables fXVar = FitUtils::Q2QErec(Pmu, cos(Pnu.Vect().Angle(Pmu.Vect())), 30., false); fPDGnu = event->PDGnu(); return; }; bool MiniBooNE_CCQE_XSec_1DQ2_antinu::isSignal(FitEvent *event) { // If CC0pi, include both charges if (fCCQElike) { if (SignalDef::isCC0pi(event, 14, EnuMin, EnuMax) || SignalDef::isCC0pi(event, -14, EnuMin, EnuMax)) { return true; } } else { if (SignalDef::isCCQELike(event, -14, EnuMin, EnuMax)) return true; } return false; }; void MiniBooNE_CCQE_XSec_1DQ2_antinu::FillExtraHistograms( MeasurementVariableBox *vars, double weight) { // No Extra Hists if not ccqelike if (!fCCQElike or !Signal) return; // Fill Stacks if (Mode != -1 and Mode != -2) { if (fabs(Mode) == 11 or fabs(Mode) == 12 or fabs(Mode == 13)) { fMCHist_CCPIM->Fill(fPDGnu, Mode, fXVar, weight); } else { fMCHist_NONCCPIM->Fill(fPDGnu, Mode, fXVar, weight); } } fMCHist_CCQELIKE->Fill(fPDGnu, Mode, fXVar, weight); } diff --git a/src/MiniBooNE/MiniBooNE_NCEL_XSec_Treco_nu.cxx b/src/MiniBooNE/MiniBooNE_NCEL_XSec_Treco_nu.cxx index 1cedc78..8da8ed0 100644 --- a/src/MiniBooNE/MiniBooNE_NCEL_XSec_Treco_nu.cxx +++ b/src/MiniBooNE/MiniBooNE_NCEL_XSec_Treco_nu.cxx @@ -1,295 +1,295 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MiniBooNE_NCEL_XSec_Treco_nu.h" #include "TLorentzVector.h" //******************************************************************** MiniBooNE_NCEL_XSec_Treco_nu::MiniBooNE_NCEL_XSec_Treco_nu(nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "MiniBooNE_NCEL_XSec_Treco_nu sample. \n" "Target: CH \n" "Flux: MiniBooNE Numu Flux \n" "Signal: Any event with True NCEL modes \n"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("T_{reco} (MeV)"); fSettings.SetYTitle("Events/(12 MeV)"); fSettings.SetAllowedTypes("FIX,FREE,SHAPE/FULL,DIAG/NORM/MASK", "FIX/FULL,DIAG"); fSettings.DefineAllowedTargets("C,H"); fSettings.DefineAllowedSpecies("numu"); fSettings.SetEnuRange(0.0, 10.0); double arr_treco[52] = { 40.0, 52.0, 63.9, 75.9, 87.8, 99.8, 111.8, 123.7, 135.7, 147.6, 159.6, 171.6, 183.5, 195.5, 207.5, 219.4, 231.4, 243.3, 255.3, 267.3, 279.2, 291.2, 303.1, 315.1, 327.1, 339.0, 351.0, 362.9, 374.9, 386.9, 398.8, 410.8, 422.7, 434.7, 446.7, 458.6, 470.6, 482.5, 494.5, 506.5, 518.4, 530.4, 542.4, 554.3, 566.3, 578.2, 590.2, 602.2, 614.1, 626.1, 638.0, 650.0}; SetDataValues(FitPar::GetDataBase() + "/MiniBooNE/ncqe/input_data.txt", arr_treco); SetCovarMatrix(FitPar::GetDataBase() + "/MiniBooNE/ncqe/ErrorMatrix.tab", 51); SetResponseMatrix(FitPar::GetDataBase() + "/MiniBooNE/ncqe/response_mat.txt", 51, arr_treco); SetFluxHistogram(FitPar::GetDataBase() + "/MiniBooNE/ncqe/flux.txt"); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // The scale factor is quite complicated because MB didn't divide by number of // targets. nMolMB is the number of CH_2 molecules in the MB FV (610.6 cm // radius sphere) and 0.845 is the published density of the mineral oil. // UPDATE: nMolMB is the number of CH_2 molecules in the MB FV (500 cm radius // sphere) and 0.845 is the published density of the mineral oil. UPDATE // UPDATE: They didn't account for fiducial cut, so neither do we. double nMolMB = 6.023E+23 * 0.845 * 4.0 * M_PI * 610.6 * 610.6 * 610.6 / 3.0; double POT = 6.46e20; // Need to update scalefactor to reflect actual flux used fScaleFactor = (this->newFluxHist->Integral("") * POT * (GetEventHistogram()->Integral("width")) * 1E-38 * 14.08 / (fNEvents + 0.)) * nMolMB; fScaleFactor /= GetFluxHistogram()->Integral("width"); // Final setup --------------------------------------------------- FinaliseMeasurement(); // Usually the MCFine histogram is a finer binned version of MC Hist. // In this case we need to use it to save the true distribution before // smearing. if (fMCFine) delete fMCFine; fMCFine = new TH1D((this->fName + "_Ttrue").c_str(), (this->fName + this->fPlotTitles).c_str(), 50, 0, 900); }; void MiniBooNE_NCEL_XSec_Treco_nu::Write(std::string arg) { newFluxHist->Write("MB_NCEL_newFlux"); response_mat->Write("MB_NCEL_response matrix"); Measurement1D::Write(arg); return; } void MiniBooNE_NCEL_XSec_Treco_nu::FillEventVariables(FitEvent *event) { double t_raw = 0.0; // Loop and add all Tnucleon for (UInt_t i = 0; i < event->Npart(); i++) { if (event->PartInfo(i)->Status() != kFinalState) continue; int pdg = event->PartInfo(i)->fPID; if (pdg == 2212 || pdg == 2112) { t_raw += FitUtils::T(event->PartInfo(i)->fP) * 1.E3; } } fXVar = t_raw; } void MiniBooNE_NCEL_XSec_Treco_nu::ScaleEvents() { // Now convert Ttrue to Treco... for (int treco = 0; treco < 51; ++treco) { double total = 0.; for (int ttrue = 0; ttrue < 50; ++ttrue) total += fMCFine->GetBinContent(ttrue + 1) * response_mat->GetBinContent(ttrue + 1, treco + 1); fMCHist->SetBinContent(treco + 1, total); } // Scale this->fMCHist->Scale(this->fScaleFactor, "width"); this->fMCFine->Scale(this->fScaleFactor, "width"); PlotUtils::ScaleNeutModeArray((TH1 **)fMCHist_PDG, fScaleFactor, "width"); // Add in the backgrounds... for (int treco = 0; treco < 51; ++treco) { double total = this->fMCHist->GetBinContent(treco + 1) + this->BKGD_other->GetBinContent(treco + 1) + this->BKGD_irrid->GetBinContent(treco + 1); this->fMCHist->SetBinContent(treco + 1, total); } } bool MiniBooNE_NCEL_XSec_Treco_nu::isSignal(FitEvent *event) { // Should put in MB SignalDef eventually if (event->Mode != 51 && event->Mode != 52) return false; // Numu or nue if (event->PDGnu() != 14 && event->PDGnu() != 12) return false; // Enu if (event->Enu() < EnuMin * 1000.0 || event->Enu() > EnuMax * 1000.0) return false; return true; }; void MiniBooNE_NCEL_XSec_Treco_nu::SetFluxHistogram(std::string dataFile) { this->newFluxHist = PlotUtils::GetTH1DFromFile( dataFile.c_str(), (this->fName + "Real Flux Hist"), "idgaf"); this->newFluxHist->Print(); return; } // Read in the covariance matrix from the file specified in the constructor void MiniBooNE_NCEL_XSec_Treco_nu::SetCovarMatrix(std::string covarFile, int dim) { // Use Utils // // Make a counter to track the line number int row = 0; std::string line; std::ifstream covar(covarFile.c_str(), std::ifstream::in); this->covar = new TMatrixDSym(dim); if (covar.is_open()) - QLOG(DEB, "Reading covariance matrix from file: " << covarFile); + NUIS_LOG(DEB, "Reading covariance matrix from file: " << covarFile); while (std::getline(covar >> std::ws, line, '\n')) { std::istringstream stream(line); double entry; int column = 0; // Loop over entries and insert them into matrix // Multiply by the errors to get the covariance, rather than the correlation // matrix while (stream >> entry) { (*this->covar)(row, column) = entry; if (row == column) this->fDataHist->SetBinError(row + 1, sqrt(entry)); column++; } row++; } // // Robust matrix inversion method TDecompSVD LU = TDecompSVD(*this->covar); this->covar = new TMatrixDSym(dim, LU.Invert().GetMatrixArray(), ""); return; }; // Override the usual function in the base class because this is more // complicated for the NCEL sample... void MiniBooNE_NCEL_XSec_Treco_nu::SetDataValues(std::string inputFile, double *arr_treco) { std::string line; std::ifstream input(inputFile.c_str(), std::ifstream::in); if (input.is_open()) { - QLOG(DEB, "Reading data from file: " << inputFile); + NUIS_LOG(DEB, "Reading data from file: " << inputFile); } this->fDataHist = new TH1D((this->fName + "_data").c_str(), (this->fName + this->fPlotTitles).c_str(), 51, arr_treco); this->BKGD_other = new TH1D((this->fName + "_BKGD_other").c_str(), (this->fName + this->fPlotTitles).c_str(), 51, arr_treco); this->BKGD_irrid = new TH1D((this->fName + "_BKGD_irrid").c_str(), (this->fName + this->fPlotTitles).c_str(), 51, arr_treco); // To get the nDOF correct... this->fNDataPointsX = 52; double entry = 0; int xBin = 0; // First line is the MB data std::getline(input >> std::ws, line, '\n'); std::istringstream stream1(line); while (stream1 >> entry) { this->fDataHist->SetBinContent(xBin + 1, entry); xBin++; } // Second line is "other" backgrounds std::getline(input >> std::ws, line, '\n'); std::istringstream stream2(line); entry = 0; xBin = 0; while (stream2 >> entry) { this->BKGD_other->SetBinContent(xBin + 1, entry); xBin++; } // Third line is the irreducible background std::getline(input >> std::ws, line, '\n'); std::istringstream stream3(line); entry = 0; xBin = 0; while (stream3 >> entry) { this->BKGD_irrid->SetBinContent(xBin + 1, entry); xBin++; } }; // Read in the response matrix -- thus far, a response matrix is unique to the // NCEL sample void MiniBooNE_NCEL_XSec_Treco_nu::SetResponseMatrix(std::string responseFile, int dim, double *arr_treco) { // Make a counter to track the line number int xBin = 0; std::string line; std::ifstream response(responseFile.c_str(), std::ifstream::in); // Response matrix: x axis is Ttrue, y axis is Treco this->response_mat = new TH2D((this->fName + "_RESPONSE_MATRIX").c_str(), (this->fName + this->fPlotTitles).c_str(), 50, 0, 900, 51, arr_treco); if (response.is_open()) { - QLOG(DEB, "Reading in the response matrix from file: " << responseFile); + NUIS_LOG(DEB, "Reading in the response matrix from file: " << responseFile); } while (std::getline(response, line, '\n')) { std::istringstream stream(line); double entry; int yBin = 0; // Loop over entries and insert them into matrix // Multiply by the errors to get the covariance, rather than the correlation // matrix while (stream >> entry) { this->response_mat->SetBinContent(xBin + 1, yBin + 1, entry); yBin++; } xBin++; } }; diff --git a/src/MiniBooNE/MiniBooNE_NCpi0_XSec_1Dppi0_nu.cxx b/src/MiniBooNE/MiniBooNE_NCpi0_XSec_1Dppi0_nu.cxx index 8cf8920..3d18838 100644 --- a/src/MiniBooNE/MiniBooNE_NCpi0_XSec_1Dppi0_nu.cxx +++ b/src/MiniBooNE/MiniBooNE_NCpi0_XSec_1Dppi0_nu.cxx @@ -1,188 +1,188 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MiniBooNE_NCpi0_XSec_1Dppi0_nu.h" // The constructor MiniBooNE_NCpi0_XSec_1Dppi0_nu::MiniBooNE_NCpi0_XSec_1Dppi0_nu( std::string inputfile, FitWeight *rw, std::string type, std::string fakeDataFile, Double_t *anuBins) : isComb(false) { if (anuBins != NULL) isComb = true; isComb = false; // Needs Updating // // Set pointer to the reweighting engine // rw_engine = rw; // this->fBeamDistance = 0.541; // // Define the energy region // this->EnuMin = 0.; // this->EnuMax = 4.; // // In future read most of these from a card file // this->inFile = inputfile; // this->fName = "MB_NCpi0_XSec_numu_1Dppi0"; // this->fPlotTitles = "; p_{#pi^{0}} (GeV/c); d#sigma/dp_{#pi^{0}} // (cm^{2}/(GeV/c)/nucleon)"; // this->SetCovarMatrix(FitPar::GetDataBase()+"/MiniBooNE/nc1pi0/nuppi0xsecerrormatrix.txt", // 11); // this->SetDataValues(FitPar::GetDataBase()+"/MiniBooNE/nc1pi0/nuppi0xsec_edit.txt"); // this->fNormError=0.107; // if (isComb) { // fName += "_comb"; // this->fNDataPointsX = 11; // this->fXBins = anuBins; // } // this->fMCHist = new TH1D((this->fName+"_MC").c_str(), // (this->fName+this->fPlotTitles).c_str(), this->fNDataPointsX-1, // this->fXBins); this->fMCFine = new TH1D((this->fName+"_MC_FINE").c_str(), // (this->fName+this->fPlotTitles).c_str(), (this->fNDataPointsX - 1)*10, // this->fXBins[0], this->fXBins[this->fNDataPointsX -1]); // this->ReadEventFile(); // // Different generators require slightly different rescaling factors. // if (this->fEventType == 0) this->fScaleFactor = // (GetEventHistogram()->Integral("width")*1E-38/(fNEvents+0.))*14.08/14.0/this->TotalIntegratedFlux(); // // NEUT else if (this->fEventType == 1) this->fScaleFactor = // (GetEventHistogram()->Integral()*1E-38/(fNEvents+0.))*14.08*6.0/14./GetFluxHistogram()->Integral(); // // NUWRO else if (this->fEventType == 5) this->fScaleFactor = // (GetEventHistogram()->Integral()*1E-38/(fNEvents+0.))*14.08*6.0/14./GetFluxHistogram()->Integral(); // // GENIE }; void MiniBooNE_NCpi0_XSec_1Dppi0_nu::FillEventVariables(FitEvent *event) { TLorentzVector Pnu = (event->PartInfo(0))->fP; TLorentzVector Pmu; TLorentzVector Ppi0; double EHad = 0; pi0Cnt = 0; bad_particle = false; for (UInt_t j = 2; j < event->Npart(); ++j) { if (!((event->PartInfo(j))->fIsAlive) && (event->PartInfo(j))->fNEUTStatusCode != 0) continue; int PID = (event->PartInfo(j))->fPID; double KE = (event->PartInfo(j))->fP.E() - (event->PartInfo(j))->fMass; if (PID == 111) { Ppi0 = event->PartInfo(j)->fP; EHad += KE; } else if (PID == 2112 || PID == 2212) EHad += KE; else if (PID == -13) Pmu = event->PartInfo(j)->fP; if (abs(PID) >= 113 && abs(PID) <= 557) bad_particle = true; else if (abs(PID) == 11 || abs(PID) == 13 || abs(PID) == 15 || abs(PID) == 17) bad_particle = true; else if (PID == 111) pi0Cnt++; } double bind = 34.0; if (isComb) bind = 30.0; // double hadMass = FitUtils::Wrec(Pnu, Pmu, Ppi0); double ppi0 = Ppi0.Vect().Mag() / 1000.0; fXVar = ppi0; return; }; bool MiniBooNE_NCpi0_XSec_1Dppi0_nu::isSignal(FitEvent *event) { return SignalDef::isNC1pi(event, 14, 111, EnuMin, EnuMax); }; void MiniBooNE_NCpi0_XSec_1Dppi0_nu::SetDataValues(std::string dataFile) { - QLOG(SAM, this->fName << "Setting data for " << this->fName); - QLOG(SAM, this->fName << "From: " << dataFile); - QLOG(SAM, this->fName << "Reading error from covariance"); + NUIS_LOG(SAM, this->fName << "Setting data for " << this->fName); + NUIS_LOG(SAM, this->fName << "From: " << dataFile); + NUIS_LOG(SAM, this->fName << "Reading error from covariance"); TGraph *gr = new TGraph(dataFile.c_str()); this->fXBins = gr->GetX(); this->fDataValues = gr->GetY(); this->fNDataPointsX = gr->GetN(); // get the diagonal elements int rows = (this->tempCovar)->GetNrows(); Double_t errors[rows + 1]; for (int i = 0; i < rows; i++) errors[i] = sqrt((*this->tempCovar)(i, i) * 1E-81); errors[rows] = 0.; this->fDataErrors = errors; this->fDataHist = new TH1D((this->fName + "_data").c_str(), (this->fName + this->fPlotTitles).c_str(), this->fNDataPointsX - 1, this->fXBins); for (int i = 0; i < this->fNDataPointsX; ++i) { this->fDataHist->SetBinContent(i + 1, this->fDataValues[i]); this->fDataHist->SetBinError(i + 1, this->fDataErrors[i]); } return; } void MiniBooNE_NCpi0_XSec_1Dppi0_nu::SetCovarMatrix(std::string covarFile, int dim) { - QLOG(SAM, this->fName << "==============="); - QLOG(SAM, this->fName << "Reading covariance: " << this->fName); - QLOG(SAM, this->fName << "From: " << covarFile); + NUIS_LOG(SAM, this->fName << "==============="); + NUIS_LOG(SAM, this->fName << "Reading covariance: " << this->fName); + NUIS_LOG(SAM, this->fName << "From: " << covarFile); // tracks line number int row = 0; std::string line; std::ifstream covar(covarFile.c_str(), ifstream::in); this->tempCovar = new TMatrixDSym(dim); // while we're on a line in covar while (std::getline(covar >> std::ws, line, '\n')) { std::istringstream stream(line); // this is the netry we're reading! double entry; // this is the column counter! int column = 0; while (stream >> entry) { // get the covariance entry. // 1E-81 from the data release listing this unit double val = entry; // * 1E-81; // then fill the covariance matrix's row and column with this value, (*this->tempCovar)(row, column) = val; column++; } row++; } this->covar = (TMatrixDSym *)this->tempCovar->Clone(); TDecompChol LU = TDecompChol(*this->covar); this->covar = new TMatrixDSym(dim, LU.Invert().GetMatrixArray(), ""); (*this->covar) *= 1E81 * 1E-76; return; }; diff --git a/src/Reweight/FitWeight.cxx b/src/Reweight/FitWeight.cxx index 205648c..5518e2a 100644 --- a/src/Reweight/FitWeight.cxx +++ b/src/Reweight/FitWeight.cxx @@ -1,290 +1,290 @@ #include "FitWeight.h" #include "GENIEWeightEngine.h" #include "LikelihoodWeightEngine.h" #include "ModeNormEngine.h" #include "NEUTWeightEngine.h" #include "NIWGWeightEngine.h" #include "NUISANCEWeightEngine.h" #include "NuWroWeightEngine.h" #include "OscWeightEngine.h" #include "SampleNormEngine.h" #include "SplineWeightEngine.h" #include "T2KWeightEngine.h" #ifdef __NOVA_ENABLED__ #include "NOvARwgtEngine.h" #endif void FitWeight::AddRWEngine(int type) { - QLOG(FIT, "Adding reweight engine " << type); + NUIS_LOG(FIT, "Adding reweight engine " << type); switch (type) { case kNEUT: fAllRW[type] = new NEUTWeightEngine("neutrw"); break; case kNUWRO: fAllRW[type] = new NuWroWeightEngine("nuwrorw"); break; case kGENIE: fAllRW[type] = new GENIEWeightEngine("genierw"); break; case kNORM: fAllRW[type] = new SampleNormEngine("normrw"); break; case kLIKEWEIGHT: fAllRW[type] = new LikelihoodWeightEngine("likerw"); break; case kT2K: fAllRW[type] = new T2KWeightEngine("t2krw"); break; case kCUSTOM: fAllRW[type] = new NUISANCEWeightEngine("nuisrw"); break; case kSPLINEPARAMETER: fAllRW[type] = new SplineWeightEngine("splinerw"); break; case kNIWG: fAllRW[type] = new NIWGWeightEngine("niwgrw"); break; case kOSCILLATION: fAllRW[type] = new OscWeightEngine(); break; case kMODENORM: fAllRW[type] = new ModeNormEngine(); break; #ifdef __NOVA_ENABLED__ case kNOvARWGT: fAllRW[type] = new NOvARwgtEngine(); break; #endif default: - QTHROW("CANNOT ADD RW Engine for unknown dial type: " << type); + NUIS_ABORT("CANNOT ADD RW Engine for unknown dial type: " << type); break; } } WeightEngineBase *FitWeight::GetRWEngine(int type) { if (HasRWEngine(type)) { return fAllRW[type]; } - QTHROW("CANNOT get RW Engine for dial type: " << type); + NUIS_ABORT("CANNOT get RW Engine for dial type: " << type); } bool FitWeight::HasRWEngine(int type) { switch (type) { case kNEUT: case kNUWRO: case kGENIE: case kNORM: case kLIKEWEIGHT: case kT2K: case kCUSTOM: case kSPLINEPARAMETER: case kNIWG: case kOSCILLATION: #ifdef __NOVA_ENABLED__ case kNOvARWGT: { return fAllRW.count(type); } #endif - default: { QTHROW("CANNOT get RW Engine for dial type: " << type); } + default: { NUIS_ABORT("CANNOT get RW Engine for dial type: " << type); } } } void FitWeight::IncludeDial(std::string name, std::string type, double val) { // Should register the dial here. int typeenum = Reweight::ConvDialType(type); IncludeDial(name, typeenum, val); } void FitWeight::IncludeDial(std::string name, int dialtype, double val) { // Get the dial enum int nuisenum = Reweight::ConvDial(name, dialtype); if (nuisenum == -1) { - QERROR(FTL, "Could not include dial " << name); - QERROR(FTL, "With dialtype: " << dialtype); - QERROR(FTL, "With value: " << val); - QTHROW("With nuisenum: " << nuisenum); + NUIS_ERR(FTL, "Could not include dial " << name); + NUIS_ERR(FTL, "With dialtype: " << dialtype); + NUIS_ERR(FTL, "With value: " << val); + NUIS_ABORT("With nuisenum: " << nuisenum); } // Setup RW Engine Pointer if (fAllRW.find(dialtype) == fAllRW.end()) { AddRWEngine(dialtype); } WeightEngineBase *rw = fAllRW[dialtype]; // Include the dial rw->IncludeDial(name, val); // Set Dial Value if (val != -9999.9) { rw->SetDialValue(name, val); } // Sort Maps fAllEnums[name] = nuisenum; fAllValues[nuisenum] = val; // Sort Lists fNameList.push_back(name); fEnumList.push_back(nuisenum); fValueList.push_back(val); } void FitWeight::Reconfigure(bool silent) { // Reconfigure all added RW engines for (std::map::iterator iter = fAllRW.begin(); iter != fAllRW.end(); iter++) { (*iter).second->Reconfigure(silent); } } void FitWeight::SetDialValue(std::string name, double val) { // Add extra check, if name not found look for one with name in it. int nuisenum = fAllEnums[name]; SetDialValue(nuisenum, val); } // Allow for name aswell using GlobalList to determine sample name. void FitWeight::SetDialValue(int nuisenum, double val) { // Conv dial type int dialtype = Reweight::GetDialType(nuisenum); if (fAllRW.find(dialtype) == fAllRW.end()) { - QERROR(FTL, "Can't find RW engine for parameter " << fNameList[dialtype]); - QERROR(FTL, "With dialtype " << dialtype << ", " + NUIS_ERR(FTL, "Can't find RW engine for parameter " << fNameList[dialtype]); + NUIS_ERR(FTL, "With dialtype " << dialtype << ", " << Reweight::RemoveDialType(nuisenum)); - QTHROW("Are you sure you enabled the right engines?"); + NUIS_ABORT("Are you sure you enabled the right engines?"); } // Get RW Engine for this dial fAllRW[dialtype]->SetDialValue(nuisenum, val); fAllValues[nuisenum] = val; // Update ValueList for (size_t i = 0; i < fEnumList.size(); i++) { if (fEnumList[i] == nuisenum) { fValueList[i] = val; } } } void FitWeight::SetAllDials(const double *x, int n) { for (size_t i = 0; i < (UInt_t)n; i++) { int rwenum = fEnumList[i]; SetDialValue(rwenum, x[i]); } Reconfigure(); } double FitWeight::GetDialValue(std::string name) { // Add extra check, if name not found look for one with name in it. int nuisenum = fAllEnums[name]; return GetDialValue(nuisenum); } double FitWeight::GetDialValue(int nuisenum) { return fAllValues[nuisenum]; } int FitWeight::GetDialPos(std::string name) { int rwenum = fAllEnums[name]; return GetDialPos(rwenum); } int FitWeight::GetDialPos(int nuisenum) { for (size_t i = 0; i < fEnumList.size(); i++) { if (fEnumList[i] == nuisenum) { return i; } } - QTHROW("No Dial Found! (enum = " << nuisenum << ") "); + NUIS_ABORT("No Dial Found! (enum = " << nuisenum << ") "); } bool FitWeight::DialIncluded(std::string name) { return (fAllEnums.find(name) != fAllEnums.end()); } bool FitWeight::DialIncluded(int rwenum) { return (fAllValues.find(rwenum) != fAllValues.end()); } double FitWeight::CalcWeight(BaseFitEvt *evt) { double rwweight = 1.0; for (std::map::iterator iter = fAllRW.begin(); iter != fAllRW.end(); iter++) { double w = (*iter).second->CalcWeight(evt); rwweight *= w; } return rwweight; } void FitWeight::UpdateWeightEngine(const double *x) { size_t count = 0; for (std::vector::iterator iter = fEnumList.begin(); iter != fEnumList.end(); iter++) { SetDialValue((*iter), x[count]); count++; } } void FitWeight::GetAllDials(double *x, int n) { for (int i = 0; i < n; i++) { x[i] = GetDialValue(fEnumList[i]); } } // bool FitWeight::NeedsEventReWeight(const double* x) { // bool haschange = false; // size_t count = 0; // // Compare old to new and decide if RW needed. // for (std::vector::iterator iter = fEnumList.begin(); // iter != fEnumList.end(); iter++) { // int nuisenum = (*iter); // int type = (nuisenum / 1000) - (nuisenum % 1000); // // Compare old to new // double oldval = GetDialValue(nuisenum); // double newval = x[count]; // if (oldval != newval) { // if (fAllRW[type]->NeedsEventReWeight()) { // haschange = true; // } // } // count++; // } // return haschange; // } double FitWeight::GetSampleNorm(std::string name) { if (name.empty()) return 1.0; // Find norm dial if (fAllEnums.find(name + "_norm") != fAllEnums.end()) { if (fAllValues.find(fAllEnums[name + "_norm"]) != fAllValues.end()) { return fAllValues[fAllEnums[name + "_norm"]]; } else { return 1.0; } } else { return 1.0; } } void FitWeight::Print() { - QLOG(REC, "Fit Weight State: "); + NUIS_LOG(REC, "Fit Weight State: "); for (size_t i = 0; i < fNameList.size(); i++) { - QLOG(REC, " -> Par " << i << ". " << fNameList[i] << " " << fValueList[i]); + NUIS_LOG(REC, " -> Par " << i << ". " << fNameList[i] << " " << fValueList[i]); } } diff --git a/src/Reweight/GENIEWeightEngine.cxx b/src/Reweight/GENIEWeightEngine.cxx index 7bf6900..4888d02 100644 --- a/src/Reweight/GENIEWeightEngine.cxx +++ b/src/Reweight/GENIEWeightEngine.cxx @@ -1,464 +1,464 @@ #include "GENIEWeightEngine.h" #ifdef __GENIE_ENABLED__ #ifdef GENIE_PRE_R3 #include "Algorithm/AlgConfigPool.h" #include "EVGCore/EventRecord.h" #include "GHEP/GHepRecord.h" #include "Ntuple/NtpMCEventRecord.h" #ifndef __NO_GENIE_REWEIGHT__ #include "ReWeight/GReWeightAGKY.h" #include "ReWeight/GReWeightDISNuclMod.h" #include "ReWeight/GReWeightFGM.h" #include "ReWeight/GReWeightFZone.h" #include "ReWeight/GReWeightINuke.h" #include "ReWeight/GReWeightNonResonanceBkg.h" #include "ReWeight/GReWeightNuXSecCCQE.h" #include "ReWeight/GReWeightNuXSecCCQEvec.h" #include "ReWeight/GReWeightNuXSecCCRES.h" #include "ReWeight/GReWeightNuXSecCOH.h" #include "ReWeight/GReWeightNuXSecDIS.h" #include "ReWeight/GReWeightNuXSecNC.h" #include "ReWeight/GReWeightNuXSecNCEL.h" #include "ReWeight/GReWeightNuXSecNCRES.h" #include "ReWeight/GReWeightResonanceDecay.h" #include "ReWeight/GSystUncertainty.h" #ifdef __GENIE_EMP_MECRW_ENABLED #include "ReWeight/GReWeightXSecEmpiricalMEC.h" #endif #endif #if __GENIE_VERSION__ >= 212 #include "ReWeight/GReWeightNuXSecCCQEaxial.h" #endif #else // GENIE v3 #include "Framework/Algorithm/AlgConfigPool.h" #include "Framework/EventGen/EventRecord.h" #include "Framework/GHEP/GHepParticle.h" #include "Framework/GHEP/GHepRecord.h" #include "Framework/Ntuple/NtpMCEventRecord.h" #include "Framework/Utils/AppInit.h" #include "Framework/Utils/RunOpt.h" using namespace genie; #ifndef __NO_GENIE_REWEIGHT__ #include "RwCalculators/GReWeightAGKY.h" #include "RwCalculators/GReWeightDISNuclMod.h" #include "RwCalculators/GReWeightFGM.h" #include "RwCalculators/GReWeightFZone.h" #include "RwCalculators/GReWeightINuke.h" #include "RwCalculators/GReWeightNonResonanceBkg.h" #include "RwCalculators/GReWeightNuXSecCCQE.h" #include "RwCalculators/GReWeightNuXSecCCQEaxial.h" #include "RwCalculators/GReWeightNuXSecCCQEvec.h" #include "RwCalculators/GReWeightNuXSecCCRES.h" #include "RwCalculators/GReWeightNuXSecCOH.h" #include "RwCalculators/GReWeightNuXSecDIS.h" #include "RwCalculators/GReWeightNuXSecNC.h" #include "RwCalculators/GReWeightNuXSecNCEL.h" #include "RwCalculators/GReWeightNuXSecNCRES.h" #include "RwCalculators/GReWeightResonanceDecay.h" #include "RwCalculators/GReWeightXSecEmpiricalMEC.h" #include "RwFramework/GSystUncertainty.h" using namespace genie::rew; #endif #endif #endif #include "FitLogger.h" GENIEWeightEngine::GENIEWeightEngine(std::string name) { #ifdef __GENIE_ENABLED__ #ifndef __NO_GENIE_REWEIGHT__ // Setup the NEUT Reweight engien fCalcName = name; - QLOG(DEB, "Setting up GENIE RW : " << fCalcName); + NUIS_LOG(DEB, "Setting up GENIE RW : " << fCalcName); // Create RW Engine suppressing cout StopTalking(); fGenieRW = new genie::rew::GReWeight(); // Get List of Vetos (Just for debugging) std::string rw_engine_list = FitPar::Config().GetParS("FitWeight_fGenieRW_veto"); bool xsec_ncel = rw_engine_list.find("xsec_ncel") == std::string::npos; bool xsec_ccqe = rw_engine_list.find("xsec_ccqe") == std::string::npos; bool xsec_coh = rw_engine_list.find("xsec_coh") == std::string::npos; bool xsec_nnres = rw_engine_list.find("xsec_nonresbkg") == std::string::npos; bool xsec_nudis = rw_engine_list.find("nuclear_dis") == std::string::npos; bool xsec_resdec = rw_engine_list.find("hadro_res_decay") == std::string::npos; bool xsec_fzone = rw_engine_list.find("hadro_intranuke") == std::string::npos; bool xsec_intra = rw_engine_list.find("hadro_fzone") == std::string::npos; bool xsec_agky = rw_engine_list.find("hadro_agky") == std::string::npos; bool xsec_qevec = rw_engine_list.find("xsec_ccqe_vec") == std::string::npos; bool xsec_dis = rw_engine_list.find("xsec_dis") == std::string::npos; bool xsec_nc = rw_engine_list.find("xsec_nc") == std::string::npos; bool xsec_ccres = rw_engine_list.find("xsec_ccres") == std::string::npos; bool xsec_ncres = rw_engine_list.find("xsec_ncres") == std::string::npos; bool xsec_nucqe = rw_engine_list.find("nuclear_qe") == std::string::npos; bool xsec_qeaxial = rw_engine_list.find("xsec_ccqe_axial") == std::string::npos; #ifdef __GENIE_EMP_MECRW_ENABLED bool xsec_empMEC = rw_engine_list.find("xsec_empMEC") == std::string::npos; #endif #ifndef GENIE_PRE_R3 genie::RunOpt *grunopt = genie::RunOpt::Instance(); grunopt->EnableBareXSecPreCalc(true); grunopt->SetEventGeneratorList(Config::GetParS("GENIEEventGeneratorList")); grunopt->SetTuneName(Config::GetParS("GENIETune")); grunopt->BuildTune(); std::string genv = std::string(getenv("GENIE")) + "/config/Messenger_laconic.xml"; genie::utils::app_init::MesgThresholds(genv); #endif // Now actually add the RW Calcs if (xsec_ncel) fGenieRW->AdoptWghtCalc("xsec_ncel", new genie::rew::GReWeightNuXSecNCEL); if (xsec_ccqe) { fGenieRW->AdoptWghtCalc("xsec_ccqe", new genie::rew::GReWeightNuXSecCCQE); // (dynamic_cast (fGenieRW->WghtCalc("xsec_ccqe"))) // ->SetXSecModel( FitPar::Config().GetParS("GENIEXSecModelCCQE") ); } #ifdef __GENIE_EMP_MECRW_ENABLED if (xsec_empMEC) { fGenieRW->AdoptWghtCalc("xsec_empMEC", new genie::rew::GReWeightXSecEmpiricalMEC); } #endif if (xsec_coh) { fGenieRW->AdoptWghtCalc("xsec_coh", new genie::rew::GReWeightNuXSecCOH()); // (dynamic_cast (fGenieRW->WghtCalc("xsec_coh"))) // ->SetXSecModel( FitPar::Config().GetParS("GENIEXSecModelCOH") ); } if (xsec_nnres) fGenieRW->AdoptWghtCalc("xsec_nonresbkg", new genie::rew::GReWeightNonResonanceBkg); if (xsec_nudis) fGenieRW->AdoptWghtCalc("nuclear_dis", new genie::rew::GReWeightDISNuclMod); if (xsec_resdec) fGenieRW->AdoptWghtCalc("hadro_res_decay", new genie::rew::GReWeightResonanceDecay); if (xsec_fzone) fGenieRW->AdoptWghtCalc("hadro_fzone", new genie::rew::GReWeightFZone); if (xsec_intra) fGenieRW->AdoptWghtCalc("hadro_intranuke", new genie::rew::GReWeightINuke); if (xsec_agky) fGenieRW->AdoptWghtCalc("hadro_agky", new genie::rew::GReWeightAGKY); if (xsec_qevec) fGenieRW->AdoptWghtCalc("xsec_ccqe_vec", new genie::rew::GReWeightNuXSecCCQEvec); #if __GENIE_VERSION__ >= 212 if (xsec_qeaxial) fGenieRW->AdoptWghtCalc("xsec_ccqe_axial", new genie::rew::GReWeightNuXSecCCQEaxial); #endif if (xsec_dis) fGenieRW->AdoptWghtCalc("xsec_dis", new genie::rew::GReWeightNuXSecDIS); if (xsec_nc) fGenieRW->AdoptWghtCalc("xsec_nc", new genie::rew::GReWeightNuXSecNC); if (xsec_ccres) { #if __GENIE_VERSION__ < 213 fGenieRW->AdoptWghtCalc("xsec_ccres", new genie::rew::GReWeightNuXSecCCRES); #else fGenieRW->AdoptWghtCalc( "xsec_ccres", new genie::rew::GReWeightNuXSecCCRES( FitPar::Config().GetParS("GENIEXSecModelCCRES"), "Default")); #endif } if (xsec_ncres) fGenieRW->AdoptWghtCalc("xsec_ncres", new genie::rew::GReWeightNuXSecNCRES); if (xsec_nucqe) fGenieRW->AdoptWghtCalc("nuclear_qe", new genie::rew::GReWeightFGM); #if __GENIE_VERSION__ >= 212 // Set the CCQE reweighting style GReWeightNuXSecCCQE *rwccqe = dynamic_cast(fGenieRW->WghtCalc("xsec_ccqe")); // For MaCCQE reweighting std::string ccqetype = FitPar::Config().GetParS("GENIEWeightEngine_CCQEMode"); if (ccqetype == "kModeMa") { - QLOG(DEB, "Setting GENIE ReWeight CCQE to kModeMa"); + NUIS_LOG(DEB, "Setting GENIE ReWeight CCQE to kModeMa"); rwccqe->SetMode(GReWeightNuXSecCCQE::kModeMa); } else if (ccqetype == "kModeNormAndMaShape") { - QLOG(DEB, "Setting GENIE ReWeight CCQE to kModeNormAndMaShape"); + NUIS_LOG(DEB, "Setting GENIE ReWeight CCQE to kModeNormAndMaShape"); rwccqe->SetMode(GReWeightNuXSecCCQE::kModeNormAndMaShape); // For z-expansion reweighting } else if (ccqetype == "kModeZExp") { - QLOG(DEB, "Setting GENIE ReWeight CCQE to kModeZExp"); + NUIS_LOG(DEB, "Setting GENIE ReWeight CCQE to kModeZExp"); rwccqe->SetMode(GReWeightNuXSecCCQE::kModeZExp); } else { - QERROR(FTL, "Did not find specified GENIE ReWeight CCQE mode"); - QTHROW("You provided: " << ccqetype << " in parameters/config.xml"); + NUIS_ERR(FTL, "Did not find specified GENIE ReWeight CCQE mode"); + NUIS_ABORT("You provided: " << ccqetype << " in parameters/config.xml"); } // Check the UserPhysicsOptions too! AlgConfigPool *Pool = genie::AlgConfigPool::Instance(); Registry *full = Pool->GlobalParameterList(); std::string name_ax = full->GetAlg("AxialFormFactorModel").name; std::string config_ax = full->GetAlg("AxialFormFactorModel").config; if (name_ax == "genie::DipoleAxialFormFactorModel" && ccqetype == "kModeZExp") { - QERROR(FTL, + NUIS_ERR(FTL, "Trying to run Z Expansion reweighting with Llewelyn-Smith model."); - QERROR(FTL, "Please check your " + NUIS_ERR(FTL, "Please check your " << std::getenv("GENIE") << "/config/UserPhysicsOptions.xml to match generated"); - QERROR(FTL, "You're telling me " << name_ax << "/" << config_ax); - QTHROW("Also check your " + NUIS_ERR(FTL, "You're telling me " << name_ax << "/" << config_ax); + NUIS_ABORT("Also check your " << std::getenv("NUISANCE") << "/parameters/config.xml GENIEWeightEngine_CCQEMode: " << ccqetype); } if (name_ax == "genie::ZExpAxialFormFactorModel" && ccqetype != "kModeZExp") { - QERROR(FTL, + NUIS_ERR(FTL, "Trying to run Llewelyn-Smith reweighting with Z Expansion model."); - QERROR(FTL, "Please change your " + NUIS_ERR(FTL, "Please change your " << std::getenv("GENIE") << "/config/UserPhysicsOptions.xml to match generated"); - QERROR(FTL, "You're telling me " << name_ax << "/" << config_ax); - QTHROW("Also check your " + NUIS_ERR(FTL, "You're telling me " << name_ax << "/" << config_ax); + NUIS_ABORT("Also check your " << std::getenv("NUISANCE") << "/parameters/config.xml GENIEWeightEngine_CCQEMode: " << ccqetype); } std::string name_qelcc = full->GetAlg("XSecModel@genie::EventGenerator/QEL-CC").name; std::string config_qelcc = full->GetAlg("XSecModel@genie::EventGenerator/QEL-CC").config; if (config_qelcc == "Default" && ccqetype == "kModeZExp") { - QERROR(FTL, + NUIS_ERR(FTL, "Trying to run Z Expansion reweighting with Llewelyn-Smith model."); - QERROR(FTL, "Please change your " + NUIS_ERR(FTL, "Please change your " << std::getenv("GENIE") << "/config/UserPhysicsOptions.xml to match generated"); - QERROR(FTL, "You're telling me " << name_qelcc << "/" << config_qelcc); - QTHROW("Also check your " + NUIS_ERR(FTL, "You're telling me " << name_qelcc << "/" << config_qelcc); + NUIS_ABORT("Also check your " << std::getenv("NUISANCE") << "/parameters/config.xml GENIEWeightEngine_CCQEMode: " << ccqetype); } if (config_qelcc == "ZExp" && ccqetype != "kModeZExp") { - QERROR(FTL, + NUIS_ERR(FTL, "Trying to run Llewelyn-Smith reweighting with Z Expansion model."); - QERROR(FTL, "Please change your " + NUIS_ERR(FTL, "Please change your " << std::getenv("GENIE") << "/config/UserPhysicsOptions.xml to match generated"); - QERROR(FTL, "You're telling me " << name_qelcc << "/" << config_qelcc); - QTHROW("Also check your " + NUIS_ERR(FTL, "You're telling me " << name_qelcc << "/" << config_qelcc); + NUIS_ABORT("Also check your " << std::getenv("NUISANCE") << "/parameters/config.xml GENIEWeightEngine_CCQEMode: " << ccqetype); } #endif if (xsec_ccres) { // Default to include shape and normalization changes for CCRES (can be // changed downstream if desired) GReWeightNuXSecCCRES *rwccres = dynamic_cast(fGenieRW->WghtCalc("xsec_ccres")); std::string marestype = FitPar::Config().GetParS("GENIEWeightEngine_CCRESMode"); if (!marestype.compare("kModeNormAndMaMvShape")) { rwccres->SetMode(GReWeightNuXSecCCRES::kModeNormAndMaMvShape); } else if (!marestype.compare("kModeMaMv")) { rwccres->SetMode(GReWeightNuXSecCCRES::kModeMaMv); } else { - QTHROW("Unkown MARES Mode in GENIE Weight Engine : " << marestype); + NUIS_ABORT("Unkown MARES Mode in GENIE Weight Engine : " << marestype); } } if (xsec_ncres) { // Default to include shape and normalization changes for NCRES (can be // changed downstream if desired) GReWeightNuXSecNCRES *rwncres = dynamic_cast(fGenieRW->WghtCalc("xsec_ncres")); rwncres->SetMode(GReWeightNuXSecNCRES::kModeMaMv); } if (xsec_dis) { // Default to include shape and normalization changes for DIS (can be // changed downstream if desired) GReWeightNuXSecDIS *rwdis = dynamic_cast(fGenieRW->WghtCalc("xsec_dis")); rwdis->SetMode(GReWeightNuXSecDIS::kModeABCV12u); // Set Abs Twk Config fIsAbsTwk = (FitPar::Config().GetParB("setabstwk")); } // allow cout again StartTalking(); #else - QERROR(FTL, "GENIE ReWeight is __NOT ENABLED__ in GENIE and you're trying to " + NUIS_ERR(FTL, "GENIE ReWeight is __NOT ENABLED__ in GENIE and you're trying to " "run NUISANCE with it enabled"); - QERROR(FTL, "Check your genie-config --libs for reweighting"); - QERROR(FTL, "If not present you need to recompile GENIE"); - QTHROW("If present you need to contact NUISANCE authors"); + NUIS_ERR(FTL, "Check your genie-config --libs for reweighting"); + NUIS_ERR(FTL, "If not present you need to recompile GENIE"); + NUIS_ABORT("If present you need to contact NUISANCE authors"); #endif #endif }; void GENIEWeightEngine::IncludeDial(std::string name, double startval) { #ifdef __GENIE_ENABLED__ #ifndef __NO_GENIE_REWEIGHT__ // Get First enum int nuisenum = Reweight::ConvDial(name, kGENIE); // Check ZExp sillyness in GENIE // If ZExpansion parameters are used we need to set a different mode in GENIE // ReWeight... GENIE doesn't have a setter either... #if __GENIE_VERSION__ >= 212 std::string ccqetype = FitPar::Config().GetParS("GENIEWeightEngine_CCQEMode"); if (ccqetype != "kModeZExp" && (name == "ZExpA1CCQE" || name == "ZExpA2CCQE" || name == "ZExpA3CCQE" || name == "ZExpA4CCQE")) { - QERROR(FTL, "Found a Z-expansion parameter in GENIE although the GENIE " + NUIS_ERR(FTL, "Found a Z-expansion parameter in GENIE although the GENIE " "ReWeighting engine is set to use Llewelyn-Smith and MaQE!"); - QTHROW("Change your GENIE UserPhysicsOptions.xml in " + NUIS_ABORT("Change your GENIE UserPhysicsOptions.xml in " << std::getenv("GENIE") << "/config/UserPhysicsOptions.xml to match requirements"); } if ((ccqetype != "kModeMa" && ccqetype != "kModeMaNormAndMaShape") && (name == "MaCCQE")) { - QERROR(FTL, "Found MaCCQE parameter in GENIE although the GENIE " + NUIS_ERR(FTL, "Found MaCCQE parameter in GENIE although the GENIE " "ReWeighting engine is set to not use this!"); - QTHROW("Change your GENIE UserPhysicsOptions.xml in " + NUIS_ABORT("Change your GENIE UserPhysicsOptions.xml in " << std::getenv("GENIE") << "/config/UserPhysicsOptions.xml to match requirements"); } #endif // Setup Maps fEnumIndex[nuisenum]; // = std::vector(0); fNameIndex[name]; // = std::vector(0); // Split by commas std::vector allnames = GeneralUtils::ParseToStr(name, ","); for (uint i = 0; i < allnames.size(); i++) { std::string singlename = allnames[i]; // Get RW genie::rew::GSyst_t rwsyst = GSyst::FromString(singlename); // Fill Maps int index = fValues.size(); fValues.push_back(0.0); fGENIESysts.push_back(rwsyst); // Initialize dial - QLOG(DEB, "Registering " << singlename << " from " << name); + NUIS_LOG(DEB, "Registering " << singlename << " from " << name); fGenieRW->Systematics().Init(fGENIESysts[index]); // If Absolute if (fIsAbsTwk) { GSystUncertainty::Instance()->SetUncertainty(rwsyst, 1.0, 1.0); } // Setup index fEnumIndex[nuisenum].push_back(index); fNameIndex[name].push_back(index); } // Set Value if given if (startval != -999.9) { SetDialValue(nuisenum, startval); } #endif #endif }; void GENIEWeightEngine::SetDialValue(int nuisenum, double val) { #ifdef __GENIE_ENABLED__ #ifndef __NO_GENIE_REWEIGHT__ std::vector indices = fEnumIndex[nuisenum]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; fGenieRW->Systematics().Set(fGENIESysts[indices[i]], val); } #endif #endif } void GENIEWeightEngine::SetDialValue(std::string name, double val) { #ifdef __GENIE_ENABLED__ #ifndef __NO_GENIE_REWEIGHT__ std::vector indices = fNameIndex[name]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; fGenieRW->Systematics().Set(fGENIESysts[indices[i]], val); } #endif #endif } void GENIEWeightEngine::Reconfigure(bool silent) { #ifdef __GENIE_ENABLED__ #ifndef __NO_GENIE_REWEIGHT__ // Hush now... if (silent) StopTalking(); // Reconf fGenieRW->Reconfigure(); fGenieRW->Print(); // Shout again if (silent) StartTalking(); #endif #endif } double GENIEWeightEngine::CalcWeight(BaseFitEvt *evt) { double rw_weight = 1.0; #ifdef __GENIE_ENABLED__ #ifndef __NO_GENIE_REWEIGHT__ // Make nom weight if (!evt) { - QTHROW("evt not found : " << evt); + NUIS_ABORT("evt not found : " << evt); } // Skip Non GENIE if (evt->fType != kGENIE) return 1.0; if (!(evt->genie_event)) { - QTHROW("evt->genie_event not found!" << evt->genie_event); + NUIS_ABORT("evt->genie_event not found!" << evt->genie_event); } if (!(evt->genie_event->event)) { - QTHROW("evt->genie_event->event GHepRecord not found!" + NUIS_ABORT("evt->genie_event->event GHepRecord not found!" << (evt->genie_event->event)); } if (!fGenieRW) { - QTHROW("GENIE RW Not Found!" << fGenieRW); + NUIS_ABORT("GENIE RW Not Found!" << fGenieRW); } rw_weight = fGenieRW->CalcWeight(*(evt->genie_event->event)); // std::cout << "Returning GENIE Weight for electron scattering = " << // rw_weight << std::endl; // if (rw_weight != 1.0 )std::cout << "mode=" << evt->Mode << " rw_weight = " // << rw_weight << std::endl; #endif #endif // Return rw_weight return rw_weight; } diff --git a/src/Reweight/GlobalDialList.cxx b/src/Reweight/GlobalDialList.cxx index b0a4b11..9ba6410 100644 --- a/src/Reweight/GlobalDialList.cxx +++ b/src/Reweight/GlobalDialList.cxx @@ -1,49 +1,49 @@ #include "GlobalDialList.h" int GlobalDialList::EnumFromNameAndType(std::string name, int type) { // Setup Type Container if (fTypeEnumCont.find(type) == fTypeEnumCont.end()) { std::map temp; temp[name] = 0; fTypeEnumCont[type] = temp; } // Get Type Container std::map enumcont = fTypeEnumCont[type]; // Check name is in container, if its not add it if (enumcont.find(name) == enumcont.end()) { int index = enumcont.size(); enumcont[name] = index; fTypeEnumCont[type][name] = index; return index; } return enumcont[name]; } void GlobalDialList::RegisterDialEnum(std::string name, int type, int nuisenum) { if (std::find(fAllDialNames.begin(), fAllDialNames.end(), name) != fAllDialNames.end()) { return; } - QLOG(FIT, + NUIS_LOG(FIT, "Registered Dial Enum : " << name << " " << type << " " << nuisenum); fAllDialNames.push_back(name); fAllDialTypes.push_back(type); fAllDialEnums.push_back(nuisenum); } /// Singleton functions GlobalDialList &Reweight::DialList() { return GlobalDialList::Get(); } GlobalDialList *GlobalDialList::m_diallistInstance = NULL; GlobalDialList &GlobalDialList::Get(void) { if (!m_diallistInstance) m_diallistInstance = new GlobalDialList; return *m_diallistInstance; } diff --git a/src/Reweight/LikelihoodWeightEngine.cxx b/src/Reweight/LikelihoodWeightEngine.cxx index 5bb5b00..9bdf0e9 100644 --- a/src/Reweight/LikelihoodWeightEngine.cxx +++ b/src/Reweight/LikelihoodWeightEngine.cxx @@ -1,81 +1,81 @@ #include "WeightUtils.h" #include "LikelihoodWeightEngine.h" LikelihoodWeightEngine::LikelihoodWeightEngine(std::string name) { // Setup the NEUT Reweight engien fCalcName = name; - QLOG(FIT, "Setting up Likelihood Weight RW : " << fCalcName); + NUIS_LOG(FIT, "Setting up Likelihood Weight RW : " << fCalcName); // Set Abs Twk Config fIsAbsTwk = true; }; void LikelihoodWeightEngine::IncludeDial(std::string name, double startval) { // Get NUISANCE Enum int nuisenum = Reweight::ConvDial(name, kNORM); // Setup Maps fEnumIndex[nuisenum]; // = std::vector(0); fNameIndex[name]; // = std::vector(0); // Split by commas std::vector allnames = GeneralUtils::ParseToStr(name, ","); for (uint i = 0; i < allnames.size(); i++) { std::string singlename = allnames[i]; // Fill Maps int index = fValues.size(); fValues.push_back(1.0); fEnumIndex[nuisenum].push_back(index); fNameIndex[name].push_back(index); } // Set Value if given if (startval != -999.9) { SetDialValue(name, startval); } }; void LikelihoodWeightEngine::SetDialValue(int nuisenum, double val) { std::vector indices = fEnumIndex[nuisenum]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; } } void LikelihoodWeightEngine::SetDialValue(std::string name, double val) { std::vector indices = fNameIndex[name]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; } } double LikelihoodWeightEngine::GetDialValue(std::string name) { // Check for exact dial names if (fNameIndex.find(name) != fNameIndex.end()) { return fValues[fNameIndex[name][0]]; // If not iterate and check entry in one of the keys } else { for (std::map>::iterator iter = fNameIndex.begin(); iter != fNameIndex.end(); iter++) { std::string keyname = iter->first; if (keyname.find(name) != std::string::npos) { return fValues[iter->second[0]]; } } } return -1.0; } void LikelihoodWeightEngine::Reconfigure(bool silent) { // Empty placeholder incase we want print statements... } diff --git a/src/Reweight/MINERvAWeightCalcs.cxx b/src/Reweight/MINERvAWeightCalcs.cxx index ebe322b..4733a3e 100644 --- a/src/Reweight/MINERvAWeightCalcs.cxx +++ b/src/Reweight/MINERvAWeightCalcs.cxx @@ -1,632 +1,632 @@ #ifdef __MINERVA_RW_ENABLED__ #ifdef __GENIE_ENABLED__ #include "MINERvAWeightCalcs.h" #include "BaseFitEvt.h" namespace nuisance { namespace reweight { //******************************************************* MINERvAReWeight_QE::MINERvAReWeight_QE() { //******************************************************* fTwk_NormCCQE = 0.0; fDef_NormCCQE = 1.0; fCur_NormCCQE = fDef_NormCCQE; } //******************************************************* MINERvAReWeight_QE::~MINERvAReWeight_QE(){}; //******************************************************* //******************************************************* double MINERvAReWeight_QE::CalcWeight(BaseFitEvt *evt) { //******************************************************* // Check GENIE if (evt->fType != kGENIE) return 1.0; // Extract the GENIE Record GHepRecord *ghep = static_cast(evt->genie_event->event); const Interaction *interaction = ghep->Summary(); // const InitialState& init_state = interaction->InitState(); const ProcessInfo &proc_info = interaction->ProcInfo(); // const Target& tgt = init_state.Tgt(); // If the event is not QE this Calc doesn't handle it if (!proc_info.IsQuasiElastic()) return 1.0; // WEIGHT CALCULATIONS ------------- double w = 1.0; // CCQE Dial if (!proc_info.IsWeakCC()) w *= fCur_NormCCQE; // Return Combined Weight return w; } //******************************************************* void MINERvAReWeight_QE::SetDialValue(std::string name, double val) { //******************************************************* SetDialValue(Reweight::ConvDial(name, kCUSTOM), val); } //******************************************************* void MINERvAReWeight_QE::SetDialValue(int rwenum, double val) { //******************************************************* // Check Handled int curenum = rwenum % 1000; if (!IsHandled(curenum)) return; // Set Values if (curenum == Reweight::kMINERvARW_NormCCQE) { fTwk_NormCCQE = val; fCur_NormCCQE = fDef_NormCCQE + fTwk_NormCCQE; } // Define Tweaked fTweaked = ((fTwk_NormCCQE != 0.0)); } //******************************************************* bool MINERvAReWeight_QE::IsHandled(int rwenum) { //******************************************************* int curenum = rwenum % 1000; switch (curenum) { case Reweight::kMINERvARW_NormCCQE: return true; default: return false; } } //******************************************************* MINERvAReWeight_MEC::MINERvAReWeight_MEC() { //******************************************************* fTwk_NormCCMEC = 0.0; fDef_NormCCMEC = 1.0; fCur_NormCCMEC = fDef_NormCCMEC; } //******************************************************* MINERvAReWeight_MEC::~MINERvAReWeight_MEC(){}; //******************************************************* //******************************************************* double MINERvAReWeight_MEC::CalcWeight(BaseFitEvt *evt) { //******************************************************* // Check GENIE if (evt->fType != kGENIE) return 1.0; // Extract the GENIE Record GHepRecord *ghep = static_cast(evt->genie_event->event); const Interaction *interaction = ghep->Summary(); // const InitialState& init_state = interaction->InitState(); const ProcessInfo &proc_info = interaction->ProcInfo(); // const Target& tgt = init_state.Tgt(); // If the event is not MEC this Calc doesn't handle it if (!proc_info.IsMEC()) return 1.0; // WEIGHT CALCULATIONS ------------- double w = 1.0; // CCMEC Dial if (!proc_info.IsWeakCC()) w *= fCur_NormCCMEC; // Return Combined Weight return w; } //******************************************************* void MINERvAReWeight_MEC::SetDialValue(std::string name, double val) { //******************************************************* SetDialValue(Reweight::ConvDial(name, kCUSTOM), val); } //******************************************************* void MINERvAReWeight_MEC::SetDialValue(int rwenum, double val) { //******************************************************* // Check Handled int curenum = rwenum % 1000; if (!IsHandled(curenum)) return; // Set Values if (curenum == Reweight::kMINERvARW_NormCCMEC) { fTwk_NormCCMEC = val; fCur_NormCCMEC = fDef_NormCCMEC + fTwk_NormCCMEC; } // Define Tweaked fTweaked = ((fTwk_NormCCMEC != 0.0)); } //******************************************************* bool MINERvAReWeight_MEC::IsHandled(int rwenum) { //******************************************************* int curenum = rwenum % 1000; switch (curenum) { case Reweight::kMINERvARW_NormCCMEC: return true; default: return false; } } //******************************************************* MINERvAReWeight_RES::MINERvAReWeight_RES() { //******************************************************* fTwk_NormCCRES = 0.0; fDef_NormCCRES = 1.0; fCur_NormCCRES = fDef_NormCCRES; } //******************************************************* MINERvAReWeight_RES::~MINERvAReWeight_RES(){}; //******************************************************* //******************************************************* double MINERvAReWeight_RES::CalcWeight(BaseFitEvt *evt) { //******************************************************* // std::cout << "Caculating RES" << std::endl; // Check GENIE if (evt->fType != kGENIE) return 1.0; // Extract the GENIE Record GHepRecord *ghep = static_cast(evt->genie_event->event); const Interaction *interaction = ghep->Summary(); // const InitialState& init_state = interaction->InitState(); const ProcessInfo &proc_info = interaction->ProcInfo(); // const Target& tgt = init_state.Tgt(); // If the event is not RES this Calc doesn't handle it if (!proc_info.IsResonant()) return 1.0; // WEIGHT CALCULATIONS ------------- double w = 1.0; // CCRES Dial if (proc_info.IsWeakCC()) w *= fCur_NormCCRES; // Return Combined Weight return w; } //******************************************************* void MINERvAReWeight_RES::SetDialValue(std::string name, double val) { //******************************************************* SetDialValue(Reweight::ConvDial(name, kCUSTOM), val); } //******************************************************* void MINERvAReWeight_RES::SetDialValue(int rwenum, double val) { //******************************************************* // Check Handled int curenum = rwenum % 1000; if (!IsHandled(curenum)) return; // Set Values if (curenum == Reweight::kMINERvARW_NormCCRES) { fTwk_NormCCRES = val; fCur_NormCCRES = fDef_NormCCRES + fTwk_NormCCRES; } // Define Tweaked fTweaked = ((fTwk_NormCCRES != 0.0)); } //******************************************************* bool MINERvAReWeight_RES::IsHandled(int rwenum) { //******************************************************* int curenum = rwenum % 1000; switch (curenum) { case Reweight::kMINERvARW_NormCCRES: return true; default: return false; } } //******************************************************* RikRPA::RikRPA() { //******************************************************* // - Syst : kMINERvA_RikRPA_ApplyRPA // - Type : Binary // - Limits : 0.0 (false) -> 1.0 (true) // - Default : 0.0 fApplyDial_RPACorrection = false; // - Syst : kMINERvA_RikRPA_LowQ2 // - Type : Absolute // - Limits : 1.0 -> 1.0 // - Default : 0.0 // - Frac Error : 100% fDefDial_RPALowQ2 = 0.0; fCurDial_RPALowQ2 = fDefDial_RPALowQ2; fErrDial_RPALowQ2 = 0.0; // - Syst : kMINERvA_RikRPA_HighQ2 // - Type : Absolute // - Limits : 1.0 -> 1.0 // - Default : 0.0 // - Frac Error : 100% fDefDial_RPAHighQ2 = 0.0; fCurDial_RPAHighQ2 = fDefDial_RPAHighQ2; fErrDial_RPAHighQ2 = 1.0; // - Syst : kMINERvA_RikRESRPA_ApplyRPA // - Type : Binary // - Limits : 0.0 (false) -> 1.0 (true) // - Default : 0.0 fApplyDial_RESRPACorrection = false; // - Syst : kMINERvA_RikRESRPA_LowQ2 // - Type : Absolute // - Limits : 1.0 -> 1.0 // - Default : 0.0 // - Frac Error : 100% fDefDial_RESRPALowQ2 = 0.0; fCurDial_RESRPALowQ2 = fDefDial_RESRPALowQ2; fErrDial_RESRPALowQ2 = 0.0; // - Syst : kMINERvA_RikRESRPA_HighQ2 // - Type : Absolute // - Limits : 1.0 -> 1.0 // - Default : 0.0 // - Frac Error : 100% fDefDial_RESRPAHighQ2 = 0.0; fCurDial_RESRPAHighQ2 = fDefDial_RESRPAHighQ2; fErrDial_RESRPAHighQ2 = 1.0; // Setup Calculators fEventWeights = new double[5]; for (int i = 0; i < kMaxCalculators; i++) { fRPACalculators[i] = NULL; } fTweaked = false; } //******************************************************* RikRPA::~RikRPA() { //******************************************************* // delete fEventWeights; // for (size_t i = 0; i < kMaxCalculators; i++) { // if (fRPACalculators[i]) delete fRPACalculators[i]; // fRPACalculators[i] = NULL; // } } //******************************************************* double RikRPA::CalcWeight(BaseFitEvt *evt) { //******************************************************* // LOG(FIT) << "Calculating RikRPA" << std::endl; // Return 1.0 if not tweaked if (!fTweaked) return 1.0; double w = 1.0; // Extract the GENIE Record GHepRecord *ghep = static_cast(evt->genie_event->event); const Interaction *interaction = ghep->Summary(); const InitialState &init_state = interaction->InitState(); const ProcessInfo &proc_info = interaction->ProcInfo(); // const Kinematics & kine = interaction->Kine(); // const XclsTag & xcls = interaction->ExclTag(); const Target &tgt = init_state.Tgt(); // If not QE return 1.0 // LOG(FIT) << "RikRPA : Event QE = " << proc_info.IsQuasiElastic() << // std::endl; if (!tgt.IsNucleus()) { return 1.0; } if (!proc_info.IsQuasiElastic() && !proc_info.IsResonant()) return 1.0; // Extract Beam and Target PDG GHepParticle *neutrino = ghep->Probe(); int bpdg = neutrino->Pdg(); GHepParticle *target = ghep->TargetNucleus(); assert(target); int tpdg = target->Pdg(); // Find the enum we need int calcenum = GetRPACalcEnum(bpdg, tpdg); if (calcenum == -1) return 1.0; // Check we have the RPA Calc setup for this enum // if not, set it up at that point if (!fRPACalculators[calcenum]) SetupRPACalculator(calcenum); weightRPA *rpacalc = fRPACalculators[calcenum]; if (!rpacalc) { - QTHROW("Failed to grab the RPA Calculator : " << calcenum); + NUIS_ABORT("Failed to grab the RPA Calculator : " << calcenum); } // Extract Q0-Q3 GHepParticle *fsl = ghep->FinalStatePrimaryLepton(); const TLorentzVector &k1 = *(neutrino->P4()); const TLorentzVector &k2 = *(fsl->P4()); double q0 = fabs((k1 - k2).E()); double q3 = fabs((k1 - k2).Vect().Mag()); double Q2 = fabs((k1 - k2).Mag2()); // Quasielastic if (proc_info.IsQuasiElastic()) { // Now use q0-q3 and RPA Calculator to fill fWeights rpacalc->getWeight(q0, q3, fEventWeights); if (fApplyDial_RPACorrection) { w *= fEventWeights[0]; // CV } // Syst Application : kMINERvA_RikRPA_LowQ2 if (fabs(fCurDial_RPALowQ2) > 0.0) { double interpw = fEventWeights[0]; if (fCurDial_RPALowQ2 > 0.0 && Q2 < 2.0) { interpw = fEventWeights[0] - (fEventWeights[0] - fEventWeights[1]) * fCurDial_RPALowQ2; // WLow+ } else if } else if (fCurDial_RPALowQ2 < 0.0 && Q2 < 2.0) { interpw = fEventWeights[0] - (fEventWeights[2] - fEventWeights[0]) * fCurDial_RPALowQ2; // WLow- } w *= interpw / fEventWeights[0]; // Div by CV again } // Syst Application : kMINERvA_RikRPA_HighQ2 if (fabs(fCurDial_RPAHighQ2) > 0.0) { double interpw = fEventWeights[0]; if (fCurDial_RPAHighQ2 > 0.0) { interpw = fEventWeights[0] - (fEventWeights[0] - fEventWeights[3]) * fCurDial_RPAHighQ2; // WHigh+ } else if (fCurDial_RPAHighQ2 < 0.0) { interpw = fEventWeights[0] - (fEventWeights[4] - fEventWeights[0]) * fCurDial_RPAHighQ2; // WHigh- } w *= interpw / fEventWeights[0]; // Div by CV again } } // Resonant Events if (proc_info.IsResonant()) { // Now use Q2 and RESRPA Calculator to fill fWeights double CV = rpacalc->getWeight(Q2); if (fApplyDial_RESRPACorrection) { w *= CV; // fEventWeights[0]; // CVa } /* // Syst Application : kMINERvA_RikRESRPA_LowQ2 if (fabs(fCurDial_RESRPAHighQ2) > 0.0) { double interpw = fEventWeights[0]; if (fCurDial_RESRPAHighQ2 > 0.0) { interpw = fEventWeights[0] - (fEventWeights[0] - fEventWeights[3]) * fCurDial_RESRPAHighQ2; // WHigh+ } else if (fCurDial_RESRPAHighQ2 < 0.0) { interpw = fEventWeights[0] - (fEventWeights[4] - fEventWeights[0]) * fCurDial_RESRPAHighQ2; // WHigh- } w *= interpw / fEventWeights[0]; // Div by CV again } // Syst Application : kMINERvA_RikRESRPA_HighQ2 if (fabs(fCurDial_RESRPAHighQ2) > 0.0) { double interpw = fEventWeights[0]; if (fCurDial_RESRPAHighQ2 > 0.0) { interpw = fEventWeights[0] - (fEventWeights[0] - fEventWeights[3]) * fCurDial_RESRPAHighQ2; // WHigh+ } else if (fCurDial_RESRPAHighQ2 < 0.0) { interpw = fEventWeights[0] - (fEventWeights[4] - fEventWeights[0]) * fCurDial_RESRPAHighQ2; // WHigh- } w *= interpw / fEventWeights[0]; // Div by CV again } */ } // LOG(FIT) << "RPA Weight = " << w << std::endl; return w; } // namespace reweight //******************************************************* void RikRPA::SetDialValue(std::string name, double val) { //******************************************************* SetDialValue(Reweight::ConvDial(name, kCUSTOM), val); } //******************************************************* void RikRPA::SetDialValue(int rwenum, double val) { //******************************************************* int curenum = rwenum % 1000; // Check Handled if (!IsHandled(curenum)) return; if (curenum == Reweight::kMINERvARW_RikRPA_ApplyRPA) fApplyDial_RPACorrection = (val > 0.5); if (curenum == Reweight::kMINERvARW_RikRPA_LowQ2) fCurDial_RPALowQ2 = val; if (curenum == Reweight::kMINERvARW_RikRPA_HighQ2) fCurDial_RPAHighQ2 = val; if (curenum == Reweight::kMINERvARW_RikRESRPA_ApplyRPA) fApplyDial_RESRPACorrection = (val > 0.5); if (curenum == Reweight::kMINERvARW_RikRESRPA_LowQ2) fCurDial_RESRPALowQ2 = val; if (curenum == Reweight::kMINERvARW_RikRESRPA_HighQ2) fCurDial_RESRPAHighQ2 = val; // Assign flag to say stuff has changed fTweaked = (fApplyDial_RPACorrection || fabs(fCurDial_RPAHighQ2 - fDefDial_RPAHighQ2) > 0.0 || fabs(fCurDial_RPALowQ2 - fDefDial_RPALowQ2) > 0.0 || fApplyDial_RESRPACorrection || fabs(fCurDial_RESRPAHighQ2 - fDefDial_RESRPAHighQ2) > 0.0 || fabs(fCurDial_RESRPALowQ2 - fDefDial_RESRPALowQ2) > 0.0); } //******************************************************* bool RikRPA::IsHandled(int rwenum) { //******************************************************* int curenum = rwenum % 1000; switch (curenum) { case Reweight::kMINERvARW_RikRESRPA_ApplyRPA: return true; case Reweight::kMINERvARW_RikRESRPA_LowQ2: return true; case Reweight::kMINERvARW_RikRESRPA_HighQ2: return true; case Reweight::kMINERvARW_RikRPA_ApplyRPA: return true; case Reweight::kMINERvARW_RikRPA_LowQ2: return true; case Reweight::kMINERvARW_RikRPA_HighQ2: return true; default: return false; } } //******************************************************* void RikRPA::SetupRPACalculator(int calcenum) { //******************************************************* std::string rwdir = FitPar::GetDataBase() + "reweight/MINERvA/RikRPA/"; std::string fidir = ""; switch (calcenum) { case kNuMuC12: fidir = "outNievesRPAratio-nu12C-20GeV-20170202.root"; break; case kNuMuO16: fidir = "outNievesRPAratio-nu16O-20GeV-20170202.root"; break; case kNuMuAr40: fidir = "outNievesRPAratio-nu40Ar-20GeV-20170202.root"; break; case kNuMuCa40: fidir = "outNievesRPAratio-nu40Ca-20GeV-20170202.root"; break; case kNuMuFe56: fidir = "outNievesRPAratio-nu56Fe-20GeV-20170202.root"; break; case kNuMuBarC12: fidir = "outNievesRPAratio-anu12C-20GeV-20170202.root"; break; case kNuMuBarO16: fidir = "outNievesRPAratio-anu16O-20GeV-20170202.root"; break; case kNuMuBarAr40: fidir = "outNievesRPAratio-anu40Ar-20GeV-20170202.root"; break; case kNuMuBarCa40: fidir = "outNievesRPAratio-anu40Ca-20GeV-20170202.root"; break; case kNuMuBarFe56: fidir = "outNievesRPAratio-anu56Fe-20GeV-20170202.root"; break; } - QLOG(FIT, "Loading RPA CALC : " << fidir); + NUIS_LOG(FIT, "Loading RPA CALC : " << fidir); TDirectory *olddir = gDirectory; - QLOG(FIT, "***********************************************"); - QLOG(FIT, "Loading a new weightRPA calculator"); - QLOG(FIT, "Authors: Rik Gran, Heidi Schellman"); - QLOG(FIT, "Citation: arXiv:1705.02932 [hep-ex]"); - QLOG(FIT, "***********************************************"); + NUIS_LOG(FIT, "***********************************************"); + NUIS_LOG(FIT, "Loading a new weightRPA calculator"); + NUIS_LOG(FIT, "Authors: Rik Gran, Heidi Schellman"); + NUIS_LOG(FIT, "Citation: arXiv:1705.02932 [hep-ex]"); + NUIS_LOG(FIT, "***********************************************"); // Test the file exists std::ifstream infile((rwdir + fidir).c_str()); if (!infile.good()) { - QERROR(FTL, "*** ERROR ***"); - QERROR(FTL, "RikRPA file " << rwdir + fidir << " does not exist!"); - QERROR(FTL, + NUIS_ERR(FTL, "*** ERROR ***"); + NUIS_ERR(FTL, "RikRPA file " << rwdir + fidir << " does not exist!"); + NUIS_ERR(FTL, "These can be found at https://nuisance.hepforge.org/files/RikRPA/"); - QERROR(FTL, + NUIS_ERR(FTL, "Please run: wget -r -nH --cut-dirs=2 -np -e robots=off -R " "\"index.html*\" https://nuisance.hepforge.org/files/RikRPA/ -P " << rwdir); - QERROR(FTL, "And try again"); - QTHROW("*************"); + NUIS_ERR(FTL, "And try again"); + NUIS_ABORT("*************"); } fRPACalculators[calcenum] = new weightRPA(rwdir + fidir); olddir->cd(); return; } //******************************************************* int RikRPA::GetRPACalcEnum(int bpdg, int tpdg) { //******************************************************* if (bpdg == 14 && tpdg == 1000060120) return kNuMuC12; else if (bpdg == 14 && tpdg == 1000080160) return kNuMuO16; else if (bpdg == 14 && tpdg == 1000180400) return kNuMuAr40; else if (bpdg == 14 && tpdg == 1000200400) return kNuMuCa40; else if (bpdg == 14 && tpdg == 1000280560) return kNuMuFe56; else if (bpdg == -14 && tpdg == 1000060120) return kNuMuBarC12; else if (bpdg == -14 && tpdg == 1000080160) return kNuMuBarO16; else if (bpdg == -14 && tpdg == 1000180400) return kNuMuBarAr40; else if (bpdg == -14 && tpdg == 1000200400) return kNuMuBarCa40; else if (bpdg == -14 && tpdg == 1000280560) return kNuMuBarFe56; else { - // QERROR(WRN, "Unknown beam and target combination for RPA Calcs! " + // NUIS_ERR(WRN, "Unknown beam and target combination for RPA Calcs! " //<< bpdg << " " << tpdg); } return -1; } } // namespace reweight } // namespace nuisance #endif #endif diff --git a/src/Reweight/ModeNormEngine.h b/src/Reweight/ModeNormEngine.h index ee9f0d8..124b189 100644 --- a/src/Reweight/ModeNormEngine.h +++ b/src/Reweight/ModeNormEngine.h @@ -1,86 +1,86 @@ #ifndef ModeNormEngine_H #define ModeNormEngine_H #include "FitLogger.h" #include "GeneratorUtils.h" #include "WeightEngineBase.h" class ModeNormEngine : public WeightEngineBase { public: ModeNormEngine(std::string name = "ModeNormEngine") : fName(name){}; ~ModeNormEngine(){}; void IncludeDial(std::string name, double startval) { int rwenum = Reweight::ConvDial(name, kMODENORM); int mode = Reweight::RemoveDialType(rwenum); if (fDialEnumIndex.count(mode)) { - QTHROW("Mode dial: " << mode + NUIS_ABORT("Mode dial: " << mode << " already included. Cannot include twice."); } fDialEnumIndex[mode] = fDialValues.size(); fDialValues.push_back(startval); - QLOG(FIT, "Added mode dial for mode: " << mode); + NUIS_LOG(FIT, "Added mode dial for mode: " << mode); } void SetDialValue(int rwenum, double val) { int mode = Reweight::RemoveDialType(rwenum); if (!fDialEnumIndex.count(mode)) { - QTHROW("Mode dial: " << mode + NUIS_ABORT("Mode dial: " << mode << " has not been included. Cannot set value."); } - QLOG(DEB, "[INFO]: ModeNormEngine ObsMode: " << mode << " weight " << val + NUIS_LOG(DEB, "[INFO]: ModeNormEngine ObsMode: " << mode << " weight " << val << ", rwenum = " << rwenum); fDialValues[fDialEnumIndex[mode]] = val; } void SetDialValue(std::string name, double val) { SetDialValue(Reweight::ConvDial(name, kMODENORM), val); } void Reconfigure(bool silent = false) { (void)silent; } static int ModeToDial(int mode) { return 60 + mode; } double CalcWeight(BaseFitEvt *evt) { int mode = ModeToDial(abs(evt->Mode)); if (!fDialEnumIndex.count(mode)) { return 1; } - QLOG(DEB, "[INFO]: Ev mode " + NUIS_LOG(DEB, "[INFO]: Ev mode " << evt->Mode << ", ObsMode: " << mode << ", weight = " << fDialValues[fDialEnumIndex[mode]]); return fDialValues[fDialEnumIndex[mode]]; }; bool NeedsEventReWeight() { return false; }; double GetDialValue(std::string name) { int rwenum = Reweight::ConvDial(name, kMODENORM); int mode = Reweight::RemoveDialType(rwenum); if (fDialEnumIndex.count(mode)) { return fDialValues[fDialEnumIndex[mode]]; } else { return 0xdeadbeef; } } static int SystEnumFromString(std::string const &name) { std::vector splits = GeneralUtils::ParseToStr(name, "_"); if (splits.size() != 2) { - QTHROW("Attempting to parse dial name: \"" + NUIS_ABORT("Attempting to parse dial name: \"" << name << "\" as a mode norm dial but failed. Expect e.g. \"mode_2\"."); } int mode_num = GeneralUtils::StrToInt(splits[1]); if (!mode_num) { - QTHROW("Attempting to parse dial name: \"" + NUIS_ABORT("Attempting to parse dial name: \"" << name << "\" as a mode norm dial but failed."); } return ModeToDial(mode_num); } std::map fDialEnumIndex; std::vector fDialValues; std::string fName; }; #endif diff --git a/src/Reweight/NEUTWeightEngine.cxx b/src/Reweight/NEUTWeightEngine.cxx index 429b044..88b515f 100644 --- a/src/Reweight/NEUTWeightEngine.cxx +++ b/src/Reweight/NEUTWeightEngine.cxx @@ -1,179 +1,179 @@ #include "NEUTWeightEngine.h" NEUTWeightEngine::NEUTWeightEngine(std::string name) { #ifdef __NEUT_ENABLED__ // Setup the NEUT Reweight engien fCalcName = name; - QLOG(FIT, "Setting up NEUT RW : " << fCalcName); + NUIS_LOG(FIT, "Setting up NEUT RW : " << fCalcName); // Create RW Engine suppressing cout StopTalking(); fNeutRW = new neut::rew::NReWeight(); TDirectory *olddir = gDirectory; // get list of vetoed calc engines (just for debug really) std::string rw_engine_list = FitPar::Config().GetParS("FitWeight_fNeutRW_veto"); bool xsec_ccqe = rw_engine_list.find("xsec_ccqe") == std::string::npos; bool xsec_res = rw_engine_list.find("xsec_res") == std::string::npos; bool xsec_ccres = rw_engine_list.find("xsec_ccres") == std::string::npos; bool xsec_coh = rw_engine_list.find("xsec_coh") == std::string::npos; bool xsec_dis = rw_engine_list.find("xsec_dis") == std::string::npos; bool xsec_ncel = rw_engine_list.find("xsec_ncel") == std::string::npos; bool xsec_nc = rw_engine_list.find("xsec_nc") == std::string::npos; bool xsec_ncres = rw_engine_list.find("xsec_ncres") == std::string::npos; bool nucl_casc = rw_engine_list.find("nucl_casc") == std::string::npos; bool nucl_piless = rw_engine_list.find("nucl_piless") == std::string::npos; // Activate each calc engine if (xsec_ccqe) fNeutRW->AdoptWghtCalc("xsec_ccqe", new neut::rew::NReWeightNuXSecCCQE); if (xsec_res) fNeutRW->AdoptWghtCalc("xsec_res", new neut::rew::NReWeightNuXSecRES); if (xsec_ccres) fNeutRW->AdoptWghtCalc("xsec_ccres", new neut::rew::NReWeightNuXSecCCRES); if (xsec_coh) fNeutRW->AdoptWghtCalc("xsec_coh", new neut::rew::NReWeightNuXSecCOH); if (xsec_dis) fNeutRW->AdoptWghtCalc("xsec_dis", new neut::rew::NReWeightNuXSecDIS); if (xsec_ncel) fNeutRW->AdoptWghtCalc("xsec_ncel", new neut::rew::NReWeightNuXSecNCEL); if (xsec_nc) fNeutRW->AdoptWghtCalc("xsec_nc", new neut::rew::NReWeightNuXSecNC); if (xsec_ncres) fNeutRW->AdoptWghtCalc("xsec_ncres", new neut::rew::NReWeightNuXSecNCRES); if (nucl_casc) fNeutRW->AdoptWghtCalc("nucl_casc", new neut::rew::NReWeightCasc); if (nucl_piless) fNeutRW->AdoptWghtCalc("nucl_piless", new neut::rew::NReWeightNuclPiless); fNeutRW->Reconfigure(); olddir->cd(); // Set Abs Twk Config fIsAbsTwk = (FitPar::Config().GetParB("setabstwk")); // allow cout again StartTalking(); #else - QTHROW("NEUT RW NOT ENABLED!"); + NUIS_ABORT("NEUT RW NOT ENABLED!"); #endif }; void NEUTWeightEngine::IncludeDial(std::string name, double startval) { #ifdef __NEUT_ENABLED__ // Get First enum int nuisenum = Reweight::ConvDial(name, kNEUT); // Setup Maps fEnumIndex[nuisenum]; // = std::vector(0); fNameIndex[name]; // = std::vector(0); // Split by commas std::vector allnames = GeneralUtils::ParseToStr(name, ","); for (uint i = 0; i < allnames.size(); i++) { std::string singlename = allnames[i]; // Get Syst neut::rew::NSyst_t gensyst = NSyst::FromString(singlename); // Fill Maps int index = fValues.size(); fValues.push_back(0.0); fNEUTSysts.push_back(gensyst); // Initialize dial - QLOG(FIT, "Registering " << singlename << " dial."); + NUIS_LOG(FIT, "Registering " << singlename << " dial."); fNeutRW->Systematics().Init(fNEUTSysts[index]); // If Absolute if (fIsAbsTwk) { NSystUncertainty::Instance()->SetUncertainty(fNEUTSysts[index], 1.0, 1.0); } // Setup index fEnumIndex[nuisenum].push_back(index); fNameIndex[name].push_back(index); } // Set Value if given if (startval != -999.9) { SetDialValue(nuisenum, startval); } #endif } void NEUTWeightEngine::SetDialValue(int nuisenum, double val) { #ifdef __NEUT_ENABLED__ std::vector indices = fEnumIndex[nuisenum]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; - QLOG(FIT, "Setting Dial Value for " << nuisenum << " " << i << " " + NUIS_LOG(FIT, "Setting Dial Value for " << nuisenum << " " << i << " " << indices[i] << " " << fValues[indices[i]] << " Enum: " << fNEUTSysts[indices[i]]); fNeutRW->Systematics().Set(fNEUTSysts[indices[i]], val); } #endif } void NEUTWeightEngine::SetDialValue(std::string name, double val) { #ifdef __NEUT_ENABLED__ std::vector indices = fNameIndex[name]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; - QLOG(FIT, "Setting Dial Value for " + NUIS_LOG(FIT, "Setting Dial Value for " << name << " = " << i << " " << indices[i] << " " << fValues[indices[i]] << " Enum: " << fNEUTSysts[indices[i]]); fNeutRW->Systematics().Set(fNEUTSysts[indices[i]], val); } #endif } void NEUTWeightEngine::Reconfigure(bool silent) { #ifdef __NEUT_ENABLED__ // Hush now... if (silent) StopTalking(); // Reconf fNeutRW->Reconfigure(); // if (LOG_LEVEL(DEB)){ fNeutRW->Print(); // } // Shout again if (silent) StartTalking(); #endif } double NEUTWeightEngine::CalcWeight(BaseFitEvt *evt) { double rw_weight = 1.0; #ifdef __NEUT_ENABLED__ // Skip Non NEUT if (evt->fType != kNEUT) return 1.0; // Hush now StopTalking(); // Fill NEUT Common blocks NEUTUtils::FillNeutCommons(evt->fNeutVect); // Call Weight calculation rw_weight = fNeutRW->CalcWeight(); // Speak Now StartTalking(); #endif // Return rw_weight return rw_weight; } diff --git a/src/Reweight/NIWGWeightEngine.cxx b/src/Reweight/NIWGWeightEngine.cxx index aa94d07..a1dd53a 100644 --- a/src/Reweight/NIWGWeightEngine.cxx +++ b/src/Reweight/NIWGWeightEngine.cxx @@ -1,215 +1,215 @@ #include "NIWGWeightEngine.h" NIWGWeightEngine::NIWGWeightEngine(std::string name) { #ifdef __NIWG_ENABLED__ #ifdef __NEUT_ENABLED__ // Setup the NEUT Reweight engien fCalcName = name; - QLOG(FIT, "Setting up NIWG RW : " << fCalcName); + NUIS_LOG(FIT, "Setting up NIWG RW : " << fCalcName); // Create RW Engine suppressing cout StopTalking(); fNIWGRW = new niwg::rew::NIWGReWeight(); // Get List of Veto Calcs (For Debugging) std::string rw_engine_list = FitPar::Config().GetParS("FitWeight_fNIWGRW_veto"); bool niwg_2012a = rw_engine_list.find("niwg_2012a") == std::string::npos; bool niwg_2014a = rw_engine_list.find("niwg_2014a") == std::string::npos; bool niwg_pimult = rw_engine_list.find("niwg_pimult") == std::string::npos; bool niwg_mec = rw_engine_list.find("niwg_mec") == std::string::npos; bool niwg_rpa = rw_engine_list.find("niwg_rpa") == std::string::npos; bool niwg_eff_rpa = rw_engine_list.find("niwg_eff_rpa") == std::string::npos; bool niwg_proton = rw_engine_list.find("niwg_protonFSIbug") == std::string::npos; bool niwg_hadron = rw_engine_list.find("niwg_HadronMultSwitch") == std::string::npos; // Add the RW Calcs if (niwg_2012a) fNIWGRW->AdoptWghtCalc("niwg_2012a", new niwg::rew::NIWGReWeight2012a); if (niwg_2014a) fNIWGRW->AdoptWghtCalc("niwg_2014a", new niwg::rew::NIWGReWeight2014a); if (niwg_pimult) fNIWGRW->AdoptWghtCalc("niwg_pimult", new niwg::rew::NIWGReWeightPiMult); if (niwg_mec) fNIWGRW->AdoptWghtCalc("niwg_mec", new niwg::rew::NIWGReWeightMEC); if (niwg_rpa) fNIWGRW->AdoptWghtCalc("niwg_rpa", new niwg::rew::NIWGReWeightRPA); if (niwg_eff_rpa) fNIWGRW->AdoptWghtCalc("niwg_eff_rpa", new niwg::rew::NIWGReWeightEffectiveRPA); if (niwg_proton) fNIWGRW->AdoptWghtCalc("niwg_protonFSIbug", new niwg::rew::NIWGReWeightProtonFSIbug); if (niwg_hadron) fNIWGRW->AdoptWghtCalc("niwg_HadronMultSwitch", new niwg::rew::NIWGReWeightHadronMultSwitch); fNIWGRW->Reconfigure(); // Set Abs Twk Config fIsAbsTwk = (FitPar::Config().GetParB("setabstwk")); // allow cout again StartTalking(); #else - QTHROW("NIWG RW Enabled but NEUT RW is not!"); + NUIS_ABORT("NIWG RW Enabled but NEUT RW is not!"); #endif #else - QTHROW("NIWG RW NOT ENABLED!"); + NUIS_ABORT("NIWG RW NOT ENABLED!"); #endif }; void NIWGWeightEngine::IncludeDial(std::string name, double startval) { #ifdef __NIWG_ENABLED__ #ifdef __NEUT_ENABLED__ // Get First enum int nuisenum = Reweight::ConvDial(name, kNIWG); // Setup Maps fEnumIndex[nuisenum]; // = std::vector(0); fNameIndex[name]; // = std::vector(0); // Split by commas std::vector allnames = GeneralUtils::ParseToStr(name, ","); for (uint i = 0; i < allnames.size(); i++) { std::string singlename = allnames[i]; // Get RW niwg::rew::NIWGSyst_t gensyst = niwg::rew::NIWGSyst::FromString(name); // Fill Maps int index = fValues.size(); fValues.push_back(0.0); fNIWGSysts.push_back(gensyst); // Initialize dial - QLOG(FIT, "Registering " << singlename << " from " << name); + NUIS_LOG(FIT, "Registering " << singlename << " from " << name); fNIWGRW->Systematics().Init(fNIWGSysts[index]); // If Absolute if (fIsAbsTwk) { niwg::rew::NIWGSystUncertainty::Instance()->SetUncertainty( fNIWGSysts[index], 1.0, 1.0); } // Setup index fEnumIndex[nuisenum].push_back(index); fNameIndex[name].push_back(index); } // Set Value if given if (startval != -999.9) { SetDialValue(nuisenum, startval); } #endif #endif } void NIWGWeightEngine::SetDialValue(int nuisenum, double val) { #ifdef __NIWG_ENABLED__ #ifdef __NEUT_ENABLED__ std::vector indices = fEnumIndex[nuisenum]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; std::cout << "Setting NIWG Dial Value " << i << " " << indices[i] << " " << fNIWGSysts[indices[i]] << std::endl; fNIWGRW->Systematics().Set(fNIWGSysts[indices[i]], val); } #endif #endif } void NIWGWeightEngine::SetDialValue(std::string name, double val) { #ifdef __NIWG_ENABLED__ #ifdef __NEUT_ENABLED__ std::vector indices = fNameIndex[name]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; fNIWGRW->Systematics().Set(fNIWGSysts[indices[i]], val); } #endif #endif } void NIWGWeightEngine::Reconfigure(bool silent) { #ifdef __NIWG_ENABLED__ #ifdef __NEUT_ENABLED__ // Hush now... if (silent) StopTalking(); // Reconf fNIWGRW->Reconfigure(); // Shout again if (silent) StartTalking(); #endif #endif } double NIWGWeightEngine::CalcWeight(BaseFitEvt *evt) { double rw_weight = 1.0; #ifdef __NEUT_ENABLED__ #ifdef __NIWG_ENABLED__ // Skip Non GENIE if (evt->fType != kNEUT) return 1.0; // Hush now StopTalking(); niwg::rew::NIWGEvent *niwg_event = NIWGWeightEngine::GetNIWGEventLocal(evt->fNeutVect); rw_weight *= fNIWGRW->CalcWeight(*niwg_event); delete niwg_event; // Speak Now StartTalking(); #endif #endif // Return rw_weight return rw_weight; } #ifdef __NEUT_ENABLED__ #ifdef __NIWG_ENABLED__ niwg::rew::NIWGEvent *NIWGWeightEngine::GetNIWGEventLocal(NeutVect *nvect) { niwg::rew::NIWGEvent *fDummyNIWGEvent = NULL; fDummyNIWGEvent = new niwg::rew::NIWGEvent(); fDummyNIWGEvent->detid = 1; // MiniBooNE (apply CCQE LowE variations) fDummyNIWGEvent->neutmode = nvect->Mode; fDummyNIWGEvent->targetA = nvect->TargetA; fDummyNIWGEvent->recenu_ccqe_sk = -1; if (nvect->Ibound == 0) fDummyNIWGEvent->targetA = 1; // RT: identifies as H, rather than O16 // Fill initial particle stack for (int ip = 0; ip < nvect->Npart(); ++ip) { niwg::rew::NIWGPartStack fDummyPartStack; fDummyPartStack.p = (nvect->PartInfo(ip)->fP) * 0.001; // Convert to GeV fDummyPartStack.pdg = nvect->PartInfo(ip)->fPID; fDummyPartStack.chase = nvect->PartInfo(ip)->fIsAlive; fDummyPartStack.parent = nvect->ParentIdx(ip) - 1; // WARNING: this needs to be tested with a NeutRoot file fDummyNIWGEvent->part_stack.push_back(fDummyPartStack); } fDummyNIWGEvent->CalcKinematics(); return fDummyNIWGEvent; } #endif #endif diff --git a/src/Reweight/NOvARwgtEngine.cxx b/src/Reweight/NOvARwgtEngine.cxx index a1831b0..c9d2b3b 100644 --- a/src/Reweight/NOvARwgtEngine.cxx +++ b/src/Reweight/NOvARwgtEngine.cxx @@ -1,346 +1,346 @@ #include "NOvARwgtEngine.h" #include "NOvARwgt/interfaces/GenieInterface.h" #include "NOvARwgt/rwgt/genie/QE/MAQEWgts.h" #include "NOvARwgt/rwgt/genie/QE/RPAWeights.h" #include "NOvARwgt/rwgt/genie/MEC/EmpiricalMECOtherTunes.h" #include "NOvARwgt/rwgt/genie/MEC/EmpiricalMECTune2017.h" #include "NOvARwgt/rwgt/genie/MEC/EmpiricalMECTune2018.h" #include "NOvARwgt/rwgt/genie/MEC/EmpiricalMECTuneSA.h" #include "NOvARwgt/rwgt/genie/DIS/HighWDISWeight.h" #include "NOvARwgt/rwgt/genie/DIS/Nonres1piWeights.h" #include "NOvARwgt/rwgt/tunes/Tunes2017.h" #include "NOvARwgt/rwgt/tunes/Tunes2018.h" #include "NOvARwgt/rwgt/tunes/Tunes2019.h" #include "NOvARwgt/rwgt/tunes/TunesSA.h" #include "NOvARwgt/rwgt/EventRecord.h" #include "NOvARwgt/rwgt/IWeightGenerator.h" #include "NOvARwgt/rwgt/Tune.h" static size_t const kRPAWeightCCQESA = 0; static size_t const kRPAWeightCCQE_2017 = 1; static size_t const kRPAWeightQ2_2017 = 2; static size_t const kMAQEWeight_2018 = 3; static size_t const kTufts2p2hWgtSA = 4; static size_t const kEmpiricalMEC_to_Valencia_Wgt = 5; static size_t const kEmpiricalMECWgt2018 = 6; static size_t const kMECEnuShapeWgt = 7; static size_t const kMECInitStateNPFracWgt = 8; static size_t const kEmpiricalMECWgt2017 = 9; static size_t const kEmpiricalMEC_to_GENIEQE_Wgt = 10; static size_t const kEmpiricalMEC_to_GENIERES_Wgt = 11; static size_t const kEmpiricalMECWgt2018RPAFix = 12; static size_t const kMEC2018_QElike_Wgt = 13; static size_t const kMEC2018_RESlike_Wgt = 14; static size_t const kMEC2018RPAFix_QElike_Wgt = 15; static size_t const kMEC2018RPAFix_RESlike_Wgt = 16; static size_t const kNonres1PiWgt = 17; static size_t const kHighWDISWgt_2018 = 18; static size_t const kTuneSeparator = 100; static size_t const kTune2017 = kTuneSeparator + 1; static size_t const kTune2018 = kTuneSeparator + 2; static size_t const kTune2019 = kTuneSeparator + 3; static size_t const kTuneSA = kTuneSeparator + 4; static size_t const kNoSuchWeightEngine = std::numeric_limits::max(); size_t NOvARwgtEngine::GetWeightGeneratorIndex(std::string const &strname) { if (strname == "RPAWeightCCQESA") { return kRPAWeightCCQESA; } else if (strname == "RPAWeightCCQE_2017") { return kRPAWeightCCQE_2017; } else if (strname == "RPAWeightQ2_2017") { return kRPAWeightQ2_2017; } else if (strname == "MAQEWeight_2018") { return kMAQEWeight_2018; } else if (strname == "Tufts2p2hWgtSA") { return kTufts2p2hWgtSA; } else if (strname == "EmpiricalMEC_to_Valencia_Wgt") { return kEmpiricalMEC_to_Valencia_Wgt; } else if (strname == "EmpiricalMECWgt2018") { return kEmpiricalMECWgt2018; } else if (strname == "MECEnuShapeWgt") { return kMECEnuShapeWgt; } else if (strname == "MECInitStateNPFracWgt") { return kMECInitStateNPFracWgt; } else if (strname == "EmpiricalMECWgt2017") { return kEmpiricalMECWgt2017; } else if (strname == "EmpiricalMEC_to_GENIEQE_Wgt") { return kEmpiricalMEC_to_GENIEQE_Wgt; } else if (strname == "EmpiricalMEC_to_GENIERES_Wgt") { return kEmpiricalMEC_to_GENIERES_Wgt; } else if (strname == "EmpiricalMECWgt2018RPAFix") { return kEmpiricalMECWgt2018RPAFix; } else if (strname == "MEC2018_QElike_Wgt") { return kMEC2018_QElike_Wgt; } else if (strname == "MEC2018_RESlike_Wgt") { return kMEC2018_RESlike_Wgt; } else if (strname == "MEC2018RPAFix_QElike_Wgt") { return kMEC2018RPAFix_QElike_Wgt; } else if (strname == "MEC2018RPAFix_RESlike_Wgt") { return kMEC2018RPAFix_RESlike_Wgt; } else if (strname == "Nonres1PiWgt") { return kNonres1PiWgt; } else if (strname == "HighWDISWgt_2018") { return kHighWDISWgt_2018; } else if (strname == "Tune2017") { return kTune2017; } else if (strname == "Tune2018") { return kTune2018; } else if (strname == "Tune2019") { return kTune2019; } else if (strname == "TuneSA") { return kTuneSA; } return kNoSuchWeightEngine; } novarwgt::IWeightGenerator *IWeightGeneratorFactory(size_t e) { switch (e) { case kRPAWeightCCQESA: { return new novarwgt::RPAWeightCCQESA(); } case kRPAWeightCCQE_2017: { return new novarwgt::RPAWeightCCQE_2017("CV"); } case kRPAWeightQ2_2017: { return new novarwgt::RPAWeightQ2_2017(); } case kMAQEWeight_2018: { return new novarwgt::MAQEWeight_2018(); } case kTufts2p2hWgtSA: { return new novarwgt::Tufts2p2hWgtSA(); } case kEmpiricalMEC_to_Valencia_Wgt: { return new novarwgt::EmpiricalMEC_to_Valencia_Wgt(); } case kEmpiricalMECWgt2018: { return new novarwgt::EmpiricalMECWgt2018(); } case kMECEnuShapeWgt: { return new novarwgt::MECEnuShapeWgt(); } case kMECInitStateNPFracWgt: { return new novarwgt::MECInitStateNPFracWgt(); } case kEmpiricalMECWgt2017: { return new novarwgt::EmpiricalMECWgt2017(); } case kEmpiricalMEC_to_GENIEQE_Wgt: { return new novarwgt::EmpiricalMEC_to_GENIEQE_Wgt(); } case kEmpiricalMEC_to_GENIERES_Wgt: { return new novarwgt::EmpiricalMEC_to_GENIERES_Wgt(); } case kEmpiricalMECWgt2018RPAFix: { return new novarwgt::EmpiricalMECWgt2018RPAFix(); } case kMEC2018_QElike_Wgt: { return new novarwgt::MEC2018_QElike_Wgt(); } case kMEC2018_RESlike_Wgt: { return new novarwgt::MEC2018_RESlike_Wgt(); } case kMEC2018RPAFix_QElike_Wgt: { return new novarwgt::MEC2018RPAFix_QElike_Wgt(); } case kMEC2018RPAFix_RESlike_Wgt: { return new novarwgt::MEC2018RPAFix_RESlike_Wgt(); } case kNonres1PiWgt: { return new novarwgt::Nonres1PiWgt(); } case kHighWDISWgt_2018: { return new novarwgt::HighWDISWgt_2018(); } default: { return NULL; } } } novarwgt::Tune const *TuneFactory(size_t e) { switch (e) { case kTune2017: { return &novarwgt::kCVTune2017; } case kTune2018: { return &novarwgt::kCVTune2018; } case kTune2019: { return &novarwgt::kCVTune2019; } case kTuneSA: { return &novarwgt::kCVTuneSA; } default: { return NULL; } } } void NOvARwgtEngine::IncludeDial(std::string name, double startval) { size_t we_e = GetWeightGeneratorIndex(name); if (we_e == kNoSuchWeightEngine) { - QTHROW("[ERROR]: Invalid NOvARwgt Engine name: " << name); + NUIS_ABORT("[ERROR]: Invalid NOvARwgt Engine name: " << name); } if (we_e < kTuneSeparator) { if (fWeightEngineEnums.find(we_e) != fWeightEngineEnums.end()) { - QTHROW("[ERROR]: NOvARwgt Engine name: " << name << " already included."); + NUIS_ABORT("[ERROR]: NOvARwgt Engine name: " << name << " already included."); } fWeightEngineEnums[we_e] = fWeightEngines.size(); fWeightEngines.push_back(IWeightGeneratorFactory(we_e)); fWeightEngineValues.push_back(startval); } else { if (fTuneEnums.find(we_e) != fTuneEnums.end()) { - QTHROW("[ERROR]: NOvARwgt Tune name: " << name << " already included."); + NUIS_ABORT("[ERROR]: NOvARwgt Tune name: " << name << " already included."); } fTuneEnums[we_e] = fTunes.size(); fTunes.push_back(TuneFactory(we_e)); fTuneValues.push_back(startval); } }; void NOvARwgtEngine::SetDialValue(int nuisenum, double val) { size_t we_indx = (nuisenum % 1000); if (we_indx < kTuneSeparator) { if (!fWeightEngineEnums.count(we_indx)) { - QTHROW("[ERROR]: SetDialValue for NOvARwgt dial: " + NUIS_ABORT("[ERROR]: SetDialValue for NOvARwgt dial: " << we_indx << " but that engine hasn't been included yet."); } size_t engine_index = fWeightEngineEnums[we_indx]; fWeightEngineValues[engine_index] = val; } else { if (!fTuneEnums.count(we_indx)) { - QTHROW("[ERROR]: SetDialValue for NOvARwgt dial: " + NUIS_ABORT("[ERROR]: SetDialValue for NOvARwgt dial: " << we_indx << " but that tune hasn't been included yet."); } size_t engine_index = fTuneEnums[we_indx]; fTuneValues[engine_index] = val; } } void NOvARwgtEngine::SetDialValue(std::string name, double val) { size_t we_indx = GetWeightGeneratorIndex(name); if (we_indx == kNoSuchWeightEngine) { - QTHROW("[ERROR]: Invalid NOvARwgt Engine name: " << name); + NUIS_ABORT("[ERROR]: Invalid NOvARwgt Engine name: " << name); } if (we_indx < kTuneSeparator) { if (!fWeightEngineEnums.count(we_indx)) { - QTHROW("[ERROR]: SetDialValue for NOvARwgt dial: " + NUIS_ABORT("[ERROR]: SetDialValue for NOvARwgt dial: " << we_indx << " but that engine hasn't been included yet."); } size_t engine_index = fWeightEngineEnums[we_indx]; fWeightEngineValues[engine_index] = val; } else { if (!fTuneEnums.count(we_indx)) { - QTHROW("[ERROR]: SetDialValue for NOvARwgt dial: " + NUIS_ABORT("[ERROR]: SetDialValue for NOvARwgt dial: " << we_indx << " but that tune hasn't been included yet."); } size_t engine_index = fTuneEnums[we_indx]; fTuneValues[engine_index] = val; } } bool NOvARwgtEngine::IsDialIncluded(std::string name) { size_t we_indx = GetWeightGeneratorIndex(name); if (we_indx == kNoSuchWeightEngine) { - QTHROW("[ERROR]: Invalid NOvARwgt Engine name: " << name); + NUIS_ABORT("[ERROR]: Invalid NOvARwgt Engine name: " << name); } if (we_indx < kTuneSeparator) { return fWeightEngineEnums.count(we_indx); } else { return fTuneEnums.count(we_indx); } } bool NOvARwgtEngine::IsDialIncluded(int nuisenum) { size_t we_indx = (nuisenum % 1000); if (we_indx < kTuneSeparator) { return fWeightEngineEnums.count(we_indx); } else { return fTuneEnums.count(we_indx); } } double NOvARwgtEngine::GetDialValue(std::string name) { size_t we_indx = GetWeightGeneratorIndex(name); if (we_indx == kNoSuchWeightEngine) { - QTHROW("[ERROR]: Invalid NOvARwgt Engine name: " << name); + NUIS_ABORT("[ERROR]: Invalid NOvARwgt Engine name: " << name); } if (we_indx < kTuneSeparator) { if (!fWeightEngineEnums.count(we_indx)) { - QTHROW("[ERROR]: SetDialValue for NOvARwgt dial: " + NUIS_ABORT("[ERROR]: SetDialValue for NOvARwgt dial: " << we_indx << " but that engine hasn't been included yet."); } return fWeightEngineValues[fWeightEngineEnums[we_indx]]; } else { if (!fTuneEnums.count(we_indx)) { - QTHROW("[ERROR]: SetDialValue for NOvARwgt dial: " + NUIS_ABORT("[ERROR]: SetDialValue for NOvARwgt dial: " << we_indx << " but that tune hasn't been included yet."); } return fTuneValues[fTuneEnums[we_indx]]; } } double NOvARwgtEngine::GetDialValue(int nuisenum) { size_t we_indx = (nuisenum % 1000); if (!fWeightEngineEnums.count(we_indx)) { - QTHROW("[ERROR]: SetDialValue for NOvARwgt dial: " + NUIS_ABORT("[ERROR]: SetDialValue for NOvARwgt dial: " << we_indx << " but that engine hasn't been included yet."); } if (we_indx < kTuneSeparator) { return fWeightEngineValues[fWeightEngineEnums[we_indx]]; } else { return fTuneValues[fTuneEnums[we_indx]]; } } double NOvARwgtEngine::CalcWeight(BaseFitEvt *evt) { double rw_weight = 1.0; // Make nom weight if (!evt) { - QTHROW("evt not found : " << evt); + NUIS_ABORT("evt not found : " << evt); } // Skip Non GENIE if (evt->fType != kGENIE) return 1.0; if (!(evt->genie_event)) { - QTHROW("evt->genie_event not found!" << evt->genie_event); + NUIS_ABORT("evt->genie_event not found!" << evt->genie_event); } if (!(evt->genie_event->event)) { - QTHROW("evt->genie_event->event GHepRecord not found!" + NUIS_ABORT("evt->genie_event->event GHepRecord not found!" << (evt->genie_event->event)); } novarwgt::EventRecord rcd = novarwgt::ConvertGenieEvent(evt->genie_event->event); static novarwgt::InputVals const dummyparams; for (size_t w_it = 0; w_it < fWeightEngines.size(); ++w_it) { if (fWeightEngineValues[w_it] == 0) { // if a dial is set to 0, don't include its weight continue; } rw_weight *= fWeightEngines[w_it]->GetWeight(rcd, dummyparams); } for (size_t w_it = 0; w_it < fTunes.size(); ++w_it) { if (fTuneValues[w_it] == 0) { // if a dial is set to 0, don't include its weight continue; } rw_weight *= fTunes[w_it]->EventWeight(rcd); } return rw_weight; } diff --git a/src/Reweight/NUISANCEWeightCalcs.cxx b/src/Reweight/NUISANCEWeightCalcs.cxx index 8b971b4..bdf0a8b 100644 --- a/src/Reweight/NUISANCEWeightCalcs.cxx +++ b/src/Reweight/NUISANCEWeightCalcs.cxx @@ -1,538 +1,538 @@ #include "NUISANCEWeightCalcs.h" #include "FitEvent.h" #include "GeneralUtils.h" #include "NUISANCESyst.h" #include "WeightUtils.h" using namespace Reweight; ModeNormCalc::ModeNormCalc() { fNormRES = 1.0; } double ModeNormCalc::CalcWeight(BaseFitEvt *evt) { int mode = abs(evt->Mode); double w = 1.0; if (mode == 11 or mode == 12 or mode == 13) { w *= fNormRES; } return w; } void ModeNormCalc::SetDialValue(std::string name, double val) { SetDialValue(Reweight::ConvDial(name, kCUSTOM), val); } void ModeNormCalc::SetDialValue(int rwenum, double val) { int curenum = rwenum % 1000; // Check Handled if (!IsHandled(curenum)) return; if (curenum == kModeNorm_NormRES) fNormRES = val; } bool ModeNormCalc::IsHandled(int rwenum) { int curenum = rwenum % 1000; switch (curenum) { case kModeNorm_NormRES: return true; default: return false; } } BeRPACalc::BeRPACalc() : fBeRPA_A(0.59), fBeRPA_B(1.05), fBeRPA_D(1.13), fBeRPA_E(0.88), fBeRPA_U(1.2), nParams(0) { // A = 0.59 +/- 20% // B = 1.05 +/- 20% // D = 1.13 +/- 15% // E = 0.88 +/- 40% // U = 1.2 } double BeRPACalc::CalcWeight(BaseFitEvt *evt) { FitEvent *fevt = static_cast(evt); int mode = abs(evt->Mode); double w = 1.0; if (nParams == 0) { return w; } // Get Q2 // Get final state lepton if (mode == 1) { double Q2 = -1.0 * (fevt->GetHMFSAnyLeptons()->P4() - fevt->GetNeutrinoIn()->P4()) * (fevt->GetHMFSAnyLeptons()->P4() - fevt->GetNeutrinoIn()->P4()) / 1.E6; // Only CCQE events w *= calcRPA(Q2, fBeRPA_A, fBeRPA_B, fBeRPA_D, fBeRPA_E, fBeRPA_U); } return w; } void BeRPACalc::SetDialValue(std::string name, double val) { SetDialValue(Reweight::ConvDial(name, kCUSTOM), val); } void BeRPACalc::SetDialValue(int rwenum, double val) { int curenum = rwenum % 1000; // Check Handled if (!IsHandled(curenum)) return; // Need 4 or 5 reconfigures if (curenum == kBeRPA_A) fBeRPA_A = val; else if (curenum == kBeRPA_B) fBeRPA_B = val; else if (curenum == kBeRPA_D) fBeRPA_D = val; else if (curenum == kBeRPA_E) fBeRPA_E = val; else if (curenum == kBeRPA_U) fBeRPA_U = val; nParams++; } bool BeRPACalc::IsHandled(int rwenum) { int curenum = rwenum % 1000; switch (curenum) { case kBeRPA_A: case kBeRPA_B: case kBeRPA_D: case kBeRPA_E: case kBeRPA_U: return true; default: return false; } } SBLOscWeightCalc::SBLOscWeightCalc() { fDistance = 0.0; fMassSplitting = 0.0; fSin2Theta = 0.0; } double SBLOscWeightCalc::CalcWeight(BaseFitEvt *evt) { FitEvent *fevt = static_cast(evt); FitParticle *pnu = fevt->PartInfo(0); double E = pnu->fP.E() / 1.E3; // Extract energy return GetSBLOscWeight(E); } void SBLOscWeightCalc::SetDialValue(std::string name, double val) { SetDialValue(Reweight::ConvDial(name, kCUSTOM), val); } void SBLOscWeightCalc::SetDialValue(int rwenum, double val) { int curenum = rwenum % 1000; if (!IsHandled(curenum)) return; if (curenum == kSBLOsc_Distance) fDistance = val; if (curenum == kSBLOsc_MassSplitting) fMassSplitting = val; if (curenum == kSBLOsc_Sin2Theta) fSin2Theta = val; } bool SBLOscWeightCalc::IsHandled(int rwenum) { int curenum = rwenum % 1000; switch (curenum) { case kSBLOsc_Distance: return true; case kSBLOsc_MassSplitting: return true; case kSBLOsc_Sin2Theta: return true; default: return false; } } double SBLOscWeightCalc::GetSBLOscWeight(double E) { if (E <= 0.0) return 1.0 - 0.5 * fSin2Theta; return 1.0 - fSin2Theta * pow(sin(1.267 * fMassSplitting * fDistance / E), 2); } GaussianModeCorr::GaussianModeCorr() { // Apply the tilt-shift Gauss by Patrick // Alternatively set in config fMethod = true; // Init fApply_CCQE = false; fGausVal_CCQE[kPosNorm] = 0.0; fGausVal_CCQE[kPosTilt] = 0.0; fGausVal_CCQE[kPosPq0] = 1.0; fGausVal_CCQE[kPosWq0] = 1.0; fGausVal_CCQE[kPosPq3] = 1.0; fGausVal_CCQE[kPosWq3] = 1.0; fApply_2p2h = false; fGausVal_2p2h[kPosNorm] = 0.0; fGausVal_2p2h[kPosTilt] = 0.0; fGausVal_2p2h[kPosPq0] = 1.0; fGausVal_2p2h[kPosWq0] = 1.0; fGausVal_2p2h[kPosPq3] = 1.0; fGausVal_2p2h[kPosWq3] = 1.0; fApply_2p2h_PPandNN = false; fGausVal_2p2h_PPandNN[kPosNorm] = 0.0; fGausVal_2p2h_PPandNN[kPosTilt] = 0.0; fGausVal_2p2h_PPandNN[kPosPq0] = 1.0; fGausVal_2p2h_PPandNN[kPosWq0] = 1.0; fGausVal_2p2h_PPandNN[kPosPq3] = 1.0; fGausVal_2p2h_PPandNN[kPosWq3] = 1.0; fApply_2p2h_NP = false; fGausVal_2p2h_NP[kPosNorm] = 0.0; fGausVal_2p2h_NP[kPosTilt] = 0.0; fGausVal_2p2h_NP[kPosPq0] = 1.0; fGausVal_2p2h_NP[kPosWq0] = 1.0; fGausVal_2p2h_NP[kPosPq3] = 1.0; fGausVal_2p2h_NP[kPosWq3] = 1.0; fApply_CC1pi = false; fGausVal_CC1pi[kPosNorm] = 0.0; fGausVal_CC1pi[kPosTilt] = 0.0; fGausVal_CC1pi[kPosPq0] = 1.0; fGausVal_CC1pi[kPosWq0] = 1.0; fGausVal_CC1pi[kPosPq3] = 1.0; fGausVal_CC1pi[kPosWq3] = 1.0; fAllowSuppression = false; fDebugStatements = FitPar::Config().GetParB("GaussianModeCorr_DEBUG"); // fDebugStatements = true; } double GaussianModeCorr::CalcWeight(BaseFitEvt *evt) { FitEvent *fevt = static_cast(evt); double rw_weight = 1.0; // Get Neutrino if (!fevt->Npart()) { - QTHROW("NO particles found in stack!"); + NUIS_ABORT("NO particles found in stack!"); } FitParticle *pnu = fevt->GetHMISAnyLeptons(); if (!pnu) { - QTHROW("NO Starting particle found in stack!"); + NUIS_ABORT("NO Starting particle found in stack!"); } int pdgnu = pnu->fPID; int expect_fsleppdg = 0; if (pdgnu & 1) { expect_fsleppdg = pdgnu; } else { expect_fsleppdg = abs(pdgnu) - 1; } FitParticle *plep = fevt->GetHMFSParticle(expect_fsleppdg); if (!plep) return 1.0; TLorentzVector q = pnu->fP - plep->fP; // Extra q0,q3 double q0 = fabs(q.E()) / 1.E3; double q3 = fabs(q.Vect().Mag()) / 1.E3; int initialstate = -1; // Undef if (abs(fevt->Mode) == 2) { int npr = 0; int nne = 0; for (UInt_t j = 0; j < fevt->Npart(); j++) { if ((fevt->PartInfo(j))->fIsAlive) continue; if (fevt->PartInfo(j)->fPID == 2212) npr++; else if (fevt->PartInfo(j)->fPID == 2112) nne++; } if (fevt->Mode == 2 && npr == 1 && nne == 1) { initialstate = 2; } else if (fevt->Mode == 2 && ((npr == 0 && nne == 2) || (npr == 2 && nne == 0))) { initialstate = 1; } } // Apply weighting if (fApply_CCQE && abs(fevt->Mode) == 1) { if (fDebugStatements) std::cout << "Getting CCQE Weight" << std::endl; double g = GetGausWeight(q0, q3, fGausVal_CCQE); if (g < 1.0) g = 1.0; rw_weight *= g; } if (fApply_2p2h && abs(fevt->Mode) == 2) { if (fDebugStatements) std::cout << "Getting 2p2h Weight" << std::endl; if (fDebugStatements) std::cout << "Got q0 q3 = " << q0 << " " << q3 << " mode = " << fevt->Mode << std::endl; rw_weight *= GetGausWeight(q0, q3, fGausVal_2p2h); if (fDebugStatements) std::cout << "Returning Weight " << rw_weight << std::endl; } if (fApply_2p2h_PPandNN && abs(fevt->Mode) == 2 && initialstate == 1) { if (fDebugStatements) std::cout << "Getting 2p2h PPandNN Weight" << std::endl; rw_weight *= GetGausWeight(q0, q3, fGausVal_2p2h_PPandNN); } if (fApply_2p2h_NP && abs(fevt->Mode) == 2 && initialstate == 2) { if (fDebugStatements) std::cout << "Getting 2p2h NP Weight" << std::endl; rw_weight *= GetGausWeight(q0, q3, fGausVal_2p2h_NP); } if (fApply_CC1pi && abs(fevt->Mode) >= 11 && abs(fevt->Mode) <= 13) { if (fDebugStatements) std::cout << "Getting CC1pi Weight" << std::endl; rw_weight *= GetGausWeight(q0, q3, fGausVal_CC1pi); } return rw_weight; } void GaussianModeCorr::SetMethod(bool method) { fMethod = method; if (fMethod == true) { - QLOG(FIT, + NUIS_LOG(FIT, " Using tilt-shift Gaussian parameters for Gaussian enhancement..."); } else { - QLOG(FIT, " Using Normal Gaussian parameters for Gaussian enhancement..."); + NUIS_LOG(FIT, " Using Normal Gaussian parameters for Gaussian enhancement..."); } }; double GaussianModeCorr::GetGausWeight(double q0, double q3, double vals[]) { // The weight double w = 1.0; // Use tilt-shift method by Patrick if (fMethod) { if (fDebugStatements) { std::cout << "Using Patrick gaussian" << std::endl; } // // CCQE Without Suppression // double Norm = 4.82788679036; // double Tilt = 2.3501416116; // double Pq0 = 0.363964889702; // double Wq0 = 0.133976806938; // double Pq3 = 0.431769740224; // double Wq3 = 0.207666663434; // // Also add for CCQE at the end // return (w > 1.0) ? w : 1.0; // // 2p2h with suppression // double Norm = 15.967; // double Tilt = -0.455655; // double Pq0 = 0.214598; // double Wq0 = 0.0291061; // double Pq3 = 0.480194; // double Wq3 = 0.134588; double Norm = vals[kPosNorm]; double Tilt = vals[kPosTilt]; double Pq0 = vals[kPosPq0]; double Wq0 = vals[kPosWq0]; double Pq3 = vals[kPosPq3]; double Wq3 = vals[kPosWq3]; double a = cos(Tilt) * cos(Tilt) / (2 * Wq0 * Wq0); a += sin(Tilt) * sin(Tilt) / (2 * Wq3 * Wq3); double b = -sin(2 * Tilt) / (4 * Wq0 * Wq0); b += sin(2 * Tilt) / (4 * Wq3 * Wq3); double c = sin(Tilt) * sin(Tilt) / (2 * Wq0 * Wq0); c += cos(Tilt) * cos(Tilt) / (2 * Wq3 * Wq3); w = Norm; w *= exp(-a * (q0 - Pq0) * (q0 - Pq0)); w *= exp(+2.0 * b * (q0 - Pq0) * (q3 - Pq3)); w *= exp(-c * (q3 - Pq3) * (q3 - Pq3)); if (fDebugStatements) { std::cout << "Applied Tilt " << Tilt << " " << cos(Tilt) << " " << sin(Tilt) << std::endl; std::cout << "abc = " << a << " " << b << " " << c << std::endl; std::cout << "Returning " << Norm << " " << Pq0 << " " << Wq0 << " " << Pq3 << " " << Wq3 << " " << w << std::endl; } if (w != w || std::isnan(w) || w < 0.0) { w = 0.0; } if (w < 1.0 and !fAllowSuppression) { w = 1.0; } // Use the MINERvA Gaussian method } else { /* * From MINERvA and Daniel Ruterbories: * Old notes here: * * http://cdcvs.fnal.gov/cgi-bin/public-cvs/cvsweb-public.cgi/AnalysisFramework/Ana/CCQENu/ana_common/data/?cvsroot=mnvsoft * These parameters are slightly altered * * FRESH: * 10.5798 * 0.254032 * 0.50834 * 0.0571035 * 0.129051 * 0.875287 */ if (fDebugStatements) { std::cout << "Using MINERvA Gaussian" << std::endl; } double norm = vals[kPosNorm]; double meanq0 = vals[kPosTilt]; double meanq3 = vals[kPosPq0]; double sigmaq0 = vals[kPosWq0]; double sigmaq3 = vals[kPosPq3]; double corr = vals[kPosWq3]; double z = (q0 - meanq0) * (q0 - meanq0) / sigmaq0 / sigmaq0 + (q3 - meanq3) * (q3 - meanq3) / sigmaq3 / sigmaq3 - 2 * corr * (q0 - meanq0) * (q3 - meanq3) / (sigmaq0 * sigmaq3); double ret = norm * exp(-0.5 * z / (1 - corr * corr)); // Need to add 1 to the results w = 1.0 + ret; } return w; } void GaussianModeCorr::SetDialValue(std::string name, double val) { SetDialValue(Reweight::ConvDial(name, kCUSTOM), val); } void GaussianModeCorr::SetDialValue(int rwenum, double val) { int curenum = rwenum % 1000; // Check Handled if (!IsHandled(curenum)) return; // CCQE Setting for (int i = kGaussianCorr_CCQE_norm; i <= kGaussianCorr_CCQE_Wq3; i++) { if (i == curenum) { int index = i - kGaussianCorr_CCQE_norm; fGausVal_CCQE[index] = val; fApply_CCQE = true; } } // 2p2h Setting for (int i = kGaussianCorr_2p2h_norm; i <= kGaussianCorr_2p2h_Wq3; i++) { if (i == curenum) { int index = i - kGaussianCorr_2p2h_norm; fGausVal_2p2h[index] = val; fApply_2p2h = true; } } // 2p2h_PPandNN Setting for (int i = kGaussianCorr_2p2h_PPandNN_norm; i <= kGaussianCorr_2p2h_PPandNN_Wq3; i++) { if (i == curenum) { int index = i - kGaussianCorr_2p2h_PPandNN_norm; fGausVal_2p2h_PPandNN[index] = val; fApply_2p2h_PPandNN = true; } } // 2p2h_NP Setting for (int i = kGaussianCorr_2p2h_NP_norm; i <= kGaussianCorr_2p2h_NP_Wq3; i++) { if (i == curenum) { int index = i - kGaussianCorr_2p2h_NP_norm; fGausVal_2p2h_NP[index] = val; fApply_2p2h_NP = true; } } // CC1pi Setting for (int i = kGaussianCorr_CC1pi_norm; i <= kGaussianCorr_CC1pi_Wq3; i++) { if (i == curenum) { int index = i - kGaussianCorr_CC1pi_norm; fGausVal_CC1pi[index] = val; fApply_CC1pi = true; } } if (curenum == kGaussianCorr_AllowSuppression) { fAllowSuppression = (val > 0.5); } } bool GaussianModeCorr::IsHandled(int rwenum) { int curenum = rwenum % 1000; switch (curenum) { case kGaussianCorr_CCQE_norm: case kGaussianCorr_CCQE_tilt: case kGaussianCorr_CCQE_Pq0: case kGaussianCorr_CCQE_Wq0: case kGaussianCorr_CCQE_Pq3: case kGaussianCorr_CCQE_Wq3: case kGaussianCorr_2p2h_norm: case kGaussianCorr_2p2h_tilt: case kGaussianCorr_2p2h_Pq0: case kGaussianCorr_2p2h_Wq0: case kGaussianCorr_2p2h_Pq3: case kGaussianCorr_2p2h_Wq3: case kGaussianCorr_2p2h_PPandNN_norm: case kGaussianCorr_2p2h_PPandNN_tilt: case kGaussianCorr_2p2h_PPandNN_Pq0: case kGaussianCorr_2p2h_PPandNN_Wq0: case kGaussianCorr_2p2h_PPandNN_Pq3: case kGaussianCorr_2p2h_PPandNN_Wq3: case kGaussianCorr_2p2h_NP_norm: case kGaussianCorr_2p2h_NP_tilt: case kGaussianCorr_2p2h_NP_Pq0: case kGaussianCorr_2p2h_NP_Wq0: case kGaussianCorr_2p2h_NP_Pq3: case kGaussianCorr_2p2h_NP_Wq3: case kGaussianCorr_CC1pi_norm: case kGaussianCorr_CC1pi_tilt: case kGaussianCorr_CC1pi_Pq0: case kGaussianCorr_CC1pi_Wq0: case kGaussianCorr_CC1pi_Pq3: case kGaussianCorr_CC1pi_Wq3: case kGaussianCorr_AllowSuppression: return true; default: return false; } } diff --git a/src/Reweight/NUISANCEWeightEngine.cxx b/src/Reweight/NUISANCEWeightEngine.cxx index 567c689..8bbd716 100644 --- a/src/Reweight/NUISANCEWeightEngine.cxx +++ b/src/Reweight/NUISANCEWeightEngine.cxx @@ -1,123 +1,123 @@ #include "NUISANCEWeightEngine.h" #include "NUISANCEWeightCalcs.h" #ifdef __MINERVA_RW_ENABLED__ #ifdef __GENIE_ENABLED__ #include "MINERvAWeightCalcs.h" #endif #endif NUISANCEWeightEngine::NUISANCEWeightEngine(std::string name) { // Setup the NUISANCE Reweight engine fCalcName = name; - QLOG(FIT, "Setting up NUISANCE Custom RW : " << fCalcName); + NUIS_LOG(FIT, "Setting up NUISANCE Custom RW : " << fCalcName); // Load in all Weight Calculations GaussianModeCorr *GaussianMode = new GaussianModeCorr(); std::string Gaussian_Method = FitPar::Config().GetParS("Gaussian_Enhancement"); if (Gaussian_Method == "Tilt-Shift") { GaussianMode->SetMethod(true); } else if (Gaussian_Method == "Normal") { GaussianMode->SetMethod(false); } else { - QTHROW("I do not recognise method " + NUIS_ABORT("I do not recognise method " << Gaussian_Method << " for the Gaussian enhancement, so will die now..."); } fWeightCalculators.push_back(GaussianMode); fWeightCalculators.push_back(new ModeNormCalc()); fWeightCalculators.push_back(new SBLOscWeightCalc()); fWeightCalculators.push_back(new BeRPACalc()); #ifdef __MINERVA_RW_ENABLED__ #ifdef __GENIE_ENABLED__ fWeightCalculators.push_back(new nuisance::reweight::MINERvAReWeight_MEC()); fWeightCalculators.push_back(new nuisance::reweight::MINERvAReWeight_RES()); fWeightCalculators.push_back(new nuisance::reweight::RikRPA()); #endif #endif // Set Abs Twk Config fIsAbsTwk = true; }; void NUISANCEWeightEngine::IncludeDial(std::string name, double startval) { // Get First enum int nuisenum = Reweight::ConvDial(name, kCUSTOM); // Setup Maps fEnumIndex[nuisenum]; // = std::vector(0); fNameIndex[name]; // = std::vector(0); // Split by commas std::vector allnames = GeneralUtils::ParseToStr(name, ","); for (uint i = 0; i < allnames.size(); i++) { std::string singlename = allnames[i]; // Get RW int singleenum = Reweight::ConvDial(singlename, kCUSTOM); // Fill Maps int index = fValues.size(); fValues.push_back(0.0); fNUISANCEEnums.push_back(singleenum); // Initialize dial - QLOG(FIT, "Registering " << singlename << " from " << name); + NUIS_LOG(FIT, "Registering " << singlename << " from " << name); // Setup index fEnumIndex[nuisenum].push_back(index); fNameIndex[name].push_back(index); } // Set Value if given if (startval != -999.9) { SetDialValue(nuisenum, startval); } }; void NUISANCEWeightEngine::SetDialValue(int nuisenum, double val) { std::vector indices = fEnumIndex[nuisenum]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; } } void NUISANCEWeightEngine::SetDialValue(std::string name, double val) { std::vector indices = fNameIndex[name]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; } } void NUISANCEWeightEngine::Reconfigure(bool silent) { for (size_t i = 0; i < fNUISANCEEnums.size(); i++) { for (std::vector::iterator calciter = fWeightCalculators.begin(); calciter != fWeightCalculators.end(); calciter++) { NUISANCEWeightCalc *nuiscalc = static_cast(*calciter); if (nuiscalc->IsHandled(fNUISANCEEnums[i])) { nuiscalc->SetDialValue(fNUISANCEEnums[i], fValues[i]); } } } } double NUISANCEWeightEngine::CalcWeight(BaseFitEvt *evt) { double rw_weight = 1.0; // Cast as usable class for (std::vector::iterator iter = fWeightCalculators.begin(); iter != fWeightCalculators.end(); iter++) { NUISANCEWeightCalc *nuiscalc = static_cast(*iter); rw_weight *= nuiscalc->CalcWeight(evt); } // Return rw_weight return rw_weight; } diff --git a/src/Reweight/NuWroWeightEngine.cxx b/src/Reweight/NuWroWeightEngine.cxx index e17d54e..87526bd 100644 --- a/src/Reweight/NuWroWeightEngine.cxx +++ b/src/Reweight/NuWroWeightEngine.cxx @@ -1,139 +1,139 @@ #include "NuWroWeightEngine.h" NuWroWeightEngine::NuWroWeightEngine(std::string name) { #ifdef __NUWRO_REWEIGHT_ENABLED__ // Setup the NEUT Reweight engien fCalcName = name; - QLOG(FIT, "Setting up NuWro RW : " << fCalcName); + NUIS_LOG(FIT, "Setting up NuWro RW : " << fCalcName); // Create RW Engine suppressing cout StopTalking(); // Create the engine fNuwroRW = new nuwro::rew::NuwroReWeight(); // Get List of Veto Calcs (For Debugging) std::string rw_engine_list = FitPar::Config().GetParS("FitWeight_fNuwroRW_veto"); bool xsec_qel = rw_engine_list.find("nuwro_QEL") == std::string::npos; bool xsec_flag = rw_engine_list.find("nuwro_FlagNorm") == std::string::npos; bool xsec_res = rw_engine_list.find("nuwro_RES") == std::string::npos; // Add the RW Calcs if (xsec_qel) fNuwroRW->AdoptWghtCalc("nuwro_QEL", new nuwro::rew::NuwroReWeight_QEL); if (xsec_flag) fNuwroRW->AdoptWghtCalc("nuwro_FlagNorm", new nuwro::rew::NuwroReWeight_FlagNorm); if (xsec_res) fNuwroRW->AdoptWghtCalc("nuwro_RES", new nuwro::rew::NuwroReWeight_SPP); // Set Abs Twk Config fIsAbsTwk = (FitPar::Config().GetParB("setabstwk")); // allow cout again StartTalking(); #else - QTHROW("NUWRO RW NOT ENABLED! "); + NUIS_ABORT("NUWRO RW NOT ENABLED! "); #endif }; void NuWroWeightEngine::IncludeDial(std::string name, double startval) { #ifdef __NUWRO_REWEIGHT_ENABLED__ // Get RW Enum and name int nuisenum = Reweight::ConvDial(name, kNUWRO); // Initialise new vector fEnumIndex[nuisenum]; fNameIndex[name]; // Split by commas std::vector allnames = GeneralUtils::ParseToStr(name, ","); for (uint i = 0; i < allnames.size(); i++) { std::string singlename = allnames[i]; // Get Syst nuwro::rew::NuwroSyst_t gensyst = nuwro::rew::NuwroSyst::FromString(name); // Fill Maps int index = fValues.size(); fValues.push_back(0.0); fNUWROSysts.push_back(gensyst); // Initialise Dial - QLOG(FIT, "Adding NuWro Syst " << fNUWROSysts[index]); + NUIS_LOG(FIT, "Adding NuWro Syst " << fNUWROSysts[index]); fNuwroRW->Systematics().Add(fNUWROSysts[index]); if (fIsAbsTwk) { nuwro::rew::NuwroSystUncertainty::Instance()->SetUncertainty( fNUWROSysts[index], 1.0, 1.0); } // Setup index fEnumIndex[nuisenum].push_back(index); fNameIndex[name].push_back(index); } // Set Value if given if (startval != -999.9) { SetDialValue(name, startval); } #endif }; void NuWroWeightEngine::SetDialValue(int nuisenum, double val) { #ifdef __NUWRO_REWEIGHT_ENABLED__ std::vector indices = fEnumIndex[nuisenum]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; fNuwroRW->Systematics().SetSystVal(fNUWROSysts[indices[i]], val); } #endif } void NuWroWeightEngine::SetDialValue(std::string name, double val) { #ifdef __NUWRO_REWEIGHT_ENABLED__ std::vector indices = fNameIndex[name]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; fNuwroRW->Systematics().SetSystVal(fNUWROSysts[indices[i]], val); } #endif } void NuWroWeightEngine::Reconfigure(bool silent) { #ifdef __NUWRO_REWEIGHT_ENABLED__ // Hush now... if (silent) StopTalking(); // Reconf fNuwroRW->Reconfigure(); // Shout again if (silent) StartTalking(); #endif } double NuWroWeightEngine::CalcWeight(BaseFitEvt *evt) { double rw_weight = 1.0; #ifdef __NUWRO_REWEIGHT_ENABLED__ // Skip Non GENIE if (evt->fType != kNUWRO) return 1.0; #ifdef __USE_NUWRO_SRW_EVENTS__ rw_weight = fNuwroRW->CalcWeight(evt->fNuwroSRWEvent, *evt->fNuwroParams); #else // Call Weight calculation rw_weight = fNuwroRW->CalcWeight(evt->fNuwroEvent); #endif #endif // Return rw_weight return rw_weight; } diff --git a/src/Reweight/OscWeightEngine.cxx b/src/Reweight/OscWeightEngine.cxx index fe9cbe9..bf9331f 100644 --- a/src/Reweight/OscWeightEngine.cxx +++ b/src/Reweight/OscWeightEngine.cxx @@ -1,331 +1,331 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ //#define DEBUG_OSC_WE #include "OscWeightEngine.h" #include enum nuTypes { kNuebarType = -1, kNumubarType = -2, kNutaubarType = -3, kNueType = 1, kNumuType = 2, kNutauType = 3, }; nuTypes GetNuType(int pdg) { switch (pdg) { case 16: return kNutauType; case 14: return kNumuType; case 12: return kNueType; case -16: return kNutaubarType; case -14: return kNumubarType; case -12: return kNuebarType; - default: { QTHROW("Attempting to convert \"neutrino pdg\": " << pdg); } + default: { NUIS_ABORT("Attempting to convert \"neutrino pdg\": " << pdg); } } } OscWeightEngine::OscWeightEngine() : #ifdef __PROB3PP_ENABLED__ bp(), #endif theta12(0.825), theta13(0.10), theta23(1.0), dm12(7.9e-5), dm23(2.5e-3), dcp(0.0), LengthParam(0xdeadbeef), TargetNuType(0), ForceFromNuPDG(0) { Config(); } void OscWeightEngine::Config() { std::vector OscParam = Config::QueryKeys("OscParam"); if (OscParam.size() < 1) { - QERROR(WRN, + NUIS_ERR(WRN, "Oscillation parameters specified but no OscParam element " "configuring the experimental characteristics found.\nExpect at " "least . Pausing for " "10..."); sleep(10); return; } if (OscParam[0].Has("baseline_km")) { LengthParamIsZenith = false; LengthParam = OscParam[0].GetD("baseline_km"); constant_density = OscParam[0].Has("matter_density") ? OscParam[0].GetD("matter_density") : 0xdeadbeef; } else if (OscParam[0].Has("detection_zenith_deg")) { LengthParamIsZenith = true; static const double deg2rad = asin(1) / 90.0; LengthParam = cos(OscParam[0].GetD("detection_zenith_deg") * deg2rad); } else { - QERROR(WRN, + NUIS_ERR(WRN, "It appeared that you wanted to set up an oscillation weight " "branch, but it was not correctly configured. You need to specify " "either: detection_zenith_deg or baseline_km attributes on the " "OscParam element, and if baseline_km is specified, you can " "optionally also set matter_density for oscillations through a " "constant matter density. Pausing for 10..."); sleep(10); return; } dm23 = OscParam[0].Has("dm23") ? OscParam[0].GetD("dm23") : dm23; theta23 = OscParam[0].Has("sinsq_theta23") ? OscParam[0].GetD("sinsq_theta23") : theta23; theta13 = OscParam[0].Has("sinsq_theta13") ? OscParam[0].GetD("sinsq_theta13") : theta13; dm12 = OscParam[0].Has("dm12") ? OscParam[0].GetD("dm12") : dm12; theta12 = OscParam[0].Has("sinsq_theta12") ? OscParam[0].GetD("sinsq_theta12") : theta12; dcp = OscParam[0].Has("dcp") ? OscParam[0].GetD("dcp") : dcp; TargetNuType = OscParam[0].Has("TargetNuPDG") ? GetNuType(OscParam[0].GetI("TargetNuPDG")) : 0; ForceFromNuPDG = OscParam[0].Has("ForceFromNuPDG") ? GetNuType(OscParam[0].GetI("ForceFromNuPDG")) : 0; - QLOG(FIT, "Configured oscillation weighter:"); + NUIS_LOG(FIT, "Configured oscillation weighter:"); if (LengthParamIsZenith) { - QLOG(FIT, + NUIS_LOG(FIT, "Earth density profile with detection cos(zenith) = " << LengthParam); } else { if (constant_density != 0xdeadbeef) { - QLOG(FIT, + NUIS_LOG(FIT, "Constant density with experimental baseline = " << LengthParam); } else { - QLOG(FIT, + NUIS_LOG(FIT, "Vacuum oscillations with experimental baseline = " << LengthParam); } } params[0] = dm23; params[1] = theta23; params[2] = theta13; params[3] = dm12; params[4] = theta12; params[5] = dcp; - QLOG(FIT, "\tdm23 : " << params[0]); - QLOG(FIT, "\tsinsq_theta23: " << params[1]); - QLOG(FIT, "\tsinsq_theta13: " << params[2]); - QLOG(FIT, "\tdm12 : " << params[3]); - QLOG(FIT, "\tsinsq_theta12: " << params[4]); - QLOG(FIT, "\tdcp : " << params[5]); + NUIS_LOG(FIT, "\tdm23 : " << params[0]); + NUIS_LOG(FIT, "\tsinsq_theta23: " << params[1]); + NUIS_LOG(FIT, "\tsinsq_theta13: " << params[2]); + NUIS_LOG(FIT, "\tdm12 : " << params[3]); + NUIS_LOG(FIT, "\tsinsq_theta12: " << params[4]); + NUIS_LOG(FIT, "\tdcp : " << params[5]); if (TargetNuType) { - QLOG(FIT, "\tTargetNuType: " << TargetNuType); + NUIS_LOG(FIT, "\tTargetNuType: " << TargetNuType); } if (ForceFromNuPDG) { - QLOG(FIT, "\tForceFromNuPDG: " << ForceFromNuPDG); + NUIS_LOG(FIT, "\tForceFromNuPDG: " << ForceFromNuPDG); } #ifdef __PROB3PP_ENABLED__ bp.SetMNS(params[theta12_idx], params[theta13_idx], params[theta23_idx], params[dm12_idx], params[dm23_idx], params[dcp_idx], 1, true, 2); bp.DefinePath(LengthParam, 0); if (LengthParamIsZenith) { - QLOG(FIT, "\tBaseline : " << (bp.GetBaseline() / 100.0) << " km."); + NUIS_LOG(FIT, "\tBaseline : " << (bp.GetBaseline() / 100.0) << " km."); } #endif } void OscWeightEngine::IncludeDial(std::string name, double startval) { #ifdef DEBUG_OSC_WE std::cout << "IncludeDial: " << name << " at " << startval << std::endl; #endif int dial = SystEnumFromString(name); if (!dial) { - QTHROW("OscWeightEngine passed dial: " << name + NUIS_ABORT("OscWeightEngine passed dial: " << name << " that it does not understand."); } params[dial - 1] = startval; } void OscWeightEngine::SetDialValue(int nuisenum, double val) { #ifdef DEBUG_OSC_WE std::cout << "SetDial: " << (nuisenum % 1000) << " at " << val << std::endl; #endif fHasChanged = (params[(nuisenum % 1000) - 1] - val) > std::numeric_limits::epsilon(); params[(nuisenum % 1000) - 1] = val; } void OscWeightEngine::SetDialValue(std::string name, double val) { #ifdef DEBUG_OSC_WE std::cout << "SetDial: " << name << " at " << val << std::endl; #endif int dial = SystEnumFromString(name); if (!dial) { - QTHROW("OscWeightEngine passed dial: " << name + NUIS_ABORT("OscWeightEngine passed dial: " << name << " that it does not understand."); } fHasChanged = (params[dial - 1] - val) > std::numeric_limits::epsilon(); params[dial - 1] = val; } bool OscWeightEngine::IsDialIncluded(std::string name) { return SystEnumFromString(name); } bool OscWeightEngine::IsDialIncluded(int nuisenum) { return ((nuisenum % 1000) > 0) && ((nuisenum % 1000) < 6); } double OscWeightEngine::GetDialValue(std::string name) { int dial = SystEnumFromString(name); if (!dial) { - QTHROW("OscWeightEngine passed dial: " << name + NUIS_ABORT("OscWeightEngine passed dial: " << name << " that it does not understand."); } return params[dial - 1]; } double OscWeightEngine::GetDialValue(int nuisenum) { if (!(nuisenum % 1000) || (nuisenum % 1000) > 6) { - QTHROW("OscWeightEngine passed dial enum: " + NUIS_ABORT("OscWeightEngine passed dial enum: " << (nuisenum % 1000) << " that it does not understand, expected [1,6]."); } return params[(nuisenum % 1000) - 1]; } void OscWeightEngine::Reconfigure(bool silent) { fHasChanged = false; }; bool OscWeightEngine::NeedsEventReWeight() { if (fHasChanged) { return true; } return false; } double OscWeightEngine::CalcWeight(BaseFitEvt* evt) { static bool Warned = false; if (evt->probe_E == 0xdeadbeef) { if (!Warned) { - QERROR(WRN, + NUIS_ERR(WRN, "Oscillation weights asked for but using 'litemode' or " "unsupported generator input. Pasuing for 10..."); sleep(10); Warned = true; } return 1; } return CalcWeight(evt->probe_E * 1E-3, evt->probe_pdg); } double OscWeightEngine::CalcWeight(double ENu, int PDGNu, int TargetPDGNu) { if (LengthParam == 0xdeadbeef) { // not configured. return 1; } #ifdef __PROB3PP_ENABLED__ int NuType = (ForceFromNuPDG != 0) ? ForceFromNuPDG : GetNuType(PDGNu); bp.SetMNS(params[theta12_idx], params[theta13_idx], params[theta23_idx], params[dm12_idx], params[dm23_idx], params[dcp_idx], ENu, true, NuType); int pmt = 0; double prob_weight = 1; TargetPDGNu = (TargetPDGNu == -1) ? (TargetNuType ? TargetNuType : NuType) : GetNuType(TargetPDGNu); if (LengthParamIsZenith) { // Use earth density bp.DefinePath(LengthParam, 0); bp.propagate(NuType); pmt = 0; prob_weight = bp.GetProb(NuType, TargetPDGNu); } else { if (constant_density != 0xdeadbeef) { bp.propagateLinear(NuType, LengthParam, constant_density); pmt = 1; prob_weight = bp.GetProb(NuType, TargetPDGNu); } else { pmt = 2; prob_weight = bp.GetVacuumProb(NuType, TargetPDGNu, ENu * 1E-3, LengthParam); } } #ifdef DEBUG_OSC_WE if (prob_weight != prob_weight) { - QTHROW("Calculated bad prob weight: " << prob_weight << "(Osc Type: " << pmt + NUIS_ABORT("Calculated bad prob weight: " << prob_weight << "(Osc Type: " << pmt << " -- " << NuType << " -> " << TargetPDGNu << ")"); } if (prob_weight > 1) { - QTHROW("Calculated bad prob weight: " << prob_weight << "(Osc Type: " << pmt + NUIS_ABORT("Calculated bad prob weight: " << prob_weight << "(Osc Type: " << pmt << " -- " << NuType << " -> " << TargetPDGNu << ")"); } std::cout << NuType << " -> " << TargetPDGNu << ": " << ENu << " = " << prob_weight << "%%." << std::endl; #endif return prob_weight; #else return 1; #endif } int OscWeightEngine::SystEnumFromString(std::string const& name) { if (name == "dm23") { return 1; } else if (name == "sinsq_theta23") { return 2; } else if (name == "sinsq_theta13") { return 3; } else if (name == "dm12") { return 4; } else if (name == "sinsq_theta12") { return 5; } else if (name == "dcp") { return 6; } else { return 0; } } void OscWeightEngine::Print() { std::cout << "OscWeightEngine: " << std::endl; std::cout << "\t theta12: " << params[theta12_idx] << std::endl; std::cout << "\t theta13: " << params[theta13_idx] << std::endl; std::cout << "\t theta23: " << params[theta23_idx] << std::endl; std::cout << "\t dm12: " << params[dm12_idx] << std::endl; std::cout << "\t dm23: " << params[dm23_idx] << std::endl; std::cout << "\t dcp: " << params[dcp_idx] << std::endl; } diff --git a/src/Reweight/SampleNormEngine.cxx b/src/Reweight/SampleNormEngine.cxx index 349f382..80be47e 100644 --- a/src/Reweight/SampleNormEngine.cxx +++ b/src/Reweight/SampleNormEngine.cxx @@ -1,80 +1,80 @@ #include "WeightUtils.h" #include "SampleNormEngine.h" SampleNormEngine::SampleNormEngine(std::string name) { // Setup the NEUT Reweight engien fCalcName = name; - QLOG(FIT, "Setting up Likelihood Weight RW : " << fCalcName); + NUIS_LOG(FIT, "Setting up Likelihood Weight RW : " << fCalcName); // Set Abs Twk Config fIsAbsTwk = true; }; void SampleNormEngine::IncludeDial(std::string name, double startval) { // Get NUISANCE Enum int nuisenum = Reweight::ConvDial(name, kNORM); // Setup Maps fEnumIndex[nuisenum]; // = std::vector(0); fNameIndex[name]; // = std::vector(0); // Split by commas std::vector allnames = GeneralUtils::ParseToStr(name, ","); for (uint i = 0; i < allnames.size(); i++) { std::string singlename = allnames[i]; // Fill Maps int index = fValues.size(); fValues.push_back(1.0); fEnumIndex[nuisenum].push_back(index); fNameIndex[name].push_back(index); } // Set Value if given if (startval != -999.9) { SetDialValue(name, startval); } }; void SampleNormEngine::SetDialValue(int nuisenum, double val) { std::vector indices = fEnumIndex[nuisenum]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; } } void SampleNormEngine::SetDialValue(std::string name, double val) { std::vector indices = fNameIndex[name]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; } } double SampleNormEngine::GetDialValue(std::string name) { // Check for exact dial names if (fNameIndex.find(name) != fNameIndex.end()) { return fValues[fNameIndex[name][0]]; // If not iterate and check entry in one of the keys } else { for (std::map>::iterator iter = fNameIndex.begin(); iter != fNameIndex.end(); iter++) { std::string keyname = iter->first; if (keyname.find(name) != std::string::npos) { return fValues[iter->second[0]]; } } } return -1.0; } void SampleNormEngine::Reconfigure(bool silent) { // Empty placeholder incase we want print statements... } diff --git a/src/Reweight/SplineWeightEngine.cxx b/src/Reweight/SplineWeightEngine.cxx index ad2c1bb..e99645c 100644 --- a/src/Reweight/SplineWeightEngine.cxx +++ b/src/Reweight/SplineWeightEngine.cxx @@ -1,83 +1,83 @@ #include "WeightUtils.h" #include "SplineWeightEngine.h" SplineWeightEngine::SplineWeightEngine(std::string name) { // Setup the Reweight engien fCalcName = name; - QLOG(FIT, "Setting up Spline RW : " << fCalcName); + NUIS_LOG(FIT, "Setting up Spline RW : " << fCalcName); // Set Abs Twk Config fIsAbsTwk = true; }; void SplineWeightEngine::IncludeDial(std::string name, double startval) { // Get RW Enum and name int nuisenum = Reweight::ConvDial(name, kSPLINEPARAMETER); // Initialise new vector fEnumIndex[nuisenum]; fNameIndex[name]; // Split by commas std::vector allnames = GeneralUtils::ParseToStr(name, ","); for (uint i = 0; i < allnames.size(); i++) { std::string singlename = allnames[i]; // Get Single Enum For this dial int singleenum = Reweight::ConvDial(singlename, kCUSTOM); // Fill Maps int index = fValues.size(); fValues.push_back(0.0); fSingleEnums.push_back(singleenum); fSingleNames.push_back(singlename); // Setup index fEnumIndex[nuisenum].push_back(index); fNameIndex[name].push_back(index); } // Set Value if given if (startval != -999.9) { SetDialValue(name, startval); } } void SplineWeightEngine::SetDialValue(int nuisenum, double val) { std::vector indices = fEnumIndex[nuisenum]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; } } void SplineWeightEngine::SetDialValue(std::string name, double val) { std::vector indices = fNameIndex[name]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; } } void SplineWeightEngine::Reconfigure(bool silent) { for (size_t i = 0; i < fSingleNames.size(); i++) { fSplineValueMap[fSingleNames[i]] = fValues[i]; } } double SplineWeightEngine::CalcWeight(BaseFitEvt *evt) { if (!evt->fSplineRead) return 1.0; if (evt->fSplineRead->NeedsReconfigure()) { evt->fSplineRead->Reconfigure(fSplineValueMap); } double rw_weight = evt->fSplineRead->CalcWeight(evt->fSplineCoeff); if (rw_weight < 0.0) rw_weight = 0.0; return rw_weight; } diff --git a/src/Reweight/T2KWeightEngine.cxx b/src/Reweight/T2KWeightEngine.cxx index 3deadf6..7a12d0b 100644 --- a/src/Reweight/T2KWeightEngine.cxx +++ b/src/Reweight/T2KWeightEngine.cxx @@ -1,137 +1,137 @@ #include "T2KWeightEngine.h" T2KWeightEngine::T2KWeightEngine(std::string name) { #ifdef __T2KREW_ENABLED__ // Setup the NEUT Reweight engien fCalcName = name; - QLOG(FIT, "Setting up T2K RW : " << fCalcName); + NUIS_LOG(FIT, "Setting up T2K RW : " << fCalcName); // Create RW Engine suppressing cout StopTalking(); // Create Main RW Engine fT2KRW = new t2krew::T2KReWeight(); // Setup Sub RW Engines (Only activated for neut and niwg) fT2KNeutRW = new t2krew::T2KNeutReWeight(); fT2KNIWGRW = new t2krew::T2KNIWGReWeight(); fT2KRW->AdoptWghtEngine("fNeutRW", fT2KNeutRW); fT2KRW->AdoptWghtEngine("fNIWGRW", fT2KNIWGRW); fT2KRW->Reconfigure(); // allow cout again StartTalking(); // Set Abs Twk Config fIsAbsTwk = (FitPar::Config().GetParB("setabstwk")); #else - QTHROW("T2K RW NOT ENABLED"); + NUIS_ABORT("T2K RW NOT ENABLED"); #endif }; void T2KWeightEngine::IncludeDial(std::string name, double startval) { #ifdef __T2KREW_ENABLED__ // Get First enum int nuisenum = Reweight::ConvDial(name, kT2K); // Setup Maps fEnumIndex[nuisenum]; // = std::vector(0); fNameIndex[name]; // = std::vector(0); // Split by commas std::vector allnames = GeneralUtils::ParseToStr(name, ","); for (uint i = 0; i < allnames.size(); i++) { std::string singlename = allnames[i]; // Get RW t2krew::T2KSyst_t gensyst = t2krew::T2KSyst::FromString(name); // Fill Maps int index = fValues.size(); fValues.push_back(0.0); fT2KSysts.push_back(gensyst); // Initialize dial std::cout << "Registering " << singlename << " from " << name << std::endl; fT2KRW->Systematics().Include(gensyst); // If Absolute if (fIsAbsTwk) { fT2KRW->Systematics().SetAbsTwk(gensyst); } // Setup index fEnumIndex[nuisenum].push_back(index); fNameIndex[name].push_back(index); } // Set Value if given if (startval != -999.9) { SetDialValue(nuisenum, startval); } #endif } void T2KWeightEngine::SetDialValue(int nuisenum, double val) { #ifdef __T2KREW_ENABLED__ std::vector indices = fEnumIndex[nuisenum]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; fT2KRW->Systematics().SetTwkDial(fT2KSysts[indices[i]], val); } #endif } void T2KWeightEngine::SetDialValue(std::string name, double val) { #ifdef __T2KREW_ENABLED__ std::vector indices = fNameIndex[name]; for (uint i = 0; i < indices.size(); i++) { fValues[indices[i]] = val; fT2KRW->Systematics().SetTwkDial(fT2KSysts[indices[i]], val); } #endif } void T2KWeightEngine::Reconfigure(bool silent) { #ifdef __T2KREW_ENABLED__ // Hush now... if (silent) StopTalking(); // Reconf StopTalking(); fT2KRW->Reconfigure(); StartTalking(); // Shout again if (silent) StartTalking(); #endif } double T2KWeightEngine::CalcWeight(BaseFitEvt *evt) { double rw_weight = 1.0; #ifdef __T2KREW_ENABLED__ // Skip Non GENIE if (evt->fType != kNEUT) return 1.0; // Hush now StopTalking(); // Get Weight For NEUT rw_weight = fT2KRW->CalcWeight(evt->fNeutVect); // Speak Now StartTalking(); #endif // Return rw_weight return rw_weight; } diff --git a/src/Reweight/WeightEngineBase.cxx b/src/Reweight/WeightEngineBase.cxx index f4dff2a..ef04e5a 100644 --- a/src/Reweight/WeightEngineBase.cxx +++ b/src/Reweight/WeightEngineBase.cxx @@ -1,23 +1,23 @@ #include "WeightEngineBase.h" bool WeightEngineBase::IsDialIncluded(std::string name) { return (fNameIndex.find(name) != fNameIndex.end()); } bool WeightEngineBase::IsDialIncluded(int nuisenum) { return (fEnumIndex.find(nuisenum) != fEnumIndex.end()); } double WeightEngineBase::GetDialValue(std::string name) { if (!IsDialIncluded(name)) { - QTHROW("Dial " << name << " not included in " << fCalcName); + NUIS_ABORT("Dial " << name << " not included in " << fCalcName); } return fValues[fNameIndex[name][0]]; } double WeightEngineBase::GetDialValue(int nuisenum) { if (!IsDialIncluded(nuisenum)) { - QTHROW("Dial Enum " << nuisenum << " not included in " << fCalcName); + NUIS_ABORT("Dial Enum " << nuisenum << " not included in " << fCalcName); } return fValues[fEnumIndex[nuisenum][0]]; } diff --git a/src/Reweight/WeightUtils.cxx b/src/Reweight/WeightUtils.cxx index c86e928..eecb32c 100644 --- a/src/Reweight/WeightUtils.cxx +++ b/src/Reweight/WeightUtils.cxx @@ -1,592 +1,592 @@ #include "WeightUtils.h" #include "FitLogger.h" #ifdef __T2KREW_ENABLED__ #include "T2KGenieReWeight.h" #include "T2KNIWGReWeight.h" #include "T2KNIWGUtils.h" #include "T2KNeutReWeight.h" #include "T2KNeutUtils.h" #include "T2KReWeight.h" using namespace t2krew; #endif #ifdef __NIWG_ENABLED__ #include "NIWGReWeight.h" #include "NIWGSyst.h" #endif #ifdef __NEUT_ENABLED__ #include "NReWeight.h" #include "NSyst.h" #endif #ifdef __NUWRO_REWEIGHT_ENABLED__ #include "NuwroReWeight.h" #include "NuwroSyst.h" #endif #ifdef __GENIE_ENABLED__ #ifdef GENIE_PRE_R3 #ifndef __NO_GENIE_REWEIGHT__ #include "ReWeight/GReWeight.h" #include "ReWeight/GSyst.h" #endif #else using namespace genie; #ifndef __NO_GENIE_REWEIGHT__ #include "RwFramework/GReWeight.h" #include "RwFramework/GSyst.h" using namespace genie::rew; #endif #endif #endif #ifdef __NOVA_ENABLED__ #include "NOvARwgtEngine.h" #endif #include "GlobalDialList.h" #include "ModeNormEngine.h" #include "NUISANCESyst.h" #include "OscWeightEngine.h" //******************************************************************** TF1 FitBase::GetRWConvFunction(std::string const &type, std::string const &name) { //******************************************************************** std::string dialfunc = "x"; std::string parType = type; double low = -10000.0; double high = 10000.0; if (parType.find("parameter") == std::string::npos) parType += "_parameter"; std::string line; std::ifstream card( (GeneralUtils::GetTopLevelDir() + "/parameters/dial_conversion.card") .c_str(), std::ifstream::in); while (std::getline(card >> std::ws, line, '\n')) { std::vector inputlist = GeneralUtils::ParseToStr(line, " "); // Check the line length if (inputlist.size() < 4) continue; // Check whether this is a comment if (inputlist[0].c_str()[0] == '#') continue; // Check whether this is the correct parameter type if (inputlist[0].compare(parType) != 0) continue; // Check the parameter name if (inputlist[1].compare(name) != 0) continue; // inputlist[2] should be the units... ignore for now dialfunc = inputlist[3]; // High and low are optional, check whether they exist if (inputlist.size() > 4) low = GeneralUtils::StrToDbl(inputlist[4]); if (inputlist.size() > 5) high = GeneralUtils::StrToDbl(inputlist[5]); } TF1 convfunc = TF1((name + "_convfunc").c_str(), dialfunc.c_str(), low, high); return convfunc; } //******************************************************************** std::string FitBase::GetRWUnits(std::string const &type, std::string const &name) { //******************************************************************** std::string unit = "sig."; std::string parType = type; if (parType.find("parameter") == std::string::npos) { parType += "_parameter"; } std::string line; std::ifstream card( (GeneralUtils::GetTopLevelDir() + "/parameters/dial_conversion.card") .c_str(), std::ifstream::in); while (std::getline(card >> std::ws, line, '\n')) { std::vector inputlist = GeneralUtils::ParseToStr(line, " "); // Check the line length if (inputlist.size() < 3) continue; // Check whether this is a comment if (inputlist[0].c_str()[0] == '#') continue; // Check whether this is the correct parameter type if (inputlist[0].compare(parType) != 0) continue; // Check the parameter name if (inputlist[1].compare(name) != 0) continue; unit = inputlist[2]; break; } return unit; } //******************************************************************** double FitBase::RWAbsToSigma(std::string const &type, std::string const &name, double val) { //******************************************************************** TF1 f1 = GetRWConvFunction(type, name); double conv_val = f1.GetX(val); if (fabs(conv_val) < 1E-10) conv_val = 0.0; - QLOG(FIT, "AbsToSigma(" << name << ") = " << val << " -> " << conv_val); + NUIS_LOG(FIT, "AbsToSigma(" << name << ") = " << val << " -> " << conv_val); return conv_val; } //******************************************************************** double FitBase::RWSigmaToAbs(std::string const &type, std::string const &name, double val) { //******************************************************************** TF1 f1 = GetRWConvFunction(type, name); double conv_val = f1.Eval(val); return conv_val; } //******************************************************************** double FitBase::RWFracToSigma(std::string const &type, std::string const &name, double val) { //******************************************************************** TF1 f1 = GetRWConvFunction(type, name); double conv_val = f1.GetX((val * f1.Eval(0.0))); if (fabs(conv_val) < 1E-10) conv_val = 0.0; return conv_val; } //******************************************************************** double FitBase::RWSigmaToFrac(std::string const &type, std::string const &name, double val) { //******************************************************************** TF1 f1 = GetRWConvFunction(type, name); double conv_val = f1.Eval(val) / f1.Eval(0.0); return conv_val; } int FitBase::ConvDialType(std::string const &type) { if (!type.compare("neut_parameter")) return kNEUT; else if (!type.compare("niwg_parameter")) return kNIWG; else if (!type.compare("nuwro_parameter")) return kNUWRO; else if (!type.compare("t2k_parameter")) return kT2K; else if (!type.compare("genie_parameter")) return kGENIE; else if (!type.compare("custom_parameter")) return kCUSTOM; else if (!type.compare("norm_parameter")) return kNORM; else if (!type.compare("likeweight_parameter")) return kLIKEWEIGHT; else if (!type.compare("spline_parameter")) return kSPLINEPARAMETER; else if (!type.compare("osc_parameter")) return kOSCILLATION; else if (!type.compare("modenorm_parameter")) return kMODENORM; else if (!type.compare("nova_parameter")) return kNOvARWGT; else return kUNKNOWN; } std::string FitBase::ConvDialType(int type) { switch (type) { case kNEUT: { return "neut_parameter"; } case kNIWG: { return "niwg_parameter"; } case kNUWRO: { return "nuwro_parameter"; } case kT2K: { return "t2k_parameter"; } case kGENIE: { return "genie_parameter"; } case kNORM: { return "norm_parameter"; } case kCUSTOM: { return "custom_parameter"; } case kLIKEWEIGHT: { return "likeweight_parameter"; } case kSPLINEPARAMETER: { return "spline_parameter"; } case kOSCILLATION: { return "osc_parameter"; } case kMODENORM: { return "modenorm_parameter"; } case kNOvARWGT: { return "nova_parameter"; } default: return "unknown_parameter"; } } int FitBase::GetDialEnum(std::string const &type, std::string const &name) { return FitBase::GetDialEnum(FitBase::ConvDialType(type), name); } int FitBase::GetDialEnum(int type, std::string const &name) { int offset = type * 1000; int this_enum = Reweight::kNoDialFound; // Not Found - QLOG(DEB, "Getting dial enum " << type << " " << name); + NUIS_LOG(DEB, "Getting dial enum " << type << " " << name); // Select Types switch (type) { // NEUT DIAL TYPE case kNEUT: { #ifdef __NEUT_ENABLED__ int neut_enum = (int)neut::rew::NSyst::FromString(name); if (neut_enum != 0) { this_enum = neut_enum + offset; } #else this_enum = Reweight::kNoTypeFound; // Not enabled #endif break; } // NIWG DIAL TYPE case kNIWG: { #ifdef __NIWG_ENABLED__ int niwg_enum = (int)niwg::rew::NIWGSyst::FromString(name); if (niwg_enum != 0) { this_enum = niwg_enum + offset; } #else this_enum = Reweight::kNoTypeFound; #endif break; } // NUWRO DIAL TYPE case kNUWRO: { #ifdef __NUWRO_REWEIGHT_ENABLED__ int nuwro_enum = (int)nuwro::rew::NuwroSyst::FromString(name); if (nuwro_enum > 0) { this_enum = nuwro_enum + offset; } #else this_enum = Reweight::kNoTypeFound; #endif } // GENIE DIAL TYPE case kGENIE: { #if defined(__GENIE_ENABLED__) && !defined(__NO_GENIE_REWEIGHT__) int genie_enum = (int)genie::rew::GSyst::FromString(name); if (genie_enum > 0) { this_enum = genie_enum + offset; } #else this_enum = Reweight::kNoTypeFound; #endif break; } case kCUSTOM: { int custom_enum = 0; // PLACEHOLDER this_enum = custom_enum + offset; break; } // T2K DIAL TYPE case kT2K: { #ifdef __T2KREW_ENABLED__ int t2k_enum = (int)t2krew::T2KSyst::FromString(name); if (t2k_enum > 0) { this_enum = t2k_enum + offset; } #else this_enum = Reweight::kNoTypeFound; #endif break; } case kNORM: { if (gNormEnums.find(name) == gNormEnums.end()) { gNormEnums[name] = gNormEnums.size() + 1 + offset; } this_enum = gNormEnums[name]; break; } case kLIKEWEIGHT: { if (gLikeWeightEnums.find(name) == gLikeWeightEnums.end()) { gLikeWeightEnums[name] = gLikeWeightEnums.size() + 1 + offset; } this_enum = gLikeWeightEnums[name]; break; } case kSPLINEPARAMETER: { if (gSplineParameterEnums.find(name) == gSplineParameterEnums.end()) { gSplineParameterEnums[name] = gSplineParameterEnums.size() + 1 + offset; } this_enum = gSplineParameterEnums[name]; break; } case kOSCILLATION: { #ifdef __PROB3PP_ENABLED__ int oscEnum = OscWeightEngine::SystEnumFromString(name); if (oscEnum != 0) { this_enum = oscEnum + offset; } #else this_enum = Reweight::kNoTypeFound; // Not enabled #endif } case kMODENORM: { size_t us_pos = name.find_first_of('_'); std::string numstr = name.substr(us_pos + 1); int mode_num = std::atoi(numstr.c_str()); - QLOG(FTL, "Getting mode num " << mode_num); + NUIS_LOG(FTL, "Getting mode num " << mode_num); if (!mode_num) { - QTHROW("Attempting to parse dial name: \"" + NUIS_ABORT("Attempting to parse dial name: \"" << name << "\" as a mode norm dial but failed."); } this_enum = 60 + mode_num + offset; break; } } // If Not Enabled if (this_enum == Reweight::kNoTypeFound) { - QERROR(FTL, "RW Engine not supported for " << FitBase::ConvDialType(type)); - QTHROW("Check dial " << name); + NUIS_ERR(FTL, "RW Engine not supported for " << FitBase::ConvDialType(type)); + NUIS_ABORT("Check dial " << name); } // If Not Found if (this_enum == Reweight::kNoDialFound) { - QTHROW("Dial " << name << " not found."); + NUIS_ABORT("Dial " << name << " not found."); } return this_enum; } int Reweight::ConvDialType(std::string const &type) { return FitBase::ConvDialType(type); } std::string Reweight::ConvDialType(int type) { return FitBase::ConvDialType(type); } int Reweight::GetDialType(int type) { int t = (type / 1000); return t > kNOvARWGT ? Reweight::kNoDialFound : t; } int Reweight::RemoveDialType(int type) { return (type % 1000); } int Reweight::NEUTEnumFromName(std::string const &name) { #ifdef __NEUT_ENABLED__ int neutenum = (int)neut::rew::NSyst::FromString(name); return (neutenum > 0) ? neutenum : Reweight::kNoDialFound; #else return Reweight::kGeneratorNotBuilt; #endif } int Reweight::NIWGEnumFromName(std::string const &name) { #ifdef __NIWG_ENABLED__ int niwgenum = (int)niwg::rew::NIWGSyst::FromString(name); return (niwgenum != 0) ? niwgenum : Reweight::kNoDialFound; #else return Reweight::kGeneratorNotBuilt; #endif } int Reweight::NUWROEnumFromName(std::string const &name) { #ifdef __NUWRO_REWEIGHT_ENABLED__ int nuwroenum = (int)nuwro::rew::NuwroSyst::FromString(name); return (nuwroenum > 0) ? nuwroenum : Reweight::kNoDialFound; #else return Reweight::kGeneratorNotBuilt; #endif } int Reweight::GENIEEnumFromName(std::string const &name) { #ifdef defined(__GENIE_ENABLED__) && !defined(__NO_GENIE_REWEIGHT__) int genieenum = (int)genie::rew::GSyst::FromString(name); return (genieenum > 0) ? genieenum : Reweight::kNoDialFound; #else return Reweight::kGeneratorNotBuilt; #endif } int Reweight::T2KEnumFromName(std::string const &name) { #ifdef __T2KREW_ENABLED__ int t2kenum = (int)t2krew::T2KSyst::FromString(name); return (t2kenum > 0) ? t2kenum : Reweight::kNoDialFound; #else return Reweight::kGeneratorNotBuilt; #endif } int Reweight::OscillationEnumFromName(std::string const &name) { #ifdef __PROB3PP_ENABLED__ int oscEnum = OscWeightEngine::SystEnumFromString(name); return (oscEnum > 0) ? oscEnum : Reweight::kNoDialFound; #else return Reweight::kGeneratorNotBuilt; #endif } int Reweight::NUISANCEEnumFromName(std::string const &name, int type) { int nuisenum = Reweight::DialList().EnumFromNameAndType(name, type); return nuisenum; } int Reweight::CustomEnumFromName(std::string const &name) { int custenum = Reweight::ConvertNUISANCEDial(name); return custenum; } int Reweight::ConvDial(std::string const &name, std::string const &type, bool exceptions) { return Reweight::ConvDial(name, Reweight::ConvDialType(type), exceptions); } int Reweight::ConvDial(std::string const &fullname, int type, bool exceptions) { std::string name = GeneralUtils::ParseToStr(fullname, ",")[0]; // Only use first dial given // Produce offset seperating each type. int offset = type * 1000; int genenum = Reweight::kNoDialFound; switch (type) { case kNEUT: genenum = NEUTEnumFromName(name); break; case kNIWG: genenum = NIWGEnumFromName(name); break; case kNUWRO: genenum = NUWROEnumFromName(name); break; case kGENIE: genenum = GENIEEnumFromName(name); break; case kT2K: genenum = T2KEnumFromName(name); break; case kCUSTOM: genenum = CustomEnumFromName(name); break; case kNORM: case kLIKEWEIGHT: case kSPLINEPARAMETER: case kNEWSPLINE: genenum = NUISANCEEnumFromName(name, type); break; case kOSCILLATION: genenum = OscillationEnumFromName(name); break; case kMODENORM: genenum = ModeNormEngine::SystEnumFromString(name); break; #ifdef __NOVA_ENABLED__ case kNOvARWGT: genenum = NOvARwgtEngine::GetWeightGeneratorIndex(name); break; #endif default: genenum = Reweight::kNoTypeFound; break; } // Throw if required. if (exceptions) { // If Not Enabled if (genenum == Reweight::kGeneratorNotBuilt) { - QERROR(FTL, + NUIS_ERR(FTL, "RW Engine not supported for " << FitBase::ConvDialType(type)); - QTHROW("Check dial " << name); + NUIS_ABORT("Check dial " << name); } // If no type enabled if (genenum == Reweight::kNoTypeFound) { - QTHROW("Type mismatch inside ConvDialEnum"); + NUIS_ABORT("Type mismatch inside ConvDialEnum"); } // If Not Found if (genenum == Reweight::kNoDialFound) { - QTHROW("Dial " << name << " not found."); + NUIS_ABORT("Dial " << name << " not found."); } } // Add offset if no issue int nuisenum = genenum; if ((genenum != Reweight::kGeneratorNotBuilt) && (genenum != Reweight::kNoTypeFound) && (genenum != Reweight::kNoDialFound)) { nuisenum += offset; } // Now register dial Reweight::DialList().RegisterDialEnum(name, type, nuisenum); return nuisenum; } std::string Reweight::ConvDial(int nuisenum) { for (size_t i = 0; i < Reweight::DialList().fAllDialEnums.size(); i++) { if (Reweight::DialList().fAllDialEnums[i] == nuisenum) { return Reweight::DialList().fAllDialNames[i]; } } - QLOG(FIT, "Cannot find dial with enum = " << nuisenum); + NUIS_LOG(FIT, "Cannot find dial with enum = " << nuisenum); return ""; } diff --git a/src/Routines/BayesianRoutines.cxx b/src/Routines/BayesianRoutines.cxx index 9af9458..50d951c 100755 --- a/src/Routines/BayesianRoutines.cxx +++ b/src/Routines/BayesianRoutines.cxx @@ -1,518 +1,518 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "BayesianRoutines.h" void BayesianRoutines::Init() { fInputFile = ""; fInputRootFile = NULL; fOutputFile = ""; fOutputRootFile = NULL; fStrategy = "BayesianThrows"; fRoutines.clear(); fRoutines.push_back("BayesianThrows"); fCardFile = ""; fFakeDataInput = ""; fSampleFCN = NULL; fAllowedRoutines = ("f"); }; BayesianRoutines::~BayesianRoutines(){}; BayesianRoutines::BayesianRoutines(int argc, char *argv[]) { // Initialise Defaults Init(); nuisconfig configuration = Config::Get(); // Default containers std::string cardfile = ""; std::string maxevents = "-1"; int errorcount = 0; int verbocount = 0; std::vector xmlcmds; std::vector configargs; fNThrows = 250; fStartThrows = 0; fThrowString = ""; // Make easier to handle arguments. std::vector args = GeneralUtils::LoadCharToVectStr(argc, argv); ParserUtils::ParseArgument(args, "-c", fCardFile, true); ParserUtils::ParseArgument(args, "-o", fOutputFile, false, false); ParserUtils::ParseArgument(args, "-n", maxevents, false, false); ParserUtils::ParseArgument(args, "-f", fStrategy, false, false); ParserUtils::ParseArgument(args, "-t", fNThrows, false, false); ParserUtils::ParseArgument(args, "-i", xmlcmds); ParserUtils::ParseArgument(args, "-q", configargs); ParserUtils::ParseCounter(args, "e", errorcount); ParserUtils::ParseCounter(args, "v", verbocount); ParserUtils::CheckBadArguments(args); // Add extra defaults if none given if (fCardFile.empty() and xmlcmds.empty()) { - QTHROW("No input supplied!"); + NUIS_ABORT("No input supplied!"); } if (fOutputFile.empty() and !fCardFile.empty()) { fOutputFile = fCardFile + ".root"; - QERROR(WRN, "No output supplied so saving it to: " << fOutputFile); + NUIS_ERR(WRN, "No output supplied so saving it to: " << fOutputFile); } else if (fOutputFile.empty()) { - QTHROW("No output file or cardfile supplied!"); + NUIS_ABORT("No output file or cardfile supplied!"); } // Configuration Setup ============================= // Check no comp key is available if (Config::Get().GetNodes("nuiscomp").empty()) { fCompKey = Config::Get().CreateNode("nuiscomp"); } else { fCompKey = Config::Get().GetNodes("nuiscomp")[0]; } if (!fCardFile.empty()) fCompKey.Set("cardfile", fCardFile); if (!fOutputFile.empty()) fCompKey.Set("outputfile", fOutputFile); if (!fStrategy.empty()) fCompKey.Set("strategy", fStrategy); // Load XML Cardfile configuration.LoadSettings(fCompKey.GetS("cardfile"), ""); // Add Config Args for (size_t i = 0; i < configargs.size(); i++) { configuration.OverrideConfig(configargs[i]); } if (maxevents.compare("-1")) { configuration.OverrideConfig("MAXEVENTS=" + maxevents); } // Finish configuration XML configuration.FinaliseSettings(fCompKey.GetS("outputfile") + ".xml"); // Add Error Verbo Lines verbocount += Config::GetParI("VERBOSITY"); errorcount += Config::GetParI("ERROR"); std::cout << "[ NUISANCE ]: Setting VERBOSITY=" << verbocount << std::endl; std::cout << "[ NUISANCE ]: Setting ERROR=" << errorcount << std::endl; SETVERBOSITY(verbocount); // Proper Setup if (fStrategy.find("ErrorBands") != std::string::npos || fStrategy.find("MergeErrors") != std::string::npos) { fOutputRootFile = new TFile(fCompKey.GetS("outputfile").c_str(), "RECREATE"); } // fOutputRootFile = new TFile(fCompKey.GetS("outputfile").c_str(), // "RECREATE"); SetupSystematicsFromXML(); SetupRWEngine(); SetupFCN(); return; }; void BayesianRoutines::SetupSystematicsFromXML() { - QLOG(FIT, "Setting up nuismin"); + NUIS_LOG(FIT, "Setting up nuismin"); // Setup Parameters ------------------------------------------ std::vector parkeys = Config::QueryKeys("parameter"); if (!parkeys.empty()) { - QLOG(FIT, "Number of parameters : " << parkeys.size()); + NUIS_LOG(FIT, "Number of parameters : " << parkeys.size()); } for (size_t i = 0; i < parkeys.size(); i++) { nuiskey key = parkeys.at(i); // Check for type,name,nom if (!key.Has("type")) { - QTHROW("No type given for parameter " << i); + NUIS_ABORT("No type given for parameter " << i); } else if (!key.Has("name")) { - QTHROW("No name given for parameter " << i); + NUIS_ABORT("No name given for parameter " << i); } else if (!key.Has("nominal")) { - QTHROW("No nominal given for parameter " << i); + NUIS_ABORT("No nominal given for parameter " << i); } // Get Inputs std::string partype = key.GetS("type"); std::string parname = key.GetS("name"); double parnom = key.GetD("nominal"); double parlow = parnom - 1; double parhigh = parnom + 1; double parstep = 1; // Override if state not given if (!key.Has("state")) { key.SetS("state", "FIX"); } std::string parstate = key.GetS("state"); // Extra limits if (key.Has("low")) { parlow = key.GetD("low"); parhigh = key.GetD("high"); parstep = key.GetD("step"); - QLOG(FIT, "Read " << partype << " : " << parname << " = " << parnom + NUIS_LOG(FIT, "Read " << partype << " : " << parname << " = " << parnom << " : " << parlow << " < p < " << parhigh << " : " << parstate); } else { - QLOG(FIT, "Read " << partype << " : " << parname << " = " << parnom + NUIS_LOG(FIT, "Read " << partype << " : " << parname << " = " << parnom << " : " << parstate); } // Run Parameter Conversion if needed if (parstate.find("ABS") != std::string::npos) { parnom = FitBase::RWAbsToSigma(partype, parname, parnom); parlow = FitBase::RWAbsToSigma(partype, parname, parlow); parhigh = FitBase::RWAbsToSigma(partype, parname, parhigh); parstep = FitBase::RWAbsToSigma(partype, parname, parstep); } else if (parstate.find("FRAC") != std::string::npos) { parnom = FitBase::RWFracToSigma(partype, parname, parnom); parlow = FitBase::RWFracToSigma(partype, parname, parlow); parhigh = FitBase::RWFracToSigma(partype, parname, parhigh); parstep = FitBase::RWFracToSigma(partype, parname, parstep); } // Push into vectors fParams.push_back(parname); fTypeVals[parname] = FitBase::ConvDialType(partype); ; fStartVals[parname] = parnom; fCurVals[parname] = parnom; fErrorVals[parname] = 0.0; fStateVals[parname] = parstate; bool fixstate = parstate.find("FIX") != std::string::npos; fFixVals[parname] = fixstate; fStartFixVals[parname] = fFixVals[parname]; fMinVals[parname] = parlow; fMaxVals[parname] = parhigh; fStepVals[parname] = parstep; } // Setup Samples ---------------------------------------------- std::vector samplekeys = Config::QueryKeys("sample"); if (!samplekeys.empty()) { - QLOG(FIT, "Number of samples : " << samplekeys.size()); + NUIS_LOG(FIT, "Number of samples : " << samplekeys.size()); } else { - QERROR(WRN, "NO SAMPLES LOADED"); + NUIS_ERR(WRN, "NO SAMPLES LOADED"); } for (size_t i = 0; i < samplekeys.size(); i++) { nuiskey key = samplekeys.at(i); // Get Sample Options std::string samplename = key.GetS("name"); std::string samplefile = key.GetS("input"); std::string sampletype = key.Has("type") ? key.GetS("type") : "DEFAULT"; double samplenorm = key.Has("norm") ? key.GetD("norm") : 1.0; // Print out - QLOG(FIT, "Read sample info " << i << " : " << samplename << std::endl + NUIS_LOG(FIT, "Read sample info " << i << " : " << samplename << std::endl << "\t\t input -> " << samplefile << std::endl << "\t\t state -> " << sampletype << std::endl << "\t\t norm -> " << samplenorm); // If FREE add to parameters otherwise continue if (sampletype.find("FREE") == std::string::npos) { continue; } // Form norm dial from samplename + sampletype + "_norm"; std::string normname = samplename + "_norm"; // Check normname not already present if (fTypeVals.find(normname) != fTypeVals.end()) { continue; } // Add new norm dial to list if its passed above checks fParams.push_back(normname); fTypeVals[normname] = kNORM; fStateVals[normname] = sampletype; fCurVals[normname] = samplenorm; fErrorVals[normname] = 0.0; fMinVals[normname] = 0.1; fMaxVals[normname] = 10.0; fStepVals[normname] = 0.5; bool state = sampletype.find("FREE") == std::string::npos; fFixVals[normname] = state; fStartFixVals[normname] = state; } // Setup Fake Parameters ----------------------------- std::vector fakekeys = Config::QueryKeys("fakeparameter"); if (!fakekeys.empty()) { - QLOG(FIT, "Number of fake parameters : " << fakekeys.size()); + NUIS_LOG(FIT, "Number of fake parameters : " << fakekeys.size()); } for (size_t i = 0; i < fakekeys.size(); i++) { nuiskey key = fakekeys.at(i); // Check for type,name,nom if (!key.Has("name")) { - QTHROW("No name given for fakeparameter " << i); + NUIS_ABORT("No name given for fakeparameter " << i); } else if (!key.Has("nom")) { - QTHROW("No nominal given for fakeparameter " << i); + NUIS_ABORT("No nominal given for fakeparameter " << i); } // Get Inputs std::string parname = key.GetS("name"); double parnom = key.GetD("nom"); // Push into vectors fFakeVals[parname] = parnom; } } /* Setup Functions */ //************************************* void BayesianRoutines::SetupRWEngine() { //************************************* for (UInt_t i = 0; i < fParams.size(); i++) { std::string name = fParams[i]; FitBase::GetRW()->IncludeDial(name, fTypeVals.at(name)); } UpdateRWEngine(fStartVals); return; } //************************************* void BayesianRoutines::SetupFCN() { //************************************* - QLOG(FIT, "Making the jointFCN"); + NUIS_LOG(FIT, "Making the jointFCN"); if (fSampleFCN) delete fSampleFCN; fSampleFCN = new JointFCN(fOutputRootFile); fInputThrows = fSampleFCN->GetPullList(); return; } /* Fitting Functions */ //************************************* void BayesianRoutines::UpdateRWEngine( std::map &updateVals) { //************************************* for (UInt_t i = 0; i < fParams.size(); i++) { std::string name = fParams[i]; if (updateVals.find(name) == updateVals.end()) continue; FitBase::GetRW()->SetDialValue(name, updateVals.at(name)); } FitBase::GetRW()->Reconfigure(); return; } //************************************* void BayesianRoutines::ThrowParameters() { //************************************* // Set fThrownVals to all values in currentVals for (UInt_t i = 0; i < fParams.size(); i++) { std::string name = fParams.at(i); fThrownVals[name] = fCurVals[name]; } for (PullListConstIter iter = fInputThrows.begin(); iter != fInputThrows.end(); iter++) { ParamPull *pull = *iter; pull->ThrowCovariance(); TH1D dialhist = pull->GetDataHist(); for (int i = 0; i < dialhist.GetNbinsX(); i++) { std::string name = std::string(dialhist.GetXaxis()->GetBinLabel(i + 1)); if (fCurVals.find(name) != fCurVals.end()) { fThrownVals[name] = dialhist.GetBinContent(i + 1); } } // Reset throw incase pulls are calculated. pull->ResetToy(); } // Now update Parameters UpdateRWEngine(fThrownVals); // Update Pulls for (PullListConstIter iter = fInputThrows.begin(); iter != fInputThrows.end(); iter++) { ParamPull *pull = *iter; pull->Reconfigure(); } return; }; //************************************* void BayesianRoutines::Run() { //************************************* std::cout << "Running routines " << std::endl; fRoutines = GeneralUtils::ParseToStr(fStrategy, ","); for (UInt_t i = 0; i < fRoutines.size(); i++) { std::string routine = fRoutines.at(i); - QLOG(FIT, "Running Routine: " << routine); + NUIS_LOG(FIT, "Running Routine: " << routine); if (!routine.compare("BayesianThrows")) GenerateThrows(); else { - QTHROW("UNKNOWN ROUTINE " << routine); + NUIS_ABORT("UNKNOWN ROUTINE " << routine); } } return; } //************************************* void BayesianRoutines::GenerateThrows() { //************************************* // Create a new output file TFile *outfile = new TFile((fOutputFile + ".throws.root").c_str(), "RECREATE"); outfile->cd(); int nthrows = fNThrows; // Setting Seed // Matteo Mazzanti's Fix struct timeval mytime; gettimeofday(&mytime, NULL); Double_t seed = time(NULL) + int(getpid()) + (mytime.tv_sec * 1000.) + (mytime.tv_usec / 1000.); gRandom->SetSeed(seed); - QLOG(FIT, "Using Seed : " << seed); - QLOG(FIT, "nthrows = " << nthrows); + NUIS_LOG(FIT, "Using Seed : " << seed); + NUIS_LOG(FIT, "nthrows = " << nthrows); // Run the Initial Reconfigure - QLOG(FIT, "Making nominal prediction "); + NUIS_LOG(FIT, "Making nominal prediction "); TDirectory *nominal = (TDirectory *)outfile->mkdir("nominal"); nominal->cd(); UpdateRWEngine(fStartVals); fSampleFCN->ReconfigureUsingManager(); fSampleFCN->Write(); // Create an iteration tree inside SampleFCN fSampleFCN->CreateIterationTree("error_iterations", FitBase::GetRW()); // Create a new iteration TTree TTree *LIKETREE = new TTree("likelihood", "likelihood"); std::vector likenames = fSampleFCN->GetAllNames(); std::vector likevals = fSampleFCN->GetAllLikelihoods(); std::vector likendof = fSampleFCN->GetAllNDOF(); double *LIKEVALS = new double[likevals.size()]; int *LIKENDOF = new int[likendof.size()]; for (size_t i = 0; i < likendof.size(); i++) { LIKETREE->Branch((likenames[i] + "_likelihood").c_str(), &LIKEVALS[i], (likenames[i] + "_likelihood/D").c_str()); LIKETREE->Branch((likenames[i] + "_ndof").c_str(), &LIKENDOF[i], (likenames[i] + "_ndof/I").c_str()); LIKENDOF[i] = likendof[i]; } likenames.clear(); likevals.clear(); likendof.clear(); double *PARAMVALS = new double[fParams.size()]; for (size_t i = 0; i < fParams.size(); i++) { LIKETREE->Branch(fParams[i].c_str(), &PARAMVALS[i], (fParams[i] + "/D").c_str()); } // Run Throws and save for (Int_t i = 0; i < nthrows; i++) { // Skip the start throw if (i == 0) continue; - QLOG(FIT, "Throw " << i << " ================================"); + NUIS_LOG(FIT, "Throw " << i << " ================================"); // Throw Parameters ThrowParameters(); FitBase::GetRW()->Print(); // Get Parameter Values for (size_t i = 0; i < fParams.size(); i++) { PARAMVALS[i] = fThrownVals[fParams[i]]; } // Run Sample Prediction fSampleFCN->ReconfigureFastUsingManager(); // Get vector of likelihoods/ndof std::vector likevals = fSampleFCN->GetAllLikelihoods(); for (size_t i = 0; i < likevals.size(); i++) { LIKEVALS[i] = likevals[i]; } // Save to TTree LIKETREE->Fill(); // Save the FCN // if (fSavePredictions){ SaveSamplePredictions(); } - QLOG(FIT, "END OF THROW ================================"); + NUIS_LOG(FIT, "END OF THROW ================================"); } // Finish up outfile->cd(); LIKETREE->Write(); outfile->Close(); delete LIKEVALS; delete LIKENDOF; delete PARAMVALS; } diff --git a/src/Routines/ComparisonRoutines.cxx b/src/Routines/ComparisonRoutines.cxx index 0282758..fe687ba 100755 --- a/src/Routines/ComparisonRoutines.cxx +++ b/src/Routines/ComparisonRoutines.cxx @@ -1,521 +1,521 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "ComparisonRoutines.h" /* Constructor/Destructor */ //************************ void ComparisonRoutines::Init() { //************************ fOutputFile = ""; fOutputRootFile = NULL; fStrategy = "Compare"; fRoutines.clear(); fCardFile = ""; fFakeDataInput = ""; fSampleFCN = NULL; fAllowedRoutines = ("Compare"); }; //************************************* ComparisonRoutines::~ComparisonRoutines() { //************************************* delete fOutputRootFile; }; /* Input Functions */ //************************************* ComparisonRoutines::ComparisonRoutines(int argc, char *argv[]) { //************************************* // Initialise Defaults Init(); nuisconfig configuration = Config::Get(); // Default containers std::string cardfile = ""; std::string maxevents = "-1"; int errorcount = 0; int verbocount = 0; std::vector xmlcmds; std::vector configargs; // Make easier to handle arguments. std::vector args = GeneralUtils::LoadCharToVectStr(argc, argv); ParserUtils::ParseArgument(args, "-c", fCardFile, true); ParserUtils::ParseArgument(args, "-o", fOutputFile, false, false); ParserUtils::ParseArgument(args, "-n", maxevents, false, false); ParserUtils::ParseArgument(args, "-f", fStrategy, false, false); ParserUtils::ParseArgument(args, "-d", fFakeDataInput, false, false); ParserUtils::ParseArgument(args, "-i", xmlcmds); ParserUtils::ParseArgument(args, "-q", configargs); ParserUtils::ParseCounter(args, "e", errorcount); ParserUtils::ParseCounter(args, "v", verbocount); ParserUtils::CheckBadArguments(args); // Add extra defaults if none given if (fCardFile.empty() and xmlcmds.empty()) { - QTHROW("No input supplied!"); + NUIS_ABORT("No input supplied!"); } if (fOutputFile.empty() and !fCardFile.empty()) { fOutputFile = fCardFile + ".root"; - QERROR(WRN, "No output supplied so saving it to: " << fOutputFile); + NUIS_ERR(WRN, "No output supplied so saving it to: " << fOutputFile); } else if (fOutputFile.empty()) { - QTHROW("No output file or cardfile supplied!"); + NUIS_ABORT("No output file or cardfile supplied!"); } // Configuration Setup ============================= // Check no comp key is available nuiskey fCompKey; if (Config::Get().GetNodes("nuiscomp").empty()) { fCompKey = Config::Get().CreateNode("nuiscomp"); } else { fCompKey = Config::Get().GetNodes("nuiscomp")[0]; } if (!fCardFile.empty()) fCompKey.Set("cardfile", fCardFile); if (!fOutputFile.empty()) fCompKey.Set("outputfile", fOutputFile); if (!fStrategy.empty()) fCompKey.Set("strategy", fStrategy); // Load XML Cardfile configuration.LoadSettings(fCompKey.GetS("cardfile"), ""); // Add Config Args for (size_t i = 0; i < configargs.size(); i++) { configuration.OverrideConfig(configargs[i]); } if (maxevents.compare("-1")) { configuration.OverrideConfig("MAXEVENTS=" + maxevents); } // Finish configuration XML configuration.FinaliseSettings(fCompKey.GetS("outputfile") + ".xml"); // Add Error Verbo Lines verbocount += Config::GetParI("VERBOSITY"); errorcount += Config::GetParI("ERROR"); bool trace = Config::GetParB("TRACE"); std::cout << "[ NUISANCE ]: Setting VERBOSITY=" << verbocount << std::endl; std::cout << "[ NUISANCE ]: Setting ERROR=" << errorcount << std::endl; SETVERBOSITY(verbocount); SETTRACE(trace); // Comparison Setup ======================================== // Proper Setup fOutputRootFile = new TFile(fCompKey.GetS("outputfile").c_str(), "RECREATE"); SetupComparisonsFromXML(); SetupRWEngine(); SetupFCN(); return; }; //************************************* void ComparisonRoutines::SetupComparisonsFromXML() { //************************************* - QLOG(FIT, "Setting up nuiscomp"); + NUIS_LOG(FIT, "Setting up nuiscomp"); // Setup Parameters ------------------------------------------ std::vector parkeys = Config::QueryKeys("parameter"); if (!parkeys.empty()) { - QLOG(FIT, "Number of parameters : " << parkeys.size()); + NUIS_LOG(FIT, "Number of parameters : " << parkeys.size()); } for (size_t i = 0; i < parkeys.size(); i++) { nuiskey key = parkeys.at(i); // Check for type,name,nom if (!key.Has("type")) { - QERROR(FTL, "No type given for parameter " << i); - QTHROW("type='PARAMETER_TYPE'"); + NUIS_ERR(FTL, "No type given for parameter " << i); + NUIS_ABORT("type='PARAMETER_TYPE'"); } else if (!key.Has("name")) { - QERROR(FTL, "No name given for parameter " << i); - QTHROW("name='SAMPLE_NAME'"); + NUIS_ERR(FTL, "No name given for parameter " << i); + NUIS_ABORT("name='SAMPLE_NAME'"); } else if (!key.Has("nominal")) { - QERROR(FTL, "No nominal given for parameter " << i); - QTHROW("nominal='NOMINAL_VALUE'"); + NUIS_ERR(FTL, "No nominal given for parameter " << i); + NUIS_ABORT("nominal='NOMINAL_VALUE'"); } // Get Inputs std::string partype = key.GetS("type"); std::string parname = key.GetS("name"); double parnom = key.GetD("nominal"); double parlow = parnom - 1; double parhigh = parnom + 1; double parstep = 1; // override if state not given if (!key.Has("state")) { key.SetS("state", "FIX"); } std::string parstate = key.GetS("state"); // Check for incomplete limtis int limdef = ((int)key.Has("low") + (int)key.Has("high") + (int)key.Has("step")); if (limdef > 0 and limdef < 3) { - QERROR(FTL, "Incomplete limit set given for parameter : " << parname); - QTHROW( + NUIS_ERR(FTL, "Incomplete limit set given for parameter : " << parname); + NUIS_ABORT( "Requires: low='LOWER_LIMIT' high='UPPER_LIMIT' step='STEP_SIZE' "); } // Extra limits if (key.Has("low")) { parlow = key.GetD("low"); parhigh = key.GetD("high"); parstep = key.GetD("step"); - QLOG(FIT, "Read " << partype << " : " << parname << " = " << parnom + NUIS_LOG(FIT, "Read " << partype << " : " << parname << " = " << parnom << " : " << parlow << " < p < " << parhigh << " : " << parstate); } else { - QLOG(FIT, "Read " << partype << " : " << parname << " = " << parnom + NUIS_LOG(FIT, "Read " << partype << " : " << parname << " = " << parnom << " : " << parstate); } // Convert if required if (parstate.find("ABS") != std::string::npos) { parnom = FitBase::RWAbsToSigma(partype, parname, parnom); parlow = FitBase::RWAbsToSigma(partype, parname, parlow); parhigh = FitBase::RWAbsToSigma(partype, parname, parhigh); parstep = FitBase::RWAbsToSigma(partype, parname, parstep); } else if (parstate.find("FRAC") != std::string::npos) { parnom = FitBase::RWFracToSigma(partype, parname, parnom); parlow = FitBase::RWFracToSigma(partype, parname, parlow); parhigh = FitBase::RWFracToSigma(partype, parname, parhigh); parstep = FitBase::RWFracToSigma(partype, parname, parstep); } // Push into vectors fParams.push_back(parname); fTypeVals[parname] = FitBase::ConvDialType(partype); fCurVals[parname] = parnom; fStateVals[parname] = parstate; } // Setup Samples ---------------------------------------------- std::vector samplekeys = Config::QueryKeys("sample"); if (!samplekeys.empty()) { - QLOG(FIT, "Number of samples : " << samplekeys.size()); + NUIS_LOG(FIT, "Number of samples : " << samplekeys.size()); } for (size_t i = 0; i < samplekeys.size(); i++) { nuiskey key = samplekeys.at(i); // Get Sample Options std::string samplename = key.GetS("name"); std::string samplefile = key.GetS("input"); std::string sampletype = key.Has("type") ? key.GetS("type") : "DEFAULT"; double samplenorm = key.Has("norm") ? key.GetD("norm") : 1.0; // Print out - QLOG(FIT, "Read Sample " << i << ". : " << samplename << " (" << sampletype + NUIS_LOG(FIT, "Read Sample " << i << ". : " << samplename << " (" << sampletype << ") [Norm=" << samplenorm << "]" << std::endl << " -> input='" << samplefile << "'"); // If FREE add to parameters otherwise continue if (sampletype.find("FREE") == std::string::npos) { if (samplenorm != 1.0) { - QERROR(FTL, "You provided a sample normalisation but did not specify " + NUIS_ERR(FTL, "You provided a sample normalisation but did not specify " "that the sample is free"); - QTHROW("Change so sample contains type=\"FREE\" and re-run"); + NUIS_ABORT("Change so sample contains type=\"FREE\" and re-run"); } continue; } // Form norm dial from samplename + sampletype + "_norm"; std::string normname = samplename + "_norm"; // Check normname not already present if (fTypeVals.find("normname") != fTypeVals.end()) { continue; } // Add new norm dial to list if its passed above checks fParams.push_back(normname); fTypeVals[normname] = kNORM; fStateVals[normname] = sampletype; fCurVals[normname] = samplenorm; } // Setup Fake Parameters ----------------------------- std::vector fakekeys = Config::QueryKeys("fakeparameter"); if (!fakekeys.empty()) { - QLOG(FIT, "Number of fake parameters : " << fakekeys.size()); + NUIS_LOG(FIT, "Number of fake parameters : " << fakekeys.size()); } for (size_t i = 0; i < fakekeys.size(); i++) { nuiskey key = fakekeys.at(i); // Check for type,name,nom if (!key.Has("name")) { - QTHROW("No name given for fakeparameter " << i); + NUIS_ABORT("No name given for fakeparameter " << i); } else if (!key.Has("nominal")) { - QTHROW("No nominal given for fakeparameter " << i); + NUIS_ABORT("No nominal given for fakeparameter " << i); } // Get Inputs std::string parname = key.GetS("name"); double parnom = key.GetD("nominal"); // Push into vectors fFakeVals[parname] = parnom; } } //************************************* void ComparisonRoutines::SetupRWEngine() { //************************************* - QLOG(FIT, "Setting up FitWeight Engine"); + NUIS_LOG(FIT, "Setting up FitWeight Engine"); for (UInt_t i = 0; i < fParams.size(); i++) { std::string name = fParams[i]; FitBase::GetRW()->IncludeDial(name, fTypeVals.at(name)); } return; } //************************************* void ComparisonRoutines::SetupFCN() { //************************************* - QLOG(FIT, "Building the SampleFCN"); + NUIS_LOG(FIT, "Building the SampleFCN"); if (fSampleFCN) delete fSampleFCN; Config::Get().out = fOutputRootFile; fOutputRootFile->cd(); fSampleFCN = new JointFCN(fOutputRootFile); SetFakeData(); return; } //************************************* void ComparisonRoutines::SetFakeData() { //************************************* if (fFakeDataInput.empty()) return; if (fFakeDataInput.compare("MC") == 0) { - QLOG(FIT, "Setting fake data from MC starting prediction."); + NUIS_LOG(FIT, "Setting fake data from MC starting prediction."); UpdateRWEngine(fFakeVals); FitBase::GetRW()->Reconfigure(); fSampleFCN->ReconfigureAllEvents(); fSampleFCN->SetFakeData("MC"); UpdateRWEngine(fCurVals); - QLOG(FIT, "Set all data to fake MC predictions."); + NUIS_LOG(FIT, "Set all data to fake MC predictions."); } else { - QLOG(FIT, "Setting fake data from: " << fFakeDataInput); + NUIS_LOG(FIT, "Setting fake data from: " << fFakeDataInput); fSampleFCN->SetFakeData(fFakeDataInput); } return; } /* Fitting Functions */ //************************************* void ComparisonRoutines::UpdateRWEngine( std::map &updateVals) { //************************************* for (UInt_t i = 0; i < fParams.size(); i++) { std::string name = fParams[i]; if (updateVals.find(name) == updateVals.end()) continue; FitBase::GetRW()->SetDialValue(name, updateVals.at(name)); } FitBase::GetRW()->Reconfigure(); return; } //************************************* void ComparisonRoutines::Run() { //************************************* - QLOG(FIT, "Running ComparisonRoutines : " << fStrategy); + NUIS_LOG(FIT, "Running ComparisonRoutines : " << fStrategy); if (FitPar::Config().GetParB("save_nominal")) { SaveNominal(); } // Parse given routines fRoutines = GeneralUtils::ParseToStr(fStrategy, ","); if (fRoutines.empty()) { - QTHROW("Trying to run ComparisonRoutines with no routines given!"); + NUIS_ABORT("Trying to run ComparisonRoutines with no routines given!"); } for (UInt_t i = 0; i < fRoutines.size(); i++) { std::string routine = fRoutines.at(i); - QLOG(FIT, "Routine: " << routine); + NUIS_LOG(FIT, "Routine: " << routine); if (!routine.compare("Compare")) { UpdateRWEngine(fCurVals); GenerateComparison(); PrintState(); SaveCurrentState(); } } return; } //************************************* void ComparisonRoutines::GenerateComparison() { //************************************* - QLOG(FIT, "Generating Comparison."); + NUIS_LOG(FIT, "Generating Comparison."); // Main Event Loop from event Manager fSampleFCN->ReconfigureAllEvents(); return; } //************************************* void ComparisonRoutines::PrintState() { //************************************* - QLOG(FIT, "------------"); + NUIS_LOG(FIT, "------------"); // Count max size int maxcount = 0; for (UInt_t i = 0; i < fParams.size(); i++) { maxcount = max(int(fParams[i].size()), maxcount); } // Header - QLOG(FIT, " # " << left << setw(maxcount) << "Parameter " + NUIS_LOG(FIT, " # " << left << setw(maxcount) << "Parameter " << " = " << setw(10) << "Value" << " +- " << setw(10) << "Error" << " " << setw(8) << "(Units)" << " " << setw(10) << "Conv. Val" << " +- " << setw(10) << "Conv. Err" << " " << setw(8) << "(Units)"); // Parameters for (UInt_t i = 0; i < fParams.size(); i++) { std::string syst = fParams.at(i); std::string typestr = FitBase::ConvDialType(fTypeVals[syst]); std::string curunits = "(sig.)"; double curval = fCurVals[syst]; double curerr = 0.0; if (fStateVals[syst].find("ABS") != std::string::npos) { curval = FitBase::RWSigmaToAbs(typestr, syst, curval); curerr = (FitBase::RWSigmaToAbs(typestr, syst, curerr) - FitBase::RWSigmaToAbs(typestr, syst, 0.0)); curunits = "(Abs.)"; } else if (fStateVals[syst].find("FRAC") != std::string::npos) { curval = FitBase::RWSigmaToFrac(typestr, syst, curval); curerr = (FitBase::RWSigmaToFrac(typestr, syst, curerr) - FitBase::RWSigmaToFrac(typestr, syst, 0.0)); curunits = "(Frac)"; } std::string convunits = "(" + FitBase::GetRWUnits(typestr, syst) + ")"; double convval = FitBase::RWSigmaToAbs(typestr, syst, curval); double converr = (FitBase::RWSigmaToAbs(typestr, syst, curerr) - FitBase::RWSigmaToAbs(typestr, syst, 0.0)); std::ostringstream curparstring; curparstring << " " << setw(3) << left << i << ". " << setw(maxcount) << syst << " = " << setw(10) << curval << " +- " << setw(10) << curerr << " " << setw(8) << curunits << " " << setw(10) << convval << " +- " << setw(10) << converr << " " << setw(8) << convunits; - QLOG(FIT, curparstring.str()); + NUIS_LOG(FIT, curparstring.str()); } - QLOG(FIT, "------------"); + NUIS_LOG(FIT, "------------"); double like = fSampleFCN->GetLikelihood(); - QLOG(FIT, std::left << std::setw(46) << "Likelihood for JointFCN: " << like); - QLOG(FIT, "------------"); + NUIS_LOG(FIT, std::left << std::setw(46) << "Likelihood for JointFCN: " << like); + NUIS_LOG(FIT, "------------"); } /* Write Functions */ //************************************* void ComparisonRoutines::SaveCurrentState(std::string subdir) { //************************************* - QLOG(FIT, "Saving current full FCN predictions"); + NUIS_LOG(FIT, "Saving current full FCN predictions"); // Setup DIRS TDirectory *curdir = gDirectory; if (!subdir.empty()) { TDirectory *newdir = (TDirectory *)gDirectory->mkdir(subdir.c_str()); newdir->cd(); } fSampleFCN->Write(); // Change back to current DIR curdir->cd(); return; } //************************************* void ComparisonRoutines::SaveNominal() { //************************************* fOutputRootFile->cd(); - QLOG(FIT, "Saving Nominal Predictions (be cautious with this)"); + NUIS_LOG(FIT, "Saving Nominal Predictions (be cautious with this)"); FitBase::GetRW()->Reconfigure(); GenerateComparison(); SaveCurrentState("nominal"); }; diff --git a/src/Routines/MinimizerRoutines.cxx b/src/Routines/MinimizerRoutines.cxx index 7485b23..4e20a4a 100755 --- a/src/Routines/MinimizerRoutines.cxx +++ b/src/Routines/MinimizerRoutines.cxx @@ -1,1535 +1,1535 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "MinimizerRoutines.h" #include "Simple_MH_Sampler.h" /* Constructor/Destructor */ //************************ void MinimizerRoutines::Init() { //************************ fInputFile = ""; fInputRootFile = NULL; fOutputFile = ""; fOutputRootFile = NULL; fCovar = NULL; fCovFree = NULL; fCorrel = NULL; fCorFree = NULL; fDecomp = NULL; fDecFree = NULL; fStrategy = "Migrad,FixAtLimBreak,Migrad"; fRoutines.clear(); fCardFile = ""; fFakeDataInput = ""; fSampleFCN = NULL; fMinimizer = NULL; fMinimizerFCN = NULL; fCallFunctor = NULL; fAllowedRoutines = ("Migrad,Simplex,Combined," "Brute,Fumili,ConjugateFR," "ConjugatePR,BFGS,BFGS2," "SteepDesc,GSLSimAn,FixAtLim,FixAtLimBreak," "Chi2Scan1D,Chi2Scan2D,Contours,ErrorBands," "DataToys,MCMC"); }; //************************************* MinimizerRoutines::~MinimizerRoutines(){ //************************************* }; /* Input Functions */ //************************************* MinimizerRoutines::MinimizerRoutines() { //************************************* Init(); } //************************************* MinimizerRoutines::MinimizerRoutines(int argc, char *argv[]) { //************************************* // Initialise Defaults Init(); nuisconfig configuration = Config::Get(); // Default containers std::string cardfile = ""; std::string maxevents = "-1"; int errorcount = 0; int verbocount = 0; std::vector xmlcmds; std::vector configargs; // Make easier to handle arguments. std::vector args = GeneralUtils::LoadCharToVectStr(argc, argv); ParserUtils::ParseArgument(args, "-c", fCardFile, true); ParserUtils::ParseArgument(args, "-o", fOutputFile, false, false); ParserUtils::ParseArgument(args, "-n", maxevents, false, false); ParserUtils::ParseArgument(args, "-f", fStrategy, false, false); ParserUtils::ParseArgument(args, "-d", fFakeDataInput, false, false); ParserUtils::ParseArgument(args, "-i", xmlcmds); ParserUtils::ParseArgument(args, "-q", configargs); ParserUtils::ParseCounter(args, "e", errorcount); ParserUtils::ParseCounter(args, "v", verbocount); ParserUtils::CheckBadArguments(args); // Add extra defaults if none given if (fCardFile.empty() and xmlcmds.empty()) { - QTHROW("No input supplied!"); + NUIS_ABORT("No input supplied!"); } if (fOutputFile.empty() and !fCardFile.empty()) { fOutputFile = fCardFile + ".root"; - QERROR(WRN, "No output supplied so saving it to: " << fOutputFile); + NUIS_ERR(WRN, "No output supplied so saving it to: " << fOutputFile); } else if (fOutputFile.empty()) { - QTHROW("No output file or cardfile supplied!"); + NUIS_ABORT("No output file or cardfile supplied!"); } // Configuration Setup ============================= // Check no comp key is available nuiskey fCompKey; if (Config::Get().GetNodes("nuiscomp").empty()) { fCompKey = Config::Get().CreateNode("nuiscomp"); } else { fCompKey = Config::Get().GetNodes("nuiscomp")[0]; } if (!fCardFile.empty()) fCompKey.Set("cardfile", fCardFile); if (!fOutputFile.empty()) fCompKey.Set("outputfile", fOutputFile); if (!fStrategy.empty()) fCompKey.Set("strategy", fStrategy); // Load XML Cardfile configuration.LoadSettings(fCompKey.GetS("cardfile"), ""); // Add Config Args for (size_t i = 0; i < configargs.size(); i++) { configuration.OverrideConfig(configargs[i]); } if (maxevents.compare("-1")) { configuration.OverrideConfig("MAXEVENTS=" + maxevents); } // Finish configuration XML configuration.FinaliseSettings(fCompKey.GetS("outputfile") + ".xml"); // Add Error Verbo Lines verbocount += Config::GetParI("VERBOSITY"); errorcount += Config::GetParI("ERROR"); - QLOG(FIT, "[ NUISANCE ]: Setting VERBOSITY=" << verbocount); - QLOG(FIT, "[ NUISANCE ]: Setting ERROR=" << errorcount); + NUIS_LOG(FIT, "[ NUISANCE ]: Setting VERBOSITY=" << verbocount); + NUIS_LOG(FIT, "[ NUISANCE ]: Setting ERROR=" << errorcount); // FitPar::log_verb = verbocount; SETVERBOSITY(verbocount); // ERR_VERB(errorcount); // Minimizer Setup ======================================== fOutputRootFile = new TFile(fCompKey.GetS("outputfile").c_str(), "RECREATE"); SetupMinimizerFromXML(); SetupCovariance(); SetupRWEngine(); SetupFCN(); return; }; //************************************* void MinimizerRoutines::SetupMinimizerFromXML() { //************************************* - QLOG(FIT, "Setting up nuismin"); + NUIS_LOG(FIT, "Setting up nuismin"); // Setup Parameters ------------------------------------------ std::vector parkeys = Config::QueryKeys("parameter"); if (!parkeys.empty()) { - QLOG(FIT, "Number of parameters : " << parkeys.size()); + NUIS_LOG(FIT, "Number of parameters : " << parkeys.size()); } for (size_t i = 0; i < parkeys.size(); i++) { nuiskey key = parkeys.at(i); // Check for type,name,nom if (!key.Has("type")) { - QTHROW("No type given for parameter " << i); + NUIS_ABORT("No type given for parameter " << i); } else if (!key.Has("name")) { - QTHROW("No name given for parameter " << i); + NUIS_ABORT("No name given for parameter " << i); } else if (!key.Has("nominal")) { - QTHROW("No nominal given for parameter " << i); + NUIS_ABORT("No nominal given for parameter " << i); } // Get Inputs std::string partype = key.GetS("type"); std::string parname = key.GetS("name"); double parnom = key.GetD("nominal"); double parlow = parnom - 1; double parhigh = parnom + 1; double parstep = 1; // Override state if none given if (!key.Has("state")) { key.SetS("state", "FIX"); } std::string parstate = key.GetS("state"); // Extra limits if (key.Has("low")) { parlow = key.GetD("low"); parhigh = key.GetD("high"); parstep = key.GetD("step"); - QLOG(FIT, "Read " << partype << " : " << parname << " = " << parnom + NUIS_LOG(FIT, "Read " << partype << " : " << parname << " = " << parnom << " : " << parlow << " < p < " << parhigh << " : " << parstate); } else { - QLOG(FIT, "Read " << partype << " : " << parname << " = " << parnom + NUIS_LOG(FIT, "Read " << partype << " : " << parname << " = " << parnom << " : " << parstate); } // Run Parameter Conversion if needed if (parstate.find("ABS") != std::string::npos) { double opnom = parnom; double oparstep = parstep; parnom = FitBase::RWAbsToSigma(partype, parname, parnom); parlow = FitBase::RWAbsToSigma(partype, parname, parlow); parhigh = FitBase::RWAbsToSigma(partype, parname, parhigh); parstep = FitBase::RWAbsToSigma(partype, parname, opnom + parstep) - parnom; - QLOG(FIT, "ParStep: " << parstep << " (" << oparstep << ")."); + NUIS_LOG(FIT, "ParStep: " << parstep << " (" << oparstep << ")."); } else if (parstate.find("FRAC") != std::string::npos) { parnom = FitBase::RWFracToSigma(partype, parname, parnom); parlow = FitBase::RWFracToSigma(partype, parname, parlow); parhigh = FitBase::RWFracToSigma(partype, parname, parhigh); parstep = FitBase::RWFracToSigma(partype, parname, parstep); } // Push into vectors fParams.push_back(parname); fTypeVals[parname] = FitBase::ConvDialType(partype); fStartVals[parname] = parnom; fCurVals[parname] = parnom; fErrorVals[parname] = 0.0; fStateVals[parname] = parstate; bool fixstate = parstate.find("FIX") != std::string::npos; fFixVals[parname] = fixstate; fStartFixVals[parname] = fFixVals[parname]; fMinVals[parname] = parlow; fMaxVals[parname] = parhigh; fStepVals[parname] = parstep; } // Setup Samples ---------------------------------------------- std::vector samplekeys = Config::QueryKeys("sample"); if (!samplekeys.empty()) { - QLOG(FIT, "Number of samples : " << samplekeys.size()); + NUIS_LOG(FIT, "Number of samples : " << samplekeys.size()); } for (size_t i = 0; i < samplekeys.size(); i++) { nuiskey key = samplekeys.at(i); // Get Sample Options std::string samplename = key.GetS("name"); std::string samplefile = key.GetS("input"); std::string sampletype = key.Has("type") ? key.GetS("type") : "DEFAULT"; double samplenorm = key.Has("norm") ? key.GetD("norm") : 1.0; // Print out - QLOG(FIT, "Read sample info " << i << " : " << samplename << std::endl + NUIS_LOG(FIT, "Read sample info " << i << " : " << samplename << std::endl << "\t\t input -> " << samplefile << std::endl << "\t\t state -> " << sampletype << std::endl << "\t\t norm -> " << samplenorm); // If FREE add to parameters otherwise continue if (sampletype.find("FREE") == std::string::npos) { if (samplenorm != 1.0) { - QERROR(FTL, "You provided a sample normalisation but did not specify " + NUIS_ERR(FTL, "You provided a sample normalisation but did not specify " "that the sample is free"); - QTHROW("Change so sample contains type=\"FREE\" and re-run"); + NUIS_ABORT("Change so sample contains type=\"FREE\" and re-run"); } continue; } // Form norm dial from samplename + sampletype + "_norm"; std::string normname = samplename + "_norm"; // Check normname not already present if (fTypeVals.find(normname) != fTypeVals.end()) { continue; } // Add new norm dial to list if its passed above checks fParams.push_back(normname); fTypeVals[normname] = kNORM; fStateVals[normname] = sampletype; fStartVals[normname] = samplenorm; fCurVals[normname] = samplenorm; fErrorVals[normname] = 0.0; fMinVals[normname] = 0.1; fMaxVals[normname] = 10.0; fStepVals[normname] = 0.5; bool state = sampletype.find("FREE") == std::string::npos; fFixVals[normname] = state; fStartFixVals[normname] = state; } // Setup Fake Parameters ----------------------------- std::vector fakekeys = Config::QueryKeys("fakeparameter"); if (!fakekeys.empty()) { - QLOG(FIT, "Number of fake parameters : " << fakekeys.size()); + NUIS_LOG(FIT, "Number of fake parameters : " << fakekeys.size()); } for (size_t i = 0; i < fakekeys.size(); i++) { nuiskey key = fakekeys.at(i); // Check for type,name,nom if (!key.Has("name")) { - QTHROW("No name given for fakeparameter " << i); + NUIS_ABORT("No name given for fakeparameter " << i); } else if (!key.Has("nom")) { - QTHROW("No nominal given for fakeparameter " << i); + NUIS_ABORT("No nominal given for fakeparameter " << i); } // Get Inputs std::string parname = key.GetS("name"); double parnom = key.GetD("nom"); // Push into vectors fFakeVals[parname] = parnom; } } /* Setup Functions */ //************************************* void MinimizerRoutines::SetupRWEngine() { //************************************* for (UInt_t i = 0; i < fParams.size(); i++) { std::string name = fParams[i]; FitBase::GetRW()->IncludeDial(name, fTypeVals.at(name)); } UpdateRWEngine(fStartVals); return; } //************************************* void MinimizerRoutines::SetupFCN() { //************************************* - QLOG(FIT, "Making the jointFCN"); + NUIS_LOG(FIT, "Making the jointFCN"); if (fSampleFCN) delete fSampleFCN; // fSampleFCN = new JointFCN(fCardFile, fOutputRootFile); fSampleFCN = new JointFCN(fOutputRootFile); SetFakeData(); fMinimizerFCN = new MinimizerFCN(fSampleFCN); fCallFunctor = new ROOT::Math::Functor(*fMinimizerFCN, fParams.size()); fSampleFCN->CreateIterationTree("fit_iterations", FitBase::GetRW()); return; } //****************************************** void MinimizerRoutines::SetupFitter(std::string routine) { //****************************************** // Make the fitter std::string fitclass = ""; std::string fittype = ""; bool UseMCMC = false; // Get correct types if (!routine.compare("Migrad")) { fitclass = "Minuit2"; fittype = "Migrad"; } else if (!routine.compare("Simplex")) { fitclass = "Minuit2"; fittype = "Simplex"; } else if (!routine.compare("Combined")) { fitclass = "Minuit2"; fittype = "Combined"; } else if (!routine.compare("Brute")) { fitclass = "Minuit2"; fittype = "Scan"; } else if (!routine.compare("Fumili")) { fitclass = "Minuit2"; fittype = "Fumili"; } else if (!routine.compare("ConjugateFR")) { fitclass = "GSLMultiMin"; fittype = "ConjugateFR"; } else if (!routine.compare("ConjugatePR")) { fitclass = "GSLMultiMin"; fittype = "ConjugatePR"; } else if (!routine.compare("BFGS")) { fitclass = "GSLMultiMin"; fittype = "BFGS"; } else if (!routine.compare("BFGS2")) { fitclass = "GSLMultiMin"; fittype = "BFGS2"; } else if (!routine.compare("SteepDesc")) { fitclass = "GSLMultiMin"; fittype = "SteepestDescent"; // } else if (!routine.compare("GSLMulti")) { fitclass = "GSLMultiFit"; // fittype = ""; // Doesn't work out of the box } else if (!routine.compare("GSLSimAn")) { fitclass = "GSLSimAn"; fittype = ""; } else if (!routine.compare("MCMC")) { UseMCMC = true; } // make minimizer if (fMinimizer) delete fMinimizer; if (UseMCMC) { fMinimizer = new Simple_MH_Sampler(); } else { fMinimizer = ROOT::Math::Factory::CreateMinimizer(fitclass, fittype); } fMinimizer->SetMaxFunctionCalls(FitPar::Config().GetParI("MAXCALLS")); if (!routine.compare("Brute")) { fMinimizer->SetMaxFunctionCalls(fParams.size() * fParams.size() * 4); fMinimizer->SetMaxIterations(fParams.size() * fParams.size() * 4); } fMinimizer->SetMaxIterations(FitPar::Config().GetParI("MAXITERATIONS")); fMinimizer->SetTolerance(FitPar::Config().GetParD("TOLERANCE")); fMinimizer->SetStrategy(FitPar::Config().GetParI("STRATEGY")); fMinimizer->SetFunction(*fCallFunctor); int ipar = 0; // Add Fit Parameters for (UInt_t i = 0; i < fParams.size(); i++) { std::string syst = fParams.at(i); bool fixed = true; double vstart, vstep, vlow, vhigh; vstart = vstep = vlow = vhigh = 0.0; if (fCurVals.find(syst) != fCurVals.end()) vstart = fCurVals.at(syst); if (fMinVals.find(syst) != fMinVals.end()) vlow = fMinVals.at(syst); if (fMaxVals.find(syst) != fMaxVals.end()) vhigh = fMaxVals.at(syst); if (fStepVals.find(syst) != fStepVals.end()) vstep = fStepVals.at(syst); if (fFixVals.find(syst) != fFixVals.end()) fixed = fFixVals.at(syst); // fix for errors if (vhigh == vlow) vhigh += 1.0; fMinimizer->SetVariable(ipar, syst, vstart, vstep); fMinimizer->SetVariableLimits(ipar, vlow, vhigh); if (fixed) { fMinimizer->FixVariable(ipar); - QLOG(FIT, "Fixed Param: " << syst); + NUIS_LOG(FIT, "Fixed Param: " << syst); } else { - QLOG(FIT, "Free Param: " << syst << " Start:" << vstart + NUIS_LOG(FIT, "Free Param: " << syst << " Start:" << vstart << " Range:" << vlow << " to " << vhigh << " Step:" << vstep); } ipar++; } - QLOG(FIT, "Setup Minimizer: " << fMinimizer->NDim() << "(NDim) " + NUIS_LOG(FIT, "Setup Minimizer: " << fMinimizer->NDim() << "(NDim) " << fMinimizer->NFree() << "(NFree)"); return; } //************************************* // Set fake data from user input void MinimizerRoutines::SetFakeData() { //************************************* // If the fake data input field (-d) isn't provided, return to caller if (fFakeDataInput.empty()) return; // If user specifies -d MC we set the data to the MC // User can also specify fake data parameters to reweight by doing // "fake_parameter" in input card file // "fake_parameter" gets read in ReadCard function (reads to fFakeVals) if (fFakeDataInput.compare("MC") == 0) { - QLOG(FIT, "Setting fake data from MC starting prediction."); + NUIS_LOG(FIT, "Setting fake data from MC starting prediction."); // fFakeVals get read in in ReadCard UpdateRWEngine(fFakeVals); // Reconfigure the reweight engine FitBase::GetRW()->Reconfigure(); // Reconfigure all the samples to the new reweight fSampleFCN->ReconfigureAllEvents(); // Feed on and set the fake-data in each measurement class fSampleFCN->SetFakeData("MC"); // Changed the reweight engine values back to the current values // So we start the fit at a different value than what we set the fake-data // to UpdateRWEngine(fCurVals); - QLOG(FIT, "Set all data to fake MC predictions."); + NUIS_LOG(FIT, "Set all data to fake MC predictions."); } else { fSampleFCN->SetFakeData(fFakeDataInput); } return; } /* Fitting Functions */ //************************************* void MinimizerRoutines::UpdateRWEngine( std::map &updateVals) { //************************************* for (UInt_t i = 0; i < fParams.size(); i++) { std::string name = fParams[i]; if (updateVals.find(name) == updateVals.end()) continue; FitBase::GetRW()->SetDialValue(name, updateVals.at(name)); } FitBase::GetRW()->Reconfigure(); return; } //************************************* void MinimizerRoutines::Run() { //************************************* - QLOG(FIT, "Running MinimizerRoutines : " << fStrategy); + NUIS_LOG(FIT, "Running MinimizerRoutines : " << fStrategy); if (FitPar::Config().GetParB("save_nominal")) { SaveNominal(); } // Parse given routines fRoutines = GeneralUtils::ParseToStr(fStrategy, ","); if (fRoutines.empty()) { - QTHROW("Trying to run MinimizerRoutines with no routines given!"); + NUIS_ABORT("Trying to run MinimizerRoutines with no routines given!"); } for (UInt_t i = 0; i < fRoutines.size(); i++) { std::string routine = fRoutines.at(i); int fitstate = kFitUnfinished; - QLOG(FIT, "Running Routine: " << routine); + NUIS_LOG(FIT, "Running Routine: " << routine); // Try Routines if (routine.find("LowStat") != std::string::npos) LowStatRoutine(routine); else if (routine == "FixAtLim") FixAtLimit(); else if (routine == "FixAtLimBreak") fitstate = FixAtLimit(); else if (routine.find("ErrorBands") != std::string::npos) GenerateErrorBands(); else if (routine.find("DataToys") != std::string::npos) ThrowDataToys(); else if (!routine.compare("Chi2Scan1D")) Create1DScans(); else if (!routine.compare("Chi2Scan2D")) Chi2Scan2D(); else fitstate = RunFitRoutine(routine); // If ending early break here if (fitstate == kFitFinished || fitstate == kNoChange) { - QLOG(FIT, "Ending fit routines loop."); + NUIS_LOG(FIT, "Ending fit routines loop."); break; } } return; } //************************************* int MinimizerRoutines::RunFitRoutine(std::string routine) { //************************************* int endfits = kFitUnfinished; // set fitter at the current start values fOutputRootFile->cd(); SetupFitter(routine); // choose what to do with the minimizer depending on routine. if (!routine.compare("Migrad") or !routine.compare("Simplex") or !routine.compare("Combined") or !routine.compare("Brute") or !routine.compare("Fumili") or !routine.compare("ConjugateFR") or !routine.compare("ConjugatePR") or !routine.compare("BFGS") or !routine.compare("BFGS2") or !routine.compare("SteepDesc") or // !routine.compare("GSLMulti") or !routine.compare("GSLSimAn") or !routine.compare("MCMC")) { if (fMinimizer->NFree() > 0) { - QLOG(FIT, fMinimizer->Minimize()); + NUIS_LOG(FIT, fMinimizer->Minimize()); GetMinimizerState(); } } // other otptions else if (!routine.compare("Contour")) { CreateContours(); } return endfits; } //************************************* void MinimizerRoutines::PrintState() { //************************************* - QLOG(FIT, "------------"); + NUIS_LOG(FIT, "------------"); // Count max size int maxcount = 0; for (UInt_t i = 0; i < fParams.size(); i++) { maxcount = max(int(fParams[i].size()), maxcount); } // Header - QLOG(FIT, " # " << left << setw(maxcount) << "Parameter " + NUIS_LOG(FIT, " # " << left << setw(maxcount) << "Parameter " << " = " << setw(10) << "Value" << " +- " << setw(10) << "Error" << " " << setw(8) << "(Units)" << " " << setw(10) << "Conv. Val" << " +- " << setw(10) << "Conv. Err" << " " << setw(8) << "(Units)"); // Parameters for (UInt_t i = 0; i < fParams.size(); i++) { std::string syst = fParams.at(i); std::string typestr = FitBase::ConvDialType(fTypeVals[syst]); std::string curunits = "(sig.)"; double curval = fCurVals[syst]; double curerr = fErrorVals[syst]; if (fStateVals[syst].find("ABS") != std::string::npos) { curval = FitBase::RWSigmaToAbs(typestr, syst, curval); curerr = (FitBase::RWSigmaToAbs(typestr, syst, curerr) - FitBase::RWSigmaToAbs(typestr, syst, 0.0)); curunits = "(Abs.)"; } else if (fStateVals[syst].find("FRAC") != std::string::npos) { curval = FitBase::RWSigmaToFrac(typestr, syst, curval); curerr = (FitBase::RWSigmaToFrac(typestr, syst, curerr) - FitBase::RWSigmaToFrac(typestr, syst, 0.0)); curunits = "(Frac)"; } std::string convunits = "(" + FitBase::GetRWUnits(typestr, syst) + ")"; double convval = FitBase::RWSigmaToAbs(typestr, syst, curval); double converr = (FitBase::RWSigmaToAbs(typestr, syst, curerr) - FitBase::RWSigmaToAbs(typestr, syst, 0.0)); std::ostringstream curparstring; curparstring << " " << setw(3) << left << i << ". " << setw(maxcount) << syst << " = " << setw(10) << curval << " +- " << setw(10) << curerr << " " << setw(8) << curunits << " " << setw(10) << convval << " +- " << setw(10) << converr << " " << setw(8) << convunits; - QLOG(FIT, curparstring.str()); + NUIS_LOG(FIT, curparstring.str()); } - QLOG(FIT, "------------"); + NUIS_LOG(FIT, "------------"); double like = fSampleFCN->GetLikelihood(); - QLOG(FIT, std::left << std::setw(46) << "Likelihood for JointFCN: " << like); - QLOG(FIT, "------------"); + NUIS_LOG(FIT, std::left << std::setw(46) << "Likelihood for JointFCN: " << like); + NUIS_LOG(FIT, "------------"); } //************************************* void MinimizerRoutines::GetMinimizerState() { //************************************* - QLOG(FIT, "Minimizer State: "); + NUIS_LOG(FIT, "Minimizer State: "); // Get X and Err const double *values = fMinimizer->X(); const double *errors = fMinimizer->Errors(); // int ipar = 0; for (UInt_t i = 0; i < fParams.size(); i++) { std::string syst = fParams.at(i); fCurVals[syst] = values[i]; fErrorVals[syst] = errors[i]; } PrintState(); // Covar SetupCovariance(); if (fMinimizer->CovMatrixStatus() > 0) { // Fill Full Covar - QLOG(FIT, "Filling covariance"); + NUIS_LOG(FIT, "Filling covariance"); for (int i = 0; i < fCovar->GetNbinsX(); i++) { for (int j = 0; j < fCovar->GetNbinsY(); j++) { fCovar->SetBinContent(i + 1, j + 1, fMinimizer->CovMatrix(i, j)); } } int freex = 0; int freey = 0; for (int i = 0; i < fCovar->GetNbinsX(); i++) { if (fMinimizer->IsFixedVariable(i)) continue; freey = 0; for (int j = 0; j < fCovar->GetNbinsY(); j++) { if (fMinimizer->IsFixedVariable(j)) continue; fCovFree->SetBinContent(freex + 1, freey + 1, fMinimizer->CovMatrix(i, j)); freey++; } freex++; } fCorrel = PlotUtils::GetCorrelationPlot(fCovar, "correlation"); fDecomp = PlotUtils::GetDecompPlot(fCovar, "decomposition"); if (fMinimizer->NFree() > 0) { fCorFree = PlotUtils::GetCorrelationPlot(fCovFree, "correlation_free"); fDecFree = PlotUtils::GetDecompPlot(fCovFree, "decomposition_free"); } } return; }; //************************************* void MinimizerRoutines::LowStatRoutine(std::string routine) { //************************************* - QLOG(FIT, "Running Low Statistics Routine: " << routine); + NUIS_LOG(FIT, "Running Low Statistics Routine: " << routine); int lowstatsevents = FitPar::Config().GetParI("LOWSTATEVENTS"); int maxevents = FitPar::Config().GetParI("MAXEVENTS"); int verbosity = FitPar::Config().GetParI("VERBOSITY"); std::string trueroutine = routine; std::string substring = "LowStat"; trueroutine.erase(trueroutine.find(substring), substring.length()); // Set MAX EVENTS=1000 Config::SetPar("MAXEVENTS", lowstatsevents); Config::SetPar("VERBOSITY", 3); SetupFCN(); RunFitRoutine(trueroutine); Config::SetPar("MAXEVENTS", maxevents); SetupFCN(); Config::SetPar("VERBOSITY", verbosity); return; } //************************************* void MinimizerRoutines::Create1DScans() { //************************************* // 1D Scan Routine // Steps through all free parameters about nominal using the step size // Creates a graph for each free parameter // At the current point create a 1D Scan for all parametes (Uncorrelated) for (UInt_t i = 0; i < fParams.size(); i++) { if (fFixVals[fParams[i]]) continue; - QLOG(FIT, "Running 1D Scan for " << fParams[i]); + NUIS_LOG(FIT, "Running 1D Scan for " << fParams[i]); fSampleFCN->CreateIterationTree(fParams[i] + "_scan1D_iterations", FitBase::GetRW()); double scanmiddlepoint = fCurVals[fParams[i]]; // Determine N points needed double limlow = fMinVals[fParams[i]]; double limhigh = fMaxVals[fParams[i]]; double step = fStepVals[fParams[i]]; int npoints = int(fabs(limhigh - limlow) / (step + 0.)); TH1D *contour = new TH1D(("Chi2Scan1D_" + fParams[i]).c_str(), ("Chi2Scan1D_" + fParams[i] + ";" + fParams[i]).c_str(), npoints, limlow, limhigh); // Fill bins for (int x = 0; x < contour->GetNbinsX(); x++) { // Set X Val fCurVals[fParams[i]] = contour->GetXaxis()->GetBinCenter(x + 1); // Run Eval double *vals = FitUtils::GetArrayFromMap(fParams, fCurVals); double chi2 = fSampleFCN->DoEval(vals); delete vals; // Fill Contour contour->SetBinContent(x + 1, chi2); } // Save contour contour->Write(); // Reset Parameter fCurVals[fParams[i]] = scanmiddlepoint; // Save TTree fSampleFCN->WriteIterationTree(); } return; } //************************************* void MinimizerRoutines::Chi2Scan2D() { //************************************* // Chi2 Scan 2D // Creates a 2D chi2 scan by stepping through all free parameters // Works for all pairwise combos of free parameters // Scan I for (UInt_t i = 0; i < fParams.size(); i++) { if (fFixVals[fParams[i]]) continue; // Scan J for (UInt_t j = 0; j < i; j++) { if (fFixVals[fParams[j]]) continue; fSampleFCN->CreateIterationTree(fParams[i] + "_" + fParams[j] + "_" + "scan2D_iterations", FitBase::GetRW()); double scanmid_i = fCurVals[fParams[i]]; double scanmid_j = fCurVals[fParams[j]]; double limlow_i = fMinVals[fParams[i]]; double limhigh_i = fMaxVals[fParams[i]]; double step_i = fStepVals[fParams[i]]; double limlow_j = fMinVals[fParams[j]]; double limhigh_j = fMaxVals[fParams[j]]; double step_j = fStepVals[fParams[j]]; int npoints_i = int(fabs(limhigh_i - limlow_i) / (step_i + 0.)) + 1; int npoints_j = int(fabs(limhigh_j - limlow_j) / (step_j + 0.)) + 1; TH2D *contour = new TH2D( ("Chi2Scan2D_" + fParams[i] + "_" + fParams[j]).c_str(), ("Chi2Scan2D_" + fParams[i] + "_" + fParams[j] + ";" + fParams[i] + ";" + fParams[j]) .c_str(), npoints_i, limlow_i, limhigh_i, npoints_j, limlow_j, limhigh_j); // Begin Scan - QLOG(FIT, "Running scan for " << fParams[i] << " " << fParams[j]); + NUIS_LOG(FIT, "Running scan for " << fParams[i] << " " << fParams[j]); // Fill bins for (int x = 0; x < contour->GetNbinsX(); x++) { // Set X Val fCurVals[fParams[i]] = contour->GetXaxis()->GetBinCenter(x + 1); // Loop Y for (int y = 0; y < contour->GetNbinsY(); y++) { // Set Y Val fCurVals[fParams[j]] = contour->GetYaxis()->GetBinCenter(y + 1); // Run Eval double *vals = FitUtils::GetArrayFromMap(fParams, fCurVals); double chi2 = fSampleFCN->DoEval(vals); delete vals; // Fill Contour contour->SetBinContent(x + 1, y + 1, chi2); fCurVals[fParams[j]] = scanmid_j; } fCurVals[fParams[i]] = scanmid_i; fCurVals[fParams[j]] = scanmid_j; } // Save contour contour->Write(); // Save Iterations fSampleFCN->WriteIterationTree(); } } return; } //************************************* void MinimizerRoutines::CreateContours() { //************************************* // Use MINUIT for this if possible - QTHROW("Contours not yet implemented as it is really slow!"); + NUIS_ABORT("Contours not yet implemented as it is really slow!"); return; } //************************************* int MinimizerRoutines::FixAtLimit() { //************************************* bool fixedparam = false; for (UInt_t i = 0; i < fParams.size(); i++) { std::string syst = fParams.at(i); if (fFixVals[syst]) continue; double curVal = fCurVals.at(syst); double minVal = fMinVals.at(syst); double maxVal = fMinVals.at(syst); if (fabs(curVal - minVal) < 0.0001) { fCurVals[syst] = minVal; fFixVals[syst] = true; fixedparam = true; } if (fabs(maxVal - curVal) < 0.0001) { fCurVals[syst] = maxVal; fFixVals[syst] = true; fixedparam = true; } } if (!fixedparam) { - QLOG(FIT, "No dials needed fixing!"); + NUIS_LOG(FIT, "No dials needed fixing!"); return kNoChange; } else return kStateChange; } /* Write Functions */ //************************************* void MinimizerRoutines::SaveResults() { //************************************* fOutputRootFile->cd(); if (fMinimizer) { SetupCovariance(); SaveMinimizerState(); } SaveCurrentState(); } //************************************* void MinimizerRoutines::SaveMinimizerState() { //************************************* - QLOG(FIT, "Saving Minimizer State"); + NUIS_LOG(FIT, "Saving Minimizer State"); if (!fMinimizer) { - QTHROW("Can't save minimizer state without min object"); + NUIS_ABORT("Can't save minimizer state without min object"); } // Save main fit tree fSampleFCN->WriteIterationTree(); // Get Vals and Errors GetMinimizerState(); // Save tree with fit status std::vector nameVect; std::vector valVect; std::vector errVect; std::vector minVect; std::vector maxVect; std::vector startVect; std::vector endfixVect; std::vector startfixVect; // int NFREEPARS = fMinimizer->NFree(); int NPARS = fMinimizer->NDim(); int ipar = 0; // Dial Vals for (UInt_t i = 0; i < fParams.size(); i++) { std::string name = fParams.at(i); nameVect.push_back(name); valVect.push_back(fCurVals.at(name)); errVect.push_back(fErrorVals.at(name)); minVect.push_back(fMinVals.at(name)); maxVect.push_back(fMaxVals.at(name)); startVect.push_back(fStartVals.at(name)); endfixVect.push_back(fFixVals.at(name)); startfixVect.push_back(fStartFixVals.at(name)); ipar++; } int NFREE = fMinimizer->NFree(); int NDIM = fMinimizer->NDim(); double CHI2 = fSampleFCN->GetLikelihood(); int NBINS = fSampleFCN->GetNDOF(); int NDOF = NBINS - NFREE; // Write fit results TTree *fit_tree = new TTree("fit_result", "fit_result"); fit_tree->Branch("parameter_names", &nameVect); fit_tree->Branch("parameter_values", &valVect); fit_tree->Branch("parameter_errors", &errVect); fit_tree->Branch("parameter_min", &minVect); fit_tree->Branch("parameter_max", &maxVect); fit_tree->Branch("parameter_start", &startVect); fit_tree->Branch("parameter_fix", &endfixVect); fit_tree->Branch("parameter_startfix", &startfixVect); fit_tree->Branch("CHI2", &CHI2, "CHI2/D"); fit_tree->Branch("NDOF", &NDOF, "NDOF/I"); fit_tree->Branch("NBINS", &NBINS, "NBINS/I"); fit_tree->Branch("NDIM", &NDIM, "NDIM/I"); fit_tree->Branch("NFREE", &NFREE, "NFREE/I"); fit_tree->Fill(); fit_tree->Write(); // Make dial variables TH1D dialvar = TH1D("fit_dials", "fit_dials", NPARS, 0, NPARS); TH1D startvar = TH1D("start_dials", "start_dials", NPARS, 0, NPARS); TH1D minvar = TH1D("min_dials", "min_dials", NPARS, 0, NPARS); TH1D maxvar = TH1D("max_dials", "max_dials", NPARS, 0, NPARS); TH1D dialvarfree = TH1D("fit_dials_free", "fit_dials_free", NFREE, 0, NFREE); TH1D startvarfree = TH1D("start_dials_free", "start_dials_free", NFREE, 0, NFREE); TH1D minvarfree = TH1D("min_dials_free", "min_dials_free", NFREE, 0, NFREE); TH1D maxvarfree = TH1D("max_dials_free", "max_dials_free", NFREE, 0, NFREE); int freecount = 0; for (UInt_t i = 0; i < nameVect.size(); i++) { std::string name = nameVect.at(i); dialvar.SetBinContent(i + 1, valVect.at(i)); dialvar.SetBinError(i + 1, errVect.at(i)); dialvar.GetXaxis()->SetBinLabel(i + 1, name.c_str()); startvar.SetBinContent(i + 1, startVect.at(i)); startvar.GetXaxis()->SetBinLabel(i + 1, name.c_str()); minvar.SetBinContent(i + 1, minVect.at(i)); minvar.GetXaxis()->SetBinLabel(i + 1, name.c_str()); maxvar.SetBinContent(i + 1, maxVect.at(i)); maxvar.GetXaxis()->SetBinLabel(i + 1, name.c_str()); if (NFREE > 0) { if (!startfixVect.at(i)) { freecount++; dialvarfree.SetBinContent(freecount, valVect.at(i)); dialvarfree.SetBinError(freecount, errVect.at(i)); dialvarfree.GetXaxis()->SetBinLabel(freecount, name.c_str()); startvarfree.SetBinContent(freecount, startVect.at(i)); startvarfree.GetXaxis()->SetBinLabel(freecount, name.c_str()); minvarfree.SetBinContent(freecount, minVect.at(i)); minvarfree.GetXaxis()->SetBinLabel(freecount, name.c_str()); maxvarfree.SetBinContent(freecount, maxVect.at(i)); maxvarfree.GetXaxis()->SetBinLabel(freecount, name.c_str()); } } } // Save Dial Plots dialvar.Write(); startvar.Write(); minvar.Write(); maxvar.Write(); if (NFREE > 0) { dialvarfree.Write(); startvarfree.Write(); minvarfree.Write(); maxvarfree.Write(); } // Save fit_status plot TH1D statusplot = TH1D("fit_status", "fit_status", 8, 0, 8); std::string fit_labels[8] = {"status", "cov_status", "maxiter", "maxfunc", "iter", "func", "precision", "tolerance"}; double fit_vals[8]; fit_vals[0] = fMinimizer->Status() + 0.; fit_vals[1] = fMinimizer->CovMatrixStatus() + 0.; fit_vals[2] = fMinimizer->MaxIterations() + 0.; fit_vals[3] = fMinimizer->MaxFunctionCalls() + 0.; fit_vals[4] = fMinimizer->NIterations() + 0.; fit_vals[5] = fMinimizer->NCalls() + 0.; fit_vals[6] = fMinimizer->Precision() + 0.; fit_vals[7] = fMinimizer->Tolerance() + 0.; for (int i = 0; i < 8; i++) { statusplot.SetBinContent(i + 1, fit_vals[i]); statusplot.GetXaxis()->SetBinLabel(i + 1, fit_labels[i].c_str()); } statusplot.Write(); // Save Covars if (fCovar) fCovar->Write(); if (fCovFree) fCovFree->Write(); if (fCorrel) fCorrel->Write(); if (fCorFree) fCorFree->Write(); if (fDecomp) fDecomp->Write(); if (fDecFree) fDecFree->Write(); return; } //************************************* void MinimizerRoutines::SaveCurrentState(std::string subdir) { //************************************* - QLOG(FIT, "Saving current full FCN predictions"); + NUIS_LOG(FIT, "Saving current full FCN predictions"); // Setup DIRS TDirectory *curdir = gDirectory; if (!subdir.empty()) { TDirectory *newdir = (TDirectory *)gDirectory->mkdir(subdir.c_str()); newdir->cd(); } FitBase::GetRW()->Reconfigure(); fSampleFCN->ReconfigureAllEvents(); fSampleFCN->Write(); // Change back to current DIR curdir->cd(); return; } //************************************* void MinimizerRoutines::SaveNominal() { //************************************* fOutputRootFile->cd(); - QLOG(FIT, "Saving Nominal Predictions (be cautious with this)"); + NUIS_LOG(FIT, "Saving Nominal Predictions (be cautious with this)"); FitBase::GetRW()->Reconfigure(); SaveCurrentState("nominal"); }; //************************************* void MinimizerRoutines::SavePrefit() { //************************************* fOutputRootFile->cd(); - QLOG(FIT, "Saving Prefit Predictions"); + NUIS_LOG(FIT, "Saving Prefit Predictions"); UpdateRWEngine(fStartVals); SaveCurrentState("prefit"); UpdateRWEngine(fCurVals); }; /* MISC Functions */ //************************************* int MinimizerRoutines::GetStatus() { //************************************* return 0; } //************************************* void MinimizerRoutines::SetupCovariance() { //************************************* // Remove covares if they exist if (fCovar) delete fCovar; if (fCovFree) delete fCovFree; if (fCorrel) delete fCorrel; if (fCorFree) delete fCorFree; if (fDecomp) delete fDecomp; if (fDecFree) delete fDecFree; - QLOG(FIT, "Building covariance matrix.."); + NUIS_LOG(FIT, "Building covariance matrix.."); int NFREE = 0; int NDIM = 0; // Get NFREE from min or from vals (for cases when doing throws) if (fMinimizer) { NFREE = fMinimizer->NFree(); NDIM = fMinimizer->NDim(); } else { NDIM = fParams.size(); for (UInt_t i = 0; i < fParams.size(); i++) { - QLOG(FIT, "Getting Param " << fParams[i]); + NUIS_LOG(FIT, "Getting Param " << fParams[i]); if (!fFixVals[fParams[i]]) NFREE++; } } if (NDIM == 0) return; - QLOG(FIT, "NFREE == " << NFREE); + NUIS_LOG(FIT, "NFREE == " << NFREE); fCovar = new TH2D("covariance", "covariance", NDIM, 0, NDIM, NDIM, 0, NDIM); if (NFREE > 0) { fCovFree = new TH2D("covariance_free", "covariance_free", NFREE, 0, NFREE, NFREE, 0, NFREE); } else { fCovFree = NULL; } // Set Bin Labels int countall = 0; int countfree = 0; for (UInt_t i = 0; i < fParams.size(); i++) { fCovar->GetXaxis()->SetBinLabel(countall + 1, fParams[i].c_str()); fCovar->GetYaxis()->SetBinLabel(countall + 1, fParams[i].c_str()); countall++; if (!fFixVals[fParams[i]] and NFREE > 0) { fCovFree->GetXaxis()->SetBinLabel(countfree + 1, fParams[i].c_str()); fCovFree->GetYaxis()->SetBinLabel(countfree + 1, fParams[i].c_str()); countfree++; } } fCorrel = PlotUtils::GetCorrelationPlot(fCovar, "correlation"); fDecomp = PlotUtils::GetDecompPlot(fCovar, "decomposition"); if (NFREE > 0) { fCorFree = PlotUtils::GetCorrelationPlot(fCovFree, "correlation_free"); fDecFree = PlotUtils::GetDecompPlot(fCovFree, "decomposition_free"); } else { fCorFree = NULL; fDecFree = NULL; } return; }; //************************************* void MinimizerRoutines::ThrowCovariance(bool uniformly) { //************************************* std::vector rands; if (!fDecFree) { - QERROR(WRN, "Trying to throw 0 free parameters"); + NUIS_ERR(WRN, "Trying to throw 0 free parameters"); return; } // Generate Random Gaussians for (Int_t i = 0; i < fDecFree->GetNbinsX(); i++) { rands.push_back(gRandom->Gaus(0.0, 1.0)); } // Reset Thrown Values for (UInt_t i = 0; i < fParams.size(); i++) { fThrownVals[fParams[i]] = fCurVals[fParams[i]]; } // Loop and get decomp for (Int_t i = 0; i < fDecFree->GetNbinsX(); i++) { std::string parname = std::string(fDecFree->GetXaxis()->GetBinLabel(i + 1)); double mod = 0.0; if (!uniformly) { for (Int_t j = 0; j < fDecFree->GetNbinsY(); j++) { mod += rands[j] * fDecFree->GetBinContent(j + 1, i + 1); } } if (fCurVals.find(parname) != fCurVals.end()) { if (uniformly) fThrownVals[parname] = gRandom->Uniform(fMinVals[parname], fMaxVals[parname]); else { fThrownVals[parname] = fCurVals[parname] + mod; } } } // Check Limits for (UInt_t i = 0; i < fParams.size(); i++) { std::string syst = fParams[i]; if (fFixVals[syst]) continue; if (fThrownVals[syst] < fMinVals[syst]) fThrownVals[syst] = fMinVals[syst]; if (fThrownVals[syst] > fMaxVals[syst]) fThrownVals[syst] = fMaxVals[syst]; } return; }; //************************************* void MinimizerRoutines::GenerateErrorBands() { //************************************* TDirectory *errorDIR = (TDirectory *)fOutputRootFile->mkdir("error_bands"); errorDIR->cd(); // Make a second file to store throws std::string tempFileName = fOutputFile; if (tempFileName.find(".root") != std::string::npos) tempFileName.erase(tempFileName.find(".root"), 5); tempFileName += ".throws.root"; TFile *tempfile = new TFile(tempFileName.c_str(), "RECREATE"); tempfile->cd(); int nthrows = FitPar::Config().GetParI("error_throws"); UpdateRWEngine(fCurVals); fSampleFCN->ReconfigureAllEvents(); TDirectory *nominal = (TDirectory *)tempfile->mkdir("nominal"); nominal->cd(); fSampleFCN->Write(); TDirectory *outnominal = (TDirectory *)fOutputRootFile->mkdir("nominal_throw"); outnominal->cd(); fSampleFCN->Write(); errorDIR->cd(); TTree *parameterTree = new TTree("throws", "throws"); double chi2; for (UInt_t i = 0; i < fParams.size(); i++) parameterTree->Branch(fParams[i].c_str(), &fThrownVals[fParams[i]], (fParams[i] + "/D").c_str()); parameterTree->Branch("chi2", &chi2, "chi2/D"); bool uniformly = FitPar::Config().GetParB("error_uniform"); // Run Throws and save for (Int_t i = 0; i < nthrows; i++) { TDirectory *throwfolder = (TDirectory *)tempfile->mkdir(Form("throw_%i", i)); throwfolder->cd(); // Generate Random Parameter Throw ThrowCovariance(uniformly); // Run Eval double *vals = FitUtils::GetArrayFromMap(fParams, fThrownVals); chi2 = fSampleFCN->DoEval(vals); delete vals; // Save the FCN fSampleFCN->Write(); parameterTree->Fill(); } errorDIR->cd(); fDecFree->Write(); fCovFree->Write(); parameterTree->Write(); delete parameterTree; // Now go through the keys in the temporary file and look for TH1D, and TH2D // plots TIter next(nominal->GetListOfKeys()); TKey *key; while ((key = (TKey *)next())) { TClass *cl = gROOT->GetClass(key->GetClassName()); if (!cl->InheritsFrom("TH1D") and !cl->InheritsFrom("TH2D")) continue; TH1D *baseplot = (TH1D *)key->ReadObj(); std::string plotname = std::string(baseplot->GetName()); int nbins = baseplot->GetNbinsX() * baseplot->GetNbinsY(); // Setup TProfile with RMS option TProfile *tprof = new TProfile((plotname + "_prof").c_str(), (plotname + "_prof").c_str(), nbins, 0, nbins, "S"); // Setup The TTREE double *bincontents; bincontents = new double[nbins]; double *binlowest; binlowest = new double[nbins]; double *binhighest; binhighest = new double[nbins]; errorDIR->cd(); TTree *bintree = new TTree((plotname + "_tree").c_str(), (plotname + "_tree").c_str()); for (Int_t i = 0; i < nbins; i++) { bincontents[i] = 0.0; binhighest[i] = 0.0; binlowest[i] = 0.0; bintree->Branch(Form("content_%i", i), &bincontents[i], Form("content_%i/D", i)); } for (Int_t i = 0; i < nthrows; i++) { TH1 *newplot = (TH1 *)tempfile->Get(Form(("throw_%i/" + plotname).c_str(), i)); for (Int_t j = 0; j < nbins; j++) { tprof->Fill(j + 0.5, newplot->GetBinContent(j + 1)); bincontents[j] = newplot->GetBinContent(j + 1); if (bincontents[j] < binlowest[j] or i == 0) binlowest[j] = bincontents[j]; if (bincontents[j] > binhighest[j] or i == 0) binhighest[j] = bincontents[j]; } errorDIR->cd(); bintree->Fill(); delete newplot; } errorDIR->cd(); for (Int_t j = 0; j < nbins; j++) { if (!uniformly) { baseplot->SetBinError(j + 1, tprof->GetBinError(j + 1)); } else { baseplot->SetBinContent(j + 1, (binlowest[j] + binhighest[j]) / 2.0); baseplot->SetBinError(j + 1, (binhighest[j] - binlowest[j]) / 2.0); } } errorDIR->cd(); baseplot->Write(); tprof->Write(); bintree->Write(); delete baseplot; delete tprof; delete bintree; delete[] bincontents; } return; }; void MinimizerRoutines::ThrowDataToys() { - QLOG(FIT, "Generating Toy Data Throws"); + NUIS_LOG(FIT, "Generating Toy Data Throws"); int verb = Config::GetParI("VERBOSITY"); SETVERBOSITY(FIT); int nthrows = FitPar::Config().GetParI("NToyThrows"); double maxlike = -1.0; double minlike = -1.0; std::vector values; for (int i = 0; i < 1.E4; i++) { fSampleFCN->ThrowDataToy(); double like = fSampleFCN->GetLikelihood(); values.push_back(like); if (maxlike == -1.0 or like > maxlike) maxlike = like; if (minlike == -1.0 or like < minlike) minlike = like; } SETVERBOSITY(verb); // Fill Histogram TH1D *likes = new TH1D("toydatalikelihood", "toydatalikelihood", int(sqrt(nthrows)), minlike, maxlike); for (size_t i = 0; i < values.size(); i++) { likes->Fill(values[i]); } // Save to file - QLOG(FIT, "Writing toy data throws"); + NUIS_LOG(FIT, "Writing toy data throws"); fOutputRootFile->cd(); likes->Write(); } diff --git a/src/Routines/Simple_MH_Sampler.h b/src/Routines/Simple_MH_Sampler.h index 1d42eb8..f9a4c53 100644 --- a/src/Routines/Simple_MH_Sampler.h +++ b/src/Routines/Simple_MH_Sampler.h @@ -1,334 +1,334 @@ #include "Math/Minimizer.h" #include "FitLogger.h" using ROOT::Math::Minimizer; class Simple_MH_Sampler : public Minimizer { TRandom3 RNJesus; size_t step_i; int moved; size_t thin; size_t thin_ctr; size_t discard; struct Param { Param() : IsFixed(false), name(""), Val(0xdeadbeef), StepWidth(0xdeadbeef), LowLim(0xdeadbeef), UpLim(0xdeadbeef) {} Param(bool i, std::string n, double v, double s, double l, double u) : IsFixed(i), name(n), Val(v), StepWidth(s), LowLim(l), UpLim(u) {} bool IsFixed; std::string name; double Val, StepWidth, LowLim, UpLim; }; std::vector start_params; double curr_value; std::vector curr_params; double propose_value; std::vector propose_params; double min_value; std::vector min_params; TGraph trace; void RestartParams() { curr_params.resize(start_params.size()); for (size_t p_it = 0; p_it < start_params.size(); ++p_it) { curr_params[p_it] = start_params[p_it].Val; } min_params = curr_params; propose_params = curr_params; } TTree *StepTree; void Write(); ROOT::Math::IMultiGenFunction const *FCN; public: Simple_MH_Sampler() : Minimizer(), RNJesus(), trace() { thin = Config::GetParI("MCMC.thin"); thin_ctr = 0; discard = Config::GetParI("MCMC.BurnInSteps"); } void SetFunction(ROOT::Math::IMultiGenFunction const &func) { FCN = &func; } bool SetVariable(unsigned int ivar, std::string const &name, double val, double step) { if (start_params.size() <= ivar) { start_params.resize(ivar + 1); } start_params[ivar] = Param(false, name, val, step, 0xdeadbeef, 0xdeadbeef); RestartParams(); return true; } bool SetLowerLimitedVariable(unsigned int ivar, std::string const &name, double val, double step, double lower) { SetVariable(ivar, name, val, step); start_params[ivar].LowLim = lower; return true; } bool SetUpperLimitedVariable(unsigned int ivar, std::string const &name, double val, double step, double upper) { SetVariable(ivar, name, val, step); start_params[ivar].UpLim = upper; return true; } bool SetLimitedVariable(unsigned int ivar, std::string const &name, double val, double step, double lower, double upper) { SetLowerLimitedVariable(ivar, name, val, step, lower); start_params[ivar].UpLim = upper; return true; } bool SetFixedVariable(unsigned int ivar, std::string const &name, double val) { SetVariable(ivar, name, val, 0xdeadbeef); start_params[ivar].IsFixed = true; return true; } bool SetVariableValue(unsigned int ivar, double value) { if (start_params.size() <= ivar) { - QERROR(WRN, "Tried to set uninitialised variable."); + NUIS_ERR(WRN, "Tried to set uninitialised variable."); return false; } start_params[ivar].Val = value; return true; } bool SetVariableStepSize(unsigned int ivar, double value) { if (start_params.size() <= ivar) { - QERROR(WRN, "Tried to set uninitialised variable."); + NUIS_ERR(WRN, "Tried to set uninitialised variable."); return false; } start_params[ivar].StepWidth = value; return true; } bool SetVariableLowerLimit(unsigned int ivar, double lower) { if (start_params.size() <= ivar) { - QERROR(WRN, "Tried to set uninitialised variable."); + NUIS_ERR(WRN, "Tried to set uninitialised variable."); return false; } start_params[ivar].LowLim = lower; return true; } bool SetVariableUpperLimit(unsigned int ivar, double upper) { if (start_params.size() <= ivar) { - QERROR(WRN, "Tried to set uninitialised variable."); + NUIS_ERR(WRN, "Tried to set uninitialised variable."); return false; } start_params[ivar].UpLim = upper; return true; } bool SetVariableLimits(unsigned int ivar, double lower, double upper) { SetVariableLowerLimit(ivar, lower); SetVariableUpperLimit(ivar, upper); return true; } bool FixVariable(unsigned int ivar) { if (start_params.size() <= ivar) { - QERROR(WRN, "Tried to fix uninitialised variable."); + NUIS_ERR(WRN, "Tried to fix uninitialised variable."); return false; } start_params[ivar].IsFixed = true; return true; } bool ReleaseVariable(unsigned int ivar) { if (start_params.size() <= ivar) { - QERROR(WRN, "Tried to fix uninitialised variable."); + NUIS_ERR(WRN, "Tried to fix uninitialised variable."); return false; } start_params[ivar].IsFixed = false; return true; } bool IsFixedVariable(unsigned int ivar) { if (start_params.size() <= ivar) { - QERROR(WRN, "Tried to fix uninitialised variable."); + NUIS_ERR(WRN, "Tried to fix uninitialised variable."); return false; } return start_params[ivar].IsFixed; } double MinValue() const { return min_value; } const double *X() const { return min_params.data(); } const double *Errors() const { return min_params.data(); } unsigned int NDim() const { return start_params.size(); } unsigned int NFree() const { unsigned int NFree = 0; for (size_t p_it = 0; p_it < start_params.size(); ++p_it) { NFree += !start_params[p_it].IsFixed; } return NFree; } void AddBranches() { TFile *ogf = gFile; if (Config::Get().out && Config::Get().out->IsOpen()) { Config::Get().out->cd(); } StepTree = new TTree("MCMChain", ""); StepTree->Branch("Step", &step_i, "Step/I"); StepTree->Branch("Value", &curr_value, "Value/D"); StepTree->Branch("Moved", &moved, "Moved/I"); std::stringstream ss(""); for (size_t p_it = 0; p_it < curr_params.size(); ++p_it) { ss.str(""); ss << "param_" << p_it; StepTree->Branch(ss.str().c_str(), &curr_params[p_it], (ss.str() + "/D").c_str()); } if (ogf && ogf->IsOpen()) { ogf->cd(); } } void Fill() { StepTree->Fill(); } void Propose() { for (size_t p_it = 0; p_it < start_params.size(); ++p_it) { double propose_param = curr_params[p_it]; if (!start_params[p_it].IsFixed) { size_t attempts = 0; do { if (attempts > 1000) { - QTHROW("After 1000 attempts, failed to throw Gaus(" + NUIS_ABORT("After 1000 attempts, failed to throw Gaus(" << start_params[p_it].Val << ", " << start_params[p_it].StepWidth << ") inside limits: [ " << start_params[p_it].LowLim << " -- " << start_params[p_it].UpLim << " ]"); } double thr = RNJesus.Gaus(curr_params[p_it], start_params[p_it].StepWidth); if ((start_params[p_it].LowLim != 0xdeadbeef) && (thr < start_params[p_it].LowLim)) { attempts++; continue; } if ((start_params[p_it].UpLim != 0xdeadbeef) && (thr > start_params[p_it].UpLim)) { attempts++; continue; } propose_param = thr; break; } while (true); } propose_params[p_it] = propose_param; } } void Evaluate() { propose_value = exp(-(*FCN)(propose_params.data()) / 10000.0); if (propose_value < min_value) { min_params = propose_params; } } void PrintResults() { - QLOG(FIT, "Simple_MH_Sampler State: "); + NUIS_LOG(FIT, "Simple_MH_Sampler State: "); for (size_t p_it = 0; p_it < start_params.size(); ++p_it) { - QLOG(FIT, "\t[" << p_it + NUIS_LOG(FIT, "\t[" << p_it << "]: " << (start_params[p_it].IsFixed ? " FIX" : "FREE") << " " << curr_params[p_it]); } - QLOG(FIT, "Curr LHood: " << curr_value << ", Min LHood: " << min_value); + NUIS_LOG(FIT, "Curr LHood: " << curr_value << ", Min LHood: " << min_value); } void Step() { moved = false; if (propose_value != propose_value) { curr_params = propose_params; curr_value = propose_value; PrintResults(); - QTHROW("Proposed a NAN value."); + NUIS_ABORT("Proposed a NAN value."); } std::cout << "[" << step_i << "] proposed: " << propose_value << " | current: " << curr_value << std::endl; double a = propose_value / curr_value; std::cout << "\ta = " << a << std::endl; if (a >= 1.0) { moved = true; std::cout << "\tMoved." << std::endl; } else { double b = RNJesus.Uniform(1); if (b < a) { moved = true; std::cout << "\tMoved (" << b << ")" << std::endl; } else { std::cout << "\tStayed. (" << b << ")" << std::endl; } } if (moved) { curr_params = propose_params; curr_value = propose_value; } } bool Minimize() { if (!start_params.size()) { - QERROR(FTL, "No Parameters passed to Simple_MH_Sampler."); + NUIS_ERR(FTL, "No Parameters passed to Simple_MH_Sampler."); return false; } RestartParams(); AddBranches(); size_t NSteps = Options().MaxIterations(); trace.Set(NSteps); - QLOG(FIT, "Running chain for " << NSteps << " steps."); + NUIS_LOG(FIT, "Running chain for " << NSteps << " steps."); step_i = 0; while (step_i < NSteps) { Propose(); Evaluate(); Step(); trace.SetPoint(step_i, step_i, curr_value); if (step_i >= discard) { thin_ctr++; if (thin_ctr == thin) { Fill(); thin_ctr = 0; } } step_i++; } StepTree->Write(); trace.Write("MCMCTrace"); return true; }; }; diff --git a/src/Routines/SplineRoutines.cxx b/src/Routines/SplineRoutines.cxx index 2be20c0..6e9409b 100755 --- a/src/Routines/SplineRoutines.cxx +++ b/src/Routines/SplineRoutines.cxx @@ -1,2598 +1,2598 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "SplineRoutines.h" void SplineRoutines::Init() { fStrategy = "SaveEvents"; fRoutines.clear(); fCardFile = ""; fSampleFCN = NULL; fRW = NULL; fAllowedRoutines = ("SaveEvents,TestEvents,SaveSplineEvents"); }; SplineRoutines::~SplineRoutines(){}; SplineRoutines::SplineRoutines(int argc, char *argv[]) { // Initialise Defaults Init(); nuisconfig configuration = Config::Get(); // Default containers std::string cardfile = ""; std::string maxevents = "-1"; int errorcount = 0; int verbocount = 0; std::vector xmlcmds; std::vector configargs; // Make easier to handle arguments. std::vector args = GeneralUtils::LoadCharToVectStr(argc, argv); ParserUtils::ParseArgument(args, "-c", fCardFile, true); ParserUtils::ParseArgument(args, "-o", fOutputFile, false, false); ParserUtils::ParseArgument(args, "-n", maxevents, false, false); ParserUtils::ParseArgument(args, "-f", fStrategy, false, false); ParserUtils::ParseArgument(args, "-i", xmlcmds); ParserUtils::ParseArgument(args, "-q", configargs); ParserUtils::ParseCounter(args, "e", errorcount); ParserUtils::ParseCounter(args, "v", verbocount); ParserUtils::CheckBadArguments(args); // Add extra defaults if none given if (fCardFile.empty() and xmlcmds.empty()) { - QTHROW("No input supplied!"); + NUIS_ABORT("No input supplied!"); } if (fOutputFile.empty() and !fCardFile.empty()) { fOutputFile = fCardFile + ".root"; - QERROR(WRN, "No output supplied so saving it to: " << fOutputFile); + NUIS_ERR(WRN, "No output supplied so saving it to: " << fOutputFile); } else if (fOutputFile.empty()) { - QTHROW("No output file or cardfile supplied!"); + NUIS_ABORT("No output file or cardfile supplied!"); } // Configuration Setup ============================= // Check no comp key is available nuiskey fCompKey; if (Config::Get().GetNodes("nuiscomp").empty()) { fCompKey = Config::Get().CreateNode("nuiscomp"); } else { fCompKey = Config::Get().GetNodes("nuiscomp")[0]; } if (!fCardFile.empty()) fCompKey.Set("cardfile", fCardFile); fCompKey.Set("outputfile", fOutputFile); if (!fStrategy.empty()) fCompKey.Set("strategy", fStrategy); // Load XML Cardfile configuration.LoadSettings(fCompKey.GetS("cardfile"), ""); // Add Config Args for (size_t i = 0; i < configargs.size(); i++) { configuration.OverrideConfig(configargs[i]); } if (maxevents.compare("-1")) { std::cout << "[ NUISANCE ] : Overriding " << "MAXEVENTS=" + maxevents << std::endl; configuration.OverrideConfig("MAXEVENTS=" + maxevents); } // Finish configuration XML configuration.FinaliseSettings(fCompKey.GetS("outputfile") + ".xml"); // Add Error Verbo Lines verbocount += Config::GetParI("VERBOSITY"); errorcount += Config::GetParI("ERROR"); std::cout << "[ NUISANCE ]: Setting VERBOSITY=" << verbocount << std::endl; std::cout << "[ NUISANCE ]: Setting ERROR=" << errorcount << std::endl; // FitPar::log_verb = verbocount; SETVERBOSITY(verbocount); // ERR_VERB(errorcount); // Starting Setup // --------------------------- SetupRWEngine(); return; }; /* Setup Functions */ //************************************* void SplineRoutines::SetupRWEngine() { //************************************* fRW = new FitWeight("splineweight"); // std::vector splinekeys = Config::QueryKeys("spline"); std::vector parameterkeys = Config::QueryKeys("parameter"); // Add Parameters for (size_t i = 0; i < parameterkeys.size(); i++) { nuiskey key = parameterkeys[i]; std::string parname = key.GetS("name"); std::string partype = key.GetS("type"); double nom = key.GetD("nominal"); fRW->IncludeDial(key.GetS("name"), FitBase::ConvDialType(key.GetS("type")), nom); fRW->SetDialValue(key.GetS("name"), key.GetD("nominal")); } fRW->Reconfigure(); return; } /* Fitting Functions */ //************************************* void SplineRoutines::UpdateRWEngine(std::map &updateVals) { //************************************* for (UInt_t i = 0; i < fParams.size(); i++) { std::string name = fParams[i]; if (updateVals.find(name) == updateVals.end()) continue; fRW->SetDialValue(name, updateVals.at(name)); } fRW->Reconfigure(); return; } //************************************* void SplineRoutines::Run() { //************************************* std::cout << "Running " << std::endl; // Parse given routines fRoutines = GeneralUtils::ParseToStr(fStrategy, ","); if (fRoutines.empty()) { - QTHROW("Trying to run ComparisonRoutines with no routines given!"); + NUIS_ABORT("Trying to run ComparisonRoutines with no routines given!"); } for (size_t i = 0; i < fRoutines.size(); i++) { - QLOG(FIT, "Running Routine: " << fRoutines[i]); + NUIS_LOG(FIT, "Running Routine: " << fRoutines[i]); std::string rout = fRoutines[i]; if (!rout.compare("SaveEvents")) SaveEvents(); else if (!rout.compare("TestEvents")) TestEvents(); else if (!rout.compare("GenerateEventSplines")) { GenerateEventWeights(); BuildEventSplines(); } else if (!rout.compare("GenerateEventWeights")) { GenerateEventWeights(); } else if (!rout.compare("GenerateEventWeightChunks")) { GenerateEventWeightChunks(FitPar::Config().GetParI("spline_procchunk")); } else if (!rout.compare("BuildEventSplines")) { BuildEventSplines(); } else if (!rout.compare("TestSplines_1DEventScan")) TestSplines_1DEventScan(); else if (!rout.compare("TestSplines_NDEventThrow")) TestSplines_NDEventThrow(); else if (!rout.compare("SaveSplinePlots")) SaveSplinePlots(); else if (!rout.compare("TestSplines_1DLikelihoodScan")) TestSplines_1DLikelihoodScan(); else if (!rout.compare("TestSplines_NDLikelihoodThrow")) TestSplines_NDLikelihoodThrow(); else if (!rout.compare("BuildEventSplinesChunks")) { int chunk = FitPar::Config().GetParI("spline_procchunk"); BuildEventSplines(chunk); } else if (!rout.compare("MergeEventSplinesChunks")) { MergeEventSplinesChunks(); } } } //************************************* void SplineRoutines::SaveEvents() { //************************************* if (fRW) delete fRW; SetupRWEngine(); fRW->Reconfigure(); fRW->Print(); // Generate a set of nominal events // Method, Loop over inputs, create input handler, then create a ttree std::vector eventkeys = Config::QueryKeys("events"); for (size_t i = 0; i < eventkeys.size(); i++) { nuiskey key = eventkeys.at(i); // Get I/O std::string inputfilename = key.GetS("input"); if (inputfilename.empty()) { - QTHROW("No input given for set of input events!"); + NUIS_ABORT("No input given for set of input events!"); } std::string outputfilename = key.GetS("output"); if (outputfilename.empty()) { outputfilename = inputfilename + ".nuisance.root"; - QERROR(WRN, "No output give for set of output events! Saving to " + NUIS_ERR(WRN, "No output give for set of output events! Saving to " << outputfilename); } // Make new outputfile TFile *outputfile = new TFile(outputfilename.c_str(), "RECREATE"); outputfile->cd(); // Make a new input handler std::vector file_descriptor = GeneralUtils::ParseToStr(inputfilename, ":"); if (file_descriptor.size() != 2) { - QTHROW("File descriptor had no filetype declaration: \"" + NUIS_ABORT("File descriptor had no filetype declaration: \"" << inputfilename << "\". expected \"FILETYPE:file.root\""); } InputUtils::InputType inptype = InputUtils::ParseInputType(file_descriptor[0]); InputHandlerBase *input = InputUtils::CreateInputHandler( "eventsaver", inptype, file_descriptor[1]); // Get info from inputhandler int nevents = input->GetNEvents(); int countwidth = (nevents / 10); FitEvent *nuisevent = input->FirstNuisanceEvent(); // Setup a TTree to save the event outputfile->cd(); TTree *eventtree = new TTree("nuisance_events", "nuisance_events"); nuisevent->AddBranchesToTree(eventtree); // Loop over all events and fill the TTree int icount = 0; // int countwidth = nevents / 5; while (nuisevent) { // Get Event Weight nuisevent->RWWeight = fRW->CalcWeight(nuisevent); // if (nuisevent->RWWeight != 1.0){ // std::cout << "Weight = " << nuisevent->RWWeight << std::endl; // } // Save everything eventtree->Fill(); // Logging if (icount % countwidth == 0) { - QLOG(REC, "Saved " << icount << "/" << nevents + NUIS_LOG(REC, "Saved " << icount << "/" << nevents << " nuisance events. [M, W] = [" << nuisevent->Mode << ", " << nuisevent->RWWeight << "]"); } // iterate nuisevent = input->NextNuisanceEvent(); icount++; } // Save flux and close file outputfile->cd(); eventtree->Write(); input->GetFluxHistogram()->Write("nuisance_fluxhist"); input->GetEventHistogram()->Write("nuisance_eventhist"); // Close Output outputfile->Close(); // Delete Inputs delete input; } // remove Keys eventkeys.clear(); // Finished - QLOG(FIT, "Finished processing all nuisance events."); + NUIS_LOG(FIT, "Finished processing all nuisance events."); } //************************************* void SplineRoutines::TestEvents() { //************************************* - QLOG(FIT, "Testing events."); + NUIS_LOG(FIT, "Testing events."); // Create a new file for the test samples if (!fOutputRootFile) { fOutputRootFile = new TFile(fCompKey.GetS("outputfile").c_str(), "RECREATE"); } // Loop over all tests int count = 0; std::vector testkeys = Config::QueryKeys("sampletest"); for (std::vector::iterator iter = testkeys.begin(); iter != testkeys.end(); iter++) { nuiskey key = (*iter); // 0. Create new measurement list std::list samplelist; // 1. Build Sample From Events std::string samplename = key.GetS("name"); std::string eventsid = key.GetS("inputid"); nuiskey eventskey = Config::QueryLastKey("events", "id=" + eventsid); std::string rawfile = eventskey.GetS("input"); - QLOG(FIT, "Creating sample " << samplename); + NUIS_LOG(FIT, "Creating sample " << samplename); MeasurementBase *rawsample = SampleUtils::CreateSample( samplename, rawfile, "", "", FitBase::GetRW()); // 2. Build Sample From Nuisance Events std::string eventsfile = eventskey.GetS("output"); - QLOG(FIT, "Creating Fit Eevnt Sample " << samplename << " " << eventsfile); + NUIS_LOG(FIT, "Creating Fit Eevnt Sample " << samplename << " " << eventsfile); MeasurementBase *nuissample = SampleUtils::CreateSample( samplename, "FEVENT:" + eventsfile, "", "", FitBase::GetRW()); // 3. Make some folders to save stuff TDirectory *sampledir = (TDirectory *)fOutputRootFile->mkdir( Form((samplename + "_test_%d").c_str(), count)); TDirectory *rawdir = (TDirectory *)sampledir->mkdir("raw"); TDirectory *nuisancedir = (TDirectory *)sampledir->mkdir("nuisance"); TDirectory *difdir = (TDirectory *)sampledir->mkdir("difference"); // 4. Reconfigure both rawdir->cd(); rawsample->Reconfigure(); rawsample->Write(); nuisancedir->cd(); nuissample->Reconfigure(); nuissample->Write(); // 4. Compare Raw to Nuisance Events // Loop over all keyse TIter next(rawdir->GetListOfKeys()); TKey *dirkey; while ((dirkey = (TKey *)next())) { // If not a 1D/2D histogram skip TClass *cl = gROOT->GetClass(dirkey->GetClassName()); if (!cl->InheritsFrom("TH1D") and !cl->InheritsFrom("TH2D")) continue; // Get TH1* from both dir TH1 *rawplot = (TH1 *)rawdir->Get(dirkey->GetName()); TH1 *nuisanceplot = (TH1 *)nuisancedir->Get(dirkey->GetName()); // Take Difference nuisanceplot->Add(rawplot, -1.0); // Save to dif folder difdir->cd(); nuisanceplot->Write(); } // 5. Tidy Up samplelist.clear(); // Iterator count++; } } void SplineRoutines::GenerateEventWeightChunks(int procchunk) { if (fRW) delete fRW; SetupRWEngine(); // Setup the spline reader SplineWriter *splwrite = new SplineWriter(fRW); std::vector splinekeys = Config::QueryKeys("spline"); // Add splines to splinewriter for (std::vector::iterator iter = splinekeys.begin(); iter != splinekeys.end(); iter++) { nuiskey splkey = (*iter); // Add Spline Info To Reader splwrite->AddSpline(splkey); } splwrite->SetupSplineSet(); // Event Loop // Loop over all events and calculate weights for each parameter set. // Generate a set of nominal events // Method, Loop over inputs, create input handler, then create a ttree std::vector eventkeys = Config::QueryKeys("events"); for (size_t i = 0; i < eventkeys.size(); i++) { nuiskey key = eventkeys.at(i); // Get I/O std::string inputfilename = key.GetS("input"); if (inputfilename.empty()) { - QTHROW("No input given for set of input events!"); + NUIS_ABORT("No input given for set of input events!"); } std::string outputfilename = key.GetS("output"); if (outputfilename.empty()) { outputfilename = inputfilename + ".nuisance.root"; - QERROR(WRN,"No output give for set of output events! Saving to " + NUIS_ERR(WRN,"No output give for set of output events! Saving to " << outputfilename); } outputfilename += ".weights.root"; // Make new outputfile TFile *outputfile = new TFile(outputfilename.c_str(), "RECREATE"); outputfile->cd(); // Make a new input handler std::vector file_descriptor = GeneralUtils::ParseToStr(inputfilename, ":"); if (file_descriptor.size() != 2) { - QTHROW("File descriptor had no filetype declaration: \"" + NUIS_ABORT("File descriptor had no filetype declaration: \"" << inputfilename << "\". expected \"FILETYPE:file.root\""); } InputUtils::InputType inptype = InputUtils::ParseInputType(file_descriptor[0]); InputHandlerBase *input = InputUtils::CreateInputHandler( "eventsaver", inptype, file_descriptor[1]); // Get info from inputhandler int nevents = input->GetNEvents(); // int countwidth = (nevents / 1000); FitEvent *nuisevent = input->FirstNuisanceEvent(); // Setup a TTree to save the event outputfile->cd(); TTree *eventtree = new TTree("nuisance_events", "nuisance_events"); // Add a flag that allows just splines to be saved. nuisevent->AddBranchesToTree(eventtree); // Save the spline reader splwrite->Write("spline_reader"); // Setup the spline TTree TTree *weighttree = new TTree("weight_tree", "weight_tree"); splwrite->AddWeightsToTree(weighttree); // Make container for all weights int nweights = splwrite->GetNWeights(); // int npar = splwrite->GetNPars(); // double* weightcont = new double[nweights]; int lasttime = time(NULL); // Load N Chunks of the Weights into Memory // Split into N processing chunks int nchunks = FitPar::Config().GetParI("spline_chunks"); if (nchunks <= 0) nchunks = 1; if (nchunks >= nevents / 2) nchunks = nevents / 2; std::cout << "Starting NChunks " << nchunks << std::endl; for (int ichunk = 0; ichunk < nchunks; ichunk++) { // Skip to only do one processing chunk if (procchunk != -1 and procchunk != ichunk) continue; - QLOG(FIT, "On Processing Chunk " << ichunk); + NUIS_LOG(FIT, "On Processing Chunk " << ichunk); int neventsinchunk = nevents / nchunks; int loweventinchunk = neventsinchunk * ichunk; // int higheventinchunk = neventsinchunk * (ichunk + 1); double **allweightcont = new double *[neventsinchunk]; for (int k = 0; k < neventsinchunk; k++) { allweightcont[k] = new double[nweights]; } // Start Set Processing Here. for (int iset = 0; iset < nweights; iset++) { splwrite->ReconfigureSet(iset); // Could reorder this to save the weightconts in order instead of // reconfiguring per event. Loop over all events and fill the TTree for (int i = 0; i < neventsinchunk; i++) { nuisevent = input->GetNuisanceEvent(i + loweventinchunk); double w = splwrite->GetWeightForThisSet(nuisevent); if (iset == 0) { allweightcont[i][0] = w; } else { allweightcont[i][iset] = w / allweightcont[i][0]; } // Save everything if (iset == 0) { eventtree->Fill(); } } std::ostringstream timestring; int timeelapsed = time(NULL) - lasttime; if (timeelapsed) { lasttime = time(NULL); int setsleft = (nweights - iset - 1) + (nweights * (nchunks - ichunk - 1)); float proj = (float(setsleft) * timeelapsed) / 60 / 60; timestring << setsleft << " sets remaining. Last one took " << timeelapsed << ". " << proj << " hours remaining."; } - QLOG(REC, "Processed Set " << iset << "/" << nweights << " in chunk " + NUIS_LOG(REC, "Processed Set " << iset << "/" << nweights << " in chunk " << ichunk << "/" << nchunks << " " << timestring.str()); } // Fill weights for this chunk into the TTree for (int k = 0; k < neventsinchunk; k++) { splwrite->SetWeights(allweightcont[k]); weighttree->Fill(); } } // at end of the chunk, when all sets have been done // loop over the container and fill weights to ttree outputfile->cd(); eventtree->Write(); weighttree->Write(); input->GetFluxHistogram()->Write("nuisance_fluxhist"); input->GetEventHistogram()->Write("nuisance_eventhist"); splwrite->Write("spline_reader"); outputfile->Close(); // Close Output outputfile->Close(); // Delete Inputs delete input; } // remove Keys eventkeys.clear(); } //************************************* void SplineRoutines::GenerateEventWeights() { //************************************* if (fRW) delete fRW; SetupRWEngine(); // Setup the spline reader SplineWriter *splwrite = new SplineWriter(fRW); std::vector splinekeys = Config::QueryKeys("spline"); // Add splines to splinewriter for (std::vector::iterator iter = splinekeys.begin(); iter != splinekeys.end(); iter++) { nuiskey splkey = (*iter); // Add Spline Info To Reader splwrite->AddSpline(splkey); } splwrite->SetupSplineSet(); // Event Loop // Loop over all events and calculate weights for each parameter set. // Generate a set of nominal events // Method, Loop over inputs, create input handler, then create a ttree std::vector eventkeys = Config::QueryKeys("events"); for (size_t i = 0; i < eventkeys.size(); i++) { nuiskey key = eventkeys.at(i); // Get I/O std::string inputfilename = key.GetS("input"); if (inputfilename.empty()) { - QTHROW("No input given for set of input events!"); + NUIS_ABORT("No input given for set of input events!"); } std::string outputfilename = key.GetS("output"); if (outputfilename.empty()) { outputfilename = inputfilename + ".nuisance.root"; - QERROR(WRN, "No output give for set of output events! Saving to " + NUIS_ERR(WRN, "No output give for set of output events! Saving to " << outputfilename); } outputfilename += ".weights.root"; // Make new outputfile TFile *outputfile = new TFile(outputfilename.c_str(), "RECREATE"); outputfile->cd(); // Make a new input handler std::vector file_descriptor = GeneralUtils::ParseToStr(inputfilename, ":"); if (file_descriptor.size() != 2) { - QTHROW("File descriptor had no filetype declaration: \"" + NUIS_ABORT("File descriptor had no filetype declaration: \"" << inputfilename << "\". expected \"FILETYPE:file.root\""); } InputUtils::InputType inptype = InputUtils::ParseInputType(file_descriptor[0]); InputHandlerBase *input = InputUtils::CreateInputHandler( "eventsaver", inptype, file_descriptor[1]); // Get info from inputhandler int nevents = input->GetNEvents(); int countwidth = (nevents / 1000); FitEvent *nuisevent = input->FirstNuisanceEvent(); // Setup a TTree to save the event outputfile->cd(); TTree *eventtree = new TTree("nuisance_events", "nuisance_events"); // Add a flag that allows just splines to be saved. nuisevent->AddBranchesToTree(eventtree); // Save the spline reader splwrite->Write("spline_reader"); // Setup the spline TTree TTree *weighttree = new TTree("weight_tree", "weight_tree"); splwrite->AddWeightsToTree(weighttree); // Make container for all weights int nweights = splwrite->GetNWeights(); // int npar = splwrite->GetNPars(); double *weightcont = new double[nweights]; int lasttime = time(NULL); // Could reorder this to save the weightconts in order instead of // reconfiguring per event. Loop over all events and fill the TTree while (nuisevent) { // Calculate the weights for each parameter set splwrite->GetWeightsForEvent(nuisevent, weightcont); // Save everything eventtree->Fill(); weighttree->Fill(); // Logging if (i % countwidth == 0) { std::ostringstream timestring; int timeelapsed = time(NULL) - lasttime; if (i != 0 and timeelapsed) { lasttime = time(NULL); int eventsleft = nevents - i; float speed = float(countwidth) / float(timeelapsed); float proj = (float(eventsleft) / float(speed)) / 60 / 60; timestring << proj << " hours remaining."; } - QLOG(REC, "Saved " << i << "/" << nevents + NUIS_LOG(REC, "Saved " << i << "/" << nevents << " nuisance spline weights. " << timestring.str()); } // Iterate i++; nuisevent = input->NextNuisanceEvent(); } // at end of the chunk, when all sets have been done // loop over the container and fill weights to ttree outputfile->cd(); eventtree->Write(); weighttree->Write(); input->GetFluxHistogram()->Write("nuisance_fluxhist"); input->GetEventHistogram()->Write("nuisance_eventhist"); splwrite->Write("spline_reader"); outputfile->Close(); // Close Output outputfile->Close(); // Delete Inputs delete input; } // remove Keys eventkeys.clear(); } //************************************* void SplineRoutines::GenerateEventSplines() { //************************************* if (fRW) delete fRW; SetupRWEngine(); // Setup the spline reader SplineWriter *splwrite = new SplineWriter(fRW); std::vector splinekeys = Config::QueryKeys("spline"); // Add splines to splinewriter for (std::vector::iterator iter = splinekeys.begin(); iter != splinekeys.end(); iter++) { nuiskey splkey = (*iter); // Add Spline Info To Reader splwrite->AddSpline(splkey); } splwrite->SetupSplineSet(); // Make an ugly list for N cores int ncores = FitPar::Config().GetParI("NCORES"); // omp_get_max_threads(); std::vector splwriterlist; for (int i = 0; i < ncores; i++) { SplineWriter *tmpwriter = new SplineWriter(fRW); for (std::vector::iterator iter = splinekeys.begin(); iter != splinekeys.end(); iter++) { nuiskey splkey = (*iter); // Add Spline Info To Reader tmpwriter->AddSpline(splkey); } tmpwriter->SetupSplineSet(); splwriterlist.push_back(tmpwriter); } // Event Loop // Loop over all events and calculate weights for each parameter set. // Generate a set of nominal events // Method, Loop over inputs, create input handler, then create a ttree std::vector eventkeys = Config::QueryKeys("events"); for (size_t i = 0; i < eventkeys.size(); i++) { nuiskey key = eventkeys.at(i); // Get I/O std::string inputfilename = key.GetS("input"); if (inputfilename.empty()) { - QTHROW("No input given for set of input events!"); + NUIS_ABORT("No input given for set of input events!"); } std::string outputfilename = key.GetS("output"); if (outputfilename.empty()) { outputfilename = inputfilename + ".nuisance.root"; - QERROR(WRN, "No output give for set of output events! Saving to " + NUIS_ERR(WRN, "No output give for set of output events! Saving to " << outputfilename); } // Make new outputfile TFile *outputfile = new TFile(outputfilename.c_str(), "RECREATE"); outputfile->cd(); // Make a new input handler std::vector file_descriptor = GeneralUtils::ParseToStr(inputfilename, ":"); if (file_descriptor.size() != 2) { - QTHROW("File descriptor had no filetype declaration: \"" + NUIS_ABORT("File descriptor had no filetype declaration: \"" << inputfilename << "\". expected \"FILETYPE:file.root\""); } InputUtils::InputType inptype = InputUtils::ParseInputType(file_descriptor[0]); InputHandlerBase *input = InputUtils::CreateInputHandler( "eventsaver", inptype, file_descriptor[1]); // Get info from inputhandler int nevents = input->GetNEvents(); int countwidth = (nevents / 1000); FitEvent *nuisevent = input->FirstNuisanceEvent(); // Setup a TTree to save the event outputfile->cd(); TTree *eventtree = new TTree("nuisance_events", "nuisance_events"); // Add a flag that allows just splines to be saved. nuisevent->AddBranchesToTree(eventtree); // Save the spline reader splwrite->Write("spline_reader"); // Setup the spline TTree TTree *weighttree = new TTree("weight_tree", "weight_tree"); splwrite->AddWeightsToTree(weighttree); // Make container for all weights int nweights = splwrite->GetNWeights(); double **weightcont = new double *[nevents]; for (int k = 0; k < nevents; k++) { weightcont[k] = new double[nweights]; } int npar = splwrite->GetNPars(); int lasttime = time(NULL); // Could reorder this to save the weightconts in order instead of // reconfiguring per event. Loop over all events and fill the TTree while (nuisevent) { // std::cout << "Fitting event " << i << std::endl; // Calculate the weights for each parameter set // splwrite->FitSplinesForEvent(nuisevent); splwrite->GetWeightsForEvent(nuisevent, weightcont[i]); bool hasresponse = false; for (int j = 0; j < nweights; j++) { if (weightcont[i][j] != 1.0) { // std::cout << "Non Zero Weight at " << i << " " << j << // std::endl; hasresponse = true; } else { // std::cout << "Empty Weight at " << i << " " << j << std::endl; } } if (!hasresponse) { // std::cout << "Deleting flat response " << nuisevent->Mode << // std::endl; delete weightcont[i]; weightcont[i] = NULL; } // Save everything eventtree->Fill(); weighttree->Fill(); // splinetree->Fill(); // nuisevent->Print(); // std::cout << "Done with event " << i << std::endl; // Push weight sets into a the array // sleep(4); // Logging if (i % countwidth == 0) { std::ostringstream timestring; int timeelapsed = time(NULL) - lasttime; if (i != 0 and timeelapsed) { lasttime = time(NULL); int eventsleft = nevents - i; float speed = float(countwidth) / float(timeelapsed); float proj = (float(eventsleft) / float(speed)) / 60 / 60; timestring << proj << " hours remaining."; } - QLOG(REC, "Saved " << i << "/" << nevents + NUIS_LOG(REC, "Saved " << i << "/" << nevents << " nuisance spline weights. " << timestring.str()); } // Iterate i++; nuisevent = input->NextNuisanceEvent(); } outputfile->cd(); eventtree->Write(); weighttree->Write(); input->GetFluxHistogram()->Write("nuisance_fluxhist"); input->GetEventHistogram()->Write("nuisance_eventhist"); outputfile->Close(); outputfile = new TFile(outputfilename.c_str(), "UPDATE"); outputfile->cd(); weighttree = (TTree *)outputfile->Get("weight_tree"); // splwrite->ReadWeightsFromTree(weighttree); // Divide weights container into Ncores. // Parrallelise this loop checking for what core we are on. // for (int i = 0; i < nevents; i++){ // splwriterlist[int(i / (nevents/4))]->FitSplinesForEvent(coeff); // } // // Now loop over weights tree // for (int i = 0; i < weighttree->GetEntries(); i++) { // weighttree->GetEntry(i); // splwrite->FitSplinesForEvent(); // splinetree->Fill(); // if (i % countwidth == 0) { // std::ostringstream timestring; // int timeelapsed = time(NULL) - lasttime; // if (i != 0 and timeelapsed) { // lasttime = time(NULL); // int eventsleft = nevents - i; // float speed = float(countwidth) / float(timeelapsed); // float proj = (float(eventsleft) / float(speed)) / 60 / 60; // timestring << proj << " hours remaining."; // } // LOG(REC) << "Built " << i << "/" << nevents << " nuisance spline // events. " << timestring.str() << std::endl; // } // } // Get Splines float **allcoeff = new float *[nevents]; for (int k = 0; k < nevents; k++) { allcoeff[k] = new float[npar]; } // #pragma omp parallel for num_threads(ncores) for (int i = 0; i < nevents; i++) { //#pragma omp atomic // printf("Using Thread %d to build event %d \n", // int(omp_get_thread_num()), (int)i ); std::cout<< " -> Writer = " // << splwriterlist[ i / (nevents/ncores) ] << std::endl; // #pragma omp atomic if (weightcont[i]) { splwriterlist[int(omp_get_thread_num())]->FitSplinesForEvent( weightcont[i], allcoeff[i]); } else { for (int j = 0; j < npar; j++) { allcoeff[i][j] = float(0.0); } } // splwrite->FitSplinesForEvent(weightcont[i], allcoeff[i]); if (i % 500 == 0) { if (LOG_LEVEL(REC)) { printf("Using Thread %d to build event %d \n", int(omp_get_thread_num()), (int)i); } } /* std::ostringstream timestring; int timeelapsed = time(NULL) - lasttime; if (i != 0 and timeelapsed) { lasttime = time(NULL); int eventsleft = nevents - i; float speed = float(countwidth) / float(timeelapsed); float proj = (float(eventsleft) / float(speed)) / 60 / 60; timestring << proj << " hours remaining."; timestring << " Using Writer at " << i / (nevents/ncores) << " = " << splwriterlist[ i / (nevents/ncores) ] << std::endl; } LOG(REC) << "Built " << i << "/" << nevents << " nuisance spline events. " << timestring.str() << std::endl; } */ } // Save Splines into TTree float *coeff = new float[npar]; outputfile->cd(); TTree *splinetree = new TTree("spline_tree", "spline_tree"); splinetree->Branch("SplineCoeff", coeff, Form("SplineCoeff[%d]/F", npar)); std::cout << "Saving to the allcoeff" << std::endl; for (int k = 0; k < nevents; k++) { for (int l = 0; l < npar; l++) { coeff[l] = allcoeff[k][l]; } std::cout << "Coeff 0, 1, 2 = " << coeff[0] << " " << coeff[1] << " " << coeff[2] << std::endl; splinetree->Fill(); } // Save flux and close file outputfile->cd(); splinetree->Write(); // Delete the container. for (int k = 0; k < nevents; k++) { delete weightcont[k]; } delete weightcont; delete coeff; // Close Output outputfile->Close(); // Delete Inputs delete input; } // remove Keys eventkeys.clear(); } //************************************* void SplineRoutines::BuildEventSplines(int procchunk) { //************************************* if (fRW) delete fRW; SetupRWEngine(); // Setup the spline reader SplineWriter *splwrite = new SplineWriter(fRW); std::vector splinekeys = Config::QueryKeys("spline"); // Add splines to splinewriter for (std::vector::iterator iter = splinekeys.begin(); iter != splinekeys.end(); iter++) { nuiskey splkey = (*iter); // Add Spline Info To Reader splwrite->AddSpline(splkey); } splwrite->SetupSplineSet(); // Make an ugly list for N cores int ncores = FitPar::Config().GetParI("spline_cores"); // omp_get_max_threads(); if (ncores > omp_get_max_threads()) ncores = omp_get_max_threads(); if (ncores <= 0) ncores = 1; std::vector splwriterlist; for (int i = 0; i < ncores; i++) { SplineWriter *tmpwriter = new SplineWriter(fRW); for (std::vector::iterator iter = splinekeys.begin(); iter != splinekeys.end(); iter++) { nuiskey splkey = (*iter); // Add Spline Info To Reader tmpwriter->AddSpline(splkey); } tmpwriter->SetupSplineSet(); splwriterlist.push_back(tmpwriter); } // Event Loop // Loop over all events and calculate weights for each parameter set. // Generate a set of nominal events // Method, Loop over inputs, create input handler, then create a ttree std::vector eventkeys = Config::QueryKeys("events"); for (size_t i = 0; i < eventkeys.size(); i++) { nuiskey key = eventkeys.at(i); // Get I/O std::string inputfilename = key.GetS("input"); if (inputfilename.empty()) { - QTHROW("No input given for set of input events!"); + NUIS_ABORT("No input given for set of input events!"); } std::string outputfilename = key.GetS("output"); if (outputfilename.empty()) { outputfilename = inputfilename + ".nuisance.root"; - QERROR(WRN, "No output give for set of output events! Saving to " + NUIS_ERR(WRN, "No output give for set of output events! Saving to " << outputfilename); } // Make new outputfile TFile *outputfile; if (procchunk == -1) outputfile = new TFile(outputfilename.c_str(), "RECREATE"); else outputfile = new TFile( (outputfilename + std::string(Form(".coeffchunk_%d.root", procchunk))) .c_str(), "RECREATE"); outputfile->cd(); // Get Weights File TFile *weightsfile = new TFile((outputfilename + ".weights.root").c_str(), "READ"); TTree *weighttree = (TTree *)weightsfile->Get("weight_tree"); // Get SPLWRite Info // splwrite->ReadWeightsFromTree(weighttree); int nevents = weighttree->GetEntries(); // int countwidth = (nevents / 1000); int nweights = splwrite->GetNWeights(); int npar = splwrite->GetNPars(); // Access Weights double *eventweights = new double[nweights]; weighttree->SetBranchAddress("SplineWeights", eventweights); // Make counter // int lasttime = time(NULL); // Setup Splines To Be Saved into TTree outputfile->cd(); TTree *splinetree = new TTree("spline_tree", "spline_tree"); float *coeff = new float[npar]; splinetree->Branch("SplineCoeff", coeff, Form("SplineCoeff[%d]/F", npar)); // Load N Chunks of the Weights into Memory // Split into N processing chunks int nchunks = FitPar::Config().GetParI("spline_chunks"); if (nchunks <= 0) nchunks = 1; if (nchunks >= nevents / 2) nchunks = nevents / 2; std::cout << "Starting NChunks " << nchunks << std::endl; sleep(1); for (int ichunk = 0; ichunk < nchunks; ichunk++) { // Skip to only do one processing chunk if (procchunk != -1 and procchunk != ichunk) continue; - QLOG(FIT, "On Processing Chunk " << ichunk); + NUIS_LOG(FIT, "On Processing Chunk " << ichunk); int neventsinchunk = nevents / nchunks; int loweventinchunk = neventsinchunk * ichunk; // int higheventinchunk = neventsinchunk * (ichunk + 1); // Build Chunk Containers for Event Weights double **weightcont = new double *[nevents]; float **allcoeff = new float *[nevents]; // Load Chunks into Containers for (int k = 0; k < neventsinchunk; k++) { weighttree->GetEntry(loweventinchunk + k); weightcont[k] = new double[nweights]; allcoeff[k] = new float[npar]; bool hasresponse = false; for (int j = 0; j < nweights; j++) { weightcont[k][j] = eventweights[j]; if (eventweights[j] != 1.0) hasresponse = true; } if (!hasresponse) delete weightcont[k]; } // Loop over ncores and process chunks // #pragma omp parallel for num_threads(ncores) for (int k = 0; k < neventsinchunk; k++) { if (weightcont[k]) { splwriterlist[int(omp_get_thread_num())]->FitSplinesForEvent( weightcont[k], allcoeff[k]); } else { for (int j = 0; j < npar; j++) { allcoeff[k][j] = float(0.0); } } if (k + loweventinchunk % 500 == 0) { if (LOG_LEVEL(REC)) { printf("Using Thread %d to build event %d in chunk %d \n", int(omp_get_thread_num()), (int)loweventinchunk + k, ichunk); } } } // Save Coeff To Tree std::cout << "Saving coeffs to Tree in Chunk " << ichunk << std::endl; for (int k = 0; k < neventsinchunk; k++) { for (int l = 0; l < npar; l++) { coeff[l] = allcoeff[k][l]; } // std::cout << "Coeff 0, 1, 2 = " << coeff[0] << " " << coeff[1] << " " // << coeff[2] << std::endl; splinetree->Fill(); } // Delete the container. for (int k = 0; k < neventsinchunk; k++) { if (weightcont[k]) delete weightcont[k]; if (allcoeff[k]) delete allcoeff[k]; } delete allcoeff; delete weightcont; } // Save flux and close file outputfile->cd(); splinetree->Write(); if (procchunk == -1 or procchunk == 0) { outputfile->cd(); splwrite->Write("spline_reader"); TTree *nuisanceevents = (TTree *)weightsfile->Get("nuisance_events"); nuisanceevents->CloneTree()->Write(); weighttree->CloneTree()->Write(); TH1D *nuisance_fluxhist = (TH1D *)weightsfile->Get("nuisance_fluxhist"); TH1D *nuisance_eventhist = (TH1D *)weightsfile->Get("nuisance_eventhist"); nuisance_fluxhist->Write("nuisance_fluxhist"); nuisance_eventhist->Write("nuisance_eventhist"); } weightsfile->Close(); // Add option to build seperate chunks // Close Output outputfile->Close(); } // remove Keys eventkeys.clear(); } void SplineRoutines::MergeEventSplinesChunks() { if (fRW) delete fRW; SetupRWEngine(); // Setup the spline reader SplineWriter *splwrite = new SplineWriter(fRW); std::vector splinekeys = Config::QueryKeys("spline"); // Add splines to splinewriter for (std::vector::iterator iter = splinekeys.begin(); iter != splinekeys.end(); iter++) { nuiskey splkey = (*iter); // Add Spline Info To Reader splwrite->AddSpline(splkey); } splwrite->SetupSplineSet(); std::vector eventkeys = Config::QueryKeys("events"); for (size_t i = 0; i < eventkeys.size(); i++) { nuiskey key = eventkeys.at(i); // Get I/O std::string inputfilename = key.GetS("input"); if (inputfilename.empty()) { - QTHROW("No input given for set of input events!"); + NUIS_ABORT("No input given for set of input events!"); } std::string outputfilename = key.GetS("output"); if (outputfilename.empty()) { outputfilename = inputfilename + ".nuisance.root"; - QERROR(WRN, "No output give for set of output events! Saving to " + NUIS_ERR(WRN, "No output give for set of output events! Saving to " << outputfilename); } // Make new outputfile TFile *outputfile = new TFile(outputfilename.c_str(), "RECREATE"); outputfile->cd(); // Get Weights File TFile *weightsfile = new TFile((outputfilename + ".weights.root").c_str(), "READ"); TTree *weighttree = (TTree *)weightsfile->Get("weight_tree"); // Get SPLWRite Info // splwrite->ReadWeightsFromTree(weighttree); int nevents = weighttree->GetEntries(); // int countwidth = (nevents / 1000); // int nweights = splwrite->GetNWeights(); int npar = splwrite->GetNPars(); // Make counter // int lasttime = time(NULL); // Setup Splines To Be Saved into TTree outputfile->cd(); TTree *splinetree = new TTree("spline_tree", "spline_tree"); float *coeff = new float[npar]; splinetree->Branch("SplineCoeff", coeff, Form("SplineCoeff[%d]/F", npar)); // Load N Chunks of the Weights into Memory // Split into N processing chunks int nchunks = FitPar::Config().GetParI("spline_chunks"); if (nchunks <= 0) nchunks = 1; if (nchunks >= nevents / 2) nchunks = nevents / 2; int neventsinchunk = nevents / nchunks; for (int ichunk = 0; ichunk < nchunks; ichunk++) { // Get Output File TFile *chunkfile = new TFile( (outputfilename + std::string(Form(".coeffchunk_%d.root", ichunk))) .c_str()); // Get TTree for spline coeffchunk TTree *splinetreechunk = (TTree *)chunkfile->Get("spline_tree"); // Set Branch Address to coeffchunk float *coeffchunk = new float[npar]; splinetreechunk->SetBranchAddress("SplineCoeff", coeffchunk); // Loop over nevents in chunk for (int k = 0; k < neventsinchunk; k++) { splinetreechunk->GetEntry(k); for (int j = 0; j < npar; j++) { coeff[j] = coeffchunk[j]; } splinetree->Fill(); } // Close up chunkfile->Close(); delete coeffchunk; std::cout << "Merged chunk " << ichunk << std::endl; } // Save flux and close file outputfile->cd(); splinetree->Write(); outputfile->cd(); splwrite->Write("spline_reader"); TTree *nuisanceevents = (TTree *)weightsfile->Get("nuisance_events"); nuisanceevents->CloneTree()->Write(); weighttree->CloneTree()->Write(); TH1D *nuisance_fluxhist = (TH1D *)weightsfile->Get("nuisance_fluxhist"); TH1D *nuisance_eventhist = (TH1D *)weightsfile->Get("nuisance_eventhist"); nuisance_fluxhist->Write("nuisance_fluxhist"); nuisance_eventhist->Write("nuisance_eventhist"); weightsfile->Close(); // Add option to build seperate chunks // Close Output outputfile->Close(); } // remove Keys eventkeys.clear(); } // void SplineRoutines::BuildSplineChunk(){ //} // void SplineRoutines::MergeSplineChunks(){ //} //************************************* void SplineRoutines::MergeSplines() { //************************************* // Loop over all 'splinemerge' keys. // Add them to the Merger. // Call setup splines. // Get the key with eventinput // - remaining keys should have splineinput // - Loop over number of entries. // - FillEntry in merger. // - Fill NUISANCEEvent into a new TTree. SplineMerger *splmerge = new SplineMerger(); std::vector splinekeys = Config::QueryKeys("splinemerge"); for (std::vector::iterator iter = splinekeys.begin(); iter != splinekeys.end(); iter++) { nuiskey splkey = (*iter); TFile *infile = new TFile(splkey.GetS("input").c_str(), "READ"); splmerge->AddSplineSetFromFile(infile); } splmerge->SetupSplineSet(); // Now get Event File std::vector eventkeys = Config::QueryKeys("eventmerge"); nuiskey key = eventkeys[0]; std::string inputfilename = key.GetS("input"); // Make a new input handler std::vector file_descriptor = GeneralUtils::ParseToStr(inputfilename, ":"); if (file_descriptor.size() != 2) { - QTHROW("File descriptor had no filetype declaration: \"" + NUIS_ABORT("File descriptor had no filetype declaration: \"" << inputfilename << "\". expected \"FILETYPE:file.root\""); } InputUtils::InputType inptype = InputUtils::ParseInputType(file_descriptor[0]); InputHandlerBase *input = InputUtils::CreateInputHandler("eventsaver", inptype, file_descriptor[1]); std::string outputfilename = key.GetS("output"); if (outputfilename.empty()) { outputfilename = inputfilename + ".nuisance.root"; - QERROR(WRN, "No output give for set of output events! Saving to " + NUIS_ERR(WRN, "No output give for set of output events! Saving to " << outputfilename); } // Make new outputfile TFile *outputfile = new TFile(outputfilename.c_str(), "RECREATE"); outputfile->cd(); // Get info from inputhandler int nevents = input->GetNEvents(); int countwidth = (nevents / 1000); FitEvent *nuisevent = input->FirstNuisanceEvent(); // Setup a TTree to save the event outputfile->cd(); TTree *eventtree = new TTree("nuisance_events", "nuisance_events"); // Add a flag that allows just splines to be saved. nuisevent->AddBranchesToTree(eventtree); // Save the spline reader splmerge->Write("spline_reader"); // Setup the spline TTree TTree *splinetree = new TTree("spline_tree", "spline_tree"); splmerge->AddCoefficientsToTree(splinetree); int lasttime = time(NULL); int i = 0; // Loop over all events and fill the TTree while (nuisevent) { // Calculate the weights for each parameter set splmerge->FillMergedSplines(i); // Save everything eventtree->Fill(); splinetree->Fill(); // Logging if (i % countwidth == 0) { std::ostringstream timestring; int timeelapsed = time(NULL) - lasttime; if (i != 0 and timeelapsed) { lasttime = time(NULL); int eventsleft = nevents - i; float speed = float(countwidth) / float(timeelapsed); float proj = (float(eventsleft) / float(speed)) / 60 / 60; timestring << proj << " hours remaining."; } - QLOG(REC, "Saved " << i << "/" << nevents << " nuisance spline events. " + NUIS_LOG(REC, "Saved " << i << "/" << nevents << " nuisance spline events. " << timestring.str()); } // Iterate i++; nuisevent = input->NextNuisanceEvent(); } // Save flux and close file outputfile->cd(); eventtree->Write(); splinetree->Write(); input->GetFluxHistogram()->Write("nuisance_fluxhist"); input->GetEventHistogram()->Write("nuisance_eventhist"); // Close Output outputfile->Close(); // Delete Inputs delete input; } //************************************* void SplineRoutines::TestSplines_1DEventScan() { //************************************* // Setup RW Engine if (fRW) delete fRW; SetupRWEngine(); // Make a spline RW Engine too. FitWeight *splweight = new FitWeight("splinerwaweight"); // std::vector splinekeys = Config::QueryKeys("spline"); std::vector parameterkeys = Config::QueryKeys("parameter"); TH1D *parhisttemplate = new TH1D("parhist", "parhist", parameterkeys.size(), 0.0, float(parameterkeys.size())); // Add Parameters for (size_t i = 0; i < parameterkeys.size(); i++) { nuiskey key = parameterkeys[i]; std::string parname = key.GetS("name"); std::string partype = key.GetS("type"); double nom = key.GetD("nominal"); parhisttemplate->SetBinContent(i + 1, nom); parhisttemplate->GetXaxis()->SetBinLabel(i + 1, parname.c_str()); splweight->IncludeDial(key.GetS("name"), kSPLINEPARAMETER, nom); splweight->SetDialValue(key.GetS("name"), key.GetD("nominal")); } splweight->Reconfigure(); // Make a high resolution spline set. std::vector nomvals = fRW->GetDialValues(); // int testres = FitPar::Config().GetParI("spline_test_resolution"); std::vector> scanparset_vals; std::vector scanparset_hists; // Loop over all params // Add Parameters for (size_t i = 0; i < parameterkeys.size(); i++) { nuiskey key = parameterkeys[i]; // Get Par Name std::string name = key.GetS("name"); if (!key.Has("low") or !key.Has("high") or !key.Has("step")) { continue; } // Push Back Scan double low = key.GetD("low"); double high = key.GetD("high"); double cur = low; double step = key.GetD("step"); while (cur <= high) { // Make new set std::vector newvals = nomvals; newvals[i] = cur; // Add to vects scanparset_vals.push_back(newvals); TH1D *parhist = (TH1D *)parhisttemplate->Clone(); for (size_t j = 0; j < newvals.size(); j++) { parhist->SetBinContent(j + 1, newvals[j]); } scanparset_hists.push_back(parhist); // Move to next one cur += step; } } // Print out the parameter set to test for (uint i = 0; i < scanparset_vals.size(); i++) { std::cout << "Parset " << i; for (uint j = 0; j < scanparset_vals[i].size(); j++) { std::cout << " " << scanparset_vals[i][j]; } std::cout << std::endl; } // Weight holders double *rawweights = new double[scanparset_vals.size()]; double *splweights = new double[scanparset_vals.size()]; double *difweights = new double[scanparset_vals.size()]; int nweights = scanparset_vals.size(); // int NParSets = scanparset_vals.size(); // Loop over all event I/O std::vector eventkeys = Config::QueryKeys("events"); for (size_t i = 0; i < eventkeys.size(); i++) { nuiskey key = eventkeys.at(i); // Get I/O std::string inputfilename = key.GetS("input"); if (inputfilename.empty()) { - QTHROW("No input given for set of input events!") + NUIS_ABORT("No input given for set of input events!") } std::string outputfilename = key.GetS("output"); if (outputfilename.empty()) { outputfilename = inputfilename + ".nuisance.root"; - QERROR(WRN, "No output give for set of output events! Saving to " + NUIS_ERR(WRN, "No output give for set of output events! Saving to " << outputfilename); } // Make a new input handler std::vector file_descriptor = GeneralUtils::ParseToStr(inputfilename, ":"); if (file_descriptor.size() != 2) { - QTHROW("File descriptor had no filetype declaration: \"" + NUIS_ABORT("File descriptor had no filetype declaration: \"" << inputfilename << "\". expected \"FILETYPE:file.root\""); } InputUtils::InputType inptype = InputUtils::ParseInputType(file_descriptor[0]); // Make handlers for input and output InputHandlerBase *input = InputUtils::CreateInputHandler( "rawevents", inptype, file_descriptor[1]); InputHandlerBase *output = InputUtils::CreateInputHandler( "splineevents", InputUtils::kEVSPLN_Input, outputfilename); // Get Base Events for each case. FitEvent *rawevent = input->FirstNuisanceEvent(); FitEvent *splevent = output->FirstNuisanceEvent(); // Setup outputfile std::string outputtest = outputfilename + ".splinetest.1DEventScan.root"; TFile *outputtestfile = new TFile(outputtest.c_str(), "RECREATE"); outputtestfile->cd(); // Save Parameter Sets for (size_t i = 0; i < scanparset_hists.size(); i++) { scanparset_hists[i]->Write(Form("Paramater_Set_%i", (int)i)); } // Save a TTree of weights and differences. TTree *weighttree = new TTree("weightscan", "weightscan"); // Make a branch for each weight set for (size_t i = 0; i < scanparset_hists.size(); i++) { weighttree->Branch(Form("RawWeights_Set_%i", (int)i), &rawweights[i], Form("RawWeights_Set_%i/D", (int)i)); weighttree->Branch(Form("SplineWeights_Set_%i", (int)i), &splweights[i], Form("SplineWeights_Set_%i/D", (int)i)); weighttree->Branch(Form("DifWeights_Set_%i", (int)i), &difweights[i], Form("DifWeights_Set_%i/D", (int)i)); } // Count // int i = 0; int nevents = input->GetNEvents(); int lasttime = time(NULL); // Load N Chunks of the Weights into Memory // Split into N processing chunks int nchunks = FitPar::Config().GetParI("spline_chunks"); if (nchunks <= 0) nchunks = 1; if (nchunks >= nevents / 2) nchunks = nevents / 2; std::cout << "Starting NChunks " << nchunks << std::endl; for (int ichunk = 0; ichunk < nchunks; ichunk++) { // Skip to only do one processing chunk // if (procchunk != -1 and procchunk != ichunk) continue; - QLOG(FIT, "On Processing Chunk " << ichunk); + NUIS_LOG(FIT, "On Processing Chunk " << ichunk); int neventsinchunk = nevents / nchunks; int loweventinchunk = neventsinchunk * ichunk; // int higheventinchunk = neventsinchunk * (ichunk + 1); double **allrawweights = new double *[neventsinchunk]; double **allsplweights = new double *[neventsinchunk]; double **alldifweights = new double *[neventsinchunk]; for (int k = 0; k < neventsinchunk; k++) { allrawweights[k] = new double[nweights]; allsplweights[k] = new double[nweights]; alldifweights[k] = new double[nweights]; } // Start Set Processing Here. for (int iset = 0; iset < nweights; iset++) { // Reconfigure fRW->SetAllDials(&scanparset_vals[iset][0], scanparset_vals[iset].size()); fRW->Reconfigure(); // Reconfigure spline RW splweight->SetAllDials(&scanparset_vals[iset][0], scanparset_vals[iset].size()); splweight->Reconfigure(); splevent->fSplineRead->SetNeedsReconfigure(true); // Could reorder this to save the weightconts in order instead of // reconfiguring per event. Loop over all events and fill the TTree for (int i = 0; i < neventsinchunk; i++) { rawevent = input->GetNuisanceEvent(i + loweventinchunk); splevent = output->GetNuisanceEvent(i + loweventinchunk); allrawweights[i][iset] = fRW->CalcWeight(rawevent); allsplweights[i][iset] = splweight->CalcWeight(splevent); alldifweights[i][iset] = allsplweights[i][iset] - allrawweights[i][iset]; } std::ostringstream timestring; int timeelapsed = time(NULL) - lasttime; if (timeelapsed) { lasttime = time(NULL); int setsleft = (nweights - iset - 1) + (nweights * (nchunks - ichunk - 1)); float proj = (float(setsleft) * timeelapsed) / 60 / 60; timestring << setsleft << " sets remaining. Last one took " << timeelapsed << ". " << proj << " hours remaining."; } - QLOG(REC, "Processed Set " << iset << "/" << nweights << " in chunk " + NUIS_LOG(REC, "Processed Set " << iset << "/" << nweights << " in chunk " << ichunk << "/" << nchunks << " " << timestring.str()); } // Fill weights for this chunk into the TTree for (int k = 0; k < neventsinchunk; k++) { for (int l = 0; l < nweights; l++) { rawweights[l] = allrawweights[k][l]; splweights[l] = allsplweights[k][l]; difweights[l] = alldifweights[k][l]; } weighttree->Fill(); } } // Loop over nchunks // Loop over parameter sets // Set All Dials and reconfigure // Loop over events in chunk // Fill Chunkweightcontainers // Once all dials are done, fill the weight tree // Iterator to next chunk outputtestfile->cd(); weighttree->Write(); outputtestfile->Close(); } } /* // Make a high resolution spline set. std::vector nomvals = fRW->GetDialValues(); int testres = FitPar::Config().GetParI("spline_test_resolution"); std::vector< std::vector > scanparset_vals; std::vector< TH1D* > scanparset_hists; // Loop over all params // Add Parameters for (size_t i = 0; i < parameterkeys.size(); i++) { nuiskey key = parameterkeys[i]; // Get Par Name std::string name = key.GetS("name"); if (!key.Has("low") or !key.Has("high") or !key.Has("step")) { continue; } // Push Back Scan double low = key.GetD("low"); double high = key.GetD("high"); double cur = low; double step = key.GetD("step"); while (cur <= high) { // Make new set std::vector newvals = nomvals; newvals[i] = cur; // Add to vects scanparset_vals.push_back(newvals); TH1D* parhist = (TH1D*)parhisttemplate->Clone(); for (size_t j = 0; j < newvals.size(); j++) { parhist->SetBinContent(j + 1, newvals[j]); } scanparset_hists.push_back(parhist); // Move to next one cur += step; } } // Print out the parameter set to test for (int i = 0; i < scanparset_vals.size(); i++) { std::cout << "Parset " << i; for (int j = 0 ; j < scanparset_vals[i].size(); j++) { std::cout << " " << scanparset_vals[i][j]; } std::cout << std::endl; } // Weight holders double* rawweights = new double[scanparset_vals.size()]; double* splweights = new double[scanparset_vals.size()]; double* difweights = new double[scanparset_vals.size()]; int NParSets = scanparset_vals.size(); // Loop over all event I/O std::vector eventkeys = Config::QueryKeys("events"); for (size_t i = 0; i < eventkeys.size(); i++) { nuiskey key = eventkeys.at(i); // Get I/O std::string inputfilename = key.GetS("input"); if (inputfilename.empty()) { ERR(FTL) << "No input given for set of input events!" << std::endl; throw; } std::string outputfilename = key.GetS("output"); if (outputfilename.empty()) { outputfilename = inputfilename + ".nuisance.root"; ERR(FTL) << "No output give for set of output events! Saving to " << outputfilename << std::endl; } // Make a new input handler std::vector file_descriptor = GeneralUtils::ParseToStr(inputfilename, ":"); if (file_descriptor.size() != 2) { ERR(FTL) << "File descriptor had no filetype declaration: \"" << inputfilename << "\". expected \"FILETYPE:file.root\"" << std::endl; throw; } InputUtils::InputType inptype = InputUtils::ParseInputType(file_descriptor[0]); // Make handlers for input and output InputHandlerBase* input = InputUtils::CreateInputHandler("rawevents", inptype, file_descriptor[1]); InputHandlerBase* output = InputUtils::CreateInputHandler("splineevents", InputUtils::kEVSPLN_Input, outputfilename); // Get Base Events for each case. FitEvent* rawevent = input->FirstNuisanceEvent(); FitEvent* splevent = output->FirstNuisanceEvent(); // Setup outputfile std::string outputtest = outputfilename + ".splinetest.1DEventScan.root"; TFile* outputtestfile = new TFile(outputtest.c_str(), "RECREATE"); outputtestfile->cd(); // Save Parameter Sets for (size_t i = 0; i < scanparset_hists.size(); i++) { scanparset_hists[i]->Write(Form("Paramater_Set_%i", (int)i)); } // Save a TTree of weights and differences. TTree* weighttree = new TTree("weightscan", "weightscan"); // Make a branch for each weight set for (size_t i = 0; i < scanparset_hists.size(); i++) { weighttree->Branch(Form("RawWeights_Set_%i", (int)i), &rawweights[i], Form("RawWeights_Set_%i/D", (int)i) ); weighttree->Branch(Form("SplineWeights_Set_%i", (int)i), &splweights[i], Form("SplineWeights_Set_%i/D", (int)i) ); weighttree->Branch(Form("DifWeights_Set_%i", (int)i), &difweights[i], Form("DifWeights_Set_%i/D", (int)i) ); } // Count int i = 0; int nevents = input->GetNEvents(); while (rawevent and splevent) { // Loop over 1D parameter sets. for (size_t j = 0; j < scanparset_vals.size(); j++) { // Reconfigure fRW->SetAllDials(&scanparset_vals[j][0], scanparset_vals[j].size()); fRW->Reconfigure(); // Reconfigure spline RW splweight->SetAllDials(&scanparset_vals[j][0], scanparset_vals[j].size()); splweight->Reconfigure(); splevent->fSplineRead->SetNeedsReconfigure(true); // Calc weight for both events rawweights[j] = fRW->CalcWeight(rawevent); splweights[j] = splweight->CalcWeight(splevent); difweights[j] = splweights[j] - rawweights[j]; } if (i % 1000 == 0) { LOG(FIT) << "Processed " << i << "/" << nevents << std::endl; } // Fill Array weighttree->Fill(); // Iterate to next event. i++; rawevent = input->NextNuisanceEvent(); splevent = output->NextNuisanceEvent(); } outputtestfile->cd(); weighttree->Write(); outputtestfile->Close(); } } */ //************************************* void SplineRoutines::TestSplines_NDEventThrow() { //************************************* // Setup RW Engine if (fRW) delete fRW; SetupRWEngine(); // Make a spline RW Engine too. FitWeight *splweight = new FitWeight("splinerwaweight"); std::vector parameterkeys = Config::QueryKeys("parameter"); TH1D *parhisttemplate = new TH1D("parhist", "parhist", parameterkeys.size(), 0.0, float(parameterkeys.size())); // Add Parameters for (size_t i = 0; i < parameterkeys.size(); i++) { nuiskey key = parameterkeys[i]; std::string parname = key.GetS("name"); std::string partype = key.GetS("type"); double nom = key.GetD("nominal"); parhisttemplate->SetBinContent(i + 1, nom); parhisttemplate->GetXaxis()->SetBinLabel(i + 1, parname.c_str()); splweight->IncludeDial(key.GetS("name"), kSPLINEPARAMETER, nom); splweight->SetDialValue(key.GetS("name"), key.GetD("nominal")); } splweight->Reconfigure(); // Make a high resolution spline set. std::vector nomvals = fRW->GetDialValues(); // int testres = FitPar::Config().GetParI("spline_test_resolution"); std::vector scanparset_names; std::vector> scanparset_vals; std::vector scanparset_hists; // Loop over all params // Add Parameters int nthrows = FitPar::Config().GetParI("spline_test_throws"); for (int i = 0; i < nthrows; i++) { std::vector newvals = nomvals; for (size_t j = 0; j < parameterkeys.size(); j++) { nuiskey key = parameterkeys[j]; if (!key.Has("low") or !key.Has("high") or !key.Has("step")) { continue; } // Push Back Scan double low = key.GetD("low"); double high = key.GetD("high"); newvals[j] = gRandom->Uniform(low, high); } // Add to vects scanparset_vals.push_back(newvals); TH1D *parhist = (TH1D *)parhisttemplate->Clone(); for (size_t j = 0; j < newvals.size(); j++) { parhist->SetBinContent(j + 1, newvals[j]); } scanparset_hists.push_back(parhist); } // Print out the parameter set to test for (uint i = 0; i < scanparset_vals.size(); i++) { std::cout << "Parset " << i; for (uint j = 0; j < scanparset_vals[i].size(); j++) { std::cout << " " << scanparset_vals[i][j]; } std::cout << std::endl; } // Weight holders double *rawweights = new double[scanparset_vals.size()]; double *splweights = new double[scanparset_vals.size()]; double *difweights = new double[scanparset_vals.size()]; int nweights = scanparset_vals.size(); // int NParSets = scanparset_vals.size(); // Loop over all event I/O std::vector eventkeys = Config::QueryKeys("events"); for (size_t i = 0; i < eventkeys.size(); i++) { nuiskey key = eventkeys.at(i); // Get I/O std::string inputfilename = key.GetS("input"); if (inputfilename.empty()) { - QTHROW("No input given for set of input events!"); + NUIS_ABORT("No input given for set of input events!"); } std::string outputfilename = key.GetS("output"); if (outputfilename.empty()) { outputfilename = inputfilename + ".nuisance.root"; - QERROR(WRN, "No output give for set of output events! Saving to " + NUIS_ERR(WRN, "No output give for set of output events! Saving to " << outputfilename); } // Make a new input handler std::vector file_descriptor = GeneralUtils::ParseToStr(inputfilename, ":"); if (file_descriptor.size() != 2) { - QTHROW("File descriptor had no filetype declaration: \"" + NUIS_ABORT("File descriptor had no filetype declaration: \"" << inputfilename << "\". expected \"FILETYPE:file.root\""); } InputUtils::InputType inptype = InputUtils::ParseInputType(file_descriptor[0]); // Make handlers for input and output InputHandlerBase *input = InputUtils::CreateInputHandler( "rawevents", inptype, file_descriptor[1]); InputHandlerBase *output = InputUtils::CreateInputHandler( "splineevents", InputUtils::kEVSPLN_Input, outputfilename); // Get Base Events for each case. FitEvent *rawevent = input->FirstNuisanceEvent(); FitEvent *splevent = output->FirstNuisanceEvent(); // Setup outputfile std::string outputtest = outputfilename + ".splinetest.NDEventThrow.root"; TFile *outputtestfile = new TFile(outputtest.c_str(), "RECREATE"); outputtestfile->cd(); // Save Parameter Sets for (size_t i = 0; i < scanparset_hists.size(); i++) { scanparset_hists[i]->Write(Form("Paramater_Set_%i", (int)i)); } // Save a TTree of weights and differences. TTree *weighttree = new TTree("weightscan", "weightscan"); // Make a branch for each weight set for (size_t i = 0; i < scanparset_hists.size(); i++) { weighttree->Branch(Form("RawWeights_Set_%i", (int)i), &rawweights[i], Form("RawWeights_Set_%i/D", (int)i)); weighttree->Branch(Form("SplineWeights_Set_%i", (int)i), &splweights[i], Form("SplineWeights_Set_%i/D", (int)i)); weighttree->Branch(Form("DifWeights_Set_%i", (int)i), &difweights[i], Form("DifWeights_Set_%i/D", (int)i)); } // Count // int i = 0; int nevents = input->GetNEvents(); int lasttime = time(NULL); // Load N Chunks of the Weights into Memory // Split into N processing chunks int nchunks = FitPar::Config().GetParI("spline_chunks"); if (nchunks <= 0) nchunks = 1; if (nchunks >= nevents / 2) nchunks = nevents / 2; std::cout << "Starting NChunks " << nchunks << std::endl; for (int ichunk = 0; ichunk < nchunks; ichunk++) { // Skip to only do one processing chunk // if (procchunk != -1 and procchunk != ichunk) continue; - QLOG(FIT, "On Processing Chunk " << ichunk); + NUIS_LOG(FIT, "On Processing Chunk " << ichunk); int neventsinchunk = nevents / nchunks; int loweventinchunk = neventsinchunk * ichunk; // int higheventinchunk = neventsinchunk * (ichunk + 1); double **allrawweights = new double *[neventsinchunk]; double **allsplweights = new double *[neventsinchunk]; double **alldifweights = new double *[neventsinchunk]; for (int k = 0; k < neventsinchunk; k++) { allrawweights[k] = new double[nweights]; allsplweights[k] = new double[nweights]; alldifweights[k] = new double[nweights]; } // Start Set Processing Here. for (int iset = 0; iset < nweights; iset++) { // Reconfigure fRW->SetAllDials(&scanparset_vals[iset][0], scanparset_vals[iset].size()); fRW->Reconfigure(); // Reconfigure spline RW splweight->SetAllDials(&scanparset_vals[iset][0], scanparset_vals[iset].size()); splweight->Reconfigure(); splevent->fSplineRead->SetNeedsReconfigure(true); // Could reorder this to save the weightconts in order instead of // reconfiguring per event. Loop over all events and fill the TTree for (int i = 0; i < neventsinchunk; i++) { rawevent = input->GetNuisanceEvent(i + loweventinchunk); splevent = output->GetNuisanceEvent(i + loweventinchunk); allrawweights[i][iset] = fRW->CalcWeight(rawevent); allsplweights[i][iset] = splweight->CalcWeight(splevent); alldifweights[i][iset] = allsplweights[i][iset] - allrawweights[i][iset]; } std::ostringstream timestring; int timeelapsed = time(NULL) - lasttime; if (timeelapsed) { lasttime = time(NULL); int setsleft = (nweights - iset - 1) + (nweights * (nchunks - ichunk - 1)); float proj = (float(setsleft) * timeelapsed) / 60 / 60; timestring << setsleft << " sets remaining. Last one took " << timeelapsed << ". " << proj << " hours remaining."; } - QLOG(REC, "Processed Set " << iset << "/" << nweights << " in chunk " + NUIS_LOG(REC, "Processed Set " << iset << "/" << nweights << " in chunk " << ichunk << "/" << nchunks << " " << timestring.str()); } // Fill weights for this chunk into the TTree for (int k = 0; k < neventsinchunk; k++) { for (int l = 0; l < nweights; l++) { rawweights[l] = allrawweights[k][l]; splweights[l] = allsplweights[k][l]; difweights[l] = alldifweights[k][l]; } weighttree->Fill(); } } // Loop over nchunks // Loop over parameter sets // Set All Dials and reconfigure // Loop over events in chunk // Fill Chunkweightcontainers // Once all dials are done, fill the weight tree // Iterator to next chunk outputtestfile->cd(); weighttree->Write(); outputtestfile->Close(); } } void SplineRoutines::SaveSplinePlots() { if (fRW) delete fRW; SetupRWEngine(); // Setup the spline reader SplineWriter *splwrite = new SplineWriter(fRW); std::vector splinekeys = Config::QueryKeys("spline"); // Add splines to splinewriter for (std::vector::iterator iter = splinekeys.begin(); iter != splinekeys.end(); iter++) { nuiskey splkey = (*iter); // Add Spline Info To Reader splwrite->AddSpline(splkey); } splwrite->SetupSplineSet(); // Event Loop // Loop over all events and calculate weights for each parameter set. // Generate a set of nominal events // Method, Loop over inputs, create input handler, then create a ttree std::vector eventkeys = Config::QueryKeys("events"); for (size_t i = 0; i < eventkeys.size(); i++) { nuiskey key = eventkeys.at(i); // Get I/O std::string inputfilename = key.GetS("input"); if (inputfilename.empty()) { - QTHROW("No input given for set of input events!"); + NUIS_ABORT("No input given for set of input events!"); } std::string outputfilename = key.GetS("output"); if (outputfilename.empty()) { outputfilename = inputfilename + ".nuisance.root"; - QERROR(WRN, "No output give for set of output events! Saving to " + NUIS_ERR(WRN, "No output give for set of output events! Saving to " << outputfilename); } // Make new outputfile outputfilename += ".SplinePlots.root"; TFile *outputfile = new TFile(outputfilename.c_str(), "RECREATE"); outputfile->cd(); // Make a new input handler std::vector file_descriptor = GeneralUtils::ParseToStr(inputfilename, ":"); if (file_descriptor.size() != 2) { - QTHROW("File descriptor had no filetype declaration: \"" + NUIS_ABORT("File descriptor had no filetype declaration: \"" << inputfilename << "\". expected \"FILETYPE:file.root\""); } InputUtils::InputType inptype = InputUtils::ParseInputType(file_descriptor[0]); InputHandlerBase *input = InputUtils::CreateInputHandler( "eventsaver", inptype, file_descriptor[1]); // Get info from inputhandler int nevents = input->GetNEvents(); int countwidth = (nevents / 1000); FitEvent *nuisevent = input->FirstNuisanceEvent(); outputfile->cd(); // int lasttime = time(NULL); TCanvas *fitcanvas = NULL; // Loop over all events and fill the TTree while (nuisevent) { // std::cout << "Fitting event " << i << std::endl; // Calculate the weights for each parameter set splwrite->GetWeightsForEvent(nuisevent); splwrite->FitSplinesForEvent(fitcanvas, true); if (fitcanvas) { outputfile->cd(); fitcanvas->Write(Form("Event_SplineCanvas_%i", (int)i)); } // Logging if (i % countwidth == 0) { - QLOG(REC, + NUIS_LOG(REC, "Saved " << i << "/" << nevents << " nuisance spline plots. "); } // Iterate i++; nuisevent = input->NextNuisanceEvent(); } // Save flux and close file outputfile->cd(); // Close Output outputfile->Close(); // Delete Inputs delete input; } // remove Keys eventkeys.clear(); } void SplineRoutines::TestSplines_NDLikelihoodThrow() { // Setup RW Engine if (fRW) delete fRW; SetupRWEngine(); // Make a spline RW Engine too. FitWeight *splweight = new FitWeight("splinerwaweight"); std::vector parameterkeys = Config::QueryKeys("parameter"); TH1D *parhisttemplate = new TH1D("parhist", "parhist", parameterkeys.size(), 0.0, float(parameterkeys.size())); // Add Parameters for (size_t i = 0; i < parameterkeys.size(); i++) { nuiskey key = parameterkeys[i]; std::string parname = key.GetS("name"); std::string partype = key.GetS("type"); double nom = key.GetD("nominal"); parhisttemplate->SetBinContent(i + 1, nom); parhisttemplate->GetXaxis()->SetBinLabel(i + 1, parname.c_str()); splweight->IncludeDial(key.GetS("name"), kSPLINEPARAMETER, nom); splweight->SetDialValue(key.GetS("name"), key.GetD("nominal")); } splweight->Reconfigure(); // Make a high resolution spline set. std::vector nomvals = fRW->GetDialValues(); // int testres = FitPar::Config().GetParI("spline_test_resolution"); std::vector scanparset_names; std::vector> scanparset_vals; std::vector scanparset_hists; // Loop over all params // Add Parameters int nthrows = FitPar::Config().GetParI("spline_test_throws"); for (int i = 0; i < nthrows; i++) { std::vector newvals = nomvals; for (size_t j = 0; j < parameterkeys.size(); j++) { nuiskey key = parameterkeys[j]; if (!key.Has("low") or !key.Has("high") or !key.Has("step")) { continue; } // Push Back Scan double low = key.GetD("low"); double high = key.GetD("high"); newvals[j] = gRandom->Uniform(low, high); } // Add to vects scanparset_vals.push_back(newvals); TH1D *parhist = (TH1D *)parhisttemplate->Clone(); for (size_t j = 0; j < newvals.size(); j++) { parhist->SetBinContent(j + 1, newvals[j]); } scanparset_hists.push_back(parhist); } // Print out the parameter set to test for (uint i = 0; i < scanparset_vals.size(); i++) { std::cout << "Parset " << i; for (uint j = 0; j < scanparset_vals[i].size(); j++) { std::cout << " " << scanparset_vals[i][j]; } std::cout << std::endl; } // Make a new set of Raw/Spline Sample Keys std::vector eventkeys = Config::QueryKeys("events"); std::vector testkeys = Config::QueryKeys("sampletest"); std::vector rawkeys; std::vector splkeys; for (std::vector::iterator iter = testkeys.begin(); iter != testkeys.end(); iter++) { nuiskey key = (*iter); std::string samplename = key.GetS("name"); std::string eventsid = key.GetS("inputid"); nuiskey eventskey = Config::QueryLastKey("events", "id=" + eventsid); std::string rawfile = eventskey.GetS("input"); std::string splfile = eventskey.GetS("output"); nuiskey rawkeytemp = Config::CreateKey("sample"); rawkeytemp.SetS("name", samplename); rawkeytemp.SetS("input", rawfile); nuiskey splkeytemp = Config::CreateKey("sample"); splkeytemp.SetS("name", samplename); splkeytemp.SetS("input", "EVSPLN:" + splfile); rawkeys.push_back(rawkeytemp); splkeys.push_back(splkeytemp); } if (fOutputRootFile) delete fOutputRootFile; fOutputRootFile = new TFile(fOutputFile.c_str(), "RECREATE"); fOutputRootFile->ls(); // Make two new JointFCN JointFCN *rawfcn = new JointFCN(rawkeys, fOutputRootFile); JointFCN *splfcn = new JointFCN(splkeys, fOutputRootFile); // Create iteration tree in output file fOutputRootFile->cd(); rawfcn->CreateIterationTree("raw_iterations", fRW); splfcn->CreateIterationTree("spl_iterations", splweight); // Loop over parameter sets. for (size_t j = 0; j < scanparset_vals.size(); j++) { FitBase::SetRW(fRW); double rawtotal = rawfcn->DoEval(&scanparset_vals[j][0]); FitBase::SetRW(splweight); double spltotal = splfcn->DoEval(&scanparset_vals[j][0]); - QLOG(FIT, "RAW SPLINE DIF = " << rawtotal << " " << spltotal << " " + NUIS_LOG(FIT, "RAW SPLINE DIF = " << rawtotal << " " << spltotal << " " << spltotal - rawtotal); } fOutputRootFile->cd(); rawfcn->WriteIterationTree(); splfcn->WriteIterationTree(); } void SplineRoutines::TestSplines_1DLikelihoodScan() { // Setup RW Engine. if (fRW) delete fRW; SetupRWEngine(); // Setup Parameter Set. // Make a spline RW Engine too. FitWeight *splweight = new FitWeight("splinerwaweight"); // std::vector splinekeys = Config::QueryKeys("spline"); std::vector parameterkeys = Config::QueryKeys("parameter"); TH1D *parhisttemplate = new TH1D("parhist", "parhist", parameterkeys.size(), 0.0, float(parameterkeys.size())); // Add Parameters for (size_t i = 0; i < parameterkeys.size(); i++) { nuiskey key = parameterkeys[i]; std::string parname = key.GetS("name"); std::string partype = key.GetS("type"); double nom = key.GetD("nominal"); parhisttemplate->SetBinContent(i + 1, nom); parhisttemplate->GetXaxis()->SetBinLabel(i + 1, parname.c_str()); splweight->IncludeDial(key.GetS("name"), kSPLINEPARAMETER, nom); splweight->SetDialValue(key.GetS("name"), key.GetD("nominal")); } splweight->Reconfigure(); // Make a high resolution spline set. std::vector nomvals = fRW->GetDialValues(); // int testres = FitPar::Config().GetParI("spline_test_resolution"); std::vector> scanparset_vals; std::vector scanparset_hists; // Loop over all params // Add Parameters for (size_t i = 0; i < parameterkeys.size(); i++) { nuiskey key = parameterkeys[i]; // Get Par Name std::string name = key.GetS("name"); if (!key.Has("low") or !key.Has("high") or !key.Has("step")) { continue; } // Push Back Scan double low = key.GetD("low"); double high = key.GetD("high"); double cur = low; double step = key.GetD("step"); while (cur <= high) { // Make new set std::vector newvals = nomvals; newvals[i] = cur; // Add to vects scanparset_vals.push_back(newvals); TH1D *parhist = (TH1D *)parhisttemplate->Clone(); for (size_t j = 0; j < newvals.size(); j++) { parhist->SetBinContent(j + 1, newvals[j]); } scanparset_hists.push_back(parhist); // Move to next one cur += step; } } // Print out the parameter set to test for (uint i = 0; i < scanparset_vals.size(); i++) { std::cout << "Parset " << i; for (uint j = 0; j < scanparset_vals[i].size(); j++) { std::cout << " " << scanparset_vals[i][j]; } std::cout << std::endl; } // Make a new set of Raw/Spline Sample Keys std::vector eventkeys = Config::QueryKeys("events"); std::vector testkeys = Config::QueryKeys("sampletest"); std::vector rawkeys; std::vector splkeys; for (std::vector::iterator iter = testkeys.begin(); iter != testkeys.end(); iter++) { nuiskey key = (*iter); std::string samplename = key.GetS("name"); std::string eventsid = key.GetS("inputid"); nuiskey eventskey = Config::QueryLastKey("events", "id=" + eventsid); std::string rawfile = eventskey.GetS("input"); std::string splfile = eventskey.GetS("output"); nuiskey rawkeytemp = Config::CreateKey("sample"); rawkeytemp.SetS("name", samplename); rawkeytemp.SetS("input", rawfile); nuiskey splkeytemp = Config::CreateKey("sample"); splkeytemp.SetS("name", samplename); splkeytemp.SetS("input", "EVSPLN:" + splfile); rawkeys.push_back(rawkeytemp); splkeys.push_back(splkeytemp); } if (fOutputRootFile) delete fOutputRootFile; fOutputRootFile = new TFile(fOutputFile.c_str(), "RECREATE"); fOutputRootFile->ls(); // Make two new JointFCN JointFCN *rawfcn = new JointFCN(rawkeys, fOutputRootFile); JointFCN *splfcn = new JointFCN(splkeys, fOutputRootFile); // Create iteration tree in output file fOutputRootFile->cd(); rawfcn->CreateIterationTree("raw_iterations", fRW); splfcn->CreateIterationTree("spl_iterations", splweight); // Loop over parameter sets. for (size_t j = 0; j < scanparset_vals.size(); j++) { FitBase::SetRW(fRW); double rawtotal = rawfcn->DoEval(&scanparset_vals[j][0]); FitBase::SetRW(splweight); double spltotal = splfcn->DoEval(&scanparset_vals[j][0]); - QLOG(FIT, "RAW SPLINE DIF = " << rawtotal << " " << spltotal << " " + NUIS_LOG(FIT, "RAW SPLINE DIF = " << rawtotal << " " << spltotal << " " << spltotal - rawtotal); } fOutputRootFile->cd(); rawfcn->WriteIterationTree(); splfcn->WriteIterationTree(); } /* MISC Functions */ //************************************* int SplineRoutines::GetStatus() { //************************************* return 0; } diff --git a/src/Routines/SystematicRoutines.cxx b/src/Routines/SystematicRoutines.cxx index 679b7e8..2c0e39b 100755 --- a/src/Routines/SystematicRoutines.cxx +++ b/src/Routines/SystematicRoutines.cxx @@ -1,1488 +1,1488 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "SystematicRoutines.h" void SystematicRoutines::Init() { fInputFile = ""; fInputRootFile = NULL; fOutputFile = ""; fOutputRootFile = NULL; fCovar = fCovarFree = NULL; fCorrel = fCorrelFree = NULL; fDecomp = fDecompFree = NULL; fStrategy = "ErrorBands"; fRoutines.clear(); fRoutines.push_back("ErrorBands"); fCardFile = ""; fFakeDataInput = ""; fSampleFCN = NULL; fAllowedRoutines = ("ErrorBands,PlotLimits"); }; SystematicRoutines::~SystematicRoutines(){}; SystematicRoutines::SystematicRoutines(int argc, char *argv[]) { // Initialise Defaults Init(); nuisconfig configuration = Config::Get(); // Default containers std::string cardfile = ""; std::string maxevents = "-1"; int errorcount = 0; int verbocount = 0; std::vector xmlcmds; std::vector configargs; fNThrows = 250; fStartThrows = 0; fThrowString = ""; // Make easier to handle arguments. std::vector args = GeneralUtils::LoadCharToVectStr(argc, argv); ParserUtils::ParseArgument(args, "-c", fCardFile, true); ParserUtils::ParseArgument(args, "-o", fOutputFile, false, false); ParserUtils::ParseArgument(args, "-n", maxevents, false, false); ParserUtils::ParseArgument(args, "-f", fStrategy, false, false); ParserUtils::ParseArgument(args, "-d", fFakeDataInput, false, false); ParserUtils::ParseArgument(args, "-s", fStartThrows, false, false); ParserUtils::ParseArgument(args, "-t", fNThrows, false, false); ParserUtils::ParseArgument(args, "-p", fThrowString, false, false); ParserUtils::ParseArgument(args, "-i", xmlcmds); ParserUtils::ParseArgument(args, "-q", configargs); ParserUtils::ParseCounter(args, "e", errorcount); ParserUtils::ParseCounter(args, "v", verbocount); ParserUtils::CheckBadArguments(args); // Add extra defaults if none given if (fCardFile.empty() and xmlcmds.empty()) { - QTHROW("No input supplied!"); + NUIS_ABORT("No input supplied!"); } if (fOutputFile.empty() and !fCardFile.empty()) { fOutputFile = fCardFile + ".root"; - QERROR(WRN, "No output supplied so saving it to: " << fOutputFile); + NUIS_ERR(WRN, "No output supplied so saving it to: " << fOutputFile); } else if (fOutputFile.empty()) { - QTHROW("No output file or cardfile supplied!"); + NUIS_ABORT("No output file or cardfile supplied!"); } // Configuration Setup ============================= // Check no comp key is available if (Config::Get().GetNodes("nuiscomp").empty()) { fCompKey = Config::Get().CreateNode("nuiscomp"); } else { fCompKey = Config::Get().GetNodes("nuiscomp")[0]; } if (!fCardFile.empty()) fCompKey.Set("cardfile", fCardFile); if (!fOutputFile.empty()) fCompKey.Set("outputfile", fOutputFile); if (!fStrategy.empty()) fCompKey.Set("strategy", fStrategy); // Load XML Cardfile configuration.LoadSettings(fCompKey.GetS("cardfile"), ""); // Add Config Args for (size_t i = 0; i < configargs.size(); i++) { configuration.OverrideConfig(configargs[i]); } if (maxevents.compare("-1")) { configuration.OverrideConfig("MAXEVENTS=" + maxevents); } // Finish configuration XML configuration.FinaliseSettings(fCompKey.GetS("outputfile") + ".xml"); // Add Error Verbo Lines verbocount += Config::GetParI("VERBOSITY"); errorcount += Config::GetParI("ERROR"); std::cout << "[ NUISANCE ]: Setting VERBOSITY=" << verbocount << std::endl; std::cout << "[ NUISANCE ]: Setting ERROR=" << errorcount << std::endl; SETVERBOSITY(verbocount); // Proper Setup if (fStrategy.find("ErrorBands") != std::string::npos || fStrategy.find("MergeErrors") != std::string::npos) { fOutputRootFile = new TFile(fCompKey.GetS("outputfile").c_str(), "RECREATE"); } // fOutputRootFile = new TFile(fCompKey.GetS("outputfile").c_str(), // "RECREATE"); SetupSystematicsFromXML(); SetupCovariance(); SetupRWEngine(); SetupFCN(); GetCovarFromFCN(); // Run(); return; }; void SystematicRoutines::SetupSystematicsFromXML() { - QLOG(FIT, "Setting up nuismin"); + NUIS_LOG(FIT, "Setting up nuismin"); // Setup Parameters ------------------------------------------ std::vector parkeys = Config::QueryKeys("parameter"); if (!parkeys.empty()) { - QLOG(FIT, "Number of parameters : " << parkeys.size()); + NUIS_LOG(FIT, "Number of parameters : " << parkeys.size()); } for (size_t i = 0; i < parkeys.size(); i++) { nuiskey key = parkeys.at(i); // Check for type,name,nom if (!key.Has("type")) { - QTHROW("No type given for parameter " << i); + NUIS_ABORT("No type given for parameter " << i); } else if (!key.Has("name")) { - QTHROW("No name given for parameter " << i); + NUIS_ABORT("No name given for parameter " << i); } else if (!key.Has("nominal")) { - QTHROW("No nominal given for parameter " << i); + NUIS_ABORT("No nominal given for parameter " << i); } // Get Inputs std::string partype = key.GetS("type"); std::string parname = key.GetS("name"); double parnom = key.GetD("nominal"); double parlow = parnom - 1; double parhigh = parnom + 1; double parstep = 1; // Override if state not given if (!key.Has("state")) { key.SetS("state", "FIX"); } std::string parstate = key.GetS("state"); // Extra limits if (key.Has("low")) { parlow = key.GetD("low"); parhigh = key.GetD("high"); parstep = key.GetD("step"); - QLOG(FIT, "Read " << partype << " : " << parname << " = " << parnom + NUIS_LOG(FIT, "Read " << partype << " : " << parname << " = " << parnom << " : " << parlow << " < p < " << parhigh << " : " << parstate); } else { - QLOG(FIT, "Read " << partype << " : " << parname << " = " << parnom + NUIS_LOG(FIT, "Read " << partype << " : " << parname << " = " << parnom << " : " << parstate); } // Run Parameter Conversion if needed if (parstate.find("ABS") != std::string::npos) { parnom = FitBase::RWAbsToSigma(partype, parname, parnom); parlow = FitBase::RWAbsToSigma(partype, parname, parlow); parhigh = FitBase::RWAbsToSigma(partype, parname, parhigh); parstep = FitBase::RWAbsToSigma(partype, parname, parstep); } else if (parstate.find("FRAC") != std::string::npos) { parnom = FitBase::RWFracToSigma(partype, parname, parnom); parlow = FitBase::RWFracToSigma(partype, parname, parlow); parhigh = FitBase::RWFracToSigma(partype, parname, parhigh); parstep = FitBase::RWFracToSigma(partype, parname, parstep); } // Push into vectors fParams.push_back(parname); fTypeVals[parname] = FitBase::ConvDialType(partype); fStartVals[parname] = parnom; fCurVals[parname] = parnom; fErrorVals[parname] = 0.0; fStateVals[parname] = parstate; bool fixstate = parstate.find("FIX") != std::string::npos; fFixVals[parname] = fixstate; fStartFixVals[parname] = fFixVals[parname]; fMinVals[parname] = parlow; fMaxVals[parname] = parhigh; fStepVals[parname] = parstep; } // Setup Samples ---------------------------------------------- std::vector samplekeys = Config::QueryKeys("sample"); if (!samplekeys.empty()) { - QLOG(FIT, "Number of samples : " << samplekeys.size()); + NUIS_LOG(FIT, "Number of samples : " << samplekeys.size()); } for (size_t i = 0; i < samplekeys.size(); i++) { nuiskey key = samplekeys.at(i); // Get Sample Options std::string samplename = key.GetS("name"); std::string samplefile = key.GetS("input"); std::string sampletype = key.Has("type") ? key.GetS("type") : "DEFAULT"; double samplenorm = key.Has("norm") ? key.GetD("norm") : 1.0; // Print out - QLOG(FIT, "Read sample info " << i << " : " << samplename << std::endl + NUIS_LOG(FIT, "Read sample info " << i << " : " << samplename << std::endl << "\t\t input -> " << samplefile << std::endl << "\t\t state -> " << sampletype << std::endl << "\t\t norm -> " << samplenorm); // If FREE add to parameters otherwise continue if (sampletype.find("FREE") == std::string::npos) { continue; } // Form norm dial from samplename + sampletype + "_norm"; std::string normname = samplename + "_norm"; // Check normname not already present if (fTypeVals.find(normname) != fTypeVals.end()) { continue; } // Add new norm dial to list if its passed above checks fParams.push_back(normname); fTypeVals[normname] = kNORM; fStateVals[normname] = sampletype; fCurVals[normname] = samplenorm; fErrorVals[normname] = 0.0; fMinVals[normname] = 0.1; fMaxVals[normname] = 10.0; fStepVals[normname] = 0.5; bool state = sampletype.find("FREE") == std::string::npos; fFixVals[normname] = state; fStartFixVals[normname] = state; } // Setup Fake Parameters ----------------------------- std::vector fakekeys = Config::QueryKeys("fakeparameter"); if (!fakekeys.empty()) { - QLOG(FIT, "Number of fake parameters : " << fakekeys.size()); + NUIS_LOG(FIT, "Number of fake parameters : " << fakekeys.size()); } for (size_t i = 0; i < fakekeys.size(); i++) { nuiskey key = fakekeys.at(i); // Check for type,name,nom if (!key.Has("name")) { - QTHROW("No name given for fakeparameter " << i); + NUIS_ABORT("No name given for fakeparameter " << i); } else if (!key.Has("nom")) { - QTHROW("No nominal given for fakeparameter " << i); + NUIS_ABORT("No nominal given for fakeparameter " << i); } // Get Inputs std::string parname = key.GetS("name"); double parnom = key.GetD("nom"); // Push into vectors fFakeVals[parname] = parnom; } } /* Setup Functions */ //************************************* void SystematicRoutines::SetupRWEngine() { //************************************* for (UInt_t i = 0; i < fParams.size(); i++) { std::string name = fParams[i]; FitBase::GetRW()->IncludeDial(name, fTypeVals.at(name)); } UpdateRWEngine(fStartVals); return; } //************************************* void SystematicRoutines::SetupFCN() { //************************************* - QLOG(FIT, "Making the jointFCN"); + NUIS_LOG(FIT, "Making the jointFCN"); if (fSampleFCN) delete fSampleFCN; fSampleFCN = new JointFCN(fOutputRootFile); SetFakeData(); return; } //************************************* void SystematicRoutines::SetFakeData() { //************************************* if (fFakeDataInput.empty()) return; if (fFakeDataInput.compare("MC") == 0) { - QLOG(FIT, "Setting fake data from MC starting prediction."); + NUIS_LOG(FIT, "Setting fake data from MC starting prediction."); UpdateRWEngine(fFakeVals); FitBase::GetRW()->Reconfigure(); fSampleFCN->ReconfigureAllEvents(); fSampleFCN->SetFakeData("MC"); UpdateRWEngine(fCurVals); - QLOG(FIT, "Set all data to fake MC predictions."); + NUIS_LOG(FIT, "Set all data to fake MC predictions."); } else { fSampleFCN->SetFakeData(fFakeDataInput); } return; } //***************************************** // Setup the parameter covariances from the FCN void SystematicRoutines::GetCovarFromFCN() { //***************************************** - QLOG(FIT, "Loading ParamPull objects from FCN to build covariance..."); + NUIS_LOG(FIT, "Loading ParamPull objects from FCN to build covariance..."); // Make helperstring std::ostringstream helperstr; // Keep track of what is being thrown std::map dialthrowhandle; // Get Covariance Objects from FCN std::list inputpulls = fSampleFCN->GetPullList(); for (PullListConstIter iter = inputpulls.begin(); iter != inputpulls.end(); iter++) { ParamPull *pull = (*iter); if (pull->GetType().find("THROW") != std::string::npos) { fInputThrows.push_back(pull); fInputCovar.push_back(pull->GetFullCovarMatrix()); fInputDials.push_back(pull->GetDataHist()); - QLOG(FIT, "Read ParamPull: " << pull->GetName() << " " << pull->GetType()); + NUIS_LOG(FIT, "Read ParamPull: " << pull->GetName() << " " << pull->GetType()); } TH1D dialhist = pull->GetDataHist(); TH1D minhist = pull->GetMinHist(); TH1D maxhist = pull->GetMaxHist(); TH1I typehist = pull->GetDialTypes(); for (int i = 0; i < dialhist.GetNbinsX(); i++) { std::string name = std::string(dialhist.GetXaxis()->GetBinLabel(i + 1)); dialthrowhandle[name] = pull->GetName(); // Add to Containers // Set the starting values etc to the postfit fParams.push_back(name); fCurVals[name] = dialhist.GetBinContent(i + 1); // Set the starting values to be nominal MC fStartVals[name] = 0.0; fMinVals[name] = minhist.GetBinContent(i + 1); fMaxVals[name] = maxhist.GetBinContent(i + 1); fStepVals[name] = 1.0; fFixVals[name] = false; fStartFixVals[name] = false; fTypeVals[name] = typehist.GetBinContent(i + 1); fStateVals[name] = "FREE," + pull->GetType(); // If we find the string if (fCurVals.find(name) == fCurVals.end()) { // Maker Helper helperstr << std::string(16, ' ') << FitBase::ConvDialType(fTypeVals[name]) << " " << name << " " << fMinVals[name] << " " << fMaxVals[name] << " " << fStepVals[name] << " " << fStateVals[name] << std::endl; } } } // Check if no throws given if (fInputThrows.empty()) { - QERROR(WRN, "No covariances given to nuissyst"); - QERROR(WRN, "Pushing back an uncorrelated gaussian throw error for each " + NUIS_ERR(WRN, "No covariances given to nuissyst"); + NUIS_ERR(WRN, "Pushing back an uncorrelated gaussian throw error for each " "free parameter using step size"); for (UInt_t i = 0; i < fParams.size(); i++) { std::string syst = fParams[i]; if (fFixVals[syst]) continue; // Make Terms std::string name = syst + "_pull"; std::ostringstream pullterm; pullterm << "DIAL:" << syst << ";" << fStartVals[syst] << ";" << fStepVals[syst]; std::string type = "GAUSTHROW/NEUT"; // Push Back Pulls ParamPull *pull = new ParamPull(name, pullterm.str(), type); fInputThrows.push_back(pull); fInputCovar.push_back(pull->GetFullCovarMatrix()); fInputDials.push_back(pull->GetDataHist()); // Print Whats added - QLOG(FIT, "Added ParamPull : " << name << " " << pullterm.str() << " " + NUIS_LOG(FIT, "Added ParamPull : " << name << " " << pullterm.str() << " " << type); // Add helper string for future fits helperstr << std::string(16, ' ') << "covar " << name << " " << pullterm.str() << " " << type << std::endl; // Keep Track of Throws dialthrowhandle[syst] = pull->GetName(); } } // Print Helper String if (!helperstr.str().empty()) { - QLOG(FIT, "To remove these statements in future studies, add the lines " + NUIS_LOG(FIT, "To remove these statements in future studies, add the lines " "below to your card:"); // Can't use the logger properly because this can be multi-line. Use cout // and added spaces to look better! std::cout << helperstr.str(); sleep(2); } // Print Throw State for (UInt_t i = 0; i < fParams.size(); i++) { std::string syst = fParams[i]; if (dialthrowhandle.find(syst) != dialthrowhandle.end()) { - QLOG(FIT, "Dial " << i << ". " << setw(20) << syst << " = THROWing with " + NUIS_LOG(FIT, "Dial " << i << ". " << setw(20) << syst << " = THROWing with " << dialthrowhandle[syst]); } else { - QLOG(FIT, "Dial " << i << ". " << setw(20) << syst << " = is FIXED"); + NUIS_LOG(FIT, "Dial " << i << ". " << setw(20) << syst << " = is FIXED"); } } } /* Fitting Functions */ //************************************* void SystematicRoutines::UpdateRWEngine( std::map &updateVals) { //************************************* for (UInt_t i = 0; i < fParams.size(); i++) { std::string name = fParams[i]; if (updateVals.find(name) == updateVals.end()) continue; FitBase::GetRW()->SetDialValue(name, updateVals.at(name)); } FitBase::GetRW()->Reconfigure(); } //************************************* void SystematicRoutines::PrintState() { //************************************* - QLOG(FIT, "------------"); + NUIS_LOG(FIT, "------------"); // Count max size int maxcount = 0; for (UInt_t i = 0; i < fParams.size(); i++) { maxcount = max(int(fParams[i].size()), maxcount); } // Header - QLOG(FIT, " # " << left << setw(maxcount) << "Parameter " + NUIS_LOG(FIT, " # " << left << setw(maxcount) << "Parameter " << " = " << setw(10) << "Value" << " +- " << setw(10) << "Error" << " " << setw(8) << "(Units)" << " " << setw(10) << "Conv. Val" << " +- " << setw(10) << "Conv. Err" << " " << setw(8) << "(Units)"); // Parameters for (UInt_t i = 0; i < fParams.size(); i++) { std::string syst = fParams.at(i); std::string typestr = FitBase::ConvDialType(fTypeVals[syst]); std::string curunits = "(sig.)"; double curval = fCurVals[syst]; double curerr = fErrorVals[syst]; if (fStateVals[syst].find("ABS") != std::string::npos) { curval = FitBase::RWSigmaToAbs(typestr, syst, curval); curerr = (FitBase::RWSigmaToAbs(typestr, syst, curerr) - FitBase::RWSigmaToAbs(typestr, syst, 0.0)); curunits = "(Abs.)"; } else if (fStateVals[syst].find("FRAC") != std::string::npos) { curval = FitBase::RWSigmaToFrac(typestr, syst, curval); curerr = (FitBase::RWSigmaToFrac(typestr, syst, curerr) - FitBase::RWSigmaToFrac(typestr, syst, 0.0)); curunits = "(Frac)"; } std::string convunits = "(" + FitBase::GetRWUnits(typestr, syst) + ")"; double convval = FitBase::RWSigmaToAbs(typestr, syst, curval); double converr = (FitBase::RWSigmaToAbs(typestr, syst, curerr) - FitBase::RWSigmaToAbs(typestr, syst, 0.0)); std::ostringstream curparstring; curparstring << " " << setw(3) << left << i << ". " << setw(maxcount) << syst << " = " << setw(10) << curval << " +- " << setw(10) << curerr << " " << setw(8) << curunits << " " << setw(10) << convval << " +- " << setw(10) << converr << " " << setw(8) << convunits; - QLOG(FIT, curparstring.str()); + NUIS_LOG(FIT, curparstring.str()); } - QLOG(FIT, "------------"); + NUIS_LOG(FIT, "------------"); double like = fSampleFCN->GetLikelihood(); - QLOG(FIT, std::left << std::setw(46) << "Likelihood for JointFCN: " << like); - QLOG(FIT, "------------"); + NUIS_LOG(FIT, std::left << std::setw(46) << "Likelihood for JointFCN: " << like); + NUIS_LOG(FIT, "------------"); } /* Write Functions */ //************************************* void SystematicRoutines::SaveResults() { //************************************* if (!fOutputRootFile) fOutputRootFile = new TFile(fCompKey.GetS("outputfile").c_str(), "RECREATE"); fOutputRootFile->cd(); SaveCurrentState(); } //************************************* void SystematicRoutines::SaveCurrentState(std::string subdir) { //************************************* - QLOG(FIT, "Saving current full FCN predictions"); + NUIS_LOG(FIT, "Saving current full FCN predictions"); // Setup DIRS TDirectory *curdir = gDirectory; if (!subdir.empty()) { TDirectory *newdir = (TDirectory *)gDirectory->mkdir(subdir.c_str()); newdir->cd(); } FitBase::GetRW()->Reconfigure(); fSampleFCN->ReconfigureAllEvents(); fSampleFCN->Write(); // Change back to current DIR curdir->cd(); return; } //************************************* void SystematicRoutines::SaveNominal() { //************************************* if (!fOutputRootFile) fOutputRootFile = new TFile(fCompKey.GetS("outputfile").c_str(), "RECREATE"); fOutputRootFile->cd(); - QLOG(FIT, "Saving Nominal Predictions (be cautious with this)"); + NUIS_LOG(FIT, "Saving Nominal Predictions (be cautious with this)"); FitBase::GetRW()->Reconfigure(); SaveCurrentState("nominal"); }; //************************************* void SystematicRoutines::SavePrefit() { //************************************* if (!fOutputRootFile) fOutputRootFile = new TFile(fCompKey.GetS("outputfile").c_str(), "RECREATE"); fOutputRootFile->cd(); - QLOG(FIT, "Saving Prefit Predictions"); + NUIS_LOG(FIT, "Saving Prefit Predictions"); UpdateRWEngine(fStartVals); SaveCurrentState("prefit"); UpdateRWEngine(fCurVals); }; /* MISC Functions */ //************************************* int SystematicRoutines::GetStatus() { //************************************* return 0; } //************************************* void SystematicRoutines::SetupCovariance() { //************************************* // Remove covares if they exist if (fCovar) delete fCovar; if (fCovarFree) delete fCovarFree; if (fCorrel) delete fCorrel; if (fCorrelFree) delete fCorrelFree; if (fDecomp) delete fDecomp; if (fDecompFree) delete fDecompFree; int NFREE = 0; int NDIM = 0; // Get NFREE from min or from vals (for cases when doing throws) NDIM = fParams.size(); for (UInt_t i = 0; i < fParams.size(); i++) { if (!fFixVals[fParams[i]]) NFREE++; } if (NDIM == 0) return; fCovar = new TH2D("covariance", "covariance", NDIM, 0, NDIM, NDIM, 0, NDIM); if (NFREE > 0) { fCovarFree = new TH2D("covariance_free", "covariance_free", NFREE, 0, NFREE, NFREE, 0, NFREE); } // Set Bin Labels int countall = 0; int countfree = 0; for (UInt_t i = 0; i < fParams.size(); i++) { fCovar->GetXaxis()->SetBinLabel(countall + 1, fParams[i].c_str()); fCovar->GetYaxis()->SetBinLabel(countall + 1, fParams[i].c_str()); countall++; if (!fFixVals[fParams[i]] and NFREE > 0) { fCovarFree->GetXaxis()->SetBinLabel(countfree + 1, fParams[i].c_str()); fCovarFree->GetYaxis()->SetBinLabel(countfree + 1, fParams[i].c_str()); countfree++; } } fCorrel = PlotUtils::GetCorrelationPlot(fCovar, "correlation"); fDecomp = PlotUtils::GetDecompPlot(fCovar, "decomposition"); if (NFREE > 0) fCorrelFree = PlotUtils::GetCorrelationPlot(fCovarFree, "correlation_free"); if (NFREE > 0) fDecompFree = PlotUtils::GetDecompPlot(fCovarFree, "decomposition_free"); return; }; //************************************* void SystematicRoutines::ThrowCovariance(bool uniformly) { //************************************* // Set fThrownVals to all values in currentVals for (UInt_t i = 0; i < fParams.size(); i++) { std::string name = fParams.at(i); fThrownVals[name] = fCurVals[name]; } for (PullListConstIter iter = fInputThrows.begin(); iter != fInputThrows.end(); iter++) { ParamPull *pull = *iter; pull->ThrowCovariance(); TH1D dialhist = pull->GetDataHist(); for (int i = 0; i < dialhist.GetNbinsX(); i++) { std::string name = std::string(dialhist.GetXaxis()->GetBinLabel(i + 1)); if (fCurVals.find(name) != fCurVals.end()) { fThrownVals[name] = dialhist.GetBinContent(i + 1); } } // Reset throw in case pulls are calculated. pull->ResetToy(); } }; //************************************* void SystematicRoutines::PlotLimits() { //************************************* std::cout << "Plotting Limits" << std::endl; if (!fOutputRootFile) fOutputRootFile = new TFile(fCompKey.GetS("outputfile").c_str(), "RECREATE"); TDirectory *limfolder = (TDirectory *)fOutputRootFile->mkdir("Limits"); limfolder->cd(); // Set all parameters at their starting values for (UInt_t i = 0; i < fParams.size(); i++) { fCurVals[fParams[i]] = fStartVals[fParams[i]]; } TDirectory *nomfolder = (TDirectory *)limfolder->mkdir("nominal"); nomfolder->cd(); UpdateRWEngine(fCurVals); fSampleFCN->ReconfigureAllEvents(); fSampleFCN->Write(); limfolder->cd(); std::vector allfolders; // Loop through each parameter for (UInt_t i = 0; i < fParams.size(); i++) { std::string syst = fParams[i]; std::cout << "Starting Param " << syst << std::endl; if (fFixVals[syst]) continue; // Loop Downwards while (fCurVals[syst] > fMinVals[syst]) { fCurVals[syst] = fCurVals[syst] - fStepVals[syst]; // Check Limit if (fCurVals[syst] < fMinVals[syst]) fCurVals[syst] = fMinVals[syst]; // Check folder exists std::string curvalstring = std::string(Form((syst + "_%f").c_str(), fCurVals[syst])); if (std::find(allfolders.begin(), allfolders.end(), curvalstring) != allfolders.end()) break; // Make new folder for variation TDirectory *minfolder = (TDirectory *)limfolder->mkdir( Form((syst + "_%f").c_str(), fCurVals[syst])); minfolder->cd(); allfolders.push_back(curvalstring); // Update Iterations double *vals = FitUtils::GetArrayFromMap(fParams, fCurVals); fSampleFCN->DoEval(vals); delete vals; // Save to folder fSampleFCN->Write(); } // Reset before next loop fCurVals[syst] = fStartVals[syst]; // Loop Upwards now while (fCurVals[syst] < fMaxVals[syst]) { fCurVals[syst] = fCurVals[syst] + fStepVals[syst]; // Check Limit if (fCurVals[syst] > fMaxVals[syst]) fCurVals[syst] = fMaxVals[syst]; // Check folder exists std::string curvalstring = std::string(Form((syst + "_%f").c_str(), fCurVals[syst])); if (std::find(allfolders.begin(), allfolders.end(), curvalstring) != allfolders.end()) break; // Make new folder TDirectory *maxfolder = (TDirectory *)limfolder->mkdir( Form((syst + "_%f").c_str(), fCurVals[syst])); maxfolder->cd(); allfolders.push_back(curvalstring); // Update Iterations double *vals = FitUtils::GetArrayFromMap(fParams, fCurVals); fSampleFCN->DoEval(vals); delete vals; // Save to file fSampleFCN->Write(); } // Reset before leaving fCurVals[syst] = fStartVals[syst]; UpdateRWEngine(fCurVals); } return; } //************************************* void SystematicRoutines::Run() { //************************************* fRoutines = GeneralUtils::ParseToStr(fStrategy, ","); for (UInt_t i = 0; i < fRoutines.size(); i++) { std::string routine = fRoutines.at(i); int fitstate = kFitUnfinished; - QLOG(FIT, "Running Routine: " << routine); + NUIS_LOG(FIT, "Running Routine: " << routine); if (routine.compare("PlotLimits") == 0) PlotLimits(); else if (routine.compare("ErrorBands") == 0) GenerateErrorBands(); else if (routine.compare("ThrowErrors") == 0) GenerateThrows(); else if (routine.compare("MergeErrors") == 0) MergeThrows(); else if (routine.compare("EigenErrors") == 0) EigenErrors(); else { - QTHROW("Unknown ROUTINE : " << routine); + NUIS_ABORT("Unknown ROUTINE : " << routine); } // If ending early break here if (fitstate == kFitFinished || fitstate == kNoChange) { - QLOG(FIT, "Ending fit routines loop."); + NUIS_LOG(FIT, "Ending fit routines loop."); break; } } } void SystematicRoutines::GenerateErrorBands() { GenerateThrows(); MergeThrows(); } //************************************* void SystematicRoutines::GenerateThrows() { //************************************* TFile *tempfile = new TFile((fOutputFile + ".throws.root").c_str(), "RECREATE"); tempfile->cd(); // For generating throws we check with the config int nthrows = Config::GetParI("error_throws"); int startthrows = fStartThrows; int endthrows = startthrows + nthrows; if (nthrows < 0) nthrows = endthrows; if (startthrows < 0) startthrows = 0; if (endthrows < 0) endthrows = startthrows + nthrows; // Setting Seed // Matteo Mazzanti's Fix struct timeval mytime; gettimeofday(&mytime, NULL); Double_t seed = time(NULL) + int(getpid()) + (mytime.tv_sec * 1000.) + (mytime.tv_usec / 1000.); gRandom->SetSeed(seed); // int seed = (gRandom->Uniform(0.0,1.0)*100000 + 100000000*(startthrows + // endthrows) + time(NULL) + int(getpid()) ); gRandom->SetSeed(seed); - QLOG(FIT, "Using Seed : " << seed); - QLOG(FIT, "nthrows = " << nthrows); - QLOG(FIT, "startthrows = " << startthrows); - QLOG(FIT, "endthrows = " << endthrows); + NUIS_LOG(FIT, "Using Seed : " << seed); + NUIS_LOG(FIT, "nthrows = " << nthrows); + NUIS_LOG(FIT, "startthrows = " << startthrows); + NUIS_LOG(FIT, "endthrows = " << endthrows); UpdateRWEngine(fStartVals); fSampleFCN->ReconfigureAllEvents(); // Make the nominal if (startthrows == 0) { - QLOG(FIT, "Making nominal "); + NUIS_LOG(FIT, "Making nominal "); TDirectory *nominal = (TDirectory *)tempfile->mkdir("nominal"); nominal->cd(); fSampleFCN->Write(); // Make the postfit reading from the pull - QLOG(FIT, "Making postfit "); + NUIS_LOG(FIT, "Making postfit "); TDirectory *postfit = (TDirectory *)tempfile->mkdir("postfit"); postfit->cd(); UpdateRWEngine(fCurVals); fSampleFCN->ReconfigureSignal(); fSampleFCN->Write(); } fSampleFCN->CreateIterationTree("error_iterations", FitBase::GetRW()); // Would anybody actually want to do uniform throws of any parameter?? bool uniformly = FitPar::Config().GetParB("error_uniform"); // Run Throws and save for (Int_t i = 0; i < endthrows + 1; i++) { // Generate Random Parameter Throw ThrowCovariance(uniformly); if (i < startthrows) continue; if (i == 0) continue; - QLOG(FIT, "Throw " << i << "/" << endthrows + NUIS_LOG(FIT, "Throw " << i << "/" << endthrows << " ================================"); TDirectory *throwfolder = (TDirectory *)tempfile->mkdir(Form("throw_%i", i)); throwfolder->cd(); // Run Eval double *vals = FitUtils::GetArrayFromMap(fParams, fThrownVals); fSampleFCN->DoEval(vals); delete vals; // Save the FCN fSampleFCN->Write(); } tempfile->cd(); fSampleFCN->WriteIterationTree(); tempfile->Close(); } // Merge throws together into one summary void SystematicRoutines::MergeThrows() { fOutputRootFile = new TFile(fCompKey.GetS("outputfile").c_str(), "RECREATE"); fOutputRootFile->cd(); // Make a container folder TDirectory *errorDIR = (TDirectory *)fOutputRootFile->mkdir("error_bands"); errorDIR->cd(); TDirectory *outnominal = (TDirectory *)fOutputRootFile->mkdir("nominal_throw"); outnominal->cd(); // Split Input Files if (!fThrowString.empty()) fThrowList = GeneralUtils::ParseToStr(fThrowString, ","); // Add default if no throwlist given if (fThrowList.size() < 1) fThrowList.push_back(fOutputFile + ".throws.root"); /// Save location of file containing nominal std::string nominalfile; bool nominalfound; // Loop over files and check they exist. for (uint i = 0; i < fThrowList.size(); i++) { std::string file = fThrowList[i]; bool found = false; // normal std::string newfile = file; TFile *throwfile = new TFile(file.c_str(), "READ"); if (throwfile and !throwfile->IsZombie()) { found = true; } // normal.throws.root if (!found) { newfile = file + ".throws.root"; throwfile = new TFile((file + ".throws.root").c_str(), "READ"); if (throwfile and !throwfile->IsZombie()) { found = true; } } // If its found save to throwlist, else save empty. // Also search for nominal if (found) { fThrowList[i] = newfile; - QLOG(FIT, "Throws File :" << newfile); + NUIS_LOG(FIT, "Throws File :" << newfile); // Find input which contains nominal if (throwfile->Get("nominal")) { nominalfound = true; nominalfile = newfile; } throwfile->Close(); } else { fThrowList[i] = ""; } delete throwfile; } // Make sure we have a nominal file if (!nominalfound or nominalfile.empty()) { - QTHROW("No nominal found when merging! Exiting!"); + NUIS_ABORT("No nominal found when merging! Exiting!"); } // Get the nominal throws file TFile *tempfile = new TFile((nominalfile).c_str(), "READ"); tempfile->cd(); TDirectory *nominal = (TDirectory *)tempfile->Get("nominal"); bool uniformly = FitPar::Config().GetParB("error_uniform"); // Check percentage of bad files is okay. int badfilecount = 0; for (uint i = 0; i < fThrowList.size(); i++) { if (!fThrowList[i].empty()) { - QLOG(FIT, "Loading Throws From File " << i << " : " << fThrowList[i]); + NUIS_LOG(FIT, "Loading Throws From File " << i << " : " << fThrowList[i]); } else { badfilecount++; } } // Check we have at least one good file if ((uint)badfilecount == fThrowList.size()) { - QTHROW("Found no good throw files for MergeThrows"); + NUIS_ABORT("Found no good throw files for MergeThrows"); throw; } else if (badfilecount > (fThrowList.size() * 0.25)) { - QERROR( + NUIS_ERR( WRN, "Over 25% of your throw files are dodgy. Please check this is okay!"); - QERROR(WRN, "Will continue for the time being..."); + NUIS_ERR(WRN, "Will continue for the time being..."); sleep(5); } // Now go through the keys in the temporary file and look for TH1D, and TH2D // plots TIter next(nominal->GetListOfKeys()); TKey *key; while ((key = (TKey *)next())) { TClass *cl = gROOT->GetClass(key->GetClassName()); if (!cl->InheritsFrom("TH1D") and !cl->InheritsFrom("TH2D")) continue; TH1 *baseplot = (TH1D *)key->ReadObj(); std::string plotname = std::string(baseplot->GetName()); - QLOGN(FIT, "Creating error bands for " << plotname); + NUIS_LOGN(FIT, "Creating error bands for " << plotname); if (LOG_LEVEL(FIT)) { if (!uniformly) { - QLOG(FIT, " : Using COVARIANCE Throws! "); + NUIS_LOG(FIT, " : Using COVARIANCE Throws! "); } else { - QLOG(FIT, " : Using UNIFORM THROWS!!! "); + NUIS_LOG(FIT, " : Using UNIFORM THROWS!!! "); } } int nbins = 0; if (cl->InheritsFrom("TH1D")) nbins = ((TH1D *)baseplot)->GetNbinsX(); else nbins = ((TH1D *)baseplot)->GetNbinsX() * ((TH1D *)baseplot)->GetNbinsY(); // Setup TProfile with RMS option TProfile *tprof = new TProfile((plotname + "_prof").c_str(), (plotname + "_prof").c_str(), nbins, 0, nbins, "S"); // Setup The TTREE double *bincontents; bincontents = new double[nbins]; double *binlowest; binlowest = new double[nbins]; double *binhighest; binhighest = new double[nbins]; errorDIR->cd(); TTree *bintree = new TTree((plotname + "_tree").c_str(), (plotname + "_tree").c_str()); for (Int_t i = 0; i < nbins; i++) { bincontents[i] = 0.0; binhighest[i] = 0.0; binlowest[i] = 0.0; bintree->Branch(Form("content_%i", i), &bincontents[i], Form("content_%i/D", i)); } // Make new throw plot TH1 *newplot; // Run Throw Merging. for (UInt_t i = 0; i < fThrowList.size(); i++) { TFile *throwfile = new TFile(fThrowList[i].c_str(), "READ"); // Loop over all throws in a folder TIter nextthrow(throwfile->GetListOfKeys()); TKey *throwkey; while ((throwkey = (TKey *)nextthrow())) { // Skip non throw folders if (std::string(throwkey->GetName()).find("throw_") == std::string::npos) continue; // Get Throw DIR TDirectory *throwdir = (TDirectory *)throwkey->ReadObj(); // Get Plot From Throw newplot = (TH1 *)throwdir->Get(plotname.c_str()); if (!newplot) continue; // Loop Over Plot for (Int_t j = 0; j < nbins; j++) { tprof->Fill(j + 0.5, newplot->GetBinContent(j + 1)); bincontents[j] = newplot->GetBinContent(j + 1); if (bincontents[j] < binlowest[j] or i == 0) binlowest[j] = bincontents[j]; if (bincontents[j] > binhighest[j] or i == 0) binhighest[j] = bincontents[j]; } errorDIR->cd(); bintree->Fill(); } throwfile->Close(); delete throwfile; } errorDIR->cd(); if (uniformly) { - QLOG(FIT, "Uniformly Calculating Plot Errors!"); + NUIS_LOG(FIT, "Uniformly Calculating Plot Errors!"); } TH1 *statplot = (TH1 *)baseplot->Clone(); for (Int_t j = 0; j < nbins; j++) { if (!uniformly) { // if ((baseplot->GetBinError(j+1)/baseplot->GetBinContent(j+1)) //< 1.0) { // baseplot->SetBinError(j+1,sqrt(pow(tprof->GetBinError(j+1),2) //+ pow(baseplot->GetBinError(j+1),2))); } else { baseplot->SetBinContent(j + 1, tprof->GetBinContent(j + 1)); baseplot->SetBinError(j + 1, tprof->GetBinError(j + 1)); // } } else { baseplot->SetBinContent(j + 1, 0.0); //(binlowest[j] + binhighest[j]) / 2.0); baseplot->SetBinError(j + 1, 0.0); //(binhighest[j] - binlowest[j])/2.0); } } baseplot->SetTitle("Profiled throws"); errorDIR->cd(); baseplot->Write(); tprof->Write(); bintree->Write(); outnominal->cd(); for (int i = 0; i < nbins; i++) { baseplot->SetBinError(i + 1, sqrt(pow(statplot->GetBinError(i + 1), 2) + pow(baseplot->GetBinError(i + 1), 2))); } baseplot->Write(); delete statplot; delete baseplot; delete tprof; delete bintree; delete[] bincontents; } }; void SystematicRoutines::EigenErrors() { fOutputRootFile = new TFile(fCompKey.GetS("outputfile").c_str(), "RECREATE"); fOutputRootFile->cd(); // Make Covariance TMatrixDSym *fullcovar = new TMatrixDSym(fParams.size()); // Extract covariance from all loaded ParamPulls for (PullListConstIter iter = fInputThrows.begin(); iter != fInputThrows.end(); iter++) { ParamPull *pull = *iter; // Check pull is actualyl Gaussian std::string pulltype = pull->GetType(); if (pulltype.find("GAUSTHROW") == std::string::npos) { - QTHROW("Can only calculate EigenErrors for Gaussian pulls!"); + NUIS_ABORT("Can only calculate EigenErrors for Gaussian pulls!"); } // Get data and covariances TH1D dialhist = pull->GetDataHist(); TH2D covhist = pull->GetFullCovar(); // Loop over all dials and compare names for (size_t pari = 0; pari < fParams.size(); pari++) { for (size_t parj = 0; parj < fParams.size(); parj++) { std::string name_pari = fParams[pari]; std::string name_parj = fParams[parj]; // Compare names to those in the pull for (int pulli = 0; pulli < dialhist.GetNbinsX(); pulli++) { for (int pullj = 0; pullj < dialhist.GetNbinsX(); pullj++) { std::string name_pulli = dialhist.GetXaxis()->GetBinLabel(pulli + 1); std::string name_pullj = dialhist.GetXaxis()->GetBinLabel(pullj + 1); if (name_pulli == name_pari && name_pullj == name_parj) { (*fullcovar)[pari][parj] = covhist.GetBinContent(pulli + 1, pullj + 1); fCurVals[name_pari] = dialhist.GetBinContent(pulli + 1); fCurVals[name_parj] = dialhist.GetBinContent(pullj + 1); } } } } } } /* TFile* test = new TFile("testingcovar.root","RECREATE"); test->cd(); TH2D* joinedcov = new TH2D("COVAR","COVAR", fullcovar->GetNrows(), 0.0, float(fullcovar->GetNrows()), fullcovar->GetNrows(), 0.0, float(fullcovar->GetNrows())); for (int i = 0; i < fullcovar->GetNrows(); i++){ for (int j = 0; j < fullcovar->GetNcols(); j++){ joinedcov->SetBinContent(i+1, j+1, (*fullcovar)[i][j]); } } joinedcov->Write("COVAR"); test->Close(); */ // Calculator all EigenVectors and EigenValues TMatrixDSymEigen *eigen = new TMatrixDSymEigen(*fullcovar); const TVectorD eigenVals = eigen->GetEigenValues(); const TMatrixD eigenVect = eigen->GetEigenVectors(); eigenVals.Print(); eigenVect.Print(); TDirectory *outnominal = (TDirectory *)fOutputRootFile->mkdir("nominal"); outnominal->cd(); double *valst = FitUtils::GetArrayFromMap(fParams, fCurVals); // double chi2 = fSampleFCN->DoEval( valst ); delete valst; fSampleFCN->Write(); // Loop over all throws TDirectory *throwsdir = (TDirectory *)fOutputRootFile->mkdir("throws"); throwsdir->cd(); int count = 0; // Produce all error throws. for (int i = 0; i < eigenVect.GetNrows(); i++) { TDirectory *throwfolder = (TDirectory *)throwsdir->mkdir(Form("throw_%i", count)); throwfolder->cd(); // Get New Parameter Vector - QLOG(FIT, "Parameter Set " << count); + NUIS_LOG(FIT, "Parameter Set " << count); for (int j = 0; j < eigenVect.GetNrows(); j++) { std::string param = fParams[j]; - QLOG(FIT, " " << j << ". " << param << " : " + NUIS_LOG(FIT, " " << j << ". " << param << " : " << fCurVals[param] + sqrt(eigenVals[i]) * eigenVect[j][i]); fThrownVals[param] = fCurVals[param] + sqrt(eigenVals[i]) * eigenVect[j][i]; } // Run Eval double *vals = FitUtils::GetArrayFromMap(fParams, fThrownVals); double chi2 = fSampleFCN->DoEval(vals); delete vals; count++; fSampleFCN->Write(); throwfolder = (TDirectory *)throwsdir->mkdir(Form("throw_%i", count)); throwfolder->cd(); // Get New Parameter Vector - QLOG(FIT, "Parameter Set " << count); + NUIS_LOG(FIT, "Parameter Set " << count); for (int j = 0; j < eigenVect.GetNrows(); j++) { std::string param = fParams[j]; - QLOG(FIT, " " << j << ". " << param << " : " + NUIS_LOG(FIT, " " << j << ". " << param << " : " << fCurVals[param] - sqrt(eigenVals[i]) * eigenVect[j][i]); fThrownVals[param] = fCurVals[param] - sqrt(eigenVals[i]) * eigenVect[j][i]; } // Run Eval double *vals2 = FitUtils::GetArrayFromMap(fParams, fThrownVals); chi2 = fSampleFCN->DoEval(vals2); delete vals2; count++; // Save the FCN fSampleFCN->Write(); } fOutputRootFile->Close(); fOutputRootFile = new TFile(fCompKey.GetS("outputfile").c_str(), "UPDATE"); fOutputRootFile->cd(); throwsdir = (TDirectory *)fOutputRootFile->Get("throws"); outnominal = (TDirectory *)fOutputRootFile->Get("nominal"); // Loop through Error DIR TDirectory *outerr = (TDirectory *)fOutputRootFile->mkdir("errors"); outerr->cd(); TIter next(outnominal->GetListOfKeys()); TKey *key; while ((key = (TKey *)next())) { TClass *cl = gROOT->GetClass(key->GetClassName()); if (!cl->InheritsFrom("TH1D") and !cl->InheritsFrom("TH2D")) continue; - QLOG(FIT, "Creating error bands for " << key->GetName()); + NUIS_LOG(FIT, "Creating error bands for " << key->GetName()); std::string plotname = std::string(key->GetName()); if (plotname.find("_EVT") != std::string::npos) continue; if (plotname.find("_FLUX") != std::string::npos) continue; if (plotname.find("_FLX") != std::string::npos) continue; TH1 *baseplot = (TH1D *)key->ReadObj()->Clone(Form("%s_ORIGINAL", key->GetName())); TH1 *errorplot_upper = (TH1D *)baseplot->Clone(Form("%s_ERROR_UPPER", key->GetName())); TH1 *errorplot_lower = (TH1D *)baseplot->Clone(Form("%s_ERROR_LOWER", key->GetName())); TH1 *meanplot = (TH1D *)baseplot->Clone(Form("%s_SET_MEAN", key->GetName())); TH1 *systplot = (TH1D *)baseplot->Clone(Form("%s_SYST", key->GetName())); TH1 *statplot = (TH1D *)baseplot->Clone(Form("%s_STAT", key->GetName())); TH1 *totlplot = (TH1D *)baseplot->Clone(Form("%s_TOTAL", key->GetName())); int nbins = 0; if (cl->InheritsFrom("TH1D")) nbins = ((TH1D *)baseplot)->GetNbinsX(); else nbins = ((TH1D *)baseplot)->GetNbinsX() * ((TH1D *)baseplot)->GetNbinsY(); meanplot->Reset(); errorplot_upper->Reset(); errorplot_lower->Reset(); for (int j = 0; j < nbins; j++) { errorplot_upper->SetBinError(j + 1, 0.0); errorplot_lower->SetBinError(j + 1, 0.0); } // Loop over throws and calculate mean and error for +- throws int addcount = 0; // Add baseplot first to slightly bias to central value meanplot->Add(baseplot); addcount++; for (int i = 0; i < count; i++) { TH1 *newplot = (TH1D *)throwsdir->Get(Form("throw_%i/%s", i, plotname.c_str())); if (!newplot) { - QERROR(WRN, "Cannot find new plot : " << Form("throw_%i/%s", i, + NUIS_ERR(WRN, "Cannot find new plot : " << Form("throw_%i/%s", i, plotname.c_str())); - QERROR(WRN, "This plot will not have the correct errors!"); + NUIS_ERR(WRN, "This plot will not have the correct errors!"); continue; } newplot->SetDirectory(0); nbins = newplot->GetNbinsX(); for (int j = 0; j < nbins; j++) { if (i % 2 == 0) { errorplot_upper->SetBinContent( j + 1, errorplot_upper->GetBinContent(j + 1) + pow(baseplot->GetBinContent(j + 1) - newplot->GetBinContent(j + 1), 2)); } else { errorplot_lower->SetBinContent( j + 1, errorplot_lower->GetBinContent(j + 1) + pow(baseplot->GetBinContent(j + 1) - newplot->GetBinContent(j + 1), 2)); } meanplot->SetBinContent(j + 1, meanplot->GetBinContent(j + 1) + baseplot->GetBinContent(j + 1)); } delete newplot; addcount++; } // Get mean Average for (int j = 0; j < nbins; j++) { meanplot->SetBinContent(j + 1, meanplot->GetBinContent(j + 1) / double(addcount)); } for (int j = 0; j < nbins; j++) { errorplot_upper->SetBinContent( j + 1, sqrt(errorplot_upper->GetBinContent(j + 1))); errorplot_lower->SetBinContent( j + 1, sqrt(errorplot_lower->GetBinContent(j + 1))); statplot->SetBinError(j + 1, baseplot->GetBinError(j + 1)); systplot->SetBinError(j + 1, (errorplot_upper->GetBinContent(j + 1) + errorplot_lower->GetBinContent(j + 1)) / 2.0); totlplot->SetBinError(j + 1, sqrt(pow(statplot->GetBinError(j + 1), 2) + pow(systplot->GetBinError(j + 1), 2))); meanplot->SetBinError(j + 1, sqrt(pow(statplot->GetBinError(j + 1), 2) + pow(systplot->GetBinError(j + 1), 2))); } outerr->cd(); errorplot_upper->Write(); errorplot_lower->Write(); baseplot->Write(); meanplot->Write(); statplot->Write(); systplot->Write(); totlplot->Write(); delete errorplot_upper; delete errorplot_lower; delete baseplot; delete meanplot; delete statplot; delete systplot; delete totlplot; } } diff --git a/src/Smearceptance/EfficiencyApplicator.cxx b/src/Smearceptance/EfficiencyApplicator.cxx index a6079cb..ebed17b 100644 --- a/src/Smearceptance/EfficiencyApplicator.cxx +++ b/src/Smearceptance/EfficiencyApplicator.cxx @@ -1,388 +1,388 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "EfficiencyApplicator.h" #include "TEfficiency.h" #include "TH2.h" #include "TH3.h" //#define DEBUG_EFFAPP EfficiencyApplicator::DependVar GetVarType(std::string const &axisvar) { if (axisvar == "kMomentum") { return EfficiencyApplicator::kMomentum; } else if (axisvar == "kKE") { return EfficiencyApplicator::kKE; } else if (axisvar == "kTheta") { return EfficiencyApplicator::kTheta; } else if (axisvar == "kCosTheta") { return EfficiencyApplicator::kCosTheta; } else if (axisvar == "kPhi") { return EfficiencyApplicator::kPhi; } return EfficiencyApplicator::kNoAxis; } TH1 *GetEffHist(TFile *inputFile, std::string const &HistName) { TH1 *hist = dynamic_cast(inputFile->Get(HistName.c_str())); if (hist) { return hist; } TEfficiency *effHist = dynamic_cast(inputFile->Get(HistName.c_str())); if (effHist) { TH1D *numer = dynamic_cast(effHist->GetCopyPassedHisto()); TH1D *denom = dynamic_cast(effHist->GetCopyTotalHisto()); if (numer && denom) { numer->Divide(denom); denom->SetDirectory(NULL); delete denom; // Gonna be a memory leak, but I'll get over it numer->SetDirectory(NULL); return numer; } - QERROR(FTL, "TEfficiency internal histograms were not TH1Ds."); + NUIS_ERR(FTL, "TEfficiency internal histograms were not TH1Ds."); } - QTHROW("Couldn't get appropriate efficiency object named " + NUIS_ABORT("Couldn't get appropriate efficiency object named " << HistName << " from input file " << inputFile->GetName()); } /// Reads particle efficiency nodes /// /// Nodes look like: /// /// /// /// /// /// void EfficiencyApplicator::SpecifcSetup(nuiskey &nk) { rand.~TRandom3(); new (&rand) TRandom3(); std::vector effDescriptors = nk.GetListOfChildNodes("EfficiencyCurve"); for (size_t t_it = 0; t_it < effDescriptors.size(); ++t_it) { std::string inputFileName = effDescriptors[t_it].GetS("InputFile"); std::string HistName = effDescriptors[t_it].GetS("HistName"); TFile inputFile(inputFileName.c_str()); if (!inputFile.IsOpen()) { - QTHROW("Couldn't open specified input root file: " << inputFileName); + NUIS_ABORT("Couldn't open specified input root file: " << inputFileName); } TH1 *inpHist = GetEffHist(&inputFile, HistName); if (!inpHist) { - QTHROW("Couldn't get TH1D named: " << HistName << " from input root file: " + NUIS_ABORT("Couldn't get TH1D named: " << HistName << " from input root file: " << inputFileName); } int NDims = effDescriptors[t_it].GetI("NDims"); if (NDims < 1 || NDims > 3) { - QTHROW("Read NDims attribute as: " << NDims << ", efficiency curve can " + NUIS_ABORT("Read NDims attribute as: " << NDims << ", efficiency curve can " "currently have between 1 " "and 3 dimensions."); } EfficiencyApplicator::DependVar XVar = GetVarType(effDescriptors[t_it].GetS("XAxis")); double XAxisScale = effDescriptors[t_it].Has("XAxisScaleToInternal") ? effDescriptors[t_it].GetD("XAxisScaleToInternal") : 1; EfficiencyApplicator::DependVar YVar = NDims > 1 ? GetVarType(effDescriptors[t_it].GetS("YAxis")) : EfficiencyApplicator::kNoAxis; double YAxisScale = effDescriptors[t_it].Has("YAxisScaleToInternal") ? effDescriptors[t_it].GetD("YAxisScaleToInternal") : 1; EfficiencyApplicator::DependVar ZVar = NDims > 2 ? GetVarType(effDescriptors[t_it].GetS("ZAxis")) : EfficiencyApplicator::kNoAxis; double ZAxisScale = effDescriptors[t_it].Has("ZAxisScaleToInternal") ? effDescriptors[t_it].GetD("ZAxisScaleToInternal") : 1; bool Interpolate = effDescriptors[t_it].Has("Interpolate") && effDescriptors[t_it].GetI("Interpolate"); // bool ApplyAsWeight = effDescriptors[t_it].Has("ApplyAsWeight") && // effDescriptors[t_it].GetI("ApplyAsWeight"); std::string pdgs_s = effDescriptors[t_it].GetS("PDG"); std::vector pdgs_i = GeneralUtils::ParseToInt(pdgs_s, ","); for (size_t pdg_it = 0; pdg_it < pdgs_i.size(); ++pdg_it) { if (Efficiencies.count(pdgs_i[pdg_it])) { - QERROR(WRN, "Smearceptor " << ElementName << ":" << InstanceName + NUIS_ERR(WRN, "Smearceptor " << ElementName << ":" << InstanceName << " already has a efficiency for PDG: " << pdgs_i[pdg_it]); } EffMap em; em.EffCurve = static_cast(inpHist->Clone()); em.EffCurve->SetDirectory(NULL); em.Interpolate = Interpolate; // em.ApplyAsWeight = ApplyAsWeight; em.NDims = NDims; em.DependVars[0] = XVar; em.DependVars[1] = YVar; em.DependVars[2] = ZVar; em.AxisScales[0] = XAxisScale; em.AxisScales[1] = YAxisScale; em.AxisScales[2] = ZAxisScale; Efficiencies[pdgs_i[pdg_it]] = em; - QLOG(FIT, + NUIS_LOG(FIT, "Added reconstruction efficiency curve for PDG: " << pdgs_i[pdg_it]); } } SlaveTA.Setup(nk); } RecoInfo *EfficiencyApplicator::Smearcept(FitEvent *fe) { RecoInfo *ri = new RecoInfo(); for (size_t p_it = 0; p_it < fe->NParticles(); ++p_it) { FitParticle *fp = fe->GetParticle(p_it); #ifdef DEBUG_EFFAPP std::cout << std::endl; std::cout << "[" << p_it << "]: " << fp->PDG() << ", " << fp->Status() << ", " << fp->E() << " -- KE:" << fp->KE() << " Mom: " << fp->P3().Mag() << std::flush; #endif if (fp->Status() != kFinalState) { #ifdef DEBUG_EFFAPP std::cout << " -- Not final state." << std::flush; #endif continue; } if (!Efficiencies.count(fp->PDG())) { SlaveTA.SmearceptOneParticle(ri, fp #ifdef DEBUG_THRESACCEPT , p_it #endif ); continue; } EffMap &em = Efficiencies[fp->PDG()]; double kineProps[3]; for (Int_t dim_it = 0; dim_it < em.NDims; ++dim_it) { switch (em.DependVars[dim_it]) { case kMomentum: { kineProps[dim_it] = fp->P3().Mag(); break; } case kKE: { kineProps[dim_it] = fp->KE(); break; } case kTheta: { kineProps[dim_it] = fp->P3().Theta(); break; } case kCosTheta: { kineProps[dim_it] = fp->P3().CosTheta(); break; } case kPhi: { kineProps[dim_it] = fp->P3().Phi(); break; } - default: { QTHROW("Trying to find particle value for a kNoAxis."); } + default: { NUIS_ABORT("Trying to find particle value for a kNoAxis."); } } kineProps[dim_it] /= em.AxisScales[dim_it]; } double effProb = 0; switch (em.NDims) { case 1: { TH1 *hist = em.EffCurve; if (em.Interpolate && (hist->GetXaxis()->GetBinCenter(1) < kineProps[0]) && (hist->GetXaxis()->GetBinCenter(hist->GetXaxis()->GetNbins()) > kineProps[0])) { effProb = hist->Interpolate(kineProps[0]); } else { Int_t xbin = hist->GetXaxis()->FindFixBin(kineProps[0]); if (!xbin || ((hist->GetXaxis()->GetNbins() + 1) == xbin)) { - QERROR(WRN, "Tried to apply effiency but XBin: " + NUIS_ERR(WRN, "Tried to apply effiency but XBin: " << xbin << " is outside range (/" << hist->GetXaxis()->GetNbins() << "): Prop " << kineProps[0] << ", [" << hist->GetXaxis()->GetBinLowEdge(1) << " -- " << hist->GetXaxis()->GetBinUpEdge( hist->GetXaxis()->GetNbins())); } effProb = hist->GetBinContent(xbin); } break; } case 2: { TH2 *hist = static_cast(em.EffCurve); if (em.Interpolate && (hist->GetXaxis()->GetBinCenter(1) < kineProps[0]) && (hist->GetXaxis()->GetBinCenter(hist->GetXaxis()->GetNbins()) > kineProps[0]) && (hist->GetYaxis()->GetBinCenter(1) < kineProps[1]) && (hist->GetYaxis()->GetBinCenter(hist->GetYaxis()->GetNbins()) > kineProps[1])) { effProb = hist->Interpolate(kineProps[0], kineProps[1]); } else { Int_t xbin = hist->GetXaxis()->FindFixBin(kineProps[0]); Int_t ybin = hist->GetYaxis()->FindFixBin(kineProps[1]); if (!xbin || ((hist->GetXaxis()->GetNbins() + 1) == xbin)) { - QERROR(WRN, "Tried to apply effiency but XBin: " + NUIS_ERR(WRN, "Tried to apply effiency but XBin: " << xbin << " is outside range (/" << hist->GetXaxis()->GetNbins() << "): Prop " << kineProps[0] << ", [" << hist->GetXaxis()->GetBinLowEdge(1) << " -- " << hist->GetXaxis()->GetBinUpEdge( hist->GetXaxis()->GetNbins())); } if (!ybin || ((hist->GetYaxis()->GetNbins() + 1) == ybin)) { - QERROR(WRN, "Tried to apply effiency but XBin: " + NUIS_ERR(WRN, "Tried to apply effiency but XBin: " << ybin << " is outside range (/" << hist->GetYaxis()->GetNbins() << "): Prop " << kineProps[0] << ", [" << hist->GetYaxis()->GetBinLowEdge(1) << " -- " << hist->GetYaxis()->GetBinUpEdge( hist->GetYaxis()->GetNbins())); } effProb = hist->GetBinContent(xbin, ybin); #ifdef DEBUG_EFFAPP std::cout << "\t\t: XProp: " << kineProps[0] << ", YProp: " << kineProps[1] << " x/y bins: " << xbin << "/" << ybin << ". Prop ? " << effProb << std::endl; #endif } break; } case 3: { TH3 *hist = static_cast(em.EffCurve); if (em.Interpolate && (hist->GetXaxis()->GetBinCenter(1) < kineProps[0]) && (hist->GetXaxis()->GetBinCenter(hist->GetXaxis()->GetNbins()) > kineProps[0]) && (hist->GetYaxis()->GetBinCenter(1) < kineProps[1]) && (hist->GetYaxis()->GetBinCenter(hist->GetYaxis()->GetNbins()) > kineProps[2]) && (hist->GetZaxis()->GetBinCenter(hist->GetZaxis()->GetNbins()) > kineProps[2])) { effProb = hist->Interpolate(kineProps[0], kineProps[1], kineProps[2]); } else { Int_t xbin = hist->GetXaxis()->FindFixBin(kineProps[0]); Int_t ybin = hist->GetYaxis()->FindFixBin(kineProps[1]); Int_t zbin = hist->GetZaxis()->FindFixBin(kineProps[2]); if (!xbin || ((hist->GetXaxis()->GetNbins() + 1) == xbin)) { - QERROR(WRN, "Tried to apply effiency but XBin: " + NUIS_ERR(WRN, "Tried to apply effiency but XBin: " << xbin << " is outside range (/" << hist->GetXaxis()->GetNbins() << "): Prop " << kineProps[0] << ", [" << hist->GetXaxis()->GetBinLowEdge(1) << " -- " << hist->GetXaxis()->GetBinUpEdge( hist->GetXaxis()->GetNbins())); } if (!ybin || ((hist->GetYaxis()->GetNbins() + 1) == ybin)) { - QERROR(WRN, "Tried to apply effiency but XBin: " + NUIS_ERR(WRN, "Tried to apply effiency but XBin: " << ybin << " is outside range (/" << hist->GetYaxis()->GetNbins() << "): Prop " << kineProps[0] << ", [" << hist->GetYaxis()->GetBinLowEdge(1) << " -- " << hist->GetYaxis()->GetBinUpEdge( hist->GetYaxis()->GetNbins())); } if (!zbin || ((hist->GetZaxis()->GetNbins() + 1) == zbin)) { - QERROR(WRN, "Tried to apply effiency but ZBin: " + NUIS_ERR(WRN, "Tried to apply effiency but ZBin: " << zbin << " is outside range (/" << hist->GetZaxis()->GetNbins() << "): Prop " << kineProps[0] << ", [" << hist->GetZaxis()->GetBinLowEdge(1) << " -- " << hist->GetZaxis()->GetBinUpEdge( hist->GetZaxis()->GetNbins())); } effProb = hist->GetBinContent(xbin, ybin, zbin); } break; } } bool accepted = (rand.Uniform() < effProb); if (accepted) { #ifdef DEBUG_EFFAPP std::cout << " -- Reconstructed with probability: " << effProb << std::flush; #endif ri->RecObjMom.push_back(fp->P3()); ri->RecObjClass.push_back(fp->PDG()); continue; } #ifdef DEBUG_EFFAPP std::cout << " -- Rejected with probability: " << effProb << std::flush; #endif SlaveTA.SmearceptOneParticle(ri, fp #ifdef DEBUG_THRESACCEPT , p_it #endif ); } #ifdef DEBUG_EFFAPP std::cout << std::endl; #endif #ifdef DEBUG_EFFAPP std::cout << "Reconstructed " << ri->RecObjMom.size() << " particles. " << std::endl; #endif return ri; } diff --git a/src/Smearceptance/EnergyShuffler.cxx b/src/Smearceptance/EnergyShuffler.cxx index 7dc274f..ba2dafd 100644 --- a/src/Smearceptance/EnergyShuffler.cxx +++ b/src/Smearceptance/EnergyShuffler.cxx @@ -1,157 +1,157 @@ #include "EnergyShuffler.h" /// Node looks like /// /// /// /// void EnergyShuffler::Setup(nuiskey &nk) { std::vector shuffleDescriptors = nk.GetListOfChildNodes("Shuffler"); for (size_t t_it = 0; t_it < shuffleDescriptors.size(); ++t_it) { if (!shuffleDescriptors[t_it].Has("From") || !shuffleDescriptors[t_it].Has("Fraction")) { - QTHROW( + NUIS_ABORT( "Shuffler element must have at least the From and Fraction " "attributes."); } std::string from_pdgs_s = shuffleDescriptors[t_it].GetS("From"); std::vector from_pdgs_i = GeneralUtils::ParseToInt(from_pdgs_s, ","); if (!from_pdgs_i.size()) { - QTHROW("Shuffler element must have at least one From PDG specified."); + NUIS_ABORT("Shuffler element must have at least one From PDG specified."); } std::vector to_pdgs_i; if (shuffleDescriptors[t_it].Has("To")) { std::string to_pdgs_s = shuffleDescriptors[t_it].GetS("To"); to_pdgs_i = GeneralUtils::ParseToInt(to_pdgs_s, ","); } double Fraction = shuffleDescriptors[t_it].GetD("Fraction"); for (size_t f_it = 0; f_it < from_pdgs_i.size(); ++f_it) { ShuffleDescriptor sd; sd.ToPDGs = to_pdgs_i; sd.EFraction = Fraction; ShufflersDescriptors.push_back(std::make_pair(from_pdgs_i[f_it], sd)); - QLOG(FIT, "\tAdded EnergyShuffler from " + NUIS_LOG(FIT, "\tAdded EnergyShuffler from " << from_pdgs_i[f_it] << " to " << to_pdgs_i.size() << " particle species at " << sd.EFraction << " KE fraction.") } } } void EnergyShuffler::DoTheShuffle(FitEvent *fe) { std::map TakenEnergy; std::map NumParticlesToShare; // For each particle. // If in a from: take energy and add it to a sum. // Count particles of each species. for (size_t p_it = 0; p_it < fe->NParticles(); ++p_it) { FitParticle *fp = fe->GetParticle(p_it); if (fp->Status() != kFinalState) { continue; } int PDG = fp->PDG(); for (size_t sh_it = 0; sh_it < ShufflersDescriptors.size(); ++sh_it) { ShuffleDescriptor &sd = ShufflersDescriptors[sh_it].second; if (std::find(sd.ToPDGs.begin(), sd.ToPDGs.end(), PDG) != sd.ToPDGs.end()) { // If this is a particle // that we're giving energy // to, take note. if (!NumParticlesToShare.count(sh_it)) { NumParticlesToShare[sh_it] = 0; } NumParticlesToShare[sh_it]++; #ifdef DEBUG_ESHUFFLER std::cout << "Found recieving particle in pool " << sh_it << "." << std::endl; #endif } if (ShufflersDescriptors[sh_it].first != PDG) { continue; } double KETaken = sd.EFraction * fp->KE(); if (!TakenEnergy.count(sh_it)) { TakenEnergy[sh_it] = 0; } TakenEnergy[sh_it] += KETaken; #ifdef DEBUG_ESHUFFLER std::cout << "Taking " << KETaken << " KE from " << fp->PDG() << " (" << fp << ") with " << fp->KE() << " (mom: " << fp->p() << ")." << std::endl; #endif fe->RemoveKE(p_it, KETaken); fp = fe->GetParticle(p_it); #ifdef DEBUG_ESHUFFLER std::cout << "\t->" << fp->KE() << " (mom: " << fp->p() << ") => " << sh_it << "." << std::endl; #endif } } double LostEnergy = 0; for (std::map::iterator te_it = TakenEnergy.begin(); te_it != TakenEnergy.end(); ++te_it) { double EToGive = te_it->second; // Get energy share for each 'to' particle if (NumParticlesToShare.count(te_it->first)) { // If we have any particles // to share the energy // between. #ifdef DEBUG_ESHUFFLER std::cout << "Energy from Shuffler " << te_it->first << " " << EToGive << " shared between " << NumParticlesToShare[te_it->first] << " particle." << std::endl; #endif EToGive /= double(NumParticlesToShare[te_it->first]); } else { LostEnergy += EToGive; continue; } ShuffleDescriptor &sd = ShufflersDescriptors[te_it->first].second; for (size_t p_it = 0; p_it < fe->NParticles(); ++p_it) { FitParticle *fp = fe->GetParticle(p_it); if (fp->Status() != kFinalState) { continue; } int PDG = fp->PDG(); if (std::find(sd.ToPDGs.begin(), sd.ToPDGs.end(), PDG) == sd.ToPDGs.end()) { // This shuffler has no energy for this particle continue; } #ifdef DEBUG_ESHUFFLER std::cout << "Giving " << EToGive << " KE to " << fp->PDG() << " with " << fp->KE() << " (mom: " << fp->p() << ")." << std::endl; #endif fe->GiveKE(p_it, EToGive); fp = fe->GetParticle(p_it); #ifdef DEBUG_ESHUFFLER std::cout << "\t->" << fp->KE() << " (mom: " << fp->p() << ")." << std::endl; #endif } } #ifdef DEBUG_ESHUFFLER if (LostEnergy > 0) { std::cout << "" << LostEnergy << " of KE went nowhere..." << std::endl; } #endif } diff --git a/src/Smearceptance/GaussianSmearer.cxx b/src/Smearceptance/GaussianSmearer.cxx index 10eeebe..7fe6d66 100644 --- a/src/Smearceptance/GaussianSmearer.cxx +++ b/src/Smearceptance/GaussianSmearer.cxx @@ -1,529 +1,529 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "GaussianSmearer.h" namespace { GaussianSmearer::GSmearType GetVarType(std::string const &type) { if (type == "Absolute") { return GaussianSmearer::kAbsolute; } else if (type == "Fractional") { return GaussianSmearer::kFractional; } else if (type == "Function") { return GaussianSmearer::kFunction; } return GaussianSmearer::kNoType; } GaussianSmearer::DependVar GetKineType(std::string const &axisvar) { if (axisvar == "Momentum") { return GaussianSmearer::kMomentum; } else if (axisvar == "KE") { return GaussianSmearer::kKE; } else if (axisvar == "TEVis") { return GaussianSmearer::kTEVis; } else if (axisvar == "KEVis") { return GaussianSmearer::kKEVis; } else if (axisvar == "CosTheta") { return GaussianSmearer::kCosTheta; } else if (axisvar == "Theta") { return GaussianSmearer::kTheta; } - QTHROW("Failed to parse smear type from \"" << axisvar << "\""); + NUIS_ABORT("Failed to parse smear type from \"" << axisvar << "\""); } std::string GetKineTypeName(GaussianSmearer::DependVar dv) { switch (dv) { case GaussianSmearer::kMomentum: { return "Momentum"; } case GaussianSmearer::kKE: { return "KE"; } case GaussianSmearer::kTEVis: { return "TEVis"; } case GaussianSmearer::kKEVis: { return "KEVis"; } case GaussianSmearer::kCosTheta: { return "CosTheta"; } case GaussianSmearer::kTheta: { return "Theta"; } - default: { QTHROW("NO VAR!"); } + default: { NUIS_ABORT("NO VAR!"); } } } } /// Nodes look like: /// Function attribute is given to a TF1, where any "V"s are replaced with the /// selected kinematic property on an event-by-event basis. e.g Function="{V} + /// gaus({P1}),..." with P1="0.2", should give the same result as /// Type="kFractional" and Width="0.2". /// /// /// void GaussianSmearer::SpecifcSetup(nuiskey &nk) { rand.~TRandom3(); new (&rand) TRandom3(); std::vector smearDescriptors = nk.GetListOfChildNodes("Smear"); for (size_t t_it = 0; t_it < smearDescriptors.size(); ++t_it) { std::string pdgs_s = smearDescriptors[t_it].GetS("PDG"); std::vector pdgs_i = GeneralUtils::ParseToInt(pdgs_s, ","); double Width = smearDescriptors[t_it].Has("Width") ? smearDescriptors[t_it].GetD("Width") : 0xdeadbeef; GaussianSmearer::GSmearType Type = GetVarType(smearDescriptors[t_it].GetS("Type")); GaussianSmearer::DependVar Kinematics = GetKineType(smearDescriptors[t_it].GetS("Kinematics")); bool IsVisSmear = (Kinematics == GaussianSmearer::kKEVis) || (Kinematics == GaussianSmearer::kTEVis); TF1 *sf = NULL; if (Type == GaussianSmearer::kFunction) { std::string funcDescriptor = smearDescriptors[t_it].Has("Function") ? smearDescriptors[t_it].GetS("Function") : ""; if (funcDescriptor.size()) { std::vector funcP = GeneralUtils::ParseToStr(funcDescriptor, "$"); if (funcP.size() != 3) { - QTHROW( + NUIS_ABORT( "Expected Function attribute to contain 3 comma separated " "entries. e.g. Function=\"1/{V}$$\". "); } bool FoundParam; int pCtr = 1; std::map PVals; do { std::stringstream pv_str(""); pv_str << "P" << pCtr++; if (smearDescriptors[t_it].Has(pv_str.str())) { PVals.insert( std::make_pair(std::string("{") + pv_str.str() + "}", smearDescriptors[t_it].GetS(pv_str.str()))); FoundParam = true; } else { FoundParam = false; } } while (FoundParam); for (std::map::iterator v_it = PVals.begin(); v_it != PVals.end(); ++v_it) { funcP[0] = GeneralUtils::ReplaceAll(funcP[0], v_it->first, v_it->second); } funcP[0] = GeneralUtils::ReplaceAll(funcP[0], "{V}", "[0]"); - QLOG(FIT, "Added smearing func: " + NUIS_LOG(FIT, "Added smearing func: " << funcP[0] << ", [" << GeneralUtils::StrToDbl(funcP[1]) << " -- " << GeneralUtils::StrToDbl(funcP[2]) << "]."); sf = new TF1("smear_dummy", funcP[0].c_str(), GeneralUtils::StrToDbl(funcP[1]), GeneralUtils::StrToDbl(funcP[2])); } else { - QTHROW( + NUIS_ABORT( "Expected Function attribute with 3 comma separated " "entries. e.g. Function=\"1/x,,\". "); } } for (size_t pdg_it = 0; pdg_it < pdgs_i.size(); ++pdg_it) { if (IsVisSmear && VisGausSmears.count(pdgs_i[pdg_it])) { - QERROR(WRN, + NUIS_ERR(WRN, "Smearceptor " << ElementName << ":" << InstanceName << " already has a Visible Energy smearing function for PDG: " << pdgs_i[pdg_it]); } GSmear gs; gs.type = Type; gs.smearVar = Kinematics; gs.width = Width; gs.func = sf ? static_cast(sf->Clone()) : NULL; if (sf) { std::stringstream ss(""); ss << "GausSmear" << "_PDG" << pdgs_i[pdg_it]; gs.func->SetName(ss.str().c_str()); } if (IsVisSmear) { VisGausSmears[pdgs_i[pdg_it]] = gs; } else { TrackedGausSmears[pdgs_i[pdg_it]].push_back(gs); } - QLOG(SAM, "Added gaussian " + NUIS_LOG(SAM, "Added gaussian " << GetKineTypeName(gs.smearVar) << " smearing function for PDG: " << pdgs_i[pdg_it]); } delete sf; } } void GaussianSmearer::SmearceptOneParticle(RecoInfo *ri, FitParticle *fp #ifdef DEBUG_GAUSSSMEAR , size_t p_it #endif ) { #ifdef DEBUG_GAUSSSMEAR std::cout << std::endl; std::cout << "[" << p_it << "]: " << fp->PDG() << ", " << fp->Status() << ", " << fp->E() << " -- KE:" << fp->KE() << " Mom: " << fp->P3().Mag() << std::flush; #endif if (fp->Status() != kFinalState) { #ifdef DEBUG_GAUSSSMEAR std::cout << " -- Not final state." << std::flush; #endif return; } if ((TrackedGausSmears.count(fp->PDG()) + VisGausSmears.count(fp->PDG())) == 0) { #ifdef DEBUG_GAUSSSMEAR std::cout << " -- Undetectable." << std::flush; #endif return; } if (TrackedGausSmears.count(fp->PDG())) { TVector3 ThreeMom = fp->P3(); for (size_t sm_it = 0; sm_it < TrackedGausSmears[fp->PDG()].size(); ++sm_it) { GSmear &sm = TrackedGausSmears[fp->PDG()][sm_it]; double kineProp = 0; switch (sm.smearVar) { case GaussianSmearer::kMomentum: { kineProp = fp->P3().Mag(); break; } case GaussianSmearer::kKE: { kineProp = fp->KE(); break; } case GaussianSmearer::kCosTheta: { kineProp = fp->P3().CosTheta(); break; } case GaussianSmearer::kTheta: { kineProp = fp->P3().Theta(); break; } - default: { QTHROW("Trying to find particle value for a kNoVar."); } + default: { NUIS_ABORT("Trying to find particle value for a kNoVar."); } } double Smeared; size_t attempt = 0; bool ok = false; while (!ok) { if (sm.type == GaussianSmearer::kFunction) { sm.func->SetParameter(0, kineProp); Smeared = sm.func->GetRandom(); } else { double sThrow = rand.Gaus( 0, sm.width * ((sm.type == GaussianSmearer::kAbsolute) ? 1 : kineProp)); Smeared = kineProp + sThrow; } switch ( sm.smearVar) { // Different kinematics have different truncation. case GaussianSmearer::kMomentum: case GaussianSmearer::kKE: { ok = (Smeared > 0); break; } case GaussianSmearer::kCosTheta: { ok = ((Smeared >= -1) && (Smeared <= 1)); break; } case GaussianSmearer::kTheta: { ok = true; break; } - default: { QTHROW("SHOULDN'T BE HERE."); } + default: { NUIS_ABORT("SHOULDN'T BE HERE."); } } attempt++; if (attempt > 1000) { - QTHROW("Didn't get a good smeared value after " << attempt + NUIS_ABORT("Didn't get a good smeared value after " << attempt << " attempts."); } } switch (sm.smearVar) { case GaussianSmearer::kMomentum: { ThreeMom = (ThreeMom.Unit() * Smeared); break; } case GaussianSmearer::kKE: { double mass = fp->P4().M(); double TE = mass + Smeared; double magP = sqrt(TE * TE - mass * mass); ThreeMom = (ThreeMom.Unit() * magP); break; } case GaussianSmearer::kCosTheta: { ThreeMom.SetTheta(acos(Smeared)); break; } case GaussianSmearer::kTheta: { ThreeMom.SetTheta(Smeared); break; } default: {} } } #ifdef DEBUG_GAUSSSMEAR std::cout << " -- momentum reconstructed as Mom: " << ri->RecObjMom.back().Mag() << ", CT: " << ri->RecObjMom.back().CosTheta() << " from " << ThreeMom.Mag() << ", " << fp->P3().CosTheta() << " true." << std::endl; #endif ri->RecObjMom.push_back(ThreeMom); ri->RecObjClass.push_back(fp->PDG()); } else { // Smear to EVis GSmear &sm = VisGausSmears[fp->PDG()]; double kineProp = 0; switch (sm.smearVar) { case GaussianSmearer::kKEVis: { kineProp = fp->KE(); break; } case GaussianSmearer::kTEVis: { kineProp = fp->E(); break; } - default: { QTHROW("Trying to find particle value for a kNoVar."); } + default: { NUIS_ABORT("Trying to find particle value for a kNoVar."); } } double Smeared; if (sm.type == GaussianSmearer::kFunction) { sm.func->SetParameter(0, kineProp); Smeared = sm.func->GetRandom(); } else { double sThrow = rand.Gaus( 0, sm.width * ((sm.type == GaussianSmearer::kAbsolute) ? 1.0 : kineProp)); Smeared = kineProp + sThrow; } Smeared = (Smeared < 0) ? 0 : Smeared; #ifdef DEBUG_GAUSSSMEAR std::cout << " -- Saw " << Smeared << " visible energy from " << kineProp << " available. [PDG: " << fp->PDG() << "]" << std::endl; #endif ri->RecVisibleEnergy.push_back(Smeared); ri->TrueContribPDGs.push_back(fp->PDG()); } #ifdef DEBUG_GAUSSSMEAR std::cout << std::endl; #endif } RecoInfo *GaussianSmearer::Smearcept(FitEvent *fe) { RecoInfo *ri = new RecoInfo(); for (size_t p_it = 0; p_it < fe->NParticles(); ++p_it) { FitParticle *fp = fe->GetParticle(p_it); SmearceptOneParticle(ri, fp #ifdef DEBUG_GAUSSSMEAR , p_it #endif ); } return ri; } void GaussianSmearer::SmearceptOneParticle(TVector3 &RecObjMom, int RecObjClass) { if (!TrackedGausSmears.count(RecObjClass)) { return; } TVector3 ThreeMom = RecObjMom; TVector3 OriginalKP = ThreeMom; for (size_t sm_it = 0; sm_it < TrackedGausSmears[RecObjClass].size(); ++sm_it) { GSmear &sm = TrackedGausSmears[RecObjClass][sm_it]; double kineProp = 0; switch (sm.smearVar) { case GaussianSmearer::kMomentum: { kineProp = RecObjMom.Mag(); break; } case GaussianSmearer::kKE: { double mass = PhysConst::GetMass(RecObjClass) * 1.0E3; kineProp = sqrt(RecObjMom.Mag2() + mass * mass) - mass; break; } case GaussianSmearer::kCosTheta: { kineProp = OriginalKP.CosTheta(); break; } case GaussianSmearer::kTheta: { kineProp = OriginalKP.Theta(); break; } - default: { QTHROW("Trying to find particle value for a kNoVar."); } + default: { NUIS_ABORT("Trying to find particle value for a kNoVar."); } } double Smeared; bool ok = false; int attempt = 0; while (!ok) { if (sm.type == GaussianSmearer::kFunction) { sm.func->SetParameter(0, kineProp); Smeared = sm.func->GetRandom(); } else { double sThrow = rand.Gaus( 0, sm.width * ((sm.type == GaussianSmearer::kAbsolute) ? 1.0 : kineProp)); Smeared = kineProp + sThrow; #ifdef DEBUG_GAUSSSMEAR std::cout << "*** [" << attempt << "] Gaus(0," << (sm.width * (sm.type == GaussianSmearer::kAbsolute) ? 1 : kineProp) << "[" << sm.width << "]) = " << sThrow << ": " << kineProp << " -> " << Smeared << std::endl; #endif } switch (sm.smearVar) { // Different kinematics have different truncation. case GaussianSmearer::kMomentum: case GaussianSmearer::kKE: { ok = (Smeared > 0); break; } case GaussianSmearer::kCosTheta: { ok = ((Smeared >= -1) && (Smeared <= 1)); break; } case GaussianSmearer::kTheta: { ok = true; break; } - default: { QTHROW("SHOULDN'T BE HERE."); } + default: { NUIS_ABORT("SHOULDN'T BE HERE."); } } attempt++; if (attempt > 1000) { - QTHROW("Didn't get a good smeared value after " << attempt + NUIS_ABORT("Didn't get a good smeared value after " << attempt << " attempts."); } } switch (sm.smearVar) { case GaussianSmearer::kMomentum: { ThreeMom = (ThreeMom.Unit() * Smeared); break; } case GaussianSmearer::kKE: { double mass = PhysConst::GetMass(RecObjClass) * 1.0E3; double TE = mass + Smeared; double magP = sqrt(TE * TE - mass * mass); ThreeMom = (ThreeMom.Unit() * magP); break; } case GaussianSmearer::kCosTheta: { ThreeMom.SetTheta(acos(Smeared)); break; } case GaussianSmearer::kTheta: { ThreeMom.SetTheta(Smeared); break; } default: {} } } RecObjMom = ThreeMom; #ifdef DEBUG_GAUSSSMEAR std::cout << " -- momentum reconstructed as Mom: " << RecObjMom.Mag() << ", CT: " << RecObjMom.CosTheta() << " from " << OriginalKP.Mag() << ", " << OriginalKP.CosTheta() << " true." << std::endl; #endif } void GaussianSmearer::SmearceptOneParticle(double &RecVisibleEnergy, int TrueContribPDG) { if (!VisGausSmears.count(TrueContribPDG)) { return; } GSmear &sm = VisGausSmears[TrueContribPDG]; double kineProp = RecVisibleEnergy; double Smeared; if (sm.type == GaussianSmearer::kFunction) { sm.func->SetParameter(0, kineProp); Smeared = sm.func->GetRandom(); } else { double sThrow = rand.Gaus( 0, sm.width * ((sm.type == GaussianSmearer::kAbsolute) ? 1.0 : kineProp)); Smeared = kineProp + sThrow; } Smeared = (Smeared < 0) ? 0 : Smeared; #ifdef DEBUG_GAUSSSMEAR std::cout << " -- Saw " << Smeared << " visible energy from " << kineProp << " available. [PDG: " << TrueContribPDG << "]" << std::endl; #endif RecVisibleEnergy = Smeared; } void GaussianSmearer::SmearRecoInfo(RecoInfo *ri) { // Smear tracked particles for (size_t p_it = 0; p_it < ri->RecObjMom.size(); ++p_it) { SmearceptOneParticle(ri->RecObjMom[p_it], ri->RecObjClass[p_it]); } for (size_t ve_it = 0; ve_it < ri->RecVisibleEnergy.size(); ++ve_it) { SmearceptOneParticle(ri->RecVisibleEnergy[ve_it], ri->TrueContribPDGs[ve_it]); } #ifdef DEBUG_GAUSSSMEAR std::cout << std::endl; #endif } diff --git a/src/Smearceptance/ISmearcepter.cxx b/src/Smearceptance/ISmearcepter.cxx index 7f12bf8..b75b12c 100644 --- a/src/Smearceptance/ISmearcepter.cxx +++ b/src/Smearceptance/ISmearcepter.cxx @@ -1,11 +1,11 @@ #include "ISmearcepter.h" void ISmearcepter::Setup(nuiskey& nk) { InstanceName = nk.GetS("Name"); ElementName = nk.GetElementName(); - QLOG(SAM, "Setting up smearcepter (Type:" << ElementName << ", InstanceName: " + NUIS_LOG(SAM, "Setting up smearcepter (Type:" << ElementName << ", InstanceName: " << InstanceName << ")."); SpecifcSetup(nk); } diff --git a/src/Smearceptance/ISmearcepter.h b/src/Smearceptance/ISmearcepter.h index 9bef39d..0e814c0 100644 --- a/src/Smearceptance/ISmearcepter.h +++ b/src/Smearceptance/ISmearcepter.h @@ -1,87 +1,87 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #ifndef ISMEARCEPTER_HXX_SEEN #define ISMEARCEPTER_HXX_SEEN #include "FitEvent.h" #include "NuisKey.h" #include "TVector3.h" #include #include /// Base reconstructed information that a smearcepter should fill. /// Smearcepters may allocate and return instances of RecoInfo subclasses. struct RecoInfo { RecoInfo() : RecObjMom(), RecObjClass(), RecVisibleEnergy(0), TrueContribPDGs(), Weight(1){}; /// Reconstructed 3-momentum std::vector RecObjMom; ///\brief 'Class' of a reconstructed object. Might be a PDG particle code, or /// some smearer-defined classification like MIP track/EMShower/... std::vector RecObjClass; /// The visible energy not left by fully reconstructed tracks std::vector RecVisibleEnergy; /// The true pdgs of particles that contributed to the visible energy std::vector TrueContribPDGs; double Weight; }; class ISmearcepter { protected: std::string ElementName; std::string InstanceName; public: void Setup(nuiskey &); virtual void SpecifcSetup(nuiskey &) = 0; std::string GetName() { return InstanceName; } std::string GetElementName() { return ElementName; } virtual RecoInfo *Smearcept(FitEvent *) = 0; /// Helper method for using this class as a component in a more complex /// smearer virtual void SmearRecoInfo(RecoInfo *) { - QTHROW("Smearcepter: " << ElementName + NUIS_ABORT("Smearcepter: " << ElementName << " doesn't implement SmearRecoInfo."); ; } }; template ISmearcepter* BuildSmearcepter(nuiskey& nk) { ISmearcepter* rtn = new T(); rtn->Setup(nk); return rtn; } typedef ISmearcepter* (*SmearceptionFactory_fcn)(nuiskey&); #endif diff --git a/src/Smearceptance/MetaSimpleSmearcepter.cxx b/src/Smearceptance/MetaSimpleSmearcepter.cxx index 269e410..8b80334 100644 --- a/src/Smearceptance/MetaSimpleSmearcepter.cxx +++ b/src/Smearceptance/MetaSimpleSmearcepter.cxx @@ -1,74 +1,74 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "EfficiencyApplicator.h" #include "GaussianSmearer.h" #include "ThresholdAccepter.h" #include "TrackedMomentumMatrixSmearer.h" #include "VisECoalescer.h" #include "MetaSimpleSmearcepter.h" void MetaSimpleSmearcepter::SpecifcSetup(nuiskey &nk) { std::map factories; factories["ThresholdAccepter"] = &BuildSmearcepter; factories["EfficiencyApplicator"] = &BuildSmearcepter; factories["GaussianSmearer"] = &BuildSmearcepter; factories["VisECoalescer"] = &BuildSmearcepter; factories["TrackedMomentumMatrixSmearer"] = &BuildSmearcepter; std::vector smearcepters = nk.GetListOfChildNodes(); for (size_t smear_it = 0; smear_it < smearcepters.size(); ++smear_it) { std::string const &smearType = smearcepters[smear_it].GetElementName(); if (smearType == "EnergyShuffler") { ES = new EnergyShuffler(); ES->Setup(smearcepters[smear_it]); continue; } if (!factories.count(smearType)) { - QERROR(WRN, "No known smearer accepts elements named: \"" << smearType + NUIS_ERR(WRN, "No known smearer accepts elements named: \"" << smearType << "\""); continue; } Smearcepters.push_back(factories[smearType](smearcepters[smear_it])); - QLOG(FIT, "MetaSimpleSmearcepter adopted child smearcepter: " + NUIS_LOG(FIT, "MetaSimpleSmearcepter adopted child smearcepter: " << Smearcepters.back()->GetName() << " of type: " << Smearcepters.back()->GetElementName()); } NSmearcepters = Smearcepters.size(); } RecoInfo *MetaSimpleSmearcepter::Smearcept(FitEvent *fe) { if (ES) { ES->DoTheShuffle(fe); } RecoInfo *ri = NULL; for (size_t sm_it = 0; sm_it < NSmearcepters; ++sm_it) { if (!sm_it) { ri = Smearcepters[sm_it]->Smearcept(fe); } else { Smearcepters[sm_it]->SmearRecoInfo(ri); } } return ri; } diff --git a/src/Smearceptance/SmearceptanceUtils.cxx b/src/Smearceptance/SmearceptanceUtils.cxx index b7e3fac..de66d37 100644 --- a/src/Smearceptance/SmearceptanceUtils.cxx +++ b/src/Smearceptance/SmearceptanceUtils.cxx @@ -1,284 +1,284 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "SmearceptanceUtils.h" #include "TDecompSVD.h" #include "FitLogger.h" namespace SmearceptanceUtils { double Smear1DProp(TH2D *mapping, double TrueProp, TRandom3 *rnjesus) { bool myrand = false; if (!rnjesus) { rnjesus = new TRandom3(); myrand = true; } if (myrand) { delete rnjesus; } - QTHROW("NIMPLEMENTED"); + NUIS_ABORT("NIMPLEMENTED"); return 0; } TVectorD SVDInverseSolve(TVectorD *inp, TMatrixD *mapping) { TDecompSVD svd(*mapping); bool ok; TVectorD c_svd = svd.Solve(*inp, ok); if (!ok) { - QTHROW("Failed to solve SVD matrix equation."); + NUIS_ABORT("Failed to solve SVD matrix equation."); } return c_svd; } TVectorD SVDInverseSolve(TH1D *inp, TMatrixD *mapping) { TVectorD inp_v = GetVector(inp); return SVDInverseSolve(&inp_v, mapping); } TVectorD SVDInverseSolve(TH1D *inp, TH2D *mapping) { TMatrixD mat(mapping->GetXaxis()->GetNbins(), mapping->GetYaxis()->GetNbins()); for (Int_t xb_it = 0; xb_it < mapping->GetXaxis()->GetNbins(); ++xb_it) { for (Int_t yb_it = 0; yb_it < mapping->GetYaxis()->GetNbins(); ++yb_it) { mat[xb_it][yb_it] = mapping->GetBinContent(xb_it + 1, yb_it + 1); } } return SVDInverseSolve(inp, &mat); } TH2D *SVDGetInverse(TH2D *mapping, int NToTruncate) { TMatrixD mat = GetMatrix(mapping); if (mat.GetNcols() > mat.GetNrows()) { - QTHROW("Trying to invert a " << mat.GetNrows() << "x" << mat.GetNcols() + NUIS_ABORT("Trying to invert a " << mat.GetNrows() << "x" << mat.GetNcols() << " matrix."); } TH2D *inverse = dynamic_cast(mapping->Clone()); inverse->SetName("inverse"); inverse->Reset(); TDecompSVD svd(mat); svd.Decompose(); if (NToTruncate) { TVectorD Sig(svd.GetSig()); TMatrixD U(svd.GetU()); TMatrixD V(svd.GetV()); if (svd.GetV().TestBit(TMatrixD::kTransposed)) { - QTHROW("ARGHH"); + NUIS_ABORT("ARGHH"); } TMatrixD V_T = V.Transpose(V); TMatrixD Sig_TruncM(U.GetNrows(), V.GetNrows()); for (Int_t i = 0; i < U.GetNrows(); ++i) { for (Int_t j = 0; j < V.GetNrows(); ++j) { Sig_TruncM[i][j] = ((i != j) || (i >= (Sig.GetNrows() - NToTruncate))) ? 0 : Sig[i]; } } TMatrixD Trunc = U * Sig_TruncM * V_T; svd.~TDecompSVD(); new (&svd) TDecompSVD(Trunc); } TMatrixD inv = svd.Invert(); if (fabs(inv[mapping->GetXaxis()->GetNbins() / 2] [mapping->GetXaxis()->GetNbins() / 2] - mat[mapping->GetXaxis()->GetNbins() / 2] [mapping->GetXaxis()->GetNbins() / 2]) < std::numeric_limits::epsilon()) { - QTHROW("Failed to SVD invert matrix."); + NUIS_ABORT("Failed to SVD invert matrix."); } for (Int_t xb_it = 0; xb_it < inverse->GetXaxis()->GetNbins(); ++xb_it) { for (Int_t yb_it = 0; yb_it < inverse->GetYaxis()->GetNbins(); ++yb_it) { inverse->SetBinContent(xb_it + 1, yb_it + 1, inv[yb_it][xb_it]); } } return inverse; } void GetSVDDecomp(TH2D *mapping, TVectorD &Sig, TMatrixD &U, TMatrixD &V) { TMatrixD mat = GetMatrix(mapping); TDecompSVD svd(mat); U.ResizeTo(svd.GetU()); U = svd.GetU(); V.ResizeTo(svd.GetV()); V = svd.GetU(); Sig.ResizeTo(svd.GetSig()); Sig = svd.GetSig(); } TVectorD GetVector(TH1D *inp) { TVectorD vec(inp->GetXaxis()->GetNbins()); for (Int_t xb_it = 0; xb_it < inp->GetXaxis()->GetNbins(); ++xb_it) { vec[xb_it] = inp->GetBinContent(xb_it + 1); } return vec; } TVectorD GetErrorVector(TH1D *inp) { TVectorD vec(inp->GetXaxis()->GetNbins()); for (Int_t xb_it = 0; xb_it < inp->GetXaxis()->GetNbins(); ++xb_it) { vec[xb_it] = inp->GetBinError(xb_it + 1); } return vec; } TMatrixD GetMatrix(TH2D *inp) { TMatrixD mat(inp->GetYaxis()->GetNbins(), inp->GetXaxis()->GetNbins()); for (Int_t xb_it = 0; xb_it < inp->GetXaxis()->GetNbins(); ++xb_it) { for (Int_t yb_it = 0; yb_it < inp->GetYaxis()->GetNbins(); ++yb_it) { mat[yb_it][xb_it] = inp->GetBinContent(xb_it + 1, yb_it + 1); } } return mat; } TH1D *GetTH1FromVector(TVectorD const &inp, TH1D *templ) { TH1D *hist; if (templ) { hist = static_cast(templ->Clone()); hist->Reset(); hist->SetName("vectHist"); } else { hist = new TH1D("vectHist", "", inp.GetNrows(), 0, inp.GetNrows()); } hist->SetDirectory(NULL); for (Int_t xb_it = 0; xb_it < inp.GetNrows(); ++xb_it) { hist->SetBinContent(xb_it + 1, inp[xb_it]); } return hist; } TH2D *GetTH2FromMatrix(TMatrixD const &inp, TH2D *templ) { TH2D *hist; if (templ) { hist = static_cast(templ->Clone()); hist->Reset(); hist->SetName("matHist"); } else { hist = new TH2D("matHist", "", inp.GetNcols(), 0, inp.GetNcols(), inp.GetNrows(), 0, inp.GetNrows()); } hist->SetDirectory(NULL); for (Int_t xb_it = 0; xb_it < inp.GetNcols(); ++xb_it) { for (Int_t yb_it = 0; yb_it < inp.GetNrows(); ++yb_it) { hist->SetBinContent(xb_it + 1, yb_it + 1, inp[yb_it][xb_it]); } } return hist; } TVectorD ThrowVectFromHist(TH1D *inp, TRandom3 *rnjesus, bool allowNeg) { TVectorD vec(inp->GetXaxis()->GetNbins()); for (Int_t xb_it = 0; xb_it < inp->GetXaxis()->GetNbins(); ++xb_it) { size_t attempt = 0; do { if (attempt > 1000) { - QTHROW("Looks like we aren't getting anywhere with this bin: " + NUIS_ABORT("Looks like we aren't getting anywhere with this bin: " << inp->GetBinContent(xb_it + 1) << " +- " << inp->GetBinError(xb_it + 1)); } vec[xb_it] = inp->GetBinContent(xb_it + 1) + inp->GetBinError(xb_it + 1) * rnjesus->Gaus(); attempt++; } while ((!allowNeg) && (vec[xb_it] < 0)); } return vec; } void PushTH1ThroughMatrixWithErrors(TH1D *inp, TH1D *oup, TMatrixD &response, size_t NToys, bool allowNeg) { TRandom3 rnjesus; oup->Reset(); TVectorD Mean(oup->GetXaxis()->GetNbins()); TVectorD RMS(oup->GetXaxis()->GetNbins()); std::vector Toys; Toys.reserve(NToys); double NToysFact = 1.0 / double(NToys); for (size_t t_it = 0; t_it < NToys; ++t_it) { TVectorD Toy = ThrowVectFromHist(inp, &rnjesus, allowNeg); TVectorD UnfoldToy = response * Toy; for (Int_t bi_it = 0; bi_it < oup->GetXaxis()->GetNbins(); ++bi_it) { Mean[bi_it] += UnfoldToy[bi_it] * NToysFact; } Toys.push_back(UnfoldToy); } for (size_t t_it = 0; t_it < NToys; ++t_it) { for (Int_t bi_it = 0; bi_it < oup->GetXaxis()->GetNbins(); ++bi_it) { RMS[bi_it] += (Mean[bi_it] - Toys[t_it][bi_it]) * (Mean[bi_it] - Toys[t_it][bi_it]) * NToysFact; } } for (Int_t bi_it = 0; bi_it < oup->GetXaxis()->GetNbins(); ++bi_it) { oup->SetBinContent(bi_it + 1, Mean[bi_it]); oup->SetBinError(bi_it + 1, sqrt(RMS[bi_it])); } } TH2D * SwapXYTH2D(TH2D *templ) { TH2D *Swapped = new TH2D( (std::string(templ->GetName()) + "_c").c_str(), "", templ->GetYaxis()->GetNbins(), templ->GetYaxis()->GetXbins()->GetArray(), templ->GetXaxis()->GetNbins(), templ->GetXaxis()->GetXbins()->GetArray()); Swapped->Reset(); Swapped->SetDirectory(NULL); std::string title = ";"; title += templ->GetYaxis()->GetTitle(); title += ";"; title += templ->GetXaxis()->GetTitle(); Swapped->SetTitle(title.c_str()); for (Int_t x_it = 0; x_it < templ->GetXaxis()->GetNbins() + 2; ++x_it) { for (Int_t y_it = 0; y_it < templ->GetYaxis()->GetNbins() + 2; ++y_it) { Swapped->SetBinContent(y_it, x_it, templ->GetBinContent(x_it, y_it)); Swapped->SetBinError(y_it, x_it, templ->GetBinError(x_it, y_it)); } } return Swapped; } } diff --git a/src/Smearceptance/Smearcepterton.cxx b/src/Smearceptance/Smearcepterton.cxx index d8ea280..36db754 100644 --- a/src/Smearceptance/Smearcepterton.cxx +++ b/src/Smearceptance/Smearcepterton.cxx @@ -1,352 +1,352 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "Smearcepterton.h" #include "EfficiencyApplicator.h" #include "GaussianSmearer.h" #include "MetaSimpleSmearcepter.h" #include "ThresholdAccepter.h" #include "TrackedMomentumMatrixSmearer.h" #include "VisECoalescer.h" #include #ifdef __USE_DYNSAMPLES__ #include "TRegexp.h" #include // linux #include DynamicSmearceptorFactory::DynamicSmearceptorFactory() : NSmearceptors(0), NManifests(0) { LoadPlugins(); - QLOG(FIT, "Loaded " << NSmearceptors << " from " << NManifests + NUIS_LOG(FIT, "Loaded " << NSmearceptors << " from " << NManifests << " shared object libraries."); } DynamicSmearceptorFactory* DynamicSmearceptorFactory::glblDSF = NULL; DynamicSmearceptorFactory::PluginManifest::~PluginManifest() { for (size_t i_it = 0; i_it < Instances.size(); ++i_it) { (*(DSF_DestroySmearceptor))(Instances[i_it]); } } std::string EnsureTrailingSlash(std::string const& inp) { if (!inp.length()) { return "/"; } if (inp[inp.length() - 1] == '/') { return inp; } return inp + "/"; } void DynamicSmearceptorFactory::LoadPlugins() { std::vector SearchDirectories; if (Config::HasPar("dynamic_smearceptor.path")) { SearchDirectories = GeneralUtils::ParseToStr( Config::GetParS("dynamic_smearceptor.path"), ":"); } char const* envPath = getenv("NUISANCE_DS_PATH"); if (envPath) { std::vector envPaths = GeneralUtils::ParseToStr(envPath, ":"); for (size_t ep_it = 0; ep_it < envPaths.size(); ++ep_it) { SearchDirectories.push_back(envPaths[ep_it]); } } if (!SearchDirectories.size()) { char const* pwdPath = getenv("PWD"); if (pwdPath) { SearchDirectories.push_back(pwdPath); } } for (size_t sp_it = 0; sp_it < SearchDirectories.size(); ++sp_it) { std::string dirpath = EnsureTrailingSlash(SearchDirectories[sp_it]); - QLOG(FIT, "Searching for dynamic smearceptor manifests in: " << dirpath); + NUIS_LOG(FIT, "Searching for dynamic smearceptor manifests in: " << dirpath); Ssiz_t len = 0; DIR* dir; struct dirent* ent; dir = opendir(dirpath.c_str()); if (dir != NULL) { TRegexp matchExp("*.so", true); while ((ent = readdir(dir)) != NULL) { if (matchExp.Index(TString(ent->d_name), &len) != Ssiz_t(-1)) { - QLOG(FIT, "\tFound shared object: " + NUIS_LOG(FIT, "\tFound shared object: " << ent->d_name << " checking for relevant methods..."); void* dlobj = dlopen((dirpath + ent->d_name).c_str(), RTLD_NOW | RTLD_GLOBAL); char const* dlerr_cstr = dlerror(); std::string dlerr; if (dlerr_cstr) { dlerr = dlerr_cstr; } if (dlerr.length()) { - QERROR(WRN, "\tDL Load Error: " << dlerr); + NUIS_ERR(WRN, "\tDL Load Error: " << dlerr); continue; } PluginManifest plgManif; plgManif.dllib = dlobj; plgManif.soloc = (dirpath + ent->d_name); plgManif.DSF_NSmearceptors = reinterpret_cast( dlsym(dlobj, "DSF_NSmearceptors")); dlerr = ""; dlerr_cstr = dlerror(); if (dlerr_cstr) { dlerr = dlerr_cstr; } if (dlerr.length()) { - QERROR(WRN, "\tFailed to load symbol \"DSF_NSmearceptors\" from " + NUIS_ERR(WRN, "\tFailed to load symbol \"DSF_NSmearceptors\" from " << (dirpath + ent->d_name) << ": " << dlerr); dlclose(dlobj); continue; } plgManif.DSF_GetSmearceptorName = reinterpret_cast( dlsym(dlobj, "DSF_GetSmearceptorName")); dlerr = ""; dlerr_cstr = dlerror(); if (dlerr_cstr) { dlerr = dlerr_cstr; } if (dlerr.length()) { - QERROR(WRN, + NUIS_ERR(WRN, "\tFailed to load symbol \"DSF_GetSmearceptorName\" from " << (dirpath + ent->d_name) << ": " << dlerr); dlclose(dlobj); continue; } plgManif.DSF_GetSmearceptor = reinterpret_cast( dlsym(dlobj, "DSF_GetSmearceptor")); dlerr = ""; dlerr_cstr = dlerror(); if (dlerr_cstr) { dlerr = dlerr_cstr; } if (dlerr.length()) { - QERROR(WRN, "\tFailed to load symbol \"DSF_GetSmearceptor\" from " + NUIS_ERR(WRN, "\tFailed to load symbol \"DSF_GetSmearceptor\" from " << (dirpath + ent->d_name) << ": " << dlerr); dlclose(dlobj); continue; } plgManif.DSF_DestroySmearceptor = reinterpret_cast( dlsym(dlobj, "DSF_DestroySmearceptor")); dlerr = ""; dlerr_cstr = dlerror(); if (dlerr_cstr) { dlerr = dlerr_cstr; } if (dlerr.length()) { - QERROR(WRN, "Failed to load symbol \"DSF_DestroySmearceptor\" from " + NUIS_ERR(WRN, "Failed to load symbol \"DSF_DestroySmearceptor\" from " << (dirpath + ent->d_name) << ": " << dlerr); dlclose(dlobj); continue; } plgManif.NSmearceptors = (*(plgManif.DSF_NSmearceptors))(); - QLOG(FIT, "\tSuccessfully loaded dynamic smearceptor manifest: " + NUIS_LOG(FIT, "\tSuccessfully loaded dynamic smearceptor manifest: " << plgManif.soloc << ". Contains " << plgManif.NSmearceptors << " smearceptors."); for (size_t smp_it = 0; smp_it < plgManif.NSmearceptors; ++smp_it) { char const* smp_name = (*(plgManif.DSF_GetSmearceptorName))(smp_it); if (!smp_name) { - QTHROW("Could not load smearceptor " + NUIS_ABORT("Could not load smearceptor " << smp_it << " / " << plgManif.NSmearceptors << " from " << plgManif.soloc); } if (Smearceptors.count(smp_name)) { - QERROR(WRN, "Already loaded a smearceptor named: \"" + NUIS_ERR(WRN, "Already loaded a smearceptor named: \"" << smp_name << "\". cannot load duplciates. This " "smearceptor will be skipped."); continue; } plgManif.SmearceptorsProvided.push_back(smp_name); Smearceptors[smp_name] = std::make_pair(plgManif.soloc, smp_it); - QLOG(FIT, "\t\t" << smp_name); + NUIS_LOG(FIT, "\t\t" << smp_name); } if (plgManif.SmearceptorsProvided.size()) { Manifests[plgManif.soloc] = plgManif; NSmearceptors += plgManif.SmearceptorsProvided.size(); NManifests++; } else { dlclose(dlobj); } } } closedir(dir); } else { - QERROR(WRN, "Tried to open non-existant directory."); + NUIS_ERR(WRN, "Tried to open non-existant directory."); } } } DynamicSmearceptorFactory& DynamicSmearceptorFactory::Get() { if (!glblDSF) { glblDSF = new DynamicSmearceptorFactory(); } return *glblDSF; } void DynamicSmearceptorFactory::Print() { std::map > ManifestSmearceptors; for (std::map >::iterator smp_it = Smearceptors.begin(); smp_it != Smearceptors.end(); ++smp_it) { if (!ManifestSmearceptors.count(smp_it->second.first)) { ManifestSmearceptors[smp_it->second.first] = std::vector(); } ManifestSmearceptors[smp_it->second.first].push_back(smp_it->first); } - QLOG(FIT, "Dynamic smearceptor manifest: "); + NUIS_LOG(FIT, "Dynamic smearceptor manifest: "); for (std::map >::iterator m_it = ManifestSmearceptors.begin(); m_it != ManifestSmearceptors.end(); ++m_it) { - QLOG(FIT, "\tLibrary " << m_it->first << " contains: "); + NUIS_LOG(FIT, "\tLibrary " << m_it->first << " contains: "); for (size_t s_it = 0; s_it < m_it->second.size(); ++s_it) { - QLOG(FIT, "\t\t" << m_it->second[s_it]); + NUIS_LOG(FIT, "\t\t" << m_it->second[s_it]); } } } bool DynamicSmearceptorFactory::HasSmearceptor(std::string const& name) { return Smearceptors.count(name); } bool DynamicSmearceptorFactory::HasSmearceptor(nuiskey& smearceptorkey) { return HasSmearceptor(smearceptorkey.GetElementName()); } ISmearcepter* DynamicSmearceptorFactory::CreateSmearceptor( nuiskey& smearceptorkey) { if (!HasSmearceptor(smearceptorkey)) { - QERROR(WRN, "Asked to load unknown smearceptor: \"" + NUIS_ERR(WRN, "Asked to load unknown smearceptor: \"" << smearceptorkey.GetElementName() << "\"."); return NULL; } std::pair smearceptor = Smearceptors[smearceptorkey.GetElementName()]; - QLOG(SAM, "\tLoading smearceptor " << smearceptor.second << " from " + NUIS_LOG(SAM, "\tLoading smearceptor " << smearceptor.second << " from " << smearceptor.first); ISmearcepter* smear = (*(Manifests[smearceptor.first].DSF_GetSmearceptor))( smearceptor.second, &smearceptorkey); return smear; } DynamicSmearceptorFactory::~DynamicSmearceptorFactory() { Manifests.clear(); } #endif Smearcepterton* Smearcepterton::_inst = NULL; Smearcepterton& Smearcepterton::Get() { if (!_inst) { _inst = new Smearcepterton(); } return *_inst; } Smearcepterton::Smearcepterton() { InitialiserSmearcepters(); } void Smearcepterton::InitialiserSmearcepters() { // hard coded list of tag name -> smearcepter factories, add here to add your // own. std::map factories; factories["ThresholdAccepter"] = &BuildSmearcepter; factories["EfficiencyApplicator"] = &BuildSmearcepter; factories["GaussianSmearer"] = &BuildSmearcepter; factories["TrackedMomentumMatrixSmearer"] = &BuildSmearcepter; factories["VisECoalescer"] = &BuildSmearcepter; factories["MetaSimpleSmearcepter"] = &BuildSmearcepter; Config::Get().PrintXML(NULL); std::vector smearcepterBlocks = Config::QueryKeys("smearcepters"); // std::cout << "[INFO]: " << nodelist.size() << " smearcepter nodes." << std::endl; // for(size_t i = 0; i < nodelist.size(); ++i){ // Config::Get().PrintXML(nodelist[i]); // } for (size_t smearB_it = 0; smearB_it < smearcepterBlocks.size(); ++smearB_it) { std::vector smearcepters = smearcepterBlocks[smearB_it].GetListOfChildNodes(); for (size_t smear_it = 0; smear_it < smearcepters.size(); ++smear_it) { std::string const& smearType = smearcepters[smear_it].GetElementName(); ISmearcepter* smearer = NULL; #ifdef __USE_DYNSAMPLES__ if (DynamicSmearceptorFactory::Get().HasSmearceptor(smearType)) { smearer = DynamicSmearceptorFactory::Get().CreateSmearceptor( smearcepters[smear_it]); } else #endif { if (!factories.count(smearType)) { - QERROR(WRN, "No known smearer accepts elements named: \"" << smearType + NUIS_ERR(WRN, "No known smearer accepts elements named: \"" << smearType << "\""); continue; } smearer = factories[smearType](smearcepters[smear_it]); } if (!smearer) { - QTHROW("Failed to load smearceptor."); + NUIS_ABORT("Failed to load smearceptor."); } if (!smearer->GetName().length()) { - QTHROW("Smearcepter type " << smearer->GetElementName() + NUIS_ABORT("Smearcepter type " << smearer->GetElementName() << " had no instance name."); } Smearcepters[smearer->GetName()] = smearer; - QLOG(FIT, "Configured smearer named: " << smearer->GetName() + NUIS_LOG(FIT, "Configured smearer named: " << smearer->GetName() << " of type: " << smearer->GetElementName()); } } } diff --git a/src/Smearceptance/Smearcepterton.h b/src/Smearceptance/Smearcepterton.h index 5e2d4ff..1e6c6f6 100644 --- a/src/Smearceptance/Smearcepterton.h +++ b/src/Smearceptance/Smearcepterton.h @@ -1,112 +1,112 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #ifndef SMEARCEPTERTON_HXX_SEEN #define SMEARCEPTERTON_HXX_SEEN #include "FitLogger.h" #include "ISmearcepter.h" #include #include #ifdef __USE_DYNSAMPLES__ /// Expect each .so containing smearceptors to supply 4 c-style methods. /// int DSF_NSmearceptors(); /// char const * DSF_GetSmearceptorName(int); /// ISmearcepter* DSF_GetSmearceptor(int, nuiskey *); /// void DSF_DestroySmearceptor(ISmearcepter *); class DynamicSmearceptorFactory { size_t NSmearceptors; size_t NManifests; DynamicSmearceptorFactory(); static DynamicSmearceptorFactory* glblDSF; typedef int (*DSF_NSmearceptors_ptr)(void); typedef char const* (*DSF_GetSmearceptorName_ptr)(int); typedef ISmearcepter* (*DSF_GetSmearceptor_ptr)(int, nuiskey *); typedef void (*DSF_DestroySmearceptor_ptr)(ISmearcepter*); struct PluginManifest { void* dllib; DSF_NSmearceptors_ptr DSF_NSmearceptors; DSF_GetSmearceptorName_ptr DSF_GetSmearceptorName; DSF_GetSmearceptor_ptr DSF_GetSmearceptor; DSF_DestroySmearceptor_ptr DSF_DestroySmearceptor; std::string soloc; std::vector Instances; std::vector SmearceptorsProvided; size_t NSmearceptors; ~PluginManifest(); }; std::map Manifests; std::map > Smearceptors; void LoadPlugins(); public: static DynamicSmearceptorFactory& Get(); void Print(); bool HasSmearceptor(std::string const& name); bool HasSmearceptor(nuiskey& smearceptorkey); ISmearcepter* CreateSmearceptor(nuiskey& smearceptorkey); ~DynamicSmearceptorFactory(); }; #endif /// Singleton handling the loading and configuring of known smearcepters. class Smearcepterton { Smearcepterton(); void InitialiserSmearcepters(); static Smearcepterton *_inst; std::map Smearcepters; public: static Smearcepterton &Get(); ISmearcepter &GetSmearcepter(std::string const &name) { if (!Smearcepters.count(name) || !Smearcepters[name]) { - QERROR(FTL, "Known smearcepters:"); + NUIS_ERR(FTL, "Known smearcepters:"); for (std::map::iterator sm_it = Smearcepters.begin(); sm_it != Smearcepters.end(); ++sm_it) { - QERROR(FTL, "\t" << sm_it->first); + NUIS_ERR(FTL, "\t" << sm_it->first); } - QTHROW("No smearcepter named: \"" << name << "\" defined."); + NUIS_ABORT("No smearcepter named: \"" << name << "\" defined."); } return *Smearcepters[name]; } }; #endif diff --git a/src/Smearceptance/ThresholdAccepter.cxx b/src/Smearceptance/ThresholdAccepter.cxx index e82e5ea..f2e8e44 100644 --- a/src/Smearceptance/ThresholdAccepter.cxx +++ b/src/Smearceptance/ThresholdAccepter.cxx @@ -1,330 +1,330 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "ThresholdAccepter.h" namespace { ThresholdAccepter::KineVar GetKineType(nuiskey &nk) { if (nk.Has("RecoThresholdMomentum_MeV")) { return ThresholdAccepter::kMomentum; } else if (nk.Has("RecoThresholdKE_MeV")) { return ThresholdAccepter::kKE; } else if (nk.Has("RecoThresholdCosTheta_Max")) { return ThresholdAccepter::kCosTheta_Max; } else if (nk.Has("RecoThresholdCosTheta_Min")) { return ThresholdAccepter::kCosTheta_Min; } else if (nk.Has("RecoThresholdAbsCosTheta_Max")) { return ThresholdAccepter::kAbsCosTheta_Max; } else if (nk.Has("RecoThresholdAbsCosTheta_Min")) { return ThresholdAccepter::kAbsCosTheta_Min; } else { - QTHROW("Cannot determine the threshold type for Smearcepter element."); + NUIS_ABORT("Cannot determine the threshold type for Smearcepter element."); } return ThresholdAccepter::kNoVar; } std::string GetKineTypeName(ThresholdAccepter::KineVar kv) { switch (kv) { case ThresholdAccepter::kMomentum: return "Momentum"; case ThresholdAccepter::kKE: return "KE"; case ThresholdAccepter::kCosTheta_Max: return "CosTheta_Max"; case ThresholdAccepter::kCosTheta_Min: return "CosTheta_Min"; case ThresholdAccepter::kAbsCosTheta_Max: return "AbsCosTheta_Max"; case ThresholdAccepter::kAbsCosTheta_Min: return "CosTheta_Min"; default: return "NoVar"; } } double GetKineThreshold(nuiskey &nk, ThresholdAccepter::KineVar kv) { switch (kv) { case ThresholdAccepter::kMomentum: return nk.GetD("RecoThresholdMomentum_MeV"); case ThresholdAccepter::kKE: return nk.GetD("RecoThresholdKE_MeV"); case ThresholdAccepter::kCosTheta_Max: return nk.GetD("RecoThresholdCosTheta_Max"); case ThresholdAccepter::kCosTheta_Min: return nk.GetD("RecoThresholdCosTheta_Min"); case ThresholdAccepter::kAbsCosTheta_Max: return nk.GetD("RecoThresholdAbsCosTheta_Max"); case ThresholdAccepter::kAbsCosTheta_Min: return nk.GetD("RecoThresholdAbsCosTheta_Min"); default: return 0; } } double GetKineVal(FitParticle *fp, ThresholdAccepter::Thresh &rt) { switch (rt.ThresholdType) { case ThresholdAccepter::kMomentum: return fp->P3().Mag(); case ThresholdAccepter::kKE: return fp->KE(); case ThresholdAccepter::kCosTheta_Max: return fp->P3().CosTheta(); case ThresholdAccepter::kCosTheta_Min: return fp->P3().CosTheta(); case ThresholdAccepter::kAbsCosTheta_Max: return fabs(fp->P3().CosTheta()); case ThresholdAccepter::kAbsCosTheta_Min: return fabs(fp->P3().CosTheta()); default: return 0; } } bool PassesThreshold(FitParticle *fp, ThresholdAccepter::Thresh &rt) { switch (rt.ThresholdType) { case ThresholdAccepter::kMomentum: return (fp->P3().Mag() > rt.ThresholdVal); case ThresholdAccepter::kKE: return (fp->KE() > rt.ThresholdVal); case ThresholdAccepter::kCosTheta_Max: return (fp->P3().CosTheta() < rt.ThresholdVal); case ThresholdAccepter::kCosTheta_Min: return (fp->P3().CosTheta() > rt.ThresholdVal); case ThresholdAccepter::kAbsCosTheta_Max: return (fabs(fp->P3().CosTheta()) < rt.ThresholdVal); case ThresholdAccepter::kAbsCosTheta_Min: return (fabs(fp->P3().CosTheta()) > rt.ThresholdVal); default: return 0; } } } /// Reads particle threshold nodes /// /// Nodes look like: /// /// /// /// /// /// /// /// void ThresholdAccepter::SpecifcSetup(nuiskey &nk) { std::vector recoThresholdDescriptors = nk.GetListOfChildNodes("RecoThreshold"); for (size_t t_it = 0; t_it < recoThresholdDescriptors.size(); ++t_it) { std::string pdgs_s = recoThresholdDescriptors[t_it].GetS("PDG"); std::vector pdgs_i = GeneralUtils::ParseToInt(pdgs_s, ","); for (size_t pdg_it = 0; pdg_it < pdgs_i.size(); ++pdg_it) { Thresh t; t.ThresholdType = GetKineType(recoThresholdDescriptors[t_it]); t.ThresholdVal = GetKineThreshold(recoThresholdDescriptors[t_it], t.ThresholdType); ReconThresholds[pdgs_i[pdg_it]].push_back(t); - QLOG(FIT, "Added reconstruction threshold of type: " + NUIS_LOG(FIT, "Added reconstruction threshold of type: " << ReconThresholds[pdgs_i[pdg_it]].back().ThresholdVal << " " << GetKineTypeName( ReconThresholds[pdgs_i[pdg_it]].back().ThresholdType) << ", for PDG: " << pdgs_i[pdg_it]); } } std::vector visThresholdDescriptors = nk.GetListOfChildNodes("VisThreshold"); for (size_t t_it = 0; t_it < visThresholdDescriptors.size(); ++t_it) { std::string pdgs_s = visThresholdDescriptors[t_it].GetS("PDG"); std::vector pdgs_i = GeneralUtils::ParseToInt(pdgs_s, ","); for (size_t pdg_it = 0; pdg_it < pdgs_i.size(); ++pdg_it) { if (VisThresholds.count(pdgs_i[pdg_it])) { - QERROR(WRN, "Smearceptor " << ElementName << ":" << InstanceName + NUIS_ERR(WRN, "Smearceptor " << ElementName << ":" << InstanceName << " already has a threshold for PDG: " << pdgs_i[pdg_it]); } VisThresh vt; vt.UseKE = visThresholdDescriptors[t_it].Has("Contrib") ? (visThresholdDescriptors[t_it].GetS("Contrib") == "K") : false; vt.Fraction = visThresholdDescriptors[t_it].Has("Fraction") ? visThresholdDescriptors[t_it].GetD("Fraction") : 1; if (visThresholdDescriptors[t_it].Has("VisThresholdKE_MeV")) { vt.ThresholdType = ThresholdAccepter::kKE; vt.ThresholdVal = visThresholdDescriptors[t_it].GetD("VisThresholdKE_MeV"); } else if (visThresholdDescriptors[t_it].Has( "VisThresholdMomentum_MeV")) { vt.ThresholdType = ThresholdAccepter::kMomentum; vt.ThresholdVal = visThresholdDescriptors[t_it].GetD("VisThresholdMomentum_MeV"); ; } else { - QERROR(WRN, "Smearceptor " + NUIS_ERR(WRN, "Smearceptor " << ElementName << ":" << InstanceName << " cannot find threshold information for PDG: " << pdgs_i[pdg_it]); continue; } VisThresholds[pdgs_i[pdg_it]] = vt; - QLOG(FIT, + NUIS_LOG(FIT, "Added visibility threshold of MeV " << VisThresholds[pdgs_i[pdg_it]].ThresholdVal << " " << GetKineTypeName(VisThresholds[pdgs_i[pdg_it]].ThresholdType) << ", for PDG: " << pdgs_i[pdg_it] << ". If visible, particle deposits: " << (VisThresholds[pdgs_i[pdg_it]].UseKE ? "KE" : "TE")); } } } void ThresholdAccepter::SmearceptOneParticle(RecoInfo *ri, FitParticle *fp #ifdef DEBUG_THRESACCEPT , size_t p_it #endif ) { #ifdef DEBUG_THRESACCEPT std::cout << std::endl; std::cout << "[" << p_it << " = " << fp << "]: " << fp->PDG() << ", " << fp->Status() << ", " << fp->E() << " -- KE:" << fp->KE() << " Mom: " << fp->P3().Mag() << std::flush; #endif if (fp->Status() != kFinalState) { #ifdef DEBUG_THRESACCEPT std::cout << " -- Not final state." << std::flush; #endif return; } if ((ReconThresholds.count(fp->PDG()) + VisThresholds.count(fp->PDG())) == 0) { #ifdef DEBUG_THRESACCEPT std::cout << " -- Undetectable." << std::flush; #endif return; } // If no reco thresholds it should fall through to EVis bool Passes = ReconThresholds[fp->PDG()].size(); bool FailEnergyThresh = !ReconThresholds[fp->PDG()].size(); for (size_t rt_it = 0; rt_it < ReconThresholds[fp->PDG()].size(); ++rt_it) { bool Passed = PassesThreshold(fp, ReconThresholds[fp->PDG()][rt_it]); if (!Passed) { #ifdef DEBUG_THRESACCEPT std::cout << "\n\t -- Rejected. (" << GetKineTypeName( ReconThresholds[fp->PDG()][rt_it].ThresholdType) << " Threshold: " << ReconThresholds[fp->PDG()][rt_it].ThresholdVal << " | " << GetKineVal(fp, ReconThresholds[fp->PDG()][rt_it]) << ")" << std::flush; #endif if ((ReconThresholds[fp->PDG()][rt_it].ThresholdType == ThresholdAccepter::kMomentum) || (ReconThresholds[fp->PDG()][rt_it].ThresholdType == ThresholdAccepter::kKE)) { FailEnergyThresh = true; } } else { #ifdef DEBUG_THRESACCEPT std::cout << "\n\t -- Accepted. (" << GetKineTypeName( ReconThresholds[fp->PDG()][rt_it].ThresholdType) << " Threshold: " << ReconThresholds[fp->PDG()][rt_it].ThresholdVal << " | " << GetKineVal(fp, ReconThresholds[fp->PDG()][rt_it]) << ")" << std::flush; #endif } Passes = Passes && Passed; } if (Passes) { #ifdef DEBUG_THRESACCEPT std::cout << " -- Reconstructed." << std::flush; #endif ri->RecObjMom.push_back(fp->P3()); ri->RecObjClass.push_back(fp->PDG()); return; } else if (!FailEnergyThresh) { #ifdef DEBUG_THRESACCEPT std::cout << " -- Failed non-Energy threshold, no chance for EVis." << std::flush; #endif return; } if (((VisThresholds[fp->PDG()].ThresholdType == ThresholdAccepter::kKE) && (VisThresholds[fp->PDG()].ThresholdVal < fp->KE())) // Above KE-style threshold || ((VisThresholds[fp->PDG()].ThresholdType == ThresholdAccepter::kMomentum) && (VisThresholds[fp->PDG()].ThresholdVal < fp->P3().Mag())) // Above mom-style threshold ) { #ifdef DEBUG_THRESACCEPT std::cout << " -- Contributed to VisE. (" << GetKineTypeName(VisThresholds[fp->PDG()].ThresholdType) << ": " << VisThresholds[fp->PDG()].ThresholdVal << ")" << std::flush; #endif ri->RecVisibleEnergy.push_back( VisThresholds[fp->PDG()].Fraction * (VisThresholds[fp->PDG()].UseKE ? fp->KE() : fp->E())); ri->TrueContribPDGs.push_back(fp->PDG()); return; } else { #ifdef DEBUG_THRESACCEPT std::cout << " -- Rejected. " << " Vis: (" << GetKineTypeName(VisThresholds[fp->PDG()].ThresholdType) << ": " << VisThresholds[fp->PDG()].ThresholdVal << ")" << std::flush; #endif } } RecoInfo *ThresholdAccepter::Smearcept(FitEvent *fe) { RecoInfo *ri = new RecoInfo(); for (size_t p_it = 0; p_it < fe->NParticles(); ++p_it) { FitParticle *fp = fe->GetParticle(p_it); SmearceptOneParticle(ri, fp #ifdef DEBUG_THRESACCEPT , p_it #endif ); } #ifdef DEBUG_THRESACCEPT std::cout << std::endl; #endif return ri; } diff --git a/src/Smearceptance/TrackedMomentumMatrixSmearer.cxx b/src/Smearceptance/TrackedMomentumMatrixSmearer.cxx index 2efb211..7b0993b 100644 --- a/src/Smearceptance/TrackedMomentumMatrixSmearer.cxx +++ b/src/Smearceptance/TrackedMomentumMatrixSmearer.cxx @@ -1,416 +1,416 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "TrackedMomentumMatrixSmearer.h" namespace { TrackedMomentumMatrixSmearer::DependVar GetVarType(std::string const &axisvar) { if (axisvar == "Momentum") { return TrackedMomentumMatrixSmearer::kMomentum; } else if (axisvar == "KE") { return TrackedMomentumMatrixSmearer::kKE; } else if (axisvar == "TE") { return TrackedMomentumMatrixSmearer::kTE; } return TrackedMomentumMatrixSmearer::kNoVar; } } TH1D const *TrackedMomentumMatrixSmearer::SmearMap::GetRecoSlice(double val) { if ((val < RecoSlices.front().first.first) || (val > RecoSlices.back().first.second)) { - QERROR(WRN, + NUIS_ERR(WRN, "Kinematic property: " << val << ", not within smearable range: [" << RecoSlices.front().first.first << " -- " << RecoSlices.back().first.second << "]."); return NULL; } int L = 0, U = RecoSlices.size(); while (true) { if (U == L) { return RecoSlices[L].second; } int R = (U - L); int m = L + (R / 2); if (val <= RecoSlices[m].first.first) { U = m - 1; continue; } if (val > RecoSlices[m].first.second) { L = m + 1; continue; } if ((val > RecoSlices[m].first.first) && (val <= RecoSlices[m].first.second)) { return RecoSlices[m].second; } - QTHROW("Binary smearing search failed. Check logic."); + NUIS_ABORT("Binary smearing search failed. Check logic."); } } TH1D *GetMapSlice(TH2D *mp, int SliceBin, bool AlongX) { int NBins = (AlongX ? mp->GetXaxis() : mp->GetYaxis())->GetNbins(); int NOtherBins = (AlongX ? mp->GetYaxis() : mp->GetXaxis())->GetNbins(); if (SliceBin >= NOtherBins) { - QTHROW("Asked for slice " << SliceBin << " but the " << (AlongX ? 'Y' : 'X') + NUIS_ABORT("Asked for slice " << SliceBin << " but the " << (AlongX ? 'Y' : 'X') << " axis only has " << NOtherBins); } if ((AlongX ? mp->GetXaxis() : mp->GetYaxis())->IsVariableBinSize() && ((NBins + 1) != (AlongX ? mp->GetXaxis() : mp->GetYaxis())->GetXbins()->GetSize())) { - QTHROW( + NUIS_ABORT( "Attemping to take binning slice of variable binning, but NBins+1 != " "NBinEdges: " << (NBins + 1) << " != " << (AlongX ? mp->GetXaxis() : mp->GetYaxis())->GetXbins()->GetSize()); } std::stringstream ss(""); ss << mp->GetName() << (AlongX ? 'Y' : 'X') << "Slice_" << SliceBin; std::stringstream st(""); st << mp->GetTitle() << ";" << (AlongX ? mp->GetXaxis() : mp->GetYaxis())->GetTitle() << ";" << "Count"; TH1D *Ret; if ((AlongX ? mp->GetXaxis() : mp->GetYaxis())->IsVariableBinSize()) { Ret = new TH1D( ss.str().c_str(), st.str().c_str(), NBins, (AlongX ? mp->GetXaxis() : mp->GetYaxis())->GetXbins()->GetArray()); } else { Ret = new TH1D(ss.str().c_str(), st.str().c_str(), NBins, (AlongX ? mp->GetXaxis() : mp->GetYaxis())->GetXmin(), (AlongX ? mp->GetXaxis() : mp->GetYaxis())->GetXmax()); } for (int bi_it = 0; bi_it < NBins + 2; ++bi_it) { int X = AlongX ? bi_it : SliceBin + 1; int Y = AlongX ? SliceBin + 1 : bi_it; int GBin = mp->GetBin(X, Y); Ret->SetBinContent(bi_it, mp->GetBinContent(GBin)); Ret->SetBinError(bi_it, mp->GetBinError(GBin)); } #ifdef DEBUG_MATSMEAR std::cout << "Took slice: " << SliceBin << " spanning [" << Ret->GetXaxis()->GetBinLowEdge(1) << " -- " << Ret->GetXaxis()->GetBinUpEdge(Ret->GetXaxis()->GetNbins()) << "] (Orignal span [" << (AlongX ? mp->GetXaxis() : mp->GetYaxis())->GetBinLowEdge(1) << " -- " << (AlongX ? mp->GetXaxis() : mp->GetYaxis()) ->GetBinUpEdge( (AlongX ? mp->GetXaxis() : mp->GetYaxis())->GetNbins()) << "]) " << (AlongX ? mp->GetXaxis() : mp->GetYaxis())->GetXmin() << " -- " << (AlongX ? mp->GetXaxis() : mp->GetYaxis())->GetXmax() << " IsVBin: " << (AlongX ? mp->GetXaxis() : mp->GetYaxis())->IsVariableBinSize() << std::endl; #endif Ret->SetDirectory(NULL); return Ret; } void TrackedMomentumMatrixSmearer::SmearMap::SetSlicesFromMap(TH2D *map, bool TruthIsY) { int NSlices = (TruthIsY ? map->GetYaxis() : map->GetXaxis())->GetNbins(); for (Int_t TrueSlice_it = 0; TrueSlice_it < NSlices; ++TrueSlice_it) { std::pair BinEdges; BinEdges.first = (TruthIsY ? map->GetYaxis() : map->GetXaxis()) ->GetBinLowEdge(TrueSlice_it + 1); BinEdges.second = (TruthIsY ? map->GetYaxis() : map->GetXaxis()) ->GetBinUpEdge(TrueSlice_it + 1); TH1D *slice = GetMapSlice(map, TrueSlice_it, TruthIsY); RecoSlices.push_back(std::make_pair(BinEdges, slice)); } - QLOG(FIT, "\tAdded " << RecoSlices.size() << " reco slices."); + NUIS_LOG(FIT, "\tAdded " << RecoSlices.size() << " reco slices."); } /// Reads particle efficiency nodes /// /// Nodes look like: /// /// /// void TrackedMomentumMatrixSmearer::SpecifcSetup(nuiskey &nk) { std::vector effDescriptors = nk.GetListOfChildNodes("SmearMatrix"); for (size_t t_it = 0; t_it < effDescriptors.size(); ++t_it) { std::string inputFileName = effDescriptors[t_it].GetS("InputFile"); std::string HistName = effDescriptors[t_it].GetS("HistName"); bool YIsTrue = effDescriptors[t_it].Has("YIsTrue") ? effDescriptors[t_it].GetI("YIsTrue") : true; double UnitsScale = effDescriptors[t_it].Has("MatrixToInternal") ? effDescriptors[t_it].GetD("MatrixToInternal") : 1; TFile inputFile(inputFileName.c_str()); if (!inputFile.IsOpen()) { - QTHROW("Couldn't open specified input root file: " << inputFileName); + NUIS_ABORT("Couldn't open specified input root file: " << inputFileName); } TH2D *inpHist = dynamic_cast(inputFile.Get(HistName.c_str())); if (!inpHist) { - QTHROW("Couldn't get TH2D named: " << HistName << " from input root file: " + NUIS_ABORT("Couldn't get TH2D named: " << HistName << " from input root file: " << inputFileName); } TrackedMomentumMatrixSmearer::DependVar var = GetVarType(effDescriptors[t_it].GetS("Kinematics")); std::string pdgs_s = effDescriptors[t_it].GetS("PDG"); std::vector pdgs_i = GeneralUtils::ParseToInt(pdgs_s, ","); for (size_t pdg_it = 0; pdg_it < pdgs_i.size(); ++pdg_it) { if (ParticleMappings.count(pdgs_i[pdg_it])) { - QERROR(WRN, "Smearceptor " << ElementName << ":" << InstanceName + NUIS_ERR(WRN, "Smearceptor " << ElementName << ":" << InstanceName << " already has a smearing for PDG: " << pdgs_i[pdg_it]); } SmearMap sm; sm.SetSlicesFromMap(inpHist, YIsTrue); sm.SmearVar = var; sm.UnitsScale = UnitsScale; ParticleMappings[pdgs_i[pdg_it]] = sm; - QLOG(FIT, "Added smearing map for PDG: " << pdgs_i[pdg_it]); + NUIS_LOG(FIT, "Added smearing map for PDG: " << pdgs_i[pdg_it]); } } SlaveGS.Setup(nk); } RecoInfo *TrackedMomentumMatrixSmearer::Smearcept(FitEvent *fe) { RecoInfo *ri = new RecoInfo(); for (size_t p_it = 0; p_it < fe->NParticles(); ++p_it) { FitParticle *fp = fe->GetParticle(p_it); #ifdef DEBUG_MATSMEAR std::cout << std::endl; std::cout << "[" << p_it << "]: " << fp->PDG() << ", " << fp->Status() << ", " << fp->E() << " -- KE:" << fp->KE() << " Mom: " << fp->P3().Mag() << std::flush; #endif if (fp->Status() != kFinalState) { #ifdef DEBUG_MATSMEAR std::cout << " -- Not final state." << std::flush; #endif continue; } if (!ParticleMappings.count(fp->PDG())) { SlaveGS.SmearceptOneParticle(ri, fp #ifdef DEBUG_GAUSSSMEAR , p_it #endif ); continue; } SmearMap &sm = ParticleMappings[fp->PDG()]; double kineProp = 0; switch (sm.SmearVar) { case kMomentum: { kineProp = fp->P3().Mag(); break; } case kKE: { kineProp = fp->KE(); break; } case kTE: { kineProp = fp->E(); break; } - default: { QTHROW("Trying to find particle value for a kNoAxis."); } + default: { NUIS_ABORT("Trying to find particle value for a kNoAxis."); } } TH1 const *recoDistrib = sm.GetRecoSlice(kineProp / sm.UnitsScale); #ifdef DEBUG_MATSMEAR std::cout << " -- Got slice spanning [" << recoDistrib->GetXaxis()->GetBinLowEdge(1) << " -- " << recoDistrib->GetXaxis()->GetBinUpEdge( recoDistrib->GetXaxis()->GetNbins()) << "]" << std::endl; #endif if (!recoDistrib) { #ifdef DEBUG_MATSMEAR std::cout << " -- outside smearable range." << std::flush; #endif continue; } if (recoDistrib->Integral() == 0) { - QERROR(WRN, "True slice has no reconstructed events. Not smearing.") + NUIS_ERR(WRN, "True slice has no reconstructed events. Not smearing.") continue; } double Smeared = recoDistrib->GetRandom() * sm.UnitsScale; #ifdef DEBUG_MATSMEAR std::cout << "GotRandom: " << Smeared << ", MPV: " << recoDistrib->GetXaxis()->GetBinCenter( recoDistrib->GetMaximumBin()) * sm.UnitsScale << std::endl; #endif switch (sm.SmearVar) { case kMomentum: { ri->RecObjMom.push_back(fp->P3().Unit() * Smeared); #ifdef DEBUG_MATSMEAR std::cout << " -- Smeared: " << fp->p() << " -> " << Smeared << "." << std::flush; #endif break; } case kKE: { double mass = fp->P4().M(); double TE = mass + Smeared; double magP = sqrt(TE * TE - mass * mass); ri->RecObjMom.push_back(fp->P3().Unit() * magP); #ifdef DEBUG_MATSMEAR std::cout << " -- Smeared: " << fp->KE() << " (mass: " << mass << ") -> " << Smeared << ". Smear Mom: " << ri->RecObjMom.back().Mag() << "." << std::flush; #endif break; } case kTE: { double mass = fp->P4().M(); double TE = Smeared; double magP = sqrt(TE * TE - mass * mass); ri->RecObjMom.push_back(fp->P3().Unit() * magP); #ifdef DEBUG_MATSMEAR std::cout << " -- Smeared: " << fp->E() << " (mass: " << mass << ") -> " << Smeared << ". Smear Mom: " << ri->RecObjMom.back().Mag() << "." << std::flush; #endif break; } default: {} } #ifdef DEBUG_MATSMEAR std::cout << " -- momentum reconstructed as " << ri->RecObjMom.back().Mag() << "." << std::endl; #endif if (ri->RecObjMom.back().Mag() != ri->RecObjMom.back().Mag()) { - QERROR(WRN, "Invalid particle built."); + NUIS_ERR(WRN, "Invalid particle built."); ri->RecObjMom.pop_back(); #include "TCanvas.h" TCanvas *Test = new TCanvas("c1", ""); static_cast(recoDistrib->Clone())->Draw(); Test->SaveAs("Fail.png"); delete Test; - QTHROW("ARGH"); + NUIS_ABORT("ARGH"); } else { ri->RecObjClass.push_back(fp->PDG()); } } #ifdef DEBUG_MATSMEAR std::cout << std::endl; #endif return ri; } void TrackedMomentumMatrixSmearer::SmearRecoInfo(RecoInfo *ri) { for (size_t p_it = 0; p_it < ri->RecObjMom.size(); ++p_it) { if (!ParticleMappings.count(ri->RecObjClass[p_it])) { SlaveGS.SmearceptOneParticle(ri->RecObjMom[p_it], ri->RecObjClass[p_it]); continue; } SmearMap &sm = ParticleMappings[ri->RecObjClass[p_it]]; double kineProp = 0; switch (sm.SmearVar) { case kMomentum: { kineProp = ri->RecObjMom[p_it].Mag(); break; } case kKE: { double mass = PhysConst::GetMass(ri->RecObjClass[p_it]) * 1E3; kineProp = sqrt(ri->RecObjMom[p_it].Mag2() + mass * mass) - mass; break; } case kTE: { double mass = PhysConst::GetMass(ri->RecObjClass[p_it]) * 1E3; kineProp = sqrt(ri->RecObjMom[p_it].Mag2() + mass * mass); break; } - default: { QTHROW("Trying to find particle value for a kNoAxis."); } + default: { NUIS_ABORT("Trying to find particle value for a kNoAxis."); } } TH1 const *recoDistrib = sm.GetRecoSlice(kineProp / sm.UnitsScale); if (!recoDistrib) { continue; } if (recoDistrib->Integral() == 0) { - QERROR(WRN, "True slice has no reconstructed events. Not smearing.") + NUIS_ERR(WRN, "True slice has no reconstructed events. Not smearing.") continue; } double Smeared = recoDistrib->GetRandom() * sm.UnitsScale; switch (sm.SmearVar) { case kMomentum: { ri->RecObjMom[p_it] = ri->RecObjMom[p_it].Unit() * Smeared; break; } case kKE: { double mass = PhysConst::GetMass(ri->RecObjClass[p_it]) * 1E3; double TE = mass + Smeared; double magP = sqrt(TE * TE - mass * mass); ri->RecObjMom[p_it] = ri->RecObjMom[p_it].Unit() * magP; break; } case kTE: { double mass = PhysConst::GetMass(ri->RecObjClass[p_it]) * 1E3; double TE = Smeared; double magP = sqrt(TE * TE - mass * mass); ri->RecObjMom[p_it] = ri->RecObjMom[p_it].Unit() * magP; break; } default: {} } } } diff --git a/src/Smearceptance/VisECoalescer.h b/src/Smearceptance/VisECoalescer.h index 65bebdf..a1a8158 100644 --- a/src/Smearceptance/VisECoalescer.h +++ b/src/Smearceptance/VisECoalescer.h @@ -1,61 +1,61 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #ifndef VISECOALESCER_HXX_SEEN #define VISECOALESCER_HXX_SEEN #include "ISmearcepter.h" #include ///Stacks all VisE deposits from particles of the same PDG class VisECoalescer : public ISmearcepter { private: void SpecifcSetup(nuiskey &) {} public: RecoInfo *Smearcept(FitEvent *) { - QTHROW("VisECoalescer cannot act as an accepter"); + NUIS_ABORT("VisECoalescer cannot act as an accepter"); } /// Helper method for using this class as a component in a more complex /// smearer void SmearRecoInfo(RecoInfo *ri) { std::map TotalSpeciesVisE; for (size_t ve_it = 0; ve_it < ri->RecVisibleEnergy.size(); ++ve_it) { if (!TotalSpeciesVisE.count(ri->TrueContribPDGs[ve_it])) { TotalSpeciesVisE[ri->TrueContribPDGs[ve_it]] = 0; } TotalSpeciesVisE[ri->TrueContribPDGs[ve_it]] += ri->RecVisibleEnergy[ve_it]; } ri->RecVisibleEnergy.clear(); ri->TrueContribPDGs.clear(); for (std::map::iterator ve_it = TotalSpeciesVisE.begin(); ve_it != TotalSpeciesVisE.end(); ++ve_it) { ri->TrueContribPDGs.push_back(ve_it->first); ri->RecVisibleEnergy.push_back(ve_it->second); } } }; #endif diff --git a/src/Splines/FitSpline.cxx b/src/Splines/FitSpline.cxx index 74820a1..d141944 100644 --- a/src/Splines/FitSpline.cxx +++ b/src/Splines/FitSpline.cxx @@ -1,411 +1,411 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "FitSpline.h" // TODO (P.Stowell) ReWrite Spline Classes to be more efficient. Make // inheritance system. // Form etc, //************************************************* FitSpline::FitSpline() { //************************************************* this->id = ""; this->form = ""; this->npar = 0; this->ndim = 0; this->spline = 0; this->offset = 1; this->needs_fit = false; } //************************************************* FitSpline::FitSpline(std::string ident, std::string dist, std::vector list_enums, std::string points_def) { //************************************************* this->id = ident; this->form = dist; this->var_enums = list_enums; // this->x_vals = FitBase::FillScanPoints(points_def); this->npar = 0; this->ndim = 0; this->spline = 0; this->offset = 1; this->points = points_def; // Point DEF is given as TYPEA:1,2,3;TYPEB:1,2,3 // ETC std::vector parsed_points = GeneralUtils::ParseToStr(points_def, ";"); for (UInt_t i = 0; i < parsed_points.size(); i++) { std::string temp = parsed_points.at(i); std::vector split_temp = GeneralUtils::ParseToStr(temp, ":"); std::string choose_type = split_temp.at(0); std::string choose_points = split_temp.at(1); std::vector points_temp = GeneralUtils::ParseToDbl(choose_points, ","); std::vector points_final; if (!choose_type.compare("PNTS")) points_final = points_temp; else if (!choose_type.compare("SCAN")) { - QLOG(FIT, "RUNNING SCAN"); + NUIS_LOG(FIT, "RUNNING SCAN"); int npoints = int(points_temp[0]); double low = double(points_temp[1]); double high = double(points_temp[2]); - QLOG(FIT, "Npoints " << npoints << " " << low << " " << high); + NUIS_LOG(FIT, "Npoints " << npoints << " " << low << " " << high); for (int i = 0; i < npoints; i++) { - QLOG(FIT, "Pushing back " + NUIS_LOG(FIT, "Pushing back " << low + (i + 0.) * (high - low) / (npoints - 1.0 + 0.)); points_final.push_back(low + (i + 0.) * (high - low) / (npoints - 1.0 + 0.)); } } this->x.push_back(0.0); this->x_vals.push_back(points_final); this->x_low.push_back(points_final[0]); this->x_high.push_back(points_final[points_final.size() - 1]); } this->SetType(dist); } //************************************************* void FitSpline::ReconfigureSpline(std::vector dial_enums, std::vector dial_values) { //************************************************* for (unsigned int i = 0; i < var_enums.size(); i++) { for (unsigned int j = 0; j < dial_enums.size(); j++) { if (var_enums[i] == dial_enums[j]) { x[i] = dial_values[j]; if (x[i] > x_high[i]) x[i] = x_high[i]; else if (x[i] < x_low[i]) x[i] = x_low[i]; } } } }; //************************************************* double FitSpline::operator()(const Double_t *x, const Double_t *par) const { //************************************************* double weight = this->DoEval(x, par, false); if (weight <= 0.0) weight = 0.0; return weight; }; //************************************************* double FitSpline::DoEval(const double *par) const { //************************************************* double weight = this->DoEval(&x[0], &par[0]); if (weight <= 0.0) weight = 0.0; return weight; }; //************************************************* void FitSpline::SetType(int t, int p, int d, bool f) { //************************************************* spline = t; npar = p; ndim = d; needs_fit = f; } //************************************************* // Adding new spline functions // 1. Add a new value to the enumeration in the header. // 2. Setup a string comparison call here using // SetType( enum, ndim, npar ); // 3. Implement the function evaluation in the DoEval function. //************************************************* void FitSpline::SetType(std::string type) { //************************************************* if (!type.compare("1Dpol1")) { SetType(k1DPol1, 1, 1); } else if (!type.compare("1Dpol2")) { SetType(k1DPol2, 2, 1); } else if (!type.compare("1Dpol3")) { SetType(k1DPol3, 3, 1); } else if (!type.compare("1Dpol4")) { SetType(k1DPol4, 4, 1); } else if (!type.compare("1Dpol5")) { SetType(k1DPol5, 5, 1); } else if (!type.compare("1Dpol6")) { SetType(k1DPol6, 6, 1); } else if (!type.compare("1Dpol1C")) { SetType(k1DPol1C, 2, 1); } else if (!type.compare("1Dpol2C")) { SetType(k1DPol2C, 3, 1); } else if (!type.compare("1Dpol3C")) { SetType(k1DPol3C, 4, 1); } else if (!type.compare("1Dpol4C")) { SetType(k1DPol4C, 5, 1); } else if (!type.compare("1Dpol5C")) { SetType(k1DPol5C, 6, 1); } else if (!type.compare("1Dpol5C_LX")) { SetType(k1DPol5C_LX, 7, 1); } else if (!type.compare("1Dpol10")) { SetType(k1DPol10, 10, 1); } else if (!type.compare("1Dpol25")) { SetType(k1DPol25, 25, 1); } else if (!type.compare("2Dpol6")) { SetType(k2DPol6, 9, 2); } else if (!type.compare("1DTSpline3")) { SetType(k1DTSpline3, x_vals[0].size() * 4, 1, false); } else { - QTHROW("Unkown dial value: " << type); + NUIS_ABORT("Unkown dial value: " << type); } return; } //************************************************* double FitSpline::DoEval(const double *x, const double *par, const bool use_offset) const { //************************************************* // Fill Vector with limits std::vector y = std::vector(this->ndim, 0); for (UInt_t i = 0; i < ndim; i++) { y[i] = x[i]; if (x[i] < x_low[i]) y[i] = x_low[i]; else if (x[i] > x_high[i]) y[i] = x_high[i]; } // Get Offset in array int off = 0; if (use_offset) off = this->offset; if (par[0 + off] <= -998) { return 1.0; } switch (this->spline) { // N Polynomial sets without constant case (k1DPol1): { - QLOG(DEB, "Calcing pol1 with " << y[0] << " " << par[0 + off]); + NUIS_LOG(DEB, "Calcing pol1 with " << y[0] << " " << par[0 + off]); return (1.0 + par[0 + off] * y[0]); } case (k1DPol2): { return (1.0 + par[0 + off] * y[0] + par[1 + off] * y[0] * y[0]); } case (k1DPol3): { return (1.0 + par[0 + off] * y[0] + par[1 + off] * y[0] * y[0] + par[2 + off] * y[0] * y[0] * y[0]); } case (k1DPol4): { return (1.0 + par[0 + off] * y[0] + par[1 + off] * y[0] * y[0] + par[2 + off] * y[0] * y[0] * y[0] + par[3 + off] * pow(y[0], 4)); } case (k1DPol5): { return (1.0 + par[0 + off] * y[0] + par[1 + off] * y[0] * y[0] + par[2 + off] * y[0] * y[0] * y[0] + par[3 + off] * pow(y[0], 4) + par[4 + off] * pow(y[0], 5)); } case (k1DPol6): { - QLOG(DEB, "Calcing 1Dpol6 with " << y[0]); - QLOG(DEB, "Par 0 " << par[0 + off]); - QLOG(DEB, "Par 1 " << par[1 + off]); - QLOG(DEB, "Par 2 " << par[2 + off]); + NUIS_LOG(DEB, "Calcing 1Dpol6 with " << y[0]); + NUIS_LOG(DEB, "Par 0 " << par[0 + off]); + NUIS_LOG(DEB, "Par 1 " << par[1 + off]); + NUIS_LOG(DEB, "Par 2 " << par[2 + off]); double val = (1.0 + par[0 + off] * y[0] + par[1 + off] * y[0] * y[0] + par[2 + off] * y[0] * y[0] * y[0] + par[3 + off] * pow(y[0], 4) + par[4 + off] * pow(y[0], 5) + par[5 + off] * pow(y[0], 6)); - QLOG(DEB, "VAL = " << val); + NUIS_LOG(DEB, "VAL = " << val); return val; } // N Polynomial sets (with constant) case (k1DPol1C): { return (par[0 + off] + par[1 + off] * y[0]); } case (k1DPol2C): { return (par[0 + off] + par[1 + off] * y[0] + par[2 + off] * y[0] * y[0]); } case (k1DPol3C): { return (par[0 + off] + par[1 + off] * y[0] + par[2 + off] * y[0] * y[0] + par[3 + off] * y[0] * y[0] * y[0]); } case (k1DPol4C): { return (par[0 + off] + par[1 + off] * y[0] + par[2 + off] * y[0] * y[0] + par[3 + off] * y[0] * y[0] * y[0] + par[4 + off] * pow(y[0], 4)); } case (k1DPol5C): { return (par[0 + off] + par[1 + off] * y[0] + par[2 + off] * y[0] * y[0] + par[3 + off] * y[0] * y[0] * y[0] + par[4 + off] * pow(y[0], 4) + par[5 + off] * pow(y[0], 5)); } case (k1DPol5C_LX): { return ((par[0 + off] + par[1 + off] * y[0] + par[2 + off] * y[0] * y[0] + par[3 + off] * y[0] * y[0] * y[0] + par[4 + off] * pow(y[0], 4) + par[5 + off] * pow(y[0], 5)) * double(y[0] > par[6 + off] - 4.0)); } case (k1DPol10): { return ((par[0 + off] + par[1 + off] * y[0] + par[2 + off] * y[0] * y[0] + par[3 + off] * y[0] * y[0] * y[0] + par[4 + off] * pow(y[0], 4) + par[5 + off] * pow(y[0], 5) + par[6 + off] * pow(y[0], 6) + par[7 + off] * pow(y[0], 7) + par[8 + off] * pow(y[0], 8) + par[9 + off] * pow(y[0], 9))); } // Silly 25th order polynomial (ROOT can't fit this anyway) case (k1DPol25): { double weight = par[0 + off]; for (UInt_t i = 1; i < npar; i++) { weight += par[i + off] * pow(y[0], i); } return weight; } case (k2DPol6): { double weight = 1.0; return weight; } // TSpline3 --- REQUIRES COEFF BE FILLED into spline3 case (k1DTSpline3): { // iterator over knot values and find width std::vector::iterator iter_low = x_vals[0].begin(); std::vector::iterator iter_high = x_vals[0].begin(); iter_high++; int count = off; while (iter_high != x_vals[0].end()) { if (y[0] >= (*iter_low) and y[0] < (*iter_high)) { break; } count += 4; iter_low++; iter_high++; } double dx = y[0] - (*iter_low); double weight = (par[count] + dx * (par[count + 1] + dx * (par[count + 2] + dx * par[count + 3]))); if (weight != weight) weight = 0.0; return weight; } // DEFAULT OPTION default: - QTHROW("Evaluating function enum not found!"); + NUIS_ABORT("Evaluating function enum not found!"); } }; std::vector FitSpline::GetSplineCoeff(double *weights) { std::vector coeff; switch (this->spline) { // TSPLINE 3 DIAL COEFFICIENT SET ----------------- case (k1DTSpline3): { std::vector xval; std::vector yval; // CREATE TEMP OBJECT TSpline3 temp_spline = TSpline3("temp_spline", &((x_vals[0])[0]), weights, x_vals[0].size()); for (UInt_t i = 0; i < x_vals[0].size(); i++) { /// EXTRA ZERO SUPPRESSION, we must save co-effecients for each point /// scanned to remain consistent across events. (-1) flag is used if (weights[i] <= 0.0 and i < x_vals[0].size() - 1 and weights[i + 1] <= 0.0) { coeff.push_back(0.0); coeff.push_back(0.0); coeff.push_back(0.0); coeff.push_back(0.0); /// Get Normal Coefficients for the point } else { coeff.push_back(weights[i]); double x, y, b, c, d; temp_spline.GetCoeff(i, x, y, b, c, d); coeff.push_back(b); coeff.push_back(c); coeff.push_back(d); } } break; } /// DEFAULT default: - QERROR(FTL, "DIAL HAS NO COEFFICIENT SET Implementation"); - QTHROW("Dial Enum = " << this->spline); + NUIS_ERR(FTL, "DIAL HAS NO COEFFICIENT SET Implementation"); + NUIS_ABORT("Dial Enum = " << this->spline); } if (coeff.empty()) { - QTHROW("Error no dial coefficients saved from GetDialCoeff()"); + NUIS_ABORT("Error no dial coefficients saved from GetDialCoeff()"); } return coeff; } diff --git a/src/Splines/Spline.cxx b/src/Splines/Spline.cxx index 89f629b..54bc6e0 100644 --- a/src/Splines/Spline.cxx +++ b/src/Splines/Spline.cxx @@ -1,473 +1,473 @@ #include "Spline.h" using namespace SplineUtils; // Setup Functions // ---------------------------------------------- Spline::Spline(std::string splname, std::string form, std::string points) { // Save Definition fName = splname; fForm = form; fPoints = points; fROOTFunction = NULL; // Setup Min Max for each Parameter fSplitNames = GeneralUtils::ParseToStr(splname, ";"); std::vector> gridvals = SplineUtils::GetSplitDialPoints(fPoints); for (size_t i = 0; i < fSplitNames.size(); i++) { for (size_t j = 0; j < gridvals.size(); j++) { if (i == 0) fXScan.push_back(gridvals[j][0]); if (i == 1) fXScan.push_back(gridvals[j][1]); } double xmin = 9999.9; double xmax = -9999.9; for (size_t j = 0; j < gridvals.size(); j++) { if (gridvals[j][i] < xmin) xmin = gridvals[j][i]; if (gridvals[j][i] > xmax) xmax = gridvals[j][i]; } fVal.push_back(0.0); fValMin.push_back(xmin); fValMax.push_back(xmax); // Define TSpline3 1D iterators here if (i == 0) { iter_low = fXScan.begin(); iter_high = fXScan.begin(); iter_high++; off = 0; } } // Set form from list if (!fForm.compare("1DPol1")) { Setup(k1DPol1, 1, 2); } else if (!fForm.compare("1DPol2")) { Setup(k1DPol2, 1, 3); } else if (!fForm.compare("1DPol3")) { Setup(k1DPol3, 1, 4); } else if (!fForm.compare("1DPol4")) { Setup(k1DPol4, 1, 5); } else if (!fForm.compare("1DPol5")) { Setup(k1DPol5, 1, 6); } else if (!fForm.compare("1DPol6")) { Setup(k1DPol6, 1, 7); } else if (!fForm.compare("1DTSpline3")) { Setup(k1DTSpline3, 1, fXScan.size() * 4); } else if (!fForm.compare("2DPol6")) { Setup(k2DPol6, 2, 28); } else if (!fForm.compare("2DGaus")) { Setup(k2DGaus, 2, 8); } else if (!fForm.compare("2DTSpline3")) { Setup(k2DTSpline3, 2, fXScan.size() * fYScan.size() * 8); } else { - QTHROW("Unknown spline form : " << fForm); + NUIS_ABORT("Unknown spline form : " << fForm); } // Run Checks if ((UInt_t)fNDim != fSplitNames.size()) { - QTHROW("Spline Dim:Names mismatch!"); + NUIS_ABORT("Spline Dim:Names mismatch!"); } - QLOG(SAM, "Setup Spline " << fForm << " = " << fType << " " << fNPar); + NUIS_LOG(SAM, "Setup Spline " << fForm << " = " << fType << " " << fNPar); }; void Spline::Setup(int type, int ndim, int npar) { fType = type; fNDim = ndim; fNPar = npar; } // Reconfigure Functions // ---------------------------------------------- void Spline::Reconfigure(float x, int index) { // std::cout << "Reconfigured spline : " << fName << " : " << fForm << " to be // " << x << " " << index << std::endl; fVal[index] = x; fOutsideLimits = false; if (fVal[index] > fValMax[index]) fVal[index] = fValMax[index]; if (fVal[index] < fValMin[index]) fVal[index] = fValMin[index]; // std::cout << "Set at edge = " << fVal[index] << " " << index << std::endl; } void Spline::Reconfigure(std::string name, float x) { for (size_t i = 0; i < fSplitNames.size(); i++) { // std::cout << "-> Comparing in spline " << name << " to " << // fSplitNames[i] << " = " << !fSplitNames[i].compare(name.c_str()) << // std::endl; if (!fSplitNames[i].compare(name.c_str())) { // std::cout << "-> Reconfigured spline : " << fSplitNames[i] << " " << // name << " to be " << x << " " << i << std::endl; Reconfigure(x, i); } } } // Evaluation Functions // ---------------------------------------------- double Spline::operator()(const Double_t *x, const Double_t *par) { Float_t *tempx = new Float_t[fNDim]; for (size_t i = 0; i < (UInt_t)fNDim; i++) { tempx[i] = x[i]; } Float_t *tempp = new Float_t[fNPar]; for (size_t i = 0; i < (UInt_t)fNPar; i++) { tempp[i] = par[i]; } float val = DoEval(tempx, tempp); delete tempp; delete tempx; if (val < 0.0) val = 0.0; return val; } double Spline::DoEvalPar(const double *x, const double *p) const { Float_t *tempx = new Float_t[fNDim]; for (size_t i = 0; i < (UInt_t)fNDim; i++) { tempx[i] = x[i]; } Float_t *tempp = new Float_t[fNPar]; for (size_t i = 0; i < (UInt_t)fNPar; i++) { tempp[i] = p[i]; } float val = DoEval(tempx, tempp); delete tempp; delete tempx; if (val < 0.0) val = 0.0; return val; } float Spline::operator()(const Float_t *x, const Float_t *par) const { float val = DoEval(x, par); if (val < 0.0) val = 0.0; return val; } float Spline::DoEval(const Float_t *x, const Float_t *par) const { // Setup current fX to value for (size_t i = 0; i < (UInt_t)fNDim; i++) { fVal[i] = x[i]; if (fVal[i] > fValMax[i]) fVal[i] = fValMax[i]; if (fVal[i] < fValMin[i]) fVal[i] = fValMin[i]; } double w = DoEval(&par[0], false); if (w < 0.0) w = 0.0; // Now evaluate spline how FitWeight will do it. return w; } float Spline::DoEval(const Float_t *par, bool checkresponse) const { if (!par) return 1.0; // std::cout << "Spline::DoEval = " << par << std::endl; // Check response if (checkresponse) { bool hasresponse = false; for (int i = 0; i < fNPar; i++) { if (par[i] != 0.0) { hasresponse = true; break; } } if (!hasresponse) { // std::cout << "No Response" << std::endl; return 1.0; } } // std::cout << "TYpe = " << fType << " "<< fForm << std::endl; // Now evaluate spline switch (fType) { case k1DPol1: { return Spline1DPol1(par); } case k1DPol2: { return Spline1DPol2(par); } case k1DPol3: { return Spline1DPol3(par); } case k1DPol4: { return Spline1DPol4(par); } case k1DPol5: { return Spline1DPol5(par); } case k1DPol6: { return Spline1DPol6(par); } case k1DTSpline3: { return Spline1DTSpline3(par); } case k2DPol6: { return Spline2DPol(par, 6); } case k2DGaus: { return Spline2DGaus(par); } case k2DTSpline3: { return Spline2DTSpline3(par); } } // Return nominal weight return 1.0; }; // Spline Functions // ---------------------------------------------- // 1D Functions // ---------------------------------------------- float Spline::Spline1DPol1(const Float_t *par) const { float xp = fVal[0]; return par[0] + par[1] * xp; }; float Spline::Spline1DPol2(const Float_t *par) const { float xp = fVal[0]; return par[0] + par[1] * xp + par[2] * xp * xp; }; float Spline::Spline1DPol3(const Float_t *par) const { float xp = fVal[0]; return par[0] + par[1] * xp + par[2] * xp * xp + par[3] * xp * xp * xp; }; float Spline::Spline1DPol4(const Float_t *par) const { float xp = fVal[0]; return (par[0] + par[1] * xp + par[2] * xp * xp + par[3] * xp * xp * xp + par[4] * xp * xp * xp * xp); }; float Spline::Spline1DPol5(const Float_t *par) const { float xp = fVal[0]; return (par[0] + par[1] * xp + par[2] * xp * xp + par[3] * xp * xp * xp + par[4] * xp * xp * xp * xp + par[5] * xp * xp * xp * xp * xp); }; float Spline::Spline1DPol6(const Float_t *par) const { float xp = fVal[0]; float w = 0.0; // std::cout << "Pol Eval " << std::endl; for (int i = fNPar - 1; i > 0; i--) { w = xp * (par[0 + i] + w); } w += par[0]; return w; }; float Spline::Spline1DTSpline3(const Float_t *par) const { // Find matching point iter_low = fXScan.begin(); iter_high = fXScan.begin(); iter_high++; off = 0; fX = fVal[0]; while (iter_high != fXScan.end() and (fX < (*iter_low) or fX >= (*iter_high))) { off += 4; iter_low++; iter_high++; } float dx = fX - (*iter_low); float weight = (par[off] + dx * (par[off + 1] + dx * (par[off + 2] + dx * par[off + 3]))); return weight; }; // 2D Functions // ---------------------------------------------- float Spline::Spline2DPol(const Float_t *par, int n) const { float wx = (fVal[0] - fValMin[0]) / (fValMax[0] - fValMin[0]); float wy = (fVal[1] - fValMin[1]) / (fValMax[1] - fValMin[1]); float w = 0.0; int count = 0; w += par[count++]; w += par[count++] * wx; w += par[count++] * wy; w += par[count++] * wx * wx; w += par[count++] * wx * wy; w += par[count++] * wy * wy; w += par[count++] * wx * wx * wx; w += par[count++] * wx * wx * wy; w += par[count++] * wx * wy * wy; w += par[count++] * wy * wy * wy; w += par[count++] * wx * wx * wx * wx; w += par[count++] * wx * wx * wx * wy; w += par[count++] * wx * wx * wy * wy; w += par[count++] * wx * wy * wy * wy; w += par[count++] * wy * wy * wy * wy; w += par[count++] * wx * wx * wx * wx * wx; w += par[count++] * wx * wx * wx * wx * wy; w += par[count++] * wx * wx * wx * wy * wy; w += par[count++] * wx * wx * wy * wy * wy; w += par[count++] * wx * wy * wy * wy * wy; w += par[count++] * wy * wy * wy * wy * wy; w += par[count++] * wx * wx * wx * wx * wx * wx; w += par[count++] * wx * wx * wx * wx * wx * wy; w += par[count++] * wx * wx * wx * wx * wy * wy; w += par[count++] * wx * wx * wx * wy * wy * wy; w += par[count++] * wx * wx * wy * wy * wy * wy; w += par[count++] * wx * wy * wy * wy * wy * wy; w += par[count++] * wy * wy * wy * wy * wy * wy; return w; } float Spline::Spline2DGaus(const Float_t *par) const { double Norm = 5.0 + par[1] * 20.0; double Tilt = par[2] * 10.0; double Pq0 = 1.0 + par[3] * 1.0; double Wq0 = 0.5 + par[4] * 1.0; double Pq3 = 1.0 + par[5] * 1.0; double Wq3 = 0.5 + par[6] * 1.0; double q0 = (fVal[0] - fValMin[0]) / (fValMax[0] - fValMin[0]); double q3 = (fVal[1] - fValMin[1]) / (fValMax[1] - fValMin[1]); double a = cos(Tilt) * cos(Tilt) / (2 * Wq0 * Wq0); a += sin(Tilt) * sin(Tilt) / (2 * Wq3 * Wq3); double b = -sin(2 * Tilt) / (4 * Wq0 * Wq0); b += sin(2 * Tilt) / (4 * Wq3 * Wq3); double c = sin(Tilt) * sin(Tilt) / (2 * Wq0 * Wq0); c += cos(Tilt) * cos(Tilt) / (2 * Wq3 * Wq3); double w = Norm; w *= exp(-a * (q0 - Pq0) * (q0 - Pq0)); w *= exp(+2.0 * b * (q0 - Pq0) * (q3 - Pq3)); w *= exp(-c * (q3 - Pq3) * (q3 - Pq3)); return w; } float Spline::Spline2DTSpline3(const Float_t *par) const { // Find matching point std::vector::iterator iter_low_x = fXScan.begin(); std::vector::iterator iter_high_x = fXScan.begin(); std::vector::iterator iter_low_y = fYScan.begin(); std::vector::iterator iter_high_y = fYScan.begin(); iter_high_x++; iter_high_y++; off = 0; fX = fVal[0]; fY = fVal[1]; while ((iter_high_x != fXScan.end() and iter_high_y != fYScan.end()) and (fX < (*iter_low_y) or fX >= (*iter_high) or fY < (*iter_low_y) or fY >= (*iter_low_y))) { off += 9; iter_low_x++; iter_high_x++; if (iter_high_x == fXScan.end()) { iter_low_x = fXScan.begin(); iter_high_x = fXScan.begin(); iter_low_y++; iter_high_y++; std::cout << "Skipping to next tspline 3 rung " << *iter_low_y << std::endl; } } std::cout << "Evaluting TSpline3 at " << fX << " " << (*iter_low_x) << " " << fY << " " << (*iter_low_y) << std::endl; // sleep(1.0); float dx = fX - (*iter_low_x); float dy = fY - (*iter_low_y); float weight = (par[off] + dx * (par[off + 1] + dx * (par[off + 2] + dx * par[off + 3]))); float weight2 = (par[off + 4] + dy * (par[off + 5] + dy * (par[off + 6] + dy * par[off + 7]))); return weight * weight2 * par[off + 8]; }; TF1 *Spline::GetFunction() { if (!fROOTFunction) { if (fNDim == 1) { std::cout << "Creating new 1D Function"; fROOTFunction = new TF1("f1", this, -30.0, 30.0, this->GetNPar()); } if (fNDim == 2) { std::cout << "Creating new 2D Function" << std::endl; // ROOT::Math::IParametricFunctionMultiDim* func; // = new // ROOT::Math::IParametricFunctionMultiDim(this); fROOTFunction = new TF2("f2", SplineUtils::Func2DWrapper, -30.0, 30.0, -30.0, -30.0, this->GetNPar()); } } // Reset ROOT function before returning. fROOTFunction->SetParameter(0, 1.0); for (int i = 1; i < this->GetNPar(); i++) { fROOTFunction->SetParameter(i, 0.1); } if (fNDim == 2) { if (SplineUtils::gSpline != this) SplineUtils::gSpline = this; } return (TF1 *)fROOTFunction; } namespace SplineUtils { Spline *gSpline = NULL; } double SplineUtils::Func2DWrapper(double *x, double *p) { return (*gSpline)(x, p); } diff --git a/src/Splines/SplineReader.cxx b/src/Splines/SplineReader.cxx index bd8d26b..d5b25dd 100644 --- a/src/Splines/SplineReader.cxx +++ b/src/Splines/SplineReader.cxx @@ -1,123 +1,123 @@ #include "SplineReader.h" // Spline reader should have access to every spline. // Should know when reconfigure is called what its limits are and adjust // accordingly. Then should pass it the index required in the stack as // &xvals[index], and &pars[parindex] void SplineReader::AddSpline(nuiskey splinekey) { // Read info from key std::string splname = splinekey.GetS("name"); std::string type = splinekey.GetS("type"); std::string form = splinekey.GetS("form"); std::string points = splinekey.GetS("points"); std::string extrapolate = splinekey.GetS("extrapolate"); // std::cout << "AddSpline " << splname << " " << type << " " << form << " " // << points << std::endl; // Add the spline to the list of all forms fAllSplines.push_back(Spline(splname, form, points)); fSpline.push_back(splname); fType.push_back(type); fForm.push_back(form); fPoints.push_back(points); } void SplineReader::Read(TTree *tr) { std::vector *tempspline = 0; std::vector *temptype = 0; std::vector *tempform = 0; std::vector *temppoints = 0; // Loop over all splines and add a TString in the TTree for its inputs tr->SetBranchAddress("Spline", &tempspline); tr->SetBranchAddress("Type", &temptype); tr->SetBranchAddress("Form", &tempform); tr->SetBranchAddress("Points", &temppoints); tr->GetEntry(0); // Copy over for (size_t i = 0; i < tempspline->size(); i++) { fSpline.push_back(tempspline->at(i)); fType.push_back(temptype->at(i)); fForm.push_back(tempform->at(i)); fPoints.push_back(temppoints->at(i)); } // Loop through and add splines from read type. for (size_t i = 0; i < fSpline.size(); i++) { - QLOG(SAM, "Registering Input Spline " << fSpline[i] << " " << fForm[i] + NUIS_LOG(SAM, "Registering Input Spline " << fSpline[i] << " " << fForm[i] << " " << fPoints[i]); fAllSplines.push_back(Spline(fSpline[i], fForm[i], fPoints[i])); } } void SplineReader::Reconfigure(std::map &vals) { // std::cout << "NEW SPLINE READER =========" << std::endl; for (std::map::iterator iter = vals.begin(); iter != vals.end(); iter++) { // std::cout << "Found " << iter->first << " in map handed to reader." << // std::endl; for (size_t i = 0; i < fSpline.size(); i++) { // std::cout << "Passing it to : " << fSpline[i] << std::endl; // if (!fSpline[i].compare(iter->first.c_str())){ // std::cout << "Reconfiguring Value inside Reader to be " << fSpline[i] // << " " << iter->second << std::endl; fAllSplines[i].Reconfigure(iter->first, iter->second); // } } } fNeedsReconfigure = false; } bool SplineReader::NeedsReconfigure() { return fNeedsReconfigure; } void SplineReader::SetNeedsReconfigure(bool val) { fNeedsReconfigure = val; } double SplineReader::CalcWeight(float *coeffs) { int off = 0; double rw_weight = 1.0; // Form Offset list std::vector offsets; for (size_t i = 0; i < fAllSplines.size(); i++) { offsets.push_back(off); off += fAllSplines[i].GetNPar(); } // #pragma omp parrallel for for (size_t i = 0; i < fAllSplines.size(); i++) { // std::cout << "Evaluating spline " << fAllSplines[i].GetName() << " at // coeff offset " << off << "(" << coeffs << ")" << std::endl; for (int j = // 0; j < fAllSplines[i].GetNPar(); j++){ std::cout << "Coeff " << j+off << // " " << coeffs[off+j] << std::endl; // } double w = fAllSplines[i].DoEval(&coeffs[offsets[i]]); rw_weight *= w; // std::cout << "Spline RW Weight = " << rw_weight << " " << w << std::endl; } if (rw_weight <= 0.0) rw_weight = 1.0; // std::cout << "Returning spline rw_weight = " << rw_weight << std::endl; return rw_weight; } int SplineReader::GetNPar() { int n = 0; for (size_t i = 0; i < fAllSplines.size(); i++) { n += fAllSplines[i].GetNPar(); } return n; } diff --git a/src/Splines/SplineWriter.cxx b/src/Splines/SplineWriter.cxx index 02e025b..3cad0bc 100644 --- a/src/Splines/SplineWriter.cxx +++ b/src/Splines/SplineWriter.cxx @@ -1,780 +1,780 @@ #include "SplineWriter.h" using namespace SplineUtils; // Spline reader should have access to every spline. // Should know when reconfigure is called what its limits are and adjust // accordingly. Then should pass it the index required in the stack as // &xvals[index], and &pars[parindex] void SplineWriter::Write(std::string name) { // Create a TTree with each form and scan points in it. TTree *tr = new TTree(name.c_str(), name.c_str()); // Loop over all splines and add a TString in the TTree for its inputs tr->Branch("Spline", &fSpline); tr->Branch("Type", &fType); tr->Branch("Form", &fForm); tr->Branch("Points", &fPoints); tr->Fill(); tr->Write(); delete tr; } void SplineWriter::AddWeightsToTree(TTree *tr) { // Add only the fitted spline coefficients to the ttree std::cout << "Saving Spline Weights to TTree = " << Form("SplineWeights[%d]/F", (int)fValList.size()) << std::endl; // sleep(1); tr->Branch("SplineWeights", fWeightList, Form("SplineWeights[%d]/D", (int)fValList.size())); } void SplineWriter::ReadWeightsFromTree(TTree *tr) { tr->SetBranchAddress("SplineWeights", fWeightList); } void SplineWriter::AddCoefficientsToTree(TTree *tr) { // Add only the fitted spline coefficients to the ttree std::cout << "Saving Spline Coeff to TTree = " << Form("SplineCoeff[%d]/F", fNCoEff) << std::endl; // sleep(1); tr->Branch("SplineCoeff", fCoEffStorer, Form("SplineCoeff[%d]/F", fNCoEff)); } void SplineWriter::SetupSplineSet() { std::cout << "Setting up spline set" << std::endl; fDrawSplines = FitPar::Config().GetParB("draw_splines"); // Create the coefficients double* fNCoEff = 0; for (size_t i = 0; i < fAllSplines.size(); i++) { fNCoEff += fAllSplines[i].GetNPar(); } fCoEffStorer = new float[fNCoEff]; std::cout << "NCoeff = " << fNCoEff << std::endl; // Calculate the grid of parsets // Setup the list of parameter coefficients. std::vector nomvals = fRW->GetDialValues(); fParVect.clear(); fSetIndex.clear(); fParVect.push_back(nomvals); fSetIndex.push_back(0); // fWeightList.push_back(1.0); fValList.push_back(std::vector(1, 0.0)); // Loop over all splines. for (size_t i = 0; i < fAllSplines.size(); i++) { // For each dial loop over all points within a given position std::vector newvals = nomvals; std::vector pos; // = SplineUtils::GetSplitDialPositions(fRW, fSpline[i]); std::vector splitnames = GeneralUtils::ParseToStr(fSpline[i], ";"); for (size_t j = 0; j < splitnames.size(); j++) { int temppos = fRW->GetDialPos(splitnames[j]); pos.push_back(temppos); } std::vector> vals = SplineUtils::GetSplitDialPoints(fPoints[i]); for (size_t j = 0; j < vals.size(); j++) { for (size_t k = 0; k < pos.size(); k++) { newvals[pos[k]] = vals[j][k]; } fParVect.push_back(newvals); fValList.push_back(vals[j]); // fWeightList.push_back(1.0); fSetIndex.push_back(i + 1); } } fWeightList = new double[fValList.size()]; for (uint i = 0; i < fValList.size(); i++) { fWeightList[i] = 1.0; } // Print out the parameter set - QLOG(FIT, "Parset | Index | Pars --- "); + NUIS_LOG(FIT, "Parset | Index | Pars --- "); for (size_t i = 0; i < fSetIndex.size(); i++) { - QLOGN(FIT, " Set " << i << ". | " << fSetIndex[i] << " | "); + NUIS_LOGN(FIT, " Set " << i << ". | " << fSetIndex[i] << " | "); if (LOG_LEVEL(FIT)) { for (size_t j = 0; j < fParVect[i].size(); j++) { - QLOGN(FIT, " " << fParVect[i][j]); + NUIS_LOGN(FIT, " " << fParVect[i][j]); } - QLOG(FIT, ""); + NUIS_LOG(FIT, ""); } } } void SplineWriter::GetWeightsForEvent(FitEvent *event) { // Get Starting Weight fRW->SetAllDials(&fParVect[0][0], fParVect[0].size()); double nomweight = fRW->CalcWeight(event); event->RWWeight = nomweight; if (fDrawSplines) { std::cout << "Nominal Spline Weight = " << nomweight << std::endl; } fWeightList[0] = nomweight; // Loop over parameter sets for (size_t i = 1; i < fParVect.size(); i++) { // Update FRW fRW->SetAllDials(&fParVect[i][0], fParVect[i].size()); // Calculate a weight for event double weight = fRW->CalcWeight(event); if (weight >= 0.0 and weight < 200) { // Fill Weight Set fWeightList[i] = weight / nomweight; if (fDrawSplines) std::cout << "Calculating values from weight set " << i << " " << fParVect[i][0] << " = " << weight << " " << weight / nomweight << std::endl; } else { fWeightList[i] = 1.0; } } } void SplineWriter::GetWeightsForEvent(FitEvent *event, double *weights) { // Get Starting Weight fRW->SetAllDials(&fParVect[0][0], fParVect[0].size()); double nomweight = fRW->CalcWeight(event); event->RWWeight = nomweight; if (fDrawSplines) { std::cout << "Nominal Spline Weight = " << nomweight << std::endl; } weights[0] = nomweight; // Loop over parameter sets for (size_t i = 1; i < fParVect.size(); i++) { // Update FRW fRW->SetAllDials(&fParVect[i][0], fParVect[i].size()); // Calculate a weight for event double weight = fRW->CalcWeight(event); if (weight >= 0.0 and weight < 200) { // Fill Weight Set weights[i] = weight / nomweight; if (fDrawSplines) std::cout << "Calculating values from weight set " << i << " " << fParVect[i][0] << " = " << weight << " " << weight / nomweight << std::endl; } else { weights[i] = 1.0; } fWeightList[i] = weights[i]; } } void SplineWriter::ReconfigureSet(int iset) { fCurrentSet = iset; fRW->SetAllDials(&fParVect[iset][0], fParVect[iset].size()); } double SplineWriter::GetWeightForThisSet(FitEvent *event, int iset) { if (iset != -1 and iset != fCurrentSet) { ReconfigureSet(iset); } return fRW->CalcWeight(event); } void SplineWriter::SetWeights(double *weights) { for (uint i = 0; i < fParVect.size(); i++) { fWeightList[i] = weights[i]; } } void SplineWriter::FitSplinesForEvent(double *inputweights, float *coeff) { int n = fAllSplines.size(); int coeffcount = 0; for (int i = 0; i < n; i++) { // DialVals std::vector> dialvals; std::vector weightvals; bool hasresponse = false; for (size_t j = 0; j < fSetIndex.size(); j++) { if (fSetIndex[j] != i + 1) continue; dialvals.push_back(fValList[j]); double tempw = inputweights[j]; weightvals.push_back(tempw); if (tempw != 1.0) hasresponse = true; } // Perform Fit if (hasresponse) { // std::cout << "Fitting Coeff" << std::endl; FitCoeff(&fAllSplines[i], dialvals, weightvals, &coeff[coeffcount], fDrawSplines); } else { for (int j = 0; coeffcount + j < fNCoEff; j++) { // std::cout << "Setting 0.0 response " << coeffcount + i << " " << // fNCoEff << std::endl; coeff[coeffcount + j] = 0.0; } } // std::cout << "Adding coeffcount" << std::endl; // Offset coeffcount coeffcount += (fAllSplines[i]).GetNPar(); } // std::cout << "FitEvent" << std::endl; return; } void SplineWriter::FitSplinesForEvent(TCanvas *fitcanvas, bool saveplot) { // Loop over splines // int count = 0; int coeffcount = 0; int n = fAllSplines.size(); std::vector splinecounter; for (int i = 0; i < n; i++) { splinecounter.push_back(coeffcount); coeffcount += fAllSplines[i].GetNPar(); } // #pragma omp parallel for for (int i = 0; i < n; i++) { // Store X/Y Vals std::vector> dialvals; std::vector weightvals; bool hasresponse = false; int npar = (fAllSplines[i]).GetNPar(); coeffcount = splinecounter[i]; for (size_t j = 0; j < fSetIndex.size(); j++) { if (fSetIndex[j] != i + 1) continue; dialvals.push_back(fValList[j]); double tempw = fWeightList[j]; weightvals.push_back(tempw); if (tempw != 1.0) hasresponse = true; } // Make a new graph and fit coeff if response if (hasresponse) { FitCoeff(&fAllSplines[i], dialvals, weightvals, &fCoEffStorer[coeffcount], fDrawSplines); } else { for (int i = 0; i < npar; i++) { fCoEffStorer[coeffcount + i] = 0.0; } } } // Check overrides // if (saveplot) { // coeffcount = 0; // // Make new canvas to save stuff into // if (fitcanvas) delete fitcanvas; // fitcanvas = new TCanvas("c1", "c1", fAllSplines.size() * 400 , 600); // fitcanvas->Divide(fAllSplines.size(), 1); // // Clear out points // for (size_t i = 0; i < fAllDrawnGraphs.size(); i++) { // if (fAllDrawnGraphs[i]) delete fAllDrawnGraphs[i]; // if (fAllDrawnHists[i]) delete fAllDrawnHists[i]; // } // fAllDrawnGraphs.clear(); // fAllDrawnHists.clear(); // for (size_t i = 0; i < fAllSplines.size(); i++) { // fitcanvas->cd(i + 1); // // Store X/Y Vals // std::vector > dialvals; // std::vector weightvals; // bool hasresponse = false; // int npar = (fAllSplines[i]).GetNPar(); // for (size_t j = 0; j < fSetIndex.size(); j++) { // if ((UInt_t)fSetIndex[j] != (UInt_t)i + 1) continue; // dialvals.push_back(fValList[j]); // weightvals.push_back(fWeightList[j] - 0.0); // if (fWeightList[j] != 1.0) hasresponse = true; // } // if (hasresponse) { // TGraph* gr = new TGraph(dialvals.size(), dialvals, weightvals); // fAllDrawnGraphs.push_back(gr); // // Get XMax Min // int n = xvals.size(); // double xmin = 99999.9; // double xmax = -99999.9; // for (int j = 0; j < n; j++) { // if (xvals[j] > xmax) xmax = xvals[j]; // if (xvals[j] < xmin) xmin = xvals[j]; // } // TH1D* hist = new TH1D("temp", "temp", 100, xmin, xmax); // fAllDrawnHists.push_back(hist); // for (int k = 0; k < 100; k++) { // double xtemp = hist->GetXaxis()->GetBinCenter(k + 1); // fAllSplines[i].Reconfigure(xtemp); // double ytemp = fAllSplines[i].DoEval(&fCoEffStorer[coeffcount]); // hist->SetBinContent(k + 1, ytemp); // } // // gr->Draw("APL"); // hist->SetLineColor(kRed); // hist->Draw("HIST C"); // hist->SetTitle("Spline Response"); // // hist->GetYaxis()->SetRangeUser(0.0, 3.0); // // gStyle->SetOptStat(0); // hist->SetStats(0); // gr->SetMarkerStyle(20); // gr->SetTitle("True Weight Points"); // gr->Draw("P SAME"); // gPad->BuildLegend(0.6, 0.6, 0.85, 0.85); // gPad->Update(); // hist->SetTitle(fSpline[i].c_str()); // hist->GetXaxis()->SetTitle("Dial Variation"); // hist->GetYaxis()->SetTitle("Event Weight"); // fitcanvas->Update(); // } // coeffcount += npar; // } // } } // Fitting // ---------------------------------------------- void SplineWriter::FitCoeff(Spline *spl, std::vector> &v, std::vector &w, float *coeff, bool draw) { std::vector x; std::vector y; std::vector z; for (size_t i = 0; i < v.size(); i++) { x.push_back(v[i][0]); if (v[i].size() > 1) y.push_back(v[i][1]); if (v[i].size() > 2) z.push_back(v[i][2]); } switch (spl->GetType()) { // Polynominal Graph Fits case k1DPol1: case k1DPol2: case k1DPol3: case k1DPol4: case k1DPol5: case k1DPol6: FitCoeff1DGraph(spl, v.size(), &x[0], &w[0], coeff, draw); break; case k1DTSpline3: GetCoeff1DTSpline3(spl, x.size(), &x[0], &w[0], coeff, draw); break; case k2DPol6: case k2DGaus: case k2DTSpline3: FitCoeff2DGraph(spl, v.size(), &x[0], &y[0], &w[0], coeff, draw); break; default: break; } #ifdef __MINUIT2_ENABLED__ if (fDrawSplines) { fSplineFCNs[spl] = new SplineFCN(spl, v, w); fSplineFCNs[spl]->SaveAs("mysplinetest_" + spl->GetName() + ".pdf", coeff); sleep(1); delete fSplineFCNs[spl]; } #endif } void SplineWriter::FitCoeff1DGraph(Spline *spl, int n, double *x, double *y, float *coeff, bool draw) { TGraph *gr = new TGraph(n, x, y); double xmin = 99999.9; double xmax = -99999.9; for (int i = 0; i < n; i++) { if (x[i] > xmax) xmax = x[i]; if (x[i] < xmin) xmin = x[i]; } double xwidth = xmax - xmin; xmin = xmin - xwidth * 0.01; xmax = xmax + xwidth * 0.01; // Create a new function for fitting. TF1 *func = spl->GetFunction(); // Run the actual spline fit StopTalking(); // If linear fit with two points if (n == 2 and spl->GetType() == k1DPol1) { float m = (y[1] - y[0]) / (x[1] - x[0]); float c = y[0] - (0.0 - x[0]) * m; func->SetParameter(0, c); func->SetParameter(1, m); } else if (spl->GetType() == k1DPol1) { gr->Fit(func, "WQ"); } else { gr->Fit(func, "FMWQ"); } StartTalking(); for (int i = 0; i < spl->GetNPar(); i++) { coeff[i] = func->GetParameter(i); } if (draw) { gr->Draw("APL"); gPad->Update(); gPad->SaveAs(("plot_test_" + spl->GetName() + ".pdf").c_str()); std::cout << "Saving Graph" << std::endl; sleep(3); } // delete func; delete gr; } double SplineFCN::operator()(const double *x) const { return DoEval(x); } double SplineFCN::DoEval(const double *x) const { float *fx = new float[fSpl->GetNPar()]; for (int i = 0; i < fSpl->GetNPar(); i++) { fx[i] = x[i]; } // double tot = 0; for (size_t i = 0; i < fVal.size(); i++) { int nonzero = 0; for (size_t j = 0; j < fVal[i].size(); j++) { fSpl->Reconfigure(fVal[i][j], j); // std::cout << "Reconfiguring " << fVal[i][j] << " " << j << std::endl; if (fVal[i][j] != 0.0) nonzero++; } if (uncorrelated and nonzero > 1) continue; double w = fSpl->DoEval(fx); double wdif = (w - fWeight[i]); // / (fWeight[i] * 0.05); tot += sqrt(wdif * wdif); } // delete fx; return tot; } void SplineFCN::UpdateWeights(std::vector &w) { for (uint i = 0; i < w.size(); i++) { fWeight[i] = w[i]; } } void SplineFCN::SetCorrelated(bool state) { uncorrelated = !state; } void SplineFCN::SaveAs(std::string name, const float *fx) { if (fVal[0].size() > 2) { TCanvas *c1 = new TCanvas("c1", "c1", 800, 600); c1->Divide(2, 1); TH1D *histmc = new TH1D("hist", "hist", fVal.size(), 0.0, double(fVal.size())); TH1D *histdt = new TH1D("histdt", "histdt", fVal.size(), 0.0, double(fVal.size())); for (size_t i = 0; i < fVal.size(); i++) { for (size_t j = 0; j < fVal[i].size(); j++) { fSpl->Reconfigure(fVal[i][j], j); } histmc->SetBinContent(i + 1, fSpl->DoEval(fx)); histdt->SetBinContent(i + 1, fWeight[i]); } // histmc->Add(histdt,-1.0); c1->cd(1); histmc->SetTitle("Spline;Parameter Set;Weight"); histmc->Draw("HIST"); histdt->SetLineColor(kRed); histdt->Draw("SAME HIST"); c1->cd(2); TH1D *histdif = (TH1D *)histmc->Clone(); histdif->Add(histdt, -1.0); histdif->Draw("HIST"); c1->Update(); c1->SaveAs(name.c_str()); delete c1; } else if (fVal[0].size() == 2) { TGraph2D *histmc = new TGraph2D(); TGraph2D *histdt = new TGraph2D(); TGraph2D *histdif = new TGraph2D(); for (size_t i = 0; i < fVal.size(); i++) { for (size_t j = 0; j < fVal[i].size(); j++) { fSpl->Reconfigure(fVal[i][j], j); } histmc->SetPoint(histmc->GetN(), fVal[i][0], fVal[i][1], fSpl->DoEval(fx)); histdt->SetPoint(histdt->GetN(), fVal[i][0], fVal[i][1], fWeight[i]); histdif->SetPoint(histdif->GetN(), fVal[i][0], fVal[i][1], fabs(fSpl->DoEval(fx) - fWeight[i])); } TCanvas *c1 = new TCanvas("c1", "c1", 800, 600); c1->Divide(3, 1); c1->cd(1); histmc->SetTitle(("Spline;" + fSpl->GetName()).c_str()); histmc->Draw("COLZ"); gPad->Update(); c1->cd(2); histdt->SetTitle(("Raw;" + fSpl->GetName()).c_str()); histdt->Draw("COLZ"); c1->cd(3); histdif->SetTitle(("Dif;" + fSpl->GetName()).c_str()); histdif->Draw("COLZ"); gPad->SetRightMargin(0.15); // gPad->SetLogz(1); gPad->Update(); c1->SaveAs(name.c_str()); delete c1; } else if (fVal[0].size() == 1) { TGraph *histmc = new TGraph(); TGraph *histdt = new TGraph(); TGraph *histdif = new TGraph(); for (size_t i = 0; i < fVal.size(); i++) { for (size_t j = 0; j < fVal[i].size(); j++) { fSpl->Reconfigure(fVal[i][j], j); } histmc->SetPoint(histmc->GetN(), fVal[i][0], fSpl->DoEval(fx)); histdt->SetPoint(histdt->GetN(), fVal[i][0], fWeight[i]); histdif->SetPoint(histdif->GetN(), fVal[i][0], fabs(fSpl->DoEval(fx) - fWeight[i])); } TCanvas *c1 = new TCanvas("c1", "c1", 800, 600); c1->Divide(2, 1); c1->cd(1); histmc->SetTitle(("Spline;" + fSpl->GetName()).c_str()); histmc->Draw("AC"); histmc->SetLineColor(kRed); histdt->SetTitle(("Raw;" + fSpl->GetName()).c_str()); histdt->Draw("SAME P"); histdt->SetMarkerStyle(20); gPad->Update(); c1->cd(2); histdif->SetTitle(("Dif;" + fSpl->GetName()).c_str()); histdif->Draw("APL"); gPad->Update(); c1->SaveAs(name.c_str()); delete c1; } // gPad->SaveAs(name.c_str()); } void SplineWriter::FitCoeff2DGraph(Spline *spl, int n, double *x, double *y, double *w, float *coeff, bool draw) { #pragma omp critical { TF2 *f2 = (TF2 *)spl->GetFunction(); TGraph2D *histmc = new TGraph2D(n, x, y, w); f2->SetNpx(400); StopTalking(); histmc->Fit(f2, "FMWQ"); StartTalking(); for (int i = 0; i < spl->GetNPar(); i++) { coeff[i] = f2->GetParameter(i); } // delete f2; delete histmc; } } void SplineWriter::FitCoeffNDGraph(Spline *spl, std::vector> &v, std::vector &w, float *coeff, bool draw) { #ifdef __MINUIT2_ENABLED__ if (fSplineFunctors.find(spl) != fSplineFunctors.end()) { delete fSplineFunctors[spl]; fSplineFunctors.erase(spl); } if (fSplineFCNs.find(spl) != fSplineFCNs.end()) { delete fSplineFCNs[spl]; fSplineFCNs.erase(spl); } if (fSplineMinimizers.find(spl) != fSplineMinimizers.end()) { delete fSplineMinimizers[spl]; fSplineMinimizers.erase(spl); } if (fSplineMinimizers.find(spl) == fSplineMinimizers.end()) { std::cout << "Building new ND minimizer for " << spl << std::endl; fSplineFCNs[spl] = new SplineFCN(spl, v, w); // fSplineFCNs[spl] = new SplineFCN(spl, v, w); fSplineFunctors[spl] = new ROOT::Math::Functor(*fSplineFCNs[spl], spl->GetNPar()); fSplineMinimizers[spl] = ROOT::Math::Factory::CreateMinimizer("Minuit2", "Combined"); fSplineMinimizers[spl]->SetMaxFunctionCalls(1E8); fSplineMinimizers[spl]->SetMaxIterations(1E8); fSplineMinimizers[spl]->SetTolerance(1.E-6); fSplineMinimizers[spl]->SetStrategy(2); for (int j = 0; j < spl->GetNPar(); j++) { fSplineMinimizers[spl]->SetVariable(j, Form("Par_%i", j), 0.1, 0.1); } } // Create a new function for fitting. // StopTalking(); // Update FCN fSplineFCNs[spl]->UpdateWeights(w); // fSplineMinimizers[spl]->SetDefaultOptions(); // fSplineMinimizers[spl]->Clear(); for (int j = 0; j < spl->GetNPar(); j++) { if (j != 0) { fSplineMinimizers[spl]->SetVariableValue(j, 0.1); // fSplineMinimizers[spl]->SetParameter(j, Form("Par_%i", j), 0.1, 0.1, // -100.0, 100.0 ); // fSplineMinimizers[spl]->SetVariableValue(j, 0.1); } } // fSplineFCNs[spl]->SetCorrelated(false); // fSplineFunctors[spl] = new ROOT::Math::Functor( *fSplineFCNs[spl], // spl->GetNPar() ); // fSplineMinimizers[spl]->SetFunction(*fSplineFunctors[spl]); // fSplineMinimizers[spl]->Minimize(); fSplineFCNs[spl]->SetCorrelated(true); delete fSplineFunctors[spl]; fSplineFunctors[spl] = new ROOT::Math::Functor(*fSplineFCNs[spl], spl->GetNPar()); fSplineMinimizers[spl]->SetFunction(*fSplineFunctors[spl]); // ((TFitterMinuit*)fSplineMinimizers[spl])->CreateMinimizer(TFitterMinuit::kMigrad); fSplineMinimizers[spl]->Minimize(); fSplineMinimizers[spl]->Minimize(); // ((TFitterMinuit*)fSplineMinimizers[spl])->CreateMinimizer(TFitterMinuit::kMigrad); // fSplineMinimizers[spl]->Minimize(); // delete minimizer; // StartTalking(); // Now Get Parameters const double *values = fSplineMinimizers[spl]->X(); for (int i = 0; i < spl->GetNPar(); i++) { std::cout << "Updated Coeff " << i << " " << values[i] << std::endl; coeff[i] = values[i]; } // Save a sample fSplineFCNs[spl]->SaveAs("mysplinetest_" + spl->GetName() + ".pdf", coeff); sleep(1); // delete values; // delete minimizer; #endif } // Spline extraction Functions void SplineWriter::GetCoeff1DTSpline3(Spline *spl, int n, double *x, double *y, float *coeff, bool draw) { StopTalking(); TSpline3 temp_spline = TSpline3("temp_spline", x, y, n); StartTalking(); for (size_t i = 0; i < (UInt_t)n; i++) { double a, b, c, d, e; temp_spline.GetCoeff(i, a, b, c, d, e); coeff[i * 4] = y[i]; coeff[i * 4 + 1] = c; coeff[i * 4 + 2] = d; coeff[i * 4 + 3] = e; } if (draw) { TGraph *gr = new TGraph(n, x, y); temp_spline.Draw("CA"); gr->Draw("PL SAME"); gPad->Update(); gPad->SaveAs(("plot_test_" + spl->GetName() + ".pdf").c_str()); delete gr; } return; } diff --git a/src/Statistical/StatUtils.cxx b/src/Statistical/StatUtils.cxx index b097cfc..c4fa68b 100644 --- a/src/Statistical/StatUtils.cxx +++ b/src/Statistical/StatUtils.cxx @@ -1,1406 +1,1406 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "StatUtils.h" #include "GeneralUtils.h" #include "NuisConfig.h" #include "TH1D.h" //******************************************************************* Double_t StatUtils::GetChi2FromDiag(TH1D *data, TH1D *mc, TH1I *mask) { //******************************************************************* Double_t Chi2 = 0.0; TH1D *calc_data = (TH1D *)data->Clone(); TH1D *calc_mc = (TH1D *)mc->Clone(); // Add MC Error to data if required if (FitPar::Config().GetParB("addmcerror")) { for (int i = 0; i < calc_data->GetNbinsX(); i++) { double dterr = calc_data->GetBinError(i + 1); double mcerr = calc_mc->GetBinError(i + 1); if (dterr > 0.0) { calc_data->SetBinError(i + 1, sqrt(dterr * dterr + mcerr * mcerr)); } } } // Apply masking if required if (mask) { calc_data = ApplyHistogramMasking(data, mask); calc_mc = ApplyHistogramMasking(mc, mask); } // Iterate over bins in X for (int i = 0; i < calc_data->GetNbinsX(); i++) { // Ignore bins with zero data or zero bin error if (calc_data->GetBinError(i + 1) <= 0.0 || calc_data->GetBinContent(i + 1) == 0.0) continue; // Take mc data difference double diff = calc_data->GetBinContent(i + 1) - calc_mc->GetBinContent(i + 1); double err = calc_data->GetBinError(i + 1); Chi2 += (diff * diff) / (err * err); } // cleanup delete calc_data; delete calc_mc; return Chi2; }; //******************************************************************* Double_t StatUtils::GetChi2FromDiag(TH2D *data, TH2D *mc, TH2I *map, TH2I *mask) { //******************************************************************* // Generate a simple map if (!map) map = GenerateMap(data); // Convert to 1D Histograms TH1D *data_1D = MapToTH1D(data, map); TH1D *mc_1D = MapToTH1D(mc, map); TH1I *mask_1D = MapToMask(mask, map); // Calculate 1D chi2 from 1D Plots Double_t Chi2 = StatUtils::GetChi2FromDiag(data_1D, mc_1D, mask_1D); // CleanUp delete data_1D; delete mc_1D; delete mask_1D; return Chi2; }; //******************************************************************* Double_t StatUtils::GetChi2FromCov(TH1D *data, TH1D *mc, TMatrixDSym *invcov, TH1I *mask, double data_scale, double covar_scale) { //******************************************************************* Double_t Chi2 = 0.0; TMatrixDSym *calc_cov = (TMatrixDSym *)invcov->Clone(); TH1D *calc_data = (TH1D *)data->Clone(); TH1D *calc_mc = (TH1D *)mc->Clone(); // If a mask if applied we need to apply it before the matrix is inverted if (mask) { calc_cov = ApplyInvertedMatrixMasking(invcov, mask); calc_data = ApplyHistogramMasking(data, mask); calc_mc = ApplyHistogramMasking(mc, mask); } // Add MC Error to data if required if (FitPar::Config().GetParB("statutils.addmcerror")) { // Make temp cov TMatrixDSym *newcov = StatUtils::GetInvert(calc_cov); // Add MC err to diag for (int i = 0; i < calc_data->GetNbinsX(); i++) { double mcerr = calc_mc->GetBinError(i + 1) * sqrt(covar_scale); double oldval = (*newcov)(i, i); - QLOG(FIT, + NUIS_LOG(FIT, "Adding cov stat " << mcerr * mcerr << " to " << (*newcov)(i, i)); (*newcov)(i, i) = oldval + mcerr * mcerr; } // Reset the calc_cov to new invert delete calc_cov; calc_cov = GetInvert(newcov); // Delete the tempcov delete newcov; } calc_data->Scale(data_scale); calc_mc->Scale(data_scale); (*calc_cov) *= covar_scale; // iterate over bins in X (i,j) - QLOG(DEB, "START Chi2 Calculation================="); + NUIS_LOG(DEB, "START Chi2 Calculation================="); for (int i = 0; i < calc_data->GetNbinsX(); i++) { - QLOG(DEB, + NUIS_LOG(DEB, "[CHI2] i = " << i << " [" << calc_data->GetXaxis()->GetBinLowEdge(i + 1) << " -- " << calc_data->GetXaxis()->GetBinUpEdge(i + 1) << "]."); for (int j = 0; j < calc_data->GetNbinsX(); j++) { - QLOG(DEB, "[CHI2]\t j = " + NUIS_LOG(DEB, "[CHI2]\t j = " << i << " [" << calc_data->GetXaxis()->GetBinLowEdge(j + 1) << " -- " << calc_data->GetXaxis()->GetBinUpEdge(j + 1) << "]."); if ((calc_data->GetBinContent(i + 1) != 0 || calc_mc->GetBinContent(i + 1) != 0) && ((*calc_cov)(i, j) != 0)) { - QLOG(DEB, + NUIS_LOG(DEB, "[CHI2]\t\t Chi2 contribution (i,j) = (" << i << "," << j << ")"); - QLOG(DEB, "[CHI2]\t\t Data - MC(i) = " + NUIS_LOG(DEB, "[CHI2]\t\t Data - MC(i) = " << calc_data->GetBinContent(i + 1) << " - " << calc_mc->GetBinContent(i + 1) << " = " << (calc_data->GetBinContent(i + 1) - calc_mc->GetBinContent(i + 1))); - QLOG(DEB, "[CHI2]\t\t Data - MC(j) = " + NUIS_LOG(DEB, "[CHI2]\t\t Data - MC(j) = " << calc_data->GetBinContent(j + 1) << " - " << calc_mc->GetBinContent(j + 1) << " = " << (calc_data->GetBinContent(j + 1) - calc_mc->GetBinContent(j + 1))); - QLOG(DEB, "[CHI2]\t\t Covar = " << (*calc_cov)(i, j)); + NUIS_LOG(DEB, "[CHI2]\t\t Covar = " << (*calc_cov)(i, j)); - QLOG(DEB, + NUIS_LOG(DEB, "[CHI2]\t\t Cont chi2 = " << ((calc_data->GetBinContent(i + 1) - calc_mc->GetBinContent(i + 1)) * (*calc_cov)(i, j) * (calc_data->GetBinContent(j + 1) - calc_mc->GetBinContent(j + 1))) << " " << Chi2); Chi2 += ((calc_data->GetBinContent(i + 1) - calc_mc->GetBinContent(i + 1)) * (*calc_cov)(i, j) * (calc_data->GetBinContent(j + 1) - calc_mc->GetBinContent(j + 1))); } else { - QLOG(DEB, "Skipping chi2 contribution (i,j) = (" + NUIS_LOG(DEB, "Skipping chi2 contribution (i,j) = (" << i << "," << j << "), Data = " << calc_data->GetBinContent(i + 1) << ", MC = " << calc_mc->GetBinContent(i + 1) << ", Cov = " << (*calc_cov)(i, j)); Chi2 += 0.; } } } // Cleanup delete calc_cov; delete calc_data; delete calc_mc; return Chi2; } //******************************************************************* Double_t StatUtils::GetChi2FromCov(TH2D *data, TH2D *mc, TMatrixDSym *invcov, TH2I *map, TH2I *mask) { //******************************************************************* // Generate a simple map if (!map) { map = StatUtils::GenerateMap(data); } // Convert to 1D Histograms TH1D *data_1D = MapToTH1D(data, map); TH1D *mc_1D = MapToTH1D(mc, map); TH1I *mask_1D = MapToMask(mask, map); // Calculate 1D chi2 from 1D Plots Double_t Chi2 = StatUtils::GetChi2FromCov(data_1D, mc_1D, invcov, mask_1D); // CleanUp delete data_1D; delete mc_1D; delete mask_1D; return Chi2; } //******************************************************************* Double_t StatUtils::GetChi2FromSVD(TH1D *data, TH1D *mc, TMatrixDSym *cov, TH1I *mask) { //******************************************************************* Double_t Chi2 = 0.0; TMatrixDSym *calc_cov = (TMatrixDSym *)cov->Clone(); TH1D *calc_data = (TH1D *)data->Clone(); TH1D *calc_mc = (TH1D *)mc->Clone(); // If a mask if applied we need to apply it before the matrix is inverted if (mask) { calc_cov = StatUtils::ApplyMatrixMasking(cov, mask); calc_data = StatUtils::ApplyHistogramMasking(data, mask); calc_mc = StatUtils::ApplyHistogramMasking(mc, mask); } // Decompose matrix TDecompSVD LU = TDecompSVD((*calc_cov)); LU.Decompose(); TMatrixDSym *cov_U = new TMatrixDSym(calc_data->GetNbinsX(), LU.GetU().GetMatrixArray(), ""); TVectorD *cov_S = new TVectorD(LU.GetSig()); // Apply basis rotation before adding up chi2 Double_t rotated_difference = 0.0; for (int i = 0; i < calc_data->GetNbinsX(); i++) { rotated_difference = 0.0; // Rotate basis of Data - MC for (int j = 0; j < calc_data->GetNbinsY(); j++) rotated_difference += (calc_data->GetBinContent(j + 1) - calc_mc->GetBinContent(j + 1)) * (*cov_U)(j, i); // Divide by rotated error cov_S Chi2 += rotated_difference * rotated_difference * 1E76 / (*cov_S)(i); } // Cleanup delete calc_cov; delete calc_data; delete calc_mc; delete cov_U; delete cov_S; return Chi2; } //******************************************************************* Double_t StatUtils::GetChi2FromSVD(TH2D *data, TH2D *mc, TMatrixDSym *cov, TH2I *map, TH2I *mask) { //******************************************************************* // Generate a simple map if (!map) map = StatUtils::GenerateMap(data); // Convert to 1D Histograms TH1D *data_1D = MapToTH1D(data, map); TH1D *mc_1D = MapToTH1D(mc, map); TH1I *mask_1D = MapToMask(mask, map); // Calculate from 1D Double_t Chi2 = StatUtils::GetChi2FromSVD(data_1D, mc_1D, cov, mask_1D); // CleanUp delete data_1D; delete mc_1D; delete mask_1D; return Chi2; } //******************************************************************* double StatUtils::GetChi2FromEventRate(TH1D *data, TH1D *mc, TH1I *mask) { //******************************************************************* // If just an event rate, for chi2 just use Poission Likelihood to calculate // the chi2 component double chi2 = 0.0; TH1D *calc_data = (TH1D *)data->Clone(); TH1D *calc_mc = (TH1D *)mc->Clone(); // Apply masking if required if (mask) { calc_data = ApplyHistogramMasking(data, mask); calc_mc = ApplyHistogramMasking(mc, mask); } // Iterate over bins in X for (int i = 0; i < calc_data->GetNbinsX(); i++) { double dt = calc_data->GetBinContent(i + 1); double mc = calc_mc->GetBinContent(i + 1); if (mc <= 0) continue; if (dt <= 0) { // Only add difference chi2 += 2 * (mc - dt); } else { // Do the chi2 for Poisson distributions chi2 += 2 * (mc - dt + (dt * log(dt / mc))); } /* LOG(REC)<<"Evt Chi2 cont = "<Clone(); // If a mask is provided we need to apply it before getting NDOF if (mask) { calc_hist = StatUtils::ApplyHistogramMasking(hist, mask); } // NDOF is defined as total number of bins with non-zero errors Int_t NDOF = 0; for (int i = 0; i < calc_hist->GetNbinsX(); i++) { if (calc_hist->GetBinError(i + 1) > 0.0) NDOF++; } delete calc_hist; return NDOF; }; //******************************************************************* Int_t StatUtils::GetNDOF(TH2D *hist, TH2I *map, TH2I *mask) { //******************************************************************* Int_t NDOF = 0; if (!map) map = StatUtils::GenerateMap(hist); for (int i = 0; i < hist->GetNbinsX(); i++) { for (int j = 0; j < hist->GetNbinsY(); j++) { if (mask->GetBinContent(i + 1, j + 1)) continue; if (map->GetBinContent(i + 1, j + 1) <= 0) continue; NDOF++; } } return NDOF; }; //******************************************************************* TH1D *StatUtils::ThrowHistogram(TH1D *hist, TMatrixDSym *cov, bool throwdiag, TH1I *mask) { //******************************************************************* TH1D *calc_hist = (TH1D *)hist->Clone((std::string(hist->GetName()) + "_THROW").c_str()); TMatrixDSym *calc_cov = (TMatrixDSym *)cov->Clone(); Double_t correl_val = 0.0; // If a mask if applied we need to apply it before the matrix is decomposed if (mask) { calc_cov = ApplyMatrixMasking(cov, mask); calc_hist = ApplyHistogramMasking(calc_hist, mask); } // If a covariance is provided we need a preset random vector and a decomp std::vector rand_val; TMatrixDSym *decomp_cov = NULL; if (cov) { for (int i = 0; i < hist->GetNbinsX(); i++) { rand_val.push_back(gRandom->Gaus(0.0, 1.0)); } // Decomp the matrix decomp_cov = StatUtils::GetDecomp(calc_cov); } // iterate over bins for (int i = 0; i < hist->GetNbinsX(); i++) { // By Default the errors on the histogram are thrown uncorrelated to the // other errors /* if (throwdiag) { calc_hist->SetBinContent(i + 1, (calc_hist->GetBinContent(i + 1) + \ gRandom->Gaus(0.0, 1.0) * calc_hist->GetBinError(i + 1)) ); } */ // If a covariance is provided that is also thrown if (cov) { correl_val = 0.0; for (int j = 0; j < hist->GetNbinsX(); j++) { correl_val += rand_val[j] * (*decomp_cov)(j, i); } calc_hist->SetBinContent( i + 1, (calc_hist->GetBinContent(i + 1) + correl_val * 1E-38)); } } delete calc_cov; delete decomp_cov; // return this new thrown data return calc_hist; }; //******************************************************************* TH2D *StatUtils::ThrowHistogram(TH2D *hist, TMatrixDSym *cov, TH2I *map, bool throwdiag, TH2I *mask) { //******************************************************************* // PLACEHOLDER!!!!!!!!! // Currently no support for throwing 2D Histograms from a covariance (void)hist; (void)cov; (void)map; (void)throwdiag; (void)mask; // /todo // Sort maps if required // Throw the covariance for a 1D plot // Unmap back to 2D Histogram return hist; } //******************************************************************* TH1D *StatUtils::ApplyHistogramMasking(TH1D *hist, TH1I *mask) { //******************************************************************* if (!mask) return ((TH1D *)hist->Clone()); // This masking is only sufficient for chi2 calculations, and will have dodgy // bin edges. // Get New Bin Count Int_t NBins = 0; for (int i = 0; i < hist->GetNbinsX(); i++) { if (mask->GetBinContent(i + 1)) continue; NBins++; } // Make new hist std::string newmaskname = std::string(hist->GetName()) + "_MSKD"; TH1D *calc_hist = new TH1D(newmaskname.c_str(), newmaskname.c_str(), NBins, 0, NBins); // fill new hist int binindex = 0; for (int i = 0; i < hist->GetNbinsX(); i++) { if (mask->GetBinContent(i + 1)) { - QLOG(REC, "Applying mask to bin " << i + 1 << " " << hist->GetName()); + NUIS_LOG(REC, "Applying mask to bin " << i + 1 << " " << hist->GetName()); continue; } calc_hist->SetBinContent(binindex + 1, hist->GetBinContent(i + 1)); calc_hist->SetBinError(binindex + 1, hist->GetBinError(i + 1)); binindex++; } return calc_hist; }; //******************************************************************* TH2D *StatUtils::ApplyHistogramMasking(TH2D *hist, TH2I *mask) { //******************************************************************* TH2D *newhist = (TH2D *)hist->Clone(); if (!mask) return newhist; for (int i = 0; i < hist->GetNbinsX(); i++) { for (int j = 0; j < hist->GetNbinsY(); j++) { if (mask->GetBinContent(i + 1, j + 1) > 0) { newhist->SetBinContent(i + 1, j + 1, 0.0); newhist->SetBinContent(i + 1, j + 1, 0.0); } } } return newhist; } //******************************************************************* TMatrixDSym *StatUtils::ApplyMatrixMasking(TMatrixDSym *mat, TH1I *mask) { //******************************************************************* if (!mask) return (TMatrixDSym *)(mat->Clone()); // Get New Bin Count Int_t NBins = 0; for (int i = 0; i < mask->GetNbinsX(); i++) { if (mask->GetBinContent(i + 1)) continue; NBins++; } // make new matrix TMatrixDSym *calc_mat = new TMatrixDSym(NBins); int col, row; // Need to mask out bins in the current matrix row = 0; for (int i = 0; i < mask->GetNbinsX(); i++) { col = 0; // skip if masked if (mask->GetBinContent(i + 1) > 0.5) continue; for (int j = 0; j < mask->GetNbinsX(); j++) { // skip if masked if (mask->GetBinContent(j + 1) > 0.5) continue; (*calc_mat)(row, col) = (*mat)(i, j); col++; } row++; } return calc_mat; }; //******************************************************************* TMatrixDSym *StatUtils::ApplyMatrixMasking(TMatrixDSym *mat, TH2D *data, TH2I *mask, TH2I *map) { //******************************************************************* if (!map) map = StatUtils::GenerateMap(data); TH1I *mask_1D = StatUtils::MapToMask(mask, map); TMatrixDSym *newmat = StatUtils::ApplyMatrixMasking(mat, mask_1D); delete mask_1D; return newmat; } //******************************************************************* TMatrixDSym *StatUtils::ApplyInvertedMatrixMasking(TMatrixDSym *mat, TH1I *mask) { //******************************************************************* TMatrixDSym *new_mat = GetInvert(mat); TMatrixDSym *masked_mat = ApplyMatrixMasking(new_mat, mask); TMatrixDSym *inverted_mat = GetInvert(masked_mat); delete masked_mat; delete new_mat; return inverted_mat; }; //******************************************************************* TMatrixDSym *StatUtils::ApplyInvertedMatrixMasking(TMatrixDSym *mat, TH2D *data, TH2I *mask, TH2I *map) { //******************************************************************* if (!map) map = StatUtils::GenerateMap(data); TH1I *mask_1D = StatUtils::MapToMask(mask, map); TMatrixDSym *newmat = ApplyInvertedMatrixMasking(mat, mask_1D); delete mask_1D; return newmat; } //******************************************************************* TMatrixDSym *StatUtils::GetInvert(TMatrixDSym *mat) { //******************************************************************* TMatrixDSym *new_mat = (TMatrixDSym *)mat->Clone(); // Check for diagonal bool non_diagonal = false; for (int i = 0; i < new_mat->GetNrows(); i++) { for (int j = 0; j < new_mat->GetNrows(); j++) { if (i == j) continue; if ((*new_mat)(i, j) != 0.0) { non_diagonal = true; break; } } } // If diag, just flip the diag if (!non_diagonal or new_mat->GetNrows() == 1) { for (int i = 0; i < new_mat->GetNrows(); i++) { if ((*new_mat)(i, i) != 0.0) (*new_mat)(i, i) = 1.0 / (*new_mat)(i, i); else (*new_mat)(i, i) = 0.0; } return new_mat; } // Invert full matrix TDecompSVD LU = TDecompSVD((*new_mat)); new_mat = new TMatrixDSym(new_mat->GetNrows(), LU.Invert().GetMatrixArray(), ""); return new_mat; } //******************************************************************* TMatrixDSym *StatUtils::GetDecomp(TMatrixDSym *mat) { //******************************************************************* TMatrixDSym *new_mat = (TMatrixDSym *)mat->Clone(); int nrows = new_mat->GetNrows(); // Check for diagonal bool diagonal = true; for (int i = 0; i < nrows; i++) { for (int j = 0; j < nrows; j++) { if (i == j) continue; if ((*new_mat)(i, j) != 0.0) { diagonal = false; break; } } } // If diag, just flip the diag if (diagonal or nrows == 1) { for (int i = 0; i < nrows; i++) { if ((*new_mat)(i, i) > 0.0) (*new_mat)(i, i) = sqrt((*new_mat)(i, i)); else (*new_mat)(i, i) = 0.0; } return new_mat; } TDecompChol LU = TDecompChol(*new_mat); LU.Decompose(); delete new_mat; TMatrixDSym *dec_mat = new TMatrixDSym(nrows, LU.GetU().GetMatrixArray(), ""); return dec_mat; } //******************************************************************* void StatUtils::ForceNormIntoCovar(TMatrixDSym *&mat, TH1D *hist, double norm) { //******************************************************************* if (!mat) mat = MakeDiagonalCovarMatrix(hist); int nbins = mat->GetNrows(); TMatrixDSym *new_mat = new TMatrixDSym(nbins); for (int i = 0; i < nbins; i++) { for (int j = 0; j < nbins; j++) { double valx = hist->GetBinContent(i + 1) * 1E38; double valy = hist->GetBinContent(j + 1) * 1E38; (*new_mat)(i, j) = (*mat)(i, j) + norm * norm * valx * valy; } } // Swap the two delete mat; mat = new_mat; return; }; //******************************************************************* void StatUtils::ForceNormIntoCovar(TMatrixDSym *mat, TH2D *data, double norm, TH2I *map) { //******************************************************************* if (!map) map = StatUtils::GenerateMap(data); TH1D *data_1D = MapToTH1D(data, map); StatUtils::ForceNormIntoCovar(mat, data_1D, norm); delete data_1D; return; } //******************************************************************* TMatrixDSym *StatUtils::MakeDiagonalCovarMatrix(TH1D *data, double scaleF) { //******************************************************************* TMatrixDSym *newmat = new TMatrixDSym(data->GetNbinsX()); for (int i = 0; i < data->GetNbinsX(); i++) { (*newmat)(i, i) = data->GetBinError(i + 1) * data->GetBinError(i + 1) * scaleF * scaleF; } return newmat; } //******************************************************************* TMatrixDSym *StatUtils::MakeDiagonalCovarMatrix(TH2D *data, TH2I *map, double scaleF) { //******************************************************************* if (!map) map = StatUtils::GenerateMap(data); TH1D *data_1D = MapToTH1D(data, map); return StatUtils::MakeDiagonalCovarMatrix(data_1D, scaleF); }; //******************************************************************* void StatUtils::SetDataErrorFromCov(TH1D *DataHist, TMatrixDSym *cov, double scale, bool ErrorCheck) { //******************************************************************* // Check if (ErrorCheck) { if (cov->GetNrows() != DataHist->GetNbinsX()) { - QERROR( + NUIS_ERR( FTL, "Nrows in cov don't match nbins in DataHist for SetDataErrorFromCov"); - QERROR(FTL, "Nrows = " << cov->GetNrows()); - QTHROW("Nbins = " << DataHist->GetNbinsX()); + NUIS_ERR(FTL, "Nrows = " << cov->GetNrows()); + NUIS_ABORT("Nbins = " << DataHist->GetNbinsX()); } } // Set bin errors form cov diag // Check if the errors are set bool ErrorsSet = false; for (int i = 0; i < DataHist->GetNbinsX(); i++) { if (ErrorsSet == true) break; if (DataHist->GetBinError(i + 1) != 0 && DataHist->GetBinContent(i + 1) > 0) ErrorsSet = true; } // Now loop over if (ErrorsSet && ErrorCheck) { for (int i = 0; i < DataHist->GetNbinsX(); i++) { double DataHisterr = DataHist->GetBinError(i + 1); double coverr = sqrt((*cov)(i, i)) * scale; // Check that the errors are within 1% of eachother if (fabs(DataHisterr - coverr) / DataHisterr > 0.01) { - QERROR(WRN, "Data error does not match covariance error for bin " + NUIS_ERR(WRN, "Data error does not match covariance error for bin " << i + 1 << " (" << DataHist->GetXaxis()->GetBinLowEdge(i + 1) << "-" << DataHist->GetXaxis()->GetBinLowEdge(i + 2) << ")"); - QERROR(WRN, "Data error: " << DataHisterr); - QERROR(WRN, "Cov error: " << coverr); + NUIS_ERR(WRN, "Data error: " << DataHisterr); + NUIS_ERR(WRN, "Cov error: " << coverr); } } // Else blindly trust the covariance } else { for (int i = 0; i < DataHist->GetNbinsX(); i++) { DataHist->SetBinError(i + 1, sqrt((*cov)(i, i)) * scale); } } return; } //******************************************************************* void StatUtils::SetDataErrorFromCov(TH2D *data, TMatrixDSym *cov, TH2I *map, double scale, bool ErrorCheck) { //******************************************************************* // Check if (ErrorCheck) { if (cov->GetNrows() != data->GetNbinsX() * data->GetNbinsY()) { - QERROR( + NUIS_ERR( FTL, - "Nrows in cov don't match nbins in data for SetDataQERRORorFromCov"); - QERROR(FTL, "Nrows = " << cov->GetNrows()); - QTHROW("Nbins = " << data->GetNbinsX()); + "Nrows in cov don't match nbins in data for SetDataNUIS_ERRorFromCov"); + NUIS_ERR(FTL, "Nrows = " << cov->GetNrows()); + NUIS_ABORT("Nbins = " << data->GetNbinsX()); } } // Set bin errors form cov diag // Check if the errors are set bool ErrorsSet = false; for (int i = 0; i < data->GetNbinsX(); i++) { for (int j = 0; j < data->GetNbinsX(); j++) { if (ErrorsSet == true) break; if (data->GetBinError(i + 1, j + 1) != 0) ErrorsSet = true; } } // Create map if required if (!map) map = StatUtils::GenerateMap(data); // Set Bin Errors from cov diag int count = 0; for (int i = 0; i < data->GetNbinsX(); i++) { for (int j = 0; j < data->GetNbinsY(); j++) { if (data->GetBinContent(i + 1, j + 1) == 0.0) continue; // If we have errors on our histogram the map is good count = map->GetBinContent(i + 1, j + 1) - 1; double dataerr = data->GetBinError(i + 1, j + 1); double coverr = sqrt((*cov)(count, count)) * scale; // Check that the errors are within 1% of eachother if (ErrorsSet && ErrorCheck) { if (fabs(dataerr - coverr) / dataerr > 0.01) { - QERROR(WRN, "Data error does not match covariance error for bin " + NUIS_ERR(WRN, "Data error does not match covariance error for bin " << i + 1 << " (" << data->GetXaxis()->GetBinLowEdge(i + 1) << "-" << data->GetXaxis()->GetBinLowEdge(i + 2) << ")"); - QERROR(WRN, "Data error: " << dataerr); - QERROR(WRN, "Cov error: " << coverr); + NUIS_ERR(WRN, "Data error: " << dataerr); + NUIS_ERR(WRN, "Cov error: " << coverr); } } else { data->SetBinError(i + 1, j + 1, sqrt((*cov)(count, count)) * scale); } } } // Delete the map now that we don't need it // Woops, it's needed elsewhere there! (Grrrrr) // map->Delete(); } TMatrixDSym *StatUtils::ExtractShapeOnlyCovar(TMatrixDSym *full_covar, TH1 *data_hist, double data_scale) { int nbins = full_covar->GetNrows(); TMatrixDSym *shape_covar = new TMatrixDSym(nbins); // Check nobody is being silly if (data_hist->GetNbinsX() != nbins) { - QERROR(WRN, "Inconsistent matrix and data histogram passed to " + NUIS_ERR(WRN, "Inconsistent matrix and data histogram passed to " "StatUtils::ExtractShapeOnlyCovar!"); - QERROR(WRN, "data_hist has " << data_hist->GetNbinsX() << " matrix has " + NUIS_ERR(WRN, "data_hist has " << data_hist->GetNbinsX() << " matrix has " << nbins); int err_bins = data_hist->GetNbinsX(); if (nbins > err_bins) err_bins = nbins; for (int i = 0; i < err_bins; ++i) { - QERROR(WRN, "Matrix diag. = " << (*full_covar)(i, i) << " data = " + NUIS_ERR(WRN, "Matrix diag. = " << (*full_covar)(i, i) << " data = " << data_hist->GetBinContent(i + 1)); } return NULL; } double total_data = 0; double total_covar = 0; // Initial loop to calculate some constants for (int i = 0; i < nbins; ++i) { total_data += data_hist->GetBinContent(i + 1) * data_scale; for (int j = 0; j < nbins; ++j) { total_covar += (*full_covar)(i, j); } } if (total_data == 0 || total_covar == 0) { - QERROR(WRN, "Stupid matrix or data histogram passed to " + NUIS_ERR(WRN, "Stupid matrix or data histogram passed to " "StatUtils::ExtractShapeOnlyCovar! Ignoring..."); return NULL; } - QLOG(SAM, "Norm error = " << sqrt(total_covar) / total_data); + NUIS_LOG(SAM, "Norm error = " << sqrt(total_covar) / total_data); // Now loop over and calculate the shape-only matrix for (int i = 0; i < nbins; ++i) { double data_i = data_hist->GetBinContent(i + 1) * data_scale; for (int j = 0; j < nbins; ++j) { double data_j = data_hist->GetBinContent(j + 1) * data_scale; double norm_term = data_i * data_j * total_covar / total_data / total_data; double mix_sum1 = 0; double mix_sum2 = 0; for (int k = 0; k < nbins; ++k) { mix_sum1 += (*full_covar)(k, j); mix_sum2 += (*full_covar)(i, k); } double mix_term1 = data_i * (mix_sum1 / total_data - total_covar * data_j / total_data / total_data); double mix_term2 = data_j * (mix_sum2 / total_data - total_covar * data_i / total_data / total_data); (*shape_covar)(i, j) = (*full_covar)(i, j) - mix_term1 - mix_term2 - norm_term; } } return shape_covar; } //******************************************************************* TH2I *StatUtils::GenerateMap(TH2D *hist) { //******************************************************************* std::string maptitle = std::string(hist->GetName()) + "_MAP"; TH2I *map = new TH2I(maptitle.c_str(), maptitle.c_str(), hist->GetNbinsX(), 0, hist->GetNbinsX(), hist->GetNbinsY(), 0, hist->GetNbinsY()); Int_t index = 1; for (int i = 0; i < hist->GetNbinsX(); i++) { for (int j = 0; j < hist->GetNbinsY(); j++) { if (hist->GetBinContent(i + 1, j + 1) > 0) { map->SetBinContent(i + 1, j + 1, index); index++; } else { map->SetBinContent(i + 1, j + 1, 0); } } } return map; } //******************************************************************* TH1D *StatUtils::MapToTH1D(TH2D *hist, TH2I *map) { //******************************************************************* if (!hist) return NULL; // Get N bins for 1D plot Int_t Nbins = map->GetMaximum(); std::string name1D = std::string(hist->GetName()) + "_1D"; // Make new 1D Hist TH1D *newhist = new TH1D(name1D.c_str(), name1D.c_str(), Nbins, 0, Nbins); // map bin contents for (int i = 0; i < map->GetNbinsX(); i++) { for (int j = 0; j < map->GetNbinsY(); j++) { if (map->GetBinContent(i + 1, j + 1) == 0) continue; newhist->SetBinContent(map->GetBinContent(i + 1, j + 1), hist->GetBinContent(i + 1, j + 1)); newhist->SetBinError(map->GetBinContent(i + 1, j + 1), hist->GetBinError(i + 1, j + 1)); } } // return return newhist; } //******************************************************************* TH1I *StatUtils::MapToMask(TH2I *hist, TH2I *map) { //******************************************************************* TH1I *newhist = NULL; if (!hist) return newhist; // Get N bins for 1D plot Int_t Nbins = map->GetMaximum(); std::string name1D = std::string(hist->GetName()) + "_1D"; // Make new 1D Hist newhist = new TH1I(name1D.c_str(), name1D.c_str(), Nbins, 0, Nbins); // map bin contents for (int i = 0; i < map->GetNbinsX(); i++) { for (int j = 0; j < map->GetNbinsY(); j++) { if (map->GetBinContent(i + 1, j + 1) == 0) continue; newhist->SetBinContent(map->GetBinContent(i + 1, j + 1), hist->GetBinContent(i + 1, j + 1)); } } // return return newhist; } TMatrixDSym *StatUtils::GetCovarFromCorrel(TMatrixDSym *correl, TH1D *data) { int nbins = correl->GetNrows(); TMatrixDSym *covar = new TMatrixDSym(nbins); for (int i = 0; i < nbins; i++) { for (int j = 0; j < nbins; j++) { (*covar)(i, j) = (*correl)(i, j) * data->GetBinError(i + 1) * data->GetBinError(j + 1); } } return covar; } //******************************************************************* TMatrixD *StatUtils::GetMatrixFromTextFile(std::string covfile, int dimx, int dimy) { //******************************************************************* // Determine dim if (dimx == -1 and dimy == -1) { std::string line; std::ifstream covar(covfile.c_str(), std::ifstream::in); int row = 0; while (std::getline(covar >> std::ws, line, '\n')) { int column = 0; std::vector entries = GeneralUtils::ParseToDbl(line, " "); if (entries.size() <= 1) { - QERROR(WRN, "StatUtils::GetMatrixFromTextFile, matrix only has <= 1 " + NUIS_ERR(WRN, "StatUtils::GetMatrixFromTextFile, matrix only has <= 1 " "entries on this line: " << row); } for (std::vector::iterator iter = entries.begin(); iter != entries.end(); iter++) { column++; if (column > dimx) dimx = column; } row++; if (row > dimy) dimy = row; } } // Or assume symmetric if (dimx != -1 and dimy == -1) { dimy = dimx; } assert(dimy != -1 && " matrix dimy not set."); // Make new matrix TMatrixD *mat = new TMatrixD(dimx, dimy); std::string line; std::ifstream covar(covfile.c_str(), std::ifstream::in); int row = 0; while (std::getline(covar >> std::ws, line, '\n')) { int column = 0; std::vector entries = GeneralUtils::ParseToDbl(line, " "); if (entries.size() <= 1) { - QERROR(WRN, "StatUtils::GetMatrixFromTextFile, matrix only has <= 1 " + NUIS_ERR(WRN, "StatUtils::GetMatrixFromTextFile, matrix only has <= 1 " "entries on this line: " << row); } for (std::vector::iterator iter = entries.begin(); iter != entries.end(); iter++) { // Check Rows // assert(row > mat->GetNrows() && " covar rows doesn't match matrix // rows."); // assert(column > mat->GetNcols() && " covar cols doesn't match matrix // cols."); // Fill Matrix (*mat)(row, column) = (*iter); column++; } row++; } return mat; } //******************************************************************* TMatrixD *StatUtils::GetMatrixFromRootFile(std::string covfile, std::string histname) { //******************************************************************* std::string inputfile = covfile + ";" + histname; std::vector splitfile = GeneralUtils::ParseToStr(inputfile, ";"); if (splitfile.size() < 2) { - QTHROW("No object name given!"); + NUIS_ABORT("No object name given!"); } // Get file TFile *tempfile = new TFile(splitfile[0].c_str(), "READ"); // Get Object TObject *obj = tempfile->Get(splitfile[1].c_str()); if (!obj) { - QTHROW("Object " << splitfile[1] << " doesn't exist!"); + NUIS_ABORT("Object " << splitfile[1] << " doesn't exist!"); } // Try casting TMatrixD *mat = dynamic_cast(obj); if (mat) { TMatrixD *newmat = (TMatrixD *)mat->Clone(); delete mat; tempfile->Close(); return newmat; } TMatrixDSym *matsym = dynamic_cast(obj); if (matsym) { TMatrixD *newmat = new TMatrixD(matsym->GetNrows(), matsym->GetNrows()); for (int i = 0; i < matsym->GetNrows(); i++) { for (int j = 0; j < matsym->GetNrows(); j++) { (*newmat)(i, j) = (*matsym)(i, j); } } delete matsym; tempfile->Close(); return newmat; } TH2D *mathist = dynamic_cast(obj); if (mathist) { TMatrixD *newmat = new TMatrixD(mathist->GetNbinsX(), mathist->GetNbinsX()); for (int i = 0; i < mathist->GetNbinsX(); i++) { for (int j = 0; j < mathist->GetNbinsX(); j++) { (*newmat)(i, j) = mathist->GetBinContent(i + 1, j + 1); } } delete mathist; tempfile->Close(); return newmat; } return NULL; } //******************************************************************* TMatrixDSym *StatUtils::GetCovarFromTextFile(std::string covfile, int dim) { //******************************************************************* // Delete TempMat TMatrixD *tempmat = GetMatrixFromTextFile(covfile, dim, dim); // Make a symmetric covariance TMatrixDSym *newmat = new TMatrixDSym(tempmat->GetNrows()); for (int i = 0; i < tempmat->GetNrows(); i++) { for (int j = 0; j < tempmat->GetNrows(); j++) { (*newmat)(i, j) = (*tempmat)(i, j); } } delete tempmat; return newmat; } //******************************************************************* TMatrixDSym *StatUtils::GetCovarFromRootFile(std::string covfile, std::string histname) { //******************************************************************* TMatrixD *tempmat = GetMatrixFromRootFile(covfile, histname); TMatrixDSym *newmat = new TMatrixDSym(tempmat->GetNrows()); for (int i = 0; i < tempmat->GetNrows(); i++) { for (int j = 0; j < tempmat->GetNrows(); j++) { (*newmat)(i, j) = (*tempmat)(i, j); } } delete tempmat; return newmat; } diff --git a/src/T2K/T2K_CC0pi_XSec_2DPcos_nu.cxx b/src/T2K/T2K_CC0pi_XSec_2DPcos_nu.cxx index 033b255..4196e6f 100644 --- a/src/T2K/T2K_CC0pi_XSec_2DPcos_nu.cxx +++ b/src/T2K/T2K_CC0pi_XSec_2DPcos_nu.cxx @@ -1,170 +1,170 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "T2K_SignalDef.h" #include "T2K_CC0pi_XSec_2DPcos_nu.h" //******************************************************************** T2K_CC0pi_XSec_2DPcos_nu::T2K_CC0pi_XSec_2DPcos_nu(nuiskey samplekey) { //******************************************************************** // Sample overview --------------------------------------------------- std::string descrip = "T2K_CC0pi_XSec_2DPcos_nu sample. \n" \ "Target: CH \n" \ "Flux: MINERvA Medium Energy FHC numu \n" \ "Signal: CC-inclusive with theta < 20deg \n"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle("P_{#mu} (GeV)"); fSettings.SetYTitle("cos#theta_{#mu}"); fSettings.SetZTitle("d^{2}#sigma/dP_{#mu}dcos#theta_{#mu} (cm^{2}/GeV)"); fSettings.SetAllowedTypes("DIAG,FULL/FREE,SHAPE,FIX/SYSTCOV/STATCOV","FIX"); fSettings.SetEnuRange(0.0, 10.0); fSettings.DefineAllowedTargets("C,H"); if (fName == "T2K_CC0pi_XSec_2DPcos_nu_I") fAnalysis = 1; else fAnalysis = 2; // CCQELike plot information fSettings.SetTitle("T2K_CC0pi_XSec_2DPcos_nu"); fSettings.DefineAllowedSpecies("numu"); forwardgoing = (fSettings.GetS("type").find("REST") != std::string::npos); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = ((GetEventHistogram()->Integral("width")/(fNEvents+0.)) * 1E-38 / (TotalIntegratedFlux())); // Setup Histograms SetHistograms(); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; bool T2K_CC0pi_XSec_2DPcos_nu::isSignal(FitEvent *event){ return SignalDef::isT2K_CC0pi(event, EnuMin, EnuMax, forwardgoing); }; void T2K_CC0pi_XSec_2DPcos_nu::FillEventVariables(FitEvent* event){ if (event->NumFSParticle(13) == 0) return; TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; double pmu = Pmu.Vect().Mag()/1000.; double CosThetaMu = cos(Pnu.Vect().Angle(Pmu.Vect())); fXVar = pmu; fYVar = CosThetaMu; return; }; void T2K_CC0pi_XSec_2DPcos_nu::SetHistograms(){ fIsSystCov = fSettings.GetS("type").find("SYSTCOV") != std::string::npos; fIsStatCov = fSettings.GetS("type").find("STATCOV") != std::string::npos; fIsNormCov = fSettings.GetS("type").find("NORMCOV") != std::string::npos; fNDataPointsX = 12; fNDataPointsY = 10; // Open file std::string infile = FitPar::GetDataBase()+"/T2K/CC0pi/T2K_CC0PI_2DPmuCosmu_Data.root"; TFile* rootfile = new TFile(infile.c_str(), "READ"); TH2D* tempcov = NULL; // ANALYSIS 2 if (fAnalysis == 2){ // Get Data fDataHist = (TH2D*) rootfile->Get("analysis2_data"); fDataHist->SetDirectory(0); fDataHist->SetNameTitle((fName + "_data").c_str(), (fName + "_data" + fPlotTitles).c_str()); // For some reason the error on the data in the data release is 1E-20 // That is wrong, so set it to zero here for (int i = 0; i < fDataHist->GetXaxis()->GetNbins()+1; ++i) { for (int j = 0; j < fDataHist->GetYaxis()->GetNbins()+1; ++j) { fDataHist->SetBinError(i+1, j+1, 0.0); } } // Get Map fMapHist = (TH2I*) rootfile->Get("analysis2_map"); fMapHist->SetDirectory(0); fMapHist->SetNameTitle((fName + "_map").c_str(), (fName + "_map" + fPlotTitles).c_str()); // Get Syst/Stat Covar TH2D* tempsyst = (TH2D*) rootfile->Get("analysis2_systcov"); TH2D* tempstat = (TH2D*) rootfile->Get("analysis2_statcov"); TH2D* tempnorm = (TH2D*) rootfile->Get("analysis2_normcov"); // Create covar [Default is both] tempcov = (TH2D*) tempsyst->Clone(); tempcov->Reset(); if (fIsSystCov) tempcov->Add(tempsyst); if (fIsStatCov) tempcov->Add(tempstat); if (fIsNormCov) tempcov->Add(tempnorm); if (!fIsSystCov && !fIsStatCov && !fIsNormCov){ tempcov->Add(tempsyst); tempcov->Add(tempstat); tempcov->Add(tempnorm); } } if (!tempcov){ - QTHROW("TEMPCOV NOT SET"); + NUIS_ABORT("TEMPCOV NOT SET"); } // Setup Covar int nbins = tempcov->GetNbinsX(); fFullCovar = new TMatrixDSym(nbins); for (int i = 0; i < nbins; i++){ for (int j = 0; j < nbins; j++){ (*fFullCovar)(i,j) = tempcov->GetBinContent(i+1,j+1); } } covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(covar); // Set Data Errors StatUtils::SetDataErrorFromCov(fDataHist, fFullCovar, fMapHist, 1E-38); // Remove root file rootfile->Close(); return; }; diff --git a/src/T2K/T2K_CCinc_XSec_2DPcos_nu_nonuniform.cxx b/src/T2K/T2K_CCinc_XSec_2DPcos_nu_nonuniform.cxx index d5e213a..5624011 100644 --- a/src/T2K/T2K_CCinc_XSec_2DPcos_nu_nonuniform.cxx +++ b/src/T2K/T2K_CCinc_XSec_2DPcos_nu_nonuniform.cxx @@ -1,256 +1,256 @@ #include "T2K_CCinc_XSec_2DPcos_nu_nonuniform.h" #include "T2K_SignalDef.h" // *********************************** // Implemented by Alfonso Garcia, Barcelona (now NIKHEF) // Clarence Wret, Rochester // (Alfonso was the T2K analyser) // *********************************** //******************************************************************** T2K_CCinc_XSec_2DPcos_nu_nonuniform::T2K_CCinc_XSec_2DPcos_nu_nonuniform( nuiskey samplekey) { //******************************************************************** fAllowedTypes += "/GENIE/NEUT"; // Sample overview --------------------------------------------------- std::string descrip = "T2K_CCinc_XSec_2DPcos_nu_nonuniform sample. \n" "Target: CH \n" "Flux: T2K FHC numu \n" "Signal: CC-inclusive \n"; // Setup common settings fSettings = LoadSampleSettings(samplekey); fSettings.SetDescription(descrip); fSettings.SetXTitle(""); // fSettings.SetXTitle("p_{#mu} (GeV)"); // fSettings.SetYTitle("cos#theta_{#mu}"); fSettings.SetYTitle("#frac{d^{2}#sigma}{dp_{#mu}dcos#theta_{#mu}} " "[#frac{cm^{2}}{nucleon/GeV/c}]"); fSettings.SetEnuRange(0.0, 30.0); fSettings.DefineAllowedTargets("C,H"); // CCQELike plot information fSettings.SetTitle("T2K CC-inclusive p_{#mu} cos#theta_{#mu}"); fSettings.DefineAllowedSpecies("numu"); FinaliseSampleSettings(); // Scaling Setup --------------------------------------------------- // ScaleFactor automatically setup for DiffXSec/cm2/Nucleon fScaleFactor = GetEventHistogram()->Integral("width") * 1E-38 / fNEvents / TotalIntegratedFlux(); // Default to using the NEUT unfolded data UnfoldWithGENIE = false; // Check option if (fSettings.Found("type", "GENIE")) UnfoldWithGENIE = true; // Tell user what's happening if (UnfoldWithGENIE) { - QLOG(SAM, fName << " is using GENIE unfolded data. Want NEUT? Specify " + NUIS_LOG(SAM, fName << " is using GENIE unfolded data. Want NEUT? Specify " "type=\"NEUT\" in your config file"); } else { - QLOG(SAM, fName << " is using NEUT unfolded data. Want GENIE? Specify " + NUIS_LOG(SAM, fName << " is using NEUT unfolded data. Want GENIE? Specify " "type=\"GENIE\" in your config file"); } // Setup Histograms SetHistograms(); // Final setup --------------------------------------------------- FinaliseMeasurement(); }; // Signal is simply a CC inclusive without any angular/momentum cuts bool T2K_CCinc_XSec_2DPcos_nu_nonuniform::isSignal(FitEvent *event) { return SignalDef::isCCINC(event, 14, EnuMin, EnuMax); }; void T2K_CCinc_XSec_2DPcos_nu_nonuniform::FillEventVariables(FitEvent *event) { if (event->NumFSParticle(13) == 0) return; TLorentzVector Pnu = event->GetNeutrinoIn()->fP; TLorentzVector Pmu = event->GetHMFSParticle(13)->fP; double pmu = Pmu.Vect().Mag() / 1000.; double CosThetaMu = cos(Pnu.Vect().Angle(Pmu.Vect())); fXVar = pmu; fYVar = CosThetaMu; }; // Fill up the MCSlice void T2K_CCinc_XSec_2DPcos_nu_nonuniform::FillHistograms() { if (Signal) FillMCSlice(fXVar, fYVar, Weight); } // Modification is needed after the full reconfigure to move bins around void T2K_CCinc_XSec_2DPcos_nu_nonuniform::ConvertEventRates() { // Do standard conversion. Measurement1D::ConvertEventRates(); // First scale MC slices also by their width in Y fMCHist_Slices[0]->Scale(1.0 / 0.25); fMCHist_Slices[1]->Scale(1.0 / 0.50); fMCHist_Slices[2]->Scale(1.0 / 0.20); fMCHist_Slices[3]->Scale(1.0 / 0.15); fMCHist_Slices[4]->Scale(1.0 / 0.11); fMCHist_Slices[5]->Scale(1.0 / 0.09); fMCHist_Slices[6]->Scale(1.0 / 0.07); fMCHist_Slices[7]->Scale(1.0 / 0.05); fMCHist_Slices[8]->Scale(1.0 / 0.04); fMCHist_Slices[9]->Scale(1.0 / 0.025); fMCHist_Slices[10]->Scale(1.0 / 0.015); // Now Convert into 1D list fMCHist->Reset(); int bincount = 0; for (int i = 0; i < nSlices; i++) { for (int j = 0; j < fMCHist_Slices[i]->GetNbinsX(); j++) { fMCHist->SetBinContent(bincount + 1, fMCHist_Slices[i]->GetBinContent(j + 1)); fMCHist->SetBinError(bincount + 1, fMCHist_Slices[i]->GetBinError(j + 1)); bincount++; } } }; void T2K_CCinc_XSec_2DPcos_nu_nonuniform::FillMCSlice(double x, double y, double w) { if (y >= -1.0 && y < -0.25) fMCHist_Slices[0]->Fill(x, w); else if (y >= -0.25 && y < 0.25) fMCHist_Slices[1]->Fill(x, w); else if (y >= 0.25 && y < 0.45) fMCHist_Slices[2]->Fill(x, w); else if (y >= 0.45 && y < 0.6) fMCHist_Slices[3]->Fill(x, w); else if (y >= 0.6 && y < 0.71) fMCHist_Slices[4]->Fill(x, w); else if (y >= 0.71 && y < 0.80) fMCHist_Slices[5]->Fill(x, w); else if (y >= 0.80 && y < 0.87) fMCHist_Slices[6]->Fill(x, w); else if (y >= 0.87 && y < 0.92) fMCHist_Slices[7]->Fill(x, w); else if (y >= 0.92 && y < 0.96) fMCHist_Slices[8]->Fill(x, w); else if (y >= 0.96 && y <= 0.985) fMCHist_Slices[9]->Fill(x, w); else if (y >= 0.985 && y <= 1.0) fMCHist_Slices[10]->Fill(x, w); }; void T2K_CCinc_XSec_2DPcos_nu_nonuniform::SetHistograms() { // Read in 1D Data Histograms TFile *fInputFile = new TFile((FitPar::GetDataBase() + "T2K/CCinc/nd280data-numu-cc-inc-xs-on-c-2018/histograms.root") .c_str(), "OPEN"); // Number of theta slices in the release nSlices = 11; // Data release includes unfolding with NEUT or GENIE as prior // Choose whichever the user specifies std::string basename; if (UnfoldWithGENIE) basename = "hist_xsec_data_prior_neut_cthbin"; else basename = "hist_xsec_data_prior_neut_cthbin"; // Read in 2D Data Slices and Make MC Slices // Count the number of bins we have in total so we can match covariance matrix int bincount = 0; for (int i = 0; i < nSlices; i++) { // Get Data Histogram // fDataHist_Slices.push_back((TH1D*)fInputFile->Get(Form("dataslice_%i",i))->Clone()); fDataHist_Slices.push_back( (TH1D *)fInputFile->Get(Form("%s%i", basename.c_str(), i)) ->Clone( Form("T2K_CCinc_XSec_2DPcos_nu_nonuniform_slice%i_data", i))); fDataHist_Slices[i]->SetDirectory(0); fDataHist_Slices[i]->Scale(1E-39); fDataHist_Slices[i]->GetYaxis()->SetTitle(fSettings.GetS("ytitle").c_str()); // Count up the bins bincount += fDataHist_Slices.back()->GetNbinsX(); // Make MC Clones fMCHist_Slices.push_back((TH1D *)fDataHist_Slices[i]->Clone( Form("T2K_CCinc_XSec_2DPcos_nu_nonuniform_Slice%i_MC", i))); fMCHist_Slices[i]->Reset(); fMCHist_Slices[i]->SetDirectory(0); fMCHist_Slices[i]->SetLineColor(kRed); fMCHist_Slices[i]->GetYaxis()->SetTitle(fSettings.GetS("ytitle").c_str()); SetAutoProcessTH1(fDataHist_Slices[i], kCMD_Write); SetAutoProcessTH1(fMCHist_Slices[i]); } fDataHist = new TH1D((fSettings.GetName() + "_data").c_str(), (fSettings.GetFullTitles()).c_str(), bincount, 0, bincount); fDataHist->SetDirectory(0); int counter = 0; for (int i = 0; i < nSlices; ++i) { // Set a nice title std::string costitle = fDataHist_Slices[i]->GetTitle(); costitle = costitle.substr(costitle.find("-> ") + 3, costitle.size()); std::string found = costitle.substr(0, costitle.find(" < ")); std::string comp = costitle.substr(costitle.find(found) + found.size() + 3, costitle.size()); comp = comp.substr(comp.find(" < ") + 3, comp.size()); costitle = "cos#theta_{#mu}=" + found + "-" + comp; for (int j = 0; j < fDataHist_Slices[i]->GetNbinsX(); j++) { fDataHist->SetBinContent(counter + 1, fDataHist_Slices[i]->GetBinContent(j + 1)); fDataHist->SetBinError(counter + 1, fDataHist_Slices[i]->GetBinError(j + 1)); // Set a nice axis if (j == 0) fDataHist->GetXaxis()->SetBinLabel( counter + 1, Form("%s, p_{#mu}=%.1f-%.1f", costitle.c_str(), fDataHist_Slices[i]->GetBinLowEdge(j + 1), fDataHist_Slices[i]->GetBinLowEdge(j + 2))); else fDataHist->GetXaxis()->SetBinLabel( counter + 1, Form("p_{#mu}=%.1f-%.1f", fDataHist_Slices[i]->GetBinLowEdge(j + 1), fDataHist_Slices[i]->GetBinLowEdge(j + 2))); counter++; } } // The correlation matrix // Major in angular bins, minor in momentum bins: runs theta1, pmu1, pmu2, // theta2, pmu1, pmu2, theta3, pmu1, pmu2 etc The correlation matrix TH2D *tempcov = NULL; if (UnfoldWithGENIE) tempcov = (TH2D *)fInputFile->Get("covariance_matrix_genie"); else tempcov = (TH2D *)fInputFile->Get("covariance_matrix_neut"); fFullCovar = new TMatrixDSym(bincount); for (int i = 0; i < fDataHist->GetNbinsX(); i++) { for (int j = 0; j < fDataHist->GetNbinsX(); j++) { (*fFullCovar)(i, j) = tempcov->GetBinContent(i + 1, j + 1); } } covar = StatUtils::GetInvert(fFullCovar); fDecomp = StatUtils::GetDecomp(fFullCovar); (*fFullCovar) *= 1E38 * 1E38; (*covar) *= 1E-38 * 1E-38; fInputFile->Close(); }; diff --git a/src/Tests/ParserTests.cxx b/src/Tests/ParserTests.cxx index 8ae5278..a7908c3 100644 --- a/src/Tests/ParserTests.cxx +++ b/src/Tests/ParserTests.cxx @@ -1,99 +1,99 @@ #include #include #include "FitLogger.h" #include "GeneralUtils.h" #include "InputUtils.h" #include "NuisConfig.h" #include "StatUtils.h" int main(int argc, char const *argv[]) { SETVERBOSITY(SAM); - QLOG(FIT, "* Running InputUtils Tests"); - QLOG(FIT, "***************************************************"); + NUIS_LOG(FIT, "* Running InputUtils Tests"); + NUIS_LOG(FIT, "***************************************************"); Config::SetPar("NEUT_DIR", "/var/test/NEUT"); Config::SetPar("NUWRO_DIR", "/var/test/NUWRO"); Config::SetPar("GIBUU_DIR", "/var/test/NIBUU"); Config::SetPar("GENIE_DIR", "/var/test/GENIE"); std::string NEUTInp = "NEUT:@NEUT_DIR/file.root"; InputUtils::InputType NEUTInpt = InputUtils::ParseInputType(GeneralUtils::ParseToStr(NEUTInp, ":")[0]); std::string ExpandNEUT = InputUtils::ExpandInputDirectories( GeneralUtils::ParseToStr(NEUTInp, ":")[1]); bool IsJointNEUT_not = InputUtils::IsJointInput(GeneralUtils::ParseToStr(NEUTInp, ":")[1]); std::string NEUTJointInp = "NEUT:(@NEUT_DIR/file1.root,@NEUT_DIR/file2.root)"; bool IsJointNEUT = InputUtils::IsJointInput(GeneralUtils::ParseToStr(NEUTJointInp, ":")[1]); std::string ExpandNEUTJoint = InputUtils::ExpandInputDirectories( GeneralUtils::ParseToStr(NEUTJointInp, ":")[1]); std::string NEUTJointInp_MissFSlash = "NEUT:(@NEUT_DIR/file1.root,@NEUT_DIR/file2.root)"; std::string ExpandNEUTJoint_MissFSlash = InputUtils::ExpandInputDirectories( GeneralUtils::ParseToStr(NEUTJointInp_MissFSlash, ":")[1]); Config::SetPar("NEUT_DIR", "/var/test/NEUT/"); std::string NEUTJointInp_DoubleFSlash = "NEUT:(@NEUT_DIR/file1.root,@NEUT_DIR/file2.root)"; std::string ExpandNEUTJoint_DoubleFSlash = InputUtils::ExpandInputDirectories( GeneralUtils::ParseToStr(NEUTJointInp_DoubleFSlash, ":")[1]); - QLOG(FIT, " * Test input type parse"); - QLOG(FIT, " * Test parse 'NEUT'"); + NUIS_LOG(FIT, " * Test input type parse"); + NUIS_LOG(FIT, " * Test parse 'NEUT'"); if (!(NEUTInpt == InputUtils::kNEUT_Input)) { - QERROR(FTL, GeneralUtils::ParseToStr(NEUTInp, ":")[0] << " parsed as type: " + NUIS_ERR(FTL, GeneralUtils::ParseToStr(NEUTInp, ":")[0] << " parsed as type: " << NEUTInpt); } assert(NEUTInpt == InputUtils::kNEUT_Input); - QLOG(FIT, " * Test IsJoint check"); - QLOG(FIT, " * Test IsJoint on non joint"); + NUIS_LOG(FIT, " * Test IsJoint check"); + NUIS_LOG(FIT, " * Test IsJoint on non joint"); if (IsJointNEUT_not) { - QERROR(FTL, + NUIS_ERR(FTL, GeneralUtils::ParseToStr(NEUTInp, ":")[1] << " parsed as Joint."); } assert(!IsJointNEUT_not); - QLOG(FIT, " * Test IsJoint on joint"); + NUIS_LOG(FIT, " * Test IsJoint on joint"); if (!IsJointNEUT) { - QERROR(FTL, GeneralUtils::ParseToStr(NEUTJointInp, ":")[1] + NUIS_ERR(FTL, GeneralUtils::ParseToStr(NEUTJointInp, ":")[1] << " parsed as not Joint."); } assert(IsJointNEUT); - QLOG(FIT, " * Test directory expansion"); + NUIS_LOG(FIT, " * Test directory expansion"); if ("/var/test/NEUT/file.root" != ExpandNEUT) { - QERROR(FTL, GeneralUtils::ParseToStr(NEUTInp, ":")[1] << " expanded to: " + NUIS_ERR(FTL, GeneralUtils::ParseToStr(NEUTInp, ":")[1] << " expanded to: " << ExpandNEUT); } assert("/var/test/NEUT/file.root" == ExpandNEUT); - QLOG(FIT, " * Test joint directory expansion"); + NUIS_LOG(FIT, " * Test joint directory expansion"); if ("(/var/test/NEUT/file1.root,/var/test/NEUT/file2.root)" != ExpandNEUTJoint) { - QERROR(FTL, GeneralUtils::ParseToStr(NEUTJointInp, ":")[1] + NUIS_ERR(FTL, GeneralUtils::ParseToStr(NEUTJointInp, ":")[1] << " expanded to: " << ExpandNEUTJoint); } assert("(/var/test/NEUT/file1.root,/var/test/NEUT/file2.root)" == ExpandNEUTJoint); - QLOG(FIT, " * Test joint directory expansion missing slash"); + NUIS_LOG(FIT, " * Test joint directory expansion missing slash"); if ("(/var/test/NEUT/file1.root,/var/test/NEUT/file2.root)" != ExpandNEUTJoint_MissFSlash) { - QERROR(FTL, GeneralUtils::ParseToStr(NEUTJointInp_MissFSlash, ":")[1] + NUIS_ERR(FTL, GeneralUtils::ParseToStr(NEUTJointInp_MissFSlash, ":")[1] << " expanded to: " << ExpandNEUTJoint_MissFSlash); } assert("(/var/test/NEUT/file1.root,/var/test/NEUT/file2.root)" == ExpandNEUTJoint_MissFSlash); - QLOG(FIT, " * Test joint directory expansion double slash"); + NUIS_LOG(FIT, " * Test joint directory expansion double slash"); if ("(/var/test/NEUT/file1.root,/var/test/NEUT/file2.root)" != ExpandNEUTJoint_DoubleFSlash) { - QERROR(FTL, GeneralUtils::ParseToStr(NEUTJointInp_DoubleFSlash, ":")[1] + NUIS_ERR(FTL, GeneralUtils::ParseToStr(NEUTJointInp_DoubleFSlash, ":")[1] << " expanded to: " << ExpandNEUTJoint_DoubleFSlash); } assert("(/var/test/NEUT/file1.root,/var/test/NEUT/file2.root)" == ExpandNEUTJoint_DoubleFSlash); - QLOG(FIT, "* Passed InputUtils Tests"); - QLOG(FIT, "***************************************************"); + NUIS_LOG(FIT, "* Passed InputUtils Tests"); + NUIS_LOG(FIT, "***************************************************"); } diff --git a/src/Tests/SignalDefTests.cxx b/src/Tests/SignalDefTests.cxx index 5399028..493c4b6 100644 --- a/src/Tests/SignalDefTests.cxx +++ b/src/Tests/SignalDefTests.cxx @@ -1,380 +1,380 @@ #include #include #include "ConstructibleFitEvent.h" #include "SignalDef.h" int main(int argc, char const *argv[]) { bool FailOnFail = (argc > 1); SETVERBOSITY(SAM); - QLOG(FIT, "* Running SignalDef Tests"); - QLOG(FIT, "***************************************************"); + NUIS_LOG(FIT, "* Running SignalDef Tests"); + NUIS_LOG(FIT, "***************************************************"); int IS[] = {14}; int FS_CC0pi_1[] = {13, 2112, 2212, 2112, 2212}; ConstructibleFitEvent fe_CC0pi_1 = MakePDGStackEvent(IS, FS_CC0pi_1); int FS_CC0pi_2[] = {13, 2112, 2212, 2112, 2212}; ConstructibleFitEvent fe_CC0pi_2 = MakePDGStackEvent(IS, FS_CC0pi_2, 2); int FS_CC0pi_3[] = {-13, 2112, 2212, 2112, 2212}; ConstructibleFitEvent fe_CC0pi_3 = MakePDGStackEvent(IS, FS_CC0pi_3); int FS_CC0pi_4[] = {13, 2112, 2212}; ConstructibleFitEvent fe_CC0pi_4 = MakePDGStackEvent(IS, FS_CC0pi_4, 12); int FS_CC1pip_1[] = {13, 2212, 2112, 211}; ConstructibleFitEvent fe_CC1pip_1 = MakePDGStackEvent(IS, FS_CC1pip_1, 2); int FS_CC1pim_1[] = {13, -211, 2212, 2112}; ConstructibleFitEvent fe_CC1pim_1 = MakePDGStackEvent(IS, FS_CC1pim_1, 11); int FS_CC1pi0_1[] = {13, 2212, 111, 2112}; ConstructibleFitEvent fe_CC1pi0_1 = MakePDGStackEvent(IS, FS_CC1pi0_1, 12); int FS_CC1pi0_2[] = {11, 2212, 111, 2112}; ConstructibleFitEvent fe_CC1pi0_2 = MakePDGStackEvent(IS, FS_CC1pi0_2, 12); int FS_CCNpi_1[] = {13, 2212, 111, 2112, 211}; ConstructibleFitEvent fe_CCNpi_1 = MakePDGStackEvent(IS, FS_CCNpi_1, 21); int FS_CCNpi_2[] = {13, -211, 211, 2112, 211}; ConstructibleFitEvent fe_CCNpi_2 = MakePDGStackEvent(IS, FS_CCNpi_2, 21); int FS_CCNpi_3[] = {13, 2212, 111, 211, -211}; ConstructibleFitEvent fe_CCNpi_3 = MakePDGStackEvent(IS, FS_CCNpi_3, 26); int FS_CCNpi_4[] = {13, 2212, 111, 111, 111}; ConstructibleFitEvent fe_CCNpi_4 = MakePDGStackEvent(IS, FS_CCNpi_4, 26); int FS_CCCOH_1[] = {13, 211}; ConstructibleFitEvent fe_CCCOH_1 = MakePDGStackEvent(IS, FS_CCCOH_1, 16); int FS_NCel_1[] = {14, 2112}; ConstructibleFitEvent fe_NCel_1 = MakePDGStackEvent(IS, FS_NCel_1, 52); int FS_NCel_2[] = {12, 2212}; ConstructibleFitEvent fe_NCel_2 = MakePDGStackEvent(IS, FS_NCel_2, 51); int FS_NC1pi_1[] = {14, 2112, -211}; ConstructibleFitEvent fe_NC1pi_1 = MakePDGStackEvent(IS, FS_NC1pi_1, 31); int FS_NCNpi_1[] = {14, 2212, 211}; ConstructibleFitEvent fe_NCNpi_1 = MakePDGStackEvent(IS, FS_NCNpi_1, 32); - QLOG(FIT, "* Testing: SignalDef::isCCINC"); + NUIS_LOG(FIT, "* Testing: SignalDef::isCCINC"); std::map isCCINC_PassExpectations; isCCINC_PassExpectations[&fe_CC0pi_1] = true; // numu CC0pi isCCINC_PassExpectations[&fe_CC0pi_2] = true; // numu CC0pi (2p2h) isCCINC_PassExpectations[&fe_CC0pi_3] = false; // numub CC0pi isCCINC_PassExpectations[&fe_CC0pi_4] = true; // numu CC0pi (RES) isCCINC_PassExpectations[&fe_CC1pip_1] = true; // numu CC1pip (2p2h) isCCINC_PassExpectations[&fe_CC1pim_1] = true; // numu CC1pim isCCINC_PassExpectations[&fe_CC1pi0_1] = true; // numu CC1pi0 isCCINC_PassExpectations[&fe_CC1pi0_2] = false; // nue CC1pi0 isCCINC_PassExpectations[&fe_CCNpi_1] = true; // numu CC multi pi isCCINC_PassExpectations[&fe_CCNpi_2] = true; // numu CC multi pi isCCINC_PassExpectations[&fe_CCNpi_3] = true; // numu CC multi pi isCCINC_PassExpectations[&fe_CCNpi_4] = true; // numu CC multi pi isCCINC_PassExpectations[&fe_CCCOH_1] = true; // numu CC COH pi isCCINC_PassExpectations[&fe_NCel_1] = false; // numu NCEl isCCINC_PassExpectations[&fe_NCel_2] = false; // nue NCEl isCCINC_PassExpectations[&fe_NC1pi_1] = false; // numu NC1pi isCCINC_PassExpectations[&fe_NCNpi_1] = false; // numu NC multi pi size_t ctr = 0; for (std::map::iterator fe_it = isCCINC_PassExpectations.begin(); fe_it != isCCINC_PassExpectations.end(); ++fe_it, ++ctr) { bool res = SignalDef::isCCINC(fe_it->first, 14); if (res != fe_it->second) { - QERROR(FTL, "Event: (" << ctr << ")\n" << fe_it->first->ToString()); - QERROR(FTL, (res ? "passed" : "failed") + NUIS_ERR(FTL, "Event: (" << ctr << ")\n" << fe_it->first->ToString()); + NUIS_ERR(FTL, (res ? "passed" : "failed") << " SignalDef::isCCINC unexpectedly."); } else { - QLOG(SAM, "Event: (" << ctr << ") " << (res ? "passed" : "failed") + NUIS_LOG(SAM, "Event: (" << ctr << ") " << (res ? "passed" : "failed") << " as expected."); } if (FailOnFail) { assert(res == fe_it->second); } } - QLOG(FIT, "* Testing: SignalDef::isNCINC"); + NUIS_LOG(FIT, "* Testing: SignalDef::isNCINC"); std::map isNCINC_PassExpectations; isNCINC_PassExpectations[&fe_CC0pi_1] = false; // numu CC0pi isNCINC_PassExpectations[&fe_CC0pi_2] = false; // numu CC0pi (2p2h) isNCINC_PassExpectations[&fe_CC0pi_3] = false; // numub CC0pi isNCINC_PassExpectations[&fe_CC0pi_4] = false; // numu CC0pi (RES) isNCINC_PassExpectations[&fe_CC1pip_1] = false; // numu CC1pip (2p2h) isNCINC_PassExpectations[&fe_CC1pim_1] = false; // numu CC1pim isNCINC_PassExpectations[&fe_CC1pi0_1] = false; // numu CC1pi0 isNCINC_PassExpectations[&fe_CC1pi0_2] = false; // nue CC1pi0 isNCINC_PassExpectations[&fe_CCNpi_1] = false; // numu CC multi pi isNCINC_PassExpectations[&fe_CCNpi_2] = false; // numu CC multi pi isNCINC_PassExpectations[&fe_CCNpi_3] = false; // numu CC multi pi isNCINC_PassExpectations[&fe_CCNpi_4] = false; // numu CC multi pi isNCINC_PassExpectations[&fe_CCCOH_1] = false; // numu CC COH pi isNCINC_PassExpectations[&fe_NCel_1] = true; // numu NCEl isNCINC_PassExpectations[&fe_NCel_2] = false; // nue NCEl isNCINC_PassExpectations[&fe_NC1pi_1] = true; // numu NC1pi isNCINC_PassExpectations[&fe_NCNpi_1] = true; // numu NC multi pi ctr = 0; for (std::map::iterator fe_it = isNCINC_PassExpectations.begin(); fe_it != isNCINC_PassExpectations.end(); ++fe_it, ++ctr) { bool res = SignalDef::isNCINC(fe_it->first, 14); if (res != fe_it->second) { - QERROR(FTL, "Event: (" << ctr << ")\n" << fe_it->first->ToString()); - QERROR(FTL, (res ? "passed" : "failed") + NUIS_ERR(FTL, "Event: (" << ctr << ")\n" << fe_it->first->ToString()); + NUIS_ERR(FTL, (res ? "passed" : "failed") << " SignalDef::isNCINC unexpectedly."); } else { - QLOG(SAM, "Event: (" << ctr << ") " << (res ? "passed" : "failed") + NUIS_LOG(SAM, "Event: (" << ctr << ") " << (res ? "passed" : "failed") << " as expected."); } if (FailOnFail) { assert(res == fe_it->second); } } - QLOG(FIT, "* Testing: SignalDef::isCC0pi"); + NUIS_LOG(FIT, "* Testing: SignalDef::isCC0pi"); std::map isCC0pi_PassExpectations; isCC0pi_PassExpectations[&fe_CC0pi_1] = true; // numu CC0pi isCC0pi_PassExpectations[&fe_CC0pi_2] = true; // numu CC0pi (2p2h) isCC0pi_PassExpectations[&fe_CC0pi_3] = false; // numub CC0pi isCC0pi_PassExpectations[&fe_CC0pi_4] = true; // numu CC0pi (RES) isCC0pi_PassExpectations[&fe_CC1pip_1] = false; // numu CC1pip (2p2h) isCC0pi_PassExpectations[&fe_CC1pim_1] = false; // numu CC1pim isCC0pi_PassExpectations[&fe_CC1pi0_1] = false; // numu CC1pi0 isCC0pi_PassExpectations[&fe_CC1pi0_2] = false; // nue CC1pi0 isCC0pi_PassExpectations[&fe_CCNpi_1] = false; // numu CC multi pi isCC0pi_PassExpectations[&fe_CCNpi_2] = false; // numu CC multi pi isCC0pi_PassExpectations[&fe_CCNpi_3] = false; // numu CC multi pi isCC0pi_PassExpectations[&fe_CCNpi_4] = false; // numu CC multi pi isCC0pi_PassExpectations[&fe_CCCOH_1] = false; // numu CC COH pi isCC0pi_PassExpectations[&fe_NCel_1] = false; // numu NCEl isCC0pi_PassExpectations[&fe_NCel_2] = false; // nue NCEl isCC0pi_PassExpectations[&fe_NC1pi_1] = false; // numu NC1pi isCC0pi_PassExpectations[&fe_NCNpi_1] = false; // numu NC multi pi ctr = 0; for (std::map::iterator fe_it = isCC0pi_PassExpectations.begin(); fe_it != isCC0pi_PassExpectations.end(); ++fe_it, ++ctr) { bool res = SignalDef::isCC0pi(fe_it->first, 14); if (res != fe_it->second) { - QERROR(FTL, "Event: (" << ctr << ")\n" + NUIS_ERR(FTL, "Event: (" << ctr << ")\n" << fe_it->first->ToString() << " "); - QERROR(FTL, (res ? "passed" : "failed") + NUIS_ERR(FTL, (res ? "passed" : "failed") << " SignalDef::isCC0pi unexpectedly."); } else { - QLOG(SAM, "Event: (" << ctr << ") " << (res ? "passed" : "failed") + NUIS_LOG(SAM, "Event: (" << ctr << ") " << (res ? "passed" : "failed") << " as expected."); } if (FailOnFail) { assert(res == fe_it->second); } } - QLOG(FIT, "* Testing: SignalDef::isCCQELike"); + NUIS_LOG(FIT, "* Testing: SignalDef::isCCQELike"); std::map isCCQELike_PassExpectations; isCCQELike_PassExpectations[&fe_CC0pi_1] = true; // numu CC0pi isCCQELike_PassExpectations[&fe_CC0pi_2] = true; // numu CC0pi (2p2h) isCCQELike_PassExpectations[&fe_CC0pi_3] = false; // numub CC0pi isCCQELike_PassExpectations[&fe_CC0pi_4] = false; // numu CC0pi (RES) isCCQELike_PassExpectations[&fe_CC1pip_1] = true; // numu CC1pip (2p2h) isCCQELike_PassExpectations[&fe_CC1pim_1] = false; // numu CC1pim isCCQELike_PassExpectations[&fe_CC1pi0_1] = false; // numu CC1pi0 isCCQELike_PassExpectations[&fe_CC1pi0_2] = false; // nue CC1pi0 isCCQELike_PassExpectations[&fe_CCNpi_1] = false; // numu CC multi pi isCCQELike_PassExpectations[&fe_CCNpi_2] = false; // numu CC multi pi isCCQELike_PassExpectations[&fe_CCNpi_3] = false; // numu CC multi pi isCCQELike_PassExpectations[&fe_CCNpi_4] = false; // numu CC multi pi isCCQELike_PassExpectations[&fe_CCCOH_1] = false; // numu CC COH pi isCCQELike_PassExpectations[&fe_NCel_1] = false; // numu NCEl isCCQELike_PassExpectations[&fe_NCel_2] = false; // nue NCEl isCCQELike_PassExpectations[&fe_NC1pi_1] = false; // numu NC1pi isCCQELike_PassExpectations[&fe_NCNpi_1] = false; // numu NC multi pi ctr = 0; for (std::map::iterator fe_it = isCCQELike_PassExpectations.begin(); fe_it != isCCQELike_PassExpectations.end(); ++fe_it, ++ctr) { bool res = SignalDef::isCCQELike(fe_it->first, 14); if (res != fe_it->second) { - QERROR(FTL, "Event: (" << ctr << ")\n" << fe_it->first->ToString()); - QERROR(FTL, (res ? "passed" : "failed") + NUIS_ERR(FTL, "Event: (" << ctr << ")\n" << fe_it->first->ToString()); + NUIS_ERR(FTL, (res ? "passed" : "failed") << " SignalDef::isCCQELike unexpectedly."); } else { - QLOG(SAM, "Event: (" << ctr << ") " << (res ? "passed" : "failed") + NUIS_LOG(SAM, "Event: (" << ctr << ") " << (res ? "passed" : "failed") << " as expected."); } if (FailOnFail) { assert(res == fe_it->second); } } - QLOG(FIT, "* Testing: SignalDef::isCCQE"); + NUIS_LOG(FIT, "* Testing: SignalDef::isCCQE"); std::map isCCQE_PassExpectations; isCCQE_PassExpectations[&fe_CC0pi_1] = true; // numu CC0pi isCCQE_PassExpectations[&fe_CC0pi_2] = false; // numu CC0pi (2p2h) isCCQE_PassExpectations[&fe_CC0pi_3] = false; // numub CC0pi isCCQE_PassExpectations[&fe_CC0pi_4] = false; // numu CC0pi (RES) isCCQE_PassExpectations[&fe_CC1pip_1] = false; // numu CC1pip (2p2h) isCCQE_PassExpectations[&fe_CC1pim_1] = false; // numu CC1pim isCCQE_PassExpectations[&fe_CC1pi0_1] = false; // numu CC1pi0 isCCQE_PassExpectations[&fe_CC1pi0_2] = false; // nue CC1pi0 isCCQE_PassExpectations[&fe_CCNpi_1] = false; // numu CC multi pi isCCQE_PassExpectations[&fe_CCNpi_2] = false; // numu CC multi pi isCCQE_PassExpectations[&fe_CCNpi_3] = false; // numu CC multi pi isCCQE_PassExpectations[&fe_CCNpi_4] = false; // numu CC multi pi isCCQE_PassExpectations[&fe_CCCOH_1] = false; // numu CC COH pi isCCQE_PassExpectations[&fe_NCel_1] = false; // numu NCEl isCCQE_PassExpectations[&fe_NCel_2] = false; // nue NCEl isCCQE_PassExpectations[&fe_NC1pi_1] = false; // numu NC1pi isCCQE_PassExpectations[&fe_NCNpi_1] = false; // numu NC multi pi ctr = 0; for (std::map::iterator fe_it = isCCQE_PassExpectations.begin(); fe_it != isCCQE_PassExpectations.end(); ++fe_it, ++ctr) { bool res = SignalDef::isCCQE(fe_it->first, 14); if (res != fe_it->second) { - QERROR(FTL, "Event: (" << ctr << ")\n" << fe_it->first->ToString()); - QERROR(FTL, (res ? "passed" : "failed") + NUIS_ERR(FTL, "Event: (" << ctr << ")\n" << fe_it->first->ToString()); + NUIS_ERR(FTL, (res ? "passed" : "failed") << " SignalDef::isCCQE unexpectedly."); } else { - QLOG(SAM, "Event: (" << ctr << ") " << (res ? "passed" : "failed") + NUIS_LOG(SAM, "Event: (" << ctr << ") " << (res ? "passed" : "failed") << " as expected."); } if (FailOnFail) { assert(res == fe_it->second); } } - QLOG(FIT, "* Testing: SignalDef::isCCCOH"); + NUIS_LOG(FIT, "* Testing: SignalDef::isCCCOH"); std::map isCCCOH_PassExpectations; isCCCOH_PassExpectations[&fe_CC0pi_1] = false; // numu CC0pi isCCCOH_PassExpectations[&fe_CC0pi_2] = false; // numu CC0pi (2p2h) isCCCOH_PassExpectations[&fe_CC0pi_3] = false; // numub CC0pi isCCCOH_PassExpectations[&fe_CC0pi_4] = false; // numu CC0pi (RES) isCCCOH_PassExpectations[&fe_CC1pip_1] = false; // numu CC1pip (2p2h) isCCCOH_PassExpectations[&fe_CC1pim_1] = false; // numu CC1pim isCCCOH_PassExpectations[&fe_CC1pi0_1] = false; // numu CC1pi0 isCCCOH_PassExpectations[&fe_CC1pi0_2] = false; // nue CC1pi0 isCCCOH_PassExpectations[&fe_CCNpi_1] = false; // numu CC multi pi isCCCOH_PassExpectations[&fe_CCNpi_2] = false; // numu CC multi pi isCCCOH_PassExpectations[&fe_CCNpi_3] = false; // numu CC multi pi isCCCOH_PassExpectations[&fe_CCNpi_4] = false; // numu CC multi pi isCCCOH_PassExpectations[&fe_CCCOH_1] = true; // numu CC COH pi isCCCOH_PassExpectations[&fe_NCel_1] = false; // numu NCEl isCCCOH_PassExpectations[&fe_NCel_2] = false; // nue NCEl isCCCOH_PassExpectations[&fe_NC1pi_1] = false; // numu NC1pi isCCCOH_PassExpectations[&fe_NCNpi_1] = false; // numu NC multi pi ctr = 0; for (std::map::iterator fe_it = isCCCOH_PassExpectations.begin(); fe_it != isCCCOH_PassExpectations.end(); ++fe_it, ++ctr) { bool res = SignalDef::isCCCOH(fe_it->first, 14, 211); if (res != fe_it->second) { - QERROR(FTL, "Event: (" << ctr << ")\n" << fe_it->first->ToString()); - QERROR(FTL, (res ? "passed" : "failed") + NUIS_ERR(FTL, "Event: (" << ctr << ")\n" << fe_it->first->ToString()); + NUIS_ERR(FTL, (res ? "passed" : "failed") << " SignalDef::isCCCOH unexpectedly."); } else { - QLOG(SAM, "Event: (" << ctr << ") " << (res ? "passed" : "failed") + NUIS_LOG(SAM, "Event: (" << ctr << ") " << (res ? "passed" : "failed") << " as expected."); } if (FailOnFail) { assert(res == fe_it->second); } } - QLOG(FIT, "* Testing: SignalDef::isCC1pi"); + NUIS_LOG(FIT, "* Testing: SignalDef::isCC1pi"); std::map isCC1pi_PassExpectations; isCC1pi_PassExpectations[&fe_CC0pi_1] = false; // numu CC0pi isCC1pi_PassExpectations[&fe_CC0pi_2] = false; // numu CC0pi (2p2h) isCC1pi_PassExpectations[&fe_CC0pi_3] = false; // numub CC0pi isCC1pi_PassExpectations[&fe_CC0pi_4] = false; // numu CC0pi (RES) isCC1pi_PassExpectations[&fe_CC1pip_1] = true; // numu CC1pip (2p2h) isCC1pi_PassExpectations[&fe_CC1pim_1] = false; // numu CC1pim isCC1pi_PassExpectations[&fe_CC1pi0_1] = false; // numu CC1pi0 isCC1pi_PassExpectations[&fe_CC1pi0_2] = false; // nue CC1pi0 isCC1pi_PassExpectations[&fe_CCNpi_1] = false; // numu CC multi pi isCC1pi_PassExpectations[&fe_CCNpi_2] = false; // numu CC multi pi isCC1pi_PassExpectations[&fe_CCNpi_3] = false; // numu CC multi pi isCC1pi_PassExpectations[&fe_CCNpi_4] = false; // numu CC multi pi isCC1pi_PassExpectations[&fe_CCCOH_1] = true; // numu CC COH pi isCC1pi_PassExpectations[&fe_NCel_1] = false; // numu NCEl isCC1pi_PassExpectations[&fe_NCel_2] = false; // nue NCEl isCC1pi_PassExpectations[&fe_NC1pi_1] = false; // numu NC1pi isCC1pi_PassExpectations[&fe_NCNpi_1] = false; // numu NC multi pi ctr = 0; for (std::map::iterator fe_it = isCC1pi_PassExpectations.begin(); fe_it != isCC1pi_PassExpectations.end(); ++fe_it, ++ctr) { bool res = SignalDef::isCC1pi(fe_it->first, 14, 211); if (res != fe_it->second) { - QERROR(FTL, "Event: (" << ctr << ")\n" << fe_it->first->ToString()); - QERROR(FTL, (res ? "passed" : "failed") + NUIS_ERR(FTL, "Event: (" << ctr << ")\n" << fe_it->first->ToString()); + NUIS_ERR(FTL, (res ? "passed" : "failed") << " SignalDef::isCC1pi unexpectedly."); } else { - QLOG(SAM, "Event: (" << ctr << ") " << (res ? "passed" : "failed") + NUIS_LOG(SAM, "Event: (" << ctr << ") " << (res ? "passed" : "failed") << " as expected."); } if (FailOnFail) { assert(res == fe_it->second); } } - QLOG(FIT, "* Testing: SignalDef::isNC1pi"); + NUIS_LOG(FIT, "* Testing: SignalDef::isNC1pi"); std::map isNC1pi_PassExpectations; isNC1pi_PassExpectations[&fe_CC0pi_1] = false; // numu CC0pi isNC1pi_PassExpectations[&fe_CC0pi_2] = false; // numu CC0pi (2p2h) isNC1pi_PassExpectations[&fe_CC0pi_3] = false; // numub CC0pi isCCINC_PassExpectations[&fe_CC0pi_4] = false; // numu CC0pi (RES) isNC1pi_PassExpectations[&fe_CC1pip_1] = false; // numu CC1pip (2p2h) isNC1pi_PassExpectations[&fe_CC1pim_1] = false; // numu CC1pim isNC1pi_PassExpectations[&fe_CC1pi0_1] = false; // numu CC1pi0 isNC1pi_PassExpectations[&fe_CC1pi0_2] = false; // nue CC1pi0 isNC1pi_PassExpectations[&fe_CCNpi_1] = false; // numu CC multi pi isNC1pi_PassExpectations[&fe_CCNpi_2] = false; // numu CC multi pi isNC1pi_PassExpectations[&fe_CCNpi_3] = false; // numu CC multi pi isNC1pi_PassExpectations[&fe_CCNpi_4] = false; // numu CC multi pi isCCINC_PassExpectations[&fe_CCCOH_1] = false; // numu CC COH pi isNC1pi_PassExpectations[&fe_NCel_1] = false; // numu NCEl isNC1pi_PassExpectations[&fe_NCel_2] = false; // nue NCEl isCCINC_PassExpectations[&fe_NC1pi_1] = true; // numu NC1pi isCCINC_PassExpectations[&fe_NCNpi_1] = false; // numu NC multi pi ctr = 0; for (std::map::iterator fe_it = isNC1pi_PassExpectations.begin(); fe_it != isNC1pi_PassExpectations.end(); ++fe_it, ++ctr) { bool res = SignalDef::isNC1pi(fe_it->first, 14, -211); if (res != fe_it->second) { - QERROR(FTL, "Event: (" << ctr << ")\n" << fe_it->first->ToString()); - QERROR(FTL, (res ? "passed" : "failed") + NUIS_ERR(FTL, "Event: (" << ctr << ")\n" << fe_it->first->ToString()); + NUIS_ERR(FTL, (res ? "passed" : "failed") << " SignalDef::isNC1pi unexpectedly."); } else { - QLOG(SAM, "Event: (" << ctr << ") " << (res ? "passed" : "failed") + NUIS_LOG(SAM, "Event: (" << ctr << ") " << (res ? "passed" : "failed") << " as expected."); } if (FailOnFail) { assert(res == fe_it->second); } } // SignalDef::isCCWithFS(&fe,14); } diff --git a/src/Tests/SmearceptanceTests.cxx b/src/Tests/SmearceptanceTests.cxx index f31ddca..bf8479f 100644 --- a/src/Tests/SmearceptanceTests.cxx +++ b/src/Tests/SmearceptanceTests.cxx @@ -1,73 +1,73 @@ #include "SmearceptanceUtils.h" #include "FitLogger.h" #include "TDecompSVD.h" #include #include int main(int argc, char const *argv[]) { double numerTol = 1.E2 * std::numeric_limits::epsilon(); // a = 10, b = 4 // x = 5a + 3b (= 62) // y = 6a - 2b (= 52) // A = (10,4) // M = ( (5, 3) // (6, -2) ) // X = (62,52) // A^T M = X TVectorD A(2); A[0] = 10; A[1] = 4; TVectorD X(2); X[0] = 62; X[1] = 52; TMatrixD M(2, 2); M[0][0] = 5; M[0][1] = 3; M[1][0] = 6; M[1][1] = -2; TVectorD ForwardSolve = M * A; bool similar = true; for (int i = 0; i < A.GetNrows(); ++i) { if (fabs(X[i] - ForwardSolve[i]) > numerTol) { - QERROR(FTL, "Element " << i << " was not multiplied as expected: " << X[i] + NUIS_ERR(FTL, "Element " << i << " was not multiplied as expected: " << X[i] << " != " << ForwardSolve[i] << " (Tol: " << fabs(X[i] - ForwardSolve[i]) << " > " << numerTol << ")"); similar = false; } } assert(similar); // TVectorD SVDSolve = SmearceptanceUtils::SVDInverseSolve(&A, &M); TDecompSVD svd(M); TMatrixD inv = svd.Invert(); TVectorD SVDSolve = inv * X; similar = true; for (int i = 0; i < A.GetNrows(); ++i) { if (fabs(A[i] - SVDSolve[i]) > numerTol) { - QERROR(FTL, "Element " << i << " was not solved as expected: " << A[i] + NUIS_ERR(FTL, "Element " << i << " was not solved as expected: " << A[i] << " != " << SVDSolve[i] << " (Tol: " << fabs(A[i] - SVDSolve[i]) << " > " << numerTol << ")"); similar = false; } } assert(similar); } diff --git a/src/Utils/BeamUtils.cxx b/src/Utils/BeamUtils.cxx index a6c0c55..0e996f6 100644 --- a/src/Utils/BeamUtils.cxx +++ b/src/Utils/BeamUtils.cxx @@ -1,327 +1,327 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "BeamUtils.h" std::vector BeamUtils::ParseSpeciesToIntVect(std::string spc) { // Split by comma std::vector splitspc = GeneralUtils::ParseToStr(spc, ","); std::vector convspc; // Run through hard coded list for (size_t i = 0; i < splitspc.size(); i++) { std::string type = splitspc[i]; if (!type.compare("electron")) convspc.push_back(11); else if (!type.compare("positron")) convspc.push_back(-11); else if (!type.compare("muon")) convspc.push_back(13); else if (!type.compare("antimuon")) convspc.push_back(-13); else if (!type.compare("nue")) convspc.push_back(12); else if (!type.compare("numu")) convspc.push_back(14); else if (!type.compare("antinue")) convspc.push_back(12); else if (!type.compare("antinumu")) convspc.push_back(14); else { convspc.push_back(GeneralUtils::StrToInt(type)); } } return convspc; } ///____________________________________________________________________________ void BeamUtils::ListFluxIDs() { // Keep in sync with ConvertTargetIDs - QLOG( + NUIS_LOG( FIT, "Possible Flux IDs: \n" << "\n MINERvA_fhc_numu : " << BeamUtils::ConvertFluxIDs("MINERvA_fhc_numu") << "\n MINERvA_fhc_numunumubar : " << BeamUtils::ConvertFluxIDs("MINERvA_fhc_numunumubar") << "\n MINERvA_fhc_nue : " << BeamUtils::ConvertFluxIDs("MINERvA_fhc_nue") << "\n MINERvA_fhc_nuenuebar : " << BeamUtils::ConvertFluxIDs("MINERvA_fhc_nuenuebar") << "\n MINERvA_fhc_all : " << BeamUtils::ConvertFluxIDs("MINERvA_fhc_all") << "\n MINERvA_rhc_numubar : " << BeamUtils::ConvertFluxIDs("MINERvA_rhc_numubar") << "\n MINERvA_rhc_numubarnumu : " << BeamUtils::ConvertFluxIDs("MINERvA_rhc_numubarnumu") << "\n MINERvA_rhc_nuebar : " << BeamUtils::ConvertFluxIDs("MINERvA_rhc_nuebar") << "\n MINERvA_rhc_nuebarnue : " << BeamUtils::ConvertFluxIDs("MINERvA_rhc_nuebarnue") << "\n MINERvA_rhc_all : " << BeamUtils::ConvertFluxIDs("MINERvA_rhc_all") << "\n MiniBooNE_fhc_numu : " << BeamUtils::ConvertFluxIDs("MiniBooNE_fhc_numu") << "\n MiniBooNE_fhc_numubar : " << BeamUtils::ConvertFluxIDs("MiniBooNE_fhc_numubar") << "\n MiniBooNE_fhc_numunumubar : " << BeamUtils::ConvertFluxIDs("MiniBooNE_fhc_numunumubar") << "\n MiniBooNE_fhc_all : " << BeamUtils::ConvertFluxIDs("MiniBooNE_fhc_all") << "\n MiniBooNE_rhc_numubar : " << BeamUtils::ConvertFluxIDs("MiniBooNE_rhc_numubar") << "\n MiniBooNE_rhc_numu : " << BeamUtils::ConvertFluxIDs("MiniBooNE_rhc_numu") << "\n MiniBooNE_rhc_numubarnumu : " << BeamUtils::ConvertFluxIDs("MiniBooNE_rhc_numubarnumu") << "\n MiniBooNE_rhc_all : " << BeamUtils::ConvertFluxIDs("MiniBooNE_rhc_all") << "\n ArgoNeut_fhc_numu : " << BeamUtils::ConvertFluxIDs("ArgoNeut_fhc_numu") << "\n ArgoNeut_rhc_numubar : " << BeamUtils::ConvertFluxIDs("ArgoNeut_rhc_numubar") << "\n K2K_fhc_numu : " << BeamUtils::ConvertFluxIDs("K2K_fhc_numu") << "\n ND280_fhc_numu : " << BeamUtils::ConvertFluxIDs("ND280_fhc_numu") << "\n ND280_fhc_numubar : " << BeamUtils::ConvertFluxIDs("ND280_fhc_numubar") << "\n ND280_fhc_numunumubar : " << BeamUtils::ConvertFluxIDs("ND280_fhc_numunumubar") << "\n ND280_fhc_nue : " << BeamUtils::ConvertFluxIDs("ND280_fhc_nue") << "\n ND280_fhc_nuebar : " << BeamUtils::ConvertFluxIDs("ND280_fhc_nuebar") << "\n ND280_fhc_nuenuebar : " << BeamUtils::ConvertFluxIDs("ND280_fhc_nuenuebar") << "\n ND280_fhc_all : " << BeamUtils::ConvertFluxIDs("ND280_fhc_all") << "\n ND280_rhc_numubar : " << BeamUtils::ConvertFluxIDs("ND280_rhc_numubar") << "\n ND280_rhc_numu : " << BeamUtils::ConvertFluxIDs("ND280_rhc_numu") << "\n ND280_rhc_numubarnumu : " << BeamUtils::ConvertFluxIDs("ND280_rhc_numubarnumu") << "\n ND280_rhc_nuebar : " << BeamUtils::ConvertFluxIDs("ND280_rhc_nuebar") << "\n ND280_rhc_nue : " << BeamUtils::ConvertFluxIDs("ND280_rhc_nue") << "\n ND280_rhc_nuebarnue : " << BeamUtils::ConvertFluxIDs("ND280_rhc_nuebarnue") << "\n ND280_rhc_all : " << BeamUtils::ConvertFluxIDs("ND280_rhc_all") << "\n SK_fhc_numu : " << BeamUtils::ConvertFluxIDs("SK_fhc_numu") << "\n SK_fhc_numubar : " << BeamUtils::ConvertFluxIDs("SK_fhc_numubar") << "\n SK_fhc_numunumubar : " << BeamUtils::ConvertFluxIDs("SK_fhc_numunumubar") << "\n SK_fhc_nue : " << BeamUtils::ConvertFluxIDs("SK_fhc_nue") << "\n SK_fhc_nuebar : " << BeamUtils::ConvertFluxIDs("SK_fhc_nuebar") << "\n SK_fhc_nuenuebar : " << BeamUtils::ConvertFluxIDs("SK_fhc_nuenuebar") << "\n SK_fhc_all : " << BeamUtils::ConvertFluxIDs("SK_fhc_all") << "\n SK_rhc_numubar : " << BeamUtils::ConvertFluxIDs("SK_rhc_numubar") << "\n SK_rhc_numu : " << BeamUtils::ConvertFluxIDs("SK_rhc_numu") << "\n SK_rhc_numubarnumu : " << BeamUtils::ConvertFluxIDs("SK_rhc_numubarnumu") << "\n SK_rhc_nuebar : " << BeamUtils::ConvertFluxIDs("SK_rhc_nuebar") << "\n SK_rhc_nue : " << BeamUtils::ConvertFluxIDs("SK_rhc_nue") << "\n SK_rhc_nuebarnue : " << BeamUtils::ConvertFluxIDs("SK_rhc_nuebarnue") << "\n SK_rhc_all : " << BeamUtils::ConvertFluxIDs("SK_rhc_all") << "\n ANL_fhc_numu : " << BeamUtils::ConvertFluxIDs("ANL_fhc_numu") << "\n BNL_fhc_numu : " << BeamUtils::ConvertFluxIDs("BNL_fhc_numu") << "\n BNL_fhc_numu_ALT1986 : " << BeamUtils::ConvertFluxIDs("BNL_fhc_numu_ALT1986") << "\n BNL_fhc_numu_ALT1981 : " << BeamUtils::ConvertFluxIDs("BNL_fhc_numu_ALT1981") << "\n BEBC_fhc_numu : " << BeamUtils::ConvertFluxIDs("BEBC_fhc_numu") << "\n FNAL_fhc_numu : " << BeamUtils::ConvertFluxIDs("FNAL_fhc_numu") << "\n FNAL_rhc_numub : " << BeamUtils::ConvertFluxIDs("FNAL_rhc_numub") << "\n GGM_fhc_numu : " << BeamUtils::ConvertFluxIDs("GGM_fhc_numu")); } //____________________________________________________________________________ std::string BeamUtils::ConvertFluxIDs(std::string id) { char *const var = getenv("NUISANCE"); if (!var) { std::cout << "Cannot find top level directory! Set the NUISANCE " "environmental variable" << std::endl; exit(-1); } std::string topnuisancedir = std::string(var); std::string fluxfolder = topnuisancedir + "/data/flux/"; std::string inputs = ""; if (!id.compare("MINERvA_fhc_numu")) inputs = "minerva_flux.root,numu_fhc[14]"; else if (!id.compare("MINERvA_fhc_numunumubar")) inputs = "minerva_flux.root,numu_fhc[14],numubar_fhc[-14]"; else if (!id.compare("MINERvA_fhc_nue")) inputs = "minerva_flux.root,nue_fhc[12]"; else if (!id.compare("MINERvA_fhc_nuenuebar")) inputs = "minerva_flux.root,nue_fhc[12],nuebar_fhc[-12]"; else if (!id.compare("MINERvA_fhc_all")) inputs = "minerva_flux.root,numu_fhc[14],numubar_fhc[-14],nue_fhc[12]," "nuebar_fhc[-12]"; else if (!id.compare("MINERvA_rhc_numubar")) inputs = "minerva_flux.root,numubar_rhc[-14]"; else if (!id.compare("MINERvA_rhc_numubarnumu")) inputs = "minerva_flux.root,numubar_rhc[-14],numu_rhc[14]"; else if (!id.compare("MINERvA_rhc_nuebar")) inputs = "minerva_flux.root,nuebar_rhc[-12]"; else if (!id.compare("MINERvA_rhc_nuebarnue")) inputs = "minerva_flux.root,nuebar_rhc[-12],nue_rhc[12]"; else if (!id.compare("MINERvA_rhc_all")) inputs = "minerva_flux.root,numu_rhc[14],numubar_rhc[-14],nue_rhc[12]," "nuebar_rhc[-12]"; else if (!id.compare("MiniBooNE_fhc_numu")) inputs = "MiniBooNE_numu_flux.root,numu_mb[14]"; else if (!id.compare("MiniBooNE_fhc_numubar")) inputs = "MiniBooNE_numu_flux.root,numub_mb[-14]"; else if (!id.compare("MiniBooNE_fhc_numunumubar")) inputs = "MiniBooNE_numu_flux.root,numu_mb[14],numub_mb[-14]"; else if (!id.compare("MiniBooNE_fhc_all")) inputs = "MiniBooNE_numu_flux.root,numu_mb[14],numub_mb[-14],nue_mb[12]," "nueb_mb[-12]"; else if (!id.compare("MiniBooNE_rhc_numubar")) inputs = "MiniBooNE_numubar_flux.root,numub_mb[-14]"; else if (!id.compare("MiniBooNE_rhc_numu")) inputs = "MiniBooNE_numubar_flux.root,numu_mb[14]"; else if (!id.compare("MiniBooNE_rhc_numubarnumu")) inputs = "MiniBooNE_numubar_flux.root,numub_mb[-14],numu_mb[14]"; else if (!id.compare("MiniBooNE_rhc_all")) inputs = "MiniBooNE_numubar_flux.root,numub_mb[-14],numu_mb[14],nueb_mb[-" "12],nue_mb[12]"; else if (!id.compare("ArgoNeut_fhc_numu")) inputs = "ArgoNeut_numu_flux.root,numu[14]"; else if (!id.compare("ArgoNeut_rhc_numub")) inputs = "ArgoNeut_numub_flux,numub[-14]"; else if (!id.compare("K2K_fhc_numu")) inputs = "K2K_flux.root,numu_flux[14]"; else if (!id.compare("ND280_fhc_numu")) inputs = "t2kflux_2016_plus250kA.root,enu_nd280_numu[14]"; else if (!id.compare("ND280_fhc_numubar")) inputs = "t2kflux_2016_plus250kA.root,enu_nd280_numub[-14]"; else if (!id.compare("ND280_fhc_numunumubar")) inputs = "t2kflux_2016_plus250kA.root,enu_nd280_numu[14],enu_nd280_numub[-14]"; else if (!id.compare("ND280_fhc_nue")) inputs = "t2kflux_2016_plus250kA.root,enu_nd280_nue[12]"; else if (!id.compare("ND280_fhc_nuebar")) inputs = "t2kflux_2016_plus250kA.root,enu_nd280_nueb[-12]"; else if (!id.compare("ND280_fhc_nuenuebar")) inputs = "t2kflux_2016_plus250kA.root,enu_nd280_nue[12],enu_nd280_nueb[-12]"; else if (!id.compare("ND280_fhc_all")) inputs = "t2kflux_2016_plus250kA.root,enu_nd280_numu[14],enu_nd280_numub[-" "14],enu_nd280_nue[12],enu_nd280_nueb[-12]"; else if (!id.compare("ND280_rhc_numubar")) inputs = "t2kflux_2016_minus250kA.root,enu_nd280_numub[-14]"; else if (!id.compare("ND280_rhc_numu")) inputs = "t2kflux_2016_minus250kA.root,enu_nd280_numu[14]"; else if (!id.compare("ND280_rhc_numubarnumu")) inputs = "t2kflux_2016_minus250kA.root,enu_nd280_numub[-14],enu_nd280_numu[14]"; else if (!id.compare("ND280_rhc_nuebar")) inputs = "t2kflux_2016_minus250kA.root,enu_nd280_nueb[-12]"; else if (!id.compare("ND280_rhc_nue")) inputs = "t2kflux_2016_minus250kA.root,enu_nd280_nue[12]"; else if (!id.compare("ND280_rhc_nuebarnue")) inputs = "t2kflux_2016_minus250kA.root,enu_nd280_nueb[-12],enu_nd280_nue[12]"; else if (!id.compare("ND280_rhc_all")) inputs = "t2kflux_2016_minus250kA.root,enu_nd280_numub[-14],enu_nd280_numu[" "14],enu_nd280_nueb[-12],enu_nd280_nue[12]"; else if (!id.compare("SK_fhc_numu")) inputs = "t2kflux_2016_plus250kA.root,enu_sk_numu[14]"; else if (!id.compare("SK_fhc_numubar")) inputs = "t2kflux_2016_plus250kA.root,enu_sk_numub[-14]"; else if (!id.compare("SK_fhc_numunumubar")) inputs = "t2kflux_2016_plus250kA.root,enu_sk_numu[14],enu_sk_numub[-14]"; else if (!id.compare("SK_fhc_nue")) inputs = "t2kflux_2016_plus250kA.root,enu_sk_nue[12]"; else if (!id.compare("SK_fhc_nuebar")) inputs = "t2kflux_2016_plus250kA.root,enu_sk_nueb[-12]"; else if (!id.compare("SK_fhc_nuenuebar")) inputs = "t2kflux_2016_plus250kA.root,enu_sk_nue[12],enu_sk_nueb[-12]"; else if (!id.compare("SK_fhc_all")) inputs = "t2kflux_2016_plus250kA.root,enu_sk_numu[14],enu_sk_numub[-14]," "enu_sk_nue[12],enu_sk_nueb[-12]"; else if (!id.compare("SK_rhc_numubar")) inputs = "t2kflux_2016_minus250kA.root,enu_sk_numub[-14]"; else if (!id.compare("SK_rhc_numu")) inputs = "t2kflux_2016_minus250kA.root,enu_sk_numu[14]"; else if (!id.compare("SK_rhc_numubarnumu")) inputs = "t2kflux_2016_minus250kA.root,enu_sk_numub[-14],enu_sk_numu[14]"; else if (!id.compare("SK_rhc_nuebar")) inputs = "t2kflux_2016_minus250kA.root,enu_sk_nueb[-12]"; else if (!id.compare("SK_rhc_nue")) inputs = "t2kflux_2016_minus250kA.root,enu_sk_nue[12]"; else if (!id.compare("SK_rhc_nuebarnue")) inputs = "t2kflux_2016_minus250kA.root,enu_sk_nueb[-12],enu_sk_nue[12]"; else if (!id.compare("SK_rhc_all")) inputs = "t2kflux_2016_minus250kA.root,enu_sk_numub[-14],enu_sk_numu[14]," "enu_sk_nueb[-12],enu_nd280_nue[12]"; else if (!id.compare("ANL_fhc_numu")) inputs = "ANL_1977_2horn_rescan.root, numu_flux[14]"; else if (!id.compare("BNL_fhc_numu")) inputs = "BNL_NuInt02_rescan.root, numu_flux[14]"; else if (!id.compare("BNL_fhc_numu_ALT1986")) inputs = "BNL_1986_flux - ALTERNATIVE.root, numu_flux[14]"; else if (!id.compare("BNL_fhc_numu_ALT1981")) inputs = "BNL_CCQE_1981_rescan - ALTERNATIVE.root, numu_flux[14]"; else if (!id.compare("BEBC_fhc_numu")) inputs = "BEBC_Wachsmuth_numu_table.root, numu_flux[14]"; else if (!id.compare("FNAL_fhc_numu")) inputs = "FNAL_CCinc_1982_nu_MCadj.root, numu_flux[14]"; else if (!id.compare("FNAL_rhc_numub")) inputs = "FNAL_coh_1993_anu.root, numu_flux[-14]"; else if (!id.compare("GGM_fhc_numu")) inputs = "GGM_nu_flux_1979_rescan.root, numu_flux[14]"; else return ""; return fluxfolder + inputs; }; diff --git a/src/Utils/GeneralUtils.cxx b/src/Utils/GeneralUtils.cxx index bb5399d..9b32531 100644 --- a/src/Utils/GeneralUtils.cxx +++ b/src/Utils/GeneralUtils.cxx @@ -1,195 +1,195 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "GeneralUtils.h" std::string GeneralUtils::BoolToStr(bool val) { std::ostringstream ss; ss << val; return ss.str(); } std::string GeneralUtils::IntToStr(int val) { std::ostringstream ss; ss << val; return ss.str(); }; std::string GeneralUtils::DblToStr(double val) { std::ostringstream ss; ss << val; return ss.str(); }; std::vector GeneralUtils::LoadCharToVectStr(int argc, char* argv[]) { std::vector vect; for (int i = 1; i < argc; i++) { vect.push_back(std::string(argv[i])); } return vect; } std::vector GeneralUtils::ParseToStr(std::string str, const char* del) { std::istringstream stream(str); std::string temp_string; std::vector vals; while (std::getline(stream >> std::ws, temp_string, *del)) { if (temp_string.empty()) continue; vals.push_back(temp_string); } return vals; } std::vector GeneralUtils::ParseToDbl(std::string str, const char* del) { std::istringstream stream(str); std::string temp_string; std::vector vals; while (std::getline(stream >> std::ws, temp_string, *del)) { if (temp_string.empty()) continue; std::istringstream stream(temp_string); double entry; stream >> entry; vals.push_back(entry); } return vals; } std::vector GeneralUtils::ParseToInt(std::string str, const char* del) { std::istringstream stream(str); std::string temp_string; std::vector vals; while (std::getline(stream >> std::ws, temp_string, *del)) { if (temp_string.empty()) continue; std::istringstream stream(temp_string); int entry; stream >> entry; vals.push_back(entry); } return vals; } double GeneralUtils::StrToDbl(std::string str) { std::istringstream stream(str); double val; stream >> val; return val; } int GeneralUtils::StrToInt(std::string str) { std::istringstream stream(str); int val; stream >> val; return val; } bool GeneralUtils::StrToBool(std::string str) { // convert result to lower case for (uint i = 0; i < str.size(); i++) str[i] = std::tolower(str[i]); // Test for true/false if (!str.compare("false")) return false; else if (!str.compare("true")) return true; if (str.empty()) return false; // Push into bool std::istringstream stream(str); bool val; stream >> val; return val; } std::vector GeneralUtils::ParseFileToStr(std::string str, const char* del) { std::vector linevect; std::string line; std::ifstream read; read.open(str.c_str()); if (!read.is_open()) { - QERROR(FTL, "Cannot open file " << str << " in ParseFileToStr"); + NUIS_ERR(FTL, "Cannot open file " << str << " in ParseFileToStr"); throw; } while (std::getline(read >> std::ws, line, *del)) { linevect.push_back(line); } read.close(); return linevect; } std::string GeneralUtils::GetTopLevelDir() { static bool first = true; static std::string topLevelVarVal; if (first) { char* const var = getenv("NUISANCE"); if (!var) { - QERROR(FTL, + NUIS_ERR(FTL, "Cannot find top level directory! Set the NUISANCE environmental " "variable"); throw; } topLevelVarVal = std::string(var); first = false; } return topLevelVarVal; } std::string GeneralUtils::ReplaceAll(std::string const& inp, std::string const& from, std::string const& to) { std::stringstream ss(""); size_t nextOccurence = 0; size_t prevOccurence = 0; bool AtEnd = false; while (!AtEnd) { nextOccurence = inp.find(from, prevOccurence); if (nextOccurence == std::string::npos) { if (prevOccurence == inp.length()) { break; } AtEnd = true; } if ((nextOccurence != prevOccurence) || (nextOccurence == 0)) { ss << inp.substr(prevOccurence, (nextOccurence - prevOccurence)); if (!AtEnd) { ss << to; } } prevOccurence = nextOccurence + from.size(); } return ss.str(); } diff --git a/src/Utils/ParserUtils.cxx b/src/Utils/ParserUtils.cxx index cee0f37..4c4c770 100644 --- a/src/Utils/ParserUtils.cxx +++ b/src/Utils/ParserUtils.cxx @@ -1,190 +1,190 @@ #include "ParserUtils.h" void ParserUtils::CheckBadArguments(std::vector args) { // Any argument that has not already been erased is considered bad. for (size_t i = 0; i < args.size(); i++) { if (args[i][0] == '-') { - QTHROW("Unknown command line option given : \'" << args[i] << "\'"); + NUIS_ABORT("Unknown command line option given : \'" << args[i] << "\'"); } } } void ParserUtils::ParseArgument(std::vector& args, std::string opt, int& val, bool required, bool duplicates) { int indexfound = -1; for (size_t i = 0; i < args.size() - 1; i++) { if (args.empty()) break; if (!(args[i]).compare(opt.c_str())) { // Found it if (indexfound != -1 and !duplicates) { - QTHROW("Duplicate arguments given with : " << opt << std::endl + NUIS_ABORT("Duplicate arguments given with : " << opt << std::endl << "1 -> " << opt << " " << val << std::endl << "2 -> " << opt << " " << args[i + 1]); } // Get Value val = GeneralUtils::StrToInt(args[i + 1]); indexfound = i; } } // if not found if (indexfound == -1 and required) { - QTHROW("No flag " << opt << " found in commands." + NUIS_ABORT("No flag " << opt << " found in commands." << "This is required!"); } // Remove from vector if (indexfound != -1) { args.erase(args.begin() + indexfound); args.erase(args.begin() + indexfound); } } void ParserUtils::ParseArgument(std::vector& args, std::string opt, std::string& val, bool required, bool duplicates) { int indexfound = -1; for (size_t i = 0; i < args.size() - 1; i++) { if (args.empty()) break; if (!(args[i]).compare(opt.c_str())) { // Found it if (indexfound != -1 and !duplicates) { - QTHROW("Duplicate arguments given with : " << opt << std::endl + NUIS_ABORT("Duplicate arguments given with : " << opt << std::endl << "1 -> " << opt << " " << val << std::endl << "2 -> " << opt << " " << args[i + 1]); } // Get Value val = (args[i + 1]); indexfound = i; } } // if not found if (indexfound == -1 and required) { - QTHROW("No flag " << opt << " found in commands." + NUIS_ABORT("No flag " << opt << " found in commands." << "This is required!"); } // Remove from vector if (indexfound != -1) { args.erase(args.begin() + indexfound); args.erase(args.begin() + indexfound); } } void ParserUtils::ParseArgument(std::vector& args, std::string opt, std::vector& val, bool required, bool duplicates) { while (std::find(args.begin(), args.end(), opt) != args.end()) { std::string temp = ""; ParseArgument(args, opt, temp, required); val.push_back(temp); } if (required and val.empty()) { - QTHROW("No flag " << opt << " found in commands." + NUIS_ABORT("No flag " << opt << " found in commands." << "This is required!"); } } void ParserUtils::ParseSplitArgument(std::vector& args, std::string opt, std::string& val, bool required, bool duplicates) { int indexfound = -1; std::string splitline = ""; int linecount = 0; for (size_t i = 0; i < args.size(); i++) { if (args.empty()) break; // Start saving if (!(args[i]).compare(opt.c_str())) { indexfound = i; splitline = ""; continue; } if (indexfound != -1) { if (args[i][0] == '-') { break; } splitline += args[i] + " "; linecount++; } } // Remove from vector if (indexfound != -1) { for (int i = indexfound; i <= indexfound + linecount; i++) { args.erase(args.begin() + i); } val = splitline; } } void ParserUtils::ParseSplitArgument(std::vector& args, std::string opt, std::vector& val, bool required, bool duplicates) { //std::cout << "Starting split argument" << std::endl; while (std::find(args.begin(), args.end(), opt) != args.end()) { std::string temp = ""; ParseArgument(args, opt, temp, required, duplicates); val.push_back(temp); } if (required and val.empty()) { - QTHROW( "No flag " << opt << " found in commands." + NUIS_ABORT( "No flag " << opt << " found in commands." << "This is required!"); throw; } } // void ParserUtils::ParseRemainingXML(std::vector& args, std::vector& cmds) { // // Make one big string again and parse it by '' // std::string temp = ""; // for (size_t i = 0; i < args.size(); i++) { // temp += args[i] + " "; // } // return; // } void ParserUtils::ParseCounter(std::vector& args, std::string opt, int& count) { std::vector indexlist; for (size_t i = 0; i < args.size(); i++) { if (!(args[i]).compare( "+" + opt)) { count++; indexlist.push_back(i); } else if (!(args[i]).compare( "-" + opt)) { count--; indexlist.push_back(i); } } for (size_t i = 0; i < indexlist.size(); i++) { args.erase(args.begin() + indexlist[i]); } } diff --git a/src/Utils/PhysConst.h b/src/Utils/PhysConst.h index 936c4ca..f1841b4 100644 --- a/src/Utils/PhysConst.h +++ b/src/Utils/PhysConst.h @@ -1,112 +1,112 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #ifndef PHYSCONST_H_SEEN #define PHYSCONST_H_SEEN #include #include #include #include #include #include #include #include #include #include #include #include #include "FitLogger.h" /// namespace to contain all physical constants used by NUISANCE namespace PhysConst { const double mass_proton = 0.93827203; // Proton mass in GeV const double mass_neutron = 0.93956536; // Neutron mass in GeV const double mass_nucleon = (mass_proton + mass_neutron) / 2.; const double mass_proton_kg = 1.6727E-27; // Proton mass in kg const double mass_neutron_kg = 1.6750E-27; // Neutron mass in kg const double mass_nucleon_kg = (mass_proton_kg + mass_neutron_kg) / 2.; const double mass_delta = 1.232; // Delta mass in GeV const double mass_muon = 0.10565837; // Muon mass in GeV const double mass_electron = 0.000510998928; // Electron mass in GeV const double mass_cpi = 0.13957; // charged pion mass in GeV const double mass_pi0 = 0.13498; // neutral pion mass in GeV const double mass_cK = 0.493677; // charged kaon mass in GeV const double mass_K0 = 0.497611; // neutral kaon mass in GeV inline double GetMass(int pdg) { switch (abs(pdg)) { case 11: return mass_electron; case 13: return mass_muon; case 111: return mass_pi0; case 211: return mass_cpi; case 321: return mass_cK; case 311: case 310: case 130: return mass_K0; case 2112: return mass_neutron; case 2212: return mass_proton; default: { - QERROR(WRN, "Attempted to get mass for PDG: " + NUIS_ERR(WRN, "Attempted to get mass for PDG: " << pdg << ", but it is not catered for. Please add it to " "src/Utils/PhysConst.h"); return -1; } } } const double mass_MeV = 1000; // MeV/GeV const int pdg_neutrinos[] = {12, -12, 14, -14 /*, 16, -16*/}; const int pdg_muons[] = {13, -13}; const int pdg_leptons[] = {11, -11, 13, -13, 15, -15}; const int pdg_all_leptons[] = {11, -11, 13, -13, 15, -15, 12, -12, 14, -14, 16, -16}; const int pdg_pions[] = {211, -211, 111}; const int pdg_charged_pions[] = {211, -211}; const int pdg_strangemesons[] = { 130, 310, 311, 321, 9000311, 9000321, 10311, 10321, 100311, 100321, 9010311, 9010321, 9020311, 9020321, 313, 323, 10313, 10323, 20313, 20323, 100313, 100323, 9000313, 9000323, 30313, 30323, 315, 325, 9000315, 9000325, 10315, 10325, 20315, 20325, 9010315, 9010325, 9020315, 9020325, 317, 327, 9010317, 9010327}; // Just *-1 to cover possibility const int pdg_kplus = 321; const int pdg_antistrangemesons[] = { -130, -310, -311, -321, -9000311, -9000321, -10311, -10321, -100311, -100321, -9010311, -9010321, -9020311, -9020321, -313, -323, -10313, -10323, -20313, -20323, -100313, -100323, -9000313, -9000323, -30313, -30323, -315, -325, -9000315, -9000325, -10315, -10325, -20315, -20325, -9010315, -9010325, -9020315, -9020325, -317, -327, -9010317, -9010327}; } /*! @} */ #endif diff --git a/src/Utils/PlotUtils.cxx b/src/Utils/PlotUtils.cxx index acf979b..207551a 100644 --- a/src/Utils/PlotUtils.cxx +++ b/src/Utils/PlotUtils.cxx @@ -1,1195 +1,1195 @@ // Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret /******************************************************************************* * This file is part of NUISANCE. * * NUISANCE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NUISANCE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NUISANCE. If not, see . *******************************************************************************/ #include "PlotUtils.h" #include "FitEvent.h" #include "StatUtils.h" // MOVE TO MB UTILS! // This function is intended to be modified to enforce a consistent masking for // all models. TH2D *PlotUtils::SetMaskHist(std::string type, TH2D *data) { TH2D *fMaskHist = (TH2D *)data->Clone("fMaskHist"); for (int xBin = 0; xBin < fMaskHist->GetNbinsX(); ++xBin) { for (int yBin = 0; yBin < fMaskHist->GetNbinsY(); ++yBin) { if (data->GetBinContent(xBin + 1, yBin + 1) == 0) fMaskHist->SetBinContent(xBin + 1, yBin + 1, 0); else fMaskHist->SetBinContent(xBin + 1, yBin + 1, 0.5); if (!type.compare("MB_numu_2D")) { if (yBin == 19 && xBin < 8) fMaskHist->SetBinContent(xBin + 1, yBin + 1, 1.0); } else { if (yBin == 19 && xBin < 11) fMaskHist->SetBinContent(xBin + 1, yBin + 1, 1.0); } if (yBin == 18 && xBin < 3) fMaskHist->SetBinContent(xBin + 1, yBin + 1, 1.0); if (yBin == 17 && xBin < 2) fMaskHist->SetBinContent(xBin + 1, yBin + 1, 1.0); if (yBin == 16 && xBin < 1) fMaskHist->SetBinContent(xBin + 1, yBin + 1, 1.0); } } return fMaskHist; }; // MOVE TO GENERAL UTILS? bool PlotUtils::CheckObjectWithName(TFile *inFile, std::string substring) { TIter nextkey(inFile->GetListOfKeys()); TKey *key; while ((key = (TKey *)nextkey())) { std::string test(key->GetName()); if (test.find(substring) != std::string::npos) return true; } return false; }; // MOVE TO GENERAL UTILS? std::string PlotUtils::GetObjectWithName(TFile *inFile, std::string substring) { TIter nextkey(inFile->GetListOfKeys()); TKey *key; std::string output = ""; while ((key = (TKey *)nextkey())) { std::string test(key->GetName()); if (test.find(substring) != std::string::npos) output = test; } return output; }; void PlotUtils::CreateNeutModeArray(TH1 *hist, TH1 *neutarray[]) { for (int i = 0; i < 60; i++) { neutarray[i] = (TH1 *)hist->Clone(Form("%s_NMODE_%i", hist->GetName(), i)); } return; }; void PlotUtils::DeleteNeutModeArray(TH1 *neutarray[]) { for (int i = 0; i < 60; i++) { delete neutarray[i]; } return; }; void PlotUtils::FillNeutModeArray(TH1D *hist[], int mode, double xval, double weight) { if (abs(mode) > 60) return; hist[abs(mode)]->Fill(xval, weight); return; }; void PlotUtils::FillNeutModeArray(TH2D *hist[], int mode, double xval, double yval, double weight) { if (abs(mode) > 60) return; hist[abs(mode)]->Fill(xval, yval, weight); return; }; THStack PlotUtils::GetNeutModeStack(std::string title, TH1 *ModeStack[], int option) { (void)option; THStack allmodes = THStack(title.c_str(), title.c_str()); for (int i = 0; i < 60; i++) { allmodes.Add(ModeStack[i]); } // Credit to Clarence for copying all this out. // CC ModeStack[1]->SetTitle("CCQE"); ModeStack[1]->SetFillColor(kBlue); // ModeStack[1]->SetFillStyle(3444); ModeStack[1]->SetLineColor(kBlue); ModeStack[2]->SetTitle("2p/2h Nieves"); ModeStack[2]->SetFillColor(kRed); // ModeStack[2]->SetFillStyle(3344); ModeStack[2]->SetLineColor(kRed); // ModeStack[11]->SetTitle("#it{#nu + p #rightarrow l^{-} + p + #pi^{+}}"); ModeStack[11]->SetTitle("CC1#pi^{+} on p"); ModeStack[11]->SetFillColor(kGreen); // ModeStack[11]->SetFillStyle(3004); ModeStack[11]->SetLineColor(kGreen); // ModeStack[12]->SetTitle("#it{#nu + n #rightarrow l^{-} + p + #pi^{0}}"); ModeStack[12]->SetTitle("CC1#pi^{0} on n"); ModeStack[12]->SetFillColor(kGreen + 3); // ModeStack[12]->SetFillStyle(3005); ModeStack[12]->SetLineColor(kGreen); // ModeStack[13]->SetTitle("#it{#nu + n #rightarrow l^{-} + n + #pi^{+}}"); ModeStack[13]->SetTitle("CC1#pi^{+} on n"); ModeStack[13]->SetFillColor(kGreen - 2); // ModeStack[13]->SetFillStyle(3004); ModeStack[13]->SetLineColor(kGreen); ModeStack[16]->SetTitle("CC coherent"); ModeStack[16]->SetFillColor(kBlue); // ModeStack[16]->SetFillStyle(3644); ModeStack[16]->SetLineColor(kBlue); // ModeStack[17]->SetTitle("#it{#nu + n #rightarrow l^{-} + p + #gamma}"); ModeStack[17]->SetTitle("CC1#gamma"); ModeStack[17]->SetFillColor(kMagenta); // ModeStack[17]->SetFillStyle(3001); ModeStack[17]->SetLineColor(kMagenta); ModeStack[21]->SetTitle("Multi #pi (1.3 < W < 2.0)"); ModeStack[21]->SetFillColor(kYellow); // ModeStack[21]->SetFillStyle(3005); ModeStack[21]->SetLineColor(kYellow); // ModeStack[22]->SetTitle("#it{#nu + n #rightarrow l^{-} + p + #eta^{0}}"); ModeStack[22]->SetTitle("CC1#eta^{0} on n"); ModeStack[22]->SetFillColor(kYellow - 2); // ModeStack[22]->SetFillStyle(3013); ModeStack[22]->SetLineColor(kYellow - 2); // ModeStack[23]->SetTitle("#it{#nu + n #rightarrow l^{-} + #Lambda + // K^{+}}"); ModeStack[23]->SetTitle("CC1#Labda1K^{+}"); ModeStack[23]->SetFillColor(kYellow - 6); // ModeStack[23]->SetFillStyle(3013); ModeStack[23]->SetLineColor(kYellow - 6); ModeStack[26]->SetTitle("DIS (W > 2.0)"); ModeStack[26]->SetFillColor(kRed); // ModeStack[26]->SetFillStyle(3006); ModeStack[26]->SetLineColor(kRed); // NC // ModeStack[31]->SetTitle("#it{#nu + n #rightarrow #nu + n + #pi^{0}}"); ModeStack[31]->SetTitle("NC1#pi^{0} on n"); ModeStack[31]->SetFillColor(kBlue); // ModeStack[31]->SetFillStyle(3004); ModeStack[31]->SetLineColor(kBlue); // ModeStack[32]->SetTitle("#it{#nu + p #rightarrow #nu + p + #pi^{0}}"); ModeStack[32]->SetTitle("NC1#pi^{0} on p"); ModeStack[32]->SetFillColor(kBlue + 3); // ModeStack[32]->SetFillStyle(3004); ModeStack[32]->SetLineColor(kBlue + 3); // ModeStack[33]->SetTitle("#it{#nu + n #rightarrow #nu + p + #pi^{-}}"); ModeStack[33]->SetTitle("NC1#pi^{-} on n"); ModeStack[33]->SetFillColor(kBlue - 2); // ModeStack[33]->SetFillStyle(3005); ModeStack[33]->SetLineColor(kBlue - 2); // ModeStack[34]->SetTitle("#it{#nu + p #rightarrow #nu + n + #pi^{+}}"); ModeStack[34]->SetTitle("NC1#pi^{+} on p"); ModeStack[34]->SetFillColor(kBlue - 8); // ModeStack[34]->SetFillStyle(3005); ModeStack[34]->SetLineColor(kBlue - 8); ModeStack[36]->SetTitle("NC Coherent"); ModeStack[36]->SetFillColor(kBlue + 8); // ModeStack[36]->SetFillStyle(3644); ModeStack[36]->SetLineColor(kBlue + 8); // ModeStack[38]->SetTitle("#it{#nu + n #rightarrow #nu + n + #gamma}"); ModeStack[38]->SetTitle("NC1#gamma on n"); ModeStack[38]->SetFillColor(kMagenta); // ModeStack[38]->SetFillStyle(3001); ModeStack[38]->SetLineColor(kMagenta); // ModeStack[39]->SetTitle("#it{#nu + p #rightarrow #nu + p + #gamma}"); ModeStack[39]->SetTitle("NC1#gamma on p"); ModeStack[39]->SetFillColor(kMagenta - 10); // ModeStack[39]->SetFillStyle(3001); ModeStack[39]->SetLineColor(kMagenta - 10); ModeStack[41]->SetTitle("Multi #pi (1.3 < W < 2.0)"); ModeStack[41]->SetFillColor(kBlue - 10); // ModeStack[41]->SetFillStyle(3005); ModeStack[41]->SetLineColor(kBlue - 10); // ModeStack[42]->SetTitle("#it{#nu + n #rightarrow #nu + n + #eta^{0}}"); ModeStack[42]->SetTitle("NC1#eta^{0} on n"); ModeStack[42]->SetFillColor(kYellow - 2); // ModeStack[42]->SetFillStyle(3013); ModeStack[42]->SetLineColor(kYellow - 2); // ModeStack[43]->SetTitle("#it{#nu + p #rightarrow #nu + p + #eta^{0}}"); ModeStack[43]->SetTitle("NC1#eta^{0} on p"); ModeStack[43]->SetFillColor(kYellow - 4); // ModeStack[43]->SetFillStyle(3013); ModeStack[43]->SetLineColor(kYellow - 4); // ModeStack[44]->SetTitle("#it{#nu + n #rightarrow #nu + #Lambda + K^{0}}"); ModeStack[44]->SetTitle("NC1#Lambda1K^{0} on n"); ModeStack[44]->SetFillColor(kYellow - 6); // ModeStack[44]->SetFillStyle(3014); ModeStack[44]->SetLineColor(kYellow - 6); // ModeStack[45]->SetTitle("#it{#nu + p #rightarrow #nu + #Lambda + K^{+}}"); ModeStack[45]->SetTitle("NC1#Lambda1K^{+}"); ModeStack[45]->SetFillColor(kYellow - 10); // ModeStack[45]->SetFillStyle(3014); ModeStack[45]->SetLineColor(kYellow - 10); ModeStack[46]->SetTitle("DIS (W > 2.0)"); ModeStack[46]->SetFillColor(kRed); // ModeStack[46]->SetFillStyle(3006); ModeStack[46]->SetLineColor(kRed); // ModeStack[51]->SetTitle("#it{#nu + p #rightarrow #nu + p}"); ModeStack[51]->SetTitle("NC on p"); ModeStack[51]->SetFillColor(kBlack); // ModeStack[51]->SetFillStyle(3444); ModeStack[51]->SetLineColor(kBlack); // ModeStack[52]->SetTitle("#it{#nu + n #rightarrow #nu + n}"); ModeStack[52]->SetTitle("NC on n"); ModeStack[52]->SetFillColor(kGray); // ModeStack[52]->SetFillStyle(3444); ModeStack[52]->SetLineColor(kGray); return allmodes; }; TLegend PlotUtils::GenerateStackLegend(THStack stack, int xlow, int ylow, int xhigh, int yhigh) { TLegend leg = TLegend(xlow, ylow, xhigh, yhigh); TObjArray *histarray = stack.GetStack(); int nhist = histarray->GetEntries(); for (int i = 0; i < nhist; i++) { TH1 *hist = (TH1 *)(histarray->At(i)); leg.AddEntry((hist), ((TH1 *)histarray->At(i))->GetTitle(), "fl"); } leg.SetName(Form("%s_LEG", stack.GetName())); return leg; }; void PlotUtils::ScaleNeutModeArray(TH1 *hist[], double factor, std::string option) { for (int i = 0; i < 60; i++) { if (hist[i]) hist[i]->Scale(factor, option.c_str()); } return; }; void PlotUtils::ResetNeutModeArray(TH1 *hist[]) { for (int i = 0; i < 60; i++) { if (hist[i]) hist[i]->Reset(); } return; }; //******************************************************************** // This assumes the Enu axis is the x axis, as is the case for MiniBooNE 2D // distributions void PlotUtils::FluxUnfoldedScaling(TH2D *fMCHist, TH1D *fhist, TH1D *ehist, double scalefactor) { //******************************************************************** // Make clones to avoid changing stuff TH1D *eventhist = (TH1D *)ehist->Clone(); TH1D *fFluxHist = (TH1D *)fhist->Clone(); // Undo width integral in SF fMCHist->Scale(scalefactor / eventhist->Integral(1, eventhist->GetNbinsX() + 1, "width")); // Standardise The Flux eventhist->Scale(1.0 / fFluxHist->Integral()); fFluxHist->Scale(1.0 / fFluxHist->Integral()); // Do interpolation for 2D plots? // fFluxHist = PlotUtils::InterpolateFineHistogram(fFluxHist,100,"width"); // eventhist = PlotUtils::InterpolateFineHistogram(eventhist,100,"width"); // eventhist->Scale(1.0/fFluxHist->Integral()); // fFluxHist->Scale(1.0/fFluxHist->Integral()); // Scale fMCHist by eventhist integral fMCHist->Scale(eventhist->Integral(1, eventhist->GetNbinsX() + 1)); // Find which axis is the Enu axis bool EnuOnXaxis = false; std::string xaxis = fMCHist->GetXaxis()->GetTitle(); if (xaxis.find("E") != std::string::npos && xaxis.find("nu") != std::string::npos) EnuOnXaxis = true; std::string yaxis = fMCHist->GetYaxis()->GetTitle(); if (yaxis.find("E") != std::string::npos && xaxis.find("nu") != std::string::npos) { // First check that xaxis didn't also find Enu if (EnuOnXaxis) { - QERROR(FTL, fMCHist->GetTitle() << " error:"); - QERROR(FTL, "Found Enu in xaxis title: " << xaxis); - QERROR(FTL, "AND"); - QERROR(FTL, "Found Enu in yaxis title: " << yaxis); - QTHROW("Enu on x and Enu on y flux unfolded scaling isn't " + NUIS_ERR(FTL, fMCHist->GetTitle() << " error:"); + NUIS_ERR(FTL, "Found Enu in xaxis title: " << xaxis); + NUIS_ERR(FTL, "AND"); + NUIS_ERR(FTL, "Found Enu in yaxis title: " << yaxis); + NUIS_ABORT("Enu on x and Enu on y flux unfolded scaling isn't " "implemented, please modify " << __FILE__ << ":" << __LINE__); } EnuOnXaxis = false; } // Now Get a flux PDF assuming X axis is Enu TH1D *pdfflux = NULL; // If xaxis is Enu if (EnuOnXaxis) pdfflux = (TH1D *)fMCHist->ProjectionX()->Clone(); // If yaxis is Enu else pdfflux = (TH1D *)fMCHist->ProjectionY()->Clone(); // pdfflux->Write( (std::string(fMCHist->GetName()) + "_PROJX").c_str()); pdfflux->Reset(); // Awful MiniBooNE Check for the time being // Needed because the flux is in GeV whereas the measurement is in MeV bool ismb = std::string(fMCHist->GetName()).find("MiniBooNE") != std::string::npos; for (int i = 0; i < pdfflux->GetNbinsX(); i++) { double Ml = pdfflux->GetXaxis()->GetBinLowEdge(i + 1); double Mh = pdfflux->GetXaxis()->GetBinLowEdge(i + 2); // double Mc = pdfflux->GetXaxis()->GetBinCenter(i+1); // double Mw = pdfflux->GetBinWidth(i+1); double fluxint = 0.0; // Scaling to match flux for MB if (ismb) { Ml /= 1.E3; Mh /= 1.E3; // Mc /= 1.E3; // Mw /= 1.E3; } for (int j = 0; j < fFluxHist->GetNbinsX(); j++) { // double Fc = fFluxHist->GetXaxis()->GetBinCenter(j+1); double Fl = fFluxHist->GetXaxis()->GetBinLowEdge(j + 1); double Fh = fFluxHist->GetXaxis()->GetBinLowEdge(j + 2); double Fe = fFluxHist->GetBinContent(j + 1); double Fw = fFluxHist->GetXaxis()->GetBinWidth(j + 1); if (Fl >= Ml and Fh <= Mh) { fluxint += Fe; } else if (Fl < Ml and Fl < Mh and Fh > Ml and Fh < Mh) { fluxint += Fe * (Fh - Ml) / Fw; } else if (Fh > Mh and Fl < Mh and Fh > Ml and Fl > Ml) { fluxint += Fe * (Mh - Fl) / Fw; } else if (Ml >= Fl and Mh <= Fh) { fluxint += Fe * (Mh - Ml) / Fw; } else { continue; } } pdfflux->SetBinContent(i + 1, fluxint); } // Then finally divide by the bin-width in for (int i = 0; i < fMCHist->GetNbinsX(); i++) { for (int j = 0; j < fMCHist->GetNbinsY(); j++) { if (pdfflux->GetBinContent(i + 1) == 0.0) continue; // Different scaling depending on if Enu is on x or y axis double scaling = 1.0; // If Enu is on the x-axis, we want the ith entry of the flux // And to divide by the bin width of the jth bin if (EnuOnXaxis) { double binWidth = fMCHist->GetYaxis()->GetBinLowEdge(j + 2) - fMCHist->GetYaxis()->GetBinLowEdge(j + 1); scaling = pdfflux->GetBinContent(i + 1) * binWidth; } else { double binWidth = fMCHist->GetXaxis()->GetBinLowEdge(i + 2) - fMCHist->GetXaxis()->GetBinLowEdge(i + 1); scaling = pdfflux->GetBinContent(j + 1) * binWidth; } // fMCHist->SetBinContent(i + 1, j + 1, // fMCHist->GetBinContent(i + 1, j + 1) / // pdfflux->GetBinContent(i + 1) / binWidth); // fMCHist->SetBinError(i + 1, j + 1, fMCHist->GetBinError(i + 1, j + 1) / // pdfflux->GetBinContent(i + 1) / // binWidth); fMCHist->SetBinContent(i + 1, j + 1, fMCHist->GetBinContent(i + 1, j + 1) / scaling); fMCHist->SetBinError(i + 1, j + 1, fMCHist->GetBinError(i + 1, j + 1) / scaling); } } delete eventhist; delete fFluxHist; }; TH1D *PlotUtils::InterpolateFineHistogram(TH1D *hist, int res, std::string opt) { int nbins = hist->GetNbinsX(); double elow = hist->GetXaxis()->GetBinLowEdge(1); double ehigh = hist->GetXaxis()->GetBinLowEdge(nbins + 1); bool width = true; // opt.find("width") != std::string::npos; TH1D *fine = new TH1D("fine", "fine", nbins * res, elow, ehigh); TGraph *temp = new TGraph(); for (int i = 0; i < nbins; i++) { double E = hist->GetXaxis()->GetBinCenter(i + 1); double C = hist->GetBinContent(i + 1); double W = hist->GetXaxis()->GetBinWidth(i + 1); if (!width) W = 1.0; if (W != 0.0) temp->SetPoint(temp->GetN(), E, C / W); } for (int i = 0; i < fine->GetNbinsX(); i++) { double E = fine->GetXaxis()->GetBinCenter(i + 1); double W = fine->GetBinWidth(i + 1); if (!width) W = 1.0; fine->SetBinContent(i + 1, temp->Eval(E, 0, "S") * W); } fine->Scale(hist->Integral(1, hist->GetNbinsX() + 1) / fine->Integral(1, fine->GetNbinsX() + 1)); // std::cout << "Interpolation Difference = " //<< fine->Integral(1, fine->GetNbinsX() + 1) << "/" //<< hist->Integral(1, hist->GetNbinsX() + 1) << std::endl; return fine; } //******************************************************************** // This interpolates the flux by a TGraph instead of requiring the flux and MC // flux to have the same binning void PlotUtils::FluxUnfoldedScaling(TH1D *mcHist, TH1D *fhist, TH1D *ehist, double scalefactor, int nevents) { //******************************************************************** TH1D *eventhist = (TH1D *)ehist->Clone(); TH1D *fFluxHist = (TH1D *)fhist->Clone(); if (FitPar::Config().GetParB("save_flux_debug")) { std::string name = std::string(mcHist->GetName()); mcHist->Write((name + "_UNF_MC").c_str()); fFluxHist->Write((name + "_UNF_FLUX").c_str()); eventhist->Write((name + "_UNF_EVT").c_str()); TH1D *scalehist = new TH1D("scalehist", "scalehist", 1, 0.0, 1.0); scalehist->SetBinContent(1, scalefactor); scalehist->SetBinContent(2, nevents); scalehist->Write((name + "_UNF_SCALE").c_str()); } // Undo width integral in SF mcHist->Scale(scalefactor / eventhist->Integral(1, eventhist->GetNbinsX() + 1, "width")); // Standardise The Flux eventhist->Scale(1.0 / fFluxHist->Integral()); fFluxHist->Scale(1.0 / fFluxHist->Integral()); // Scale mcHist by eventhist integral mcHist->Scale(eventhist->Integral(1, eventhist->GetNbinsX() + 1)); // Now Get a flux PDF TH1D *pdfflux = (TH1D *)mcHist->Clone(); pdfflux->Reset(); for (int i = 0; i < mcHist->GetNbinsX(); i++) { double Ml = mcHist->GetXaxis()->GetBinLowEdge(i + 1); double Mh = mcHist->GetXaxis()->GetBinLowEdge(i + 2); // double Mc = mcHist->GetXaxis()->GetBinCenter(i+1); // double Me = mcHist->GetBinContent(i+1); // double Mw = mcHist->GetBinWidth(i+1); double fluxint = 0.0; for (int j = 0; j < fFluxHist->GetNbinsX(); j++) { // double Fc = fFluxHist->GetXaxis()->GetBinCenter(j+1); double Fl = fFluxHist->GetXaxis()->GetBinLowEdge(j + 1); double Fh = fFluxHist->GetXaxis()->GetBinLowEdge(j + 2); double Fe = fFluxHist->GetBinContent(j + 1); double Fw = fFluxHist->GetXaxis()->GetBinWidth(j + 1); if (Fl >= Ml and Fh <= Mh) { fluxint += Fe; } else if (Fl < Ml and Fl < Mh and Fh > Ml and Fh < Mh) { fluxint += Fe * (Fh - Ml) / Fw; } else if (Fh > Mh and Fl < Mh and Fh > Ml and Fl > Ml) { fluxint += Fe * (Mh - Fl) / Fw; } else if (Ml >= Fl and Mh <= Fh) { fluxint += Fe * (Mh - Ml) / Fw; } else { continue; } } pdfflux->SetBinContent(i + 1, fluxint); } // Scale MC hist by pdfflux for (int i = 0; i < mcHist->GetNbinsX(); i++) { if (pdfflux->GetBinContent(i + 1) == 0.0) continue; mcHist->SetBinContent(i + 1, mcHist->GetBinContent(i + 1) / pdfflux->GetBinContent(i + 1)); mcHist->SetBinError(i + 1, mcHist->GetBinError(i + 1) / pdfflux->GetBinContent(i + 1)); } delete eventhist; delete fFluxHist; }; // MOVE TO GENERAL UTILS //******************************************************************** void PlotUtils::Set2DHistFromText(std::string dataFile, TH2 *hist, double norm, bool skipbins) { //******************************************************************** std::string line; std::ifstream data(dataFile.c_str(), std::ifstream::in); int yBin = 0; while (std::getline(data >> std::ws, line, '\n')) { std::vector entries = GeneralUtils::ParseToDbl(line, " "); // Loop over entries and insert them into the histogram for (uint xBin = 0; xBin < entries.size(); xBin++) { if (!skipbins || entries[xBin] != -1.0) hist->SetBinContent(xBin + 1, yBin + 1, entries[xBin] * norm); } yBin++; } return; } // MOVE TO GENERAL UTILS TH1D *PlotUtils::GetTH1DFromFile(std::string dataFile, std::string title, std::string fPlotTitles, std::string alt_name) { TH1D *tempPlot; // If format is a root file if (dataFile.find(".root") != std::string::npos) { TFile *temp_infile = new TFile(dataFile.c_str(), "READ"); tempPlot = (TH1D *)temp_infile->Get(title.c_str()); tempPlot->SetDirectory(0); temp_infile->Close(); delete temp_infile; // Else its a space seperated txt file } else { // Make a TGraph Errors TGraphErrors *gr = new TGraphErrors(dataFile.c_str(), "%lg %lg %lg"); if (gr->IsZombie()) { - QTHROW(dataFile + NUIS_ABORT(dataFile << " is a zombie and could not be read. Are you sure it exists?" << std::endl); } double *bins = gr->GetX(); double *values = gr->GetY(); double *errors = gr->GetEY(); int npoints = gr->GetN(); // Fill the histogram from it tempPlot = new TH1D(title.c_str(), title.c_str(), npoints - 1, bins); for (int i = 0; i < npoints; ++i) { tempPlot->SetBinContent(i + 1, values[i]); // If only two columns are present in the input file, use the sqrt(values) // as the error equivalent to assuming that the error is statistical. Also // check that we're looking at an event rate rather than a cross section if (!errors[i] && values[i] > 1E-30) { tempPlot->SetBinError(i + 1, sqrt(values[i])); } else { tempPlot->SetBinError(i + 1, errors[i]); } } delete gr; } // Allow alternate naming for root files if (!alt_name.empty()) { tempPlot->SetNameTitle(alt_name.c_str(), alt_name.c_str()); } // Allow alternate axis titles if (!fPlotTitles.empty()) { tempPlot->SetNameTitle( tempPlot->GetName(), (std::string(tempPlot->GetTitle()) + fPlotTitles).c_str()); } return tempPlot; }; TH1D *PlotUtils::GetRatioPlot(TH1D *hist1, TH1D *hist2) { // make copy of first hist TH1D *new_hist = (TH1D *)hist1->Clone(); // Do bins and errors ourselves as scales can go awkward for (int i = 0; i < new_hist->GetNbinsX(); i++) { if (hist2->GetBinContent(i + 1) == 0.0) { new_hist->SetBinContent(i + 1, 0.0); } new_hist->SetBinContent(i + 1, hist1->GetBinContent(i + 1) / hist2->GetBinContent(i + 1)); new_hist->SetBinError(i + 1, hist1->GetBinError(i + 1) / hist2->GetBinContent(i + 1)); } return new_hist; }; TH1D *PlotUtils::GetRenormalisedPlot(TH1D *hist1, TH1D *hist2) { // make copy of first hist TH1D *new_hist = (TH1D *)hist1->Clone(); if (hist1->Integral("width") == 0 or hist2->Integral("width") == 0) { new_hist->Reset(); return new_hist; } Double_t scaleF = hist2->Integral("width") / hist1->Integral("width"); new_hist->Scale(scaleF); return new_hist; }; TH1D *PlotUtils::GetShapePlot(TH1D *hist1) { // make copy of first hist TH1D *new_hist = (TH1D *)hist1->Clone(); if (hist1->Integral("width") == 0) { new_hist->Reset(); return new_hist; } Double_t scaleF1 = 1.0 / hist1->Integral("width"); new_hist->Scale(scaleF1); return new_hist; }; TH1D *PlotUtils::GetShapeRatio(TH1D *hist1, TH1D *hist2) { TH1D *new_hist1 = GetShapePlot(hist1); TH1D *new_hist2 = GetShapePlot(hist2); // Do bins and errors ourselves as scales can go awkward for (int i = 0; i < new_hist1->GetNbinsX(); i++) { if (hist2->GetBinContent(i + 1) == 0) { new_hist1->SetBinContent(i + 1, 0.0); } new_hist1->SetBinContent(i + 1, new_hist1->GetBinContent(i + 1) / new_hist2->GetBinContent(i + 1)); new_hist1->SetBinError(i + 1, new_hist1->GetBinError(i + 1) / new_hist2->GetBinContent(i + 1)); } delete new_hist2; return new_hist1; }; TH2D *PlotUtils::GetCovarPlot(TMatrixDSym *cov, std::string name, std::string title) { TH2D *CovarPlot; if (cov) CovarPlot = new TH2D((*cov)); else CovarPlot = new TH2D(name.c_str(), title.c_str(), 1, 0, 1, 1, 0, 1); CovarPlot->SetName(name.c_str()); CovarPlot->SetTitle(title.c_str()); return CovarPlot; } TH2D *PlotUtils::GetFullCovarPlot(TMatrixDSym *cov, std::string name) { return PlotUtils::GetCovarPlot( cov, name + "_COV", name + "_COV;Bins;Bins;Covariance (#times10^{-76})"); } TH2D *PlotUtils::GetInvCovarPlot(TMatrixDSym *cov, std::string name) { return PlotUtils::GetCovarPlot( cov, name + "_INVCOV", name + "_INVCOV;Bins;Bins;Inv. Covariance (#times10^{-76})"); } TH2D *PlotUtils::GetDecompCovarPlot(TMatrixDSym *cov, std::string name) { return PlotUtils::GetCovarPlot( cov, name + "_DECCOV", name + "_DECCOV;Bins;Bins;Decomp Covariance (#times10^{-76})"); } TH1D *PlotUtils::GetTH1DFromRootFile(std::string file, std::string name) { if (name.empty()) { std::vector tempfile = GeneralUtils::ParseToStr(file, ";"); file = tempfile[0]; name = tempfile[1]; } TFile *rootHistFile = new TFile(file.c_str(), "READ"); TH1D *tempHist = (TH1D *)rootHistFile->Get(name.c_str())->Clone(); if (tempHist == NULL) { - QTHROW("Could not find distribution " << name << " in file " << file); + NUIS_ABORT("Could not find distribution " << name << " in file " << file); } tempHist->SetDirectory(0); rootHistFile->Close(); return tempHist; } TH2D *PlotUtils::GetTH2DFromRootFile(std::string file, std::string name) { if (name.empty()) { std::vector tempfile = GeneralUtils::ParseToStr(file, ";"); file = tempfile[0]; name = tempfile[1]; } TFile *rootHistFile = new TFile(file.c_str(), "READ"); TH2D *tempHist = (TH2D *)rootHistFile->Get(name.c_str())->Clone(); tempHist->SetDirectory(0); rootHistFile->Close(); delete rootHistFile; return tempHist; } TH1 *PlotUtils::GetTH1FromRootFile(std::string file, std::string name) { if (name.empty()) { std::vector tempfile = GeneralUtils::ParseToStr(file, ";"); file = tempfile[0]; name = tempfile[1]; } TFile *rootHistFile = new TFile(file.c_str(), "READ"); if (!rootHistFile || rootHistFile->IsZombie()) { - QTHROW("Couldn't open root file: \"" << file << "\"."); + NUIS_ABORT("Couldn't open root file: \"" << file << "\"."); } TH1 *tempHist = dynamic_cast(rootHistFile->Get(name.c_str())->Clone()); if (!tempHist) { - QTHROW("Couldn't retrieve: \"" << name << "\" from root file: \"" << file + NUIS_ABORT("Couldn't retrieve: \"" << name << "\" from root file: \"" << file << "\"."); } tempHist->SetDirectory(0); rootHistFile->Close(); delete rootHistFile; return tempHist; } TGraph *PlotUtils::GetTGraphFromRootFile(std::string file, std::string name) { if (name.empty()) { std::vector tempfile = GeneralUtils::ParseToStr(file, ";"); file = tempfile[0]; name = tempfile[1]; } TDirectory *olddir = gDirectory; TFile *rootHistFile = new TFile(file.c_str(), "READ"); if (!rootHistFile || rootHistFile->IsZombie()) { - QTHROW("Couldn't open root file: \"" << file << "\"."); + NUIS_ABORT("Couldn't open root file: \"" << file << "\"."); } TDirectory *newdir = gDirectory; TGraph *temp = dynamic_cast(rootHistFile->Get(name.c_str())->Clone()); if (!temp) { - QTHROW("Couldn't retrieve: \"" << name << "\" from root file: \"" << file + NUIS_ABORT("Couldn't retrieve: \"" << name << "\" from root file: \"" << file << "\"."); } newdir->Remove(temp); olddir->Append(temp); rootHistFile->Close(); olddir->cd(); return temp; } /// Returns a vector of named TH1*s found in a single input file. /// /// Expects a descriptor like: file.root[hist1|hist2|...] std::vector PlotUtils::GetTH1sFromRootFile(std::string const &descriptor) { std::vector descriptors = GeneralUtils::ParseToStr(descriptor, ","); std::vector hists; for (size_t d_it = 0; d_it < descriptors.size(); ++d_it) { std::string &d = descriptors[d_it]; std::vector fname = GeneralUtils::ParseToStr(d, "["); if (!fname.size() || !fname[0].length()) { - QTHROW("Couldn't find input file when attempting to parse : \"" + NUIS_ABORT("Couldn't find input file when attempting to parse : \"" << d << "\". Expected input.root[hist1|hist2|...]."); } if (fname[1][fname[1].length() - 1] == ']') { fname[1] = fname[1].substr(0, fname[1].length() - 1); } std::vector histnames = GeneralUtils::ParseToStr(fname[1], "|"); if (!histnames.size()) { - QTHROW("Couldn't find any histogram name specifiers when attempting to " + NUIS_ABORT("Couldn't find any histogram name specifiers when attempting to " "parse " ": \"" << fname[1] << "\". Expected hist1|hist2|..."); } TFile *rootHistFile = new TFile(fname[0].c_str(), "READ"); if (!rootHistFile || rootHistFile->IsZombie()) { - QTHROW("Couldn't open root file: \"" << fname[0] << "\"."); + NUIS_ABORT("Couldn't open root file: \"" << fname[0] << "\"."); } for (size_t i = 0; i < histnames.size(); ++i) { TH1 *tempHist = dynamic_cast(rootHistFile->Get(histnames[i].c_str())->Clone()); if (!tempHist) { - QTHROW("Couldn't retrieve: \"" + NUIS_ABORT("Couldn't retrieve: \"" << histnames[i] << "\" from root file: \"" << fname[0] << "\"."); } tempHist->SetDirectory(0); hists.push_back(tempHist); } rootHistFile->Close(); } return hists; } // Create an array from an input file std::vector PlotUtils::GetArrayFromTextFile(std::string DataFile) { std::string line; std::ifstream data(DataFile.c_str(), std::ifstream::in); // Get first line std::getline(data >> std::ws, line, '\n'); // Convert from a string into a vector of double std::vector entries = GeneralUtils::ParseToDbl(line, " "); return entries; } // Get a 2D array from a text file std::vector> PlotUtils::Get2DArrayFromTextFile(std::string DataFile) { std::string line; std::vector> DataArray; std::ifstream data(DataFile.c_str(), std::ifstream::in); while (std::getline(data >> std::ws, line, '\n')) { std::vector entries = GeneralUtils::ParseToDbl(line, " "); DataArray.push_back(entries); } return DataArray; } TH2D *PlotUtils::GetTH2DFromTextFile(std::string data, std::string binx, std::string biny) { // First read in the binning // Array of x binning std::vector xbins = GetArrayFromTextFile(binx); // Array of y binning std::vector ybins = GetArrayFromTextFile(biny); // Read in the data std::vector> Data = Get2DArrayFromTextFile(data); // And finally fill the data TH2D *DataPlot = new TH2D("TempHist", "TempHist", xbins.size() - 1, &xbins[0], ybins.size() - 1, &ybins[0]); int nBinsX = 0; int nBinsY = 0; for (std::vector>::iterator it = Data.begin(); it != Data.end(); ++it) { nBinsX++; // Get the inner vector std::vector temp = *it; // Save the previous number[of bins to make sure it's uniform binning int oldBinsY = nBinsY; // Reset the counter nBinsY = 0; for (std::vector::iterator jt = temp.begin(); jt != temp.end(); ++jt) { nBinsY++; DataPlot->SetBinContent(nBinsX, nBinsY, *jt); DataPlot->SetBinError(nBinsX, nBinsY, 0.0); } if (oldBinsY > 0 && oldBinsY != nBinsY) { - QERROR(FTL, "Found non-uniform y-binning in " << data); - QERROR(FTL, "Previous slice: " << oldBinsY); - QERROR(FTL, "Current slice: " << nBinsY); - QTHROW("Non-uniform binning is not supported in " + NUIS_ERR(FTL, "Found non-uniform y-binning in " << data); + NUIS_ERR(FTL, "Previous slice: " << oldBinsY); + NUIS_ERR(FTL, "Current slice: " << nBinsY); + NUIS_ABORT("Non-uniform binning is not supported in " "PlotUtils::GetTH2DFromTextFile"); } } // Check x bins if (size_t(nBinsX + 1) != xbins.size()) { - QERROR(FTL, "Number of x bins in data histogram does not match the binning " + NUIS_ERR(FTL, "Number of x bins in data histogram does not match the binning " "histogram!"); - QERROR(FTL, + NUIS_ERR(FTL, "Are they the wrong way around (i.e. xbinning should be ybinning)?"); - QERROR(FTL, "Data: " << nBinsX); - QTHROW("From " << binx << " binning: " << xbins.size()); + NUIS_ERR(FTL, "Data: " << nBinsX); + NUIS_ABORT("From " << binx << " binning: " << xbins.size()); } // Check y bins if (size_t(nBinsY + 1) != ybins.size()) { - QERROR(FTL, "Number of y bins in data histogram does not match the binning " + NUIS_ERR(FTL, "Number of y bins in data histogram does not match the binning " "histogram!"); - QERROR(FTL, + NUIS_ERR(FTL, "Are they the wrong way around (i.e. xbinning should be ybinning)?"); - QERROR(FTL, "Data: " << nBinsY); - QTHROW("From " << biny << " binning: " << ybins.size()); + NUIS_ERR(FTL, "Data: " << nBinsY); + NUIS_ABORT("From " << biny << " binning: " << ybins.size()); } return DataPlot; } TH1D *PlotUtils::GetSliceY(TH2D *Hist, int SliceNo) { TH1D *Slice = Hist->ProjectionX(Form("%s_SLICEY%i", Hist->GetName(), SliceNo), SliceNo, SliceNo, "e"); Slice->SetTitle(Form("%s, %.2f-%.2f", Hist->GetYaxis()->GetTitle(), Hist->GetYaxis()->GetBinLowEdge(SliceNo), Hist->GetYaxis()->GetBinLowEdge(SliceNo + 1))); Slice->GetYaxis()->SetTitle(Hist->GetZaxis()->GetTitle()); return Slice; } TH1D *PlotUtils::GetSliceX(TH2D *Hist, int SliceNo) { TH1D *Slice = Hist->ProjectionY(Form("%s_SLICEX%i", Hist->GetName(), SliceNo), SliceNo, SliceNo, "e"); Slice->SetTitle(Form("%s, %.2f-%.2f", Hist->GetXaxis()->GetTitle(), Hist->GetXaxis()->GetBinLowEdge(SliceNo), Hist->GetXaxis()->GetBinLowEdge(SliceNo + 1))); Slice->GetYaxis()->SetTitle(Hist->GetZaxis()->GetTitle()); return Slice; } void PlotUtils::AddNeutModeArray(TH1D *hist1[], TH1D *hist2[], double scaling) { for (int i = 0; i < 60; i++) { if (!hist2[i]) continue; if (!hist1[i]) continue; hist1[i]->Add(hist2[i], scaling); } return; } void PlotUtils::ScaleToData(TH1D *data, TH1D *mc, TH1I *mask) { double scaleF = GetDataMCRatio(data, mc, mask); mc->Scale(scaleF); return; } void PlotUtils::MaskBins(TH1D *hist, TH1I *mask) { for (int i = 0; i < hist->GetNbinsX(); i++) { if (mask->GetBinContent(i + 1) <= 0.5) continue; hist->SetBinContent(i + 1, 0.0); hist->SetBinError(i + 1, 0.0); - QLOG(REC, "MaskBins: Set " << hist->GetName() << " Bin " << i + 1 + NUIS_LOG(REC, "MaskBins: Set " << hist->GetName() << " Bin " << i + 1 << " to 0.0 +- 0.0"); } return; } void PlotUtils::MaskBins(TH2D *hist, TH2I *mask) { for (int i = 0; i < hist->GetNbinsX(); i++) { for (int j = 0; j < hist->GetNbinsY(); j++) { if (mask->GetBinContent(i + 1, j + 1) <= 0.5) continue; hist->SetBinContent(i + 1, j + 1, 0.0); hist->SetBinError(i + 1, j + 1, 0.0); - QLOG(REC, "MaskBins: Set " << hist->GetName() << " Bin " << i + 1 << " " + NUIS_LOG(REC, "MaskBins: Set " << hist->GetName() << " Bin " << i + 1 << " " << j + 1 << " to 0.0 +- 0.0"); } } return; } double PlotUtils::GetDataMCRatio(TH1D *data, TH1D *mc, TH1I *mask) { double rat = 1.0; TH1D *newmc = (TH1D *)mc->Clone(); TH1D *newdt = (TH1D *)data->Clone(); if (mask) { MaskBins(newmc, mask); MaskBins(newdt, mask); } rat = newdt->Integral() / newmc->Integral(); return rat; } TH2D *PlotUtils::GetCorrelationPlot(TH2D *cov, std::string name) { TH2D *cor = (TH2D *)cov->Clone(); cor->Reset(); for (int i = 0; i < cov->GetNbinsX(); i++) { for (int j = 0; j < cov->GetNbinsY(); j++) { if (cov->GetBinContent(i + 1, i + 1) != 0.0 and cov->GetBinContent(j + 1, j + 1) != 0.0) cor->SetBinContent(i + 1, j + 1, cov->GetBinContent(i + 1, j + 1) / (sqrt(cov->GetBinContent(i + 1, i + 1) * cov->GetBinContent(j + 1, j + 1)))); } } if (!name.empty()) { cor->SetNameTitle(name.c_str(), (name + ";;correlation").c_str()); } cor->SetMinimum(-1); cor->SetMaximum(1); return cor; } TH2D *PlotUtils::GetDecompPlot(TH2D *cov, std::string name) { TMatrixDSym *covarmat = new TMatrixDSym(cov->GetNbinsX()); for (int i = 0; i < cov->GetNbinsX(); i++) for (int j = 0; j < cov->GetNbinsY(); j++) (*covarmat)(i, j) = cov->GetBinContent(i + 1, j + 1); TMatrixDSym *decompmat = StatUtils::GetDecomp(covarmat); TH2D *dec = (TH2D *)cov->Clone(); for (int i = 0; i < cov->GetNbinsX(); i++) for (int j = 0; j < cov->GetNbinsY(); j++) dec->SetBinContent(i + 1, j + 1, (*decompmat)(i, j)); delete covarmat; delete decompmat; dec->SetNameTitle(name.c_str(), (name + ";;;decomposition").c_str()); return dec; } TH2D *PlotUtils::MergeIntoTH2D(TH1D *xhist, TH1D *yhist, std::string zname) { std::vector xedges, yedges; for (int i = 0; i < xhist->GetNbinsX() + 2; i++) { xedges.push_back(xhist->GetXaxis()->GetBinLowEdge(i + 1)); } for (int i = 0; i < yhist->GetNbinsX() + 2; i++) { yedges.push_back(yhist->GetXaxis()->GetBinLowEdge(i + 1)); } int nbinsx = xhist->GetNbinsX(); int nbinsy = yhist->GetNbinsX(); std::string name = std::string(xhist->GetName()) + "_vs_" + std::string(yhist->GetName()); std::string titles = ";" + std::string(xhist->GetXaxis()->GetTitle()) + ";" + std::string(yhist->GetXaxis()->GetTitle()) + ";" + zname; TH2D *newplot = new TH2D(name.c_str(), (name + titles).c_str(), nbinsx, &xedges[0], nbinsy, &yedges[0]); return newplot; } //*************************************************** void PlotUtils::MatchEmptyBins(TH1D *data, TH1D *mc) { //************************************************** for (int i = 0; i < data->GetNbinsX(); i++) { if (data->GetBinContent(i + 1) == 0.0 or data->GetBinError(i + 1) == 0.0) mc->SetBinContent(i + 1, 0.0); } return; } //*************************************************** void PlotUtils::MatchEmptyBins(TH2D *data, TH2D *mc) { //************************************************** for (int i = 0; i < data->GetNbinsX(); i++) { for (int j = 0; j < data->GetNbinsY(); j++) { if (data->GetBinContent(i + 1, j + 1) == 0.0 or data->GetBinError(i + 1, j + 1) == 0.0) mc->SetBinContent(i + 1, j + 1, 0.0); } } return; } //*************************************************** TH1D *PlotUtils::GetProjectionX(TH2D *hist, TH2I *mask) { //*************************************************** TH2D *maskedhist = StatUtils::ApplyHistogramMasking(hist, mask); // This includes the underflow/overflow TH1D *hist_X = maskedhist->ProjectionX(); delete maskedhist; return hist_X; } //*************************************************** TH1D *PlotUtils::GetProjectionY(TH2D *hist, TH2I *mask) { //*************************************************** TH2D *maskedhist = StatUtils::ApplyHistogramMasking(hist, mask); // This includes the underflow/overflow TH1D *hist_Y = maskedhist->ProjectionY(); delete maskedhist; return hist_Y; } diff --git a/src/Utils/TargetUtils.cxx b/src/Utils/TargetUtils.cxx index 67e58b7..1481ed5 100644 --- a/src/Utils/TargetUtils.cxx +++ b/src/Utils/TargetUtils.cxx @@ -1,81 +1,81 @@ #include "TargetUtils.h" std::vector TargetUtils::ParseTargetsToIntVect(std::string targets) { std::vector splittgt = GeneralUtils::ParseToStr(targets, ","); std::vector convtgt; for (size_t i = 0; i < splittgt.size(); i++) { std::string type = splittgt[i]; convtgt.push_back(GetTargetPDGFromString(type)); } return convtgt; } int TargetUtils::GetTargetPDGFromString(std::string target) { if (!target.compare("H")) return 1000010010; else if (!target.compare("C")) return 1000060120; else if (!target.compare("O")) return 1000080160; else { int conv = GeneralUtils::StrToInt(target); if (abs(conv) > 1) return conv; } return 0; } int TargetUtils::GetTargetPDGFromZA(int Z, int A) { return 1000000000 + A * 10 + Z * 10000; } int TargetUtils::GetTargetAFromPDG(int PDG) { return ((PDG % 10000)) / 10; } int TargetUtils::GetTargetZFromPDG(int PDG) { return (PDG % 1000000000 - PDG % 10000) / 10000; } ///____________________________________________________________________________ void TargetUtils::ListTargetIDs() { // Keep in sync with ConvertTargetIDs - QLOG(FIT, "Possible Target IDs: \n" + NUIS_LOG(FIT, "Possible Target IDs: \n" << "\n H : " << TargetUtils::ConvertTargetIDs("H") << "\n C : " << TargetUtils::ConvertTargetIDs("C") << "\n CH : " << TargetUtils::ConvertTargetIDs("CH") << "\n CH2 : " << TargetUtils::ConvertTargetIDs("CH2") << "\n H2O : " << TargetUtils::ConvertTargetIDs("H2O") << "\n Fe : " << TargetUtils::ConvertTargetIDs("Fe") << "\n Pb : " << TargetUtils::ConvertTargetIDs("Pb") << "\n D2 : " << TargetUtils::ConvertTargetIDs("D2") << "\n D2-free : " << TargetUtils::ConvertTargetIDs("D2-free")); } //____________________________________________________________________________ std::string TargetUtils::ConvertTargetIDs(std::string id) { if (!id.compare("H")) return "1000010010"; else if (!id.compare("C")) return "1000060120"; else if (!id.compare("CH")) return "13,1000060120[0.9231],1000010010[0.0769]"; else if (!id.compare("CH2")) return "14,1000060120[0.8571],1000010010[0.1429]"; else if (!id.compare("H2O")) return "18,1000080160[0.8888],1000010010[0.1111]"; else if (!id.compare("Fe")) return "1000260560"; else if (!id.compare("Pb")) return "1000822070"; else if (!id.compare("D2")) return "1000010020"; else if (!id.compare("D2-free")) return "2,1000010010[0.5],1000000010[0.5]"; else return ""; };