Import Geant4 5.2.0 source tree

This commit is contained in:
Gabriele Cosmo
2016-06-09 10:28:22 +02:00
parent fbd4999cf7
commit 4aea781e80
5454 changed files with 223141 additions and 67347 deletions
@@ -0,0 +1,175 @@
# $Id: dataAcess.py,v 1.2 2003/06/16 17:06:44 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
import os
import shelve
import myLiz
import dpsManip
import detector
class ExperimentalData(object):
def __init__(self):
tiara_dir = os.environ["TIARA_BASE"]
if not tiara_dir:
print "dataAcess.ExperimentalData: TIARA_BASE not defined run tiara...sh first"
dataFile = tiara_dir + "/data/expDataConverted/TiaraData2.xml"
print "display.ExperimentalData.dataFile:" ,dataFile
self.dataTree = myLiz.tf.create (dataFile,"xml",1,0)
def getDataDPS(self, she, detector):
energy = she["energy"]
shieldWidth = she["shieldWidth"]
dataName = "Tiara-" + energy + "c" + shieldWidth + \
"-" + detector
if shieldWidth == "25" or shieldWidth == "50":
dataName += "a"
dataName += ".pnt"
print dataName
pData = self.dataTree.findDataPointSet(dataName)
dpsManip.setDPSErrorsToZero(pData, 0)
return pData
def getScaledDataaDPS(self, she, detname, df):
pDataO = self.getDataDPS(she, detname)
pData = dpsManip.createScaledDPS(0,
pDataO,
df,
"scaled_" + pDataO.title (),
0.000001)
return pData
class MC_Data(object):
def __init__(self, she, mcTree):
self.she = she
self.energy = self.she["energy"]
self.shield = self.she["shieldWidth"]
self.mcTree = mcTree
self.coli = 0
if self.shield == "25" or \
self.shield == "50":
self.coli = 1
self.baseName = self.energy + "c" + self.shield +\
"_detector_"
def getGeneratedHisto(self):
name = "source_detector"
hGen = self.mcTree.findH1D(name)
return hGen
def getMcPlot(self, detector, histo):
mcName = "detector_" + detector + histo
print mcName
hMc = self.mcTree.findH1D(mcName)
return hMc
def getScale(self, atColiExit):
coli = 0
if atColiExit==1:
coli = 0
else:
coli = self.coli
nPeakNeutrons = self.she["generatorTally"].measures[1].sum
scale = detector.detScale(nPeakNeutrons, self.energy, coli)
print "CompPlot.getScale: scaling with:", scale
return scale
def getScaledMcDPS(self, atColiExit, det, df, histo = ""):
dname = self.baseName + det.name
if histo:
dname += "_" + histo
scale = self.getScale (atColiExit)
hMc = self.getMcPlot (det.name, histo )
binEdges = dpsManip.getBinEdges(hMc)
dScaled = dpsManip.getScaledDPS(hMc, scale/det.volume,
df, dname + "scaled")
dLethScaled = dpsManip.dLogWeightDPS (dScaled,
df,
dname + "df_dlgE",
binEdges)
return dLethScaled
def getScaledGeneratedDPS(self, atColiExit, det, df, histo = ""):
dname = self.baseName + det.name
if histo:
dname += "_" + histo
sourceDetectorVolume = 9.33
scale = self.getScale (atColiExit)
hGen = self.getGeneratedHisto()
binEdges = dpsManip.getBinEdges(hGen)
dGenScaled = dpsManip.getScaledDPS(hGen,
scale/sourceDetectorVolume,
df,
dname + "GenScaled")
dGenLethScaled = dpsManip.dLogWeightDPS(dGenScaled, df,
dname + "gen, df_dlgE",
binEdges)
return dGenLethScaled
class ExpMcPlot(object):
"""Prepare and hold source information for a plot.
Hold experimental and Monte Carlo data to plot in one diagram.
"""
def __init__(self, shelveName, dist, detType="ring", histo = ""):
path = os.path.dirname(shelveName)
shelveFile = os.path.basename(shelveName)
self.tt = myLiz.tf.create ()
self.df = myLiz.af.createDataPointSetFactory (self.tt)
self.she = shelve.open(shelveName,"r")
xmlFile = self.she["xmlStoreName"]
if path:
xmlFile = path + "/" + xmlFile
self.mcTree = myLiz.tf.create (xmlFile, "xml", 1, 0)
self.det = detector.Detector(dist,detType)
self.expData = ExperimentalData()
self.mcData = MC_Data(self.she, self.mcTree)
self.pDataDPS = self.expData.getScaledDataaDPS(self.she,
self.det.name,
self.df)
self.pMcDPS = self.mcData.getScaledMcDPS(atColiExit=1,
det=self.det,
df=self.df,
histo="")
self.pGenDPS = self.mcData.getScaledGeneratedDPS(atColiExit=1,
det=self.det,
df=self.df,
histo="")
self.regions = []
def display(self):
if "pl" not in dir(myLiz):
myLiz.pf = myLiz.af.createPlotterFactory ()
myLiz.pl = myLiz.pf.create()
region = myLiz.pl.currentRegion()
self.regions.append(region)
region.plot (self.pDataDPS,"markers overlay")
region.plot (self.pMcDPS,"markers overlay")
myLiz.pl.refresh ()
@@ -0,0 +1,64 @@
# $Id: detector.py,v 1.2 2003/06/16 17:06:44 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
# A detector is either the of the "simple" or "ring" type.
# the volumina of the "simple" detectors are the same at all
# positions (00, 20, 40 cm off beam axis). The "ring" type detectors
# have different volumina at the different positions.
# For convinience a class Detector is provided to link a detector
# position and it's volume.
d00Volume = 1608.8 # volume of the 12.9 cm x 12.9 cm cyinder
d20Volume = 20268.3 # volume of the ring at 20 cm
d40Volume = 40536.6 # volume of the ring at 40 cm
# map of distances to volumina for the 12.9 cm x 12.9 cm detectors
SimpleDetectorVolume = {"00":d00Volume, "20":d00Volume, "40":d00Volume}
# map of distances to volumina for ring detectors
RingDetectorVolume = {"00":d00Volume, "20":d20Volume, "40":d40Volume}
# map of detector type to distance-volumina map
DetectorVolume = {"simple":SimpleDetectorVolume,
"ring" :RingDetectorVolume}
class Detector(object):
"Distance and volume of a Detector."
def __init__(self, dist, detType):
self.name = dist
self.volume = DetectorVolume[detType][dist]
# function to calculate the scale factor
def detScale(ngen, energy, coli):
"""Detrmine scale.
Determine scale according to the number of generated neutrons,
the proton beam energy. If coli == 1, the flux at the
colimator exit is used, else the flux at 401 cm is used.
"""
Asrc = 93.31
Fexp = 0
if energy == "43":
if coli == 1:
Fexp = 1.76E+04
else:
Fexp = 1.94E+04
else:
if energy == "68":
if coli == 1:
Fexp = 2.04E+04
else:
Fexp = 2.46E+04
S = Fexp * Asrc / ngen
return S
@@ -0,0 +1,90 @@
# $Id: dpsManip.py,v 1.2 2003/06/16 17:06:44 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
import math
# functions to manipulate a DPS (data point set)
def getScaledDPS(hSrc, scale, df, name):
"Create a scaled DPS from a histogramm."
hSrc.scale(scale)
dp = df.create(name, hSrc)
setDPSErrorsToZero(dp, 0)
hSrc.scale(1./scale)
return dp
def setDPSErrorsToZero(dps, coNum):
"Set errors of a DPS to zero."
for i in range(dps.size()):
p = dps.point(i)
co = p.coordinate(coNum)
co.setErrorMinus(coNum)
co.setErrorPlus(coNum)
def copyDPS(dSrc, df, name):
"Make a copy of a DPS using the data point set factory df."
dp = df.create(name, dSrc.dimension ())
for i in range( dSrc.size() ):
dp.addPoint()
pNew = dp.point(i)
pOld = dSrc.point(i)
for d in range(dSrc.dimension ()):
cOld = pOld.coordinate(d)
cNew = pNew.coordinate(d)
cNew.setValue(cOld.value())
em = cOld.errorMinus()
ep = cOld.errorPlus()
cNew.setErrorMinus(em)
cNew.setErrorPlus(ep)
return dp
def dLogWeightDPS(dSrc, df, name, binEdges):
"""Create a dps with the coordinate 1 scaled by 1/dlog(coordinate 0).
"""
dp = copyDPS(dSrc, df, name)
for i in range(len(binEdges) - 1):
s = math.log(binEdges[i+1]) - math.log(binEdges[i])
c = dp.point(i).coordinate (1)
value = dSrc.point(i).coordinate(1).value()
errorMinus = dSrc.point(i).coordinate(1).errorMinus()
errorPlus = dSrc.point(i).coordinate(1).errorPlus()
c.setValue(value / s)
c.setErrorMinus(errorMinus / s)
c.setErrorPlus(errorPlus / s)
return dp
def createScaledDPS(coNum, pDataO, df, name, scale):
"""Create a scaled DPS from a DPS.
The coordinate \'coNum\' of the source DPS \'pDataO\' is scaled by
\'scale\'. The result is returned in the DPS created by the given
data point set factory \'df\' named \'name\'.
"""
dp = copyDPS(pDataO, df, name)
for i in range( dp.size() ):
p = dp.point(i)
co = p.coordinate(coNum)
co.setValue(co.value()*scale)
co.setErrorMinus(co.errorMinus()*scale)
co.setErrorPlus(co.errorPlus()*scale)
return dp
def getBinEdges(h):
"Get bin edges of a histogramm."
binEdges = []
a = h.axis ()
for i in range(a.bins ()):
binEdges.append(a.binLowerEdge(i))
binEdges.append(a.binUpperEdge(a.bins () - 1))
return binEdges
@@ -0,0 +1,108 @@
# $Id: extractShelve.py,v 1.2 2003/06/16 17:06:44 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
import string
import math
import os
import shelve
import string
import detector
# some functions for calculating the FOM
def getR2(measure):
"Error squared of a measure."
v = measure.variance
m2 = math.pow(measure.mean, 2)
n = measure.entries
r2 = 1e+10
if n>0 and m2 > 0:
r2 = v/m2/n
return r2
def getFOMbyName(shelveName, tallyName, bin):
"FOM by shelve name, tally name and bin of energy region"
she = shelve.open (shelveName, "r")
measure = she[tallyName].measures[bin]
R2= getR2(measure)
T = she["runTime"]
return 1./(T*R2)
def getFOM(aShelve, tallyName, bin):
"FOM given a shelve, tally name and energy bin."
measure = aShelve[tallyName].measures[bin]
R2= getR2(measure)
T = aShelve["runTime"]
return 1./(T*R2)
# functions to retrive information from the shelve
def infoShelve(file):
"Print information stored in a shelve."
she = shelve.open(file, "r")
print file
for k in she.keys():
value = she[k]
if value.__class__.__module__ == "__builtin__" :
print " ", k, ":", value
def lsShelve(path):
"List shelve information found in and under the given path. "
if os.path.isfile(path):
if string.find(path,".shelve") > -1:
infoShelve(path)
else:
if os.path.isdir(path):
files = os.listdir(path)
for file in files:
f=path + "/" + file
lsShelve(f)
def getFluxInRegion(she, dist="00", detType="ring", region=1):
"Get the flux in a detector."
tally = she["detector_" + dist + "Tally"]
m = tally.measures[region]
rawFlux = m.sum
nPeakNeutrons = she["generatorTally"].measures[1].sum
scale = detector.detScale(nPeakNeutrons, she["energy"], 0)
return rawFlux * scale / detector.DetectorVolume[detType][dist]
def getFluxes(she, detType = "ring"):
"Get all fluxes and FOM in a shelve."
fluxName = "flux_" + she["energy"]+"_"+\
she["shieldWidth"]
keys = she.keys()
fluxes = {}
for k in keys:
if string.find(k,"detector_") > -1:
sp = string.split(k,"detector_")
sp = string.split(sp[1],"Tally")
dist = sp[0]
fluxNameD = fluxName + "_" + dist
for i in range(1,3):
fom = getFOM(she, k, i)
f = fluxNameD + "_" + "%(i)d" % vars()
v = getFluxInRegion(she, dist, detType, i)
sv = '%1.2E' % (v)
print f, sv, " FOM:", fom
fluxes[f] = sv
return fluxes
@@ -0,0 +1,445 @@
# $Id: liz.py,v 1.2 2003/06/16 17:06:44 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
import os, sys, string
if ( not os.environ.has_key("ANAPHETOP") ) :
os.environ["ANAPHETOP"] = "/afs/cern.ch/sw/lhcxx"
if ( not os.environ.has_key("PLATF") ) :
os.environ["PLATF"] = "redhat73/gcc-3.2"
if ( not os.environ.has_key("ANAPHE_VERSION") ) :
if ( not os.environ.has_key("ANAPHEVERS") ) :
os.environ["ANAPHEVERS"] = "5.0.4"
else :
os.environ["ANAPHEVERS"] = os.environ["ANAPHE_VERSION"]
if ( not os.environ.has_key("PUBDOMVERS") ) :
os.environ["PUBDOMVERS"] = "2.0.0"
if ( not os.environ.has_key("ANAPHE_REL_DIR") ) :
os.environ["ANAPHE_REL_DIR"] = os.environ["ANAPHETOP"]+"/specific/"+os.environ["PLATF"]+"/"+os.environ["ANAPHEVERS"]
if ( not os.environ.has_key("OS") ) :
os.environ["OS"] = "Linux" # for now !!!
# for debugging purposes this might be set differently ...
if ( not os.environ.has_key("LIZARD_ROOT") ) :
os.environ["LIZARD_ROOT"] = os.environ["ANAPHE_REL_DIR"] + "/python"
os.environ["LIZARD_LIB"] = os.environ["LIZARD_ROOT"] + "/lib"
#-toDo: clean up the LD_LIBRARY_PATH, PATH and PYTHONPATH variables from wrong versions
# of Anaphe s/w
#export LD_LIBRARY_PATH=`${LIZARD_ROOT}/bin/cleanupPath.py LD_LIBRARY_PATH`
#export PATH=`${LIZARD_ROOT}/bin/cleanupPath.py PATH`
#export PYTHONPATH=`${LIZARD_ROOT}/bin/cleanupPath.py PYTHONPATH`
# add to path in order to find xmgrace ...
if (not os.environ.has_key("GRACE_DIR") ) :
os.environ["GRACE_DIR"] = os.environ["ANAPHETOP"]+"/specific/"+os.environ["PLATF"]+"/PublicDomainPackages/" + os.environ["PUBDOMVERS"] + "/grace"
os.environ["PATH"] = os.environ["GRACE_DIR"] + "/bin:" + os.environ["PATH"]
os.environ["LD_LIBRARY_PATH"] = os.environ["LD_LIBRARY_PATH"] + ":" + os.environ["LIZARD_LIB"] + ":" + os.environ["ANAPHE_REL_DIR"] + "/lib"
# toDo:
# if [ `uname` = "SunOS" ] ; then
# SUN_CC_DIR=/afs/cern.ch/project/sun/solaris/opt/SUNWspro62Apr02
# export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${SUN_CC_DIR}/lib:/usr/local/lib # /opt/SUNWspro/lib:/usr/local/lib:/opt/SUNWspro/WS6U1/lib
# fi
#
# to find the proper versions of libs for python-2.0 and swig-1.3a5
# (it should be SWIG_DIR)
if (not os.environ.has_key("SWIG_DIR")) :
os.environ["SWIG_DIR"] = os.environ["ANAPHETOP"]+"/specific/"+os.environ["PLATF"]+"/PublicDomainPackages/" + os.environ["PUBDOMVERS"]
os.environ["LD_LIBRARY_PATH"] = os.environ["SWIG_DIR"] + "/lib:" + os.environ["LD_LIBRARY_PATH"]
# need to add "." for automatic code compilation (ntuples et al)
os.environ["LD_LIBRARY_PATH"] = os.environ["LD_LIBRARY_PATH"] + ":" + os.environ["LIZARD_ROOT"] + "/" + os.environ["PLATF"] + ":."
# add to PYTHONPATH
sys.path.append(os.environ["LIZARD_LIB"])
sys.path.append(os.environ["LIZARD_ROOT"] + "/" + os.environ["PLATF"])
sys.path.append(os.environ["LIZARD_ROOT"] + "/src")
sys.path.append(os.environ["HOME"])
sys.path.append(os.environ["LIZARD_ROOT"] + "/contrib")
# toDo
#if [ -z $LIZARD_NO_PUBLIC_CONTRIB ] ; then
# export PYTHONPATH=${PYTHONPATH}:${ANAPHETOP}/share/PythonContrib
#fi
# # define location of python
# if [ -z $PYDIR ] ; then
# export PYDIR=${ANAPHETOP}/specific/${PLATF}/PublicDomainPackages/${PUBDOMVERS}
# fi
#
# if [ -z $PYTHON ] ; then
# export PYTHON=${PYDIR}/bin/python2.2
# fi
#
# create a local temporary file (with the PID as part of the name) to
# speed up access from Nag fitter if starting directory is in AFS:
if (not os.environ.has_key("LIZARD_KEEP_FITRESULT")) :
os.system("rm -f e04ucc.r")
os.system("ln -s /tmp/pid-$$-e04ucc.r e04ucc.r")
# $PYTHON -i ${LIZARD_ROOT}/bin/.Lizardrc $*
print "executing startup from'"+os.environ["LIZARD_ROOT"] + "/bin/.Lizardrc"+"'"
# execfile(os.environ["LIZARD_ROOT"] + "/bin/.Lizardrc")
# Settings for Lizard
lizardVersion = "3.0.0.5"
lizardVersionDate = "20 Dec 2002"
lizardBatch = None
lizardObjy = None
lizardNag = None
lizardNoGraphics = None
from math import *
from time import *
import string
import os
import sys
import random
import atexit
import gc
# the following works only for python-2.0 (or later)
# for command-line completion :
import rlcompleter
rlcompleter.readline.parse_and_bind("tab: complete")
try :
if (sys.version_info[0] == 2) :
# for history (across-sessions)
import readline
# limit history file to 1000 lines
readline.set_history_length(1000)
# read previous file (if existing)
histfile = os.path.join(os.environ["HOME"], ".LizHist")
try:
readline.read_history_file(histfile)
except IOError:
print "cannot read command history file ", histfile
pass
# register function to write history file at exit
atexit.register(readline.write_history_file, histfile)
del histfile
# end history
except :
print "\nerror while accessing command history file"
raise
# end python-2.0 specific part ...
# --------------------------------------------------------------------------------
def usage ():
print """
usage: startLizard.sh [<options>] [<file1> <file2> ...]
where the optional <options> can be one of the following:
-?, -h, --help : print this text
-v, --version : print version info
-b, --batch : run in batch mode and execute the scripts passed after all options
--noGraphics : don't instantiate a Plotter (use this if your DISPLAY variable is not set)
--useNag : use minimizer engine from Nag-C library
--useObjy : use Objectivity/DB for persistent Histograms and (row-wise) Ntuples
default : use FML with Minuit minimizer engine
the (optional) list of files will be executed after startup
NOTE: the options need to be _before_ any script file
"""
# --------------------------------------------------------------------------------
# set some defaults: use FML, Objy, Nag-C
# --------------------------------------------------------------------------------
lizardFML = 1
lizardHBook = 0
lizardNag = 0
# --------------------------------------------------------------------------------
# --------------------------------------------------------------------------------
def lizardVersionInfo() :
print "\nThis is Lizard version " + lizardVersion + "\n"
# --------------------------------------------------------------------------------
# check if we got any flags:
# --------------------------------------------------------------------------------
import getopt
#optlist = []
#args = []
try:
optlist, args = getopt.getopt(sys.argv[1:], ['?', 'h', 'v', 'b'],
['help', 'version', 'batch', 'noGraphics',
'useNag', 'useNag', 'useObjy', 'objy' ])
except :
print "\nunknown option:",o,"\n"
usage()
sys.exit()
# --------------------------------------------------------------------------------
# have a first look at options now, see if the user wants some info without
# the need to start the system ...
# --------------------------------------------------------------------------------
for o, a in optlist:
if o in ("-?", "-h", "--help"):
usage()
sys.exit()
elif o in ("-v", "--version",):
lizardVersionInfo()
sys.exit()
elif o in ("", "--useObjy", "--objy",):
lizardObjy = 1
import dl
# --------------------------------------------------------------------------------
# check if Objectivity can be used, if requested
# --------------------------------------------------------------------------------
if (lizardObjy == 1) :
try:
dl.open( "liboo.so" )
except:
print "Objectivity requested, but liboo not found in LD_LIBRARY_PATH !! Aborting !"
sys.exit()
# --------------------------------------------------------------------------------
# check if Nag_C can be used,
# --------------------------------------------------------------------------------
if (lizardNag == 1 ) :
try:
dl.open( "libnagc.so" )
except:
print "Minimizer from NAG requested, but libnagc not found in LD_LIBRARY_PATH !! Aborting !"
sys.exit()
# --------------------------------------------------------------------------------
# check the other possible flags:
# --------------------------------------------------------------------------------
for o, a in optlist:
if o in ("-b", "--batch",):
lizardBatch = 1
elif o in ("--noGraphics",):
lizardNoGraphics = 1
elif o in ("--nag", "--useNag"):
lizardNag = 1
# --------------------------------------------------------------------------------
print "\n"
# --------------------------------------------------------------------------------
# check now whether DISPLAY is set.
# --------------------------------------------------------------------------------
if (lizardNoGraphics != 1) :
try:
disp = os.environ["DISPLAY"]
except:
print "\n==========> no DISPLAY set, switching to no-graphics mode."
lizardNoGraphics = 1
# prompt
sys.ps1=":-) "
# --------------------------------------------------------------------------------
# welcome message parameters
lizMsgWelcome = "Welcome to Lizard"
lizMsgID = "Version "+ lizardVersion + " (" + lizardVersionDate + ")"
lizMsgURL = "http://cern.ch/Anaphe"
lizMsgSide = "|"
lizMsgCorner = "+"
lizMsgTop = "-"
lizMsgWidth = 50
lizMsgSideIndent = 8
lizMsgTopIndent = 1
# generate welcome message
lizMsgBar = ""
for i in range (0,lizMsgWidth) :
lizMsgBar = lizMsgBar + lizMsgTop
lizMsgPad = ""
for i in range (0,lizMsgSideIndent) :
lizMsgPad = lizMsgPad + " "
lizMsgBlank = lizMsgSide + string.center("",lizMsgWidth) + lizMsgSide
for i in range (0, lizMsgTopIndent) :
print ""
print lizMsgPad + lizMsgCorner + lizMsgBar + lizMsgCorner
print lizMsgPad + lizMsgBlank
print lizMsgPad + lizMsgSide + string.center(lizMsgWelcome,lizMsgWidth) + lizMsgSide
print lizMsgPad + lizMsgBlank
print lizMsgPad + lizMsgSide + string.center(lizMsgID,lizMsgWidth) + lizMsgSide
print lizMsgPad + lizMsgBlank
print lizMsgPad + lizMsgSide + string.center(lizMsgURL,lizMsgWidth) + lizMsgSide
print lizMsgPad + lizMsgBlank
print lizMsgPad + lizMsgCorner + lizMsgBar + lizMsgCorner
for i in range (0, lizMsgTopIndent) :
print ""
# --------------------------------------------------------------------------------
print "Chosen configuration: ",
if ( lizardObjy == 1 ) :
print "Objectivity",
else:
print "HBook and XML",
print " persistency and ",
if ( lizardNag == 1 ) :
print "Nag-C",
else:
print "Minuit",
print "minimizer engine"
print "\nType help() for help\n"
sys.stdout.flush()
# --------------------------------------------------------------------------------
# global startup files ...
# --------------------------------------------------------------------------------
# remember where we started from ...
curDir = os.getcwd()
# check for global StartupFiles (so far, the order doesn't matter):
startDir = os.environ['LIZARD_ROOT']+"/startUpFiles/"
fileList = os.listdir(startDir)
# change to directory containing the startup files and exec them one by one:
os.chdir(startDir)
try:
for file in fileList :
if (string.find(file,".py") == -1) :
continue;
if (file == "constants.py") :
continue;
if (os.path.isfile(file)) :
# print "loading startUp file ", file
execfile(file)
else :
print "Strange: cannot \"execfile\" startUp file ", file, " in ", startDir, " !?!?"
except:
raise
#-ap execfile("constants.py")
# return to where we left from ...
os.chdir(curDir)
LizardIsInitialized = 1
print "\n\nLizard initialised\n"
# --------------------------------------------------------------------------------
# local/user-specific startup files ...
# --------------------------------------------------------------------------------
# check for local initfiles:
homeStart = os.environ['HOME']+"/.Lizardrc"
if os.path.isfile(homeStart):
execfile(homeStart)
# avoid reading it twice ...
if (os.getcwd() != os.environ['HOME'] and
os.getcwd() != os.environ['LIZARD_ROOT']+"/bin" ) :
localStart = "./.Lizardrc"
if os.path.isfile(localStart):
execfile(localStart)
# --------------------------------------------------------------------------------
def lizardCleanUp() :
global af, tf, pf, pl
# in reverse order of construction
if (lizardNoGraphics != 1) :
pl.thisown = 1 ; del pl
pf.thisown = 1 ; del pf
tf.thisown = 1 ; del tf
af.thisown = 1 ; del af
# print "global objects deleted ... " ; sys.stdout.flush()
for lib in theListOfLoadedLibraries.keys() :
sys.stdout.flush()
theListOfLoadedLibraries[lib].close()
# print "\nall libs unloaded ... " ; sys.stdout.flush()
print "\nobjects deleted and libs unloaded, exiting python ... " ; sys.stdout.flush()
return
# --------------------------------------------------------------------------------
def exit() :
lizardCleanUp()
sys.exit()
# --------------------------------------------------------------------------------
# execute file given at input (ignoring startup file .Lizardrc) ...
# --------------------------------------------------------------------------------
if (len(args) > 0 ) :
args[0] = os.path.abspath(args[0])
file = args[0]
# reset the environment ... the scripts will now look as if invoked from the shell ...
sys.argv = args
print "executing ", file
if (os.path.isfile(file)) :
try :
execfile(file)
except:
# if something goes wrong in batch mode, clean up and exit ...
if (lizardBatch == 1) :
lizardCleanUp()
sys.exit(2)
else :
raise
else :
print "file ", file, " not found."
if (lizardBatch == 1) :
# clean up (explicitly destroy some objects)
lizardCleanUp()
sys.exit()
@@ -0,0 +1,10 @@
# $Id: myLiz.py,v 1.2 2003/06/16 17:06:44 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
import sys
origArgv = sys.argv
sys.argv = ["","--noGraphics"]
from liz import *
sys.argv = origArgv
@@ -0,0 +1,272 @@
# $Id: myUtils.py,v 1.4 2003/06/20 12:41:06 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
import CLHEP
import G4Kernel
import string
import os
import time
import shelve
G4analysisUse = os.environ.has_key("G4ANALYSIS_USE")
if G4analysisUse:
import myLiz
def createParallelSampler(impGeo, impScorer):
parallelSampler = G4Kernel. \
G4ParallelGeometrySampler(\
impGeo.getWorldVolume(), "neutron")
parallelSampler.PrepareScoring(impScorer)
if impGeo.base > 1:
istore = impGeo.getImportanceStore()
parallelSampler.PrepareImportanceSampling(istore,None)
parallelSampler.Configure()
return parallelSampler
def printImpTable(impScorer, istore = ""):
iScMap = impScorer.GetMapGeometryCellCellScorer()
table = ""
if istore:
table = G4Kernel.G4ScoreTable(istore)
else:
table = G4Kernel.G4ScoreTable()
table.Print(iScMap)
def saveResults(tApp, path, shelveName, impScorer, impGeo):
myShelve = shelve.open(path + "/" + shelveName)
printImpTable(impScorer, impGeo.getImportanceStore())
table = G4Kernel.G4ScoreTable()
table.Print(tApp.cellScorerStore.GetMapGeometryCellCellScorer())
if G4analysisUse:
storePath = path + "/" + myShelve["xmlStoreName"]
persistantStore = myLiz.tf.create(storePath,"xml",0,1)
coppyTrees(tApp.tree, persistantStore)
persistantStore.commit()
persistantStore.close()
print "wrote to store: ", storePath
tApp.fillShelve(myShelve)
myShelve.close()
print "wrote shelve: ", shelveName
def coppyTrees(srcTree, cpTree):
mntPoint = "cpTreeMountPoint"
srcTree.mkdir("/" + mntPoint)
srcTree.mount("/" + mntPoint, cpTree, "/")
objectNames = srcTree.listObjectNames()
objectTypes = srcTree.listObjectTypes()
for i in range(len(objectNames)):
name = objectNames[i]
type = objectTypes[i]
if string.find(name, mntPoint) < 0:
srcTree.cp (name,"/" + mntPoint +"/")
min = 6000
hour = 60 * min
day = 24 * hour
def getTotalTime(totalTime):
days = totalTime / day
dayRest = totalTime - days*day
hours = dayRest / hour
minrest = dayRest - hours*hour
minutes = minrest / min
tString = ""
if days > 0:
tString += "%(days)dd" % vars()
if hours > 0:
tString += "%(hours)dh" % vars()
if minutes > 0:
tString += "%(minutes)dm" % vars()
return tString
def getStoreName():
Y, M, D, h, m, s, wd, jd, ds = time.localtime()
hostName = os.environ["HOST"]
storeName = "tiara-" + \
"%(Y)d" % vars() + "_" + \
"%(M)d" % vars() + "_" + \
"%(D)d" % vars() + "_" + \
"%(h)d" % vars() + "_" + \
"%(m)d" % vars() + "_" + \
"%(s)d" % vars() + "_" + \
hostName
return storeName
def getConfigurationInfo(impGeo, experiment, physicsList, totalTime,
comment):
configInfo = {}
configInfo["energy"] = experiment.energy
configInfo["shieldMaterial"] = experiment.shieldMaterial
width = experiment.shieldWidth / CLHEP.cm
s_width = "%(width)d" % vars()
configInfo["shieldWidth"] = s_width
base = impGeo.base
simp = "no"
if base > 1:
simp = "ImpBase_%(base)f" % vars()
configInfo["biasing"] = simp
configInfo["physListName"] = physicsList.getName()
particles = ""
configInfo["minEnergyCut"] = experiment.particleCut
stime = "no"
if totalTime > 0:
stime = getTotalTime(totalTime)
configInfo["timeLimit"] = stime
configInfo["impGeoName"] = impGeo.nameExt
configInfo["hostName"] = os.environ["HOST"]
configInfo["comment"] = comment
return configInfo
def setConfigInfo(tree, confInfo, af):
hf = af.createHistogramFactory(tree)
h = hf.createHistogram1D("configInfo","configInfo",1,0,1)
anno = h.annotation()
for k in confInfo:
anno.addItem(k, confInfo[k])
def getConfigInfoFromTree(tree):
configInfo = {}
h = tree.findH1D("configInfo")
anno = h.annotation ()
for i in range(8, anno.size()):
configInfo[anno.key(i)] = anno.value(i)
return configInfo
if G4analysisUse:
def addToXML(mergedXMLStore, xmlStore):
objNames = xmlStore.listObjectNames()
objTypes = xmlStore.listObjectTypes()
hf = myLiz.af.createHistogramFactory(mergedXMLStore)
for i in range(len(objNames)):
oName = objNames[i]
oType = objTypes[i]
if oType == "IHistogram1D":
h1 = mergedXMLStore.findH1D(oName)
h2 = xmlStore.findH1D(oName)
hf.add(oName,h1,h2)
if G4analysisUse:
def comparableShelves(she, mergedXMLStore):
comp = 1
if mergedShelve["energy"] != she["energy"]:
comp = 0
if mergedShelve["shieldWidth"] != she["shieldWidth"]:
comp = 0
def setUpMergedShelve(she, mergedShelve, mergedXMLname, shelveNameToBeAdded):
mergedShelve["xmlStoreName"] = mergedXMLname
mergedShelve["energy"] = she["energy"]
mergedShelve["shieldWidth"] = she["shieldWidth"]
mergedShelve["mergedFiles"] = shelveNameToBeAdded
mergedShelve["runTime"] = she["runTime"]
mergedShelve["generatorTally"] = she["generatorTally"]
mergedShelve["sourceDetectorTally"] = she["sourceDetectorTally"]
mergedShelve["detector_00Tally"] = she["detector_00Tally"]
mergedShelve["detector_20Tally"] = she["detector_20Tally"]
mergedShelve["detector_40Tally"] = she["detector_40Tally"]
def addToShelve(mergedShelve, she, shelveNameToBeAdded):
mergedShelve["mergedFiles"] += shelveNameToBeAdded + " "
mergedShelve["runTime"] += she["runTime"]
mergedShelve["generatorTally"].addMeasures(she["generatorTally"])
mergedShelve["sourceDetectorTally"].addMeasures(she["sourceDetectorTally"])
mergedShelve["detector_00Tally"].addMeasures(she["detector_00Tally"])
mergedShelve["detector_20Tally"].addMeasures(she["detector_20Tally"])
mergedShelve["detector_40Tally"].addMeasures(she["detector_40Tally"])
if G4analysisUse:
def mergeData(mergedName, shelveList):
mergedShelveName = mergedName + ".shelve"
print "createing merged shelve: ", mergedShelveName
mergedShelve = shelve.open(mergedShelveName)
mergedXMLname = mergedName + ".xml"
print "createing merged XML store: ", mergedXMLname
mergedXMLStore = myLiz.tf.create(mergedXMLname, "xml", 0, 1)
for i in range(len(shelveList)):
shelveName = shelveList[i]
print "adding data from: ", shelveName
she = shelve.open(shelveName,"r")
xmlStoreName = she["xmlStoreName"]
print "opening: ", xmlStoreName
xmlStore = myLiz.tf.create(xmlStoreName,"xml",1,0)
if i == 0:
if mergedXMLStore.listObjectNames() == ():
setUpMergedShelve(she, mergedShelve, mergedXMLname, shelveName)
coppyTrees(xmlStore, mergedXMLStore)
else:
if comparableShelves(she, mergedXMLStore):
addToShelve(mergedShelve, she, shelveName)
addToXML(mergedXMLStore, xmlStore)
else:
addToShelve(mergedShelve, she, shelveName)
addToXML(mergedXMLStore, xmlStore)
mergedShelve.close()
mergedXMLStore.commit()
mergedXMLStore.close()
def rmPath(she):
xmlFile = she["xmlStoreName"]
n = string.rfind(xmlFile,"/")
if n > -1:
xmlFile = xmlFile[n+1:]
she["xmlStoreName"] = xmlFile
@@ -0,0 +1,60 @@
# $Id: parallelHall.py,v 1.4 2003/06/20 12:41:06 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
import G4Kernel
import CLHEP
import string
class ParallelHall(object):
def __init__(self, tiaraSpecs):
self.halfWidth = tiaraSpecs.dimensions.worldHalfWidth + \
10*CLHEP.cm
self.halfLength = tiaraSpecs.dimensions.worldHalfLength + \
10*CLHEP.cm
self.hallSolid = G4Kernel.G4Box("parallelBox",
self.halfWidth,
self.halfWidth,
self.halfLength)
vacuum = tiaraSpecs.materials.GetMaterial("vacuum")
self.logHall = G4Kernel.G4LogicalVolume(self.hallSolid,
vacuum,
"paralleleLog")
rot = G4Kernel.G4RotationMatrix()
self.worldVolume = G4Kernel.\
G4PVPlacement(rot,
CLHEP.Hep3Vector(0, 0, 0),
self.logHall,
"ParallelHall");
self.geoCells = []
def getWorldVolume(self):
return self.worldVolume
def placeCells(self, arrPosLogVol):
for ele in arrPosLogVol:
phys = self.placeOneCell(ele)
self.geoCells.append(G4Kernel.G4GeometryCell(phys, 0))
def placeOneCell(self, pLog, name = ""):
rot = G4Kernel.G4RotationMatrix()
z = int(pLog.pos)
zstr = "%(z)d" % vars()
zstr = string.rjust(zstr, 5)
zstr = string.replace(zstr,' ','0')
if not name:
name = "cell_z_" + zstr
vPhys = G4Kernel.\
G4PVPlacement(rot,
CLHEP.Hep3Vector(0, 0, pLog.pos),
pLog.log,
name,
self.logHall);
return vPhys
def getGeometryCells(self):
return self.geoCells
@@ -0,0 +1,10 @@
# $Id: posLog.py,v 1.2 2003/06/16 17:06:44 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
class PosLog(object):
def __init__(self, pos, log):
self.pos = pos
self.log = log
@@ -0,0 +1,119 @@
# $Id: runSequence.py,v 1.3 2003/06/16 17:06:44 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
import Tiara
import myUtils
import shelve
import os
import string
class RunConfig(object):
def __init__(self):
self.basePath = ""
self.tApp = ""
self.tiaraSpecs = ""
self.impGeo = ""
self.impScorer = ""
self.totalTime = ""
self.comment = ""
def getConfInfo(self):
return myUtils.\
getConfigurationInfo(self.impGeo,
self.tiaraSpecs.experiment,
self.tApp.physicsList,
self.totalTime,
self.comment)
class RunSequence(object):
# methods to be used public
def __init__(self, runConfig, useLizard = True):
self.rc = runConfig
self.useLizard = useLizard
self.runNum = -1
self.confInfo = self.rc.getConfInfo()
self.storeName = myUtils.getStoreName()
self.xmlStore = ""
self.pathXMLName = ""
self.shelveName = ""
self.pathShelveName = ""
self.randomNumberFileName = ""
self.path = self.mkPath()
def runNevents(self, events):
self.runNum += 1
self.mkNames()
self.mkShelve()
self.report()
self.rc.tApp.tiaraSim.BeamOn (events)
Tiara.saveRandomStatus(self.randomNumberFileName)
myUtils.saveResults(self.rc.tApp,
self.path,
self.shelveName,
self.rc.impScorer,
self.rc.impGeo)
def runLoop(self):
while ( not \
(self.rc.tApp.eventAction.\
GetTotalProcessedTime() > self.rc.totalTime)):
self.runNevents(10000000) # dummy num. events
# methods used privately
def report(self):
print "\n\nRunSequence.report:"
print self.confInfo
if self.useLizard:
print "the xml store will be named: "
print " ", self.pathXMLName
print "the shelve name: "
print " ", self.pathShelveName
print "\n\n"
def mkPath(self):
if not os.path.exists(self.rc.basePath):
os.mkdir(self.rc.basePath)
path = self.rc.basePath + "/" + self.storeName
if not os.path.exists(path):
os.mkdir(path)
return path
def mkNames(self):
rn = self.runNum
rns = "%(rn)d" % vars()
rns = string.rjust(rns, 5)
rns = string.replace(rns,' ','0')
rId = "_run" + rns
if self.useLizard:
self.xmlStore = self.storeName + rId + ".xml"
self.pathXMLName = self.path + "/" + self.xmlStore
self.shelveName = self.storeName + rId + ".shelve"
self.pathShelveName = self.path + "/" + self.shelveName
self.randomNumberFileName = self.path + "/randomNumberFile" + rId
def mkShelve(self):
myShelve = shelve.open(self.pathShelveName)
if self.useLizard:
myShelve["xmlStoreName"] = self.xmlStore
for info in self.confInfo:
myShelve[info] = self.confInfo[info]
myShelve.close()
# end of RunSeuence
@@ -0,0 +1,119 @@
# $Id: slabGeometry.py,v 1.3 2003/06/20 12:41:07 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
import math
import G4Kernel
import parallelHall
import posLog
class SlabedGeometry(object):
def __init__(self, tiaraSpecs, cellWidth, parallelGeo):
self.arrPosLogVol = []
self.normalCellSolid = None
self.logNormCell = None
self.lastCellSolid = None
self.logLastCell = None
self.createCells(tiaraSpecs, cellWidth, parallelGeo)
def createCells(self, tiaraSpecs, cellWidth, parallelGeo):
print "SlabedGeometry::createCells:"
print "halfLength", parallelGeo.halfLength,\
"halfWidth", parallelGeo.halfWidth
nCells = int(tiaraSpecs.experiment.shieldWidth / cellWidth)
print "cellWidth", cellWidth
print "nCells", nCells
zCellStart = tiaraSpecs.dimensions.targetPosZ + \
tiaraSpecs.dimensions.distTargetExperiment + \
tiaraSpecs.experiment.colWidth
print "zCellStart", zCellStart
zCellRegion = parallelGeo.halfLength - zCellStart
print "zCellRegion", zCellRegion
lengthLastCell = zCellRegion - nCells * cellWidth
print "lengthLastCell", lengthLastCell
print "sum cell length:", lengthLastCell + nCells * cellWidth
vacuum = tiaraSpecs.materials.GetMaterial("vacuum")
self.normalCellSolid = G4Kernel.G4Box("cellBox",
parallelGeo.halfWidth,
parallelGeo.halfWidth,
cellWidth/2)
print "normal box:",parallelGeo.halfWidth,cellWidth/2
self.logNormCell = G4Kernel.G4LogicalVolume(self.normalCellSolid,
vacuum,
"cellLog")
zPos = zCellStart - 0.5 * cellWidth
for i in range(nCells):
zPos += cellWidth
self.arrPosLogVol.append(posLog.PosLog(zPos, self.logNormCell))
print "zPos", zPos
self.lastCellSolid = G4Kernel.G4Box("lastCellBox",
parallelGeo.halfWidth,
parallelGeo.halfWidth,
lengthLastCell/2)
self.logLastCell = G4Kernel.G4LogicalVolume(self.lastCellSolid,
vacuum,
"lastCellLog")
print "last cell:", parallelGeo.halfWidth, lengthLastCell/2
zPos += cellWidth/2+lengthLastCell/2
self.arrPosLogVol.append(posLog.PosLog(zPos, self.logLastCell))
print "last cell zPos", zPos
def getArrPosLogVol(self):
return self.arrPosLogVol
class SlabedImportanceGeometry(object):
def __init__(self, tiaraSpecs, cellWidth, impBase, parallelGeo = None):
self.parallelGeo = parallelGeo
self.tiaraSpecs = tiaraSpecs
self.cellWidth = cellWidth
self.iStore = None
self.geometryCells = []
self.base = impBase
cellwidth_cm = cellWidth / CLHEP.cm
self.nameExt = "-cellWidth_%(cellwidth_cm)d" %vars()
self.buildParallelGeometry()
self.setImportances()
def buildParallelGeometry(self):
self.parallelGeo = parallelHall.ParallelHall(self.tiaraSpecs)
self.slabedGeo = SlabedGeometry(self.tiaraSpecs,
self.cellWidth,
self.parallelGeo)
self.parallelGeo.placeCells(self.slabedGeo.getArrPosLogVol())
self.iStore = G4Kernel.G4IStore(self.parallelGeo.getWorldVolume())
self.geometryCells = self.parallelGeo.getGeometryCells()
def setImportances(self):
worldCell = G4Kernel.G4GeometryCell(self.parallelGeo.\
getWorldVolume(), 0)
self.iStore.AddImportanceGeometryCell(1, worldCell)
nCells = len(self.geometryCells)
for i in range(nCells-1):
cell = self.geometryCells[i]
importance = math.pow(self.base, i)
print "i=", importance
self.iStore.AddImportanceGeometryCell(importance, cell)
lastCell = self.geometryCells[nCells-1]
importance = math.pow(self.base, nCells-2)
print "last cells i=", importance
self.iStore.AddImportanceGeometryCell(importance, lastCell)
def getWorldVolume(self):
return self.parallelGeo.getWorldVolume()
def getImportanceStore(self):
return self.iStore
@@ -0,0 +1,72 @@
# $Id: tallyData.py,v 1.2 2003/06/16 17:06:44 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
class MeasureData:
def __init__(self, entries, mean, sum, sumSquared, variance):
self.entries = entries
self.mean = mean
self.sum = sum
self.sumSquared = sumSquared
self.variance = variance
def __iadd__(self,m):
self.entries += m.entries
self.sum += m.sum
self.sumSquared += m.sumSquared
self.mean = self.getMean()
self.variance = self.getVariance()
return self
def __add__(self,b):
c = MeasureData(self.entries,
self.mean,
self.sum,
self.sumSquared,
self.variance)
c+=b
return c
def getMean(self):
return 1.0 * self.sum / self.entries
def getVariance(self):
n = 0
f = 0
if self.entries > 1:
mean = self.getMean()
n = 1.0 * self.entries/(self.entries -1)
f = 1.0 * self.sumSquared/self.entries - mean*mean
return n * f
class TallyData:
def __init__(self, binEdges, measures):
self.binEdges = binEdges
self.measures = measures
def addMeasures(self, tally):
if tally.binEdges != self.binEdges:
print "TallyData.addMeasures: tally.binEdges != self.binEdges"
else:
for i in range(len(self.measures)):
self.measures[i] += tally.measures[i]
def createTallyDat(tally):
measures = []
for i in range(tally.size()):
m = tally.measure(i)
measures.append(MeasureData(m.GetEntries(),
m.GetMean(),
m.GetSum(),
m.GetSumSquared(),
m.GetVariance()))
t = TallyData(tally.binEdges(), measures)
return t
@@ -0,0 +1,223 @@
# $Id: tiaraApplication.py,v 1.3 2003/06/16 17:06:44 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
import string
import CLHEP
import G4Kernel
import Tiara
import tiaraSpecifications
import tallyData
class TiaraApplet(object):
tiaraSim = None
def __init__(self, tiaraSpecs, tSim = None, useLizard = True):
if useLizard:
import myLiz
self.tree = myLiz.tf.create()
self.hf = myLiz.af.createHistogramFactory (self.tree)
else:
self.tree = None
self.hf = None
if (not TiaraApplet.tiaraSim):
if not tSim:
print "Error: TiaraApplet: argument is empty, and no tiaraSim exists!"
else:
TiaraApplet.tiaraSim = tSim
self.tiaraSpecs = tiaraSpecs
self.tiaraHall = Tiara.TiaraGeometry(self.tiaraSpecs.\
materials)
self.cellScorerStore = Tiara.TiaraCellScorerStore()
self.sampler = G4Kernel.G4MassGeometrySampler("neutron")
self.eventAction = None
self.scorer = None
self.primGen = None
self.scSrc = None
self.physicsList = None
self.nameExt = ""
self.scoreDets = []
self.scoreDetectorCreator = None
self.noComponents = 0
self.createdDPS = 0
self.tiaraSim.SetGeometry(self.tiaraHall)
def setScoreDetectorCreator(self, creator):
self.scoreDetectorCreator=creator
def visMode(self):
if self.eventAction:
print "TiaraApplet.visMode(): event action exists already"
else:
self.eventAction = Tiara.TiaraVisEventAction()
self.tiaraSim.AddVisRunAction()
self.tiaraSim.AddTiaraEventAction(self.eventAction)
return
def timedMode(self, time, randomNumFileName = ""):
if self.eventAction:
print "TiaraApplet.timedMode(): event action exists already"
else:
self.eventAction = Tiara.TiaraTimedEventAction(time)
if randomNumFileName:
self.eventAction.SetRnadomNumFilename(randomNumFileName)
self.tiaraSim.AddTiaraEventAction(self.eventAction)
return
def specifyPhysicsList(self, pl, particleCut):
self.particleCut = particleCut
self.physicsList = pl
def buildColimator(self):
posColi = \
CLHEP.Hep3Vector(0,0, self.tiaraSpecs.
dimensions.targetPosZ +
self.tiaraSpecs.
dimensions.distTargetExperiment +
self.tiaraSpecs.\
experiment.colWidth/2)
logCol = self.tiaraHall.BuildCollimator(self.tiaraSpecs.\
experiment.colWidth,
"iron",
"air")
self.tiaraHall.PlaceExpComponent(posColi,
logCol,
"colimator")
return
def buildShield(self):
log = self.tiaraHall.BuildShield(self.tiaraSpecs.\
experiment.shieldWidth,
self.tiaraSpecs.\
experiment.shieldMaterial)
posShield = CLHEP.Hep3Vector(0,0, self.tiaraSpecs.
dimensions.targetPosZ +
self.tiaraSpecs.
dimensions.
distTargetExperiment +
self.tiaraSpecs.experiment.
colWidth +
self.tiaraSpecs.experiment.\
shieldWidth/2)
self.tiaraHall.PlaceExpComponent(posShield, log, "shield")
return
def buildGeometry(self):
self.tiaraHall.BuildGeometry(self.tiaraSpecs.dimensions)
if self.noComponents != 1:
self.tiaraHall.CreateComponents()
if self.tiaraSpecs.experiment.colWidth > 0:
self.buildColimator()
self.buildShield()
def createCellScorers(self):
self.cellScorer = []
tally = Tiara.TiaraTally()
tally.setBinEdges(tiaraSpecifications.\
tallyBinEdges[self.tiaraSpecs.\
experiment.energy])
for det in self.scoreDets:
det.scorer = None
if self.hf:
det.scorer = \
Tiara.\
TiaraCellScorer(self.hf,
det.name,
self.tiaraSpecs.
experiment.binEdgesScinti,
self.tiaraSpecs.
experiment.binEdgesBonner,
tally)
else:
det.scorer = \
Tiara.\
TiaraCellScorer(det.name,
tally)
self.cellScorer.append(det.scorer)
def buildDetectors(self):
tally = Tiara.TiaraTally()
tally.setBinEdges(tiaraSpecifications.\
tallyBinEdges[self.tiaraSpecs.
experiment.energy])
physSrcDet = self.tiaraHall.AddSourceDetector()
self.scSrc = None
if self.hf:
self.scSrc = Tiara.\
TiaraCellScorer(self.hf,
"source_detector",
self.tiaraSpecs.
experiment.binEdgesScinti,
self.tiaraSpecs.
experiment.binEdgesBonner,
tally)
else:
self.scSrc = Tiara.\
TiaraCellScorer("source_detector",
tally)
self.scoreDets = self.scoreDetectorCreator.\
createScoreDetectors(self.tiaraHall)
self.createCellScorers()
self.cellScorerStore.AddTiaraCellScorer(self.scSrc,
G4Kernel.G4GeometryCell(physSrcDet,
0))
for det in self.scoreDets:
self.cellScorerStore.AddTiaraCellScorer(det.scorer,
G4Kernel.\
G4GeometryCell(det.
phys,
0))
self.scorer = G4Kernel.G4CellStoreScorer(self.cellScorerStore.
GetG4VCellScorerStore())
self.eventAction.SetScorerStore(self.cellScorerStore)
return
def setPrimaryGenerator(self, primGen):
self.primGen = primGen
self.tiaraSim.SetPrimaryGenerator(self.primGen)
return
def fillShelve(self, shelveDB):
t = self.primGen.GetTally()
shelveDB["generatorTally"] = tallyData.createTallyDat(t)
t = self.scSrc.GetTally()
shelveDB["sourceDetectorTally"] = tallyData.createTallyDat(t)
for det in self.scoreDets:
t = det.scorer.GetTally()
shelveDB[det.name + "Tally"] = tallyData.createTallyDat(t)
shelveDB["runTime"] = self.eventAction.GetTotalProcessedTime()
def config(self):
self.tiaraSim.SetPhysicsList(self.physicsList)
self.buildDetectors()
self.tiaraSim.initialize()
if len(self.particleCut) > 0:
for p in self.particleCut:
self.tiaraSim.AddParticleCut(p, self.particleCut[p]);
self.sampler.PrepareScoring(self.scorer)
self.sampler.Configure()
@@ -0,0 +1,42 @@
# $Id: tiaraDetectors.py,v 1.3 2003/06/20 12:41:07 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
import CLHEP
import G4Kernel
class ScoreDetector(object):
def __init__(self, name):
self.name = name
self.phys = ""
self.scorer = ""
class DetectorSlab(object):
def __init__(self):
pass
def createScoreDetectors(self, tiaraHall):
scoreDets = []
scoreDets.append(ScoreDetector("detectorSlab"))
scoreDets[0].phys = tiaraHall.AddDetectorSlab(scoreDets[0].name)
print "+++ DetectorSlab: created slab detector."
return scoreDets
class ThreeZylindricDetectors(object):
def __init__(self):
pass
def createScoreDetectors(self, tiaraHall):
scoreDets = []
scoreDets.append(ScoreDetector("detector_00"))
scoreDets.append(ScoreDetector("detector_20"))
scoreDets.append(ScoreDetector("detector_40"))
dist = 0.0
for det in scoreDets:
if dist > 0.0:
det.phys = tiaraHall.AddPhysicalRingDetector(dist,
det.name)
else:
det.phys = tiaraHall.AddPhysicalDetector(dist, det.name)
dist += 20*CLHEP.cm
print "+++ ThreeZylindricDetectors: created 3 zylindric detectors"
return scoreDets
@@ -0,0 +1,93 @@
# $Id: tiaraGenerators.py,v 1.2 2003/06/16 17:06:44 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
import string
import tiaraSpecifications
import Tiara
import os
tiara_dir = os.environ["TIARA_BASE"]
class TiaraPrimaryGenerator(object):
def __init__(self, tiaraSpecs):
self.name = "preIntegratedSource"
self.eSamp = Tiara.TiaraSampledEnergy(\
tiaraSpecs.experiment.energy,
tiaraSpecs.experiment.minNeutronEnergyCut,
tiara_dir + "/data/expDataConverted/source.xml",
"_v3")
self.tally = Tiara.TiaraTally()
self.tally.setBinEdges(tiaraSpecifications.\
sourceTallyEdges[tiaraSpecs.experiment.energy])
self.directionGenerator = Tiara.TiaraIsotropicDirections(\
0,
tiaraSpecs.dimensions)
self.primGen = Tiara.TiaraPrimaryGeneratorAction(\
self.eSamp,
self.directionGenerator,
self.tally,
tiaraSpecs.dimensions)
return
class TiaraDPSEnergyGenerator(object):
def __init__(self, tiaraSpecs, xmlName):
self.Name = "dpsSource"
self.eSamp = Tiara.\
TiaraDPSSampledEnergy(tiaraSpecs.
experiment.energy,
tiaraSpecs.
experiment.minNeutronEnergyCut,
xmlName,
"")
self.tally = Tiara.TiaraTally()
if string.find(xmlName,"other") > -1:
if tiaraSpecs.experiment.energy == "43":
self.tally.setBinEdges([0,37.5, 43,50])
else:
if tiaraSpecs.experiment.energy == "68":
self.tally.setBinEdges([0,61, 69,80])
else:
self.tally.setBinEdges(tiaraSpecifications.\
sourceTallyEdges[tiaraSpecs.
experiment.energy])
self.directionGenerator = Tiara.TiaraIsotropicDirections(\
0,
tiaraSpecs.dimensions)
self.primGen = Tiara.TiaraPrimaryGeneratorAction(\
self.eSamp,
self.directionGenerator,
self.tally,
tiaraSpecs.dimensions)
return
class FixedEnergyPrimaryGenerator(object):
def __init__(self, tiaraSpecs):
self.name = "fixedSource"
self.eSamp = Tiara.TiaraFixedEnergyGenerator(\
float(tiaraSpecs.experiment.energy))
self.tally = Tiara.TiaraTally()
self.tally.setBinEdges(tiaraSpecifications.\
sourceTallyEdges[tiaraSpecs.
experiment.energy])
self.directionGenerator = Tiara.TiaraIsotropicDirections(\
0,
tiaraSpecs.dimensions)
self.primGen = Tiara.TiaraPrimaryGeneratorAction(\
self.eSamp,
self.directionGenerator,
self.tally,
tiaraSpecs.dimensions)
return
@@ -0,0 +1,100 @@
# $Id: tiaraSpecifications.py,v 1.3 2003/06/20 12:41:07 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
import CLHEP
import G4Kernel
ColWidth = {"43":40*CLHEP.cm,
"68":80*CLHEP.cm}
BinEdgesScinti = {"43":range(4,45),
"68":range(6,45) + range(46,71,2)}
BinEdgesBonner = {"43": [4.500E+07,
3.500E+07,
2.750E+07,
2.250E+07,
1.750E+07,
1.350E+07,
1.000E+07,
6.700E+06,
4.490E+06,
3.010E+06,
2.020E+06,
1.350E+06,
9.070E+05,
4.980E+05,
2.240E+05,
8.650E+04,
1.500E+04,
3.350E+03,
4.540E+02,
2.260E+01,
5.040E+00,
1.120E+00,
4.140E-01,
1.000E-04],
"68": [ 8.000E+07,
6.500E+07,
5.500E+07,
4.500E+07,
3.500E+07,
2.750E+07,
2.250E+07,
1.750E+07,
1.350E+07,
1.000E+07,
6.700E+06,
4.490E+06,
3.010E+06,
2.020E+06,
1.350E+06,
9.070E+05,
4.980E+05,
2.240E+05,
8.650E+04,
1.500E+04,
3.350E+03,
4.540E+02,
2.260E+01,
5.040E+00,
1.120E+00,
4.140E-01,
1.000E-04]}
tallyBinEdges = {}
tallyBinEdges["43"] = [0,10,35,45]
tallyBinEdges["68"] = [0,10,60,70]
sourceTallyEdges = {}
sourceTallyEdges["43"] = [0,36.3, 45.5,50]
sourceTallyEdges["68"] = [0,60.8, 72.5,80]
class Experiment(object):
def __init__(self,
energy,
minNeutronEnergyCut,
particleCut,
shieldWidth,
shieldMaterial):
self.energy = "%(energy)d" % vars()
self.minNeutronEnergyCut = minNeutronEnergyCut
self.particleCut = particleCut
self.shieldWidth = shieldWidth
self.shieldMaterial = shieldMaterial
self.binEdgesBonner = BinEdgesBonner[self.energy]
self.binEdgesScinti = BinEdgesScinti[self.energy]
self.colWidth = 0
if self.shieldWidth <= 50.0*CLHEP.cm:
self.colWidth = ColWidth[self.energy]
class Specifications(object):
def __init__(self,dimensions, experiment, materials):
self.dimensions = dimensions
self.experiment = experiment
self.materials = materials
@@ -0,0 +1,137 @@
# $Id: variableGeometry.py,v 1.2 2003/06/16 17:06:45 dressel Exp $
# -------------------------------------------------------------------
# GEANT4 tag $Name: geant4-05-02 $
# -------------------------------------------------------------------
#
import G4Kernel
import parallelHall
import posLog
class VariableSlobedGeometry(object):
def __init__(self,\
tiaraSpecs,
cellSizeImportanceList,
parallelGeo):
self.arrPosLogVol = []
self.normalCellSolids = []
self.logNormCells = []
self.lastCellSolid = None
self.logLastCell = None
self.createCells(tiaraSpecs,
cellSizeImportanceList, parallelGeo)
def createCells(self, tiaraSpecs,
cellSizeImportanceList, parallelGeo):
nImps = len(cellSizeImportanceList)
zCellStart = tiaraSpecs.dimensions.targetPosZ + \
tiaraSpecs.dimensions.distTargetExperiment + \
tiaraSpecs.experiment.colWidth
zCellRegion = parallelGeo.halfLength - zCellStart
print "zCellStart", zCellStart, "zCellRegion", zCellRegion
vacuum = tiaraSpecs.materials.GetMaterial("vacuum")
for i in range(nImps):
ncsName = "cellBox_%(i)d" % vars()
print "i", i, "cswidth", cellSizeImportanceList[i]["width"]
ncs = G4Kernel.G4Box(ncsName,
parallelGeo.halfWidth,
parallelGeo.halfWidth,
0.5 * cellSizeImportanceList[i]["width"])
self.normalCellSolids.append(ncs)
nclName = "cellLog_%(i)d" % vars()
ncl = G4Kernel.G4LogicalVolume(ncs,
vacuum,
nclName)
self.logNormCells.append(ncl)
zPos = zCellStart
for i in range(nImps):
zPos += 0.5 * cellSizeImportanceList[i]["width"]
print "zPos", zPos, "cellNum", i
self.arrPosLogVol.append(posLog.PosLog(zPos, self.logNormCells[i]))
zPos += 0.5 * cellSizeImportanceList[i]["width"]
allCellWidth = 0.0
for i in range(nImps):
allCellWidth+=cellSizeImportanceList[i]["width"]
print "allCellWidth", allCellWidth
lengthLastCell = zCellRegion - allCellWidth
self.lastCellSolid = G4Kernel.G4Box("lastCellBox",
parallelGeo.halfWidth,
parallelGeo.halfWidth,
lengthLastCell/2)
self.logLastCell = G4Kernel.G4LogicalVolume(self.lastCellSolid,
vacuum,
"lastCellLog")
zPos += lengthLastCell/2
print "last cell zPos", zPos, "length", lengthLastCell
self.arrPosLogVol.append(posLog.PosLog(zPos, self.logLastCell))
def getArrPosLogVol(self):
return self.arrPosLogVol
class VariableImpSlabGeometry(object):
def __init__(self, tiaraSpecs,
parallelGeo = None):
self.tiaraSpecs = tiaraSpecs
self.cellSizeImportanceList = []
self.parallelGeo = parallelGeo
self.iStore = None
self.geometryCells = []
self.base = 0.0
self.nameExt = "-variableCellWidth"
def addCellImportance(self, width, faktor):
self.cellSizeImportanceList.append(
{"width":width, "faktor":faktor})
def construct(self):
nImps = len(self.cellSizeImportanceList)
if nImps>0:
for i in range(nImps):
self.base+=1.0*self.cellSizeImportanceList[i]["faktor"]
self.base/=nImps
self.createParallelGeometry(self.tiaraSpecs)
self.setImportances()
def createParallelGeometry(self, tiaraSpecs):
self.parallelGeo = parallelHall.ParallelHall(tiaraSpecs)
self.slobedGeo = VariableSlobedGeometry(\
tiaraSpecs,
self.cellSizeImportanceList,
self.parallelGeo)
self.parallelGeo.placeCells(self.slobedGeo.getArrPosLogVol())
self.iStore = G4Kernel.G4IStore(self.parallelGeo.getWorldVolume())
self.geometryCells = self.parallelGeo.getGeometryCells()
def setImportances(self):
worldCell = G4Kernel.G4GeometryCell(self.parallelGeo.\
getWorldVolume(), 0)
self.iStore.AddImportanceGeometryCell(1, worldCell)
nCells = len(self.geometryCells)
nImps = len(self.cellSizeImportanceList)
if ((nCells - 1) != nImps):
print "VariableImpSlabGeometry: ERROR importances and cells don't mach!", nCells, nImps
importance = 1
for i in range(nImps):
cell = self.geometryCells[i]
importance*=self.cellSizeImportanceList[i]["faktor"]
print "i=", importance
self.iStore.AddImportanceGeometryCell(importance, cell)
lastCell = self.geometryCells[nCells-1]
print "last cells i=", importance
self.iStore.AddImportanceGeometryCell(importance, lastCell)
def getWorldVolume(self):
return self.parallelGeo.getWorldVolume()
def getImportanceStore(self):
return self.iStore