7.  Python Interface

Python is a popular scripting language with an interactive interpreter. Geant4Py, a Geant4-Python bridge, provides a bridge for Geant4 classes. This enables to directly access Geant4 classes from Python scripting. User applications can be easily configured with many Python third-party modules, such as PyROOT, on the Python software bus.

Geant4Py is supplied in the directory environments/g4py/ of the Geant4 source package.

7.1.  Installation

7.1.1.  Software Requirements

Geant4Py requires the Boost-C++ external library, which helps Python binding of C++ codes.

7.1.2.  Building Geant4Py module

Geant4Py provides a configure script for building modules.

`configure' configures Geant4Py to adapt to many kinds of systems.

Usage:  ./configure SYSTEM [OPTION]... [VAR=VALUE]...

SYSTEM: System type (see Supported Arhitectures)

Options:
  -h, --help                Display this help and exit

Installation directories:
  --prefix=PREFIX           Installation prefix  [./]
  --libdir=DIR              Python modules dir [PREFIX/lib]

Fine tuning of the library path:
  --with-g4install-dir=DIR  Geant4 installed dir

  --with-python-incdir=DIR  Python header dir [/usr/include/python(2.#)],
                            (location of pyconfig.h)
  --with-python-libdir=DIR  Python library dir [/usr/lib(64)]
  --with-python3            Use Python3

  --with-boost-incdir=DIR   BOOST-C++ header dir [/usr/include],
                            (location of boost/)
  --with-boost-libdir=DIR   BOOST-C++ library dir [/usr/lib]
  --with-boost-python-lib=LIB library name of libboost_python.so [boost_python]

  --with-extra-dir=DIR      Install path for extra packages [/usr/local]

  --with-xercesc-incdir=DIR Xerces-C header dir [/usr/include]
  --with-xercesc-libdir=DIR Xerces-C library dir [/usr/lib(64)]

Enable/disable options: prefix with either --enable- or --disable-
  openglx      OpenGLX support    [auto]
  openglxm     OpenGLXm support   [disable]
  raytracerx   RayTracerX support [disable]

Supported Architectures:
  linux           for Linux gcc (32bit)
  linux64         for Linux gcc (64bit)
  linuxx8664gcc   for Linux gcc (64bit)
  macosx          for Apple OS X with gcc

For example, you run it like

  # ./configure linux64 -with-g4install-dir=[geant4 install path with CMake]

The configure script automatically check your environment, and create config/config.gmk, which describes your envrionment. After executing the configure script successfully, then

# make
# make install

7.2.  Using Geant4Py

PYTHONPATH environment variable should be set at tun time. PYTHONPATH environment variable indicates Python module search directories, given by a colon-separated list of directories. Practically, the variable is (your g4py directory)/lib.

7.2.1.  Import Geant4

To use Geant4Py, you start with importing the module called "Geant4".

# python
Python 2.6.2 (r262:71600, Oct 24 2009, 03:15:21)
[GCC 4.4.1 [gcc-4_4-branch revision 150839]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from Geant4 import *

*************************************************************
 Geant4 version Name: geant4-09-03         (18-December-2009)
                      Copyright : Geant4 Collaboration
                      Reference : NIM A 506 (2003), 250-303
                            WWW : http://cern.ch/geant4
*************************************************************

Visualization Manager instantiating...
>>>

7.2.2.  Access to Geant4 Globals

When importing the Geant4 module, the G4RunManager object will be automatically instantiated. Geant4 singleton objects are also automatically instantiated. These singleton objects can be accessed by "gXXXX" variables, like "gRunManager".

                        gLossTableManager       gTerminate
gApplyUICommand         gMaterialTable          gTrackingManager
gControlExecute         gNistManager            gTransportationManager
gElementTable           gParticleIterator       gUImanager
gEmCalculator           gParticleTable          gVisManager
gEventManager           gProcessTable
gExceptionHandler       gProductionCutsTable
gG4Date                 gRunManager
gG4VERSION_NUMBER       gRunManagerKernel
gG4Version              gStackManager
gGeometryManager        gStartUISession
gGetCurrentValues       gStateManager

7.2.3.  Call Geant4 Methods

Once a Python object of a Geant4 class instantiated, Geant4 methods can be directly called the same way as in C++.

>>> from Geant4 import *

*************************************************************
 Geant4 version Name: geant4-09-03         (18-December-2009)
                      Copyright : Geant4 Collaboration
                      Reference : NIM A 506 (2003), 250-303
                            WWW : http://cern.ch/geant4
*************************************************************

Visualization Manager instantiating...

>>> print gRunManager.GetVersionString()
 Geant4 version Name: geant4-09-03    (18-December-2009)

7.3.  Site-modules

Geant4Py provides additional utility modules called "g4py" in the directory site-modules. It consists of predifined geometries, materials, physics lists, primary generator actions, and so on.

7.3.1.  ezgeom module

The ezgeom module provides an alternative way of defining simple geometry. An example code for defining a simple geometry is shown here:

import g4py.ezgeom
from g4py.ezgeom import G4EzVolume

def ConstructGeom():
  print "* Constructing geometry..."
  # reset world material
  air= G4Material.GetMaterial("G4_AIR")
  g4py.ezgeom.SetWorldMaterial(air)

  # a target box is placed
  global target
  target= G4EzVolume("Target")
  au= G4Material.GetMaterial("G4_Au")
  target.CreateTubeVolume(au, 0., 1.*cm, 1.*mm)
  target.PlaceIt(G4ThreeVector(0.,0.,-10.*cm))

7.3.2.  NISTmaterials module

The NISTmaterials module provides an instant use of Geant4 NIST materials. An example code for creating NIST materials:

from Geant4 import *
import g4py.NISTmaterials

g4py.NISTmaterials.Construct()
print Geant4.gMaterialTable

7.3.3.  ParticleGun module

The ParticleGun module provides a primary generator action with G4ParticleGun. An example code is shown here:

import g4py.ParticleGun

# normal way for constructing user primary generator action
#pgPGA= g4py.ParticleGun.ParticleGunAction()
#gRunManager.SetUserAction(pgPGA)
#pg= pgPGA.GetParticleGun()

# 2nd way, short-cut way
pg= g4py.ParticleGun.Construct()

# set parameters of particle gun
pg.SetParticleByName("e-")
pg.SetParticleEnergy(300.*MeV)
primary_position= G4ThreeVector(0.,0., -14.9*cm)
primary_direction= G4ThreeVector(0.2, 0., 1.)
pg.SetParticlePosition(primary_position)
pg.SetParticleMomentumDirection(primary_direction)

7.4.  Examples

There are some examples of Geant4Py in the directories "tests/" and "examples/".

In the "tests/" directory,
gtest01 : exposes a user application
gtest02 : test for using site-module packages
gtest03 : test for ezgeom package
gtest04 : test for getting command tree and command information
gtest05 : test for constructing CSG geometries in Python
gtest06 : test for constructing/visualizing boolean geoemtries
gtest07 : test for checking overlapped geometries
The "examples/" directory contains a set of examples of Geant4Py.
demos/water_phantom

An example of "water phantom dosimetry". This demo program shows that a Geant4 application well coworks with Root on Python front end. VisManager, PrimaryGeneratorAction, UserAction-s, histogramming with Root are implemented in Python;

  • dose calculation in a water phantom
  • Python overloading of user actions
  • on-line histogramming with Root
  • visualization

education

Educational examples with Graphical User Interface using TKinter

* lesson1

The first version of the courseware of the mass attenuation coefficient.

* lesson2

GUI interface of ExN03, which can control geometry configuration, intial particle condition, physics processes, cut value, magnetic field and visualization outputs.

emplot

Examples of plotting photon cross sections and stopping powers with Root.

gdml

Examples of writing/reading user's geometry to/from a GDML file