79
Geant4 Tutorial European Medical Physics School, Archamps, France

Geant4 Tutorial European Medical Physics School, Archamps, France

Embed Size (px)

Citation preview

Page 1: Geant4 Tutorial European Medical Physics School, Archamps, France

Geant4 TutorialEuropean Medical Physics School,

Archamps, France

Page 2: Geant4 Tutorial European Medical Physics School, Archamps, France

Overview of the contents

Software process

Geant4 advanced example brachytherapy

Integration of the brachytherapy application

in a distributed computing environment

Run the brachytherapy example

Page 3: Geant4 Tutorial European Medical Physics School, Archamps, France

Software Process

How to develop a rigorous and reliable

software application

Documentation: http://www.ge.infn.it/geant4 link: training, software engineering documentation

Page 4: Geant4 Tutorial European Medical Physics School, Archamps, France

Software process

User Requirements Define the software functionality

Design Project of the software structure

Implementation

Test

For example, a process model is theUnified Software Development Process (USDP)

Iterative-incremental method

Concepts:

Page 5: Geant4 Tutorial European Medical Physics School, Archamps, France

Capture User RequirementsCapture User Requirements

Define the scope of the software system to be built (“what it should do”)

Page 6: Geant4 Tutorial European Medical Physics School, Archamps, France

How to collect User Requirements

•Study of the experimental set-up: involved particles, involved physics, detectors•What is the scope of the simulation

Example of User Requirement

UR1. The user shall be able to define electromagnetic processes for gammaNeed: EssentialPriority: HighSource: ESA

Page 7: Geant4 Tutorial European Medical Physics School, Archamps, France

User Requirements

1. General UR 1.1 Configure the Run UR 1.2 Configure the Event Loop

2. Description of the experimental set-up UR 2.1 Describe a geometrical set-up: a Si-W tracker, a

CsI calorimeter and an anti-coincidence system made out of plastic scintillators.

UR 2.2 Record the coordinates of impact of tracks in the layers of the tracker. Record the energy release in the strips of the tracker.

UR 2.3 Record the energy deposited in each element of the calorimeter at every event.

UR 2.4 Record the energy deposited in each element of the anticoincidence at every event.

UR 2.5 Digitise the hits, setting a threshold for the energy deposit in the tracker.

UR 2.6 Generate a trigger signal combining signals from different detectors.

3. Physics UR 3.1 Generate primary events according to various

distributions relevant to gamma astrophysics UR 3.2 Activate electromagnetic processes appropriate

to the energy range of the experiment. UR 3.3 Activate hadronic processes appropriate to the

energy range of the experiment.

4. Analysis UR 4.1 Plot the x-y distribution of impact of the track. UR 4.2 Plot histograms during the simulation execution. UR 4.3 Store significant quantities in a ntuple (energy

release in the strips, hit strips) for further analysis. UR 4.4 Plot the energy distribution in the calorimeter.

5. Visualisation UR 5.1 Visualise the experimental set-up. UR 5.2 Visualise tracks in the experimental set-up. UR 5.3 Visualise hits in the experimental set-up.

6. User Interface UR 6.1 Configure the tracker, by modifying the number

of active planes, the pitch of the strips, the area of silicon tiles, the material of the converter

UR 6.2 Configure the calorimeter, by modifying the number of active elements, the number of layers.

UR 6.3 Configure the source. UR 6.4 Configure digitisation by modifying threshold UR 6.5 Configure the histograms

7. Persistency UR 7.1 Produce an intermediate output of the simulation

at the level of hits in the tracker. UR 7.2 Store significant results in FITS format. UR 7.3 Read in an intermediate output for further

elaboration.

Collect User Requirements in proper domains

Page 8: Geant4 Tutorial European Medical Physics School, Archamps, France

DesignDesign

Define the structure of the software by a

software engineering point of view

Page 9: Geant4 Tutorial European Medical Physics School, Archamps, France

OOAD Primaryparticles

Analysis

Detector

Visualisation

Run

Physics

Event

Design

Page 10: Geant4 Tutorial European Medical Physics School, Archamps, France

Software development

UR1

design

implementation

test

Test phase is crucial and extremelyimportant

Page 11: Geant4 Tutorial European Medical Physics School, Archamps, France

Test

Important and crucial issue

Always in respect to experimental dataexperimental data

Comparisons in respect to other MC toolkit are just

curiosity

Levels of tests:Microscopic test

Test on components of the application (i.e. Physics models adopted)Macroscopic test Test on the experimental set-up (physics, geometry, etc. together)

Page 12: Geant4 Tutorial European Medical Physics School, Archamps, France

Iterative, incremental method

UR1

UR2

UR3

UR1 design implementation

test

UR2designimplementationtest

UR3 design implementation

test…..

Gain feedback on the developed software:Examples: - Is the UR satisfied? - Do we need new UR? - How can we improve the software ?

Page 13: Geant4 Tutorial European Medical Physics School, Archamps, France

Documentation

User Requirement document

Design

Traceability documents

How to use the software application

Comments in the code

Software process and documentation are important for:Develop a rigorous and reliable softwareDevelop clear and clean softwareLimit the possibility of introducing bugsHelp other people to understand the software application

Page 14: Geant4 Tutorial European Medical Physics School, Archamps, France

Geant4 brachytherapy advanced Geant4 brachytherapy advanced exampleexample

F. Foppiano3, S.Guatelli2,J.Moscicki1, M.G. Pia2

CERN1 ,INFN Genova2, National Institute for Cancer Research, IST

Genova3

www.ge.infn.it/geant4, advanced examples

Page 15: Geant4 Tutorial European Medical Physics School, Archamps, France

Brachytherapy is a medical therapy used for cancer treatment

Radioactive sources are used to deposit therapeutic doses near tumors, while preserving surrounding healthy tissues

BrachytherapyEndocavitarybrachytherapy(lungs, uterus)

Interstitial brachytherapy (prostate)

Superficial brachytherapy(skin) Software is used to define patient’s treatment planning

It calculates the dose in the patient

Treatment planning: how to set (where?, how long?)radioactive sources in treatment’s target area

Page 16: Geant4 Tutorial European Medical Physics School, Archamps, France

Commercial software for brachytherapy

Various commercial software products for treatment planning

No commercial software available for superficial brachytherapy with Leipzig applicators

PrecisionPrecision

CostCost

Based on approximated analytical methods,approximated analytical methods, because of speed constraints Uniform materialUniform material: water

Each software is specific to one techniquespecific to one technique Treatment planning software is expensiveexpensive (~ hundreds K $/euro)

Page 17: Geant4 Tutorial European Medical Physics School, Archamps, France

Develop a Develop a general purposegeneral purpose

precise precise dosimetric system

with the capability of

Patient’s anatomy Patient’s anatomy modelingmodeling

interface to CT imagesinterface to CT images

with a user-friendly interfaceuser-friendly interface

adequate adequate speedspeed for clinical usage for clinical usageperforming atperforming at

Page 18: Geant4 Tutorial European Medical Physics School, Archamps, France

PrecisionPrecision

Accurate model of the real experimental set-upAccurate model of the

real experimental set-up

Easy configuration for hospital usage

Easy configuration for hospital usage

SpeedSpeed

Calculation of 3-D dose distribution3-D dose distribution in the treatment area

Determination of isodose isodose curves

Based on Monte CarloMonte Carlo methodsAccurate description of physicsphysics interactions

Realistic description of geometrygeometry and tissuetissuePossibility to interface to CT images

Simple user interface + Graphic visualisation Elaboration of dose distributionsdose distributions and isodosesisodoses

ParallelisationParallelisationAccess to distributed computing resourcesdistributed computing resources

Other requirementsOther requirementsTransparentTransparentOpen to extension extension and new functionalityPublicly accessiblePublicly accessible

RequirementsRequirements

Page 19: Geant4 Tutorial European Medical Physics School, Archamps, France

User Requirements

1.The user shall be able to visualise the geometry involved and the trajectories of the particles

The application provides the simulation of energy deposit of brachytherapic sources in a phantom

Geometry

Physics

Analysis

Visualisation

1.The phantom is a box 2.The user shall be able to change the absorber material of the phantom 3.The user shall be able to model patient anatomy 4.The dose should be collected in 1. mm wide voxels

1. Particles: e+,e-, gamma 2. Low Energy electromagnetic processes

1. The user shall be able to calculate the total absorbed energy in the phantom:

3D distribution in the volume2D distribution in the plain containing the source

Page 20: Geant4 Tutorial European Medical Physics School, Archamps, France

PrecisionPrecisionPrecisionPrecision

Based on Monte Carlo methodsMonte Carlo methods

Microscopic validation of the physics modelsMicroscopic validation of the physics modelsComparison Comparison with experimental data experimental data

specific to the brachytherapic practice

Experimental validationvalidation of physics involved

Page 21: Geant4 Tutorial European Medical Physics School, Archamps, France

Low Energy Package

Validity range: 250 eV – 100 GeV250 eV – 100 GeV– 250 eV is a “suggested” lower limit – data libraries down to 10 eV– 1 < Z < 100

Exploit evaluated data librariesevaluated data libraries (from LLNL): EADL (Evaluated Atomic Data Library) EEDL (Evaluated Electron Data Library) EPDL97 (Evaluated Photon Data Library)

for the calculation of total cross section and generation of the final state

Photon transmission, 1m Pb

shell effects

Compton scattering Rayleigh scattering Photoelectric effect Pair production Bremsstrahlung Ionisation

+ atomic relaxationshell effects

Photon transmission, 1m Al

Page 22: Geant4 Tutorial European Medical Physics School, Archamps, France

Al

NISTGeant4-LowEGeant4-Standard

Stopping power

Photons and

electron physics

processes

2N-L=13.1 – =20 - p=0.87

NISTGeant4-LowEGeant4-Standard

Photon attenuation coefficient

Al

2N-S=23.2 – =15 - p=0.08

0 10 20 30 40 500,0

0,2

0,4

0,6

0,8

1,0

1,2 Simulazione Nucletron Misure

Dos

e %

Distanza lungo Z (mm)Distance along Z (mm)

SimulationNucletronDataF. Foppiano et al., IST

Genova

Comparison to protocol data,

original experimental

data

Dosimetric validation

Dosimetric validation

Microscopic validation

Microscopic validation

Page 23: Geant4 Tutorial European Medical Physics School, Archamps, France

General purpose systemGeneral purpose systemGeneral purpose systemGeneral purpose system

Object Oriented technologySoftware system designed in terms of Abstract Interfaces

Abstract Factory design patternSource spectrum and geometry transparently interchangeableSource spectrum and geometry transparently interchangeable

For any brachytherapy technique

For any source type

Page 24: Geant4 Tutorial European Medical Physics School, Archamps, France

Flexibility of modeling

CT DICOM interface

through Geant4 parameterised volumesGeant4 parameterised volumes parameterisation function: materialparameterisation function: material

Abstract Factory

Configuration of

any brachytherapy technique any brachytherapy technique

any source type any source type

through an Abstract FactoryAbstract Factory to define geometry, primary geometry, primary spectrumspectrum

Phantom

various materialsvarious materials water, soft tissue, bone, muscle etc.

General purpose software system for brachytherapy

No commercial general software exists!

Page 25: Geant4 Tutorial European Medical Physics School, Archamps, France

Realistic model Realistic model of the experimental set-upof the experimental set-up

Realistic model Realistic model of the experimental set-upof the experimental set-up

Spectrum (192IrIr, 125II)Geometry

Phantom with realistic material modelPhantom with realistic material modelPossibility to interface the system to CT imagesPossibility to interface the system to CT images

Radioactive source

Patient

Page 26: Geant4 Tutorial European Medical Physics School, Archamps, France

Titanium capsule tipsTitanium tube

Iodium core:Inner radius :0Outer radius: 0.30mmHalf length:1.75mm

Air:Outer radius:0.35mm half length:1.84mm

Titanium tube:Outer radius:0.40mmHalf length:1.84mm

Titanium capsule tip:Semisphereradius:0.40mm

Model of a I-125 brachytherapic sourcegeometry and materials

Model the source geometry

Air

Iodium core

Golden marker

Golden marker:Inner radius :0Outer radius: 0.085 mmHalf length:1.75mm

Precise geometry and material model of any type of source

Ir-192 source + applicator for superficial brachytherapy

3 m m ste e l c a b le

5.0 m m

0.6 m m

3.5 m m

1.1 m m

Ac tive Ir-192 C o re

Ir-192

Page 27: Geant4 Tutorial European Medical Physics School, Archamps, France

Effects of source anisotropyEffects of source anisotropy

LongitudinalLongitudinal axis of the source axis of the sourceDifficult to make direct measurements

TransverseTransverse axis of the source axis of the sourceComparison with experimental data

Plato-BPS treatment planning algorithm makes some crude

approximation ( dependence,

no radial dependence)

-40 -30 -20 -10 0 10 20 30 400,0

0,5

1,0

1,5

2,0

2,5

Simulazioni Plato Misure

Dose %

Distanza lungo X (mm)Distance along X (mm)

SimulationSimulationPlatoPlatoDataData

-40 -30 -20 -10 0 10 20 30 400,0

0,5

1,0

1,5

2,0

2,5 Simulazioni Plato

Dose %

Distanza lungo Z (mm)

Distance along Z (mm)

Effects of source

anisotropySimulationSimulation

PlatoPlato

Rely on simulation for better accuracy than

conventional treatment planning software

Page 28: Geant4 Tutorial European Medical Physics School, Archamps, France

Modeling the patient

source

Modeling a phantomModeling a phantom

of any material (water, tissue, bone, muscle etc.)

thanks to the flexibility of Geant4 materials package

Modeling geometry Modeling geometry and materials from and materials from

CT dataCT data

Page 29: Geant4 Tutorial European Medical Physics School, Archamps, France

DICOMDICOM

Acquisition of CT image 3D patient anatomy

Computerized Tomography allows to reproduce the real 3D geometry of the patient

file

Pixels

grey tone proportional to material density

Digital Imaging and COmunication in Medicine

DICOM is the universal standard for sharing resources between heterogeneous and

multi-vendor equipment

Page 30: Geant4 Tutorial European Medical Physics School, Archamps, France

Geant4-DICOM interface

Developed by L. Archambault, L. Beaulieu, V.-H. Tremblay (Univ. Laval and l'Hôtel-Dieu, Québec)

Donated to Geant4 for the common profit of the scientific community– under the condition that further improvements and developments are made

publicly available to the community

Released with Geant4 5.2, June 2003 in an extended example– with some software improvement by S. Guatelli and M.G. Pia

First implementation, further improvements foreseen

Page 31: Geant4 Tutorial European Medical Physics School, Archamps, France

User-friendly interfaceUser-friendly interfaceto facilitate the usage in hospitalsto facilitate the usage in hospitals

User-friendly interfaceUser-friendly interfaceto facilitate the usage in hospitalsto facilitate the usage in hospitals

Store simulation information in histograms and ntuples

Graphic visualisation of dose distributions

Application configurationApplication configurationJob submissionJob submission

Dosimetric analysis

Web interface

AIDA + Anaphe

Page 32: Geant4 Tutorial European Medical Physics School, Archamps, France

DosimetryDosimetry

AIDA + Anaphe

Analysis of the energy deposit in the phantom resulting from the simulation

Dose distribution

Isodose curves

for analysis

Simulation of energy deposit through Geant4 Low Energy Electromagnetic package

to obtain accurate dose distributionProduction threshold: 100 m

Page 33: Geant4 Tutorial European Medical Physics School, Archamps, France

AIDAHistograms

NtuplesData vectors

FitVisualisation of

results

Abstract Interfaces for Data Analysis

Data Analysis

Primary particlesEnergy Spectrum(1D histogram)

Energy deposit(2D histogram)

http://aida.freehep.org

source

Page 34: Geant4 Tutorial European Medical Physics School, Archamps, France

Bebig Isoseed I-125 source

0.16 mGy =100%

Isodose curvesIsodose curves

MicroSelectron-HDR source

Leipzig applicator

Interstitial brachytherapy

Superficialbrachytherapy

EndocavitaryBrachytherapy

DosimetryDosimetryDosimetryDosimetry

Page 35: Geant4 Tutorial European Medical Physics School, Archamps, France

Application configuration

Fully configurable from the web

Type of source

Phantom configuration

# events

Run modes:

demo

parallel on a cluster (under test)

on the GRID (under development)

Page 36: Geant4 Tutorial European Medical Physics School, Archamps, France

Speed adequate for clinic useSpeed adequate for clinic useSpeed adequate for clinic useSpeed adequate for clinic use

Transparent configuration in sequential or parallel mode

Transparent access to the GRID through an Transparent access to the GRID through an intermediate software layerintermediate software layer

Parallelisation

Access to distributed computing resources

Page 37: Geant4 Tutorial European Medical Physics School, Archamps, France

Performance

Endocavitary brachytherapy

1M events

61 minutes

Interstitial brachytherapy

1M events

67 minutes

Superficial brachytherapy

1M events

65 minutes

on an “average” PIII machine, as an “average” hospital may own

Monte Carlo simulation is not practically conceivable for clinical application, even if more precise

Page 38: Geant4 Tutorial European Medical Physics School, Archamps, France

Performance: parallel mode

1M events

4 minutes 34’’

1M events

4 minutes 36’’

1M events

4 minutes 25’’

on up to 50 workers, LSF at CERN, PIII machine, 500-1000 MHz

Performance adequate for clinical application, but…

it is not realistic to expect any hospital to own and maintain a PC farm

Endocavitary brachytherapy

Interstitial brachytherapy

Superficial brachytherapy

preliminary: further optimisation in progress

prototype for an intermediate layer between applications and

the GRID

Diane has been developed by J. MoscickiE-mail: [email protected] http://www.cern.ch/diane

Page 39: Geant4 Tutorial European Medical Physics School, Archamps, France

Running on the GRID

Via DIANE

Same application code as running on a sequential machine or on a dedicated cluster

– completely transparent to the user

A hospital is not required to own and maintain extensive computing resources to exploit the scientific advantages of Monte Carlo simulation for radiotherapy

Any hospital

– even small ones, or in less wealthy countries, that cannot even small ones, or in less wealthy countries, that cannot afford expensive commercial software systemsafford expensive commercial software systems –

may have access to advanced software technologies and tools for radiotherapy

Distributed Geant4 application

Page 40: Geant4 Tutorial European Medical Physics School, Archamps, France

Traceback from a run on CrossGrid testbed

Current #Grid setup (computing elements):5000 events, 2 workers, 10 tasks (500 events each)

- aocegrid.uab.es:2119/jobmanager-pbs-workq- bee001.ific.uv.es:2119/jobmanager-pbs-qgrid- cgnode00.di.uoa.gr:2119/jobmanager-pbs-workq- cms.fuw.edu.pl:2119/jobmanager-pbs-workq- grid01.physics.auth.gr:2119/jobmanager-pbs-workq- xg001.inp.demokritos.gr:2119/jobmanager-pbs-workq- xgrid.icm.edu.pl:2119/jobmanager-pbs-workq- zeus24.cyf-kr.edu.pl:2119/jobmanager-pbs-infinite- zeus24.cyf-kr.edu.pl:2119/jobmanager-pbs-long- zeus24.cyf-kr.edu.pl:2119/jobmanager-pbs-medium- zeus24.cyf-kr.edu.pl:2119/jobmanager-pbs-short- ce01.lip.pt:2119/jobmanager-pbs-qgrid

Spain

Poland

Greece

Portugal

Resource broker running in Portugal

matchmaking CrossGrid computing elements

Page 41: Geant4 Tutorial European Medical Physics School, Archamps, France

Summary

A precise dosimetric system, based on Geant4– Accurate physics, geometry and material modeling, CT interface

Full dosimetric analysis– AIDA + Anaphe

Simple interface– configuration from WWW

Fast performance– parallel processing

Access to distributed computing resources– GRID

Beware: R&D prototype!Beware: R&D prototype!

Page 42: Geant4 Tutorial European Medical Physics School, Archamps, France

General dosimetric system for radiotherapy

The system was developed for endocavitary brachytherapy

It has been extended to all the brachytherapic techniques

It is possible to generalise the system to other radiotherapic techniques

Plug-in system under development

Thanks to Object Orientedtechnique

Page 43: Geant4 Tutorial European Medical Physics School, Archamps, France

Run Geant4 brachytherapy Run Geant4 brachytherapy advanced exampleadvanced example

Page 44: Geant4 Tutorial European Medical Physics School, Archamps, France

Structure of the brachytherapy example

Brachytherapy exampleheader files in include/*.hh, source code in src/ *.ccmain in Brachy.ccmacro: VisualisationMacro.mac

ClassesBrachyAnalysisManagerBrachyDetectorConstructionBrachyDetectorMessengerBrachyEventActionBrachyMaterialBrachyPhantomHitBrachyPhantomROGeometry

BrachyPhantomSD BrachyPrimaryGeneratorAction BrachyPhysicsList BrachyRunAction BrachyEventAction BrachyVisManager

Page 45: Geant4 Tutorial European Medical Physics School, Archamps, France

How to run

Define necessary environment variablessource geant4/env.csh

How to compile and linkgmake

How to run$G4WORKDIR/bin/Linux-g++/Brachy

Page 46: Geant4 Tutorial European Medical Physics School, Archamps, France

Details on the brachytherapy Details on the brachytherapy

advanced example implementationadvanced example implementation

Page 47: Geant4 Tutorial European Medical Physics School, Archamps, France

Mandatory user classes

PhysicsPrimary events

Detector

Page 48: Geant4 Tutorial European Medical Physics School, Archamps, France

Abstract FactoriesConfiguration of

any brachytherapy technique any brachytherapy technique

any source type any source type

through an Abstract FactoryAbstract Factory to define geometry, primary geometry, primary spectrumspectrum

Page 49: Geant4 Tutorial European Medical Physics School, Archamps, France

Titanium capsule tipsTitanium tubeIodium core:

Inner radius :0Outer radius: 0.30mmHalf length:1.75mm

Air:Outer radius:0.35mm half length:1.84mm

Titanium tube:Outer radius:0.40mmHalf length:1.84mm

Titanium capsule tip:Semisphereradius:0.40mm

Model of a I-125 brachytherapic sourcegeometry and materials

BrachyDetectorConstruction

Air

Iodium core

Golden marker

Golden marker:Inner radius :0Outer radius: 0.085 mmHalf length:1.75mm

Page 50: Geant4 Tutorial European Medical Physics School, Archamps, France

BrachyDetectorConstruction::BrachyDetectorConstruction{}

BrachyDetectorConstruction::~BrachyDetectorConstruction{}

G4VPhysicalVolume* BrachyDetectorConstruction::Construct()

{

pMaterial-> DefineMaterials();

ConstructSource();

ConstructPhantom();

ConstructSensitiveDetector();

return WorldPhys;

}

BrachyDetectorConstruction

Page 51: Geant4 Tutorial European Medical Physics School, Archamps, France

ConstructSource()

// source Bebig Isoseed I-125 ...// source Bebig Isoseed I-125 ...

// Iodium core

iodiumCore = new new G4TubsG4Tubs("ICore",0.085*mm,0.35*mm,1.75*mm,0.*deg,360.*deg);

iodiumCoreLog = new G4LogicalVolumenew G4LogicalVolume(iodiumCore,iodium,"iodiumCoreLog");

iodiumCorePhys = new G4PVPlacementnew G4PVPlacement(0, G4ThreeVector(0.,0.,0.), "iodiumCorePhys",

iodiumCoreLog, defaultTubPhys, false, 0);

// Golden marker

marker = new new G4TubsG4Tubs("GoldenMarker",0.*mm,0.085*mm,1.75*mm,0.*deg,360.*deg);

markerLog = new G4LogicalVolumenew G4LogicalVolume(marker,gold,"MarkerLog");

markerPhys = new G4PVPlacementnew G4PVPlacement(0, G4ThreeVector(0.,0.,0.), "MarkerPhys", markerLog,

defaultTubPhys, false, 0);

…. construct iodium core and golden marker…Air the mother volume is an air tube

Page 52: Geant4 Tutorial European Medical Physics School, Archamps, France

BrachyPhysicsListBrachyPhysicsList::BrachyPhysicsList():

G4VUserPhysicsList()G4VUserPhysicsList()

{

defaultCutValue = 0.1*mm;

…..}

BrachyPhysicsList::~BrachyPhysicsList(){}void BrachyPhysicsList::ConstructParticle()ConstructParticle()

{

ConstructBosons();

ConstructLeptons();

}void BrachyPhysicsList::ConstructBosons(){ G4Gamma::GammaDefinition();}

void BrachyPhysicsList::ConstructLeptons(){ G4Electron::ElectronDefinition(); G4Positron::PositronDefinition();}

void BrachyPhysicsList::ConstructProceConstructProcess()ss()

{

AddTransportation();

ConstructEM();

}

Page 53: Geant4 Tutorial European Medical Physics School, Archamps, France

BrachyPhysicsList Set the EM processes

void BrachyPhysicsList::ConstructEM()

{ theParticleIterator->reset();

while( (*theParticleIterator)() ){

G4ParticleDefinition* particle = theParticleIterator->value();

G4ProcessManager* pmanager = particle->GetProcessManager();

G4String particleName = particle->GetParticleName();

if (particleName == "gamma") {

lowePhot = new G4LowEnergyPhotoElectric("LowEnPhotoElec");

pmanager->AddDiscreteProcess(new G4LowEnergyRayleigh);

pmanager->AddDiscreteProcess(lowePhot);

pmanager->AddDiscreteProcess(new G4LowEnergyCompton);

pmanager->AddDiscreteProcess(new G4LowEnergyGammaConversion);

} else if (particleName == "e-") {

loweIon = new G4LowEnergyIonisation("LowEnergyIoni");

loweBrem = new G4LowEnergyBremsstrahlung("LowEnBrem");

pmanager->AddProcess(new G4MultipleScattering, -1, 1,1);

pmanager->AddProcess(loweIon, -1, 2,2);

pmanager->AddProcess(loweBrem, -1,-1,3);

} else if (particleName == "e+"){…}

}

Set EM processesfor e-, e+, gamma

Page 54: Geant4 Tutorial European Medical Physics School, Archamps, France

BrachyPrimaryGeneratorAction

Energy(keV) Probability

27.4 0.783913

31.4 0.170416

35.5 0.045671

I-125 delivers gamma

•Gamma Energy Spectrum

•Random direction

•Random position inside the iodium core

void BrachyPrimaryGeneratorAction::GeneratePrimaries(G4Event* anEvent)GeneratePrimaries(G4Event* anEvent)

{…..particleGun->SetParticlePosition(position);particleGun -> SetParticleDirection(direction);particleGun -> SetParticleEnergy(energy);particleGun->GeneratePrimaryVertex(anEvent);}

Page 55: Geant4 Tutorial European Medical Physics School, Archamps, France

Energy deposit

How to retrieve the energy deposit in the phantom

Concepts:

–Sensitive Detector

–Readout Geometry

–Hits

Page 56: Geant4 Tutorial European Medical Physics School, Archamps, France

Set Sensitive Detector and RO Geometry

void BrachyDetectorConstruction::ConstructSensitiveDetector()

{

G4SDManager* pSDManager = G4SDManager::GetSDMpointer();G4SDManager* pSDManager = G4SDManager::GetSDMpointer();

if(!phantomSD){

phantomSD = new phantomSD = new BrachyPhantomSDBrachyPhantomSD(sensitiveDetectorName,numberOfVoxelsAlongX,

numberOfVoxelsAlongZ);

G4String ROGeometryName = "PhantomROGeometry";

phantomROGeometry = newBrachyPhantomROGeometryphantomROGeometry = newBrachyPhantomROGeometry(ROGeometryName,

phantomDimensionX,phantomDimensionZ,numberOfVoxelsAlongX,numberOfVoxelsAlongZ);

phantomROGeometry->BuildROGeometry();phantomROGeometry->BuildROGeometry();

phantomSD->SetROgeometry(phantomROGeometry);phantomSD->SetROgeometry(phantomROGeometry);

pSDManager->AddNewDetector(phantomSD);pSDManager->AddNewDetector(phantomSD);

PhantomLog->SetSensitiveDetector(phantomSD);PhantomLog->SetSensitiveDetector(phantomSD);

}

Page 57: Geant4 Tutorial European Medical Physics School, Archamps, France

BrachyPhantomROGeometry::BrachyPhantomROGeometry() {}

BrachyROGeometry::~BrachyROGeometry() {}

G4VPhysicalVolume* BrachyPhantomROGeometry :: Build()Build(){ // example : X division ROPhantomXDivision = new G4Box( ….);

ROPhantomXDivisionLog = newG4LogicalVolume(….);

ROPhantomXDivisionPhys = new G4PVReplica(….);……..}

x

Readout Geometry

Page 58: Geant4 Tutorial European Medical Physics School, Archamps, France

Store the energy deposit in one hit

Sensitive DetectorG4bool BrachyPhantomSD::ProcessHits

(G4Step* aStep, G4TouchableHistory* ROhist)

{….

G4double energyDeposit = aStep->GetTotalEnergyDeposit();

….

G4VPhysicalVolume* physVol = ROhist->GetVolume();

// Read Voxel indexes: i is the x index, k is the z index

G4int k = ROhist->GetReplicaNumber(1);

G4int i = ROhist->GetReplicaNumber(2);

G4int j= ROhist->GetReplicaNumber();

…..

BrachyPhantomHit* PhantomHit = new BrachyPhantomHit(

physVol ->GetLogicalVolume(), i,j,k)

PhantomHit->SetEdep(energyDeposit);

PhantomHit->SetPos(physVol->GetTranslation());

… }

Page 59: Geant4 Tutorial European Medical Physics School, Archamps, France

HitsHit is a user-defined class derived from G4VHit

You can store various types information by implementing your own concrete Hit class:

position and time of the step momentum and energy of the track energy deposit of the step geometrical information etc.

Hit objects of a concrete hit class must be stored in a dedicated collection, which is instantiated from G4THitsCollection template G4THitsCollection template classclass

Page 60: Geant4 Tutorial European Medical Physics School, Archamps, France

BrachyPhantomHit (header file)class BrachyPhantomHit : public G4VHitpublic G4VHit

{

public:

BrachyPhantomHit(G4LogicalVolume* ,G4int ,G4int ,G4int );

~BrachyPhantomHit();

…..

inline void SetCellID(G4int XID,G4int YID,G4int ZID) // Set Hit position

{xHitPosition = XID; zHitPosition = ZID; yHitPosition = YID; }

inline void SetEdep(G4double edep) {energyDeposit = edep;} //Set hit energy deposit

inline void SetPos(G4ThreeVector xyz) {hitPosition = xyz;} // Set hit position

inline G4int GetXID() {return xHitPosition;} //Get hit x coordinate

inline G4int GetZID() {return zHitPosition;} // Get hit z coordinate

inline G4int GetYID() {return yHitPosition;} // Get hit y coordinate

inline G4double GetEdep() {return energyDeposit;} // Get energy deposit

….}

Page 61: Geant4 Tutorial European Medical Physics School, Archamps, France

BrachyEventAction

Retrieve energy deposit in the phantom

void BrachyEventAction::EndOfEventAction(const G4Event* evt)

{….

G4HCofThisEvent* HCE = evt->GetHCofThisEvent();

BrachyPhantomHitsCollection* CHC = NULL;

if(HCE)

CHC = (BrachyPhantomHitsCollection*)(HCE->GetHC(hitsCollectionID));

if(CHC)

{

G4int hitCount = CHC->entries();

for (G4int h = 0; h < hitCount; h++)

{

G4int i=((*CHC)[h])->GetZID();

G4int k=((*CHC)[h])->GetXID();

G4int j=((*CHC)[h])->GetYID();

G4double EnergyDep=((*CHC)[h]->GetEdep());

…}

…}

…}

Page 62: Geant4 Tutorial European Medical Physics School, Archamps, France

Initialisationmain Run manager user detector

const ructionuser physics

list

1: initialize2 : const ruct

3: material const ruct ion

4: geometry construct ion5: world volume

6 : const ruct

7 : physics process const ruction

8: set cuts

Describe the geometrical set-up

Activate electromagnetic/hadronic

processes appropriate to the energy range of the experiment

Page 63: Geant4 Tutorial European Medical Physics School, Archamps, France

Beam On

main Run Manager Geometry manager

Event generator

EventManager

1: Beam On2: close

3: generate one event

4: process one event

5: open

Generate primary events

Page 64: Geant4 Tutorial European Medical Physics School, Archamps, France

Event processing

Event manager

Stacking manager

Tracking manager

Stepping manager

User sensitive detector

1: pop

2: process one track3: Stepping

4: generate hits

5: secondaries

6: push

Record the energy deposit and the position associated

Page 65: Geant4 Tutorial European Medical Physics School, Archamps, France

How to produce •1D histograms•2D histograms•Ntuple

Analysis Tool•AIDA 3.0•Anaphe 5.0.5

Page 66: Geant4 Tutorial European Medical Physics School, Archamps, France

BrachyAnalysisManagerBrachyAnalysisManager::BrachyAnalysisManager() :

….

{

//build up the factories

aFact = AIDA_createAnalysisFactory();

AIDA::ITreeFactory *treeFact = aFact->createTreeFactory();

theTree = treeFact->create(fileName,"hbook",false, true);

….

histFact = aFact->createHistogramFactory( *theTree );

tupFact = aFact->createTupleFactory ( *theTree );

}

void BrachyAnalysisManager::finish()

{

theTree->commit(); // write all histograms to file ...

theTree->close(); // close (will again commit) ...

}

Create the .hbk file…

Close the .hbk file

Page 67: Geant4 Tutorial European Medical Physics School, Archamps, France

BrachyAnalysisManager

void BrachyAnalysisManager::book()

{

//creating a 2D histogram ...

h1 = histFact->createHistogram2D("10","Energy, pos",

300 ,-150.,150., //bins'number,xmin,xmax

300,-150.,150. );//bins'number,ymin,ymax

//creating a 1D histogram ...

h2 = histFact->createHistogram1D("20","Initial Energy", 500,0.,50.);

//creating a ntuple ...

if (tupFact) ntuple = tupFact->create("1","1",columnNames, options);

….}

Page 68: Geant4 Tutorial European Medical Physics School, Archamps, France

BrachyAnalysisManager

void BrachyAnalysisManager::FillHistogramWithEnergyFillHistogramWithEnergy (G4double x, G4double z, G4float energyDeposit)

{

//2DHistogram: energy deposit in a voxel which center is fixed in position (x,z)

h1->fill(x,z,energyDeposit);

}

void BrachyAnalysisManager::PrimaryParticleEnergySpectrumPrimaryParticleEnergySpectrum

(G4double primaryParticleEnergy)

{

//1DHisotgram: energy spectrum of primary particles

h2->fill(primaryParticleEnergy);

}

How to fill histograms….

Page 69: Geant4 Tutorial European Medical Physics School, Archamps, France

BrachyAnalysisManager

void BrachyAnalysisManager::FillNtupleWithEnergyFillNtupleWithEnergy(G4double xx,G4double yy, G4double zz, G4float en)

{…..

G4int indexX = ntuple->findColumn( "x" );

G4int indexY = ntuple->findColumn( "y" );

G4int indexZ = ntuple->findColumn( "z" );

G4int indexEnergy = ntuple->findColumn( "energy" );

ntuple->fill(indexEnergy, en);

ntuple->fill(indexX, xx);

ntuple->fill(indexY, yy);

ntuple->fill(indexZ, zz);

ntuple ->addRow();

}

How to fill Ntuples….

Page 70: Geant4 Tutorial European Medical Physics School, Archamps, France

Analysis management

In the BrachyRunAction

void BrachyRunAction::BeginOfRunAction(const G4Run*)

{

….

BrachyAnalysisManager* analysis = BrachyAnalysisManager::getInstance();

analysis->book();

….

}

void BrachyRunAction::EndOfRunAction(const G4Run* aRun)

{

…..

BrachyAnalysisManager* analysis = BrachyAnalysisManager::getInstance()

…..

analysis->finish();

….

}

Booking histograms and ntuple …

…Closing the hbook file

Page 71: Geant4 Tutorial European Medical Physics School, Archamps, France

Energy deposit

In the BrachyEventAction

void BrachyEventAction::EndOfEventAction(const G4Event* evt)

{

…. // here the energy deposit information is retrieved

//Store information about energy deposit in a 2DHistogram and in a ntuple ...

BrachyAnalysisManager* analysis = BrachyAnalysisManager::getInstance

analysis->FillHistogramWithEnergy(x,z,EnergyDep/MeV);}}

analysis->FillNtupleWithEnergy(x,y,z,EnergyDep/MeV);

}

Page 72: Geant4 Tutorial European Medical Physics School, Archamps, France

Gamma energy spectrum

BrachyPrimaryGeneratorAction:: GeneratePrimaries(G4Event* anEvent)

{

//Store the initial energy in a 1D histogram

analysis-> PrimaryParticleEnergySpectrum(primaryParticleEnergy/keV);

// generate primary particle

}

In the BrachyPrimaryGeneratorAction

Page 73: Geant4 Tutorial European Medical Physics School, Archamps, France

Analysis dynamic flow

Page 74: Geant4 Tutorial European Medical Physics School, Archamps, France

Some Results

Primary particlesEnergy Spectrum(1D histogram)

Energy deposit(2D histogram)

Page 75: Geant4 Tutorial European Medical Physics School, Archamps, France

Control, monitor the simulation

Page 76: Geant4 Tutorial European Medical Physics School, Archamps, France

BrachyDetectorMessenger

BrachyDetectorMessenger::BrachyDetectorMessenger( BrachyDetectorConstruction* Det): detector(Det)

{ detectorDir = new G4UIdirectory("/phantom/");

detectorDir->SetGuidance(" phantom control.");

phantomMaterialCmd = new G4UIcmdWithAString("/phantom/selectMaterial",this);

phantomMaterialCmd->SetGuidance("Select Material of the detector.");

phantomMaterialCmd->SetParameterName("choice",false);

phantomMaterialCmd->AvailableForStates(G4State_Idle);

}

void BrachyDetectorMessenger::SetNewValue(G4UIcommand* command,G4String newValue)

{

if( command == phantomMaterialCmd )

{ detector->SetPhantomMaterial(newValue);}

}

Page 77: Geant4 Tutorial European Medical Physics School, Archamps, France

(G)UIHow to change the phantom absorber material

• Run $G4WORKDIR/bin/Linux-g++/Brachy

• (G)UI session : interactive session

• Type /phantom/selectMaterial Lead

The phantom absorber material now is lead

Page 78: Geant4 Tutorial European Medical Physics School, Archamps, France

Macro

A macro is an ASCII file containing UI commandsAll commands must be given with their full-path directories

A macro can be executed by /control/execute /control/loop /control/foreach

in UI session

/control/verbose 1/run/verbose 1/event /verbose 1/phantom/selectMaterial Lead

# run 10 events/run/beamOn 10

A macro can be executed also typing: $G4WORKDIR/bin/Linux-g++/Brachy macro.mac

Page 79: Geant4 Tutorial European Medical Physics School, Archamps, France

Visualisation

Control of several kinds of visualisation

detector geometry particle trajectories hits in the detectors

In the Brachytherapy Example OGLIX, DAWN

VisualisationMacro.mac

# Macro file for the visualisation

# create empty scene

#

/vis/scene/create

#/vis/open OGLIX

/vis/open DAWN

/vis/viewer/flush

# for drawing the tracks

/tracking/storeTrajectory 1

/vis/scene/endOfEventAction accumulate

/vis/viewer/update

/run/initialize

/run/beamOn 10