31.1. Organizing Source Code
Table of Contents
Why Source Code Organization Matters
For small test programs, you can put almost everything into a few files and still manage to find your way around. For any realistic Geant4 application, this quickly becomes painful. Clear source code organization makes it easier to understand your simulation, to extend it, to debug it, and to let others (or your future self) work on it.
Geant4 encourages a modular structure through its class design. Your goal is to reflect that modularity in your directory layout, file naming, and dependencies between parts of the code. In this chapter we focus on practical structure, not on C++ syntax or Geant4 physics.
A well organized project:
- Separates independent concerns into separate files and directories.
- Keeps dependencies one way, from high level to low level, not in circles.
- Groups related classes so you can find and reuse them.
Mirror the Geant4 Simulation Structure
A simple way to start is to mirror the main conceptual blocks of a Geant4 simulation. You already know the roles of geometry, physics, primary generation, and actions from earlier chapters. Each of these can correspond to groups of source files.
Typically, you will have one main file that creates the run manager and plugs in user classes. Around this center you organize user code for geometry, physics, primary generation, and analysis. This keeps each part focused, with clear responsibilities, and avoids mixing unrelated logic inside single classes.
When the project grows, you can subdivide these groups further. For example, geometry can be split into world geometry, individual detector components, and support structures. Actions can separate event level, track level, and step level logic into their respective classes, not only because Geant4 requires it, but also because it keeps different levels of logic clearly isolated.
Typical Directory Layout for a Geant4 Project
Although Geant4 does not enforce a particular directory layout, a conventional structure makes your project easier to understand and use. A common pattern is to split the project into source code, headers, build directory, macros, and optional configuration or data files.
A simple and practical layout looks like this:
| Directory or file | Typical contents |
|---|---|
CMakeLists.txt | Build configuration for the whole project |
src/ | All .cc implementation files |
include/ | All .hh header files |
macros/ | Macro files used to configure and run simulations |
data/ | Additional data files specific to the application |
vis/ | Optional visualization macros or styles |
build/ | Out of source build directory, created by you |
Inside src and include you can further group related classes into subdirectories. For example, geometry classes under geometry, detector specific code under detectors, and analysis classes under analysis. The important point is consistency. If a class header is in include/geometry, its implementation belongs under src/geometry with the same base filename.
Rule of thumb: one class per header and source file, in matching subdirectories, with matching names.
This avoids large, monolithic files that contain many unrelated classes and makes it much easier to locate the implementation of a given class.
Grouping Related Classes
Within your src and include directories, think in terms of functional groups, not in terms of the order in which you wrote the classes. The following grouping works well for many Geant4 applications.
Geometry and materials classes form one group. Your main detector construction class resides here, together with helper classes for complex detector components and any material factory classes that create custom materials.
Primary generation forms another small group. The primary generator action and any custom source description code, spectra loaders, or GPS helper classes can live together.
Physics configuration can be in its own group. If you write custom physics lists or modify reference lists, keep that code separate from the rest.
User actions such as run, event, stepping, and tracking actions are closely related and should be grouped. They all manage the flow of data through the simulation and often coordinate with analysis code.
Analysis code, such as classes that wrap G4AnalysisManager or manage histograms and ntuples, should be kept together and not mixed into geometry or primary generator code.
You can reflect these groups in subdirectories, for example:
| Subdirectory | Typical contents |
|---|---|
geometry/ | Detector construction and component classes |
materials/ | Material definitions and helpers |
primary/ | Primary generator actions and source helpers |
physics/ | Physics list configuration classes |
actions/ | Run, event, stepping, tracking, stacking actions |
analysis/ | Histogram, ntuple, and output file management |
Using this style, the path of a file already tells you its role and approximate dependencies.
Managing Dependencies Between Modules
Good organization is not only about where files sit, but also about how they depend on each other. Cyclic dependencies make code harder to compile, refactor, and test. In Geant4 applications, a clean dependency direction is especially useful.
A practical dependency order from low level to high level is:
- Utility and configuration code, which should not depend on any detector specific classes.
- Materials and simple geometry helpers.
- Detector components and overall detector construction.
- Physics list configuration.
- Primary generator description.
- User actions that observe and record what happens.
- Analysis and output.
Your main program sits on top and knows about all these modules. The lower a module is in this list, the fewer project specific things it should know. Ideally, geometry should not know about analysis. Geometry does not need to fill histograms, it only needs to define where things are. Analysis code can query energy deposit in volumes, using sensitive detectors and hits, without adding dependencies back into geometry.
Avoid tying geometry, physics, and primary generation directly to analysis output. Let analysis observe, not control, the rest of the simulation.
This makes it far easier to reuse geometry in another project, or to switch from one analysis backend to another, without touching the core of your simulation.
Splitting Geometry into Reusable Components
Detector constructions become complex very quickly. If you put everything into a single DetectorConstruction class, it will soon be long and hard to modify. A more scalable method is to treat complex detectors as compositions of smaller parts. Each part can be a class that creates its own logical volumes and placements and then returns a handle to the top logical volume of that component.
For example, a scintillation detector setup can be built from separate classes that describe the scintillator crystal, light guides, photodetectors, and shielding. The main detector construction then creates the world and instantiates each component, placing them with G4PVPlacement calls. Each component class focuses on a single part of the geometry, and you can test and modify it without scrolling through the entire detector description.
By placing each component in its own header and source files and grouping them under a directory such as geometry/ or detectors/, you gain a library of reusable parts. Another simulation can reuse a detector module by including its header and linking the corresponding source file, without copying large blocks of code.
Organizing User Actions and Analysis Hooks
User action classes are the natural place to access simulation results and pass them to analysis. To keep code organization clean, let each action focus on its own level. For example, the event action can collect event level quantities, but should not handle file opening and closing. Run action is better suited for that.
You can design a small analysis manager class of your own that wraps G4AnalysisManager calls. This manager can expose simple methods such as FillEnergySpectrum or RecordHit, and hide details of histogram IDs and column indices. User actions then depend only on your analysis manager interface, not directly on how histograms are organized.
Keep analysis classes under a dedicated analysis/ directory, and pass pointers or references to these classes into your action initialization. This keeps initialization code in one place and avoids scattering file names and histogram definitions throughout the application.
This separation makes it easy to change the analysis output format. If you later decide to switch from ROOT to CSV output, most changes occur inside analysis classes, not in geometry or primary generator code.
Configuration and Parameters in a Structured Project
Once your project has a clear structure, you can also think clearly about where configuration lives. Hard coding physical parameters into many classes makes it difficult to perform parameter studies or to maintain consistency. A more organized approach is to centralize key parameters and expose them through a configuration class or macro commands.
A configuration class can hold values such as detector dimensions, material choices, and source characteristics. Geometry and primary generator classes can query this configuration rather than using literal numbers. Place such configuration classes under a directory such as config/ or keep them close to the main program if they are simple.
You can also connect configuration to the Geant4 command system. For example, a messenger class can modify parameters in your configuration object in response to macro commands. This allows you to change aspects of your simulation through macro files without recompilation, while still keeping code structure clean and consistent.
Scaling Up: From Example to Framework
As you gain experience, your Geant4 project can evolve from a single application into a small framework for your group or for a particular class of detectors. The organization principles remain the same, but you start thinking of directories as modules that you could plug into more than one executable.
For example, you may keep a generic detector framework under one top level directory, and several applications under another. Each application then selects components, geometry modules, and analysis modules that it needs. This is easiest if you have already kept modules independent, with their own headers and source files, and with a clean dependency direction.
Even for beginners, adopting a consistent layout and grouping from the start makes this evolution smoother. You do not need to design a large framework in advance, you only need to avoid mixing unrelated responsibilities and to keep files small, focused, and easy to locate.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Introduction to Geant4
- ☰ 1.1. What Is Geant4?
- ☰ 1.2. How Geant4 Works
- ☰ 1.3. Geant4 Simulation Structure
- ☰ 1.4. Geant4 and C++
-
- ☰ 2. Installing Geant4
- ☰ 2.1. Geant4 Requirements
- ☰ 2.2. Installing Geant4 on Linux
- ☰ 2.3. Installing Visualization Libraries
- ☰ 2.4. Verifying the Installation
- ☰ 2.5. Geant4 Example Applications
-
- ☰ 3. C++ Basics for Geant4
- ☰ 3.1. Classes and Objects
- ☰ 3.2. Inheritance
- ☰ 3.3. Pointers and References
- ☰ 3.4. Header and Source Files
- ☰ 3.5. Standard Library Containers
-
- ☰ 4. Creating Your First Geant4 Project
- ☰ 4.1. Project Structure
- ☰ 4.2. CMake Configuration
- ☰ 4.3. The Main Program
- ☰ 4.4. User Initialization Classes
- ☰ 4.5. Building and Running
-
- ☰ 5. Geant4 Units and Constants
- ☰ 5.1. Geant4 Unit System
- ☰ 5.2. Using Units in C++
- ☰ 5.3. Physical Constants
- ☰ 5.4. Printing Values with Units
-
- ☰ 6. Creating the Simulation World
- ☰ 6.1. DetectorConstruction
- ☰ 6.2. Solids
- ☰ 6.3. Logical Volumes
- ☰ 6.4. Physical Volumes
- ☰ 6.5. Creating the World Volume
-
- ☰ 7. Materials
- ☰ 7.1. Geant4 Materials
- ☰ 7.2. NIST Material Database
- ☰ 7.3. Common Materials
- ☰ 7.4. Creating Custom Materials
- ☰ 7.5. Detector Materials
-
- ☰ 8. Building Detector Geometry
- ☰ 8.1. Basic Geometrical Shapes
- ☰ 8.2. Boolean Solids
- ☰ 8.3. Positioning Volumes
- ☰ 8.4. Repeated Geometry
- ☰ 8.5. Detector Arrays
- ☰ 8.6. Geometry Overlap Checking
-
- ☰ 9. Geometry Visualization
- ☰ 9.1. Visualization in Geant4
- ☰ 9.2. Starting the Visualization System
- ☰ 9.3. Changing the View
- ☰ 9.4. Visualization Attributes
- ☰ 9.5. Displaying Particle Tracks
-
- ☰ 10. Primary Particle Generation
- ☰ 10.1. PrimaryGeneratorAction
- ☰ 10.2. Particle Gun
- ☰ 10.3. Particle Energy
- ☰ 10.4. Particle Position
- ☰ 10.5. Particle Direction
- ☰ 10.6. Common Particle Sources
-
- ☰ 11. General Particle Source
- ☰ 11.1. Introduction to GPS
- ☰ 11.2. Position Distributions
- ☰ 11.3. Angular Distributions
- ☰ 11.4. Energy Distributions
- ☰ 11.5. Configuring Sources with Macros
-
- ☰ 12. Physics Lists
- ☰ 12.1. What Is a Physics List?
- ☰ 12.2. Reference Physics Lists
- ☰ 12.3. Electromagnetic Physics
- ☰ 12.4. Gamma Interactions
- ☰ 12.5. Positron Physics
- ☰ 12.6. Hadronic Physics
- ☰ 12.7. Choosing a Physics List
-
- ☰ 13. Particle Tracking
- ☰ 13.1. Tracks
- ☰ 13.2. Steps
- ☰ 13.3. Energy Deposition
- ☰ 13.4. Track Status
- ☰ 13.5. Parent and Secondary Particles
-
- ☰ 14. User Actions
- ☰ 14.1. RunAction
- ☰ 14.2. EventAction
- ☰ 14.3. SteppingAction
- ☰ 14.4. TrackingAction
- ☰ 14.5. StackingAction
- ☰ 14.6. ActionInitialization
-
- ☰ 15. Sensitive Detectors
- ☰ 15.1. What Is a Sensitive Detector?
- ☰ 15.2. Creating a Sensitive Detector
- ☰ 15.3. Hits
- ☰ 15.4. Hit Collections
- ☰ 15.5. Assigning Sensitive Detectors
-
- ☰ 16. Recording Energy Deposition
- ☰ 16.1. Energy Deposition
- ☰ 16.2. Energy per Event
- ☰ 16.3. Energy per Detector
- ☰ 16.4. Energy Spectra
- ☰ 16.5. Detector Efficiency
-
- ☰ 17. Particle Position and Timing
- ☰ 17.1. Particle Position
- ☰ 17.2. Interaction Position
- ☰ 17.3. Global Time
- ☰ 17.4. Time of Flight
- ☰ 17.5. Detector Timing
-
- ☰ 18. Geant4 Analysis System
- ☰ 18.1. Introduction to G4AnalysisManager
- ☰ 18.2. Histograms
- ☰ 18.3. Ntuples
- ☰ 18.4. Filling Ntuples
- ☰ 18.5. Writing Output Files
- ☰ 18.6. Closing Analysis Files
-
- ☰ 19. Geant4 and ROOT
- ☰ 19.1. ROOT Output from Geant4
- ☰ 19.2. Reading Geant4 Output with ROOT
- ☰ 19.3. Plotting Energy Spectra
- ☰ 19.4. Event Analysis
- ☰ 19.5. Simulation-to-Analysis Workflow
-
- ☰ 20. Geant4 Macro Commands
- ☰ 20.1. Macro Files
- ☰ 20.2. Run Commands
- ☰ 20.3. Particle Source Commands
- ☰ 20.4. Visualization Commands
- ☰ 20.5. Controlling Simulations Without Recompiling
-
- ☰ 21. Random Numbers and Reproducibility
- ☰ 21.1. Monte Carlo Random Numbers
- ☰ 21.2. Setting Random Seeds
- ☰ 21.3. Running Independent Simulations
- ☰ 21.4. Reproducing an Event
-
- ☰ 22. Multithreading
- ☰ 22.1. Geant4 Multithreading
- ☰ 22.2. Running with Multiple Threads
- ☰ 22.3. Thread-Safe User Code
- ☰ 22.4. Analysis with Multithreading
- ☰ 22.5. Performance Considerations
-
- ☰ 23. Practical Example: Gamma-Ray Detector
- ☰ 23.1. Project Overview
- ☰ 23.2. Creating the World
- ☰ 23.3. Creating the Detector
- ☰ 23.4. Adding the Material
- ☰ 23.5. Creating a Gamma Source
- ☰ 23.6. Selecting Electromagnetic Physics
- ☰ 23.7. Recording Energy Deposition
- ☰ 23.8. Creating an Energy Spectrum
- ☰ 23.9. Simulating Detector Resolution
- ☰ 23.10. Analyzing the Spectrum with ROOT
-
- ☰ 24. Practical Example: Radiation Shielding
- ☰ 24.1. Project Overview
- ☰ 24.2. Creating the Source
- ☰ 24.3. Creating the Shield
- ☰ 24.4. Comparing Shielding Materials
- ☰ 24.5. Varying Shield Thickness
- ☰ 24.6. Recording Transmitted Particles
- ☰ 24.7. Calculating Transmission
- ☰ 24.8. Calculating Attenuation
- ☰ 24.9. Comparing Simulation Results
-
- ☰ 25. Practical Example: PET Scanner
- ☰ 25.1. Introduction to PET Simulation
- ☰ 25.2. Creating a PET Detector Ring
- ☰ 25.3. Creating Detector Crystals
- ☰ 25.4. Assigning Detector IDs
- ☰ 25.5. Creating a Positron Source
- ☰ 25.6. Simulating Positron Annihilation
- ☰ 25.7. Recording Detector Hits
- ☰ 25.8. Applying an Energy Window
- ☰ 25.9. Finding Coincidence Events
- ☰ 25.10. Recording Detector Positions
- ☰ 25.11. Creating Lines of Response
- ☰ 25.12. Saving PET Events to ROOT
- ☰ 25.13. Analyzing PET Data with ROOT
-
- ☰ 26. Practical Example: Proton Beam in Water
- ☰ 26.1. Project Overview
- ☰ 26.2. Creating the Water Phantom
- ☰ 26.3. Creating a Proton Beam
- ☰ 26.4. Selecting the Physics List
- ☰ 26.5. Recording Energy Deposition
- ☰ 26.6. Dividing the Phantom into Slices
- ☰ 26.7. Calculating Depth Dose
- ☰ 26.8. Observing the Bragg Peak
- ☰ 26.9. Plotting the Depth-Dose Curve
-
- ☰ 27. Detector Resolution and Smearing
- ☰ 27.1. Ideal vs Realistic Detector Response
- ☰ 27.2. Energy Resolution
- ☰ 27.3. Position Resolution
- ☰ 27.4. Time Resolution
- ☰ 27.5. Applying Detector Effects
- ☰ 27.6. Comparing Ideal and Smeared Results
-
- ☰ 28. Simulation Validation
- ☰ 28.1. Why Validate a Simulation?
- ☰ 28.2. Checking Geometry
- ☰ 28.3. Checking Energy Conservation
- ☰ 28.4. Comparing with Analytical Calculations
- ☰ 28.5. Comparing with Reference Data
- ☰ 28.6. Statistical Uncertainties
- ☰ 28.7. Number of Simulated Events
-
- ☰ 29. Improving Simulation Performance
- ☰ 29.1. Geometry Performance
- ☰ 29.2. Physics List Performance
- ☰ 29.3. Production Cuts
- ☰ 29.4. Reducing Unnecessary Output
- ☰ 29.5. Multithreading
- ☰ 29.6. Running Large Simulations
- ☰ 29.7. Parameter Scans
-
- ☰ 30. Debugging Geant4 Simulations
- ☰ 30.1. Compilation Errors
- ☰ 30.2. Geometry Errors
- ☰ 30.3. Overlapping Volumes
- ☰ 30.4. Missing Particles
- ☰ 30.5. Missing Energy Deposition
- ☰ 30.6. Physics List Problems
- ☰ 30.7. Sensitive Detector Problems
- ☰ 30.8. Empty Output Files
- ☰ 30.9. Segmentation Faults
- ☰ 30.10. Using Geant4 Verbose Output
-
- ☰ 31. Writing Better Geant4 Applications
- ☰ 31.1. Organizing Source Code
- ☰ 31.2. Separating Geometry and Analysis
- ☰ 31.3. Using Configuration Parameters
- ☰ 31.4. Avoiding Hard-Coded Values
- ☰ 31.5. Creating Reusable Detector Components
- ☰ 31.6. Naming Conventions
- ☰ 31.7. Documentation
- ☰ 31.8. Version Control with Git
-
- ☰ 32. Advanced Geometry
- ☰ 32.1. Parameterized Geometry
- ☰ 32.2. Replica Volumes
- ☰ 32.3. Nested Geometry
- ☰ 32.4. Complex Detector Arrays
- ☰ 32.5. Importing CAD Geometry
- ☰ 32.6. Exporting Geometry with GDML
-
- ☰ 33. Optical Photons
- ☰ 33.1. Introduction to Optical Physics
- ☰ 33.2. Optical Photons
- ☰ 33.3. Material Optical Properties
- ☰ 33.4. Scintillation Light
- ☰ 33.5. Optical Surfaces
- ☰ 33.6. Photodetectors
- ☰ 33.7. Counting Optical Photons
-
- ☰ 34. Medical Physics Applications
- ☰ 34.1. Geant4 in Medical Physics
- ☰ 34.2. Radiation Dose Simulation
- ☰ 34.3. PET Simulation
- ☰ 34.4. SPECT Simulation
- ☰ 34.5. Radiotherapy Simulation
- ☰ 34.6. Proton Therapy Simulation
- ☰ 34.7. Biological Tissue Materials
-
- ☰ 35. Final Project
- ☰ 35.1. Project Overview
- ☰ 35.2. Define the Simulation Goal
- ☰ 35.3. Create the Geometry
- ☰ 35.4. Define Materials
- ☰ 35.5. Configure the Particle Source
- ☰ 35.6. Select the Physics List
- ☰ 35.7. Implement Sensitive Detectors
- ☰ 35.8. Record Simulation Data
- ☰ 35.9. Run the Simulation
- ☰ 35.10. Analyze the Results with ROOT
- ☰ 35.11. Validate the Simulation
- ☰ 35.12. Create Scientific Figures
- ☰ 35.13. Document the Simulation
-
- ☰ 36. Appendices
- ☰ 36.1. Geant4 Class Cheat Sheet
- ☰ 36.2. Geant4 Units Cheat Sheet
- ☰ 36.3. Common Geant4 Macro Commands
- ☰ 36.4. Common Geometry Classes
- ☰ 36.5. Common Particle Definitions
- ☰ 36.6. Common Physics Lists
- ☰ 36.7. G4AnalysisManager Cheat Sheet
- ☰ 36.8. Common Visualization Commands
- ☰ 36.9. Common Geant4 Errors and Solutions
- ☰ 36.10. Recommended Geant4 Project Structure
- ☰ 36.11. Recommended Geant4 Simulation Workflow
-
Comments
Please login to add a comment.
Don't have an account? Register now!