### Configure G4HepEm Example Application with CMake Source: https://github.com/mnovak42/g4hepem/blob/master/docs/source/IntroAndInstall/install.rst This snippet shows the CMake configuration step for building an example application like TestEm3. It requires specifying the installation directories for Geant4 and G4HepEm using CMake variables. The output includes compiler identification and checks for compiler functionality. ```bash cd g4hepem/apps/examples/TestEm3/ mkdir build cd build/ cmake ../ -DGeant4_DIR=G4_INSTALL -DG4HepEm_DIR=G4HepEm_INSTALL/lib/cmake/G4HepEm/ -- The C compiler identification is GNU 8.3.1 -- The CXX compiler identification is GNU 8.3.1 -- Check for working C compiler: /usr/bin/cc ... ``` -------------------------------- ### Execute G4HepEm Example Application Source: https://github.com/mnovak42/g4hepem/blob/master/docs/source/IntroAndInstall/install.rst This snippet illustrates how to execute a built example application, such as TestEm3. It shows the command-line invocation with an example macro file. The output includes Geant4 version information and other runtime details. ```bash ./TestEm3 -m ../ATLASbar.mac ************************************************************** Geant4 version Name: geant4-10-07-patch-01 [MT] (5-February-2021) << in Multi-threaded mode >> Copyright : Geant4 Collaboration References : NIM A 506 (2003), 250-303 : IEEE-TNS 53 (2006), 270-278 : NIM A 835 (2016), 186-225 WWW : http://geant4.org/ ... ... ``` -------------------------------- ### Build and Execute a G4HepEm Example Application Source: https://github.com/mnovak42/g4hepem/blob/master/README.md This snippet shows how to build and run a sample application (TestEm3) that utilizes G4HepEm. It requires G4HepEm and Geant4 to be installed and configured correctly via CMake. ```bash cd g4hepem/apps/examples/TestEm3/ mkdir build cd build/ cmake ../ -DGeant4_DIR=G4_INSTALL -DG4HepEm_DIR=G4HepEm_INSTALL/lib/cmake/G4HepEm/ make ./TestEm3 -m ../ATLASbar.mac ``` -------------------------------- ### CMake Build and Installation Settings Source: https://github.com/mnovak42/g4hepem/blob/master/CMakeLists.txt Configures various CMake settings for the project, including absolute install destination policy, package registry, include directory order, link dependencies, and installation messages. It also sets the default build type to 'Release'. ```cmake # CMake and Build Settings # - Don't allow absolute paths other than CMAKE_INSTALL_PREFIX set(CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION ON) # - Never export to or search in user/system package registry set(CMAKE_EXPORT_NO_PACKAGE_REGISTRY ON) set(CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY ON) set(CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY ON) # - Force project directories to appear first in any list of includes set(CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE ON) # - Only relink shared libs when interface changes set(CMAKE_LINK_DEPENDS_NO_SHARED ON) # - Only report newly installed files set(CMAKE_INSTALL_MESSAGE LAZY) # - Default to Release mode build in single mode if(NOT CMAKE_CONFIGURATION_TYPES) if(NOT CMAKE_BUILD_TYPE) # Default to a Release build if nothing else... set(CMAKE_BUILD_TYPE Release) endif() # Force to the cache, but use existing value. set(CMAKE_BUILD_TYPE "${CMAKE_BUILD_TYPE}" CACHE STRING "Choose the type of build, options are: None Release Debug RelWithDebInfo MinSizeRel" FORCE) endif() # - Prefer shared libs set(BUILD_SHARED_LIBS ON) set(BUILD_STATIC_LIBS OFF) ``` -------------------------------- ### Build G4HepEm Example Application with Make Source: https://github.com/mnovak42/g4hepem/blob/master/docs/source/IntroAndInstall/install.rst This snippet demonstrates the build process for an example application using the 'make' command. It shows the compilation of C++ source files into object files and linking them to create the final executable. The output indicates the progress of scanning dependencies and building targets. ```bash make Scanning dependencies of target TestEm3 [ 4%] Building CXX object CMakeFiles/TestEm3.dir/TestEm3.cc.o [ 8%] Building CXX object CMakeFiles/TestEm3.dir/src/ActionInitialization.cc.o [ 13%] Building CXX object CMakeFiles/TestEm3.dir/src/DetectorConstruction.cc.o ... ... ``` -------------------------------- ### Build and Run TestEm3 Example Application (Bash) Source: https://context7.com/mnovak42/g4hepem/llms.txt This bash script outlines the steps to build and run the TestEm3 example application, which is a simplified calorimeter simulation. It includes commands for navigating to the example directory, creating a build environment, configuring CMake with Geant4 and G4HepEm paths, compiling the application, and running it with different macros. ```bash # Build the TestEm3 example cd g4hepem/apps/examples/TestEm3/ mkdir build && cd build/ cmake ../ -DGeant4_DIR=/path/to/geant4 -DG4HepEm_DIR=/path/to/g4hepem/lib/cmake/G4HepEm/ make # Run with the ATLAS-bar calorimeter macro ./TestEm3 -m ../ATLASbar.mac # Run in performance mode (no scoring) ./TestEm3 -p -m ../ATLASbar.mac ``` -------------------------------- ### Build and Install G4HepEm using CMake Source: https://github.com/mnovak42/g4hepem/blob/master/README.md This snippet demonstrates the process of cloning the G4HepEm repository, configuring the build with CMake, and installing the project. It assumes Geant4 is already installed and its configuration directory is known. ```bash git clone https://github.com/mnovak42/g4hepem.git cd g4hepem/ mkdir build cd build/ cmake ../ -DGeant4_DIR=G4_INSTALL -DCMAKE_INSTALL_PREFIX=G4HepEm_INSTALL make install ``` -------------------------------- ### Add Example Application as Test (CMake) Source: https://github.com/mnovak42/g4hepem/blob/master/testing/CMakeLists.txt Configures an example application ('TestEm3') as a test. It sets the G4HepEm directory and adds the example subdirectory to the build. Finally, it defines a CTest test named 'TestEm3' that executes the application with a specified macro file. ```cmake set(G4HepEm_DIR "${CMAKE_CURRENT_LIST_DIR}/shims") add_subdirectory(${PROJECT_SOURCE_DIR}/apps/examples/TestEm3 ${CMAKE_CURRENT_BINARY_DIR}/TestEm3) add_test(NAME TestEm3 COMMAND TestEm3 -m "${PROJECT_SOURCE_DIR}/apps/examples/TestEm3/ATLASbar.mac") ``` -------------------------------- ### CMake Project Setup and Package Finding Source: https://github.com/mnovak42/g4hepem/blob/master/apps/examples/TestEm3/CMakeLists.txt Initializes the CMake project, sets the minimum required version, and finds the necessary Geant4 and G4HepEm packages. It ensures that the required versions of these libraries are available for the project. ```cmake cmake_minimum_required(VERSION 3.8...3.19) if(${CMAKE_VERSION} VERSION_LESS 3.12) cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}) endif() project(TestEm3) find_package(Geant4 REQUIRED) find_package(G4HepEm REQUIRED) ``` -------------------------------- ### CMake Project Setup and Versioning Source: https://github.com/mnovak42/g4hepem/blob/master/CMakeLists.txt Initializes the CMake project with a specified minimum version and project name. It sets up policies to avoid warnings with older CMake versions and defines the project version. ```cmake cmake_minimum_required(VERSION 3.17...3.18 FATAL_ERROR) project(G4HepEm VERSION 0.1.0) ``` -------------------------------- ### Generate Package Configuration Files (CMake) Source: https://github.com/mnovak42/g4hepem/blob/master/CMakeLists.txt Generates CMake package configuration files (G4HepEmConfig.cmake and G4HepEmConfigVersion.cmake) for both the build tree and the install tree. These files allow other CMake projects to find and use the G4HepEm library, specifying include directories and version information. ```cmake include(CMakePackageConfigHelpers) # - Common write_basic_package_version_file( ${PROJECT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake VERSION ${PROJECT_VERSION} COMPATIBILITY AnyNewerVersion) # - Build Tree set(G4HEPEM_EXPORTED_INCLUDE_DIR "${PROJECT_SOURCE_DIR}/G4HepEm") configure_package_config_file(cmake/G4HepEmConfig.cmake.in ${PROJECT_BINARY_DIR}/G4HepEmConfig.cmake INSTALL_PREFIX "${PROJECT_BINARY_DIR}" INSTALL_DESTINATION "${PROJECT_BINARY_DIR}" PATH_VARS G4HEPEM_EXPORTED_INCLUDE_DIR) export(EXPORT ${PROJECT_NAME}Targets NAMESPACE ${PROJECT_NAME}:: FILE ${PROJECT_BINARY_DIR}/${PROJECT_NAME}Targets.cmake) # - Install Tree set(G4HEPEM_EXPORTED_INCLUDE_DIR "${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}") configure_package_config_file(cmake/G4HepEmConfig.cmake.in ${PROJECT_BINARY_DIR}/InstallTree/G4HepEmConfig.cmake INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}" PATH_VARS G4HEPEM_EXPORTED_INCLUDE_DIR) install(FILES ${PROJECT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake ${PROJECT_BINARY_DIR}/InstallTree/${PROJECT_NAME}Config.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}) install(EXPORT ${PROJECT_NAME}Targets NAMESPACE ${PROJECT_NAME}:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}) ``` -------------------------------- ### CMake Function for Library Management Source: https://github.com/mnovak42/g4hepem/blob/master/CMakeLists.txt A CMake function 'g4hepem_add_library' to manage the creation of shared and static libraries. It handles source files, headers, linking, and installation, with options for early tracking exit. ```cmake function(g4hepem_add_library _name) cmake_parse_arguments(_g4hepem "" "" "HEADERS;SOURCES;LINK" ${ARGN}) # Build shared library, if enabled. if(BUILD_SHARED_LIBS) add_library(${_name} SHARED ${_g4hepem_SOURCES}) target_compile_features(${_name} PUBLIC cxx_std_${CMAKE_CXX_STANDARD}) add_library(${PROJECT_NAME}::${_name} ALIAS ${_name}) target_include_directories(${_name} PUBLIC $ $) target_link_libraries(${_name} PUBLIC ${_g4hepem_LINK}) if(G4HepEm_EARLY_TRACKING_EXIT) target_compile_definitions(${_name} PUBLIC G4HepEm_EARLY_TRACKING_EXIT) endif() endif() # Build static library, if enabled. if(BUILD_STATIC_LIBS) add_library(${_name}-static STATIC ${_g4hepem_SOURCES}) set_target_properties(${_name}-static PROPERTIES OUTPUT_NAME ${_name}) target_compile_features(${_name}-static PUBLIC cxx_std_${CMAKE_CXX_STANDARD}) add_library(${PROJECT_NAME}::${_name}-static ALIAS ${_name}-static) target_include_directories(${_name}-static PUBLIC $ $) foreach(_lib ${_g4hepem_LINK}) target_link_libraries(${_name}-static PUBLIC ${_lib}-static) endforeach() if(G4HepEm_EARLY_TRACKING_EXIT) target_compile_definitions(${_name}-static PUBLIC G4HepEm_EARLY_TRACKING_EXIT) endif() # If only the static library, add alias targets for convenience. if(NOT BUILD_SHARED_LIBS) add_library(${_name} ALIAS ${_name}-static) add_library(${PROJECT_NAME}::${_name} ALIAS ${_name}-static) # In that case, also change the name of the exported target. set_target_properties(${_name}-static PROPERTIES EXPORT_NAME ${_name}) endif() endif() # Install headers. install(FILES ${_g4hepem_HEADERS} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}") # Install libraries, as built. if(BUILD_SHARED_LIBS) install(TARGETS ${_name} EXPORT ${PROJECT_NAME}Targets ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") endif() if(BUILD_STATIC_LIBS) install(TARGETS ${_name}-static EXPORT ${PROJECT_NAME}Targets ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") endif() endfunction() ``` -------------------------------- ### Configure Library Output Directories (CMake) Source: https://github.com/mnovak42/g4hepem/blob/master/CMakeLists.txt Sets the output directories for library build products to a 'lib' subdirectory within the project's binary directory. This ensures all compiled libraries are placed in a consistent location. ```cmake set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib) ``` -------------------------------- ### Find and Configure Geant4 Support (CMake) Source: https://github.com/mnovak42/g4hepem/blob/master/CMakeLists.txt Finds the Geant4 package and configures build settings based on its availability. It determines whether to build static or shared libraries and sets the C++ standard to match Geant4's requirements. It also includes a compile check for G4VTrackingManager support. ```cmake option(G4HepEm_GEANT4_BUILD "Build with Geant4 runtime support" ON) if(G4HepEm_GEANT4_BUILD) find_package(Geant4 10.6 REQUIRED) if(Geant4_static_FOUND) set(BUILD_STATIC_LIBS ON) endif() if(NOT Geant4_shared_FOUND) set(BUILD_SHARED_LIBS OFF) endif() set(CMAKE_CXX_STANDARD ${Geant4_CXX_STANDARD}) # use value from Geant4Config.cmake # Check if Geant4 is supports G4VTrackingManager # Always available from v11.0, but experiments may backport it to earlier versions # so we do a compile check. include(CheckCXXSourceCompiles) set(CMAKE_REQUIRED_LIBRARIES ${Geant4_LIBRARIES}) check_cxx_source_compiles("\n #include \"G4VTrackingManager.hh\"\n class testtm_ : public G4VTrackingManager {\n public:\n void HandOverOneTrack(G4Track*) {} };\n int main() { testtm_ model; return 0; }" G4HepEm_HAS_G4VTRACKINGMANAGER) else() # Need workaround for G4VERSION_NUM G4HepEmRun... # ... done in that component for now. endif() if(NOT CMAKE_CXX_STANDARD) set(CMAKE_CXX_STANDARD 11) message(WARNING "Find of Geant4 did not set Geant4_CXX_STANDARD value expected from Geant4Config.cmake. Defaulting to C++11.") endif() set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) ``` -------------------------------- ### CMake Source File and Executable Definition Source: https://github.com/mnovak42/g4hepem/blob/master/apps/examples/TestEm3/CMakeLists.txt Defines the source files for the project, including core application logic and G4HepEm-specific components. It then adds an executable target named 'TestEm3' and links it against the Geant4 and G4HepEm libraries. ```cmake include_directories(${PROJECT_SOURCE_DIR}/include) set(sources src/ActionInitialization.cc src/DetectorConstruction.cc src/DetectorMessenger.cc src/EmAcceptance.cc src/EventAction.cc src/G4HepEmProcess.cc src/HistoManager.cc src/PhysicsList.cc src/PhysicsListMessenger.cc src/PhysListEmStandard.cc src/PhysListG4Em.cc src/PhysListHepEm.cc src/PrimaryGeneratorAction.cc src/PrimaryGeneratorMessenger.cc src/RunAction.cc src/RunActionMessenger.cc src/Run.cc src/StepMax.cc src/StepMaxMessenger.cc src/SteppingAction.cc src/SteppingVerbose.cc src/TrackingAction.cc ) if (G4HepEm_trackingmanager_FOUND) set(G4HepEm_HAS_G4VTRACKINGMANAGER TRUE) endif() if(G4HepEm_HAS_G4VTRACKINGMANAGER) set(sources ${sources} src/PhysListG4EmTracking.cc src/PhysListHepEmTracking.cc ) endif() add_executable(TestEm3 ${PROJECT_SOURCE_DIR}/TestEm3.cc ${sources}) target_compile_definitions(TestEm3 PRIVATE $<$:G4HepEm_HAS_G4VTRACKINGMANAGER>) target_link_libraries(TestEm3 ${Geant4_LIBRARIES} ${G4HepEm_LIBRARIES}) ``` -------------------------------- ### Add Testing Subdirectory (CMake) Source: https://github.com/mnovak42/g4hepem/blob/master/CMakeLists.txt Includes the 'testing' subdirectory to build test programs if the BUILD_TESTING option is enabled. It also checks if Geant4 support is enabled, as tests may depend on it, and provides a warning if testing is enabled without Geant4 support. ```cmake option(BUILD_TESTING "Build the testing tree." OFF) include(CTest) if(BUILD_TESTING) if(G4HepEm_GEANT4_BUILD) message(STATUS "Building test programs is enabled!") add_subdirectory(testing) else() message(WARNING "BUILD_TESTING is ON, but no tests will be created as Geant4 runtime support is disabled") endif() endif() ``` -------------------------------- ### TestEm3 Geant4 Macro Configuration (Macro) Source: https://context7.com/mnovak42/g4hepem/llms.txt This is an example Geant4 macro file (ATLASbar.mac) used to configure the TestEm3 application for simulating an ATLAS-like sampling calorimeter. It sets up detector geometry, enables G4HepEm tracking, configures physics processes, and defines the particle gun properties for simulation. ```macro # Configure ATLAS-like sampling calorimeter /testem/det/setSizeYZ 40 cm /testem/det/setNbOfLayers 50 /testem/det/setNbOfAbsor 2 /testem/det/setAbsor 1 G4_Pb 2.3 mm /testem/det/setAbsor 2 G4_lAr 5.7 mm # Use G4HepEm tracking (recommended) /testem/phys/addPhysics HepEmTracking /testem/phys/verbose 1 # Enable gamma-general process /process/em/UseGeneralProcess true /process/em/applyCuts true # Set production cuts and initialize /run/setCut 0.7 mm /run/initialize # Run 10 GeV electrons /gun/particle e- /gun/energy 10 GeV /run/beamOn 1000 ``` -------------------------------- ### Enable and Configure CUDA Support (CMake) Source: https://github.com/mnovak42/g4hepem/blob/master/CMakeLists.txt Enables CUDA support if the G4HepEm_CUDA_BUILD option is set. It configures the CUDA host compiler, checks for CUDA compiler availability, finds the CUDAToolkit, and sets CUDA architecture flags and standard compliance. This allows G4HepEm to leverage GPU acceleration. ```cmake option(G4HepEm_CUDA_BUILD "BUILD with CUDA support" OFF) if(G4HepEm_CUDA_BUILD) # Use host compiler by default to ensure ABI consistency set(CMAKE_CUDA_HOST_COMPILER "${CMAKE_CXX_COMPILER}" CACHE STRING "Set to CMAKE_CXX_COMPILER by G4HepEM CMakeLists") check_language(CUDA) if(CMAKE_CUDA_COMPILER) enable_language(CUDA) else() message(FATAL_ERROR "No CUDA compiler/support available") endif() # Find needed toolkit libraries find_package(CUDAToolkit REQUIRED) # On CMake < 3.18, need FindCUDA for Arch flags, and it's messy... if(CMAKE_VERSION VERSION_LESS 3.18) find_package(CUDA 10 REQUIRED QUIET) cuda_select_nvcc_arch_flags(G4HEPEM_CUDA_ARCH_FLAGS) string(REPLACE ";" " " G4HEPEM_CUDA_ARCH_FLAGS "${G4HEPEM_CUDA_ARCH_FLAGS}") set(CMAKE_CUDA_FLAGS "${G4HEPEM_CUDA_ARCH_FLAGS}") endif() set(CMAKE_CUDA_STANDARD ${CMAKE_CXX_STANDARD}) set(CMAKE_CUDA_STANDARD_REQUIRED ON) set(CMAKE_CUDA_EXTENSIONS OFF) endif() ``` -------------------------------- ### CMake Option for Early Tracking Exit Source: https://github.com/mnovak42/g4hepem/blob/master/CMakeLists.txt Defines a boolean option 'G4HepEm_EARLY_TRACKING_EXIT' to control early tracking exit functionality. If enabled, a status message is printed. ```cmake option(G4HepEm_EARLY_TRACKING_EXIT "Enable user-defined early tracking exit" OFF) if(G4HepEm_EARLY_TRACKING_EXIT) message(STATUS "User-defined early tracking exit is enabled") endif() ``` -------------------------------- ### Link zlib for Static G4HepEm Initialization Library (CMake) Source: https://github.com/mnovak42/g4hepem/blob/master/G4HepEm/G4HepEmInit/CMakeLists.txt Conditionally links the `Geant4::G4zlib-static` or `ZLIB::ZLIB` library to the `g4HepEmInit-static` target if `BUILD_STATIC_LIBS` is enabled. This ensures the static library has access to zlib functionality. ```cmake if(BUILD_STATIC_LIBS) if(TARGET Geant4::G4zlib-static) target_link_libraries(g4HepEmInit-static PUBLIC Geant4::G4zlib-static) elseif(TARGET ZLIB::ZLIB) # Not a typo, Geant4 also takes what it can get from zlib. target_link_libraries(g4HepEmInit-static PUBLIC ZLIB::ZLIB) endif() endif() ``` -------------------------------- ### Simulate Electron Step with Thread-Local Data (C++) Source: https://context7.com/mnovak42/g4hepem/llms.txt Simulates a single step for an electron using Geant4's thread-local data interface. It initializes a primary electron track, calculates the physics step length, performs interactions, and processes any secondary particles generated. Dependencies include G4HepEmElectronManager, G4HepEmElectronTrack, G4HepEmTLData, G4HepEmData, and G4HepEmParameters. ```cpp #include "G4HepEmElectronManager.hh" #include "G4HepEmElectronTrack.hh" #include "G4HepEmTLData.hh" #include "G4HepEmData.hh" #include "G4HepEmParameters.hh" // Using thread-local data interface (recommended for Geant4 integration) void SimulateElectronStep(G4HepEmData* hepEmData, G4HepEmParameters* hepEmPars, G4HepEmTLData* tlData) { // Get primary electron track from thread-local data G4HepEmElectronTrack* elTrack = tlData->GetPrimaryElectronTrack(); G4HepEmTrack* track = elTrack->GetTrack(); // Set up track properties track->SetEKin(100.0); // 100 MeV kinetic energy track->SetPosition(0.0, 0.0, 0.0); track->SetDirection(1.0, 0.0, 0.0); track->SetMCIndex(0); // Material-cuts couple index track->SetCharge(-1.0); // Electron charge // Calculate physics step length (how far particle travels) G4HepEmElectronManager::HowFar(hepEmData, hepEmPars, tlData); // After geometry navigation, perform physics interactions G4HepEmElectronManager::Perform(hepEmData, hepEmPars, tlData); // Check for secondary particles int numSecElectrons = tlData->GetNumSecondaryElectronTrack(); int numSecGammas = tlData->GetNumSecondaryGammaTrack(); for (int i = 0; i < numSecElectrons; ++i) { G4HepEmElectronTrack* secTrack = tlData->GetSecondaryElectronTrack(i); double secEnergy = secTrack->GetTrack()->GetEKin(); // Process secondary electron... } // Reset secondary counters for next step tlData->ResetNumSecondaryElectronTrack(); tlData->ResetNumSecondaryGammaTrack(); } ``` -------------------------------- ### Link zlib for Shared G4HepEm Initialization Library (CMake) Source: https://github.com/mnovak42/g4hepem/blob/master/G4HepEm/G4HepEmInit/CMakeLists.txt Conditionally links the `Geant4::G4zlib` or `ZLIB::ZLIB` library to the `g4HepEmInit` target if `BUILD_SHARED_LIBS` is enabled. This ensures the shared library has access to zlib functionality. ```cmake if(BUILD_SHARED_LIBS) if(TARGET Geant4::G4zlib) target_link_libraries(g4HepEmInit PUBLIC Geant4::G4zlib) elseif(TARGET ZLIB::ZLIB) target_link_libraries(g4HepEmInit PUBLIC ZLIB::ZLIB) endif() endif() ``` -------------------------------- ### Create G4HepEm Initialization Library (CMake) Source: https://github.com/mnovak42/g4hepem/blob/master/G4HepEm/G4HepEmInit/CMakeLists.txt Defines a CMake target `g4HepEmInit` using the `g4hepem_add_library` command. It specifies the source files, header files, and links against `g4HepEmData` and required Geant4 libraries. ```cmake g4hepem_add_library(g4HepEmInit SOURCES ${G4HEPEMInit_sources} HEADERS ${G4HEPEMInit_headers} LINK g4HepEmData ${G4HEPEMInit_Geant4_LIBRARIES}) ``` -------------------------------- ### Sample Compton Scattering Parameters (C++) Source: https://context7.com/mnovak42/g4hepem/llms.txt Samples Compton scattering energy and direction directly, suitable for GPU execution. This function takes a random engine and samples the final energy and direction of the scattered photon, as well as the energy of the resulting Compton electron. ```cpp #include "G4HepEmGammaInteractionCompton.hh" #include "G4HepEmTLData.hh" #include "G4HepEmData.hh" #include "G4HepEmRandomEngine.hh" // Sample Compton scattering directly (GPU-compatible) void SampleComptonScattering(G4HepEmRandomEngine* rnge) { double gammaEnergy = 1.0; // 1 MeV photon double gammaDir[3] = {1.0, 0.0, 0.0}; double orgDir[3] = {1.0, 0.0, 0.0}; // Sample scattered photon energy and direction double finalEnergy = G4HepEmGammaInteractionCompton::SamplePhotonEnergyAndDirection( gammaEnergy, gammaDir, orgDir, rnge); // Compton electron energy double electronEnergy = gammaEnergy - finalEnergy; } ``` -------------------------------- ### G4HepEmRunManager: Core Run Management for HEP EM Simulation Source: https://context7.com/mnovak42/g4hepem/llms.txt This C++ code illustrates the usage of G4HepEmRunManager for managing global data structures and particle-specific data for e-/e+ and gamma transport. It covers initialization for master and worker threads, random engine integration, and accessing data structures. It requires Geant4 headers and G4HepEm headers. ```cpp #include "G4HepEmRunManager.hh" #include "G4HepEmRandomEngine.hh" #include "G4HepEmData.hh" #include "G4HepEmParameters.hh" #include "Randomize.hh" // Create master run manager (on master thread) G4HepEmRunManager* masterRM = new G4HepEmRunManager(true); // Create random engine wrapper G4HepEmRandomEngine* rngEngine = new G4HepEmRandomEngine(G4Random::getTheEngine()); // Initialize for different particle types: // 0 = electron, 1 = positron, 2 = gamma masterRM->Initialize(rngEngine, 0); // Initialize electron data masterRM->Initialize(rngEngine, 1); // Initialize positron data masterRM->Initialize(rngEngine, 2); // Initialize gamma data // Access the initialized data structures G4HepEmData* hepEmData = masterRM->GetHepEmData(); G4HepEmParameters* hepEmPars = masterRM->GetHepEmParameters(); // Create worker run manager (on worker threads) G4HepEmRunManager* workerRM = new G4HepEmRunManager(false); workerRM->Initialize(rngEngine, 0); // Sets pointers to master data // Access thread-local data for particle tracking G4HepEmTLData* tlData = workerRM->GetTheTLData(); // Clean up when done masterRM->Clear(); delete masterRM; ``` -------------------------------- ### Link Libraries for 'testBrem' Source: https://github.com/mnovak42/g4hepem/blob/master/testing/testElectronInteractionBrem/CMakeLists.txt Links the necessary libraries to the 'testBrem' executable. This includes 'g4HepEm', 'TestUtils', and Geant4 libraries, ensuring all dependencies are resolved. ```cmake target_link_libraries(testBrem PRIVATE g4HepEm TestUtils ${Geant4_LIBRARIES}) ``` -------------------------------- ### G4HepEmTrackingManager: Custom Particle Tracking for Geant4 Source: https://context7.com/mnovak42/g4hepem/llms.txt This C++ code demonstrates how to integrate G4HepEmTrackingManager into a Geant4 physics list to replace standard tracking for e-/e+/gamma particles. It shows configuration of Geant4 EM parameters, enabling Woodcock tracking, setting MSC and energy loss parameters per region, and registering the tracking manager for specific particles. It requires Geant4 and G4HepEm headers. ```cpp #include "G4HepEmTrackingManager.hh" #include "G4HepEmConfig.hh" #include "G4Electron.hh" #include "G4Positron.hh" #include "G4Gamma.hh" #include "G4EmParameters.hh" // In your physics list ConstructProcess() method: void MyPhysicsList::ConstructProcess() { // Configure Geant4 EM parameters G4EmParameters* param = G4EmParameters::Instance(); param->SetDefaults(); param->SetMscRangeFactor(0.04); // Create G4HepEm tracking manager with verbosity level G4HepEmTrackingManager* trackingManager = new G4HepEmTrackingManager(1); // Get configuration object for advanced settings G4HepEmConfig* config = trackingManager->GetConfig(); // Enable Woodcock tracking for photons in specific region config->SetWoodcockTrackingRegion("Calorimeter_Region"); // Configure MSC parameters per region config->SetMSCRangeFactor(0.06, "Tracker_Region"); config->SetMSCSafetyFactor(0.7, "Tracker_Region"); // Configure energy loss parameters config->SetEnergyLossStepLimitFunctionParameters(0.2, 1.0, "Calorimeter_Region"); // Enable/disable energy loss fluctuation per region config->SetEnergyLossFluctuation(true, "Calorimeter_Region"); // Register tracking manager for all EM particles G4Electron::Definition()->SetTrackingManager(trackingManager); G4Positron::Definition()->SetTrackingManager(trackingManager); G4Gamma::Definition()->SetTrackingManager(trackingManager); } ``` -------------------------------- ### Simulate Bremsstrahlung Interaction with G4HepEmElectronInteractionBrem Source: https://context7.com/mnovak42/g4hepem/llms.txt Implements bremsstrahlung photon emission for electrons and positrons using Seltzer-Berger and Bethe-Heitler models. Supports both thread-local data and direct sampling for photon energy and directions. ```cpp #include "G4HepEmElectronInteractionBrem.hh" #include "G4HepEmData.hh" #include "G4HepEmRandomEngine.hh" #include "G4HepEmTLData.hh" // Perform bremsstrahlung interaction void PerformBremsstrahlung(G4HepEmTLData* tlData, G4HepEmData* hepEmData) { G4HepEmElectronTrack* elTrack = tlData->GetPrimaryElectronTrack(); double ekin = elTrack->GetTrack()->GetEKin(); // Determine which model to use based on energy bool useSBmodel = (ekin < 1000.0); // Use Seltzer-Berger below 1 GeV bool isElectron = (elTrack->GetCharge() < 0); // Perform the interaction G4HepEmElectronInteractionBrem::Perform(tlData, hepEmData, isElectron, useSBmodel); // Secondary gamma is added to tlData int numGammas = tlData->GetNumSecondaryGammaTrack(); if (numGammas > 0) { G4HepEmGammaTrack* bremGamma = tlData->GetSecondaryGammaTrack(0); double gammaEnergy = bremGamma->GetTrack()->GetEKin(); } } // Sample bremsstrahlung photon energy directly (GPU-compatible) void SampleBremPhotonEnergy(G4HepEmData* hepEmData, G4HepEmRandomEngine* rnge) { double primaryEkin = 500.0; // 500 MeV electron double logPrimEkin = G4HepEmLog(primaryEkin); int imcIndex = 0; // Material-cuts index bool isElectron = true; // Sample using Seltzer-Berger model (for E < 1 GeV) double gammaEnergy = G4HepEmElectronInteractionBrem::SampleETransferSB( hepEmData, primaryEkin, logPrimEkin, imcIndex, rnge, isElectron); // For high energies (E > 1 GeV), use relativistic Bethe-Heitler model double highEkin = 10000.0; // 10 GeV double gammaEnergyRB = G4HepEmElectronInteractionBrem::SampleETransferRB( hepEmData, highEkin, G4HepEmLog(highEkin), imcIndex, rnge, isElectron); // Sample directions for primary electron and secondary gamma double primDir[3] = {1.0, 0.0, 0.0}; double secGammaDir[3]; G4HepEmElectronInteractionBrem::SampleDirections( primaryEkin, gammaEnergy, secGammaDir, primDir, rnge); } ``` -------------------------------- ### Configure G4HepEm Physics Parameters Per Region (C++) Source: https://context7.com/mnovak42/g4hepem/llms.txt This C++ code snippet demonstrates how to configure G4HepEm physics parameters for different detector regions using the G4HepEmConfig class. It allows fine-tuning of settings like Woodcock tracking, energy loss step limiting, Multiple Scattering (MSC) parameters, and secondary production cuts. ```cpp #include "G4HepEmConfig.hh" #include "G4HepEmTrackingManager.hh" void ConfigureG4HepEm(G4HepEmTrackingManager* tm) { G4HepEmConfig* config = tm->GetConfig(); // Enable Woodcock (delta) tracking for photons in a region config->SetWoodcockTrackingRegion("Calorimeter", true); config->SetWDTEnergyLimit(100.0); // Turn off WDT below 100 keV // Configure energy loss step limiting per region // dRoverRange: fraction of range used for step limit // finalRange: range below which step = range config->SetEnergyLossStepLimitFunctionParameters(0.2, 1.0, "Tracker"); config->SetEnergyLossStepLimitFunctionParameters(0.1, 0.5, "Calorimeter"); // Configure MSC parameters per region config->SetMSCRangeFactor(0.04, "Tracker"); // Tighter MSC in tracker config->SetMSCRangeFactor(0.08, "Calorimeter"); // Looser in calorimeter config->SetMSCSafetyFactor(0.6, "Tracker"); config->SetMSCSafetyFactor(0.8, "Calorimeter"); // Use minimal MSC step limit in high-precision region config->SetMinimalMSCStepLimit(true, "Vertex_Region"); // Enable/disable energy loss fluctuations config->SetEnergyLossFluctuation(true, "Tracker"); config->SetEnergyLossFluctuation(false, "Calorimeter"); // Faster, less accurate // Control multiple steps in combined MSC+Transportation config->SetMultipleStepsInMSCWithTransportation(true, "Tracker"); // Apply secondary production cuts to all processes (not just ioni/brem) config->SetApplyCuts(true, "Tracker"); // Print configuration config->Dump(); } ``` -------------------------------- ### Import G4HepEm State from JSON (C++) Source: https://context7.com/mnovak42/g4hepem/llms.txt Imports a complete G4HepEm state, including physics data and parameters, from a JSON file. It deserializes the state and provides access to the loaded data and parameters. ```cpp #include "G4HepEmDataJsonIO.hh" #include "G4HepEmState.hh" #include // Import complete state from JSON G4HepEmState* ImportHepEmState(const std::string& filename) { std::ifstream jsonFile(filename); G4HepEmState* state = G4HepEmStateFromJson(jsonFile); jsonFile.close(); if (state != nullptr) { G4HepEmData* data = state->fData; G4HepEmParameters* params = state->fParameters; // Use imported data and parameters... } return state; } ``` -------------------------------- ### Set Include Directories for 'testBrem' Source: https://github.com/mnovak42/g4hepem/blob/master/testing/testElectronInteractionBrem/CMakeLists.txt Specifies the include directories for the 'testBrem' target. It makes header files in the 'include' directory relative to the current source directory available during compilation. ```cmake target_include_directories(testBrem PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) ``` -------------------------------- ### Specify Include Directories for Test Executable Source: https://github.com/mnovak42/g4hepem/blob/master/testing/GammaXSections/CMakeLists.txt Sets the include directories for the 'TestGammaXSectionData' executable. It adds the 'include' directory from the current source directory as a private dependency. ```cmake target_include_directories(TestGammaXSectionData PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) ``` -------------------------------- ### Link Libraries to Executable (CMake) Source: https://github.com/mnovak42/g4hepem/blob/master/testing/DataImportExport/CMakeLists.txt Links the necessary libraries to the 'TestDataImportExport' executable. This ensures that all required dependencies are available at runtime. ```cmake target_link_libraries(TestDataImportExport \ PRIVATE \ g4HepEm g4HepEmDataJsonIO TestUtils ${Geant4_LIBRARIES}) ``` -------------------------------- ### Define Executable and Source Files (CMake) Source: https://github.com/mnovak42/g4hepem/blob/master/testing/DataImportExport/CMakeLists.txt Defines the 'TestDataImportExport' executable and lists its source and header files. This is a fundamental step in building the project's executables. ```cmake add_executable(TestDataImportExport \ TestDataImportExport.cc \ include/SimpleFakeG4Setup.h \ src/SimpleFakeG4Setup.cc) ``` -------------------------------- ### Sample Pair Production Parameters (C++) Source: https://context7.com/mnovak42/g4hepem/llms.txt Samples electron-positron pair production kinetic energies and directions directly, optimized for GPU. This function takes G4HepEmData and a random engine to sample the energies and directions of the created electron and positron. ```cpp #include "G4HepEmGammaInteractionConversion.hh" #include "G4HepEmTLData.hh" #include "G4HepEmData.hh" #include "G4HepEmRandomEngine.hh" // Sample pair production directly (GPU-compatible) void SamplePairProduction(G4HepEmData* hepEmData, G4HepEmRandomEngine* rnge) { double gammaEnergy = 100.0; // 100 MeV photon double logGammaE = G4HepEmLog(gammaEnergy); int imcIndex = 0; double electronKinE, positronKinE; // Sample kinetic energies of electron and positron G4HepEmGammaInteractionConversion::SampleKinEnergies( hepEmData, gammaEnergy, logGammaE, imcIndex, electronKinE, positronKinE, rnge); // Sample directions double orgGammaDir[3] = {1.0, 0.0, 0.0}; double electronDir[3], positronDir[3]; G4HepEmGammaInteractionConversion::SampleDirections( orgGammaDir, electronDir, positronDir, electronKinE, positronKinE, rnge); } ``` -------------------------------- ### Define Geant4 Libraries for G4HepEm Initialization (CMake) Source: https://github.com/mnovak42/g4hepem/blob/master/G4HepEm/G4HepEmInit/CMakeLists.txt Defines a CMake variable `G4HEPEMInit_Geant4_LIBRARIES` listing the necessary Geant4 libraries for the G4HepEm initialization. These include core Geant4 modules required for physics simulations. ```cmake set(G4HEPEMInit_Geant4_LIBRARIES Geant4::G4global Geant4::G4materials Geant4::G4particles Geant4::G4processes ) ``` -------------------------------- ### Define G4HepEm Initialization Sources (CMake) Source: https://github.com/mnovak42/g4hepem/blob/master/G4HepEm/G4HepEmInit/CMakeLists.txt Defines a CMake variable `G4HEPEMInit_sources` containing a list of source files for the G4HepEm initialization module. These source files implement the functionality for initializing G4HepEm. ```cmake set(G4HEPEMInit_sources src/G4HepEmElectronInit.cc src/G4HepEmElectronTableBuilder.cc src/G4HepEmGammaInit.cc src/G4HepEmGammaTableBuilder.cc src/G4HepEmInitUtils.cc src/G4HepEmMaterialInit.cc src/G4HepEmParametersInit.cc src/G4HepEmSBBremTableBuilder.cc src/G4HepEmStateInit.cc ) ``` -------------------------------- ### Add Executable 'testBrem' with CUDA Support Source: https://github.com/mnovak42/g4hepem/blob/master/testing/testElectronInteractionBrem/CMakeLists.txt Defines the 'testBrem' executable, compiling source files including conditional CUDA files based on the G4HepEm_CUDA_BUILD flag. This allows for GPU acceleration when available. ```cmake add_executable(testBrem testBrem.cc src/Implementation.cc src/TestBremArgs.cc $<$:src/SBTableData.cu>) ``` -------------------------------- ### Add Executable for G4HepEm Initialization Test Source: https://github.com/mnovak42/g4hepem/blob/master/testing/DataInitialization/CMakeLists.txt Defines an executable target named 'TestG4HepEmInit' and specifies its source file as 'TestG4HepEmInit.cc'. This is a common CMake command for building standalone programs. ```cmake add_executable(TestG4HepEmInit TestG4HepEmInit.cc) ``` -------------------------------- ### Sample Photoelectric Effect Directly in G4HepEm (C++) Source: https://context7.com/mnovak42/g4hepem/llms.txt Samples the photoelectric effect directly, suitable for GPU compatibility. It calculates the macroscopic cross-section, selects binding energy, and determines photoelectron energy and direction. ```cpp #include "G4HepEmGammaInteractionPhotoelectric.hh" #include "G4HepEmData.hh" #include "G4HepEmRandomEngine.hh" // Sample photoelectric effect directly (GPU-compatible) void SamplePhotoelectric(G4HepEmData* hepEmData, G4HepEmRandomEngine* rnge) { double gammaEnergy = 0.1; // 100 keV photon int imcIndex = 0; // Get photoelectric macroscopic cross-section double mxsec = G4HepEmGammaManager::GetMacXSecPE(hepEmData, 0, gammaEnergy); // Select element and get binding energy double bindingEnergy = G4HepEmGammaInteractionPhotoelectric::SelectElementBindingEnergy( hepEmData, imcIndex, mxsec, gammaEnergy, rnge); // Photoelectron energy double photoelectronE = gammaEnergy - bindingEnergy; // Sample photoelectron direction double gammaDir[3] = {1.0, 0.0, 0.0}; double electronDir[3]; G4HepEmGammaInteractionPhotoelectric::SamplePhotoElectronDirection( gammaEnergy, gammaDir, electronDir, rnge); } ``` -------------------------------- ### Run G4HepEM Data Import/Export Test (Shell) Source: https://github.com/mnovak42/g4hepem/blob/master/testing/DataImportExport/Readme.md Executes the G4HepEM data import/export test in either 'full' or 'simple' mode. This command is run from the build directory. ```shell ./Testing/DataImportExport/TestDataImportExport full ``` ```shell ./Testing/DataImportExport/TestDataImportExport simple ``` -------------------------------- ### Link Libraries for TestEnergyLossData (CMake) Source: https://github.com/mnovak42/g4hepem/blob/master/testing/ElectronEnergyLoss/CMakeLists.txt Links the necessary libraries to the TestEnergyLossData executable. This includes g4HepEm, TestUtils, and Geant4 libraries, which are essential for the executable's functionality. ```cmake target_link_libraries(TestEnergyLossData \ PRIVATE \ g4HepEm TestUtils ${Geant4_LIBRARIES}) ``` -------------------------------- ### Add 'TestBrem-Interaction' Test Source: https://github.com/mnovak42/g4hepem/blob/master/testing/testElectronInteractionBrem/CMakeLists.txt Defines a test case named 'TestBrem-Interaction' that executes the 'testBrem' command. This is used for verifying the functionality of the 'testBrem' executable. ```cmake add_test(NAME TestBrem-Interaction COMMAND testBrem) ```