13 #ifndef DD4HEP_DDG4_GEANT4OUTPUT2EDM4hep_H
14 #define DD4HEP_DDG4_GEANT4OUTPUT2EDM4hep_H
25 #include <edm4hep/MCParticleCollection.h>
26 #include <edm4hep/SimTrackerHitCollection.h>
27 #include <edm4hep/CaloHitContributionCollection.h>
28 #include <edm4hep/SimCalorimeterHitCollection.h>
29 #include <edm4hep/EDM4hepVersion.h>
30 #include <edm4hep/Constants.h>
31 #if EDM4HEP_BUILD_VERSION < EDM4HEP_VERSION(0, 99, 0)
32 using edm4hep::CellIDEncoding;
34 using edm4hep::labels::CellIDEncoding;
36 #if EDM4HEP_BUILD_VERSION >= EDM4HEP_VERSION(0, 99, 3)
37 #include <edm4hep/GeneratorEventParametersCollection.h>
41 #include <podio/CollectionBase.h>
42 #include <podio/podioVersion.h>
43 #include <podio/Frame.h>
44 #include <podio/FrameCategories.h>
45 #if PODIO_BUILD_VERSION >= PODIO_VERSION(1, 0, 0)
46 #include <podio/Writer.h>
48 #if PODIO_BUILD_VERSION >= PODIO_VERSION(0, 99, 0)
49 #include <podio/ROOTWriter.h>
51 #include <podio/ROOTFrameWriter.h>
53 using ROOTWriter = podio::ROOTFrameWriter;
78 #if PODIO_BUILD_VERSION >= PODIO_VERSION(1, 0, 0)
86 using trackermap_t = std::map< std::string, edm4hep::SimTrackerHitCollection >;
87 using calorimeterpair_t = std::pair< edm4hep::SimCalorimeterHitCollection, edm4hep::CaloHitContributionCollection >;
89 std::unique_ptr<writer_t>
m_file { };
126 virtual void beginRun(
const G4Run* run);
128 virtual void endRun(
const G4Run* run);
131 virtual void saveRun(
const G4Run* run);
140 virtual void begin(
const G4Event* event);
143 template <
typename T>
145 for(
const auto& p : parameters) {
146 std::stringstream output;
147 output <<
"Saving event parameter: "
148 << std::setw(32) << p.first
149 << std::setw(20) << p.second;
150 info(output.str().c_str());
151 m_frame.putParameter(p.first, p.second);
158 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving event parameter: %s", p.first.c_str());
159 frame.putParameter(p.first, p.second);
162 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving event parameter: %s", p.first.c_str());
163 frame.putParameter(p.first, p.second);
166 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving event parameter: %s", p.first.c_str());
167 frame.putParameter(p.first, p.second);
171 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving event parameter: %s", p.first.c_str());
172 frame.putParameter(p.first, p.second);
178 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving run parameter: %s", p.first.c_str());
179 frame.putParameter(p.first, p.second);
182 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving run parameter: %s", p.first.c_str());
183 frame.putParameter(p.first, p.second);
186 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving run parameter: %s", p.first.c_str());
187 frame.putParameter(p.first, p.second);
191 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving run parameter: %s", p.first.c_str());
192 frame.putParameter(p.first, p.second);
197 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving meta parameter: %s", p.first.c_str());
198 frame.putParameter(p.first, p.second);
201 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving meta parameter: %s", p.first.c_str());
202 frame.putParameter(p.first, p.second);
205 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving meta parameter: %s", p.first.c_str());
206 frame.putParameter(p.first, p.second);
210 printout(DEBUG,
"Geant4OutputEDM4hep",
"Saving meta parameter: %s", p.first.c_str());
211 frame.putParameter(p.first, p.second);
217 #endif // DD4HEP_DDG4_GEANT4OUTPUT2EDM4hep_H
245 #include <G4AutoLock.hh>
246 #include <G4Version.hh>
247 #include <G4ParticleDefinition.hh>
248 #include <G4VProcess.hh>
249 #include <G4Event.hh>
252 #include <CLHEP/Units/SystemOfUnits.h>
255 #include <edm4hep/EventHeaderCollection.h>
265 :
Geant4OutputAction(ctxt,nam), m_runNo(0), m_runNumberOffset(0), m_eventNumberOffset(0)
267 declareProperty(
"RunHeader", m_runHeader);
268 declareProperty(
"EventParametersInt", m_eventParametersInt);
269 declareProperty(
"EventParametersFloat", m_eventParametersFloat);
270 declareProperty(
"EventParametersString", m_eventParametersString);
271 declareProperty(
"RunParametersInt", m_runParametersInt);
272 declareProperty(
"RunParametersFloat", m_runParametersFloat);
273 declareProperty(
"RunParametersString", m_runParametersString);
274 declareProperty(
"RunNumberOffset", m_runNumberOffset);
275 declareProperty(
"EventNumberOffset", m_eventNumberOffset);
276 declareProperty(
"SectionName", m_section_name);
277 declareProperty(
"FilesByRun", m_filesByRun);
278 declareProperty(
"RNTuple", m_rntuple);
280 info(
"Writer is now instantiated ..." );
286 G4AutoLock protection_lock(
mutex());
292 G4AutoLock protection_lock(
mutex());
296 std::size_t idx =
m_output.rfind(
".");
297 if ( idx != std::string::npos ) {
302 if ( !fname.empty() && !
m_file ) {
303 #if PODIO_BUILD_VERSION >= PODIO_VERSION(1, 0, 0)
304 m_file = std::make_unique<podio::Writer>(podio::makeWriter(fname,
m_rntuple ?
"rntuple" :
"default"));
306 m_file = std::make_unique<podio::ROOTWriter>(fname);
309 fatal(
"+++ Failed to open output file: %s", fname.c_str());
311 printout( INFO,
"Geant4Output2EDM4hep" ,
"Opened %s for output", fname.c_str() ) ;
318 G4AutoLock protection_lock(
mutex());
325 printout(ERROR,
"Geant4Output2EDM4hep" ,
"Some other thread already stored RunParameters");
336 printout(ERROR,
"Geant4Output2EDM4hep" ,
"Some other thread already stored FileParameters");
356 podio::Frame metaFrame{};
358 metaFrame.putParameter(podio::collMetadataParamName(
name, CellIDEncoding), encodingStr);
364 m_file->writeFrame(metaFrame, podio::Category::Metadata);
372 m_frame.put( std::move(it->second), it->first);
375 m_frame.put( std::move(calorimeterHits.first), colName);
376 m_frame.put( std::move(calorimeterHits.second), colName +
"Contributions");
385 except(
"+++ Failed to write output file. [Stream is not open]");
393 podio::Frame runHeader {};
395 runHeader.putParameter(
key, value);
398 runHeader.putParameter(
key, value);
401 runHeader.putParameter(
key, value);
404 runHeader.putParameter(
key, value);
407 runHeader.putParameter(
"runNumber",
m_runNo);
408 runHeader.putParameter(
"GEANT4Version", G4Version);
410 runHeader.putParameter(
"detectorName",
context()->detectorDescription().header().
name());
415 m_file->writeFrame(runHeader, podio::Category::Run);
429 typedef detail::ReferenceBitMask<const int>
PropertyMask;
434 if ( pm.size() > 0 ) {
437 std::map<int,int> p_ids;
438 std::vector<const Geant4Particle*> p_part;
439 p_part.reserve(pm.size());
441 for (
const auto& iParticle : pm) {
442 int id = iParticle.first;
446 const G4ParticleDefinition* def = p.
definition();
448 mcp.setPDG(p->
pdgID);
450 using MT = decltype(std::declval<edm4hep::MCParticle>().getMomentum().x);
451 mcp.setMomentum( {MT(p->
psx/CLHEP::GeV),MT(p->
psy/CLHEP::GeV),MT(p->
psz/CLHEP::GeV)} );
452 mcp.setMomentumAtEndpoint( {MT(p->
pex/CLHEP::GeV),MT(p->
pey/CLHEP::GeV),MT(p->
pez/CLHEP::GeV)} );
454 double vs_fa[3] = { p->
vsx/CLHEP::mm, p->
vsy/CLHEP::mm, p->
vsz/CLHEP::mm } ;
455 mcp.setVertex( vs_fa );
457 double ve_fa[3] = { p->
vex/CLHEP::mm, p->
vey/CLHEP::mm, p->
vez/CLHEP::mm } ;
458 mcp.setEndpoint( ve_fa );
460 mcp.setTime(p->
time/CLHEP::ns);
461 mcp.setMass(p->
mass/CLHEP::GeV);
462 mcp.setCharge(def ? def->GetPDGCharge() : 0);
465 mcp.setGeneratorStatus(0);
484 mcp.setOverlay(
false );
487 if( mcp.isCreatedInSimulation() )
488 mcp.setGeneratorStatus( 0 ) ;
490 #if EDM4HEP_MCPARTICLE_HAS_HELICITY
491 mcp.setHelicity(p->
spin[2]);
493 mcp.setSpin(p->
spin);
501 for(
size_t i=0; i < p_ids.size(); ++i) {
506 const auto k = p_ids.find(idau);
507 if (k == p_ids.end()) {
508 fatal(
"+++ Particle %d: FAILED to find daughter with ID:%d",p->
id,idau);
511 int iqdau = (*k).second;
513 q.addToDaughters(qdau);
516 for (
const auto& ipar : p->
parents) {
518 const auto k = p_ids.find(ipar);
519 if (k == p_ids.end()) {
520 fatal(
"+++ Particle %d: FAILED to find parent with ID:%d",p->
id,ipar);
523 int iqpar = (*k).second;
525 q.addToParents(qpar);
535 int runNumber(0), eventNumber(0);
538 double eventWeight{0};
541 runNumber = parameters->
runNumber() + runNumberOffset;
542 eventNumber = parameters->
eventNumber() + eventNumberOffset;
544 #if PODIO_BUILD_VERSION > PODIO_VERSION(0, 99, 0)
545 eventWeight =
m_frame.getParameter<
double>(
"EventWeights").value_or(0.0);
547 eventWeight =
m_frame.getParameter<
double>(
"EventWeights");
550 runNumber =
m_runNo + runNumberOffset;
551 eventNumber = ctxt.
context->GetEventID() + eventNumberOffset;
553 printout(INFO,
"Geant4Output2EDM4hep",
"+++ Saving EDM4hep event %d run %d.", eventNumber, runNumber);
556 edm4hep::EventHeaderCollection header_collection;
558 auto header = header_collection.create();
559 header.setRunNumber(runNumber);
560 header.setEventNumber(eventNumber);
561 header.setWeight(eventWeight);
563 header.setTimeStamp(std::time(
nullptr));
568 header.setTimeStamp(meh->getTimeStamp());
569 #if EDM4HEP_BUILD_VERSION >= EDM4HEP_VERSION(0, 99, 0)
570 for (
auto const& weight: meh->getWeights()) {
571 header.addToWeights(weight);
576 m_frame.put(std::move(header_collection),
"EventHeader");
578 #if EDM4HEP_BUILD_VERSION >= EDM4HEP_VERSION(0, 99, 3)
582 edm4hep::GeneratorEventParametersCollection genEvtParamsColl{};
583 genEvtParamsColl.push_back(*genEvtParams);
584 m_frame.put(std::move(genEvtParamsColl), edm4hep::labels::GeneratorEventParameters);
594 print(
"+++ Saving %d EDM4hep particles....",
int(part_map->
particleMap.size()));
611 operator std::string()
const {
612 const auto* sd = m_coll->sensitive();
623 std::string colName = collection->GetName();
624 if( coll ==
nullptr ){
625 error(
" no Geant4HitCollection: %s ", colName.c_str());
628 size_t nhits = collection->GetSize();
630 debug(
"+++ Saving EDM4hep collection %s with %d entries.", colName.c_str(),
int(nhits));
639 for(
unsigned i=0 ; i < nhits ; ++i){
640 auto sth = hits.create();
648 sth.setCellID( hit->
cellID ) ;
650 sth.setPathLength(hit->
length/CLHEP::mm);
652 #if EDM4HEP_BUILD_VERSION >= EDM4HEP_VERSION(0, 10, 99)
653 sth.setParticle(mcp);
655 sth.setMCParticle(mcp);
657 sth.setPosition( {pos.x()/CLHEP::mm, pos.y()/CLHEP::mm, pos.z()/CLHEP::mm} );
658 sth.setMomentum( {float(mom.x()/CLHEP::GeV),float(mom.y()/CLHEP::GeV),float(mom.z()/CLHEP::GeV)} );
659 auto particleIt = pm->
particles().find(trackID);
660 if( ( particleIt != pm->
particles().end()) ){
664 sth.setProducedBySecondary( (particleIt->second->originalG4ID != t.
trackID) );
674 for(
unsigned i=0 ; i < nhits ; ++i){
675 auto sch = hits.first.create();
678 sch.setCellID( hit->
cellID );
679 sch.setPosition({float(pos.x()/CLHEP::mm), float(pos.y()/CLHEP::mm), float(pos.z()/CLHEP::mm)});
684 for(
auto ci=hit->
truth.begin(); ci != hit->
truth.end(); ++ci){
686 auto sCaloHitCont = hits.second.create();
687 sch.addToContributions( sCaloHitCont );
692 sCaloHitCont.setEnergy( c.
deposit/CLHEP::GeV );
693 sCaloHitCont.setTime( c.
time/CLHEP::ns );
694 sCaloHitCont.setParticle( mcp );
696 #if EDM4HEP_BUILD_VERSION > EDM4HEP_VERSION(1, 0, 0)
702 mcp.setHandledByFastSim(
true);
706 edm4hep::Vector3f p(c.
x/CLHEP::mm, c.
y/CLHEP::mm, c.
z/CLHEP::mm);
707 sCaloHitCont.setPDG( c.
pdgID );
708 sCaloHitCont.setStepPosition( p );
709 #if EDM4HEP_BUILD_VERSION >= EDM4HEP_VERSION(0, 99, 3)
710 sCaloHitCont.setStepLength(c.
length / CLHEP::mm);
717 error(
"+++ unknown type in Geant4HitCollection %s ", coll->
type().type().name());