GAMOS an easy and flexible framework for GEANT4 simulations Pedro Arce (CIEMAT, Madrid) CIEMAT, 5th July 2012 CIEMAT, July 2012 GAMOS 1 Outline Introduction MC applications GAMOS objectives GAMOS plug-in’s Applications PET/SPECT Defining the input Geometry from text files Movements Primary generator Physics Radiotherapy Accelerator geometry Phase space files Phantom voxelised geometries Dose in phantom Extracting detailed data Optimisationn GAMOS data Filtering Classifying Scoring Sensitive detectors Installation Histogramming Parameter management Verbosity Release and user support Analysis and visualization Installation/Documentation/User support Documentation Summary Optimisation CIEMAT, July 2012 GAMOS 2 Introduction CIEMAT, July 2012 GAMOS 3 MC applications Often the use a MC simulation is a difficult task for a non-expert software user – In the case of Geant4 most of the application has to be written in C++ Several applications try to facilitate the use of MC in a specific field • Providing an scripting language tailored to the field CIEMAT, July 2012 GAMOS 4 MC applications But users find some problems with these applications 1. User wants to describe some input not included in the application A peculiar volume shape, a new primary generator position distribution, some option in the physics,… 2. User wants to have some kind of output or detailed information to debug or understand some part of the simulation, and the application only provides a limited amount of output possibilities Dose from the gammas that entered the phantom with small energy, energy lost by particle traversing a volume as a function of the initial energy, … 3. The available applications cover a limited amount of physics fields, and many users do not find an appropriate one for their needs CIEMAT, July 2012 GAMOS 5 GAMOS objectives After almost ten years providing different utilities to make easier the use of Geant4 we created GAMOS with the objectives: to provide a framework not only easy-to-use but also flexible, that may cover the needs of a wide range of Geant4 users (a framework should not become an obstacle for an advanced user who wants to exploit all the functionality that Geant4 offers) Comprehensive scripting language Very wide range of input possibilities Allow extraction of detailed information at any moment of the simulation Easily extendible with new user code Provide a mechanism so that users can easily extend the framework functionalities with their code - Without the need to understand how GAMOS works internally CIEMAT, July 2012 GAMOS 6 GAMOS history GAMOS became a framework during first months of 2007 to help in the simulation of CIEMAT PET detector projects it was soon extended for radiotherapy applications GAMOS is the fruit of +10 years experience developing Geant4-based frameworks Member of Geant4 since 1998 Coordination of the CMS Geant4 framework during its first years The first LHC Geant4 framework to be fully operative Coordination the HARP (PS) Geant4 framework (by nomination from S. Giani, first Geant4 spokesman) CIEMAT group had several years experience with PET detectors and radiotherapy CIEMAT, July 2012 GAMOS 7 Defining the input Geant4 simulation To do simulation with Geant4 a user has first to define the input: Geometry Optionally if a volume is a sensitive detector Primary generator (initial particles) Physics There is no predefined physics in Geant4, user has to choose the one more appropriate for her/his simulation And the output: Histograms Scores (counts) Files with data for later analysis The output is mainly obtained through: User actions Sensitive detectors / hits Scorers CIEMAT, July 2012 GAMOS 9 Geometry Three different ways to define it: C++ code: The usual GEANT4 way Add one line to transform your class in a plug-in DEFINE_GAMOS_GEOMETRY (MyGeometry); so that you can select it in your input macro /gamos/geometry MyGeometry Using one of the GAMOS examples for simple cases Simple PET can be defined through an 8-parameters file (n_crystals, crystal_x/y/z, radius, …) Simple phantoms with a few user commands Define it in ASCII (text) files The easiest way to define a geometry Based on simple tags Same order of parameters as corresponding GEANT4 classes CIEMAT, July 2012 GAMOS 10 Geometry from text files Based on simple tags, with same order of parameters as corresponding GEANT4 classes :MATE Cu 29 29 63.54 63.54 8.9333*g/cm3 8.9333*g/cm3 MATE Cu :VOLU :VOLUyoke yokeTUBE TUBE 62.*cm 62.*cm 820.*mm 820.*mm 1.27*m 1.27*m Cu Cu :ROTM :ROTM RM0 RM0 0.0. 0.0. 0.0. :PLACE :PLACE yoke yoke 11 expHall expHall RM0 RM0 0.0. 0.0. 370.*cm 370.*cm MATERIALS: Isotopes Elements Simple materials Material mixtures by weight, volume or number of atoms GEANT4 intrinsic materials + 300 predefined materials common in the medical field SOLIDS: All GEANT4 “CSG” and “specific” solids Twisted solids Tessellated solids Boolean solids CIEMAT, July 2012 GAMOS 11 Geometry from text files ROTATION MATRICES: 3 rotation angles around X,Y,Z 6 theta and phi angles of X,Y,Z axis 9 matrix values PLACEMENTS: Simple placements Divisions Replicas Assemblies Parameterisations Linear, circular, square or phantom-like For complicated parameterisations example of how to mix the C++ parameterisation with the ASCII geometry file COLOUR VISUALISATION ON/OFF CIEMAT, July 2012 GAMOS 12 Geometry from text files PARAMETERS: Can be defined to use them later :P :PInnerR InnerR12. 12. :VOLU :VOLUyoke yoke:TUBS :TUBS Iron Iron 33 $InnerR $InnerR 400. 400. 300. 300. :VOLUyoke2 yoke2:TUBS :TUBS Iron Iron 33 $InnerR $InnerR 200. 200. 200. 200. :VOLU ARITHMETIC EXPRESSIONS: Elaborated expressions can be used :SOLID yoke TUBE sin($ANGX)*2+4*exp(1.5)*cm 820. 1270.*mm UNITS: Default units for each parameter Each value can be overridden by user INCLUDE OTHER FILES (hierarchical approach): #include mygeom2.txt. CIEMAT, July 2012 GAMOS 13 Geometry from text files User can extend it: add new tags and process it without touching base code Can mix a C++ geometry with a text geometry GEANT4 in memory geometry text files Install and use it as another GEANT4 library G4VPhysicalVolume* MyDetectorConstruction::Construct(){ G4tgbVolumeMgr* volmgr = G4tgbVolumeMgr::GetInstance(); volmgr->AddTextFile(filename); // Several files can be added return = volmgr->ReadAndConstructDetector(); HISTORY: In use to build GEANT4 geometries since 10 years ago An evolving code… It is part of the GEANT4 release since December ‘08 CIEMAT, July 2012 GAMOS :ROTM R00 0. 0. 0. :VOLU world BOX 100. 100. 100. G4_AIR :VIS world OFF :VOLU "my tube" TUBE 0. 10. 20. G4_WATER :P POSZ 5 :PLACE "my tube" 1 world R00 0. 0. -$POSZ :VOLU sphere ORB 5. G4_Si :PLACE sphere 1 "my tube" R00 0. 1. $POSZ 14 Movements User can move any volume with user commands Several movements of the same volume or different ones can be set at the same time Displacements, rotations or text file that allows to define any movement Every N events or every interval of time N times or forever Offset can be defined Sinusoidal movement simulated with GAMOS CIEMAT, July 2012 GAMOS 15 Particle generator C++ code • The usual GEANT4 way • Add one line to transform your class in a plug-in DEFINE_GAMOS_GENERATOR(MyGenerator); so that you can select it in your input macro /gamos/generator MyGenerator GAMOS generator Wide range of particles: gamma, e-, e+, proton, neutron, ions, isotopes, … Combine any number of particles in one event (history) For each particle or isotope user may select by user commands any combination of time, energy, position and direction distributions Geant4 radioactive decay can be selected with user command Decay branching ratios and energy spectra of all isotopes /gamos/generator/timeDist source GmGenerTimeDecay CIEMAT, July 2012 /gamos/generator/directionDist source GmGenerPositionDiscGaussian 1.*mm GAMOS 16 Generator distributions Common medical physics distributions are available POSITION: Point Square Rectangle Disc DiscGaussian LineSteps InVolumes (sphere/box/tube_section/ellipsoid) InVolumeSurfaces (sphere/box/tube_section/ellipsoid) InVolumesGeneral (any solid) VoxelPhantomMaterials DIRECTION: Random Const Cone Gaussian RandomFlat ENERGY: Constant BetaDecay ConstantIsotopeDecay TIME: Constant Decay POSITION & DIRECTION: InVolumeSurfaceTowardsCentre F18 decay energy TowardsBox User can create its own distribution and select it with a user command (plug-in) CIEMAT, July 2012 GAMOS 17 Generator distributions EXAMPLE: Select as primary particle a gamma of 5.75 MeV: /gamos/generator/addSingleParticleSource MySource gamma 5.75*MeV Select as position uniformly distributed into the volume called ‘source’: /gamos/generator/positionDist MySource GmGenerDistPositionInG4Volumes source Select as direction a cone with axis along X and aperture 3 degrees: /gamos/generator/directionDist MySource GmGenerDistDirectionCone 1. 0. 0. 3*deg CIEMAT, July 2012 GAMOS 18 Physics GAMOS physics list Selection of all options of GEANT4 electromagnetic physics with user commands standard / low energy / Penelope different multiple scattering models gamma/electron – nuclear interactions atomic deexcitation X-ray reflection (new development by Zhentian Wang, Dept. of Physics Engineering, Tsinghua University, China) All physics lists in Geant4 code can be selected through a user command Production cuts: can be set different for each volume region /gamos/physics/setCuts collimator 1.*mm 1*mm /gamos/physics/setCuts MLCs 10.*mm 1*mm User limits: (min Ekin, min range, max track length, max step length, max time of flight) can be set different for each volume Utility to automatically optimize production cuts and user limits (see User’s Guide) CIEMAT, July 2012 GAMOS 19 Extracting detailed data CIEMAT, July 2012 GAMOS 20 Obtaining detailed data Most users are researchers, it is not enough to provide some final results, like dose distribution, or PET event classification table Want to have a deep understanding of what happens in the simulation Want to have the capability to evaluate the reliability of the results Want to choose the best physics configuration For example: Which is the dose contributed by the electrons that reach the phantom in a gamma accelerator treatment? How many gammas traverse completely the jaws? How much energy they lose? What is the length travelled by electrons produced by Compton interactions in a crystal? … Something we GAMOS developers have never imagined… CIEMAT, July 2012 GAMOS 21 GAMOS data Almost 200 types of data can be obtained at each step, track, event or run event ID, trackID, particle, process, kinetic energy, energy lost, energy deposited, step length, number of secondary's, position (X/Y/Z/R2/R3/phi/theta), direction, change in position, change in angle, energy secondary/energy primary, angle secondary – primary, etc. Also composed data, using arithmetic expressions sqrt(2.*FinalLocalPosX*FinalLocalPosY) With a few user commands data can be used to fill histograms (1D, 2D, profile), be dumped in text or binary files, or be printed on the screen EXAMPLE: Plot at each track step the logarithm of the initial kinetic energy and also the final X position vs final Y position /gamos/userAction GmStepDataHistosUA /gamos/setParam GmStepDataHistosUA:DataList log10(InitialKineticEnergy) FinalPosX.vs.FinalPosY CIEMAT, July 2012 GAMOS 22 Filtering A filter is an algorithm that accepts or reject a step or track ● > 100 filters in GAMOS Starts/Ends/Enters/Exits/Traverses/In LogicalVolume/PhysicalVolume/Touchable/Region, or any of their children, particle type, process type, primary or secondary, charged or neutral, etc. Composed filters: ● AND, OR, XOR, Inverse, OnSecondary (apply filter to secondary tracks created in a step), with history (pass filter in any previous track step or any ancestor previous track step), etc. Filter on numeric data: if the data is inside an interval /gamos/filter energyF GmNumericDataFilter InitialKineticEnergy 100.*keV 1.*MeV Filter on string data: if the data is included in a list /gamos/filter scatteringF GmStringDataFilter Process compt rayleigh CIEMAT, July 2012 GAMOS 23 Filtering example Dump in a text file the energy lost by the tracks in all kind of jaws # only when track steps happen in JAWS_X or JAWS_Y /gamos/filter jawsF GmInLogicalVolumeFilter MY_JAWS* # Select what to dump into text file /gamos/setParam GmTrackDataTextFileUA_jawsF:DataList EventID TrackID Particle AccumulatedEnergyLost # Include a header line in text file /gamos/setParam GmTrackDataTextFileUA_jawsF:WriteHeader 1 # Dump data in text file /gamos/userAction GmTrackDataTextFileUA jawsF HEADER: 4,"EventID","TrackID","Particle","AccumulatedEnergyLost" 2,2,"e-",0.0198374 40,2,"e-",0.151526 63,2,"e-",0.188402 119,52,"e-",0.494147 119,49,"gamma",0.514096 CIEMAT, July 2012 GAMOS 119,46,"gamma",4.02731 24 Classifying A classifier is an algorithm that classifies a step or track information, returning an index ● ByParticle, ByKineticEnergy, ByNAncestors, ByLogicalVolume, ByPhysicalVolume, ByTouchable, ByRegion, ByProcess, ByMaterial, etc. Compound classifiers: return an index combining two or more classifiers /gamos/classifier particleAndProcessC GmClassifierByParticle GmClassifierByProcess Classifier on numeric data: different index for each interval /gamos/classifier energyC GmClassifierByNumericData InitialKineticEnergy 0. 10.*MeV 1*MeV Classifier on string data: different index for each data value /gamos/classifier processC GmClassifierByStringData CreatorProcess CIEMAT, July 2012 GAMOS 25 Classifying example Plot for each Z layer the X vs Y position only when an interaction occurred in the “phantom” volume # only when track steps happen in phantom /gamos/filter InPhantomF GmInLogicalVolumeFilter phantom # classify by the Z position (a different histogram for each Z interval) /gamos/classifier ZposC GmClassifierByNumericData FinalPosZ -100. 100. 200./10 # select what to plot /gamos/setParam GmStepDataHistosUA_InPhantomF_ZposC:DataList FinalPosX.vs.FinalPosY # build histograms at each step using filter and classifier gamos/userAction GmStepDataHistosUA InPhantomF ZposC -100 < Z < -80 CIEMAT, July 2012 -80 < Z < -60 GAMOS -60 < Z < -40 26 Scoring Scoring may be an important part of a simulation powerful and flexible framework developed, fully based on user commands: Many possible quantities can be scored in one or several volumes (based on Geant4 scorers) ● Dose ● Current (in/out/passage) ● Number of particles ● Number of steps ● Deposited energy ● Charge ● Number of interactions ● Minimum kinetic energy ● Flux (in/out/passage) ● Step length ● Number of 2ary particles ● Kerma For each scored quantity one of several filters can be used only electrons, only particles with energy in a given interval, … Several ways to classify the different scores One different score for each volume copy, or volume name, or energy bin, … Results can be printed in one or several formats for each scored quantity Standard output, text/binary file, histograms Scoring can be made in real or in parallel worlds All scored quantities can be calculated with/without errors All scored quantities can be calculated per event or per run Taking into account correlations from particles from same event CIEMAT, July 2012 GAMOS 27 Scoring Everything managed with user commands For example: score the number of interactions (collisions) of gammas in each volume copy - Select all volumes for scoring /gamos/scoring/createMFDetector nInterDet * - Score number of interactions /gamos/scoring/addScorer2MFD nInterScorer GmG4PSNofCollision nInterDet - One score per each physical volume /gamos/scoring/assignClassifier2Scorer GmClassifierByPhysicalVolume nInterScorer - Only score for gammas /gamos/scoring/addFilter2Scorer GmGammaFilter nInterScorer OUTPUT: MultiFunctionalDet: nInterDet PrimitiveScorer: nInterScorer Number of entries= 6 index: target:1 = 2.111 +-(REL) 0.024593555 index: primary collimator:1 = 1.066 +-(REL) 0.049482843 index: flattening filter:1 = 0.028 +-(REL) 0.28856012 index: jaws_X:1 = 0.003 +-(REL) 1 index: jaws_X:2 = 0.006 +-(REL) 0.6231189 index: expHall:0 = 0.002 +-(REL) 0.70675279 CIEMAT, July 2012 GAMOS 28 Sensitive Detectors To produce hits in GEANT4 a user has to (with C++): Define a class inheriting from G4VSensitiveDetector Associate it to a G4LogicalVolume Create hits in the ProcessHits method Clean the hits at EndOfEvent In GAMOS you can do all this with a user command /gamos/assocSD2LogVol SD_CLASS SD_TYPE LOGVOL_NAME • SD_CLASS: the G4VSensitiveDetector class • SD_TYPE: an identifier string, so that different SD/hits can have different treatment Users can create her/his own SD class and make it a plug-in DEFINE_GAMOS_SENSDET(MySD); CIEMAT, July 2012 GAMOS 29 Hits A GAMOS hit has the following information: • ID of the sensitive volume copy • event ID Bi fluorescence peak • energy • time of the first E deposit 511 keV photoelectric (PE) peak backscattering peak • time of the last E deposit • position escape peak • list of all tracks that contributed • list of all ‘primary´tracks that contributed E > 511 keV photoelectric peaks • list of all deposited energies • SD type /gamos/userAction GmHitsHistosUA Users can create his/her own hit class Hits can be stored in a job and read in another job • Format compatible with STIR software (PET reconstruction) CIEMAT, July 2012 GAMOS 30 Detector effects Measuring time - A detector is not able to separate signals from different events if they come close in time Dead time - When a detector is triggered, this detector (or even the whole group it belongs to) is not able to take data during some time - Paralizable (if a new event happens while it is dead the dead time restarts) - Non-paralizable (dead time is fixed, a new event has no effect) • Both can be set by the user in the input macro • A different time for each SD_TYPE /gamos/setParam SD:MeasuringTime:MySD_1 1000.*ns /gamos/setParam SD:MeasuringTime:MySD_2 250.*ns CIEMAT, July 2012 GAMOS 31 Hits digitization and reconstruction • Framework to transform simulated hits digital signals reconstructed hits (energy/time/position) • Digitization and hits reconstruction are very detector specific : it is not possible to provide a general solution • GAMOS provides a few simple digitizers and hits reconstructor’s • 1 hit 1 digit • Merge hits close enough • Same set of sensitive volumes • Closer than a given distance -- hits -- clusters of hits • User may implement detector specific effects • Trigger • Pulse simulation • Sampling • Noise •… CIEMAT, July 2012 GAMOS /gamos/userAction GmHitsHistosUA /gamos/userAction GmRecHitsHistosUA 32 Histograms By default histograms are written in ROOT format But many medical users have never heard of ROOT, while they are experts on Matlab, Origin, … Own format: can write histograms in text files (CSV) without any external dependency Read them in Matlab, Origin, Octave, GNUplot,…, even MS Excel ++ 2500 2000 N entries 1500 /gamos/userAction GmGenerHistosUA /gamos/analysis/fileFormat CSV 1000 500 0 Energy MS Excel graphics of energy of e+ from F18 decay CIEMAT, July 2012 GAMOS 33 Parameter management Many classes change their behaviour depending on the value of some parameters, that the user can set with user commands GAMOS code use parameters extensively to maximise the flexibility Always a default value in case the user does not care Parameters can be numbers, strings, list of numbers or list of strings Units and mathematical expressions can be used 10*cos(30*deg) (3-0.5*0.6)*becquerel Wildcards can be used crystal_* *layer* GAMOS provides a unique command to manage all these parameters • A parameter is defined in the input macro /gamos/setParam SD:EnergyResol 0.1*mm • Any class can use this value in any part of the code float enerResol = GmParameterMgr::GetInstance() ->GetNumericValue(“SD:EnergyResol”,0.); Over 300 parameters (all clearly documented) CIEMAT, July 2012 GAMOS 34 Verbosity When a user finds a problem, or to better understand the simulation, she/he wants to get a lot of detailed output But only for a few events, not always! Framework should provide a simple mechanism to activate/deactivate verbosity Per event and/or track Per simulation component (geometry, physics, PET, radiotherapy, …) CIEMAT, July 2012 GAMOS 35 GAMOS verbosity Verbosity controlled through user commands Different verbosities for different simulation parts (geometry, physics, generator, PET, radiotherapy, …) 6 levels of verbosity (silent, error, warning, info, debug, test) Controlled per event Selectable by user commands /gamos/verbosity GenerVerbosity info /gamos/verbosity PETVerbosity debug Verbosity managers are plug-ins: user can easily create its own one GEANT4 tracking verbosity can be controlled by event and by track /gamos/setParam /gamos/setParam /gamos/setparam /gamos/setparam CIEMAT, July 2012 GmTrackingVerboseUA:EventMin GmTrackingVerboseUA:EventMin GmTrackingVerboseUA:TrackMin GmTrackingVerboseUA:TrackMax GAMOS 14632 14635 1 20 36 Optimisation CIEMAT, July 2012 GAMOS 37 Optimisation: time studies User commands to get CPU time study By particle, energy bins, volume, region (or combination of them) Just add user commands: /gamos/classifier ParticleAndEnergyClassifier GmCompoundClassifier GmClassifierByParticle GmClassifierByEnergy /gamos/userAction GmTimeStudyUA ParticleAndEnergyClassifier gamma/0.001-0.01: User=0.01 Real=0 gamma/0.01-0.1: User=2.01 Real=2.45 gamma/0.1-1: User=19.12 gamma/1-10: User=4.25 Real=5.4 Sys=0.3 e-/0.0001-0.001: User=0.07 Real=0.1 Sys=0 e-/0.001-0.01: User=0.54 Real=0.69 Sys=0.06 e-/0.01-0.1: User=4.71 Real=5.41 Sys=0.38 e-/0.1-1: User=15.59 Real=18.19 Sys=1.79 e-/1-10: User=82.83 Real=98.62 Sys=7.45 CIEMAT, July 2012 Sys=0 Sys=0.27 Real=22.05 GAMOS Sys=1.51 38 Optimisation: physics cuts Two kind of physics cuts in Geant4: Production thresholds Limit secondary production for ionisation and bremsstrahlung (and e+e-) User Limits: Limit step size: better done tuning EM physics parameters Limit track length Limit time of flight Kinetic energy/range minimum (stop particle if kinE/range below a limit): useful to kill particles when energy not enough to reach target Better use range because more uniform for different regions Better use kinetic energy because more efficient calculation GAMOS solution: use kinetic energy inside but user provides it as range through a command Different physics cuts per particle and region (group of volumes) can be defined through user commands CIEMAT, July 2012 GAMOS 39 Optimisation: setting best cuts Normally people want that optimising the cuts produces only few % (or less) difference in results need to run very big statistics Cuts can be very different for different particle/regions, and a cut in one particle/region may affect another need to run many sets of cut values RESULT: usually people think it is too complicated Do not optimise cuts Just copy the cuts from someone, which usually are not the best one for them In GAMOS we propose an Automatic determination of best production cuts or user limits in one job CIEMAT, July 2012 GAMOS 40 Extending the scripting language: plug-in’s CIEMAT, July 2012 GAMOS 41 GAMOS plug-in’s If I want some functionality that GAMOS does not have? Best solution for biggest flexibility: plug-in’s What’s is a plug-in? It is the same in software that USB in hardware: The easiest way to add a new device (class), without touching the operative system (framework): no need to install a driver (modify framework classes) How it works in GAMOS: If you want to use, for example, your own physics list instead of one of the GAMOS ones Add one line in user’s code DEFINE_GAMOS_PHYSICS(MyPhysicsList); Code is transformed into a plug-in Automatically it may be selected with a user command /gamos/physics MyPhysicsList CIEMAT, July 2012 GAMOS 42 GAMOS plug-in’s Advantages of plug-in’s: No need to understand how GAMOS works internally (how GAMOS would invoke my code?) or modify GAMOS code No need to recompile each time I want to alternate between the GAMOS component and my own one GAMOS has no predefined components: user has full freedom in choosing components - Any user written code (geometry, primary generator, physics list, sensitive detector, user actions, …) can substitute any GAMOS component while still using the rest of GAMOS utilities - If you have a working application, you may still use it, while you take profit of the part of GAMOS you like No restrictions on the way to do things: all Geant4 functionality is available to GAMOS users CIEMAT, July 2012 GAMOS 43 Applications CIEMAT, July 2012 GAMOS 44 PET/SPECT CIEMAT, July 2012 GAMOS 45 PET/SPECT Any PET/SPECT detector can be simulated with simple text format Utility to create simple PET geometries from a few parameters (number of crystals per block, number of block per ring, radius, ...) Several sensitive detectors types selectable by user commands User can create it own one and make it a plug-in Automatic creation of hits with detailed information /gamos/assocSD2LogVol GmSDSimple SD_TYPE VOLUME_NAME Writing hits into text or binary file Retrieving them in next job (for doing parametric studies) Format compatible with STIR software Hits energy LaBr3 Several algorithms for identifying first interaction for detectors with DOI info CIEMAT, July 2012 GAMOS 46 PET/SPECT Detector effects Energy resolution Time resolution Dead time (paralizable / non-paralizable) Measuring time Coincidence time Digitizer and reconstructed hits framework and examples ClearPET sensitivity profile optical photons in BrainPET CIEMAT, July 2012 GAMOS 47 PET/SPECT Table of PET/SPECT classification True / scattered / random coincidences / scattered&random PET/SPECT line far or close to vertex Optionally merge hits if there is more than one because of Compton interactions SPECT: gamma passed through collimator or not Histograms of hits or reconstructed hits with a user command Histograms of positron history Histograms of PET/SPECT information PixelPET sensitivity of different event types ClearPET derenzo reconstruction CIEMAT, July 2012 GAMOS 48 Radiotherapy CIEMAT, July 2012 GAMOS 49 Radiotherapy GAMOS framework covers the needs of an external beam radiotherapy simulation user: Easy way to build accelerator geometries Reading DICOM patient geometries Common primary generator distributions Writing/reading phase space files Dose deposition in phantoms Histograms and binary files CPU Optimisation Optimising cuts Variance reduction techniques Debugging tools CIEMAT, July 2012 GAMOS 50 Accelerator geometry Accelerator geometry can be written with simple text format But some accelerator parts are difficult VRML view of VARIAN 6000 accelerator we provide modules that allow to build them with a short list of parameters JAWS: Use radiotherapist point of view: provide field at a plane (10x10 cm, 40x40 cm, …) : Type (X / Y) Box dimensions Focus Z Box position Z Field Z Projections on field Material Mother volume to place it CIEMAT, July 2012 GAMOS 51 Accelerator geometry MULTILEAF COLLIMATOR: Use radiotherapist point of view: provide conformal beam Leave profile (list of points) End leaves type (Rounded or straight) VRML view of curved MLC Top MLC Z plane position Focus Z Isocentre Z Interleaves gap Materials … CIEMAT, July 2012 GAMOS 52 Phase space files Write phase space files IAEA format One or several Z planes in the same job Stop after last Z plane or not Save header after N events (not to lose everything if job is aborted) Save extra info: Regions particle traversed Regions particle created Regions particle interacted Particle origin Z Big flexibility More can be easily added (they are plug-in’s) User selects which information and how many bytes each one occupies CIEMAT, July 2012 GAMOS 53 Phase space files Use phase space files as generator Displace or rotate phase space particles Reuse phase space particles Optional automatic calculation of reuse number Optional mirroring in X, Y or XY Particles can be reused without writing phase space files Recycle phase space files Optional skipping of first N events Optional histograms of particles read Filter particles by extra info Also read EGSnrc phase space format CIEMAT, July 2012 GAMOS 54 Phantom voxelised geometries CT DICOM files provide image information CT is sensitive to electronic density (Hounsfield numbers) But simulation codes need information on material densities Geant4 provides an utility to convert DICOM images to material and density information (example advanced/medical/DICOM: DICOM ASCII) GAMOS reads Geant4 format And also EGSnrc format Split one material in several if voxel densities are different User defines an interval X and a material is created for the densities in each X interval Displace or rotate read-in phantom geometry Simple phantoms can be created with a few user commands CIEMAT, July 2012 GAMOS 55 Inserting objects in phantom voxelised geometries Geant4 allows to build parallel worlds But only geometry is seen, not materials (=no interactions) We have developed a tool that allows to insert objects in phantom geometries and produce the interactions in them Realistic simulation of brachytherapy sources or ionisation chambers! Brachytherapy seed inserted in phantom CIEMAT, July 2012 GAMOS 56 Dose in voxelised phantom Fast Geant4 regular navigation is default Dose from brachytherapy seeds New dose scorer, taking into account effect of energy loss and multiple scattering when distributing dose in voxels Dose with errors can be calculated Different printing formats in each run Text in standard output Dose histograms (X, Y, Z, XY, XZ, YZ, dose, dose-volume) File with dose and error at each voxel File with dose and dose2 at each voxel (to properly take into account correlations) Many different doses can be calculated in the same job, with different filters, for detailed studies Dose in total or by event Proper management of original number of events when reading phase space files CIEMAT, July 2012 GAMOS 57 Analysis of results A set of easy-to-use executables and scripts Sum phase space files Analyse phase space files Statistics Histograms by particle type at each Z plane Dose (normalized) Phase space files PDD of gamma accelerator P D D Datos exper. - GAMOS (= when writing PS) Compare two phase space files Dose files PDD of gamma accelerator Sum dose files Analyse dose files Statistics Dose histograms (X, Y, Z, XY, XZ, YZ, dose, dose-volume) (= when writing dose) Dose (normalized) Position (mm) a Datos exper. - GAMOS Compare two dose files GUI under development (MIRAS project) CIEMAT, July 2012 GAMOS Position (mm) 58 Radiotherapy visualisation IMRT dose visualisation with CIEMAT’s tool (MIRAS) CIEMAT, July 2012 GAMOS 59 Radiotherapy visualisation gMocren visualisation of DICOM geometry and tracks CIEMAT, July 2012 GAMOS 60 Radiotherapy optimisation CIEMAT, July 2012 GAMOS 61 Accelerator: Automatic optim. prod cuts Which is the highest cuts we can use without decreasing the number of particles reaching the phase space plane? In GAMOS we use an ‘inverse reasoning’: For each particle reaching the plane Get range of particle when it was created Get range of mother particle where it was created Do it consecutively for all ancestors Make statistics of all these ranges, per particle, region and process At EndOfRun print statistics of which is the minimum range per particle, region and process You know that if you use a bigger production cut at least one particle would be killed and this particle or one of its children would not reach the phase space CIEMAT, July 2012 GAMOS 62 Accelerator: Automatic optim. prod cuts Often you allow some small % loss of particles.. Make histograms of all ranges per particle, region and proces Provide an script so that for a given cut it gives you the proportion of particles killed log10(range) of gammas created at target Be aware of double counting (very low: < 1%) that reach the patient or produce a secondary that reaches the patient Make histogram of minimum range (one entry per particle + particle ancestors) and CUT use it for statistics of % particles killed Check distributions of killed particles How to use it in GAMOS: Add one user command in one job /gamos/userAction GmProdCutsStudy RTPhaseSpaceFilter Similar approach for user limits… CIEMAT, July 2012 GAMOS 63 Dose: Automatic optim. prod cuts In GAMOS we use an ‘inverse reasoning’: Compute dose due to particles that would be killed with a certain cut (and all their daughters) When a particle is killed dose is deposited locally only count dose in voxels different that where particle is killed by cut GAMOS can estimate in one job the dose with several different cut values Use GAMOS filters /gamos/filter ProdCutFilter GmProdCutOutsideVoxelFilter 10.*mm 1.*mm /gamos/scoring/addFilter2Scorer ProdCutFilter PDDscorerPC10.1. It may happen that dose is small but distributed in a different manner than total dose (produces bias) Percent Depth Dose curve for all particles Use GAMOS dose histograms and particles rejected by cut 1mm/e- 10 mm/gamma to check dose shape Similar approach for user limits… CIEMAT, July 2012 GAMOS 64 RESULTS: Optim. production cuts We have simulated a VARIAN accelerator – Plane at 100 cm from the source and of half-width 100 cm in X and Y. We have computed the dose in a water phantom of 104 voxel Select the maximum cut values that change the total dose << 1 % CPU gain Accelerator: 20% w.r..t cuts ‘standard’ in BEAMnrc/DOSXYZnrc (700 keV for e-/e+, 10 keV for gamma) Dose: 0-30% w.r..t cuts ‘standard’ in BEAMnrc/DOSXYZnrc A command serves to apply production cuts to other processes, not only ionisation & bremsstrahlung (not needed but useful) We gain an extra 3% in CPU time RANGE REJECTION: Automatic procedure gives you also information on number of particles that would be killed by range rejection Does not improve CPU significatively (few particles are killed by it) CIEMAT, July 2012 GAMOS 65 Select EM physics parameters In Geant4 there is a long list of parameters that a user can change... (detailed explanation at http://fismed.ciemat.es/GAMOS/RToptim/ParameterHelp.html#EMparam) Most are related to the fact that charged particle interactions are simulated in an approximative manner Simulating the interactions with each atom would be too long A ‘long’ step is simulated and the multiple scattering and energy loss is calculated with approxmate equations Several parameters serve to tune the approximations: longer steps would mean less CPU, but less precision We have used the following method to optimise EM physics parameters: Start with default values which have been found good for radiotherapy simulations They are quite conservative Except dE/dx and lambda tables bin size Change values to less precision and watch CPU time Only consider those for which CPU gain is not negligible Try also higher precision to check Watch for change in dose (look also at change in phase space) Detailed study can be found at http://fismed.ciemat.es/GAMOS/RToptim CIEMAT, July 2012 GAMOS 66 Increase N bins in tables /process/eLoss/binsDEDX 1200 /process/eLoss/binsLambda 1200 Effect in phase space: - About 1 % less particles, uniformly distributed in E and space PDD: new param/old param Effect in dose: - 0.6 – 0.8 % decrease in dose, increasing with energy CPU gain: -1 % default cuts 0% optimised cuts CONCLUSIONS: we recommend using new values CIEMAT, July 2012 GAMOS 67 Fewer e-/e+ steps: multiple scattering range factor = 0.05 /process/msc/RangeFactor 0.05 Effect in phase space: - About 1.5 % more particles, uniformly PDD: new param/old param distributed in E and space Effect in dose: - 1.3 – 1.4 % increase in dose, quite uniformly CPU gain: 29 % default cuts 12 % optimised cuts CONCLUSIONS: acceptable, with caution (if change in dose is fully uniform it does not matter) CIEMAT, July 2012 GAMOS 68 CPU time comparison with BEAMnrc VARIAN 2100 gamma accelerator, 6 MeV: 106 events on Pentium Dual-Core 3 GHz geant4.9.3.beta01 BEAMnrc 277 s GAMOS GAMOS (standard) (low energy)* 291 s 476 s * No latest log-log interpolation speed improvements CIEMAT, July 2012 GAMOS 69 CPU time comparison with DOSZXYnrc Dose in phantom, phase space file as generator 104 5x5x3 mm water phantom and 4.5 106 head & neck phantom 106 events on Pentium Dual-Core 3 GHz geant4.9.3.beta01 (regular navigation, skipping voxel boundaries) DOSXYZnrc GAMOS/GEANT4 GAMOS/GEANT4 (standard) (low energy) water 234 s 150 s 338 s patient 300 s 179 s 324 s Dependency with number of materials GEANT4: (1 density = 1 material) DOSXYZnrc: • 4 materials: 179 s • 23 materials: 316 s • 68 materials: 394 s • 196 materials: 516 s Need to implement density-changing materials in Geant4… • 4 densities: • All densities: CIEMAT, July 2012 297 s 300 s GAMOS 70 Particle splitting UNIFORM BREMSSTRAHLUNG SPLITTING All bremmstrahlung photons are replicated the same number of times Z-PLANE DIRECTION BREMSSTRAHLUNG SPLITTING User defines a Z plane with limits in X & Y (represents entrance of phantom) Same as uniform BS, but if gamma does not aim at Z plane, Russian roulette is played EQUAL-WEIGHT SPLITTING Similar as Z-plane direction BS, but splits every gamma produced, not only from bremsstrahlung Russian roulette is played with e-/e+, so that very few reach Z plane Aim is that all particles that reach phantom have the same weight Based on EGSnrc DBS technique CIEMAT, July 2012 GAMOS 71 Particle splitting: RESULTS EM physics “standard”: UNIFORM BREMSSTRAHLUNG SPLITTING Maximum efficiency gain: Efficiency = σ2 /T 2.2 times Z-PLANE DIRECTION BREMSSTRAHLUNG SPLITTING Maximum efficiency gain: 6.5 times EQUAL-WEIGHT SPLITTING Maximum efficiency gain: 45 times Algorithm in GAMOS is not fully implemented yet…, we hope to reach a factor 100 CIEMAT, July 2012 GAMOS 72 Installation Documentation User support CIEMAT, July 2012 GAMOS 73 Installation GAMOS is freely available from CIEMAT web • User registers and downloads installation scripts We provide a no-choice but very easy way: one-line installation sh installGamos.sh $HOME/gamos No need to manually download and install packages No need to define environmental variables Checks that your system has the needed components Downloads, installs and compiles CLHEP, Geant4, (optionally) ROOT and GAMOS in the selected directory GAMOS compiles = Geant4 Optionally an expert user can make several choices, Geant4-like Installation tested on Scientific Linux, Fedora Core, Debian and Ubuntu, and on MacOS CIEMAT, July 2012 GAMOS 74 Documentation User’s Guide: Installation All available functionality How to provide new functionality by creating a plug-in Software reference manual (doxygen): Documentation of the classes and their dependencies Examples: A simple one and a few more complicated ones test.in: /gamos/setParam GmGeometryFromText:FileName mygeom.txt /gamos/geometry GmGeometryFromText /gamos/physics GmEMPhysics /gamos/generator GmGenerator /run/initialize /gamos/generator/addSingleParticleSource my_source gamma 6.*MeV /run/beamOn 1000 and type: CIEMAT, July 2012 gamos test.in GAMOS 75 Tutorials Five tutorials Radiotherapy tutorial PET tutorial Histograms and scorers tutorial Shielding tutorial Plug-in tutorial Propose about 15 exercises each Increasing in difficulty Reference output provided Solutions provided User can do them by her/himself 12 GAMOS tutorial courses have been given in Europe and America CIEMAT, July 2012 GAMOS 76 Release and user support Releases are checked in three different platforms > 50 different tests are run Geographical distribution of GAMOS users More than 700 registered users since August ’09 (plus 100-150 more before) Not only in medical physics GAMOS Discussion Forum Users ask questions, new requirements GAMOS Bug Report System (based on Bugzilla) Users report bugs Automatically assigned to a GAMOS developer Physics fields of interest of GAMOS users Users mailing list Only announcements (new releases, new courses) Developers mailing list Interchange of info between GAMOS developers in different institutes CIEMAT, July 2012 GAMOS 77 Summary GAMOS is a user-friendly and flexible framework many utilities allow to do full GEANT4 simulation through user commands plug-in’s allow to extend functionality by converting C++ classes into user commands, by adding one or a few lines You can do many things with GAMOS utilities, but you may easily replace any GAMOS component with a Geant4 or own one Special effort to provide debugging and optimisation tools flexible and powerful framework to extract detailed information several tools to optimise CPU performance GAMOS core is application independent PET, SPECT and radiotherapy fully functional Other applications being built: Neutron shielding, Compton camera (Laura Harkness, Univ. Liverpool) CIEMAT, July 2012 GAMOS 78 http://fismed.ciemat.es/GAMOS or Geant4 web (http://geant4.cern.ch) Applications Medical CIEMAT, July 2012 GAMOS 79