-
Notifications
You must be signed in to change notification settings - Fork 37
/
managers.py
1578 lines (1387 loc) · 57 KB
/
managers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import time
from box import Box
from anytree import RenderTree, LoopError
import shutil
import opengate_core as g4
import os
from pathlib import Path
import itk
from .base import (
GateObject,
GateObjectSingleton,
process_cls,
find_all_gate_objects,
find_paths_in_gate_object_dictionary,
)
from .definitions import __world_name__, __gate_list_objects__
from .element import new_element
from .engines import SimulationEngine
from .exception import fatal, warning
from .geometry.materials import MaterialDatabase
from .image import (
create_image_with_volume_extent,
create_image_with_extent,
voxelize_volume,
update_image_py_to_cpp,
get_cpp_image,
write_itk_image,
)
from .utility import (
assert_unique_element_name,
g4_units,
indent,
read_mac_file_to_commands,
ensure_directory_exists,
ensure_filename_is_str,
insert_suffix_before_extension,
)
from .logger import INFO, log
from .physics import Region, OpticalSurface, cut_particle_names
from .userinfo import UserInfo
from .serialization import dump_json, dumps_json, loads_json, load_json
from .processing import dispatch_to_subprocess
from .geometry.volumes import (
VolumeBase,
BoxVolume,
SphereVolume,
TrapVolume,
ImageVolume,
TubsVolume,
PolyhedraVolume,
HexagonVolume,
TesselatedVolume,
ConsVolume,
TrdVolume,
BooleanVolume,
RepeatParametrisedVolume,
ParallelWorldVolume,
VolumeTreeRoot,
)
particle_names_Gate_to_G4 = {
"gamma": "gamma",
"electron": "e-",
"positron": "e+",
"proton": "proton",
"neutron": "neutron",
}
def retrieve_g4_physics_constructor_class(g4_physics_constructor_class_name):
"""
Dynamically create a class with the given PhysicList
Only possible if the class exist in g4
"""
# Retrieve the G4VPhysicsConstructor class
try:
a = getattr(sys.modules["opengate_core"], g4_physics_constructor_class_name)
# sanity check:
assert g4_physics_constructor_class_name == a.__name__
return a
except AttributeError:
s = f"Cannot find the class {g4_physics_constructor_class_name} in opengate_core"
fatal(s)
def create_modular_physics_list_class(g4_physics_constructor_class_name):
"""
Create a class (not on object!) which:
- inherit from g4.G4VModularPhysicsList
- register a single G4 PhysicsConstructor (inherited from G4VPhysicsConstructor)
- has the same name as this PhysicsConstructor
"""
g4_physics_constructor_class = retrieve_g4_physics_constructor_class(
g4_physics_constructor_class_name
)
# create the class with __init__ method
cls = type(
g4_physics_constructor_class_name,
(g4.G4VModularPhysicsList,),
{
"g4_physics_constructor_class": g4_physics_constructor_class,
"__init__": init_method,
},
)
return cls
def init_method(self, verbosity):
"""
Init method of the dynamically created physics list class.
- call the init method of the super class (G4VModularPhysicsList)
- Create and register the physics constructor (G4VPhysicsConstructor)
"""
g4.G4VModularPhysicsList.__init__(self)
self.g4_physics_constructor = self.g4_physics_constructor_class(verbosity)
self.RegisterPhysics(self.g4_physics_constructor)
class FilterManager:
"""
Manage all the Filters in the simulation
"""
def __init__(self, simulation):
self.simulation = simulation
self.user_info_filters = {}
self.filters = {}
def __str__(self):
v = [v.name for v in self.user_info_filters.values()]
s = f'{" ".join(v)} ({len(self.user_info_filters)})'
return s
def dump(self):
n = len(self.user_info_filters)
s = f"Number of filters: {n}"
for Filter in self.user_info_filters.values():
if n > 1:
a = "\n" + "-" * 20
else:
a = ""
a += f"\n {Filter}"
s += indent(2, a)
return s
def get_filter(self, name):
if name not in self.filters:
fatal(
f"The Filter {name} is not in the current "
f"list of Filters: {self.filters}"
)
return self.filters[name]
def add_filter(self, filter_type, name):
# check that another element with the same name does not already exist
assert_unique_element_name(self.filters, name)
# build it
a = UserInfo("Filter", filter_type, name)
# append to the list
self.user_info_filters[name] = a
# return the info
return a
def initialize(self):
for ui in self.user_info_filters.values():
filter = new_element(ui, self.simulation)
log.debug(f"Filter: initialize [{ui.type_name}] {ui.name}")
filter.Initialize(ui)
self.filters[ui.name] = filter
class SourceManager:
"""
Manage all the sources in the simulation.
The function prepare_generate_primaries will be called during
the main run loop to set the current time and source.
"""
def __init__(self, simulation):
# Keep a pointer to the current simulation
self.simulation = simulation
# List of run times intervals
self.run_timing_intervals = None
self.current_run_interval = None
# List of sources user info
self.user_info_sources = {}
def __str__(self):
"""
str only dump the user info on a single line
"""
v = [v.name for v in self.user_info_sources.values()]
s = f'{" ".join(v)} ({len(self.user_info_sources)})'
return s
def dump_source_types(self):
s = f""
# FIXME: workaround to avoid circular import, will be solved when refactoring sources
from opengate.sources.builders import source_builders
for t in source_builders:
s += f"{t} "
return s
def dump_sources(self):
n = len(self.user_info_sources)
s = f"Number of sources: {n}"
for source in self.user_info_sources.values():
a = f"\n {source}"
s += indent(2, a)
return s
def get_source_info(self, name):
if name not in self.user_info_sources:
fatal(
f"The source {name} is not in the current "
f"list of sources: {self.user_info_sources}"
)
return self.user_info_sources[name]
"""def get_source(self, name):
n = len(self.g4_thread_source_managers)
if n > 0:
gate.exception.warning(f"Cannot get source in multithread mode, use get_source_mt")
return None
for source in self.sources:
if source.user_info.name == name:
return source.g4_source
gate.exception.fatal(
f'The source "{name}" is not in the current '
f"list of sources: {self.user_info_sources}"
)
def get_source_mt(self, name, thread):
n = len(self.g4_thread_source_managers)
if n == 0:
gate.exception.warning(f"Cannot get source in mono-thread mode, use get_source")
return None
i = 0
for source in self.sources:
if source.user_info.name == name:
if i == thread:
return source.g4_source
i += 1
gate.exception.fatal(
f'The source "{name}" is not in the current '
f"list of sources: {self.user_info_sources}"
)"""
def add_source(self, source_type, name):
# check that another element with the same name does not already exist
assert_unique_element_name(self.user_info_sources, name)
# init the user info
s = UserInfo("Source", source_type, name)
# append to the list
self.user_info_sources[name] = s
# return the info
return s
def initialize_before_g4_engine(self):
for source in self.user_info_sources.values():
if source.initialize_source_before_g4_engine:
source.initialize_source_before_g4_engine(source)
class ActorManager:
"""
Manage all the actors in the simulation
"""
def __init__(self, simulation):
self.simulation = simulation
self.user_info_actors = {}
def __str__(self):
v = [v.name for v in self.user_info_actors.values()]
s = f'{" ".join(v)} ({len(self.user_info_actors)})'
return s
"""def __getstate__(self):
if self.simulation.verbose_getstate:
gate.exception.warning("Getstate ActorManager")
# needed to not pickle. Need to reset user_info_actors to avoid to store the actors
self.user_info_actors = {}
return self.__dict__"""
def dump_actors(self):
n = len(self.user_info_actors)
s = f"Number of Actors: {n}"
for actor in self.user_info_actors.values():
if n > 1:
a = "\n" + "-" * 20
else:
a = ""
a += f"\n {actor}"
s += indent(2, a)
return s
def dump_actor_types(self):
s = f""
# FIXME: workaround to avoid circular import, will be solved when refactoring actors
from opengate.actors.actorbuilders import actor_builders
for t in actor_builders:
s += f"{t} "
return s
def get_actor_user_info(self, name):
if name not in self.user_info_actors:
fatal(
f"The actor {name} is not in the current "
f"list of actors: {self.user_info_actors}"
)
return self.user_info_actors[name]
def add_actor(self, actor_type, name):
# check that another element with the same name does not already exist
assert_unique_element_name(self.user_info_actors, name)
# build it
a = UserInfo("Actor", actor_type, name)
# append to the list
self.user_info_actors[name] = a
# return the info
return a
class PhysicsListManager(GateObject):
# Names of the physics constructors that can be created dynamically
available_g4_physics_constructors = [
"G4EmStandardPhysics",
"G4EmStandardPhysics_option1",
"G4EmStandardPhysics_option2",
"G4EmStandardPhysics_option3",
"G4EmStandardPhysics_option4",
"G4EmStandardPhysicsGS",
"G4EmLowEPPhysics",
"G4EmLivermorePhysics",
"G4EmLivermorePolarizedPhysics",
"G4EmPenelopePhysics",
"G4EmDNAPhysics",
"G4OpticalPhysics",
"G4GenericBiasingPhysics",
]
special_physics_constructor_classes = {}
special_physics_constructor_classes["G4DecayPhysics"] = g4.G4DecayPhysics
special_physics_constructor_classes["G4RadioactiveDecayPhysics"] = (
g4.G4RadioactiveDecayPhysics
)
special_physics_constructor_classes["G4OpticalPhysics"] = g4.G4OpticalPhysics
special_physics_constructor_classes["G4EmDNAPhysics"] = g4.G4EmDNAPhysics
special_physics_constructor_classes["G4GenericBiasingPhysics"] = (
g4.G4GenericBiasingPhysics
)
def __init__(self, physics_manager, *args, **kwargs):
super().__init__(*args, **kwargs)
self.physics_manager = physics_manager
# declare the attribute here as None;
# set to dict in create_physics_list_classes()
self.created_physics_list_classes = None
self.create_physics_list_classes()
self.particle_with_biased_process_dictionary = {}
def __getstate__(self):
# This is needed because cannot be pickled.
dict_to_return = super().__getstate__()
dict_to_return["created_physics_list_classes"] = None
return dict_to_return
def __setstate__(self, d):
self.__dict__ = d
self.create_physics_list_classes()
def create_physics_list_classes(self):
self.created_physics_list_classes = {}
for g4pc_name in self.available_g4_physics_constructors:
self.created_physics_list_classes[g4pc_name] = (
create_modular_physics_list_class(g4pc_name)
)
def get_physics_list(self, physics_list_name):
if physics_list_name in self.created_physics_list_classes:
physics_list = self.created_physics_list_classes[physics_list_name](
self.physics_manager.simulation.g4_verbose_level
)
else:
g4_factory = g4.G4PhysListFactory()
if g4_factory.IsReferencePhysList(physics_list_name):
physics_list = g4_factory.GetReferencePhysList(physics_list_name)
else:
s = (
f"Cannot find the physic list: {physics_list_name}\n"
f"{self.dump_info_physics_lists()}"
f"Default is {self.physics_manager.user_info_defaults['physics_list_name']}\n"
f"Help : https://geant4-userdoc.web.cern.ch/UsersGuides/PhysicsListGuide/html/physicslistguide.html"
)
fatal(s)
# add special physics constructors
for (
spc,
switch,
) in self.physics_manager.special_physics_constructors.items():
if switch is True:
try:
if spc == "G4GenericBiasingPhysics":
Bias = self.physics_manager.add_physics_bias()
physics_list.RegisterPhysics(Bias)
else:
physics_list.ReplacePhysics(
self.special_physics_constructor_classes[spc](
self.physics_manager.simulation.g4_verbose_level
)
)
except KeyError:
fatal(
f"Special physics constructor named '{spc}' not found. Available constructors are: {self.special_physics_constructor_classes.keys()}."
)
return physics_list
def dump_info_physics_lists(self):
g4_factory = g4.G4PhysListFactory()
s = (
"\n**** INFO about GATE physics lists ****\n"
f"* Known Geant4 lists are: {g4_factory.AvailablePhysLists()}\n"
f"* With EM options: {g4_factory.AvailablePhysListsEM()[1:]}\n"
f"* Or the following simple physics lists with a single PhysicsConstructor: \n"
f"* {self.available_g4_physics_constructors} \n"
"**** ----------------------------- ****\n\n"
)
return s
class PhysicsManager(GateObject):
"""
Everything related to the physics (lists, cuts, etc.) should be here.
"""
user_info_defaults = {
"physics_list_name": (
"QGSP_BERT_EMV",
{"doc": "Name of the Geant4 physics list. "},
),
"global_production_cuts": (
Box([("all", None)] + [(pname, None) for pname in cut_particle_names]),
{
"doc": "Dictionary containing the production cuts (range) for gamma, electron, positron, proton. Option 'all' overrides individual cuts."
},
),
"apply_cuts": (
True,
{
"doc": "Flag to turn of cuts 'on the fly'. Still under development in Gate."
},
),
"energy_range_min": (
None,
{
"doc": "Minimum energy for secondary particle production. If None, physics list default is used."
},
),
"energy_range_max": (
None,
{
"doc": "Maximum energy for secondary particle production. If None, physics list default is used."
},
),
"optical_properties_file": (
Path(os.path.dirname(__file__)) / "data" / "OpticalProperties.xml",
{
"doc": "Path to the xml file containing the optical material properties to be used by G4OpticalPhysics. "
"Default: file shipped with GATE.",
"is_input_file": True,
},
),
"surface_properties_file": (
Path(os.path.dirname(__file__)) / "data" / "SurfaceProperties.xml",
{
"doc": "Path to the xml file containing the surface material properties to be used by "
"optical surface, i.e. G4LogicalBorderSurface."
f"The default file shipped with GATE located is in "
f"{Path(os.path.dirname(__file__)) / 'data' / 'SurfaceProperties.xml'}",
"is_input_file": True,
},
),
"user_limits_particles": (
Box(
[
("all", False),
("all_charged", True),
("gamma", False),
("electron", False),
("positron", False),
("proton", False),
]
),
{
"doc": "Switch on (True) or off (False) UserLimits, e.g. step limiter, for individual particles. Default: Step limiter is applied to all charged particles (in accordance with G4 default)."
},
),
"em_parameters": (
Box(
[
("fluo", None),
("auger", None),
("auger_cascade", None),
("pixe", None),
("deexcitation_ignore_cut", None),
]
),
{"doc": "Switches on (True) or off (False) Geant4's EM parameters."},
),
"em_switches_world": (
Box([("deex", None), ("auger", None), ("pixe", None)]),
{
"doc": "Switch on/off EM parameters in the world region.",
"expose_items": False,
},
),
"special_physics_constructors": (
Box(
[
(spc, False)
for spc in PhysicsListManager.special_physics_constructor_classes
]
),
{
"doc": "Special physics constructors to be added to the physics list, e.g. G4Decay, G4OpticalPhysics. "
},
),
"processes_to_bias": (
Box(
[
("all", None),
("all_charged", None),
("gamma", None),
("electron", None),
("positron", None),
("proton", None),
]
),
{
"doc": "Define the process to bias (if wanted) on the different particle types."
},
),
}
def __init__(self, simulation, *args, **kwargs):
super().__init__(name="physics_manager", *args, **kwargs)
# Keep a pointer to the current simulation
self.simulation = simulation
self.physics_list_manager = PhysicsListManager(self, name="PhysicsListManager")
# dictionary containing all the region objects
# key=region_name, value=region_object
self.regions = {}
# Dictionary to quickly find the region to which a volume is associated.
# This dictionary is updated by the region's associate_volume method.
# Do not update manually!
# key=volume_name, value=region=object
# NB: It is well-defined because each volume has only one region.
self.volumes_regions_lut = {}
# dictionary containing all the optical surface objects
self.optical_surfaces = {}
def reset(self):
self.__init__(self.simulation)
def to_dictionary(self):
d = super().to_dictionary()
d["regions"] = dict([(k, v.to_dictionary()) for k, v in self.regions.items()])
d["optical_surfaces"] = dict(
[(k, v.to_dictionary()) for k, v in self.optical_surfaces.items()]
)
return d
def from_dictionary(self, d):
self.reset()
super().from_dictionary(d)
for r in d["regions"].values():
region = self.add_region(r["user_info"]["name"])
region.from_dictionary(r)
for s in d["optical_surfaces"].values():
optical_surface = self.add_optical_surface(
s["user_info"]["volume_from"],
s["user_info"]["volume_to"],
s["user_info"]["g4_surface_name"],
)
optical_surface.from_dictionary(s)
def __str__(self):
s = ""
for k, v in self.user_info.items():
s += f"{k}: {v}\n"
return s
def __getstate__(self):
if self.simulation.verbose_getstate:
warning("Getstate PhysicsManager")
dict_to_return = dict([(k, v) for k, v in self.__dict__.items()])
dict_to_return["physics_list_manager"] = None
return dict_to_return
def __setstate__(self, d):
self.__dict__ = d
self.physics_list_manager = PhysicsListManager(self, name="PhysicsListManager")
def _simulation_engine_closing(self):
"""This function should be called from the simulation engine
when it is closing to make sure that G4 references are set to None.
"""
# Region contain references to G4 objects, so they need to close
for r in self.regions.values():
r.close()
def dump_available_physics_lists(self):
return self.physics_list_manager.dump_info_physics_lists()
def dump_info_physics_lists(self):
return self.physics_list_manager.dump_info_physics_lists()
def dump_production_cuts(self):
s = "*** Production cuts for World: ***\n"
for k, v in self.user_info.global_production_cuts.items():
s += f"{k}: {v}\n"
if len(self.regions.keys()) > 0:
s += f"*** Production cuts per regions ***\n"
for region in self.regions.values():
s += f"In region {region.name}:\n"
s += region.dump_production_cuts()
else:
s += "*** No cuts per region defined. ***\n"
return s
def dump_optical_surfaces(self):
"""
Prints each volume's name and its associated surfaces' details (surface name and connected volumes)
from the `volume_surfaces` dictionary in a readable format.
"""
s = "The PhysicsManager is storing the following optical surfaces:\n\n"
for surf in self.optical_surfaces.values():
s += str(surf)
s += "\n"
return s
@property
def enable_decay(self):
"""Properties to quickly enable decay.
Note that setting enable_decay to False means that the physics list
default is used, i.e. it does not forcefully remove
G4DecayPhysics from the physics list.
"""
switch1 = self.special_physics_constructors["G4DecayPhysics"]
switch2 = self.special_physics_constructors["G4RadioactiveDecayPhysics"]
if switch1 is True and switch2 is True:
return True
elif switch1 is False and switch2 is False:
return False
else:
fatal(
f"Inconsistent G4Decay constructors: G4DecayPhysics = {switch1}, G4RadioactiveDecayPhysics = {switch2}."
)
@enable_decay.setter
def enable_decay(self, value):
self.special_physics_constructors["G4DecayPhysics"] = value
self.special_physics_constructors["G4RadioactiveDecayPhysics"] = value
def add_optical_surface(self, volume_from, volume_to, g4_surface_name):
"""
Creates an object of class OpticalSurface with surface info.
:param volume_from: Name of the first volume (str)
:param volume_to: Name of the second volume (str)
:param g4_surface_name: Name of the surface between volumes (str)
"""
name = "optical_surface_" + volume_from + "_" + volume_to
# Throw an error if the optical surface already exists
if name in self.optical_surfaces.keys():
fatal("An optical surface between these volumes already exists")
self.optical_surfaces[name] = OpticalSurface(
name=name,
physics_manager=self,
volume_from=volume_from,
volume_to=volume_to,
g4_surface_name=g4_surface_name,
)
return self.optical_surfaces[name]
def add_region(self, name):
if name in self.regions.keys():
fatal("A region with this name already exists.")
self.regions[name] = Region(name=name, physics_manager=self)
return self.regions[name]
def find_or_create_region(self, volume_name):
if volume_name not in self.volumes_regions_lut.keys():
region = self.add_region(volume_name + "_region")
region.associate_volume(volume_name)
else:
region = self.volumes_regions_lut[volume_name]
return region
# New name, more specific
def set_production_cut(self, volume_name, particle_name, value):
if volume_name == self.simulation.world.name:
self.global_production_cuts[particle_name] = value
else:
region = self.find_or_create_region(volume_name)
region.production_cuts[particle_name] = value
def add_physics_bias(self):
self.processes_to_bias = self.user_info["processes_to_bias"]
BiasToApply = self.physics_list_manager.special_physics_constructor_classes[
"G4GenericBiasingPhysics"
]()
list_of_particles = self.processes_to_bias.keys()
try:
if self.processes_to_bias["all"] != None:
for particle in list_of_particles:
if particle != "all" and particle != "all_charged":
BiasToApply.PhysicsBias(
particle_names_Gate_to_G4[particle],
self.processes_to_bias["all"],
)
elif self.processes_to_bias["all_charged"] != None:
for particle in list_of_particles:
if (
particle != "all"
and particle != "all_charged"
and particle != "gamma"
and particle != "neutron"
):
BiasToApply.PhysicsBias(
particle_names_Gate_to_G4[particle],
self.processes_to_bias["all_charged"],
)
else:
for particle in list_of_particles:
list_of_process = self.processes_to_bias[particle]
if list_of_process != None:
BiasToApply.PhysicsBias(
particle_names_Gate_to_G4[particle], list_of_process
)
except KeyError:
fatal(
f"Found unknown particle name '{particle}' in processes_to_bias()."
f" Eligible names are "
+ ", ".join(self.user_info_defaults["processes_to_bias"][0].keys())
+ "."
)
return BiasToApply
# set methods for the user_info parameters
# logic: every volume with user_infos must be associated
# with a region. If it does not yet have one, created it.
# Outlook: These setter methods might be linked to properties
# implemented in a future version of the Volume class
def set_max_step_size(self, volume_name, max_step_size):
region = self.find_or_create_region(volume_name)
region.user_limits["max_step_size"] = max_step_size
def set_max_track_length(self, volume_name, max_track_length):
region = self.find_or_create_region(volume_name)
region.user_limits["max_track_length"] = max_track_length
def set_min_ekine(self, volume_name, min_ekine):
region = self.find_or_create_region(volume_name)
region.user_limits["min_ekine"] = min_ekine
def set_max_time(self, volume_name, max_time):
region = self.find_or_create_region(volume_name)
region.user_limits["max_time"] = max_time
def set_min_range(self, volume_name, min_range):
region = self.find_or_create_region(volume_name)
region.user_limits["min_range"] = min_range
def set_user_limits_particles(self, particle_names):
if not isinstance(particle_names, (list, set, tuple)):
particle_names = list([particle_names])
for pn in list(particle_names):
# try to get current value to check if particle_name is eligible
try:
_ = self.user_info.user_limits_particles[pn]
except KeyError:
fatal(
f"Found unknown particle name '{pn}' in set_user_limits_particles(). Eligible names are "
+ ", ".join(list(self.user_info.user_limits_particles.keys()))
+ "."
)
self.user_info.user_limits_particles[pn] = True
class VolumeManager(GateObject):
"""
Store and manage a hierarchical list of geometrical volumes and associated materials.
This tree will be converted into Geant4 Solid/PhysicalVolume/LogicalVolumes
"""
volume_types = {
"BoxVolume": BoxVolume,
"SphereVolume": SphereVolume,
"TrapVolume": TrapVolume,
"ImageVolume": ImageVolume,
"TubsVolume": TubsVolume,
"PolyhedraVolume": PolyhedraVolume,
"TextTesselatedVolume": TesselatedVolume,
"HexagonVolume": HexagonVolume,
"ConsVolume": ConsVolume,
"TrdVolume": TrdVolume,
"BooleanVolume": BooleanVolume,
"RepeatParametrisedVolume": RepeatParametrisedVolume,
"TesselatedVolume": TesselatedVolume,
}
def __init__(self, simulation, *args, **kwargs):
"""
Class that store geometry description.
"""
self.simulation = simulation
# force name to VolumeManager
kwargs["name"] = "VolumeManager"
super().__init__(*args, **kwargs)
self.volume_tree_root = VolumeTreeRoot(
volume_manager=self
) # abstract element used as common root for volume tree
m = g4_units.m
# default world volume
self.volumes = {}
self.volumes[__world_name__] = BoxVolume(
volume_manager=self,
name=__world_name__,
size=[3 * m, 3 * m, 3 * m],
material="G4_AIR",
mother=None,
)
# attach the world to the tree root
self.volumes[__world_name__].parent = self.volume_tree_root
self.parallel_world_volumes = {}
self._need_tree_update = True # flag to store state of volume tree
# database of materials
self.material_database = MaterialDatabase()
def reset(self):
self.__init__(self.simulation)
def __str__(self):
s = "**** Volume manager ****\n"
if len(self.parallel_world_volumes) > 0:
s += f"Number of parallel worlds: {len(self.parallel_world_volumes)}\n"
s += f"Names of the parallel worlds: {self.parallel_world_names}\n"
s += f"Number of volumes: {len(self.volumes)}\n"
s += "The volumes are organized in the following hierarchy:\n"
s += self.dump_volume_tree()
return s
def to_dictionary(self):
d = super().to_dictionary()
d["volumes"] = dict([(k, v.to_dictionary()) for k, v in self.volumes.items()])
d["parallel_world_volumes"] = list(self.parallel_world_volumes.keys())
return d
def from_dictionary(self, d):
self.reset()
super().from_dictionary(d)
# First create all volumes
for k, v in d["volumes"].items():
# the world volume is always created in __init__
if v["user_info"]["name"] != self.world_volume.name:
self.add_volume(v["object_type"], name=v["user_info"]["name"])
# ... then process them to make sure that any reference
# to a volume in the volumes dictionary is satisfied
for k, v in d["volumes"].items():
self.volumes[k].from_dictionary(v)
@property
def world_volume(self):
return self.volumes[__world_name__]
@property
def all_world_volumes(self):
"""List of all world volumes, including the mass world volume."""
world_volumes = [self.world_volume]
world_volumes.extend(list(self.parallel_world_volumes.values()))
return world_volumes
@property
def volume_names(self):
return list(self.volumes.keys())
@property
def parallel_world_names(self):
return list(self.parallel_world_volumes.keys())
@property
def all_volume_names(self):
return self.volume_names + self.parallel_world_names
@property
def dynamic_volumes(self):
return [vol for vol in self.volumes.values() if vol.is_dynamic]
def get_volume(self, volume_name):
try:
return self.volumes[volume_name]
except KeyError:
try:
return self.parallel_world_volumes[volume_name]
except KeyError:
fatal(
f"Cannot find volume {volume_name}. "
f"Volumes included in this simulation are: {self.volumes.keys()}"
)
def update_volume_tree_if_needed(self):
if self._need_tree_update is True:
self.update_volume_tree()
def update_volume_tree(self):
for v in self.volumes.values():
if (
v not in self.parallel_world_volumes.values()
and v is not self.world_volume
):
try:
v._update_node()
except LoopError:
fatal(
f"There seems to be a loop in the volume tree involving volume {v.name}."
)
self._need_tree_update = False
def add_volume(self, volume, name=None):
if isinstance(volume, str):
if name is None:
fatal("You must provide a name for the volume.")
new_volume = self.create_volume(volume, name)
elif isinstance(volume, VolumeBase):
new_volume = volume
else:
fatal(
"You need to either provide a volume type and name, or a volume object."
)
if new_volume.name in self.all_volume_names:
fatal(
f"The volume name {new_volume.name} already exists. Existing volume names are: {self.volumes.keys()}"
)
self.volumes[new_volume.name] = new_volume
self.volumes[new_volume.name].volume_manager = self
self._need_tree_update = True
# return the volume if it has not been passed as input, i.e. it was created here
if new_volume is not volume:
return new_volume
def create_volume(self, volume_type, name):
# check that another element with the same name does not already exist
volume_type_variants = [volume_type, volume_type + "Volume"]
for vt in volume_type_variants:
if vt in self.volume_types.keys():
return self.volume_types[vt](name=name)
fatal(
f"Unknown volume type {volume_type}. Known types are: {list(self.volume_types.keys())}."
)
def add_parallel_world(self, name):
if name in self.all_volume_names:
fatal(
f"Cannot create the parallel world named {name} because it already exists."
)
# constructor needs self, i.e. the volume manager
self.parallel_world_volumes[name] = ParallelWorldVolume(name, self)
self._need_tree_update = True