From a312b904910f28436c9b7be9f4ca390e02981f0d Mon Sep 17 00:00:00 2001
From: Andre Sailer <andre.philippe.sailer@cern.ch>
Date: Mon, 2 Mar 2020 14:00:15 +0100
Subject: [PATCH] DDSim: properly add option for hepmc input files,
 automatically enable use of hepmc3 if available

---
 CMakeLists.txt                        |  5 +++
 DDG4/CMakeLists.txt                   | 16 +++++++--
 DDG4/hepmc/HepMC3EventReader.cpp      |  2 +-
 DDG4/python/DDSim/DD4hepSimulation.py | 16 +++++----
 DDG4/python/DDSim/Helper/HepMC3.py    | 47 +++++++++++++++++++++++++++
 5 files changed, 76 insertions(+), 10 deletions(-)
 create mode 100644 DDG4/python/DDSim/Helper/HepMC3.py

diff --git a/CMakeLists.txt b/CMakeLists.txt
index f54391d06..c9e4120c8 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -67,6 +67,7 @@ option(DD4HEP_USE_GEANT4  "Enable the simulation part based on Geant4"    OFF)
 option(DD4HEP_IGNORE_GEANT4_TLS "Ignore the tls flag Geant4 was compiled with" OFF)
 option(DD4HEP_USE_GEAR    "Build gear wrapper for backward compatibility" OFF)
 option(DD4HEP_USE_LCIO    "Build lcio extensions"                         OFF)
+option(DD4HEP_USE_HEPMC3  "Build hepmc3 extensions"                       OFF)
 option(DD4HEP_LOAD_ASSIMP "Download and build ASSIMP from github"         OFF)
 option(BUILD_TESTING      "Enable and build tests"                        ON)
 option(BUILD_SHARED_LIBS  "If OFF build STATIC Libraries"                 ON)
@@ -132,6 +133,10 @@ if(DD4HEP_USE_LCIO)
   DD4HEP_SETUP_LCIO_TARGETS()
 endif()
 
+IF(DD4HEP_USE_HEPMC3)
+  find_package(HepMC3 REQUIRED)
+ENDIF()
+
 ######################
 # Set compiler flags #
 ######################
diff --git a/DDG4/CMakeLists.txt b/DDG4/CMakeLists.txt
index 5d9c1f51a..f6c75d430 100644
--- a/DDG4/CMakeLists.txt
+++ b/DDG4/CMakeLists.txt
@@ -99,16 +99,16 @@ IF(TARGET LCIO::LCIO)
 
 ENDIF()
 
-find_package(HepMC3)
-IF(HEPMC3_VERSION)
+IF(DD4HEP_USE_HEPMC3)
   dd4hep_add_plugin(DDG4HepMC3
     SOURCES hepmc/*.cpp
     USES    DD4hep::DDG4
-    INCLUDES $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/hepmc> ${HEPMC3_INCLUDE_DIR}
+    INCLUDES $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/hepmc> $<BUILD_INTERFACE:${HEPMC3_INCLUDE_DIR}>
     USES ${HEPMC3_LIBRARIES}
     )
   install(TARGETS DDG4HepMC3 EXPORT DD4hep LIBRARY DESTINATION lib)
   set_target_properties(DDG4HepMC3 PROPERTIES VERSION ${DD4hep_VERSION} SOVERSION ${DD4hep_SOVERSION})
+  SET(DD4HEP_USE_HEPMC3 ON)
 ENDIF()
 
 #
@@ -139,6 +139,16 @@ install(PROGRAMS python/bin/checkOverlaps.py DESTINATION bin RENAME checkOverlap
 install(PROGRAMS python/bin/checkGeometry.py DESTINATION bin RENAME checkGeometry)
 install(PROGRAMS python/bin/g4MaterialScan.py DESTINATION bin RENAME g4MaterialScan)
 
+# configure and install DD4hepSimulation files
+file(GLOB_RECURSE DDSIM_FILES RELATIVE ${CMAKE_CURRENT_LIST_DIR}/python/DDSim/ python/DDSim/*.py)
+execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/python/DDSim/Helper)
+FOREACH(ddsimFile ${DDSIM_FILES})
+  dd4hep_debug("Configuring ${ddsimFile}")
+  # we pass all DDSim files through configure, because it is easier then only configuring only one of them, because we
+  # need all of them to end up in the same directory to install them from there
+  configure_file(python/DDSim/${ddsimFile} ${CMAKE_BINARY_DIR}/python/DDSim/${ddsimFile} @ONLY)
+ENDFOREACH()
+
 install(DIRECTORY python/DDSim DESTINATION ${DD4HEP_PYTHON_INSTALL_DIR})
 
 install(DIRECTORY examples DESTINATION examples/DDG4)
diff --git a/DDG4/hepmc/HepMC3EventReader.cpp b/DDG4/hepmc/HepMC3EventReader.cpp
index 790c78cc7..67c576ff4 100644
--- a/DDG4/hepmc/HepMC3EventReader.cpp
+++ b/DDG4/hepmc/HepMC3EventReader.cpp
@@ -73,7 +73,7 @@ HEPMC3EventReader::readParticles(int event_number, Vertices& vertices, Particles
     for(auto const& inAttr: attr.second){
       if(attr.first == m_flow1){
         colorFlow[0][inAttr.first] = std::atoi(inAttr.second->unparsed_string().c_str());
-      } else if(attr.first == m_flow1){
+      } else if(attr.first == m_flow2){
         colorFlow[1][inAttr.first] = std::atoi(inAttr.second->unparsed_string().c_str());
       }
     }
diff --git a/DDG4/python/DDSim/DD4hepSimulation.py b/DDG4/python/DDSim/DD4hepSimulation.py
index 881d4f043..5f3d72368 100644
--- a/DDG4/python/DDSim/DD4hepSimulation.py
+++ b/DDG4/python/DDSim/DD4hepSimulation.py
@@ -12,6 +12,7 @@ import sys
 import os
 from DDSim.Helper.Meta import Meta
 from DDSim.Helper.LCIO import LCIO
+from DDSim.Helper.HepMC3 import HepMC3
 from DDSim.Helper.GuineaPig import GuineaPig
 from DDSim.Helper.Physics import Physics
 from DDSim.Helper.Filter import Filter
@@ -34,7 +35,7 @@ try:
 except ImportError:
   ARGCOMPLETEENABLED = False
 
-POSSIBLEINPUTFILES = (".stdhep", ".slcio", ".HEPEvt", ".hepevt", ".hepmc", ".pairs", ".hepmc3")
+POSSIBLEINPUTFILES = (".stdhep", ".slcio", ".HEPEvt", ".hepevt", ".hepmc", ".pairs")
 
 
 def outputLevel(level):
@@ -94,6 +95,7 @@ class DD4hepSimulation(object):
     self.action = Action()
     self.guineapig = GuineaPig()
     self.lcio = LCIO()
+    self.hepmc3 = HepMC3()
     self.meta = Meta()
 
     self.filter = Filter()
@@ -397,12 +399,14 @@ class DD4hepSimulation(object):
       elif inputFile.endswith(".hepevt"):
         gen = DDG4.GeneratorAction(kernel, "Geant4InputAction/hepevt%d" % index)
         gen.Input = "Geant4EventReaderHepEvtLong|" + inputFile
-      elif inputFile.endswith(".hepmc3"):
-        gen = DDG4.GeneratorAction(kernel, "Geant4InputAction/hepmc%d" % index)
-        gen.Input = "HEPMC3FileReader|" + inputFile
       elif inputFile.endswith(".hepmc"):
-        gen = DDG4.GeneratorAction(kernel, "Geant4InputAction/hepmc%d" % index)
-        gen.Input = "Geant4EventReaderHepMC|" + inputFile
+        if self.hepmc3.useHepMC3:
+          gen = DDG4.GeneratorAction(kernel, "Geant4InputAction/hepmc%d" % index)
+          gen.Parameters = self.hepmc3.getParameters()
+          gen.Input = "HEPMC3FileReader|" + inputFile
+        else:
+          gen = DDG4.GeneratorAction(kernel, "Geant4InputAction/hepmc%d" % index)
+          gen.Input = "Geant4EventReaderHepMC|" + inputFile
       elif inputFile.endswith(".pairs"):
         gen = DDG4.GeneratorAction(kernel, "Geant4InputAction/GuineaPig%d" % index)
         gen.Input = "Geant4EventReaderGuineaPig|" + inputFile
diff --git a/DDG4/python/DDSim/Helper/HepMC3.py b/DDG4/python/DDSim/Helper/HepMC3.py
new file mode 100644
index 000000000..64423df4e
--- /dev/null
+++ b/DDG4/python/DDSim/Helper/HepMC3.py
@@ -0,0 +1,47 @@
+"""Helper object for hepmc3 input control"""
+
+from __future__ import absolute_import, unicode_literals
+from DDSim.Helper.Input import Input
+
+
+class HepMC3(Input):
+  """Configuration for the hepmc3 InputFiles"""
+
+  def __init__(self):
+    super(HepMC3, self).__init__()
+    self._parameters["Flow1"] = "flow1"
+    self._parameters["Flow2"] = "flow2"
+    # this option will evaluate to True if the HEPMC3 plugin was build
+    self._useHepMC3 = ("@DD4HEP_USE_HEPMC3@" != "OFF")
+
+  @property
+  def useHepMC3(self):
+    """Set to false if the input should be opened with the hepmc2 ascii reader.
+
+    If ``True`` a  '.hepmc' file will be opened with the HEPMC3 Reader Factory.
+
+    Defaults to true if DD4hep was build with HEPMC3 support.
+    """
+    return self._useHepMC3
+
+  @useHepMC3.setter
+  def useHepMC3(self, val):
+    self._useHepMC3 = self.makeBool(val)
+
+  @property
+  def Flow1(self):
+    """Set the name of the attribute contraining color flow information index 0."""
+    return self._parameters["Flow1"]
+
+  @Flow1.setter
+  def Flow1(self, val):
+    self._parameters["Flow1"] = val
+
+  @property
+  def Flow2(self):
+    """Set the name of the attribute contraining color flow information index 1."""
+    return self._parameters["Flow2"]
+
+  @Flow2.setter
+  def Flow2(self, val):
+    self._parameters["Flow2"] = val
-- 
GitLab