0% found this document useful (0 votes)
24 views59 pages

Introduction

The document provides an introduction to the Geant4 simulation toolkit, focusing on its structure, capabilities, and applications in various fields such as physics and medical imaging. It outlines the course structure, including theoretical lectures and hands-on coding sessions, and emphasizes the use of the Monte Carlo method for simulating complex interactions. Geant4 is an open-source, object-oriented toolkit that requires users to configure their simulations and provides extensive documentation and examples for guidance.

Uploaded by

hamid.oubajja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views59 pages

Introduction

The document provides an introduction to the Geant4 simulation toolkit, focusing on its structure, capabilities, and applications in various fields such as physics and medical imaging. It outlines the course structure, including theoretical lectures and hands-on coding sessions, and emphasizes the use of the Monte Carlo method for simulating complex interactions. Geant4 is an open-source, object-oriented toolkit that requires users to configure their simulations and provides extensive documentation and examples for guidance.

Uploaded by

hamid.oubajja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

The Geant4

simulation toolkit:
an introduction

Giada Petringa (LNS-INFN)

XVI Seminar on Software for Nuclear, subnuclear and


Applied Physics

[Link]@[Link] 1
G4 School Outline
2

Generals on Monte Carlo


Basic capability of Geant4
Basic structure of the Geant4 components

At the end of the school


Configuration
Generation of particles
Geometry and materials
Tracking
Physics
Scoring

[Link]@[Link]
Finding the material
3

Pablo Cirrone, Giada Petringa, Davide Chiappara, Ruhani Khanna


INFN-Laboratori Nazionali del Sud - Catania, (I)

Official tutorial and school regularly offered:


see the Geant4 web pages
Official Geant4 web pages:
[Link]
The Italian Geant4 group:
[Link]
[Link]

[Link]@[Link]
Structure and Logistics-1
4

■ This course is organized in a mixture of theoretical lectures and


practical hands-on sessions
■ The hands-on sessions require real C++ coding to build up a
simplified Geant4 application
■ Staged approach in tasks
■ [Link]

■ A pre-installed virtual machine is provided for the hands-on


sessions
■ Includes Geant4 10.05.p01 on a Linux environment
■ You should already have it downloaded and tested
■ Please let us know ASAP if you have problems with the VM

[Link]@[Link]
Structure and Logistics-2
5

■ You can try to install Geant4 on your (Linux/Mac) laptop,


if you wish
■ The course is not meant to show that, though

■ All lectures (pdf) will be uploaded on-the-fly on the course


indico page
■ [Link]

■ Please feel free to ask any question, either during the


lectures , during the exercises or during the breaks
■ Solutions of the exercises will be uploaded after the end
of each exercise session

[Link]@[Link]
Lesson Outline
6

Introduction to the Monte Carlo method


Introduction to Geant4
Structure of the Geant4 Kernel
Structure of a typical Geant4 application

[Link]@[Link]
Monte Carlo method
Monte Carlo techinque
8

■ Numerical solution of a (complex) macroscopic


problem, by simulating the microscopic interactions
among the components
■ Uses random sampling, until convergence is
achieved
■ Name after Monte Carlo's casino
■ Applications not only in physics and science, but
also finances, traffic flow, social studies
■ And not only problems that are intrisically
probabilistic (e.g. numerical integration)

[Link]@[Link]
Monte Carlo techinque
9

■ Produce a configuration (or a "final state"), according to


some "laws", e.g.
■ People mostly arrive in pairs
■ Audience members prefer an un-obstructed view of the
stage
■ Audience members prefer seats in the middle, and close to
the front row
■ Only one person can occupy a seat
■ Contrarily e.g. to physics, the laws are not known
■ Rather use "working assumptions"
■ The math (exact) formulation can be impossible or unpratical
=> MC is more effective

[Link]@[Link]
MC in science
10

■ In physics, elementary laws are (typically) known =>


MC is used to predict the outcome of a (complex)
experiment
■ Exact calculation from the basic laws is unpractical
■ Optimize an experimental setup, support data
analysis
■ Can be used to validate/disproof a theory, and/or to
provide small corrections to the theory
■ In this course: Monte Carlo for particle tracking
(interaction of radiation with matter)

[Link]@[Link]
Interplay between theory, simulations and experiments
11

[Link]@[Link]
MC application

nav
a l ba
ttle
Monte Carlo methods vary, but tend to

Can you sink the ship?


follow a particular pattern:
1) Define a domain of possible inputs
2) Generate inputs randomly from a
probability distribution over the domain
3) Perform a deterministic computation
on the inputs
4) Aggregate the results

[Link]@[Link]
The simplest MC application
13

0<x<1
0<y<1
For example, consider a quadrant
(circular sector) inscribed in a unit M(x,y)
square. Given that the ratio of their
areas is π/4, the value of π can be
approximated using a Monte Carlo
method

[Link]@[Link]
The simplest MC application
14

0<x<1
0<y<1
■ Shoot N couples (x,y) randomly
in [0,1] M(x,y)
■ Count n: how many couples
satisfy (x2+y2≤1)

■ n/N = r*π/4 (ratio of areas)


■ Probability=Asector/Asquare
■ Convergence as 1/ √N
[Link]@[Link]
When are MC useful to the math solution?
15

■ Usually the
Monte Carlo
wins over the
exact
(mathematical)
solution for
complex
problems

[Link]@[Link]
A bit of history
16

■ Very concept of Monte


Carlo comes in the XVIII
century (Buffon, 1777,
and then Laplace, 1786)
■ Monte Carlo estimate of
π
■ Concept of MC is much
older than real computers
■ one can also implement
the algorithms manually,
with dice (= Random
Number Generator)
[Link]@[Link]
A bit of history
17

■ Boost in the '50 (Ulam and Von


Neumann) for the development of
thermonuclear weapons
■ Von Neumann invented the name
"Monte Carlo" and settled a
number of basic theorems
■ First (proto)computers available at
that time
■ MC mainly CPU load, minimal I/O

[Link]@[Link]
Geant4
Monte Carlo codes and Geant4
19

MCNP (neutrons mainly) Geant4


GEometry ANd Traking
Penelope (e- and gamma)
Geant4 - a simulation toolkit
PETRA (protons) Nucl. Inst. and Methods Phys. Res. A,
506:250-303 (2003);
EGSnrc (e- and gammas) Geant4 developments and
applications
Transaction on Nuclear Science 53,
PHIT (protons/ions) 270-278 (2006);

FLUKA (any particle) Recent developments in Geant4


Nucl. Inst. and Methods Phys. Res. A,
835:186-225 (2016)

[Link]@[Link]
Facts about Geant4
20

Geant4 started at CHEP 1994 @ San Francisco


“Geant steps into the future”, R Brun et al.
“Object oriented analysis and design of a Geant based detector simulator”,
K Amako et al
Dec ’94 - CERN RD44 project starts
Apr ’97 - First alpha release
Jul ’98 - First beta release
Dec ’98 - First Geant4 public release - version 1.0
........

April, 2019 - Geant4 10.5 patch 01 release Current version in the VM

We currently provide one public release every year (next release December 9th)
[Link]@[Link]
Facts about Geant4
21

[Link]

■ Code and documentation available in the main web


page
■ Regular tutorial courses held worldwide

[Link]@[Link]
Facts about Geant4
22

• BaBar is the pioneer HEP experiment in use of OO technology and the first
customer of Geant4
- During the R&D phase of Geant4 a lot of evaluable feedbacks were provided
• BaBar started its simulation production in 2000 and had produced more than
10 bilion events at more than 20 sites in Europe and North America.

[Link]@[Link]
Facts about Geant4
23

[Link]@[Link]
LHC @CERN
ATLAS
■ All four big LHC
experiments have a Geant4
simulation
■ M of volumes
■ Physics at the TeV scale

■ Benchmark with
test-beam data
■ Key role for the
Higgs searches
CMS

[Link]@[Link]
Space application

■ Satellites (γ astrophysics, planetary sciences)


■ Funding from ESA

GLAST

AGILE

Typical telescope:
Tracker
Calorimeter
Anticoincidence

[Link]@[Link]
Facts about Geant4
26

Major use cases


Beam therapy
Brachytherapy
Imaging
Irradiation study
Nuclear medicine and radioisotopes
Biological damage

[Link]@[Link]
Medical Physics
■ Treatment planning for
hadrontherapy and proton-therapy
systems
■ Goal: deliver dose to the

tumor while sparing the


healthy tissues
■ Alternative to less-precise (and

commercial) TP software
■ Medical imaging
■ Radiation fields from medical
accelerators and devices
■ medical_linac
Medical Physics group of LNS-INFN ■ gamma-knife
■ brachytherapy

[Link]@[Link]
Basic concepts and
Geant4 capabilities

[Link]@[Link] 28
Geant4 overview
29

C++ language
Object Oriented
Open Source
Once per year released
It is a toolkit, i.e. a collection of tools the User can use for his/her simulation
Consequences:
There are not such concepts as “Geant4 defaults”
You must provide the necessary the necessary information to configure your
simulation
You must choose the Geant4 tool to use
Guidance: many examples are provided:
Basic examples: overview of the Geant4 tools
Extended examples: showing specific Geant4 functionalities
Advanced Examples: Geant4 tools in real-life applications

[Link]@[Link]
Geant4 basics
30

What you MUST do:


Describe your experimental set-up
Provide the primary particles input to your simulation
Decide which particles and physics models you want to use out of those available in
Geant4 and the precision of your simulation (cuts to produce and track secondary
particles)
You MAY ALSO WANT:
To interact with the Geant4 kernel to control your simulation
To visualise your simulation set-up and particles
To produce histograms, tuples, etc. to be further analysed

[Link]@[Link]
Multi-threading
31

Geant4 supports multi-thread (MT) approach that can be used in multi-cores


machines
Simulation is automatically split on a event-by-event basis
Different events are processes by different cores
Unique copy of Geometry and Physics
All cores have them as read-only
Functionality in place since Geant4 10.0
Backward compatible with the sequential mode
MT programming requires some cares
Need to avoid conflicts between threads

[Link]@[Link]
Multi-threading
Master
Geometry Physics RunAction

READONLY

Workers

Primary Primary Primary

RunAction RunAction RunAction

EvtAction EvtAction EvtAction

[Link]@[Link]
Files composing a Geant4 application
33

Main() file
Sources files (*.cc)
usually included in the src/ folder
Header files (*.hh)
usually included in the include/ files
Three classes are necessary (with the [Link] ons), each typically in a dedicated
header/source pair of files
The PrimaryGeneratorAction (.cc and .hh)
The DetectorConstruction (.cc and .hh)
The PhysicsList (.cc and .hh)

[Link]@[Link]
Mandatory User’s classes – v1
34

Initialisation classes
Invoked at the initialisation Action classes
Invoked during the execution loop
G4VUserDetectorConstruction
G4VUserPhysicsList G4VUserPrimaryGeneratorAction

G4UserRunAction
G4UserEventAction
G4UserTrackingAction
G4UserStackingAction
G4UserSteppingAction

[Link]@[Link]
Mandatory User’s classes – v2 (MT)
35

Initialisation classes Action classes


Invoked at the initialisation Invoked during the execution loop

G4VUserDetectorConstruction G4VUserActionInitialization
G4VUserPhysicsList
G4VUserPrimaryGeneratorAction
G4UserRunAction (*)
G4UserEventAction
Global: only one instance of them G4UserTrackingAction
exists in memory, shared by all G4UserStackingAction
G4UserSteppingAction
threads (readonly).
Managed only by the master thread.
Local: an instance of each action class
exists for each thread.

(*) Two RunAction's allowed: one for


master and one for threads

[Link]@[Link]
The main() file

36
The main()
37

• Geant4 does not provide a main() file

- Geant4 is a toolkit!
- The main() is part of the User application
• In his/her main(), the user must:

- Construct the G4RunManager


- Notify the G4RunManager the mandatory user classes derived from:

✓ runManager -> SetUserInitialization


(new MyApplicationDetectorConstruction)

[Link]@[Link]
The main()
38

The user MAY define in his/her main():

Optional user action classes

VisManager, (G)UI session

The User has also to take care of retrieve and save the relevant information
from the simulation (Geant4 will not do that by default)

Do not forget to delete the G4RunManager at the end

[Link]@[Link]
An example of sequential main()
39

{
// Construct the default run manager
G4RunManager* runManager = new G4RunManager;

// Set mandatory user initialization classes


MyDetectorConstruction* detector = new MyDetectorConstruction;
runManager -> SetUserInitialization(detector);
MyPhysicsList* physicsList = new MyPhysicsList;
runManager -> SetUserInitialization(myPhysicsList);

// Set mandatory user action classes


runManager -> SetUserAction(new MyPrimaryGeneratorAction);

// Set optional user action classes


MyEventAction* eventAction = new MyEventAction();
runManager -> SetUserAction(eventAction);
MyRunAction* runAction = new MyRunAction();
runManager -> SetUserAction(runAction);
}

[Link]@[Link]
Methods for Users classes
40

G4UserRunAction
BeginOfRunAction(const G4Run*) // book histos

EndOfRunAction(const G4Run*) // store histos

G4UserEventAction
BeginOfEventAction(const G4Event*) //initialize event

EndOfEventAction (const G4Event*) // analyze event

G4UserTrackingAction
//decide to store/not store a given track

PreUserTrackingAction(const G4Track*)

PostUserTrackingAction(const G4Track*)

[Link]@[Link]
Methods for Users classes
41

G4UserSteppingAction
UserSteppingAction(const G4Step*)
//kill, suspend, pospone the track, draw the step, …

G4UserStackingAction
PrepareNewEvent()
//reset priority control

ClassifyNewTrack(const G4Track*)
// Invoked when a new track is registered (e.g. kill, pospone)

NewStage()
// Invoked when the Urgent stack becomes empty (re-classify, abort event)

[Link]@[Link]
Selection of physics processes
and optional capabilities

[Link]@[Link] 42
Physics processes
43

Geant4 doesn’t have any default particles or processes


Derive your own concrete class from the G4VUserPhysicsList abstract base class

Define all necessary particles


Define all necessary processes and assign them to proper particles
Define particles production threshold (in terms of range)
Methods of G4VUserPhysicsList:
ContructParticles()
ConstructProcesses()
SetCuts()

[Link]@[Link]
Physics Lists
Geant4 doesn’t have any default particles or processes
Partially true: there is no default, but there are a set of "ready-for-use"
physics lists released with Geant4, tailored to different use cases. Mix and
match
Different sets of hadronic models (depending on the energy scale and
modelling of the interactions)
Different options for neutron tracking
Do we need (CPU-intensive) description of thermal neutrons, neutron capture,
etc?
Different options for EM physics
Do you need (CPU-intensive) precise description at the low-energy scale (< 1
MeV)?
E.g. fluorescence, Doppler effects in the Compton scattering, Auger
emission, Rayleigh diffusion

[Link]@[Link]
Optional (G)UI
45

•In your main(), taking into account your computer environment, instantiate a
G4UISession provided by Geant4 and invoke its SessionStart() method:

- mysession -> SessionStart();

• Geant4 provides:

- G4UIterminal; Interfaces to various


graphics drivers
- csh or tcsh like shell Dawn
Wired
- G4UIBatch RayTracer
OpenGL
- Bach job with macro files OpenInventor
VRML

[Link]@[Link]
Summary: general
recipe for novice Users

[Link]@[Link] 46
A general recipe
47

• Design your application .... requires preliminary thinking (what is supposed to do?)

• Create your derived mandatory user classes


- MyDetectorConstruction

- MyPhysicsList

- MyPrimaryGeneratorAction

• Create optional derived user action classes

- MyUserRunAction, MyUserEventAction
• Create your main() file

- Instantiate G4RunManager
- Notify the RunManager of your mandatory and optional user classes
- Optionally initialise your favourite User Interface and Visualisation

[Link]@[Link]
Thank you
User Interface

[Link]@[Link] 49
Three ways of steering the simulation

hard-coded application
no user interaction
everything specified in the C++ source
re-compile needed to apply changes
batch session
commands in external macro file
interactive session
real-time command input by user
textual, graphical, (network-based)

[Link]@[Link]
Select the way of control
51

int main(int argc, char** argv) {


G4RunManager* runManager = new G4RunManager;
[Link]
runManager->SetUserInitialization(new MyDetectorConstruction());

// Physics list
G4VModularPhysicsList* physicsList = new MyPhysicsList;
physicsList->SetVerboseLevel(1);
runManager->SetUserInitialization(physicsList);

// User actions initialization


runManager->SetUserInitialization(new MyActionInitialization());

Insert the control code here!


delete runManager;
}

[Link]@[Link]
Hard-coded C++
52

// ...
// User actions initialization
runManager->SetUserInitialization(new MyActionInitialization());

runManager->Initialize();
runManager->BeamOn(!000);

// ...
delete runManager;
}

• You must initialize and start the run by issuing “beam


on”.

• Even the number of events has to be specified!


[Link]@[Link]
Batch session
53

// ...
// User actions initialization
runManager->SetUserInitialization(new MyActionInitialization());

G4UImanager* UImanager = G4UImanager::GetUIpointer();


G4String command = "/control/execute ";
G4String fileName = argv[1];
UImanager->ApplyCommand(command + fileName);

// ...
delete runManager;
}

• This example gets the file name of the macro from the
command-line argument:
./myApplication [Link]
[Link]@[Link]
Interactive sessions
Many different session types, inheriting from
G4UIsession class:
command-line based (dumb terminal)
graphical
special
your own? ☺
G4UIExecutive class enabling to select the
appropriate session at runtime, based on the environment
variables (recommended)

[Link]@[Link]
G4UIQt session

[Link]@[Link]
Universal batch/interactive approach
56

int main(int argc, char** argv) {


// ...
if (argc == 1) { No argument
// Interactive mode
G4UIExecutive* ui = new G4UIExecutive(argc, argv);
ui->SessionStart();
delete ui;
} else {
One argument (or more)
// Batch mode
G4UImanager* UImanager = G4UImanager::GetUIpointer();
G4String command = "/control/execute ";
G4String fileName = argv[1];
UImanager->ApplyCommand(command + fileName);
}
// ...

■ Mode selected based on application argument:


■ No argument = interactive mode
■ One argument = batch mode

[Link]@[Link]
Example UI commands
57

• /run/verbose 1 – sets how much output the run manager will


print (similar for other classes)

• /run/initialize – initializes the run (constructing the geometry,


physics and preparing the user actions)

• /run/beamOn 100 – starts a run with 100 events


• /control/execute
macro file
macroName – run the commands in a

• A complete list of built-in commands is available in the Geant4


Application Developers Guide, Chapter 7.1 ([Link]
G4UsersDocuments/UsersGuides/ForApplicationDeveloper/html/
Control/[Link])

[Link]@[Link]
Visualization
• To enable visualization, instantiate a G4VisExecutive and invoke its Initialize()
method

• Geant4 provides interfaces to various graphics (and “graphics”) drivers:


• OpenGL (+Qt)

• HepRApp #include <[Link]>


// ...
• Dawn
int main(int argc, char** argv) {
• Wired // ...
G4VisManager* visManager = new G4VisExecutive;
• RayTracer visManager->Initialize();
G4UIExecutive* ui = new G4UIExecutive(argc, argv);
• OpenInventor ui->SessionStart();
delete ui;
• VRML delete visManager;
delete runManager;

• .... }

[Link]@[Link]
Thank you

You might also like