3.2.  Global Usage Classes

The "global" category in Geant4 collects all classes, types, structures and constants which are considered of general use within the Geant4 toolkit. This category also defines the interface with third-party software libraries (CLHEP, STL, etc.) and system-related types, by defining, where appropriate, typedefs according to the Geant4 code conventions.

3.2.1.  Signature of Geant4 classes

In order to keep an homogeneous naming style, and according to the Geant4 coding style conventions, each class part of the Geant4 kernel has its name beginning with the prefix G4, e.g., G4VHit, G4GeometryManager, G4ProcessVector, etc. Instead of the raw C types, G4 types are used within the Geant4 code. For the basic numeric types (int, float, double, etc.), different compilers and different platforms provide different value ranges. In order to assure portability, the use of G4int, G4float, G4double, G4bool, globally defined, is preferable. G4 types implement the right generic type for a given architecture.

3.2.1.1.  Basic types

The basic types in Geant4 are considered to be the following:

  • G4int,
  • G4long,
  • G4float,
  • G4double,
  • G4bool,
  • G4complex,
  • G4String.

which currently consist of simple typedefs to respective types defined in the CLHEP, STL or system libraries. Most definitions of these basic types come with the inclusion of a single header file, globals.hh. This file also provides inclusion of required system headers, as well as some global utility functions needed and used within the Geant4 kernel.

3.2.1.2.  Typedefs to CLHEP classes and their usage

The following classes are typedefs to the corresponding classes of the CLHEP (Computing Library for High Energy Physics) distribution. For more detailed documentation please refer to the CLHEP reference guide and the CLHEP user manual .

  • G4ThreeVector, G4RotationMatrix, G4LorentzVector and G4LorentzRotation

    Vector classes: defining 3-component (x,y,z) vector entities, rotation of such objects as 3x3 matrices, 4-component (x,y,z,t) vector entities and their rotation as 4x4 matrices.

  • G4Plane3D, G4Transform3D, G4Normal3D, G4Point3D, and G4Vector3D

    Geometrical classes: defining geometrical entities and transformations in 3D space.

3.2.2.  The HEPRandom module in CLHEP

The HEPRandom module, originally part of the Geant4 kernel, and now distributed as a module of CLHEP, has been designed and developed starting from the Random class of MC++, the original CLHEP's HepRandom module and the Rogue Wave approach in the Math.h++ package. For detailed documentation on the HEPRandom classes see the CLHEP reference guide and the CLHEP user manual .

Information written in this manual is extracted from the original manifesto distributed with the HEPRandom package.

The HEPRandom module consists of classes implementing different random ``engines'' and different random ``distributions''. A distribution associated to an engine constitutes a random ``generator''. A distribution class can collect different algorithms and different calling sequences for each method to define distribution parameters or range-intervals. An engine implements the basic algorithm for pseudo-random numbers generation.

There are 3 different ways of shooting random values:

  1. Using the static generator defined in the HepRandom class: random values are shot using static methods shoot() defined for each distribution class. The static generator will use, as default engine, a HepJamesRandom object, and the user can set its properties or change it with a new instantiated engine object by using the static methods defined in the HepRandom class.

  2. Skipping the static generator and specifying an engine object: random values are shot using static methods shoot(*HepRandomEngine) defined for each distribution class. The user must instantiate an engine object and give it as argument to the shoot method. The generator mechanism will then be by-passed by using the basic flat() method of the specified engine. The user must take care of the engine objects he/she instantiates.

  3. Skipping the static generator and instantiating a distribution object: random values are shot using fire() methods (NOT static) defined for each distribution class. The user must instantiate a distribution object giving as argument to the constructor an engine by pointer or by reference. By doing so, the engine will be associated to the distribution object and the generator mechanism will be by-passed by using the basic flat() method of that engine.

In this guide, we'll only focus on the static generator (point 1.), since the static interface of HEPRandom is the only one used within the Geant4 toolkit.

3.2.2.1.  HEPRandom engines

The class HepRandomEngine is the abstract class defining the interface for each random engine. It implements the getSeed() and getSeeds() methods which return the `initial seed' value and the initial array of seeds (if any) respectively. Many concrete random engines can be defined and added to the structure, simply making them inheriting from HepRandomEngine. Several different engines are currently implemented in HepRandom, we describe here five of them:

  • HepJamesRandom

    It implements the algorithm described in ``F.James, Comp. Phys. Comm. 60 (1990) 329'' for pseudo-random number generation. This is the default random engine for the static generator; it will be invoked by each distribution class unless the user sets a different one.

  • DRand48Engine

    Random engine using the drand48() and srand48() system functions from C standard library to implement the flat() basic distribution and for setting seeds respectively. DRand48Engine uses the seed48() function from C standard library to retrieve the current internal status of the generator, which is represented by 3 short values. DRand48Engine is the only engine defined in HEPRandom which intrinsically works in 32 bits precision. Copies of an object of this kind are not allowed.

  • RandEngine

    Simple random engine using the rand() and srand() system functions from the C standard library to implement the flat() basic distribution and for setting seeds respectively. Please note that it's well known that the spectral properties of rand() leave a great deal to be desired, therefore the usage of this engine is not recommended if a good randomness quality or a long period is required in your code. Copies of an object of this kind are not allowed.

  • RanluxEngine

    The algorithm for RanluxEngine has been taken from the original implementation in FORTRAN77 by Fred James, part of the MATHLIB HEP library. The initialisation is carried out using a Multiplicative Congruential generator using formula constants of L'Ecuyer as described in ``F.James, Comp. Phys. Comm. 60 (1990) 329-344''. The engine provides five different luxury levels for quality of random generation. When instantiating a RanluxEngine, the user can specify the luxury level to the constructor (if not, the default value 3 is taken). For example:

          RanluxEngine theRanluxEngine(seed,4);
          // instantiates an engine with `seed' and the best luxury-level
          ... or
          RanluxEngine theRanluxEngine;
          // instantiates an engine with default seed value and luxury-level
          ...
        

    The class provides a getLuxury() method to get the engine luxury level.

    The SetSeed() and SetSeeds() methods to set the initial seeds for the engine, can be invoked specifying the luxury level. For example:

          // static interface
          HepRandom::setTheSeed(seed,4);  // sets the seed to `seed' and luxury to 4
          HepRandom::setTheSeed(seed);    // sets the seed to `seed' keeping
                                          // the current luxury level
        

  • RanecuEngine

    The algorithm for RanecuEngine is taken from the one originally written in FORTRAN77 as part of the MATHLIB HEP library. The initialisation is carried out using a Multiplicative Congruential generator using formula constants of L'Ecuyer as described in ``F.James, Comp. Phys. Comm. 60 (1990) 329-344''. Handling of seeds for this engine is slightly different than the other engines in HEPRandom. Seeds are taken from a seed table given an index, the getSeed() method returns the current index of seed table. The setSeeds() method will set seeds in the local SeedTable at a given position index (if the index number specified exceeds the table's size, [index%size] is taken). For example:

                                         
          // static interface
          const G4long* table_entry;
          table_entry = HepRandom::getTheSeeds();
          // it returns a pointer `table_entry' to the local SeedTable
          // at the current `index' position. The couple of seeds
          // accessed represents the current `status' of the engine itself !
          ...
          G4int index=n;
          G4long seeds[2];
          HepRandom::setTheSeeds(seeds,index);
          // sets the new `index' for seeds and modify the values inside
          // the local SeedTable at the `index' position. If the index
          // is not specified, the current index in the table is considered.
          ...
        

    The setSeed() method resets the current `status' of the engine to the original seeds stored in the static table of seeds in HepRandom, at the specified index.

Except for the RanecuEngine, for which the internal status is represented by just a couple of longs, all the other engines have a much more complex representation of their internal status, which currently can be obtained only through the methods saveStatus(), restoreStatus() and showStatus(), which can also be statically called from HepRandom. The status of the generator is needed for example to be able to reproduce a run or an event in a run at a given stage of the simulation.

RanecuEngine is probably the most suitable engine for this kind of operation, since its internal status can be fetched/reset by simply using getSeeds()/setSeeds() (getTheSeeds()/setTheSeeds() for the static interface in HepRandom).

3.2.2.2.  The static interface in the HepRandom class

HepRandom a singleton class and using a HepJamesRandom engine as default algorithm for pseudo-random number generation. HepRandom defines a static private data member, theGenerator, and a set of static methods to manipulate it. By means of theGenerator, the user can change the underlying engine algorithm, get and set the seeds, and use any kind of defined random distribution. The static methods setTheSeed() and getTheSeed() will set and get respectively the `initial' seed to the main engine used by the static generator. For example:

                                     
      HepRandom::setTheSeed(seed);  // to change the current seed to 'seed'
      int startSeed = HepRandom::getTheSeed();  // to get the current initial seed
      HepRandom::saveEngineStatus();    // to save the current engine status on file
      HepRandom::restoreEngineStatus(); // to restore the current engine to a previous
                                        // saved configuration
      HepRandom::showEngineStatus();    // to display the current engine status to stdout
      ...
      int index=n;
      long seeds[2];
      HepRandom::getTheTableSeeds(seeds,index);
        // fills `seeds' with the values stored in the global
        // seedTable at position `index'

Only one random engine can be active at a time, the user can decide at any time to change it, define a new one (if not done already) and set it. For example:

                                      
      RanecuEngine theNewEngine;
      HepRandom::setTheEngine(&theNewEngine);
       ...

or simply setting it to an old instantiated engine (the old engine status is kept and the new random sequence will start exactly from the last one previously interrupted). For example:

                                      
      HepRandom::setTheEngine(&myOldEngine);

Other static methods defined in this class are:

  • void setTheSeeds(const G4long* seeds, G4int)

  • const G4long* getTheSeeds()

    To set/get an array of seeds for the generator, in the case of a RanecuEngine this corresponds also to set/get the current status of the engine.

  • HepRandomEngine* getTheEngine()

    To get a pointer to the current engine used by the static generator.

3.2.2.3.  HEPRandom distributions

A distribution-class can collect different algorithms and different calling sequences for each method to define distribution parameters or range-intervals; it also collects methods to fill arrays, of specified size, of random values, according to the distribution. This class collects either static and not static methods. A set of distribution classes are defined in HEPRandom. Here is the description of some of them:

  • RandFlat

    Class to shoot flat random values (integers or double) within a specified interval. The class provides also methods to shoot just random bits.

  • RandExponential

    Class to shoot exponential distributed random values, given a mean (default mean = 1)

  • RandGauss

    Class to shoot Gaussian distributed random values, given a mean (default = 0) or specifying also a deviation (default = 1). Gaussian random numbers are generated two at the time, so every other time a number is shot, the number returned is the one generated the time before.

  • RandBreitWigner

    Class to shoot numbers according to the Breit-Wigner distribution algorithms (plain or mean^2).

  • RandPoisson

    Class to shoot numbers according to the Poisson distribution, given a mean (default = 1) (Algorithm taken from ``W.H.Press et al., Numerical Recipes in C, Second Edition'').

3.2.3.  The HEPNumerics module

A set of classes implementing numerical algorithms has been developed in Geant4. Most of the algorithms and methods have been implemented mainly based on recommendations given in the books:

  • B.H. Flowers, ``An introduction to Numerical Methods In C++'', Claredon Press, Oxford 1995.

  • M. Abramowitz, I. Stegun, ``Handbook of mathematical functions'', DOVER Publications INC, New York 1965 ; chapters 9, 10, and 22.

This set of classes includes:

  • G4ChebyshevApproximation

    Class creating the Chebyshev approximation for a function pointed by fFunction data member. The Chebyshev polynomial approximation provides an efficient evaluation of the minimax polynomial, which (among all polynomials of the same degree) has the smallest maximum deviation from the true function.

  • G4DataInterpolation

    Class providing methods for data interpolations and extrapolations: Polynomial, Cubic Spline, ...

  • G4GaussChebyshevQ

  • G4GaussHermiteQ

  • G4GaussJacobiQ

  • G4GaussLaguerreQ

    Classes implementing the Gauss-Chebyshev, Gauss-Hermite, Gauss-Jacobi, Gauss-Laguerre and Gauss-Legendre quadrature methods. Roots of orthogonal polynomials and corresponding weights are calculated based on iteration method (by bisection Newton algorithm).

  • G4Integrator

    Template class collecting integrator methods for generic functions (Legendre, Simpson, Adaptive Gauss, Laguerre, Hermite, Jacobi).

  • G4SimpleIntegration

    Class implementing simple numerical methods (Trapezoidal, MidPoint, Gauss, Simpson, Adaptive Gauss, for integration of functions with signature: double f(double).

3.2.4.  General management classes

The `global' category defines also a set of `utility' classes generally used within the kernel of Geant4. These classes include:

  • G4Allocator

    A class for fast allocation of objects to the heap through paging mechanism. It's meant to be used by associating it to the object to be allocated and defining for it new and delete operators via MallocSingle() and FreeSingle() methods of G4Allocator.

    Note: G4Allocator assumes that objects being allocated have all the same size for the type they represent. For this reason, classes which are handled by G4Allocator should avoid to be used as base-classes for others. Similarly, base-classes of sub-classes handled through G4Allocator should not define their (eventually empty) virtual destructors inlined; such measure is necessary in order also to prevent bad aliasing optimisations by compilers which may potentially lead to crashes in the attempt to free allocated chunks of memory when using the base-class pointer or not.

    The list of allocators implicitely defined and used in Geant4 is reported here:

          - events (G4Event): anEventAllocator
          - tracks (G4Track): aTrackAllocator
          - stacked tracks (G4StackedTrack): aStackedTrackAllocator
          - primary particles (G4PrimaryParticle): aPrimaryParticleAllocator
          - primary vertices (G4PrimaryVertex): aPrimaryVertexAllocator
          - decay products (G4DecayProducts): aDecayProductsAllocator
          - digits collections of an event (G4DCofThisEvent): anDCoTHAllocator
          - digits collections (G4DigiCollection): aDCAllocator
          - hits collections of an event (G4HCofThisEvent): anHCoTHAllocator
          - hits collections (G4HitsCollection): anHCAllocator
          - touchable histories (G4TouchableHistory): aTouchableHistoryAllocator
          - trajectories (G4Trajectory): aTrajectoryAllocator
          - trajectory points (G4TrajectoryPoint): aTrajectoryPointAllocator
          - trajectory containers (G4TrajectoryContainer): aTrajectoryContainerAllocator
          - navigation levels (G4NavigationLevel): aNavigationLevelAllocator
          - navigation level nodes (G4NavigationLevelRep): aNavigLevelRepAllocator
          - reference-counted handles (G4ReferenceCountedHandle<X>): aRCHAllocator
          - counted objects (G4CountedObject<X>): aCountedObjectAllocator
          - HEPEvt primary particles (G4HEPEvtParticle): aHEPEvtParticleAllocator
          - electron occupancy objects(G4ElectronOccupancy): aElectronOccupancyAllocator
          - "rich" trajectories (G4RichTrajectory): aRichTrajectoryAllocator
          - "rich" trajectory points (G4RichTrajectoryPoint): aRichTrajectoryPointAllocator
          - "smooth" trajectories (G4SmoothTrajectory): aSmoothTrajectoryAllocator
          - "smooth" trajectory points (G4SmoothTrajectoryPoint): aSmoothTrajectoryPointAllocator
          - "ray" trajectories (G4RayTrajectory): G4RayTrajectoryAllocator
          - "ray" trajectory points (G4RayTrajectoryPoint): G4RayTrajectoryPointAllocator
        

    For each of these allocators, accessible from the global namespace, it is possible to monitor the allocation in their memory pools or force them to release the allocated memory (for example at the end of a run):

          // Return the size of the total memory allocated for tracks
          //
          aTrackAllocator.GetAllocatedSize();
    
          // Return allocated storage for tracks to the free store
          //
          aTrackAllocator.ResetStorage();
        

  • G4ReferenceCountedHandle

    Template class acting as a smart pointer and wrapping the type to be counted. It performs the reference counting during the life-time of the counted object.

  • G4FastVector

    Template class defining a vector of pointers, not performing boundary checking.

  • G4PhysicsVector

    Defines a physics vector which has values of energy-loss, cross-section, and other physics values of a particle in matter in a given range of the energy, momentum, etc. This class serves as the base class for a vector having various energy scale, for example like 'log' (G4PhysicsLogVector) 'linear' (G4PhysicsLinearVector), 'free' (G4PhysicsFreeVector), etc.

  • G4LPhysicsFreeVector

    Implements a free vector for low energy physics cross-section data. A subdivision method is used to find the energy|momentum bin.

  • G4PhysicsOrderedFreeVector

    A physics ordered free vector inherits from G4PhysicsVector. It provides, in addition, a method for the user to insert energy/value pairs in sequence. Methods to retrieve the max and min energies and values from the vector are also provided.

  • G4Timer

    Utility class providing methods to measure elapsed user/system process time. Uses <sys/times.h> and <unistd.h> - POSIX.1.

  • G4UserLimits

    Class collecting methods for get and set any kind of step limitation allowed in Geant4.

  • G4UnitsTable

    Placeholder for the system of units in Geant4.