Exemplo n.º 1
0
def test_write():
    """
    Creates a sample dataset.
    """
    # Box is 100 Mpc
    boxsize = 100 * unyt.Mpc

    # Generate object. cosmo_units corresponds to default Gadget-oid units
    # of 10^10 Msun, Mpc, and km/s
    x = Writer("galactic", boxsize)

    # 32^3 particles.
    n_p = 32**3

    # Randomly spaced coordinates from 0, 100 Mpc in each direction
    x.gas.coordinates = np.random.rand(n_p, 3) * (100 * unyt.Mpc)

    # Random velocities from 0 to 1 km/s
    x.gas.velocities = np.random.rand(n_p, 3) * (unyt.km / unyt.s)

    # Generate uniform masses as 10^6 solar masses for each particle
    x.gas.masses = np.ones(n_p, dtype=float) * (1e6 * unyt.msun)

    # Generate internal energy corresponding to 10^4 K
    x.gas.internal_energy = np.ones(
        n_p, dtype=float) * (1e4 * unyt.kb * unyt.K) / (1e6 * unyt.msun)

    # Generate initial guess for smoothing lengths based on MIPS
    x.gas.generate_smoothing_lengths(boxsize=boxsize, dimension=3)

    # If IDs are not present, this automatically generates
    x.write("test.hdf5")
Exemplo n.º 2
0
def generate_ics(redshift: float, filename: str, glass_filename: str) -> None:
    """
    Generate initial conditions for the CoolingRedshiftDependence example.
    """

    scale_factor = 1 / (1 + redshift)
    comoving_boxsize = boxsize / scale_factor

    glass_coordinates = get_coordinates(glass_filename)
    number_of_particles = len(glass_coordinates)

    gas_particle_mass = physical_density * (boxsize ** 3) / number_of_particles

    writer = Writer(cosmo_units, comoving_boxsize)

    writer.gas.coordinates = glass_coordinates * comoving_boxsize

    writer.gas.velocities = np.zeros_like(glass_coordinates) * cm / s

    writer.gas.masses = np.ones(number_of_particles, dtype=float) * gas_particle_mass

    # Leave in physical units; handled by boxsize change.
    writer.gas.internal_energy = (
        np.ones(number_of_particles, dtype=float)
        * 3.0
        / 2.0
        * (temperature * kb)
        / (mu_hydrogen * mh)
    )

    writer.gas.generate_smoothing_lengths(boxsize=comoving_boxsize, dimension=3)

    writer.write(filename)

    return
Exemplo n.º 3
0
def write_out_ics(
        filename,
        num_on_side,
        side_length=1.0,
        duplications=4,
        blob_radius=0.1,
        blob_location_x=0.5,
        inside_density=10,
        velocity_outside=2.7,  # Actually the mach number
):
    x = Writer(cgs_unit_system,
               [side_length * duplications, side_length, side_length] * cm)

    positions_outside, velocities_outside = generate_outside_of_blob(
        num_on_side,
        duplications,
        side_length,
        blob_location_x,
        blob_radius,
        initial_velocity=1.0,
    )
    positions_inside, velocities_inside = generate_blob(
        int(num_on_side * np.cbrt(inside_density)),
        side_length,
        blob_location_x,
        blob_radius,
    )

    coordinates = np.concatenate([positions_inside, positions_outside])

    velocities = np.concatenate([velocities_inside, velocities_outside])

    x.gas.coordinates = coordinates * cm

    x.gas.velocities = velocities * cm / s

    x.gas.masses = (np.ones(coordinates.shape[0], dtype=float) *
                    (side_length / num_on_side) * g)

    # Set to be (1 / n) c_s
    x.gas.internal_energy = (np.ones(coordinates.shape[0], dtype=float) * (
        (1.0 / velocity_outside) * x.gas.velocities[-1][0])**2 /
                             (5.0 / 3.0 - 1))

    # Need to correct the particles inside the sphere so that we are in pressure equilibrium everywhere
    x.gas.internal_energy[:len(positions_inside)] /= inside_density

    x.gas.generate_smoothing_lengths(boxsize=(duplications / 2) * side_length *
                                     cm,
                                     dimension=3)

    x.write(filename)

    return
Exemplo n.º 4
0
def test_reading_ic_units():
    """
    Test to ensure we are able to correctly read ICs created with swiftsimio
    """
    # File we're writing to
    test_filename = "test_write_output_units.hdf5"

    # Box is 100 Mpc
    boxsize = 100 * unyt.Mpc

    # Generate object. cosmo_units corresponds to default Gadget-oid units
    # of 10^10 Msun, Mpc, and km/s
    x = Writer(cosmo_units, boxsize)

    # 32^3 particles.
    n_p = 32 ** 3

    # Randomly spaced coordinates from 0, 100 Mpc in each direction
    x.gas.coordinates = np.random.rand(n_p, 3) * (100 * unyt.Mpc)

    # Random velocities from 0 to 1 km/s
    x.gas.velocities = np.random.rand(n_p, 3) * (unyt.km / unyt.s)

    # Generate uniform masses as 10^6 solar masses for each particle
    x.gas.masses = np.ones(n_p, dtype=float) * (1e6 * unyt.msun)

    # Generate internal energy corresponding to 10^4 K
    x.gas.internal_energy = (
        np.ones(n_p, dtype=float) * (1e4 * unyt.kb * unyt.K) / (1e6 * unyt.msun)
    )

    # Generate initial guess for smoothing lengths based on MIPS
    x.gas.generate_smoothing_lengths(boxsize=boxsize, dimension=3)

    # If IDs are not present, this automatically generates
    x.write(test_filename)

    data = load(test_filename)

    assert np.array_equal(data.gas.coordinates, x.gas.coordinates)
    assert np.array_equal(data.gas.velocities, x.gas.velocities)
    assert np.array_equal(data.gas.masses, x.gas.masses)
    assert np.array_equal(data.gas.internal_energy, x.gas.internal_energy)
    assert np.array_equal(data.gas.smoothing_length, x.gas.smoothing_length)

    remove(test_filename)

    return
Exemplo n.º 5
0
def write_out_glass(filename, cube, side_length=1.0):
    x = Writer(cgs_unit_system, side_length * cm)

    x.gas.coordinates = cube * cm

    x.gas.velocities = np.zeros_like(cube) * cm / s

    x.gas.masses = np.ones(cube.shape[0], dtype=float) * g

    x.gas.internal_energy = np.ones(cube.shape[0], dtype=float) * erg / g

    x.gas.generate_smoothing_lengths(boxsize=side_length * cm, dimension=3)

    x.write(filename)

    return
Exemplo n.º 6
0
def test_write():
    """
    Tests whether swiftsimio can handle a new particle type. If the test doesn't crash
    this is a success.
    """
    # Use default units, i.e. cm, grams, seconds, Ampere, Kelvin
    unit_system = unyt.UnitSystem(name="default",
                                  length_unit=unyt.cm,
                                  mass_unit=unyt.g,
                                  time_unit=unyt.s)
    # Specify a new type in the metadata - currently done by editing the dictionaries directly.
    # TODO: Remove this terrible way of setting up different particle types.
    swp.particle_name_underscores[6] = "extratype"
    swp.particle_name_class[6] = "Extratype"
    swp.particle_name_text[6] = "Extratype"

    swmw.extratype = {"smoothing_length": "SmoothingLength", **swmw.shared}

    boxsize = 10 * unyt.cm

    x = Writer(unit_system, boxsize, unit_fields_generate_units=generate_units)

    x.extratype.coordinates = np.zeros((10, 3)) * unyt.cm
    for i in range(0, 10):
        x.extratype.coordinates[i][0] = float(i)

    x.extratype.velocities = np.zeros((10, 3)) * unyt.cm / unyt.s

    x.extratype.masses = np.ones(10, dtype=float) * unyt.g

    x.extratype.smoothing_length = np.ones(10, dtype=float) * (5.0 * unyt.cm)

    x.write("extra_test.hdf5")

    # Clean up these global variables we screwed around with...
    swp.particle_name_underscores.pop(6)
    swp.particle_name_class.pop(6)
    swp.particle_name_text.pop(6)
Exemplo n.º 7
0
# generate the coordinates
dist = np.random.rand(num_part) * (max_r - min_r) + min_r
angle = np.random.rand(num_part) * 2 * np.pi
# more easy to do it in 2D, therefore coords[:, 2] == 0
coords = np.zeros((num_part, 3))
coords[:, 0] = dist * np.sin(angle)
coords[:, 1] = dist * np.cos(angle)
coords += boxsize * 0.5

# generate the masses
m = np.ones(num_part) * masses

# generate the velocities
sign = np.random.rand(num_part)
sign[sign < 0.5] = -1
sign[sign >= 0.5] = 1

v = np.zeros((num_part, 3))
v[:, 0] = sign * np.sqrt(G * M / (dist * (1 + np.tan(angle)**2)))
v[:, 1] = - np.tan(angle) * v[:, 0]

# Write the snapshot
units = unyt.UnitSystem("Planets", unyt.AU, unyt.mearth, unyt.yr)

snapshot = Writer(units, boxsize * unyt.AU)
snapshot.dark_matter.coordinates = coords * unyt.AU
snapshot.dark_matter.velocities = v * unyt.AU / unyt.yr
snapshot.dark_matter.masses = m * unyt.mearth

snapshot.write(filename)
Exemplo n.º 8
0

unitL = unyt.cm
t_end = 1e-3 * unyt.s
edgelen = unyt.c.to("cm/s") * t_end * 2.0
edgelen = edgelen.to(unitL)
boxsize = unyt.unyt_array([edgelen.v, edgelen.v, 0.0], unitL)

xs = unyt.unyt_array(
    [np.array([xs[0] * edgelen, xs[1] * edgelen, 0.0 * edgelen])], unitL
)
xp *= edgelen
h *= edgelen


w = Writer(unit_system=unyt.unit_systems.cgs_unit_system, box_size=boxsize, dimension=2)

w.gas.coordinates = xp
w.stars.coordinates = xs
w.gas.velocities = np.zeros(xp.shape) * (unyt.cm / unyt.s)
w.stars.velocities = np.zeros(xs.shape) * (unyt.cm / unyt.s)
w.gas.masses = np.ones(xp.shape[0], dtype=np.float64) * 100 * unyt.g
w.stars.masses = np.ones(xs.shape[0], dtype=np.float64) * 100 * unyt.g
w.gas.internal_energy = (
    np.ones(xp.shape[0], dtype=np.float64) * (300.0 * unyt.kb * unyt.K) / (unyt.g)
)

w.gas.smoothing_length = h
w.stars.smoothing_length = w.gas.smoothing_length[:1]

w.write("propagationTest-2D.hdf5")
Exemplo n.º 9
0
        mask = xp[:, i] > 1.0
        xp[mask, i] -= 1.0

    # Set up metadata
    unitL = unyt.Mpc
    edgelen = 22 * 1e-3 * unitL  # 22 so we can cut off 1kpc on each edge for image
    edgelen = edgelen.to(unitL)
    boxsize = np.array([1.0, 1.0, 0.0]) * edgelen

    xs = unyt.unyt_array(
        [np.array([xs[0] * edgelen, xs[1] * edgelen, 0.0 * edgelen])], unitL
    )
    xp *= edgelen
    h *= edgelen

    w = Writer(unit_system=cosmo_units, box_size=boxsize, dimension=2)

    # write particle positions ans smoothing lengths
    w.gas.coordinates = xp
    w.stars.coordinates = xs
    w.gas.velocities = np.zeros(xp.shape) * (unitL / unyt.Myr)
    w.stars.velocities = np.zeros(xs.shape) * (unitL / unyt.Myr)
    w.gas.smoothing_length = h
    w.stars.smoothing_length = w.gas.smoothing_length[:1]

    # get gas masses
    nH = 1e-3 * unyt.cm ** (-3)
    rhoH = nH * unyt.proton_mass
    Mtot = rhoH * edgelen ** 3
    mpart = Mtot / xp.shape[0]
    mpart = mpart.to(cosmo_units["mass"])
Exemplo n.º 10
0
                        type=float,
                        default=1.0)

    args = vars(parser.parse_args())
    boxsize = args["boxsize"] * unyt.cm
    n_part = args["npart"]
    mass = args["mass"] * unyt.g
    low = args["low"] * unyt.erg / unyt.g
    high = args["high"] * unyt.erg / unyt.g

    if not (n_part % 2 == 0):
        raise AttributeError("Please ensure --npart is even.")

    cgs = unyt.unit_systems.cgs_unit_system

    boxsize = 1.0 * unyt.cm

    writer = Writer(cgs, boxsize, dimension=1)

    coordinates = np.zeros((n_part, 3), dtype=float) * unyt.cm
    coordinates[:, 0] = get_particle_positions(boxsize, n_part)

    writer.gas.coordinates = coordinates
    writer.gas.velocities = np.zeros(
        (n_part, 3), dtype=float) * unyt.cm / unyt.s
    writer.gas.masses = get_particle_masses(mass, n_part)
    writer.gas.internal_energy = get_particle_u(low, high, n_part)
    writer.gas.smoothing_length = get_particle_hsml(boxsize, n_part)

    writer.write("diffusion.hdf5")
Exemplo n.º 11
0
            xp.append(np.array([x, y, z], dtype=np.float64))

# Generate star coordinates
for i in range(n_s):
    # factor 0.52 below: shift particles a bit so they don't overlap with hydro
    x = 0.4 * boxsize + (i + 0.52) * ds
    for j in range(n_s):
        y = 0.4 * boxsize + (j + 0.52) * ds
        for k in range(n_s):
            z = 0.4 * boxsize + (k + 0.52) * ds
            xs.append(np.array([x, y, z], dtype=np.float64))

xp = unyt.unyt_array(xp, boxsize.units)
xs = unyt.unyt_array(xs, boxsize.units)

w = Writer(unyt.unit_systems.cgs_unit_system, boxsize)

w.gas.coordinates = xp
w.stars.coordinates = xs
w.gas.velocities = np.zeros(xp.shape) * (unyt.cm / unyt.s)
w.stars.velocities = np.zeros(xs.shape) * (unyt.cm / unyt.s)
w.gas.masses = np.ones(xp.shape[0], dtype=np.float64) * 1000 * unyt.g
w.stars.masses = np.ones(xs.shape[0], dtype=np.float64) * 1000 * unyt.g
w.gas.internal_energy = (np.ones(xp.shape[0], dtype=np.float64) *
                         (300.0 * unyt.kb * unyt.K) / unyt.g)

# Generate initial guess for smoothing lengths based on MIPS
w.gas.generate_smoothing_lengths(boxsize=boxsize, dimension=3)
w.stars.generate_smoothing_lengths(boxsize=boxsize, dimension=3)

# If IDs are not present, this automatically generates
Exemplo n.º 12
0

xp_tot = np.vstack((xp, xp_sampled))
xp = unyt.unyt_array(xp_tot, boxsize.units)

xs_tot = np.vstack((xs, xs_sampled))
xs = unyt.unyt_array(xs_tot, boxsize.units)

vp_tot = np.vstack((velp, velp_sampled))
vp = unyt.unyt_array(vp_tot, unyt.km / unyt.s)

vs_tot = np.vstack((vels, vels_sampled))
vs = unyt.unyt_array(vs_tot, unyt.km / unyt.s)


w = Writer(cosmo_units, boxsize)
w.gas.coordinates = xp
w.stars.coordinates = xs
w.gas.velocities = vp
w.stars.velocities = vs
w.gas.masses = np.ones(xp.shape[0], dtype=np.float64) * 1e6 * unyt.msun
w.stars.masses = np.random.uniform(1e8, 1e10, size=xs.shape[0]) * unyt.msun
# Generate internal energy corresponding to 10^4 K
w.gas.internal_energy = (
    np.ones(xp.shape[0], dtype=np.float64)
    * (1e4 * unyt.kb * unyt.K)
    / (1e6 * unyt.msun)
)


# Generate initial guess for smoothing lengths based on MIPS
Exemplo n.º 13
0
    number_of_particles = len(h)
    side_length = (number_of_particles * particle_mass / initial_density)**(1 /
                                                                            3)
    side_length.convert_to_base(unit_system)

    print(f"Your box has a side length of {side_length}")

    # Find the central particle
    central_particle = np.sum((positions - 0.5)**2, axis=1).argmin()

    # Inject the feedback into that central particle
    background_internal_energy = ((1.0 / (mu * mh)) * (kb / (gamma - 1.0)) *
                                  initial_temperature)
    heated_internal_energy = (1.0 /
                              (mu * mh)) * (kb /
                                            (gamma - 1.0)) * inject_temperature
    internal_energy = np.ones_like(h) * background_internal_energy
    internal_energy[central_particle] = heated_internal_energy

    # Now we have all the information we need to set up the initial conditions!
    output = Writer(unit_system=unit_system, box_size=side_length)

    output.gas.coordinates = positions * side_length
    output.gas.velocities = np.zeros_like(positions) * cm / s
    output.gas.smoothing_length = h * side_length
    output.gas.internal_energy = internal_energy
    output.gas.masses = np.ones_like(h) * particle_mass

    output.write(file_name)
Exemplo n.º 14
0
filename = "/cosma7/data/dp004/jlvc76/nIFTy/IC_CLUSTER_00019"

length = unyt.kpc
mass = 1e10 * unyt.msun
time = (1.0 * unyt.s * unyt.kpc / unyt.km).to("s")
velocity = length / time
energy_per_unit_mass = (length / time)**2

nifty_units = unyt.UnitSystem("nifty", 1e3 * length, mass, time)

writer = Writer(
    unit_system=nifty_units,
    box_size=readheader(filename, "boxsize") * length,
    dimension=3,
    compress=True,
    extra_header={
        "Redshift": readheader(filename, "redshift"),
        "Omega0": readheader(filename, "O0"),
        "OmegaLambda": readheader(filename, "Ol"),
        "HubbleParam": readheader(filename, "h"),
    },
)

writer.gas.coordinates = unyt.unyt_array(readsnap(filename, "pos", 0), length)

writer.gas.velocities = unyt.unyt_array(readsnap(filename, "vel", 0), velocity)

writer.gas.masses = unyt.unyt_array(readsnap(filename, "mass", 0), mass)

writer.gas.internal_energy = unyt.unyt_array(readsnap(filename, "u", 0),
                                             energy_per_unit_mass)
Exemplo n.º 15
0
n_p = n_p_1D**3
# Read particle positions and from the glass
glass_pos = glass["/PartType1/Coordinates"][:, :]
glass.close()

# Calculate mean baryon density today from comological parameters
H_0 = 100.0 * hubble_param * unyt.km / unyt.s / unyt.Mpc
rho_crit_0 = 3.0 * H_0**2 / (8.0 * np.pi * unyt.G)
rho_bar_0 = Omega_bar * rho_crit_0

# From this, we calculate the mass of the gas particles
gas_particle_mass = rho_bar_0 * boxsize**3 / (n_p_1D**3)

# Generate object. cosmo_units corresponds to default Gadget-oid units
# of 10^10 Msun, Mpc, and km/s
x = Writer(cosmo_units, boxsize)

# 32^3 particles.
n_p = 32**3

# Make gas coordinates from 0, 100 Mpc in each direction
x.gas.coordinates = glass_pos * boxsize

# Random velocities from 0 to 1 km/s
x.gas.velocities = np.zeros((n_p, 3)) * (unyt.km / unyt.s)

# Generate uniform masses as 10^6 solar masses for each particle
x.gas.masses = np.ones(n_p, dtype=float) * gas_particle_mass

# Generate internal energy corresponding to 10^4 K
x.gas.internal_energy = (np.ones(n_p, dtype=float) * (T_i * unyt.kb * unyt.K) /
Exemplo n.º 16
0
if __name__ == "__main__":
    glass = h5py.File("glassPlane_128.hdf5", "r")

    # Read particle positions and h from the glass
    pos = glass["/PartType0/Coordinates"][:, :]
    h = glass["/PartType0/SmoothingLength"][:]
    glass.close()

    pos *= boxsize
    h *= boxsize

    numPart = np.size(h)
    V = boxsize**2 / numPart

    w = Writer(unyt.unit_systems.cgs_unit_system, boxsize, dimension=2)

    w.gas.coordinates = pos
    w.gas.velocities = np.zeros((numPart, 3)) * (unyt.cm / unyt.s)
    w.gas.masses = np.ones(numPart, dtype=np.float64) * 1000 * unyt.g
    w.gas.internal_energy = (np.ones(numPart, dtype=np.float64) *
                             (300.0 * unyt.kb * unyt.K) / (unyt.g))

    # Generate initial guess for smoothing lengths based on MIPS
    w.gas.smoothing_length = h

    # If IDs are not present, this automatically generates
    w.write(outputfilename)

    # Now open file back up again and add photon groups
    # you can make them unitless, the units have already been
Exemplo n.º 17
0
    glass = h5py.File("glassPlane_64.hdf5", "r")
    parts = glass["PartType0"]
    xp = parts["Coordinates"][:]
    h = parts["SmoothingLength"][:]
    glass.close()

    # Set up metadata
    unitL = unyt.Mpc
    edgelen = 2 * 15 * 1e-3 * unitL  # 30 kpc
    edgelen = edgelen.to(unitL)
    boxsize = np.array([1.0, 1.0, 0.0]) * edgelen

    xp *= edgelen
    h *= edgelen

    w = Writer(unit_system=cosmo_units, box_size=boxsize, dimension=2)

    # write particle positions ans smoothing lengths
    w.gas.coordinates = xp
    w.gas.smoothing_length = h

    # get gas masses
    mpart = 1.6e5 * unyt.Msun
    masses = np.ones(xp.shape[0], dtype=np.float64) * mpart
    # change some gas masses
    mask = xp[:, 0] > 0.5 * edgelen
    masses[mask] *= 3
    w.gas.masses = masses

    w.gas.internal_energy = (np.ones(xp.shape[0], dtype=np.float64) * 1.25e6 *
                             unyt.m**2 / unyt.s**2)
Exemplo n.º 18
0
16 * 16 * 16 particles.
"""

import numpy as np
import unyt

from swiftsimio import Writer

NUMBER_OF_PARTICLES = 16  # in 1D
TOTAL_NUMBER_OF_PARTICLES = NUMBER_OF_PARTICLES**3
PARTICLE_OVER_MASS_FACTOR = 16  # how many times over-massive is the main particle?
TIME_STEP = 0.1  # in seconds

dataset = Writer(
    unit_system=unyt.unit_systems.cgs_unit_system,
    box_size=unyt.unyt_array([1, 1, 1], "cm"),
    dimension=3,
)

base_coordinates = np.arange(0.0, 1.0, 1.0 / NUMBER_OF_PARTICLES)
dataset.gas.coordinates = unyt.unyt_array(
    [x.flatten() for x in np.meshgrid(*[base_coordinates] * 3)], "cm").T
dataset.gas.generate_smoothing_lengths(boxsize=dataset.box_size, dimension=3)

base_velocities = np.zeros_like(base_coordinates)
dataset.gas.velocities = unyt.unyt_array(
    [x.flatten() for x in np.meshgrid(*[base_velocities] * 3)], "cm/s").T

# Set the particle with the highest mass to be in the centre of
# the volume for easier plotting later
special_particle = (np.linalg.norm(dataset.gas.coordinates -