Beispiel #1
0
def main():
    """
    This test illustrates the setting a ParticleContainer with pre-existing IDs
    """
    print "************************************************************************************"
    print " This test illustrates the setting a ParticleContainer with pre-existing IDs "
    print "************************************************************************************ \n"

    p1 = Particle([0.2, 1.3, 33.0], "Si", 2.0, 1.23)
    p2 = Particle([5.0, 2.3, -22.1], "C", 1.0, 2.34)
    p3 = Particle([5.0, 2.3, -20.1], "C", 1.0, 2.34)
    p4 = Particle([0.0, 2.3, -20.1], "C", 1.0, 2.34)
    p5 = Particle([90.0, -0.0, -80.1], "Zr", 1.0, 4.0)

    idList = [2, 3, 6, 10]
    print "Using idList = ", idList, " to initialize particle container"
    atoms1 = ParticleContainer(idList)
    print "Initial atoms1 state from a pre-set ID list ", atoms1, "\n"

    atoms1[2] = p1
    atoms1[3] = p2
    atoms1[6] = p3
    atoms1[10] = p4
    print "atoms1 state from a pre-set ID list populated atoms1[..] = ... ", atoms1, "\n"

    atoms1.put(p5)
    print "atoms1 state after a put(p5) call ", atoms1, "\n"
Beispiel #2
0
def positron_track(positronSource, mat, Estep):

    positron = Particle('Positron', 511, 1)
    xpath, ypath, zpath = [0], [0], [0]
    x, y, z = 0, 0, 0
    positron.eKin = samplingEnergy(positronSource)

    r = np.random.uniform(-1, 1)
    theta = np.arccos(r)
    phi = np.random.uniform(0, 2 * np.pi)
    alpha, beta, gamma = np.sin(phi) * np.sin(theta), np.cos(phi) * np.sin(
        theta), np.cos(theta)
    n = np.array([alpha, beta, gamma])

    while positron.eKin > 25e-6:

        let = bethe_bloch(positron, mat)  #+ bremsstrahlung(positron, mat)
        r = Estep / let
        theta_sc = samplingTheta(positron, mat, r)
        phi_sc = np.random.uniform(0, 2 * np.pi)

        x += (r * n[0])
        y += (r * n[1])
        z += (r * n[2])

        n = ms3d(*n, theta_sc, phi_sc)

        xpath.append(x)
        ypath.append(y)
        zpath.append(z)

        #de = enStraggling(positron, mat, Estep/r, r)
        positron.eKin = positron.eKin - Estep

    return xpath, ypath, zpath
Beispiel #3
0
    def rope_particles(self, screen: pygame.Surface, camera: pygame.Vector3,
                       rx: int, ry: int, k_rx, x1: int, x2: int):
        left = projection(self.polygons[1].points[0], camera, rx, ry, True,
                          k_rx)
        right = projection(self.polygons[0].points[2], camera, rx, ry, True,
                           k_rx)
        pygame.draw.line(screen, "grey", (x1, SCREEN_DIMENSION[1]), left.xy, 2)
        pygame.draw.line(screen, "grey", (x2, SCREEN_DIMENSION[1]), right.xy,
                         2)
        body_left = projection(self.polygons[0].points[0], camera, rx, ry,
                               True, k_rx)
        body_right = projection(self.polygons[1].points[2], camera, rx, ry,
                                True, k_rx)
        self.particles.append(
            Particle((body_left.x -
                      random.randint(0, abs(int(body_right.x - body_left.x))),
                      body_left.y + 10), (0, 10), random.randint(10, 30)))
        self.particles.append(
            Particle((body_right.x +
                      random.randint(0, abs(int(body_right.x - body_left.x))),
                      body_right.y + 10), (0, 10), random.randint(10, 30)))

        for particle in self.particles:
            particle.update()
            particle.draw(screen)
Beispiel #4
0
def main():

    """
    This test illustrates the different ways Particle constructors can be used
    by using default values etc
    """
    print "************************************************************************************"
    print " This test illustrates the different ways Particle constructors can be used  "
    print " by using default values etc "
    print "************************************************************************************ \n"

    p1 = Particle( [0.2, 1.3,  33.0], "Si", 2.0, 1.23)
    p2 = Particle( [5.0, 2.3, -22.1], "C",  1.0, 2.34)
    p3 = Particle( [5.0, 2.3, -20.1], "C",  1.0, 2.34)
    p4 = Particle( [0.0, 2.3, -20.1], "C",  1.0, 2.34)

    p5 = Particle( type="Si", charge=2.0, pos=[0.2, 1.3, 54.0], mass=100.0)
    p6 = Particle( pos=[0.2, 1.3, 54.0], mass=100.0)
    p7 = Particle()
    p8 = Particle( [0.01, 2.4, 10.2], "Co", mass=134.0, charge=0.001 )
    p9 = Particle( [0.2, 1.3, 54.0], mass=100.0)
    p10 = Particle( [0.2, 1.3, 54.0] )

    # The following fail with argument checking native python functionality
    # p9  = Particle( [0.01, 2.4, 10.2], "Co", mass=134.0, 0.001 )
    # p10 = Particle( [0.01, 2.4, 10.2], mass=134.0, "Co" )

    print "p5  = ", p5.__dict__
    print "p6  = ", p6.__dict__
    print "p7  = ", p7.__dict__
    print "p8  = ", p8.__dict__
    print "p9  = ", p9.__dict__
    print "p10 = ", p10.__dict__
Beispiel #5
0
def test_visualize():
    particles = [
        Particle(0.3, 0.5, +1),
        Particle(0.0, -0.5, -1),
        Particle(-0.1, -0.4, +3)
    ]
    sim = ParticleSimulator(particles)
    sim.visualize()
Beispiel #6
0
def dust_regime_test(params):

    proton = Particle(params=params, **SMP.hadrons.proton)
    assert proton.in_equilibrium, "Proton must always stay in equilibrium"
    assert not proton.decoupling_temperature, "Proton can't decouple"
    assert proton.mass != 0, "Proton is massive"
    assert proton.eta == 1, "Proton is a fermion, it's eta must be equal to 1"
    assert proton.numerator() != 0, "Massive particles contribute to the numerator"
    assert proton.denominator() != 0, "Massive particles contribute to the denominator"
def main():
    """
    This test shows how to add StructureContainer objects together
    A special test to double-check re-labeling ... add a big container to a 'small' one
    """
    print "***************************************************************************************"
    print " This test shows how to add StructureContainer objects together "
    print " A special test to double-check re-labeling ... add a big container to a 'small' one "
    print "*************************************************************************************** \n"

    p1 = Particle([1.1, 1.1, 1.1], "Si", 2.0, 1.23)
    p2 = Particle([2.2, 2.2, 2.2], "C", 1.0, 2.34)
    p3 = Particle([3.3, 3.3, 3.3], "C", 1.0, 2.34)

    b1 = Bond(1, 2, 1.111, "hooke")
    b2 = Bond(2, 3, 2.222, "hooke")

    atoms1 = ParticleContainer()
    atoms1.put(p1)
    atoms1.put(p2)
    atoms1.put(p3)

    bonds1 = BondContainer()
    bonds1.put(b1)
    bonds1.put(b2)

    polymer1 = StructureContainer(atoms1,
                                  bonds1)  # Complete structure 1 completely

    p1other = Particle([1.11, 1.11, 1.11], "C", 1.0, 2.34)
    p2other = Particle([2.22, 2.22, 2.22], "Ar", 2.0, 2.34)

    b1other = Bond(1, 2, 1.1,
                   "hooke-2")  # Correct ptclIDs for second structure

    atoms2 = ParticleContainer()
    atoms2.put(p1other)
    atoms2.put(p2other)

    bonds2 = BondContainer()
    bonds2.put(b1other)

    polymer2 = StructureContainer(atoms2,
                                  bonds2)  # Complete structure 1 completely

    del p1, p2, p3, p1other, p2other, b1, b2, b1other, atoms1, atoms2, bonds1, bonds2
    print "\n Cleaning memory for initial objects \n"

    print "-------------------- Before adding --------------------"
    print "polymer1 = ", polymer1
    print "polymer2 = ", polymer2
    print " "

    print "-------------------- After adding --------------------"
    # polymer1 += polymer2
    polymer2 += polymer1
    print "polymer2 = ", polymer2
Beispiel #8
0
def three_particle_free_non_equilibrium_test(params):
    eps = 1e-14

    photon = Particle(**SMP.photon)
    neutrino_e = Particle(**SMP.leptons.neutrino_e)
    neutrino_mu = Particle(**SMP.leptons.neutrino_mu)
    sterile = Particle(**NuP.dirac_sterile_neutrino(mass=140 * UNITS.MeV))
    neutral_pion = Particle(**SMP.hadrons.neutral_pion)

    theta = 1e-3
    thetas = defaultdict(float, {
        'electron': theta,
    })

    interaction = NuI.sterile_hadrons_interactions(
        thetas = thetas, sterile=sterile,
        neutrinos = [neutrino_e],
        leptons = [],
        mesons = [neutral_pion]
    )

    universe = Universe(params=params)
    universe.add_particles([photon, neutrino_e, neutrino_mu, sterile, neutral_pion])
    universe.interactions += interaction

    params.update(universe.total_energy_density(), universe.total_entropy())

    universe.update_particles()
    universe.init_interactions()

    photon_distribution = photon._distribution
    neutrino_e_distribution = neutrino_e._distribution
    neutrino_mu_distribution = neutrino_mu._distribution
    sterile_distribution = sterile._distribution
    neutral_pion_distribution = neutral_pion._distribution

    universe.calculate_collisions()

    assert all(photon.collision_integral == 0), "Equilibrium particle integral is non-zero"
    assert all(numpy.abs(neutrino_e.collision_integral * params.h) < eps), "Integrals do not cancel"
    assert all(numpy.abs(sterile.collision_integral * params.h) < eps), "Integrals do not cancel"
    assert all(numpy.abs(neutral_pion.collision_integral * params.h) < eps), "Integrals do not cancel"
    assert all(neutrino_mu.collision_integral == 0), "Free particle integral is non-zero"

    universe.update_distributions()

    assert all(photon._distribution == photon_distribution),\
        "Equilibrium particle distribution changed"
    assert all(neutrino_e._distribution - neutrino_e_distribution < eps),\
        "Interacting particle distribution changed"
    assert all(sterile._distribution - sterile_distribution < eps),\
        "Interacting particle distribution changed"
    assert all(neutral_pion._distribution - neutral_pion_distribution < eps),\
        "Interacting particle distribution changed"
    assert all(neutrino_mu._distribution == neutrino_mu_distribution),\
        "Free particle distribution changed"
Beispiel #9
0
def mass_regime_switching_test(params):

    electron = Particle(params=params, **SMP.leptons.electron)
    assert electron.regime == REGIMES.INTERMEDIATE

    electron.mass = 0
    assert electron.regime == REGIMES.RADIATION

    electron.mass = 1e5 * UNITS.MeV
    assert electron.regime == REGIMES.DUST
Beispiel #10
0
def radiation_regime_test(params):

    photon = Particle(params=params, **SMP.photon)
    assert photon.in_equilibrium, "Photon must always stay in equilibrium"
    assert not photon.decoupling_temperature, "Photon can't decouple"
    assert photon.regime == REGIMES.RADIATION, "Photon is a relativistic particle"
    assert photon.mass == 0, "Photon is massless"
    assert photon.eta == -1, "Photon is a boson, it's eta must be equal to -1"
    assert photon.numerator() == 0, "Photon does not contribute to the numerator"
    assert photon.denominator() != 0, "Photon does contribute to the denominator"
Beispiel #11
0
def mass_regime_switching_test(params):

    electron = Particle(params=params, **SMP.leptons.electron)
    assert electron.regime == REGIMES.INTERMEDIATE

    electron.mass = 0
    assert electron.regime == REGIMES.RADIATION

    electron.mass = 1e5 * UNITS.MeV
    assert electron.regime == REGIMES.DUST
Beispiel #12
0
def dust_regime_test(params):

    proton = Particle(params=params, **SMP.hadrons.proton)
    assert proton.in_equilibrium, "Proton must always stay in equilibrium"
    assert not proton.decoupling_temperature, "Proton can't decouple"
    assert proton.mass != 0, "Proton is massive"
    assert proton.eta == 1, "Proton is a fermion, it's eta must be equal to 1"
    assert proton.numerator(
    ) != 0, "Massive particles contribute to the numerator"
    assert proton.denominator(
    ) != 0, "Massive particles contribute to the denominator"
Beispiel #13
0
def dust_regime_test(params):

    proton = Particle(params=params, **SMP.hadrons.proton)
    assert proton.in_equilibrium, "Proton must always stay in equilibrium"
    assert not proton.decoupling_temperature, "Proton can't decouple"
    assert proton.regime == REGIMES.DUST, \
        "Proton non-relativistic at {} MeV".format(params.T/UNITS.MeV)
    assert proton.mass != 0, "Proton is massive"
    assert proton.eta == 1, "Proton is a fermion, it's eta must be equal to 1"
    assert proton.numerator() != 0, "Massive particles contribute to the numerator"
    assert proton.denominator() != 0, "Massive particles contribute to the denominator"
Beispiel #14
0
def init_distribution_test(params):

    photon = Particle(params=params, **SMP.photon)
    neutrino = Particle(params=params, **SMP.leptons.neutrino_e)

    neutrino.update()

    assert numpy.allclose(photon._distribution,
                          numpy.vectorize(photon.distribution)(photon.grid.TEMPLATE))
    assert numpy.allclose(neutrino._distribution,
                          numpy.vectorize(neutrino.distribution)(neutrino.grid.TEMPLATE))
Beispiel #15
0
def intermediate_regime_test(params):

    electron = Particle(params=params, **SMP.leptons.electron)
    assert electron.in_equilibrium, "Electron must always stay in equilibrium"
    assert not electron.decoupling_temperature, "Electron can't decouple"
    assert electron.regime == REGIMES.INTERMEDIATE, \
        "Electron is not strictly relativistic at {} MeV".format(params.T/UNITS.MeV)
    assert electron.mass != 0, "Electron is massive"
    assert electron.eta == 1, "Electron is a fermion, it's eta must be equal to 1"
    assert electron.numerator() != 0, "Massive particles contribute to the numerator"
    assert electron.denominator() != 0, "Massive particles contribute to the denominator"
Beispiel #16
0
def main():
    """
    This test shows various operators within Particle and ParticleContainer classes.
    Shows memory management structure and access methods.
    """
    p1 = Particle([0.2, 1.3, 33.0], "Si", 2.0, 1.23)
    p2 = Particle([5.0, 2.3, -22.1], "C", 1.0, 2.34)
    p3 = Particle([5.0, 2.3, -20.1], "C", 1.0, 2.34)
    p4 = Particle([0.0, 2.3, -20.1], "C", 1.0, 2.34)

    atoms1 = ParticleContainer()
    atoms2 = ParticleContainer()

    atoms1.put(p1)
    atoms1.put(p2)
    #
    atoms2.put(p3)
    atoms2.put(p4)

    del p1, p2, p3, p4
    print "\n Cleaning memory for initial objects \n"

    print "x = atoms1[1] returns x as an effective 'reference' \n"
    x = atoms1[1]
    print "x = ", x.__dict__, "\n"
    x.position = [1.0, 1.0, 1.0]
    print "after changing with x.position = [1.0, 1.0, 1.0]"
    print "x = ", x.__dict__, "\n"

    # This value has been changed by code above
    print "atoms1 has been changed"
    print atoms1

    print "before, atoms1--> ", atoms1, "\n"
    del atoms1[2]
    print "after 'del atoms1[2]' atoms1 --> ", atoms1, "\n"

    print "Testing 'in' operator (1 in atoms1)"
    if (1 in atoms1):
        print "atoms1 contains gid 1"
    else:
        print "key not found in atoms1"

    print "Testing 'in' operator (5 in atoms1)"
    if (5 in atoms1):
        print "atoms1 contains gid 5"
    else:
        print "key not found in atoms1"

    print " "
    atoms1 += atoms2
    print "Will print the new atoms1 after adding atoms1 += atoms2"
    print atoms1
Beispiel #17
0
def radiation_regime_test(params):

    photon = Particle(params=params, **SMP.photon)
    assert photon.in_equilibrium, "Photon must always stay in equilibrium"
    assert not photon.decoupling_temperature, "Photon can't decouple"
    assert photon.regime == REGIMES.RADIATION, "Photon is a relativistic particle"
    assert photon.mass == 0, "Photon is massless"
    assert photon.eta == -1, "Photon is a boson, it's eta must be equal to -1"
    assert photon.numerator(
    ) == 0, "Photon does not contribute to the numerator"
    assert photon.denominator(
    ) != 0, "Photon does contribute to the denominator"
Beispiel #18
0
def temperature_regime_switching_test(params):

    electron = Particle(params=params, **SMP.leptons.electron)
    assert electron.regime == REGIMES.INTERMEDIATE

    params.T = 100 * UNITS.MeV
    electron.update()
    assert electron.regime == REGIMES.RADIATION

    params.T = 1 * UNITS.keV
    electron.update()
    assert electron.regime == REGIMES.DUST
Beispiel #19
0
def runStrucAdd(numPtcls1, numPtcls2):
    """
    Creates structures with ptcls and bonds between consecutive IDs
    Adds and reports timing

    Args:
        numPtcls1 (int): # of ptcls in first  struc
        numPtcls2 (int): # of ptcls in second struc
    Returns:
           (initTime, addTime, compressTime)
    """

    atoms1 = ParticleContainer()
    bonds1 = BondContainer()
    atoms2 = ParticleContainer()
    bonds2 = BondContainer()

    start_time = time.time()
    for n in range(numPtcls1):
        pobj1 = Particle([1.1, 1.1, 1.1], "Si", 2.0, float(n + 1))
        atoms1.put(pobj1)

    for n in range(1, numPtcls1):
        bobj1 = Bond(n, n + 1, 1.233, "hooke-1")
        bonds1.put(bobj1)

    for n in range(numPtcls2):
        pobj2 = Particle([2.2, 2.2, 2.2], "C", 1.0, float(n + 1))
        atoms2.put(pobj2)

    for n in range(1, numPtcls2):
        bobj2 = Bond(n, n + 1, 1.233, "hooke-2")
        bonds2.put(bobj2)
    end_time = time.time()

    initTime = end_time - start_time

    polymer1 = StructureContainer(atoms1, bonds1)  # Complete structure 1
    polymer2 = StructureContainer(atoms2, bonds2)  # Complete structure 2
    del atoms1, atoms2
    print "\n Cleaning memory for initial objects \n"

    start_time = time.time()
    polymer1 += polymer2
    end_time = time.time()
    addTime = end_time - start_time

    start_time = time.time()
    polymer1.compressPtclIDs()
    end_time = time.time()
    compressTime = end_time - start_time

    return (numPtcls1, numPtcls2, initTime, addTime, compressTime)
Beispiel #20
0
def temperature_regime_switching_test(params):

    electron = Particle(params=params, **SMP.leptons.electron)
    assert electron.regime == REGIMES.INTERMEDIATE

    params.aT = params.a * electron.mass * environment.get('REGIME_SWITCHING_FACTOR') * 2
    electron.update()
    assert electron.regime == REGIMES.RADIATION

    params.aT = params.a * electron.mass / environment.get('REGIME_SWITCHING_FACTOR') / 2
    electron.update()
    assert electron.regime == REGIMES.DUST
Beispiel #21
0
def intermediate_regime_test(params):

    electron = Particle(params=params, **SMP.leptons.electron)
    assert electron.in_equilibrium, "Electron must always stay in equilibrium"
    assert not electron.decoupling_temperature, "Electron can't decouple"
    assert electron.regime == REGIMES.INTERMEDIATE, \
        "Electron is not strictly relativistic at {} MeV".format(params.T/UNITS.MeV)
    assert electron.mass != 0, "Electron is massive"
    assert electron.eta == 1, "Electron is a fermion, it's eta must be equal to 1"
    assert electron.numerator(
    ) != 0, "Massive particles contribute to the numerator"
    assert electron.denominator(
    ) != 0, "Massive particles contribute to the denominator"
Beispiel #22
0
def samplingEnergy(beta_sourge):

    p = Particle('Positron', 511, 1)
    i = 0

    while i != 1:
        p.eKin = np.random.uniform(0, beta_sourge.Emax)
        y = np.random.uniform(0, 0.8)

        if y < beta_sourge.beta_spectrum(p):
            i = 1

    return p.eKin
def init_distribution_test(params):

    photon = Particle(params=params, **SMP.photon)
    neutrino = Particle(params=params, **SMP.leptons.neutrino_e)

    neutrino.update()

    assert numpy.allclose(
        photon._distribution,
        numpy.vectorize(photon.distribution)(photon.grid.TEMPLATE))
    assert numpy.allclose(
        neutrino._distribution,
        numpy.vectorize(neutrino.distribution)(neutrino.grid.TEMPLATE))
Beispiel #24
0
def main():
    """
    This test shows how the setPtclPos method works to externally set all particle
    positions from a list
    """
    print "************************************************************************************"
    print " This test shows how the setPtclPos method works to externally set all particle "
    print " positions from a list"
    print "************************************************************************************ \n"

    p1 = Particle([0.2, 1.3, 33.0], "Si", 2.0, 1.23)
    p2 = Particle([5.0, 2.3, -22.1], "C", 1.0, 2.34)
    p3 = Particle([5.0, 2.3, -20.1], "C", 1.0, 2.34)
    p4 = Particle([0.0, 2.3, -20.1], "C", 1.0, 2.34)

    b1 = Bond(1, 2, 1.233, "hooke")
    b2 = Bond(2, 3, 0.500, "hooke")
    b3 = Bond(3, 4, 2.301, "hooke")
    b4 = Bond(1, 3, 0.828, "hooke")

    atoms1 = ParticleContainer()
    atoms1.put(p1)
    atoms1.put(p2)
    atoms1.put(p3)
    atoms1.put(p4)

    bonds = BondContainer()
    bonds.put(b1)
    bonds.put(b2)
    bonds.put(b3)
    bonds.put(b4)

    del p1, p2, p3, p4, b1, b2, b3, b4
    polymer1 = StructureContainer(atoms1, bonds)
    del atoms1, bonds
    polymer1.setBoxLengths([[-3.0, 100], [-5, 23.0], [34.3, 100.1]])

    print "Initial state of structure before reset ", polymer1

    newPtclPos = [[1, 0.111, 0.222, 0.333], [2, 0.222, 0.333, 0.444],
                  [4, 0.444, 0.555, 0.666]]

    print "new positions = ", newPtclPos

    polymer1.setPtclPositions(newPtclPos)

    ptclPosList = polymer1.getPtclPositions()

    print "new positions from structure = ", ptclPosList
    print " "
    print "After position reset/get ", polymer1
Beispiel #25
0
def non_equilibium_setup():
    args, _ = setup()
    params = args[0]

    photon = Particle(**SMP.photon)
    neutrino_e = Particle(**SMP.leptons.neutrino_e)
    neutrino_mu = Particle(**SMP.leptons.neutrino_mu)
    neutrino_self_scattering = SMI.neutrino_scattering(neutrino_e, neutrino_e)

    universe = Universe(params=params)
    universe.add_particles([photon, neutrino_e, neutrino_mu])
    universe.interactions += [neutrino_self_scattering]

    return [params, universe], {}
Beispiel #26
0
def smooth_decoupling_test(params):

    neutrino = Particle(params=params, **SMP.leptons.neutrino_e)
    neutrino.update()

    energy_density = REGIMES.RADIATION.energy_density(neutrino)
    density = REGIMES.RADIATION.density(neutrino)
    pressure = REGIMES.RADIATION.pressure(neutrino)
    numerator = REGIMES.RADIATION.numerator(neutrino)
    denominator = REGIMES.RADIATION.denominator(neutrino)
    assert neutrino.energy_density - energy_density < eps
    assert neutrino.density - density < eps
    assert neutrino.pressure - pressure < eps
    assert neutrino.numerator() - numerator < eps
    assert neutrino.denominator() - denominator < eps
Beispiel #27
0
def distribution_interpolation_accuracy_test(params):

    neutrino = Particle(params=params, **SMP.leptons.neutrino_e)

    detailed_grid = numpy.linspace(neutrino.grid.MIN_MOMENTUM, neutrino.grid.MAX_MOMENTUM*2,
                                   num=neutrino.grid.MOMENTUM_SAMPLES*10, endpoint=True)

    print numpy.abs(
        neutrino.equilibrium_distribution_function(detailed_grid / neutrino.aT)
        - numpy.vectorize(neutrino.distribution)(detailed_grid)
    )

    assert all(numpy.abs(
        neutrino.equilibrium_distribution_function(detailed_grid / neutrino.aT)
        - numpy.vectorize(neutrino.distribution)(detailed_grid)
    ) < 1e-9)
Beispiel #28
0
 def kill(self, sprite):
     for _ in range(10):
         Particle((self.sprite_groups[PARTICLES], self.sprite_groups[ALL]),
                  sprite.get_pos(), sprite.particle_color, 10, 10, 10, 10)
     sprite.kill()
     if is_sounds():
         choice(self.death_sounds).play()
Beispiel #29
0
    def update(self):
        # particle fireworks VFX
        # create new bunch of sparks
        if randint(0, glb.FPS) == 5:
            x = randint(self.rect.left + 30, self.rect.right - 30)
            y = randint(self.rect.top + 150, self.rect.bottom - 10)
            color = [randint(150, 255), randint(150, 255), randint(150, 255)]
            color[randint(0, 2)] -= 150
            gravity = 0.1
            bounding_rect = self.rect.inflate(-10, -10)
            for i in range(randint(80, 200)):
                vx = gauss(0, 3)
                vy = -uniform(6, 2)
                radius = randint(2, 5)
                glow_size = radius*2
                glow_value = 25
                lifetime = randint(3*glb.FPS, 5*glb.FPS)
                particle = Particle(x, y, vx, vy, color, radius, lifetime, gravity,
                              vx_func=lambda vx: vx - 0.02,
                              size_func=lambda size: size - 0.03,
                              rect=bounding_rect,
                              glow_size=glow_size, glow_value=glow_value,
                              glow_size_func=lambda gsz: gsz - 0.02,
                              glow_value_func=lambda gval: gval - 0.3)
                self.particles.append(particle)

        self.particles = [p for p in self.particles if p.alive]
        
        super().update()
 def __init__(self,
              init_state = [[1, 0, 0, -1],
                            [-0.5, 0.5, 0.5, 0.5],
                            [-0.5, -0.5, -0.5, 0.5]],
              bounds = [-2, 2, -2, 2],
              size = 0.04,
              M = 0.05,
              G = 0.0, 
              interaction = None,):
     self.init_state = np.asarray(init_state, dtype=float)
     self.M = M * np.ones(self.init_state.shape[0])
     self.size = size
     self.state = self.init_state.copy()
     self.particles = []
     for idx, elem in enumerate(init_state):
         self.particles.append(Particle(particle_id = idx, 
                             position = elem[:2], 
                             velocity = elem[2:4], 
                             properties = {'mass' : M, 
                                           'size' : size,}))
     self.time_elapsed = 0
     self.bounds = bounds
     self.G = G
     self.pressure_record = []
     self.interaction = interaction
def benchmark():
    particles = [
        Particle(random.uniform(-1.0, 1.0), random.uniform(-1.0, 1.0),
                 random.uniform(-1.0, 1.0)) for i in range(1000)
    ]
    sim = ParticleSimulator(particles)
    sim.evolve(0.1)
Beispiel #32
0
def create_particles(x, y, color):
    count = random.randrange(20, 30, 1)
    numbers = range(-5, -1) + range(1, 5)
    for i in range(0, count):
        particle_group.add(
            Particle(x + 40, y + 40, random.choice(numbers),
                     random.choice(numbers), random.randint(3, 8), color))
 def addParticle(self):
     # self.particles.append(Particle(self.location))
     ch = random(10)
     if ch <= 5:
         self.particles.append(Particle(self.location))
     else:
         self.particles.append(RectParticle(self.location))
def main():
    """
    This test shows how to save/dump/restore state of structureContainers using pickle
    """
    print "************************************************************************************"
    print " This test shows how to save/dump/restore state of structureContainers using pickle"
    print "************************************************************************************ \n"

    p1 = Particle([0.2, 1.3, 33.0], "Si", 2.0, 1.23)
    p2 = Particle([5.0, 2.3, -22.1], "C", 1.0, 2.34)
    p3 = Particle([5.0, 2.3, -20.1], "C", 1.0, 2.34)
    p4 = Particle([0.0, 2.3, -20.1], "C", 1.0, 2.34)

    b1 = Bond(1, 2, 1.233, "hooke")
    b2 = Bond(2, 3, 0.500, "hooke")
    b3 = Bond(3, 4, 2.301, "hooke")
    b4 = Bond(1, 3, 0.828, "hooke")

    atoms1 = ParticleContainer()
    atoms1.put(p1)
    atoms1.put(p2)
    atoms1.put(p3)
    atoms1.put(p4)

    bonds = BondContainer()
    bonds.put(b1)
    bonds.put(b2)
    bonds.put(b3)
    bonds.put(b4)

    del p1, p2, p3, p4, b1, b2, b3, b4
    polymer1 = StructureContainer(atoms1, bonds)
    del atoms1, bonds
    polymer1.setBoxLengths([[-3.0, 100], [-5, 23.0], [34.3, 100.1]])

    print "Initial state of structure before dump ", polymer1

    print "-------------------------------------------------------------------------------- \n"

    polymer1.dump('polymer1')

    polymerNew = StructureContainer()
    polymerNew.restore('polymer1.pkl')

    print "After load from pickle \n"
    print polymerNew
    print "-------------------------------------------------------------------------------- \n"
def main():
    """
    This test shows basics of the Simulation classes
    Highlights differences between setting reference to the structure
    container and a deepcopy
    """
    print "************************************************************************************"
    print " This test shows basics of the Simulation classes"
    print " Highlights differences between setting reference to the structure"
    print "  container and a deepcopy"
    print "************************************************************************************ \n"

    p1 = Particle([0.2, 1.3, 33.0], "Si", 2.0, 1.23)
    p2 = Particle([5.0, 2.3, -22.1], "C", 1.0, 2.34)
    p3 = Particle([5.0, 2.3, -20.1], "C", 1.0, 2.34)

    atoms1 = ParticleContainer()
    atoms1.put(p1)
    atoms1.put(p2)
    atoms1.put(p3)

    polymer1 = StructureContainer(
        atoms1, verbose=False)  # Complete structure 1 completely
    polymer2 = StructureContainer(verbose=False)
    polymer2 += polymer1

    del p1, p2, p3, atoms1
    print "\n Cleaning memory for initial objects \n"

    print "-------------------- Before adding --------------------"
    print "polymer1 = ", polymer1
    print "polymer2 = ", polymer2
    print " "

    simObj1 = Simulation("GaussianJuly2014")
    simObj2 = Simulation("Lammps012038")

    simObj1.setStructureContainer(polymer1)
    simObj2.copyStructureContainerInto(polymer1)

    del polymer1.ptclC[1]

    print "-------------------- After changing polymer1 struc --------------------"
    print "polymer1 = ", polymer1
    simObj1.printStruc()
    simObj2.printStruc()
Beispiel #36
0
def distribution_interpolation_accuracy_test(params):
    eps = 1e-8

    neutrino = Particle(params=params, **SMP.leptons.neutrino_e)
    neutrino.update()

    detailed_grid = numpy.linspace(neutrino.grid.MIN_MOMENTUM, neutrino.grid.MAX_MOMENTUM*2,
                                   num=neutrino.grid.MOMENTUM_SAMPLES*10, endpoint=True)

    x = numpy.abs(
        neutrino.equilibrium_distribution_function(detailed_grid / neutrino.aT)
        / numpy.vectorize(neutrino.distribution)(detailed_grid)
        - 1
    )

    assert all(x < eps), ("Precision is worse than 1e-8 for momenta {}"
                          .format(detailed_grid[x >= eps] / UNITS.MeV))
def distribution_interpolation_accuracy_test(params):
    eps = 1e-8

    neutrino = Particle(params=params, **SMP.leptons.neutrino_e)
    neutrino.update()

    detailed_grid = numpy.linspace(neutrino.grid.MIN_MOMENTUM,
                                   neutrino.grid.MAX_MOMENTUM * 2,
                                   num=neutrino.grid.MOMENTUM_SAMPLES * 10,
                                   endpoint=True)

    x = numpy.abs(
        neutrino.equilibrium_distribution_function(detailed_grid /
                                                   neutrino.aT) /
        numpy.vectorize(neutrino.distribution)(detailed_grid) - 1)

    assert all(x < eps), ("Precision is worse than 1e-8 for momenta {}".format(
        detailed_grid[x >= eps] / UNITS.MeV))
Beispiel #38
0
def four_particle_decay_test(params):
    os.environ['SPLIT_COLLISION_INTEGRAL'] = ''

    photon = Particle(**SMP.photon)
    neutrino_e = Particle(**SMP.leptons.neutrino_e)
    sterile = Particle(**NuP.dirac_sterile_neutrino(mass=200 * UNITS.MeV))

    theta = 1e-4
    thetas = defaultdict(float, {
        'electron': theta,
    })

    interaction = NuI.sterile_leptons_interactions(
        thetas=thetas, sterile=sterile,
        neutrinos=[neutrino_e],
        leptons=[],
        kind = CollisionIntegralKind.F_f_vacuum_decay
    )

    for inter in interaction:
        inter.integrals = [integral for integral in inter.integrals
                            if sum(reactant.side for reactant in integral.reaction) in [2]]

    universe = Universe(params=params)
    universe.add_particles([photon, neutrino_e, sterile])
    universe.interactions += interaction

    params.update(universe.total_energy_density(), universe.total_entropy())

    universe.update_particles()
    universe.init_interactions()

    collision_integral = sterile.collision_integrals[0].integrate(sterile.grid.TEMPLATE)

    theo_value = (CONST.G_F * theta)**2 * sterile.mass**5 / (192 * numpy.pi**3) / UNITS.MeV

    decay_rate = -(collision_integral * sterile.params.H \
                * sterile.conformal_energy(sterile.grid.TEMPLATE) / sterile.conformal_mass \
                / sterile._distribution) / UNITS.MeV

    ratio = decay_rate / theo_value

    assert any(numpy.abs(val) - 1 < 1e-2 for val in ratio), "Four-particle decay test failed"
Beispiel #39
0
def three_particle_decay_test(params):
    os.environ['SPLIT_COLLISION_INTEGRAL'] = ''

    photon = Particle(**SMP.photon)
    neutrino_e = Particle(**SMP.leptons.neutrino_e)
    sterile = Particle(**NuP.dirac_sterile_neutrino(mass=200 * UNITS.MeV))
    neutral_pion = Particle(**SMP.hadrons.neutral_pion)

    theta = 1e-2
    thetas = defaultdict(float, {
        'electron': theta,
    })

    interaction = NuI.sterile_hadrons_interactions(
        thetas = thetas, sterile=sterile,
        neutrinos = [neutrino_e],
        leptons = [],
        mesons = [neutral_pion],
        kind = CollisionIntegralKind.F_f_vacuum_decay
    )

    universe = Universe(params=params)
    universe.add_particles([photon, neutrino_e, sterile, neutral_pion])
    universe.interactions += interaction

    params.update(universe.total_energy_density(), universe.total_entropy())

    universe.update_particles()
    universe.init_interactions()

    collision_integral = sterile.collision_integrals[0].integrate(sterile.grid.TEMPLATE)

    theo_value = (CONST.G_F * theta * neutral_pion.decay_constant)**2 \
                * sterile.mass**3 * (1 - (neutral_pion.mass / sterile.mass)**2)**2 \
                / (16 * numpy.pi) / UNITS.MeV

    decay_rate = -(collision_integral * sterile.params.H \
                * sterile.conformal_energy(sterile.grid.TEMPLATE) / sterile.conformal_mass \
                / sterile._distribution) / UNITS.MeV

    ratio = decay_rate / theo_value

    assert any(numpy.abs(val) - 1 < 1e-2 for val in ratio), "Three-particle decay test failed"
Beispiel #40
0
def decoupling_test():

    params = Params(T=SMP.leptons.neutrino_e['decoupling_temperature'] * 2,
                    dy=0.025)
    neutrino = Particle(params=params, **SMP.leptons.neutrino_e)

    assert neutrino.in_equilibrium
    eq_distribution = neutrino._distribution

    params.T /= 2
    params.a = params.m / params.T
    params.infer()

    assert neutrino.in_equilibrium, "Neutrino should not depend on global temperature change"
    neutrino.update()

    assert not neutrino.in_equilibrium, "Neutrino should have decoupled"
    noneq_distribution = neutrino._distribution

    assert all(eq_distribution == noneq_distribution), \
        "Free massless particle distribution should be conserved in conformal coordinates"
Beispiel #41
0
def decoupling_test():

    params = Params(T=SMP.leptons.neutrino_e['decoupling_temperature'] * 2,
                    dy=0.025)
    neutrino = Particle(params=params, **SMP.leptons.neutrino_e)

    assert neutrino.in_equilibrium
    eq_distribution = neutrino._distribution

    params.T /= 2
    params.a = params.m / params.T
    params.infer()

    assert neutrino.in_equilibrium, "Neutrino should not depend on global temperature change"
    neutrino.update()

    assert not neutrino.in_equilibrium, "Neutrino should have decoupled"
    noneq_distribution = neutrino._distribution

    assert all(eq_distribution == noneq_distribution), \
        "Free massless particle distribution should be conserved in conformal coordinates"
def main():
    """
    This test illustrates the different ways ParticleContainer can set Particle
    object data (eg the [] operator on ParticleContainer)
    """
    p1 = Particle([0.2, 1.3, 33.0], "Si", 2.0, 1.23)
    p2 = Particle([5.0, 2.3, -22.1], "C", 1.0, 2.34)
    p3 = Particle([5.0, 2.3, -20.1], "C", 1.0, 2.34)
    p4 = Particle([0.0, 2.3, -20.1], "C", 1.0, 2.34)

    p5 = Particle([9.0, -8.0, -80.1], "Ar", 1.0, 4.0)
    p6 = Particle([90.0, -0.0, -80.1], "Zr", 1.0, 4.0)

    atoms1 = ParticleContainer()
    atoms1.put(p1)
    atoms1.put(p2)
    atoms1.put(p3)
    atoms1.put(p4)

    print "Initial atoms1 state from an empty container, populated with put()", atoms1, "\n"

    tag = 4
    print "Replacing ID tag", tag, "with p5 particle data \n"
    atoms1[4] = p5
    print "atoms1 state", atoms1, "\n"

    tag = 5
    print "Setting ID tag that does not exist", tag, "with p6 particle data ---> atoms1[5]=p6 \n"
    atoms1[5] = p6
    print "atoms1 state", atoms1, "\n"
Beispiel #43
0
def homeostasis_test(params):

    params.T *= 2
    params.infer()

    neutrino = Particle(params=params, **SMP.leptons.neutrino_e)

    energy_density = neutrino.energy_density
    density = neutrino.density
    pressure = neutrino.pressure
    numerator = neutrino.numerator()
    denominator = neutrino.denominator()

    params.T /= 2
    params.aT *= 7
    params.a += 4

    assert neutrino.energy_density == energy_density \
        and neutrino.density == density \
        and neutrino.pressure == pressure \
        and neutrino.numerator() == numerator \
        and neutrino.denominator() == denominator, "Particle state should be persistent"
Beispiel #44
0
def test_evolve(benchmark):  # pytest-benchmark
    particles = [
        Particle(0.3, 0.5, +1),
        Particle(0.0, -0.5, -1),
        Particle(-0.1, -0.4, +3)
    ]
    sim = ParticleSimulator(particles)
    sim.evolve(0.1)

    p0, p1, p2 = particles

    def fequal(a, b, eps=1e-5):
        return abs(a - b) < eps

    assert fequal(p0.x, 0.210269)
    assert fequal(p0.y, 0.543863)
    assert fequal(p1.x, -0.099334)
    assert fequal(p1.y, -0.490034)
    assert fequal(p2.x, 0.191358)
    assert fequal(p2.y, -0.365227)

    benchmark(sim.evolve, 0.1)  # pytest-benchmark
Beispiel #45
0
mass = float(args.mass) * UNITS.MeV


folder = os.path.join(os.path.split(__file__)[0], 'output', 'mass={}'.format(args.mass))

T_initial = 20. * UNITS.MeV
T_final = 0.015 * UNITS.MeV
params = Params(T=T_initial,
                dy=0.1)

universe = Universe(params=params, folder=folder)

photon = Particle(**SMP.photon)
electron = Particle(**SMP.leptons.electron)
neutrino_e = Particle(**SMP.leptons.neutrino_e)
neutrino_mu = Particle(**SMP.leptons.neutrino_mu)
neutrino_tau = Particle(**MNP.leptons.neutrino_tau)
neutrino_tau.mass = mass

neutrino_e.decoupling_temperature = T_initial
neutrino_mu.decoupling_temperature = T_initial
neutrino_tau.decoupling_temperature = T_initial


universe.add_particles([
    photon,
    electron,
    neutrino_e,
    neutrino_mu,
    neutrino_tau,
Beispiel #46
0
from evolution import Universe
from common import UNITS, Params


folder = os.path.split(__file__)[0]

T_initial = 50. * UNITS.MeV
T_final = 10 * UNITS.MeV
params = Params(T=T_initial,
                dy=0.025)

universe = Universe(params=params, folder=folder)

photon = Particle(**SMP.photon)
electron = Particle(**SMP.leptons.electron)
neutrino_e = Particle(**SMP.leptons.neutrino_e)
neutrino_mu = Particle(**SMP.leptons.neutrino_mu)
neutrino_tau = Particle(**SMP.leptons.neutrino_tau)

universe.add_particles([
    photon,
    electron,
    neutrino_e,
    neutrino_mu,
    neutrino_tau,
])

neutrinos = [neutrino_e, neutrino_mu, neutrino_tau]
for neutrino in neutrinos:
    neutrino.decoupling_temperature = T_initial
Beispiel #47
0
from common import UNITS, Params, GRID

folder = os.path.split(__file__)[0]

T_initial = 1000. * UNITS.MeV
T_final = 100 * UNITS.MeV
params = Params(T=T_initial,
                dy=0.1)

universe = Universe(params=params, folder=folder)

photon = Particle(**SMP.photon)
electron = Particle(**SMP.leptons.electron)
muon = Particle(**SMP.leptons.muon)
tau = Particle(**SMP.leptons.tau)
neutrino_e = Particle(**SMP.leptons.neutrino_e)
neutrino_mu = Particle(**SMP.leptons.neutrino_mu)
neutrino_tau = Particle(**SMP.leptons.neutrino_tau)

universe.add_particles([
    photon,
    electron,
    muon,
    tau,
    neutrino_e,
    neutrino_mu,
    neutrino_tau,
])

neutrinos = [neutrino_e, neutrino_mu, neutrino_tau]
for neutrino in neutrinos:
Beispiel #48
0
    def read_cply(self,cply_file,debug = False):
        """
        Read cply file
        """
        
        # Load periodic table 
        pt = periodictable()

        read_lattice = False
        read_segment = False 

        with open(cply_file) as f:
            for line in f:
                col = line.split()
                if( read_lattice ):
                    self.latvec[lv_cnt][0] = float( col[0] )
                    self.latvec[lv_cnt][1] = float( col[1] )
                    self.latvec[lv_cnt][2] = float( col[2] )
                    if( lv_cnt == 2 ):
                        read_lattice = False 
                    lv_cnt += 1
                elif( read_segment ):
                    if( debug ):
                        print " Readin degment line ",col
                    
                    if( str(col[0]) == 'unit' ):
                        if( len(col) > 2 ):
                            error_line = "Each segment can only have 1 unit "
                            error_line += "\n {} in unit line will be ignored ".format(str(col[2::]))
                            print error_line
                        segment_i['unit'] =  col[1] 
                    if( str(col[0]) == 'func' ):
                        segment_i['func'] =  col[1::] 
                    if( str(col[0]) == 'end' ):
                        read_segment = False 
                                        
                elif( len(col) >= 4  and col[0] != "bond" and col[0] != "#" ):

                    pt_i = Particle()
                    pt_i.type = str(col[0])
                    pt_i.position = [ float(col[1]),float(col[2]),float(col[3]) ]
                    
                    add_dict = pt_i.tagsDict
                    el = pt.getelementWithSymbol(str(col[0]))
                    add_dict["symbol"] = str(col[0])
                    add_dict["number"] = el.number
                    add_dict["mass"] = el.mass

                    add_dict["cplytag"] = ""
                    add_dict["linkid"] = ""
                    add_dict["link"] = ""
                    pt_i.mass = el.mass
                    add_dict["chain"] = 1
                    add_dict["ring"] = 0
                    add_dict["residue"] = 1
                    add_dict["resname"] = "RES"
                    add_dict["qgroup"] = 1
                    add_dict["fftype"] = "??"
                    add_dict["label"] =  el.symbol  
                    add_dict["cov_radii"] = el.cov_radii
                    add_dict["vdw_radii"] = el.vdw_radii
                    add_dict["lmptype"] = -1
                    if (len(col) >= 14 ):
                        add_dict["label"] = str(col[4])
                        add_dict["fftype"] = str(col[5])
                        add_dict["mass"] = float(col[6])                        
                        pt_i.mass = float(col[6])                   
                        pt_i.charge = float(col[7])
                        add_dict["qgroup"] = int(col[8])                        
                        add_dict["ring"] = int(col[9])                        
                        add_dict["residue"] = int(col[10])
                        add_dict["resname"] = str(col[11])                        
                        add_dict["chain"] = int(col[12])                        
                        add_dict["cplytag"] = str(col[13])
                    elif (len(col) == 13 ):
                        add_dict["label"] = str(col[4])
                        add_dict["fftype"] = str(col[5])
                        add_dict["mass"] = float(col[6])                        
                        pt_i.mass = float(col[6])                   
                        pt_i.charge = float(col[7])
                        add_dict["qgroup"] = int(col[8])                        
                        add_dict["ring"] = int(col[9])                        
                        add_dict["residue"] = int(col[10])
                        add_dict["resname"] = str(col[11])                        
                        add_dict["chain"] = int(col[12])                        
                    elif (len(col) == 8 ):
                        add_dict["residue"] = int(col[5])
                        add_dict["resname"] = str(col[6])                        
                        add_dict["cplytag"] = str(col[7])
                    elif (len(col) == 7 ):
                        pt_i.charge = float(col[4])
                        add_dict["residue"] = int(col[5])
                        add_dict["resname"] = str(col[6])                                                
                    elif (len(col) == 5 ):
                        add_dict["cplytag"] = str(col[4])

                    pt_i.setTagsDict(add_dict)                    
                    self.ptclC.put(pt_i)

                    # # # print "debug pt_i ",len(col),pt_i
                    
                elif(len(col) >= 3 ):
                    if( col[0] == "bond"):
                        b_i = int(col[1])
                        b_j = int(col[2])
                        bnd = Bond(b_i,b_j)
                        #print "process_line bond line ",col
                        self.bondC.put(bnd)
                # Key word search 
                if( len(col) > 0 ):
                    if( str(col[0]) == 'lattice' ):
                        read_lattice = True
                        lv_cnt = 0
                    if( str(col[0]) == 'segment' ):
                        read_segment = True 
                        segment_i = {} #segment(str(col[1]))
                                       # segment_i = segment()
                        segment_i['tag'] = str(col[1])
                        segment_i['segment'] = {}
                        self.segments.append(segment_i)
        if( debug ):
            print segments
            sys.exit("debug in read_cply is True ")
Beispiel #49
0
def read_lmpdata( strucC , parmC , data_file):
    """
    Read Lammps data file


    Arguments:
        strucC     (StructureContainer)
        parmC      (ParameterContainer)
        data_file  (str) data file
    
    ReturnS:
        strucC     (StructureContainer)
        parmC      (ParameterContainer)
    
    """
        
    debug = 0
    verbose = True

    set_chain_numbers = True

    if( not set_chain_numbers ):
        print " Warning not reading in chain numbers!!! "

    # Load periodic table 
    pt = periodictable()
    

    F = open(data_file , 'r' )
    lines = F.readlines()
    F.close()
    
    #
    # Read in data header with number of parameters 
    #
    for line in lines:
        col = line.split()
        if ( len(col) >=2 ):
            # Read in number of each topolgical component  
            if( col[1] == "atoms" ):
                n_atoms = int( col[0] )
            elif( col[1] == "bonds" ):
                n_bonds = int( col[0] )
            elif( col[1] == "angles" ):
                n_angles = int( col[0] )
            elif( col[1] == "dihedrals" ):
                n_dihedrals = int( col[0] )
            elif( col[1] == "impropers" ):
                n_impropers = int( col[0] )

        if ( len(col) >= 3 ):
            # Read in number of each parameter type 
            if( col[1] == "atom" and   col[2] == "types" ):
                n_atypes = int( col[0] )
            elif( col[1] == "bond" and   col[2] == "types"  ):
                n_btypes = int( col[0] )
            elif( col[1] == "angle" and   col[2] == "types"  ):
                n_angtypes = int( col[0] )
            elif( col[1] == "dihedral" and   col[2] == "types"  ):
                n_dtypes = int( col[0] )
            elif( col[1] == "improper" and   col[2] == "types"  ):
                n_imptypes = int( col[0] )
                
        # Read in box size    
        if ( len(col) >= 4 ):
            if( col[2]  == "xlo"  and col[3]  == "xhi"  ):
                strucC.latvec[0][0] = float( col[1] ) - float( col[0] ) 
            if( col[2]  == "ylo"  and col[3]  == "yhi"  ):
                strucC.latvec[1][1] = float( col[1] ) - float( col[0] ) 
            if( col[2]  == "zlo"  and col[3]  == "zhi"  ):
                strucC.latvec[2][2] = float( col[1] ) - float( col[0] )

    # Prind debug
    if( verbose ):
        print " atoms ",n_atoms
        print " n_bonds ",n_bonds
        print " n_angles ",n_angles
        print " n_dihedrals ",n_dihedrals
        print " n_impropers ",n_impropers
        print ""
        print "n_atom_types",n_atypes
        print "n_bond_types",n_btypes
        print "n_angle_types",n_angtypes
        print "n_dihedral_types",n_dtypes
        print "n_imp_dihedral_types",n_imptypes



    # Check to see if a previous read has occured
    pt_overwrite = False
    if( len(strucC.ptclC) > 0 ):
        pt_overwrite = True
    # Check of conistent number of atoms
    if( pt_overwrite ):
        if(  len(strucC.ptclC)  != n_atoms):
            print "  %d atoms in passed structure "%(len(strucC.ptclC))
            print "  %d atoms in data file "%(n_atoms)
            sys.exit(" Inconsistent number of atoms " )

    else:
        #
        # Initialize particle container
        #
        for pid_i in range(n_atoms):
            pt_i = Particle( )
            strucC.ptclC.put(pt_i)

 
    bonds_overwrite = False
    if( len(strucC.bondC) > 0 ):
        bonds_overwrite = True

        if(  len(strucC.bondC)  != n_bonds):
            print "  %d bonds in passed structure "%(len(strucC.bondC))
            print "  %d bonds in data file "%(n_bonds)
            sys.exit(" Inconsistent number of bonds " )
    
    angles_overwrite = False
    if( len(strucC.angleC) > 0 ):
        angles_overwrite = True
        if(  len(strucC.angleC)  != n_angles):
            print "  %d angles in passed structure "%(len(strucC.angleC))
            print "  %d angles in data file "%(n_angles)
            sys.exit(" Inconsistent number of angles " )
    
    dih_overwrite = False
    if( len(strucC.dihC) > 0 ):
        dih_overwrite = True
        if(  len(strucC.dihC)  != n_dihedrals):
            print "  %d dihedrals in passed structure "%(len(strucC.dihC))
            print "  %d dihedrals in data file "%(n_dihedrals)
            sys.exit(" Inconsistent number of dihedrals " )
              
    imp_overwrite = False
    if( len(strucC.impC) > 0 ):
        imp_overwrite = True
        if(  len(strucC.impC)  != n_impropers):
            print "  %d impropers in passed structure "%(len(strucC.impC))
            print "  %d impropers in data file "%(n_impropers)
            sys.exit(" Inconsistent number of impropers " )          
            
    #
    # Intialize
    #   - read in boolean to off
    #
    read_Masses = 0
    read_Pair = 0
    read_Bond_coeff = 0
    read_Angle_coeff = 0
    read_Dihedral_coeff = 0
    read_Improper_coeff = 0
    
    read_Atoms = 0
    read_Bonds = 0
    read_Angles = 0
    read_Dihedrals = 0
    read_Impropers = 0
    
    #   - lists as indecise can be out of order in data file
    ATYPE_REF = n_atypes*[""]
    ATYPE_MASS = np.zeros(n_atypes)
    ATYPE_EP = np.zeros(n_atypes)
    ATYPE_SIG = np.zeros(n_atypes)
    
    BTYPE_REF = n_btypes*[2*[""]]
    BONDTYPE_R0 = np.zeros(n_btypes)
    BONDTYPE_K = np.zeros(n_btypes)
    
    ANGTYPE_REF = n_angtypes*[3*[""]]
    ANGLETYPE_R0 = np.zeros(n_angtypes)
    ANGLETYPE_K = np.zeros(n_angtypes)
    
    DTYPE_REF = n_dtypes*[4*[""]]
    DIHTYPE_C = np.zeros((n_dtypes,4))
    DIHTYPE_F = np.zeros(n_dtypes)
    DIHTYPE_K = np.zeros(n_dtypes)
    DIHTYPE_PN = np.zeros(n_dtypes)
    DIHTYPE_PHASE = np.zeros(n_dtypes)

    IMPTYPE_REF = n_imptypes*[4*[""]]
    IMPTYPE_F = np.zeros(n_imptypes)
    IMPTYPE_E0 = np.zeros(n_imptypes)
    IMPTYPE_K = np.zeros(n_imptypes)

    MOLNUMB = n_atoms*[0]
    ATYPE_IND  = n_atoms*[0]
    CHARGES  = np.zeros(n_atoms)
    R = n_atoms*[np.zeros(3)]
    ATYPE  = n_atoms*[""]
    
    BONDS = n_bonds*[[0,0]]
    BTYPE_IND = n_bonds*[0]
    
    ANGLES = n_angles*[[0,0,0]]
    ANGTYPE_IND = n_angles*[0]
    
    DIH = n_dihedrals*[[0,0,0,0]]
    DTYPE_IND = n_dihedrals*[0]


    

    #
    # Check if values exist and need to be updated or don't and need to be created 
    #
    ljtyp_update = False
    ljtyp_cnt = 0 
    if( len(parmC.ljtypC) > 0 ):
        print " LJ types will be updated "
        ljtyp_update = True
    btyp_update = False
    btyp_cnt = 0 
    if( len(parmC.btypC) > 0 ):
        print " Bond types will be updated "
        btyp_update = True
    atyp_update = False
    atyp_cnt = 0 
    if( len(parmC.atypC) > 0 ):
        print " Angle types will be updated "
        atyp_update = True
    dtyp_update = False
    dtyp_cnt = 0 
    if( len(parmC.dtypC) > 0 ):
        print " Dihedral types will be updated "
        dtyp_update = True
    imptyp_update = False
    imptyp_cnt = 0 
    if( len(parmC.imptypC) > 0 ):
        print " Improper dihedrals types will be updated "
        imptyp_update = True
    #
    # Read in data parameters 
    #
    
    for line in lines:
        col = line.split()
        if( read_Masses and  len(col) >= 2 ):
            
            cnt_Masses += 1
            ind = int(col[0]) - 1
            ATYPE_MASS[ind] = float(col[1])
                
            if( len(col) >= 4 ):
                ATYPE_REF[ind] = col[3]
                ptype1 = col[3]
            else:
                ATYPE_REF[ind] = "??"
                ptype1 = "??"
            
            mass_i = float(col[1])

        
            if( ljtyp_update ):
                ljtyp_cnt = ind  + 1
                if( ljtyp_cnt > len(parmC.ljtypC) ):
                    print "Mass index %d larger then length of previously read ljtypC %d"%(ind,len(parmC.ljtypC))
                ljtyp_i = parmC.ljtypC[ljtyp_cnt]
                ljtyp_i.setmass(mass_i)
            else:
                ljtyp_i = ljtype(ptype1)
                ljtyp_i.setmass(mass_i)
                parmC.ljtypC.put(ljtyp_i)
            
            # Turn of mass read
            if(cnt_Masses ==  n_atypes ):
                read_Masses = 0

        if( read_Pair and  len(col) >= 3 ):
            cnt_Pair += 1
            
            ind = int(col[0]) - 1
            ATYPE_EP[ind] = float(col[1])
            ATYPE_SIG[ind] = float(col[2])

            epsilon = float(col[1])
            sigma = float(col[2])
            ljtyp_ind = int(col[0])

            ljtyp_i = parmC.ljtypC[ljtyp_ind]
            ljtyp_i.setparam(epsilon,sigma)
            # Turn pair parameter read off 
            if(cnt_Pair >=  n_atypes ):
                read_Pair = 0

        
        if( read_Bond_coeff and  len(col) >= 3 ):
            cnt_Bond_coeff += 1
            #AT_i = int(col[0])
            #AT_j = int(col[1])
            b_ind = int( col[0]) - 1
            if( b_ind > n_btypes ):
                error_line = " Error in data file index of bond parameter exceeds number of bond parameters specified with bond types "
                sys.exit(error_line)
                
            BTYPE_REF[b_ind][0] = "??"
            BTYPE_REF[b_ind][1] = "??"
            BONDTYPE_K[b_ind] = float(col[1])
            BONDTYPE_R0[b_ind] = float(col[2])

            ptype1 = "??"
            ptype2 = "??"
            lmpindx = int( col[0])
            kb = float(col[1]) 
            r0 = float(col[2]) 
            btype = "harmonic"
            g_type = 1

            if( btyp_update ):
                btyp_cnt = b_ind + 1 
                btyp_i = parmC.btypC[btyp_cnt]
                btyp_i.setharmonic(r0,kb)
                btyp_i.set_g_indx(g_type)
                btyp_i.set_lmpindx(lmpindx)
            else:
                btyp_i = bondtype(ptype1,ptype2,btype)
                btyp_i.setharmonic(r0,kb)
                btyp_i.set_g_indx(g_type)
                btyp_i.set_lmpindx(lmpindx)
                parmC.btypC.put(btyp_i)
            
            if( cnt_Bond_coeff >=  n_btypes ):
                read_Bond_coeff = 0
                
        
        if( read_Angle_coeff and  len(col) >= 3 ):
            cnt_Angle_coeff += 1
            #AT_i = int(col[0])
            #AT_j = int(col[1])
            a_ind = int( col[0]) - 1
            if( a_ind > n_angtypes ):
                print sys.exit(" Error in data file index of angle parameter exceeds number of angle parameters specified with angle types ")
                
            ANGTYPE_REF[a_ind][0] = "??"
            ANGTYPE_REF[a_ind][1] = "??"
            ANGTYPE_REF[a_ind][2] = "??"
            ANGLETYPE_K[a_ind] = float(col[1])
            ANGLETYPE_R0[a_ind] = float(col[2])

            ptype1 = "??"
            ptype2 = "??"
            ptype3 = "??"
            lmpindx = int( col[0])
            theta0 = float( col[2] )        # degrees 
            kb =  float( col[1] ) 
            atype = "harmonic"
            gfunc_type = 1


            if( atyp_update ):
                atyp_cnt = a_ind + 1 
                atyp_i = parmC.atypC[atyp_cnt]
                atyp_i.set_g_indx(gfunc_type)
                atyp_i.set_lmpindx(lmpindx)
                atyp_i.setharmonic(theta0,kb)
            else:
                atyp_i = angletype(ptype1,ptype2,ptype3,atype)
                atyp_i.set_g_indx(gfunc_type)
                atyp_i.set_lmpindx(lmpindx)
                atyp_i.setharmonic(theta0,kb)
                parmC.atypC.put(atyp_i)
            
            if( cnt_Angle_coeff >=  n_angtypes ):
                read_Angle_coeff = 0
                
        
        if( read_Dihedral_coeff and  len(col) >= 3 ):
            cnt_Dihedral_coeff += 1
            #AT_i = int(col[0])
            #AT_j = int(col[1])
            d_ind = int( col[0]) - 1
            
            if( debug): print " reading dih type ",d_ind," cnt ",cnt_Dihedral_coeff," of ",n_dtypes
            
            if( d_ind > n_dtypes ):
                error_line =  " Error in data file index of dihedral parameter %d exceeds number of dihedral parameters %d "%(d_ind , n_dtypes)
                error_line += " specified with dihedral types "
                print sys.exit(error_line)
                
            DTYPE_REF[d_ind][0] = "??"
            DTYPE_REF[d_ind][1] = "??"
            DTYPE_REF[d_ind][2] = "??"
            DTYPE_REF[d_ind][3] = "??"
            
            # Assume OPLS dihedral type
            DIHTYPE_F[d_ind] = 3
            DIHTYPE_C[d_ind][0] = float(col[1])
            DIHTYPE_C[d_ind][1] = float(col[2])
            DIHTYPE_C[d_ind][2] = float(col[3])
            DIHTYPE_C[d_ind][3] = float(col[4])

            ptype1 = "??"
            ptype2 = "??"
            ptype3 = "??"
            ptype4 = "??"
            # Set parameters according to type 
            gfunc_type = 3 
            dtype = "opls"

            lmpindx = int( col[0] )
            k1 =  float( col[1] )
            k2 =  float( col[2] ) 
            k3 =  float( col[3] ) 
            k4 =  float( col[4] )


            if( dtyp_update ):
                dtyp_cnt = d_ind + 1 
                dtyp_i = parmC.dtypC[dtyp_cnt]
                dtyp_i.set_g_indx(gfunc_type)
                dtyp_i.set_lmpindx(lmpindx)
                dtyp_i.setopls(k1,k2,k3,k4)
            else:
                dtyp_i = dihtype(ptype1,ptype2,ptype3,ptype4,dtype)
                dtyp_i.set_g_indx(gfunc_type)
                dtyp_i.set_lmpindx(lmpindx)
                dtyp_i.setopls(k1,k2,k3,k4)
                parmC.dtypC.put(dtyp_i)
            
            if( cnt_Dihedral_coeff >=  n_dtypes ):
                read_Dihedral_coeff = 0
                
        
        if( read_Improper_coeff and  len(col) >= 3 ):
            cnt_Improper_coeff += 1
            #AT_i = int(col[0])
            #AT_j = int(col[1])
            imp_ind = int( col[0]) - 1
            
            if( debug): print " reading imp dih type ",imp_ind," cnt ",cnt_Improper_coeff," of ",n_imptypes
            
            if( imp_ind > n_imptypes ):
                error_line =  " Error in data file index of improper parameter %d exceeds number of improper parameters %d "%(imp_ind , n_imptypes)
                error_line += " specified with dihedral types "
                print sys.exit(error_line)
                
            IMPTYPE_REF[imp_ind][0] = "??"
            IMPTYPE_REF[imp_ind][1] = "??"
            IMPTYPE_REF[imp_ind][2] = "??"
            IMPTYPE_REF[imp_ind][3] = "??"
            
            # Assume OPLS dihedral type
            IMPTYPE_F[imp_ind] = 2
            KE = float(col[1])
            Eo = float(col[2])
            IMPTYPE_E0[imp_ind] = Eo
            IMPTYPE_K[imp_ind] = KE

            ptype1 = "??"
            ptype2 = "??"
            ptype3 = "??"
            ptype4 = "??"
            # Set parameters according to type 
            g_indx = 2
            dtype = "improper"

            lmpindx = int( col[0] )


            if( imptyp_update ):
                imptyp_cnt = imp_ind + 1 
                imptyp_i = parmC.imptypC[imptyp_cnt]
                imptyp_i.set_g_indx(g_indx)
                imptyp_i.setimp(Eo,KE)
                imptyp_i.set_lmpindx(lmpindx)                
            else:
                imptyp_i = imptype(ptype1,ptype2,ptype3,ptype4,dtype)
                imptyp_i.set_g_indx(g_indx)
                imptyp_i.setimp(Eo,KE)
                imptyp_i.set_lmpindx(lmpindx)
                parmC.imptypC.put(imptyp_i)
            
            if( cnt_Improper_coeff >=  n_imptypes ):
                read_Improper_coeff = 0
            
        if( read_Atoms and len(col) >= 7 ):
            cnt_Atoms += 1
            ind = int( col[0]) - 1
            if( ind > n_atoms ):
                print sys.exit(" Error in data file index of atoms exceeds number of atoms specified with atoms ")
            
            chain_i = int(col[1]) 
            lmptype_i = int(col[2]) #- 1
            indx = int(col[2]) - 1
            q_i = float(col[3])
            m_i = ATYPE_MASS[indx]
            fftype_i = ATYPE_REF[indx]
            el = pt.getelementWithMass(m_i)
            
            if( el.symbol == "VS" ):
                el.symbol = ATYPE_l[atom_indx].strip()
                fftype_i = "VS"
                m_i = 0.0 

            # HACK !!
            if( ATYPE_MASS[indx] == 9.0  ):
                el.symbol = "LP"
                fftype_i = "LP"
                m_i = 0.0
            
            r_i =  [ float(col[4]),float(col[5]),float(col[6])] 
            type_i = str(lmptype_i)

            #tagsD = {"chain":chain_i,"symbol":el.symbol,"number":el.number,"mass":el.mass,"cov_radii":el.cov_radii,"vdw_radii":el.vdw_radii}
            #if( pt_overwrite ):
            pt_i = strucC.ptclC[ind+1]
            pt_i.position = r_i

            update_coord = True
            if( not update_coord ):

                pt_i.type = el.symbol
                pt_i.charge = q_i
                pt_i.mass = m_i

                add_dict = pt_i.tagsDict
                # Set properties read in data file 
                if( set_chain_numbers ): add_dict["chain"] = chain_i
                add_dict["symbol"] = el.symbol
                add_dict["number"] = el.number
                add_dict["mass"] = el.mass
                add_dict["cov_radii"] = el.cov_radii
                add_dict["vdw_radii"] = el.vdw_radii
                add_dict["lmptype"] = lmptype_i
                add_dict["fftype"] = fftype_i 
                # 
                add_dict["ffmass"] = ATYPE_MASS[indx]
                add_dict["residue"] = chain_i
                add_dict["qgroup"] = chain_i
                add_dict["resname"] = "MOLR"
                add_dict["ring"] = 0
                add_dict["label"] = add_dict["symbol"]
                pt_i.setTagsDict(add_dict)

            
            if( cnt_Atoms >=  n_atoms ):
                read_Atoms = 0

        if(read_Bonds and len(col) >= 4 ):
            cnt_Bonds += 1
            ind = int( col[0]) - 1

            if( ind > n_bonds ):
                print sys.exit(" Error in data file index of bonds exceeds number of bonds specified with bonds ")
                
            BTYPE_IND[ind] = int(col[1] ) - 1
            BONDS[ind] = [int(col[2]) - 1 , int(col[3]) - 1 ]
            i_o = int(col[2])
            j_o = int(col[3])

            if( bonds_overwrite ):
                bondObj = strucC.bondC[cnt_Bonds]
                bondObj.pgid1 = i_o
                bondObj.pgid2 = j_o
                bondObj.set_lmpindx(int(col[1] ))
            else:
                bondObj = Bond( i_o, j_o )
                bondObj.set_lmpindx(int(col[1] ))
                strucC.bondC.put(bondObj)
                
            if( cnt_Bonds >=  n_bonds ):
                read_Bonds = 0

        if(read_Angles and len(col) >= 5 ):
            cnt_Angles += 1
            ind = int( col[0]) - 1
            ANGTYPE_IND[ind] = int(col[1] ) - 1
            ANGLES[ind] = [int(col[2]) - 1, int(col[3]) - 1, int(col[4]) - 1 ]
            
            k_o = int(col[2])
            i_o = int(col[3])
            j_o = int(col[4])
            
            if( cnt_Angles >=  n_angles ):
                read_Angles = 0

            if( angles_overwrite ):
                angleObj = strucC.angleC[cnt_Angles]
                angleObj.pgid1 = k_o
                angleObj.pgid2 = i_o
                angleObj.pgid3 = j_o
                angleObj.set_lmpindx(int(col[1] ))
            else:
                angleObj = Angle( k_o,i_o, j_o )
                angleObj.set_lmpindx(int(col[1] ))
                strucC.angleC.put(angleObj)
            
                
            
        if(read_Dihedrals and len(col) >= 6 ):
            cnt_Dihedrals += 1
            ind = int( col[0]) - 1
            
            DTYPE_IND[ind] = int(col[1] ) - 1
            DIH[ind] = [int(col[2]) - 1,int(col[3]) - 1, int(col[4]) - 1,int(col[5]) - 1]

            k_o = int(col[2])
            i_o = int(col[3])
            j_o = int(col[4])
            l_o = int(col[5])
            
            if( dih_overwrite ):
                dObj = strucC.dihC[cnt_Dihedrals]
                dObj.pgid1 = k_o
                dObj.pgid2 = i_o
                dObj.pgid3 = j_o
                dObj.pgid4 = l_o
                dObj.set_lmpindx(int(col[1] ))
            else:
                dObj = Dihedral( k_o,i_o, j_o,l_o )
                dObj.set_lmpindx(int(col[1] ))
                strucC.dihC.put(dObj)
                
            if( cnt_Dihedrals >=  n_dihedrals ):
                read_Dihedrals = 0
                
            
        if(read_Impropers and len(col) >= 2 ):
            cnt_Impropers += 1
            ind = int( col[0]) - 1
            
            k_o = int(col[2])
            i_o = int(col[3])
            j_o = int(col[4])
            l_o = int(col[5])
            
            if( imp_overwrite ):
                impObj = strucC.impC[cnt_Impropers]
                impObj.pgid1 = k_o
                impObj.pgid2 = i_o
                impObj.pgid3 = j_o
                impObj.pgid4 = l_o
                impObj.set_lmpindx(int(col[1] ))
                impObj.set_type("improper")
            else:
                impObj = Improper( k_o,i_o, j_o,l_o )
                impObj.set_lmpindx(int(col[1] ))
                impObj.set_type("improper")
                strucC.impC.put(impObj)
                

            if( cnt_Impropers >=  n_impropers ):
                read_Impropers = 0

        if ( len(col) >= 1  ):
            if( col[0] == "Masses" ):
                read_Masses = 1
                cnt_Masses = 0
                
            if( col[0] == "Atoms" ):
                read_Atoms = 1
                cnt_Atoms = 0
                
            if( col[0] == "Bonds" ):
                read_Bonds = 1
                cnt_Bonds = 0
                
            if( col[0] == "Angles" ):
                read_Angles = 1
                cnt_Angles  = 0
                
            if( col[0] == "Dihedrals" ):
                read_Dihedrals = 1
                cnt_Dihedrals = 0
                
            if( col[0] == "Impropers" ):
                read_Impropers = 1
                cnt_Impropers = 0
                
        if ( len(col) >= 2 ):
            if( col[0] == "Pair" and col[1] == "Coeffs" ):
                read_Pair = 1
                cnt_Pair = 0
            if( col[0] == "Bond" and col[1] == "Coeffs" ):
                read_Bond_coeff = 1
                cnt_Bond_coeff = 0
            if( col[0] == "Angle" and col[1] == "Coeffs" ):
                read_Angle_coeff  = 1
                cnt_Angle_coeff = 0
            if( col[0] == "Dihedral" and col[1] == "Coeffs" ):
                read_Dihedral_coeff  = 1
                cnt_Dihedral_coeff  = 0
                
            if( col[0] == "Improper" and col[1] == "Coeffs" ):
                read_Improper_coeff  = 1
                cnt_Improper_coeff  = 0
                            
        #    cnt_Bonds += 1
        #    ind = int( col[0]) - 1
        #    BTYPE_IND[ind] = int(col[1] ) - 1
        #    BONDS[ind][0] = int(col[2])
        #    if( cnt_Bonds >=  n_atoms ):
        #        read_Bonds = 0
        #        
            

                #
    if( ljtyp_update ):
        if( ljtyp_cnt != len(parmC.ljtypC) ):
            print " Number of LJ types read in %d does not match previously read %d "%(ljtyp_cnt,len(parmC.ljtypC))

    if( debug):
        for ind in range(len(ATYPE_MASS)):
            print ind+1,ATYPE_MASS[ind]
            
        for ind in range(len(ATYPE_EP)):
            print ind+1,ATYPE_EP[ind],ATYPE_SIG[ind]
        
        for ind in range(n_btypes):
            print ind+1,BONDTYPE_R0[ind],BONDTYPE_K[ind]
                
        for ind in range(n_angtypes):
            print ind+1,ANGLETYPE_R0[ind],ANGLETYPE_K[ind]
        
        for ind in range(n_dtypes):
            print ind+1,DIHTYPE_C[ind]
        
    debug =0
    
    if( debug):
        for ind in range(len(BONDS)):
            print ind+1,BONDS[ind]
            
    if(debug):
        sys.exit("debug 1 ")
    #
    #      
    return (strucC,parmC)
Beispiel #50
0
folder = os.path.join(os.path.split(__file__)[0], 'output')

T_interaction_freezeout = 0.1 * UNITS.MeV
T_final = 0.0008 * UNITS.MeV
params = Params(T=5. * UNITS.MeV,
                dy=0.003125)

universe = Universe(params=params, folder=folder)

photon = Particle(**SMP.photon)
electron = Particle(**SMP.leptons.electron)

# Set linearly spaced grid for neutrinos (such that 3, 5 and 7 MeV are in the grid)
from common import LinearSpacedGrid
linear_grid = LinearSpacedGrid(MOMENTUM_SAMPLES=51, MAX_MOMENTUM=50*UNITS.MeV)
neutrino_e = Particle(**SMP.leptons.neutrino_e, grid=linear_grid)
neutrino_mu = Particle(**SMP.leptons.neutrino_mu, grid=linear_grid)
neutrino_mu.dof = 4

neutrino_e.decoupling_temperature = 5. * UNITS.MeV
neutrino_mu.decoupling_temperature = 5. * UNITS.MeV

universe.add_particles([
    photon,
    electron,
    neutrino_e,
    neutrino_mu
])

universe.interactions += (
    SMI.neutrino_interactions(
Beispiel #51
0
from common import UNITS, Params
from common import LinearSpacedGrid


folder = os.path.join(os.path.split(__file__)[0], 'output')

T_final = 0.1 * UNITS.MeV
params = Params(T=10 * UNITS.MeV, dy=0.003125)

universe = Universe(params=params, folder=folder)

linear_grid = LinearSpacedGrid(MOMENTUM_SAMPLES=201, MAX_MOMENTUM=20 * UNITS.MeV)

photon = Particle(**SMP.photon)
electron = Particle(**SMP.leptons.electron)
neutrino_e = Particle(**SMP.leptons.neutrino_e, grid=linear_grid)
neutrino_mu = Particle(**SMP.leptons.neutrino_mu, grid=linear_grid)
neutrino_tau = Particle(**SMP.leptons.neutrino_tau, grid=linear_grid)

neutrino_e.decoupling_temperature = 10 * UNITS.MeV
neutrino_mu.decoupling_temperature = 10 * UNITS.MeV
neutrino_tau.decoupling_temperature = 10 * UNITS.MeV

universe.add_particles([photon, electron, neutrino_e, neutrino_mu, neutrino_tau])

interactions_pre = (
    SMI.neutrino_interactions(leptons=[electron], neutrinos=[neutrino_e, neutrino_mu, neutrino_tau])
)

integrals = [[] for n in range(len(interactions_pre))]
Beispiel #52
0
from library.SM import particles as SMP
from interactions import CrossGeneratingInteraction
from interactions.four_particle import FourParticleM, FourParticleIntegral
from particles import Particle
from evolution import Universe
from common import CONST, UNITS, Params


params = Params(T=2 * UNITS.MeV,
                dy=0.025)

photon = Particle(**SMP.photon)
neutrino = Particle(**SMP.leptons.neutrino_e)

neutrino_scattering = CrossGeneratingInteraction(
    particles=((neutrino, neutrino), (neutrino, neutrino)),
    antiparticles=((False, True), (False, True)),
    decoupling_temperature=0 * UNITS.MeV,
    Ms=(FourParticleM(K1=64 * CONST.G_F**2, order=(0, 1, 2, 3)),),
    integral_type=FourParticleIntegral
)

universe = Universe(params=params)
universe.PARALLELIZE = False
universe.add_particles([photon, neutrino])
universe.interactions += [neutrino_scattering]


import numpy
addition = numpy.vectorize(lambda x: 0.1 * numpy.exp(-(x/UNITS.MeV-3)**2),
                           otypes=[numpy.float_])
Beispiel #53
0
T_initial = 200 * UNITS.MeV
T_final = 50 * UNITS.MeV
params = Params(T=T_initial,
                dy=0.025)

universe = Universe(params=params, logfile=os.path.join(folder, 'log.txt'))

photon = Particle(**SMP.photon)

electron = Particle(**SMP.leptons.electron)

neutrino_e = Particle(**SMP.leptons.neutrino_e)

neutral_pion = Particle(**SMP.hadrons.neutral_pion)

sterile = Particle(**NuP.sterile_neutrino(300 * UNITS.MeV))
sterile.decoupling_temperature = T_initial

universe.add_particles([
    photon,

    electron,

    neutrino_e,

    neutral_pion,

    sterile,
])

thetas = defaultdict(float, {
Beispiel #54
0
folder = utils.ensure_dir(os.path.split(__file__)[0],
                          "mass={:e}_theta={:e}".format(mass / UNITS.MeV, theta)
                          + args.comment)


T_initial = 100. * UNITS.MeV
T_final = 0.0008 * UNITS.MeV
params = Params(T=T_initial,
                dy=0.025)

universe = Universe(params=params, folder=folder)

photon = Particle(**SMP.photon)
electron = Particle(**SMP.leptons.electron)
muon = Particle(**SMP.leptons.muon)
neutrino_e = Particle(**SMP.leptons.neutrino_e)
neutrino_mu = Particle(**SMP.leptons.neutrino_mu)
neutrino_tau = Particle(**SMP.leptons.neutrino_tau)
sterile = Particle(**NuP.dirac_sterile_neutrino(mass))

sterile.decoupling_temperature = T_initial
neutrino_e.decoupling_temperature = 10 * UNITS.MeV
neutrino_mu.decoupling_temperature = 10 * UNITS.MeV
neutrino_tau.decoupling_temperature = 10 * UNITS.MeV

universe.add_particles([
    photon,
    electron,
    muon,
    neutrino_e,
    neutrino_mu,
Beispiel #55
0
from common import UNITS, Params


folder = os.path.split(__file__)[0]

T_interaction_freezeout = 0.05 * UNITS.MeV
T_final = 0.0008 * UNITS.MeV
params = Params(T=10. * UNITS.MeV,
                dy=0.025)

universe = Universe(params=params, folder=folder)

photon = Particle(**SMP.photon)
electron = Particle(**SMP.leptons.electron)
neutrino_e = Particle(**SMP.leptons.neutrino_e)
neutrino_mu = Particle(**SMP.leptons.neutrino_mu)
neutrino_mu.dof = 4

neutron = Particle(**SMP.hadrons.neutron)
proton = Particle(**SMP.hadrons.proton)

universe.add_particles([
    photon,
    electron,
    neutrino_e,
    neutrino_mu,

    neutron,
    proton
])
Beispiel #56
0
def statistics_consistency_test(params):

    photon = Particle(params=params, **SMP.photon)
    neutrino = Particle(params=params, **SMP.leptons.neutrino_e)
    neutrino.update()
    assert 7. / 8. - neutrino.energy_density / photon.energy_density < eps
Beispiel #57
0
electron = Particle(**SMP.leptons.electron)
muon = Particle(**SMP.leptons.muon)
tau = Particle(**SMP.leptons.tau)

neutrino_e = Particle(**SMP.leptons.neutrino_e)
neutrino_mu = Particle(**SMP.leptons.neutrino_mu)
neutrino_tau = Particle(**SMP.leptons.neutrino_tau)

up = Particle(**SMP.quarks.up)
down = Particle(**SMP.quarks.down)
# charm = Particle(**SMP.quarks.charm)
strange = Particle(**SMP.quarks.strange)
# top = Particle(**SMP.quarks.top)
# bottom = Particle(**SMP.quarks.bottom)

sterile = Particle(**NuP.sterile_neutrino(300 * UNITS.MeV))
sterile.decoupling_temperature = T_initial

universe.add_particles([
    photon,

    electron,
    muon,
    tau,

    neutrino_e,
    neutrino_mu,
    neutrino_tau,

    up,
    down,
Beispiel #58
0
universe = Universe(params=params, folder=folder)

photon = Particle(**SMP.photon)

electron = Particle(**SMP.leptons.electron)
muon = Particle(**SMP.leptons.muon)
tau = Particle(**SMP.leptons.tau)

neutrino_e = Particle(**SMP.leptons.neutrino_e)
neutrino_mu = Particle(**SMP.leptons.neutrino_mu)
neutrino_tau = Particle(**SMP.leptons.neutrino_tau)

neutral_pion = Particle(**SMP.hadrons.neutral_pion)
charged_pion = Particle(**SMP.hadrons.charged_pion)

sterile = Particle(**NuP.dirac_sterile_neutrino(mass))
sterile_grid = LogSpacedGrid(10, T_initial * 5)
sterile.set_grid(sterile_grid)
sterile.decoupling_temperature = T_initial

grid = HeuristicGrid(mass, lifetime)
for neutrino in [neutrino_e, neutrino_mu, neutrino_tau]:
    neutrino.decoupling_temperature = 0 * UNITS.MeV
    neutrino.set_grid(grid)


universe.add_particles([
    photon,

    electron,
    muon,
Beispiel #59
0
from particles import Particle
from evolution import Universe
from library.SM import particles as SMP
from common import Params, UNITS


folder = os.path.join(os.path.split(__file__)[0], 'output')

T_final = 1 * UNITS.keV
params = Params(T=100 * UNITS.MeV,
                dy=0.05)

universe = Universe(params=params, folder=folder)

photon = Particle(**SMP.photon)
electron = Particle(**SMP.leptons.electron)
neutrino_e = Particle(**SMP.leptons.neutrino_e)
neutrino_mu = Particle(**SMP.leptons.neutrino_mu)
neutrino_tau = Particle(**SMP.leptons.neutrino_tau)

electron.decoupling_temperature = 10 * UNITS.MeV

universe.add_particles([photon, electron, neutrino_e, neutrino_mu, neutrino_tau])
universe.evolve(T_final)

initial_aT = universe.data['aT'][0]
print ("a * T is not conserved: {}"
       .format(any([initial_aT != value for value in universe.data['aT']])))
initial_a = universe.data['a'][len(universe.data)/2]
initial_t = universe.data['t'][len(universe.data)/2] / UNITS.s
last_a = universe.data['a'][-1]