# Presentation: 149091

## A Hands-on introduction to Geant4

- Andrea Dell’Acqua
- CERN-EP/ATC
- dellacqu@mail.cern.ch

## 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
- Visualization Attributes

- Slides at http://home.cern.ch/ada/course/monday/index.htm

## 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 4.0.1 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:
- http://wwwinfo.cern.ch/asd/geant4/geant4.html
- 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
- 4.0.1 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

- http://wwwinfo.cern.ch/asd/geant4/geant4.html
- 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

- http://home.cern.ch/rimoldi/g4simulation/geant4.html

## 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-xlC			AIX 4.3, xlC set for AIX (default)
- SUN-CC		SunOS 5.6, CC 4.2
- HP-aCC			HP/UX 10.20, aCC A.01.09
- SGI-CC			SGI-IRIX 6.2, C++ 7.2
- DEC-cxx		DEC-OSF/1 4.0, DEC C++
- Linux-g++		Linux (RH 5.1), egcs 1.1
- WIN32-VC-NICE	NiceNT and MSVC++ 5.0, installed
- 			locally together with CYGWIN32
- WIN32-G++-NICE	NiceNT 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 0 10 30 cm
- /gun/direction .3 .3 .1
- 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

- 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);