|
DD4hep
1.30.0
Detector Description Toolkit for High Energy Physics
|
Go to the documentation of this file.
13 #ifndef DD4HEP_DDG4_GEANT4OUTPUT2EDM4hep_H
14 #define DD4HEP_DDG4_GEANT4OUTPUT2EDM4hep_H
23 #include <edm4hep/MCParticleCollection.h>
24 #include <edm4hep/SimTrackerHitCollection.h>
25 #include <edm4hep/CaloHitContributionCollection.h>
26 #include <edm4hep/SimCalorimeterHitCollection.h>
27 #include <edm4hep/EDM4hepVersion.h>
28 #include <edm4hep/Constants.h>
30 #include <podio/CollectionBase.h>
31 #include <podio/podioVersion.h>
32 #include <podio/Frame.h>
33 #include <podio/FrameCategories.h>
34 #if PODIO_BUILD_VERSION >= PODIO_VERSION(0, 99, 0)
35 #include <podio/ROOTWriter.h>
37 #include <podio/ROOTFrameWriter.h>
39 using ROOTWriter = podio::ROOTFrameWriter;
63 using trackermap_t = std::map< std::string, edm4hep::SimTrackerHitCollection >;
64 using calorimeterpair_t = std::pair< edm4hep::SimCalorimeterHitCollection, edm4hep::CaloHitContributionCollection >;
66 std::unique_ptr<writer_t>
m_file { };
93 virtual void beginRun(
const G4Run* run);
95 virtual void endRun(
const G4Run* run);
98 virtual void saveRun(
const G4Run* run);
100 virtual void saveEvent( OutputContext<G4Event>& ctxt);
104 virtual void commit( OutputContext<G4Event>& ctxt);
107 virtual void begin(
const G4Event* event);
110 template <
typename T>
112 for(
const auto& p : parameters) {
113 info(
"Saving event parameter: %-32s = %s", p.first.c_str(), p.second.c_str());
114 m_frame.putParameter(p.first, p.second);
121 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving event parameter: %s", p.first.c_str());
122 frame.putParameter(p.first, p.second);
125 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving event parameter: %s", p.first.c_str());
126 frame.putParameter(p.first, p.second);
129 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving event parameter: %s", p.first.c_str());
130 frame.putParameter(p.first, p.second);
132 #if PODIO_BUILD_VERSION > PODIO_VERSION(0, 16, 2)
135 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving event parameter: %s", p.first.c_str());
136 frame.putParameter(p.first, p.second);
143 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving run parameter: %s", p.first.c_str());
144 frame.putParameter(p.first, p.second);
147 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving run parameter: %s", p.first.c_str());
148 frame.putParameter(p.first, p.second);
151 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving run parameter: %s", p.first.c_str());
152 frame.putParameter(p.first, p.second);
154 #if PODIO_BUILD_VERSION > PODIO_VERSION(0, 16, 2)
157 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving run parameter: %s", p.first.c_str());
158 frame.putParameter(p.first, p.second);
165 #endif // DD4HEP_DDG4_GEANT4OUTPUT2EDM4hep_H
193 #include <G4Threading.hh>
194 #include <G4AutoLock.hh>
195 #include <G4Version.hh>
196 #include <G4ParticleDefinition.hh>
197 #include <G4VProcess.hh>
198 #include <G4Event.hh>
201 #include <CLHEP/Units/SystemOfUnits.h>
204 #include <edm4hep/EventHeaderCollection.h>
210 G4Mutex action_mutex = G4MUTEX_INITIALIZER;
218 :
Geant4OutputAction(ctxt,nam), m_runNo(0), m_runNumberOffset(0), m_eventNumberOffset(0)
220 declareProperty(
"RunHeader", m_runHeader);
221 declareProperty(
"EventParametersInt", m_eventParametersInt);
222 declareProperty(
"EventParametersFloat", m_eventParametersFloat);
223 declareProperty(
"EventParametersString", m_eventParametersString);
224 declareProperty(
"RunNumberOffset", m_runNumberOffset);
225 declareProperty(
"EventNumberOffset", m_eventNumberOffset);
226 declareProperty(
"SectionName", m_section_name);
227 declareProperty(
"FilesByRun", m_filesByRun);
228 info(
"Writer is now instantiated ..." );
234 G4AutoLock protection_lock(&action_mutex);
241 G4AutoLock protection_lock(&action_mutex);
245 std::size_t idx =
m_output.rfind(
".");
246 if ( idx != std::string::npos ) {
250 if ( !fname.empty() ) {
251 m_file = std::make_unique<podio::ROOTWriter>(fname);
253 fatal(
"+++ Failed to open output file: %s", fname.c_str());
255 printout( INFO,
"Geant4Output2EDM4hep" ,
"Opened %s for output", fname.c_str() ) ;
270 podio::Frame metaFrame{};
272 metaFrame.putParameter(podio::collMetadataParamName(
name, edm4hep::labels::CellIDEncoding), encodingStr);
275 m_file->writeFrame(metaFrame,
"metadata");
281 G4AutoLock protection_lock(&action_mutex);
284 m_frame.put( std::move(it->second), it->first);
287 m_frame.put( std::move(calorimeterHits.first), colName);
288 m_frame.put( std::move(calorimeterHits.second), colName +
"Contributions");
297 except(
"+++ Failed to write output file. [Stream is not open]");
302 G4AutoLock protection_lock(&action_mutex);
306 podio::Frame runHeader {};
308 runHeader.putParameter(
key, value);
311 runHeader.putParameter(
"runNumber",
m_runNo);
312 runHeader.putParameter(
"GEANT4Version", G4Version);
314 runHeader.putParameter(
"detectorName",
context()->detectorDescription().header().
name());
321 m_file->writeFrame(runHeader,
"runs");
335 typedef detail::ReferenceBitMask<const int>
PropertyMask;
340 if ( pm.size() > 0 ) {
343 std::map<int,int> p_ids;
344 std::vector<const Geant4Particle*> p_part;
345 p_part.reserve(pm.size());
347 for (
const auto& iParticle : pm) {
348 int id = iParticle.first;
352 const G4ParticleDefinition* def = p.
definition();
354 mcp.setPDG(p->
pdgID);
356 using MT = decltype(std::declval<edm4hep::MCParticle>().getMomentum().x);
357 mcp.setMomentum( {MT(p->
psx/CLHEP::GeV),MT(p->
psy/CLHEP::GeV),MT(p->
psz/CLHEP::GeV)} );
358 mcp.setMomentumAtEndpoint( {MT(p->
pex/CLHEP::GeV),MT(p->
pey/CLHEP::GeV),MT(p->
pez/CLHEP::GeV)} );
360 double vs_fa[3] = { p->
vsx/CLHEP::mm, p->
vsy/CLHEP::mm, p->
vsz/CLHEP::mm } ;
361 mcp.setVertex( vs_fa );
363 double ve_fa[3] = { p->
vex/CLHEP::mm, p->
vey/CLHEP::mm, p->
vez/CLHEP::mm } ;
364 mcp.setEndpoint( ve_fa );
366 mcp.setTime(p->
time/CLHEP::ns);
367 mcp.setMass(p->
mass/CLHEP::GeV);
368 mcp.setCharge(def ? def->GetPDGCharge() : 0);
371 mcp.setGeneratorStatus(0);
390 mcp.setOverlay(
false );
393 if( mcp.isCreatedInSimulation() )
394 mcp.setGeneratorStatus( 0 ) ;
396 mcp.setSpin(p->
spin);
404 for(
size_t i=0; i < p_ids.size(); ++i) {
409 const auto k = p_ids.find(idau);
410 if (k == p_ids.end()) {
411 fatal(
"+++ Particle %d: FAILED to find daughter with ID:%d",p->
id,idau);
414 int iqdau = (*k).second;
416 q.addToDaughters(qdau);
419 for (
const auto& ipar : p->
parents) {
421 const auto k = p_ids.find(ipar);
422 if (k == p_ids.end()) {
423 fatal(
"+++ Particle %d: FAILED to find parent with ID:%d",p->
id,ipar);
426 int iqpar = (*k).second;
428 q.addToParents(qpar);
438 int runNumber(0), eventNumber(0);
441 double eventWeight{0};
444 runNumber = parameters->
runNumber() + runNumberOffset;
445 eventNumber = parameters->
eventNumber() + eventNumberOffset;
447 #if PODIO_BUILD_VERSION > PODIO_VERSION(0, 16, 2)
449 #if PODIO_BUILD_VERSION > PODIO_VERSION(0, 99, 0)
450 eventWeight =
m_frame.getParameter<
double>(
"EventWeights").value_or(0.0);
452 eventWeight =
m_frame.getParameter<
double>(
"EventWeights");
456 runNumber =
m_runNo + runNumberOffset;
457 eventNumber = ctxt.
context->GetEventID() + eventNumberOffset;
459 printout(INFO,
"Geant4Output2EDM4hep",
"+++ Saving EDM4hep event %d run %d.", eventNumber, runNumber);
462 edm4hep::EventHeaderCollection header_collection;
463 auto header = header_collection.create();
464 header.setRunNumber(runNumber);
465 header.setEventNumber(eventNumber);
466 header.setWeight(eventWeight);
468 header.setTimeStamp( std::time(
nullptr) ) ;
469 m_frame.put( std::move(header_collection),
"EventHeader");
477 print(
"+++ Saving %d EDM4hep particles....",
int(part_map->
particleMap.size()));
494 operator std::string()
const {
495 const auto* sd = m_coll->sensitive();
506 std::string colName = collection->GetName();
507 if( coll ==
nullptr ){
508 error(
" no Geant4HitCollection: %s ", colName.c_str());
511 size_t nhits = collection->GetSize();
513 debug(
"+++ Saving EDM4hep collection %s with %d entries.", colName.c_str(),
int(nhits));
522 for(
unsigned i=0 ; i < nhits ; ++i){
523 auto sth = hits->create();
531 sth.setCellID( hit->
cellID ) ;
533 sth.setPathLength(hit->
length/CLHEP::mm);
535 #if EDM4HEP_BUILD_VERSION >= EDM4HEP_VERSION(0, 10, 99)
536 sth.setParticle(mcp);
538 sth.setMCParticle(mcp);
540 sth.setPosition( {pos.x()/CLHEP::mm, pos.y()/CLHEP::mm, pos.z()/CLHEP::mm} );
541 sth.setMomentum( {float(mom.x()/CLHEP::GeV),float(mom.y()/CLHEP::GeV),float(mom.z()/CLHEP::GeV)} );
542 auto particleIt = pm->
particles().find(trackID);
543 if( ( particleIt != pm->
particles().end()) ){
547 sth.setProducedBySecondary( (particleIt->second->originalG4ID != t.
trackID) );
557 for(
unsigned i=0 ; i < nhits ; ++i){
558 auto sch = hits.first->create();
561 sch.setCellID( hit->
cellID );
562 sch.setPosition({float(pos.x()/CLHEP::mm), float(pos.y()/CLHEP::mm), float(pos.z()/CLHEP::mm)});
567 for(
auto ci=hit->
truth.begin(); ci != hit->
truth.end(); ++ci){
569 auto sCaloHitCont = hits.second->create();
570 sch.addToContributions( sCaloHitCont );
575 sCaloHitCont.setEnergy( c.
deposit/CLHEP::GeV );
576 sCaloHitCont.setTime( c.
time/CLHEP::ns );
577 sCaloHitCont.setParticle( mcp );
580 edm4hep::Vector3f p(c.
x/CLHEP::mm, c.
y/CLHEP::mm, c.
z/CLHEP::mm);
581 sCaloHitCont.setPDG( c.
pdgID );
582 sCaloHitCont.setStepPosition( p );
588 error(
"+++ unknown type in Geant4HitCollection %s ", coll->
type().type().name());
stringmap_t m_eventParametersFloat
stringmap_t m_eventParametersInt
Direction momentum
Hit direction.
virtual void beginRun(const G4Run *run)
Callback to store the Geant4 run information.
Position position
Hit position.
stringmap_t m_eventParametersString
auto const & strParameters() const
Get the string Run parameters.
int pdgID
Particle ID from the PDG table.
virtual void saveRun(const G4Run *run)
Callback to store the Geant4 run information.
virtual void commit(OutputContext< G4Event > &ctxt)
Commit data at end of filling procedure.
@ G4PARTICLE_SIM_PARENT_RADIATED
double mass
Particle mass.
auto const & intParameters() const
Get the int event parameters.
virtual void endRun(const G4Run *run)
Callback to store the Geant4 run information.
auto const & fltParameters() const
Get the float event parameters.
std::size_t info(const std::string &src, const std::string &msg)
const ParticleMap & particles() const
Access the particle map.
virtual void saveCollection(OutputContext< G4Event > &ctxt, G4VHitsCollection *collection)
Callback to store each Geant4 hit collection.
Geant4Run & run() const
Access the geant4 run – valid only between BeginRun() and EndRun()!
auto const & dblParameters() const
Get the double Run parameters.
Generic hit container class using Geant4HitWrapper objects.
std::string versionString()
return a string with the current dd4hep version in the form vXX-YY.
auto const & strParameters() const
Get the string event parameters.
Geant4HitWrapper & hit(size_t which)
Access the hit wrapper.
std::string _toString(bool value)
String conversions: boolean value to string.
Class of the Geant4 toolkit. See http://www-geant4.kek.jp/Reference.
Base class to output Geant4 event data to persistent media.
static void increment(T *)
Increment count according to type information.
Geant4Event & event() const
Access the geant4 event – valid only between BeginEvent() and EndEvent()!
virtual void saveEvent(OutputContext< G4Event > &ctxt)
Callback to store the Geant4 event.
#define DECLARE_GEANT4ACTION(name)
Plugin defintion to create Geant4Action objects.
long long int cellID
cellID
void saveParticles(Geant4ParticleMap *particles)
Data conversion interface for MC particles to EDM4hep format.
@ G4PARTICLE_GEN_DOCUMENTATION
@ G4PARTICLE_SIM_BACKSCATTER
void fatal(const char *fmt,...) const
Support of fatal messages. Throws exception.
Base class to output Geant4 event data to EDM4hep.
Extension to pass input run data to output run data.
std::map< std::string, calorimeterpair_t > calorimetermap_t
Helper class for thread savety.
Data structure to map particles produced during the generation and the simulation.
void info(const char *fmt,...) const
Support of info messages.
T * extension(bool alert=true)
Access to type safe extension object. Exception is thrown if the object is invalid.
void except(const char *fmt,...) const
Support of exceptions: Print fatal message and throw runtime_error.
auto const & fltParameters() const
Get the float Run parameters.
std::map< std::string, std::string > stringmap_t
Geant4Sensitive * sensitive() const
Access the sensitive detector.
std::string m_section_name
void extractParameters(T &destination)
Put parameters into destination.
void error(const char *fmt,...) const
Support of error messages.
trackermap_t m_trackerHits
@ G4PARTICLE_SIM_DECAY_CALO
void saveEventParameters(const std::map< std::string, std::string > ¶meters)
Fill event parameters in EDM4hep event.
DDG4 tracker hit class used by the generic DDG4 tracker sensitive detector.
double length
Length of the track segment contributing to this hit.
std::map< int, Particle * > ParticleMap
std::pair< edm4hep::SimCalorimeterHitCollection, edm4hep::CaloHitContributionCollection > calorimeterpair_t
calorimetermap_t m_calorimeterHits
double deposit
Total energy deposit in this hit.
static void decrement(T *)
Decrement count according to type information.
Particles daughters
The list of daughters of this MC particle.
@ G4PARTICLE_SIM_DECAY_TRACKER
virtual ~Geant4Output2EDM4hep()
Default destructor.
Contribution truth
Monte Carlo / Geant4 information.
stringmap_t m_cellIDEncodingStrings
void saveFileMetaData()
Store the metadata frame with e.g. the cellID encoding strings.
const std::string & name() const
Access name of the action.
std::unique_ptr< writer_t > m_file
double time
Particle creation time.
double energyDeposit
Total energy deposit.
DDG4 calorimeter hit class used by the generic DDG4 calorimeter sensitive detector.
double pex
The track momentum at the end vertex.
const ComponentCast & type() const
Type information of the object stored.
int particleID(int track, bool throw_if_not_found=true) const
Access the equivalent track id (shortcut to the usage of TrackEquivalents)
void print(const char *fmt,...) const
Support for messages with variable output level using output level.
int trackID
Geant 4 Track identifier.
double vex
The end vertex.
T * extension(bool alert=true)
Access to type safe extension object. Exception is thrown if the object is invalid.
double vsx
The starting vertex.
double psx
The track momentum at the start vertex.
const G4ParticleDefinition * definition() const
Access the Geant4 particle definition object (expensive!)
std::string m_output
Property: "Output" output destination.
ParticleMap particleMap
Mapping of particles of this event.
@ G4PARTICLE_SIM_LEFT_DETECTOR
Namespace for the Geant4 based simulation part of the AIDA detector description toolkit.
dd4hep::detail::ReferenceBitMask< int > PropertyMask
void extractParameters(T &destination)
Put parameters into destination.
edm4hep::MCParticleCollection m_particles
float x
Proper position of the hit contribution.
Event extension to pass input event data to output event.
Contributions truth
Hit contributions by individual particles.
int hitCreationMode() const
Property access to the hit creation mode.
auto const & dblParameters() const
Get the double event parameters.
Namespace for the AIDA detector description toolkit.
Data structure to access derived MC particle information.
Particles parents
The list of parents of this MC particle.
Geant4Output2EDM4hep(Geant4Context *ctxt, const std::string &nam)
Standard constructor.
void debug(const char *fmt,...) const
Support of debug messages.
std::map< std::string, edm4hep::SimTrackerHitCollection > trackermap_t
virtual void begin(const G4Event *event)
begin-of-event callback - creates EDM4hep event and adds it to the event context
Utility class describing the monte carlo contribution of a given particle to a hit.
The base class for Geant4 sensitive detector actions implemented by users.
double energyDeposit
Energy deposit in the tracker hit.
Data structure to store the MC particle information.
static std::string encoding(VolumeManager vm, VolumeID vid)
Access to the data encoding using the volume manager and a specified volume id.
int eventNumber() const
Get the event number.
double time
Timestamp when this energy was deposited.
int runNumber() const
Get the run number.
Position position
Hit position.
podio::ROOTWriter writer_t
Generic context to extend user, run and event information.
Geant4Context * context() const
Access the context.
auto const & intParameters() const
Get the int Run parameters.