LArSoft  v10_04_05
Liquid Argon Software toolkit - https://larsoft.org/
larg4::LArG4 Class Reference

Runs Geant4 simulation and propagation of electrons and photons to readout. More...

Inheritance diagram for larg4::LArG4:
art::EDProducer art::detail::Producer art::detail::LegacyModule art::Modifier art::ModuleBase art::ProductRegistryHelper

Public Types

using ModuleType = EDProducer
 
template<typename UserConfig , typename KeysToIgnore = void>
using Table = Modifier::Table< UserConfig, KeysToIgnore >
 

Public Member Functions

 LArG4 (fhicl::ParameterSet const &pset)
 
void doBeginJob (SharedResources const &resources)
 
void doEndJob ()
 
void doRespondToOpenInputFile (FileBlock const &fb)
 
void doRespondToCloseInputFile (FileBlock const &fb)
 
void doRespondToOpenOutputFiles (FileBlock const &fb)
 
void doRespondToCloseOutputFiles (FileBlock const &fb)
 
bool doBeginRun (RunPrincipal &rp, ModuleContext const &mc)
 
bool doEndRun (RunPrincipal &rp, ModuleContext const &mc)
 
bool doBeginSubRun (SubRunPrincipal &srp, ModuleContext const &mc)
 
bool doEndSubRun (SubRunPrincipal &srp, ModuleContext const &mc)
 
bool doEvent (EventPrincipal &ep, ModuleContext const &mc, std::atomic< std::size_t > &counts_run, std::atomic< std::size_t > &counts_passed, std::atomic< std::size_t > &counts_failed)
 
void fillProductDescriptions ()
 
void registerProducts (ProductDescriptions &productsToRegister)
 
ModuleDescription const & moduleDescription () const
 
void setModuleDescription (ModuleDescription const &)
 
std::array< std::vector< ProductInfo >, NumBranchTypes > const & getConsumables () const
 
void sortConsumables (std::string const &current_process_name)
 
std::unique_ptr< Worker > makeWorker (WorkerParams const &wp)
 
template<typename T , BranchType BT>
ViewToken< T > consumesView (InputTag const &tag)
 
template<typename T , BranchType BT>
ViewToken< T > mayConsumeView (InputTag const &tag)
 

Protected Member Functions

ConsumesCollector & consumesCollector ()
 
template<typename T , BranchType = InEvent>
ProductToken< T > consumes (InputTag const &)
 
template<typename Element , BranchType = InEvent>
ViewToken< Element > consumesView (InputTag const &)
 
template<typename T , BranchType = InEvent>
void consumesMany ()
 
template<typename T , BranchType = InEvent>
ProductToken< T > mayConsume (InputTag const &)
 
template<typename Element , BranchType = InEvent>
ViewToken< Element > mayConsumeView (InputTag const &)
 
template<typename T , BranchType = InEvent>
void mayConsumeMany ()
 

Private Member Functions

void produce (art::Event &evt) override
 
void beginJob () override
 
void beginRun (art::Run &run) override
 
std::unique_ptr< util::PositionInVolumeFilterCreateParticleVolumeFilter (std::set< std::string > const &vol_names) const
 Pointer used for correctly updating the clock data state. More...
 

Private Attributes

std::unique_ptr< g4b::G4HelperfG4Help {nullptr}
 G4 interface object. More...
 
larg4::ParticleListActionfparticleListAction
 Geant4 user action to particle information. More...
 
std::string fG4PhysListName
 predefined physics list to use if not making a custom one More...
 
std::string fG4MacroPath
 
bool fCheckOverlaps
 Whether to use the G4 overlap checker. More...
 
bool fMakeMCParticles
 Whether to keep a sim::MCParticle list. More...
 
bool fStoreDroppedMCParticles
 Whether to keep a sim::MCParticleLite list of dropped particles. More...
 
bool fdumpParticleList
 Whether each event's sim::ParticleList will be displayed. More...
 
bool fdumpSimChannels
 Whether each event's sim::Channel will be displayed. More...
 
bool fUseLitePhotons
 
bool fStoreReflected {false}
 
int fSmartStacking
 Whether to instantiate and use class to. More...
 
double fOffPlaneMargin = 0.
 
std::vector< std::string > fInputLabels
 
std::vector< std::string > fKeepParticlesInVolumes
 Only write particles that have trajectories through these volumes. More...
 
bool fSparsifyTrajectories
 Sparsify MCParticle Trajectories. More...
 
CLHEP::HepRandomEngine & fEngine
 
detinfo::DetectorPropertiesData fDetProp
 Must outlive fAllPhysicsLists! More...
 
AllPhysicsLists fAllPhysicsLists
 
LArVoxelReadoutGeometryfVoxelReadoutGeometry
 

Detailed Description

Runs Geant4 simulation and propagation of electrons and photons to readout.

This module collects generated particles from one or more generators and processes them through Geant4.

Input

The module reads the particles to process from simb::MCTruth records. Each particle generator is required to produce a vector of such records: std::vector<simb::MCTruth>.

The module allows two operation modes:

  1. process specific generators: the label of the generator modules to be processed is specified explicitly in LArG4 configuration
  2. process all truth information generated so far: no generator is specified in the LArG4 module configuration, and the module will process all data products of type std::vector<simb::MCTruth>, in a non-specified order

For each simb::MCTruth, a Geant4 run is started. The interface with Geant4 is via a helper class provided by nug4. Only the particles in the truth record which have status code (simb::MCParticle::StatusCode()) equal to 1 are processed. These particles are called, in LArG4 jargon, primaries.

Output

The LArG4 module produces:

  • a collection of sim::SimChannel: each sim::SimChannel represents the set of energy depositions in liquid argon which drifted and were observed on a certain channel; it includes physics effects like attenuation, diffusion, electric field distortion, etc. Information of the generating Geant4 "track" is retained;
  • a collection of sim::SimPhotons or sim::SimPhotonsLite: each sim::SimPhotons represents the set of individual photons reaching a channel of the optical detector; it includes physics effects as well as quantum efficiency of the detector (to reduce data size early in the process); sim::SimPhotonsLite drops the information of the single photons and stores only collective information (e.g. their number).
  • a collection of sim::OpDetBacktrackerRecord (to be documented)
  • a collection of sim::AuxDetSimChannel (to be documented)
  • a collection of simb::MCParticle: the particles generated in the interaction of the primary particles with the material in the world are stored, but minor filtering by geometry and by physics is possible. An association of them with the originating simb::MCTruth object is also produced.

Notes on the conventions

  • all and the particles in the truth record (simb::MCTruth) which have status code (simb::MCParticle::StatusCode()) equal to 1 are passed to Geant4. These particles are called, in LArG4 jargon, primaries. The interface with Geant4 is via a helper class provided by nug4.
  • normally, information about each particle that Geant4 propagates (which Geant4 calls tracks), primary or not, is saved as an individual simb::MCParticle object into the output particle list. Each simb::MCParticle includes a Geant4-like track ID which is also recorded into each sim::IDE deposited by that particle. This information can be used to track all the deposition from a particle, or to backtrack the particle responsible of a deposition (but see below...). Note that the stored track ID may be different than the one Geant4 used (and, in particular, it's guaranteed to be unique within a sim::LArG4 instance output).
  • there are options (some set in sim::LArG4Parameters service) which allow for Geant4 tracks not to be saved as simb::MCParticle (e.g. ParticleKineticEnergyCut, KeepEMShowerDaughters). When these particles have deposited energy, their sim::IDE will report the ID of the first parent Geant4 track which is saved in the simb::MCParticle list, but with its sign flipped. Therefore, when tracking or backtracking (see above), comparisons should be performed using the absolute value of the sim::IDE (e.g. std::abs(ide.trackID)).

Timing

The LArG4 module produces sim::SimChannel objects from generated simb::MCParticle. Each particle ("primary") is assigned the time taken from its vertex (a 4-vector), which is expected to be represented in nanoseconds. The sim::SimChannel object is a collection of sim::IDE in time. The position in the sim::IDE is the location where some ionization occurred. The time associated to a sim::IDE is stored in tick units. The time it represents is the time when the ionization happened, which is the time of the primary particle plus the propagation time to the ionization location, plus the drift time, which the ionized electrons take to reach the anode wire. This time is then shifted to the frame of the electronics time via detinfo::DetectorClocks::G4ToElecTime(), which adds a configurable time offset. The time is converted into ticks via detinfo::DetectorClocks::TPCClock(), and this is the final value associated to the sim::IDE. For a more complete overview, see https://cdcvs.fnal.gov/redmine/projects/larsoft/wiki/Simulation#Simulation-Timing

Randomness

The random number generators used by this process are:

  • 'GEANT' instance: used by Geant4
  • 'propagation' instance: used in electron propagation

Configuration parameters

  • G4PhysListName (string, default: "larg4::PhysicsList"): whether to use the G4 overlap checker, which catches different issues than ROOT
  • CheckOverlaps (bool, default: false): whether to use the G4 overlap checker
  • DumpParticleList (bool, default: false): whether to print all MCParticles tracked; requires MakeMCParticles being true
  • DumpSimChannels (bool, default: false): whether to print all depositions on each SimChannel
  • SmartStacking (int, default: 0): whether to use class to dictate how tracks are put on stack (nonzero is on)
  • MakeMCParticles (flag, default: true): keep a list of the particles seen in the detector, and eventually save it; you almost always want this on
  • KeepParticlesInVolumes (list of strings, default: empty): list of volumes in which to keep simb::MCParticle objects (empty keeps all); requires MakeMCParticles being true
  • GeantCommandFile (string, required): G4 macro file to pass to G4Helper for setting G4 command
  • Seed (integer, not defined by default): if defined, override the seed for random number generator used in Geant4 simulation (which is obtained from NuRandomService by default)
  • PropagationSeed (integer, not defined by default): if defined, override the seed for the random generator used for electrons propagation to the wire planes (obtained from the NuRandomService by default)
  • InputLabels (list of strings, default: process all truth): optional list of generator labels whose produced simb::MCTruth will be simulated; if not specified, all simb::MCTruth vector data products are simulated
  • ChargeRecoveryMargin (double, default: 0): sets the maximum distance from a plane for the wire charge recovery to occur, in centimeters; for details on how it works, see larg4::LArVoxelReadout::SetOffPlaneChargeRecoveryMargin(). A value of 0 effectively disables this feature. All TPCs will have the same margin applied.

Simulation details

Source of the operational parameters

Some of the physical properties have their values set in FHiCL configuration (e.g. detinfo::LArParameters). Then, GEANT4 is informed of them via larg4::MaterialPropertyLoader. The material property table in GEANT4 is then used by other LArSoft components to discover the parameter values.

Among the parameters registered to GEANT4, the scintillation yields, i.e. how many scintillation photons are produced on average by 1 MeV of deposited energy, are also stored by type of ioniziong particle. These scintillation yields do include a prescale factor (that may include, for example, the photomultiplier quantum efficiency), from the ScintPreScale parameter of detinfo::LArPropertiesStandard or equivalent.

Reflectivity to optical photons

Two models are supported for the simulation of (scintillation) light crossing detector surfaces:

  1. the standard one from GEANT4, implemented in G4OpBoundaryProcess
  2. a simplified one, implemented in larg4::OpBoundaryProcessSimple

The model is chosen according to the value of detinfo::DetectorProperties::SimpleBoundary(), and the choice is currently exerted by larg4::OpticalPhysics.

The simplified model is faster and simpler: it only deals with absorption and reflection (both specular and diffues). This is the "default" model used in most contexts.

GEANT4 model is more complete and slower. It may take some art to fully configure all the properties of the materials at the sides of the surfaces. The price is a detailed simulation that includes among others refraction and wavelength shifting.

Scintillation

When using the fast optical simulation, which is the "standard" running mode, energy depositions from GEANT4 are "converted" into a number of scintillation photons by the global larg4::IonizationAndScintillation object instance, which internally utilizes the algorithm set up via configuration parameter IonAndScintCalculator in LArG4Parameters service (at the time of writing, "Separate" is supported and "NEST" is accepted too).

The number of scintillation photons per energy unit is read from GEANT4 material properties table. It includes already quantum efficiency ("prescale") and it may depend on the type of ionizing particle, depending on the configuration (LArPropertiesStandard parameter ScintByParticleType). This value ("yield") is used as the average of a Poisson distribution from which the actual number of scintillation photons is extracted case by case. The implementation larg4::ISCalculationSeparate may also include medium saturation effects as well, if configured, but only if the scintillation yield is set not to depend on the type of ionizing particle. The number of scintillation photons is then distributed between the fast and slow component by a yield ratio also set in the material parameters, and the single photons are distributed in time accordingly to their component.

Definition at line 304 of file LArG4_module.cc.

Member Typedef Documentation

Definition at line 17 of file EDProducer.h.

template<typename UserConfig , typename KeysToIgnore = void>
using art::detail::Producer::Table = Modifier::Table<UserConfig, KeysToIgnore>
inherited

Definition at line 26 of file Producer.h.

Constructor & Destructor Documentation

larg4::LArG4::LArG4 ( fhicl::ParameterSet const &  pset)
explicit

Definition at line 392 of file LArG4_module.cc.

References art::errors::Configuration, art::detail::EngineCreator::createEngine(), e, fAllPhysicsLists, fCheckOverlaps, fDetProp, fdumpParticleList, fdumpSimChannels, fEngine, fG4MacroPath, fG4PhysListName, sim::LArG4Parameters::FillSimEnergyDeposits(), fInputLabels, fKeepParticlesInVolumes, fMakeMCParticles, fOffPlaneMargin, fSmartStacking, fSparsifyTrajectories, fStoreDroppedMCParticles, fStoreReflected, fUseLitePhotons, MF_LOG_DEBUG, sim::LArG4Parameters::NoElectronPropagation(), sim::LArG4Parameters::NoPhotonPropagation(), art::ProductRegistryHelper::produces(), art::errors::ServiceNotFound, phot::PhotonVisibilityService::StoreReflected(), and sim::LArG4Parameters::UseLitePhotons().

393  : art::EDProducer{pset}
394  , fG4PhysListName(pset.get<std::string>("G4PhysListName", "larg4::PhysicsList"))
395  , fCheckOverlaps(pset.get<bool>("CheckOverlaps", false))
396  , fMakeMCParticles(pset.get<bool>("MakeMCParticles", true))
397  , fStoreDroppedMCParticles(pset.get<bool>("StoreDroppedMCParticles", false))
398  , fdumpParticleList(pset.get<bool>("DumpParticleList", false))
399  , fdumpSimChannels(pset.get<bool>("DumpSimChannels", false))
400  , fSmartStacking(pset.get<int>("SmartStacking", 0))
401  , fOffPlaneMargin(pset.get<double>("ChargeRecoveryMargin", 0.0))
402  , fKeepParticlesInVolumes(pset.get<std::vector<std::string>>("KeepParticlesInVolumes", {}))
403  , fSparsifyTrajectories(pset.get<bool>("SparsifyTrajectories", false))
404  , fEngine(art::ServiceHandle<rndm::NuRandomService>()->registerAndSeedEngine(
405  createEngine(0, "HepJamesRandom", "propagation"),
406  "HepJamesRandom",
407  "propagation",
408  pset,
409  "PropagationSeed"))
412  {
413  MF_LOG_DEBUG("LArG4") << "Debug: LArG4()";
414 
415  if (!fMakeMCParticles) { // configuration option consistency
416  if (fdumpParticleList) {
418  << "Option `DumpParticleList` can't be set if `MakeMCParticles` is unset.\n";
419  }
420  if (!fKeepParticlesInVolumes.empty()) {
422  << "Option `KeepParticlesInVolumes` can't be set if `MakeMCParticles` is unset.\n";
423  }
424  } // if
425 
426  if (pset.has_key("Seed")) {
428  << "The configuration of LArG4 module has the discontinued 'Seed' parameter.\n"
429  "Seeds are now controlled by two parameters: 'GEANTSeed' and 'PropagationSeed'.";
430  }
431  // setup the random number service for Geant4, the "G4Engine" label is a special tag
432  // setting up a global engine for use by Geant4/CLHEP; obtain the random seed from
433  // NuRandomService, unless overridden in configuration with key "Seed" or "GEANTSeed"
434  // FIXME: THIS APPEARS TO BE A NO-OP; IS IT NEEDED?
435  (void)art::ServiceHandle<rndm::NuRandomService>()->registerAndSeedEngine(
436  createEngine(0, "G4Engine", "GEANT"), "G4Engine", "GEANT", pset, "GEANTSeed");
437 
438  // get a list of generators to use, otherwise, we'll end up looking for anything
439  // that's made an MCTruth object
440  bool useInputLabels =
441  pset.get_if_present<std::vector<std::string>>("InputLabels", fInputLabels);
442  if (!useInputLabels) fInputLabels.resize(0);
443 
446 
447  if (!lgp->NoPhotonPropagation()) {
448  try {
451  }
452  catch (art::Exception const& e) {
453  // If the service is not configured, then just keep the default false for
454  // reflected light. If reflected photons are simulated without PVS they will show
455  // up in the regular SimPhotons collection
456  if (e.categoryCode() != art::errors::ServiceNotFound) throw;
457  }
458 
459  if (!fUseLitePhotons) {
460  produces<std::vector<sim::SimPhotons>>();
461  if (fStoreReflected) { produces<std::vector<sim::SimPhotons>>("Reflected"); }
462  }
463  else {
464  produces<std::vector<sim::SimPhotonsLite>>();
465  produces<std::vector<sim::OpDetBacktrackerRecord>>();
466  if (fStoreReflected) {
467  produces<std::vector<sim::SimPhotonsLite>>("Reflected");
468  produces<std::vector<sim::OpDetBacktrackerRecord>>("Reflected");
469  }
470  }
471  }
472 
473  if (lgp->FillSimEnergyDeposits()) {
474  produces<std::vector<sim::SimEnergyDeposit>>("TPCActive");
475  produces<std::vector<sim::SimEnergyDeposit>>("Other");
476  }
477 
478  if (fMakeMCParticles) {
479  produces<std::vector<simb::MCParticle>>();
480  produces<art::Assns<simb::MCTruth, simb::MCParticle, sim::GeneratedParticleInfo>>();
481  }
482  if (fStoreDroppedMCParticles) { produces<std::vector<sim::MCParticleLite>>(); }
483  if (!lgp->NoElectronPropagation()) produces<std::vector<sim::SimChannel>>();
484  produces<std::vector<sim::AuxDetSimChannel>>();
485 
486  // constructor decides if initialized value is a path or an environment variable
487  cet::search_path sp("FW_SEARCH_PATH");
488 
489  sp.find_file(pset.get<std::string>("GeantCommandFile"), fG4MacroPath);
490  struct stat sb;
491  if (fG4MacroPath.empty() || stat(fG4MacroPath.c_str(), &sb) != 0)
492  // failed to resolve the file name
493  throw cet::exception("NoG4Macro") << "G4 macro file " << fG4MacroPath << " not found!\n";
494  }
std::vector< std::string > fInputLabels
base_engine_t & createEngine(seed_t seed)
bool fStoreDroppedMCParticles
Whether to keep a sim::MCParticleLite list of dropped particles.
std::string fG4MacroPath
void produces(std::string const &instanceName={}, Persistable const persistable=Persistable::Yes)
bool fMakeMCParticles
Whether to keep a sim::MCParticle list.
bool NoPhotonPropagation() const
std::vector< std::string > fKeepParticlesInVolumes
Only write particles that have trajectories through these volumes.
bool fSparsifyTrajectories
Sparsify MCParticle Trajectories.
int fSmartStacking
Whether to instantiate and use class to.
bool fdumpSimChannels
Whether each event&#39;s sim::Channel will be displayed.
bool NoElectronPropagation() const
bool FillSimEnergyDeposits() const
bool fdumpParticleList
Whether each event&#39;s sim::ParticleList will be displayed.
cet::coded_exception< errors::ErrorCodes, ExceptionDetail::translate > Exception
Definition: Exception.h:66
bool fUseLitePhotons
#define MF_LOG_DEBUG(id)
std::string fG4PhysListName
predefined physics list to use if not making a custom one
bool fCheckOverlaps
Whether to use the G4 overlap checker.
bool fStoreReflected
AllPhysicsLists fAllPhysicsLists
detinfo::DetectorPropertiesData fDetProp
Must outlive fAllPhysicsLists!
Float_t e
Definition: plot.C:35
CLHEP::HepRandomEngine & fEngine
double fOffPlaneMargin
cet::coded_exception< error, detail::translate > exception
Definition: exception.h:33
bool UseLitePhotons() const

Member Function Documentation

void larg4::LArG4::beginJob ( )
overrideprivatevirtual

Reimplemented from art::EDProducer.

Definition at line 497 of file LArG4_module.cc.

References g4b::UserActionManager::AddAndAdoptAction(), larg4::IonizationAndScintillation::CreateInstance(), geo::GeometryCore::Cryostat(), fCheckOverlaps, fEngine, fG4Help, fG4MacroPath, fG4PhysListName, fMakeMCParticles, fOffPlaneMargin, fparticleListAction, fSmartStacking, fStoreDroppedMCParticles, fUseLitePhotons, fVoxelReadoutGeometry, geo::GeometryCore::GDMLFile(), Get, art::ServiceHandle< T, SCOPE >::get(), larg4::MaterialPropertyLoader::GetPropertiesFromServices(), g4b::UserActionManager::Instance(), sim::LArG4Parameters::KeepEMShowerDaughters(), geo::CryostatGeo::OpDetGeoName(), sim::LArG4Parameters::ParticleKineticEnergyCut(), sim::LArG4Parameters::StoreTrajectories(), and larg4::MaterialPropertyLoader::UpdateGeometry().

498  {
499  fG4Help = std::make_unique<g4b::G4Helper>(fG4MacroPath, fG4PhysListName);
500 
501  if (fCheckOverlaps) fG4Help->SetOverlapCheck(true);
502 
504  fG4Help->ConstructDetector(geom->GDMLFile());
505  auto const& wireReadoutGeom = art::ServiceHandle<geo::WireReadout const>()->Get();
506 
507  // Get the logical volume store and assign material properties
509  auto const detProp =
511  mpl.GetPropertiesFromServices(detProp);
512  mpl.UpdateGeometry(G4LogicalVolumeStore::GetInstance());
513 
514  // Tell the detector about the parallel LAr voxel geometry.
515  std::vector<G4VUserParallelWorld*> pworlds;
516 
517  // Intialize G4 physics and primary generator action
518  fG4Help->InitPhysics();
519 
520  // create the ionization and scintillation calculator; this is a singleton (!) so it
521  // does not make sense to create it in LArVoxelReadoutGeometry
523 
524  // make a parallel world for each TPC in the detector
525  // User-action class for accumulating LAr voxels.
527 
528  LArVoxelReadoutGeometry::Setup_t readoutGeomSetupData{
529  geom.get(), &wireReadoutGeom, lgp.get(), {&fEngine, fOffPlaneMargin}};
530 
532  new LArVoxelReadoutGeometry("LArVoxelReadoutGeometry", readoutGeomSetupData);
533  pworlds.push_back(fVoxelReadoutGeometry);
534  pworlds.push_back(new OpDetReadoutGeometry(
535  geom->Cryostat().OpDetGeoName(), "OpDetReadoutGeometry", fUseLitePhotons));
536  pworlds.push_back(new AuxDetReadoutGeometry(
537  art::ServiceHandle<geo::AuxDetGeometry const>()->GetProviderPtr(), "AuxDetReadoutGeometry"));
538 
539  fG4Help->SetParallelWorlds(pworlds);
540 
541  // Intialize G4 physics and primary generator action
542  fG4Help->InitPhysics();
543 
544  // Use the UserActionManager to handle all the Geant4 user hooks.
546 
547  // User-action class for accumulating particles and trajectories produced in the
548  // detector.
550  lgp->StoreTrajectories(),
551  lgp->KeepEMShowerDaughters(),
555 
556  // UserActionManager is now configured so continue G4 initialization
557  fG4Help->SetUserAction();
558 
559  // With an enormous detector with lots of rock ala LAr34 (nee LAr20) we need to be
560  // smarter about stacking.
561  if (fSmartStacking > 0) {
562  G4UserStackingAction* stacking_action = new LArStackingAction(fSmartStacking);
563  fG4Help->GetRunManager()->SetUserAction(stacking_action);
564  }
565  }
std::unique_ptr< g4b::G4Helper > fG4Help
G4 interface object.
bool fStoreDroppedMCParticles
Whether to keep a sim::MCParticleLite list of dropped particles.
bool KeepEMShowerDaughters() const
std::string fG4MacroPath
T * get() const
Definition: ServiceHandle.h:69
Stores material properties and sends them to GEANT4 geometry.
void GetPropertiesFromServices(detinfo::DetectorPropertiesData const &detProp)
Imports properties from LArSoft services.
bool fMakeMCParticles
Whether to keep a sim::MCParticle list.
cout<< "Opened file "<< fin<< " ixs= "<< ixs<< endl;if(ixs==0) hhh=(TH1F *) fff-> Get("h1")
Definition: AddMC.C:8
bool StoreTrajectories() const
int fSmartStacking
Whether to instantiate and use class to.
larg4::ParticleListAction * fparticleListAction
Geant4 user action to particle information.
std::string OpDetGeoName() const
Get name of opdet geometry element.
Definition: CryostatGeo.h:333
static void AddAndAdoptAction(UserAction *a)
CryostatGeo const & Cryostat(CryostatID const &cryoid=details::cryostat_zero) const
Returns the specified cryostat.
void UpdateGeometry(G4LogicalVolumeStore *lvs)
Updates the material properties with the collected values.
double ParticleKineticEnergyCut() const
static UserActionManager * Instance()
bool fUseLitePhotons
static IonizationAndScintillation * CreateInstance(detinfo::DetectorPropertiesData const &detProp, CLHEP::HepRandomEngine &engine)
std::string fG4PhysListName
predefined physics list to use if not making a custom one
std::string const & GDMLFile() const
Returns the full directory path to the GDML file source.
Definition: GeometryCore.h:130
bool fCheckOverlaps
Whether to use the G4 overlap checker.
CLHEP::HepRandomEngine & fEngine
double fOffPlaneMargin
LArVoxelReadoutGeometry * fVoxelReadoutGeometry
void larg4::LArG4::beginRun ( art::Run run)
overrideprivatevirtual

Reimplemented from art::EDProducer.

Definition at line 567 of file LArG4_module.cc.

References CreateParticleVolumeFilter(), fKeepParticlesInVolumes, fparticleListAction, and larg4::ParticleListAction::ParticleFilter().

568  {
569  // prepare the filter object (null if no filtering)
570  std::set<std::string> volnameset(fKeepParticlesInVolumes.begin(),
573  }
std::vector< std::string > fKeepParticlesInVolumes
Only write particles that have trajectories through these volumes.
larg4::ParticleListAction * fparticleListAction
Geant4 user action to particle information.
void ParticleFilter(std::unique_ptr< util::PositionInVolumeFilter > &&filter)
Grabs a particle filter.
std::unique_ptr< util::PositionInVolumeFilter > CreateParticleVolumeFilter(std::set< std::string > const &vol_names) const
Pointer used for correctly updating the clock data state.
template<typename T , BranchType BT>
ProductToken< T > art::ModuleBase::consumes ( InputTag const &  tag)
protectedinherited

Definition at line 61 of file ModuleBase.h.

References art::ModuleBase::collector_, and art::ConsumesCollector::consumes().

62  {
63  return collector_.consumes<T, BT>(tag);
64  }
ConsumesCollector collector_
Definition: ModuleBase.h:56
ProductToken< T > consumes(InputTag const &)
ConsumesCollector & art::ModuleBase::consumesCollector ( )
protectedinherited

Definition at line 57 of file ModuleBase.cc.

References art::ModuleBase::collector_.

58  {
59  return collector_;
60  }
ConsumesCollector collector_
Definition: ModuleBase.h:56
template<typename T , BranchType BT>
void art::ModuleBase::consumesMany ( )
protectedinherited

Definition at line 75 of file ModuleBase.h.

References art::ModuleBase::collector_, and art::ConsumesCollector::consumesMany().

76  {
77  collector_.consumesMany<T, BT>();
78  }
ConsumesCollector collector_
Definition: ModuleBase.h:56
template<typename Element , BranchType = InEvent>
ViewToken<Element> art::ModuleBase::consumesView ( InputTag const &  )
protectedinherited
template<typename T , BranchType BT>
ViewToken<T> art::ModuleBase::consumesView ( InputTag const &  tag)
inherited

Definition at line 68 of file ModuleBase.h.

References art::ModuleBase::collector_, and art::ConsumesCollector::consumesView().

69  {
70  return collector_.consumesView<T, BT>(tag);
71  }
ConsumesCollector collector_
Definition: ModuleBase.h:56
ViewToken< Element > consumesView(InputTag const &)
std::unique_ptr< util::PositionInVolumeFilter > larg4::LArG4::CreateParticleVolumeFilter ( std::set< std::string > const &  vol_names) const
private

Pointer used for correctly updating the clock data state.

Configures and returns a particle filter

Definition at line 575 of file LArG4_module.cc.

References util::empty().

Referenced by beginRun().

577  {
578  // if we don't have favourite volumes, don't even bother creating a filter
579  if (empty(vol_names)) return {};
580 
581  auto const& geom = *art::ServiceHandle<geo::Geometry const>();
582 
583  std::vector<std::vector<TGeoNode const*>> node_paths = geom.FindAllVolumePaths(vol_names);
584 
585  // collection of interesting volumes
587  GeoVolumePairs.reserve(node_paths.size()); // because we are obsessed
588 
589  //for each interesting volume, follow the node path and collect
590  //total rotations and translations
591  for (size_t iVolume = 0; iVolume < node_paths.size(); ++iVolume) {
592  std::vector<TGeoNode const*> path = node_paths[iVolume];
593 
594  auto pTransl = new TGeoTranslation(0., 0., 0.);
595  auto pRot = new TGeoRotation();
596  for (TGeoNode const* node : path) {
597  TGeoTranslation thistranslate(*node->GetMatrix());
598  TGeoRotation thisrotate(*node->GetMatrix());
599  pTransl->Add(&thistranslate);
600  *pRot = *pRot * thisrotate;
601  }
602 
603  // for some reason, pRot and pTransl don't have tr and rot bits set correctly make
604  // new translations and rotations so bits are set correctly
605  auto pTransl2 = new TGeoTranslation(
606  pTransl->GetTranslation()[0], pTransl->GetTranslation()[1], pTransl->GetTranslation()[2]);
607  double phi = 0., theta = 0., psi = 0.;
608  pRot->GetAngles(phi, theta, psi);
609  auto pRot2 = new TGeoRotation();
610  pRot2->SetAngles(phi, theta, psi);
611 
612  auto pTransf = new TGeoCombiTrans(*pTransl2, *pRot2);
613  GeoVolumePairs.emplace_back(node_paths[iVolume].back()->GetVolume(), pTransf);
614  }
615 
616  return std::make_unique<util::PositionInVolumeFilter>(std::move(GeoVolumePairs));
617  } // CreateParticleVolumeFilter()
std::vector< VolumeInfo_t > AllVolumeInfo_t
decltype(auto) constexpr empty(T &&obj)
ADL-aware version of std::empty.
Definition: StdUtils.h:109
void art::detail::Producer::doBeginJob ( SharedResources const &  resources)
inherited

Definition at line 22 of file Producer.cc.

References art::detail::Producer::beginJobWithFrame(), and art::detail::Producer::setupQueues().

23  {
24  setupQueues(resources);
25  ProcessingFrame const frame{ScheduleID{}};
26  beginJobWithFrame(frame);
27  }
virtual void setupQueues(SharedResources const &)=0
virtual void beginJobWithFrame(ProcessingFrame const &)=0
bool art::detail::Producer::doBeginRun ( RunPrincipal rp,
ModuleContext const &  mc 
)
inherited

Definition at line 65 of file Producer.cc.

References art::detail::Producer::beginRunWithFrame(), art::RangeSet::forRun(), art::RunPrincipal::makeRun(), r, art::RunPrincipal::runID(), and art::ModuleContext::scheduleID().

66  {
67  auto r = rp.makeRun(mc, RangeSet::forRun(rp.runID()));
68  ProcessingFrame const frame{mc.scheduleID()};
69  beginRunWithFrame(r, frame);
70  r.commitProducts();
71  return true;
72  }
TRandom r
Definition: spectrum.C:23
virtual void beginRunWithFrame(Run &, ProcessingFrame const &)=0
static RangeSet forRun(RunID)
Definition: RangeSet.cc:51
bool art::detail::Producer::doBeginSubRun ( SubRunPrincipal srp,
ModuleContext const &  mc 
)
inherited

Definition at line 85 of file Producer.cc.

References art::detail::Producer::beginSubRunWithFrame(), art::RangeSet::forSubRun(), art::SubRunPrincipal::makeSubRun(), art::ModuleContext::scheduleID(), and art::SubRunPrincipal::subRunID().

86  {
87  auto sr = srp.makeSubRun(mc, RangeSet::forSubRun(srp.subRunID()));
88  ProcessingFrame const frame{mc.scheduleID()};
89  beginSubRunWithFrame(sr, frame);
90  sr.commitProducts();
91  return true;
92  }
virtual void beginSubRunWithFrame(SubRun &, ProcessingFrame const &)=0
static RangeSet forSubRun(SubRunID)
Definition: RangeSet.cc:57
void art::detail::Producer::doEndJob ( )
inherited

Definition at line 30 of file Producer.cc.

References art::detail::Producer::endJobWithFrame().

31  {
32  ProcessingFrame const frame{ScheduleID{}};
33  endJobWithFrame(frame);
34  }
virtual void endJobWithFrame(ProcessingFrame const &)=0
bool art::detail::Producer::doEndRun ( RunPrincipal rp,
ModuleContext const &  mc 
)
inherited

Definition at line 75 of file Producer.cc.

References art::detail::Producer::endRunWithFrame(), art::RunPrincipal::makeRun(), r, art::ModuleContext::scheduleID(), and art::Principal::seenRanges().

76  {
77  auto r = rp.makeRun(mc, rp.seenRanges());
78  ProcessingFrame const frame{mc.scheduleID()};
79  endRunWithFrame(r, frame);
80  r.commitProducts();
81  return true;
82  }
TRandom r
Definition: spectrum.C:23
virtual void endRunWithFrame(Run &, ProcessingFrame const &)=0
bool art::detail::Producer::doEndSubRun ( SubRunPrincipal srp,
ModuleContext const &  mc 
)
inherited

Definition at line 95 of file Producer.cc.

References art::detail::Producer::endSubRunWithFrame(), art::SubRunPrincipal::makeSubRun(), art::ModuleContext::scheduleID(), and art::Principal::seenRanges().

96  {
97  auto sr = srp.makeSubRun(mc, srp.seenRanges());
98  ProcessingFrame const frame{mc.scheduleID()};
99  endSubRunWithFrame(sr, frame);
100  sr.commitProducts();
101  return true;
102  }
virtual void endSubRunWithFrame(SubRun &, ProcessingFrame const &)=0
bool art::detail::Producer::doEvent ( EventPrincipal ep,
ModuleContext const &  mc,
std::atomic< std::size_t > &  counts_run,
std::atomic< std::size_t > &  counts_passed,
std::atomic< std::size_t > &  counts_failed 
)
inherited

Definition at line 105 of file Producer.cc.

References art::detail::Producer::checkPutProducts_, e, art::EventPrincipal::makeEvent(), art::detail::Producer::produceWithFrame(), and art::ModuleContext::scheduleID().

110  {
111  auto e = ep.makeEvent(mc);
112  ++counts_run;
113  ProcessingFrame const frame{mc.scheduleID()};
114  produceWithFrame(e, frame);
115  e.commitProducts(checkPutProducts_, &expectedProducts<InEvent>());
116  ++counts_passed;
117  return true;
118  }
bool const checkPutProducts_
Definition: Producer.h:70
Float_t e
Definition: plot.C:35
virtual void produceWithFrame(Event &, ProcessingFrame const &)=0
void art::detail::Producer::doRespondToCloseInputFile ( FileBlock const &  fb)
inherited

Definition at line 44 of file Producer.cc.

References art::detail::Producer::respondToCloseInputFileWithFrame().

45  {
46  ProcessingFrame const frame{ScheduleID{}};
48  }
virtual void respondToCloseInputFileWithFrame(FileBlock const &, ProcessingFrame const &)=0
TFile fb("Li6.root")
void art::detail::Producer::doRespondToCloseOutputFiles ( FileBlock const &  fb)
inherited

Definition at line 58 of file Producer.cc.

References art::detail::Producer::respondToCloseOutputFilesWithFrame().

59  {
60  ProcessingFrame const frame{ScheduleID{}};
62  }
virtual void respondToCloseOutputFilesWithFrame(FileBlock const &, ProcessingFrame const &)=0
TFile fb("Li6.root")
void art::detail::Producer::doRespondToOpenInputFile ( FileBlock const &  fb)
inherited

Definition at line 37 of file Producer.cc.

References art::detail::Producer::respondToOpenInputFileWithFrame().

38  {
39  ProcessingFrame const frame{ScheduleID{}};
41  }
virtual void respondToOpenInputFileWithFrame(FileBlock const &, ProcessingFrame const &)=0
TFile fb("Li6.root")
void art::detail::Producer::doRespondToOpenOutputFiles ( FileBlock const &  fb)
inherited

Definition at line 51 of file Producer.cc.

References art::detail::Producer::respondToOpenOutputFilesWithFrame().

52  {
53  ProcessingFrame const frame{ScheduleID{}};
55  }
virtual void respondToOpenOutputFilesWithFrame(FileBlock const &, ProcessingFrame const &)=0
TFile fb("Li6.root")
void art::Modifier::fillProductDescriptions ( )
inherited

Definition at line 10 of file Modifier.cc.

References art::ProductRegistryHelper::fillDescriptions(), and art::ModuleBase::moduleDescription().

11  {
13  }
void fillDescriptions(ModuleDescription const &md)
ModuleDescription const & moduleDescription() const
Definition: ModuleBase.cc:13
std::array< std::vector< ProductInfo >, NumBranchTypes > const & art::ModuleBase::getConsumables ( ) const
inherited

Definition at line 43 of file ModuleBase.cc.

References art::ModuleBase::collector_, and art::ConsumesCollector::getConsumables().

44  {
45  return collector_.getConsumables();
46  }
ConsumesCollector collector_
Definition: ModuleBase.h:56
std::array< std::vector< ProductInfo >, NumBranchTypes > const & getConsumables() const
std::unique_ptr< Worker > art::ModuleBase::makeWorker ( WorkerParams const &  wp)
inherited

Definition at line 37 of file ModuleBase.cc.

References art::ModuleBase::doMakeWorker(), and art::NumBranchTypes.

38  {
39  return doMakeWorker(wp);
40  }
virtual std::unique_ptr< Worker > doMakeWorker(WorkerParams const &wp)=0
template<typename T , BranchType BT>
ProductToken< T > art::ModuleBase::mayConsume ( InputTag const &  tag)
protectedinherited

Definition at line 82 of file ModuleBase.h.

References art::ModuleBase::collector_, and art::ConsumesCollector::mayConsume().

83  {
84  return collector_.mayConsume<T, BT>(tag);
85  }
ProductToken< T > mayConsume(InputTag const &)
ConsumesCollector collector_
Definition: ModuleBase.h:56
template<typename T , BranchType BT>
void art::ModuleBase::mayConsumeMany ( )
protectedinherited

Definition at line 96 of file ModuleBase.h.

References art::ModuleBase::collector_, and art::ConsumesCollector::mayConsumeMany().

97  {
98  collector_.mayConsumeMany<T, BT>();
99  }
ConsumesCollector collector_
Definition: ModuleBase.h:56
template<typename Element , BranchType = InEvent>
ViewToken<Element> art::ModuleBase::mayConsumeView ( InputTag const &  )
protectedinherited
template<typename T , BranchType BT>
ViewToken<T> art::ModuleBase::mayConsumeView ( InputTag const &  tag)
inherited

Definition at line 89 of file ModuleBase.h.

References art::ModuleBase::collector_, and art::ConsumesCollector::mayConsumeView().

90  {
91  return collector_.mayConsumeView<T, BT>(tag);
92  }
ConsumesCollector collector_
Definition: ModuleBase.h:56
ViewToken< Element > mayConsumeView(InputTag const &)
ModuleDescription const & art::ModuleBase::moduleDescription ( ) const
inherited

Definition at line 13 of file ModuleBase.cc.

References art::errors::LogicError.

Referenced by art::OutputModule::doRespondToOpenInputFile(), art::OutputModule::doWriteEvent(), art::Modifier::fillProductDescriptions(), art::OutputModule::makePlugins_(), art::OutputWorker::OutputWorker(), reco::shower::LArPandoraModularShowerCreation::produce(), art::Modifier::registerProducts(), and art::OutputModule::registerProducts().

14  {
15  if (md_.has_value()) {
16  return *md_;
17  }
18 
20  "There was an error while calling moduleDescription().\n"}
21  << "The moduleDescription() base-class member function cannot be called\n"
22  "during module construction. To determine which module is "
23  "responsible\n"
24  "for calling it, find the '<module type>:<module "
25  "label>@Construction'\n"
26  "tag in the message prefix above. Please contact artists@fnal.gov\n"
27  "for guidance.\n";
28  }
cet::coded_exception< errors::ErrorCodes, ExceptionDetail::translate > Exception
Definition: Exception.h:66
std::optional< ModuleDescription > md_
Definition: ModuleBase.h:55
void larg4::LArG4::produce ( art::Event evt)
overrideprivatevirtual

The main routine of this module: Fetch the primary particles from the event, simulate their evolution in the detector, and produce the detector response.

Implements art::EDProducer.

Definition at line 619 of file LArG4_module.cc.

References sim::SimChannel::Channel(), larg4::AuxDetReadout::clear(), larg4::OpDetPhotonTable::ClearEnergyDeposits(), larg4::OpDetPhotonTable::ClearTable(), geo::GeometryCore::Cryostat(), DEFINE_ART_MODULE, sim::SimPhotonsLite::DetectedPhotons, sim::dump::DumpMCParticle(), sim::dump::DumpMCTruth(), util::empty(), fdumpParticleList, fdumpSimChannels, fG4Help, fInputLabels, fMakeMCParticles, fparticleListAction, fSparsifyTrajectories, fStoreDroppedMCParticles, fStoreReflected, fUseLitePhotons, fVoxelReadoutGeometry, art::Ptr< T >::get(), larg4::AuxDetReadout::GetAuxDetSimChannel(), art::ProductRetriever::getByLabel(), larg4::OpDetPhotonTable::GetLitePhotons(), art::ProductRetriever::getMany(), larg4::OpDetPhotonTable::GetPhotons(), larg4::ParticleListAction::GetPrimaryTruthIndex(), art::Event::id(), larg4::OpDetPhotonTable::Instance(), larg4::ParticleListAction::isDropped(), art::errors::LogicError, MF_LOG_DEBUG, simb::MCParticle::Mother(), geo::GeometryCore::Ncryostats(), geo::GeometryCore::NOpDets(), geo::CryostatGeo::NTPC(), sim::SimPhotonsLite::OpChannel, simb::MCTruth::Origin(), sim::MCParticleLite::Origin(), art::Handle< T >::provenance(), art::Event::put(), larg4::ParticleListAction::ResetTrackIDOffset(), sc, util::size(), sim::ParticleList::size(), simb::MCParticle::SparsifyTrajectory(), simb::MCParticle::StatusCode(), sim::SimChannel::TDCIDEMap(), simb::MCParticle::TrackId(), larg4::ParticleListAction::YieldDroppedList(), larg4::ParticleListAction::YieldList(), larg4::OpDetPhotonTable::YieldOpDetBacktrackerRecords(), larg4::OpDetPhotonTable::YieldReflectedOpDetBacktrackerRecords(), and larg4::OpDetPhotonTable::YieldSimEnergyDeposits().

620  {
621  MF_LOG_DEBUG("LArG4") << "produce()";
622  auto const clockData = art::ServiceHandle<detinfo::DetectorClocksService const>()->DataFor(evt);
623  auto const detProp =
625  LArVoxelReadoutGeometry::Sentry const set_for_event{fVoxelReadoutGeometry, clockData, detProp};
626 
627  // loop over the lists and put the particles and voxels into the event as collections
628  auto scCol = std::make_unique<std::vector<sim::SimChannel>>();
629  auto adCol = std::make_unique<std::vector<sim::AuxDetSimChannel>>();
630  auto tpassn = fMakeMCParticles ?
631  std::make_unique<
633  nullptr;
634  auto partCol = fMakeMCParticles ? std::make_unique<std::vector<simb::MCParticle>>() : nullptr;
635  auto droppedPartCol =
636  fStoreDroppedMCParticles ? std::make_unique<std::vector<sim::MCParticleLite>>() : nullptr;
637  auto PhotonCol = std::make_unique<std::vector<sim::SimPhotons>>();
638  auto PhotonColRefl = std::make_unique<std::vector<sim::SimPhotons>>();
639  auto LitePhotonCol = std::make_unique<std::vector<sim::SimPhotonsLite>>();
640  auto LitePhotonColRefl = std::make_unique<std::vector<sim::SimPhotonsLite>>();
641  auto cOpDetBacktrackerRecordCol = std::make_unique<std::vector<sim::OpDetBacktrackerRecord>>();
642  auto cOpDetBacktrackerRecordColRefl =
643  std::make_unique<std::vector<sim::OpDetBacktrackerRecord>>();
644 
645  std::optional<art::PtrMaker<simb::MCParticle>> makeMCPartPtr;
646  if (fMakeMCParticles) makeMCPartPtr.emplace(evt);
647 
648  // for energy deposits
649  auto edepCol_TPCActive = std::make_unique<std::vector<sim::SimEnergyDeposit>>();
650  auto edepCol_Other = std::make_unique<std::vector<sim::SimEnergyDeposit>>();
651 
652  // Fetch the lists of LAr voxels and particles.
655  auto const* auxDetGeom = art::ServiceHandle<geo::AuxDetGeometry const>()->GetProviderPtr();
656 
657  // Clear the detected photon table
659  if (lgp->FillSimEnergyDeposits()) OpDetPhotonTable::Instance()->ClearEnergyDeposits();
660 
661  // reset the track ID offset as we have a new collection of interactions
663 
664  // look to see if there is any MCTruth information for this event
665  std::vector<art::Handle<std::vector<simb::MCTruth>>> mclists;
666  if (empty(fInputLabels))
667  mclists = evt.getMany<std::vector<simb::MCTruth>>();
668  else {
669  mclists.resize(fInputLabels.size());
670  for (size_t i = 0; i < fInputLabels.size(); i++)
671  evt.getByLabel(fInputLabels[i], mclists[i]);
672  }
673 
674  unsigned int nGeneratedParticles = 0;
675 
676  // Need to process Geant4 simulation for each interaction separately.
677  for (size_t mcl = 0; mcl < mclists.size(); ++mcl) {
678 
679  art::Handle<std::vector<simb::MCTruth>> mclistHandle = mclists[mcl];
680 
681  for (size_t m = 0; m < mclistHandle->size(); ++m) {
682  art::Ptr<simb::MCTruth> mct(mclistHandle, m);
683 
684  MF_LOG_DEBUG("LArG4") << *(mct.get());
685 
686  // The following tells Geant4 to track the particles in this interaction.
687  fG4Help->G4Run(mct);
688 
689  if (!partCol) continue;
690  assert(tpassn);
691 
692  // receive the particle list
694 
695  for (auto const& partPair : particleList) {
696  simb::MCParticle& p = *(partPair.second);
697  ++nGeneratedParticles;
698 
699  // if the particle has been marked as dropped, we don't save it (as of LArSoft
700  // ~v5.6 this does not ever happen because ParticleListAction has already taken
701  // care of deleting them)
702  if (ParticleListAction::isDropped(&p)) continue;
703 
704  sim::GeneratedParticleInfo const truthInfo{
706  if (!truthInfo.hasGeneratedParticleIndex() && (p.Mother() == 0)) {
707  // this means it's primary but with no information; logic error!!
709  error << "Failed to match primary particle:\n";
711  error << "\nwith particles from the truth record '"
712  << mclistHandle.provenance()->inputTag() << "':\n";
713  sim::dump::DumpMCTruth(error, *mct, 2U, " "); // 2 points per line
714  error << "\n";
715  throw error;
716  }
717 
719 
720  partCol->push_back(std::move(p));
721 
722  tpassn->addSingle(mct, (*makeMCPartPtr)(partCol->size() - 1), truthInfo);
723 
724  } // for(particleList)
725 
726  if (fStoreDroppedMCParticles && droppedPartCol) {
727  // Request a list of dropped particles. Store them in MCParticleLite format
728  sim::ParticleList droppedParticleList = fparticleListAction->YieldDroppedList();
729  droppedPartCol->reserve(droppedParticleList.size());
730 
731  for (auto const& partPair : droppedParticleList) {
732  simb::MCParticle& p = *(partPair.second);
733  if (ParticleListAction::isDropped(&p)) continue;
734  if (p.StatusCode() != 1) continue;
735 
736  sim::MCParticleLite mini_mcp(p);
737  mini_mcp.Origin(mct->Origin());
738 
739  droppedPartCol->push_back(std::move(mini_mcp));
740  } // for(droppedParticleList)
741  }
742 
743  // Has the user request a detailed dump of the output objects?
744  if (fdumpParticleList) {
745  mf::LogInfo("LArG4") << "Dump sim::ParticleList; size()=" << particleList.size() << "\n"
746  << particleList;
747  }
748  }
749 
750  } // end loop over interactions
751 
752  // get the electrons from the LArVoxelReadout sensitive detector. Get the
753  // sensitive-detector manager.
754  G4SDManager* sdManager = G4SDManager::GetSDMpointer();
755 
756  // Find the sensitive detector with the name "LArVoxelSD".
757  auto theOpDetDet = dynamic_cast<OpDetSensitiveDetector*>(
758  sdManager->FindSensitiveDetector("OpDetSensitiveDetector"));
759 
760  // Store the contents of the detected photon table
761  if (theOpDetDet) {
762 
763  if (!lgp->NoPhotonPropagation()) {
764 
765  for (int Reflected = 0; Reflected <= 1; Reflected++) {
766  if (Reflected && !fStoreReflected) continue;
767 
768  if (!fUseLitePhotons) {
769  MF_LOG_DEBUG("Optical") << "Storing OpDet Hit Collection in Event";
770  std::vector<sim::SimPhotons>& ThePhotons =
772  if (Reflected)
773  PhotonColRefl->reserve(ThePhotons.size());
774  else
775  PhotonCol->reserve(ThePhotons.size());
776  for (auto& it : ThePhotons) {
777  if (Reflected)
778  PhotonColRefl->push_back(std::move(it));
779  else
780  PhotonCol->push_back(std::move(it));
781  }
782  }
783  else {
784  MF_LOG_DEBUG("Optical") << "Storing OpDet Hit Collection in Event";
785 
786  std::map<int, std::map<int, int>> ThePhotons =
788 
789  if (size(ThePhotons) > 0) {
790  LitePhotonCol->reserve(ThePhotons.size());
791  for (auto const& [opChannel, detectedPhotons] : ThePhotons) {
793  ph.OpChannel = opChannel;
794  ph.DetectedPhotons = detectedPhotons;
795  if (Reflected)
796  LitePhotonColRefl->push_back(std::move(ph));
797  else
798  LitePhotonCol->push_back(std::move(ph));
799  }
800  }
801  }
802  if (Reflected)
803  *cOpDetBacktrackerRecordColRefl =
805  else
806  *cOpDetBacktrackerRecordCol =
808  }
809  } //end if no photon propagation
810 
811  if (lgp->FillSimEnergyDeposits()) {
812  // we steal the only existing copy of the energy deposit map. Oink!
814  for (auto& [volumeName, edepCol] : edepMap) {
815  // note: constant reference to a (smart) pointer to non-const data
816  auto const& destColl =
817  boost::contains(volumeName, "TPCActive") ? edepCol_TPCActive : edepCol_Other;
818  append(*destColl, std::move(edepCol));
819  } // for
820  }
821  } //end if theOpDetDet
822 
823  if (!lgp->NoElectronPropagation()) {
824 
825  // only put the sim::SimChannels into the event once, not once for every MCTruth in
826  // the event
827 
828  std::set<LArVoxelReadout*> ReadoutList; // to be cleared later on
829 
830  for (unsigned int c = 0; c < geom->Ncryostats(); ++c) {
831 
832  // map to keep track of which channels we already have SimChannels for in scCol
833  // remake this map on each cryostat as channels ought not to be shared between
834  // cryostats, just between TPC's
835 
836  std::map<unsigned int, unsigned int> channelToscCol;
837 
838  unsigned int ntpcs = geom->Cryostat(geo::CryostatID(c)).NTPC();
839  for (unsigned int t = 0; t < ntpcs; ++t) {
840  std::string name("LArVoxelSD");
841  std::ostringstream sstr;
842  sstr << name << "_Cryostat" << c << "_TPC" << t;
843 
844  // try first to find the sensitive detector specific for this TPC; do not bother
845  // writing on screen if there is none (yet)
846  G4VSensitiveDetector* sd = sdManager->FindSensitiveDetector(sstr.str(), false);
847  // if there is none, catch the general one (called just "LArVoxelSD")
848  if (!sd) sd = sdManager->FindSensitiveDetector(name, false);
849  // If this didn't work, then a sensitive detector with the name "LArVoxelSD"
850  // does not exist.
851  if (!sd) {
852  throw cet::exception("LArG4")
853  << "Sensitive detector for cryostat " << c << " TPC " << t << " not found (neither '"
854  << sstr.str() << "' nor '" << name << "' exist)\n";
855  }
856 
857  // Convert the G4VSensitiveDetector* to a LArVoxelReadout*.
858  auto larVoxelReadout = dynamic_cast<LArVoxelReadout*>(sd);
859 
860  // If this didn't work, there is a "LArVoxelSD" detector, but it's not a
861  // LArVoxelReadout object.
862  if (!larVoxelReadout) {
863  throw cet::exception("LArG4")
864  << "Sensitive detector '" << sd->GetName() << "' is not a LArVoxelReadout object\n";
865  }
866 
867  LArVoxelReadout::ChannelMap_t& channels = larVoxelReadout->GetSimChannelMap(c, t);
868  if (!empty(channels)) {
869  MF_LOG_DEBUG("LArG4") << "now put " << channels.size() << " SimChannels from C=" << c
870  << " T=" << t << " into the event";
871  }
872 
873  for (auto ch_pair : channels) {
874  sim::SimChannel& sc = ch_pair.second;
875 
876  // push sc onto scCol but only if we haven't already put something in scCol
877  // for this channel. if we have, then merge the ionization deposits. Skip
878  // the check if we only have one TPC
879 
880  if (ntpcs > 1) {
881  unsigned int ichan = sc.Channel();
882  auto itertest = channelToscCol.find(ichan);
883  if (itertest == channelToscCol.end()) {
884  channelToscCol[ichan] = scCol->size();
885  scCol->emplace_back(std::move(sc));
886  }
887  else {
888  unsigned int idtest = itertest->second;
889  auto const& tdcideMap = sc.TDCIDEMap();
890  for (auto const& tdcide : tdcideMap) {
891  for (auto const& ide : tdcide.second) {
892  double xyz[3] = {ide.x, ide.y, ide.z};
893  scCol->at(idtest).AddIonizationElectrons(ide.trackID,
894  tdcide.first,
895  ide.numElectrons,
896  xyz,
897  ide.energy,
898  ide.origTrackID);
899  } // end loop to add ionization electrons to scCol->at(idtest)
900  } // end loop over tdc to vector<sim::IDE> map
901  } // end if check to see if we've put SimChannels in for ichan yet or not
902  }
903  else {
904  scCol->emplace_back(std::move(sc));
905  } // end of check if we only have one TPC (skips check for multiple simchannels if we have just one TPC)
906  } // end loop over simchannels for this TPC
907 
908  // mark it for clearing
909  ReadoutList.insert(const_cast<LArVoxelReadout*>(larVoxelReadout));
910 
911  } // end loop over tpcs
912  } // end loop over cryostats
913 
914  for (LArVoxelReadout* larVoxelReadout : ReadoutList) {
915  larVoxelReadout->ClearSimChannels();
916  }
917  } //endif electron prop
918 
919  // only put the sim::AuxDetSimChannels into the event once, not once for every MCTruth
920  // in the event
921 
922  adCol->reserve(auxDetGeom->NAuxDets());
923  for (unsigned int a = 0; a < auxDetGeom->NAuxDets(); ++a) {
924 
925  // there should always be at least one senstive volume because we make one for the
926  // full aux det if none are specified in the gdml file - see AuxDetGeo.cxx
927  auto const& ad = auxDetGeom->AuxDet(a);
928  for (size_t sv = 0; sv < ad.NSensitiveVolume(); ++sv) {
929 
930  // N.B. this name convention is used when creating the AuxDetReadout SD in
931  // AuxDetReadoutGeometry
932  std::stringstream name;
933  name << "AuxDetSD_AuxDet" << a << "_" << sv;
934  G4VSensitiveDetector* sd = sdManager->FindSensitiveDetector(name.str().c_str());
935  if (!sd) {
936  throw cet::exception("LArG4")
937  << "Sensitive detector '" << name.str() << "' does not exist\n";
938  }
939 
940  // Convert the G4VSensitiveDetector* to a AuxDetReadout*.
941  larg4::AuxDetReadout* auxDetReadout = dynamic_cast<larg4::AuxDetReadout*>(sd);
942 
943  MF_LOG_DEBUG("LArG4") << "now put the AuxDetSimTracks in the event";
944 
945  const sim::AuxDetSimChannel adsc = auxDetReadout->GetAuxDetSimChannel();
946  adCol->push_back(adsc);
947  auxDetReadout->clear();
948  }
949  } // Loop over AuxDets
950 
951  if (partCol) {
952  mf::LogInfo("LArG4") << "Geant4 simulated " << nGeneratedParticles
953  << " MC particles, we keep " << partCol->size() << " .";
954  }
955 
956  if (fdumpSimChannels) {
957  mf::LogVerbatim("DumpSimChannels")
958  << "Event " << evt.id() << ": " << scCol->size() << " channels with signal";
959  unsigned int nChannels = 0;
960  for (const sim::SimChannel& sc : *scCol) {
961  mf::LogVerbatim out("DumpSimChannels");
962  out << " #" << nChannels << ": ";
963  // dump indenting with " ", but not on the first line
964  sc.Dump(out, " ");
965  ++nChannels;
966  } // for
967  } // if dump SimChannels
968 
969  if (!lgp->NoElectronPropagation()) evt.put(std::move(scCol));
970 
971  evt.put(std::move(adCol));
972  if (partCol) evt.put(std::move(partCol));
973  if (droppedPartCol) {
974  std::cout << "LArG4 dropped particles length = " << droppedPartCol->size() << std::endl;
975  evt.put(std::move(droppedPartCol));
976  }
977  if (tpassn) evt.put(std::move(tpassn));
978  if (!lgp->NoPhotonPropagation()) {
979  if (!fUseLitePhotons) {
980  evt.put(std::move(PhotonCol));
981  if (fStoreReflected) evt.put(std::move(PhotonColRefl), "Reflected");
982  }
983  else {
984  evt.put(std::move(LitePhotonCol));
985  evt.put(std::move(cOpDetBacktrackerRecordCol));
986  if (fStoreReflected) {
987  evt.put(std::move(LitePhotonColRefl), "Reflected");
988  evt.put(std::move(cOpDetBacktrackerRecordColRefl), "Reflected");
989  }
990  }
991  }
992 
993  if (lgp->FillSimEnergyDeposits()) {
994  evt.put(std::move(edepCol_TPCActive), "TPCActive");
995  evt.put(std::move(edepCol_Other), "Other");
996  }
997  return;
998  } // LArG4::produce()
std::vector< std::string > fInputLabels
std::unique_ptr< g4b::G4Helper > fG4Help
G4 interface object.
MaybeLogger_< ELseverityLevel::ELsev_info, true > LogVerbatim
std::vector< sim::OpDetBacktrackerRecord > YieldReflectedOpDetBacktrackerRecords()
bool fStoreDroppedMCParticles
Whether to keep a sim::MCParticleLite list of dropped particles.
Energy deposited on a readout channel by simulated tracks.
Definition: SimChannel.h:136
MaybeLogger_< ELseverityLevel::ELsev_info, false > LogInfo
int Mother() const
Definition: MCParticle.h:214
void Dump(Stream &&out, std::string indent, std::string first_indent) const
Dumps the full content of the SimChannel into a stream.
Definition: SimChannel.h:332
bool fMakeMCParticles
Whether to keep a sim::MCParticle list.
int StatusCode() const
Definition: MCParticle.h:212
std::unordered_map< std::string, std::vector< sim::SimEnergyDeposit > > YieldSimEnergyDeposits()
Yields the map of energy deposits by volume name, and resets the internal one.
unsigned int Ncryostats() const
Returns the number of cryostats in the detector.
Definition: GeometryCore.h:303
int TrackId() const
Definition: MCParticle.h:211
std::map< int, int > DetectedPhotons
Number of photons detected at each given time: time tick -> photons.
Definition: SimPhotons.h:109
PutHandle< PROD > put(std::unique_ptr< PROD > &&edp, std::string const &instance={})
Definition: Event.h:77
bool fSparsifyTrajectories
Sparsify MCParticle Trajectories.
decltype(auto) constexpr size(T &&obj)
ADL-aware version of std::size.
Definition: StdUtils.h:101
Collection of particles crossing one auxiliary detector cell.
bool fdumpSimChannels
Whether each event&#39;s sim::Channel will be displayed.
std::vector< sim::SimPhotons > & GetPhotons(bool Reflected=false)
larg4::ParticleListAction * fparticleListAction
Geant4 user action to particle information.
sim::ParticleList && YieldList()
std::map< unsigned int, sim::SimChannel > ChannelMap_t
Type of map channel -> sim::SimChannel.
static bool isDropped(simb::MCParticle const *p)
returns whether the specified particle has been marked as dropped
Provenance const * provenance() const
Definition: Handle.h:217
virtual void clear()
void DumpMCTruth(Stream &&out, simb::MCTruth const &truth, unsigned int pointsPerLine, std::string indent, std::string firstIndent)
Dumps the content of the specified MC truth in the output stream.
Definition: MCDumpers.h:338
int OpChannel
Optical detector channel associated to this data.
Definition: SimPhotons.h:106
unsigned int NTPC() const
Number of TPCs in this cryostat.
Definition: CryostatGeo.h:171
sim::ParticleList && YieldDroppedList()
Yields the (dropped) ParticleList accumulated during the current event.
GeneratedParticleIndex_t GetPrimaryTruthIndex(int trackId) const
Returns the index of primary truth (sim::NoGeneratorIndex if none).
bool fdumpParticleList
Whether each event&#39;s sim::ParticleList will be displayed.
CryostatGeo const & Cryostat(CryostatID const &cryoid=details::cryostat_zero) const
Returns the specified cryostat.
unsigned int NOpDets() const
Number of OpDets in the whole detector.
cet::coded_exception< errors::ErrorCodes, ExceptionDetail::translate > Exception
Definition: Exception.h:66
raw::ChannelID_t Channel() const
Returns the readout channel this object describes.
Definition: SimChannel.h:323
static OpDetPhotonTable * Instance(bool LitePhotons=false)
Compact representation of photons on a channel.
Definition: SimPhotons.h:98
bool getByLabel(std::string const &label, std::string const &instance, Handle< PROD > &result) const
bool fUseLitePhotons
std::vector< sim::OpDetBacktrackerRecord > YieldOpDetBacktrackerRecords()
Float_t sc
Definition: plot.C:23
Contains information about a generated particle.
#define MF_LOG_DEBUG(id)
TDCIDEs_t const & TDCIDEMap() const
Returns all the deposited energy information as stored.
Definition: SimChannel.h:319
bool fStoreReflected
std::map< int, std::map< int, int > > GetLitePhotons(bool Reflected=false)
void SparsifyTrajectory(double margin=0.1, bool keep_second_to_last=false)
Definition: MCParticle.h:266
size_type size() const
Definition: ParticleList.h:313
void ClearTable(size_t nch=0)
EventID id() const
Definition: Event.cc:23
sim::AuxDetSimChannel const GetAuxDetSimChannel() const
Definition: AuxDetReadout.h:70
void DumpMCParticle(Stream &&out, simb::MCParticle const &particle, std::string indent, std::string firstIndent)
Dumps the content of the specified particle in the output stream.
Definition: MCDumpers.h:226
cet::coded_exception< error, detail::translate > exception
Definition: exception.h:33
decltype(auto) constexpr empty(T &&obj)
ADL-aware version of std::empty.
Definition: StdUtils.h:109
LArVoxelReadoutGeometry * fVoxelReadoutGeometry
The data type to uniquely identify a cryostat.
Definition: geo_types.h:187
std::vector< Handle< PROD > > getMany(SelectorBase const &selector=MatchAllSelector{}) const
void art::Modifier::registerProducts ( ProductDescriptions productsToRegister)
inherited

Definition at line 16 of file Modifier.cc.

References art::ModuleBase::moduleDescription(), and art::ProductRegistryHelper::registerProducts().

17  {
18  ProductRegistryHelper::registerProducts(productsToRegister,
20  }
void registerProducts(ProductDescriptions &productsToRegister, ModuleDescription const &md)
ModuleDescription const & moduleDescription() const
Definition: ModuleBase.cc:13
void art::ModuleBase::setModuleDescription ( ModuleDescription const &  md)
inherited

Definition at line 31 of file ModuleBase.cc.

References art::ModuleBase::md_.

32  {
33  md_ = md;
34  }
std::optional< ModuleDescription > md_
Definition: ModuleBase.h:55
void art::ModuleBase::sortConsumables ( std::string const &  current_process_name)
inherited

Definition at line 49 of file ModuleBase.cc.

References art::ModuleBase::collector_, and art::ConsumesCollector::sortConsumables().

50  {
51  // Now that we know we have seen all the consumes declarations,
52  // sort the results for fast lookup later.
53  collector_.sortConsumables(current_process_name);
54  }
ConsumesCollector collector_
Definition: ModuleBase.h:56
void sortConsumables(std::string const &current_process_name)

Member Data Documentation

AllPhysicsLists larg4::LArG4::fAllPhysicsLists
private

Definition at line 343 of file LArG4_module.cc.

Referenced by LArG4().

bool larg4::LArG4::fCheckOverlaps
private

Whether to use the G4 overlap checker.

Definition at line 322 of file LArG4_module.cc.

Referenced by beginJob(), and LArG4().

detinfo::DetectorPropertiesData larg4::LArG4::fDetProp
private

Must outlive fAllPhysicsLists!

Definition at line 342 of file LArG4_module.cc.

Referenced by LArG4().

bool larg4::LArG4::fdumpParticleList
private

Whether each event's sim::ParticleList will be displayed.

Definition at line 326 of file LArG4_module.cc.

Referenced by LArG4(), and produce().

bool larg4::LArG4::fdumpSimChannels
private

Whether each event's sim::Channel will be displayed.

Definition at line 327 of file LArG4_module.cc.

Referenced by LArG4(), and produce().

CLHEP::HepRandomEngine& larg4::LArG4::fEngine
private

Random-number engine for IonizationAndScintillation initialization

Definition at line 339 of file LArG4_module.cc.

Referenced by beginJob(), and LArG4().

std::unique_ptr<g4b::G4Helper> larg4::LArG4::fG4Help {nullptr}
private

G4 interface object.

Definition at line 315 of file LArG4_module.cc.

Referenced by beginJob(), and produce().

std::string larg4::LArG4::fG4MacroPath
private

directory path for Geant4 macro file to be executed before main MC processing.

Definition at line 320 of file LArG4_module.cc.

Referenced by beginJob(), and LArG4().

std::string larg4::LArG4::fG4PhysListName
private

predefined physics list to use if not making a custom one

Definition at line 319 of file LArG4_module.cc.

Referenced by beginJob(), and LArG4().

std::vector<std::string> larg4::LArG4::fInputLabels
private

Definition at line 333 of file LArG4_module.cc.

Referenced by LArG4(), and produce().

std::vector<std::string> larg4::LArG4::fKeepParticlesInVolumes
private

Only write particles that have trajectories through these volumes.

Definition at line 335 of file LArG4_module.cc.

Referenced by beginRun(), and LArG4().

bool larg4::LArG4::fMakeMCParticles
private

Whether to keep a sim::MCParticle list.

Definition at line 323 of file LArG4_module.cc.

Referenced by beginJob(), LArG4(), and produce().

double larg4::LArG4::fOffPlaneMargin = 0.
private

Off-plane charge recovery margin dictate how tracks are put on stack.

Definition at line 331 of file LArG4_module.cc.

Referenced by beginJob(), and LArG4().

larg4::ParticleListAction* larg4::LArG4::fparticleListAction
private
Initial value:
{
nullptr}

Geant4 user action to particle information.

Definition at line 316 of file LArG4_module.cc.

Referenced by beginJob(), beginRun(), and produce().

int larg4::LArG4::fSmartStacking
private

Whether to instantiate and use class to.

Definition at line 330 of file LArG4_module.cc.

Referenced by beginJob(), and LArG4().

bool larg4::LArG4::fSparsifyTrajectories
private

Sparsify MCParticle Trajectories.

Definition at line 337 of file LArG4_module.cc.

Referenced by LArG4(), and produce().

bool larg4::LArG4::fStoreDroppedMCParticles
private

Whether to keep a sim::MCParticleLite list of dropped particles.

Definition at line 325 of file LArG4_module.cc.

Referenced by beginJob(), LArG4(), and produce().

bool larg4::LArG4::fStoreReflected {false}
private

Definition at line 329 of file LArG4_module.cc.

Referenced by LArG4(), and produce().

bool larg4::LArG4::fUseLitePhotons
private

Definition at line 328 of file LArG4_module.cc.

Referenced by beginJob(), LArG4(), and produce().

LArVoxelReadoutGeometry* larg4::LArG4::fVoxelReadoutGeometry
private
Initial value:
{
nullptr}

Definition at line 344 of file LArG4_module.cc.

Referenced by beginJob(), and produce().


The documentation for this class was generated from the following file: