SND@LHC Software
Loading...
Searching...
No Matches
run_simSND.py
Go to the documentation of this file.
1#!/usr/bin/env python
2import os
3import sys
4import ROOT
5import numpy as np
6
7import shipunit as u
8import shipRoot_conf
9import rootUtils as ut
10from ShipGeoConfig import ConfigRegistry
11from argparse import ArgumentParser
12
13mcEngine = "TGeant4"
14simEngine = "Pythia8" # "Genie" # Ntuple
15inactivateMuonProcesses = False
16
17MCTracksWithHitsOnly = False # copy particles which produced a hit and their history
18MCTracksWithEnergyCutOnly = True # copy particles above a certain kin energy cut
19MCTracksWithHitsOrEnergyCut = False # or of above, factor 2 file size increase compared to MCTracksWithEnergyCutOnly
20
21parser = ArgumentParser()
22
23parser.add_argument("--H6", dest="testbeam", help="use geometry of H8/H6 testbeam setup", action="store_true")
24parser.add_argument("--HX", dest="testbeam2023", help="use geometry of 2023 testbeam setup", action="store_true")
25parser.add_argument("--H4", dest="testbeam2024", help="use geometry of 2024 testbeam setup", action="store_true")
26parser.add_argument("--target", help="target material for the 2024 testbeam setup", choices=["W","Fe"], default="W", type = str)
27parser.add_argument("--Genie", dest="genie", help="Genie for reading and processing neutrino interactions (1 standard, 2 FLUKA, 3 Pythia, 4 GENIE geometry driver)", required=False, default = 0, type = int)
28parser.add_argument("--Ntuple", dest="ntuple", help="Use ntuple as input", required=False, action="store_true")
29parser.add_argument("--MuonBack",dest="muonback", help="Generate events from muon background file, --Cosmics=0 for cosmic generator data", required=False, action="store_true")
30parser.add_argument("--Pythia8", dest="pythia8", help="Use Pythia8", required=False, action="store_true")
31parser.add_argument("--PG", dest="pg", help="Use Particle Gun", required=False, action="store_true")
32parser.add_argument("--pID", dest="pID", help="id of particle used by the gun (default=22)", required=False, default=22, type=int)
33parser.add_argument("--Estart", dest="Estart", help="start of energy range of particle gun for muflux detector (default=10 GeV)", required=False, default=10, type=float)
34parser.add_argument("--Eend", dest="Eend", help="end of energy range of particle gun for muflux detector (default=10 GeV)", required=False, default=10, type=float)
35
36parser.add_argument("--PGrunID", dest="PGrunID",help="PG run ID", required=False, type=int)
37parser.add_argument("--multiplePGSources", help="Multiple particle guns in a x-y plane at a fixed z or in a 3D volume", action="store_true")
38parser.add_argument("--EVx", dest="EVx", help="particle gun start xpos", required=False, default=0, type=float)
39parser.add_argument("--EVy", dest="EVy", help="particle gun start ypos", required=False, default=0, type=float)
40parser.add_argument("--EVz", dest="EVz", help="particle gun start zpos", required=False, default=0, type=float)
41parser.add_argument("--Dx", help="size of the full uniform spread of PG xpos", type=float)
42parser.add_argument("--Dy", help="size of the full uniform spread of PG ypos", type=float)
43parser.add_argument("--nZSlices", help="number of z slices for the PG sources", type=int)
44parser.add_argument("--zSliceStep", help="distance between the z slices for the PG sources", type=float)
45
46parser.add_argument("--FollowMuon",dest="followMuon", help="Make muonshield active to follow muons", required=False, action="store_true")
47parser.add_argument("--FastMuon", dest="fastMuon", help="Only transport muons for a fast muon only background estimate", required=False, action="store_true")
48parser.add_argument('--eMin', type=float, help="energy cut", dest='ecut', default=-1.)
49parser.add_argument('--zMax', type=float, help="max distance to apply energy cut", dest='zmax', default=70000.)
50parser.add_argument("--Nuage", dest="nuage", help="Use Nuage, neutrino generator of OPERA", required=False, action="store_true")
51parser.add_argument("--MuDIS", dest="mudis", help="Use muon deep inelastic scattering generator", required=False, action="store_true")
52parser.add_argument("-n", "--nEvents",dest="nEvents", help="Number of events to generate", required=False, default=100, type=int)
53parser.add_argument("-i", "--firstEvent",dest="firstEvent", help="First event of input file to use", required=False, default=0, type=int)
54parser.add_argument("-s", "--seed",dest="theSeed", help="Seed for random number. Only for experts, see TRrandom::SetSeed documentation", required=False, default=0, type=int)
55parser.add_argument("-f", dest="inputFile", help="Input file if not default file", required=False, default=False)
56parser.add_argument("-g", dest="geofile", help="geofile for muon shield geometry, for experts only", required=False, default=None)
57parser.add_argument("-o", "--output",dest="outputDir", help="Output directory", required=False, default=".")
58parser.add_argument("--boostFactor", dest="boostFactor", help="boost mu brems", required=False, type=float,default=0)
59parser.add_argument("--enhancePiKaDecay", dest="enhancePiKaDecay", help="decrease charged pion and kaon lifetime", required=False, type=float,default=0.)
60parser.add_argument("--debug", dest="debug", help="debugging mode, check for overlaps", required=False, action="store_true")
61parser.add_argument("-D", "--display", dest="eventDisplay", help="store trajectories", required=False, action="store_true")
62parser.add_argument("--EmuDet","--nuTargetActive",dest="nuTargetPassive",help="activate emulsiondetector", required=False,action="store_false")
63parser.add_argument("--NagoyaEmu","--useNagoyaEmulsions",dest="useNagoyaEmulsions",help="use bricks of 57 Nagoya emulsion films instead of 60 Slavich", required=False,action="store_true")
64parser.add_argument("-y", dest="year", help="specify the year to generate the respective TI18 detector setup", required=False, type=int, default=2024)
65
66options = parser.parse_args()
67
68# user hook
69userTask = False
70
71class MyTask(ROOT.FairTask):
72 "user task"
73
74 def Exec(self,opt):
75 ioman = ROOT.FairRootManager.Instance()
76 MCTracks = ioman.GetObject("MCTrack")
77 print('Hello',opt,MCTracks.GetEntries())
78 fMC = ROOT.TVirtualMC.GetMC()
79 if MCTracks.GetEntries()>100: fMC.StopRun()
80
81checking4overlaps = False
82if options.debug: checking4overlaps = True
83
84if options.pythia8: simEngine = "Pythia8"
85if options.pg: simEngine = "PG"
86if options.genie: simEngine = "Genie"
87if options.ntuple: simEngine = "Ntuple"
88if options.muonback: simEngine = "MuonBack"
89if options.nuage: simEngine = "Nuage"
90if options.mudis: simEngine = "muonDIS"
91
92if options.inputFile:
93 if options.inputFile == "none": options.inputFile = None
94 inputFile = options.inputFile
95 defaultInputFile = False
96
97if simEngine == "Genie" and defaultInputFile:
98 print('GENIE input file missing, exit')
99 sys.exit()
100if simEngine == "muonDIS" and defaultInputFile:
101 print('input file required if simEngine = muonDIS. Example:')
102 print("/eos/experiment/sndlhc/MonteCarlo/Pythia6/MuonDIS /muonDis_XXXX.root")
103 print(" XXXX = run+cycle*100+k, k: 0 or 1000 for mu+ or mu-, c: number of cycles: 10 events per incoming muon in each cycle, run: 1...10")
104 print(" c = 0 - 2: mu->proton, 5 - 7: mu->neutron")
105 sys.exit()
106if simEngine == "Nuage" and not inputFile:
107 inputFile = 'Numucc.root'
108
109if (simEngine == "Ntuple") and defaultInputFile :
110 print('input file required if simEngine = Ntuple or MuonBack. Examples:')
111 print ("crossing angle up: /eos/experiment/sndlhc/MonteCarlo/FLUKA/muons_up/version1/unit30_Nm.root (unit30_Pm.root)")
112 print ("crossing angle down: /eos/experiment/sndlhc/MonteCarlo/FLUKA/muons_down/muons_VCdown_IR1-LHC.root")
113 sys.exit()
114
115print("SND@LHC setup for",simEngine,"to produce",options.nEvents,"events")
116
117ROOT.gRandom.SetSeed(options.theSeed) # this should be propagated via ROOT to Pythia8 and Geant4VMC
118shipRoot_conf.configure(0) # load basic libraries, prepare atexit for python
119
120if options.testbeam:
121 snd_geo = ConfigRegistry.loadpy("$SNDSW_ROOT/geometry/sndLHC_H6geom_config.py")
122elif options.testbeam2023:
123 snd_geo = ConfigRegistry.loadpy("$SNDSW_ROOT/geometry/sndLHC_HXgeom_config.py",
124 tb_2023_mc = options.testbeam2023)
125elif options.testbeam2024:
126 snd_geo = ConfigRegistry.loadpy("$SNDSW_ROOT/geometry/sndLHC_H4geom_config.py",
127 tb_2024_mc = options.testbeam2024,
128 target_material = options.target)
129else:
130 snd_geo = ConfigRegistry.loadpy("$SNDSW_ROOT/geometry/sndLHC_TI18geom_config.py",
131 nuTargetPassive = options.nuTargetPassive,
132 useNagoyaEmulsions = options.useNagoyaEmulsions,
133 year=options.year)
134
135if simEngine == "PG": tag = simEngine + "_"+str(options.pID)+"-"+mcEngine
136else: tag = simEngine+"-"+mcEngine
137
138if not os.path.exists(options.outputDir):
139 os.makedirs(options.outputDir)
140if options.boostFactor>1:
141 tag+='_boost'+str(options.boostFactor)
142outFile = "%s/sndLHC.%s.root" % (options.outputDir, tag)
143
144# rm older files !!!
145for x in os.listdir(options.outputDir):
146 if not x.find(tag)<0: os.system("rm %s/%s" % (options.outputDir, x) )
147# Parameter file name
148parFile="%s/ship.params.%s.root" % (options.outputDir, tag)
149
150# In general, the following parts need not be touched, except for user task
151# ========================================================================
152
153# -----Timer--------------------------------------------------------
154timer = ROOT.TStopwatch()
155timer.Start()
156# ------------------------------------------------------------------------
157# -----Create simulation run----------------------------------------
158run = ROOT.FairRunSim()
159run.SetName(mcEngine) # Transport engine
160run.SetSink(ROOT.FairRootFileSink(outFile)) # Output file
161run.SetUserConfig("g4Config.C") # user configuration file default g4Config.C
162rtdb = run.GetRuntimeDb()
163# add user task
164if userTask:
165 userTask = MyTask()
166 run.AddTask(userTask)
167
168# -----Create geometry----------------------------------------------
169import shipLHC_conf as sndDet_conf
170modules = sndDet_conf.configure(run,snd_geo)
171
172# -----Create PrimaryGenerator--------------------------------------
173primGen = ROOT.FairPrimaryGenerator()
174
175# -----Particle Gun-----------------------
176if simEngine == "PG":
177 if not options.PGrunID:
178 print("Missing option '--PGrunID', which provides PG run ID. Set it and run again!")
179 exit()
180 myPgun = ROOT.FairBoxGenerator(options.pID,1)
181 myPgun.SetPRange(options.Estart,options.Eend)
182 myPgun.SetPhiRange(0, 360) # // Azimuth angle range [degree]
183 myPgun.SetThetaRange(0,0) # // Polar angle in lab system range [degree]
184 if options.multiplePGSources:
185 # multiple PG sources in the x-y plane; z is always the same!
186 myPgun.SetBoxXYZ(options.EVx*u.cm,
187 options.EVy*u.cm,
188 (options.EVx+options.Dx)*u.cm,
189 (options.EVy+options.Dy)*u.cm,
190 options.EVz*u.cm)
191 else:
192 # point source
193 myPgun.SetXYZ(options.EVx*u.cm, options.EVy*u.cm, options.EVz*u.cm)
194 primGen.AddGenerator(myPgun)
195 # To generate particle guns along the z axis, create z *target* layers with a set step
196 # For an **unknown** reason simply setting target z thickness doesn't produce the expected result
197 if options.multiplePGSources:
198 targetZpos = np.array(np.arange(options.nZSlices)*options.zSliceStep*u.cm, dtype='d')
199 primGen.SetMultTarget(len(targetZpos), targetZpos, 0*u.cm) # dummy thickness set to 0
200 print('===> Setting particle gun sources starting at (x1,y1,z1)='
201 f'({options.EVx},{options.EVy},{options.EVz})[cm × cm × cm] \n'
202 f'with a uniform x-y spread of (Dx,Dy)=({options.Dx},{options.Dy})[cm × cm]'
203 f' and {options.nZSlices} z slices in steps of {options.zSliceStep}[cm].')
204 run.SetPythiaDecayer('DecayConfigPy8.C')
205 ROOT.FairLogger.GetLogger().SetLogScreenLevel("WARNING") # otherwise stupid printout for each event
206# -----muon DIS Background------------------------
207if simEngine == "muonDIS":
208 ut.checkFileExists(inputFile)
209 primGen.SetTarget(0., 0.)
210 DISgen = ROOT.MuDISGenerator()
211 mu_start, mu_end = (-3.7-2.0)*u.m , -0.3*u.m # tunnel wall -30cm in front of SND
212 DISgen.SetPositions(0, mu_start, mu_end)
213 DISgen.Init(inputFile,options.firstEvent)
214 primGen.AddGenerator(DISgen)
215 options.nEvents = min(options.nEvents,DISgen.GetNevents())
216 inactivateMuonProcesses = True # avoid unwanted hadronic events of "incoming" muon flying backward
217 run.SetPythiaDecayer('DecayConfigPy8.C')
218 print('MuDIS position info input=',mu_start, mu_end)
219 print('Generate ',options.nEvents,' with DIS input', ' first event',options.firstEvent)
220
221# -----neutrino interactions from nuage------------------------
222if simEngine == "Nuage":
223 primGen.SetTarget(0., 0.)
224 Nuagegen = ROOT.NuageGenerator()
225 Nuagegen.EnableExternalDecayer(1) #with 0 external decayer is disable, 1 is enabled
226 Nuagegen.SetPositions(0., -snd_geo.EmulsionDet.zdim/2, snd_geo.EmulsionDet.zdim/2, -snd_geo.EmulsionDet.xdim/2, snd_geo.EmulsionDet.xdim/2, -snd_geo.EmulsionDet.ydim/2, snd_geo.EmulsionDet.ydim/2)
227 ut.checkFileExists(inputFile)
228 Nuagegen.Init(inputFile,options.firstEvent)
229 primGen.AddGenerator(Nuagegen)
230 options.nEvents = min(options.nEvents,Nuagegen.GetNevents())
231 run.SetPythiaDecayer("DecayConfigNuAge.C")
232 print('Generate ',options.nEvents,' with Nuage input', ' first event',options.firstEvent)
233
234# -----neutrino interactions from GENIE------------------------
235if simEngine=="Genie":
236 ut.checkFileExists(inputFile)
237 primGen.SetTarget(0., 0.) # do not interfere with GenieGenerator
238 Geniegen = ROOT.GenieGenerator()
239 Geniegen.SetGenerationOption(options.genie - 1) # 0 standard, 1 FLUKA,2 Pythia
240 Geniegen.Init(inputFile,options.firstEvent)
241 Geniegen.SetCrossingAngle(150e-6) #used only in option 2
242
243 # Neutrino vertex generation range in z:
244 # Tolerance for neutrino vertex generation range. Mostly to account for tilt in geometry alignment. Take difference in z coordinate of vertical fibres of around 0.5 cm over the fibre length, 39 cm. Assume maximum difference in z is 1 m * 0.5/39.
245 tolerance_vtx_z = 1*u.m * 0.5/39
246 # From first veto bar
247 neutrino_vtx_start_z = snd_geo.MuFilter.Veto1Dy - snd_geo.MuFilter.VetoBarZ/2. - tolerance_vtx_z
248 # To last Scifi plane
249 neutrino_vtx_end_z = snd_geo.Scifi.Ypos4 + snd_geo.Scifi.zdim/2. + tolerance_vtx_z
250
251 Geniegen.SetPositions(-480*u.m, neutrino_vtx_start_z, neutrino_vtx_end_z)
252
253 Geniegen.SetDeltaE_Matching_FLUKAGenie(10.) #energy range for the search of a GENIE interaction with similar energy of FLUKA neutrino
254 primGen.AddGenerator(Geniegen)
255 options.nEvents = min(options.nEvents,Geniegen.GetNevents())
256 run.SetPythiaDecayer('DecayConfigPy8.C')
257 print('Generate ',options.nEvents,' with Genie input for Ship@LHC', ' first event',options.firstEvent)
258
259if simEngine == "Ntuple":
260 ut.checkFileExists(inputFile)
261 Ntuplegen = ROOT.NtupleGenerator_FLUKA()
262 Ntuplegen.SetZ(snd_geo.Floor.z)
263 Ntuplegen.Init(inputFile,options.firstEvent)
264 primGen.AddGenerator(Ntuplegen)
265 options.nEvents = min(options.nEvents,Ntuplegen.GetNevents())
266 run.SetPythiaDecayer('DecayConfigPy8.C')
267
268if simEngine == "MuonBack":
269# reading muon tracks from FLUKA
270 fileType = ut.checkFileExists(inputFile)
271 if fileType == 'tree':
272 # 2018 background production
273 primGen.SetTarget(snd_geo.target.z0+70.845*u.m,0.)
274 else:
275 primGen.SetTarget(snd_geo.target.z0+50*u.m,0.)
276 #
277 MuonBackgen = ROOT.MuonBackGenerator()
278 # MuonBackgen.FollowAllParticles() # will follow all particles after hadron absorber, not only muons
279 MuonBackgen.Init(inputFile,options.firstEvent,options.phiRandom)
280 primGen.AddGenerator(MuonBackgen)
281 options.nEvents = min(options.nEvents,MuonBackgen.GetNevents())
282 MCTracksWithHitsOnly = True # otherwise, output file becomes too big
283 print('Process ',options.nEvents,' from input file, with Phi random=',options.phiRandom, ' with MCTracksWithHitsOnly',MCTracksWithHitsOnly)
284
285if options.ecut > 0:
286 modules['Floor'].SetEmin(options.ecut)
287 modules['Floor'].SetZmax(options.zmax)
288
289#
290run.SetGenerator(primGen)
291# ------------------------------------------------------------------------
292if options.followMuon :
293 if 'Veto' in modules:
294 options.fastMuon = True
295 modules['Veto'].SetFollowMuon()
296 if 'Floor' in modules:
297 modules['Floor'].MakeSensitive()
298 print('make floor sensitive')
299if options.fastMuon :
300 if 'Veto' in modules: modules['Veto'].SetFastMuon()
301 elif 'Floor' in modules:
302 modules['Floor'].SetFastMuon()
303 modules['Floor'].SetZmax(options.zmax)
304 print('transport only-muons up to z=',options.zmax)
305# ------------------------------------------------------------------------
306#---Store the visualiztion info of the tracks, this make the output file very large!!
307#--- Use it only to display but not for production!
308if options.eventDisplay: run.SetStoreTraj(ROOT.kTRUE)
309else: run.SetStoreTraj(ROOT.kFALSE)
310
311
312
313# -----Initialize simulation run------------------------------------
314run.Init()
315
316if simEngine == "PG":
317 # set the runID for
318 theHeader = run.GetMCEventHeader()
319 theHeader.SetRunID(options.PGrunID)
320
321gMC = ROOT.TVirtualMC.GetMC()
322fStack = gMC.GetStack()
323if MCTracksWithHitsOnly:
324 fStack.SetMinPoints(1)
325 fStack.SetEnergyCut(-100.*u.MeV)
326elif MCTracksWithEnergyCutOnly:
327 fStack.SetMinPoints(-1)
328 fStack.SetEnergyCut(100.*u.MeV)
329elif MCTracksWithHitsOrEnergyCut:
330 fStack.SetMinPoints(1)
331 fStack.SetEnergyCut(100.*u.MeV)
332elif options.deepCopy:
333 fStack.SetMinPoints(0)
334 fStack.SetEnergyCut(0.*u.MeV)
335
336#
337if options.boostFactor > 1:
338 ROOT.gROOT.ProcessLine('#include "Geant4/G4ProcessTable.hh"')
339 ROOT.gROOT.ProcessLine('#include "Geant4/G4MuBremsstrahlung.hh"')
340 ROOT.gROOT.ProcessLine('#include "Geant4/G4GammaConversionToMuons.hh"')
341 ROOT.gROOT.ProcessLine('#include "Geant4/G4MuPairProduction.hh"')
342 ROOT.gROOT.ProcessLine('#include "Geant4/G4AnnihiToMuPair.hh"')
343 ROOT.gROOT.ProcessLine('#include "Geant4/G4MuonToMuonPairProduction.hh"')
344 ROOT.gROOT.ProcessLine('#include "Geant4/G4MuonPlus.hh"')
345 ROOT.gROOT.ProcessLine('#include "Geant4/G4MuonMinus.hh"')
346
347 gProcessTable = ROOT.G4ProcessTable.GetProcessTable()
348 # only muon interaction
349 # procBrems = gProcessTable.FindProcess(ROOT.G4String('muBrems'),ROOT.G4String('mu+'))
350 # muPairProd = gProcessTable.FindProcess(ROOT.G4String('muPairProd'),ROOT.G4String('mu+'))
351 # muPairProd.SetCrossSectionBiasingFactor(options.boostFactor)
352 # procBrems.SetCrossSectionBiasingFactor(options.boostFactor)
353 # muon pair production
354 gammaToMuPair = gProcessTable.FindProcess(ROOT.G4String('GammaToMuPair'),ROOT.G4String('gamma'))
355 gammaToMuPair.SetCrossSecFactor(options.boostFactor)
356 AnnihiToMuPair = gProcessTable.FindProcess(ROOT.G4String('AnnihiToMuPair'),ROOT.G4String('e+'))
357 AnnihiToMuPair.SetCrossSecFactor(options.boostFactor)
358 MuonToMuonPair = gProcessTable.FindProcess(ROOT.G4String('muToMuonPairProd'),ROOT.G4String('mu+'))
359 MuonToMuonPair.SetCrossSectionBiasingFactor(options.boostFactor)
360
361 mygMC = ROOT.TGeant4.GetMC()
362 if options.debug:
363 mygMC.ProcessGeantCommand("/run/particle/dumpOrderingParam")
364 mygMC.ProcessGeantCommand("/particle/select mu+")
365 mygMC.ProcessGeantCommand("/particle/process/dump")
366 mygMC.ProcessGeantCommand("/particle/select gamma")
367 mygMC.ProcessGeantCommand("/particle/process/dump")
368 mygMC.ProcessGeantCommand("/particle/select e+")
369 mygMC.ProcessGeantCommand("/particle/process/dump")
370#
371if options.enhancePiKaDecay:
372 ROOT.gROOT.ProcessLine('#include "Geant4/G4ParticleTable.hh"')
373 ROOT.gROOT.ProcessLine('#include "Geant4/G4DecayTable.hh"')
374 ROOT.gROOT.ProcessLine('#include "Geant4/G4PhaseSpaceDecayChannel.hh"')
375 pt = ROOT.G4ParticleTable.GetParticleTable()
376 for pid in [211,-211,321,-321]:
377 particleG4 = pt.FindParticle(pid)
378 lt = particleG4.GetPDGLifeTime()
379 particleG4.SetPDGLifeTime(lt/options.enhancePiKaDecay)
380 print('### pion kaon lifetime decreased by the factor:',options.enhancePiKaDecay)
381
382if inactivateMuonProcesses :
383 ROOT.gROOT.ProcessLine('#include "Geant4/G4ProcessTable.hh"')
384 mygMC = ROOT.TGeant4.GetMC()
385 mygMC.ProcessGeantCommand("/process/inactivate muPairProd")
386 mygMC.ProcessGeantCommand("/process/inactivate muBrems")
387 #mygMC.ProcessGeantCommand("/process/inactivate muIoni") Temporary fix for DIS Simulations (incoming and outgoing muon hits)
388 mygMC.ProcessGeantCommand("/process/inactivate muonNuclear")
389 mygMC.ProcessGeantCommand("/particle/select mu+")
390 mygMC.ProcessGeantCommand("/particle/process/dump")
391 gProcessTable = ROOT.G4ProcessTable.GetProcessTable()
392 procmu = gProcessTable.FindProcess(ROOT.G4String('muIoni'),ROOT.G4String('mu+'))
393 procmu.SetVerboseLevel(2)
394
395if options.debug: ROOT.fair.Logger.SetConsoleSeverity("debug")
396# -----Start run----------------------------------------------------
397run.Run(options.nEvents)
398# -----Runtime database---------------------------------------------
399kParameterMerged = ROOT.kTRUE
400parOut = ROOT.FairParRootFileIo(kParameterMerged)
401parOut.open(parFile)
402rtdb.setOutput(parOut)
403rtdb.saveOutput()
404rtdb.printParamContexts()
405getattr(rtdb,"print")()
406# ------------------------------------------------------------------------
407geoFile = "%s/geofile_full.%s.root" % (options.outputDir, tag)
408run.CreateGeometryFile(geoFile)
409# save detector parameters dictionary in geofile
410import saveBasicParameters
411saveBasicParameters.execute(geoFile,snd_geo)
412
413# ------------------------------------------------------------------------
414# If using GENIE option 4 (geometry driver) copy GST TTree to the
415# output file. This will make it easy to access the FLUKA variables for
416# each neutrino event.
417if options.genie == 4 :
418
419 f_input = ROOT.TFile(inputFile)
420 gst = f_input.Get("gst")
421
422 selection_string = "(Entry$ >= "+str(options.firstEvent)+")"
423 if (options.firstEvent + options.nEvents) < gst.GetEntries() :
424 selection_string += "&&(Entry$ < "+str(options.firstEvent + options.nEvents)+")"
425
426 # Reopen output file
427 f_output = ROOT.TFile(outFile, "UPDATE")
428
429 # Copy only the events used in this run
430 gst_copy = gst.CopyTree(selection_string)
431 gst_copy.Write()
432
433 f_input.Close()
434 f_output.Close()
435
436# -----Finish-------------------------------------------------------
437timer.Stop()
438rtime = timer.RealTime()
439ctime = timer.CpuTime()
440print(' ')
441print("Macro finished succesfully.")
442
443print("Output file is ", outFile)
444print("Geometry file is ",geoFile)
445print("Real time ",rtime, " s, CPU time ",ctime,"s")
446
447# ------------------------------------------------------------------------
448def checkOverlaps(removeScifi=False):
449 ROOT.gROOT.SetWebDisplay("off") # Workaround for https://github.com/root-project/root/issues/18881
450 sGeo = ROOT.gGeoManager
451 if removeScifi:
452 for n in range(1,6):
453 Hscifi = sGeo.FindVolumeFast('ScifiVolume'+str(n))
454 removalList = []
455 for x in Hscifi.GetNodes():
456 if x.GetName().find('Scifi')==0: removalList.append(x)
457 for x in removalList: Hscifi.RemoveNode(x)
458 sGeo.SetNmeshPoints(10000)
459 sGeo.CheckOverlaps(0.1) # 1 micron takes 5minutes
460 sGeo.PrintOverlaps()
461# check subsystems in more detail
462 for x in sGeo.GetTopNode().GetNodes():
463 x.CheckOverlaps(0.0001)
464 sGeo.PrintOverlaps()
465
467 # after /run/initialize, but prints warning messages, problems with TGeo volume
468 mygMC = ROOT.TGeant4.GetMC()
469 mygMC.ProcessGeantCommand("/geometry/test/recursion_start 0")
470 mygMC.ProcessGeantCommand("/geometry/test/recursion_depth 2")
471 mygMC.ProcessGeantCommand("/geometry/test/run")
472
473# checking for overlaps
474if checking4overlaps:
Exec(self, opt)
Definition run_simSND.py:74
checkOverlaps(removeScifi=False)
checkOverlapsWithGeant4()
execute(f, ox, name='ShipGeo')
configure(darkphoton=None)