My Geant4 tutorial
Here are a few tips to start learning Geant4 in a less tough way than struggling alone with the G4 manual and the novice (???) examples.
This tutorial has to be seen as a "post-introduction" to G4.
1. First advices
1.1. About simulations...
Please see here.
1.2. About C++
Encapsulation, inheritance, polyphormism, templating...
If these words sound like gibberish, first do learn C++ & OOP (Object Oriented Programming)!
It's worth spending a whole week or more learning and EXPERIENCING C++ than loosing ages trying stupid things!
Feel free to go and annoy
Sébastien Greder
who must be one of the most skilled C++ coder of the lab.
Before starting Geant4, you should feel comfortable with (so you should have created your own programs (within ROOT or not)):
- basic C++ programming: pointers & references, templates, preprocessor directives, ...
- See here (CCM) & here (CPP)
- OOP: classes (attributes, methods, visibility, constructor, destructor, copy constructor, operator overloading, this, static, friend...)
& concepts (encapsulation, inheritance, polymorphism, ...)
- See here (CCM) & here (CPP)
- STL containers & algorithms: vector, (multi)map, iterators...
- See here (CPP)
At the end, you should be able to navigate through the source code (e.g. here) and find and understand everything you need, hopefully.
2. First programs
Below's a set of basic programs I wrote within the context of a collaboration with our Catalan colleagues of the
UAB/GFR.
It aims at learning G4 in more progressive way than jumping from N01 to N0whatever.
2.1. Base program
The program uab_plain is the program on which all the other examples are based. It is described below.
2.1.1. Preamble
I always use a macro file in order not to recompile every 2 secs (see below for particle generation and physics processes).
I do not use the G4 prompt.
2.1.2. A few comments on the source code
- Geometry
- All the dimensions are gathered in the constructor
- Building materials is always a bit annoying and it is very tempting to use
NIST materials
which eases the material declaration
----------------------------------------------------------------------------
BUT
(G4NistManager::Instance())->FindOrBuildMaterial("G4_AIR") ; // See $G4INSTALL/source/materials/src/G4NistMaterialBuilder.cc ----------------------------------------------------------------------------
. keep in mind the density may not be yours
. there is still ISSUES with some compounds and Low Energy physics lists.
- Physics
- Nothing special. Just note processes declared can be inactivated through your macro file (no need to recompile) with the command
----------------------------------------------------------------------------
The processName of your physics class can be found in its constructor (see its header file).
/process/inactivate processName ----------------------------------------------------------------------------
- Nothing special. Just note processes declared can be inactivated through your macro file (no need to recompile) with the command
- Source term
- In most cases, the particle source generation is simple.
So don't bother to hard code anything, just use the G4GeneralParticleSource class.
- In most cases, the particle source generation is simple.
- Output
- None, except a visualization file (see below)
2.1.3. Visualization
I recommend Wired4 (3D navigation, information picking, filtering, vectorial export...).
Tips and installation of drivers can be found here (section GDML) and here.
2.1.3.1. Installing Wired4
Jas3 is a generic platform. Plugins should be installed to display G4 .heprep.zzz files.
Once installed, launch jas3 and load all the visualization plugins clicking: View / Plugin Manager... / Available / hep / visualization / *
To test if everything went fine, execute the following steps:
- Restart JAS3
- Download this file
- Click File / View / Wired4 View
- Click File / Open Data Source... / HepRep XML (...) / Browse... / Finish
- Press F11 for the geometry (|> button)
- Press F11 once more for the geometry + the events
- Zoom with the mouse wheel & Rotate moving the mouse with the left button pressed (once you click on the "sphere" button)
2.1.3.2. How to create Wired4 files?
- Add the following lines to your main file:
----------------------------------------------------------------------------
#include "G4VisManager.hh" #include "G4VisExecutive.hh" ... G4VisManager *visManager = new G4VisExecutive (); visManager->Initialize (); ... delete visManager ; ----------------------------------------------------------------------------
- Add the following lines to your macro file:
----------------------------------------------------------------------------
/vis/open HepRepXML /vis/scene/create myFile.heprep.zip /vis/scene/add/volume /vis/scene/add/trajectories /vis/scene/add/hits /vis/sceneHandler/attach /vis/viewer/flush /tracking/storeTrajectory 1 /vis/scene/endOfEventAction accumulate ----------------------------------------------------------------------------
2.1.4. Compilation and Execution
First make sure the variable "name" in your GNUmakefile is the root name of your main.cc file, e.g. "name := mySimu" for mySimu.cc.
Type
----------------------------------------------------------------------------
make # OR make -j N # where N is the number of processors on the machine you're working on: # To get it, type: cat /proc/cpuinfo | grep "processor.*:" | wc -l ----------------------------------------------------------------------------
in the example directory (where the main file and the GNUmakefile lie).
Then
----------------------------------------------------------------------------
cd $G4BIN/$G4SYSTEM && ./myExp myExp.mac ----------------------------------------------------------------------------
where myExp.mac is a link to your macro file (working with only one version is safer)
----------------------------------------------------------------------------
cd $G4BIN/$G4SYSTEM && ln -s [the_directory_where_my_main_file_lies]/myExp.mac ----------------------------------------------------------------------------
Here's a piece of my ~/.bashrc in order to automate everything
----------------------------------------------------------------------------
export G4BINDIR=$G4BIN/$G4SYSTEM export G4TMPDIR=$G4TMP/$G4SYSTEM export G4MYFILES=/cygdrive/d/thesis/simu/geant4/myfiles export G4MYSIMU=$G4MYFILES/mytutos/myExp_plain_xxx export G4MYSIMU_EXE=myExp_plain # See the GNUmakefile export G4MYSIMU_MAC=myExp_plain.mac alias g4sim="cd $G4MYSIMU && ll" alias g4bin="cd $G4BINDIR && ll" alias g4clean="rm -rf $G4BINDIR/$G4MYSIMU_EXE $G4TMPDIR/$G4MYSIMU_EXE" alias g4bck="cd $G4BINDIR ; [ -d $G4MYSIMU/z_analysis/data ] && mv -f *.root $G4MYSIMU/z_analysis/data 2>/dev/null ; [ -d $G4MYSIMU/z_analysis/results ] && mv -f *.log $G4MYSIMU/z_analysis/results/ 2>/dev/null ; [ -d $G4MYSIMU/z_heprep ] && mv -f *.heprep* $G4MYSIMU/z_heprep/ 2>/dev/null" alias g4exec="g4bin ; [ ! -f $G4MYSIMU_MAC ] && ln -s $G4MYSIMU/$G4MYSIMU_MAC ; ./$G4MYSIMU_EXE $G4MYSIMU_MAC && alert" alias g4execbck="g4exec && g4bck && alert" export NPROC=$(cat /proc/cpuinfo | grep "processor.*:" | wc -l) alias _g4="make -j $NPROC && g4execbck" # buffer aliases (should not be called) alias g4="g4sim && _g4" alias g4k="g4sim && g4clean && _g4" ----------------------------------------------------------------------------
If this makes sense, just type:
- g4 to compile and run your example,
- g4k to erase everything, compile and run your example (this is a healthy habit to get into, especially after a change in your physics list).
Don't forget to source your ~/.bashrc
----------------------------------------------------------------------------
source ~/.bashrc ----------------------------------------------------------------------------
when you change one of the G4MYSIMU_* environment variables.
2.2. How to extract information?
There are basically 3 ways to extract information from G4
- playing around with SteppingAction/EventAction/RunAction
- See uab_actions. Mind the articulation between SteppingAction and EventAction.
- See uab_actions_root for the same program with a Root output. Mind the GNUmakefile. Root reading explanations are given at the end of the macro file.
- See $G4EXAMPLES/novice/N03.
- playing around with Hits and Sensitive Detectors (SD)
- See uab_actions_hits
- See alpharad_new, bringing in a universal Hits/SD output method with a proper root coupling, an analysis manager, ... See here.
- See $G4EXAMPLES/novice/N02.
- playing around with Scoring tools
- See uab_scoring
- See alpharad_scoring, bringing in a universal scoring output method
- See $G4EXAMPLES/novice/N07.
For the $G4EXAMPLES/novice/N0i examples, the easiest is to skim the geometry to its minimum (a plain slab or 2 is perfect) and try to understand...
Personally, I recommend the Hits/SD method since you can extract everything you want (more easily than with juggling with SteppingAction and EventAction).
The scoring method is quite limited. Besides you just get mean values or histograms. Some information is definitely lost.
Please note the output philosophies in alpharad_new and alpharad_scoring are the best I could have imagined so far. I spent bunches of hours working on them.
So I sent both codes to the Geant4 collaboration proposing them to be integrated to the G4 example official list. Cross fingers!
In the meanwhile, I put them under CeCILL licence i.e. they can be distributed and modified but my name should ever appear
and any changes to the original source should be explicitly mentionned (author name and date) in case of redistribution.
2.3. How to create new commands or how not to recompile every 2 secs?
Recompiling its code each time one wants to change something like geometry (e.g. detector size and/or position), materials,
physics processes involved, input particles, actions at run/event/step level... is very irritating.
Through the "Messenger" mechanism, Geant4 provides a way to create commands to interact with your simulation at execution time (just put them in your macro file).
See e.g. the G4GeneralParticleSourceMessenger
or the G4ProcessTableMessenger. Does it ring it bell?
Creating your own commands in exactly the same way is not difficult, see e.g. the *Messenger.{hh,cc} classes in the example novice/N03
or here.
In the last example, mind the compilation subtlety in myClass.{cc,hh} while looking at myClass_Messenger.{hh,cc} (look for the string "// for compilation reason").
Actually, lots of built-in commands (ready-to-use commands) already exist in Geant4.
For a list of all the messengers available, look the string "Messenger" up in this page
and read the corresponding .cc file.
3. Advices for Low Energy users
As mentioned here, make sure you're using the most appropriate model.
Watch out! A part of the following paragraphs should soon be obsolete (see the WARNING section at the end).
Still it contains nice tips...
3.1. Photons, electrons and positrons
- Photons: use G4LowEnergyPhotoElectric, G4LowEnergyCompton, G4LowEnergyGammaConversion, G4LowEnergyRayleigh
- Electrons: use G4eMultipleScattering, G4LowEnergyIonisation, G4LowEnergyBremsstrahlung
- Positrons: use G4eMultipleScattering, G4eIonisation, G4eBremsstrahlung, G4eplusAnnihilation (no LowEnergy extensions)
Alternatively, you can use the physics of Penelope through the G4Penelope* classes. (to be tested)
3.2. Protons, Alphas, ... i.e. LCPs & Generic ions...
Use G4hLowEnergyIonisation and G4hMultipleScattering for electromagnetic processes.
For hadronic processes, LowEnergy (LE) models exist for LCPs, e.g. for alpha particles:
---------------------------------------------------------------------------- // Elastic G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess("hElastic") ; G4LElastic* theElasticModel = new G4LElastic() ; theElasticProcess->RegisterMe(theElasticModel) ; processManager->AddDiscreteProcess(theElasticProcess) ; // Inelastic G4AlphaInelasticProcess* theAlphaInelasticProcess = new G4AlphaInelasticProcess() ; G4LEAlphaInelastic* theLEAlphaInelasticModel = new G4LEAlphaInelastic() ; theAlphaInelasticProcess->RegisterMe(theLEAlphaInelasticModel) ; processManager->AddDiscreteProcess(theAlphaInelasticProcess) ; ----------------------------------------------------------------------------
3.3. Neutrons
Complete case-driven physics lists already exist (see here).
To use one of these predefined physics list, just proceed to the physics list replacement in your main file,
e.g. for low energy neutrons which should bring in
LHEP_PRECO_HP
----------------------------------------------------------------------------
#include "LHEP_PRECO_HP.hh" ; ... runManager->SetUserInitialization ( new LHEP_PRECO_HP() ) ; // This is your new physics list! ----------------------------------------------------------------------------
By default, the EM LowEnergy classes are not included.
You will have to create your own physics list by copying and customizing one of the proposed lists.
The EM physics is called in the .icc file. Create yours and call it accordingly.
For thermal neutrons, the S(alpha,beta) treatment (free gas model) is a bit more subtle to implement.
Here's the trick I got from Pedro Arce (Pedro.Arce@ciemat.es) after one of his talk.
- Copy the following files G4HadronElasticPhysics_newThermalN.tgz in the include/ and src/ directories.
- Replace all the lines calling G4HadronElasticPhysics by G4HadronElasticPhysics_newThermalN in your physics list.
- Create the specific materials it applies to.
Actually, only 3 materials are available: water, polyethylene and graphite.
They have to be named "TS_H_of_Water", "TS_H_of_Polyethylene", "TS_C_of_Graphite" respectively
and can be created through the traditional G4Element/G4Material classes or through the NIST builder ConstructNewMaterial() method.
3.4. WARNING
The g4.9.3.b01 release (june 2009 beta release) specifies that all the G4[h]LowEnergy* classes
(check this)
and some physics lists won't be supported any more, and will be definitely removed with the next major release (g4.9.3 certainly),
especially LHEP_PRECO_HP, that should be replaced by QGSP_BIC_HP which "offers similar functionality for most use cases"... (to be tested)
If you used to work with EM LowEnergy classes, an alternative can be found here (issue still on going off the forum).
All the "EM options" commands available are in $G4SOURCE/processes/electromagnetic/utils/src/G4EnergyLossMessenger.cc
(see here).
New generic builders are also available from g4.9.3.b01: G4EmLivermorePhysics and G4EmPenelopePhysics
in addition to G4EmStandardPhysics and G4EmStandardPhysics_option{1,2,3} (see $G4SOURCE/physics_lists/builders/).
To use them, proceed like with LHEP_PRECO_HP (see above).
You could also create a modular physics list (selection of a specific physics list at execution time).
Have a look to the
- extended/electromagnetic/TesEm2 example if you just want to use EM physics lists
- extended/hadronic/Hadr01 example if you want to use different combinations of EM & HAD (hadronic) physics lists
To use a complete predefined physics list (EM+HAD) without having to create any file, see the example extended/hadronic/Hadr00.
4. GDML import
CAD files can be imported into G4 through different softwares.
Everything's explained here (section GDML).
Some examples are provided in $G4EXAMPLES/extended/persistency/gdml/, especially the example G02 contains nice tips.
I don't have much experience in interacting with .gdml geometries.
At lab Sandrine Courtin
and François Didierjean
should do.
Feel free to contact them as well as Marc Labiche (m.labiche@dl.ac.uk) at Daresbury, UK.
5. Epilogue
Useful links
- on-line source code (you can easily yours with doxygen)
- Model/Process Catalog (which processes are attached to which particles)
- Wiki (dealing with physics lists mainly)
- Forum (essential)
Viel Glück!
PS: If you use NEdit, please see here.