From 5d35adb1db4d47bdb7cd3fca13935ade4ff7070c Mon Sep 17 00:00:00 2001 From: Nathaniel Date: Mon, 16 Nov 2026 10:40:30 -0600 Subject: [PATCH] initial commit --- sbncode/EventGenerator/CMakeLists.txt | 1 + .../SinglePhoton/CMakeLists.txt | 22 ++ .../SinglePhoton/DeletePi0Photon_module.cc | 287 ++++++++++++++++++ .../SinglePhoton/PhotonTruthTools.h | 203 +++++++++++++ .../SinglePhoton/deletepi0photon_sbn.fcl | 39 +++ 5 files changed, 552 insertions(+) create mode 100644 sbncode/EventGenerator/SinglePhoton/CMakeLists.txt create mode 100644 sbncode/EventGenerator/SinglePhoton/DeletePi0Photon_module.cc create mode 100644 sbncode/EventGenerator/SinglePhoton/PhotonTruthTools.h create mode 100644 sbncode/EventGenerator/SinglePhoton/deletepi0photon_sbn.fcl diff --git a/sbncode/EventGenerator/CMakeLists.txt b/sbncode/EventGenerator/CMakeLists.txt index 292682726..604d91dbf 100644 --- a/sbncode/EventGenerator/CMakeLists.txt +++ b/sbncode/EventGenerator/CMakeLists.txt @@ -1,3 +1,4 @@ add_subdirectory(MeVPrtl) add_subdirectory(MultiPart) +add_subdirectory(SinglePhoton) add_subdirectory(WireModGen) diff --git a/sbncode/EventGenerator/SinglePhoton/CMakeLists.txt b/sbncode/EventGenerator/SinglePhoton/CMakeLists.txt new file mode 100644 index 000000000..5d58fc6dc --- /dev/null +++ b/sbncode/EventGenerator/SinglePhoton/CMakeLists.txt @@ -0,0 +1,22 @@ +cet_build_plugin(DeletePi0Photon art::EDFilter + LIBRARIES PRIVATE + larcore::Geometry_Geometry_service + larcoreobj::SummaryData + lardataobj::Simulation + nurandom::RandomUtils_NuRandomService_service + nusimdata::SimulationBase + dk2nu::Tree + art::Framework_Principal + art::Framework_Services_Registry + art::Persistency_Common + canvas::canvas + messagefacility::MF_MessageLogger + fhiclcpp::fhiclcpp + cetlib_except::cetlib_except + CLHEP::Random + ROOT::Physics +) + +install_headers() +install_fhicl() +install_source() diff --git a/sbncode/EventGenerator/SinglePhoton/DeletePi0Photon_module.cc b/sbncode/EventGenerator/SinglePhoton/DeletePi0Photon_module.cc new file mode 100644 index 000000000..be290cfa4 --- /dev/null +++ b/sbncode/EventGenerator/SinglePhoton/DeletePi0Photon_module.cc @@ -0,0 +1,287 @@ +//////////////////////////////////////////////////////////////////////// +/// \file DeletePi0Photon_module.cc +/// \brief Builds single-photon training samples from GENIE events by +/// decaying pi0s at generator level and deleting one photon. +/// +/// Intended to run in the gen stage directly after GENIEGen, which is +/// relabelled (e.g. "rawgenerator") so that this module can take the +/// "generator" label. It re-publishes every product GENIEGen makes, +/// so downstream stages (G4, detsim, reco, CAFMaker, event weights) run +/// unchanged on the modified truth: +/// +/// event : std::vector (modified) +/// std::vector (copied, index-aligned with MCTruth) +/// std::vector (copied, index-aligned with MCTruth) +/// art::Assns (rebuilt) +/// std::vector (copied) +/// Dk2Nu / NuChoice + Assns (copied, if ForwardDk2Nu) +/// subrun : sumdata::POTSummary (copied) +/// run : sumdata::RunData (rebuilt from Geometry, as GENIEGen does) +/// +/// The input label's products MUST be dropped on output, otherwise +/// larg4Main (which reads every MCTruth collection when inputCollections +/// is empty) simulates both the original and the modified interaction. +/// +/// Note that GTruth, MCFlux and the MCNeutrino describe the *unmodified* +/// interaction; the modified events do not conserve 4-momentum. +/// +/// As an EDFilter it can also require an exact number of final-state +/// photons after modification (RequiredNPhotons; < 0 disables). With +/// OnlyDeletePi0Photons, both the deletion and this count consider only +/// photons whose mother is a pi0, so other photons in the event (e.g. +/// GENIE nuclear de-excitation gammas) are left alone and not counted. +//////////////////////////////////////////////////////////////////////// + +#include "sbncode/EventGenerator/SinglePhoton/PhotonTruthTools.h" + +#include "art/Framework/Core/EDFilter.h" +#include "art/Framework/Core/ModuleMacros.h" +#include "art/Framework/Principal/Event.h" +#include "art/Framework/Principal/Run.h" +#include "art/Framework/Principal/SubRun.h" +#include "art/Framework/Services/Registry/ServiceHandle.h" +#include "art/Persistency/Common/PtrMaker.h" +#include "canvas/Persistency/Common/Assns.h" +#include "canvas/Persistency/Common/Ptr.h" +#include "canvas/Persistency/Common/FindOneP.h" +#include "canvas/Utilities/InputTag.h" +#include "cetlib_except/exception.h" +#include "fhiclcpp/ParameterSet.h" +#include "messagefacility/MessageLogger/MessageLogger.h" +#include "nurandom/RandomUtils/NuRandomService.h" + +#include "larcore/Geometry/Geometry.h" +#include "larcoreobj/SummaryData/POTSummary.h" +#include "larcoreobj/SummaryData/RunData.h" +#include "lardataobj/Simulation/BeamGateInfo.h" +#include "nusimdata/SimulationBase/GTruth.h" +#include "nusimdata/SimulationBase/MCFlux.h" +#include "nusimdata/SimulationBase/MCTruth.h" + +#include "dk2nu/tree/NuChoice.h" +#include "dk2nu/tree/dk2nu.h" + +#include "CLHEP/Random/RandomEngine.h" + +#include +#include + +namespace sbn { + + class DeletePi0Photon : public art::EDFilter { + public: + explicit DeletePi0Photon(fhicl::ParameterSet const& p); + + bool filter(art::Event& e) override; + bool beginRun(art::Run& r) override; + bool endSubRun(art::SubRun& sr) override; + void endJob() override; + + private: + art::InputTag const fInputTag; + bool const fDecayPi0s; + bool const fDeletePhoton; + bool const fOnlyDeletePi0Photons; + int const fRequiredNPhotons; + bool const fForwardDk2Nu; + bool const fVerbose; + + CLHEP::HepRandomEngine& fEngine; + + // counters for the end-of-job summary + unsigned long fNEvents = 0; + unsigned long fNPassed = 0; + unsigned long fNPi0sDecayed = 0; + unsigned long fNPhotonsDeleted = 0; + }; + +} // namespace sbn + +//------------------------------------------------------------------------------ +sbn::DeletePi0Photon::DeletePi0Photon(fhicl::ParameterSet const& p) + : EDFilter{p} + , fInputTag{p.get("InputLabel")} + , fDecayPi0s{p.get("DecayPi0s", true)} + , fDeletePhoton{p.get("DeletePhoton", true)} + , fOnlyDeletePi0Photons{p.get("OnlyDeletePi0Photons", false)} + , fRequiredNPhotons{p.get("RequiredNPhotons", -1)} + , fForwardDk2Nu{p.get("ForwardDk2Nu", false)} + , fVerbose{p.get("Verbose", false)} + , fEngine(art::ServiceHandle()->registerAndSeedEngine( + createEngine(0, "HepJamesRandom", "deletepi0photon"), + "HepJamesRandom", + "deletepi0photon", + p, + "Seed")) +{ + produces>(); + produces>(); + produces>(); + produces>(); + produces>(); + produces>(); + produces(); + produces(); + + if (fForwardDk2Nu) { + produces>(); + produces>(); + produces>(); + produces>(); + } +} + +//------------------------------------------------------------------------------ +namespace { + + /// Copy the T associated (one-to-one) with each input MCTruth into a new + /// collection, in MCTruth order, and associate it with the new MCTruth. + /// CAFMaker indexes MCFlux and Dk2Nu by MCTruth position, so the order matters. + template + void CopyAssociated(art::Event& e, + H const& inTruthH, + art::InputTag const& tag, + art::PtrMaker const& truthPtr, + std::vector& outCol, + art::Assns& outAssn, + char const* what) + { + art::FindOneP const fop(inTruthH, e, tag); + art::PtrMaker const makePtr{e}; + for (std::size_t i = 0; i < inTruthH->size(); ++i) { + art::Ptr const& in = fop.at(i); + if (in.isNull()) + throw cet::exception("DeletePi0Photon") + << "MCTruth #" << i << " from '" << tag.encode() << "' has no associated " << what + << ".\n"; + outCol.push_back(*in); + outAssn.addSingle(truthPtr(i), makePtr(outCol.size() - 1)); + } + } + +} // namespace + +//------------------------------------------------------------------------------ +bool sbn::DeletePi0Photon::filter(art::Event& e) +{ + ++fNEvents; + + auto const inTruthH = e.getValidHandle>(fInputTag); + + auto outTruth = std::make_unique>(); + outTruth->reserve(inTruthH->size()); + + unsigned int nPhotons = 0; + for (std::size_t i = 0; i < inTruthH->size(); ++i) { + simb::MCTruth truth = (*inTruthH)[i]; + + if (fDecayPi0s) { + simb::MCTruth decayed; + fNPi0sDecayed += singlephoton::DecayPi0sToTwoPhotons(truth, decayed, fEngine); + truth = std::move(decayed); + } + + if (fDeletePhoton) { + simb::MCTruth deleted; + int const idx = + singlephoton::DeleteOneRandomPhoton(truth, deleted, fEngine, fOnlyDeletePi0Photons); + if (idx >= 0) { + ++fNPhotonsDeleted; + if (fVerbose) { + auto const& g = truth.GetParticle(idx); + mf::LogInfo("DeletePi0Photon") + << "Event " << e.id() << " MCTruth #" << i << ": deleted photon track ID " + << g.TrackId() << " (mother " << g.Mother() << ", E = " << g.E() << " GeV)"; + } + } + truth = std::move(deleted); + } + + nPhotons += singlephoton::CountFinalStatePhotons(truth, fOnlyDeletePi0Photons); + outTruth->push_back(std::move(truth)); + } + + // Everything else is copied unchanged, index-aligned with the MCTruth. + art::PtrMaker const truthPtr{e}; + + auto outFlux = std::make_unique>(); + auto outFluxAssn = std::make_unique>(); + CopyAssociated(e, inTruthH, fInputTag, truthPtr, *outFlux, *outFluxAssn, "MCFlux"); + + auto outGTruth = std::make_unique>(); + auto outGTruthAssn = std::make_unique>(); + CopyAssociated(e, inTruthH, fInputTag, truthPtr, *outGTruth, *outGTruthAssn, "GTruth"); + + auto outGates = std::make_unique>( + *e.getValidHandle>(fInputTag)); + + e.put(std::move(outTruth)); + e.put(std::move(outFlux)); + e.put(std::move(outGTruth)); + e.put(std::move(outFluxAssn)); + e.put(std::move(outGTruthAssn)); + e.put(std::move(outGates)); + + // dk2nu fluxes (e.g. SBND's G4BNB) give Dk2Nu products that CAFMaker requires; + // refuse to silently lose them. + if (!fForwardDk2Nu && e.getHandle>(fInputTag)) + throw cet::exception("DeletePi0Photon") + << "Input '" << fInputTag.encode() << "' has bsim::Dk2Nu products (dk2nu flux) but " + << "ForwardDk2Nu is false; set ForwardDk2Nu: true.\n"; + + if (fForwardDk2Nu) { + auto outDk2Nu = std::make_unique>(); + auto outDk2NuAssn = std::make_unique>(); + CopyAssociated(e, inTruthH, fInputTag, truthPtr, *outDk2Nu, *outDk2NuAssn, "Dk2Nu"); + + auto outNuChoice = std::make_unique>(); + auto outNuChoiceAssn = std::make_unique>(); + CopyAssociated( + e, inTruthH, fInputTag, truthPtr, *outNuChoice, *outNuChoiceAssn, "NuChoice"); + + e.put(std::move(outDk2Nu)); + e.put(std::move(outNuChoice)); + e.put(std::move(outDk2NuAssn)); + e.put(std::move(outNuChoiceAssn)); + } + + bool const pass = + fRequiredNPhotons < 0 || nPhotons == static_cast(fRequiredNPhotons); + if (pass) ++fNPassed; + return pass; +} + +//------------------------------------------------------------------------------ +bool sbn::DeletePi0Photon::beginRun(art::Run& r) +{ + // Same as GENIEGen::beginRun. + art::ServiceHandle geo; + r.put(std::make_unique(geo->DetectorName()), art::fullRun()); + return true; +} + +//------------------------------------------------------------------------------ +bool sbn::DeletePi0Photon::endSubRun(art::SubRun& sr) +{ + // GENIEGen puts its POTSummary in endSubRun; this module must therefore be + // scheduled after it in the same path. + auto const pot = sr.getHandle(fInputTag); + if (!pot) + throw cet::exception("DeletePi0Photon") + << "No sumdata::POTSummary found under '" << fInputTag.encode() + << "' in endSubRun. Is this module after the generator in the path?\n"; + sr.put(std::make_unique(*pot), art::subRunFragment()); + return true; +} + +//------------------------------------------------------------------------------ +void sbn::DeletePi0Photon::endJob() +{ + mf::LogInfo("DeletePi0Photon") << "Summary: " << fNEvents << " events read, " + << fNPi0sDecayed << " pi0s decayed, " << fNPhotonsDeleted + << " photons deleted, " << fNPassed + << " events passed (RequiredNPhotons = " << fRequiredNPhotons + << ")."; +} + +DEFINE_ART_MODULE(sbn::DeletePi0Photon) diff --git a/sbncode/EventGenerator/SinglePhoton/PhotonTruthTools.h b/sbncode/EventGenerator/SinglePhoton/PhotonTruthTools.h new file mode 100644 index 000000000..17dee2f2e --- /dev/null +++ b/sbncode/EventGenerator/SinglePhoton/PhotonTruthTools.h @@ -0,0 +1,203 @@ +//////////////////////////////////////////////////////////////////////// +/// \file PhotonTruthTools.h +/// \brief Helpers to decay generator-level pi0s to two photons and to +/// delete one final-state photon from an MCTruth. +/// +/// Ported from the MicroBooNE implementation by L. Hagaman / E. Yandel +/// (uboone/ubsim PR #17, ubsim/NGEM), with these changes: +/// - randomness comes from a caller-supplied CLHEP engine (reproducible, +/// seeded through NuRandomService) instead of TRandom3(0); +/// - photons from each decayed pi0 get unique track IDs; +/// - the decayed pi0 keeps its trajectory, Gvtx, rescatter code, weight +/// and polarization, and records the photons as daughters. +//////////////////////////////////////////////////////////////////////// + +#ifndef SBNCODE_EVENTGENERATOR_SINGLEPHOTON_PHOTONTRUTHTOOLS_H +#define SBNCODE_EVENTGENERATOR_SINGLEPHOTON_PHOTONTRUTHTOOLS_H + +#include "nusimdata/SimulationBase/MCParticle.h" +#include "nusimdata/SimulationBase/MCTruth.h" + +#include "CLHEP/Random/RandFlat.h" +#include "CLHEP/Random/RandomEngine.h" + +#include "TLorentzVector.h" +#include "TVector3.h" + +#include +#include +#include +#include + +namespace sbn::singlephoton { + + // GENIE status codes (genie::GHepStatus_t) + constexpr int kStableFinalState = 1; + constexpr int kDecayedState = 3; + + constexpr int kPdgPhoton = 22; + constexpr int kPdgPi0 = 111; + + /// Copy everything in `in` except the particle list (origin, generator + /// info, neutrino) into `out` + /// (which must be freshly constructed, with its particles already added). + inline void CopyTruthHeader(simb::MCTruth const& in, simb::MCTruth& out) + { + out.SetOrigin(in.Origin()); + simb::MCGeneratorInfo const& gen = in.GeneratorInfo(); + out.SetGeneratorInfo(gen.generator, gen.generatorVersion, gen.generatorConfig); + if (!in.NeutrinoSet()) return; + simb::MCNeutrino const& nu = in.GetNeutrino(); + // SetNeutrino rebuilds the MCNeutrino from particle 0 (incoming neutrino) + // and the outgoing lepton, neither of which is touched by these tools. + out.SetNeutrino(nu.CCNC(), + nu.Mode(), + nu.InteractionType(), + nu.Target(), + nu.HitNuc(), + nu.HitQuark(), + nu.W(), + nu.X(), + nu.Y(), + nu.QSqr()); + } + + inline bool IsFinalStatePhoton(simb::MCParticle const& p) + { + return p.PdgCode() == kPdgPhoton && p.StatusCode() == kStableFinalState; + } + + /// Whether `p`'s mother (looked up by track ID in `truth`) is a pi0. + inline bool IsPi0Daughter(simb::MCTruth const& truth, simb::MCParticle const& p) + { + for (int j = 0; j < truth.NParticles(); ++j) { + simb::MCParticle const& m = truth.GetParticle(j); + if (m.TrackId() == p.Mother()) return m.PdgCode() == kPdgPi0; + } + return false; + } + + /// Copy of `p` with a different status code and extra daughters. + /// (MCParticle has no status-code setter.) + inline simb::MCParticle WithStatus(simb::MCParticle const& p, + int status, + std::vector const& extraDaughters = {}) + { + simb::MCParticle out(p.TrackId(), p.PdgCode(), p.Process(), p.Mother(), p.Mass(), status); + for (unsigned int i = 0; i < p.NumberTrajectoryPoints(); ++i) + out.AddTrajectoryPoint(p.Position(i), p.Momentum(i)); + for (int i = 0; i < p.NumberDaughters(); ++i) + out.AddDaughter(p.Daughter(i)); + for (int d : extraDaughters) + out.AddDaughter(d); + out.SetGvtx(p.GetGvtx()); + out.SetRescatter(p.Rescatter()); + out.SetWeight(p.Weight()); + out.SetPolarization(p.Polarization()); + out.SetEndProcess(p.EndProcess()); + return out; + } + + /// Decay every final-state (status 1) pi0 in `in` isotropically to two + /// photons in its rest frame. The pi0 is kept with status 3 so that LArG4 + /// does not track it; the photons are status 1 with the pi0 as mother. + /// The Dalitz mode (~1.2%) is not simulated. + /// \return number of pi0s decayed + inline unsigned int DecayPi0sToTwoPhotons(simb::MCTruth const& in, + simb::MCTruth& out, + CLHEP::HepRandomEngine& engine) + { + CLHEP::RandFlat flat(engine); + + int nextTrackId = 0; + for (int i = 0; i < in.NParticles(); ++i) + nextTrackId = std::max(nextTrackId, in.GetParticle(i).TrackId() + 1); + + unsigned int nDecayed = 0; + for (int i = 0; i < in.NParticles(); ++i) { + simb::MCParticle const& p = in.GetParticle(i); + + if (p.PdgCode() != kPdgPi0 || p.StatusCode() != kStableFinalState) { + out.Add(p); + continue; + } + + int const id1 = nextTrackId++; + int const id2 = nextTrackId++; + + TLorentzVector const& x = p.Position(); + TLorentzVector const& P = p.Momentum(); + double const m = P.M(); // use the 4-vector mass so the photons sum exactly to P + + double const cosTheta = flat.fire(-1., 1.); + double const sinTheta = std::sqrt(std::max(0., 1. - cosTheta * cosTheta)); + double const phi = flat.fire(0., 2. * M_PI); + double const e = 0.5 * m; + TVector3 const dir(sinTheta * std::cos(phi), sinTheta * std::sin(phi), cosTheta); + + TLorentzVector p1(e * dir, e); + TLorentzVector p2(-e * dir, e); + TVector3 const boost = P.BoostVector(); + p1.Boost(boost); + p2.Boost(boost); + + out.Add(WithStatus(p, kDecayedState, {id1, id2})); + + for (auto const& [id, mom] : {std::pair{id1, p1}, std::pair{id2, p2}}) { + simb::MCParticle gamma(id, kPdgPhoton, "primary", p.TrackId(), 0.0, kStableFinalState); + gamma.AddTrajectoryPoint(x, mom); + gamma.SetGvtx(p.GetGvtx()); + out.Add(gamma); + } + ++nDecayed; + } + + CopyTruthHeader(in, out); + return nDecayed; + } + + /// Remove one final-state photon, chosen uniformly at random, from `in`. + /// If `onlyFromPi0` is set, only photons whose mother is a pi0 in the same + /// record are candidates. If there are no candidates `out` is a copy of `in`. + /// \return index (in `in`) of the deleted particle, or -1 if none + inline int DeleteOneRandomPhoton(simb::MCTruth const& in, + simb::MCTruth& out, + CLHEP::HepRandomEngine& engine, + bool onlyFromPi0 = false) + { + std::vector candidates; + for (int i = 0; i < in.NParticles(); ++i) { + simb::MCParticle const& p = in.GetParticle(i); + if (!IsFinalStatePhoton(p)) continue; + if (onlyFromPi0 && !IsPi0Daughter(in, p)) continue; + candidates.push_back(i); + } + + int deleted = -1; + if (!candidates.empty()) { + CLHEP::RandFlat flat(engine); + deleted = candidates[flat.fireInt(static_cast(candidates.size()))]; + } + + for (int i = 0; i < in.NParticles(); ++i) + if (i != deleted) out.Add(in.GetParticle(i)); + + CopyTruthHeader(in, out); + return deleted; + } + + /// Number of final-state photons; with `onlyFromPi0`, only those whose + /// mother is a pi0 (so e.g. nuclear de-excitation photons are not counted). + inline unsigned int CountFinalStatePhotons(simb::MCTruth const& truth, bool onlyFromPi0 = false) + { + unsigned int n = 0; + for (int i = 0; i < truth.NParticles(); ++i) { + simb::MCParticle const& p = truth.GetParticle(i); + if (IsFinalStatePhoton(p) && (!onlyFromPi0 || IsPi0Daughter(truth, p))) ++n; + } + return n; + } + +} // namespace sbn::singlephoton + +#endif // SBNCODE_EVENTGENERATOR_SINGLEPHOTON_PHOTONTRUTHTOOLS_H diff --git a/sbncode/EventGenerator/SinglePhoton/deletepi0photon_sbn.fcl b/sbncode/EventGenerator/SinglePhoton/deletepi0photon_sbn.fcl new file mode 100644 index 000000000..e2c75f10d --- /dev/null +++ b/sbncode/EventGenerator/SinglePhoton/deletepi0photon_sbn.fcl @@ -0,0 +1,39 @@ +# Configuration for sbn::DeletePi0Photon (DeletePi0Photon_module.cc). +# +# Run directly after GENIEGen in the gen stage. Relabel the GENIE module as +# "rawgenerator", give this module the "generator" label, and drop +# *_rawgenerator_*_* on output, e.g.: +# +# physics.producers.rawgenerator: @local::physics.producers.generator +# physics.producers.generator: @erase +# physics.filters.generator: @local::sbn_deletepi0photon +# physics.simulate: [ rns, rawgenerator, generator ] +# outputs.out1.SelectEvents: [ simulate ] +# outputs.out1.outputCommands: [ "keep *", "drop *_rawgenerator_*_*" ] +# +# For SBND see prodgenie_nu_singleinteraction_tpc_del1g_sbnd.fcl in sbndcode. +# +# The drop is required: larg4Main simulates every MCTruth collection in the +# event unless inputCollections is set. + +BEGIN_PROLOG + +sbn_deletepi0photon: +{ + module_type: "DeletePi0Photon" + InputLabel: "rawgenerator" + + DecayPi0s: true # decay status-1 pi0s -> gamma gamma (no Dalitz) + DeletePhoton: true # delete one status-1 photon at random + OnlyDeletePi0Photons: true # delete and count (RequiredNPhotons) only photons whose mother is a pi0; + # false = any final-state photon, as in the MicroBooNE sample. Tunes with + # nuclear de-excitation (e.g. AR25) produce extra MeV-scale photons. + + RequiredNPhotons: 1 # keep events with exactly this many photons (see above); -1 keeps all + ForwardDk2Nu: false # MUST be true for dk2nu fluxes (e.g. SBND G4BNB); the module throws otherwise + Verbose: false + + # Seed: +} + +END_PROLOG