Exemple #1
0
def main():
    args = get_args()

    global random_engine
    random_engine = g4.RanecuEngine()
    g4.HepRandom.setTheEngine(random_engine)
    g4.HepRandom.setTheSeed(random.randint(0, 1e9))

    global detector
    detector = MyGeometry(args.conf)
    g4.gRunManager.SetUserInitialization(detector)

    global physics_list
    physics_list = compton.PhysicsList()
    g4.gRunManager.SetUserInitialization(physics_list)

    global pga
    pga = PrimaryGeneratorAction(args.conf)
    g4.gRunManager.SetUserAction(pga)

    num_events = args.conf['PrimaryGenerator']['NumEvents']

    global t1, t3
    t1 = MyRunAction()
    t3 = MySteppingAction()
    g4.gRunManager.SetUserAction(t1)
    g4.gRunManager.SetUserAction(t3)

    global event_actions
    event_actions = create_event_actions(args.conf)
    for action in event_actions.values():
        g4.gRunManager.SetUserAction(action)

    global fields
    fields = create_fields(args.conf)

    g4.gRunManager.Initialize()

    global detectors
    detectors = create_detectors(args.conf)

    for x in args.macro_filenames:
        g4.gControlExecute(x)

    g4.gRunManager.BeamOn(num_events)

    for k, sd in detectors.items():
        sd.finalize(num_events)

    return 0
Exemple #2
0
  def cmd_beamOn(self):
    
    # get and set particle
    if self.particleListBox.curselection():
        index =int(self.particleListBox.curselection()[0])
        g4.gApplyUICommand("/gun/particle  " +  particleList[index])

    # get and set detector Material
    if self.materialListBox.curselection():
        index =int(self.materialListBox.curselection()[0])
        g4.gApplyUICommand("/testem/det/setMat  " +  materialList[index])
	
    # get and set energy
    energy = self.energyEntry.get()
    if self.energyListBox.curselection():
        index = int(self.energyListBox.curselection()[0])
        unity =   enrgyList[index]
        g4.gApplyUICommand("/gun/energy " + energy + " " + unity)

    # get and set cuts
    cuts = self.cutsEntry.get()
    if self.cutsListBox.curselection():
        index = int(self.cutsListBox.curselection()[0])
        unity =   cutsList[index]
        g4.gApplyUICommand("/testem/phys/setCuts " + cuts + " " + unity)

    # run beamOn
    g4.gRunManager.BeamOn(1)
Exemple #3
0
    def cmd_beamOn(self):

        # get and set particle
        if self.particleListBox.curselection():
            index = int(self.particleListBox.curselection()[0])
            g4.gApplyUICommand("/gun/particle  " + particleList[index])

        # get and set detector Material
        if self.materialListBox.curselection():
            index = int(self.materialListBox.curselection()[0])
            g4.gApplyUICommand("/testem/det/setMat  " + materialList[index])

        # get and set energy
        energy = self.energyEntry.get()
        if self.energyListBox.curselection():
            index = int(self.energyListBox.curselection()[0])
            unity = enrgyList[index]
            g4.gApplyUICommand("/gun/energy " + energy + " " + unity)

        # get and set cuts
        cuts = self.cutsEntry.get()
        if self.cutsListBox.curselection():
            index = int(self.cutsListBox.curselection()[0])
            unity = cutsList[index]
            g4.gApplyUICommand("/testem/phys/setCuts " + cuts + " " + unity)

        # run beamOn
        g4.gRunManager.BeamOn(1)
Exemple #4
0
    def addParticleGun(self,
                       particle,
                       position,
                       energy=None,
                       direction=None,
                       momentum=None):
        '''
        Create a particle gun if one has not already been initialised

        Arguments
        ---------

        particle         (string)                  Particle to be fired

        position         (float, float, float)     Position of gun as either
                         (string, string, string)  floats or strings

       
        Optional Arguments
        ------------------

        Note: If momentum is set, energy and momentum direction are ignored


        energy           (float) or (string)       Energy of particle

        direction        (float, float, float)     Direction vector of particle
 
        momentum         (float, float, float)     Momentum of particle
                         (string, string, string)

        '''
        self._pgun = g4py.ParticleGun.Construct()
        self._pgun.SetParticleByName(particle)
        position = self._parse_units(position)
        self._pgun.SetParticlePosition(G4.G4ThreeVector(*position))
        if momentum:
            self._logger.warning(
                'PGun: Option for Momentum given, will ignore any options' +
                'for Direction or Energy')

            momentum = self._parse_units(momentum)
            self._pgun.SetParticlePosition(G4.G4ThreeVector(*momentum))
        elif energy:
            direction = self._parse_units(direction)
            energy = self._parse_units(energy)
            self._pgun.SetParticleEnergy(energy)
            self._pgun.SetParticleMomentumDirection(
                G4.G4ThreeVector(*direction))
Exemple #5
0
 def GeneratePrimaries(self, event):
     phi = ROOT.gRandom.Uniform(0.0, 2 * pi)
     theta = acos(ROOT.gRandom.Uniform(self.llim, self.ulim))
     vx, vy, vz = sin(theta) * cos(phi), sin(theta) * sin(phi), -cos(theta)
     self.particleGun.SetParticleMomentumDirection(
         G4.G4ThreeVector(vx, vy, vz))
     self.particleGun.GeneratePrimaryVertex(event)
    def Construct(self):  # pylint: disable-msg=C0103
        """Construct nuSTORM from a GDML file"""
        # Parse the GDML
        self.world = self.gdml_parser.GetWorldVolume()

        # Create sensitive detector
        self.sensitive_detector = ScintSD()

        # Get logical volume for X view, then attach SD
        my_lv = G4.G4LogicalVolumeStore.GetInstance().GetVolumeID(1)
        assert my_lv.GetName() == "ScintillatorBarX"
        my_lv.SetSensitiveDetector(self.sensitive_detector)

        # Get logical volume for Y view, then attach SD
        my_lv = G4.G4LogicalVolumeStore.GetInstance().GetVolumeID(2)
        assert my_lv.GetName() == "ScintillatorBarY"
        my_lv.SetSensitiveDetector(self.sensitive_detector)

        my_lv = G4.G4LogicalVolumeStore.GetInstance().GetVolumeID(0)
        assert my_lv.GetName() == "SteelPlane"

        # field
        self.field_manager = G4.G4FieldManager()
        self.my_field = MagneticField.WandsToroidField(self.field_polarity)
        self.field_manager.SetDetectorField(self.my_field)
        self.field_manager.CreateChordFinder(self.my_field)
        my_lv.SetFieldManager(self.field_manager, False)

        self.log.info("Materials:")
        self.log.info(G4.G4Material.GetMaterialTable())

        # Return pointer to world volume
        return self.world
    def __init__(self, field_polarity):
        self.log = logging.getLogger('root')
        self.log = self.log.getChild(self.__class__.__name__)
        self.log.debug('Initialized %s', self.__class__.__name__)

        G4.G4VUserDetectorConstruction.__init__(self)
        self.world = None
        self.gdml_parser = G4.G4GDMLParser()
        self.sensitive_detector = None

        self.config = Configuration.GLOBAL_CONFIG
        self.filename = os.path.join(self.config['data_dir'],
                                     'iron_scint_bars.gdml')
        self.field_manager = None
        self.my_field = None
        self.field_polarity = field_polarity

        self.gdml_parser.Read(self.filename)

        # Grab constants from the GDML <define>
        rc['layers'] = int(self.gdml_parser.GetConstant("layers"))
        rc['bars'] = int(self.gdml_parser.GetConstant("bars"))
        for name in ["width", "thickness_layer", "thickness_bar",
                     "density_scint", "density_iron"]:
            rc[name] = self.gdml_parser.GetConstant(name)

        det_width = rc['width'] * rc['bars']
        iron_volume = det_width * det_width * (rc['layers']/2 * (rc['thickness_layer'] - rc['thickness_bar']))
        scint_volume = det_width * det_width * (rc['layers']/2 * rc['thickness_bar'])
        self.mass = iron_volume * rc['density_iron'] + scint_volume * rc['density_scint']
        self.mass /= 10**3 # mm^2 -> cm^3, density in /cm^3 but distances in mm
        self.log.info("Mass [g]: %f" % self.mass)
    def build_mixtured_material(name, base_materials, fractions):
        """
        """
        density = 0.
        for base_mat, fraction in zip(base_materials, fractions):
            density += base_mat.GetDensity() * fraction
        ncomponents = len(base_materials)
        new_material = g4.G4Material(name, density, ncomponents)
        for base_mat, fraction in zip(base_materials, fractions):
            new_material.AddMaterial(base_mat, fraction)

        return new_material
Exemple #9
0
def pattern_spray():
    energies = (14.2*MeV)/2**np.arange(7)
    # energies = np.array((30*keV,))
    for particle in ['e+', 'e-']:
        for energy in energies:
            yield particle, g4.G4ThreeVector(), g4.G4ThreeVector(0,0,1), energy

    # energies = (14.2*MeV/2)/2**np.arange(6)
    # for particle in ['e-']:
    #     for energy in energies:
    #         yield particle, g4.G4ThreeVector(0,-10*mm,0), g4.G4ThreeVector(0,0,1), energy

    # energies = (14.2*MeV/4)/2**np.arange(5)
    # for particle in ['e-']:
    #     for energy in energies:
    #         yield particle, g4.G4ThreeVector(0,-20*mm,0), g4.G4ThreeVector(0,0,1), energy

    energies = (14.2*MeV/8)/2**np.arange(4)
    for particle in ['e-']:
        for energy in energies:
            yield particle, g4.G4ThreeVector(0,-30*mm,0), g4.G4ThreeVector(0,0,1), energy
Exemple #10
0
    def GeneratePrimaries(self, event):
        particles = self.particle_generator.generate()

        for particle in particles:
            pp = G4.G4PrimaryParticle()
            pp.SetPDGcode(particle['pid'])

            pp.SetMomentum(particle['momentum']['x'],
                           particle['momentum']['y'],
                           particle['momentum']['z'])

            v = G4.G4PrimaryVertex()
            v.SetPosition(particle['position']['x'], particle['position']['y'],
                          particle['position']['z'])

            v.SetPrimary(pp)

            event.AddPrimaryVertex(v)

        # Write particleS information to the runtime configuration so the Truth
        #  processor can find it in order to output it
        self.setMCInfo(particles)
    def __init__(self, name):
        self.log = logging.getLogger('root')
        self.log = self.log.getChild(self.__class__.__name__)
        self.log.debug('Initialized %s', self.__class__.__name__)

        G4.G4VUserDetectorConstruction.__init__(self)
        self.world = None
        self.gdml_parser = G4.G4GDMLParser()
        self.sensitive_detector = None

        self.config = Configuration.GLOBAL_CONFIG

        self.filename = os.path.join(self.config['data_dir'], name)
Exemple #12
0
 def __init__(self, conf):
     g4.G4VUserPrimaryGeneratorAction.__init__(self)
     self.pg = g4.G4ParticleGun(1)
     self.conf = conf
     c = conf['PrimaryGenerator']
     p, m = c['PythonGenerator'].rsplit('.', 1)
     gen_args = []
     if 'PythonGeneratorArgs' in c:
         for x in c['PythonGeneratorArgs']:
             try:
                 gen_args.append(eval(x))
             except:
                 gen_args.append(x)
     sys.path.append('./')
     mod = import_module(p)
     self.generator = getattr(mod, m)(*gen_args)
Exemple #13
0
    def GetFieldValue(self, pos, time):
        bfield = G4.G4ThreeVector()

        # Set to zero, only change if r != 0 and sign != 0
        bfield.x = 0
        bfield.y = 0
        bfield.z = 0.

        if self.scale == 0.0:
            return bfield * G4.tesla

        r = math.sqrt(pos.x ** 2 + pos.y ** 2)

        if r != 0.0:
            B = self.scale * self.PhenomModel(r)
            bfield.x = -1 * (pos.y / r) * B
            bfield.y = 1 * (pos.x / r) * B

        return bfield * G4.tesla
Exemple #14
0
def create_materials(conf):
    result = {}

    if 'Materials' not in conf:
        return result

    for name in (conf['Materials']):
        c = conf['Materials'][name]
        mat = g4.gNistManager.FindOrBuildMaterial(name)
        if mat is None:
            atoms = c['AtomicComposition']
            mat = g4.G4Material(name, c['Density'] * gram / cm**3,
                                len(atoms[0]))
            for atom_name, num_atoms in zip(*atoms):
                mat.AddElement(g4.gNistManager.FindOrBuildElement(atom_name),
                               num_atoms)
        for property_name in c['Properties']:
            property_table = mat.GetMaterialPropertiesTable()
            if property_table is None:
                property_table = compton.G4MaterialPropertiesTable()
                mat.SetMaterialPropertiesTable(property_table)
            property_conf = c['Properties'][property_name]
            if 'Value' in property_conf:
                property_table.AddConstProperty(property_name,
                                                property_conf['Value'])
            else:
                values = np.array(property_conf['Values'])
                if 'PhotonEnergies' in property_conf:
                    photon_energies = np.array(
                        property_conf['PhotonEnergies']) * eV
                else:
                    photon_wavelengths = np.array(
                        property_conf['PhotonWavelengths']) * nanometer
                    photon_energies = h_Planck * c_light / photon_wavelengths
                assert (len(values) == len(photon_energies))
                idx = photon_energies.argsort()
                photon_energies = photon_energies[idx]
                values = values[idx]
                property_table.AddProperty(property_name, photon_energies,
                                           values)

        result[name] = mat
    return result
Exemple #15
0
myPL = TestEm0.PhysicsList()
g4.gRunManager.SetUserInitialization(myPL)

# set user actions...
myPGA = TestEm0.PrimaryGeneratorAction(myDC)
g4.gRunManager.SetUserAction(myPGA)

myRA = TestEm0.RunAction(myDC, myPGA)

# set user action classes
g4.gRunManager.SetUserAction(myRA)

g4.gRunManager.Initialize()

pg = g4.G4ParticleGun()

materialList = TestEm0.getMaterialTable()

particleList = TestEm0.getParticleTable()

enrgyList = ["eV", "keV", "MeV", "GeV", "TeV", "PeV"]

cutsList = ["um", "mm", "cm", "m", "km"]

# GUI

from tkinter import *


class App(Frame):
def repeater(particle, energy, x0, direction):
    x0 = g4.G4ThreeVector(*x0)
    direction = g4.G4ThreeVector(*direction)
    while 1:
        yield particle, x0, direction, energy
Exemple #17
0
def gamma_spray(energy, y0):
    z0 = -25 * mm
    direction = g4.G4ThreeVector(0, 0, 1)
    while 1:
        yield 'gamma', g4.G4ThreeVector(0, y0, z0), direction, energy
Exemple #18
0
def pattern_spray():
    energies = (29*MeV)/2**np.arange(6)
    for particle in ['e+', 'e-']:
        for energy in energies:
            yield particle, g4.G4ThreeVector(), g4.G4ThreeVector(0,0,1), energy
Exemple #19
0
def repetitive_spray(particle, energy, x0, y0, z0):
    direction = g4.G4ThreeVector(0,0,1)
    while 1:
        yield particle, g4.G4ThreeVector(x0, y0, z0), direction, energy
Exemple #20
0
    def Construct(self):
        check_overlap = False
        many = False

        geometry_keys = list(self.conf['Geometry'].keys())
        if len(geometry_keys) != 1:
            raise ValueError('Must define exactly one top-level Geometry')
        world_name = geometry_keys[0]

        global geom_s, geom_l, geom_p
        geom_s = {}
        geom_l = {}
        geom_p = {}

        for geom in depth_first_tree_traversal(self.conf['Geometry']):
            geom_type = geom['Type']
            geom_name = geom['Name']
            parent_name = geom_name.rsplit('.', 1)[0]
            if parent_name in geom_p:
                parent_p = geom_p[parent_name]
            else:
                parent_p = None

            if geom_type == 'G4Box':
                solid = g4.G4Box(geom_name, geom['pX'] * mm, geom['pY'] * mm,
                                 geom['pZ'] * mm)
            elif geom_type == 'G4Tubs':
                solid = g4.G4Tubs(geom_name, geom['pRMin'] * mm,
                                  geom['pRMax'] * mm, geom['pDz'] * mm,
                                  geom['pSPhi'] * deg, geom['pDPhi'] * deg)
            elif geom_type == 'CadMesh':
                mesh = compton.cadmesh.TessellatedMesh(geom['File'])
                if 'SolidName' in geom:
                    solid = mesh.GetSolid(geom['SolidName'])
                else:
                    solid = mesh.GetSolid(0)
            else:
                raise ValueError(
                    "unimplemented geometry type '{}'".format(geom_type))

            logical = g4.G4LogicalVolume(
                solid, g4.gNistManager.FindOrBuildMaterial(geom['Material']),
                geom_name)
            transform = g4.G4Transform3D()
            if 'Transformation' in geom:
                for operation, value in zip(*geom['Transformation']):
                    translation = g4.G4ThreeVector()
                    rotation = g4.G4RotationMatrix()
                    if operation == 'TranslateX':
                        translation += g4.G4ThreeVector(value * mm, 0, 0)
                    elif operation == 'TranslateY':
                        translation += g4.G4ThreeVector(0, value * mm, 0)
                    elif operation == 'TranslateZ':
                        translation += g4.G4ThreeVector(0, 0, value * mm)
                    elif operation == 'RotateX':
                        rotation.rotateX(value * deg)
                    elif operation == 'RotateY':
                        rotation.rotateY(value * deg)
                    elif operation == 'RotateZ':
                        rotation.rotateZ(value * deg)
                    else:
                        assert (False)
                    transform = (g4.G4Transform3D(rotation, translation) *
                                 transform)
            if 'Rotation' in geom:
                euler = np.array(geom['Rotation']) * deg
                rotation = g4.G4RotationMatrix()
                rotation.rotateZ(euler[0])
                rotation.rotateY(euler[1])
                rotation.rotateZ(euler[2])
            else:
                rotation = g4.G4RotationMatrix()
            if 'Translation' in geom:
                translation = g4.G4ThreeVector(*np.array(geom['Translation']) *
                                               mm)
            else:
                translation = g4.G4ThreeVector()
            physical = g4.G4PVPlacement(
                g4.G4Transform3D(rotation, translation) * transform, geom_name,
                logical, parent_p, many, 0, check_overlap)

            if 'Visible' in geom:
                logical.SetVisAttributes(g4.G4VisAttributes(geom['Visible']))
            if 'Color' in geom:
                logical.SetVisAttributes(
                    g4.G4VisAttributes(g4.G4Color(*geom['Color'])))

            geom_s[geom_name] = solid
            geom_l[geom_name] = logical
            geom_p[geom_name] = physical

        return geom_p[world_name]
Exemple #21
0
    #Geant4.gRunManager.SetUserAction(stepping_action)

    rand_engine= Geant4.Ranlux64Engine()
    Geant4.HepRandom.setTheEngine(rand_engine)
    seed = random.randint(0, 2**32)
    Geant4.HepRandom.setTheSeed(seed)

    if args.dicom:
        g4.RegisterParallelWorld(detector_construction, physics_list)
        detector_construction.SetCTDirectory(args.dicom, args.ct_acquisition)
        #primary_generator.LoadActivityData(args.dicom, detector_construction.GetCTOrigin())
   
    Geant4.gRunManager.Initialize()
    
    if args.macro:
        Geant4.gVisManager.Initialize()
        Geant4.gApplyUICommand("/control/execute %s" % args.macro)

    Geant4.gRunManager.BeamOn(args.histories)
    
    if args.start_session:
        Geant4.StartUISession()

    if args.save:
        hist = detector_construction.GetHistogram()
        numpy.save("output/hist_%i_%i_%i.npy" % (args.gun_x, args.gun_y, args.gun_z), hist)

    #if not args.start_session:
    #    raw_input("Press <enter> to exit.")

Exemple #22
0
                                         overload=vars(args))
    Configuration.GLOBAL_CONFIG = config_class.get_configuration_dict()

    Logging.setupLogging(args.log_level, args.name)
    log = logging.getLogger('root').getChild('simulate')
    log.debug('Commandline args: %s', str(args))

    random.seed()

    # make shorter variable name for us
    config = config_class.get_configuration_dict()

    log.info('Using the following configuration:')
    log.info(config)

    rand_engine = G4.Ranlux64Engine()
    HepRandom.setTheEngine(rand_engine)
    seed = config['seed']
    if seed == 0:
        seed = random.randint(1, 65536)
        log.warning('Using random seed %d', seed)
    else:
        log.info('Using seed %d', seed)
    HepRandom.setTheSeed(seed)

    detector = VlenfDetectorConstruction(field_polarity=config['polarity'])
    gRunManager.SetUserInitialization(detector)

    physics_list = G4.G4physicslists.QGSP_BERT()
    gRunManager.SetUserInitialization(physics_list)
    physics_list.SetDefaultCutValue(1.0 * mm)
def electron_spray():
    energies = (30.0 * MeV) * 2**np.arange(6)/32
    for energy in energies:
        yield 'e-', g4.G4ThreeVector(), g4.G4ThreeVector(0,0,1), energy
Exemple #24
0
    def __init__(self, **options):

        if 'visualize' in options: self.visualize = options['visualize']
        else: self.visualize = False

        if 'wait' in options: self.wait = options['wait']
        else: self.wait = False

        # setup of the random number generator
        self.randEngine = G4.Ranlux64Engine()
        #    te = G4.HepRandom.getTheSeeds()
        G4.HepRandom.setTheEngine(self.randEngine)

        # creation/registering of the matter interaction physics
        G4.gRunManager.SetUserInitialization(G4.G4physicslists.LBE())

        # creation/registering of the detector constructor
        import Detector
        self.setup = Detector.Constructor()
        self.crystal = self.setup.calorimeter.logical
        self.hpge = Detector.MySD()
        self.crystal.SetSensitiveDetector(self.hpge)
        G4.gRunManager.SetUserInitialization(self.setup)

        # creation/registering of the source constructor
        import Generator
        self.hist = ROOT.TH1D("hist", "Energy deposit [keV]", 1500, 0, 3000.0)
        self.uaction = Generator.MyEventAction(self.hpge, self.hist)
        self.myPGA = Generator.MyPrimaryGeneratorAction()
        G4.gRunManager.SetUserAction(self.myPGA)
        G4.gRunManager.SetUserAction(self.uaction)

        G4.gRunManager.Initialize()
        #    G4.gVisManager.Initialize()
        #    G4.gUImanager.Initialize()
        if self.visualize != None:
            G4.gApplyUICommand("/vis/open %s 1600x1200-0+0" % self.visualize)
            G4.gApplyUICommand("/vis/scene/create")
            #      G4.gApplyUICommand("/vis/viewer/set/style surface")
            G4.gApplyUICommand("/vis/viewer/set/style wireframe")
            G4.gApplyUICommand("/vis/viewer/set/viewpointThetaPhi 90. 0.")
            G4.gApplyUICommand("/vis/scene/add/volume")
            G4.gApplyUICommand("/vis/sceneHandler/attach")
            G4.gApplyUICommand("/tracking/storeTrajectory 1")
            G4.gApplyUICommand("/vis/scene/add/trajectories")
            G4.gApplyUICommand("/vis/scene/endOfEventAction accumulate")
            G4.gApplyUICommand("/vis/enable true")
        print self.visualize
Exemple #25
0
g4py.NISTmaterials.Construct()
g4py.ezgeom.Construct()
# fill the world with air
air = Geant4.G4Material.GetMaterial("G4_AIR")
g4py.ezgeom.SetWorldMaterial(air)
g4py.ezgeom.ResizeWorld(5.0 * m, 5.0 * m, 6.0 * m)

# Plate
Au = Geant4.G4Material.GetMaterial("G4_Au")
target_plate = g4py.ezgeom.G4EzVolume("Aurum_plate")
target_plate.CreateBoxVolume(Au, 10.0 * cm, 10.0 * cm, 1.0 * mm)

detector_plate = MySD()
target_plate.SetSensitiveDetector(detector_plate)
target_plate.PlaceIt(Geant4.G4ThreeVector(0.0, 0.0, 1.0 * m))

# Cube
Pb = Geant4.G4Material.GetMaterial("G4_Pb")
target = g4py.ezgeom.G4EzVolume("Plumbum_cube")
target.CreateBoxVolume(Pb, 1.0 * m, 1.0 * m, 1.0 * m)

detector_cube = MySD()
target.SetSensitiveDetector(detector_cube)
target.PlaceIt(Geant4.G4ThreeVector(0.0, 0.0, 1.5 * m))

# гистограммы
hist_au = ROOT.TH1D("hist_au", "Energy_au", 70, -1, 12.0)
hist_pb = ROOT.TH1D("hist_pb", "Energy_pb", 70, -1, 12.0)
hist_coordinates = ROOT.TH2D("hist_coord", "coordinatess", 50, -100, 50, 100,
                             -100, 100)
Exemple #26
0
    def ConstructDevice(self):
        """
        """
        # make colours
        white = g4.G4Color(1.0, 1.0, 1.0)
        orange = g4.G4Color(.75, .55, 0.0)
        world_visatt = g4.G4VisAttributes(True, white)
        process_space_visatt = g4.G4VisAttributes(False, orange)

        # ========
        #  World
        # ========
        world_length_x = settings.world_length_x * g4.micrometer
        world_length_y = settings.world_length_y * g4.micrometer
        world_length_z = settings.world_length_z * g4.micrometer

        world_solid = g4.G4Box("world_solid", world_length_x, world_length_y,
                               world_length_z)

        world_logical = g4.G4LogicalVolume(world_solid, self.world_material,
                                           "world_logical")
        world_logical.SetVisAttributes(world_visatt)

        self.world_physical = g4.G4PVPlacement(g4.G4Transform3D(),
                                               world_logical, "world_physical",
                                               None, False, 0)

        # ===============
        #  process space
        # ===============
        process_space_length_x = settings.process_space_length_x * g4.micrometer
        process_space_length_y = settings.process_space_length_y * g4.micrometer
        process_space_length_z = settings.process_space_length_z * g4.micrometer

        process_space_solid = g4.G4Box("process_space_solid",
                                       process_space_length_x,
                                       process_space_length_y,
                                       process_space_length_z)

        process_space_logical = g4.G4LogicalVolume(process_space_solid,
                                                   self.process_space_material,
                                                   "process_space_logical")
        process_space_logical.SetVisAttributes(process_space_visatt)

        process_space_pos = g4.G4ThreeVector(0, 0, -process_space_length_z)
        process_space_physical = g4.G4PVPlacement(None, process_space_pos,
                                                  "process_space_physical",
                                                  process_space_logical,
                                                  self.world_physical, False,
                                                  0, True)

        # ========================
        #  process wafer phantom
        # ========================
        voxel_length_x = process_space_length_x / self.n_voxel_x
        voxel_length_y = process_space_length_y / self.n_voxel_y
        voxel_length_z = process_space_length_z / self.n_voxel_z
        voxel_solid = g4.G4Box("voxel_solid", voxel_length_x, voxel_length_y,
                               voxel_length_z)
        self.voxel_logical = g4.G4LogicalVolume(voxel_solid,
                                                self.process_space_material,
                                                "voxel_logical")
        # voxel_logical.SetVisAttributes(g4.G4VisAttributes(G4VisAttributes::GetInvisible()))

        wafer = PhantomParameterisationColour()
        # set color
        for mat_name, color in settings.COLOR_MAP.items():
            cred = color[0]
            cgreen = color[1]
            cblue = color[2]
            copacity = color[3]
            g4_color = g4.G4Color(cred, cgreen, cblue, copacity)
            visAtt = g4.G4VisAttributes(g4_color)
            # visAtt.SetForceSolid(True)
            visAtt.SetVisibility(True)
            wafer.AddColor(mat_name, visAtt)

        wafer.SetVoxelDimensions(voxel_length_x, voxel_length_y,
                                 voxel_length_z)
        wafer.SetNoVoxel(self.n_voxel_x, self.n_voxel_y, self.n_voxel_z)
        wafer.SetMaterials(self.materials)
        wafer.SetMaterialIndices(self.material_IDs)
        wafer.BuildContainerSolid(process_space_physical)
        wafer.CheckVoxelsFillContainer(process_space_solid.GetXHalfLength(),
                                       process_space_solid.GetYHalfLength(),
                                       process_space_solid.GetZHalfLength())

        n_voxel = self.n_voxel_x * self.n_voxel_y * self.n_voxel_z
        wafer_physical = G4PVParameterised("wafer_physical",
                                           self.voxel_logical,
                                           process_space_logical,
                                           g4.G4global.EAxis.kXAxis, n_voxel,
                                           wafer, False)
        wafer_physical.SetRegularStructureId(1)

        return self.world_physical
Exemple #27
0
def convert_dict_to_g4vector(value, new_vector=G4.G4ThreeVector()):
    new_vector.x = value['x']
    new_vector.y = value['y']
    new_vector.z = value['z']

    return new_vector
Exemple #28
0
 def finalize(self, num_events):
     g4.gApplyUICommand('/vis/enable')
     g4.gApplyUICommand('/vis/viewer/flush')
Exemple #29
0
import sys

import Geant4
import g4 

import pyublas


if __name__ == "__main__":
    detector_construction = g4.DetectorConstruction()
    Geant4.gRunManager.SetUserInitialization(detector_construction)

    physics_list = g4.PhysicsList()
    Geant4.gRunManager.SetUserInitialization(physics_list)

    primary_generator = g4.PrimaryGeneratorAction()
    Geant4.gRunManager.SetUserAction(primary_generator)

    stepping_action = g4.SteppingAction()
    Geant4.gRunManager.SetUserAction(stepping_action)

    Geant4.gRunManager.Initialize()
    Geant4.gVisManager.Initialize()
    Geant4.gApplyUICommand("/control/execute %s" % sys.argv[1])
    Geant4.gRunManager.BeamOn(10)
    #Geant4.StartUISession()

    energy = detector_construction.GetEnergyHistogram()

Exemple #30
0
def ugh():
    yield 'e-', g4.G4ThreeVector(), g4.G4ThreeVector(0,0,1), 4*MeV
Exemple #31
0
    def addVolume(self,
                  name,
                  material,
                  vol_type,
                  dimensions,
                  position,
                  colour='red'):
        '''
        Add a new volume to the Geometry

        Arguments
        ---------

        name       (string)                  Volume name
        
        material   (string)                  GEANT4 material, e.g. 'Si'

        vol_type   (string)                  Volume type, e.g. 'Box'

        dimensions (float, float, float)     Dimensions as either floats or 
                   (string, string, string)  strings. e.g. (1,1,2) or ('1cm', '1cm', '2cm')

        position   (float, float, float)     Position as either strings or floats
                   (string, string, string)

        Optional Arguments
        ------------------

        colour     (string)                  Colour of volume

        '''

        try:
            assert vol_type in _g4_vol_types
        except AssertionError as e:
            self._logger.error(
                "Volume of type '{}' not present in GEANT4".format(vol_type))
            raise e

        try:
            self._log_vols[name] = g4py.ezgeom.G4EzVolume(name)
            self._logger.info(
                'Creating {} Volume from {} of size ({}, {}, {})'.format(
                    vol_type, material, *dimensions))
            getattr(self._log_vols[name], 'Create{}Volume'.format(vol_type))(
                self._get_material(material), *self._parse_units(dimensions))
            _color = G4.G4Color(*_colour_dict[colour.lower()])
            self._log_vols[name].SetColor(_color)
            self._log_vols[name].PlaceIt(
                G4.G4ThreeVector(*self._parse_units(position)))

        except Exception as e:
            if isBoostArgumentError(e):
                self._logger.error('Invalid Arguments for Volume Creation')
                self._logger.error(_g4_vol_types[vol_type])
                self._logger.error(
                    'Arguments:\n\tMaterial: {}\n\tDimension: {}\n\tPosition: {}'
                    .format(
                        material, ', '.join(
                            [str(self._parse_units(i)) for i in dimensions]),
                        ', '.join(
                            [str(self._parse_units(i)) for i in position])))
            raise e
Exemple #32
0
def main():
    args = get_args()

    global random_engine
    random_engine = g4.RanecuEngine()
    g4.HepRandom.setTheEngine(random_engine)
    g4.HepRandom.setTheSeed(random.randint(0, 1e9))

    global detector
    detector = MyGeometry(args.conf)
    g4.gRunManager.SetUserInitialization(detector)

    global physics_list
    physics_list = compton.PhysicsList()
    g4.gRunManager.SetUserInitialization(physics_list)

    global pga
    pga = PrimaryGeneratorAction(args.conf)
    g4.gRunManager.SetUserAction(pga)

    num_events = args.conf['PrimaryGenerator']['NumEvents']

    global t1, t3
    t1 = MyRunAction()
    t3 = MySteppingAction()
    g4.gRunManager.SetUserAction(t1)
    g4.gRunManager.SetUserAction(t3)

    global event_actions
    event_actions = create_event_actions(args.conf)
    for action in event_actions.values():
        g4.gRunManager.SetUserAction(action)

    # global stacking_action
    # stack_action = MyStackingAction()
    # g4.gRunManager.SetUserAction(stack_action)

    global tracking_action
    track_action = MyTrackingAction()
    g4.gRunManager.SetUserAction(track_action)

    global fields
    fields = create_fields(args.conf)

    g4.gRunManager.Initialize()

    global materials
    materials = create_materials(args.conf)
    # for mat in materials.values():
    #     property_table = mat.GetMaterialPropertiesTable()
    #     if property_table is not None:
    #         property_table.DumpTable()

    global detectors
    detectors = create_detectors(args.conf)

    for x in args.macro_filenames:
        g4.gControlExecute(x)

    # g4.gApplyUICommand('/tracking/storeTrajectory 1')
    g4.gRunManager.BeamOn(num_events)

    for k, sd in detectors.items():
        sd.finalize(num_events)

    return 0
Exemple #33
0
def gamma_spray(total, desc):
    i = 0
    y_bins = 50
    y_lower = -29
    y_upper = 30
    e_bins = 50
    e_lower, e_upper = 0.25, 25

    get_distrib_func = {
        "r": get_distrib_random,
        "g": get_distrib_gaussian,
        "c": get_distrib_cosine,
        "a": get_distrib_rayleigh,
        "m": get_distrib_mono,
    }

    tags = desc.split("-")
    tag = tags[0]
    #gYrE-col-2e7-KBYQ19-7
    if (tag == "triag"):
        ye = triangle_spray.triangle_spray(y_bins, y_lower, y_upper, e_bins,
                                           e_lower, e_upper, total)
        histo, _, _ = np.histogram2d(ye[:, 0],
                                     ye[:, 1],
                                     range=[[-29, 30], [0, 25]],
                                     bins=[50, 50])
    elif (tag == "image"):
        ye = image_spray.image_spray(y_bins, y_lower, y_upper, e_bins, e_lower,
                                     e_upper, total)
        histo, _, _ = np.histogram2d(ye[:, 0],
                                     ye[:, 1],
                                     range=[[-29, 30], [0, 25]],
                                     bins=[50, 50])
    else:
        Y_command_index = tag.find("Y") - 1
        E_command_index = tag.find("E") - 1
        if (tag.len != 4 or Y_command_index < 0 or E_command_index < 0):
            print("Illegal tag")
            return
        else:
            yc = tag[Y_command_index]
            ec = tag[E_command_index]
            ys = get_distrib_func[yc](total, y_bins, y_lower, y_upper)
            es = get_distrib_func[ec](total, e_bins, e_lower, e_upper)
            histo, _, _ = np.histogram2d(ys,
                                         es,
                                         range=[[-29, 30], [0, 25]],
                                         bins=[50, 50])

    #ys = get_ys(total)
    #energies = get_energies(total)
    #histo, _, _ = np.histogram2d(ys, energies, range=[[-29, 30],[0, 25]], bins=[50, 50])
    #ye = triangle_spray.triangle_spray(y_bins, y_lower, y_upper, e_bins, e_lower, e_upper, total)
    ye = image_spray.image_spray(y_bins, y_lower, y_upper, e_bins, e_lower,
                                 e_upper, total)
    histo, _, _ = np.histogram2d(ye[:, 0],
                                 ye[:, 1],
                                 range=[[-29, 30], [0, 25]],
                                 bins=[50, 50])
    #print("here once")
    np.savez("{}.npz".format(desc), histo=histo)
    while i < total:
        yield 'gamma', g4.G4ThreeVector(0, ye[i, 0] * mm,
                                        -25 * mm), g4.G4ThreeVector(0, 0,
                                                                    1), ye[i,
                                                                           1]
        i = i + 1