A Hands-on introduction to Geant4 Andrea Dell’Acqua CERN-EP/ATC

Slides:



Advertisements
Similar presentations
Use of G EANT 4 in CMS AIHENP’99 Crete, April 1999 Véronique Lefébure CERN EP/CMC.
Advertisements

Geant4 v9.2p02 Primary Particle Makoto Asai (SLAC) Geant4 Tutorial Course.
Road Map Introduction to object oriented programming. Classes
Makoto Asai (SLAC) Geant4 Users SLAC Feb. 18 th, 2002 Getting Started.
Geometry I Makoto Asai (SLAC) Geant4 Tutorial Course Geant4 v8.2p01.
Makoto Asai (SLAC) Geant4 Users CERN Nov. 15 th, 2002 Customizing Run Management.
Geant4 v9.4 Primary Particle Makoto Asai (SLAC) Geant4 Tutorial Course.
Makoto Asai (SLAC) Geant4 Users SLAC Feb. 18 th, 2002 Getting Started.
Geant4 v9.3p01 Primary Particle Makoto Asai (SLAC) Geant4 Tutorial Course.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
Software Installation The full set of lecture notes of this Geant4 Course is available at
A Hands-on introduction to Geant4 Andrea Dell’Acqua CERN-EP/ATC
Tabular Editors for Geant4 Geant4 Geometry Editor and Geant4 Physics Editor CHEP 2000 at Padova Hajime Yoshida Naruto University of Education.
Materials 1 Images: Isotopic composition Molecular composition Density Pressure State Temperature.
Tuesday, Nov 9th 9:30-12:30 –Visualization attributes –Physics processes 14:00-17:00 –Kinematics and event generation (from yesterday) Particle gun –Boolean.
Geometry Detector geometry A detector geometry in Geant4 is made of a number of volumes. The largest volume is called the World volume. It must contain.
Materials In nature, general materials (compounds, mixtures) are made by elements and elements are made by isotopes. These are the three main classes.
Geant4 Electromagnetic Physics Introduction V.Ivanchenko, M.Maire, M.Verderi  Process interface  Physics categories  Electromagnetic physics  PhysicsList.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
17-19 Oct, 2007Geant4 Japan Oct, 2007Geant4 Japan Oct, 2007Geant4 Japan 2007 Geant4 Collaboration.
Physics I: Physics Lists Geant4 Tutorial at Jefferson Lab 10 July 2012 Dennis Wright (SLAC) Geant4 9.6 beta.
1 Primary particles Geant4 User's Tutorial CERN, February 2010 Talk from previous tutorial by Giovanni Santin Ecole Geant4, Annecy 2008.
Work_Geant4 Bo-Wen Shiou. #include "G4RunManager.hh“ #include "G4RunManager.hh“ #include "G4UImanager.hh" #include "G4UImanager.hh" #include "ExN01DetectorConstruction.hh“
Special Topics in Nuclear Physics, JU, Second Semester, (Saed Dababneh). 1 Course web or
Maria Grazia Pia Detector Response Acknowledgements: A. Lechner, J. Apostolakis, M. Asai, G. Cosmo, A. Howard.
Primary particle Giovanni Santin ESA / ESTEC and RheaTech Ltd On behalf of the Geant4 collaboration Ecole Geant4 Annecy, and Nov 2008 With.
W. Pokorski - CERN Simulation Project1 Python binding for Geant4 toolkit using Reflex/PyROOT tool Witek Pokorski EuroPython 2006, CERN, Geneva
1 Physics I: Physics Lists Paris Geant4 Tutorial 4 June 2007 Marc Verderi Laboratoire Leprince-Ringuet (Heavily copied from D. Wright) Geant4 V8.3.
Monte Carlo /12/07. What is Geant ? Monte Carlo simulation tool for nuclear and particle physics Set up detectors –Sensitive detector which returns.
User Application Toolkit + User application toolkit Geant4 is a toolkit –i.e. you cannot “run” it out of the box –You must write.
User Application Luciano Pandola INFN-LNGS Partially based on a presentation by Maria Grazia Pia (INFN-Ge)
17-19 Oct, 2007Geant4 Japan Oct, 2007Geant4 Japan Oct, 2007Geant4 Japan 2007 Geant4 Collaboration.
Generating Primary Particles Each Geant4 Event starts with generation of one or multiple primary particles It is up to the user to define primary particle.
Maria Grazia Pia INFN Genova Salamanca, July 2002
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Introduction What is detector simulation? A detector simulation program must provide the possibility of describing accurately an experimental setup (both.
Run and Event G4Run and G4RunManager In Geant4, the Run is the largest unit of simulation and it consist of a series of events Within a Run, the detector.
May 20, 2005Wah-kai Ngai1 Basic Visualization Tutorial Using Geant4.
CLHEP Components Geant4 and CLHEP Geant4 makes a rather substantial use of CLHEP components –System of units –Vector classes and matrices G4ThreeVector(typedef.
Introduction to OOP CPS235: Introduction.
Geant4 examples Sébastien Incerti On behalf of the Geant4 collaboration with special thanks to Luciano Pandola, INFN.
WORK Bo-Wen Shiou. GNUmakefile GNUmakefile XXX.cc (ex:try03.cc) XXX.cc (ex:try03.cc) include folder (xxx.hh) include folder (xxx.hh) src folder (xxx.cc)
Detector Description: Basics
V.Ivanchenko Salamanca1 Geant4: Electromagnetic Processes 1  Introduction  Interfaces  PhysicsList  Optical process.
Makoto Asai (SLAC) Getting Started MGP: added class diagram of basic user application.
Physics I: Physics Lists Puebla Geant4 Tutorial 15 June 2010 Dennis Wright Geant4 V9.3.p01.
Geant4 release 5.1 summary Gabriele Cosmo EP/SFT.
Detector Description - Materials
Physics II : processes Paris Geant4 Tutorial 5 June 2007 Marc Verderi Ecole Polytechnique - LLR.
1 Exercises 0 Go inside the “hadrontherapy” directory: cd hadrontherapy Copy the Hadrontherapy example to your home folder: cp –r $G4INSTALL/examples/advanced/hadrontherapy.
A Short Course on Geant4 Simulation Toolkit Introduction
Starting with an example PART I Set your environment up and get a Geant4 example.
A Hands-on introduction to Geant4
C++ for Geant4 users A collection of most useful and/or common features used in and to use Geant4 Marc Verderi LLR – Ecole polytechnique 14/11/2018 Marc.
Primary Particle Generation
Physics I: Physics Lists
Primary Particle Generation
Software Installation
Classes and Objects.
A Short Course on Geant4 Simulation Toolkit Introduction
User Application
User Application
User Application
The full set of lecture notes of this Geant4 Course is available at
Software Installation, release 4.0
Customizing Run Management
The full set of lecture notes of this Geant4 Course is available at
The full set of lecture notes of this Geant4 Course is available at
Monte Carlo /12/25.
SPL – PS1 Introduction to C++.
Presentation transcript:

A Hands-on introduction to Geant4 Andrea Dell’Acqua CERN-EP/ATC

Monday, Oct. 8th 9:00-12:30 –Introduction –Installation –DAWN + display features –Rotation Matrixes –3-vectors 14:00-17:00 –Geometry (part I) Simple solids Logical Volumes Positioning

Introduction

Geant4 - Why? Geant3 was a detector simulation program developed for the LEP era –Fortran, ZEBRA –Electromagnetic physics directly from EGS –Hadronic physics added as an afterthought (and always by interfacing with external packages) –Powerful but simplistic geometry model –Physics processes very often limited to LEP energy range (100 Gev) –(Painfully) debugged with the help and the collaboration of 100s of physicist from all over the world LHC detectors need powerful simulation tools for the next 20 years –reliability, extensibility, maintainability, openness –good physics, with the possibility of extending

Geant4 - Why? Geant3 –The geometry model is limited to a pre-defined set of basic shapes. Adding a new shape requires changing the code of several (~20) routines. Interface to CAD systems in not possible –Tracking is the result of several iterations (by different people) and as such it has become a garbled mess. Not for the fainthearted –EM physics is built in, but several processes are missing and their implementation would be very hard –Hadronic physics is implemented via external (and obsolete) packages. Modifications require the author’s intervention Geant4 –The geometry has been based since the beginning on a CAD-oriented model. The introduction of a new shape does not influence tracking –Tracking has been made independent from geometrical navigation, tracking in electromagnetic fields (or any field) has been improved –EM and hadronic physics implemented in terms of processes. A process can be easily added or modified by the user and assigned to the relevant particles with no change in the tracking. The cut philosophy has been changed so as to make result less dependent on the cuts used for the simulation. Framework for physics parameterisation in place

Geant4 - How? The principle points behind the Geant4 development have been: –Ease on maintainability –openness of the design –performance –development by a rather substantial group of physicists An Object Oriented approach facilitates the achievement of these goals –the problem domain is naturally split into categories which can be tackled by different groups (with different expertise) –the process (if done properly) is self-documenting. The components are relatively independent from each other and can easily be replaced without affecting the whole program too much

Geant4 - How? (2) Geant4 is a toolkit –the framework part in Geant4 has been reduced to a minimum, so as to allow the user to implement his/her own program structure –bits and pieces of Geant4 can be used independently from the rest –no main program is provided –libraries have been made as granular as possible, in order to reduce (re-) compilation time and to allow the user to only link against those parts of G4 which are needed C++ as implementation language –de-facto standard for what concerns OO programming these days –high performance –big commercial support, well known in the scientific world –there is practically no Fortran in Geant4 anymore, hence the user must know some elements of C++ in order to get the best from G4

Geant4 - How? (3) Make Geant4 as independent as possible from commercial packages –You don’t need an Objectivity license to run Geant4! –Interfaces to commercial products have been provided whenever it was felt appropriate (so you can use Objectivity to store your data) –The only commercial package which was needed to run Geant4 was Rogue Wave’s Tools.h++ which did provide utility classes (as vectors, strings, containers and iterators), waiting for the Standard Template Library to become available. An interface to STL has been made available with the release, hence Tools.h++ in not needed anymore (in principle…) The Geant4 code is written in reasonable C++ –migration to ISO/ANSI C++ to follow when most of the compilers will deal with it… –for the moment use Stroustrup’s 2nd edition...

Geant4 documentation For a complete documentation set go to: – There you’ll find –Information on how to install a Geant4 application –Documentation on how to get started with Geant4 and how to build your detector simulation program –Class diagrams which document the G4 design –A complete Class Documentation set –Useful links

Geant4 status In terms of performance and potentiality, Geant4 should be at least at the same level of Geant3 First “production” version (geant4.0.0) released at the end of 1998 –Full of bugs –Several part still under heavy development –Many improvements proposed, A&D cycles still undergoing –Physics part still being improved new version (geant4.0.1) available since the end of July –bug fixes –Interface to STL –Breaks user’s code :( geant4.1.0 foreseen by the end of 1999 –new hadronic physics, bug fixes –move to ISO/ANSI C++, based on STL, drop Tools.h++

A word on STL STL provides a set of utility classes (vectors, lists, maps) to be used as tools No compiler (as of today) provides a consistent set Tools.h++ was chosen (when the G4 project was started) as an interim replacement for STL, with the idea of migrating to STL as soon as a standard implementation would become available provides an interface to STL (prototype) but –using the ObjectSpace STL on HP and SUN –using the native STL on Linux (but needs modifying a system include to get it running on RedHat 5.2!) We are going to use Tools.h++ for the moment, waiting for better days...

Installation

How to install Geant4 To run a Geant4 application you must: –Install the Geant4 libraries on your system The source code is available from the web –Install the CLHEP library and code These can be taken from or from and then click on source /afs/cern.ch/sw/lhcxx /afs/cern.ch/atlas/project/geant4/CLHEP

How to install Geant4 (2) In case you want to use Tools.h++, install the Rogue Wave Tools.h++ libraries and code –This is the only commercial component need by Geant4 as of today –Used for container classes (like vectors, maps, lists) but soon to be replaced by an interface built on top of the Standard Template Library (STL) –The RW stuff is commercial, but waiting for the STL interface, you can “steal” it from: –or from /afs/cern.ch/atlas/project/geant4/rogue

How to install Geant4 (3) Once you got all this code on your machine, you simply follow a straightforward procedure –Set the G4SYSTEM variable –Set the CLHEP_BASE_DIR variable to point to where you put the CLHEP stuff –Set the RWBASE variable to point to where you installed RW Tools.h++ –cd to the source directory of your geant4 installation and make all libraries setenv CLHEP_BASE_DIR /afs/cern.ch/atlas/project/geant4/CLHEP/$G4SYSTEM/pro setenv G4SYSTEM SUN-CC setenv RWBASE /afs/cern.ch/atlas/project/geant4/rogue/$G4SYSTEM cd /afs/cern.ch/atlas/project/geant4/4.0.1/geant4.0.1/source gmake

How to install Geant4 (4) In case you want to use the STL interface, set the G4USE_STL variable setenv G4USE_STL 1 if you are using a system where the ObjectSpace implementation of STL is required, set the G4USE_OSPACE variable and tell the system where the ObjectSpace stuff was installed setenv G4USE_OSPACE 1 setenv OSPACE_BASE_DIR /afs/cern.ch/sw/lhcxx/specific/sun/ObjectSpace/2.1/ToolKit

How to install Geant4 (5) G4SYSTEM is the variable one must set to tell gmake which system and compiler are you running on G4SYSTEM can be: AIX-xlCAIX 4.3, xlC set for AIX (default) SUN-CCSunOS 5.6, CC 4.2 HP-aCCHP/UX 10.20, aCC A SGI-CCSGI-IRIX 6.2, C DEC-cxxDEC-OSF/1 4.0, DEC C++ Linux-g++Linux (RH 5.1), egcs 1.1 WIN32-VC-NICENiceNT and MSVC++ 5.0, installed locally together with CYGWIN32 WIN32-G++-NICENiceNT and CYGWIN32 with g++ as base compiler

How to install Geant4 (6) The visualization libraries will need some special treatment –Go to the source/visualization directory of your Geant4 installation –Read the README file over there and choose the graphics drivers you want to get installed –make the visualization libraries cd /afs/cern.ch/atlas/project/geant4/4.0.1/geant4.0.1/source/visualization setenv G4VIS_BUILD_DAWN_DRIVER 1 setenv G4VIS_BUILD_DAWNFILE_DRIVER 1 gmake

How to build an example Set the G4INSTALL variable to point where Geant4 was installed Set the CLHEP_BASE_DIR and RWBASE variable as in the case of the Geant4 installation Set the G4SYSTEM variable Set the G4WORKDIR variable to point to your working directory go into the example directory (e.g $G4WORKDIR/N02), run gmake and pray… The executable will be put in $G4WORKDIR/bin/$G4SYSTEM setenv G4INSTALL /afs/cern.ch/atlas/project/geant4/4.0.1/geant4.0.0 setenv G4WORKDIR /export/home/userN/geant4

How to build an example (2) For examples using graphics you have to set a few more variables. We are going to use the simplest among the graphics systems implemented with Geant4, DAWN Tell the visualisation that we are going to use DAWN Tell the visualisation where to find the DAWN executable Reset your PATH to include G4DAWN_HOME setenv G4VIS_USE_DAWN 1 setenv G4DAWN_MULTI_WINDOW 1 setenv G4DAWN_HOME /afs/cern.ch/atlas/project/geant4/DAWN/SUN-CC set path= ( $path $G4DAWN_HOME )

To sum up... The variables to set for this course (every time you log in) are These definitions (bar G4WORKDIR) should be grouped into a file to be “sourced” at the beginning of a session setenv G4INSTALL /afs/.fnal.gov/ups/geant/v4.0.1/geant4 setenv CLHEP_BASE_DIR /afs/.fnal.gov/ups/geant/v4.0.1/CLHEP/$G4SYSTEM/1.4 setenv RWBASE /afs/.fnal.gov/ups/geant/v4.0.1/rogue/$G4SYSTEM setenv G4SYSTEM SUN-CC setenv G4WORKDIR /afs/fnal.gov/files/home/room1/classN/geant4 setenv G4VIS_USE_DAWN 1 setenv G4DAWN_MULTI_WINDOW 1 setenv G4DAWN_HOME /afs/.fnal.gov/ups/geant/v4.0.1/DAWN/SUN-CC set path = ( $path $G4DAWN_HOME ) source G4Setup_Sun.sh(find one under /afs/.fnal.gov/ups/geant/v4.0.1)

How GNUmake works in Geant4 The GNUmake process in Geant4 is mainly controlled by the following scripts (placed into $G4INSTALL/config) –architecture.gmk defines the architecture specific settings and paths –common.gmk defines all general GNUmake rules for building objects and libraries –globlib.gmk defines all general GNUmake rules for building compound libraries –binmake.gmk defines all general GNUmake rules for building executables –GNUmakefiles placed inside each directory in the Geant4 distribution and defining specific directives to build a library (or a set of libraries) or an executable

How GNUmake works in Geant4 (2) The kernel libraries are placed by default in $G4INSTALL/lib/$G4SYSTEM Executable binaries are placed in $G4WORKDIR/bin/$G4SYSTEM Temporary files (object files, dependency files, data products of the compilation process) are placed in $G4WORKDIR/tmp/$G4SYSTEM –don’t delete it!!! You would have to recompile all your files!!! G4WORKDIR is set by default to $G4INSTALL and it should be reset by the user

Naming conventions Sorry, but it is necessary… All Geant4 source files have a.cc extensions, all Geant4 header files carry a.hh extension All Geant4 classes have their name prefixed with a G4 –G4RunManager, G4Step, G4LogicalVolume Abstract classes add a V to the prefix –G4VHit, G4VPhysicalVolume Each word in a composite name is capitalized –G4UserAction, G4VPVParameterisation Methods and functions obey the same naming conventions as the class names –G4RunManager::SetUserAction(), G4LogicalVolume::GetName()

Basic types For basic numeric types, different compilers on different plattforms provide different value ranges To assure portability, Geant4 redefines the basic types for them to have always the same bit yield the definitions of these types are all placed in a single header file (globals.hh), which also provides inclusion of all system headers, as well as global functions needed by the Geant4 kernel int  G4int long  G4long float  G4float double  G4double bool  G4bool (native, or from RW, or from CLHEP) string  G4String (from RW, and now from STL)

The main program Geant4 is a detector simulation toolkit, hence it does not provide a main() method Users must supply their own main program to build their simulation program The G4RunManager class is the only manager class in the Geant4 kernel which should be explicitly instantiated in the main program to specify: –How the detector geometry should be built –Which physics processes one is interested in –How the primary particles in an event should be produced –Additional requests during the simulation procedures

G4RunManager G4RunManager is the root class of the Geant4 hierarchy It controls the main flow of the program: –Construct the manager classes of Geant4 (in its constructor) –Manages initialization procedures including methods in the user initialization classes (in its method Initialize() ) –Manages event loops (in its method BeamOn() ) –Terminates manager classes in Geant4 (in its destructor)

User initialization and action classes Geant4 has two kinds of user defined classes –User initialization classes used for customizing the Geant4 initialization assigned to G4RunManager by invoking the SetUserInitialization() method –User action classes used during the run processing assigned to G4RunManager by invoking the SetUserAction() method The implementation of three user defined classes is mandatory –setting up of the geometry –event kinematics –physics processes

Mandatory user classes Three user classes have to be implemented by the user (two initialization classes and one action class) The base classes of these mandatory classes are abstract and no default implementation is provided G4RunManager checks whether objects belonging to these classes have been instanciated when Initialize() and BeamOn() are invoked Users must inherit from the abstract base classes provided by Geant4 and derive their own classes

Mandatory user classes (2) G4VUserDetectorConstruction (initialization) –the detector set-up must be described in a class derived from this Materials Geometry of the detector Definition of sensitive detectors Readout schemes G4VUserPhysicsList (initialization) –Particles and processes to be used in the simulation –cutoff parameters G4VUserPrimaryGeneratorAction (action) –Primary event kinematics

Optional user action classes G4UserRunAction –run by run G4UserEventAction –event by event G4UserStackingAction –to control the order with which particles are propagated through the detector G4UserTrackingAction –Actions to be undertaken at each end of the step G4UserSteppingAction –Actions to be undertaken at the end of every step

An example of main() (batch program) #include “G4RunManager.hh”// from Geant4, declaration of the run manager #include “G4UImanager.hh// from Geant4, declaration of the User Interface manager #include “MyDetectorConstruction.hh”// by the user; definition of the detector geometry #include “MyPhysicsList.hh”// by the user, list of physics processes to be added #include “MyPrimaryGenerator.hh”// by the user, kinematics of the event int main () { G4RunManager* runManager=new G4RunManager; // the run manager runManager->SetUserInitialization(new MyDetectorConstruction); // the geometry runManager->SetUserInitialization(new MyPhysicsList); // the physics runManager->SetUserAction(new MyPrimaryGenerator); // the kinematics runManager->Initialize(); // run initialization G4UImanager* UI=G4UImanager::GetUIpointer(); // pointer to the UI UI->ApplyCommand(“run/verbose 1”); // set the “print”level int numberOfEvent=3; // nr. of evts to be run runManager->BeamOn(numberOfEvent); // generate the events delete runManager; // end of run return 0; }

Batch mode with macro file int main(int argc, char** argv) { // construct the default run manager G4RunManager* runManager = new G4RunManager; runManager->SetUserInitialization(new MyDetectorConstruction); runManager->SetUserInitialization(new MyPhysicsList) runManager->SetUserAction(new MyPrimaryGeneratorAction); runManager->Initialize(); // read a macro file G4UIManager* UI = G4UImanager::GetUIpointer(); G4String command = “/control/execute “; G4String fileName = argv[1]; UI->ApplyCommand(command+fileName); delete runManager; return 0; }

Batch mode with macro file (2) The previous example can be run with the command > myProgram run.macro where myProgram is the name of the executable and run.macro is a command macro which could look like: # set verbose level for this run /run/verbose 2 /event/verbose 0 /tracking/verbose 2 # 100 electrons of 1GeV Energy /gun/particle e- /gun/energy 1 GeV /run/beamOn 100

Interactive mode int main(int argc, char** argv) { G4RunManager* runManager = new G4RunManager; runManager->SetUserInitialization(new MyDetectorConstruction); runManager->SetUserInitialization(new MyPhysicsList); G4VisManager* visManager = new MyVisManager; visManager->initialize(); runManager->SetUserAction(new MyPrimaryGeneratorAction); runManager->Initialize(); G4UIsession* session = new G4UIterminal; session->SessionStart(); delete session; delete visManager; delete runManager; return 0; }

Interactive mode (2) The previous example will be run with the command > myProgram where myProgram is the name of your executable object After the initialization phase, Geant4 will prompt: Idle> At this point, an interactive session can begin: Idle> /vis~/create_view/new_graphics_system DAWN Idle> /vis/draw/current Idle> /run/verbose 1 Idle> /event/verbose 1 Idle> /tracking/verbose 1 Idle> /gun/particle mu+ Idle> /gun/energy 10 GeV Idle> /run/beamOn 1 Idle> /vis/show/view

ExampleN02 Very basic example, depicting some kind of fix target experimental setup –not very well written but very much complete and good for reference Change directory to geant4/N02 which contains: –a GNUmakefile very basic, essentially defining the name of the executable and running binmake.gmk –the main program (exampleN02.cc) –a macro file (prerun.g4mac) –an include directory class header files –a src directory implementation of all methods

ExampleN02 (cont’d) create the executable with gmake run the executable by typing –$G4WORKDIR/bin/$G4SYSTEM/exampleN02 start the DAWN graphics system by typing –/vis~/create_view/new_graphics_system DAWN draw the experimental setup by –/vis/draw/current and get the GUI by –/vis/show/view tell the tracking of storing all track segments by –/tracking/storeTrajectory 1 and run one event –/run/beamOn 1

ExampleN02 (cont’d) You can change the beam condition by using the /gun commands –/gun/List // to have a list of all possible particles –/gun/particle e+ –/gun/energy 10 GeV –/gun/position cm –/gun/direction have a look at the online help to see what can you do...

ExampleN02 (cont’d)

DAWN DAWN is a vectorized 3D PostScript processor developed at the Fukui University Well suited to prepare high quality outputs for presentation and/or documentation Useful for detector geometry debugging (it comes with a facility, DAVID, which allows to detect overlapping volumes) Remote visualization, cut view, off-line re-visualization are supported by DAWN A DAWN process is automatically invoked as a co-process of Geant4 when visualization is performed and 3D data is passed with inter-process communication via a file or the TCP/IP socket

DAWN (2) There are two kinds of DAWN drivers –DAWN-File –DAWN-Network The DAWN-File driver send 3D data to DAWN via an intermediate file (called g4.prim) in the current directory. The contents of the file can be re-visualized (without running Geant4) by simply running DAWN on it dawn g4.prim The DAWN-Network driver send 3D data to DAWN via the TCP/IP socket or the named pipe and it can be used to perform remote visualization If you have no network, set the environment variable G4DAWN_NAMED_PIPE to 1, to switch the default socket connection to the named pipe within the same host machine

DAWN GUI (page 1) Camera distance Next page Axes Viewing mode Size Camera Position Angles

DAWN GUI (page 2)

DAWN GUI (page 3)

DAWN GUI (page 4) Save the picture in an EPS file Don’t forget this! Have a preview of the picture

Geant4 and CLHEP Geant4 makes a rather substantial use of CLHEP components –System of units –Vector classes and matrices G4ThreeVector(typedef to Hep3Vector) G4RotationMatrix(typedef to HepRotation) G4LorentzVector(typedef to HepLorentzVector) G4LorentzRotation(typedef to HepLorentzRotation) –Geometrical classes G4Plane3D(typedef to HepPlane3D) G4Transform3D(typedef to HepTransform3D) G4Normal3D(typedef to HepNormal3D) G4Point3D(typedef to HepPoint3D) G4Vector3D(typedef to HepVector3D)

System of units Geant4 offers the possibility to choose and use the units one prefers for any quantity Geant4 uses an internal and consistent set of units based on: –millimeter(mm) –nanosecond(ns) –Mega electron Volt(MeV) –Positron charge(eplus) –Degree Kelvin(kelvin) –Amount of substance(mole) –Luminosity intensity(candela) –Radian(radian) –steradian(steradian)

System of units (2) All the units are defined from the basic ones These definitions are available in the file –source/global/management/include/SystemOfUnits … and are now part of CLHEP The user is free to change the system of units to be used by the kernel millimeter=mm=1; meter = m = 1000*mm; ……. m3 = m*m*m; ……..

System of units (3) Avoid hard coded data –you better specify the unit of the data you are going to introduce –The Geant4 code is written respecting these specification and this makes the code independent from the system of units chosen by the user Be careful!!! Some built-in commands for the User interface require the unit to be specified G4double Size = 15.*km, KineticEnergy = 90.3*GeV, density = 11*mg/cm3; G4double radius=10.*m;// internally converted: radius=10000 …. G4double xposition = (radius*cos(alpha*rad))*cm// is this really what you want to do?? G4double yposition = (radius*sin(alpha*rad))*cm /gun/energy 10 GeV

System of units (4) To output the data on the unit you wish you must DIVIDE the data by the corresponding unit You can let Geant4 decide which is the most appropriate unit to represent your data. It is just sufficient to specify which category (length, time, energy…) does it belong to: You can print the whole table of units by using the static function cout << KineticEnergy/KeV << “ KeV “<<endl ; cout << G4BestUnit(StepSize, “Length”) <<endl G4UnitDefinition::PrintUnitsTable

System of units (5) You may introduce new units if you wish: –by completing the file SystemOfUnits.hh –by using the class G4UnitDefinition and creating a new object of it G4UnitDefinition (name, symbol, category, value) #include “SystemOfUnits.hh” static const G4double inch = 2.54*cm; G4UnitDefinition (“km/hour”,”km/h”,”Speed”,km/(3600*s)); G4UnitDefinition (“meter/ns”,”m/ns”,”Speed”,m/ns);

3-Vectors Geant4 makes use of the CLHEP HepVector3D and Hep3Vector for implementing several 3-dimensional object (G4ThreeVector, G4ParticleMomentum…) The definition of a 3-vector is pretty straightforward: G4ThreeVector *p=new G4ThreeVector(10,20,100); Every component can be accessed very easily: G4double px=p->x(); and set very easily; p->setZ(50); the components in polar coordinates are give by phi(), theta(), mag() and set using: setPhi(), setTheta(), setMag()

3-Vectors (2) They can be normalized: p->unit(); rotated around one of the cartesian axes p->rotateY(2.73); or around any other 3-vector p->rotate(1.57,G4ThreeVector(10,20,30)); for reference: $CLHEP_BASE_DIR/include/CLHEP/Vector/ThreeVector.h wwwinfo.cern.ch/asd/lhc++/clhep/manual/RefGuide/Vector/Hep3Vector.html

Rotation Matrixes Geant4 uses the rotation matrix implementation which comes with CLHEP (HepRotation, typedef’d into G4RotationMatrix) #include “G4RotationMatrix.hh” …. G4RotationMatrix *rm = new G4RotationMatrix; You can then rotate about the coordinate axes: rm->rotateX(45*deg);// rotation about X and combine several rotations into a 3D one: rm->rotateX(30*deg); rm->rotateY(20*deg);

Rotation Matrixes (2) You can rotate about a specified vector rm->rotate(45*deg,Hep3Vector(1.,1.,.3)); or specify the direction of the three cartesian axes after the rotation rm->rotateAxes(Hep3Vector(-sin(a),0,cos(a)), Hep3Vector(cos(a),0,sin(a)), Hep3Vector(0,1,0)); a rotation matrix can be inverted by using the invert method rm->invert();

Rotation Matrixes (3) The angles made by the rotated axes against the original axes can be obtained with the set of functions: –phiX(),phiY(),phiZ(),thetaX(),thetaY(),thetaZ() …or one can get the rotation angle and the rotation axis (awkward) G4double angle; G4ThreeVector axis; rm->getAngleAxis(angle,axis); to reset a rotation matrix use the default constructor *rm=G4RotationMatrix(); documentation at: $CLHEP_BASE_DIR/include/CLHEP/Vector/Rotation.h wwwinfo.cern.ch/asd/lhc++/clhep/manual/RefGuide/Vector/HepRotation.html

Geometry …and materials

Materials In nature, general materials (compounds, mixtures) are made by elements and elements are made by isotopes. These are the three main classes designed in Geant4 The G4Element class describes the properties of the atoms: atomic number, number of nucleons, atomic mass, shell energy… The G4Isotope class permits to describe the isotopic composition of a material The G4Material class describes the macroscopic properties of the matter: density, state, temperature, pressure, radiation length, mean free path, dE/dx… G4Material is the class visible to the rest of the toolkit and it is used by the tracking, the geometry and physics

Define a simple material A simple material can be created by specifying its name, density, mass of a mole and atomic number: The pointer to the material will then be used to specify the material a given logical volume is made of #include “G4Material.hh” … G4double density=1.390*g/cm3; G4double a=39.95*g/mole; G4double z=18.; G4String name; … G4Material* LAr = new G4Material(name=“Liquid Argon”, z, a, density);

Define a molecule A molecule is built from its components, by specifying the number of atoms in the molecule. #include “G4Element.hh” #include “G4Material.hh”... G4double a=1.01*g/mole; G4double z; G4String name,symbol; G4Element* H = new G4Element(name=“Hydrogen”, symbol=“H”,z=1.,a); a=16.0*g/mole; G4Element* O = new G4Element(name=“Oxygen”, symbol=“O”,z=8.,a); G4double density=1.000*g/cm3; G4int ncomponent,natoms; G4Material* H2O = new G4Material(name=“Water”,density,ncomponents=2); H2O->AddElement(H,natoms=2); H2O->AddElement(O,natoms=1);

Define a mixture (by fractional mass) Air is built from Nitrogen and Oxygen by giving the fractional mass of each component #include “G4Element.hh” #include “G4Material.hh”... G4double a=14.01*g/mole; G4double z; G4String name,symbol; G4Element* N = new G4Element(name=“Nitrogen”, symbol=“N”,z=7.,a); a=16.0*g/mole; G4Element* O = new G4Element(name=“Oxygen”, symbol=“O”,z=8.,a); G4double fractionmass,density=1.290*mg/cm3; G4int ncomponent,natoms; G4Material* Air = new G4Material(name=“Air”,density,ncomponents=2); Air->AddElement(N,fractionmass=70*percent); Air->AddElement(O,fractionmass=30*percent);

Materials as mixtures of materials ArCO2 can be defined as mixture of an element and a material: #include “G4Element.hh” #include “G4Material.hh”... G4double a,z,fractionmass,density; G4String name,symbol; G4int ncomponents,natoms; G4Element* Ar = new G4Element(name=“Argon”, symbol=“Ar”,z=18.,a=39.95*g/mole); G4Element* C = new G4Element(name=“Carbon”, symbol=“C”, z=6., a=12.00*g/mole); G4Element* O = new G4Element(name=“Oxygen”, symbol=“O”,z=8.,a=16.00*g/mole); G4Material* CO2 = new G4Material(name=“CO2”,density=1.977*mg/cm3,ncomponents=2); CO2->AddElement(C,natoms=1); CO2->AddElement(O,natoms=2); G4Material* ArCO2=new G4Material(name=“ArCO2”,density=1.8*mg/cm3,ncomponents=2); ArCO2-> AddElement(Ar,fractionmass=93*percent); ArCO2-> AddMaterial(CO2,fractionmass=7*percent);

Materials in non STP conditions #include “G4Element.hh” #include “G4Material.hh”... G4double a,z,fractionmass,density; G4String name,symbol, ncomponent,natoms; G4Element* Ar = new G4Element(name=“Argon”, symbol=“Ar”,z=18.,a=39.95*g/mole); G4Element* C = new G4Element(name=“Carbon”, symbol=“C”, z=6., a=12.00*g/mole); G4Element* O = new G4Element(name=“Oxygen”, symbol=“O”,z=8.,a=16.00*g/mole); G4double temperature=300.*kelvin; G4double pressure=2*atmosphere; G4Material* CO2 = new G4Material(name=“CO2”,density=1.977*mg/cm3,ncomponents=2 kStateGas,temperature,pressure); CO2->AddElement(C,natoms=1); CO2->AddElement(O,natoms=2); G4Material* ArCO2=new G4Material(name=“ArCO2”,density=1.8*mg/cm3,ncomponents=2 kStateGas,temperature,pressure); ArCO2-> AddElement(Ar,fractionmass=93*percent); ArCO2-> AddMaterial(CO2,fractionmass=7*percent);

Printing materials and elements Materials and elements (and the tables maintained internally by Geant4) can be printed very easily with: #include “G4Element.hh” #include “G4Material.hh”... cout<<ArCO2; cout<<*(G4Element::GetElementTable()); cout<<*(G4Material::GetMaterialTable());

Detector geometry A detector geometry in Geant4 is made of a number of volumes. The largest volume is called the World volume. It must contain all other volumes in the detector geometry The other volumes are created and placed inside previous volumes, including the World. Each volume is created by describing its shape and its physical characteristics and then placing it inside a containing volume. The coordinate system used to specify where the daughter volume is placed is the one of the mother.

Detector Geometry (2) Volumes cannot overlap in Geant4!!! Use boolean operations instead! Geant3 Geant4 “MANY” “ONLY”

G4VUserDetectorConstruction G4VUserDetectorConstruction is one of the three abstract classes in Geant4 the user MUST inherit from to create his/her implementation of the detector geometry An instance of a class inherited from G4VUserDetectorConstruction is passed to the G4RunManager by calling SetUserInitialization(). The Run Manager keeps a pointer to the detector geometry which the user wants to use and checks (before startup) that this pointer has indeed been set G4VUserDetectorConstruction’s method Construct() is invoked by the Run Manager to set up the detector geometry. Construct() should hence set up everything needed for the geometry definition Construct() returns a pointer the the World’s Physical Volume

Volumes To have a volume implemented in Geant4 one has to go through three steps. –A Solid is used to describe a volume’s shape. A solid is a geometrical object that has a shape and specific values for each of that shape’s dimensions –A Logical Volume is use for describing a volume’s full properties. It starts from its geometrical properties (the solid) and adds physical characteristics, like the material, the sensitivity, the magnetic field, the color… –What remains to describe is the position of the volume. For doing that, one creates a Physical volumes, which places a copy of the logical volume inside a larger, containing volume.

Solids The STEP standard supports multiple solid representations –Constructive Solid Geometry (CSG) –SWEPT solids –Boundary Represented solids (BREPs) Different representations are suitable for different purposes, applications, required complexity and levels of detail. –CSGs give superior performance and they are easy to use, but they cannot reproduce complex solids as used in CAD systems –BREPs allow to reproduce the most complex solids, thus allowing the exchange of models with CAD systems, but they are normally quite inefficient, as far as tracking is concerned

Solids To create a simple box one has simply to define its name and its dimensions along each cartesian axes: #include “G4Box.hh” …. G4double expHall_x=3.0*m; G4double expHall_y=1.0*m; G4double expHall_z=1.0*m; … G4Box* experimentalHall_box = new G4Box(“Exp. Hall box”,expHall_x,expHall_y,expHall_z);

CSG Solids CSG solids are defined directly as 3D primitives They are described by a minimal set of parameters necessary to define the shape and the size of the solid CSG solids are Boxes, Tubes and their sections, Cones and their sections, Spheres, Wedges, Toruses

G4Box The definition of a Box in Geant4 can be found in: To create a box use the constructor: G4Box(const G4String& pName, G4double pX, G4double pY, G4double pZ) where: pX:half length in X pY:half length in Y pZ:half length in Z G4Box* a_box=new G4Box(“My Box”,10*cm,0.5*m,30*cm); $G4INSTALL/source/geometry/solids/CSG/include/G4Box.hh

G4Tubs The definition of a Tube (or a section of it) is in: use the constructor: $G4INSTALL/source/geometry/solids/CSG/include/G4Tubs.hh G4Tubs(const G4String& pName, G4double pRmin, G4double pRmax, G4double pDz, G4double pSPhi, G4double pDPhi) where: pRmin:Inner Radius pRmax:Outer Radius pDZ:half length in Z pSPhi:starting phi angle pDPhi:angular span of the section G4Tubs* a_tube=new G4Tubs(“a Tube”,10*cm,30*cm,20*cm,0.,270.*deg);

G4Cons The definition of a cone (or a section of it) is in: Use the constructor: $G4INSTALL/source/geometry/solids/CSG/include/G4Cons.hh G4Cons(const G4String& pName, G4double pRmin1, G4double pRmax1, G4double pRmin2, G4double pRmax2, G4double pDz, G4double pSPhi, G4double pDPhi) where: pRmin1,pRmax1:Inner/Outer Radius at z=-pDz pRmin2,pRmax2:Inner/Outer Radius at z=pDz pDZ:half length in Z pSPhi:starting phi angle pDPhi:angular span of the section G4Cons* a_cone=new G4Cons(“a Cone”,1*cm,5*cm,10*cm,30*cm,20*cm,0.,180.*deg);

G4Trd The definition of a trapezoid is in The general constructor is: $G4INSTALL/source/geometry/solids/CSG/include/G4Trd.hh G4Trd(const G4String& pName, G4double dx1, G4double dx2, G4double dy1, G4double dy2, G4double pDz) where: dx1:Half length along x at the surface positioned at -dz dx2:Half length along x at the surface positioned at +dz dy1:Half length along y at the surface positioned at -dz dy2:Half length along y at the surface positioned at +dz dz:Half length along z axis G4Trd* a_trd=new G4Trd(“a Trd”,10*cm,20*cm,1*m,1*m,2*m);

Other CSG shapes G4Hype –an hyperbolic with curved sides parallel to the z axis G4Para –a general Parallelepiped G4Trap –a general trapezoid (possibly twisted) G4Sphere –a (section of a) sphere For additional informations about these shapes have a look in $G4INSTALL/source/geometry/solids/GSG/include

Polycone and polyhedra A polycone solid is a shape defined by a set of inner and outer conical or cylindrical surface sections and two planes perpendicular to the Z axis. Each conical surface is defined by its radius at two different planes perpendicular to the Z axis. Inner and outer conical surfaces are defined using common Z planes G4Polycone( G4String name, const G4double start_angle,// starting angle const G4double opening_angle,// opening angle const int num_z_planes,// nr. of planes const G4double z_start,// starting value of z const G4double z_values[],// z coordinate of each plane const G4double RMIN[],// inner radius of the cone at each plane const G4double RMAX[])// outer radius of the cone at each plane

Polycone and polyhedra The polyhedra solid is a shape defined by an inner and outer polygonal surface and two planes perpendicular to the Z axis. Each polygonal surface is created by linking a series of polygons created at different planes perpendicular to the Z axis. All these polygons have the same nr of sides G4Polyhedra( G4String name, const G4double start_angle,// starting angle const G4double opening_angle,// opening angle const G4int n_sides// nr. of sides const G4int num_z_planes,// nr. of planes const G4double z_start,// starting value of z const G4double z_values[],// z coordinate of each plane const G4double RMIN[],// inner radius of the cone at each plane const G4double RMAX[])// outer radius of the cone at each plane

Logical volumes To create a Logical volume one must start from a solid and a material. #include “G4LogicalVolume.hh” #include “G4Box.hh” #include “G4Material.hh” …. G4Box* a_box = new G4Box(“A box”,dx,dy,dz); G4double a=39.95*g/mole; G4double density=1.390*g/cm3; G4Material* LAr = new G4Material(name=“Liquid Argon”,z=18.,a,density); G4LogicalVolume* a_box_log = new G4LogicalVolume(a_box,LAr,”a simple box”);

Positioning a volume To position a volume, one must start with a logical volume and decide what volume (which must already exist) to place it inside, where to position it (wrt the mother’s reference system) and how to rotate it A physical volume is simply a positioned instance of a logical volume #include “G4VPhysicalVolume.hh” #include “G4PVPlacement.hh” … G4RotationMatrix *rm=new G4RotationMatrix; rm->rotateX(30*deg); G4Double aboxPosX=-1.0*m; G4VPhysicalVolume* a_box_phys= new G4PVPlacement(rm,// pointer to G4RotMatrix!! G4ThreeVector(aboxPosX,0,0),// position a_box_log,// its logical volume “a box”,// its name experimentalHall_log,// its mother false,// no boolean ops. 1);// the copy nr.

Positioning a volume (2) An exception exist to the rule that a physical volume must be placed inside a mother volume. The World volume must be created as a G4PVPlacement with a null mother pointer and be positioned unrotated at the origin of the global coordinate system #include “G4PVPlacement.hh” … G4VPhysicalVolume experimentalHall_phys =new G4PVPlacement(0, // No rotation! G4ThreeVector(0.,0.,0.), // No Translation! experimentalHall_log, // The logical volume “Experimental Hall”, // its name 0, // No mother volume! false, // no boolean operations 0); // copy number

Frame This example introduces the three mandatory classes to be implemented for a Geant4 application to run (and a visualization manager, needed for graphics applications) –have a look to the various files in the src/ and include/ directories, figure out which methods have been implemented the example, as it is, will not compile. The aim of the example is –to create the world volume. To this purpose, the FrameDetectorConstruction class contains three variables (experimentalHall_x,y,z) which can be used as dimensions for the world volume –implement elements, materials, mixtures… –create solids, logical volumes and physical volumes and position them into the world volume, try to rotate and translate them, try composite rotations to understand how the system works...

Frame (2) Try and build a calorimeter (!) made of trapezoidal wedges (dimensions and nr. of wedges are provided in the program)

Visualization Attributes

Visualization attributes are a set of information associated with objects which can be visualized This information is just used for visualization and it is not included in the geometrical information such as shapes, position and orientation A set of visualization attributes is held by an object of class G4VisAttributes

Visibility Visibility is a boolean flag used to control the visibility of the objects passed to the Visualization Manager for visualization Visibility is set by: G4VisAttributes::SetVisibility(G4bool visibility); If visibility=false, visualization is skipped for those objects to which this set of attributes is assigned The following public data member is by default defined static const G4VisAttributes Invisible This can be referred at as G4VisAttributes::Invisible experimentalHall_log->SetVisAttributes(G4VisAttributes::Invisible);

Color G4VisAttributes holds its color entry as an object of the class G4Colour G4Colour has four field which represent the RGBA (red,green,blue,alpha) of a color. Each component takes a value between 0 and 1. Alpha is the opacity, not used in the present version A G4Colour object is created by giving the red, blue and green components of the color G4Color( G4double red=1.0,G4double green=1.0,G4double blue=1.0, G4double a=1.0); The default value of each component is 1, which means white

Color (2) G4Colour white (); // white G4Colour white(1.,1.,1.); // white G4Colour gray(.5,.5,.5);// gray G4Colour black(0.,0.,0.);// black G4Colour red(1.,0.,0.);// red G4Colour green(0.,1.,0.);// green G4Colour blue(0.,0.,1.);// blue G4Colour cyan(0.,1.,1.);// cyan G4Colour magenta(1.,0.,1.);// magenta G4Colour yellow(1.,1.,0.);// yellow

Color (3) One can set the RGBA components directly into G4VisAttributes void G4VisAttributes::SetColour (G4double red, G4double green, G4double blue, G4double alpha=1.0); The following G4VisAttributes constructor is also supported G4VisAttributes::G4VisAttributes(const G4Colour& color);

Forced wireframe and forced solid styles Several drawing styles can be selected for the volumes. For instance, one can select to visualize detector components in “wireframe” or with “surfaces”. In the former, only the edges of the detector are drawn, so the detector looks transparent. In the latter, the detector looks opaque with shading effects The forced wireframe and forced solid styles make it possible to mix wireframe and solid visualization. For instance, one can make the mother volume transparent and still look inside when in “solid” mode Forced wireframe and forced solid are available via: void G4VisAttributes::SetForceWireframe(G4bool force); void G4VisAttributes::SetForceSolid(G4bool force);

Constructors for G4VisAttributes The following constructors are supported for G4VisAttributes G4VisAttributes(); G4VisAttributes(G4bool visibility); G4VisAttributes(const G4Colour& colour); G4VisAttributes(G4bool visibility, const G4Colour& colour);

How to assign G4VisAttributes to a volume In constructing the detector components, one may assign a set of visualization attributes to each Logical Volume in order to visualize it later G4LogicalVolume holds a pointer to a G4VisAttributes. This field is set and referenced by using: void G4LogicalVolume::SetVisAttributes(const G4VisAttributes* pVa); void G4LogicalVolume::SetVisAttributes(const G4VisAttributes& Va); If you want to display you experimental hall in cyan and in forced wireframe style you do: ExpHall_log=new G4LogicalVolume(ExpHall_box,Air,”exp_hall”); ….. G4VisAttributes *expHallVisAtt=new G4VisAttributes(G4Colour(0.,1.,1.)); expHallVisAtt->SetForceWireframe(true); ExpHall_log->SetVisAttributes(expHallVisAtt);

Tuesday, Nov 9th 9:30-12:30 –Visualization attributes –Physics processes 14:00-17:00 –Kinematics and event generation (from yesterday) Particle gun –Boolean solids (?)

Particles and physics processes

G4VUserPhysicsList The G4VUserPhysicsList class is the base class which one has to derive from to specify all particles and physics processes to be used in the simulation The user must inherit from G4VUserPhysicsList and implement three methods: –ConstructParticle()Particle Construction –ConstructPhysics()Physics processes –SetCuts()Cut values (in stopping range)

Particles Geant4 provides a set of ordinary particles such as electron, proton, gamma etc. The G4ParticleDefinition class provides a representation of a particle. Each particle has its own class derived from it G4ParticleDefinition contains properties which characterize individual particles such as name, mass, charge, spin… Except for lifetime, decay table and the “stable” flag, this attributes are read-only and cannot be changed without re-building the libraries There are 6 major particle classes: leptonsbosons mesonsshortlived baryonsions

Particles (2) Each particle is represented by its own class Each particle class has only one static object (singleton) –G4Electron represents the electron –G4Electron::theElectron is the only object of the G4Electron class –A pointer to the electron object can be obtained by using the static method G4Electron::ElectronDefinition() The class G4ParticleTable is a collection of defined particles. It provides a series of utility methods to retrieve particle definitions: –FindParticle(G4String name)find the particle by name –FindParticle(G4int PDGencoding)find the particle by its PDG code G4ParticleTable is a singleton and the static method G4ParticleTable::GetParticleTable() returns its pointer

Particles (3) Particles are static objects belonging to the individual particle classes As such, these object will automatically instanciated before main() is executed However, one must explicitly declare the particle classes somewehre in the program, otherwise the compiler cannot recognize these classes and no particle object will be available

Particle construction The ConstructParticle() method from G4VUserPhysicsList must be implemented by the user to create all particles which are needed in the simulation Utility classes provided to define all particles of the same types in Geant4. #include “G4Geantino.hh” #include “G4Electron.hh” #include “MyPhysicsList.hh” void MyPhysicsList::ConstructParticle() { G4Geantino::GeantinoDefinition(); G4Electron::ElectronDefinition(); } void MyPhysicsList::ConstructLeptons() { // Construct all leptons G4LeptonConstructor pConstructor; pConstructor.ConstructParticle(); }

Setting cuts SetCuts(G4double cut) is a virtual method of the class G4VUserPhisicsList to be implemented in order to set the cut in range for each particle Construction of geometry, particles and processes should precede the invocation of SetCuts() By means of SetCuts(), the cut in range is then converted to the cut-off energy for all materials defined in the geometry G4VUserPhysicsList keeps a defaultCutValue as the default cut off value for the range. A method SetCutsWithDefault() is invoked by the G4RunManager for all normal applications and this default value is passed to the argument of the SetCuts() method

Setting cuts (2) The default cut value is 1mm in all cases. Its value can be changed directly in the constructor of the class you inherit from G4VPhysicsList or by using the SetDefaultCutValue() method The cut value can be retrieved by using the method GetLengthCuts() whilst the cut-off energy for each material can be obtained by invoking GetEnergyThreshold(G4Material *) If you want to set different cut values for different particles, you must respect a specific definition order, as some particles depend on some other particle’s cut value for calculating the cross- sections gamma  electron  prositron  proton/antiproton  others

Setting cuts (3) To ease the implementation of the SetCuts() method, the G4VUserPhysicsList class provides some utility methods –SetCutValue(G4double cut_value, G4String particle_name) –SetCutValueForOthers(G4double cut_value) –SetCutValueForOtherThan(G4double cut, G4ParticleDefinition* particle) An example of implementation void MyPhysicsList::SetCuts(G4double cut) { SetCutValue(cut,”gamma”); SetCutValue(cut,”e+”); SetCutValue(cut,”e-”); SetCutValue(cut,”proton”); SetCutValueForOthers(cut); }

Production threshold vs tracking cut It is the responsibility of each individual process to produce secondary particles according to its own capabilities. On the other hand, only the Geant4 kernel can ensure an overall coherence of the whole simulation hence, as general principle –Each process has its intrinsic limits to produce secondary particles –All particles produced will be tracked up to zero range –Each particle has a suggested cut in range (converted to an energy cut for all materials) The results of this is that the cut associated to each particle is a (recommended) production threshold on secondary particles

Production below threshold A process can still decide to produce secondary particles even below the recommended production threshold –if, by checking the range of the secondary produced against quantities like safety (~the distance to the next boundary), it turns out that the particle, even below threshold, might reach a sensitive part of the detector –when mass-to-energy conversion can occur, to conserve the energy. For instance, in gamma conversion, the positron is always produced, even at 0 energy, for further annihilation

Physics Processes Physics processes describe the interaction of particles with matter In Geant4 there are 7 major categories of physics processes –electromagnetic –hadronic –transportation –decay –optical –photolepton_hadron –parameterisation

Physics Processes (2) A class G4VProcess is provided as the base class for all physics processes All physics processes are described by using three (virtual) methods: –AtRestDoIt() –AlongStepDoIt() –PostStepDoIt() The following classes are then used as base classes for simple processes –G4VAtRestProcessProcess with AtRestDoIt() only –G4VContinuousProcessProcess with AlongStepDoIt only –G4VDiscreteProcessProcess with PostStepDoIt 4 additional classes (such as G4VContinuousDiscreteProcess) are provided for complex processes

G4ProcessManager G4ProcessManager is a member of G4ParticleDefinition G4ProcessManager keeps a list of processes a particle can undergo. Moreover, it keeps the information on the order of invocation of the processes as well as which kind of DoIt method is valid for which process Physics processes should be registered with the G4ProcessManager of each particle (together with ordering information) by using AddProcess() and SetProcessOrdering(). For registering simple processes, one can use AddAtRestProcess(), AddContinuousProcess() and AddDiscreteProcess() The G4ProcessManager has the possibility of switching on/off some processes at run time by using ActivateProcess() and InActivateProcess()

AddTransportation() Transportation (propagating particles in space) is treated as a process, hence it must be defined for all particles The G4Transportation class must be registered with all particle classes. An AddTransportation() method is provided in G4VUserPhysicsList and it must be called in ConstructPhysics() void G4VUserPhysicsList::AddTransportation() { G4Transportation* theTransportation=new G4Transportation; theParticleIterator->reset(); while ( (*theParticleIterator) () ) { G4ParticleDefinition *particle=theParticleIterator->value(); G4ProcessManager* pmanager=particle->GetProcessManager(); if (!particle->IsShortLived()) { pmanager->AddProcess(theTransportationProcess); pmanager->SetProcessOrderingToFirst(theTransportationProcess,idxAlongStep); } } }

ConstructProcess() ConstructProcess() is a pure virtual method which is used to create physics processes and register them to particles For each particle which has been declared in ConstructParticle(), the user must get hold of the G4ProcessManager attached to the particle and register all relevant physics processes by using the AddProcess(G4VProcess *) method

ConstructProcess for a geantino A geantino is a geometrical probe, only the transportation process must be registered with it Void ExN01PhysicsList::ConstructProcess() { AddTransportation(); }

ConstructProcess for gammas Void MyPhysicsList::ConstructProcess() { AddTransportation(); ConstructEM(); } void MyPhysicsList::ConstructEM() { G4ParticleDefinition* particle = G4Gamma::GammaDefinition(); G4ProcessMAnager *pmanager= particle->GetProcessManager(); G4PhotoElectricEffect *thePhotoElectricEffect = new G4PhotoElectricEffect; G4ComptonScattering *theComptonScattering = new G4ComptonScattering; G4GammaConversion *theGammaConversion = new G4GammaConversion; pmanager->AddDiscreteProcess(thePhotoElectricEffect); pmanager->AddDiscreteProcess(theComptonScattering); pmanager->AddDiscreteProcess(theGammaConversion); }

Physics The aim of the exercise is to add particles and physics processes and to define cuts for these particles in the physics list go into PhysicsPhysicsList and add geantino, electron, positron, mu+ and mu- into ConstructParticles() go into CostructProcess() and add processes for the particles you just defined –geantinos only need transportation –electrons need the multiple scattering (G4MultipleScattering), the ionisation (G4eIonisation), the bremsstrahlung (G4eBremsstrahlung) to be added. In the case of positron, add the annihilation (G4eplusAnnihilation) –add processes for the muons too (G4MultipleScattering, G4MuIonisation, G4MuBremsstrahlung, G4MuPairProduction) Add cuts for these particles in SetCuts()

Physics (2) Use ExampleN02 for reference (but don’t copy&paste into the blue, try and understand what is happening) To find a particle into the particle table, use either the particle iterator or the FindParticle() method Shoot an electron (we are using the same geometry as in the Frame example). See if a shower develops in the calorimeter For displaying the tracks, copy ExN02EventAction.hh and.cc from the N02 example and register an object of it with the G4RunManager (in the main()) by using the SetUserAction() method

Kinematics

G4VUserPrimaryGeneratorAction G4VUserPrimaryGeneratorAction is one of the mandatory classes the user has to derive a concrete class from In the concrete class, one must specify how the primary event should be generated The actual generation of the primary particles will be performed in a concrete class derived from G4VPrimaryGenerator The class inherited from G4VPrimaryGenerator must implement the method: GeneratePrimaryVertex(G4Event *evt)

An example of PrimaryGeneratorAction #ifndef MyPrimaryGeneratorAction_H #define MyPrimaryGeneratorAction_H #include “G4VUserPrimaryGeneratorAction.hh” class MyTestBeam; class Event; class MyPrimaryGeneratorAction: public G4VUserPrimaryGeneratorAction{ public: MyPrimaryGeneratorAction(); ~MyPrimaryGeneratorAction(); void GeneratePrimaries(G4Event* anEvent); private: MyTestBeam *tBeam; }; #endif

An example of PrimaryGeneratorAction (2) #include “MyPrimaryGeneratorAction.hh” #include “G4Event.hh” #include “MyTestBeam.hh” #include “G4ThreeVector.hh” #include “G4Geantino.hh” #include “globals.hh” MyPrimaryGeneratorAction::MyPrimaryGeneratorAction() { tBeam=new MyTestBeam(); }

An example of PrimaryGeneratorAction (3) MyPrimaryGeneratorAction::~MyPrimaryGeneratorAction() { delete tBeam; } void MyPrimaryGeneratorAction::GeneratePrimaries(G4Event* anEvent) { cout GetEventId()<<endl; tBeam->GeneratePrimaryVertex(anEvent); }

Generation of an event The primary generator should be selected in the constructor of the concrete class derived from G4VUserPrimaryGeneratorAction This particle generator must then be destroyed in the destructor In the previous example we make use of a class (MyTestBeam) which is a predefined primary particle generator (G4VPrimaryGenerator) G4VUserPrimaryGeneratoAction has a pure virtual method named GeneratePrimaries(), invoked at the beginning of each event. In this method, one must invoke the GeneratePrimaryVertex() method of the G4VPrimaryGenerator concrete class that one instanciated

An example of PrimaryGenerator #ifndef MyTestBeam_H #define MyTestBeam_H #include “G4VPrimaryGenerator.hh” #include “G4ThreeVector.hh” #include “G4PrimaryVertex.hh” #include “G4ParticleDefinition.hh” #include “G4ParticleMomentum.hh” #include “G4Event.hh” class MyTestBeam: public G4VPrimaryGenerator { public: MyTestBeam(); void GeneratePrimaryVertex(G4Event *evt); private: G4ParticleDefinition *beamParticleDefinition; G4ParticleMomentum beamMomentum; G4double beamEnergy; G4ThreeVector beamVertex; G4double beamTime; } #endif

An example of PrimaryGenerator (2) // MyTestBeam.cc #include “G4Event.hh” #include “MyTestBeam.hh” #include “G4Electron.hh” #include “G4PrimaryParticle.hh” MyTestBeam::MyTestBeam() { beamParticleDefinition=G4Electron::ElectronDefinition(); beamEnergy=10*GeV; beamMomentum=G4ParticleMomentum(1.,0.,0); beamVertex=G4ThreeVector(0.,0.,-100); beamTime=0; } MyTestBeam::GeneratePrimaryVertex(G4Event *evt) { G4PrimaryVertex *vt=new G4PrimaryVertex(beamVertex,beamTime); G4double px=beamEnergy*beamMomentum.x(); G4PrimaryParticle *particle=new G4PrimaryParticle(beamParticleDefinition,px,py,pz); vt->SetPrimary(particle); evt->AddPrimaryVertex(vt); }

G4ParticleGun G4ParticleGun is a primary particle generator provided by Geant4. It generates primary particles with a given momentum and position Randomization of energy, momentum and position is not provided directly by G4ParticleGun but it can be realized by invoking several of its methods; this must be done in GeneratePrimaries() before invoking generatePrimaryVertex() The following methods are provided for G4ParticleGun void SetParticleDefinition(G4ParticleDefinition*) void SetParticleMomentum(G4ParticleMomentum) void SetParticleMomentumDirection(G4ThreeVector) void SetParticleEnergy(G4double) void SetParticleTime(G4double) void SetParticlePosition(G4ThreeVector) void SetParticlePolarization(G4ThreeVector) void SetNumberOfParticles(G4int)

kinematics The aim of the exercise is to implement a PrimaryGeneratorAction, either as a test beam generator or as a 4-  generator (flat generation of particles in eta-phi) Use G4ParticleGun as a first attempt (the test beam generator is trivial in this case), then try and implement your own PrimaryGenerator Use G4UniformRand() from Randomize.hh is you need a random number generator (flat distribution in ]0,1[)

boolean (2) A set of variables is already available for doing the work –idet_inner_radiusmin distance of the idet from beam pipe –idet_outer_radiusouter radius of the idet –idet_zmaxmaximum z of the idet –calo_inner_radiusmin distance of the calo from beam pipe –calo_outer_radiusouter radius of the calo –calo_zmaxmaximum z of the calorimeter –muon_inner_radiusmin distance of the muon from beam pipe –muon_outer_radiusouter radius of the muon –muon_zmaxmaximum z of the muon Visualization has not been implemented yet for boolean solids, hence the only way to check the results is to shoot particles and check that they behave as expected

Wednesday, Nov. 10 9:30-12:30 –boolean solids –more on geometry - replicas 14:00-17:00 –parameterised volumes –EM field

Boolean solids

Solids from boolean operations A very interesting feature of Geant4 is the possibility of combining simple solids with boolean operations To create such a “new” boolean solid, one needs: –Two solids –a boolean operation (union, intersection, subtraction) –(optionally) a transformation for the second solid The solids used should be either CSG solids or another boolean solid (result of a previous boolean operation)

Boolean solids #include “G4UnionSolid.hh” #include “G4SubtractionSolid.hh” #include “G4IntersectionSolid.hh” …. G4Box box1(“Box #1”,20,30,40); G4Tubs cylinder1(“Cylinder #1”,0,50,50,0,2*M_PI); G4UnionSolid b1UnionC1(“Box+Cylinder”,&box1,&cylinder1); G4IntersectionSolid b1IntersC1(“Box intersect Cylinder”,&box1,&cylinder1); G4SubtractionSolid b1MinusC1(“Box-Cylinder”,&box1,&cylinder1);

Boolean solids (2) The more useful case is the one where one of the solids is displaced from the origin of the coordinates of the first (reference) solid This can be done –Either by giving a rotation matrix and a translation vector that are used to transform the coordinate system of the first solid to the coordinate system of the second solid (passive method) –or by creating a transformation that moves the second solid from its desired position to its standard position In the first case the translation is applied first to move the origin of coordinates. Then the rotation is used to rotate the coordinate system of the first solid to the coordinate system of the second solid

Boolean solids (3) G4RotationMatrix yRot45deg; yRot45deg.rotateY(M_PI/4); G4ThreeVector translation(0,0,50); G4UnionSolid boxUnionCyl1(“box union cylinder”, &box1,&cylinder1,&yRot45deg,translation); // the same solid with the active method G4RotationMatrix InvRot=yRot45deg; InvRot.invert(); G4Transform3D transform(InvRot,translation); G4UnionSolid boxUnionCyl2(“box union cylinder”, &box1,&cylinder1,transform)

boolean The aim of the exercise is to implement the mother volumes for the three major subdetectors in Atlas (inner detector, calorimeters, muon) by using boolean solids. Implement the inner detector as a normal tube, the calorimeter as a subtraction and the muon part as union

Geometry revisited

MaterialManager One of the most unpleasant chores in GeantN is to define materials The same material can be used in two (or more) different classes, hence, to avoid duplication of information, one must find a way of storing and retrieving materials into some “container” MaterialManager is a naïve solution to this problem. By default, it has a table which contains predefined elements and materials (which can be completed, though) and a series of methods for storing new materials and retrieving the ones already stored MaterialManager is a singleton, only one object of type MaterialManager can exist at any time. You can retrieve the pointer to it by simply calling the GetMaterialManager() method –MaterialManager *matManager=MaterialManager::GetMaterialManager();

MaterialManager (2) Other methods of the MaterialManager that you can use are: –void storeElement(G4String name,G4String symbol,G4double z,G4double a) –G4Element* getElement(G4String symbol); –void storeMaterial(G4String name, G4double z,G4double a, G4double dens) –void storeMaterial(G4String name, G4double density, G4int ncomponents) –G4Material* getMaterial(G4String name) –void addMaterial(G4String name1,G4String name2,G4double fraction) –void addElement(G4String name1, G4String name2, G4double fraction) –void addElement(G4String name1, G4String name2, G4int natoms) –void printMaterialTable() –void printElementTable()

Geometry, once again The geometrical representation of the detector elements focuses on the solid models definition and their spatial position, as well as their logical relations, such as containment Geant4 manages the representation of the detector element properties via the concept of Logical Volume Geant4 manages the representation of the detector element spatial positioning and their logical relation via the concept of Physical Volume Geant4 manages the representation of the detector element solid modeling via the concept of solid The Geant4 solid modeler is STEP compliant. Step is the ISO standard for exchanging geometrical data between CAD systems

G4VSolid G4VSolid is the base class for solids, physical shapes that can be tracked through Costructors and destructor in G4VSolid automatically add/remove a solid to/from the solid store G4VSolid defines but does not implement methods to compute distances to/from the shapes. Functions are also defined to check whether a point is inside the shape, to return the surface normal at a given point and to compute the extent of a shape Protected/private utilities are implemented for the clipping of regions (to calculate the extent of a solid) and for visualization purposes

BREPs BREPs are defined via the description of their boundaries. The boundaries can be made of planar and second order surfaces. The resulting solids are know as Elementary BREPs Boundary surfaces can be made of Bezier surfaces and B-splines, or of NURBS (Non-Uniform Rational B-Splines) surfaces. These solids are Advanced BREPs BREPs solids are defined by creating each surface separately and tying them together. Although it is possible to do this using code, it is much more convenient to use a CAD system Models from a CAD system can be exported utilising the step standard, so BREP solids are normally defined via the use of a STEP reader. Implemented in G4BREPSolid and derived classes

CSGs Apart from those methods needed to create a shape, all CSGs implement a full set of methods for R/W access to the solids dimensions G4Box void SetXHalfLength(G4double)G4double GetXHalfLength() void SetYHalfLength(G4double)G4double GetYHalfLength() void SetZHalfLength(G4double)G4double GetZHalfLength() G4Trd void SetX1HalfLength(G4double)G4double GetX1HalfLength() void SetX2HalfLength(G4double)G4double GetX2HalfLength() void SetY1HalfLength(G4double)G4double GetY1HalfLength() void SetY2HalfLength(G4double)G4double GetY2HalfLength() void SetZHalfLength(G4double)G4double GetZHalfLength()

CSGs (2) These functions are needed for modifying the solid after it has been created –Create a “big” Logical Volume, fill it up with lots of other volumes, recalculate its dimensions, squeeze it to its minimum permitted size Careful! The modification of a solid after it has been assigned to the LV causes the LV, the PV etc… to be modified. Just make sure you have things under control These “modifiers” are used typically in the calculations being made inside the Parameterisations, to modify the solids shape and dimensions (see later)

Logical Volumes (again) The Logical Volume manages the information associated to detector elements represented by a given solid and material, independently from its physical position in the detector A Logical Volume knows what are the physical volumes contained in it and is defined to be their mother volume A Logical Volume can thus represent a full hierarchy of unpositioned volumes in the global reference frame (but with a defined position between themselves) A Logical Volume also manages the information relative to Visualisation attributes and user-defined parameters related to tracking, fields or cuts

Logical Volume constructor G4LogicalVolume ( G4Vsolid* pSolid, G4Material* pMaterial, const G4String& name, G4FieldManager* pFieldMgr=0, G4VSensitiveDetector* pSDetector=0, G4UserLimits* PULimits=0) Where pFieldManager is a pointer to the field (electric or magnetic) implementation pSDetector is a pointer to a Sensitive Detector (to make this volume sensitive and collect the hits PULimitsis a set of user defined cuts (for the tracking into this volume)

Physical Volume types Physical Volumes represent the spatial positioning of the volumes describing the detector elements Several different techniques can be used: –Placement involves the definition of the transformation for the volume to be positioned –Repeated positioning defined by using the nr. ff times a volume should be replicated at a given distance along a given direction –Parameterised volumes defined by describing a parameterised formula to specify the characteristics and positions of multiple copies of a volume

Single positioned copy The physical volume is created by associating a Logical volume with a rotation matrix and a translation vector The rotation matrix represents the rotation of the reference frame of the considered volume relatively to its mother’s reference frame The translation vector represents the translation of the current volume in the reference frame of its mother volume G4PVPlacement (G4RotationMatrix *pRot, // Rotation Matrix const G4ThreeVector &tlate, // Translation Vector const G4String &pName, // Name G4LogicalVolume *pLogical, // Logical Volume G4VPhysicalVolume *pMother, // Mother Vol. (physical!) G4bool pMany, // Not used G4int pCopyNo) // Copy Nr.

Single positioned copy (2) A positioned volume keeps a pointer to the rotation matrix, not a copy of it! If the rotation matrix is re-used and modified, the physical volume will be affected! Boolean operations at the level of Physical Volume (‘MANY’ in G3) are not implemented, so pMany must remain false. An alternative implementation of boolean operations exist for solids, which permits the union, intersection and subtraction of volumes The mother volume must be specified for all volumes, except for the world volume

Single positioned copy (3) An alternative way to specify a Placement utilises a different method to place a volume The solid itself is rotated and translated in order to bring it into the system of coordinates of the mother volume (active method) Where: G4PVPlacement (G4Transform3D solidTransform, const G4String &pName, G4LogicalVolume *pLogical, G4VPhysicalVolume *pMother, G4bool pMany, G4int pCopyNr); G4Transform3D (G4RotationMatrix &pRot, G4ThreeVector &tlate)

Single positioned copy (4) An alternative method is to position the daughter volume into its mother’s Logical Volume Please note the arguments order! G4PVPlacement (G4RotationMatrix *pRot, // Rotation Matrix const G4ThreeVector &tlate, // Translation Vector G4LogicalVolume *pLogical, // Logical Volume const G4String &pName, // Name G4LogicalVolume *pMother, // Mother Vol. (logical!) G4bool pMany, // Not used G4int pCopyNo) // Copy Nr.

Repeated Volumes In this case a single Physical Volume represent multiple copies of a volume within its mother volume, thus allowing to save memory. This is normally done when the volumes to be positioned show a well defined rotational or translation symmetry along a cartesian or cylindrical coordinate The Repeated Volume technique is only available for volumes described by CSG solids –Replica Similar to G3 divisions Very efficient for tracking but cumbersome and limiting –Parameterised Volume Very, very powerful, but be careful...

Replicas Replicas are Repeated Volumes in the case when the multiple copies of the volume to be positioned are all identical The coordinate axis and the number of replicas need to be specified for the program to compute at run time the transformation matrix corresponding to each copy Where: G4PVReplica (const G4String &pName, G4LogicalVolume *pLogical, G4VPhysicalVolume *pMother, const Eaxis pAxis, const G4int nReplicas, const G4double width, const G4double offset=0) pAxis = kXAxis,kYAxis,kZAxis,kRho,kRadial3D,kPHi

replica The aim of the exercise is to define a very simple lead scintillator calorimeter –the calorimeter is a box (already implemented) –its dimensions are given by the variable calo_xside and calo_yside –the thickness of the calorimeter is calculated out of the number of sandwiches one wants to position in, the thickness of the lead plates and the thickness of the scintillator plates –use the MaterialManager to get pointers to the materials needed –use a replica to position the lead-scintillator sandwiches –check, by shooting particles, that everything is correct –optionally, add physics (from ExN04) and the ExN02EventAction and try to generate a shower into the calorimeter

Parameterised Volumes Parameterised Volumes are Repeated Volumes in the case in which the multiple copies of a volume can be different in size, solid type or material The solid’s type, its dimensions, the material and the transformation matrix can all be parameterised in function of the copy number, either when a strong simmetry exist and when it does not The user implements the desired parameterisation function and the program computes and updates automatically at run time the information associated to the Physical Volume

Parameterised Volumes (2) For parameterised volumes one must always specify a mother volume, hence the World volume cannot be parameterised The mother volume can be specified either as a Physical or Logical volume Note that the search axis is just a hint to Geant4 and not a direction along which the parameterisation must take place G4PVParameterised (const G4String& pName,// Name G4LogicalVolume*pLogical,// its logical volume G4VPhysicalVolume*pMother,// it can be G4LogicalVolume const EaxispAxis,// search axis const G4intnReplicas,// nr. of replicate volumes G4VPVParametrisation*pParam);// the parameterisation

An example of Parameterised Volume (N02) // An example of Parameterised volumes // dummy values for G4Box -- modified by parameterised volume G4VSolid *solidChamber = new G4Box(“ChamberBox”,10*cm, 10*cm, 10*cm); G4LogicalVolume *trackerChamberLV = new G4LogicalVolume(solidChamber,Aluminium,”trackerChamberLV”); G4VPVParameterisation *chamberParam= new ExN02ChamberParameterisation( 6,// Nr. Of chambers -240*cm,// Z of the centre of the first 80*cm,// Z spacing of the centres 20*cm,// Width of the chambers 50*cm,// lengthInitial trackerSize/2.);// lengthFinal G4VPhysicalVolume *trackerChamber_phys = new G4PVParameterised ( “tracker chamber PV”,// name trackerChamberLV,// Its logical volume physiTracker,// Mother physical volume kZAxis,// placed along the Z axis 6,// nr. Of chambers chamberParam);// the parameterisation

The Parameterisation The power of parameterised volumes is created by the parameterisation class and its methods Geant4 parameterisations must derive from the G4VPVParameterisation class and implement (at least) two methods: –ComputeTransformation Called with a copy number for the instance of the parameterisation under consideration. It must compute the transformation for this copy and set the physical volume to utilise this transformation –ComputeDimensions Called with the copy number for the instance of the parameterisation. It must define the size of the solid for the volume being considered

An example of Parameterisation (N02) The ComputeTransformation() method set the transformation from a series of predefined parameters class ExN02ChamberParameterisation: public G4VPVParameterisation { ….. void ComputeTransformation (const G4intcopyNo, G4VPhysicalVolume*physVol) const; void ComputeDimensions(G4Box&trackerLayer, const G4intcopyNo, const G4VPhysicalVolume*physVol) const; }; void ExN02ChamberParameterisation::ComputeTransformation(const G4int copyNo, G4VPhysicalVolume* physVol) const { G4double Zposition = fStartZ + copyNo + fSpacing; G4ThreeVector origin(0,0,Zposition); physVol->SetTranslation(origin); G4RotationMatrix* identity=new G4RotationMatrix; // intentional memory leak!! Shoot me!! physVol->setRotation(identity); }

An example of Parameterisation (N02) Similarly the ComputeDimensions() method is used to set the size of that copy Users must make sure that the type of the first argument (G4Box& here) corresponds to the type of the object given to the Logical Volume of parameterised physical volume Void ExN02ChamberParameterisation::ComputeDimensions( G4Box& trackerChamber, const G4int copyNo, const G4VPhysicalVolume* physVol) const { G4double halfLength= fHalfLengthFirst + (copyNo-1) * fHalfLengthIncr; trackerChamber.SetXHalfLength(halfLength); trackerChamber.SetYHalfLength(halfLength); trackerChamber.SetZHalfLength(fHalfWidth); }

Parameterised Volumes (3) Advanced usage of Parameterised Volumes permits also: –to change the type of solid by creating a ComputeSolid() method –to change the material of the volume by creating a ComputeMaterial() method Very complex geometry descriptions can be achieved using a single (although complicated) parameterisation –who will be the first trying to describe the whole Atlas geometry with a single parameterisation? The Compute… methods are executed at every step, hence: –make the algorithmic part as simple and as fast as possible –beware of memory leaks!!!!! Currently, for many cases it is not possible to add daughter volumes to a parameterised volume (use them as “leaf” volumes)

parameterisation The aim of the exercise is again to build a lead-scintillator calorimeter, this time though the calorimeter will be a trapezoid (wedge) and one must position scintillator plates into it made out of boxes use the parameterisation which is already provided (ParameterisedScintillator.hh), figure out how many parameters do you need for doing the job, fill up the ComputeTransformation() and ComputeSolid()

Touchables

Touchable Volumes provide a way of uniquely identifying a detector element in the geometrical hierarchy –for navigating in the geometry tree for storing hits –for providing a geometry description alternative to the one used by the Geant4 tracking system –for parameterised geometries A touchable is a geometrical volume (solid) which has a unique placement in a detector description In Geant4, touchables are implemented as solids associated to a transformation matrix in the global reference system or as a hierarchy of physical volumes

G4VTouchable All G4VTouchable implementations must respond to at least two requests: –GetTranslation() and GetRotation() that return the components and the volume’s transformation –GetSolid() that gives the solid associated to the touchable additional requests can be satisfied by touchables keeping a physical volume –GetVolume() which returns a physical volume –GetReplicaNumber() which returns the copy nr. (if set) Touchables that store a complete stack of parent volumes, thus it is possible to add more functionality –GetHistoryDepth() to retrieve how many levels are there in the tree –MoveUpHistory(n) allows to navigate in the tree

Touchable History A logical volume represents unpositioned detector elements, even a physical volume can represent multiple detector elements Touchables provide a unique identification for a detector element –Transportation and tracking exploit the implementation of touchables implemented via the TouchableHistory TouchableHistory is the minimal set of information required to build the full genealogy on top of a given physical volume up to the root of the geometrical tree Touchables are made available to the user at every step during tracking by means of a G4Step object

Touchable History (2) To create a G4TouchableHistory you must ask the navigator –G4TouchableHistory* CreateTouchableHistory() const; to navigate in the geometrical tree you can use –G4int GetHistoryDepth() const; –G4int MoveUpHistory(G4int num_levels=1); The first method tells you how many level deep in the current tree the volume is, the second asks the touchable to eliminate its deepest level The MoveUpHistory significantly modifies the state of the touchable

Hits

G4Step The information about what happened in the last step can be gathered from an object of type G4Step, for instance in the stepping action –pointers to PreStep and PostStepPoint –Geometrical step length –True step length –delta of position/time between PreStep and PostStepPoint –Delta of momentum/energy between PreStep and PostStepPoint –pointer to a G4Track –Total energy deposited during the step. This is the sum of: Energy deposited by energy loss process Energy loss by secondaries which have not been generated because their energies were below the cut threshold

G4Step (2) The information in G4StepPoint (PreStep and PostStepPoint) is: –(x,y,z,t) –(px,py,pz,Ek) –momentum direction –Pointers to the physical volumes –Safety –Beta, Gamma –Polarization –Step status –Pointer to the physics process for the current step –Pointer to the physics process for the previous step –Total track length –Global time –Local time –Proper time

calorimeter (1) Example based on the Replica example (10x10 cells this time, in an array) compile the example, verify that it works add a stepping action (get it from the calorimeter/util directory) print out the G4Step contents, step by step (but use a geantino!!!) get the physical volume –astep->GetPreStepPoint()->GetPhysicalVolume(); go back to the logical volume by using the physical volume methods (have a look to the G4PhysicalVolume definition to discover how to do it), get its name, its material...

calorimeter (1) Get the TouchableHistory –(G4TouchableHistory*)(aStep->GetPreStepPoint()->GetTouchable() get the scintillator identifier and the cell nr. by navigating through the TouchableHistory calculate the amount of energy lost in the scintillator, the thickness in r.l. of the calorimeter, whatever you want… in calorimeter/util there is an HBookManager for helping you with histograms (Hbook), use it!

Hit A Hit is a snapshot of a physical interaction of a track in a sensitive region of the detector One can store various informations associated with a G4Step object, like: –Position and time of the step –momentum of the track –energy deposition of the step –geometrical information

G4VHit G4VHit is an abstract class which represents a hit The User has to inherit from this base class and derive his/her own concrete class The data members in particulare (I.e. the information that the hit will carry along) must be chosen by the user G4VHit has two virtual methods, Draw() and Print() which must be implemented to hae the hits drawn and printed Hits are associated to the current event by means of a concrete class derived from G4VHitsCollection, which represents a vector of user-defined hits G4THitsCollection is a template class derived from G4VHitsCollection which can contain a particular concrete class derived from G4VHit

ExN04TrackerHit #ifndef ExN04TrackerHit_h #define ExN04TrackerHit_h #include “G4VHit.hh” #include “G4THitsCollection.hh” #include “G4ThreeVector.hh” class ExN04TrackerHit: public G4VHit { public: ExN04TrackerHit(); ~ExN04TrackerHit(); ExN04TrackerHit(const ExN04TrackerHit &right); const ExN04TrackerHit& operator=(const ExN04TrackerHit &right); int operator==(const ExN04TrackerHit &right) const; void Draw() const; void Print() const; private: G4double edep; G4ThreeVector pos;

ExN04TrackerHit (2) public: inline void SetEdep(G4double de) {edep=de;} inline G4double GetEdep() const {return edep;} inline void SetPos(G4ThreeVector xyz) {pos=xyz;} inline G4ThreeVector GetPos() const {return pos;} }; #endif

G4VSensitiveDetector G4VSensitiveDetector is an abstract base class which represents a detector The principal mandate of a sensitive detector is the construction of one or more hit objects using the information given in the G4Step object and an optional G4TouchableHistory class object for the ReadOut geometry: these object are the arguments of the method ProcessHits() The concrete sensitive detector class should be instanciated with the unique name of a detector. The name can be associated with one or more global names for categorizing the detectors myEMcal = new myEMcal(“/myDet/myCal/myEMcal”); The pointer to the sensitive detector must be set to one or more G4LogicalVolume object and registered with G4SDManager

G4VSensitiveDetector (2) G4VSensitiveDetector has three major virtual methods: –Initialize() This method is invoked at the beginning of each event. The argument of this method is an object of G4HCofThisEvent class. Hits collections, where hits produced in this particular event are stored, can be associated to G4HCofThisEvent –ProcessHits() This method is invoked by G4SteppingManager when a step takes place in the G4LogicalVolume which point to this sensitive detector. The first argument of this method is a G4Step object for the current step. The second argument is a G4TouchableHistory object for the ReadOut geometry, if described. In this method, one or more G4VHit objects should be constructed if the current step has to be registered –EndOfEvent() This method is invoked at the end of each event, again to associate hits collections to G4HCofThisEvent

ReadOut Geometry The ReadOut geometry is a virtual, parallel geometry which can be used for describing the read-out configuration of the detector –The accordion calorimeter has a very complicated geometry. However, the readout will be performed by grouping electrodes together to form cells which can be described with a much simpler geometry Tracks will be traced in the tracking geometry (the real oneand the sensitive detector will have its own geometry that Geant4 will message to find out which “readout” cell the current hit belongs to The Sensitive Detector will be associated to the tracking geometry in the normal way. Then, an object of type G4VReadoutGeometry will be associated to the sensitive detector

ReadOut Geometry (2) At tracking time, the class G4VReadoutGeometry will provide the sensitive detector with the G4TouchableHistory in the readout geometry at the beginning of the step, and at this position only The G4TouchableHistory object is given to the sensitive detector code by means of the G4VSensitiveDetector method: G4bool processHits(G4Step *aStep, G4TouchableHistory *Rohist) in this way, one can make use at the same time of the information coming from the step (G4Step) and from the readout geometry (via the G4TouchableHistory) Since the association is done through a sensitive detector object, it is possible to have several RO geometries in parallel

Definition of a virtual geometry setup The base class for the implementation of a readout geometry is G4VReadoutGeometry. This class has a pure virtual method: virtual G4VPhysicalVolume* build()=0; which one must define in the concrete class, in order to return the physical World volume for the readout geometry The step-by-step procedure for constructing a readout geometry is the following: –inherit from G4VReadoutGeometry to define a “MyROGeom” class –implement the RO geometry in the build() method, returning the physical World volume fom this geometry in this geometry you have to declare the sensitive parts in the same way as in the tracking geometry; the pointer to the sensitive detector needs to be there but it willnot be used. You will have to use well defined materials for describing the volumes, but these will not be seen by tracking

Definition of a virtual geometry setup (2) –In the construct() method of the concrete G4VUserDetectorConstruction class you must instanciate the readout geometry: MyROGeom *ROGeom = new MyROGeom(“ROName”); build it: ROGeom->build(); Instanciate the sensitive detector which will receive the ROGeom pointer, MySensitive, and add this sensitive detector to the G4SDManager. Associate this sensitive detector to the volume(s) of the tracking as usual. Associate the readout geometry to the sensitive detector MySensitive->set_ROGeometry(ROGeom);

Access to the hits collections Hits collections are accessed for various purposes –Digitization –Event Filtering in G4VUserStackingAction –“End of Event” simple analysis –Drawing/printing hits To access the hits collections one must go through the SD Manager G4SDManager* fSDM=G4SDManager::GetSDMpointer(); G4RunManager* fRM=G4RunManager::GetRunManager(); G4int collectionID=fSDM->GetCollectionID(“collection name”); const G4Event* currentEvent=fRM->GetCurrentEvent(); G4HCofThisEvent *HCofEvent=currentEvent->GetHCofThisEvent(); MyHitsCollection *myCollection= (MyHitsCollection *)(HCofEvent->GetHC(collectionID));

calorimeter (2) Create a sensitive detector in the detector construction and assign it to the scintillator logical volume G4SDManager *sdman=G4SDManager::GetSDMpointer(); CalorimeterSensitiveDetector *CaloSd= new CalorimeterSensitiveDetector(“Calorimeter”); sdman->AddSensitiveDetector(CaloSd); scin_log->SetSensitiveDetector(CaloSD) See that you can accumulate energy from within the ProcessHits method of the sensitive detector create hits from within the ProcessHits() method –CalorimeterHit* caloHit=new CalorimeterHit(CellID,ScinID,e); create a hit collection by booking a name in the constructor of the sensitive detector

calorimeter (2) collectionName.insert(“CalorimeterCollection”); …and by creating the collection in the Initialize method of the sensitive detector caloHitsCollection=new CalorimeterHitsCollection (SensitiveDetectorName,collectionName[0]); insert the hits in the collection –int icell=caloHitsCollection->insert(caloHit); insert the collection in the hits collections of the event static G4int HCID=-1; if (HCID<0) HCID=GetCollectionID(0); HCE->AddHitsCollection(HCID,caloHitsCollection);

Run and Event

G4Run and G4RunManager In Geant4, the Run is the largest unit of simulation and it consist of a series of events Within a Run, the detector geometry, the setup of the sensitive detectors and the physics processes cannot be modified A Run is represented by an object of the G4Run class A Run begins when the beamOn() method of the G4RunManager class is invoked

G4Run G4Run contains a run identification number which should be set by the user and the number of events to be simulated during that Run The Run identification number is not used by the Geant4 kernel and it is then an arbitrary number which is provided for the convenience of the user G4Run contains pointers to the name tables of G4VHitsCollection’s and G4VDigiCollection’s which are associated in case Sensitive Detectors and Digitizers are implemented

G4RunManager The G4RunManager class manages the procedures of a run. In the G4RunManagerConstructor, all the Geant4 manager classes are constructed. These managers are then deleted in the G4RunManager destructor G4RunManager is a singleton, only one run manager can exist throughout the whole program. A pointer to this object can be obtained by invoking the G4RunManager’s method GetRunManager() All user initialization classes and user action classes should be assigned to G4RunManager before the initialization of the Geant4 kernel by using the SetUserInitialization() and the SetUserAction() methods

G4RunManager’s public methods Initialize() –construction of the detector geometry and setup of the sensitive detectors/digitizers –construction of particles and physics processes –calculation of cross-section tables beamOn(G4int numberOfEvents) –triggers the actual simulation of a run (event loop). It takes an integer argument, the number of events to be simulated GetRunManager() –returns the pointer to the G4RunManager singleton object GetCurrentEvent() –returns a pointer to the G4Event object currently being simulated. This method is only available while events are being produced (EventProc state). A const pointer is returned (read-only)

G4RunManager’s public methods (2) SetNumberOfEventsToBeStored(G4int nPrevious) –For the case of piling up more than one event, it is essential to access more than one event at the same moment. By invoking this method, G4RunManager keeps nPrevious G4Event objects in memory. This method must be invoked before beamOn() GetPreviousEvent(G4int i_thPrevious) –Returns a pointer to the i_thPrevious G4Event object stored. The pointer returned is const, hence the G4Event returned cannot be modified

G4UserRunAction G4UserRunAction is one of the user action classes one can derive his/her concrete class from The G4UserRunAction class has two virtual methods the user must implement –BeginOfRunAction() invoked at the beginning of the beamOn() method but after confirming the conditions of the Geant4 kernel. To be used for setting the run identification number, book histograms, setup run-specific conditions, etc.. –EndOfRunAction() invoked at the very end of the beamOn() method. It can be used to store histograms, manipulate run summaries, etc...

Geant4 is a state machine Geant4 is designed as a state machine. Certain methods are only available in certain states. G4RunManager controls the state changes. –PreInit state The application starts in this state. Geant4 need to be initialized. The application comes back to this state if geometry, physics or cut-off have been modified –Init state G4RunManager initialize() is being invoked –Idle state The application is ready to process a run –GeomClosed state beamOn() has been invoked –EventProc state An event is being processed. GetCurrentEvent() and GetPreviousEvent() are only available at this state –Quit state G4RunManager’s destructor has been invoked. The application is dead

Aborting a run To abort a Geant4 run being processed (for whichever reason) the AbortRun() method of G4RunManager must be invoked AbortRun() is only available in the GeomClosed and EventProc states AbortRun() safely stops the run processing even when a particular event is being simulated The last event of the aborted run is incomplete and it should not be used for further analysis

Customizing G4RunManager G4RunManager, still being a concrete class, has a complete set of virtual functions. The user may decide to inherit his/her own manager class and re- implement part or most of the functionality of the G4RunManager public: virtual void initialize();main entry point of GEANT4 kernel initialization virtual void DefineWorldVolume(G4VPhysicalVolume * worldVol); Set the world volume to G4Navigator virtual void AbortRun(); Run abortion virtual void beamOn(G4int n_event)main entry point of the event loop protected: virtual void InitializeGeometry(); Geometry construction virtual void InitializePhysics();physics processes construction virtual void InitializeCutOff();Build cross-section tables virtual G4bool ConfirmBeamOnCondition(); Check the kernel conditions for the event loop virtual void RunInitialization();Prepare a run virtual void DoEventLoop(G4int n_events);Manage an event loop virtual G4Event* GenerateEvent(G4int i_event); Generation of G4Event object virtual void AnalyzeEvent(G4Event* anEvent); Storage/analysis of an event virtual void RunTermination(); Terminate a run

Changing the detector geometry The detector geometry defined in G4VUserDetectorConstruction class can be changed during the run break (between two runs) –In the case one wants to delete the entire structure and set up a completely new structure, one has to register the new World volume with G4RunManager –More likely, one may want to modify his/her geometry only slightly (e.g. rotate a testbeam setup wrt the beam line or modify the thickness of the active layers of a calorimeter). This action does generally not require a complete redefinition of the geometry and can normally be implemented by calling some function at the beginning of each run. In any case, G4RunManager must be notified that the geometry must be re-built G4RunManager* runManager = G4RunManager::GetRunManager(); MyNewGeometry newGeometry; G4VPhysicalVolume* newWorldPhys=newGeometry.Construct(); runManager->DefineWorldVolume(newWorldPhys); runManager->GeometryHasBeenModified()

Events An Event in Geant4 is represented by the class G4Event, which contains all quantities needed to characterize the simulated event A G4Event object is constructed by the G4RunManager and sent to the G4EventManager The event being processed can be gotten at any moment by means of the GetCurrentEvent() method of G4RunManager

G4Event An G4Event object contains four major pieces of information which are available via get methods –Primary vertexes and primary particles –Trajectories Stored in an object of type G4TrajectoryContainer, which can can be accessed from G4Event –Hits collections Generated by Sensitive Detectors, they are kept in an object of type G4HCofThisEvent, whose pointer is kept in G4Event –Digits collections Generated by Digitizers, they are kept in an object of type G4DCofThisEvent, whose pointer is kept by G4Event

G4EventManager G4EventManager is the manager class which takes care of the Event. Its main tasks are –to convert G4PrimaryVertex and G4PrimaryParticle objects associated with the current G4Event object to G4Track objects. All G4Track objects are sent to G4StackManager –Pop one track object from G4StackManager and send it to G4TrackingManager. The current G4Track object is deleted by G4EventManager after the track is simulated by G4TrackingManager, if the track is marked as “killed” –In case the primary track is “suspended” or “postponed to the next event”, it is sent back to the G4StackManager. Secondary G4Track object returned by G4TrackingManager are also sent to G4StackManager –When G4StackManager returns NULL to the pop request, G4EventManager terminates the current event processing

G4UserEventAction G4UserEventAction is one of the user action classes G4UserEventAction has two virtual method which are invoked for each event and which can be implemented by the user –BeginOfEventAction() Invoked before converting the primary particles to G4Track objects. Used for initialization and/or histogram booking for one particular event –EndOfEventAction() Invoked at the very end of the event processing. Used for simple analysis of the current event