API Reference

Core Classes

GeometryParser

class GeometryParser

Parses JSON configuration files for geometry and materials.

This class handles the parsing of external JSON configuration files for both detector geometry and materials. It provides methods to:

  • Load and parse JSON files

  • Create G4 materials from JSON descriptions

  • Create G4 volumes from JSON descriptions

Public Functions

G4VPhysicalVolume *ConstructGeometry()

Load materials configuration from JSON file.

Construct the complete detector geometry.

Create the world volume from loaded configuration

Creates the world volume and places all other volumes within it according to the loaded geometry configuration from the geometry-editor

Parameters:

filename – Path to materials JSON file

Returns:

Pointer to the physical world volume

Returns:

Pointer to the world physical volume

GeometryParser()

Constructor.

Default constructor for GeometryParser.

Initializes an empty geometry parser without loading any configuration

void LoadGeometryConfig(const std::string &filename)

Load geometry configuration from JSON file.

Load detector geometry configuration from a JSON file.

Reads and parses the geometry configuration file into the geometryConfig member and stores the config path for loading external files

Parameters:
  • filename – Path to geometry JSON file

  • filename – Path to the JSON configuration file

Throws:

std::runtime_error – if file cannot be opened or parsed

void SetupSensitiveDetectors()

Setup sensitive detectors for active volumes.

Import an assembled geometry from an external JSON file.

This method assigns sensitive detectors to volumes marked as active in the JSON config

Imports a geometry defined in an external JSON file and places it in the parent volume with the specified transformation.

Setup sensitive detectors for active volumes

This method assigns sensitive detectors to volumes marked as active in the JSON config

Parameters:
  • config – JSON configuration for the import

  • parentVolume – Parent logical volume to place the imported geometry in

Throws:

std::runtime_error – if import fails

~GeometryParser()

Destructor.

Destructor for GeometryParser.

Memory management of G4 objects is handled by Geant4

Private Functions

void ApplyVisualizationAttributes(G4LogicalVolume *logicalVolume, const json &config)

Apply visualization attributes to a logical volume based on material color.

Parameters:
  • logicalVolume – The logical volume to apply attributes to

  • config – JSON configuration for the volume

void CreateAssembly(const json &config)

Create an assembly from JSON configuration.

Import an assembled geometry from an external JSON file.

Imports a geometry defined in an external JSON file and places it in the parent volume with the specified transformation.

Parameters:
  • config – JSON configuration for the assembly

  • config – JSON configuration for the import

  • parentVolume – Parent logical volume to place the imported geometry in

Throws:

std::runtime_error – if import fails

G4VSolid *CreateBooleanSolid(const json &config, const std::string &name)

Create a boolean solid (union, subtraction, intersection)

Creates a boolean solid by combining two or more solids. For unions, supports multiple components in the new format.

Parameters:
  • config – JSON configuration for the boolean operation

  • name – Name for the resulting solid

  • config – JSON configuration for the boolean operation

  • name – Name for the resulting solid

Throws:

std::runtime_error – if boolean operation fails

Returns:

Pointer to created G4VSolid

Returns:

Pointer to created G4VSolid

G4VSolid *CreateBooleanSolidFromComponents(const json &config, const std::string &name)

Create a boolean solid from components in the new format.

Creates a boolean solid by recursively combining multiple components. First processes all union operations, then all subtraction operations.

Parameters:
  • config – JSON configuration for the union with components

  • name – Name for the resulting solid

  • config – JSON configuration for the union with components

  • name – Name for the resulting solid

Throws:

std::runtime_error – if boolean operation fails

Returns:

Pointer to created G4VSolid

Returns:

Pointer to created G4VSolid

G4VSolid *CreateBoxSolid(const json &dims, const std::string &name)

Create a box solid from JSON configuration.

Parameters:
  • dims – JSON object containing box dimensions

  • name – Name for the solid

Returns:

Pointer to created G4Box

G4VSolid *CreateConeSolid(const json &dims, const std::string &name)

Create a cone solid from JSON configuration.

Parameters:
  • dims – JSON object containing cone dimensions

  • name – Name for the solid

Returns:

Pointer to created G4Cons

G4VSolid *CreateCylinderSolid(const json &dims, const std::string &name)

Create a cylinder/tube solid from JSON configuration.

Parameters:
  • dims – JSON object containing cylinder dimensions

  • name – Name for the solid

Returns:

Pointer to created G4Tubs

G4VSolid *CreateEllipsoidSolid(const json &dims, const std::string &name)

Create an ellipsoid solid from JSON configuration.

Parameters:
  • dims – JSON object containing ellipsoid dimensions

  • name – Name for the solid

Returns:

Pointer to created G4Ellipsoid

G4VSolid *CreateEllipticalTubeSolid(const json &dims, const std::string &name)

Create an elliptical tube solid from JSON configuration.

Parameters:
  • dims – JSON object containing elliptical tube dimensions

  • name – Name for the solid

Returns:

Pointer to created G4EllipticalTube

G4Material *CreateMaterial(const std::string &name, const json &config)

Create a G4Material from JSON configuration.

Load material definitions from a JSON file.

Reads and parses the materials configuration file into the materialsConfig member

Create a G4Material from JSON configuration

Supports creation of materials from NIST database or by element composition. For compound materials, requires density, state, temperature, and composition.

Parameters:
  • name – Material name

  • config – JSON configuration for the material

  • filename – Path to the JSON materials configuration file

  • name – Name of the material to create

  • config – JSON object containing material properties

Throws:
  • std::runtime_error – if file cannot be opened or parsed

  • std::runtime_error – if material creation fails

Returns:

Pointer to created G4Material

Returns:

Pointer to the created or cached G4Material

G4VSolid *CreateOrbSolid(const json &dims, const std::string &name)

Create an orb solid from JSON configuration.

Parameters:
  • dims – JSON object containing orb dimensions

  • name – Name for the solid

Returns:

Pointer to created G4Orb

G4VSolid *CreatePolyconeSolid(const json &config, const json &dims, const std::string &name)

Create a polycone solid from JSON configuration.

Parameters:
  • config – JSON configuration for the polycone (needs both dims and possibly config)

  • dims – JSON object containing polycone dimensions

  • name – Name for the solid

Returns:

Pointer to created G4Polycone

G4VSolid *CreatePolyhedraSolid(const json &config, const json &dims, const std::string &name)

Create a polyhedra solid from JSON configuration.

Parameters:
  • config – JSON configuration for the polyhedra (needs both dims and possibly config)

  • dims – JSON object containing polyhedra dimensions

  • name – Name for the solid

Returns:

Pointer to created G4VSolid

G4VSolid *CreateSolid(const json &config, const std::string &name)

Create a G4VSolid from JSON configuration.

Creates a solid based on the type specified in the config. Supports all basic Geant4 shapes and boolean operations.

Parameters:
  • config – JSON configuration for the solid

  • name – Name for the solid

  • config – JSON configuration for the solid

  • name – Name for the solid

Throws:

std::runtime_error – if solid creation fails

Returns:

Pointer to created G4VSolid

Returns:

Pointer to created G4VSolid

G4VSolid *CreateSphereSolid(const json &dims, const std::string &name)

Create a sphere solid from JSON configuration.

Parameters:
  • dims – JSON object containing sphere dimensions

  • name – Name for the solid

Returns:

Pointer to created G4Sphere

G4VSolid *CreateTorusSolid(const json &dims, const std::string &name)

Create a torus solid from JSON configuration.

Parameters:
  • dims – JSON object containing torus dimensions

  • name – Name for the solid

Returns:

Pointer to created G4Torus

G4VSolid *CreateTrapezoidSolid(const json &dims, const std::string &name)

Create a trapezoid solid from JSON configuration.

Parameters:
  • dims – JSON object containing trapezoid dimensions

  • name – Name for the solid

Returns:

Pointer to created G4Trd

G4LogicalVolume *CreateVolume(const json &config)

Create a G4LogicalVolume from JSON configuration.

Creates a logical volume with specified material and shape. Supports all Geant4 shapes, boolean operations, and external geometries.

Parameters:
  • config – JSON configuration for the volume

  • config – JSON object containing volume properties

Throws:

std::runtime_error – if volume creation fails

Returns:

Pointer to created G4LogicalVolume

Returns:

Pointer to the created G4LogicalVolume

void ImportAssembledGeometry(const json &config, G4LogicalVolume *motherVolume)

Import an assembled geometry from an external file.

Import an assembled geometry from an external JSON file.

Imports a geometry defined in an external JSON file and places it in the parent volume with the specified transformation.

Parameters:
  • config – JSON configuration for the import

  • motherVolume – Logical volume to place the imported geometry in

  • config – JSON configuration for the import

  • parentVolume – Parent logical volume to place the imported geometry in

json LoadExternalGeometry(const std::string &filename)

Load and parse an external JSON geometry file.

Loads an external JSON file, resolving the path relative to the main configuration file’s directory.

Parameters:
  • filename – Path to the external JSON file

  • filename – Path to the external JSON file

Throws:

std::runtime_error – if file cannot be opened or parsed

Returns:

JSON object containing the parsed file

Returns:

JSON object containing the parsed file

void ParsePlacement(const json &config, G4ThreeVector &position, G4RotationMatrix *&rotation)

Parse a placement object and extract position and rotation.

Handles the geometry-editor format with placements array

Handles the geometry-editor format with placement object

Parameters:
  • config – JSON object containing placement information

  • position – Reference to G4ThreeVector to store position

  • rotation – Reference to G4RotationMatrix pointer to store rotation

  • placement – JSON object containing placement information

  • position – Reference to G4ThreeVector to store position

  • rotation – Reference to G4RotationMatrix pointer to store rotation

G4RotationMatrix *ParseRotation(const json &rot, bool isAssembly = false)

Convert JSON rotation to G4RotationMatrix.

Convert JSON rotation angles to G4RotationMatrix.

Expects JSON format: {“x”: angle_x, “y”: angle_y, “z”: angle_z} Angles are assumed to be in radians Rotations are applied in the Geant4 sequence: first X, then Y, then Z

Parameters:
  • rot – JSON object containing rotation angles

  • isAssembly – Flag indicating if the rotation is for an assembly (default: false)

  • rot – JSON object containing rotation angles

Returns:

Pointer to new G4RotationMatrix

Returns:

Pointer to new G4RotationMatrix

G4ThreeVector ParseVector(const json &vec)

Convert JSON vector to G4ThreeVector with units.

Convert a JSON vector definition to G4ThreeVector.

Expects JSON format: {“x”: val, “y”: val, “z”: val} All values are assumed to be in mm

Parameters:
  • vec – JSON object containing x,y,z and unit

  • vec – JSON object containing x,y,z components

Returns:

G4ThreeVector with applied units

Returns:

G4ThreeVector with components in mm

Private Members

std::map<std::string, G4AssemblyVolume*> assemblies

Cache of created assemblies.

std::string configPath

Path to the configuration files.

json geometryConfig

Geometry configuration.

std::map<std::string, G4LogicalVolume*> logicalVolumeMap

Map of logical volumes by name.

std::map<std::string, G4Material*> materials

Cache of created materials.

json materialsConfig

Materials configuration.

std::map<std::string, G4VSolid*> solids

Cache of created solids.

std::map<std::string, G4LogicalVolume*> volumes

Cache of created volumes.

DetectorConstruction

class DetectorConstruction : public G4VUserDetectorConstruction

Constructs the detector geometry from JSON configuration files.

This class reads geometry and material definitions from JSON files and constructs the complete detector setup.

Public Functions

virtual G4VPhysicalVolume *Construct()

Construct detector geometry from configuration files.

Constructs the detector geometry from JSON configuration.

This method:

  1. Loads geometry and materials configurations

  2. Constructs all volumes using the GeometryParser

  3. Stores a pointer to the LXe volume for scoring

The complete geometry specification is read from the JSON files, allowing for easy modification without recompiling.

Returns:

Pointer to the world physical volume

Returns:

Pointer to the world physical volume

DetectorConstruction(const std::string &geomFile = "config/dummy1.json")

Constructor.

Constructor implementation.

Initializes the geometry parser with the specified configuration files.

Parameters:
  • geomFile – Path to geometry configuration file

  • geomFile – Path to geometry configuration file

  • matFile – Path to materials configuration file

inline G4String GetGeometryFile() const

Set the materials configuration file path.

Get the current geometry file path

Parameters:

path – Path to the materials JSON file

Returns:

Current geometry file path

G4bool RebuildGeometry()

Get the current materials file path.

Set the materials configuration file path.

Rebuild the geometry with the current configuration files

Rebuild the geometry with the current configuration files

Parameters:

path – Path to the materials JSON file

Returns:

Current materials file path

Returns:

true if rebuild was successful, false otherwise

Returns:

true if rebuild was successful, false otherwise

void SetGeometryFile(const G4String &path)

Set the geometry configuration file path.

Parameters:

path – Path to the geometry JSON file

virtual ~DetectorConstruction()

Destructor.

Destructor implementation.

Cleans up the messenger object.

Private Members

DetectorMessenger *fMessenger

Messenger for UI commands.

std::string geometryFile

Path to geometry config file.

GeometryParser parser

Parser for JSON configuration.

class DetectorMessenger : public G4UImessenger

Nested messenger class for DetectorConstruction.

Handles UI commands for changing geometry and material files at runtime

Public Functions

DetectorMessenger(DetectorConstruction *detector)

Constructor for the DetectorMessenger.

Parameters:

detector – Pointer to the associated DetectorConstruction

virtual void SetNewValue(G4UIcommand *command, G4String newValue)

Handle UI commands.

Parameters:
  • command – The command being executed

  • newValue – The new value for the command parameter

virtual ~DetectorMessenger()

Destructor for the DetectorMessenger.

Private Members

DetectorConstruction *fDetector
G4UIdirectory *fDetectorDir
G4UIcmdWithAString *fGeometryFileCmd
G4UIcommand *fRebuildCmd

Hits and Sensitive Detectors

MyHit

class MyHit : public G4VHit

Default hit class for storing information about energy deposits in active volumes.

This class stores basic information about hits in active volumes, including:

  • Track ID

  • Volume name (to identify which detector was hit)

  • Position

  • Energy deposit

  • Time

Public Functions

inline G4double GetEnergy() const
inline G4ThreeVector GetPosition() const
inline G4double GetTime() const
inline G4int GetTrackID() const
inline G4String GetVolumeName() const
MyHit()

Default constructor.

MyHit(const MyHit&)

Copy constructor.

inline void operator delete(void*)
inline void *operator new(size_t)
const MyHit &operator=(const MyHit&)

Assignment operator.

G4bool operator==(const MyHit&) const

Equality operator.

inline void SetEnergy(G4double e)
inline void SetPosition(G4ThreeVector xyz)
inline void SetTime(G4double t)
inline void SetTrackID(G4int track)
inline void SetVolumeName(const G4String &name)
virtual ~MyHit()

Destructor.

Private Members

G4double fEnergy
G4ThreeVector fPosition
G4double fTime
G4int fTrackID
G4String fVolumeName

MySensitiveDetector

class MySensitiveDetector : public G4VSensitiveDetector

Default sensitive detector for active volumes.

This class processes hits in active volumes and stores them in the MyHitsCollection. It records basic information like energy deposit, position, time, and track ID.

Public Functions

virtual void EndOfEvent(G4HCofThisEvent *hitCollection)

End of event processing.

Parameters:

hce – Hits collection of this event

virtual void Initialize(G4HCofThisEvent *hitCollection)

Initialize at the beginning of each event.

Parameters:

hce – Hits collection of this event

MySensitiveDetector(const G4String &name, const G4String &hitsCollectionName = "MyHitsCollection")

Constructor.

Parameters:

name – Name of the sensitive detector

virtual G4bool ProcessHits(G4Step *step, G4TouchableHistory *history)

Process hits during tracking.

Parameters:
  • step – Current step

  • history – Touchable history (not used)

Returns:

True if the hit was processed

virtual ~MySensitiveDetector()

Destructor.

Public Static Functions

static inline G4int GetVerboseLevel()
static inline void SetVerboseLevel(G4int level)

Set verbosity: 0 = silent, 1 = summary per event, 2 = every hit.

Private Members

MyHitsCollection *fHitsCollection
G4int fHitsCollectionID

Private Static Attributes

static HitsMessenger *fMessenger = nullptr
static bool fMessengerCreated = false

Ensures messenger is created once.

static G4int fVerboseLevel = 0

Shared print level (default 0)

class HitsMessenger : public G4UImessenger

Public Functions

inline HitsMessenger()
inline void SetNewValue(G4UIcommand *cmd, G4String val) override
inline ~HitsMessenger() override

Private Members

G4UIdirectory *fDir
G4UIcmdWithAnInteger *fVerboseCmd

Event Processing

EventAction

class EventAction : public G4UserEventAction

Event action class that writes per-detector hit data to ROOT tree.

This class automatically discovers all hits collections registered by sensitive detectors and creates ROOT tree branches for each detector.

Two output modes are available (controlled via /output/setSummarize):

  • Detailed (default, 0): one entry per hit

    • <det>_nHits, <det>_x/y/z, <det>_E, <det>_volName

  • Summarised (1): one entry per unique volume per event

    • <det>_nHits = number of volumes hit

    • <det>_E = summed energy deposit per volume [MeV]

    • <det>_x/y/z = energy-weighted average position [mm]

    • <det>_volName = unique volume name

    • <det>_nHitsPerVol = number of raw hits merged into each summary

Public Functions

virtual void BeginOfEventAction(const G4Event *event)
virtual void EndOfEventAction(const G4Event *event)
EventAction()
virtual ~EventAction()

Public Static Functions

static inline G4int GetSummarize()
static inline void SetSummarize(G4int val)

Set summarisation mode: 0 = detailed (per-hit), 1 = per-volume summary.

Private Functions

void InitializeCollections()

Discover all registered hits collections and create ROOT branches.

Private Members

bool fCollectionsInitialized
std::map<std::string, std::vector<double>> fE
std::map<G4String, G4int> fHitsCollectionIDs

Cache of hits collection IDs by name.

std::map<std::string, Int_t> fNHits
std::map<std::string, std::vector<int>> fNHitsPerVol
TTree *fTree

Pointer to the TTree owned by RunAction.

std::map<std::string, std::vector<std::string>> fVolName
std::map<std::string, std::vector<double>> fX
std::map<std::string, std::vector<double>> fY
std::map<std::string, std::vector<double>> fZ

Private Static Attributes

static G4int fSummarize = 0
static SummarizeMessenger *fSumMessenger = nullptr
static bool fSumMessengerCreated = false
class SummarizeMessenger : public G4UImessenger

Public Functions

inline void SetNewValue(G4UIcommand *cmd, G4String val) override
inline SummarizeMessenger()
inline ~SummarizeMessenger() override

Private Members

G4UIcmdWithAnInteger *fCmd

PrimaryGeneratorAction

class PrimaryGeneratorAction : public G4VUserPrimaryGeneratorAction

Handles the generation of primary particles using GPS.

This class uses the G4GeneralParticleSource (GPS) instead of the simple particle gun. GPS supports:

  • Point, volume, and surface sources

  • Arbitrary energy spectra (mono, linear, power-law, Gaussian, …)

  • Flexible angular distributions (isotropic, cosine, focused, …)

  • Confinement to a named physical volume

  • Multiple overlapping sources with individual intensities

All configuration is done at run-time via /gps/ macro commands.

Public Functions

void GeneratePrimaries(G4Event *anEvent) override

Generates primary particles for each event.

Parameters:
  • anEvent – Pointer to the current G4Event

  • anEvent – The current G4Event being processed

inline const G4GeneralParticleSource *GetGPS() const

Accessor for the GPS object.

PrimaryGeneratorAction()

Constructor – creates the GPS instance.

GPS defaults to a 1 MeV geantino at the origin with isotropic angular distribution. Override everything through /gps/ macros.

~PrimaryGeneratorAction() override

Destructor.

Private Members

G4GeneralParticleSource *fGPS

Pointer to the General Particle Source.

RunAction

class RunAction : public G4UserRunAction

Handles ROOT output creation and management for the simulation.

This class manages the ROOT file output, creating a TTree structure. Branches are created dynamically by EventAction for each sensitive detector.

Public Functions

virtual void BeginOfRunAction(const G4Run *run)
virtual void EndOfRunAction(const G4Run *run)
inline TTree *GetEventTree() const

Get the event TTree (used by EventAction to create branches and fill)

inline G4String GetOutputFileName() const

Get the current output file name.

RunAction()
inline void SetOutputFileName(const G4String &name)

Set the ROOT output file name (called from macro)

virtual ~RunAction()

Private Members

TTree *fEventTree

Pointer to main data TTree.

RunActionMessenger *fMessenger

Messenger for UI commands.

G4String fOutputFileName

Configurable output file name.

TFile *fRootFile

Pointer to ROOT output file.

class RunActionMessenger : public G4UImessenger

Public Functions

RunActionMessenger(RunAction *runAction)
virtual void SetNewValue(G4UIcommand *command, G4String newValue)
virtual ~RunActionMessenger()

Private Members

G4UIcmdWithAString *fFileNameCmd
G4UIdirectory *fOutputDir
RunAction *fRunAction

ActionInitialization

class ActionInitialization : public G4VUserActionInitialization

Initializes all user action classes for the simulation.

This class is responsible for creating and registering all user action classes, including:

It handles both sequential and multi-threaded execution modes.

Public Functions

ActionInitialization()

Constructor.

Constructor implementation.

No initialization needed in constructor

Calls the base class constructor. No additional initialization needed.

virtual void Build() const

Creates user actions for worker threads.

Implementation of worker thread initialization.

Creates all necessary user action objects:

Creates all necessary user actions for simulation:

  1. PrimaryGeneratorAction - Creates neutrons

  2. RunAction - Handles data collection

This method is called for each worker thread in MT mode, and for the main thread in sequential mode.

virtual void BuildForMaster() const

Creates user actions for master thread.

Implementation of master thread initialization.

Called only in multi-threading mode. Creates actions that should only run on the master thread, specifically the RunAction for ROOT file management.

Creates only the RunAction for the master thread in MT mode. This ensures proper handling of the ROOT output file in multi-threaded execution.

virtual ~ActionInitialization()

Destructor.

Destructor implementation.

No cleanup needed as user actions are managed by Geant4 kernel.