LArSoft  v09_90_00
Liquid Argon Software toolkit - https://larsoft.org/
LArG4_module.cc
Go to the documentation of this file.
1 
20 
21 #include "nug4/G4Base/G4Helper.h"
22 
23 // C++ Includes
24 #include <cassert>
25 #include <map>
26 #include <set>
27 #include <sstream>
28 #include <sys/stat.h>
29 
30 // Framework includes
40 #include "cetlib/search_path.h"
41 #include "cetlib_except/exception.h"
42 #include "fhiclcpp/ParameterSet.h"
44 
45 // art extensions
47 
48 // LArSoft Includes
50 #include "larcorealg/CoreUtils/ParticleFilters.h" // util::PositionInVolumeFilter
53 #include "lardataalg/MCDumpers/MCDumpers.h" // sim::dump namespace
77 
78 // G4 Includes
79 #include "Geant4/G4LogicalVolumeStore.hh"
80 #include "Geant4/G4RunManager.hh"
81 #include "Geant4/G4SDManager.hh"
82 #include "Geant4/G4VSensitiveDetector.hh"
83 #include "Geant4/G4VUserDetectorConstruction.hh"
84 
85 //For energy depositions
87 
88 // Boost includes
89 #include "boost/algorithm/string.hpp"
90 
92 namespace larg4 {
93 
94  // Forward declarations within namespace.
95  class LArVoxelListAction;
96 
315  class LArG4 : public art::EDProducer {
316  public:
317  explicit LArG4(fhicl::ParameterSet const& pset);
318 
319  private:
323  void produce(art::Event& evt) override;
324  void beginJob() override;
325  void beginRun(art::Run& run) override;
326 
327  std::unique_ptr<g4b::G4Helper> fG4Help{nullptr};
329  nullptr};
330 
331  std::string fG4PhysListName;
332  std::string fG4MacroPath;
333  bool fCheckOverlaps;
336  bool
341  bool fStoreReflected{false};
343  double fOffPlaneMargin = 0.;
344  std::vector<std::string> fInputLabels;
346  std::vector<std::string>
348 
350 
351  CLHEP::HepRandomEngine& fEngine;
352 
357  nullptr};
358 
360  std::unique_ptr<util::PositionInVolumeFilter> CreateParticleVolumeFilter(
361  std::set<std::string> const& vol_names) const;
362  };
363 
364 } // namespace LArG4
365 
366 namespace {
367 
368  // ---------------------------------------------------------------------------
387  template <typename T>
388  std::vector<T>& append(std::vector<T>& dest, std::vector<T>&& source)
389  {
390  if (empty(dest))
391  dest = std::move(source);
392  else {
393  dest.insert(dest.end(), std::move_iterator{begin(source)}, std::move_iterator{end(source)});
394  source = std::vector<T>{}; // ensure the old memory is released
395  }
396  return dest;
397  }
398  // ---------------------------------------------------------------------------
399 
400 } // local namespace
401 
402 namespace larg4 {
403 
404  //----------------------------------------------------------------------
405  // Constructor
407  : art::EDProducer{pset}
408  , fG4PhysListName(pset.get<std::string>("G4PhysListName", "larg4::PhysicsList"))
409  , fCheckOverlaps(pset.get<bool>("CheckOverlaps", false))
410  , fMakeMCParticles(pset.get<bool>("MakeMCParticles", true))
411  , fStoreDroppedMCParticles(pset.get<bool>("StoreDroppedMCParticles", false))
412  , fdumpParticleList(pset.get<bool>("DumpParticleList", false))
413  , fdumpSimChannels(pset.get<bool>("DumpSimChannels", false))
414  , fSmartStacking(pset.get<int>("SmartStacking", 0))
415  , fOffPlaneMargin(pset.get<double>("ChargeRecoveryMargin", 0.0))
416  , fKeepParticlesInVolumes(pset.get<std::vector<std::string>>("KeepParticlesInVolumes", {}))
417  , fSparsifyTrajectories(pset.get<bool>("SparsifyTrajectories", false))
418  , fEngine(art::ServiceHandle<rndm::NuRandomService>()->registerAndSeedEngine(
419  createEngine(0, "HepJamesRandom", "propagation"),
420  "HepJamesRandom",
421  "propagation",
422  pset,
423  "PropagationSeed"))
426  {
427  MF_LOG_DEBUG("LArG4") << "Debug: LArG4()";
428 
429  if (!fMakeMCParticles) { // configuration option consistency
430  if (fdumpParticleList) {
432  << "Option `DumpParticleList` can't be set if `MakeMCParticles` is unset.\n";
433  }
434  if (!fKeepParticlesInVolumes.empty()) {
436  << "Option `KeepParticlesInVolumes` can't be set if `MakeMCParticles` is unset.\n";
437  }
438  } // if
439 
440  if (pset.has_key("Seed")) {
442  << "The configuration of LArG4 module has the discontinued 'Seed' parameter.\n"
443  "Seeds are now controlled by two parameters: 'GEANTSeed' and 'PropagationSeed'.";
444  }
445  // setup the random number service for Geant4, the "G4Engine" label is a
446  // special tag setting up a global engine for use by Geant4/CLHEP;
447  // obtain the random seed from NuRandomService,
448  // unless overridden in configuration with key "Seed" or "GEANTSeed"
449  // FIXME: THIS APPEARS TO BE A NO-OP; IS IT NEEDED?
450  (void)art::ServiceHandle<rndm::NuRandomService>()->registerAndSeedEngine(
451  createEngine(0, "G4Engine", "GEANT"), "G4Engine", "GEANT", pset, "GEANTSeed");
452 
453  //get a list of generators to use, otherwise, we'll end up looking for anything that's
454  //made an MCTruth object
455  bool useInputLabels =
456  pset.get_if_present<std::vector<std::string>>("InputLabels", fInputLabels);
457  if (!useInputLabels) fInputLabels.resize(0);
458 
461 
462  if (!lgp->NoPhotonPropagation()) {
463  try {
466  }
467  catch (art::Exception const& e) {
468  // If the service is not configured, then just keep the default
469  // false for reflected light. If reflected photons are simulated
470  // without PVS they will show up in the regular SimPhotons collection
471  if (e.categoryCode() != art::errors::ServiceNotFound) throw;
472  }
473 
474  if (!fUseLitePhotons) {
475  produces<std::vector<sim::SimPhotons>>();
476  if (fStoreReflected) { produces<std::vector<sim::SimPhotons>>("Reflected"); }
477  }
478  else {
479  produces<std::vector<sim::SimPhotonsLite>>();
480  produces<std::vector<sim::OpDetBacktrackerRecord>>();
481  if (fStoreReflected) {
482  produces<std::vector<sim::SimPhotonsLite>>("Reflected");
483  produces<std::vector<sim::OpDetBacktrackerRecord>>("Reflected");
484  }
485  }
486  }
487 
488  if (lgp->FillSimEnergyDeposits()) {
489  produces<std::vector<sim::SimEnergyDeposit>>("TPCActive");
490  produces<std::vector<sim::SimEnergyDeposit>>("Other");
491  }
492 
493  if (fMakeMCParticles) {
494  produces<std::vector<simb::MCParticle>>();
495  produces<art::Assns<simb::MCTruth, simb::MCParticle, sim::GeneratedParticleInfo>>();
496  }
497  if (fStoreDroppedMCParticles) { produces<std::vector<sim::MCParticleLite>>(); }
498  if (!lgp->NoElectronPropagation()) produces<std::vector<sim::SimChannel>>();
499  produces<std::vector<sim::AuxDetSimChannel>>();
500 
501  // constructor decides if initialized value is a path or an environment variable
502  cet::search_path sp("FW_SEARCH_PATH");
503 
504  sp.find_file(pset.get<std::string>("GeantCommandFile"), fG4MacroPath);
505  struct stat sb;
506  if (fG4MacroPath.empty() || stat(fG4MacroPath.c_str(), &sb) != 0)
507  // failed to resolve the file name
508  throw cet::exception("NoG4Macro") << "G4 macro file " << fG4MacroPath << " not found!\n";
509  }
510 
511  //----------------------------------------------------------------------
513  {
514  fG4Help = std::make_unique<g4b::G4Helper>(fG4MacroPath, fG4PhysListName);
515 
516  if (fCheckOverlaps) fG4Help->SetOverlapCheck(true);
517 
519  fG4Help->ConstructDetector(geom->GDMLFile());
520 
521  // Get the logical volume store and assign material properties
523  auto const detProp =
525  mpl.GetPropertiesFromServices(detProp);
526  mpl.UpdateGeometry(G4LogicalVolumeStore::GetInstance());
527 
528  // Tell the detector about the parallel LAr voxel geometry.
529  std::vector<G4VUserParallelWorld*> pworlds;
530 
531  // Intialize G4 physics and primary generator action
532  fG4Help->InitPhysics();
533 
534  // create the ionization and scintillation calculator;
535  // this is a singleton (!) so it does not make sense
536  // to create it in LArVoxelReadoutGeometry
538 
539  // make a parallel world for each TPC in the detector
540  LArVoxelReadoutGeometry::Setup_t readoutGeomSetupData;
541  readoutGeomSetupData.readoutSetup.offPlaneMargin = fOffPlaneMargin;
542  readoutGeomSetupData.readoutSetup.propGen = &fEngine;
543 
545  new LArVoxelReadoutGeometry("LArVoxelReadoutGeometry", readoutGeomSetupData);
546  pworlds.push_back(fVoxelReadoutGeometry);
547  pworlds.push_back(
548  new OpDetReadoutGeometry(geom->OpDetGeoName(), "OpDetReadoutGeometry", fUseLitePhotons));
549  pworlds.push_back(new AuxDetReadoutGeometry("AuxDetReadoutGeometry"));
550 
551  fG4Help->SetParallelWorlds(pworlds);
552 
553  // moved up
554  // Intialize G4 physics and primary generator action
555  fG4Help->InitPhysics();
556 
557  // Use the UserActionManager to handle all the Geant4 user hooks.
559 
560  // User-action class for accumulating LAr voxels.
562 
563  // User-action class for accumulating particles and trajectories
564  // produced in the detector.
566  lgp->StoreTrajectories(),
567  lgp->KeepEMShowerDaughters(),
571 
572  // UserActionManager is now configured so continue G4 initialization
573  fG4Help->SetUserAction();
574 
575  // With an enormous detector with lots of rock ala LAr34 (nee LAr20)
576  // we need to be smarter about stacking.
577  if (fSmartStacking > 0) {
578  G4UserStackingAction* stacking_action = new LArStackingAction(fSmartStacking);
579  fG4Help->GetRunManager()->SetUserAction(stacking_action);
580  }
581  }
582 
584  {
585  // prepare the filter object (null if no filtering)
586  std::set<std::string> volnameset(fKeepParticlesInVolumes.begin(),
589  }
590 
591  std::unique_ptr<util::PositionInVolumeFilter> LArG4::CreateParticleVolumeFilter(
592  std::set<std::string> const& vol_names) const
593  {
594  // if we don't have favourite volumes, don't even bother creating a filter
595  if (empty(vol_names)) return {};
596 
597  auto const& geom = *art::ServiceHandle<geo::Geometry const>();
598 
599  std::vector<std::vector<TGeoNode const*>> node_paths = geom.FindAllVolumePaths(vol_names);
600 
601  // collection of interesting volumes
603  GeoVolumePairs.reserve(node_paths.size()); // because we are obsessed
604 
605  //for each interesting volume, follow the node path and collect
606  //total rotations and translations
607  for (size_t iVolume = 0; iVolume < node_paths.size(); ++iVolume) {
608  std::vector<TGeoNode const*> path = node_paths[iVolume];
609 
610  auto pTransl = new TGeoTranslation(0., 0., 0.);
611  auto pRot = new TGeoRotation();
612  for (TGeoNode const* node : path) {
613  TGeoTranslation thistranslate(*node->GetMatrix());
614  TGeoRotation thisrotate(*node->GetMatrix());
615  pTransl->Add(&thistranslate);
616  *pRot = *pRot * thisrotate;
617  }
618 
619  // for some reason, pRot and pTransl don't have tr and rot bits set
620  // correctly make new translations and rotations so bits are set correctly
621  auto pTransl2 = new TGeoTranslation(
622  pTransl->GetTranslation()[0], pTransl->GetTranslation()[1], pTransl->GetTranslation()[2]);
623  double phi = 0., theta = 0., psi = 0.;
624  pRot->GetAngles(phi, theta, psi);
625  auto pRot2 = new TGeoRotation();
626  pRot2->SetAngles(phi, theta, psi);
627 
628  auto pTransf = new TGeoCombiTrans(*pTransl2, *pRot2);
629  GeoVolumePairs.emplace_back(node_paths[iVolume].back()->GetVolume(), pTransf);
630  }
631 
632  return std::make_unique<util::PositionInVolumeFilter>(std::move(GeoVolumePairs));
633  } // CreateParticleVolumeFilter()
634 
636  {
637  MF_LOG_DEBUG("LArG4") << "produce()";
638  auto const clockData = art::ServiceHandle<detinfo::DetectorClocksService const>()->DataFor(evt);
639  auto const detProp =
641  LArVoxelReadoutGeometry::Sentry const set_for_event{fVoxelReadoutGeometry, clockData, detProp};
642 
643  // loop over the lists and put the particles and voxels into the event as
644  // collections
645  auto scCol = std::make_unique<std::vector<sim::SimChannel>>();
646  auto adCol = std::make_unique<std::vector<sim::AuxDetSimChannel>>();
647  auto tpassn = fMakeMCParticles ?
648  std::make_unique<
650  nullptr;
651  auto partCol = fMakeMCParticles ? std::make_unique<std::vector<simb::MCParticle>>() : nullptr;
652  auto droppedPartCol =
653  fStoreDroppedMCParticles ? std::make_unique<std::vector<sim::MCParticleLite>>() : nullptr;
654  auto PhotonCol = std::make_unique<std::vector<sim::SimPhotons>>();
655  auto PhotonColRefl = std::make_unique<std::vector<sim::SimPhotons>>();
656  auto LitePhotonCol = std::make_unique<std::vector<sim::SimPhotonsLite>>();
657  auto LitePhotonColRefl = std::make_unique<std::vector<sim::SimPhotonsLite>>();
658  auto cOpDetBacktrackerRecordCol = std::make_unique<std::vector<sim::OpDetBacktrackerRecord>>();
659  auto cOpDetBacktrackerRecordColRefl =
660  std::make_unique<std::vector<sim::OpDetBacktrackerRecord>>();
661 
662  std::optional<art::PtrMaker<simb::MCParticle>> makeMCPartPtr;
663  if (fMakeMCParticles) makeMCPartPtr.emplace(evt);
664 
665  // for energy deposits
666  auto edepCol_TPCActive = std::make_unique<std::vector<sim::SimEnergyDeposit>>();
667  auto edepCol_Other = std::make_unique<std::vector<sim::SimEnergyDeposit>>();
668 
669  // Fetch the lists of LAr voxels and particles.
672 
673  // Clear the detected photon table
675  if (lgp->FillSimEnergyDeposits()) OpDetPhotonTable::Instance()->ClearEnergyDeposits();
676 
677  // reset the track ID offset as we have a new collection of interactions
679 
680  //look to see if there is any MCTruth information for this
681  //event
682  std::vector<art::Handle<std::vector<simb::MCTruth>>> mclists;
683  if (empty(fInputLabels))
684  //evt.getManyByType(mclists);
685  mclists = evt.getMany<std::vector<simb::MCTruth>>();
686  else {
687  mclists.resize(fInputLabels.size());
688  for (size_t i = 0; i < fInputLabels.size(); i++)
689  evt.getByLabel(fInputLabels[i], mclists[i]);
690  }
691 
692  unsigned int nGeneratedParticles = 0;
693 
694  // Need to process Geant4 simulation for each interaction separately.
695  for (size_t mcl = 0; mcl < mclists.size(); ++mcl) {
696 
697  art::Handle<std::vector<simb::MCTruth>> mclistHandle = mclists[mcl];
698 
699  for (size_t m = 0; m < mclistHandle->size(); ++m) {
700  art::Ptr<simb::MCTruth> mct(mclistHandle, m);
701 
702  MF_LOG_DEBUG("LArG4") << *(mct.get());
703 
704  // The following tells Geant4 to track the particles in this interaction.
705  fG4Help->G4Run(mct);
706 
707  if (!partCol) continue;
708  assert(tpassn);
709 
710  // receive the particle list
712 
713  for (auto const& partPair : particleList) {
714  simb::MCParticle& p = *(partPair.second);
715  ++nGeneratedParticles;
716 
717  // if the particle has been marked as dropped, we don't save it
718  // (as of LArSoft ~v5.6 this does not ever happen because
719  // ParticleListAction has already taken care of deleting them)
720  if (ParticleListAction::isDropped(&p)) continue;
721 
722  sim::GeneratedParticleInfo const truthInfo{
724  if (!truthInfo.hasGeneratedParticleIndex() && (p.Mother() == 0)) {
725  // this means it's primary but with no information; logic error!!
727  error << "Failed to match primary particle:\n";
728  sim::dump::DumpMCParticle(error, p, " ");
729  error << "\nwith particles from the truth record '"
730  << mclistHandle.provenance()->inputTag() << "':\n";
731  sim::dump::DumpMCTruth(error, *mct, 2U, " "); // 2 points per line
732  error << "\n";
733  throw error;
734  }
735 
737 
738  partCol->push_back(std::move(p));
739 
740  tpassn->addSingle(mct, (*makeMCPartPtr)(partCol->size() - 1), truthInfo);
741 
742  } // for(particleList)
743 
744  if (fStoreDroppedMCParticles && droppedPartCol) {
745  // Request a list of dropped particles
746  // Store them in MCParticleLite format
747  sim::ParticleList droppedParticleList = fparticleListAction->YieldDroppedList();
748  droppedPartCol->reserve(droppedParticleList.size());
749 
750  for (auto const& partPair : droppedParticleList) {
751  simb::MCParticle& p = *(partPair.second);
752  if (ParticleListAction::isDropped(&p)) continue;
753  if (p.StatusCode() != 1) continue;
754 
755  sim::MCParticleLite mini_mcp(p);
756  mini_mcp.Origin(mct->Origin());
757 
758  droppedPartCol->push_back(std::move(mini_mcp));
759  } // for(droppedParticleList)
760  }
761 
762  // Has the user request a detailed dump of the output objects?
763  if (fdumpParticleList) {
764  mf::LogInfo("LArG4") << "Dump sim::ParticleList; size()=" << particleList.size() << "\n"
765  << particleList;
766  }
767  }
768 
769  } // end loop over interactions
770 
771  // get the electrons from the LArVoxelReadout sensitive detector
772  // Get the sensitive-detector manager.
773  G4SDManager* sdManager = G4SDManager::GetSDMpointer();
774 
775  // Find the sensitive detector with the name "LArVoxelSD".
776  auto theOpDetDet = dynamic_cast<OpDetSensitiveDetector*>(
777  sdManager->FindSensitiveDetector("OpDetSensitiveDetector"));
778 
779  // Store the contents of the detected photon table
780  //
781  if (theOpDetDet) {
782 
783  if (!lgp->NoPhotonPropagation()) {
784 
785  for (int Reflected = 0; Reflected <= 1; Reflected++) {
786  if (Reflected && !fStoreReflected) continue;
787 
788  if (!fUseLitePhotons) {
789  MF_LOG_DEBUG("Optical") << "Storing OpDet Hit Collection in Event";
790  std::vector<sim::SimPhotons>& ThePhotons =
792  if (Reflected)
793  PhotonColRefl->reserve(ThePhotons.size());
794  else
795  PhotonCol->reserve(ThePhotons.size());
796  for (auto& it : ThePhotons) {
797  if (Reflected)
798  PhotonColRefl->push_back(std::move(it));
799  else
800  PhotonCol->push_back(std::move(it));
801  }
802  }
803  else {
804  MF_LOG_DEBUG("Optical") << "Storing OpDet Hit Collection in Event";
805 
806  std::map<int, std::map<int, int>> ThePhotons =
808 
809  if (size(ThePhotons) > 0) {
810  LitePhotonCol->reserve(ThePhotons.size());
811  for (auto const& [opChannel, detectedPhotons] : ThePhotons) {
813  ph.OpChannel = opChannel;
814  ph.DetectedPhotons = detectedPhotons;
815  if (Reflected)
816  LitePhotonColRefl->push_back(std::move(ph));
817  else
818  LitePhotonCol->push_back(std::move(ph));
819  }
820  }
821  }
822  if (Reflected)
823  *cOpDetBacktrackerRecordColRefl =
825  else
826  *cOpDetBacktrackerRecordCol =
828  }
829  } //end if no photon propagation
830 
831  if (lgp->FillSimEnergyDeposits()) {
832  // we steal the only existing copy of the energy deposit map. Oink!
834  for (auto& [volumeName, edepCol] : edepMap) {
835  // note: constant reference to a (smart) pointer to non-const data
836  auto const& destColl =
837  boost::contains(volumeName, "TPCActive") ? edepCol_TPCActive : edepCol_Other;
838  append(*destColl, std::move(edepCol));
839  } // for
840  }
841  } //end if theOpDetDet
842 
843  if (!lgp->NoElectronPropagation()) {
844 
845  // only put the sim::SimChannels into the event once, not once for every
846  // MCTruth in the event
847 
848  std::set<LArVoxelReadout*> ReadoutList; // to be cleared later on
849 
850  for (unsigned int c = 0; c < geom->Ncryostats(); ++c) {
851 
852  // map to keep track of which channels we already have SimChannels for in scCol
853  // remake this map on each cryostat as channels ought not to be shared between
854  // cryostats, just between TPC's
855 
856  std::map<unsigned int, unsigned int> channelToscCol;
857 
858  unsigned int ntpcs = geom->Cryostat(geo::CryostatID(c)).NTPC();
859  for (unsigned int t = 0; t < ntpcs; ++t) {
860  std::string name("LArVoxelSD");
861  std::ostringstream sstr;
862  sstr << name << "_Cryostat" << c << "_TPC" << t;
863 
864  // try first to find the sensitive detector specific for this TPC;
865  // do not bother writing on screen if there is none (yet)
866  G4VSensitiveDetector* sd = sdManager->FindSensitiveDetector(sstr.str(), false);
867  // if there is none, catch the general one (called just "LArVoxelSD")
868  if (!sd) sd = sdManager->FindSensitiveDetector(name, false);
869  // If this didn't work, then a sensitive detector with
870  // the name "LArVoxelSD" does not exist.
871  if (!sd) {
872  throw cet::exception("LArG4")
873  << "Sensitive detector for cryostat " << c << " TPC " << t << " not found (neither '"
874  << sstr.str() << "' nor '" << name << "' exist)\n";
875  }
876 
877  // Convert the G4VSensitiveDetector* to a LArVoxelReadout*.
878  auto larVoxelReadout = dynamic_cast<LArVoxelReadout*>(sd);
879 
880  // If this didn't work, there is a "LArVoxelSD" detector, but
881  // it's not a LArVoxelReadout object.
882  if (!larVoxelReadout) {
883  throw cet::exception("LArG4")
884  << "Sensitive detector '" << sd->GetName() << "' is not a LArVoxelReadout object\n";
885  }
886 
887  LArVoxelReadout::ChannelMap_t& channels = larVoxelReadout->GetSimChannelMap(c, t);
888  if (!empty(channels)) {
889  MF_LOG_DEBUG("LArG4") << "now put " << channels.size() << " SimChannels from C=" << c
890  << " T=" << t << " into the event";
891  }
892 
893  for (auto ch_pair : channels) {
894  sim::SimChannel& sc = ch_pair.second;
895 
896  // push sc onto scCol but only if we haven't already put something in scCol for this channel.
897  // if we have, then merge the ionization deposits. Skip the check if we only have one TPC
898 
899  if (ntpcs > 1) {
900  unsigned int ichan = sc.Channel();
901  auto itertest = channelToscCol.find(ichan);
902  if (itertest == channelToscCol.end()) {
903  channelToscCol[ichan] = scCol->size();
904  scCol->emplace_back(std::move(sc));
905  }
906  else {
907  unsigned int idtest = itertest->second;
908  auto const& tdcideMap = sc.TDCIDEMap();
909  for (auto const& tdcide : tdcideMap) {
910  for (auto const& ide : tdcide.second) {
911  double xyz[3] = {ide.x, ide.y, ide.z};
912  scCol->at(idtest).AddIonizationElectrons(ide.trackID,
913  tdcide.first,
914  ide.numElectrons,
915  xyz,
916  ide.energy,
917  ide.origTrackID);
918  } // end loop to add ionization electrons to scCol->at(idtest)
919  } // end loop over tdc to vector<sim::IDE> map
920  } // end if check to see if we've put SimChannels in for ichan yet or not
921  }
922  else {
923  scCol->emplace_back(std::move(sc));
924  } // end of check if we only have one TPC (skips check for multiple simchannels if we have just one TPC)
925  } // end loop over simchannels for this TPC
926 
927  // mark it for clearing
928  ReadoutList.insert(const_cast<LArVoxelReadout*>(larVoxelReadout));
929 
930  } // end loop over tpcs
931  } // end loop over cryostats
932 
933  for (LArVoxelReadout* larVoxelReadout : ReadoutList) {
934  larVoxelReadout->ClearSimChannels();
935  }
936  } //endif electron prop
937 
938  // only put the sim::AuxDetSimChannels into the event once, not once for every
939  // MCTruth in the event
940 
941  adCol->reserve(geom->NAuxDets());
942  for (unsigned int a = 0; a < geom->NAuxDets(); ++a) {
943 
944  // there should always be at least one senstive volume because
945  // we make one for the full aux det if none are specified in the
946  // gdml file - see AuxDetGeo.cxx
947  for (size_t sv = 0; sv < geom->AuxDet(a).NSensitiveVolume(); ++sv) {
948 
949  // N.B. this name convention is used when creating the
950  // AuxDetReadout SD in AuxDetReadoutGeometry
951  std::stringstream name;
952  name << "AuxDetSD_AuxDet" << a << "_" << sv;
953  G4VSensitiveDetector* sd = sdManager->FindSensitiveDetector(name.str().c_str());
954  if (!sd) {
955  throw cet::exception("LArG4")
956  << "Sensitive detector '" << name.str() << "' does not exist\n";
957  }
958 
959  // Convert the G4VSensitiveDetector* to a AuxDetReadout*.
960  larg4::AuxDetReadout* auxDetReadout = dynamic_cast<larg4::AuxDetReadout*>(sd);
961 
962  MF_LOG_DEBUG("LArG4") << "now put the AuxDetSimTracks in the event";
963 
964  const sim::AuxDetSimChannel adsc = auxDetReadout->GetAuxDetSimChannel();
965  adCol->push_back(adsc);
966  auxDetReadout->clear();
967  }
968  } // Loop over AuxDets
969 
970  if (partCol) {
971  mf::LogInfo("LArG4") << "Geant4 simulated " << nGeneratedParticles
972  << " MC particles, we keep " << partCol->size() << " .";
973  }
974 
975  if (fdumpSimChannels) {
976  mf::LogVerbatim("DumpSimChannels")
977  << "Event " << evt.id() << ": " << scCol->size() << " channels with signal";
978  unsigned int nChannels = 0;
979  for (const sim::SimChannel& sc : *scCol) {
980  mf::LogVerbatim out("DumpSimChannels");
981  out << " #" << nChannels << ": ";
982  // dump indenting with " ", but not on the first line
983  sc.Dump(out, " ");
984  ++nChannels;
985  } // for
986  } // if dump SimChannels
987 
988  if (!lgp->NoElectronPropagation()) evt.put(std::move(scCol));
989 
990  evt.put(std::move(adCol));
991  if (partCol) evt.put(std::move(partCol));
992  if (droppedPartCol) {
993  std::cout << "LArG4 dropped particles length = " << droppedPartCol->size() << std::endl;
994  evt.put(std::move(droppedPartCol));
995  }
996  if (tpassn) evt.put(std::move(tpassn));
997  if (!lgp->NoPhotonPropagation()) {
998  if (!fUseLitePhotons) {
999  evt.put(std::move(PhotonCol));
1000  if (fStoreReflected) evt.put(std::move(PhotonColRefl), "Reflected");
1001  }
1002  else {
1003  evt.put(std::move(LitePhotonCol));
1004  evt.put(std::move(cOpDetBacktrackerRecordCol));
1005  if (fStoreReflected) {
1006  evt.put(std::move(LitePhotonColRefl), "Reflected");
1007  evt.put(std::move(cOpDetBacktrackerRecordColRefl), "Reflected");
1008  }
1009  }
1010  }
1011 
1012  if (lgp->FillSimEnergyDeposits()) {
1013  evt.put(std::move(edepCol_TPCActive), "TPCActive");
1014  evt.put(std::move(edepCol_Other), "Other");
1015  }
1016  return;
1017  } // LArG4::produce()
1018 
1019 } // namespace LArG4
1020 
std::vector< std::string > fInputLabels
std::unique_ptr< g4b::G4Helper > fG4Help
G4 interface object.
base_engine_t & createEngine(seed_t seed)
CLHEP::HepRandomEngine * propGen
Random engine for charge propagation.
Store parameters for running LArG4.
Collection of all it takes to set up this object.
MaybeLogger_< ELseverityLevel::ELsev_info, true > LogVerbatim
std::vector< sim::OpDetBacktrackerRecord > YieldReflectedOpDetBacktrackerRecords()
bool fStoreDroppedMCParticles
Whether to keep a sim::MCParticleLite list of dropped particles.
bool KeepEMShowerDaughters() const
std::string fG4MacroPath
Energy deposited on a readout channel by simulated tracks.
Definition: SimChannel.h:136
Stores material properties and sends them to GEANT4 geometry.
void beginJob() override
MaybeLogger_< ELseverityLevel::ELsev_info, false > LogInfo
int Mother() const
Definition: MCParticle.h:214
void GetPropertiesFromServices(detinfo::DetectorPropertiesData const &detProp)
Imports properties from LArSoft services.
std::vector< VolumeInfo_t > AllVolumeInfo_t
EDProducer(fhicl::ParameterSet const &pset)
Definition: EDProducer.cc:6
simb::Origin_t Origin() const
Definition: MCTruth.h:74
void produces(std::string const &instanceName={}, Persistable const persistable=Persistable::Yes)
bool fMakeMCParticles
Whether to keep a sim::MCParticle list.
Geant4 interface.
Class def header for MCParticleLite data container.
int StatusCode() const
Definition: MCParticle.h:212
Contains data associated to particles from detector simulation.
larg4::LArVoxelReadout::Setup_t readoutSetup
Set up data for LArVoxelReadout.
Runs Geant4 simulation and propagation of electrons and photons to readout.
std::unordered_map< std::string, std::vector< sim::SimEnergyDeposit > > YieldSimEnergyDeposits()
Yields the map of energy deposits by volume name, and resets the internal one.
bool NoPhotonPropagation() const
Use Geant4 to run the LArSoft detector simulation.
unsigned int Ncryostats() const
Returns the number of cryostats in the detector.
Definition: GeometryCore.h:430
CryostatGeo const & Cryostat(CryostatID const &cryoid=cryostat_zero) const
Returns the specified cryostat.
std::vector< std::string > fKeepParticlesInVolumes
Only write particles that have trajectories through these volumes.
std::string OpDetGeoName(CryostatID const &cid=cryostat_zero) const
Returns gdml string which gives sensitive opdet name.
Definition: Run.h:37
bool StoreTrajectories() const
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
Define the "parallel" geometry that&#39;s seen by the LAr Voxels.
PutHandle< PROD > put(std::unique_ptr< PROD > &&edp, std::string const &instance={})
Definition: Event.h:77
bool fSparsifyTrajectories
Sparsify MCParticle Trajectories.
decltype(auto) constexpr end(T &&obj)
ADL-aware version of std::end.
Definition: StdUtils.h:77
int fSmartStacking
Whether to instantiate and use class to.
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.
Simulation objects for optical detectors.
sim::ParticleList && YieldList()
std::map< unsigned int, sim::SimChannel > ChannelMap_t
Type of map channel -> sim::SimChannel.
object containing MC truth information necessary for making RawDigits and doing back tracking ...
Use Geant4&#39;s user "hooks" to maintain a list of particles generated by Geant4.
bool NoElectronPropagation() const
Utility functions to print MC truth information.
#define DEFINE_ART_MODULE(klass)
Definition: ModuleMacros.h:65
static bool isDropped(simb::MCParticle const *p)
returns whether the specified particle has been marked as dropped
static void AddAndAdoptAction(UserAction *a)
Provenance const * provenance() const
Definition: Handle.h:217
LArG4(fhicl::ParameterSet const &pset)
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
bool FillSimEnergyDeposits() const
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:175
size_t NSensitiveVolume() const
Definition: AuxDetGeo.h:144
sim::ParticleList && YieldDroppedList()
Yields the (dropped) ParticleList accumulated during the current event.
void ParticleFilter(std::unique_ptr< util::PositionInVolumeFilter > &&filter)
Grabs a particle filter.
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.
An art service to assist in the distribution of guaranteed unique seeds to all engines within an art ...
AuxDetGeo const & AuxDet(unsigned int const ad=0) const
Returns the specified auxiliary detector.
unsigned int NOpDets() const
Number of OpDets in the whole detector.
void UpdateGeometry(G4LogicalVolumeStore *lvs)
Updates the material properties with the collected values.
cet::coded_exception< errors::ErrorCodes, ExceptionDetail::translate > Exception
Definition: Exception.h:66
double ParticleKineticEnergyCut() const
raw::ChannelID_t Channel() const
Returns the readout channel this object describes.
Definition: SimChannel.h:323
static OpDetPhotonTable * Instance(bool LitePhotons=false)
A Geant4 sensitive detector that accumulates voxel information.
Define the "parallel" geometry that&#39;s seen by the AuxDet.
Compact representation of photons on a channel.
Definition: SimPhotons.h:98
double offPlaneMargin
Margin for charge recovery (see LArVoxelReadout).
bool getByLabel(std::string const &label, std::string const &instance, Handle< PROD > &result) const
std::unique_ptr< util::PositionInVolumeFilter > CreateParticleVolumeFilter(std::set< std::string > const &vol_names) const
Pointer used for correctly updating the clock data state.
static UserActionManager * Instance()
bool fUseLitePhotons
std::vector< sim::OpDetBacktrackerRecord > YieldOpDetBacktrackerRecords()
Singleton to access a unified treatment of ionization and scintillation in LAr.
Float_t sc
Definition: plot.C:23
Contains information about a generated particle.
contains information for a single step in the detector simulation
const simb::Origin_t & Origin() const
#define MF_LOG_DEBUG(id)
void produce(art::Event &evt) override
static IonizationAndScintillation * CreateInstance(detinfo::DetectorPropertiesData const &detProp, CLHEP::HepRandomEngine &engine)
object containing MC truth information necessary for making RawDigits and doing back tracking ...
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:193
Definition: MVAAlg.h:12
bool fCheckOverlaps
Whether to use the G4 overlap checker.
Transports energy depositions from GEANT4 to TPC channels.
TDCIDEs_t const & TDCIDEMap() const
Returns all the deposited energy information as stored.
Definition: SimChannel.h:319
decltype(auto) constexpr begin(T &&obj)
ADL-aware version of std::begin.
Definition: StdUtils.h:69
bool fStoreReflected
Defines classes to filter particles based on their trajectory.
AllPhysicsLists fAllPhysicsLists
TCEvent evt
Definition: DataStructs.cxx:8
std::map< int, std::map< int, int > > GetLitePhotons(bool Reflected=false)
detinfo::DetectorPropertiesData fDetProp
Must outlive fAllPhysicsLists!
Particle list in DetSim contains Monte Carlo particle information.
Float_t e
Definition: plot.C:35
T const * get() const
Definition: Ptr.h:138
CLHEP::HepRandomEngine & fEngine
void SparsifyTrajectory(double margin=0.1, bool keep_second_to_last=false)
Definition: MCParticle.h:266
double fOffPlaneMargin
void beginRun(art::Run &run) override
size_type size() const
Definition: ParticleList.h:313
void ClearTable(size_t nch=0)
A Geant4 sensitive detector that accumulates information.
EventID id() const
Definition: Event.cc:23
sim::AuxDetSimChannel const GetAuxDetSimChannel() const
Definition: AuxDetReadout.h:70
art framework interface to geometry description
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
bool UseLitePhotons() const
LArVoxelReadoutGeometry * fVoxelReadoutGeometry
unsigned int NAuxDets() const
Returns the number of auxiliary detectors.
The data type to uniquely identify a cryostat.
Definition: geo_types.h:192
std::vector< Handle< PROD > > getMany(SelectorBase const &selector=MatchAllSelector{}) const