SND@LHC Software
Loading...
Searching...
No Matches
thermalNeutrons.py
Go to the documentation of this file.
1#!/usr/bin/env python
2import ROOT
3from decorators import *
4
5# setenv NeutronHPCrossSections ${G4NEUTRONHPDATA} see https://geant4.web.cern.ch/sites/geant4.web.cern.ch/files//geant4/support/training/users_workshop_2002/lectures/models.pdf
6
7import os
8import shipunit as u
9from argparse import ArgumentParser
10ROOT.gROOT.ProcessLine('#include "Geant4/G4UIterminal.hh"')
11ROOT.gROOT.ProcessLine('#include "Geant4/G4Neutron.hh"')
12ROOT.gROOT.ProcessLine('#include "Geant4/G4ProcessManager.hh"')
13ROOT.gROOT.ProcessLine('#include "Geant4/G4ParticleHPThermalScattering.hh"')
14ROOT.gROOT.ProcessLine('#include "Geant4/G4ParticleHPElastic.hh"')
15ROOT.gROOT.ProcessLine('#include "Geant4/G4HadronElasticProcess.hh"')
16ROOT.gROOT.ProcessLine('#include "Geant4/G4HadronicProcessStore.hh"')
17ROOT.gROOT.ProcessLine('#include "Geant4/G4ParticleHPThermalScatteringData.hh"')
18ROOT.gROOT.ProcessLine('#include "Geant4/G4ParticleHPElasticData.hh"')
19ROOT.gROOT.ProcessLine('#include "Geant4/G4GenericPhysicsList.hh"')
20ROOT.gROOT.ProcessLine('#include "Geant4/G4RunManager.hh"')
21ROOT.gROOT.ProcessLine('#include "Geant4/G4TransportationManager.hh"')
22
23ROOT.gRandom.SetSeed()
24
25parser = ArgumentParser()
26parser.add_argument("-b", "--heartbeat", dest="heartbeat", type=int, help="progress report", default=10000)
27parser.add_argument("-n", "--nEvents", dest="nEvents", type=int, help="number of events", default=100)
28parser.add_argument("-r", "--run", dest="run", type=int, help="production sequence number", default=0)
29parser.add_argument('--material', dest='targetMaterial', type=str,help="target material BoronCarbide or Boratedpolyethylene", default="BoronCarbide")
30parser.add_argument('--thick', dest='targetLength', type=float,help="target thickness", default=0.1)
31parser.add_argument('-c', '--command', dest='command', help="command")
32parser.add_argument("--Estart", dest="Estart", help="start of energy range of particle gun (default= 0 MeV)", required=False, default=1E-20, type=float)
33parser.add_argument("--Eend", dest="Eend", help="end of energy range of particle gun (default=10 MeV)", required=False, default=0.01, type=float)
34parser.add_argument("--pID", dest="pID", help="id of particle used by the gun (default=2112)", required=False, default=2112, type=int)
35parser.add_argument("--setup", dest="neutron", help="setup for absorptionLength or neutron in cold box)", required=False, action='store_true')
36options = parser.parse_args()
37
38# -------------------------------------------------------------------
39logEstart = int(ROOT.TMath.Log10(options.Estart))
40logEend = int(ROOT.TMath.Log10(options.Eend))
41outFile = 'thermNeutron_'+options.targetMaterial+'_'+str(options.targetLength)+'_'+str(logEstart)+'_'+str(logEend)+'_'+str(options.run)+'.root'
42if options.neutron: outFile = 'thermNeutron_%s_%s_coldbox_%s-%iM.root'%(options.targetMaterial,str(options.targetLength),str(options.run),options.nEvents/1000000.)
43parFile = outFile.replace('thermNeutron','params-thermNeutron')
44
45# -----Timer--------------------------------------------------------
46timer = ROOT.TStopwatch()
47timer.Start()
48
49# -----Create simulation run----------------------------------------
50run = ROOT.FairRunSim()
51run.SetName('TGeant4') # Transport engine
52run.SetSink(ROOT.FairRootFileSink(outFile)) # Output file
53run.SetUserConfig("g4ConfigNeutron.C") # user configuration file default g4Config.C
54
55# -----Create PrimaryGenerator--------------------------------------
56primGen = ROOT.FairPrimaryGenerator()
57
58if options.neutron:
59 Neutrongen = ROOT.NeutronGenerator_FLUKA()
60 primGen.AddGenerator(Neutrongen)
61else:
62 myPgun = ROOT.FairBoxGenerator(options.pID,1)
63 myPgun.SetEkinRange(options.Estart,options.Eend)
64 myPgun.SetPhiRange(0, 0) # // Azimuth angle range [degree]
65 myPgun.SetThetaRange(0,0)
66 myPgun.SetXYZ(0.,0.,-1.)
67 primGen.AddGenerator(myPgun)
68 ROOT.FairLogger.GetLogger().SetLogScreenLevel("WARNING") # otherwise stupid printout for each event
69
70# -----Materials----------------------------------------------
71run.SetMaterials("media.geo")
72# -----Create geometry----------------------------------------------
73cave = ROOT.ShipCave("CAVE")
74cave.SetGeometryFileName("caveXS.geo")
75run.AddModule(cave)
76
77target = ROOT.boxTarget()
78target.SetTarget(options.targetMaterial,options.targetLength*u.cm,not options.neutron)
79run.AddModule(target)
80
81#
82run.SetGenerator(primGen)
83
84# -----Initialize simulation run------------------------------------
85run.Init()
86from decorators import *
87
88neutron = ROOT.G4Neutron.Neutron()
89pManager = neutron.GetProcessManager()
90
91thermal = False
92if thermal:
93 process = pManager.GetProcess("hadElastic")
94 if process: pManager.RemoveProcess(process)
95 process1 = ROOT.G4HadronElasticProcess()
96 pManager.AddDiscreteProcess(process1)
97 model1a = ROOT.G4ParticleHPElastic()
98 eV = 1E-6
99 model1a.SetMinEnergy(4*eV) # valid after ThermalScattering, EMax 4 eV, 1 = MeV
100 process1.RegisterMe(model1a)
101 process1.AddDataSet(ROOT.G4ParticleHPElasticData())
102 model1b = ROOT.G4ParticleHPThermalScattering()
103 process1.RegisterMe(model1b)
104 process1.AddDataSet(ROOT.G4ParticleHPThermalScatteringData())
105pManager.DumpInfo()
106
107gMC = ROOT.TVirtualMC.GetMC()
108fStack = gMC.GetStack()
109fStack.SetMinPoints(-1)
110fStack.SetEnergyCut(-1.)
111
112# -----Start run----------------------------------------------------
113run.Run(options.nEvents)
114
115# -----Finish-------------------------------------------------------
116timer.Stop()
117rtime = timer.RealTime()
118ctime = timer.CpuTime()
119print(' ')
120print("Macro finished succesfully.")
121print("Output file is ", outFile)
122print("Real time ",rtime, " s, CPU time ",ctime,"s")
123
124run.CreateGeometryFile("geofile-"+outFile)
125sGeo = ROOT.gGeoManager
126sGeo.SetNmeshPoints(10000)
127sGeo.CheckOverlaps(0.1) # 1 micron takes 5minutes
128sGeo.PrintOverlaps()
129
130
131h={}
132import rootUtils as ut
133def count(hFile = outFile):
134 f=ROOT.TFile(hFile)
135 ut.bookHist(h,'E',';log10(Ekin [MeV])',1000,-10.,4.)
136 ut.bookHist(h,'Epassed',';log10(Ekin [MeV])',1000,-10.,4.)
137 ut.bookHist(h,'Lab',';absorption Length vs logE',1000,-10.,4.,500,-0.1,10.)
138 ut.bookHist(h,'Labz',';absorption Length vs logE',1000,-10.,4.,500,-0.1,10.)
139 ut.bookHist(h,'xyz','', 100,-0.1,0.1,100,-0.1,0.1,200,-1.,1.)
140 ut.bookHist(h,'dxyz','',100,-0.1,0.1,100,-0.1,0.1,200,-1.,1.)
141 ut.bookHist(h,'Epassed',';log10(Ekin [MeV])',1000,-10.,4.)
142 Npassed = 0
143 for sTree in f.cbmsim:
144 N = sTree.MCTrack[0]
145 Ekin = N.GetP()**2/(2*N.GetMass())*1000.
146 logEkin = ROOT.TMath.Log10(Ekin)
147 rc = h['E'].Fill(logEkin)
148 for p in sTree.vetoPoint:
149 if not p.PdgCode()==2112: continue
150 if p.GetDetectorID()==1 :
151 mean = ROOT.TVector3(p.GetX(),p.GetY(),p.GetZ())
152 end = p.LastPoint()
153 D = 2*(end-mean)
154 start = 2*mean-end
155 rc = h['Lab'].Fill(logEkin,D.Mag())
156 rc = h['Labz'].Fill(logEkin,D.Z())
157 rc = h['xyz'].Fill(start.X(),start.Y(),start.Z())
158 rc = h['dxyz'].Fill(end.X(),end.Y(),end.Z())
159 else:
160 Npassed+=1
161 rc = h['Epassed'].Fill(ROOT.TMath.Log10(Ekin))
162 h['Eff'] = ROOT.TEfficiency(h['Epassed'],h['E'])
163 h['Eff'].Draw()
164 print(Npassed)
165
166pathToPlots = "/mnt/hgfs/microDisk/CERNBOX/SND@LHC/Thermal Neutrons/"
167def myPrint(tc,tname):
168 for z in ['.png','.pdf','.root']:
169 tc.Print(tname+z)
170 os.system('mv '+tname+z+' '+pathToPlots)
171
172
174 for material in ['Boratedpolyethylene','BoronCarbide']:
175 for Erange in ['-10_-8','-8_-7','-6_-4']:
176 fname = "thermNeutron_"+material+"_100.0_"+Erange+"_0.root"
177 count(fname)
178 for x in ['Lab','Labz']:
179 hname = x+'_'+material+E
180 h[hname] = h[x].ProfileX(hname,1,-1,'g')
181
182
183
184
185
187 Lfun = ROOT.TF1('Lfun','[0]*(10**x)**[1]',-9,-6)
188 Lfun.SetParameter(0,6.4)
189 Lfun.SetParameter(1,0.98)
190 hFiles = {"thermNeutron_BoronCarbide_X.XX_-E_-E_0.root":[0.08,0.3],"thermNeutron_Boratedpolyethylene_X.XX_0.root":[1.0,100.]}
191 # thermNeutron_BoronCarbide_4.0_-8_-7_0.root
192
193 Ls = {0.01:ROOT.kRed,0.1:ROOT.kOrange,0.04:ROOT.kCyan,0.4:ROOT.kBlue,4.0:ROOT.kMagenta}
194
195 for hFile in hFiles:
196 material = hFile.split('_')[1]
197 ut.bookCanvas(h,'absorb'+material,'',1200,800,1,1)
198 h['absorb'+material].cd()
199 for L in Ls:
200 l = str(L)
201 if L<3: tmp = hFile.replace("X.XX",l).replace(" _-E_-E","")
202 else: tmp = hFile.replace("X.XX",l).replace(" _-E_-E","_-8_-7")
203 count(tmp)
204 h['Eff_'+l]=h['Eff'].Clone('Eff_'+l)
205 h['L_'+l]=ROOT.TGraph()
206 h['L_'+l].SetLineColor(Ls[L])
207 h['Eff'].Draw()
208 g = h['Eff'].GetPaintedGraph()
209 for n in range(g.GetN()):
210 logE, p = g.GetPointX(n),g.GetPointY(n)
211 if p>0:
212 absL = -L/ROOT.TMath.Log(p)
213 else:
214 absL = 0
215 h['L_'+l].SetPoint(n,logE,absL)
216 ut.bookHist(h,'L',';logE; L [cm]',100,-9.,-6.)
217 h['L'].SetMaximum(hFiles[hFile][0])
218 h['L'].SetStats(0)
219 h['L'].Draw()
220 for L in Ls:
221 if L>hFiles[hFile][1]: continue
222 h['L_'+str(L)].Draw('same')
223 h['L_'+str(0.1)].Fit(Lfun)
224 myPrint(h['absorb'+material],'absorbLength'+material)
225
226
227rate = ROOT.TF1('rate','1./10**x*exp(-[0]/([1]*sqrt(10**x)))',-9,2)
228# BoronCarbide: 130cm sqrt(E/MeV) Boratedpolyethylene 1490cm sqrt(E/MeV)
229rate.SetParameter(0,1.)
230rate.SetParameter(1,130.)
231# BoronCarbide for 0.1cm: max rate at 0.13 eV 1cm: max rate at 16eV
232# Boratedpolyethylene for 0.1cm: max rate at <0.01 eV 1cm: max rate at 0.13 eV 4cm: max rate at 1.6 eV
233# attenuation of 1E-7 required.
234
235rate.Draw()
236
237import hepunit as G4Unit
238ROOT.gROOT.ProcessLine('#include "Geant4/G4HadronicProcessStore.hh"')
239
241 neutron = ROOT.G4Neutron.Neutron()
242 neutron.DumpTable()
243 pManager = neutron.GetProcessManager()
244 pManager.DumpInfo()
245 for p in pManager.GetProcessList():
246 p.DumpInfo()
247 store = ROOT.G4HadronicProcessStore.Instance()
248 store.Dump(1)
249 runManager = ROOT.G4RunManager.GetRunManager()
250 gt = ROOT.G4TransportationManager.GetTransportationManager()
251 gn = gt.GetNavigatorForTracking()
252 world = gn.GetWorldVolume().GetLogicalVolume()
253 vmap = {}
254 for da in range(world.GetNoDaughters()):
255 vl = world.GetDaughter(da)
256 vmap[vl.GetName().c_str()] = vl
257 lvl = vl.GetLogicalVolume()
258 mat = lvl.GetMaterial()
259 print("%2i %s %5.3F g/cm3 %5.2F kg %s"%(da, vl.GetName(),mat.GetDensity()/G4Unit.g*G4Unit.cm3,lvl.GetMass()/G4Unit.kg,mat.GetName()))
260 for n in range(mat.GetNumberOfElements()):
261 element = mat.GetElement(n)
262 print(" %2i %s %4.1F %5.4F "%(n,element.GetName(),element.GetAtomicMassAmu(),mat.GetFractionVector()[n]))
count(hFile=outFile)