An Introduction To Geant4: Héctor Alvarez Pol GENP, Univ. Santiago de Compostela
An Introduction To Geant4: Héctor Alvarez Pol GENP, Univ. Santiago de Compostela
An Introduction To Geant4: Héctor Alvarez Pol GENP, Univ. Santiago de Compostela
introduction to Geant4
Short introduction course to the detector simulation using Geant4
Héctor Alvarez Pol
GENP, Univ. Santiago de Compostela
INDEX
1. Geant4: an overview
2. The Geant4 kernel: runs, events, steps, tracks, ...
3. The user part
✔
Primary particles
✔
Detector construction
✔
Particles and Physics processes
✔
Other user parts
6. Other relevant topics: hits, SD, analysis, ...
7. Practicum
Geant4 overview
What is Geant4?
It is a toolkit for the simulation of the particles passage through matter. It is used in Nuclear
and High Energy Physics, Accelerators, Medicine and Space Sciences [1]
The Geant4 toolkit components can be used to simulate experiments:
✔
Geant4 allows the use of fundamental particles (leptons, hadrons, bosons, resonances, ...,
included in the PDG list [2]) and ions. The description sets mass, momentum, polarization, ...
✔
Calculates the trajectories and determines the interactions for different Physical processes
✔
After the interaction, it changes the particles state, creates new particle if needed and allows
the access to all the information about each interaction
✔
Collecting this information, it is possible to describe the outcome of the detectors (even up
to the level of the electronic signal) and determine what escapes detection
Geant4 is written in C++ following the object oriented paradigm
It was first released in December 1998 and have two releases per year since then
It was born (and is basically designed) for the requirements of large scage HEP experiments
[1] Nuclear Instruments and Methods in Physics Research A 506 (2003) 250-303,
http://pdg.lbl.gov/2006/mcdata/mc_particle_id_contents.html
Geant4 overview
Why a Monte Carlo in Nuclear and Particle Physics?
Monte Carlo methods are numerical solutions to a problem by modelling the microscopic
relationship between the problem components using statistical sampling with random numbers
✔
Monte Carlo methods are based on theoretical details of the Physics
✔
Used for the design and optimization of experimental devices, evaluation of potential risks,
assesment of performance, and test and optimization of reconstruction and physics analysis sw
✔
It helps to the interpretation of results, validation and acceptance filters, ...
✔
Helps in the comparison of the experimental data and the theoretical approaches
Basic Science
EXPERIMENT
assumptions corrections
verification verification
THEORY MONTECARLO
BASIC UNDERSTANDING
Geant4 overview
... Geant4: pros and cons
✔
A powerful tool for the simulation of complex experimental setups in HEP and Nuclear Physics
✔
Design and optimization of experimental devices, interpretation of results, acceptance filters...,
helps in the comparison of the experimental data and the theoretical approaches
✔
Design under modern OO techniques, modular and easily updatable and flexible
✔
Documented, widely used in the HEP and Nuclear Physics community
✔
Under development by an international collaboration, with the possibility of improving the
physical description and adding new features
But:
✔
Requires a large computer power and some involvement in the coding
✔
Slow learning curve, complex structure
✔
Requires a detailed study and test of the Physical processes under simulation. Every
approximation should be carefully checked for consistency
✔
In Nuclear Physics, seems to be problems describing low energy neutron interactions; there are
no complete information on nuclear scheme for low energy / total absorption spectroscopy
Geant4 overview: structure
Geant4 class category
✔
Geant4 splits in logical units defined independently,
simplifying the parallel development and debugging
✔
The categories are loosely connected via interfaces or
relations (use, containment, ...)
Next, we will study some categories, in particular:
✔
Run and Event: related with the generation of events,
secondaries and any particle that need to be tracked
✔
Tracking and Track: particle propagation, step definition,
physical interactions and any related actions
✔
Geometry and Matter: description of detectors, computation
of distances to boundaries and materials
✔
Physics and Particles: all Physical processes and all existing
particle descriptions, with different models and options
✔
Hits and Digitization: manages the Hit creation in the
“sensitive detectors” and how this information is managed
✔
Visualization and interfaces: visualization tools for geometry
and tracks, graphical user interfaces (GUIs, like G4UIRoot)
and analysis programs interfaces (like ROOT)
The Geant4 kernel: some initial definitions...
Basic types and CLHEP libraries
✔
Geant4 classes begins with G4; basic types are defined with typedefs to CLHEP and STL basic types
✔
The basic types in Geant4 are: G4int, G4long, G4float, G4double, G4bool, G4complex and G4String
✔
The "global" category in Geant4 collects all classes, types, structures and constants of general use. It
also defines the interface with thirdparty software libraries (CLHEP, STL, etc.) and needed typedefs
✔
Randoms are taken from CLHEP (HEPRandom) with different engines and possible distributions
✔
CLHEP has also numerical algorithms for interpolation, integration, ... and other basic types
Standard output and units
✔
G4cout and G4cerr are iostream objects defined by Geant4, handled by G4UIManager. Should be used
for standard output and will be redirected to the user interfaces
✔
Geant4 enforces the use of units within all definitions: padLength = 10 * mm;
✔
G4UnitsTable is the placeholder for the system of units in Geant4, based on the HepSystemOfUnits
And in general...
✔
Avoid hardcoded data, use “Messenger” commands for all that can be later redefined
✔
Write always the units of the data you introduce, also in “Messenger” commands
The Geant4 kernel: some initial definitions...
System of units:
G4double padLength = 10 * mm;
G4double dE = 2348 * keV;
G4cout << dE / MeV << “MeV” << G4endl;
G4cout << G4BestUnit(padLength,”Length”);
padLength will be printed in m, mm, km,... depending on the value
To print the list of units:
✔
From the code:
G4UnitDefinition::PrintUnitsTable();
✔
At runtime, as UI command:
Idle> /units/list
Predefined units included in Geant4:
millimetre (mm), nanosecond (ns), Mega eV (MeV), positron charge (eplus), degree Kelvin (kelvin),
the amount of substance (mole), luminous intensity (candela), radian(radian), steradian (steradian)
The Geant4 kernel: tracking particles
GEANT4 treats all processes generically, passing particles to the tracking manager:
✔
The event manager converts the primaries to tracks in the stack
✔
The tracking manager (G4TrackingManager) receives the tracks and takes actions to manage them
✔
The tracking manager contains pointers to the G4SteppingManager, the G4Trajectory and the
G4UserTrackingAction. It uses G4Track and G4Step objects containing transient information
✔
The stepping manager (G4SteppingManager) takes care of transporting a particle in steps
The interaction point is determined by:
✔ The mean free path of each process is calculated from the cross section per atom (Z , E) and the
i
number of particles per atom in the compound media ni
(E) = ( ∑ [ni ∙ (Zi , E)] )–1 where ni = (Navo wi ) / Ai
✔ The number of mean free paths (n ) which a particle travels is independent of the material and
follows the following distribution function: P(n < n ) = 1 – exp{ – n }
✔ the total number of 's the particle travels before reaching n is sampled at the beginning of the
trajectory, and updated after every step according to
n' = n ( ∆x / (x) )
until the step is the sortest and triggers the process
✔
A limit in the pathlength is imposed to avoid a change in the energy above 20% along the step
The Geant4 kernel: G4Run
A Run (G4Run) is a sequence of events, the largest unit of simulation
✔
Characterized by a runID number (selectable) and a number of events
✔
G4RunManager is a singleton which manages all procedures
✔
G4RunManager controls the state changes; Geant4 is implemented as a
state machine, which can be in different states:
✔
G4State_PreInit: applications start in this state
✔
G4State_Init: during initialization of G4RunManager and other user
initialization classes
✔
G4State_Idle: ready for starting a run; geometry or physics can be
modified before the next run begins
✔
G4State_GeomClosed: after beamOn() is invoked. Geometry, physics,
... should be fixed and cross sections tables are calculated
✔
G4State_EventProc: during event processing
✔
G4State_Quit: during destructor of G4RunManager; normal end
✔
G4State_Abort: during abortion, allowing some “saving” methods
✔
Pass control to user: beginOfRunActions() for runspecific modifiers or
initialization of analysisrelated objects; endOfRunAction() for getting run
summaries and store analysisrelated objects
✔
In analogy to acelerator physics, the function beamOn() starts the run
The Geant4 kernel: G4Event and G4Step
G4Event represents an event, with all possible inputs and outputs:
✔
Contains primary vertex and primary particles, a stack of trajectories, Hits and digits collections
✔
The G4EventManager converts the primaries to tracks in the stack and starts the transportation,
invoking the beginOfEventAction() and endOfEventActions() for user interaction
G4Step stores the transient information of a step...
... and G4SteppingManager performs the detailed calculation of the step, that is
✔
Calculates the particle's velocity at the beginning of the step
✔
Takes the smaller steplength from the open interactions for the particle
✔
Checks that the steplength is smaller than the distance to the next geometrical boundary
✔
All active continuous processes are invoked and the kinetic energy and other properties recalculated
✔
If the track was not finish by the continuous processes, the discrete process is invoked, recalculating
again the energy and adding new particles to the secondaries list
✔
If the step was limited by a boundary, pushes the particle into the next volume
✔
Checks the user intervention intervention in G4UserSteppingAction
✔
Handles hit information and saves data to G4Trajectory
✔
Updates the mean free paths of the discrete processes and resets the maximum interaction length of
the discrete process which has occurred
The Geant4 kernel: processes
General features:
✔
Ample variety of Physics descriptions through abstract interfaces
✔
Uniform treatment of electromagnetic and hadronic processes
✔
Distinction between processes and models! Multiple models can describe a physics
process, in a complementary or alternative way
✔
Users can easily (?) create and use their own models
✔
Uses external databases: ENDF/B, JENDL, FENDL, CENDL, ENSDF, JEF, BROND, EFF, MENDL, IRDF,
SAID, EPDL, EEDL, EADL, SANDIA, ICRU,...
Processes describe how particles interact with matter:
✔
Three basic types: at rest (as decay), continuous (as ionization), discrete (as Compton)
✔
Each process defines three different types (vectors) of actions:
✔
AtRest: competitive effects
✔
AlongStep: cooperative effects during the step
✔
PostStep: competitive effects deciding the end of the step
✔
Processes also emit signals for particular treatment, forcing actions if cuts are reached
The Geant4 kernel: processes technically
Processes affecting particles in fligth:
✔
At the beginning of the step, determine the step length
✔
consider all processes attached to the current G4Track
✔
define the step length as the smallest of the lengths among all
AlongStepGetPhysicalInteractionLenght() and all PostStepGetPhysicalInteractionLength()
✔
Apply all AlongStepDoIt() actions at once
✔
changes computed from particle state at the beginning of the step
✔
accumulated in G4Step
✔
then applied to G4Track, by G4Step
✔
Apply PostStepDoIt() action(s) sequentially, as long as the particle is alive
✔
apply PostStepDoIt() of the process which proposed the smallest step length
apply forced and conditionnally forced actions
Processes affecting particles at rest:
✔
If is stable and cannot annihilate, it is killed by tracking
✔
Otherwise, the lifetime is determined, taking the smallest time among all
AtRestGetPhysicalInteractionLenght()
✔
Apply the AtRestDoIt() action of the process which returned the smallest time
The Geant4 kernel: ... and the particles are ...
The particle description (stored in G4ParticleDefinition) should be given
✔
Name, mass, spin, life time, decay modes and widths, ... are included
✔
A snapshot with a given set of properties is stored in a G4DynamicParticle
✔
A G4Track contains additionally position and time for a full tracking description
✔
Note that a G4DynamicalParticle mass is not the same than a G4ParticleDefinition G4ParticleDefinition
mass for ions. The second is the ion while the first corresponds to an atom
G4ProcessManager
Particle list in Geant4; use the ConstructParticle() function of each class: Process_1
✔
Gluon, quarks, other shortlived: G4ShortLivedConstructor Process_2
G4ParticleDefinition
✔
Leptons: G4LeptonConstructor Process_3
✔
Mesons: G4MesonConstructor
G4ParticleWithCuts G4VIon
Baryons: G4BaryonConstructor
✔
G4VLepton
✔
Ions: G4IonConstructor G4VBoson
G4VShortLivedParticles
✔
More ... G4Electron
G4VMeson G4VBaryon
G4Alpha
G4Geantino
G4PionPlus G4Proton
Note: alphas or lighter ions are singletons (exist an individual class for them).
Others are created onthefly from the method G4ParticleTable::GetIon()
The Geant4 kernel: processes and production thresholds
All the decays and interactions are done by processes Liquid Pb
Liquid
Pb Ar Ar
✔
Each particle has a list of applicable processes
✔
The process with the shortest proposed length is chosen
Cut per range in GEANT4
Geant4 general principes for the particle production and tracking are:
✔
Each process has its intrinsic limits to produce secondary particles DCUTE = 2 MeV in GEANT3
✔
All particles produced and accepted will be tracked up to zero range
✔
Each particle has a suggested cut in range so, the recommended
production threshold for secondaries is the particle cut
Note that there are no tracking cuts: only production threshold, needed to
solve infrared divergence in some em processes (treated as continuous)
Other behaviors are possible...
✔
Secondaries can be produced below threshold (as in conversion, where DCUTE = 455 keV in GEANT3
positron is always produced even at zero energy, for further annihilation)
✔
Special cuts can be applied (using G4UserLimits) for particular logical
volumes; maximum allowed step size, maximum total track length, ...
✔
Cuts can be defined by region to account for different level of
description at different detectors
The user part...
Users should define within Geant4 a mandatory set Other typical user classes are:
of classes providing the (userdefined) behavior: ✔
RunAction: controls the simulation run
✔
PrimaryGenerator: specifies particles, momenta, ...;
✔
EventAction: controls info at the event level
user class derives from G4VUserPrimaryGeneratorAction
✔
SteppingAction: controls info at the step level
✔
DetectorConstruction: specifies the setup; user class
✔
VisManager: allows visualization
derives from G4VUserDetectorConstruction
✔
TrackingAction: allows track control
✔
PhysicsList: specifies Physics processes available; Additionally, user classes can define other topics as
user class should derive from G4VModularPhysicsList Analysis interface, additional Physics options, step
verbosity, event generator interface, stacking control
...the event generator: G4VUserPrimaryGeneratorAction
Every G4Event should have a set of primary particles
✔
The class G4PrimaryParticle represents a primary located in a G4PrimaryVertex
✔
Only G4PrimaryParticles with a pointer to G4ParticleDefinition or a PDG number are allowed
✔
If the primary is an “intermediate” (Z boson), the daughters are assumed to start from the vertex.
Even if it flies some distance (for instace B mesons), it could be forced to decay in the vertex
✔
Geant4 does not link with any FORTRAN library! But there are ASCII file interfaces to (old)
event generators (G4HEPEvtInterface)
✔
Geant4 provides G4HEPEvtInterface and G4HEPMCInterface for High energy Physics, for sources on
surfaces G4GeneralParticleSource (Medical, Space Physics), and a general G4ParticleGun
✔
Different event generator interfaces could be constructed for custommade codes
What to do in the user application?
✔
Derive your own generator for G4VPrimaryGenerator or use provided generators (as G4ParticleGun)
✔
Define the particles and the initial conditions (momentum, energy, polarization, ...)
✔
Define the vertex time and position, as well as the number and type of particles to be used
✔
Define any function able to modify the vertex features by an user interaction
...example of event generator
Example: using G4ParticleGun
myPrimaryGeneratorAction::GeneratePrimaries(G4Event* anEvent) {
G4int n_particle = 1;
particleGun = new G4ParticleGun(n_particle);
particleTable = G4ParticleTable::GetParticleTable();
G4ParticleDefinition* pd = particleTable->FindParticle(“proton”);
if(pd != 0)
particleGun->SetParticleDefinition(pd);
particleGun->SetParticlePosition(G4ThreeVector());
particleGun->SetParticleTime(0.0);
particleGun->SetParticlePolarization(G4ThreeVector());
particleGun->SetParticleCharge(1.0);
particleGun->SetParticleMomentumDirection(G4ThreeVector(1.,0.,0.));
particleGun->SetParticleEnergy(20.0*MeV);
particleGun->SetParticlePosition(G4ThreeVector(0,0,0));
particleGun->GeneratePrimaryVertex(anEvent);
}
...the detector geometry: G4VUserDetectorConstruction
Detectors, media and any other interposed matter could be modeled
✔
A solid can be constructed from CSG or BREPs descriptions (STEP compatible)
✔
Geant4 uses G4LogicalVolume to manage the representation of the object properties
✔
G4VPhysicalVolume represents the spatial positioning and the logical relations of objects
The different levels of representation answer to different Geant4 and user requests
✔
A solid provides geometrical methods: where are my limits, return points on my surface, ...
✔
A logical volume knows which physical volumes have inside. This allows cloning
✔
Requires the definition of materials and provides methods about its internals (mass)
✔
A physical volume is a single or repeated (with copy number) allocation of a logical volume
✔
It is instantiated by using G4PVPlacement constructors
✔
Allows the use of replicas or parameterizations for repeated allocation
What to do in the user application?
✔
Define all materials to be used in the construction of the setup
✔
In the virtual method Construct(): introduce the geometry (solids, logic and physical volumes)
of the detectors, construct sensitive detectors and maybe the visualization properties
✔
Advanced geometry (replicas, touchables, regions, assemblies, dynamical volumes... ) can
simplify and regulate complex geometries; magnetic fields could be assigned to volumes
... the detector geometry: typical solids
... the detector geometry: typical solids
... the detector geometry: typical solids
... the detector geometry: typical solids
... the detector geometry: materials, elements, isotopes
Materials should be specified by the user; tables are created storing objects of classes
✔
G4Isotope, characterized by the name, atomic number, number of nucleons and mass per mole
✔
G4Element, given by name, symbol, effective Z and A, and the effective mass per mole. It can also
be constructed specifying the isotopic content. A NIST database with natural elements is included
✔
G4Material, characterized by a name, density, physical state, temperature and pressure. It is created
from the number of elements (or an equivalent description). A NIST database is available
✔
Isotopes can be assembled into elements [AddIsotope()] and materials are made of elements
✔
Note that only G4Material is available to the geometry elements and the tracking
Different properties can be assigned:
✔
Temperature, presion, state, density
✔
Radiation length, absortion length, ...
... the detector geometry: elements, isotopes
Isotopes construction:
G4Isotope(const G4String& name,
G4int z, //atomic name
G4int n, //number of nucleons
G4int a); //mass of mole
Elements construction:
G4Element(const G4String& name,
const G4String& symbol, //element symbol
G4int nIso, //number of isotopes
G4int a); //mass of mole
G4Element::AddIsotope(G4Isotope* myiSo, //isotope
G4double relAbundance); //fraction of atoms
//per volume
As an alternative, construct the element from the NIST table
... the detector geometry: materials
Materials construction:
✔
From a single element
G4Material(const G4String& name,
G4int z, //atomic name
G4int n, //number of nucleons
G4int density); //density (remember the units)!
✔
From several elements, given by the stoichiometric contents
G4Material(const G4String& name,
G4int density, //density (remember the units)!
G4int numberOfComponents);
Adding as many elements as needed using:
G4Material::AddElement(G4Element anElement,
G4int numberOfAtoms);
G4Material::AddElement(G4Element anElement,
G4int fractionOfMass);
✔
From several materials, adding the fractional mass of each one (and mixing materials and elements)
G4Material::AddMaterial(G4Material aMaterial,
G4int fractionOfMass);
... how to describe the detector (practically)
A complete recipe for describing a detector:
G4LogicalVolume* pMyBoxLogic =
new G4LogicalVolume(pMyBox, pBoxMaterial,“MyBoxLog”,0,0,0);
G4RotationMatrix* pGlobalRot =
new G4RotationMatrix(0,3*pi/2,pi)
G4double posX = ...; G4double posY = ...; G4double posZ = ...;
G4VPhysicalVolume* pMyBoxPhys =
new G4PVPlacement(aRotation,G4ThreeVector(posX,posY,posZ),
pMyBoxLog,“MyBoxPhys”,pMotherLog,0,cpNb);
//visualization
G4VisAttributes* myBoxVisAtt = new G4VisAttributes(G4Colour(1.0,0.0,1.0));
myBoxVisAtt->SetVisibility(true);
pMyBoxLogic->SetVisAttributes(myBoxVisAtt);
... the physics lists: G4VUserPhysicsList
Transport, decay, processes, all should be explicitly defined by the user...
Electromagnetic processes:
✔
Multiple scattering, Bremsstrahlung, Ionisation, Annihilation, Photoelectric effect , Compton
scattering , Rayleigh effect, conversion, e+e pair production, Synchrotron radiation, Transition
radiation, Cherenkov, Refraction, Reflection, Absorption, Scintillation, Fluorescence, Auger, ...
✔
Different classes for different particles, interaction descriptions or approximation
See, for instance, the em energy loss for charged particles at low energies
Hadronic processes:
✔
Different approach w.r.t. G3: w/o interfaces to external packages, separating data and algorithms
✔
Complete hadronic kit, with complementary models and fine granularity
✔
User has control and responsability. The framework provides some guiding
Parameterization (fast simulation) within regions for custommade physics
What to do in the user application?
✔
Define a set of particles and processes
✔
Define the production threshold ranges and assign them to world volumes
✔
Study the physics lists (educated guess) for em and hadronic Physics
... the physics lists: G4VUserPhysicsList
In practice:
myPhysicsList::myPhysicsList(): G4VModularPhysicsList(){
G4LossTableManager::Instance()->SetVerbose(0);
defaultCutValue = 1.*mm;
cutForGamma = defaultCutValue;
cutForElectron = defaultCutValue;
pMessenger = new myPhysicsListMessenger(this);
void myPhysicsList::ConstructParticle() {
G4VModularPhysicsList::ConstructParticle();
}
void myPhysicsList::ConstructProcess() {
if(!emBuilderIsRegisted) AddPhysicsList("standard");
G4VModularPhysicsList::ConstructProcess();
void myPhysicsList::SetCuts(){
SetCutValue(cutForGamma, "gamma");
SetCutValue(cutForElectron, "e-");
if (verbose>0) DumpCutValuesTable();
}
... the user actions for run, event, step and track levels
Run: G4UserRunAction
✔
User actions to be performed at the beginning and end of a run
✔
beginOfRunActions() is used for initialization of analysisrelated objects
✔
endOfRunAction() is used for getting run summaries and store analysisrelated objects
Event: G4UserEventAction
✔
User actions to be performed at the beginning and end of an event
✔
beginOfEventAction() is used for initialization of eventrelated objects and
✔
endOfEventActions() streams the event information
Step: G4UserSteppingAction
✔
User actions to be performed every step (be cautious!)
✔
userSteppingAction() allows the analysis of step details
Track: G4UserTrackingAction
✔
PreUserTrackingAction() and PostUserTrackingAction() provide most of the functionality
Also G4UserStackingAction allows the control of the stack (priority control, event filtering, ...)
... getting information for the user analysis
G4Track keeps the (transient) information of the status of a particle after each step
From G4Track (calling the corresponding getters... )
✔
Present and start positions, local and proper time
✔
Track momentum, kinetic energy and status, both in the actual state and in the starting state
✔
Pointers to the dynamic particle, the physical volume and the process creating the current track
✔
Accumulated track length and geometrical track length
✔
Current step number, trackID and parentTrackID
Tracks do not survive to the end of an event (do not provide persistency)
From G4Step (calling the corresponding getters... or the getters of the G4StepPoint )
✔
Geometrical and true step length, with the increments in position and time and the tracklength
✔
Changes in momentum and energy, as well as total energy deposited on the step
✔
Details on position, time, particle status, velocity, ... both before and after the step
✔
Pointers to the track, the PreStepPoints and the PostStepPoints (including volume and
material) and the physical processes defining the current and the previous step
... defining new control commands: G4UImessenger
Classes deriving from the base class G4UImessenger can construct Geant4 commands
✔
Usually different user classes are created, related with the user tasks
✔
Different commands (derived from G4UIcommand) can be created, ordered in directories
(G4UIdirectory) and maybe containing parameters (G4UIparameter)
✔
The values set by the commands should be related with the user code [in method SetNewValue()]
✔
Commands can be available only for some Geant4 states (state machine)
✔
Uses strong type and range checking
Example:
particleGamCmd = new G4UIcmdWithAString("/myApp/gun/particle",this);
particleGamCmd->SetGuidance("Select the incident particle.");
particleGamCmd->SetParameterName("particle",false);
particleGamCmd->SetDefaultValue("gamma");
particleGamCmd->AvailableForStates(G4State_PreInit,G4State_Idle);
Geant4 does not provide a main()
✔
Construct a G4RunManager with pointers to the mandatory user classes
Example:
Other relevant (user defined) topics...
Other features should be defined by the user providing different behavior:
✔
Sensitive detectors and Hits: a way to recover the information in the detectors
✔
Digits: an elaborated analysis of the detectors output
✔
Electric and magnetic fields: electric and magnetic
✔
Visualization: the graphical output for the setup and the created tracks
✔
User interfaces: giving access to the commands and control of the program in
run time; multiple outputs for standard and error outputs
✔
Connection to the analysis: the output information, in dynamical structures, can
be connected to different analysis frameworks
The Geant4 toolkit allows the user to define all these parts
Sensitive detectors, Hits: G4VSensitiveDetector, G4VHit
Any volume from which the user wants to recover interaction info is a sensitive detector
✔
The detector logical volume should be labeled as a sensitive volume
✔
The steps (G4Step) in the detector volume are processed in a User class (derived from
G4VSensitiveDetector), filling G4VHits derivatives
✔
The singleton G4SDManager manages the sensitive detectors, allowing access and activation
A Geant4 Hit is a representation of the effect of a track on a sensitive detector
✔
Typically contains the position and time, information of the particle features, ...
✔
Hits fill a collection (G4THitsCollection) for every step performed in a sensitive detector
✔
The Hit collections (G4HCofThisEvent) is available at the end of the event for further analysis
#include "G4VSensitiveDetector.hh" #include "G4VHit.hh"
#include "MyDriftChamberHit.hh" class MyDriftChamberHit:public G4VHit {
class G4Step; public:
class G4HCofThisEvent; MyDriftChamberHit();
class MyDriftChamberSD:public G4VSensitiveDetector { virtual ~MyDriftChamberHit();
public: virtual void Draw();
MyDriftChamberSD(G4String name); virtual void Print();
virtual ~MyDriftChamberSD(); private:
virtual void Initialize(G4HCofThisEvent*HCE); // some data members
public:
virtual G4bool ProcessHits(G4Step*aStep,
// some set/get methods
G4TouchableHistory*ROhist);
};
virtual void EndOfEvent(G4HCofThisEvent*HCE);
private:
#include “G4THitsCollection.hh”
MyDriftChamberHitsCollection * hitsCollection;
typedef G4THitsCollection<MyDriftChamberHit>
G4int collectionID;
MyDriftChamberHitsCollection;
};
Sensitive detectors, Hits: G4VSensitiveDetector, G4VHit
Setting sensitive volume in the user implementation
G4LogicalVolume* myDriftChamber = ……;
void MyDriftChamberSD::Initialize(G4HCofThisEvent*HCE){
hitsCollection = new MyDriftChamberHitsCollection
(SensitiveDetectorName,collectionName[0]);
if(collectionID<0){
collectionID = G4SDManager::GetSDMpointer()
->GetCollectionID(hitsCollection);
}
HCE->AddHitsCollection(collectionID,hitsCollection);
Use of G4HCofThisEvent in the analysis code ...
} G4int CHCID = G4SDManager::GetSDMpointer()
->GetCollectionID("driftChamberSD");
G4bool MyDriftChamberSD::ProcessHits
G4HCofThisEvent* HCE = evt->GetHCofThisEvent();
(G4Step*aStep, G4TouchableHistory*ROhist){
MyDriftChamberHit* aHit = new MyDriftChamberHit(); HitsCollection* CHC = 0;
// some set methods if(HCE)
...
DCHC = (MyDriftChamberHitsCollection*)
hitsCollection->insert(aHit);
return true; (HCE->GetHC(CHCID));
} if(DCHC){
G4int n_hit = DCHC->entries();
void MyDriftChamberSD::EndOfEvent(G4HCofThisEvent*HCE) {;}
G4cout<<"Drift chamber has ”<<n_hit<<" hits."<<G4endl;
for(G4int i=0;i<n_hit;i++){
MyDriftChamberHit* aHit = (*CHC)[i];
aHit->Print();
}
}
Digits: G4VDigi
Any derived information useful for analysing the response of the detectors
✔
Created using information of hits and/or other digits by a digitizer module
✔
User should instance their own derivative of G4VDigitizerModule class
✔
Used for simulate ADC/TDC, readout details, trigger logics or pile up
✔
Fills in a collection (G4VDigiCollection)
✔
The digits collections (G4DCofThisEvent) is available at the end of the event for further analysis
✔
The singleton G4DigiManager manages the collections of digits
✔
In contradiction to the sensitive detector which is accessed at tracking time automatically, the
digitize() method of each G4VDigitizerModule must be explicitly invoked by the user’s code
Electric and magnetic fields: G4MagneticField
Geant4 propagates tracks in uniform or nonuniform electromagnetic fields
✔
In general, uses a RungeKutta method for the integration of ordinary diff. equations of the
motion in the field, except that exact solutions exist. Other methods are available as option
✔
The curved path is broken in linear chord segments, used for geometrical analysis
✔
The sagitta (distance to the real curve) is limited by a miss distance, important for deciding
in which volume the track is (in cases of tracks moving in complex geometries)
✔
The delta intersection limits systematic errors in the intersection with boundaries
✔
The delta one step limits statistical errors on ordinary steps. It should be a fraction of the
average physics step size.
In practice ...
✔
Uniform fields:
G4MagneticField* magField = new G4UniformMagField(G4ThreeVector(1.*Tesla,0.,0.);
✔
For nonuniform fields, a concrete class derived from G4MagneticField should be created and
the GetFieldValue() method implemented :
void MyField::GetFieldValue(const double Point[4], double *field) const
‘Tracking’ Step Chords
Real Trajectory
Miss distance
Tracks visualization: G4Trajectory
A G4Trajectory made of G4TrajectoryPoint's can be obtained for each track
✔
Created by G4TrackingManager when a G4Track is passed from the G4EventManager
✔
Contains the trackID, parentTrackID, name, charge and PDG codes and the points of the track
✔
A G4TrajectoryPoint is created at the end of each step and added to the trajectory
User can set global ( /tracking/storeTrajectory ) or
✔
code controlled (in G4UserTrackingAction) flags for
storing or plot the track's trajectories
✔
By default, trajectories are stored in
G4TrajectoryContainer and kept by G4Event
✔
Users can draw or print trajectories from the
container in their user implementation of the
function G4UserEventAction::EndOfEventAction()
✔
By default, colors are: positive, neutral and
negative particles; user can modify them
Note: G4Step and G4Track are transient objects,
while G4Trajectory could be used for persistency
Note: users should not create trajectories for
secondaries in showers due to memory problems!
General visualization: drivers
A flexible visualization scheme is incorporated, allowing the use of many graphics libraries
✔
Visualization is (almost) independent of user code. Different drivers can be easily selected
✔
Code for adding visualization in user applications is available in the examples
✔
What? Detectors, particle trajectories, hits in the detectors, Polylines, 3D markers, text, ...
✔
Visualization attributes (as colors) can be assigned to visible objects: logic volumes, tracks, ...
Why many graphical libraries?
✔
The requirements are diverse: for instance, quick response vs. highquality output for publication
✔
No one is adecuate for all possible purposes
✔
OpenGL (fast direct output with render), OpenInventor (direct output), HEPREP (file in external
browser), DAWN (file output, good rendering in ps), VRML (file to browser), RayTracer (jpeg), ...
✔
Note that most (if not all) depends on external libraries that should be previously installed
✔
Installation and details depends on platform...
User interfaces
Geant4 allows the definition of external user interfaces
✔
Basics G4UIterminal and G4UItcsh interfaces working in Unixlike platforms
✔
Xm (basically an UI w/o graphics capabilities), OPACS, GAG (Java or Tcl/Tk), ...
✔
Each one presents different features and problems
✔
The selection of the interface is made by environment variables (except the basics)
✔
Should be created in the main() function, according to your computer environment
✔
In any case, Geant4 provides a large number of user interface commands and the user adds
their own by instanciating messenger classes
G4UIRoot: a GUI built using the ROOT libraries
✔
Created and maintained by Isidro Gonzalez (CERN)
✔
All functionality available in a clickable GUI
✔
Treelike command structure
✔
Independent windows for output and errors
(G4cout and G4cerr) with saving capabilities
✔
History, help, customizable
✔
ROOT interpreter (CINT) included
✔
Access to TBrowser during runtime
✔
Download from
http://i.home.cern.ch/i/iglez/www/alice/G4UIRoot/installation.html
Connection to the analysis: histogramming and more...
Geant4 is independent of any analysis/histogramming package
✔
Examples are available for different packages: AIDA, JAS, PI, Open Scientist Lab, ...
✔
ROOT has been used in several applications in Nuclear Physics (including ours)
✔
Whatever you use, environment variables should be defined acordingly
Connecting the simulation to ROOT
✔
Add the analysis objects (TH1, TTree, TClonesArray, ...) in your classes
✔
Better if the ROOT dependencies are separated from the Geant4 code
✔
Link the ROOT libraries in the GNUmakefile
Practicum
PRÁCTICA GEANT4
Objetivos:
Iniciar al alumno en la utilización de un código Monte Carlo de simulación (GEANT4).
✔
Familiarizarlo con herramientas básicas de análisis de datos (ROOT).
✔
Comprender códigos simples en GEANT4.
✔
Comprender y realizar macros básicas de análisis de los datos obtenidos.
✔
Estudiar la respuesta de un material (detector) a la radiación .
✔
Requisitos previos:
Conocimientos básicos de Linux (moverse por directorios, correr programas, abrir editores,...);
son de utilidad conocimientos previos de ROOT y GEANT4.
Descripción del código:
El programa “practica” está instalado en la carpeta geant4/practica de la cuenta asignada. Dentro de esta carpeta encontrareis:
los ficheros README y HOWTO con descripciones de cómo correr el código;
✔
el fichero GNUmakefile con las instrucciones de compilación;
✔
las macros batch.mac y test1.mac utilizadas para pasar instrucciones al correr el programa;
✔
la macro (ROOT) plot_multichannel.C, con comandos para representar espectros de energía;
✔
finalmente, el código de la aplicación está en las carpetas src/ (archivos de implementación [.cc]) e include/ (headers, con las
✔
declaraciones de las variables [.hh]). La función main() está en el fichero practica.cc, donde se invocan las tareas definidas por
el usuario.
Practicum
Procedimiento:
●
Identifica las distintas partes del código y las funciones donde se realizan los cálculos y se describen las
acciones definidas por el usuario:
✔
Descripción geométrica: practicaDetectorConstruction
✔
Generador de eventos: practicaPrimaryGeneratorAction
✔
Salida por pantalla en cada step: practicaSteppingVerbose
✔
Almacenamiento de la energía depositada en el detector: practicaSteppingAction
✔
Control del programa durante la ejecución: clases *Messenger*
✔
Macro de visualización y ejecución: test1.mac y batch.mac
●
Ejecuta del programa (visualización); ejecuta el comando: “practica” que lanza el programa.
✔
Estudia las pantallas que aparecen, que pertenecen a una interfaz de usuario de GEANT4 (G4UIRoot).
Te permitiran controlar la simulación de forma interactiva.
✔
Navega por los menús de comandos en la ventana “Geant4 User Interface”. Observa y apunta en
particular los contenidos en el directorio “practica”, que contiene los comandos predefinidos para esta
simulación.
✔
Lanza un par de gammas ( /run/beamOn 2 ) y comprueba el resultado gráfico y la salida texto en la
ventana “G4 Output”.
✔
Prueba diferentes comandos geométricos en la interfaz de comandos; lanza una serie de gammas e
identifica gráficamente las interacciones, ayudándote con la salida texto.
✔
Prueba a cambiar el tamaño del detector mediante los comandos adecuados (acuérdate de realizar un
update para observar los cambios antes de lanzar partículas)
✔
Comprueba la salida que produce el programa: una serie de ficheros .dat (tantos como veces se ha
llamado a la función /run/beamOn) y un fichero simFile.root
Practicum
Procedimiento:
●
Estudia el espectro de energía depositada en el medio detector.
✔
Corre el programa en modo batch con el comando: “practica batch.mac”, que ejecuta los comandos
contenidos en el fichero batch.mac
✔
Identifica las características principales del espectro de energía depositada en el medio
✔
Cuantifica la eficiencia del fotopico
✔
Estudia la diferencia en el espectro y en la eficiencia cuando la incidencia de los gammas sea central o
distribuida de forma homogénea en la superficie del detector (utiliza el comando
/practica/gun/flatDistribution).
●
[Avanzado] Modifica el tipo de geometría de los detectores e incluye absorbentes entre la fuente y el detector
en el código de GEANT4, modificando el código en el fichero practicaDetectorConstruction.cc. Comprueba
cómo se modifican los espectros para distintas materiales y grosores de absorbentes delante del detector.
●
[Avanzado] Comprueba el fichero de salida ROOT y la forma en la que se generan los directorios con
diferentes histogramas, definidos en el fichero practicaAnalysisExample.cc.
●
[Avanzado] Utiliza la descripción Física “lowenergy” y observa las diferencias en la zona de bajas energías
(líneas de espectros de rayos X del Cs y del I) con gammas del 100 keV y un detector de pequeño tamaño.
Where to learn more: bibliography and manuals
Users support:
✔
Hypernews User Forum: exchange of questions and experience among users and developers
✔
Problem reporting: for unreported new problems on the code
✔
Training material, FAQ, courses, ...
http://geant4.cern.ch/
Simulation and MonteCarlo methods:
✔
Fundamentals of the Monte Carlo method for neutral and charged particle transport, A.F. Bielajew
✔
Monte Carlo Simulation, J.L. Tain (Curso de Doctorado 2005)
Geant4 manuals:
✔
Geant4: Physics Reference Manual (June 2006)
http://geant4.cern.ch/support/index.shtml
✔
Geant4: Application Developers Guide
http://geant4.web.cern.ch/geant4/UserDocumentation/UsersGuides/ForApplicationDeveloper/html/index.html
Other manuals:
✔
G4UIRoot: a Geant4 GUI using ROOT
http://i.home.cern.ch/i/iglez/www/alice/G4UIRoot/
✔
ROOT: a toolkit for the Physics analysis
http://root.cern.ch/