Detector simulation general note

From Hall A Wiki
Revision as of 19:04, 15 February 2021 by Zwzhao (Talk | contribs) (built in type "flux")

Jump to: navigation, search


This is a general description how to use GEMC to do Geant4 simulation

  • How it works
    • Geometry,material,mirror,hit processing including hit and bank definition are all external for GEMC. This allows simulate any detector without recompiling GEMC. They are defined in Delimiter-separated_values format and can be stored in simple text file or in a database. They are produced by a set of perl scripts and config files
    • parameters used to defined a detector are in Delimiter-separated_values format and can be stored in simple text file or in a database also. They can be edited by hand.
    • The hit process routine as a part of hit processing needs be defined in source code and compiled with GEMC as a library to form a final binary code.


GEMC tries to be a wrapper around Geant4, you need to know some basic of geant4, refer to Geant4 like here

Documentation on GEMC website

Introductory talks

[1] Zhiwen Zhao, 2015/03/26
[2] Zhiwen Zhao, 2015/09/11
[3] Maurizio Ungaro,2015/09/24


example of full detector including many subsystems


example of a standalone simulation

This is an example of SoLID EC simulation with customized hit processing. It's ready to be included into full SoLID simulation without any change needed

refer to the general information about standalone simulation for SoLID here

detector description files are at
Here is how to build this simulation
first source env like this one
edit solid_PVDIS_ec_forwardangle__parameters_Original.txt to modify parameter
edit to modify geometry
edit to modify material
edit to modify bank
edit to modify hit
edit * to modify mirror (not applicable to this EC simulation)
edit to include all other perl script
edit config_solid_PVDIS_ec_forwardangle.dat to make sure detector name is correct
run "./ config_solid_PVDIS_ec_forwardangle.dat" to generate all text files
edit $SoLID_GEMC/source/$GEMC_VERSION/hitprocess/ like [this one to match entries in
recompile solid_gemc by "cd $SoLID_GEMC/source/$GEMC_VERSION" and "scons OPT=1"
Then you can run simulation according to

building simulation

introduction and format

By building simulation, it means building the experiment setup in simulation.

It includes defining geometry with material or mirror property and choosing which geometry be sensitive to record output with what kind of hit processing

All things including geometry,material,mirror,bank,hit are defined in a table format with fixed entries.

It can be stored first in a txt file, then user can choose to put it into a table in a database. GEMC can read both txt file and database as input

GEMC uses a set of perl tools to generate the text file, but it can be edit directly by hand

Only the hit process routine is in C++ code, which will be compiled and linked to GEMC library.


an example here [4]

There is no general perl script to produce it yet, just edit by hand

use "our %parameters = get_parameters(%configuration);" in [5] so that the parameters can be called and used in [6]


define it


See geometry tutorial on GEMC website. [7]

The final answer to all questions are in the source code building geometries ""

  • Here are entry names and an example
 name  | mother | description  | pos  | rotation  | color  | Type  | dimensions  | material  | mfield  | ncopy | pMany | exist | visible  | style  |  sensitivity | hit_type | identifiers
meic_det1_rich_detector_holder  | root  |meic_det1_rich_detector_holder  |  0*mm 0*mm 0*mm  |  0*deg 0*deg 0*deg  | ffffff   |  Box  | 56.25*mm 56.25*mm 12*mm  |  Air_Opt  |  no  |     1   |     1   |     1   |   1   |   0   |    no  |  no  | no 
 name           name of the volume
 mother         name of its mother volume, has to be existing one or "root" which is a big box with certain size built in GEMC
 description    description of the volume, doesn't have impact on actual simulation
 pos            position relative to mother in x y z
 rotation       rotation relative to mother along axis of x y z
 color          HEX color coding, refer to and
 type           geant4 solids name
 dimensions     geant4 solids dimensions
 material       geant4 defined material or GEMC built-in material or your customized material
 mfield         local magnet field file name only applies to the volume
 ncopy          copy number
 pMany          0 or false, not used by geant4 yet at G4PVPlacement
 exist          1 or 0, active it or not in simulation
 visible        1 or 0, view it or not in graphic mode 
 style          1 or 0, display it by solid or wire frame in graphic mode
 sensitivity    "no", means not sensitive and hit_type and identifiers will be ignored; any string not "no", means sensitive (can just put same string like hit_type)
 hit_type       hit_type name string, its hit type defined by hit process routine if it's sensitive, can put "no" if no use
 identifiers    its identifiers string, its identifiers if it's sensitive, can put "no" if no use
  • The mother volume of all is called "root" which is a big box with customized size at run time
  • rotation is defined by rotating frame instead of object, so add a minus sign if you are thinking about rotating object

see more details below

define type and dimensions

  • Polycons (PCON) type, its parameter arrangement are little different from G4Polycone, it's "StartPhi,DeltaPhi,n*counts, rmin1,rmin2,...rminn,rmax1,rmax2,...rmaxn,z1,z2,...zn" in GEMC
In standard Geant4 source code
G4double StartPhi=0;
G4double DeltaPhi=360;
G4double poly_z[2] = {0*mm, 1.*mm};
G4double poly_rmin[2] = {40.0*mm, 40.0*mm};
G4double poly_rmax[2] = {50.0*mm, 40.001*mm};
G4Polycone *solidGroove1 = new G4Polycone("Groove1",StartPhi,DeltaPhi, 2, poly_z, poly_rmin, poly_rmax);
In GEMC perl script
$detector{"type"}       = "Polycone";
$detector{"dimensions"} = "0*deg 360*deg 2*counts 40*mm 40*mm 50*mm 40.001*mm 0*mm 1*mm";
  • Polyhedra (PGON) type, its parameter arrangement are little different from G4Polyhedra, it's "StartPhi,DeltaPhi,numSide*counts,numZPlanes*counts,rmin1,rmin2,...rminn,rmax1,rmax2,...rmaxn,z1,z2,...zn" in GEMC
In standard Geant4 source code
G4double StartPhi=0;
G4double DeltaPhi=360;
G4double poly_z[2] = {0*mm, 1.*mm};
G4double poly_rmin[2] = {40.0*mm, 40.0*mm}; //this is inner radius of polyhedron side line, not corner 
G4double poly_rmax[2] = {50.0*mm, 40.001*mm}; //this is inner radius of polyhedron side line, not corner
G4Polycone *solidGroove1 = new G4Polyhedra("Groove1",StartPhi,DeltaPhi,6, 2, poly_z, poly_rmin, poly_rmax);
In GEMC perl script
$detector{"type"}       = "Pgon";
$detector{"dimensions"} = "0*deg 360*deg 6*counts 2*counts 40*mm 40*mm 50*mm 40.001*mm 0*mm 1*mm";
  • geant4 volume boolean operation in gemc
1. On the "type" you can put : "operation:  volumeA + VolumeB","operation:  volumeA - VolumeB","operation:  volumeA * VolumeB" or "operation:@  volumeA + VolumeB","operation:@  volumeA - VolumeB","operation:@  volumeA * VolumeB" where "@" means that position of second object is given in the common mother volume of both objects
2. Define the volume A and B's material as "Component", so that these volumes won't be built
3. See examples in the
  • geant4 volume copy in gemc
1. On the "type" you can put: "CopyOf volumeA"
2. See examples in [8][9]

link material

  • empty materiel "" field can be filled with run time option
 > Option DEFAULT_MATERIAL: Default material for missing material field
  • the hall "root" material can be set as run time
 > Option HALL_MATERIAL: Composition of the Experimental Hall. 
           Air normal simulation
           Air_Opt Simulation with Optical Physics (default)
  • total absorber, "Kryptonite". Anything touching it will be killed.
(It ends the track in step action, but because the physics comes in before step action. so it could still in principal have  
secondary which are very close the primary particles. use mother pid "mpid" in true info to veto them. Kryptonite is 
realized in code as a very very low density material, so now the secondary is almost impossible. Another thing to 
note is the hit in a detector made of "Kryptonite" can be at the detector front or back on track path)

link local magnetic field

local magnetic field to the geometry is defined by "mfield"

It uses the same field map file like the global field which is defined in running option "HALL_FIELD"

It lives within the geometry or its field map, whichever is smaller

all daughter geometry will inherent mother field

link sensitivity

This is closely linked to hit processing

 For a non-sensitive geometry
 $detector{"sensitivity"} = "no";
 $detector{"hit_type"}    = "no";
 $detector{"identifiers"} = "no";
 For a sensitive geometry using built-in "flux" hit processing
 $detector{"sensitivity"} = "flux";
 $detector{"hit_type"}    = "flux";
 $detector{"identifiers"} = "id manual 1"; // for flux, a simple and unique integer called id is used to identify the geometry
 For a sensitive geometry using a customized "wire" hit processing as an example
 $detector{"sensitivity"} = "wire";   // match name in "wire" hit and bank definition
 $detector{"hit_type"}    = "wire";   // match name in "wire" customized hit and bank definition
 $detector{"identifiers"} = "sector ncopy 0 stack manual 3 view manual 6 strip manual 36"; 
 // match "identifiers" defined in "wire" hit definition, 
 //"ncopy 0" means number will be filled at run time, "manual" mean a number explicit here
 "identifier" has to be unique for any geometry, otherwise, hits can be averaged over different geometry and give nonphysical result

link mirror

If a volume is a mirror, we use sensitivity for now to link to its reflectivity in mirror defined here Detector_simulation_general_note#mirror

  $detector{"sensitivity"} = "mirror: SL_HGC_mirror";
  $detector{"hit_type"}    = "mirror";

check overlap

  • volume overlap will cause gemc to crash after beam on. You can check it with
   GEMC Option CHECK_OVERLAPS: Checks Overlapping Volumes:
     1.  Check Overlaps at Construction Time
     2.  Check Overlaps based on standard lines grid setup
     3.  Check Overlaps by shooting lines according to a cylindrical pattern

please note the option to check overlap only work in batch mode, NOT in graphic mode. This means it need to run with option "USE_GUI=0"

if you want a "envelope volume" to enclose some geometry (eg. a EC volume with vacuum to enclose all parts of calorimeter), you can do that. then you can set those envelope volumes' mother volume as "root". One catch here is that those envelope volume overlap won't cause crash if they are not sensitive. However gemc tracking will totally messed up if they overlap. Basically, gemc can't take any volume overlap and this is also true for geant4. So please try to avoid overlap in design.

convert geometry file from GEMC 1 to GEMC 2 format

The changes are small and here is a summary

1. header changes because IO engine changes
2. add "my %detector=init_det();" 
3. replace "print_det(\%detector, $file);" with "print_det(\%configuration, \%detector);"
4. doesn't allow "" entry anymore, you can put "no" instead
5. only lower case "flux" works, "FLUX" won't
6. add "*counts" for any pure number in "dimensions"

easy to see by comparing a old file and new file


field is defined in map file with name like field_name.dat

It's a text file including a header and the actual map

Its coordinate is absolute and in the same lab frame of the detector

see examples at


See material tutorial on GEMC website.

materials are defined by its density,composition,optical properties, see example here


See mirror tutorial on GEMC website.

mirror is defined by its type, reflectivity and efficiency, see example here

hit processing


First understand what is a "GEMC Hit"

hit processing need 3 things to work together

1. "hit definition", gives run time control to fine tune hit processing

2. "bank definition", gives what info to store and define exact entries in output file

3. "hit process routine", do the actual processing to fill banks with control by hit definition

For built-in type "flux", they are all inside GEMC code and can't be modified

One can build fully customized hit processing for any special detector after supply the three items and use it as "sensitivity" and "hit_type" in a piece of geometry with a "identifier"

The way to link them together is by a unique hit processing name in all three places, for example "solid_hgc" or "eic_ec"

hit definition

built-in type

The built-in "flux" type has timeWindow as "0" and thus it sums all steps with a sensitive volume with same ID from one track into a hit. One particular situation this won't work well is if you have a track passing through one detector more than once, (for example a low energy charge particle got bend backward in magnetic field), flux will average the multiple hits and give nonphysical results like hit positions etc

signalThreshold = 0;
timeWindow      = 0;
prodThreshold   = 1*mm (for GEMC >=2.3) or 0.001*mm (for GEMC <2.3)
maxStep         = 1*mm;

See all built-in type at

customized type

a "*" script is used to produce a text file "*__hit_*.txt" which define some parameters relevant to hit processing and it has entries similar to the following

$hit{"name"}            = "solid_hgc";
$hit{"description"}     = "solid hgc hit definition";
$hit{"identifiers"}     = "id";
$hit{"signalThreshold"} = "0.*MeV";
$hit{"timeWindow"}      = "0*ns";
$hit{"prodThreshold"}   = "1*mm";
$hit{"maxStep"}         = "1*mm";
$hit{"delay"}           = "10*ns";
$hit{"riseTime"}        = "1*ns";
$hit{"fallTime"}        = "1*ns";
$hit{"mvToMeV"}         = 100;
$hit{"pedestal"}        = -20;
  • meaning of the entries
    • name -- the same name as bank definition and hit process routine
    • identifiers -- how to distinguish individual detector component, this determine format used in geometry. eg. "sector stack view strip"
    • signalThreshold -- Minimum Energy Cut for processing the hit (not used)
    • timeWindow -- try to match ADC integration time window or TDC windows. Within the time windows, all hits within a detector component (defined by "identifiers") are combined into one. "0*ns" will have every individual hit as used in "flux" hit type, but this will slow down processing time a lot.
    • prodThreshold -- any track with energy smaller than this will not be tracked further, all energy get deposited in current volume. Too large value will give you too few tracks and being unphysical. This was defined in energy unit in Geant4, but Geant4 used a length unit to make material independent. the conversion is within Geant4. Geant4 define this globally with default 1mm, but also can be set for individual volumes. here gemc makes it to set with individual hit process type. (refer to [10] [11] [12])
    • maxStep -- Geant4 calculate step size according to material property. for gas, it can be too large if you need more steps, eg in drift chamber. gemc will take smaller one between this value and Geant4 suggested value. It can't be 0, otherwise, mem overflow
  • The built-in "flux" type has timeWindow as "0*ns" and thus it recorded every individual hit within the same detector. One particular situation this won't work well is if you have a track passing through one detector more than once, (for example a low energy charge particle got bend backward in magnetic field), flux will average the multiple hits and give nonphysical results like hit positions etc

bank definition

built-in type

The built-in "flux" type record hits "hitn" on a sensitive detector identified by an integer number id "id"

"mirror" record photon hit on mirror

See more are

customized type

a "*" script is used to produce a text file "*__hit_*.txt" which define some parameters relevant to hit processing and it has entries similar to the following

It should have at least three entries unique "bankid", "hitn" for number of hit number, and identifier

identifier format can be customized,like "sector manual 1 layer manual 2" and it has to match what is in hit definition and hit process routine

Additional entries can be defined and should be filled in hit process routine

Additional entries can't have same name what "true info" has (see below), otherwise, it create conflict when "true info" is recorded for the bank

true info

"true info" records particles in a sensitive volume

By default, it's off.

It can be turned on for flux and any customized bank by option like <option name="INTEGRATEDRAW" value="flux,solid_gem"/>

Then additional entries here will be added into the bank output

The "Process Names / ID Table" on the webpage is not correct for all version of code and it changes. To check the version you used, open the source file at "source/sensitivity/" and search for "procName"

hit process routine

All quantity should be in "MeV,mm,ns" units as geant4 default and it's important to follow the convention because the output banks doesn't carry any unit

All entries defined in bank definition should be filled one by one

The source code has same matching version with GEMC version

see examples here

generating experiment setup

Once parameter, geometry, materiel, mirror, bank, hit are all defined, we are ready to generating experiment setup by commands like

"./ config_solid_PVDIS_ec_forwardangle.dat"

the perl script set up some env variable and call all other perl scripts,

the config file defines some features like detector name and if use text file or database.

A serial of text files will be produced and loaded into database if decided, ready for simulation to run.

running simulation

running option and gcard file

run "gemc -help" to see all running option

run "gemc -help-html" or "gemc -help-options" will produce a file options.html (included with latest gemc source code) showing all running options.

see options on website and for latest gemc [13][14]

see gemc 2.3 options gemc 2.2 options and gemc 2.1 options (sometime you need to save the file to your local computer and open it with a browser to see it in right format)

All options can be used at command line with a dash

All options can be put in a XML format gcard file, one example here [15]. And you can call gcard without a dash

You can combine both, for example "gemc a.gcard -USE_GUI=1"

Please note gcard file can't recognize env variable, so the detector file and field map location need to be either relative to current running path or have absolute path. If not being careful, a job on a computer farm can fail due to this

Some special options

<detector name="detector_name" factory="TEXT" variation="Original"/>  include this detector with many files like geometry,materials,mirrors,hit,bank
<detector name="volume_name">  <existence exist="no" />    </detector> turn off a volume and its daughter volume at run time
<option name="PHYSICS" value="QGSP_BERT+STD+Optical"/>  combined physics list 
<option name="USE_GUI"  value="0"/>           run in batch model
<option name="RECORD_PASSBY" value="1"/>      record hit with no energy deposition
<option name="SAVE_ALL_MOTHERS" value="1"/>   save all mother particles info, may slow things down
<option name="INTEGRATEDRAW" value="flux"/>   activates true info output for the built-in flux bank
<option name="ALLRAWS"  value="flux,ec"/>     activates step-by-step output for the built-in flux bank and user defined ec bank
<option name="PRODUCTIONCUT"  value="1"/>     The max step size for all particles in all volume, similar to "maxStep" for the sensitive volume in the hit file.


option "HALL_FIELD" is the global magnetic field

local field is defined in a particular volume definition and only live within the volume and covers its daughter volume.

only one global field is allowed while local field can be be many and linked to individual volumes

When local and global field overlaps, local field always win because field in daughter volume will always supersede the one in the mother volume, as in geant4.

Both global and local field will try to find map files with "dat" as file extension at the location defined by "FIELD_DIR"

"SCALE_FIELD" scales a field by a factor and it works on both local and global field


particle color

Particle   Color
neutrons   black 
photons    blue 
e-         cyan 
protons    orange 
pion+      magenta 
pion-      yellow 
q=+1       red 
q= 0       white 
q=-1       green

hit color

red: hit for which the first step Edep is above threshold

blue: hit for which the first step Edep is below threshold

green: hit for which the first step Edep zero

using macro

geant4 command can be used directly in GUI window

They can also be group in macro and loaded from gcard or command line option like

<option name="EXEC_MACRO" value="meic_slice_tilt.vis"/>

macro examples here

particle ID

the standard geant4 pid, follows PDG defination

To see all pids, run this 'gemc -BEAM_P="show_all"' to get this list GMEC pid

input format and passing information into output

GEMC take two kinds of input format

The information from input are completely passed into output in two banks (header,generated) before gemc 2.6 and three banks (header,generated,userHeader) after gemc 2.6

refer to

input 1. particle guns directly from options

a particle gun for a single kind of particle
<option name="BEAM_P"   value="e-, 5*GeV, 0*deg, 0*deg"/>
<option name="SPREAD_P" value="0*GeV,0*deg,0*deg"/>
<option name="BEAM_V"   value="(0, 0, 0)m"/>
<option name="SPREAD_V" value="(0.,0)cm"/>
and up to any number of two more additional kind of particles, which can be used to add background in certain time window
<option name="LUMI_EVENT"   value="1, 1*ns, 1*ns"/>
<option name="LUMI_P"   value="e-, 5*GeV, 180*deg, 0*deg"/>
<option name="LUMI_SPREAD_P" value="0*GeV,0*deg,0*deg"/>
<option name="LUMI_V"   value="(0, 0, 80)m"/>
<option name="LUMI_SPREAD_V" value="(0.,0)cm"/>
<option name="LUMI2_EVENT"   value="1, 1*ns, 1*ns"/>
<option name="LUMI2_P"   value="neutron, 5*GeV, 50e-3*rad, 180*deg"/>
<option name="LUMI2_SPREAD_P" value="0*GeV,0*deg,0*deg"/>
<option name="LUMI2_V"   value="(0, 0, 0)m"/>
<option name="LUMI2_SPREAD_V" value="(0.,0)cm"/>

2. from an external input file pointed by an option

 <option name="INPUT_GEN_FILE" value="LUND, input.dat"/>  an example for the option

 The LUND format txt file as defined here) can be fully customized for its header part.
 particle line follow the webpage definition
 header line can be customized with 10 entries before gemc 2.3 or more after gemc 2.6

before gemc 2

gemc 1.x output doesn't have header bank so no 1st row entry will pass into gemc output.

before gemc 2.6

"generated" bank has particle info with entries "pid,px,py,pz,vx,vy,vz" and unit are MeV and mm
"header" bank has entries   "time,runNo,evn,evn_type,var1,var2,var3,beamPol,var4,var5,var6,var7,var8" 
         where evn is for event number, evn_type=-1 for simulation, beamPol for beam polarization (use 0 as default), all other variables are 0 from a particle gun
         or taken from lund header line "Number of particles,var1,var2,var3,Beam Polarization,var4,var5,var6,var7,var8"

after gemc 2.6

"generated" bank has two additional entries "time,multiplicity" added
"header" bank has entries "time,runNo,evn,evn_type,beamPol"
"userHeader" bank has entries "userVar001,userVar002,userVar003,userVar004,userVar005,userVar006,userVar007,userVar008,userVar009,userVar010,...."
             taken from lund header line "Number of particles,userVar002,userVar003,userVar004,userVar005,userVar006,userVar007,userVar008,userVar009,userVar010,...." 
             gemc will can take more than 10 lund header line entries and matches the output automatically


Direct output are txt or evio which is JLab DAQ data format

use text output to debug

convert evio to xml by

evio2xml output.evio

covert evio to root by

for built-in flux bank only
evio2root -INPUTF=output.evio  
for customized bank
evio2root -INPUTF=output.evio -B="dir1/bank1 dir2/bank2 ..." 
it will look for files dir1/bank1__bank.txt and dir2/bank2__bank.txt and more to convert the banks
use this option if the evio file produced with ALLRAWS turned on for certain banks, the default is "yes" 

see evio2root option by

evio2root -help-all


GEMC can output many detailed information for debugging if VERBOSITY options are used as show in help message, for example "-GEO_VERBOSITY=100" will give more info about geometry

If you see a warning like this "Error: directory /group/solid/apps/jlab_root/noarch/data/ could not be opened.", just ignore it.

note for 3D display file

example result

pngpdfwrl JLEIC beamline

wrl file

run simulation with this macro to generate a wrl file

This VRML file ending with wrl can be opened by many CAD program, for example, "3D builder" preinstalled in window8 and 10, meshlab, freecad

pdf file

we can convert wrl to pdf with a paid version of acrobat

Or a free way here by using meshlab and pdflatex to embed a U3D file in a tex file

go to a windows computer, open the wrl file in meshlab and export a U3D file with "color" selected. a U3D file and a tex file are generated accordingly.

edit the tex file to add line "\usepackage[a4paper,landscape,top=0mm, bottom=0mm, left=0mm, right=0mm]{geometry}" and change "{\linewidth}{\linewidth}" to "{297mm}{210mm}", so the final tex file looks like this

\usepackage[a4paper,landscape,top=0mm, bottom=0mm, left=0mm, right=0mm]{geometry}
	toolbar, %same as `controls'
	3Daac=60.000000, 3Droll=0.000000, 3Dc2c=-641.099976 -86745.000000 320.000000, 3Droo=86747.960938, 3Dcoo=-641.114990 5064.898438 -319.960022,

then you can run pdflatex with the tex and u3d file to produce the pdf and then view the pdf in latest acrobat reader and choose to trust the file for 3D content, then you can rotate,zoom,cut,shed light on the 3D object

movie15 and some other packages are for pdflatex to handle u3d file correctly
If you want to use miktex on windows, it needs to be installed on default location, then movie15 and other packages will be installed at run time
this has been verified with meshlab 1.3.3 ( and miktex 2.9 ( on 2016/02
resources: (this can in principal auto the process, but its current version doesn't work well with the meshlab 1.3.3 for color)